From 80394529793ee5c01e774024c05b0d7402a53c0c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:23 -0700 Subject: [PATCH 001/323] rc/01 tooltips (#20448) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/components/ui/tooltip.tsx | 73 ++++++++++++++++---------- 2 files changed, 46 insertions(+), 28 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index e9efaa8de126..16ac2b2f8a2b 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -24,4 +24,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/hooks/useIncrementalTimelineEntries.ts", "apps/web/src/hooks/useProactivePanels.ts", "apps/web/src/hooks/useRightPanelSurfaceClose.ts", + "apps/web/src/components/ui/tooltip.tsx", ] as const; diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index ad1ec23b4b3f..e7751a8e4128 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -1,5 +1,13 @@ import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"; -import { createContext, use, useEffect, useRef, type ComponentProps, type RefObject } from "react"; +import { + createContext, + use, + useEffect, + useRef, + useState, + type ComponentProps, + type RefObject, +} from "react"; import { cn } from "~/lib/utils"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; @@ -10,27 +18,43 @@ const COLLISION_PADDING = 5; const TooltipProvider = TooltipPrimitive.Provider; type TooltipActionsRef = RefObject; + +// Context values are frozen to the compiler, so consumers update the hovered +// tooltip through these calls rather than by writing to a shared ref. +function createTooltipHoverTracker() { + let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + return { + hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { + hovered = { trigger, actionsRef }; + }, + release(actionsRef: TooltipActionsRef) { + if (hovered?.actionsRef === actionsRef) hovered = null; + }, + dismissUnfocused() { + const tooltip = hovered; + if (!tooltip || tooltip.trigger.contains(tooltip.trigger.ownerDocument.activeElement)) { + return; + } + hovered = null; + // Base UI also cancels delayed hover opens through this action. + tooltip.actionsRef.current?.close(); + }, + }; +} + +type TooltipHoverTracker = ReturnType; const TooltipHoverContext = createContext(null); -const TooltipScrollContext = createContext | null>(null); +const TooltipScrollContext = createContext(null); function TooltipScrollDismissArea({ onScrollCapture, ...props }: ComponentProps<"div">) { - const hovered = useRef<{ trigger: HTMLElement; actionsRef: TooltipActionsRef } | null>(null); + const [tracker] = useState(createTooltipHoverTracker); return ( - +
{ onScrollCapture?.(event); - const tooltip = hovered.current; - if (!tooltip || tooltip.trigger.contains(tooltip.trigger.ownerDocument.activeElement)) { - return; - } - hovered.current = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tracker.dismissUnfocused(); }} /> @@ -38,17 +62,12 @@ function TooltipScrollDismissArea({ onScrollCapture, ...props }: ComponentProps< } function Tooltip(props: TooltipPrimitive.Root.Props) { - const hovered = use(TooltipScrollContext); + const tracker = use(TooltipScrollContext); const localActionsRef = useRef(null); const actionsRef = props.actionsRef ?? localActionsRef; - useEffect( - () => () => { - if (hovered?.current?.actionsRef === actionsRef) hovered.current = null; - }, - [actionsRef, hovered], - ); + useEffect(() => () => tracker?.release(actionsRef), [actionsRef, tracker]); - if (!hovered) return ; + if (!tracker) return ; return ( (props: TooltipPrimitive.Root.Props) { actionsRef={actionsRef} onOpenChange={(open, details) => { props.onOpenChange?.(open, details); - if (!open && !details.isCanceled && hovered.current?.actionsRef === actionsRef) { - hovered.current = null; - } + if (!open && !details.isCanceled) tracker.release(actionsRef); }} /> @@ -66,9 +83,9 @@ function Tooltip(props: TooltipPrimitive.Root.Props) { } function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { - const hovered = use(TooltipScrollContext); + const tracker = use(TooltipScrollContext); const actionsRef = use(TooltipHoverContext); - if (!hovered || !actionsRef) { + if (!tracker || !actionsRef) { return ; } return ( @@ -77,7 +94,7 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - hovered.current = { trigger: event.currentTarget, actionsRef }; + tracker.hover(event.currentTarget, actionsRef); }} /> ); From 777cd68c6aa0b816f39d1e0dc79ad34590635755 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:23 -0700 Subject: [PATCH 002/323] perf(web): the composer editor compiles with the React Compiler (#20450) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../components/ComposerPromptEditorTiptap.tsx | 628 +++++++++--------- 2 files changed, 303 insertions(+), 326 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 16ac2b2f8a2b..ec21aa9e1b3a 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -25,4 +25,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/hooks/useProactivePanels.ts", "apps/web/src/hooks/useRightPanelSurfaceClose.ts", "apps/web/src/components/ui/tooltip.tsx", + "apps/web/src/components/ComposerPromptEditorTiptap.tsx", ] as const; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 96ac3b85c000..b41bb61de60e 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -36,12 +36,10 @@ import { import { createContext, use, - useCallback, useEffect, useEffectEvent, useImperativeHandle, useLayoutEffect, - useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, @@ -55,6 +53,7 @@ import { isCollapsedCursorAdjacentToInlineToken, pastedPathQueryLength, } from "~/composer-logic"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { collectComposerPromptInlineTokens, selectionTouchesMentionBoundary, @@ -381,33 +380,30 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { const commentTarget = commentContext.openComment?.key === citeKey ? commentContext.openComment : null; - const nodePos = useCallback(() => { + const nodePos = () => { const pos = typeof getPos === "function" ? getPos() : null; return typeof pos === "number" ? pos : null; - }, [getPos]); - - const onSaveComment = useCallback( - (comment: string): boolean => { - if (!editor.isEditable) return false; - const pos = nodePos(); - if (pos === null) return false; - const current = editor.state.doc.nodeAt(pos); - if (!current || current.type.name !== "composer-citation") return false; - const currentCitation = current.attrs.citation as AssistantCitation; - const next = withAssistantCitationComment(currentCitation, comment); - const tr = editor.state.tr.setNodeMarkup(pos, undefined, { - ...current.attrs, - citation: next, - source: serializeAssistantCitation(next), - }); - editor.view.dispatch(tr); - return true; - }, - [editor, nodePos], - ); + }; + + const onSaveComment = (comment: string): boolean => { + if (!editor.isEditable) return false; + const pos = nodePos(); + if (pos === null) return false; + const current = editor.state.doc.nodeAt(pos); + if (!current || current.type.name !== "composer-citation") return false; + const currentCitation = current.attrs.citation as AssistantCitation; + const next = withAssistantCitationComment(currentCitation, comment); + const tr = editor.state.tr.setNodeMarkup(pos, undefined, { + ...current.attrs, + citation: next, + source: serializeAssistantCitation(next), + }); + editor.view.dispatch(tr); + return true; + }; const removeOnCancel = commentTarget?.removeOnCancel; - const onRemove = useCallback(() => { + const onRemove = () => { if (!editor.isEditable || !removeOnCancel) return; const pos = nodePos(); if (pos === null) return; @@ -418,16 +414,16 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { const from = removeOnCancel.before && doc.textBetween(pos - 1, pos) === " " ? pos - 1 : pos; const to = removeOnCancel.after && doc.textBetween(end, end + 1) === " " ? end + 1 : end; editor.chain().focus().deleteRange({ from, to }).run(); - }, [editor, nodePos, removeOnCancel]); + }; - const onRestoreFocus = useCallback(() => { + const onRestoreFocus = () => { if (!editor.isEditable) return; const pos = nodePos(); if (pos === null) return; const current = editor.state.doc.nodeAt(pos); if (!current || current.type.name !== "composer-citation") return; editor.commands.focus(pos + current.nodeSize); - }, [editor, nodePos]); + }; return ( + event.target instanceof Element && + event.target.closest(".chat-markdown-codeblock-header") !== null, + }); + }, + // Tiptap's own ``` + space rule would open a fence inside a + // list item or quote, where the serializer has no line for + // it. Enter on a fence line covers the gesture at top level. + addInputRules() { + return []; + }, + }), + composerCodeBlockHighlight({ + resolveTheme: () => + resolveDiffThemeName( + document.documentElement.classList.contains("dark") ? "dark" : "light", + ), + }), + ...ComposerBlockExtensions.map((extension) => + extension.name === "blockquote" + ? extension.extend({ + addInputRules() { + return [blockquoteInputRule]; + }, + }) + : extension.name === "horizontalRule" + ? extension.extend({ + addInputRules() { + return [horizontalRuleInputRule]; + }, + }) + : extension.name === "heading" + ? extension.extend({ + addInputRules() { + return [headingInputRule]; + }, + }) + : extension, + ), + ...ComposerListExtensions.map((extension) => + extension.name === "listItem" + ? extension + : extension.extend({ + addInputRules() { + return this.name === "bulletList" + ? [ + listMarkerInputRule(/^(?[*+])(?\s)$/, "bulletList"), + listMarkerInputRule( + /^(?-)(?[ \t]+)(?[^\s[])$/, + "bulletList", + ), + ] + : [listMarkerInputRule(/^(?\d+[.)])(?\s)$/, "orderedList")]; + }, + }), + ), + ComposerTaskListExtension, + ComposerTaskItemExtension.extend({ + addInputRules() { + return [taskInputRule(this.type), bulletToTaskInputRule]; + }, + }), + ] + : []), + ]; +} + +const RICH_TEXT_EXTENSIONS = createComposerExtensions(true); +const PLAIN_TEXT_EXTENSIONS = createComposerExtensions(false); + function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { const { value, @@ -806,21 +910,15 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { editorRef, } = props; const richText = !literalText && (richTextEnabled ?? false); - const clampEditorCursor = useCallback( - (text: string, position: number) => - literalText - ? Math.max( - 0, - Math.min(text.length, Number.isFinite(position) ? Math.floor(position) : text.length), - ) - : clampCollapsedComposerCursor(text, position), - [literalText], - ); - const expandEditorCursor = useCallback( - (text: string, position: number) => - literalText ? position : expandCollapsedComposerCursor(text, position), - [literalText], - ); + const clampEditorCursor = (text: string, position: number) => + literalText + ? Math.max( + 0, + Math.min(text.length, Number.isFinite(position) ? Math.floor(position) : text.length), + ) + : clampCollapsedComposerCursor(text, position); + const expandEditorCursor = (text: string, position: number) => + literalText ? position : expandCollapsedComposerCursor(text, position); const onChangeRef = useRef(onChange); const onVisibleSelectionChangeRef = useRef(onVisibleSelectionChange); @@ -828,7 +926,6 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { const isPathQueryActiveRef = useRef(isPathQueryActive); const buildFragmentRef = useRef(buildContextClipboardFragment); const importFragmentRef = useRef(importContextFragment); - const skillsRef = useRef(skills); const latestValueRef = useRef(value); const editorHolder = useRef(null); @@ -850,16 +947,14 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { useEffect(() => { importFragmentRef.current = importContextFragment; }, [importContextFragment]); - useEffect(() => { - skillsRef.current = skills; - }, [skills]); useLayoutEffect(() => { latestValueRef.current = value; }, [value]); - const skillLabelFor = useCallback((name: string): SkillMeta => { + // Stable so a skills refresh does not rerun the controlled-value effect. + const skillLabelFor = useStableCallback((name: string): SkillMeta => { const normalized = name.startsWith("$") ? name.slice(1) : name; - const skill = skillsRef.current.find((candidate) => candidate.name === normalized); + const skill = skills.find((candidate) => candidate.name === normalized); if (!skill) { return { label: formatProviderSkillDisplayName({ name: normalized }), description: null }; } @@ -868,7 +963,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { label: formatProviderSkillDisplayName(skill), description: shortDescription || skill.description?.trim() || null, }; - }, []); + }); const initialCursor = clampEditorCursor(value, cursor); const initialExpandedCursor = expandEditorCursor(value, initialCursor); @@ -886,221 +981,108 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { const citationDraftRef = useRef<{ key: string; comment: string } | null>(null); const [isEmpty, setIsEmpty] = useState(value.length === 0); - const citationCommentActions = useMemo( - () => ({ - openComment: openCitation, - onOpenChange: (nodeKey: string, open: boolean) => { - if (!open && citationDraftRef.current?.key === nodeKey) citationDraftRef.current = null; - setOpenCitation((current) => { - if (open) { - if (current?.key === nodeKey) return current; - return { key: nodeKey }; - } - return current?.key === nodeKey ? null : current; - }); - }, - onDraftChange: (nodeKey: string, comment: string) => { - citationDraftRef.current = { key: nodeKey, comment }; - }, - onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}), - }), - [onCitationSubmitAndSend, openCitation], - ); - - const handleEditorChange = useCallback( - (updated: TiptapEditor) => { - const map = serializeEditorDoc(updated.state.doc); - const contextIds = literalText ? [] : map.contextIds; - const { from, to } = updated.state.selection; - const fromFlat = pmToFlat(map, from); - const toFlat = pmToFlat(map, to); - const nextValue = map.value; - const nextCursor = clampEditorCursor(map.value, flatToCollapsed(map, fromFlat)); - const nextExpandedCursor = Math.max( - 0, - Math.min(map.value.length, flatToMarkdown(map, fromFlat)), - ); - const nextSelectionRange = { - start: Math.min(nextExpandedCursor, flatToMarkdown(map, toFlat)), - end: Math.max(nextExpandedCursor, flatToMarkdown(map, toFlat)), - }; - const previousSelectionRange = selectionRangeRef.current; - selectionRangeRef.current = nextSelectionRange; - setIsEmpty(nextValue.length === 0); - const previousSnapshot = snapshotRef.current; - const snapshotChanged = !( - previousSnapshot.value === nextValue && - previousSnapshot.cursor === nextCursor && - previousSnapshot.expandedCursor === nextExpandedCursor && - previousSnapshot.contextIds.length === contextIds.length && - previousSnapshot.contextIds.every((id, index) => id === contextIds[index]) - ); - if (isApplyingControlledUpdateRef.current) return; - if (!snapshotChanged) { - if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) { - onVisibleSelectionChangeRef.current?.(); + const citationCommentActions = { + openComment: openCitation, + onOpenChange: (nodeKey: string, open: boolean) => { + if (!open && citationDraftRef.current?.key === nodeKey) citationDraftRef.current = null; + setOpenCitation((current) => { + if (open) { + if (current?.key === nodeKey) return current; + return { key: nodeKey }; } - return; - } - // A selection-only update while a newer prompt waits to be applied (a chip - // was just inserted through the store) would report stale text and clobber - // the prompt. Let the controlled rewrite land instead. - if (previousSnapshot.value === nextValue && nextValue !== latestValueRef.current) { - return; - } - snapshotRef.current = { - value: nextValue, - cursor: nextCursor, - expandedCursor: nextExpandedCursor, - contextIds, - }; - const inCodeBlock = updated.state.selection.$from.parent.type.spec.code === true; - const suppressTrigger = - literalText || - inCodeBlock || - isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") || - isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right"); - onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds); + return current?.key === nodeKey ? null : current; + }); }, - [clampEditorCursor, literalText], - ); + onDraftChange: (nodeKey: string, comment: string) => { + citationDraftRef.current = { key: nodeKey, comment }; + }, + onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}), + }; - const editorAttributes = useMemo( - () => ({ - class: cn( - "composer-tiptap -m-1 block max-h-52 min-h-19.5 overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none", - className, - ), - "data-testid": "composer-editor", - "data-composer-rich-text": richText ? "true" : "false", - role: "textbox", - "aria-multiline": "true", - ...(ariaLabel ? { "aria-label": ariaLabel } : {}), - ...(disabled ? { "aria-readonly": "true" } : {}), - ...(!disabled && suggestionListId - ? { - "aria-autocomplete": "list", - "aria-haspopup": "listbox", - ...(activeSuggestionId - ? { - "aria-controls": suggestionListId, - "aria-activedescendant": activeSuggestionId, - } - : {}), - } - : {}), - "aria-placeholder": placeholder, - }), - [activeSuggestionId, ariaLabel, className, disabled, placeholder, richText, suggestionListId], - ); + const handleEditorChange = (updated: TiptapEditor) => { + const map = serializeEditorDoc(updated.state.doc); + const contextIds = literalText ? [] : map.contextIds; + const { from, to } = updated.state.selection; + const fromFlat = pmToFlat(map, from); + const toFlat = pmToFlat(map, to); + const nextValue = map.value; + const nextCursor = clampEditorCursor(map.value, flatToCollapsed(map, fromFlat)); + const nextExpandedCursor = Math.max( + 0, + Math.min(map.value.length, flatToMarkdown(map, fromFlat)), + ); + const nextSelectionRange = { + start: Math.min(nextExpandedCursor, flatToMarkdown(map, toFlat)), + end: Math.max(nextExpandedCursor, flatToMarkdown(map, toFlat)), + }; + const previousSelectionRange = selectionRangeRef.current; + selectionRangeRef.current = nextSelectionRange; + setIsEmpty(nextValue.length === 0); + const previousSnapshot = snapshotRef.current; + const snapshotChanged = !( + previousSnapshot.value === nextValue && + previousSnapshot.cursor === nextCursor && + previousSnapshot.expandedCursor === nextExpandedCursor && + previousSnapshot.contextIds.length === contextIds.length && + previousSnapshot.contextIds.every((id, index) => id === contextIds[index]) + ); + if (isApplyingControlledUpdateRef.current) return; + if (!snapshotChanged) { + if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) { + onVisibleSelectionChangeRef.current?.(); + } + return; + } + // A selection-only update while a newer prompt waits to be applied (a chip + // was just inserted through the store) would report stale text and clobber + // the prompt. Let the controlled rewrite land instead. + if (previousSnapshot.value === nextValue && nextValue !== latestValueRef.current) { + return; + } + snapshotRef.current = { + value: nextValue, + cursor: nextCursor, + expandedCursor: nextExpandedCursor, + contextIds, + }; + const inCodeBlock = updated.state.selection.$from.parent.type.spec.code === true; + const suppressTrigger = + literalText || + inCodeBlock || + isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") || + isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right"); + onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds); + }; + + const editorAttributes = { + class: cn( + "composer-tiptap -m-1 block max-h-52 min-h-19.5 overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none", + className, + ), + "data-testid": "composer-editor", + "data-composer-rich-text": richText ? "true" : "false", + role: "textbox", + "aria-multiline": "true", + ...(ariaLabel ? { "aria-label": ariaLabel } : {}), + ...(disabled ? { "aria-readonly": "true" } : {}), + ...(!disabled && suggestionListId + ? { + "aria-autocomplete": "list", + "aria-haspopup": "listbox", + ...(activeSuggestionId + ? { + "aria-controls": suggestionListId, + "aria-activedescendant": activeSuggestionId, + } + : {}), + } + : {}), + "aria-placeholder": placeholder, + }; const editor = useEditor( { - extensions: [ - StarterKit.configure({ - blockquote: false, - bulletList: false, - codeBlock: false, - heading: false, - horizontalRule: false, - listItem: false, - link: false, - orderedList: false, - underline: false, - dropcursor: false, - gapcursor: false, - trailingNode: false, - code: false, - listKeymap: false, - undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY }, - ...(richText ? {} : { bold: false, italic: false, strike: false }), - }), - ComposerUndoGroupingExtension, - ComposerMentionExtension, - ComposerSkillExtension, - ComposerCitationExtension, - ComposerContextReferenceExtension, - ComposerMarkersExtension, - ...(richText - ? [ - ComposerCodeExtension, - ComposerCodeBlockExtension.extend({ - addNodeView() { - return ReactNodeViewRenderer(ComposerCodeBlockNodeView, { - // The header holds the language picker. Tiptap only shields - // events aimed at the button element itself, so a click on - // its icon or label would reach ProseMirror and move the - // selection; keep every header event away from the editor. - stopEvent: ({ event }) => - event.target instanceof Element && - event.target.closest(".chat-markdown-codeblock-header") !== null, - }); - }, - // Tiptap's own ``` + space rule would open a fence inside a - // list item or quote, where the serializer has no line for - // it. Enter on a fence line covers the gesture at top level. - addInputRules() { - return []; - }, - }), - composerCodeBlockHighlight({ - resolveTheme: () => - resolveDiffThemeName( - document.documentElement.classList.contains("dark") ? "dark" : "light", - ), - }), - ...ComposerBlockExtensions.map((extension) => - extension.name === "blockquote" - ? extension.extend({ - addInputRules() { - return [blockquoteInputRule]; - }, - }) - : extension.name === "horizontalRule" - ? extension.extend({ - addInputRules() { - return [horizontalRuleInputRule]; - }, - }) - : extension.name === "heading" - ? extension.extend({ - addInputRules() { - return [headingInputRule]; - }, - }) - : extension, - ), - ...ComposerListExtensions.map((extension) => - extension.name === "listItem" - ? extension - : extension.extend({ - addInputRules() { - return this.name === "bulletList" - ? [ - listMarkerInputRule(/^(?[*+])(?\s)$/, "bulletList"), - listMarkerInputRule( - /^(?-)(?[ \t]+)(?[^\s[])$/, - "bulletList", - ), - ] - : [ - listMarkerInputRule( - /^(?\d+[.)])(?\s)$/, - "orderedList", - ), - ]; - }, - }), - ), - ComposerTaskListExtension, - ComposerTaskItemExtension.extend({ - addInputRules() { - return [taskInputRule(this.type), bulletToTaskInputRule]; - }, - }), - ] - : []), - ], + extensions: richText ? RICH_TEXT_EXTENSIONS : PLAIN_TEXT_EXTENSIONS, content: buildDocJson( value, (name) => { @@ -1454,7 +1436,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { editor.view.setProps({ attributes: editorAttributes }); }, [editor, editorAttributes]); - const readSnapshot = useCallback(() => { + const readSnapshot = () => { const snapshot = snapshotRef.current; if (!editor) return snapshot; const map = serializeEditorDoc(editor.state.doc); @@ -1473,7 +1455,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { }; snapshotRef.current = next; return next; - }, [clampEditorCursor, editor, literalText]); + }; // A question or approval swaps the controlled value while a citation comment // is open. Its node view unmounts with the old document, so save the comment @@ -1587,41 +1569,38 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { value, ]); - const focusAt = useCallback( - (nextCursor: number) => { - if (!editor) return; - // view.focus() writes the state selection to the DOM as it focuses. A - // bare DOM focus leaves the native caret at the start until - // ProseMirror resyncs it 20ms later, and dictation tools type fast - // enough to land keys there, ahead of the text already inserted. - editor.view.focus(); - if (snapshotRef.current.value !== latestValueRef.current) return; - const boundedCursor = clampEditorCursor(snapshotRef.current.value, nextCursor); - const map = serializeEditorDoc(editor.state.doc); - const flat = collapsedToFlat(map, boundedCursor); - editor.commands.setTextSelection(flatToPm(map, flat)); - scrollTiptapCaretIntoView(editor); - if (boundedCursor === snapshotRef.current.cursor) return; - snapshotRef.current = { - value: snapshotRef.current.value, - cursor: boundedCursor, - expandedCursor: expandEditorCursor(snapshotRef.current.value, boundedCursor), - contextIds: snapshotRef.current.contextIds, - }; - selectionRangeRef.current = { - start: snapshotRef.current.expandedCursor, - end: snapshotRef.current.expandedCursor, - }; - onChangeRef.current( - snapshotRef.current.value, - boundedCursor, - snapshotRef.current.expandedCursor, - literalText, - snapshotRef.current.contextIds, - ); - }, - [clampEditorCursor, editor, expandEditorCursor, literalText], - ); + const focusAt = (nextCursor: number) => { + if (!editor) return; + // view.focus() writes the state selection to the DOM as it focuses. A + // bare DOM focus leaves the native caret at the start until + // ProseMirror resyncs it 20ms later, and dictation tools type fast + // enough to land keys there, ahead of the text already inserted. + editor.view.focus(); + if (snapshotRef.current.value !== latestValueRef.current) return; + const boundedCursor = clampEditorCursor(snapshotRef.current.value, nextCursor); + const map = serializeEditorDoc(editor.state.doc); + const flat = collapsedToFlat(map, boundedCursor); + editor.commands.setTextSelection(flatToPm(map, flat)); + scrollTiptapCaretIntoView(editor); + if (boundedCursor === snapshotRef.current.cursor) return; + snapshotRef.current = { + value: snapshotRef.current.value, + cursor: boundedCursor, + expandedCursor: expandEditorCursor(snapshotRef.current.value, boundedCursor), + contextIds: snapshotRef.current.contextIds, + }; + selectionRangeRef.current = { + start: snapshotRef.current.expandedCursor, + end: snapshotRef.current.expandedCursor, + }; + onChangeRef.current( + snapshotRef.current.value, + boundedCursor, + snapshotRef.current.expandedCursor, + literalText, + snapshotRef.current.contextIds, + ); + }; useImperativeHandle( editorRef, @@ -1702,36 +1681,33 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { [editor, focusAt, literalText, readSnapshot], ); - const handleCopyCut = useCallback( - (event: React.ClipboardEvent, cut: boolean) => { - const build = buildFragmentRef.current; - if (!editor || (cut && !editor.isEditable)) return; - const clipboardData = event.clipboardData; - const { from, to } = editor.state.selection; - if (from === to) return; - const text = serializeSelection(editor.state.doc, from, to); - const contextIds = literalText ? [] : Array.from(new Set(collectInlineContextIds(text))); - const fragment = contextIds.length > 0 ? build?.(contextIds) : null; - event.preventDefault(); - clipboardData.setData("text/plain", text); - if (fragment) { - clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment); - clipboardData.setData("text/html", encodeComposerContextClipboardHtml(text, fragment)); - } - if (cut) { - editor - .chain() - .focus() - .command(({ tr }) => { - markAsClipboardEdit(tr, "cut"); - return true; - }) - .deleteSelection() - .run(); - } - }, - [editor, literalText], - ); + const handleCopyCut = (event: React.ClipboardEvent, cut: boolean) => { + const build = buildFragmentRef.current; + if (!editor || (cut && !editor.isEditable)) return; + const clipboardData = event.clipboardData; + const { from, to } = editor.state.selection; + if (from === to) return; + const text = serializeSelection(editor.state.doc, from, to); + const contextIds = literalText ? [] : Array.from(new Set(collectInlineContextIds(text))); + const fragment = contextIds.length > 0 ? build?.(contextIds) : null; + event.preventDefault(); + clipboardData.setData("text/plain", text); + if (fragment) { + clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment); + clipboardData.setData("text/html", encodeComposerContextClipboardHtml(text, fragment)); + } + if (cut) { + editor + .chain() + .focus() + .command(({ tr }) => { + markAsClipboardEdit(tr, "cut"); + return true; + }) + .deleteSelection() + .run(); + } + }; return ( From fd3420f3805aed83326ec40a6a6663681a44ef27 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:24 -0700 Subject: [PATCH 003/323] perf(web): the server browser surface compiles with the React Compiler (#20451) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/browser/ServerBrowserSurface.tsx | 97 +++++++++---------- 2 files changed, 47 insertions(+), 51 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index ec21aa9e1b3a..51be1866cede 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -26,4 +26,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/hooks/useRightPanelSurfaceClose.ts", "apps/web/src/components/ui/tooltip.tsx", "apps/web/src/components/ComposerPromptEditorTiptap.tsx", + "apps/web/src/browser/ServerBrowserSurface.tsx", ] as const; diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx index ef5070752b83..45dad35db16b 100644 --- a/apps/web/src/browser/ServerBrowserSurface.tsx +++ b/apps/web/src/browser/ServerBrowserSurface.tsx @@ -26,7 +26,6 @@ import { type KeyboardEvent, type PointerEvent, type Ref, - useCallback, useEffect, useEffectEvent, useImperativeHandle, @@ -216,11 +215,13 @@ export function ServerBrowserSurface(props: { const popupOpened = useEffectEvent((popupTabId: string) => onPopup?.(popupTabId)); const [cap, setCap] = useState<{ width: number; height: number } | null>(null); - const send = useCallback((input: PreviewStreamInput) => { + // These read only refs, so each is cached once. The stream effect keys on + // clearInput and would reconnect if it changed. + const send = (input: PreviewStreamInput) => { clientRef.current?.send(input); - }, []); + }; - const clearInput = useCallback(() => { + const clearInput = () => { if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current); inputFrameRef.current = null; pendingMoveRef.current = pendingWheelRef.current = null; @@ -231,9 +232,9 @@ export function ServerBrowserSurface(props: { keySentRef.current = false; if (inputRef.current) inputRef.current.value = INPUT_SENTINEL; inputRef.current?.blur(); - }, []); + }; - const flushInput = useCallback(() => { + const flushInput = () => { if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current); inputFrameRef.current = null; const move = pendingMoveRef.current; @@ -242,52 +243,46 @@ export function ServerBrowserSurface(props: { pendingWheelRef.current = null; if (move) send(move); if (wheel) send(wheel); - }, [send]); - - const scheduleFlush = useCallback(() => { - inputFrameRef.current ??= requestAnimationFrame(flushInput); - }, [flushInput]); - - const queueWheel = useCallback( - (point: PagePoint, deltaX: number, deltaY: number, modifiers: number) => { - const pending = pendingWheelRef.current; - pendingWheelRef.current = { - type: "wheel", - x: point.x, - y: point.y, - deltaX: (pending?.deltaX ?? 0) + deltaX, - deltaY: (pending?.deltaY ?? 0) + deltaY, - modifiers, - }; - scheduleFlush(); - }, - [scheduleFlush], - ); + }; - const pagePoint = useCallback( - (clientX: number, clientY: number, clamp: boolean): PagePoint | null => { - const canvas = canvasRef.current; - const viewport = viewportRef.current; - if (!canvas || !viewport || !hasFrameRef.current || controlRef.current?.controller !== "you") - return null; - const rect = canvas.getBoundingClientRect(); - const fit = Math.min(rect.width / canvas.width, rect.height / canvas.height); - const width = canvas.width * fit; - const height = canvas.height * fit; - if (!(width > 0 && height > 0)) return null; - const scale = viewport.width / width; - const x = (clientX - rect.left - (rect.width - width) / 2) * scale; - const y = (clientY - rect.top - (rect.height - height) / 2) * (viewport.height / height); - const inside = x >= 0 && y >= 0 && x <= viewport.width && y <= viewport.height; - if (!inside && !clamp) return null; - return { - x: Math.min(Math.max(x, 0), viewport.width), - y: Math.min(Math.max(y, 0), viewport.height), - scale, - }; - }, - [], - ); + const scheduleFlush = () => { + if (inputFrameRef.current === null) inputFrameRef.current = requestAnimationFrame(flushInput); + }; + + const queueWheel = (point: PagePoint, deltaX: number, deltaY: number, modifiers: number) => { + const pending = pendingWheelRef.current; + pendingWheelRef.current = { + type: "wheel", + x: point.x, + y: point.y, + deltaX: (pending?.deltaX ?? 0) + deltaX, + deltaY: (pending?.deltaY ?? 0) + deltaY, + modifiers, + }; + scheduleFlush(); + }; + + const pagePoint = (clientX: number, clientY: number, clamp: boolean): PagePoint | null => { + const canvas = canvasRef.current; + const viewport = viewportRef.current; + if (!canvas || !viewport || !hasFrameRef.current || controlRef.current?.controller !== "you") + return null; + const rect = canvas.getBoundingClientRect(); + const fit = Math.min(rect.width / canvas.width, rect.height / canvas.height); + const width = canvas.width * fit; + const height = canvas.height * fit; + if (!(width > 0 && height > 0)) return null; + const scale = viewport.width / width; + const x = (clientX - rect.left - (rect.width - width) / 2) * scale; + const y = (clientY - rect.top - (rect.height - height) / 2) * (viewport.height / height); + const inside = x >= 0 && y >= 0 && x <= viewport.width && y <= viewport.height; + if (!inside && !clamp) return null; + return { + x: Math.min(Math.max(x, 0), viewport.width), + y: Math.min(Math.max(y, 0), viewport.height), + scale, + }; + }; const countClick = (button: PreviewStreamMouseButton, x: number, y: number, time: number) => { const last = lastClickRef.current; From 696e0e4314a44e4614438f9c3142ddb8b5e10cbc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:25 -0700 Subject: [PATCH 004/323] perf(web): asset URL hooks compile with the React Compiler (#20452) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/assets/assetUrls.ts | 60 +++++++++++++++----------------- 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 51be1866cede..00cda514c793 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -27,4 +27,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/ui/tooltip.tsx", "apps/web/src/components/ComposerPromptEditorTiptap.tsx", "apps/web/src/browser/ServerBrowserSurface.tsx", + "apps/web/src/assets/assetUrls.ts", ] as const; diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts index d09809836a85..1c77e91f7ace 100644 --- a/apps/web/src/assets/assetUrls.ts +++ b/apps/web/src/assets/assetUrls.ts @@ -9,7 +9,6 @@ import { import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { AssetResource, EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; -import { useCallback, useMemo } from "react"; import { assetEnvironment } from "~/state/assets"; import { useFilesystemReadAccess } from "~/state/filesystem"; @@ -46,12 +45,12 @@ export function useAssetUrlRefresh( reportFailure: false, refresh: true, }); - return useCallback(async () => { + return async () => { if (environmentId === null || resource === null || httpBaseUrl === null) return null; const result = await refresh({ environmentId, input: { resource } }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); return resolveAssetUrl(httpBaseUrl, result.value.relativeUrl); - }, [environmentId, resource, refresh, httpBaseUrl]); + }; } export function useAssetUrls( @@ -60,39 +59,38 @@ export function useAssetUrls( ): ReadonlyArray { const preparedConnection = usePreparedConnection(environmentId); const { canReadFiles } = useFilesystemReadAccess(environmentId); - const allowedResources = useMemo( - () => - canReadFiles - ? resources - : resources.filter( - (resource) => - resource._tag !== "workspace-file" && - resource._tag !== "media-file" && - resource._tag !== "draft-workspace-file", - ), - [canReadFiles, resources], - ); + const allowedResources = canReadFiles + ? resources + : resources.filter((resource) => !isFileResource(resource)); const results = useAtomValue( assetEnvironment.createUrls({ environmentId, resources: allowedResources, }), ); - return useMemo(() => { - if (preparedConnection._tag === "None") return resources.map(() => null); - let resultIndex = 0; - return resources.map((resource) => { - if ( - !canReadFiles && - (resource._tag === "workspace-file" || - resource._tag === "media-file" || - resource._tag === "draft-workspace-file") - ) - return null; - const result = results[resultIndex++]; - return result && AsyncResult.isSuccess(result) + if (preparedConnection._tag === "None") return resources.map(() => null); + const urls: Array = []; + let resultIndex = 0; + for (const resource of resources) { + if (!canReadFiles && isFileResource(resource)) { + urls.push(null); + continue; + } + const result = results[resultIndex]; + resultIndex += 1; + urls.push( + result && AsyncResult.isSuccess(result) ? resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl) - : null; - }); - }, [canReadFiles, preparedConnection, resources, results]); + : null, + ); + } + return urls; +} + +function isFileResource(resource: AssetResource): boolean { + return ( + resource._tag === "workspace-file" || + resource._tag === "media-file" || + resource._tag === "draft-workspace-file" + ); } From e9712d261e74ca54e7fb662d7a04a033423aa0f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:25 -0700 Subject: [PATCH 005/323] perf(web): toggle groups compile with the React Compiler (#20453) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/components/ui/toggle-group.tsx | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 00cda514c793..6fd5b6123e3c 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -28,4 +28,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/ComposerPromptEditorTiptap.tsx", "apps/web/src/browser/ServerBrowserSurface.tsx", "apps/web/src/assets/assetUrls.ts", + "apps/web/src/components/ui/toggle-group.tsx", ] as const; diff --git a/apps/web/src/components/ui/toggle-group.tsx b/apps/web/src/components/ui/toggle-group.tsx index 846a34a1086a..191e3fd37bd0 100644 --- a/apps/web/src/components/ui/toggle-group.tsx +++ b/apps/web/src/components/ui/toggle-group.tsx @@ -16,12 +16,14 @@ const ToggleGroupContext = React.createContext) { - const value = React.useMemo(() => ({ size, variant }), [size, variant]); + const size = + sizeProp === undefined ? (variant === "segmented" ? "segmented" : "default") : sizeProp; + const value = { size, variant }; return ( Date: Fri, 16 Oct 2026 18:46:25 -0700 Subject: [PATCH 006/323] perf(web): thread notifications compile with the React Compiler (#20454) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../src/components/ThreadNotificationCoordinator.tsx | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 6fd5b6123e3c..2b69c016203f 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -29,4 +29,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/browser/ServerBrowserSurface.tsx", "apps/web/src/assets/assetUrls.ts", "apps/web/src/components/ui/toggle-group.tsx", + "apps/web/src/components/ThreadNotificationCoordinator.tsx", ] as const; diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 1b013904e82e..fab97abeeef0 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -13,7 +13,7 @@ import { MessageCircleQuestionIcon, ShieldQuestionIcon, } from "lucide-react"; -import { useCallback, useEffect, useRef } from "react"; +import { useEffect, useRef } from "react"; import { getClientSettings, useClientSettings } from "../hooks/useSettings"; import { useEnvironmentIds } from "../state/environments"; @@ -37,18 +37,18 @@ export function ThreadNotificationCoordinator() { const pending = useRef( new Map(), ); - const onNotification = useCallback((environmentId: EnvironmentId, notification: Notification) => { + const onNotification = (environmentId: EnvironmentId, notification: Notification) => { pending.current.get(notification.tag)?.notification.close(); pending.current.set(notification.tag, { environmentId, notification }); setNotificationBadge(pending.current.size); - }, []); + }; useEffect(() => { const activeIds = new Set(environmentIds); const count = pending.current.size; - for (const [tag, { environmentId, notification }] of pending.current) { - if (activeIds.has(environmentId)) continue; - notification.close(); + for (const [tag, entry] of pending.current) { + if (activeIds.has(entry.environmentId)) continue; + entry.notification.close(); pending.current.delete(tag); } if (count !== pending.current.size) setNotificationBadge(pending.current.size); From c62480abff883376fc5b0d3df16097c468cd526b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:26 -0700 Subject: [PATCH 007/323] perf(web): query hooks compile with the React Compiler (#20455) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/state/queries.ts | 101 ++++++++++++++++++--------------- 2 files changed, 57 insertions(+), 45 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 2b69c016203f..8bd9996aedbd 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -30,4 +30,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/assets/assetUrls.ts", "apps/web/src/components/ui/toggle-group.tsx", "apps/web/src/components/ThreadNotificationCoordinator.tsx", + "apps/web/src/state/queries.ts", ] as const; diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index ebf2826bcca2..a84f41fe11b8 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -22,7 +22,7 @@ import type { import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useEffect, useState } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useFilesystemReadAccess } from "./filesystem"; @@ -84,10 +84,8 @@ export function useThreadSearch( const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS); const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2; const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null; - const searchKey = useMemo( - () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)), - [environmentIds, settledQuery], - ); + const searchKey = + settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery); const result = useAtomValue( searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey), ); @@ -99,6 +97,38 @@ export function useThreadSearch( }; } +// A hook so its result is frozen: `refresh` hands a page atom to the registry, +// which the compiler would treat as a mutation and leave pagesAtom uncached, +// resubscribing every render. +function useBranchPageAtoms( + environmentId: EnvironmentId | null, + cwd: string | null, + query: string, + cursors: ReadonlyArray, + targetKey: string | null, +) { + // Calls no hooks, so the compiler needs the directive to memoize it. + "use memo"; + const pageAtoms = + environmentId !== null && cwd !== null + ? cursors.map((cursor) => + vcsEnvironment.listRefs({ + environmentId, + input: { + cwd, + ...(query.length > 0 ? { query } : {}), + ...(cursor === undefined ? {} : { cursor }), + limit: VCS_REF_LIST_LIMIT, + }, + }), + ) + : []; + const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe( + Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`), + ); + return { pageAtoms, pagesAtom }; +} + export function usePaginatedBranches(target: VcsRefTarget) { const query = target.query?.trim() ?? ""; const targetKey = @@ -113,29 +143,12 @@ export function usePaginatedBranches(target: VcsRefTarget) { cursors: INITIAL_BRANCH_CURSORS, }); const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS; - const pageAtoms = useMemo( - () => - target.environmentId !== null && target.cwd !== null - ? cursors.map((cursor) => - vcsEnvironment.listRefs({ - environmentId: target.environmentId!, - input: { - cwd: target.cwd!, - ...(query.length > 0 ? { query } : {}), - ...(cursor === undefined ? {} : { cursor }), - limit: VCS_REF_LIST_LIMIT, - }, - }), - ) - : [], - [cursors, query, target.cwd, target.environmentId], - ); - const pagesAtom = useMemo( - () => - Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe( - Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`), - ), - [pageAtoms, targetKey], + const { pageAtoms, pagesAtom } = useBranchPageAtoms( + target.environmentId, + target.cwd, + query, + cursors, + targetKey, ); const results = useAtomValue(pagesAtom); const values = results.flatMap((result) => { @@ -171,25 +184,26 @@ export function usePaginatedBranches(target: VcsRefTarget) { : "Failed to load refs."; })() : null; - const refresh = useCallback(() => { + const refresh = () => { const firstPage = pageAtoms[0]; setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS }); if (firstPage !== undefined) { appAtomRegistry.refresh(firstPage); } - }, [pageAtoms, targetKey]); - const loadNext = useCallback(() => { - if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) { + }; + const nextCursor = data?.nextCursor; + const loadNext = () => { + if (targetKey === null || nextCursor === null || nextCursor === undefined) { return; } setPagination((current) => { const currentCursors = current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS; - return currentCursors.includes(data.nextCursor!) + return currentCursors.includes(nextCursor) ? { targetKey, cursors: currentCursors } - : { targetKey, cursors: [...currentCursors, data.nextCursor!] }; + : { targetKey, cursors: [...currentCursors, nextCursor] }; }); - }, [data?.nextCursor, targetKey]); + }; return { data, @@ -226,16 +240,13 @@ export function useProjectPathSearch( options?: { readonly allowEmptyQuery?: boolean }, ) { const allowEmptyQuery = options?.allowEmptyQuery === true; - const normalizedTarget = useMemo( - () => ({ - environmentId: target.environmentId, - cwd: target.cwd, - query: target.query == null ? null : target.query.trim(), - kind: target.kind, - imageOnly: target.imageOnly, - }), - [target.cwd, target.environmentId, target.imageOnly, target.kind, target.query], - ); + const normalizedTarget = { + environmentId: target.environmentId, + cwd: target.cwd, + query: target.query == null ? null : target.query.trim(), + kind: target.kind, + imageOnly: target.imageOnly, + }; const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS); const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId); const { canReadFiles } = fileAccess; From 35dcdfb945374b3baf417b99b157d4d202020d62 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:26 -0700 Subject: [PATCH 008/323] perf(web): source control action hooks compile with the React Compiler (#20456) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/state/sourceControlActions.ts | 253 ++++++++++----------- 2 files changed, 123 insertions(+), 131 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 8bd9996aedbd..80ed343d49eb 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -31,4 +31,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/ui/toggle-group.tsx", "apps/web/src/components/ThreadNotificationCoordinator.tsx", "apps/web/src/state/queries.ts", + "apps/web/src/state/sourceControlActions.ts", ] as const; diff --git a/apps/web/src/state/sourceControlActions.ts b/apps/web/src/state/sourceControlActions.ts index ec026c00f413..12b9aff67159 100644 --- a/apps/web/src/state/sourceControlActions.ts +++ b/apps/web/src/state/sourceControlActions.ts @@ -23,7 +23,6 @@ import { import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; -import { useCallback } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { gitEnvironment } from "./git"; @@ -87,48 +86,45 @@ function useAction< const state = useAtomValue(vcsActionManager.stateAtom(input.scope)); const ownsState = state.operation === operation; - const resetError = useCallback(() => { + const resetError = () => { vcsActionManager.resetError(appAtomRegistry, input.scope, operation); - }, [input.scope, operation]); + }; - const run = useCallback( - async (...args: TArgs) => { - if ( - input.scope.environmentId === null || - !readEnvironmentScope(input.scope.environmentId, AuthSourceControlWriteScope) - ) { - return AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - requiredScope: AuthSourceControlWriteScope, - message: "This connection cannot change source control.", - }), - ), - ); + const run = async (...args: TArgs) => { + if ( + input.scope.environmentId === null || + !readEnvironmentScope(input.scope.environmentId, AuthSourceControlWriteScope) + ) { + return AsyncResult.failure( + Cause.fail( + new EnvironmentAuthorizationError({ + requiredScope: AuthSourceControlWriteScope, + message: "This connection cannot change source control.", + }), + ), + ); + } + const execute = async (): Promise< + AtomCommandResult, AtomCommandFailure> + > => { + const result = await input.action(...args); + if (AsyncResult.isSuccess(result)) { + input.onSuccess?.(); } - const execute = async (): Promise< - AtomCommandResult, AtomCommandFailure> - > => { - const result = await input.action(...args); - if (AsyncResult.isSuccess(result)) { - input.onSuccess?.(); - } - return result as AtomCommandResult, AtomCommandFailure>; - }; - return input.managedExternally === true - ? execute() - : vcsActionManager.track( - appAtomRegistry, - input.scope, - { - operation, - label: input.label, - }, - execute, - ); - }, - [input.action, input.label, input.managedExternally, input.onSuccess, input.scope, operation], - ); + return result as AtomCommandResult, AtomCommandFailure>; + }; + return input.managedExternally === true + ? execute() + : vcsActionManager.track( + appAtomRegistry, + input.scope, + { + operation, + label: input.label, + }, + execute, + ); + }; return { isAllowed, @@ -163,7 +159,7 @@ export function useSourceControlActionRunning( export function useVcsInitAction(scope: SourceControlActionScope) { const init = useAtomCommand(vcsEnvironment.init, { reportFailure: false }); - const action = useCallback(async () => { + const action = async () => { const target = resolveScope(scope); if (target === null) { return AsyncResult.failure( @@ -180,7 +176,7 @@ export function useVcsInitAction(scope: SourceControlActionScope) { environmentId: target.environmentId, input: { cwd: target.cwd }, }); - }, [init, scope]); + }; return useAction({ kind: "init", label: "Initializing repository", scope, action }); } @@ -194,7 +190,7 @@ export function useVcsPullAction(scope: SourceControlActionScope) { }) : null, ); - const action = useCallback(async () => { + const action = async () => { const target = resolveScope(scope); if (target === null) { return AsyncResult.failure( @@ -211,7 +207,7 @@ export function useVcsPullAction(scope: SourceControlActionScope) { environmentId: target.environmentId, input: { cwd: target.cwd }, }); - }, [pull, scope]); + }; return useAction({ kind: "pull", label: "Pulling latest changes...", @@ -234,23 +230,20 @@ export function useGitStackedAction(scope: SourceControlActionScope) { : null, ); - const action = useCallback( - async (input: RunVcsStackedActionInput) => { - if (resolveScope(scope) === null) { - return AsyncResult.failure( - Cause.fail( - new VcsActionUnavailableError({ - operation: "run_change_request", - environmentId: scope.environmentId, - cwd: scope.cwd, - }), - ), - ); - } - return runStackedAction(input); - }, - [runStackedAction, scope], - ); + const action = async (input: RunVcsStackedActionInput) => { + if (resolveScope(scope) === null) { + return AsyncResult.failure( + Cause.fail( + new VcsActionUnavailableError({ + operation: "run_change_request", + environmentId: scope.environmentId, + cwd: scope.cwd, + }), + ), + ); + } + return runStackedAction(input); + }; return useAction({ kind: "runStackedAction", @@ -274,36 +267,33 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi }) : null, ); - const action = useCallback( - async (input: { - provider: SourceControlProviderKind; - repository: string; - visibility: SourceControlRepositoryVisibility; - remoteName: string; - protocol: SourceControlCloneProtocol; - }) => { - const target = resolveScope(scope); - if (target === null) { - return AsyncResult.failure( - Cause.fail( - new VcsActionUnavailableError({ - operation: "publish_repository", - environmentId: scope.environmentId, - cwd: scope.cwd, - }), - ), - ); - } - return publishRepository({ - environmentId: target.environmentId, - input: { - cwd: target.cwd, - ...input, - }, - }); - }, - [publishRepository, scope], - ); + const action = async (input: { + provider: SourceControlProviderKind; + repository: string; + visibility: SourceControlRepositoryVisibility; + remoteName: string; + protocol: SourceControlCloneProtocol; + }) => { + const target = resolveScope(scope); + if (target === null) { + return AsyncResult.failure( + Cause.fail( + new VcsActionUnavailableError({ + operation: "publish_repository", + environmentId: scope.environmentId, + cwd: scope.cwd, + }), + ), + ); + } + return publishRepository({ + environmentId: target.environmentId, + input: { + cwd: target.cwd, + ...input, + }, + }); + }; return useAction({ kind: "publishRepository", label: "Publishing repository", @@ -317,46 +307,47 @@ export function usePreparePullRequestThreadAction(scope: SourceControlActionScop const preparePullRequestThread = useAtomCommand(gitEnvironment.preparePullRequestThread, { reportFailure: false, }); - const action = useCallback( - async (input: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => { - const target = resolveScope(scope); - if (target === null) { - return AsyncResult.failure( - Cause.fail( - new VcsActionUnavailableError({ - operation: "prepare_pull_request_thread", - environmentId: scope.environmentId, - cwd: scope.cwd, - }), - ), - ); - } - if ( - input.mode === "worktree" && - input.threadId !== undefined && - !readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope) - ) { - return AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - requiredScope: AuthOrchestrationOperateScope, - message: "This connection cannot change threads.", - }), - ), - ); - } - return preparePullRequestThread({ - environmentId: target.environmentId, - input: { - cwd: target.cwd, - reference: input.reference, - mode: input.mode, - ...(input.threadId ? { threadId: input.threadId } : {}), - }, - }); - }, - [preparePullRequestThread, scope], - ); + const action = async (input: { + reference: string; + mode: "local" | "worktree"; + threadId?: ThreadId; + }) => { + const target = resolveScope(scope); + if (target === null) { + return AsyncResult.failure( + Cause.fail( + new VcsActionUnavailableError({ + operation: "prepare_pull_request_thread", + environmentId: scope.environmentId, + cwd: scope.cwd, + }), + ), + ); + } + if ( + input.mode === "worktree" && + input.threadId !== undefined && + !readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope) + ) { + return AsyncResult.failure( + Cause.fail( + new EnvironmentAuthorizationError({ + requiredScope: AuthOrchestrationOperateScope, + message: "This connection cannot change threads.", + }), + ), + ); + } + return preparePullRequestThread({ + environmentId: target.environmentId, + input: { + cwd: target.cwd, + reference: input.reference, + mode: input.mode, + ...(input.threadId ? { threadId: input.threadId } : {}), + }, + }); + }; return useAction({ kind: "preparePullRequestThread", label: "Preparing pull request thread", From 998bcc226a70f307913296b859b02c80456b7100 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:27 -0700 Subject: [PATCH 009/323] perf(web): the project icon picker compiles with the React Compiler (#20457) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../settings/ProjectFaviconPickerDialog.tsx | 31 +++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 80ed343d49eb..8bdc4dce4043 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -32,4 +32,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/ThreadNotificationCoordinator.tsx", "apps/web/src/state/queries.ts", "apps/web/src/state/sourceControlActions.ts", + "apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx", ] as const; diff --git a/apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx b/apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx index 5ed077f31bcf..2bfbc6a1fca7 100644 --- a/apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx +++ b/apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx @@ -1,7 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId } from "@t3tools/contracts"; import { isWindowsAbsolutePath } from "@t3tools/shared/path"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { primaryServerKeybindingsAtom } from "~/state/server"; import { useTheme } from "~/hooks/useTheme"; @@ -48,23 +48,22 @@ export function ProjectFaviconPickerDialog(props: { ); const { resolvedTheme } = useTheme(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const pickExternal = props.onPickExternal; + const { onPickExternal: pickExternal, onSelect } = props; const fileManagerName = getLocalFileManagerName( typeof navigator === "undefined" ? "" : navigator.platform, ); - const items = useMemo( - () => - getProjectFilePickerMatches(result.entries, result.matchedQuery).map((match) => ({ - kind: "action", - value: `project-favicon:${match.path}`, - searchTerms: [match.name, match.path], - title: match.name, - description: match.path, - icon: , - run: async () => props.onSelect(match.path), - })), - [props.onSelect, resolvedTheme, result.entries, result.matchedQuery], - ); + const items: CommandPaletteActionItem[] = getProjectFilePickerMatches( + result.entries, + result.matchedQuery, + ).map((match) => ({ + kind: "action", + value: `project-favicon:${match.path}`, + searchTerms: [match.name, match.path], + title: match.name, + description: match.path, + icon: , + run: async () => onSelect(match.path), + })); return ( @@ -89,7 +88,7 @@ export function ProjectFaviconPickerDialog(props: { .then((path) => { if (!path) return; props.onOpenChange(false); - props.onSelect(path); + onSelect(path); }) .catch((error: unknown) => { toastManager.add({ From 275e55cfca59ead9ea39ab1fb514535c91bc4414 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:27 -0700 Subject: [PATCH 010/323] perf(web): the theme editor compiles with the React Compiler (#20458) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../components/settings/ThemeEditorPanel.tsx | 240 +++++++++--------- 2 files changed, 119 insertions(+), 122 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 8bdc4dce4043..f97b38bfb833 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -33,4 +33,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/state/queries.ts", "apps/web/src/state/sourceControlActions.ts", "apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx", + "apps/web/src/components/settings/ThemeEditorPanel.tsx", ] as const; diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsx index 41d5222b2a3a..6fc93c8d3f0f 100644 --- a/apps/web/src/components/settings/ThemeEditorPanel.tsx +++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx @@ -1,12 +1,6 @@ import { MousePointer2Icon, PaintbrushIcon, PlusIcon, XIcon } from "lucide-react"; import { ChevronDown, ChevronUp } from "lucide"; -import { - useCallback, - useEffect, - useRef, - useState, - type PointerEvent as ReactPointerEvent, -} from "react"; +import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; import { applyThemeColorPreview, THEME_COLOR_ROLES, @@ -277,6 +271,37 @@ function getManagedEditorColors( ); } +function clampPanelPosition( + panel: HTMLElement | null, + x: number, + y: number, + widthOverride?: number, +) { + const margin = 8; + // The caller passes a width when it has just shrunk the panel: the DOM + // still reports the old one until React commits. + const width = widthOverride ?? panel?.offsetWidth ?? 0; + return { + x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)), + y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)), + }; +} + +// Kept out of the component: the compiler cannot lower a throw inside try/catch. +function retireMergedTheme(retired: ThemeDefinition, mergeTarget: ThemeDefinition) { + try { + removeCustomTheme(retired.id); + } catch (cause) { + // The merge already persisted. Leaving it while the edited theme + // survives would collide on every retry, so the target goes back to + // its pre-merge palettes before the failure surfaces. + try { + updateCustomTheme(mergeTarget); + } catch {} + throw cause; + } +} + export function ThemeEditorPanel({ open, onOpenChange, @@ -345,7 +370,7 @@ export function ThemeEditorPanel({ }); setPosition((current) => { if (!current) return current; - const clamped = clampPosition(current.x, current.y, clampedWidth); + const clamped = clampPanelPosition(panelRef.current, current.x, current.y, clampedWidth); const height = isMinimized ? (panelRef.current?.offsetHeight ?? 0) : (clampedHeight ?? panelRef.current?.offsetHeight ?? 0); @@ -357,14 +382,13 @@ export function ThemeEditorPanel({ return () => window.removeEventListener("resize", clamp); }, [isMinimized, open]); - // The draft only reaches the live app once this open has been seeded; - // previewing in the seeding commit would paint the previous session's - // colors for a frame. - const [isDraftSeeded, setIsDraftSeeded] = useState(false); - const previousOpenRef = useRef(false); - - useEffect(() => { - if (open && !previousOpenRef.current) { + // Seeded during render so the first open commit already holds this + // session's draft; seeding in an effect would preview the previous + // session's colors for a frame. + const [seededOpen, setSeededOpen] = useState(false); + if (seededOpen !== open) { + setSeededOpen(open); + if (open) { const sourceTheme = editingTheme ?? seedTheme ?? null; const nextColors = getThemeEditorColorsByAppearance(); const nextAppearance = sourceTheme @@ -393,11 +417,8 @@ export function ThemeEditorPanel({ setUsageCount(null); setIsInspecting(false); setError(null); - setIsDraftSeeded(true); } - if (!open && isDraftSeeded) setIsDraftSeeded(false); - previousOpenRef.current = open; - }, [editingTheme, initialAppearance, isDraftSeeded, open, seedName, seedTheme]); + } const nameTargetId = themeIdFromName(name); const normalizedName = name.trim().toLowerCase(); @@ -422,22 +443,25 @@ export function ThemeEditorPanel({ return null; }; - const mergeTargetId = mergeTarget?.id ?? null; - const takenAppearancesKey = takenAppearances.join(","); - useEffect(() => { - if (isEditing || mergeTargetId === null) return; - const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[]; - if (taken.length !== 1) return; - setActiveAppearance((current) => { - if (!taken.includes(current)) return current; - return taken[0] === "light" ? "dark" : "light"; - }); - }, [isEditing, mergeTargetId, takenAppearancesKey]); + // Moves off a palette the merge target already has, once per target change. + const mergeKey = + isEditing || mergeTarget === null ? null : `${mergeTarget.id}:${takenAppearances.join(",")}`; + const [appliedMergeKey, setAppliedMergeKey] = useState(null); + if (appliedMergeKey !== mergeKey) { + setAppliedMergeKey(mergeKey); + if ( + mergeKey !== null && + takenAppearances.length === 1 && + takenAppearances.includes(activeAppearance) + ) { + setActiveAppearance(takenAppearances[0] === "light" ? "dark" : "light"); + } + } useEffect(() => { - if (!open || !isDraftSeeded) return; + if (!open) return; applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance); - }, [activeAppearance, colorsByAppearance, isDraftSeeded, open]); + }, [activeAppearance, colorsByAppearance, open]); useEffect(() => { if (!open) return; @@ -446,34 +470,31 @@ export function ThemeEditorPanel({ }; }, [open, restoreTheme]); - const updateColor = useCallback( - (role: ThemeColorRole, value: string) => { - setColorsByAppearance((current) => { - const nextColors = { ...current[activeAppearance], [role]: value }; - const shouldManageColors = - !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value); + const updateColor = (role: ThemeColorRole, value: string) => { + setColorsByAppearance((current) => { + const nextColors = { ...current[activeAppearance], [role]: value }; + const shouldManageColors = + !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value); - return { - ...current, - [activeAppearance]: isAdvanced - ? updateThemeColorFamily(activeAppearance, current[activeAppearance], role, value) - : shouldManageColors - ? getManagedEditorColors(activeAppearance, nextColors) - : nextColors, - }; - }); - if (!isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value)) { - setSimpleColorsDirtyByAppearance((current) => ({ - ...current, - [activeAppearance]: true, - })); - } - if (isAdvanced) setShouldRegenerateGuidedColors(true); - }, - [activeAppearance, isAdvanced], - ); + return { + ...current, + [activeAppearance]: isAdvanced + ? updateThemeColorFamily(activeAppearance, current[activeAppearance], role, value) + : shouldManageColors + ? getManagedEditorColors(activeAppearance, nextColors) + : nextColors, + }; + }); + if (!isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value)) { + setSimpleColorsDirtyByAppearance((current) => ({ + ...current, + [activeAppearance]: true, + })); + } + if (isAdvanced) setShouldRegenerateGuidedColors(true); + }; - const selectThemeRole = useCallback((role: ThemeColorRole, reveal = false) => { + const selectThemeRole = (role: ThemeColorRole, reveal = false) => { const visibleRole = getThemeEditorColorFamily(role)?.role ?? role; setSelectedRole(visibleRole); if (!THEME_EDITOR_SIMPLE_ROLES.includes(visibleRole)) { @@ -487,17 +508,17 @@ export function ThemeEditorPanel({ ?.querySelector(`[data-theme-color-role="${visibleRole}"]`) ?.scrollIntoView({ behavior: "smooth", block: "nearest" }); }); - }, []); + }; - const toggleThemeRole = useCallback((role: ThemeColorRole) => { + const toggleThemeRole = (role: ThemeColorRole) => { setSelectedRole((current) => (current === role ? null : role)); - }, []); + }; - const clearInspectorSelection = useCallback(() => { + const clearInspectorSelection = () => { setSelectedRole(null); setUsageCount(null); setIsInspecting(false); - }, []); + }; const selectedHighlightRoles = selectedRole ? isAdvanced @@ -514,11 +535,7 @@ export function ThemeEditorPanel({ useEffect(() => { clearThemeInspectorHighlights(); - if (!open || selectedRole === null) { - setUsageCount(null); - return; - } - if (isInspecting) return; + if (!open || selectedRole === null || isInspecting) return; const highlightedRoles = selectedHighlightRolesKey.split(",") as Array; const refreshHighlights = () => setUsageCount(highlightThemeRoleUsage(highlightedRoles)); @@ -559,7 +576,8 @@ export function ThemeEditorPanel({ observer.observe(document.body, { childList: true, subtree: true }); let spotlightFrame: number | null = null; const scheduleSpotlightRefresh = () => { - spotlightFrame ??= requestAnimationFrame(() => { + if (spotlightFrame !== null) return; + spotlightFrame = requestAnimationFrame(() => { spotlightFrame = null; refreshThemeInspectorSpotlight(); }); @@ -574,6 +592,7 @@ export function ThemeEditorPanel({ window.removeEventListener("resize", scheduleSpotlightRefresh); window.removeEventListener("scroll", scheduleSpotlightRefresh, true); clearThemeInspectorHighlights(); + setUsageCount(null); }; }, [isInspecting, open, selectedHighlightRolesKey, selectedRole]); @@ -663,8 +682,8 @@ export function ThemeEditorPanel({ clearInspectorSelection(); }; const refreshHover = () => { - if (!hoverInspection) return; - hoverFrame ??= requestAnimationFrame(() => { + if (!hoverInspection || hoverFrame !== null) return; + hoverFrame = requestAnimationFrame(() => { hoverFrame = null; if (hoverInspection) { showThemeInspectorHover( @@ -698,35 +717,32 @@ export function ThemeEditorPanel({ }; }, [clearInspectorSelection, isInspecting, open, selectThemeRole]); - const handleAdvancedChange = useCallback( - (checked: boolean) => { - setIsAdvanced(checked); - if (checked) return; - if (selectedRole && !THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)) { - setSelectedRole(null); - } - if (!shouldRegenerateGuidedColors) return; + const handleAdvancedChange = (checked: boolean) => { + setIsAdvanced(checked); + if (checked) return; + if (selectedRole && !THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)) { + setSelectedRole(null); + } + if (!shouldRegenerateGuidedColors) return; - const managedAppearances: ReadonlyArray = - editingTheme && getThemeModes(editingTheme).length > 1 - ? ["light", "dark"] - : [activeAppearance]; - setSimpleColorsDirtyByAppearance((current) => { - const next = { ...current }; - for (const appearance of managedAppearances) next[appearance] = true; - return next; - }); - setColorsByAppearance((current) => { - const next = { ...current }; - for (const appearance of managedAppearances) { - next[appearance] = getManagedEditorColors(appearance, current[appearance]); - } - return next; - }); - setShouldRegenerateGuidedColors(false); - }, - [activeAppearance, editingTheme, selectedRole, shouldRegenerateGuidedColors], - ); + const managedAppearances: ReadonlyArray = + editingTheme && getThemeModes(editingTheme).length > 1 + ? ["light", "dark"] + : [activeAppearance]; + setSimpleColorsDirtyByAppearance((current) => { + const next = { ...current }; + for (const appearance of managedAppearances) next[appearance] = true; + return next; + }); + setColorsByAppearance((current) => { + const next = { ...current }; + for (const appearance of managedAppearances) { + next[appearance] = getManagedEditorColors(appearance, current[appearance]); + } + return next; + }); + setShouldRegenerateGuidedColors(false); + }; const handleSubmit = () => { if (!name.trim()) { @@ -773,17 +789,7 @@ export function ThemeEditorPanel({ ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}), }); retiredTheme = editingTheme; - try { - removeCustomTheme(editingTheme.id); - } catch (cause) { - // The merge already persisted. Leaving it while the edited theme - // survives would collide on every retry, so the target goes back to - // its pre-merge palettes before the failure surfaces. - try { - updateCustomTheme(mergeTarget); - } catch {} - throw cause; - } + retireMergedTheme(editingTheme, mergeTarget); } else if (editingTheme) { const baseAppearance = editingTheme.appearance; const variantAppearance = baseAppearance === "light" ? "dark" : "light"; @@ -1015,17 +1021,7 @@ export function ThemeEditorPanel({ ); }; - const clampPosition = (x: number, y: number, widthOverride?: number) => { - const panel = panelRef.current; - const margin = 8; - // The caller passes a width when it has just shrunk the panel: the DOM - // still reports the old one until React commits. - const width = widthOverride ?? panel?.offsetWidth ?? 0; - return { - x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)), - y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)), - }; - }; + const clampPosition = (x: number, y: number) => clampPanelPosition(panelRef.current, x, y); const handleDragPointerDown = (event: ReactPointerEvent) => { if ((event.target as HTMLElement).closest("button, input, a")) return; From a17781f638226b2f1c5f46954175e2be969ad112 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:27 -0700 Subject: [PATCH 011/323] perf(web): panel presence keeps its retained value in state (#20459) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/panelAnimations.ts | 27 ++++++++++----------------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index f97b38bfb833..5a16279017f2 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -34,4 +34,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/state/sourceControlActions.ts", "apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx", "apps/web/src/components/settings/ThemeEditorPanel.tsx", + "apps/web/src/panelAnimations.ts", ] as const; diff --git a/apps/web/src/panelAnimations.ts b/apps/web/src/panelAnimations.ts index e917fbca3865..efbdfa526d5a 100644 --- a/apps/web/src/panelAnimations.ts +++ b/apps/web/src/panelAnimations.ts @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { createContext, useContext, useEffect, useState } from "react"; import { type PanelAnimationDurationMs } from "@t3tools/contracts/settings"; import { useMediaQuery } from "./hooks/useMediaQuery"; @@ -45,30 +45,23 @@ export function usePanelPresence( durationMs: PanelAnimationDurationMs, ): { present: boolean; value: T | null } { const [present, setPresent] = useState(open); - const retainedRef = useRef<{ scopeKey: string | null; value: T | null } | null>( + const [retained, setRetained] = useState<{ scopeKey: string | null; value: T | null } | null>( open ? { scopeKey, value } : null, ); + if (open && (retained?.scopeKey !== scopeKey || retained.value !== value)) { + setRetained({ scopeKey, value }); + } - useEffect(() => { - if (open) retainedRef.current = { scopeKey, value }; - }, [open, scopeKey, value]); + if (open && !present) setPresent(true); + if (!open && !animated && present) setPresent(false); useEffect(() => { - if (open) { - setPresent(true); - return; - } - if (!animated) { - setPresent(false); - return; - } - + if (open || !animated) return; const timeout = window.setTimeout(() => setPresent(false), durationMs); return () => window.clearTimeout(timeout); }, [animated, durationMs, open]); - const retainedValue = - retainedRef.current?.scopeKey === scopeKey ? retainedRef.current.value : null; - const visible = open || (animated && present && retainedRef.current?.scopeKey === scopeKey); + const retainedValue = retained?.scopeKey === scopeKey ? retained.value : null; + const visible = open || (animated && present && retained?.scopeKey === scopeKey); return { present: visible, value: open ? value : visible ? retainedValue : null }; } From 6293119f83e90062001c622e17841dc189efe1b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:28 -0700 Subject: [PATCH 012/323] perf(web): useCopyToClipboard reads its options through useStableCallback (#20460) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/hooks/useCopyToClipboard.ts | 28 ++++++++---------------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 5a16279017f2..23cedd8017bf 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -35,4 +35,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx", "apps/web/src/components/settings/ThemeEditorPanel.tsx", "apps/web/src/panelAnimations.ts", + "apps/web/src/hooks/useCopyToClipboard.ts", ] as const; diff --git a/apps/web/src/hooks/useCopyToClipboard.ts b/apps/web/src/hooks/useCopyToClipboard.ts index 53193188127e..5e81662b254a 100644 --- a/apps/web/src/hooks/useCopyToClipboard.ts +++ b/apps/web/src/hooks/useCopyToClipboard.ts @@ -4,6 +4,7 @@ import { COMPOSER_CONTEXT_CLIPBOARD_MIME, encodeComposerContextClipboardHtml, } from "@t3tools/shared/composerContextClipboard"; +import { useStableCallback } from "./useStableCallback"; export class ClipboardApiUnavailableError extends Schema.TaggedError()( "ClipboardApiUnavailableError", @@ -206,20 +207,9 @@ export function useCopyToClipboard({ } = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } { const [isCopied, setIsCopied] = React.useState(false); const timeoutIdRef = React.useRef(null); - const onCopyRef = React.useRef(onCopy); - const onErrorRef = React.useRef(onError); - const targetRef = React.useRef(target); - const timeoutRef = React.useRef(timeout); - - onCopyRef.current = onCopy; - onErrorRef.current = onError; - const extraFlavorsRef = React.useRef(extraFlavors); - targetRef.current = target; - timeoutRef.current = timeout; - extraFlavorsRef.current = extraFlavors; - - const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => { - void writeTextToClipboard(value, targetRef.current, extraFlavorsRef.current).then( + // Callers pass inline onCopy/onError but key callbacks and effects on this function. + const copyToClipboard = useStableCallback((value: string, ctx: TContext): void => { + void writeTextToClipboard(value, target, extraFlavors).then( (didCopy) => { if (!didCopy) return; if (timeoutIdRef.current) { @@ -227,21 +217,21 @@ export function useCopyToClipboard({ } setIsCopied(true); - onCopyRef.current?.(ctx); + onCopy?.(ctx); - if (timeoutRef.current !== 0) { + if (timeout !== 0) { timeoutIdRef.current = setTimeout(() => { setIsCopied(false); timeoutIdRef.current = null; - }, timeoutRef.current); + }, timeout); } }, (error) => { console.error(error); - onErrorRef.current?.(error, ctx); + onError?.(error, ctx); }, ); - }, []); + }); React.useEffect(() => { return (): void => { From 222ebe071e4c825574d37b180c8ab60dfecf3c15 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:28 -0700 Subject: [PATCH 013/323] perf(web): pairing surfaces read their URL token from lazy state (#20461) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../components/auth/PairingRouteSurface.tsx | 89 +++++++++---------- 2 files changed, 44 insertions(+), 46 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 23cedd8017bf..9a66d272d6fb 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -36,4 +36,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/settings/ThemeEditorPanel.tsx", "apps/web/src/panelAnimations.ts", "apps/web/src/hooks/useCopyToClipboard.ts", + "apps/web/src/components/auth/PairingRouteSurface.tsx", ] as const; diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index 4eac3c2b70a1..766029e93c7f 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -1,7 +1,7 @@ import { Alert, AlertDescription } from "../ui/alert"; import type { AuthSessionState } from "@t3tools/contracts"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import React, { startTransition, useEffect, useRef, useState, useCallback } from "react"; +import React, { startTransition, useEffect, useEffectEvent, useRef, useState } from "react"; import { APP_DISPLAY_NAME } from "../../branding"; import { connectPairing } from "../../connection/onboarding"; @@ -37,54 +37,51 @@ export function PairingRouteSurface({ initialErrorMessage?: string; onAuthenticated: () => void; }) { - const autoPairTokenRef = useRef(peekPairingTokenFromUrl()); - const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? ""); + const [autoPairToken] = useState(peekPairingTokenFromUrl); + const [credential, setCredential] = useState(autoPairToken ?? ""); const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? ""); const [isSubmitting, setIsSubmitting] = useState(false); const autoSubmitAttemptedRef = useRef(false); - const submitCredential = useCallback( - async (nextCredential: string) => { - setIsSubmitting(true); - setErrorMessage(""); + const submitCredential = async (nextCredential: string) => { + setIsSubmitting(true); + setErrorMessage(""); - const submitError = await submitServerAuthCredential(nextCredential).then( - () => null, - (error) => errorMessageFromUnknown(error), - ); + const submitError = await submitServerAuthCredential(nextCredential).then( + () => null, + (error) => errorMessageFromUnknown(error), + ); - setIsSubmitting(false); + setIsSubmitting(false); - if (submitError) { - setErrorMessage(submitError); - return; - } + if (submitError) { + setErrorMessage(submitError); + return; + } - startTransition(() => { - onAuthenticated(); - }); - }, - [onAuthenticated], - ); + startTransition(() => { + onAuthenticated(); + }); + }; - const handleSubmit = useCallback( - async (event?: React.SubmitEvent) => { - event?.preventDefault(); - await submitCredential(credential); - }, - [submitCredential, credential], - ); + const handleSubmit = async (event?: React.SubmitEvent) => { + event?.preventDefault(); + await submitCredential(credential); + }; + + const autoSubmit = useEffectEvent((token: string) => { + void submitCredential(token); + }); useEffect(() => { - const token = autoPairTokenRef.current; - if (!token || autoSubmitAttemptedRef.current) { + if (!autoPairToken || autoSubmitAttemptedRef.current) { return; } autoSubmitAttemptedRef.current = true; stripPairingTokenFromUrl(); - void submitCredential(token); - }, [submitCredential]); + autoSubmit(autoPairToken); + }, [autoPairToken]); return ( @@ -145,12 +142,12 @@ export function HostedPairingRouteSurface() { const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false, }); - const hostedPairingRequestRef = useRef(readHostedPairingRequest()); - const [status, setStatus] = useState<"pairing" | "paired" | "error">(() => - hostedPairingRequestRef.current ? "pairing" : "error", + const [request] = useState(readHostedPairingRequest); + const [status, setStatus] = useState<"pairing" | "paired" | "error">( + request ? "pairing" : "error", ); - const [message, setMessage] = useState(() => - hostedPairingRequestRef.current + const [message, setMessage] = useState( + request ? "Connecting to this backend." : "This pairing link is missing its backend host or token.", ); @@ -158,9 +155,7 @@ export function HostedPairingRouteSurface() { const submitAttemptedRef = useRef(false); const tokenSubmittedRef = useRef(false); - const submitHostedPairingRequest = useCallback(async () => { - const request = hostedPairingRequestRef.current; - + const submitHostedPairingRequest = async () => { if (!request) { setStatus("error"); setMessage("This pairing link is missing its backend host or token."); @@ -196,7 +191,11 @@ export function HostedPairingRouteSurface() { setMessage( `${errorMessageFromUnknown(squashAtomCommandFailure(result))} If the backend accepted this one-time token, request a new pairing link before retrying.`, ); - }, [connectPairingEnvironment]); + }; + + const submitOnMount = useEffectEvent(() => { + void submitHostedPairingRequest(); + }); useEffect(() => { if (submitAttemptedRef.current) { @@ -205,10 +204,8 @@ export function HostedPairingRouteSurface() { submitAttemptedRef.current = true; stripPairingTokenFromUrl(); - void submitHostedPairingRequest(); - }, [submitHostedPairingRequest]); - - const request = hostedPairingRequestRef.current; + submitOnMount(); + }, []); return ( From 546c67f443765cebcecbc5db96999ac36aafbadc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:29 -0700 Subject: [PATCH 014/323] perf(web): sidebar retained git status lives in state (#20462) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/components/Sidebar.logic.ts | 32 +++++++++++------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 9a66d272d6fb..a5ed6cf74329 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -37,4 +37,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/panelAnimations.ts", "apps/web/src/hooks/useCopyToClipboard.ts", "apps/web/src/components/auth/PairingRouteSurface.tsx", + "apps/web/src/components/Sidebar.logic.ts", ] as const; diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 2334b679b3d5..94db97c388a2 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -71,17 +71,12 @@ export function useSidebarRowSubscriptionLease(isActive: boolean): { } { const [row, setRow] = React.useState(null); const [isNearViewport, setIsNearViewport] = React.useState(isActive); + // The active row stays leased after it deactivates until the observer reports. + if (isActive && !isNearViewport) setIsNearViewport(true); + const canObserve = typeof IntersectionObserver !== "undefined"; React.useEffect(() => { - if (isActive) { - setIsNearViewport(true); - return; - } - if (row === null) return; - if (typeof IntersectionObserver === "undefined") { - setIsNearViewport(true); - return; - } + if (isActive || row === null || !canObserve) return; const scrollRoot = row.closest('[data-slot="scroll-area-viewport"]'); const observer = new IntersectionObserver( @@ -93,21 +88,24 @@ export function useSidebarRowSubscriptionLease(isActive: boolean): { ); observer.observe(row); return () => observer.disconnect(); - }, [isActive, row]); + }, [canObserve, isActive, row]); return { - leaseLiveStatus: isActive || isNearViewport, + leaseLiveStatus: isActive || isNearViewport || !canObserve, rowRef: setRow, }; } export function useRetainedValue(key: string | null, value: T | null): T | null { - const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null); - if (key !== null && value !== null) { - retained.current = { key, value }; + const [retained, setRetained] = React.useState<{ + readonly key: string; + readonly value: T; + } | null>(null); + if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) { + setRetained({ key, value }); } if (value !== null) return value; - return key !== null && retained.current?.key === key ? retained.current.value : null; + return key !== null && retained?.key === key ? retained.value : null; } // Sidebar.motion handles ordinary section changes. Sortable transforms own @@ -688,9 +686,9 @@ export function useThreadJumpHintVisibility(): { }; }, []); - const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => { + const updateThreadJumpHintsVisibility = (shouldShow: boolean) => { controllerRef.current?.sync(shouldShow); - }, []); + }; return { showThreadJumpHints, From 23290944bce8a2ff9f9438cb6d16f152559858d8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:29 -0700 Subject: [PATCH 015/323] perf(web): viewed-file tracking passes its flush target instead of reading refs (#20463) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../pullRequest/usePullRequestFilesViewed.ts | 86 ++++++++----------- 2 files changed, 38 insertions(+), 49 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index a5ed6cf74329..752a0fab7071 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -38,4 +38,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/hooks/useCopyToClipboard.ts", "apps/web/src/components/auth/PairingRouteSurface.tsx", "apps/web/src/components/Sidebar.logic.ts", + "apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts", ] as const; diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts index 0c3327fd0a87..86396134f9b8 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts @@ -1,10 +1,11 @@ import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useEffectEvent, useRef, useState } from "react"; import { pullRequestEnvironment } from "~/state/pullRequests"; import { useEnvironmentQuery } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { toastManager } from "../ui/toast"; import { @@ -45,7 +46,7 @@ export function usePullRequestFilesViewed(options: { enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null, ); const refresh = query.refresh; - const states = useMemo(() => toFileViewedStates(query.data), [query.data]); + const states = toFileViewedStates(query.data); const truncated = query.data?.truncated === true; const error = query.error; const [overlay, setOverlay] = useState(NO_OVERLAY); @@ -68,10 +69,11 @@ export function usePullRequestFilesViewed(options: { // answer that differs from it is the first read that could have seen the write, which is what // retires the press rather than the host happening to agree with it. const answeredFrom = useRef>(new Map()); - const statesRef = useRef(states); - statesRef.current = states; + // The committed answer, read when a write completes rather than when it was sent. + const committedStates = useRef(states); useEffect(() => { + committedStates.current = states; const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]); const answered = new Set(); for (const [path, from] of answeredFrom.current) { @@ -82,7 +84,11 @@ export function usePullRequestFilesViewed(options: { setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered)); }, [states]); - const flush = useCallback(() => { + // Takes the target explicitly so a scope being left still sends its last presses to itself. + const flush = (target: { + readonly environmentId: EnvironmentId; + readonly reference: PullRequestRef; + }) => { flushTimer.current = null; const batch = toFileViewedBatch(queued.current); if (batch.length === 0) return; @@ -90,7 +96,10 @@ export function usePullRequestFilesViewed(options: { const sentFrom = scope.current; const request = ++requests.current; for (const file of batch) sentBy.current.set(file.path, request); - void setFilesViewed({ environmentId, input: { ...reference, files: batch } }).then((result) => { + void setFilesViewed({ + environmentId: target.environmentId, + input: { ...target.reference, files: batch }, + }).then((result) => { const mine = batch .map((file) => file.path) .filter((path) => sentBy.current.get(path) === request); @@ -106,26 +115,23 @@ export function usePullRequestFilesViewed(options: { } // Answered for from the next read on, whatever it says. A push landing between the write // and that read comes back as `dismissed`, and the press must not stand over it. - for (const path of mine) answeredFrom.current.set(path, statesRef.current); + for (const path of mine) answeredFrom.current.set(path, committedStates.current); refresh(); }); - }, [environmentId, reference, refresh, setFilesViewed]); + }; - // Read through a ref rather than closed over: `setViewed` is handed to every file header the - // viewer draws, and a new identity per render would rebuild all of them. - const flushRef = useRef(flush); - flushRef.current = flush; + const currentTarget = useEffectEvent(() => ({ environmentId, reference })); + const flushTarget = useEffectEvent(flush); // Leaving a change request, the environment it lives on, or the page itself records what was - // pressed and then drops the rest. The flush kept here is the one bound to the scope being - // left, which is what sends those last presses where they were meant to go. + // pressed and then drops the rest, sending those last presses to the scope being left. useEffect(() => { - const flushScope = flushRef.current; + const leaving = currentTarget(); scope.current = scopeKey; return () => { if (flushTimer.current !== null) { clearTimeout(flushTimer.current); - flushScope(); + flushTarget(leaving); } queued.current = new Map(); sentBy.current = new Map(); @@ -134,41 +140,23 @@ export function usePullRequestFilesViewed(options: { }; }, [scopeKey]); - const refreshRef = useRef(refresh); - refreshRef.current = refresh; - const refreshFromHost = useCallback(() => refreshRef.current(), []); - - const setViewed = useCallback((path: string, viewed: boolean) => { + // Handed to every file header the viewer draws; a new identity would rebuild all of them. + const setViewed = useStableCallback((path: string, viewed: boolean) => { setOverlay((current) => new Map(current).set(path, viewed)); queued.current.set(path, viewed); if (flushTimer.current !== null) clearTimeout(flushTimer.current); - flushTimer.current = setTimeout(() => flushRef.current(), FLUSH_DELAY_MS); - }, []); - - const isViewed = useCallback( - (path: string) => isFileViewed(path, states, overlay), - [overlay, states], - ); - const isStale = useCallback( - (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)), - [overlay, states], - ); - const viewedCount = useMemo( - () => countViewedFiles(paths, states, overlay), - [overlay, paths, states], - ); + const target = { environmentId, reference }; + flushTimer.current = setTimeout(() => flush(target), FLUSH_DELAY_MS); + }); - return useMemo( - () => ({ - enabled, - isViewed, - isStale, - setViewed, - viewedCount, - truncated, - error, - refresh: refreshFromHost, - }), - [enabled, error, isStale, isViewed, refreshFromHost, setViewed, truncated, viewedCount], - ); + return { + enabled, + isViewed: (path: string) => isFileViewed(path, states, overlay), + isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)), + setViewed, + viewedCount: countViewedFiles(paths, states, overlay), + truncated, + error, + refresh, + }; } From de89a7a76dfae79c1defbd7baa9cd7abd5154a6f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:29 -0700 Subject: [PATCH 016/323] perf(web): useLiveRefresh reads its callback through useEffectEvent (#20464) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/hooks/useLiveRefresh.ts | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 752a0fab7071..d85925d8dfb8 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -39,4 +39,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/auth/PairingRouteSurface.tsx", "apps/web/src/components/Sidebar.logic.ts", "apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts", + "apps/web/src/hooks/useLiveRefresh.ts", ] as const; diff --git a/apps/web/src/hooks/useLiveRefresh.ts b/apps/web/src/hooks/useLiveRefresh.ts index 18e4784932fe..90d76d3ff786 100644 --- a/apps/web/src/hooks/useLiveRefresh.ts +++ b/apps/web/src/hooks/useLiveRefresh.ts @@ -1,4 +1,4 @@ -import { useEffect, useId, useRef } from "react"; +import { useEffect, useEffectEvent, useId } from "react"; export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000; @@ -83,20 +83,19 @@ export function useLiveRefresh( } = {}, ): void { const { enabled = true, key, intervalMs = LIVE_REFRESH_INTERVAL_MS } = options; - // Held in a ref so a caller can pass a fresh closure every render without re-arming the + // An effect event so a caller can pass a fresh closure every render without re-arming the // listeners, which would otherwise refresh on every render that changed anything at all. - const latest = useRef(refresh); - latest.current = refresh; + const runRefresh = useEffectEvent((viewId: string, now: number) => { + if (refresh === null) return; + lastRefreshedAtByView.set(viewId, now); + refresh(); + }); const fallbackViewId = useId(); const viewId = key ?? fallbackViewId; useEffect(() => { if (!enabled) return; - const read = (now: number) => { - if (latest.current === null) return; - lastRefreshedAtByView.set(viewId, now); - latest.current(); - }; + const read = (now: number) => runRefresh(viewId, now); const visible = () => document.visibilityState === "visible"; const onArrival = () => { const now = Date.now(); From 635396ca3cdc858f7d829e3b31dd498cda2a8cab Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:30 -0700 Subject: [PATCH 017/323] perf(web): browser viewport resize checks its source through a stable callback (#20465) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../src/browser/useBrowserViewportResize.ts | 35 +++++++++---------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index d85925d8dfb8..f41f4227d6e8 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -40,4 +40,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/Sidebar.logic.ts", "apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts", "apps/web/src/hooks/useLiveRefresh.ts", + "apps/web/src/browser/useBrowserViewportResize.ts", ] as const; diff --git a/apps/web/src/browser/useBrowserViewportResize.ts b/apps/web/src/browser/useBrowserViewportResize.ts index f56c17874fce..924e3730bd98 100644 --- a/apps/web/src/browser/useBrowserViewportResize.ts +++ b/apps/web/src/browser/useBrowserViewportResize.ts @@ -2,7 +2,6 @@ import type { PreviewViewportSetting, PreviewViewportSize } from "@t3tools/contracts"; import { - useCallback, useEffect, useRef, useState, @@ -10,6 +9,7 @@ import { type PointerEvent as ReactPointerEvent, } from "react"; +import { useStableCallback } from "../hooks/useStableCallback"; import { commitBrowserViewportChange } from "./browserViewportActions"; import { browserViewportSettingKey, @@ -43,8 +43,8 @@ export function useBrowserViewportResize(options: { const keyboardViewportRef = useRef(null); const [dragViewport, setDragViewport] = useState(null); const sourceViewportKey = browserViewportSettingKey(viewport); - const sourceViewportKeyRef = useRef(sourceViewportKey); - sourceViewportKeyRef.current = sourceViewportKey; + // Drag listeners and the keyboard commit timer outlive the render that started them. + const isCurrentSource = useStableCallback((key: string) => key === sourceViewportKey); const activeDrag = dragViewport?.sourceKey === sourceViewportKey ? dragViewport : null; const effectiveViewport = activeDrag ? ({ @@ -85,20 +85,17 @@ export function useBrowserViewportResize(options: { keyboardViewportRef.current = null; }, [sourceViewportKey]); - const commitViewportChange = useCallback( - (next: PreviewViewportSetting) => { - dragVersionRef.current += 1; - dragCleanupRef.current?.(); - if (keyboardCommitTimerRef.current !== null) { - clearTimeout(keyboardCommitTimerRef.current); - keyboardCommitTimerRef.current = null; - } - keyboardViewportRef.current = null; - setDragViewport(null); - return commitBrowserViewportChange(tabId, next); - }, - [tabId], - ); + const commitViewportChange = (next: PreviewViewportSetting) => { + dragVersionRef.current += 1; + dragCleanupRef.current?.(); + if (keyboardCommitTimerRef.current !== null) { + clearTimeout(keyboardCommitTimerRef.current); + keyboardCommitTimerRef.current = null; + } + keyboardViewportRef.current = null; + setDragViewport(null); + return commitBrowserViewportChange(tabId, next); + }; const clearDrag = () => setDragViewport(null); const commitDrag = (next: PreviewViewportSetting) => { @@ -149,7 +146,7 @@ export function useBrowserViewportResize(options: { keyboardCommitTimerRef.current = setTimeout(() => { keyboardCommitTimerRef.current = null; const latest = keyboardViewportRef.current; - if (!latest || latest.sourceKey !== sourceViewportKeyRef.current) return; + if (!latest || !isCurrentSource(latest.sourceKey)) return; keyboardViewportRef.current = null; commitDrag({ _tag: "freeform", width: latest.width, height: latest.height }); }, KEYBOARD_RESIZE_COMMIT_DELAY_MS); @@ -187,7 +184,7 @@ export function useBrowserViewportResize(options: { target.setPointerCapture(pointerId); } catch {} - const sourceChanged = () => sourceViewportKeyRef.current !== sourceViewportKey; + const sourceChanged = () => !isCurrentSource(sourceViewportKey); const move = (moveEvent: PointerEvent) => { if (moveEvent.pointerId !== pointerId) return; if (sourceChanged()) { From 1544a94578c14c17c1e6ed52c077d9b978769e76 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:30 -0700 Subject: [PATCH 018/323] perf(web): snapshot coordinator keeps the last route target in state (#20466) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../desktop/SnapShotCoordinator.tsx | 103 +++++++++++------- 2 files changed, 67 insertions(+), 37 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index f41f4227d6e8..aa87a56659e0 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -41,4 +41,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts", "apps/web/src/hooks/useLiveRefresh.ts", "apps/web/src/browser/useBrowserViewportResize.ts", + "apps/web/src/components/desktop/SnapShotCoordinator.tsx", ] as const; diff --git a/apps/web/src/components/desktop/SnapShotCoordinator.tsx b/apps/web/src/components/desktop/SnapShotCoordinator.tsx index 19afa2323fc0..429667b09e84 100644 --- a/apps/web/src/components/desktop/SnapShotCoordinator.tsx +++ b/apps/web/src/components/desktop/SnapShotCoordinator.tsx @@ -1,9 +1,10 @@ import { type DesktopPendingSnapShot, + type DesktopSnapShotEvent, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, type ScopedThreadRef, } from "@t3tools/contracts"; -import { useCallback, useEffect, useRef } from "react"; +import { useEffect, useEffectEvent, useRef, useState } from "react"; import { type DraftId, @@ -11,6 +12,7 @@ import { useComposerDraftStore, } from "../../composerDraftStore"; import { useHandleNewThread } from "../../hooks/useHandleNewThread"; +import { useStableCallback } from "../../hooks/useStableCallback"; import { useClientSettings } from "../../hooks/useSettings"; import { readThreadShell } from "../../state/entities"; import { compressImageToByteLimit, dataUrlToFile } from "../../lib/imageCompression"; @@ -36,6 +38,11 @@ import { stackedThreadToast, toastManager } from "../ui/toast"; type CaptureTarget = DraftId | ScopedThreadRef; +function isSameCaptureTarget(a: CaptureTarget, b: CaptureTarget): boolean { + if (typeof a === "string" || typeof b === "string") return a === b; + return a.environmentId === b.environmentId && a.threadId === b.threadId; +} + export function resolveExistingSnapShotTarget( target: CaptureTarget, routeThreadRef: ScopedThreadRef | null, @@ -207,25 +214,48 @@ export function SnapShotCoordinator() { ); const animateCaptures = useClientSettings((settings) => settings.snapShotAnimations); const captureTargetsRef = useRef(new Map>()); - const lastTargetRef = useRef(null); const targetResolutionRef = useRef | null>(null); const drainingRef = useRef | null>(null); const rerunRequestedRef = useRef(false); const soundedCaptureIdsRef = useRef(new Set()); const pendingAnimationStartsRef = useRef(new Set()); + // Captures go to the last thread or draft on screen, even from routes that show neither. const currentTarget = routeThreadRef ?? routeDraftId; - if (currentTarget) lastTargetRef.current = currentTarget; + const [lastRouteTarget, setLastRouteTarget] = useState(currentTarget); + if ( + currentTarget && + (lastRouteTarget === null || !isSameCaptureTarget(currentTarget, lastRouteTarget)) + ) { + setLastRouteTarget(currentTarget); + } + // What a resolution settled on (a promoted draft, a new draft, or nothing) stands in for the + // route's target until the route moves on, so captures in one drain share one new draft. + const settledTargetRef = useRef<{ + readonly routeTarget: CaptureTarget | null; + readonly target: CaptureTarget | null; + } | null>(null); + const readLastRouteTarget = useStableCallback(() => lastRouteTarget); + // A resolution records what it settled on against the route it started from, so a + // route change while it is pending cannot hand that draft to the new route. + const readSettledTarget = (routeTarget: CaptureTarget | null) => { + const settled = settledTargetRef.current; + return settled && settled.routeTarget === routeTarget ? settled.target : routeTarget; + }; + const settleTarget = (routeTarget: CaptureTarget | null, target: CaptureTarget | null) => { + settledTargetRef.current = { routeTarget, target }; + }; - const resolveTarget = useCallback(async (): Promise => { - const lastTarget = lastTargetRef.current; + const resolveTarget = async (): Promise => { + const routeTarget = readLastRouteTarget(); + const lastTarget = readSettledTarget(routeTarget); if (lastTarget) { const existingTarget = resolveExistingSnapShotTarget(lastTarget, routeThreadRef); if (existingTarget) { - lastTargetRef.current = existingTarget; + settleTarget(routeTarget, existingTarget); return existingTarget; } - lastTargetRef.current = null; + settleTarget(routeTarget, null); } const projectRef = resolveThreadActionProjectRef({ activeDraftThread, @@ -236,27 +266,21 @@ export function SnapShotCoordinator() { if (!projectRef) return null; const created = await handleNewThread(projectRef); if (!created) return null; - lastTargetRef.current = created.draftId; + settleTarget(routeTarget, created.draftId); return created.draftId; - }, [activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef]); + }; - const resolveCaptureTarget = useCallback( - () => resolveSnapShotTargetOnce(targetResolutionRef, resolveTarget), - [resolveTarget], - ); + const resolveCaptureTarget = () => resolveSnapShotTargetOnce(targetResolutionRef, resolveTarget); - const playCaptureSound = useCallback( - (id: string) => { - if (!captureSound || soundedCaptureIdsRef.current.has(id)) return; - soundedCaptureIdsRef.current.add(id); - try { - playSnapShotSound(captureSound); - } catch {} - }, - [captureSound], - ); + const playCaptureSound = (id: string) => { + if (!captureSound || soundedCaptureIdsRef.current.has(id)) return; + soundedCaptureIdsRef.current.add(id); + try { + playSnapShotSound(captureSound); + } catch {} + }; - const drain = useCallback(async () => { + const drain = async () => { const bridge = getDesktopSnapShotBridge(); if (!bridge) return; if (drainingRef.current) { @@ -326,16 +350,16 @@ export function SnapShotCoordinator() { }); drainingRef.current = operation; return operation; - }, [playCaptureSound, resolveCaptureTarget, routeThreadRef]); + }; - useEffect(() => { - const bridge = getDesktopSnapShotBridge(); - if (!bridge) return; - void drain(); - const unsubscribe = bridge.onSnapShotEvent((event) => { + // Subscriptions read the latest handlers through effect events, so they attach once + // instead of restarting (and re-draining) whenever a handler's inputs change. + const drainPending = useEffectEvent(() => drain()); + const handleSnapShotEvent = useEffectEvent( + (bridge: DesktopSnapShotBridge, event: DesktopSnapShotEvent) => { switch (event.type) { case "requested": { - const current = lastTargetRef.current; + const current = readSettledTarget(readLastRouteTarget()); const target = current ? resolveExistingSnapShotTarget(current, routeThreadRef) : null; // Creating a new draft would navigate the renderer before a self-capture finishes. if (target) { @@ -384,19 +408,24 @@ export function SnapShotCoordinator() { case "shortcut-changed": return; } - }); - return unsubscribe; - }, [animateCaptures, drain, playCaptureSound, resolveCaptureTarget, routeThreadRef]); + }, + ); + useEffect(() => { + const bridge = getDesktopSnapShotBridge(); + if (!bridge) return; + void drainPending(); + return bridge.onSnapShotEvent((event) => handleSnapShotEvent(bridge, event)); + }, []); useEffect(() => { const dismissOnBlur = () => { pendingAnimationStartsRef.current.clear(); dismissAllSnapShotAnimations(); }; - const drainOnFocus = () => void drain(); + const drainOnFocus = () => void drainPending(); const handleVisibilityChange = () => { if (document.visibilityState === "hidden") dismissOnBlur(); - else void drain(); + else void drainPending(); }; window.addEventListener("blur", dismissOnBlur); window.addEventListener("focus", drainOnFocus); @@ -406,7 +435,7 @@ export function SnapShotCoordinator() { window.removeEventListener("focus", drainOnFocus); document.removeEventListener("visibilitychange", handleVisibilityChange); }; - }, [drain]); + }, []); return null; } From 10d4fab2941f89707f08d441fac1b9b24f48d80c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:31 -0700 Subject: [PATCH 019/323] perf(web): branch toolbar label measuring reads its state through useEffectEvent (#20467) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/components/BranchToolbar.tsx | 58 ++++++++--------------- 2 files changed, 22 insertions(+), 37 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index aa87a56659e0..85542f1a7a69 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -42,4 +42,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/hooks/useLiveRefresh.ts", "apps/web/src/browser/useBrowserViewportResize.ts", "apps/web/src/components/desktop/SnapShotCoordinator.tsx", + "apps/web/src/components/BranchToolbar.tsx", ] as const; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 9d1ffe2c5e9e..3a9f2e1b1163 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -16,10 +16,9 @@ import { type MouseEvent as ReactMouseEvent, memo, useImperativeHandle, - useCallback, useEffect, + useEffectEvent, useLayoutEffect, - useMemo, useRef, useState, } from "react"; @@ -179,10 +178,8 @@ const RunContextSelector = memo(function RunContextSelector({ onUsePreviousWorktree, }: RunContextSelectorProps) { const composerFloatingLayerProps = useComposerMenuProps(); - const activeEnvironment = useMemo( - () => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null, - [availableEnvironments, environmentId], - ); + const activeEnvironment = + availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null; const WorkspaceIcon = effectiveEnvMode === "worktree" ? FolderGit2Icon @@ -425,14 +422,9 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean { const [overflows, setOverflows] = useState(false); const pendingLabelRectsRef = useRef | null>(null); const labelAnimationsRef = useRef(new Map()); - // A render-synced mirror instead of useEffectEvent: the compiler memoizes - // the event callback, which left observers reading the first render's null - // element forever. - const stateRef = useRef({ element, overflows }); - stateRef.current = { element, overflows }; - - const measure = useCallback(() => { - const { element: current, overflows: compact } = stateRef.current; + const measure = useEffectEvent(() => { + const current = element; + const compact = overflows; if (!current) return; const available = current.clientWidth; if (available === 0) return; @@ -495,7 +487,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean { ); } setOverflows(nextOverflows); - }, []); + }); useLayoutEffect(() => { const previousRects = pendingLabelRectsRef.current; @@ -536,7 +528,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean { { once: true }, ); } - }, [overflows]); + }); useEffect( () => () => { @@ -548,6 +540,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean { ); useLayoutEffect(() => { + // oxlint-disable-next-line react/set-state-in-effect -- The label mode comes from measuring the committed DOM, which render cannot read. measure(); }); @@ -559,7 +552,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean { stopObserving(); document.fonts.removeEventListener("loadingdone", measure); }; - }, [element, measure]); + }, [element]); return overflows; } @@ -590,10 +583,7 @@ export const BranchToolbar = memo(function BranchToolbar({ contextStripVisible = true, }: BranchToolbarProps) { const branchSelectorRef = useRef(null); - const threadRef = useMemo( - () => scopeThreadRef(environmentId, threadId), - [environmentId, threadId], - ); + const threadRef = scopeThreadRef(environmentId, threadId); const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); @@ -614,25 +604,19 @@ export const BranchToolbar = memo(function BranchToolbar({ const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree; - const projectRefsForWorktreeLookup = useMemo( - () => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []), - [canUsePreviousWorktree, activeProjectRef], - ); + const projectRefsForWorktreeLookup = + canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []; const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup); - const previousWorktreeSeed = useMemo( - () => - canUsePreviousWorktree - ? resolvePreviousWorktreeSeed({ - threads: projectThreads, - currentWorktreePath: activeWorktreePath, - }) - : null, - [activeWorktreePath, canUsePreviousWorktree, projectThreads], - ); + const previousWorktreeSeed = canUsePreviousWorktree + ? resolvePreviousWorktreeSeed({ + threads: projectThreads, + currentWorktreePath: activeWorktreePath, + }) + : null; const previousWorktreeLabel = previousWorktreeSeed ? resolvePreviousWorktreeLabel(previousWorktreeSeed) : null; - const onUsePreviousWorktree = useCallback(() => { + const onUsePreviousWorktree = () => { if (!previousWorktreeSeed || !activeProjectRef) return; setDraftThreadContext(draftId ?? threadRef, { branch: previousWorktreeSeed.branch, @@ -640,7 +624,7 @@ export const BranchToolbar = memo(function BranchToolbar({ envMode: "worktree", projectRef: activeProjectRef, }); - }, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]); + }; useImperativeHandle( ref, From 26bea7e62e4fae5d59eeecb74374a87a2287239c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:31 -0700 Subject: [PATCH 020/323] perf(web): diff panel reads its loader and collapse defaults without refs (#20468) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/components/DiffPanel.tsx | 367 ++++++++++++-------------- 2 files changed, 177 insertions(+), 191 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 85542f1a7a69..92932df1bba2 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -43,4 +43,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/browser/useBrowserViewportResize.ts", "apps/web/src/components/desktop/SnapShotCoordinator.tsx", "apps/web/src/components/BranchToolbar.tsx", + "apps/web/src/components/DiffPanel.tsx", ] as const; diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index f7a54e8ad07a..74481717da44 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -21,7 +21,7 @@ import { import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide"; import * as Schema from "effect/Schema"; import * as DateTime from "effect/DateTime"; -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { useOpenInPreferredEditor } from "../editorPreferences"; @@ -33,6 +33,7 @@ import { cn } from "~/lib/utils"; import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useTheme } from "../hooks/useTheme"; +import { useStableCallback } from "../hooks/useStableCallback"; import { buildFileDiffContentVersion, buildFileDiffIdentityKey, @@ -112,6 +113,62 @@ function getCachedFileEntry(fileDiff: FileDiffMetadata) { return entry; } +// These hooks call no hooks, so the compiler needs the directive to memoize them. Their results +// feed the code view and the file patch loader, which key on identity. +function useRenderablePatch( + patch: string | undefined, + theme: string, + compactPartialHunkOffsets: boolean, +) { + "use memo"; + return getRenderablePatch(patch, `diff-panel:${theme}`, { compactPartialHunkOffsets }); +} + +function useGitDiffFileContentsLoader( + getDiffFileContents: Parameters>[0], + source: Parameters>[1] | null, +): FileDiffContentsLoader | undefined { + "use memo"; + return source ? createGitDiffFileContentsLoader(getDiffFileContents, source) : undefined; +} + +function useFileStats( + files: ReadonlyArray | undefined, +) { + "use memo"; + return new Map(files?.map((file) => [file.path, file])); +} + +function useDiffFileEntries(renderableFiles: ReadonlyArray, collapsed: boolean) { + "use memo"; + const renderableFileEntries = renderableFiles.map(getCachedFileEntry); + const diffFileKeys = renderableFileEntries.map((file) => file.fileKey); + return { + renderableFileEntries, + diffFileKeys, + defaultCollapsedDiffFileKeys: collapsed + ? new Set(diffFileKeys) + : EMPTY_COLLAPSED_DIFF_FILE_KEYS, + }; +} + +function useCodeViewFiles( + entries: ReadonlyArray>, + readyFilePaths: ReadonlySet | null, + collapsedFileKeys: ReadonlySet, +) { + "use memo"; + return entries + .filter(({ fileDiff }) => !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff))) + .map(({ fileDiff, fileKey, fileVersion }) => ({ + fileDiff, + filePath: resolveFileDiffPath(fileDiff), + fileKey, + fileVersion, + collapsed: collapsedFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true, + })); +} + interface CollapsedDiffFilesState { readonly scopeKey: string | null; readonly fileKeys: ReadonlySet; @@ -260,20 +317,16 @@ export default function DiffPanel({ const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = useTurnDiffSummaries(activeThreadProjection); - const orderedTurnDiffSummaries = useMemo( - () => - [...turnDiffSummaries].toSorted((left, right) => { - const leftTurnCount = - left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0; - const rightTurnCount = - right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0; - if (leftTurnCount !== rightTurnCount) { - return rightTurnCount - leftTurnCount; - } - return right.completedAt.localeCompare(left.completedAt); - }), - [inferredCheckpointTurnCountByRunId, turnDiffSummaries], - ); + const orderedTurnDiffSummaries = [...turnDiffSummaries].toSorted((left, right) => { + const leftTurnCount = + left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0; + const rightTurnCount = + right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0; + if (leftTurnCount !== rightTurnCount) { + return rightTurnCount - leftTurnCount; + } + return right.completedAt.localeCompare(left.completedAt); + }); useEffect(() => { if (!routeThreadRef || diffSelection.kind !== "turn") return; @@ -316,16 +369,13 @@ export default function DiffPanel({ : selectedGitScope === "unstaged" ? "Uncommitted" : "Changes"; - const selectedCheckpointRange = useMemo( - () => - typeof selectedCheckpointTurnCount === "number" - ? { - fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1), - toTurnCount: selectedCheckpointTurnCount, - } - : null, - [selectedCheckpointTurnCount], - ); + const selectedCheckpointRange = + typeof selectedCheckpointTurnCount === "number" + ? { + fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1), + toTurnCount: selectedCheckpointTurnCount, + } + : null; const activeCheckpointDiff = useCheckpointDiff( { environmentId: activeThread?.environmentId ?? null, @@ -361,36 +411,27 @@ export default function DiffPanel({ const refreshPreviewQuery = branchDiffPreview.refresh; const refreshDiffFromUserAction = refreshPreviewQuery; - const currentLoadDiffFiles = useMemo(() => { - const preview = branchDiffPreview.data; - if (selectedRunId !== null || !activeThread || !preview || !selectedGitSource) { - return undefined; - } - - if (!canReadFiles) return undefined; - return createGitDiffFileContentsLoader(getDiffFileContents, { - environmentId: activeThread.environmentId, - cwd: preview.cwd, - sourceKind: selectedGitSource.kind, - baseRef: selectedGitSource.baseRef, - headRef: selectedGitSource.headRef, - cacheKey: selectedGitSource.diffHash, - }); - }, [ - activeThread, - branchDiffPreview.data, + const preview = branchDiffPreview.data; + const currentLoadDiffFiles = useGitDiffFileContentsLoader( getDiffFileContents, - canReadFiles, - selectedGitSource, - selectedRunId, - ]); - const loadDiffFilesRef = useRef(currentLoadDiffFiles); - loadDiffFilesRef.current = currentLoadDiffFiles; - const loadDiffFiles = useCallback(async (fileDiff) => { - const loader = loadDiffFilesRef.current; - if (!loader) throw new Error("Diff file contents are unavailable for this selection."); - return loader(fileDiff); - }, []); + selectedRunId === null && activeThread && preview && selectedGitSource && canReadFiles + ? { + environmentId: activeThread.environmentId, + cwd: preview.cwd, + sourceKind: selectedGitSource.kind, + baseRef: selectedGitSource.baseRef, + headRef: selectedGitSource.headRef, + cacheKey: selectedGitSource.diffHash, + } + : null, + ); + // The code view keeps one loader for its lifetime; a new identity would remount it. + const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => { + if (!currentLoadDiffFiles) { + throw new Error("Diff file contents are unavailable for this selection."); + } + return currentLoadDiffFiles(fileDiff); + }); const localBranchRefs = useEnvironmentQuery( selectedRunId === null && selectedGitScope === "branch" && @@ -453,19 +494,12 @@ export default function DiffPanel({ !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files ? selectedGitSource : null; - const renderablePatch = useMemo( - () => - lazySource - ? null - : getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, { - compactPartialHunkOffsets: selectedRunId === null, - }), - [lazySource, resolvedTheme, selectedPatch, selectedRunId], - ); - const fileStats = useMemo( - () => new Map(lazySource?.files?.map((file) => [file.path, file])), - [lazySource?.files], + const renderablePatch = useRenderablePatch( + lazySource ? undefined : selectedPatch, + resolvedTheme, + selectedRunId === null, ); + const fileStats = useFileStats(lazySource?.files); const { scope: filePatchScope, isPending: areFilePatchesPending, @@ -505,66 +539,38 @@ export default function DiffPanel({ }); const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending; - const renderableFileEntries = useMemo( - () => renderableFiles.map(getCachedFileEntry), - [renderableFiles], - ); - const defaultCollapsedDiffFileKeys = useMemo( - () => - settings.diffFilesCollapsed - ? new Set(renderableFileEntries.map((file) => file.fileKey)) - : EMPTY_COLLAPSED_DIFF_FILE_KEYS, - [renderableFileEntries, settings.diffFilesCollapsed], + const { renderableFileEntries, diffFileKeys, defaultCollapsedDiffFileKeys } = useDiffFileEntries( + renderableFiles, + settings.diffFilesCollapsed, ); const collapsedDiffFileKeys = collapsedDiffFiles.scopeKey === collapseScopeKey ? collapsedDiffFiles.fileKeys : defaultCollapsedDiffFileKeys; - const renderLoadingBoundary = useCallback( - () => - settledFileCount < renderableFiles.length ? ( - - ) : null, - [settledFileCount, renderableFiles.length, loadNextFiles], - ); - const codeViewFiles = useMemo( - () => - renderableFileEntries - .filter(({ fileDiff }) => !lazySource || readyFilePaths.has(resolveFileDiffPath(fileDiff))) - .map(({ fileDiff, fileKey, fileVersion }) => { - return { - fileDiff, - filePath: resolveFileDiffPath(fileDiff), - fileKey, - fileVersion, - collapsed: - collapsedDiffFileKeys.has(fileKey) || - fileDiff.cacheKey?.endsWith(":pending") === true, - }; - }), - [collapsedDiffFileKeys, renderableFileEntries, lazySource, readyFilePaths], - ); - const diffFileKeys = useMemo( - () => renderableFileEntries.map((file) => file.fileKey), - [renderableFileEntries], + const renderLoadingBoundary = () => + settledFileCount < renderableFiles.length ? ( + + ) : null; + const codeViewFiles = useCodeViewFiles( + renderableFileEntries, + lazySource ? readyFilePaths : null, + collapsedDiffFileKeys, ); const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys); - const diffLineStat = useMemo(() => { - if (!selectedTurn && selectedGitSource?.files) { - return selectedGitSource.files.reduce( - (total, file) => ({ - additions: total.additions + file.additions, - deletions: total.deletions + file.deletions, - }), - { additions: 0, deletions: 0 }, - ); - } - return getDiffLineStat(renderableFiles); - }, [renderableFiles, selectedGitSource, selectedTurn]); - const fileTreeEntries = useMemo(() => diffFileTreeEntries(renderableFiles), [renderableFiles]); + const diffLineStat = + !selectedTurn && selectedGitSource?.files + ? selectedGitSource.files.reduce( + (total, file) => ({ + additions: total.additions + file.additions, + deletions: total.deletions + file.deletions, + }), + { additions: 0, deletions: 0 }, + ) + : getDiffLineStat(renderableFiles); + const fileTreeEntries = diffFileTreeEntries(renderableFiles); const selectedDiffFileKey = selectedFilePath ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null) : null; @@ -572,46 +578,33 @@ export default function DiffPanel({ useEffect(() => { if (!selectedDiffFileKey || !codeView?.getInstance()) return; codeView.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" }); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A remounted viewer or a repeated reveal request scrolls to the same file again. }, [codeView, codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]); - const treeRevealScope = useMemo( - () => ({ collapseScopeKey, diffSelection }), - [collapseScopeKey, diffSelection], - ); + const treeRevealScope = { collapseScopeKey, diffSelection }; const requestTreeReveal = useCodeViewFileReveal( codeView, treeRevealScope, codeViewFiles.map((file) => file.fileKey), ); - const revealDiffFile = useCallback( - (filePath: string) => { - const index = renderableFileEntries.findIndex( - (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, + const revealDiffFile = (filePath: string) => { + const index = renderableFileEntries.findIndex( + (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, + ); + const file = renderableFileEntries[index]; + if (!file) return; + setCollapsedDiffFiles((current) => { + const next = new Set( + current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys, ); - const file = renderableFileEntries[index]; - if (!file) return; - setCollapsedDiffFiles((current) => { - const next = new Set( - current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys, - ); - next.delete(file.fileKey); - return { scopeKey: collapseScopeKey, fileKeys: next }; - }); - if (lazySource && index >= settledFileCount) { - requestFile(index); - } - requestTreeReveal(file.fileKey); - }, - [ - renderableFileEntries, - collapseScopeKey, - defaultCollapsedDiffFileKeys, - requestTreeReveal, - lazySource, - settledFileCount, - requestFile, - ], - ); + next.delete(file.fileKey); + return { scopeKey: collapseScopeKey, fileKeys: next }; + }); + if (lazySource && index >= settledFileCount) { + requestFile(index); + } + requestTreeReveal(file.fileKey); + }; const externalRevealRef = useRef<{ cache: string; key: string } | null>(null); useEffect(() => { @@ -626,40 +619,33 @@ export default function DiffPanel({ revealDiffFile(selectedFilePath); }, [lazySource, selectedFilePath, selectedFileRevealRequestId, filePatchScope, revealDiffFile]); - const openDiffFile = useCallback( - (filePath: string) => { - openDiffFilePrimaryAction({ - threadRef: routeThreadRef, - filePath, - activeCwd, - repositoryRoot: activeRepositoryRoot, - openInEditor: (targetPath) => { - void (async () => { - const result = await openInPreferredEditor(targetPath); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - console.warn("Failed to open diff file in editor.", { - operation: "open-diff-file", - ...(routeThreadRef - ? { - environmentId: routeThreadRef.environmentId, - threadId: routeThreadRef.threadId, - } - : {}), - ...safeErrorLogAttributes(squashAtomCommandFailure(result)), - }); - } - })(); - }, - }); - }, - [activeCwd, activeRepositoryRoot, openInPreferredEditor, routeThreadRef], - ); - const collapseDefaultsRef = useRef({ collapseScopeKey, defaultCollapsedDiffFileKeys }); - useLayoutEffect(() => { - collapseDefaultsRef.current = { collapseScopeKey, defaultCollapsedDiffFileKeys }; - }, [collapseScopeKey, defaultCollapsedDiffFileKeys]); - const toggleDiffFileCollapsed = useCallback((fileKey: string) => { - const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current; + const openDiffFile = (filePath: string) => { + openDiffFilePrimaryAction({ + threadRef: routeThreadRef, + filePath, + activeCwd, + repositoryRoot: activeRepositoryRoot, + openInEditor: (targetPath) => { + void (async () => { + const result = await openInPreferredEditor(targetPath); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + console.warn("Failed to open diff file in editor.", { + operation: "open-diff-file", + ...(routeThreadRef + ? { + environmentId: routeThreadRef.environmentId, + threadId: routeThreadRef.threadId, + } + : {}), + ...safeErrorLogAttributes(squashAtomCommandFailure(result)), + }); + } + })(); + }, + }); + }; + // Every file header holds these; a new identity per collapse change would redraw them all. + const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => { setCollapsedDiffFiles((current) => { const next = new Set( current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys, @@ -671,10 +657,9 @@ export default function DiffPanel({ } return { scopeKey: collapseScopeKey, fileKeys: next }; }); - }, []); + }); // Find can ask again before the unfolded file reaches the viewer, so this must never fold. - const unfoldDiffFile = useCallback((fileKey: string) => { - const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current; + const unfoldDiffFile = useStableCallback((fileKey: string) => { setCollapsedDiffFiles((current) => { const fileKeys = current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys; @@ -683,9 +668,9 @@ export default function DiffPanel({ next.delete(fileKey); return { scopeKey: collapseScopeKey, fileKeys: next }; }); - }, []); + }); - const toggleDiffFileCollapse = useCallback(() => { + const toggleDiffFileCollapse = () => { setCodeViewRevision((current) => current + 1); setCollapsedDiffFiles((current) => { const currentKeys = @@ -696,7 +681,7 @@ export default function DiffPanel({ fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys), }; }); - }, [collapseScopeKey, defaultCollapsedDiffFileKeys, diffFileKeys]); + }; const selectTurn = (runId: RunId) => { if (!routeThreadRef) return; From 8f309bce656b315aacc93ba54ed6f3933124da0e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:31 -0700 Subject: [PATCH 021/323] perf(web): welcome wizard keeps its auto-selected computers in lazy state (#20469) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../components/onboarding/WelcomeWizard.tsx | 159 +++++++++--------- 2 files changed, 79 insertions(+), 81 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 92932df1bba2..087004dc2796 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -44,4 +44,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/desktop/SnapShotCoordinator.tsx", "apps/web/src/components/BranchToolbar.tsx", "apps/web/src/components/DiffPanel.tsx", + "apps/web/src/components/onboarding/WelcomeWizard.tsx", ] as const; diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx index 496eec4ad2d7..9cf3b9d60fa1 100644 --- a/apps/web/src/components/onboarding/WelcomeWizard.tsx +++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx @@ -32,7 +32,7 @@ import { MonitorIcon, TerminalIcon, } from "lucide-react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts"; import { useLocalStorage } from "../../hooks/useLocalStorage"; @@ -120,7 +120,9 @@ export function WelcomeWizard({ const [step, setStep] = useState(resumeEnvironmentId ? "agents" : "connection"); const { environments } = useEnvironments(); const [selection, setSelection] = useState | null>(null); - const autoSelectedComputers = useRef(new Set()); + // One registry for the wizard's lifetime, shared with the connect list, so a computer is + // auto-selected once even after the user unchecks it. + const [autoSelectedComputers] = useState(() => new Set()); const [setupIds, setSetupIds] = useState( resumeEnvironmentId ? [resumeEnvironmentId] : [], ); @@ -130,14 +132,15 @@ export function WelcomeWizard({ const primaryEnvironment = usePrimaryEnvironment(); useEffect(() => { const newComputers = environments.filter( - (environment) => !autoSelectedComputers.current.has(environment.environmentId), + (environment) => !autoSelectedComputers.has(environment.environmentId), ); if (newComputers.length === 0) return; for (const environment of newComputers) { - autoSelectedComputers.current.add(environment.environmentId); + autoSelectedComputers.add(environment.environmentId); } const enabledComputers = newComputers.filter((environment) => environment.entry.enabled); if (enabledComputers.length === 0) return; + // oxlint-disable-next-line react/set-state-in-effect -- The registry marks each computer once, and only after commit; render must not mutate it. setSelection( (current) => new Set([ @@ -145,7 +148,7 @@ export function WelcomeWizard({ ...enabledComputers.map((environment) => environment.environmentId), ]), ); - }, [environments]); + }, [autoSelectedComputers, environments]); const selectedIds = selection ?? new Set(primaryEnvironment ? [primaryEnvironment.environmentId] : []); const scans = useProjectScans(step === "import" ? setupIds : NO_ENVIRONMENTS); @@ -159,59 +162,60 @@ export function WelcomeWizard({ setStep("agents"); }; const stageIndex = step === "agents" ? 1 : step === "import" ? 2 : 0; - const finish = useCallback( - (projectRef?: ScopedProjectRef, importWarning?: string, importedThreadCount = 0) => { - if (finishingPromiseRef.current !== null) return finishingPromiseRef.current; - if (completionErrorToastIdRef.current !== null) { - toastManager.close(completionErrorToastIdRef.current); - completionErrorToastIdRef.current = null; - } + const finish = ( + projectRef?: ScopedProjectRef, + importWarning?: string, + importedThreadCount = 0, + ) => { + if (finishingPromiseRef.current !== null) return finishingPromiseRef.current; + if (completionErrorToastIdRef.current !== null) { + toastManager.close(completionErrorToastIdRef.current); + completionErrorToastIdRef.current = null; + } - const completion = completeOnboarding() - .then(async () => { - if (completionErrorToastIdRef.current !== null) { - toastManager.close(completionErrorToastIdRef.current); - completionErrorToastIdRef.current = null; - } - await onDone(projectRef); - if (importWarning) { - toastManager.add({ - type: "warning", - title: "Some history was not imported", - description: importWarning, - timeout: 0, - }); - } else if (importedThreadCount > 0) { - toastManager.add({ - type: "success", - title: `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}`, - }); - } - return true; - }) - .catch(() => { - const errorToast = { - type: "error", - title: "Could not finish setup", - description: "Your settings could not be saved. Try again.", - } as const; - if (completionErrorToastIdRef.current === null) { - completionErrorToastIdRef.current = toastManager.add(errorToast); - } else { - toastManager.update(completionErrorToastIdRef.current, errorToast); - } - return false; - }) - .finally(() => { - if (finishingPromiseRef.current === completion) { - finishingPromiseRef.current = null; - } - }); - finishingPromiseRef.current = completion; - return completion; - }, - [completeOnboarding, onDone], - ); + const completion = completeOnboarding() + .then(async () => { + if (completionErrorToastIdRef.current !== null) { + toastManager.close(completionErrorToastIdRef.current); + completionErrorToastIdRef.current = null; + } + await onDone(projectRef); + if (importWarning) { + toastManager.add({ + type: "warning", + title: "Some history was not imported", + description: importWarning, + timeout: 0, + }); + } else if (importedThreadCount > 0) { + toastManager.add({ + type: "success", + title: `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}`, + }); + } + return true; + }) + .catch(() => { + const errorToast = { + type: "error", + title: "Could not finish setup", + description: "Your settings could not be saved. Try again.", + } as const; + if (completionErrorToastIdRef.current === null) { + completionErrorToastIdRef.current = toastManager.add(errorToast); + } else { + toastManager.update(completionErrorToastIdRef.current, errorToast); + } + return false; + }) + .finally(() => { + if (finishingPromiseRef.current === completion) { + finishingPromiseRef.current = null; + } + }); + finishingPromiseRef.current = completion; + return completion; + }; return ( event.cancel()}> @@ -248,7 +252,7 @@ export function WelcomeWizard({ setSelection((current) => { @@ -461,7 +465,7 @@ function ConnectAccountOption({ const { openAuthPrompt } = useT3ConnectAuthPrompt(); const [expanded, setExpanded] = useState(true); const [discoveryReady, setDiscoveryReady] = useState(false); - const onDiscoveryReady = useCallback(() => setDiscoveryReady(true), []); + const onDiscoveryReady = () => setDiscoveryReady(true); return (
@@ -709,7 +713,7 @@ function ConnectedAgentsStep({ void refreshProviders({ environmentId, input: {} }); }, [environmentId, refreshProviders]); - const byDriver = useMemo(() => selectOnboardingProvidersByDriver(providers), [providers]); + const byDriver = selectOnboardingProvidersByDriver(providers); const primaryAgents = PRIMARY_AGENT_DRIVERS.flatMap((driver) => { const instances = @@ -1013,10 +1017,7 @@ function AgentInstallTerminal({ const setupGenerationRef = useRef(0); const activeSetupGenerationRef = useRef(null); const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`); - const threadRef = useMemo( - () => scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID), - [environmentId], - ); + const threadRef = scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID); const [setupAttempt, setSetupAttempt] = useState(0); const [setupState, setSetupState] = useState< "preparing" | "ready" | "openFailed" | "writeFailed" @@ -1030,6 +1031,7 @@ function AgentInstallTerminal({ const generation = setupGenerationRef.current + 1; setupGenerationRef.current = generation; activeSetupGenerationRef.current = generation; + // oxlint-disable-next-line react/set-state-in-effect -- A retry or a new command reopens the terminal, which shows as preparing until the open settles. setSetupState("preparing"); setupQueueRef.current = setupQueueRef.current.then(async () => { @@ -1087,6 +1089,7 @@ function AgentInstallTerminal({ environmentId, openTerminal, providerInstanceId, + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry bumps setupAttempt to open the terminal again. setupAttempt, terminalId, writeTerminal, @@ -1208,6 +1211,7 @@ function ImportStep({ project.environmentId === landingProject.environmentId, ) ) { + // oxlint-disable-next-line react/set-state-in-effect -- The landing project is known only once the projects subscription delivers it. setLandingProject(null); void onDone(landingProject, importWarningRef.current, importedThreadCountRef.current).then( (completed) => { @@ -1217,23 +1221,16 @@ function ImportStep({ } }, [landingProject, onDone, projects, setIsImporting]); - const { available: candidates, recent } = useMemo( - () => - partitionOnboardingProjects( - scans.flatMap((scan) => - (scan.data?.candidates ?? []).map((candidate) => ({ - ...candidate, - environmentId: scan.environmentId, - key: onboardingProjectKey(scan.environmentId, candidate.path), - })), - ), - ), - [scans], - ); - const selectedKeys = useMemo( - () => selectedPaths ?? new Set(recent.map((candidate) => candidate.key)), - [selectedPaths, recent], + const { available: candidates, recent } = partitionOnboardingProjects( + scans.flatMap((scan) => + (scan.data?.candidates ?? []).map((candidate) => ({ + ...candidate, + environmentId: scan.environmentId, + key: onboardingProjectKey(scan.environmentId, candidate.path), + })), + ), ); + const selectedKeys = selectedPaths ?? new Set(recent.map((candidate) => candidate.key)); const selected = candidates.filter((candidate) => selectedKeys.has(candidate.key)); const canImport = selected.every((candidate) => @@ -1531,7 +1528,7 @@ function ImportCandidateList({ readonly selectedKeys: ReadonlySet; readonly onSelectionChange: (next: ReadonlySet) => void; }) { - const { repositories, other } = useMemo(() => groupOnboardingProjects(candidates), [candidates]); + const { repositories, other } = groupOnboardingProjects(candidates); const setKeys = (keys: ReadonlyArray, checked: boolean) => { const next = new Set(selectedKeys); for (const key of keys) { From 7f4142e5b07bd1027d513c88311347101b294b52 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:32 -0700 Subject: [PATCH 022/323] perf(web): thread actions compile without manual memoization (#20470) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + apps/web/src/hooks/useThreadActions.ts | 1259 +++++++++++------------- 2 files changed, 580 insertions(+), 680 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index 087004dc2796..bdcc21971f34 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -45,4 +45,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/BranchToolbar.tsx", "apps/web/src/components/DiffPanel.tsx", "apps/web/src/components/onboarding/WelcomeWizard.tsx", + "apps/web/src/hooks/useThreadActions.ts", ] as const; diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 1e15348fd07f..1c2f1f0f0a3f 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -21,12 +21,10 @@ import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { useRouter } from "@tanstack/react-router"; -import { useCallback, useMemo, useRef } from "react"; import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic"; import { useComposerDraftStore } from "../composerDraftStore"; import { environmentSession, readEnvironmentScope } from "../state/session"; -import { terminalEnvironment } from "../state/terminal"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; @@ -206,38 +204,32 @@ function useMarkThreadUnread() { reportFailure: false, }); const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread); - return useCallback( - (target: ScopedThreadRef) => { - if (readEnvironmentSupportsVisitedTracking(target.environmentId)) { - void markThreadUnreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId }, - }); - return; - } - const thread = readThreadShell(target); - markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt); - }, - [markThreadUnreadLocal, markThreadUnreadMutation], - ); + return (target: ScopedThreadRef) => { + if (readEnvironmentSupportsVisitedTracking(target.environmentId)) { + void markThreadUnreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId }, + }); + return; + } + const thread = readThreadShell(target); + markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt); + }; } export function useAcknowledgeThreadWoke() { const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); const markThreadVisited = useUiStateStore((state) => state.markThreadVisited); - return useCallback( - (target: ScopedThreadRef, wokeAt: string) => { - if (readEnvironmentSupportsVisitedTracking(target.environmentId)) { - void visitThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, visitedAt: wokeAt }, - }); - return; - } - markThreadVisited(scopedThreadKey(target), wokeAt); - }, - [markThreadVisited, visitThreadMutation], - ); + return (target: ScopedThreadRef, wokeAt: string) => { + if (readEnvironmentSupportsVisitedTracking(target.environmentId)) { + void visitThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, visitedAt: wokeAt }, + }); + return; + } + markThreadVisited(scopedThreadKey(target), wokeAt); + }; } function threadOperationFailure(target: ScopedThreadRef) { @@ -312,14 +304,8 @@ export function useThreadActions() { const markThreadVisited = useUiStateStore((state) => state.markThreadVisited); const router = useRouter(); const handleNewThread = useNewThreadHandler(); - // Keep a ref so archiveThread can call handleNewThread without appearing in - // its dependency array — handleNewThread is inherently unstable (depends on - // the projects list) and would otherwise cascade new references into every - // sidebar row via archiveThread → attemptArchiveThread. - const handleNewThreadRef = useRef(handleNewThread); - handleNewThreadRef.current = handleNewThread; - - const resolveThreadTarget = useCallback((target: ScopedThreadRef) => { + + const resolveThreadTarget = (target: ScopedThreadRef) => { const thread = readThreadShell(target); if (!thread) { return null; @@ -328,686 +314,599 @@ export function useThreadActions() { thread, threadRef: target, }; - }, []); - const getCurrentRouteThreadRef = useCallback(() => { + }; + const getCurrentRouteThreadRef = () => { const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {}; return resolveThreadRouteRef(currentRouteParams); - }, [router]); + }; + + const unarchiveThread = async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => { + ThreadUndo.invalidate("archive", scopedThreadKey(target)); + const result = await unarchiveThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId }, + }); + if (result._tag === "Failure") { + return result; + } + refreshArchivedThreadsForEnvironment(target.environmentId); + if (opts.navigate) { + return settlePromise(() => + router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }), + ); + } + return result; + }; + + const archiveThread = async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => { + const resolved = resolveThreadTarget(target); + if (!resolved) return AsyncResult.success(undefined); + const { thread, threadRef } = resolved; + if (!threadRuntimeCanArchive(thread.runtime)) { + return AsyncResult.failure( + Cause.fail( + new ThreadArchiveBlockedError({ + environmentId: threadRef.environmentId, + threadId: threadRef.threadId, + }), + ), + ); + } + + const currentRouteThreadRef = getCurrentRouteThreadRef(); + const shouldNavigateToDraft = + currentRouteThreadRef?.threadId === threadRef.threadId && + currentRouteThreadRef.environmentId === threadRef.environmentId; + const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef)); + const archiveResult = await archiveThreadMutation({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }); + if (archiveResult._tag === "Failure") { + action.finish(); + return archiveResult; + } + const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() }); + if (wokeAt !== null) { + markThreadVisited(scopedThreadKey(threadRef), wokeAt); + } + refreshArchivedThreadsForEnvironment(threadRef.environmentId); + opts.onArchived?.(); + showThreadUndoNotice({ + action: "Archived", + claim: action, + undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }), + failureTitle: "Failed to undo archive", + }); + + if (shouldNavigateToDraft) { + const navigationResult = await settlePromise(() => + handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId)), + ); + if (navigationResult._tag === "Failure") { + return navigationResult; + } + return archiveResult; + } - const unarchiveThread = useCallback( - async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => { - ThreadUndo.invalidate("archive", scopedThreadKey(target)); - const result = await unarchiveThreadMutation({ + return archiveResult; + }; + + const deleteThread = async ( + target: ScopedThreadRef, + opts: { deletedThreadKeys?: ReadonlySet } = {}, + ) => { + const permissionFailure = threadOperationFailure(target); + if (permissionFailure) return permissionFailure; + const resolved = resolveThreadTarget(target); + if (!resolved) { + const result = await deleteThreadMutation({ environmentId: target.environmentId, input: { threadId: target.threadId }, }); - if (result._tag === "Failure") { - return result; - } - refreshArchivedThreadsForEnvironment(target.environmentId); - if (opts.navigate) { - return settlePromise(() => - router.navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(target), - }), - ); + if (result._tag === "Success") { + refreshArchivedThreadsForEnvironment(target.environmentId); + clearThreadPreviewState(target); } return result; - }, - [router, unarchiveThreadMutation], - ); - - const archiveThread = useCallback( - async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => { - const resolved = resolveThreadTarget(target); - if (!resolved) return AsyncResult.success(undefined); - const { thread, threadRef } = resolved; - if (!threadRuntimeCanArchive(thread.runtime)) { - return AsyncResult.failure( - Cause.fail( - new ThreadArchiveBlockedError({ - environmentId: threadRef.environmentId, - threadId: threadRef.threadId, + } + const { thread, threadRef } = resolved; + const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => { + const shell = readThreadShell(ref); + return shell === null ? [] : [shell]; + }); + const threadProject = readProject({ + environmentId: threadRef.environmentId, + projectId: thread.projectId, + }); + const deletedIds = + opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0 + ? new Set( + [...opts.deletedThreadKeys].flatMap((threadKey) => { + const ref = parseScopedThreadKey(threadKey); + return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : []; }), - ), - ); - } - - const currentRouteThreadRef = getCurrentRouteThreadRef(); - const shouldNavigateToDraft = - currentRouteThreadRef?.threadId === threadRef.threadId && - currentRouteThreadRef.environmentId === threadRef.environmentId; - const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef)); - const archiveResult = await archiveThreadMutation({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId }, - }); - if (archiveResult._tag === "Failure") { - action.finish(); - return archiveResult; - } - const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() }); - if (wokeAt !== null) { - markThreadVisited(scopedThreadKey(threadRef), wokeAt); - } - refreshArchivedThreadsForEnvironment(threadRef.environmentId); - opts.onArchived?.(); - showThreadUndoNotice({ - action: "Archived", - claim: action, - undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }), - failureTitle: "Failed to undo archive", - }); - - if (shouldNavigateToDraft) { - const navigationResult = await settlePromise(() => - handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)), - ); - if (navigationResult._tag === "Failure") { - return navigationResult; - } - return archiveResult; - } - - return archiveResult; - }, - [ - archiveThreadMutation, - getCurrentRouteThreadRef, - markThreadVisited, - resolveThreadTarget, - unarchiveThread, - ], - ); - - const deleteThread = useCallback( - async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet } = {}) => { - const permissionFailure = threadOperationFailure(target); + ) + : undefined; + const survivingThreads = + deletedIds && deletedIds.size > 0 + ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id)) + : threads; + const orphanedWorktreePath = getOrphanedWorktreePathForThread( + survivingThreads, + threadRef.threadId, + ); + const displayWorktreePath = orphanedWorktreePath + ? formatWorktreePathForDisplay(orphanedWorktreePath) + : null; + const environmentConfig = appAtomRegistry + .get(environmentServerConfigsAtom) + .get(threadRef.environmentId); + const localApi = readLocalApi(); + let canDeleteWorktree = false; + if ( + orphanedWorktreePath !== null && + threadProject !== null && + !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) && + localApi + ) { + const sessionResult = await loadSessionState(threadRef.environmentId); + const permissionFailure = threadOperationFailure(threadRef); if (permissionFailure) return permissionFailure; - const resolved = resolveThreadTarget(target); - if (!resolved) { - const result = await deleteThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId }, - }); - if (result._tag === "Success") { - refreshArchivedThreadsForEnvironment(target.environmentId); - clearThreadPreviewState(target); - } - return result; - } - const { thread, threadRef } = resolved; - const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => { - const shell = readThreadShell(ref); - return shell === null ? [] : [shell]; - }); - const threadProject = readProject({ - environmentId: threadRef.environmentId, - projectId: thread.projectId, - }); - const deletedIds = - opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0 - ? new Set( - [...opts.deletedThreadKeys].flatMap((threadKey) => { - const ref = parseScopedThreadKey(threadKey); - return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : []; - }), - ) - : undefined; - const survivingThreads = - deletedIds && deletedIds.size > 0 - ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id)) - : threads; - const orphanedWorktreePath = getOrphanedWorktreePathForThread( - survivingThreads, - threadRef.threadId, + canDeleteWorktree = + sessionResult._tag === "Success" && + sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope); + } + let shouldDeleteWorktree = false; + const environmentSettings = environmentConfig?.settings; + const automaticWorktreeCleanup = environmentSettings + ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete + : false; + if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) { + const confirmationResult = await settlePromise(() => + localApi.dialogs.confirm( + [ + "This thread is the only one linked to this worktree:", + displayWorktreePath ?? orphanedWorktreePath, + "", + "Delete the worktree too?", + ].join("\n"), + { variant: "destructive" }, + ), ); - const displayWorktreePath = orphanedWorktreePath - ? formatWorktreePathForDisplay(orphanedWorktreePath) - : null; - const environmentConfig = appAtomRegistry - .get(environmentServerConfigsAtom) - .get(threadRef.environmentId); - const localApi = readLocalApi(); - let canDeleteWorktree = false; - if ( - orphanedWorktreePath !== null && - threadProject !== null && - !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) && - localApi - ) { - const sessionResult = await loadSessionState(threadRef.environmentId); - const permissionFailure = threadOperationFailure(threadRef); - if (permissionFailure) return permissionFailure; - canDeleteWorktree = - sessionResult._tag === "Success" && - sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope); - } - let shouldDeleteWorktree = false; - const environmentSettings = environmentConfig?.settings; - const automaticWorktreeCleanup = environmentSettings - ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete - : false; - if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) { - const confirmationResult = await settlePromise(() => - localApi.dialogs.confirm( - [ - "This thread is the only one linked to this worktree:", - displayWorktreePath ?? orphanedWorktreePath, - "", - "Delete the worktree too?", - ].join("\n"), - { variant: "destructive" }, - ), - ); - if (confirmationResult._tag === "Failure") { - return confirmationResult; - } - shouldDeleteWorktree = confirmationResult.value; - } - - if (thread.runtime !== null) { - await stopThreadSession({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId }, - }); + if (confirmationResult._tag === "Failure") { + return confirmationResult; } + shouldDeleteWorktree = confirmationResult.value; + } - const deletedThreadIds = deletedIds ?? new Set(); - const currentRouteThreadRef = getCurrentRouteThreadRef(); - const shouldNavigateToFallback = - currentRouteThreadRef?.threadId === threadRef.threadId && - currentRouteThreadRef.environmentId === threadRef.environmentId; - const fallbackThreadId = getFallbackThreadIdAfterDelete({ - threads, - deletedThreadId: threadRef.threadId, - deletedThreadIds, - sortOrder: sidebarThreadSortOrder, - }); - const deleteResult = await deleteThreadMutation({ + if (thread.runtime !== null) { + await stopThreadSession({ environmentId: threadRef.environmentId, input: { threadId: threadRef.threadId }, }); - if (deleteResult._tag === "Failure") { - return deleteResult; - } - refreshArchivedThreadsForEnvironment(threadRef.environmentId); - releaseComposerDraftUploads(threadRef); - clearComposerDraftForThread(threadRef); - clearProjectDraftThreadById( - scopeProjectRef(threadRef.environmentId, thread.projectId), - threadRef, - ); - clearTerminalUiState(threadRef); - clearThreadPreviewState(threadRef); - - if (shouldNavigateToFallback) { - const fallbackThread = fallbackThreadId - ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId)) - : null; - await navigateAfterThreadDeletion(() => - fallbackThread - ? router.navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(fallbackThread.environmentId, fallbackThread.id), - ), - replace: true, - }) - : router.navigate({ to: "/", replace: true }), - ); - } - - if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) { - return deleteResult; - } + } - const removeResult = readEnvironmentScope( - threadRef.environmentId, - AuthSourceControlWriteScope, - ) - ? await removeWorktree({ - environmentId: threadRef.environmentId, - input: { - cwd: threadProject.workspaceRoot, - path: orphanedWorktreePath, - force: true, - }, - }) - : AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - message: "This connection can no longer remove worktrees.", - requiredScope: AuthSourceControlWriteScope, - }), - ), - ); - const refreshResult = - removeResult._tag === "Success" - ? await refreshVcsStatus({ - environmentId: threadRef.environmentId, - input: { cwd: threadProject.workspaceRoot }, - }) - : null; - const cleanupFailure = - removeResult._tag === "Failure" - ? removeResult - : refreshResult?._tag === "Failure" - ? refreshResult - : null; - if (cleanupFailure) { - const removalFailed = removeResult._tag === "Failure"; - const error = squashAtomCommandFailure(cleanupFailure); - const message = error instanceof Error ? error.message : "An error occurred."; - console.error("Worktree cleanup failed after thread deletion", { - threadId: threadRef.threadId, - projectCwd: threadProject.workspaceRoot, - worktreePath: orphanedWorktreePath, - error, - }); - toastManager.add( - stackedThreadToast({ - type: "error", - title: removalFailed - ? "Failed to delete worktree" - : "Worktree deleted, but Git status refresh failed", - description: removalFailed - ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}` - : message, - }), - ); - // The thread was deleted. Cleanup has its own toast; returning its - // failure would make callers incorrectly report a thread deletion error. - } + const deletedThreadIds = deletedIds ?? new Set(); + const currentRouteThreadRef = getCurrentRouteThreadRef(); + const shouldNavigateToFallback = + currentRouteThreadRef?.threadId === threadRef.threadId && + currentRouteThreadRef.environmentId === threadRef.environmentId; + const fallbackThreadId = getFallbackThreadIdAfterDelete({ + threads, + deletedThreadId: threadRef.threadId, + deletedThreadIds, + sortOrder: sidebarThreadSortOrder, + }); + const deleteResult = await deleteThreadMutation({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }); + if (deleteResult._tag === "Failure") { return deleteResult; - }, - [ - clearComposerDraftForThread, - clearProjectDraftThreadById, - clearTerminalUiState, - deleteThreadMutation, - getCurrentRouteThreadRef, - loadSessionState, - refreshVcsStatus, - removeWorktree, - router, - resolveThreadTarget, - sidebarThreadSortOrder, - stopThreadSession, - ], - ); - - const unsettleThread = useCallback( - async (target: ScopedThreadRef) => { - if (!readEnvironmentSupportsSettlement(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadSettlementUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - ThreadUndo.invalidate("settle", scopedThreadKey(target)); - // reason "user" pins the thread active: auto-settle (PR merged / - // inactivity) stays suppressed until real activity clears the pin. - return unsettleThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, reason: "user" }, - }); - }, - [unsettleThreadMutation], - ); - - const setThreadAutoSettle = useCallback( - async (target: ScopedThreadRef, enabled: boolean) => { - if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadAutoSettleOptOutUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - return setThreadAutoSettleMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, enabled }, - }); - }, - [setThreadAutoSettleMutation], - ); + } + refreshArchivedThreadsForEnvironment(threadRef.environmentId); + releaseComposerDraftUploads(threadRef); + clearComposerDraftForThread(threadRef); + clearProjectDraftThreadById( + scopeProjectRef(threadRef.environmentId, thread.projectId), + threadRef, + ); + clearTerminalUiState(threadRef); + clearThreadPreviewState(threadRef); - const pinThread = useCallback( - async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { - if (!readEnvironmentSupportsPinning(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadPinningUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - // orderKey rides only to servers that decode it; pre-reorder servers get the bare pin they - // understand and the thread stays keyless. - const orderKey = readEnvironmentSupportsPinReorder(target.environmentId) - ? (opts.orderKey ?? topOfPinnedRunOrderKey()) - : undefined; - ThreadUndo.invalidate("pin", scopedThreadKey(target)); - return pinThreadMutation({ - environmentId: target.environmentId, - input: { - threadId: target.threadId, - ...(orderKey !== undefined ? { orderKey } : {}), - }, - }); - }, - [pinThreadMutation], - ); + if (shouldNavigateToFallback) { + const fallbackThread = fallbackThreadId + ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId)) + : null; + await navigateAfterThreadDeletion(() => + fallbackThread + ? router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams( + scopeThreadRef(fallbackThread.environmentId, fallbackThread.id), + ), + replace: true, + }) + : router.navigate({ to: "/", replace: true }), + ); + } - const unpinThread = useCallback( - async (target: ScopedThreadRef) => { - if (!readEnvironmentSupportsPinning(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadPinningUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - const thread = readThreadShell(target); - const orderKey = thread?.pinOrderKey ?? undefined; - const action = ThreadUndo.begin("pin", scopedThreadKey(target)); - const result = await unpinThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId }, - }); - if (result._tag === "Success" && action.isCurrent()) { - showThreadUndoNotice({ - action: "Unpinned", - claim: action, - undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }), - failureTitle: "Failed to undo unpin", - }); - } else { - action.finish(); - } - return result; - }, - [pinThread, unpinThreadMutation], - ); + if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) { + return deleteResult; + } - const settleThread = useCallback( - async (target: ScopedThreadRef) => { - if (!readEnvironmentSupportsSettlement(target.environmentId)) { - return AsyncResult.failure( + const removeResult = readEnvironmentScope(threadRef.environmentId, AuthSourceControlWriteScope) + ? await removeWorktree({ + environmentId: threadRef.environmentId, + input: { + cwd: threadProject.workspaceRoot, + path: orphanedWorktreePath, + force: true, + }, + }) + : AsyncResult.failure( Cause.fail( - new ThreadSettlementUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, + new EnvironmentAuthorizationError({ + message: "This connection can no longer remove worktrees.", + requiredScope: AuthSourceControlWriteScope, }), ), ); - } - const resolved = resolveThreadTarget(target); - const wokeAt = resolved - ? threadWokeAt(resolved.thread, { now: new Date().toISOString() }) + const refreshResult = + removeResult._tag === "Success" + ? await refreshVcsStatus({ + environmentId: threadRef.environmentId, + input: { cwd: threadProject.workspaceRoot }, + }) : null; - // Settling also drops the pin and the snooze server-side, so Undo - // has to put those back as well. - const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null; - const wasPinned = resolved?.thread.pinnedAt != null; - const snoozedUntil = resolved?.thread.snoozedUntil ?? null; - // An older unpin/snooze Undo would re-pin or re-snooze, and the server - // treats either as a promotion that un-settles; settling supersedes them. - ThreadUndo.invalidate("pin", scopedThreadKey(target)); - ThreadUndo.invalidate("snooze", scopedThreadKey(target)); - const action = ThreadUndo.begin("settle", scopedThreadKey(target)); - const result = await settleThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId }, + const cleanupFailure = + removeResult._tag === "Failure" + ? removeResult + : refreshResult?._tag === "Failure" + ? refreshResult + : null; + if (cleanupFailure) { + const removalFailed = removeResult._tag === "Failure"; + const error = squashAtomCommandFailure(cleanupFailure); + const message = error instanceof Error ? error.message : "An error occurred."; + console.error("Worktree cleanup failed after thread deletion", { + threadId: threadRef.threadId, + projectCwd: threadProject.workspaceRoot, + worktreePath: orphanedWorktreePath, + error, }); - if (result._tag !== "Success") { - action.finish(); - return result; - } - if (wokeAt !== null) { - markThreadVisited(scopedThreadKey(target), wokeAt); - } + toastManager.add( + stackedThreadToast({ + type: "error", + title: removalFailed + ? "Failed to delete worktree" + : "Worktree deleted, but Git status refresh failed", + description: removalFailed + ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}` + : message, + }), + ); + // The thread was deleted. Cleanup has its own toast; returning its + // failure would make callers incorrectly report a thread deletion error. + } + return deleteResult; + }; + + const unsettleThread = async (target: ScopedThreadRef) => { + if (!readEnvironmentSupportsSettlement(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadSettlementUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + ThreadUndo.invalidate("settle", scopedThreadKey(target)); + // reason "user" pins the thread active: auto-settle (PR merged / + // inactivity) stays suppressed until real activity clears the pin. + return unsettleThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, reason: "user" }, + }); + }; + + const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => { + if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadAutoSettleOptOutUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + return setThreadAutoSettleMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, enabled }, + }); + }; + + const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { + if (!readEnvironmentSupportsPinning(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadPinningUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + // orderKey rides only to servers that decode it; pre-reorder servers get the bare pin they + // understand and the thread stays keyless. + const orderKey = readEnvironmentSupportsPinReorder(target.environmentId) + ? (opts.orderKey ?? topOfPinnedRunOrderKey()) + : undefined; + ThreadUndo.invalidate("pin", scopedThreadKey(target)); + return pinThreadMutation({ + environmentId: target.environmentId, + input: { + threadId: target.threadId, + ...(orderKey !== undefined ? { orderKey } : {}), + }, + }); + }; + + const unpinThread = async (target: ScopedThreadRef) => { + if (!readEnvironmentSupportsPinning(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadPinningUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + const thread = readThreadShell(target); + const orderKey = thread?.pinOrderKey ?? undefined; + const action = ThreadUndo.begin("pin", scopedThreadKey(target)); + const result = await unpinThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId }, + }); + if (result._tag === "Success" && action.isCurrent()) { showThreadUndoNotice({ - action: "Settled", + action: "Unpinned", claim: action, - undo: async () => { - const unsettled = await unsettleThread(target); - if (unsettled._tag !== "Success") return unsettled; - if (wasPinned) { - const pinned = await pinThread( - target, - pinOrderKey == null ? {} : { orderKey: pinOrderKey }, - ); - if (pinned._tag !== "Success") return pinned; - } - if (snoozedUntil !== null) { - return snoozeThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, snoozedUntil }, - }); - } - return unsettled; - }, - failureTitle: "Failed to undo settle", + undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }), + failureTitle: "Failed to undo unpin", }); + } else { + action.finish(); + } + return result; + }; + + const settleThread = async (target: ScopedThreadRef) => { + if (!readEnvironmentSupportsSettlement(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadSettlementUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + const resolved = resolveThreadTarget(target); + const wokeAt = resolved + ? threadWokeAt(resolved.thread, { now: new Date().toISOString() }) + : null; + // Settling also drops the pin and the snooze server-side, so Undo + // has to put those back as well. + const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null; + const wasPinned = resolved?.thread.pinnedAt != null; + const snoozedUntil = resolved?.thread.snoozedUntil ?? null; + // An older unpin/snooze Undo would re-pin or re-snooze, and the server + // treats either as a promotion that un-settles; settling supersedes them. + ThreadUndo.invalidate("pin", scopedThreadKey(target)); + ThreadUndo.invalidate("snooze", scopedThreadKey(target)); + const action = ThreadUndo.begin("settle", scopedThreadKey(target)); + const result = await settleThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId }, + }); + if (result._tag !== "Success") { + action.finish(); return result; - }, - [ - markThreadVisited, - pinThread, - resolveThreadTarget, - settleThreadMutation, - snoozeThreadMutation, - unsettleThread, - ], - ); + } + if (wokeAt !== null) { + markThreadVisited(scopedThreadKey(target), wokeAt); + } + showThreadUndoNotice({ + action: "Settled", + claim: action, + undo: async () => { + const unsettled = await unsettleThread(target); + if (unsettled._tag !== "Success") return unsettled; + if (wasPinned) { + const pinned = await pinThread( + target, + pinOrderKey == null ? {} : { orderKey: pinOrderKey }, + ); + if (pinned._tag !== "Success") return pinned; + } + if (snoozedUntil !== null) { + return snoozeThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, snoozedUntil }, + }); + } + return unsettled; + }, + failureTitle: "Failed to undo settle", + }); + return result; + }; + + const confirmAndUnpinThread = async (target: ScopedThreadRef) => { + const permissionFailure = threadOperationFailure(target); + if (permissionFailure) return permissionFailure; + const localApi = readLocalApi(); + const resolved = resolveThreadTarget(target); + const confirmationResult = await requestThreadUnpinConfirmation({ + enabled: confirmThreadUnpin, + title: resolved?.thread.title ?? "this thread", + confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null, + }); + if (confirmationResult._tag === "Failure") { + return confirmationResult; + } + if (!confirmationResult.value) { + return AsyncResult.success(undefined); + } + return unpinThread(target); + }; - const confirmAndUnpinThread = useCallback( - async (target: ScopedThreadRef) => { - const permissionFailure = threadOperationFailure(target); - if (permissionFailure) return permissionFailure; - const localApi = readLocalApi(); - const resolved = resolveThreadTarget(target); - const confirmationResult = await requestThreadUnpinConfirmation({ - enabled: confirmThreadUnpin, - title: resolved?.thread.title ?? "this thread", - confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null, - }); + const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => { + if (!readEnvironmentSupportsPinReorder(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadPinReorderUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + ThreadUndo.invalidate("pin", scopedThreadKey(target)); + return reorderPinnedThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, orderKey }, + }); + }; + + const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => { + if (!readEnvironmentSupportsActiveReorder(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadActiveReorderUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + return reorderActiveThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, orderKey }, + }); + }; + + const unsnoozeThread = async (target: ScopedThreadRef) => { + if (!readEnvironmentSupportsSnooze(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadSnoozeUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + ThreadUndo.invalidate("snooze", scopedThreadKey(target)); + return unsnoozeThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, reason: "user" }, + }); + }; + + const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => { + if (!readEnvironmentSupportsSnooze(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadSnoozeUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + const resolved = resolveThreadTarget(target); + if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) { + return AsyncResult.failure( + Cause.fail( + new ThreadSnoozeBlockedError({ + environmentId: resolved.threadRef.environmentId, + threadId: resolved.threadRef.threadId, + }), + ), + ); + } + const action = ThreadUndo.begin("snooze", scopedThreadKey(target)); + const result = await snoozeThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, snoozedUntil }, + }); + if (result._tag !== "Success") { + action.finish(); + return result; + } + showThreadUndoNotice({ + action: "Snoozed", + claim: action, + undo: () => unsnoozeThread(target), + failureTitle: "Failed to wake thread", + }); + return result; + }; + + const confirmAndDeleteThread = async (target: ScopedThreadRef) => { + const permissionFailure = threadOperationFailure(target); + if (permissionFailure) return permissionFailure; + const localApi = readLocalApi(); + const resolved = resolveThreadTarget(target); + + if (confirmThreadDelete && localApi) { + const title = resolved?.thread.title ?? "this thread"; + const confirmationResult = await settlePromise(() => + localApi.dialogs.confirm( + [ + `Delete thread "${title}"?`, + "This permanently clears conversation history for this thread.", + ].join("\n"), + { variant: "destructive" }, + ), + ); if (confirmationResult._tag === "Failure") { return confirmationResult; } if (!confirmationResult.value) { return AsyncResult.success(undefined); } - return unpinThread(target); - }, - [confirmThreadUnpin, resolveThreadTarget, unpinThread], - ); - - const reorderPinnedThread = useCallback( - async (target: ScopedThreadRef, orderKey: string) => { - if (!readEnvironmentSupportsPinReorder(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadPinReorderUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - ThreadUndo.invalidate("pin", scopedThreadKey(target)); - return reorderPinnedThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, orderKey }, - }); - }, - [reorderPinnedThreadMutation], - ); - - const reorderActiveThread = useCallback( - async (target: ScopedThreadRef, orderKey: string) => { - if (!readEnvironmentSupportsActiveReorder(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadActiveReorderUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - return reorderActiveThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, orderKey }, - }); - }, - [reorderActiveThreadMutation], - ); - - const unsnoozeThread = useCallback( - async (target: ScopedThreadRef) => { - if (!readEnvironmentSupportsSnooze(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadSnoozeUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - ThreadUndo.invalidate("snooze", scopedThreadKey(target)); - return unsnoozeThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, reason: "user" }, - }); - }, - [unsnoozeThreadMutation], - ); - - const snoozeThread = useCallback( - async (target: ScopedThreadRef, snoozedUntil: string) => { - if (!readEnvironmentSupportsSnooze(target.environmentId)) { - return AsyncResult.failure( - Cause.fail( - new ThreadSnoozeUnsupportedError({ - environmentId: target.environmentId, - threadId: target.threadId, - }), - ), - ); - } - const resolved = resolveThreadTarget(target); - if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) { - return AsyncResult.failure( - Cause.fail( - new ThreadSnoozeBlockedError({ - environmentId: resolved.threadRef.environmentId, - threadId: resolved.threadRef.threadId, - }), - ), - ); - } - const action = ThreadUndo.begin("snooze", scopedThreadKey(target)); - const result = await snoozeThreadMutation({ - environmentId: target.environmentId, - input: { threadId: target.threadId, snoozedUntil }, - }); - if (result._tag !== "Success") { - action.finish(); - return result; - } - showThreadUndoNotice({ - action: "Snoozed", - claim: action, - undo: () => unsnoozeThread(target), - failureTitle: "Failed to wake thread", - }); - return result; - }, - [resolveThreadTarget, snoozeThreadMutation, unsnoozeThread], - ); - - const confirmAndDeleteThread = useCallback( - async (target: ScopedThreadRef) => { - const permissionFailure = threadOperationFailure(target); - if (permissionFailure) return permissionFailure; - const localApi = readLocalApi(); - const resolved = resolveThreadTarget(target); - - if (confirmThreadDelete && localApi) { - const title = resolved?.thread.title ?? "this thread"; - const confirmationResult = await settlePromise(() => - localApi.dialogs.confirm( - [ - `Delete thread "${title}"?`, - "This permanently clears conversation history for this thread.", - ].join("\n"), - { variant: "destructive" }, - ), - ); - if (confirmationResult._tag === "Failure") { - return confirmationResult; - } - if (!confirmationResult.value) { - return AsyncResult.success(undefined); - } - } - - return deleteThread(target); - }, - [confirmThreadDelete, deleteThread, resolveThreadTarget], - ); + } - return useMemo( - () => ({ - archiveThread, - unarchiveThread, - deleteThread, - confirmAndDeleteThread, - settleThread, - unsettleThread, - snoozeThread, - unsnoozeThread, - pinThread, - unpinThread, - confirmAndUnpinThread, - reorderPinnedThread, - reorderActiveThread, - markThreadUnread, - setThreadAutoSettle, - }), - [ - archiveThread, - confirmAndDeleteThread, - confirmAndUnpinThread, - deleteThread, - markThreadUnread, - pinThread, - reorderPinnedThread, - reorderActiveThread, - setThreadAutoSettle, - settleThread, - snoozeThread, - unarchiveThread, - unpinThread, - unsettleThread, - unsnoozeThread, - ], - ); + return deleteThread(target); + }; + + return { + archiveThread, + unarchiveThread, + deleteThread, + confirmAndDeleteThread, + settleThread, + unsettleThread, + snoozeThread, + unsnoozeThread, + pinThread, + unpinThread, + confirmAndUnpinThread, + reorderPinnedThread, + reorderActiveThread, + markThreadUnread, + setThreadAutoSettle, + }; } From bb30390933ebcc6a2f50bb153ffc155e76d655fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 16 Oct 2026 18:46:32 -0700 Subject: [PATCH 023/323] perf(web): pull request code tab compiles, with viewed toggles read through context (#20471) Co-authored-by: Claude Opus 5.5 --- apps/web/reactCompiledFiles.ts | 1 + .../pullRequest/PullRequestCodeTab.tsx | 1231 +++++++++-------- 2 files changed, 634 insertions(+), 598 deletions(-) diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts index bdcc21971f34..ae15e63499a9 100644 --- a/apps/web/reactCompiledFiles.ts +++ b/apps/web/reactCompiledFiles.ts @@ -46,4 +46,5 @@ export const REACT_COMPILED_FILES = [ "apps/web/src/components/DiffPanel.tsx", "apps/web/src/components/onboarding/WelcomeWizard.tsx", "apps/web/src/hooks/useThreadActions.ts", + "apps/web/src/components/pullRequest/PullRequestCodeTab.tsx", ] as const; diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index b7fce3059999..7ea127baa401 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,4 +1,9 @@ -import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs"; +import type { + CodeViewItem, + DiffLineAnnotation, + FileDiffMetadata, + SelectedLineRange, +} from "@pierre/diffs"; import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react"; import type { EnvironmentId, @@ -26,7 +31,15 @@ import { import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide"; import { useAtomRefresh } from "@effect/atom-react"; import * as Schema from "effect/Schema"; -import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { + createContext, + use, + useEffect, + useEffectEvent, + useRef, + useState, + type ReactNode, +} from "react"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings"; @@ -136,6 +149,79 @@ const REPLACE_FILE_COUNTS_CSS = ` const NO_SLICES: ReadonlyArray = []; +// Each slice is parsed once per cache key and the parse lives as long as the slice does, so a +// slice arriving costs one parse rather than one per slice already on screen. +const sliceParses = new WeakMap>(); + +function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) { + let parses = sliceParses.get(slice); + if (parses === undefined) { + parses = new Map(); + sliceParses.set(slice, parses); + } + if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null; + const parsed = getRenderablePatch(slice.patch, cacheKey, { + compactPartialHunkOffsets: true, + ignoreWhitespace, + }); + parses.set(cacheKey, parsed); + return parsed; +} + +interface FileViewedToggleState { + readonly enabled: boolean; + readonly isViewed: (path: string) => boolean; + readonly isStale: (path: string) => boolean; + readonly setFileViewed: (fileKey: string, path: string, viewed: boolean) => void; +} + +// Header portals are memoized on the render props; the viewed toggle reads its state through +// context so a press redraws the toggles, not every header on screen. +const FileViewedToggleContext = createContext(null); + +function FileViewedToggle({ + fileKey, + path, + stat, +}: { + readonly fileKey: string; + readonly path: string; + readonly stat: ReactNode; +}) { + const viewedFiles = use(FileViewedToggleContext); + if (viewedFiles === null || !viewedFiles.enabled) return stat; + const viewed = viewedFiles.isViewed(path); + const stale = viewedFiles.isStale(path); + return ( + + {stat} + + + ); +} + interface MutableAnnotationGroup { readonly side: PullRequestDiffSide; readonly line: number; @@ -157,6 +243,201 @@ export interface PullRequestAgentSelectionInput { readonly request: string; } +// These hooks call no hooks, so the compiler needs the directive to memoize them. The viewer +// and the viewed-file tracker key on the identity of what they return. +function usePullRequestDiffFileContentsLoader( + getDiffFileContents: Parameters>[0], + source: Parameters>[1], +) { + "use memo"; + return createPullRequestDiffFileContentsLoader(getDiffFileContents, source); +} + +function useParsedDiffSlices( + loadedSlices: ReadonlyArray, + scopeKey: string, + resolvedTheme: string, + ignoreWhitespace: boolean, +) { + "use memo"; + // The cache key carries the theme, which is what the tokenizer caches against, so a theme + // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page + // reuses its cursor, and a key of position alone would hand back the parse it replaced. + const parsedSlices = loadedSlices.map((slice) => + parseSlice( + slice, + `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`, + ignoreWhitespace, + ), + ); + const files = parsedSlices.flatMap((parsed) => + parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], + ); + const filePaths = files.map((file) => resolveFileDiffPath(file)); + const omittedFileStats = new Map( + loadedSlices.flatMap((slice) => + slice.omittedFileStats.map((file) => [file.path, file] as const), + ), + ); + const sourceFileStats = new Map( + parsedSlices.flatMap((parsed) => + parsed?.kind === "files" + ? parsed.files.map( + (file, index) => + [ + buildFileDiffRenderKey(file), + getDiffLineStat([parsed.sourceFiles[index] ?? file]), + ] as const, + ) + : [], + ), + ); + const fileTreeEntries = diffFileTreeEntries(files); + return { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries }; +} + +function useAnnotatedDiffFiles( + files: ReadonlyArray, + reviewThreads: ReadonlyArray, + pendingComments: ReadonlyArray, + draft: DraftAnchor | null, + scopedToCommit: boolean, +) { + "use memo"; + // Placing a conversation takes more than its file being in the diff: its line has to fall + // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the + // off-diff list rather than disappearing between the two. + const placedThreadIds = (() => { + const placed = new Set(); + // A commit's diff counts lines within that commit; a review comment is anchored to the + // pull request's head diff. Pinning one onto the other would put the remark against + // whichever code happens to hold that line number in this commit, so while a commit is on + // screen every conversation is listed rather than placed. + if (scopedToCommit) return placed; + for (const file of files) { + const path = resolveFileDiffPath(file); + for (const thread of reviewThreads) { + if ( + thread.path === path && + thread.line !== null && + isLineInFileDiff(file, thread.side, thread.line) + ) { + placed.add(thread.id); + } + } + } + return placed; + })(); + + const annotatedFiles = files.map((fileDiff) => { + const fileKey = buildFileDiffRenderKey(fileDiff); + const path = resolveFileDiffPath(fileDiff); + const groups = new Map(); + const groupAt = (side: PullRequestDiffSide, line: number) => { + const key = `${side}:${line}`; + const existing = groups.get(key); + if (existing) return existing; + const created: MutableAnnotationGroup = { + side, + line, + threads: [], + pending: [], + draft: false, + }; + groups.set(key, created); + return created; + }; + + for (const thread of reviewThreads) { + if (thread.path !== path || thread.line === null) continue; + if (!placedThreadIds.has(thread.id)) continue; + groupAt(thread.side, thread.line).threads.push(thread); + } + if (!scopedToCommit) { + for (const comment of pendingComments) { + if (comment.path !== path) continue; + const anchor = getReviewPositionAnchor(comment.position); + groupAt(anchor.side, anchor.line).pending.push(comment); + } + } + if (draft?.fileKey === fileKey) { + const anchor = getReviewPositionAnchor(draft.position); + groupAt(anchor.side, anchor.line).draft = true; + } + + const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({ + side: toViewerSide(group.side), + lineNumber: group.line, + metadata: { threads: group.threads, pending: group.pending, draft: group.draft }, + })); + return { + fileKey, + path, + fileDiff, + annotations, + // The viewer re-renders an item only when its version changes, so everything the + // annotations show has to be part of it. + annotationsVersion: fnv1a32( + annotations + .map( + ({ side, lineNumber, metadata }) => + `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending + .map((comment) => `${comment.id}:${comment.body}`) + .join(",")}:${metadata.threads + .map( + (thread) => + `${thread.id}:${thread.isResolved ? "r" : ""}:${ + thread.isOutdated ? "o" : "" + }:${thread.comments + .map( + (comment) => + `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${( + comment.reactions ?? [] + ) + .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`) + .join(",")}`, + ) + .join(";")}`, + ) + .join(",")}`, + ) + .join("|"), + ), + }; + }); + return { annotatedFiles, placedThreadIds }; +} + +function useDiffItems( + annotatedFiles: ReturnType["annotatedFiles"], + foldOverride: Exclude, + toggledFiles: ReadonlySet, + viewedFiles: { + readonly enabled: boolean; + readonly isViewed: (path: string) => boolean; + readonly isStale: (path: string) => boolean; + }, +) { + "use memo"; + const items: CodeViewDiffItem[] = annotatedFiles.map( + ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles); + const viewedMark = viewedFiles.enabled + ? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}` + : ""; + return { + id: fileKey, + type: "diff" as const, + fileDiff, + annotations, + collapsed, + version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), + }; + }, + ); + return items; +} + function PullRequestCodeTab({ scrollerRef, environmentId, @@ -216,7 +497,6 @@ function PullRequestCodeTab({ readonly cursor: string | null; readonly slices: ReadonlyArray; }>({ key: "", cursor: null, slices: NO_SLICES }); - const parseCache = useRef(new Map()); const [viewer, setViewer] = useState | null>( null, ); @@ -226,7 +506,9 @@ function PullRequestCodeTab({ const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`; // The panel keeps this mounted across pull requests, so an open composer would otherwise // survive the switch and attach its comment to whichever one is on screen when it is sent. - useEffect(() => { + const [stateScopeKey, setStateScopeKey] = useState(scopeKey); + if (stateScopeKey !== scopeKey) { + setStateScopeKey(scopeKey); setDraft(null); setSelectedLines(null); setToggledFiles(new Set()); @@ -234,8 +516,7 @@ function PullRequestCodeTab({ setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); - parseCache.current.clear(); - }, [scopeKey]); + } const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES; const cursor = sliceState.key === scopeKey ? sliceState.cursor : null; @@ -249,9 +530,21 @@ function PullRequestCodeTab({ }, }), ); - useEffect(() => { - const data = diffQuery.data; - if (data === null) return; + // Pages accumulate into slices as each answer arrives, so the slice list is adjusted while + // rendering the answer rather than one commit later. + const [appliedPage, setAppliedPage] = useState<{ + readonly data: typeof diffQuery.data; + readonly cursor: string | null; + readonly scopeKey: string; + } | null>(null); + const data = diffQuery.data; + if ( + data !== null && + (appliedPage?.data !== data || + appliedPage.cursor !== cursor || + appliedPage.scopeKey !== scopeKey) + ) { + setAppliedPage({ data, cursor, scopeKey }); setSliceState((previous) => { const slices = previous.key === scopeKey ? previous.slices : NO_SLICES; const next = { @@ -288,7 +581,7 @@ function PullRequestCodeTab({ // after it go with the replacement: their cursors were positions in the old diff. return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] }; }); - }, [cursor, diffQuery.data, scopeKey]); + } const refreshFirstDiffPage = useAtomRefresh( pullRequestEnvironment.diff({ environmentId, @@ -312,55 +605,22 @@ function PullRequestCodeTab({ reportFailure: false, }); const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents); - const loadDiffFiles = useMemo( - () => - createPullRequestDiffFileContentsLoader(getDiffFileContents, { - environmentId, - reference, - commit, - cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, - }), - [commit, detail.updatedAt, environmentId, getDiffFileContents, reference, referenceKey], - ); + const loadDiffFiles = usePullRequestDiffFileContentsLoader(getDiffFileContents, { + environmentId, + reference, + commit, + cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, + }); - const review = useMemo(() => { - const hostReview = detail.capabilities.review; - const viewer = detail.viewerPermissions; - return { - inlineComment: hostReview.inlineComment && viewer.comment, - reply: hostReview.reply && viewer.comment, - resolve: hostReview.resolve && viewer.resolve, - }; - }, [detail.capabilities.review, detail.viewerPermissions]); + const hostReview = detail.capabilities.review; + const review = { + inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment, + reply: hostReview.reply && detail.viewerPermissions.comment, + resolve: hostReview.resolve && detail.viewerPermissions.resolve, + }; const canCommentOnLines = review.inlineComment && commit === null; - // Every slice is parsed on its own and the result held, so a slice arriving costs one parse - // rather than one per slice already on screen. Its cache key carries the theme, which is what - // the tokenizer caches against, so a theme change is still a fresh parse. - const parsedSlices = useMemo( - () => - loadedSlices.map((slice) => { - // The patch's own hash is part of the key: a refreshed page reuses its cursor, and a - // key of position alone would keep handing back the parse of the patch it replaced. - const cacheKey = `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`; - const cached = parseCache.current.get(cacheKey); - if (cached) return cached; - const parsed = getRenderablePatch(slice.patch, cacheKey, { - compactPartialHunkOffsets: true, - ignoreWhitespace, - }); - if (parsed) parseCache.current.set(cacheKey, parsed); - return parsed; - }), - [loadedSlices, resolvedTheme, scopeKey, ignoreWhitespace], - ); - const files = useMemo( - () => - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], - ), - [parsedSlices], - ); - const filePaths = useMemo(() => files.map((file) => resolveFileDiffPath(file)), [files]); + const { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries } = + useParsedDiffSlices(loadedSlices, scopeKey, resolvedTheme, ignoreWhitespace); const viewedFilesStore = detail.capabilities.viewedFiles; const filesViewed = usePullRequestFilesViewed({ environmentId, @@ -388,172 +648,20 @@ function PullRequestCodeTab({ loadedSlices.some((slice) => slice.truncated) || parsedSlices.some((parsed) => parsed?.kind === "raw"); - // Placing a conversation takes more than its file being in the diff: its line has to fall - // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the - // off-diff list rather than disappearing between the two. - const placedThreadIds = useMemo(() => { - const placed = new Set(); - // A commit's diff counts lines within that commit; a review comment is anchored to the - // pull request's head diff. Pinning one onto the other would put the remark against - // whichever code happens to hold that line number in this commit, so while a commit is on - // screen every conversation is listed rather than placed. - if (commit !== null) return placed; - for (const file of files) { - const path = resolveFileDiffPath(file); - for (const thread of detail.reviewThreads) { - if ( - thread.path === path && - thread.line !== null && - isLineInFileDiff(file, thread.side, thread.line) - ) { - placed.add(thread.id); - } - } - } - return placed; - }, [commit, detail.reviewThreads, files]); - - const annotatedFiles = useMemo( - () => - files.map((fileDiff) => { - const fileKey = buildFileDiffRenderKey(fileDiff); - const path = resolveFileDiffPath(fileDiff); - const groups = new Map(); - const groupAt = (side: PullRequestDiffSide, line: number) => { - const key = `${side}:${line}`; - const existing = groups.get(key); - if (existing) return existing; - const created: MutableAnnotationGroup = { - side, - line, - threads: [], - pending: [], - draft: false, - }; - groups.set(key, created); - return created; - }; - - for (const thread of detail.reviewThreads) { - if (thread.path !== path || thread.line === null) continue; - if (!placedThreadIds.has(thread.id)) continue; - groupAt(thread.side, thread.line).threads.push(thread); - } - if (commit === null) { - for (const comment of pendingComments) { - if (comment.path !== path) continue; - const anchor = getReviewPositionAnchor(comment.position); - groupAt(anchor.side, anchor.line).pending.push(comment); - } - } - if (draft?.fileKey === fileKey) { - const anchor = getReviewPositionAnchor(draft.position); - groupAt(anchor.side, anchor.line).draft = true; - } - - const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({ - side: toViewerSide(group.side), - lineNumber: group.line, - metadata: { threads: group.threads, pending: group.pending, draft: group.draft }, - })); - return { - fileKey, - path, - fileDiff, - annotations, - // The viewer re-renders an item only when its version changes, so everything the - // annotations show has to be part of it. - annotationsVersion: fnv1a32( - annotations - .map( - ({ side, lineNumber, metadata }) => - `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending - .map((comment) => `${comment.id}:${comment.body}`) - .join(",")}:${metadata.threads - .map( - (thread) => - `${thread.id}:${thread.isResolved ? "r" : ""}:${ - thread.isOutdated ? "o" : "" - }:${thread.comments - .map( - (comment) => - `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${( - comment.reactions ?? [] - ) - .map( - (r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`, - ) - .join(",")}`, - ) - .join(";")}`, - ) - .join(",")}`, - ) - .join("|"), - ), - }; - }), - [commit, detail.reviewThreads, draft, files, pendingComments, placedThreadIds], + const { annotatedFiles, placedThreadIds } = useAnnotatedDiffFiles( + files, + detail.reviewThreads, + pendingComments, + draft, + commit !== null, ); - const items = useMemo[]>( - () => - annotatedFiles.map(({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { - const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles); - const viewedMark = filesViewedEnabled - ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` - : ""; - return { - id: fileKey, - type: "diff" as const, - fileDiff, - annotations, - collapsed, - version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), - }; - }), - [ - annotatedFiles, - filesViewedEnabled, - effectiveFoldOverride, - isFileViewed, - isFileViewedStale, - toggledFiles, - ], - ); - const omittedFileStats = useMemo( - () => - new Map( - loadedSlices.flatMap((slice) => - slice.omittedFileStats.map((file) => [file.path, file] as const), - ), - ), - [loadedSlices], - ); - const sourceFileStats = useMemo( - () => - new Map( - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" - ? parsed.files.map( - (file, index) => - [ - buildFileDiffRenderKey(file), - getDiffLineStat([parsed.sourceFiles[index] ?? file]), - ] as const, - ) - : [], - ), - ), - [parsedSlices], - ); - const fileKeys = useMemo(() => items.map((item) => item.id), [items]); - const collapsedFileKeys = useMemo( - () => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)), - [items], + const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed); + const fileKeys = items.map((item) => item.id); + const collapsedFileKeys = new Set( + items.filter((item) => item.collapsed === true).map((item) => item.id), ); const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys); - const fileTreeEntries = useMemo(() => diffFileTreeEntries(files), [files]); // A failed slice must not be asked for again on its own. The files already loaded keep the // sentinel on screen, so re-arming it after a failure would request the same slice forever. @@ -562,10 +670,10 @@ function PullRequestCodeTab({ nextCursor !== cursor && !diffQuery.isPending && diffQuery.error === null; - const loadNextSlice = useCallback(() => { + const loadNextSlice = () => { if (nextCursor === null) return; setSliceState((previous) => ({ ...previous, cursor: nextCursor })); - }, [nextCursor]); + }; // The sentinel is held as state rather than a ref because the viewer mounts its own footer: // an effect reading a ref could run before that node exists and would never arm the observer. @@ -582,39 +690,36 @@ function PullRequestCodeTab({ return () => observer.disconnect(); }, [canLoadNextSlice, loadNextSlice, sentinel]); - const toggleFile = useCallback( - (fileKey: string) => - setToggledFiles((current) => { - const next = new Set(current); - if (next.has(fileKey)) next.delete(fileKey); - else next.add(fileKey); - return next; - }), - [], - ); + const toggleFile = (fileKey: string) => + setToggledFiles((current) => { + const next = new Set(current); + if (next.has(fileKey)) next.delete(fileKey); + else next.add(fileKey); + return next; + }); - const setFileViewed = useCallback( - (fileKey: string, path: string, viewed: boolean) => { - setViewed(path, viewed); - setToggledFiles((current) => - toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current), - ); - }, - [effectiveFoldOverride, setViewed], - ); + const setFileViewed = (fileKey: string, path: string, viewed: boolean) => { + setViewed(path, viewed); + setToggledFiles((current) => + toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current), + ); + }; + const fileViewedToggle = { + enabled: filesViewedEnabled, + isViewed: isFileViewed, + isStale: isFileViewedStale, + setFileViewed, + }; const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey); - const revealFile = useCallback( - (path: string) => { - const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); - if (item === undefined) return; - if (item.collapsed === true) toggleFile(item.id); - requestTreeReveal(item.id); - }, - [items, requestTreeReveal, toggleFile], - ); + const revealFile = (path: string) => { + const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); + if (item === undefined) return; + if (item.collapsed === true) toggleFile(item.id); + requestTreeReveal(item.id); + }; const answeredReveal = useRef(null); - useEffect(() => { + const answerReveal = useEffectEvent(() => { if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return; if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { if (canLoadNextSlice) loadNextSlice(); @@ -622,357 +727,285 @@ function PullRequestCodeTab({ } answeredReveal.current = revealRequest.nonce; revealFile(revealRequest.path); - }, [canLoadNextSlice, items, loadNextSlice, revealFile, revealRequest]); + }); + useEffect(() => { + // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor. + answerReveal(); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives. + }, [canLoadNextSlice, items, revealRequest]); const toggleAllFiles = () => { setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); setToggledFiles(new Set()); }; - const orderedCommits = useMemo( - () => - // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits - // from different zones would sort by how they were written rather than when they landed. - detail.commits.toSorted( - (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), - ), - [detail.commits], - ); + const orderedCommits = // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits + // from different zones would sort by how they were written rather than when they landed. + detail.commits.toSorted( + (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), + ); - const beginComment = useCallback( - (range: SelectedLineRange | null, context: { item: CodeViewItem }) => { - if (!range || !canCommentOnLines) return; - const item = context.item; - if (item.type !== "diff") return; - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id); - if (!file) return; - // A range collapses to its last line: only GitHub carries a multi-line comment, and one - // that silently lost its first line on the other hosts would be worse than one line. - const path = resolveFileDiffPath(file); - const previousPath = resolveFileDiffPreviousPath(file); - const sourceFile = parsedSlices - .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : [])) - .find((candidate) => resolveFileDiffPath(candidate) === path); - const side = range.endSide ?? range.side; - const position = - (sourceFile && resolveDiffReviewPosition(sourceFile, range.end, side)) ?? - resolveDiffReviewPosition(file, range.end, side); - if (position === null) return; - setDraft({ - fileKey: item.id, - path, - oldPath: previousPath === path ? null : previousPath, - position, - range, - }); - }, - [canCommentOnLines, files, parsedSlices], - ); + const beginComment = ( + range: SelectedLineRange | null, + context: { item: CodeViewItem }, + ) => { + if (!range || !canCommentOnLines) return; + const item = context.item; + if (item.type !== "diff") return; + const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id); + if (!file) return; + // A range collapses to its last line: only GitHub carries a multi-line comment, and one + // that silently lost its first line on the other hosts would be worse than one line. + const path = resolveFileDiffPath(file); + const previousPath = resolveFileDiffPreviousPath(file); + const sourceFile = parsedSlices + .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : [])) + .find((candidate) => resolveFileDiffPath(candidate) === path); + const side = range.endSide ?? range.side; + const position = + (sourceFile && resolveDiffReviewPosition(sourceFile, range.end, side)) ?? + resolveDiffReviewPosition(file, range.end, side); + if (position === null) return; + setDraft({ + fileKey: item.id, + path, + oldPath: previousPath === path ? null : previousPath, + position, + range, + }); + }; - const finishSelection = useCallback( - (anchor: DraftAnchor, text: string, onFinish: (comment: ReviewCommentContext) => void) => { - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey); - const comment = - file === undefined - ? null - : buildDiffReviewComment({ - id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`, - sectionId: `pull-request:${detail.number}`, - sectionTitle: `PR #${detail.number} review`, - filePath: anchor.path, - fileDiff: file, - range: anchor.range, - text, - }); - setDraft(null); - setSelectedLines(null); - if (comment !== null) onFinish(comment); - }, - [detail.number, files], - ); + const finishSelection = ( + anchor: DraftAnchor, + text: string, + onFinish: (comment: ReviewCommentContext) => void, + ) => { + const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey); + const comment = + file === undefined + ? null + : buildDiffReviewComment({ + id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`, + sectionId: `pull-request:${detail.number}`, + sectionTitle: `PR #${detail.number} review`, + filePath: anchor.path, + fileDiff: file, + range: anchor.range, + text, + }); + setDraft(null); + setSelectedLines(null); + if (comment !== null) onFinish(comment); + }; // The viewer's SlotPortals memoizes each visible file's header/annotation portal on these // render props and on `options` below; a fresh identity on any of them — as a plain inline // function or object literal would be — invalidates that memo and recreates every portal on // screen on any tab re-render (a drag-selection, a keystroke in the draft, a review-store // update), which is the jank this file is otherwise clean of. - const renderCodeViewFooter = useCallback( - () => - nextCursor === null ? null : ( -
- {diffQuery.error !== null ? ( - <> - The rest of this diff could not be loaded. - - - ) : diffQuery.isPending ? ( - "Loading more files..." - ) : null} -
- ), - [nextCursor, diffQuery.error, diffQuery.isPending, diffQuery.refresh], - ); - - const renderHeaderPrefix = useCallback( - (item: CodeViewItem) => { - const collapsed = item.collapsed === true; - return ( - - ); - }, - [toggleFile], - ); + const renderCodeViewFooter = () => + nextCursor === null ? null : ( +
+ {diffQuery.error !== null ? ( + <> + The rest of this diff could not be loaded. + + + ) : diffQuery.isPending ? ( + "Loading more files..." + ) : null} +
+ ); - const filesViewedRef = useRef(filesViewed); - filesViewedRef.current = filesViewed; - const setFileViewedRef = useRef(setFileViewed); - setFileViewedRef.current = setFileViewed; + const renderHeaderPrefix = (item: CodeViewItem) => { + const collapsed = item.collapsed === true; + return ( + + ); + }; - const renderHeaderMetadata = useCallback( - (item: CodeViewItem) => { - if (item.type !== "diff") return null; - let { additions, deletions } = - sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]); - const path = resolveFileDiffPath(item.fileDiff); - if (additions === 0 && deletions === 0) { - const withheld = omittedFileStats.get(path); - if (withheld) ({ additions, deletions } = withheld); - } - const stat = ( - - ); - const viewedFiles = filesViewedRef.current; - if (!viewedFiles.enabled) return stat; - const viewed = viewedFiles.isViewed(path); - const stale = viewedFiles.isStale(path); - return ( - - {stat} - - - ); - }, - [omittedFileStats, sourceFileStats], - ); + const renderHeaderMetadata = (item: CodeViewItem) => { + if (item.type !== "diff") return null; + let { additions, deletions } = sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]); + const path = resolveFileDiffPath(item.fileDiff); + if (additions === 0 && deletions === 0) { + const withheld = omittedFileStats.get(path); + if (withheld) ({ additions, deletions } = withheld); + } + return ( + + } + /> + ); + }; - const diffViewOptions = useMemo( - () => ({ - diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const), - lineDiffType: "none" as const, - overflow: wordWrap ? ("wrap" as const) : ("scroll" as const), - theme: resolveDiffThemeName(resolvedTheme), - preferredHighlighter: PREFERRED_HIGHLIGHTER, - themeType: resolvedTheme, - stickyHeaders: true, - loadDiffFiles, - enableGutterUtility: canCommentOnLines && draft === null, - enableLineSelection: canCommentOnLines && draft === null, - onGutterUtilityClick: beginComment, - onLineSelectionEnd: beginComment, - }), - [diffLayout, wordWrap, resolvedTheme, loadDiffFiles, canCommentOnLines, draft, beginComment], - ); + const diffViewOptions = { + diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const), + lineDiffType: "none" as const, + overflow: wordWrap ? ("wrap" as const) : ("scroll" as const), + theme: resolveDiffThemeName(resolvedTheme), + preferredHighlighter: PREFERRED_HIGHLIGHTER, + themeType: resolvedTheme, + stickyHeaders: true, + loadDiffFiles, + enableGutterUtility: canCommentOnLines && draft === null, + enableLineSelection: canCommentOnLines && draft === null, + onGutterUtilityClick: beginComment, + onLineSelectionEnd: beginComment, + }; - const runThreadCommand = useCallback( - async (label: string, run: () => Promise<{ readonly _tag: string }>): Promise => { - if (threadPending) return false; - setThreadPending(true); - const result = await run(); - setThreadPending(false); - if (result._tag === "Failure") { - toastManager.add({ type: "error", title: label }); - return false; - } - onRefresh(); - return true; - }, - [onRefresh, threadPending], - ); + const runThreadCommand = async ( + label: string, + run: () => Promise<{ readonly _tag: string }>, + ): Promise => { + if (threadPending) return false; + setThreadPending(true); + const result = await run(); + setThreadPending(false); + if (result._tag === "Failure") { + toastManager.add({ type: "error", title: label }); + return false; + } + onRefresh(); + return true; + }; - const renderThreadCard = useCallback( - (thread: PullRequestReviewThread) => ( - onFixFinding({ kind: "thread", thread }) } : {})} - onLoadMore={async (cursor): Promise => { - const result = await loadThreadComments({ - environmentId, - input: { ...reference, threadId: thread.id, cursor }, + const renderThreadCard = (thread: PullRequestReviewThread) => ( + onFixFinding({ kind: "thread", thread }) } : {})} + onLoadMore={async (cursor): Promise => { + const result = await loadThreadComments({ + environmentId, + input: { ...reference, threadId: thread.id, cursor }, + }); + if (result._tag === "Failure") { + toastManager.add({ + type: "error", + title: "More comments could not be loaded", }); - if (result._tag === "Failure") { - toastManager.add({ - type: "error", - title: "More comments could not be loaded", - }); - return null; - } - return result.value; - }} - onReply={(body) => - runThreadCommand("Reply could not be posted", () => - replyToThread({ - environmentId, - input: { ...reference, threadId: thread.id, body }, - }), - ) + return null; } - canEditComment={(comment) => - canEditPullRequestComment(detail, { - author: comment.author, - kind: "review-comment", - canEdit: comment.canEdit, - }) - } - onEditComment={(commentId, body) => - runThreadCommand("The comment could not be saved", () => - updateComment({ - environmentId, - input: { ...reference, commentId, kind: "review-comment", body }, - }), - ) - } - onToggleResolved={() => - void runThreadCommand("The conversation could not be updated", () => - setThreadResolution({ - environmentId, - input: { ...reference, threadId: thread.id, resolved: !thread.isResolved }, - }), - ) - } - onReacted={onRefresh} - /> - ), - [ - detail, - environmentId, - fixFindingLabel, - loadThreadComments, - onRefresh, - onFixFinding, - pendingFinding, - reference, - replyToThread, - review.reply, - review.resolve, - runThreadCommand, - setThreadResolution, - threadPending, - updateComment, - ], + return result.value; + }} + onReply={(body) => + runThreadCommand("Reply could not be posted", () => + replyToThread({ + environmentId, + input: { ...reference, threadId: thread.id, body }, + }), + ) + } + canEditComment={(comment) => + canEditPullRequestComment(detail, { + author: comment.author, + kind: "review-comment", + canEdit: comment.canEdit, + }) + } + onEditComment={(commentId, body) => + runThreadCommand("The comment could not be saved", () => + updateComment({ + environmentId, + input: { ...reference, commentId, kind: "review-comment", body }, + }), + ) + } + onToggleResolved={() => + void runThreadCommand("The conversation could not be updated", () => + setThreadResolution({ + environmentId, + input: { ...reference, threadId: thread.id, resolved: !thread.isResolved }, + }), + ) + } + onReacted={onRefresh} + /> ); - const renderAnnotation = useCallback( - (annotation: ReviewAnnotation) => ( -
- {annotation.metadata.threads.map(renderThreadCard)} - {annotation.metadata.pending.map((comment) => ( - removeComment(reviewKey, comment.id)} - /> - ))} - {annotation.metadata.draft && draft ? ( - - finishSelection(draft, text, (comment) => - onAddToAgentSelection({ comment, request: text }), - ), - }, - } - : {})} - onCancel={() => { - setDraft(null); - setSelectedLines(null); - }} - onComment={(body) => { - addComment(reviewKey, { - id: nextPendingReviewCommentId(), - path: draft.path, - ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }), - position: draft.position, - body, - }); - setDraft(null); - setSelectedLines(null); - }} - /> - ) : null} -
- ), - [ - addComment, - draft, - finishSelection, - onAddToAgentSelection, - removeComment, - renderThreadCard, - reviewKey, - ], + const renderAnnotation = (annotation: ReviewAnnotation) => ( +
+ {annotation.metadata.threads.map(renderThreadCard)} + {annotation.metadata.pending.map((comment) => ( + removeComment(reviewKey, comment.id)} + /> + ))} + {annotation.metadata.draft && draft ? ( + + finishSelection(draft, text, (comment) => + onAddToAgentSelection({ comment, request: text }), + ), + }, + } + : {})} + onCancel={() => { + setDraft(null); + setSelectedLines(null); + }} + onComment={(body) => { + addComment(reviewKey, { + id: nextPendingReviewCommentId(), + path: draft.path, + ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }), + position: draft.position, + body, + }); + setDraft(null); + setSelectedLines(null); + }} + /> + ) : null} +
); // A rebase or a force-push can take the scoped commit out of the change. Its diff may still @@ -1439,26 +1472,28 @@ function PullRequestCodeTab({ {/* The viewer virtualizes against the element it is told is scrolling and places its rows absolutely, so it has to own that element — the thread diff panel hands it the same one. Scrolling from a parent instead leaves it painting over its neighbours. */} - - className="@container h-full overflow-auto [scrollbar-gutter:stable]" - containerRef={scrollerRef} - viewerRef={setViewer} - items={items} - selectedLines={selectedLines} - onSelectedLinesChange={setSelectedLines} - options={diffViewOptions} - renderCodeViewFooter={renderCodeViewFooter} - renderHeaderPrefix={renderHeaderPrefix} - renderHeaderMetadata={renderHeaderMetadata} - renderAnnotation={renderAnnotation} - // Find can ask again before the unfolded file arrives, so this unfolds and never folds. - onRevealSearchMatch={(item) => - setToggledFiles((current) => - toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current), - ) - } - unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS} - /> + + + className="@container h-full overflow-auto [scrollbar-gutter:stable]" + containerRef={scrollerRef} + viewerRef={setViewer} + items={items} + selectedLines={selectedLines} + onSelectedLinesChange={setSelectedLines} + options={diffViewOptions} + renderCodeViewFooter={renderCodeViewFooter} + renderHeaderPrefix={renderHeaderPrefix} + renderHeaderMetadata={renderHeaderMetadata} + renderAnnotation={renderAnnotation} + // Find can ask again before the unfolded file arrives, so this unfolds and never folds. + onRevealSearchMatch={(item) => + setToggledFiles((current) => + toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current), + ) + } + unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS} + /> +
{fileTreeOpen ? ( )} From 44ecfd65b6b1ed4d9163f886e7118fe4258454de Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:32:55 -0700 Subject: [PATCH 313/323] refactor(web): the model picker keeps its caching without "use memo" (#20815) Co-authored-by: Claude Opus 5.5 --- .../components/chat/ModelPickerContent.tsx | 926 +++++++++--------- 1 file changed, 450 insertions(+), 476 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index abfef9ac6315..363f6b0ec4d6 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -4,13 +4,23 @@ import { type EnvironmentId, type ProviderDriverKind, type ResolvedKeybindingsConfig, + MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, } from "@t3tools/contracts"; import { resolveSelectableModel } from "@t3tools/shared/model"; import { useAtomValue } from "@effect/atom-react"; import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels"; import { useNavigate } from "@tanstack/react-router"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; -import { memo, useState, useEffect, useEffectEvent, useLayoutEffect, useRef } from "react"; +import { + memo, + useState, + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + type ReactNode, + type RefObject, +} from "react"; import { ChevronRightIcon } from "lucide-react"; import { ModelListRow } from "./ModelListRow"; import { ModelPickerSidebar } from "./ModelPickerSidebar"; @@ -156,26 +166,355 @@ function ModelListSeparator() { return
; } -// Every list below keys the virtualized list, the combobox or the shortcut listener, so -// they are derived together and only rebuilt when an input changes. -function useModelPickerLists( - favorites: ReturnType["favorites"], - instanceEntries: ReadonlyArray, - modelOptionsByInstance: ReadonlyMap>, - activeInstanceId: ProviderInstanceId, - activeModelSlug: string, - activeInstanceHasSelectableUnavailableModel: boolean, - lockedProvider: ProviderDriverKind | null, - lockedContinuationGroupKey: string | null | undefined, - hasProviderSetup: boolean, - searchQuery: string, - selectedInstanceId: ProviderInstanceId | "favorites", - expandedLegacyInstances: ReadonlySet, - getModelDisabledReason: - | ((instanceId: ProviderInstanceId, model: string) => string | null) - | undefined, -) { - "use memo"; +function modelJumpLabelsByKey( + modelKeys: ReadonlyArray, + keybindings: ResolvedKeybindingsConfig, + terminalOpen: boolean, +): ReadonlyMap { + const shortcutLabelOptions = { + platform: navigator.platform, + context: { terminalFocus: false, terminalOpen, modelPickerOpen: true }, + }; + const mapping = new Map(); + for (const [index, modelKey] of modelKeys.entries()) { + const command = modelPickerJumpCommandForIndex(index); + const label = command && shortcutLabelForCommand(keybindings, command, shortcutLabelOptions); + if (label) { + mapping.set(modelKey, label); + } + } + return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS; +} + +function ModelPickerProviderNotices({ + setupEntries, + updateRequiredNotices, + onRequestClose, + onOpenProviderSetup, +}: { + setupEntries: ReadonlyArray; + updateRequiredNotices: ReadonlyArray<{ instanceId: ProviderInstanceId; notice: string }>; + onRequestClose: (() => void) | undefined; + onOpenProviderSetup: ((instanceId: ProviderInstanceId) => void) | undefined; +}) { + const navigate = useNavigate(); + return ( + <> + {setupEntries.length > 0 ? ( +
+ {setupEntries.map((entry) => ( +
+

+ {getProviderStatusMessage(entry.snapshot)} +

+ { + onRequestClose?.(); + onOpenProviderSetup?.(entry.instanceId); + }} + > + {setupEntries.length > 1 ? `Set up ${entry.displayName}` : "Open provider setup"} + +
+ ))} +
+ ) : ( + No models found + )} + {updateRequiredNotices.map(({ instanceId, notice }) => ( +

+ {notice}{" "} + { + onRequestClose?.(); + void navigate({ to: "/settings/providers" }); + }} + > + Provider settings + +

+ ))} + + ); +} + +// Owns the list's measured height and scroll fades, which change on every scroll and +// resize without touching the picker's model lists. +function ModelPickerList({ + listRef, + itemKeys, + extraData, + renderItem, +}: { + listRef: RefObject; + itemKeys: ReadonlyArray; + extraData: unknown; + renderItem: (props: { item: string; index: number }) => ReactNode; +}) { + const [showTopScrollFade, setShowTopScrollFade] = useState(false); + const [showBottomScrollFade, setShowBottomScrollFade] = useState(false); + const [contentSize, setContentSize] = useState( + () => itemKeys.length * MODEL_LIST_ESTIMATED_ITEM_SIZE, + ); + useLayoutEffect(() => listRef.current?.getState().listen("totalSize", setContentSize), [listRef]); + const updateScrollFades = () => { + const scrollElement = listRef.current?.getScrollableNode(); + if (!(scrollElement instanceof HTMLElement)) { + return; + } + const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight); + setShowTopScrollFade(scrollElement.scrollTop > 1); + setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); + }; + + // Keyed by content: a new disabled-reason closure rebuilds an identical key array. + const itemListKey = JSON.stringify(itemKeys); + // A new list starts from the top until the measurement below lands. + const [fadesResetFor, setFadesResetFor] = useState(itemListKey); + if (fadesResetFor !== itemListKey) { + setFadesResetFor(itemListKey); + setShowTopScrollFade(false); + setShowBottomScrollFade(itemKeys.length > 5); + } + const measureScrollFades = useEffectEvent(updateScrollFades); + useLayoutEffect(() => { + let nestedFrame = 0; + const frame = window.requestAnimationFrame(() => { + measureScrollFades(); + nestedFrame = window.requestAnimationFrame(() => measureScrollFades()); + }); + return () => { + window.cancelAnimationFrame(frame); + window.cancelAnimationFrame(nestedFrame); + }; + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out. + }, [itemListKey]); + + return ( +
+ + + ref={listRef} + data={itemKeys} + extraData={extraData} + keyExtractor={(modelKey) => modelKey} + renderItem={renderItem} + estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE} + drawDistance={480} + recycleItems + contentContainerClassName="pl-2 pr-px" + ItemSeparatorComponent={ModelListSeparator} + onLayout={updateScrollFades} + onScroll={updateScrollFades} + className={cn( + "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2", + getVirtualizedScrollFadeClassName({ + top: showTopScrollFade, + bottom: showBottomScrollFade, + }), + )} + /> + +
+ ); +} + +// Capture phase, so model and provider shortcuts win over the composer underneath. +function WindowKeyDownListener({ onKeyDown }: { onKeyDown: (event: KeyboardEvent) => void }) { + const handleKeyDown = useEffectEvent(onKeyDown); + useEffect(() => { + const listener = (event: KeyboardEvent) => handleKeyDown(event); + window.addEventListener("keydown", listener, true); + return () => { + window.removeEventListener("keydown", listener, true); + }; + }, []); + return null; +} + +export const ModelPickerContent = memo(function ModelPickerContent(props: { + environmentId: EnvironmentId | null; + activeInstanceId: ProviderInstanceId; + model: string; + selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; + onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; + lockedProvider: ProviderDriverKind | null; + lockedContinuationGroupKey?: string | null; + instanceEntries: ReadonlyArray; + keybindings?: ResolvedKeybindingsConfig; + modelOptionsByInstance: ReadonlyMap>; + terminalOpen: boolean; + onRequestClose?: () => void; + onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void; + getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; + onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; +}) { + const { + keybindings: providedKeybindings, + modelOptionsByInstance, + instanceEntries, + getModelDisabledReason, + onInstanceModelChange, + onToggleModel, + onRequestClose, + onOpenProviderSetup, + } = props; + const [searchQuery, setSearchQuery] = useState(""); + const searchInputRef = useRef(null); + const modelListRef = useRef(null); + const pickerContentRef = useRef(null); + const highlightedModelKeyRef = useRef(null); + const { favorites } = useEnvironmentModelPreferences(props.environmentId); + const activeEntry = props.instanceEntries.find( + (entry) => entry.instanceId === props.activeInstanceId, + ); + const activeModel = resolveModelPickerSelectedModel({ + driverKind: activeEntry?.driverKind, + model: props.model, + options: modelOptionsByInstance.get(props.activeInstanceId) ?? [], + }); + const activeModelSlug = + activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model); + const activeModelKey = activeModelSlug + ? modelPickerModelKey(props.activeInstanceId, activeModelSlug) + : null; + const selectedModelKeys = props.selectedModels?.map((selection) => { + const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId); + const model = resolveModelPickerSelectedModel({ + driverKind: entry?.driverKind, + model: selection.model, + options: modelOptionsByInstance.get(selection.instanceId) ?? [], + }); + return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model); + }); + const selectedModelKeySet = new Set( + selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []), + ); + const activeInstanceHasSelectableUnavailableModel = + activeEntry !== undefined && + (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) => + shouldIncludeModelPickerOption({ + entry: activeEntry, + option, + activeInstanceId: props.activeInstanceId, + activeModel: activeModelSlug, + }), + ) && + !isProviderInstancePickerReady(activeEntry); + const activeInstanceNeedsSetup = + onOpenProviderSetup !== undefined && + activeEntry !== undefined && + shouldOfferModelPickerSetup( + activeEntry, + modelOptionsByInstance.get(props.activeInstanceId) ?? [], + ); + const [selectedInstanceId, setSelectedInstanceId] = useState( + () => { + if ( + props.lockedProvider !== null || + activeInstanceHasSelectableUnavailableModel || + activeInstanceNeedsSetup + ) { + return props.activeInstanceId; + } + return favorites.length > 0 ? "favorites" : props.activeInstanceId; + }, + ); + const [expandedLegacyInstances, setExpandedLegacyInstances] = useState( + () => + new Set( + modelOptionsByInstance + .get(props.activeInstanceId) + ?.some((model) => model.slug === activeModelSlug && model.isLegacy) + ? [props.activeInstanceId] + : [], + ), + ); + const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom); + const keybindings = providedKeybindings ?? serverKeybindings; + const [searchHeight, setSearchHeight] = useState(0); + const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId); + + const focusSearchInput = () => { + searchInputRef.current?.focus({ preventScroll: true }); + }; + + const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => { + setSelectedInstanceId(instanceId); + window.requestAnimationFrame(() => { + focusSearchInput(); + }); + }; + + useLayoutEffect(() => { + focusSearchInput(); + const frame = window.requestAnimationFrame(() => { + focusSearchInput(); + }); + const timeout = window.setTimeout(() => { + focusSearchInput(); + }, 0); + return () => { + window.cancelAnimationFrame(frame); + window.clearTimeout(timeout); + }; + }, [focusSearchInput]); + + const toggleLegacySection = (instanceId: ProviderInstanceId) => { + setExpandedLegacyInstances((expanded) => { + const next = new Set(expanded); + if (next.has(instanceId)) { + next.delete(instanceId); + } else { + next.add(instanceId); + } + return next; + }); + }; + + const handleModelSelect = ( + modelSlug: string, + instanceId: ProviderInstanceId, + additive = false, + ) => { + if (getModelDisabledReason?.(instanceId, modelSlug)) { + return; + } + const options = modelOptionsByInstance.get(instanceId); + if (!options) { + return; + } + const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId); + if (!entry) { + return; + } + const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options); + if (resolvedModel) { + if (additive && onToggleModel) { + onToggleModel(instanceId, resolvedModel); + } else { + onInstanceModelChange(instanceId, resolvedModel); + } + } + }; + + const modelJumpShortcutContext = { + terminalFocus: false, + terminalOpen: props.terminalOpen, + modelPickerOpen: true, + } as const; + const lockedProvider = props.lockedProvider; + const lockedContinuationGroupKey = props.lockedContinuationGroupKey; + const canOpenProviderSetup = onOpenProviderSetup !== undefined; const favoritesSet = (() => { return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model))); })(); @@ -193,9 +532,9 @@ function useModelPickerLists( const selectableUnavailableInstanceIds = (() => { const instanceIds = new Set(); if (activeInstanceHasSelectableUnavailableModel) { - instanceIds.add(activeInstanceId); + instanceIds.add(props.activeInstanceId); } - if (hasProviderSetup) { + if (canOpenProviderSetup) { for (const entry of instanceEntries) { if ( shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? []) @@ -219,7 +558,7 @@ function useModelPickerLists( !shouldIncludeModelPickerOption({ entry, option: model, - activeInstanceId: activeInstanceId, + activeInstanceId: props.activeInstanceId, activeModel: activeModelSlug, }) ) { @@ -347,7 +686,7 @@ function useModelPickerLists( const selectedEntry = selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId); const providerSetupEntries = - !isSearching && hasProviderSetup + !isSearching && canOpenProviderSetup ? instanceEntries.filter( (entry) => matchesLockedProvider(entry) && @@ -361,37 +700,19 @@ function useModelPickerLists( ) : []; - const updateRequiredNotices = ( - isSearching - ? instanceEntries.filter(matchesLockedProvider) - : selectedEntry - ? [selectedEntry] - : [] - ).flatMap((entry) => { - const notice = formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery); + const updateRequiredNotices = instanceEntries.flatMap((entry) => { + const shown = isSearching + ? matchesLockedProvider(entry) + : entry.instanceId === selectedEntry?.instanceId; + const notice = shown ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery) : null; return notice ? [{ instanceId: entry.instanceId, notice }] : []; }); - const modelJumpCommandByKey = (() => { - const mapping = new Map< - string, - NonNullable> - >(); - let selectableModelIndex = 0; - for (const model of visibleModels) { - if (getModelDisabledReason?.(model.instanceId, model.slug)) { - continue; - } - const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex); - if (!jumpCommand) { - return mapping; - } - mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand); - selectableModelIndex += 1; - } - return mapping; - })(); - const modelJumpModelKeys = [...modelJumpCommandByKey.keys()]; + // The first selectable models get the numbered jump shortcuts, in list order. + const modelJumpModelKeys = visibleModels + .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug)) + .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length) + .map((model) => modelPickerModelKey(model.instanceId, model.slug)); const allItemKeys = ((): string[] => [ ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)), ...new Set( @@ -416,272 +737,12 @@ function useModelPickerLists( (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const, ), ))(); - return { - favoritesSet, - entryByInstanceId, - matchesLockedProvider, - selectableUnavailableInstanceIds, - flatModels, - isLocked, - isSearching, - lockedDisabledInstanceIds, - sidebarInstanceEntries, - showSidebar, - instanceOrder, - filteredModels, - legacySection, - visibleModels, - selectedEntry, - providerSetupEntries, - updateRequiredNotices, - modelJumpCommandByKey, - modelJumpModelKeys, - allItemKeys, - filteredItemKeys, - filteredModelByKey, - }; -} - -export const ModelPickerContent = memo(function ModelPickerContent(props: { - environmentId: EnvironmentId | null; - activeInstanceId: ProviderInstanceId; - model: string; - selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; - onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; - lockedProvider: ProviderDriverKind | null; - lockedContinuationGroupKey?: string | null; - instanceEntries: ReadonlyArray; - keybindings?: ResolvedKeybindingsConfig; - modelOptionsByInstance: ReadonlyMap>; - terminalOpen: boolean; - onRequestClose?: () => void; - onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void; - getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; - onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; -}) { - const { - keybindings: providedKeybindings, - modelOptionsByInstance, - instanceEntries, - getModelDisabledReason, - onInstanceModelChange, - onToggleModel, - } = props; - const [searchQuery, setSearchQuery] = useState(""); - const [showTopScrollFade, setShowTopScrollFade] = useState(false); - const [showBottomScrollFade, setShowBottomScrollFade] = useState(false); - const searchInputRef = useRef(null); - const modelListRef = useRef(null); - const pickerContentRef = useRef(null); - const highlightedModelKeyRef = useRef(null); - const { favorites } = useEnvironmentModelPreferences(props.environmentId); - const activeEntry = props.instanceEntries.find( - (entry) => entry.instanceId === props.activeInstanceId, - ); - const activeModel = resolveModelPickerSelectedModel({ - driverKind: activeEntry?.driverKind, - model: props.model, - options: modelOptionsByInstance.get(props.activeInstanceId) ?? [], - }); - const activeModelSlug = - activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model); - const activeModelKey = activeModelSlug - ? modelPickerModelKey(props.activeInstanceId, activeModelSlug) - : null; - const selectedModelKeys = props.selectedModels?.map((selection) => { - const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId); - const model = resolveModelPickerSelectedModel({ - driverKind: entry?.driverKind, - model: selection.model, - options: modelOptionsByInstance.get(selection.instanceId) ?? [], - }); - return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model); - }); - const selectedModelKeySet = new Set( - selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []), - ); - const activeInstanceHasSelectableUnavailableModel = - activeEntry !== undefined && - (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) => - shouldIncludeModelPickerOption({ - entry: activeEntry, - option, - activeInstanceId: props.activeInstanceId, - activeModel: activeModelSlug, - }), - ) && - !isProviderInstancePickerReady(activeEntry); - const activeInstanceNeedsSetup = - props.onOpenProviderSetup !== undefined && - activeEntry !== undefined && - shouldOfferModelPickerSetup( - activeEntry, - modelOptionsByInstance.get(props.activeInstanceId) ?? [], - ); - const [selectedInstanceId, setSelectedInstanceId] = useState( - () => { - if ( - props.lockedProvider !== null || - activeInstanceHasSelectableUnavailableModel || - activeInstanceNeedsSetup - ) { - return props.activeInstanceId; - } - return favorites.length > 0 ? "favorites" : props.activeInstanceId; - }, - ); - const [expandedLegacyInstances, setExpandedLegacyInstances] = useState( - () => - new Set( - modelOptionsByInstance - .get(props.activeInstanceId) - ?.some((model) => model.slug === activeModelSlug && model.isLegacy) - ? [props.activeInstanceId] - : [], - ), - ); - const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom); - const keybindings = providedKeybindings ?? serverKeybindings; - const navigate = useNavigate(); - const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId); - - const focusSearchInput = () => { - searchInputRef.current?.focus({ preventScroll: true }); - }; - - const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => { - setSelectedInstanceId(instanceId); - window.requestAnimationFrame(() => { - focusSearchInput(); - }); - }; - - useLayoutEffect(() => { - focusSearchInput(); - const frame = window.requestAnimationFrame(() => { - focusSearchInput(); - }); - const timeout = window.setTimeout(() => { - focusSearchInput(); - }, 0); - return () => { - window.cancelAnimationFrame(frame); - window.clearTimeout(timeout); - }; - }, [focusSearchInput]); - const { - favoritesSet, - entryByInstanceId, - selectableUnavailableInstanceIds, - isLocked, - isSearching, - lockedDisabledInstanceIds, - sidebarInstanceEntries, - showSidebar, - legacySection, - providerSetupEntries, - updateRequiredNotices, - modelJumpCommandByKey, + const modelJumpLabelByKey = modelJumpLabelsByKey( modelJumpModelKeys, - allItemKeys, - filteredItemKeys, - filteredModelByKey, - } = useModelPickerLists( - favorites, - instanceEntries, - modelOptionsByInstance, - props.activeInstanceId, - activeModelSlug, - activeInstanceHasSelectableUnavailableModel, - props.lockedProvider, - props.lockedContinuationGroupKey, - props.onOpenProviderSetup !== undefined, - searchQuery, - selectedInstanceId, - expandedLegacyInstances, - getModelDisabledReason, - ); - - const toggleLegacySection = (instanceId: ProviderInstanceId) => { - setExpandedLegacyInstances((expanded) => { - const next = new Set(expanded); - if (next.has(instanceId)) { - next.delete(instanceId); - } else { - next.add(instanceId); - } - return next; - }); - }; - - const handleModelSelect = ( - modelSlug: string, - instanceId: ProviderInstanceId, - additive = false, - ) => { - if (getModelDisabledReason?.(instanceId, modelSlug)) { - return; - } - const options = modelOptionsByInstance.get(instanceId); - if (!options) { - return; - } - const entry = entryByInstanceId.get(instanceId); - if (!entry) { - return; - } - const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options); - if (resolvedModel) { - if (additive && onToggleModel) { - onToggleModel(instanceId, resolvedModel); - } else { - onInstanceModelChange(instanceId, resolvedModel); - } - } - }; - - const [modelListContentSize, setModelListContentSize] = useState( - () => filteredItemKeys.length * MODEL_LIST_ESTIMATED_ITEM_SIZE, - ); - const [searchHeight, setSearchHeight] = useState(0); - useLayoutEffect( - () => modelListRef.current?.getState().listen("totalSize", setModelListContentSize), - [], + keybindings, + props.terminalOpen, ); - const modelListHeight = - filteredItemKeys.length === 0 ? 0 : `calc(${modelListContentSize}px + var(--spacing) * 5)`; - const updateModelListScrollFades = () => { - const scrollElement = modelListRef.current?.getScrollableNode(); - if (!(scrollElement instanceof HTMLElement)) { - return; - } - const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight); - setShowTopScrollFade(scrollElement.scrollTop > 1); - setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); - }; - const modelJumpShortcutContext = { - terminalFocus: false, - terminalOpen: props.terminalOpen, - modelPickerOpen: true, - } as const; - const modelJumpLabelByKey = ((): ReadonlyMap => { - if (modelJumpCommandByKey.size === 0) { - return EMPTY_MODEL_JUMP_LABELS; - } - const shortcutLabelOptions = { - platform: navigator.platform, - context: modelJumpShortcutContext, - }; - const mapping = new Map(); - for (const [modelKey, command] of modelJumpCommandByKey) { - const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions); - if (label) { - mapping.set(modelKey, label); - } - } - return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS; - })(); const modelListExtraData = { favoritesSet, modelJumpLabelByKey, @@ -689,7 +750,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { selectedModelKeySet, }; - const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => { + const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) { return; } @@ -728,40 +789,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { return; } handleModelSelect(model.slug, model.instanceId); - }); - useEffect(() => { - const listener = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event); - window.addEventListener("keydown", listener, true); - return () => { - window.removeEventListener("keydown", listener, true); - }; - }, []); - - // Keyed by content: a new disabled-reason closure rebuilds an identical key array. - const filteredItemListKey = JSON.stringify(filteredItemKeys); - // A new list starts from the top until the measurement below lands. - const [fadesResetFor, setFadesResetFor] = useState(filteredItemListKey); - if (fadesResetFor !== filteredItemListKey) { - setFadesResetFor(filteredItemListKey); - setShowTopScrollFade(false); - setShowBottomScrollFade(filteredItemKeys.length > 5); - } - const measureScrollFades = useEffectEvent(updateModelListScrollFades); - useLayoutEffect(() => { - let nestedFrame = 0; - const frame = window.requestAnimationFrame(() => { - measureScrollFades(); - nestedFrame = window.requestAnimationFrame(() => measureScrollFades()); - }); - return () => { - window.cancelAnimationFrame(frame); - window.cancelAnimationFrame(nestedFrame); - }; - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out. - }, [filteredItemListKey]); + }; return ( +
e.stopPropagation()} /> -
- - - ref={modelListRef} - data={filteredItemKeys} - extraData={modelListExtraData} - keyExtractor={(modelKey) => modelKey} - renderItem={({ item: modelKey, index }) => { - if (legacySection?.key === modelKey) { - return ( - -
-
Legacy models
-
- {legacySection.legacyModels.length} models -
-
- -
- ); - } - const model = filteredModelByKey.get(modelKey); - if (!model) { - return null; - } - const disabledReason = - getModelDisabledReason?.(model.instanceId, model.slug) ?? null; - return ( - { + if (legacySection?.key === modelKey) { + return ( + +
+
Legacy models
+
+ {legacySection.legacyModels.length} models +
+
+ toggleFavorite(model.instanceId, model.slug)} /> - ); - }} - estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE} - drawDistance={480} - recycleItems - contentContainerClassName="pl-2 pr-px" - ItemSeparatorComponent={ModelListSeparator} - onLayout={updateModelListScrollFades} - onScroll={updateModelListScrollFades} - className={cn( - "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2", - getVirtualizedScrollFadeClassName({ - top: showTopScrollFade, - bottom: showBottomScrollFade, - }), - )} - /> -
-
- {providerSetupEntries.length > 0 ? ( -
- {providerSetupEntries.map((entry) => ( -
-

- {getProviderStatusMessage(entry.snapshot)} -

- { - props.onRequestClose?.(); - props.onOpenProviderSetup?.(entry.instanceId); - }} - > - {providerSetupEntries.length > 1 - ? `Set up ${entry.displayName}` - : "Open provider setup"} - -
- ))} -
- ) : ( - No models found - )} - {updateRequiredNotices.map(({ instanceId, notice }) => ( -

- {notice}{" "} - { - props.onRequestClose?.(); - void navigate({ to: "/settings/providers" }); - }} - > - Provider settings - -

- ))} + + ); + } + const model = filteredModelByKey.get(modelKey); + if (!model) { + return null; + } + const disabledReason = + getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + return ( + toggleFavorite(model.instanceId, model.slug)} + /> + ); + }} + /> +
From 78f8d38ebb8c7cabddc2a0c9f114d5aa27c95ab3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:33:30 -0700 Subject: [PATCH 314/323] refactor(web): pull request code tab keeps its caching without "use memo" (#20816) Co-authored-by: Claude Opus 5.5 --- .../pullRequest/PullRequestCodeTab.tsx | 187 ++++++++---------- .../pullRequestFilesViewed.logic.test.ts | 9 - .../pullRequestFilesViewed.logic.ts | 11 -- .../usePullRequestFilesViewed.test.tsx | 4 +- .../pullRequest/usePullRequestFilesViewed.ts | 6 +- 5 files changed, 81 insertions(+), 136 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 788cae0a7124..5d06a1ff4831 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,9 +1,4 @@ -import type { - CodeViewItem, - DiffLineAnnotation, - FileDiffMetadata, - SelectedLineRange, -} from "@pierre/diffs"; +import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs"; import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react"; import type { EnvironmentId, @@ -243,47 +238,6 @@ export interface PullRequestAgentSelectionInput { readonly request: string; } -// Kept as a "use memo" hook: each item's version needs the viewed state that -// `usePullRequestFilesViewed` returns, so items are built after that hook from `annotatedFiles`. Those -// alias `files`, which already went through plain functions before the hook, and the hook itself has -// to receive `filePaths`. Built inline, that straddle leaves `files` and everything derived from it -// uncached. The viewer re-renders each item on its version. -function useDiffItems( - annotatedFiles: ReadonlyArray<{ - readonly fileKey: string; - readonly path: string; - readonly fileDiff: FileDiffMetadata; - readonly annotations: ReviewAnnotation[]; - readonly annotationsVersion: number; - }>, - foldOverride: Exclude, - toggledFiles: ReadonlySet, - viewedFiles: { - readonly enabled: boolean; - readonly isViewed: (path: string) => boolean; - readonly isStale: (path: string) => boolean; - }, -) { - "use memo"; - const items: CodeViewDiffItem[] = annotatedFiles.map( - ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { - const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles); - const viewedMark = viewedFiles.enabled - ? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}` - : ""; - return { - id: fileKey, - type: "diff" as const, - fileDiff, - annotations, - collapsed, - version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), - }; - }, - ); - return items; -} - function PullRequestCodeTab({ scrollerRef, environmentId, @@ -451,13 +405,41 @@ function PullRequestCodeTab({ reportFailure: false, }); const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents); + + const viewedFilesStore = detail.capabilities.viewedFiles; + const filesViewed = usePullRequestFilesViewed({ + environmentId, + reference, + enabled: viewedFilesStore !== undefined, + }); + const { + setViewed, + refresh: refreshFilesViewed, + enabled: filesViewedEnabled, + isViewed: isFileViewed, + isStale: isFileViewedStale, + } = filesViewed; + const appliedRefreshToken = useRef(refreshToken); + useEffect(() => { + if (appliedRefreshToken.current === refreshToken) return; + appliedRefreshToken.current = refreshToken; + setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); + refreshFirstDiffPage(); + refreshFilesViewed(); + }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]); + + // The sentinel is held as state rather than a ref because the viewer mounts its own footer: + // an effect reading a ref could run before that node exists and would never arm the observer. + const [sentinel, setSentinel] = useState(null); + const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey); + const answeredReveal = useRef(null); + const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { environmentId, reference, commit, cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, }); - const hostReview = detail.capabilities.review; const review = { inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment, @@ -632,30 +614,23 @@ function PullRequestCodeTab({ ))}
); - const viewedFilesStore = detail.capabilities.viewedFiles; - const filesViewed = usePullRequestFilesViewed({ - environmentId, - reference, - enabled: viewedFilesStore !== undefined, - paths: filePaths, - }); - const { - setViewed, - refresh: refreshFilesViewed, - enabled: filesViewedEnabled, - isViewed: isFileViewed, - isStale: isFileViewedStale, - } = filesViewed; - const appliedRefreshToken = useRef(refreshToken); - useEffect(() => { - if (appliedRefreshToken.current === refreshToken) return; - appliedRefreshToken.current = refreshToken; - setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); - refreshFirstDiffPage(); - refreshFilesViewed(); - }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]); - const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed); + const items: CodeViewDiffItem[] = annotatedFiles.map( + ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles); + const viewedMark = filesViewedEnabled + ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` + : ""; + return { + id: fileKey, + type: "diff" as const, + fileDiff, + annotations, + collapsed, + version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), + }; + }, + ); const fileKeys = items.map((item) => item.id); const collapsedFileKeys = new Set( items.filter((item) => item.collapsed === true).map((item) => item.id), @@ -674,21 +649,6 @@ function PullRequestCodeTab({ setSliceState((previous) => ({ ...previous, cursor: nextCursor })); }; - // The sentinel is held as state rather than a ref because the viewer mounts its own footer: - // an effect reading a ref could run before that node exists and would never arm the observer. - const [sentinel, setSentinel] = useState(null); - useEffect(() => { - if (sentinel === null || !canLoadNextSlice) return; - const observer = new IntersectionObserver( - (observed) => { - if (observed.some((entry) => entry.isIntersecting)) loadNextSlice(); - }, - { rootMargin: "240px" }, - ); - observer.observe(sentinel); - return () => observer.disconnect(); - }, [canLoadNextSlice, loadNextSlice, sentinel]); - const toggleFile = (fileKey: string) => setToggledFiles((current) => { const next = new Set(current); @@ -710,28 +670,12 @@ function PullRequestCodeTab({ setFileViewed, }; - const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey); const revealFile = (path: string) => { const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; if (item.collapsed === true) toggleFile(item.id); requestTreeReveal(item.id); }; - const answeredReveal = useRef(null); - const answerReveal = useEffectEvent(() => { - if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return; - if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { - if (canLoadNextSlice) loadNextSlice(); - return; - } - answeredReveal.current = revealRequest.nonce; - revealFile(revealRequest.path); - }); - useEffect(() => { - // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor. - answerReveal(); - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives. - }, [canLoadNextSlice, items, revealRequest]); const toggleAllFiles = () => { setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); @@ -1014,11 +958,6 @@ function PullRequestCodeTab({ // to the whole diff and it is not drawn without commits to list, so a scope that outlived them // would leave the tab reading one obsolete commit with nothing to press. const selectedCommit = orderedCommits.find((entry) => entry.oid === commit); - useEffect(() => { - if (commit !== null && selectedCommit === undefined) { - onSelectedCommitChange(null); - } - }, [commit, onSelectedCommitChange, selectedCommit]); const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits"; const changeIgnoreWhitespace = (next: boolean) => { setIgnoreWhitespace(next); @@ -1083,7 +1022,7 @@ function PullRequestCodeTab({ {filesViewed.enabled && files.length > 0 ? ( - {filesViewed.viewedCount} / {files.length} + {filePaths.filter(isFileViewed).length} / {files.length} {viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"} @@ -1316,6 +1255,38 @@ function PullRequestCodeTab({ ); + // The effects sit after every derivation: a hook between the diff's derivations and their + // later readers (the viewer options, the reveal handler) would leave them uncached. + useEffect(() => { + if (sentinel === null || !canLoadNextSlice) return; + const observer = new IntersectionObserver( + (observed) => { + if (observed.some((entry) => entry.isIntersecting)) loadNextSlice(); + }, + { rootMargin: "240px" }, + ); + observer.observe(sentinel); + return () => observer.disconnect(); + }, [canLoadNextSlice, loadNextSlice, sentinel]); + const answerReveal = useEffectEvent(() => { + if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return; + if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { + if (canLoadNextSlice) loadNextSlice(); + return; + } + answeredReveal.current = revealRequest.nonce; + revealFile(revealRequest.path); + }); + useEffect(() => { + // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor. + answerReveal(); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives. + }, [canLoadNextSlice, items, revealRequest]); + useEffect(() => { + if (commit !== null && selectedCommit === undefined) { + onSelectedCommitChange(null); + } + }, [commit, onSelectedCommitChange, selectedCommit]); const withToolbar = (body: ReactNode) => (
{toolbar} diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts index 4a74f3d01c73..cbf36cc85884 100644 --- a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { - countViewedFiles, isFileViewed, isStaleViewedState, revertFileViewedOverlay, @@ -47,14 +46,6 @@ describe("isFileViewed", () => { }); }); -describe("countViewedFiles", () => { - it("counts only the files on screen, presses included", () => { - expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, NO_OVERLAY)).toBe(1); - expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, new Map([["b.ts", true]]))).toBe(2); - expect(countViewedFiles(["b.ts"], states, NO_OVERLAY)).toBe(0); - }); -}); - describe("settleFileViewedOverlay", () => { it("drops a press the host has caught up on", () => { const settled = settleFileViewedOverlay( diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts index 215781a3581c..652fb3c2db2d 100644 --- a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts @@ -28,17 +28,6 @@ export function isFileViewed( return pressed ?? isViewedState(states?.get(path)); } -export function countViewedFiles( - paths: ReadonlyArray, - states: FileViewedStates | null, - overlay: FileViewedOverlay, -): number { - return paths.reduce( - (total, path) => (isFileViewed(path, states, overlay) ? total + 1 : total), - 0, - ); -} - /** * A press is held until a read that could have seen it comes back, rather than cleared when the * write succeeds: that read is a separate round trip, and dropping the press in between flashes diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx index 993e88373203..d1a29ec19eea 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx @@ -41,7 +41,6 @@ const reference: PullRequestRef = { repository: "acme/web", number: 42, }; -const paths = ["a.ts"]; function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesViewedResult { return { files: [{ path: "a.ts", state }], truncated: false }; @@ -54,7 +53,7 @@ function Probe(_props: { readonly view: PullRequestFilesViewedView }) { } function Surface() { - const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true, paths }); + const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true }); return ; } @@ -110,7 +109,6 @@ describe("a mark whose file was pushed to before the read that followed it", () expect(view().isViewed("a.ts")).toBe(false); expect(view().isStale("a.ts")).toBe(true); - expect(view().viewedCount).toBe(0); }); it("stays given way to on every later read, having nothing left to recover", async () => { diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts index 86396134f9b8..9756e49bfd73 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts @@ -9,7 +9,6 @@ import { useStableCallback } from "~/hooks/useStableCallback"; import { toastManager } from "../ui/toast"; import { - countViewedFiles, isFileViewed, isStaleViewedState, revertFileViewedOverlay, @@ -29,7 +28,6 @@ export interface PullRequestFilesViewedView { readonly isViewed: (path: string) => boolean; readonly isStale: (path: string) => boolean; readonly setViewed: (path: string, viewed: boolean) => void; - readonly viewedCount: number; readonly truncated: boolean; readonly error: string | null; readonly refresh: () => void; @@ -39,9 +37,8 @@ export function usePullRequestFilesViewed(options: { readonly environmentId: EnvironmentId; readonly reference: PullRequestRef; readonly enabled: boolean; - readonly paths: ReadonlyArray; }): PullRequestFilesViewedView { - const { environmentId, reference, enabled, paths } = options; + const { environmentId, reference, enabled } = options; const query = useEnvironmentQuery( enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null, ); @@ -154,7 +151,6 @@ export function usePullRequestFilesViewed(options: { isViewed: (path: string) => isFileViewed(path, states, overlay), isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)), setViewed, - viewedCount: countViewedFiles(paths, states, overlay), truncated, error, refresh, From 8eddd16067aabcc1d7f09b05d28814132bd27162 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:34:02 -0700 Subject: [PATCH 315/323] refactor(web): find reveal refs stay cached without "use memo" (#20818) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/ChatMarkdown.tsx | 8 ++++---- apps/web/src/components/chat/MessagesTimeline.tsx | 6 +++--- apps/web/src/components/chat/ProposedPlanCard.tsx | 6 +++--- apps/web/src/components/chat/markdownFindContext.ts | 7 +++---- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index d1b810ed56ff..68ef3e7c138e 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1,4 +1,4 @@ -import { MarkdownFindContext, useFindRevealRef } from "./chat/markdownFindContext"; +import { MarkdownFindContext, findRevealRef } from "./chat/markdownFindContext"; import { buildFileLinkParentSuffixByPath, fileLinkLabel, @@ -668,7 +668,7 @@ function MarkdownDetails({ const revealForFind = () => setIsOpen(true); // Base UI only listens for `beforematch` on a panel mounted at its first // render; a closed panel mounts later, when find starts, so listen here. - const findRevealRef = useFindRevealRef(revealForFind); + const revealRef = findRevealRef(revealForFind); const childNodes = Children.toArray(children); const summaryIndex = childNodes.findIndex( (child) => isValidElement(child) && child.type === "summary", @@ -698,7 +698,7 @@ function MarkdownDetails({ /> {summary} - +
setShowCode(true); - const sourceRevealRef = useFindRevealRef(revealSource); + const sourceRevealRef = findRevealRef(revealSource); const showDiagram = !showCode && !isStreaming && code.trim().length > 0; const toggleLabel = showCode ? "Show diagram" : "Show code"; return ( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 8f16ffd2f6b4..7e3e8ece56b8 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,7 +1,7 @@ import { ThreadFindTimelineContext } from "./ThreadFindProvider"; import { shallow } from "zustand/vanilla/shallow"; import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; -import { MarkdownFindContext, useFindRevealRef } from "./markdownFindContext"; +import { MarkdownFindContext, findRevealRef } from "./markdownFindContext"; import { useChatCanvas } from "./ChatCanvasContext"; import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog"; import { PullRequestGlyph } from "../pullRequest/pullRequestIcons"; @@ -4509,7 +4509,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop }) { const [expanded, setExpanded] = useState(false); const revealForFind = () => setExpanded(true); - const findRevealRef = useFindRevealRef(revealForFind); + const revealRef = findRevealRef(revealForFind); const hasVisibleBody = props.text.trim().length > 0; const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text); const isCollapsed = canCollapse && !expanded; @@ -4519,7 +4519,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
{hasVisibleBody ? (
setExpanded(true)); + const revealRef = findRevealRef(() => setExpanded(true)); const downloadFilename = buildProposedPlanMarkdownFilename(planMarkdown); const saveContents = normalizePlanMarkdownForExport(planMarkdown); @@ -191,7 +191,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
); } From f9baf517e0df8557b77f7782b193152967ea029c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:51:22 -0700 Subject: [PATCH 318/323] refactor(web): chat composer keeps its caching without "use memo" (#20834) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 149 ++++++++++-------- apps/web/src/composerDraftStore.ts | 27 +--- 2 files changed, 87 insertions(+), 89 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9cc804cccd0a..ddca044b0468 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -124,7 +124,8 @@ import { hydrateImagesFromPersisted, useComposerDraftStore, useComposerThreadDraft, - useEffectiveComposerModelState, + deriveEffectiveComposerModelState, + useComposerDraftModelState, } from "../../composerDraftStore"; import { MAX_STASH_ENTRIES, @@ -1764,24 +1765,37 @@ function useProviderWorkspaceSnapshotRefresh(input: { ); } +const NO_PROVIDER_MODELS: ServerProvider["models"] = []; + /** - * The provider instances the composer offers and which one is selected. - * A hook so its results reach the composer frozen: they are passed to plain - * functions across later hook calls, which would otherwise keep the compiler - * from caching them. + * The provider instances the composer offers, which one is selected, and the model and options + * the draft resolves to on it. The draft store is read first so every derivation follows the only + * hook here; in the composer body they would straddle its later hooks and lose their cache. */ -function useComposerProviderSelection( +function useComposerProviderModel( input: Omit[0], "entries"> & { readonly providerStatuses: ReadonlyArray; readonly settings: UnifiedSettings; readonly activeProjectId: ProjectId | null; + readonly threadRef: ScopedThreadRef | DraftId; + readonly threadModelSelection: ModelSelection | null | undefined; + readonly projectModelSelection: ModelSelection | null | undefined; + readonly promptInjectionState: ReturnType; }, ) { - // Kept: `providerInstanceEntries` is read by plain functions on both sides of - // `useEffectiveComposerModelState` and `useProviderWorkspaceSnapshotRefresh` (the - // `hasProviderSetup` lookup before, the model picker's `.find` after), so inline it loses its cache. - "use memo"; - const { providerStatuses, settings, activeProjectId, ...selection } = input; + const { + providerStatuses, + settings, + activeProjectId, + threadRef, + threadModelSelection, + projectModelSelection, + promptInjectionState, + candidateInstanceIds, + lockedProvider, + lockedInstanceId, + } = input; + const draftModelState = useComposerDraftModelState(threadRef); const providerInstanceEntries: ReadonlyArray = sortProviderInstanceEntries( applyProviderInstanceSettings( deriveProviderInstanceEntries(providerStatuses), @@ -1789,23 +1803,60 @@ function useComposerProviderSelection( activeProjectId, ), ); + const selection = resolveComposerProviderSelection({ + entries: providerInstanceEntries, + candidateInstanceIds, + lockedProvider, + lockedInstanceId, + }); + const selectedInstanceId = + selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId; + const selectedProvider: ProviderDriverKind = + selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind; + const modelState = deriveEffectiveComposerModelState({ + draft: draftModelState, + providers: providerStatuses, + selectedProvider, + selectedInstanceId, + threadModelSelection, + projectModelSelection, + settings, + }); + const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS; + const composerProviderState = getComposerProviderState({ + provider: selectedProvider, + model: modelState.selectedModel, + models: selectedProviderModels, + promptInjectionState, + modelOptions: modelState.modelOptions?.[selectedInstanceId], + planModeEnabled: settings.planModeEnabled, + }); return { providerInstanceEntries, - ...resolveComposerProviderSelection({ ...selection, entries: providerInstanceEntries }), + ...selection, + selectedInstanceId, + selectedProvider, + selectedProviderModels, + composerModelOptions: modelState.modelOptions, + selectedModel: modelState.selectedModel, + composerProviderState, }; } -/** Splits the draft's images into pending SnapShots and standalone images. */ +/** + * Follows the SnapShots still animating into this draft and splits the draft's images into + * pending SnapShots and standalone images. + */ function useComposerImageGroups( - pendingSnapShotAnimations: ReturnType, composerDraftTarget: ScopedThreadRef | DraftId, composerImages: ReadonlyArray, composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>, ) { - // Kept: these arrays go through plain functions here and again ~2,700 lines later - // (`.some`, `.filter`, `.slice` in the resting layout), past dozens of hook calls. Inline, the - // compiler gives them no cache scope, and moving every later use above those hooks is not possible. - "use memo"; + const pendingSnapShotAnimations = useSyncExternalStore( + subscribeToPendingSnapShotAnimations, + getPendingSnapShotAnimations, + getPendingSnapShotAnimations, + ); const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget( pendingSnapShotAnimations, composerDraftTarget, @@ -1814,6 +1865,7 @@ function useComposerImageGroups( composerPreviewAnnotations.map((annotation) => annotation.id), ); return { + pendingSnapShotAnimations, pendingSnapShotIds, pendingSnapShotIdSet: new Set(pendingSnapShotIds), uncommittedSnapShotIds: pendingSnapShotIds.filter( @@ -1826,14 +1878,6 @@ function useComposerImageGroups( const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; -function useComposerProviderState(input: Parameters[0]) { - // Kept: inline, `composerProviderState`, `selectedModelSelection` and `providerInputInputs` lose - // their cache scope. The inputs come from `useEffectiveComposerModelState`, and the results are - // read past later hooks such as `useProviderWorkspaceSnapshotRefresh`. - "use memo"; - return getComposerProviderState(input); -} - export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { const { composerDraftTarget, @@ -2015,22 +2059,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerPreviewAnnotations = composerDraft.previewAnnotations; const composerReviewComments = composerDraft.reviewComments; const composerThreadContexts = attachmentDraft.threadContexts; - const pendingSnapShotAnimations = useSyncExternalStore( - subscribeToPendingSnapShotAnimations, - getPendingSnapShotAnimations, - getPendingSnapShotAnimations, - ); const { + pendingSnapShotAnimations, pendingSnapShotIds, pendingSnapShotIdSet, uncommittedSnapShotIds, standaloneComposerImages, - } = useComposerImageGroups( - pendingSnapShotAnimations, - composerDraftTarget, - composerImages, - composerPreviewAnnotations, - ); + } = useComposerImageGroups(composerDraftTarget, composerImages, composerPreviewAnnotations); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); const openPrLink = useOpenPrLink(routeThreadRef); @@ -2224,13 +2259,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { providerInstanceEntries, selectedProviderEntry, - requestedDriverKind, lockedContinuationGroupKey, unavailableProviderInstanceId, - } = useComposerProviderSelection({ + selectedInstanceId, + selectedProvider, + selectedProviderModels, + composerModelOptions, + selectedModel, + composerProviderState, + } = useComposerProviderModel({ providerStatuses, settings, activeProjectId, + threadRef: composerDraftTarget, + threadModelSelection: activeThreadModelSelection, + projectModelSelection: activeProjectDefaultModelSelection, + promptInjectionState: getComposerPromptInjectionState(prompt), candidateInstanceIds: [ composerDraft.activeProvider ?? null, activeThread?.runtime?.providerInstanceId, @@ -2241,8 +2285,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) lockedInstanceId: activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId, }); - const selectedInstanceId = - selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId; const noProviderAvailable = selectedProviderEntry === undefined && multipleModelSelections === null; const providerCatalogPending = noProviderAvailable && !providerCatalogKnown; @@ -2255,8 +2297,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : undefined; const resolvedCompactDisabledReason = compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null); - const selectedProvider: ProviderDriverKind = - selectedProviderEntry?.driverKind ?? requestedDriverKind; const supportedRuntimeModes = selectedProviderEntry?.snapshot.supportedRuntimeModes; const compatibleRuntimeModeOptions = supportedRuntimeModes && supportedRuntimeModes.length > 0 @@ -2268,15 +2308,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? runtimeMode : (compatibleRuntimeModeOptions[0]?.mode ?? runtimeMode); - const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ - threadRef: composerDraftTarget, - providers: providerStatuses, - selectedProvider, - selectedInstanceId, - threadModelSelection: activeThreadModelSelection, - projectModelSelection: activeProjectDefaultModelSelection, - settings, - }); const providerSendBlockReason = getAntigravitySendBlockReason( selectedProviderEntry?.snapshot, selectedModel, @@ -2301,19 +2332,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId, gitCwd, selectedProviderEntry, - selectedProviderStatus, - }); - const selectedProviderModels: ReadonlyArray = - selectedProviderEntry?.models ?? []; - - const composerPromptInjectionState = getComposerPromptInjectionState(prompt); - const composerProviderState = useComposerProviderState({ - provider: selectedProvider, - model: selectedModel, - models: selectedProviderModels, - promptInjectionState: composerPromptInjectionState, - modelOptions: composerModelOptions?.[selectedInstanceId], - planModeEnabled: settings.planModeEnabled, + selectedProviderStatus: selectedProviderStatus, }); const selectedPromptEffort = composerProviderState.promptEffort; diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 5ae941213898..76b86ae4cd46 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4242,7 +4242,9 @@ export function useThreadHasUnsentDraft(threadRef: ScopedThreadRef): boolean { ); } -function useComposerDraftModelState(threadRef: ComposerThreadTarget): ComposerDraftModelState { +export function useComposerDraftModelState( + threadRef: ComposerThreadTarget, +): ComposerDraftModelState { return useComposerDraftStore( useShallow((state) => { const draft = getComposerDraftState(state, threadRef); @@ -4256,29 +4258,6 @@ function useComposerDraftModelState(threadRef: ComposerThreadTarget): ComposerDr ); } -export function useEffectiveComposerModelState(input: { - threadRef?: ComposerThreadTarget; - draftId?: DraftId; - providers: ReadonlyArray; - selectedProvider: ProviderDriverKind; - selectedInstanceId?: ProviderInstanceId | null | undefined; - threadModelSelection: ModelSelection | null | undefined; - projectModelSelection: ModelSelection | null | undefined; - settings: UnifiedSettings; -}): EffectiveComposerModelState { - const draft = useComposerDraftModelState(input.threadRef ?? input.draftId ?? DraftId.make("")); - - return deriveEffectiveComposerModelState({ - draft, - providers: input.providers, - selectedProvider: input.selectedProvider, - selectedInstanceId: input.selectedInstanceId, - threadModelSelection: input.threadModelSelection, - projectModelSelection: input.projectModelSelection, - settings: input.settings, - }); -} - export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { const draftStore = useComposerDraftStore.getState(); for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { From 8c67f77af6b4ca8a34a48f0ea87c684f99e8fa83 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:51:55 -0700 Subject: [PATCH 319/323] refactor(web): the usage page keeps its caching without "use memo" (#20807) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/usage/UsagePage.tsx | 1008 ++++++++++--------- 1 file changed, 512 insertions(+), 496 deletions(-) diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index 672d454f363f..34c3c489a6cd 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -7,6 +7,7 @@ import { USAGE_CONTRACT_VERSION, type EnvironmentId, type UsageProviderKind, + type UsageSummaryInput, } from "@t3tools/contracts"; import { CircleAlertIcon, ChevronDownIcon, InfoIcon, SlidersHorizontalIcon } from "lucide-react"; import { useEffect, useEffectEvent, useRef, useState } from "react"; @@ -114,12 +115,6 @@ function isUsageWindowDays(value: number): value is UsagePagePreferences["window const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label; -// useUsage keys its queries on this set, so it must keep its identity. -function useHiddenProviderSet(hiddenProviders: UsagePagePreferences["hiddenProviders"]) { - "use memo"; - return new Set(hiddenProviders); -} - function usageLoading( showingKept: boolean, selectedEnvironments: Parameters[0], @@ -138,37 +133,6 @@ function usageLoading( }; } -// UsageProviderChart memoizes on the provider collections, so they must keep their identity. -function useUsageProviders( - showingKept: boolean, - selectedEnvironments: Parameters[0], - refreshingUsage: boolean, - hiddenProviders: ReadonlySet, - mergedProviders: MergedUsage["providers"], -) { - "use memo"; - const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders); - const providersWithData = providersWithUsage(mergedProviders); - const activeProviders = PROVIDER_ORDER.filter( - (provider) => providersWithData.includes(provider) || loading.providers.has(provider), - ); - const chartLoadingProviders = new Set( - activeProviders.filter((provider) => loading.everyProvider || loading.providers.has(provider)), - ); - return { loading, providersWithData, activeProviders, chartLoadingProviders }; -} - -// UsageProviderChart memoizes on these arrays, so they must keep their identity. -function useUsagePeriods(usageWindow: ReturnType) { - "use memo"; - const days = enumerateDays(usageWindow.sinceDay, usageWindow.untilDay); - const hours = - usageWindow.sinceTime === undefined || usageWindow.untilTime === undefined - ? [] - : enumerateHourStarts(usageWindow.sinceTime, usageWindow.untilTime); - return { days, hours }; -} - export function UsagePage() { const [preferences, setPreferences] = useState(readUsagePagePreferences); useEscapeToGoBack(); @@ -194,12 +158,11 @@ export function UsagePage() { const [isRefreshing, setIsRefreshing] = useState(false); const [limitsNow, setLimitsNow] = useState(() => Date.now()); const refreshingRef = useRef(false); - const [breakdown, setBreakdown] = useState<"model" | "time">("model"); const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null); const [selectedModelKey, setSelectedModelKey] = useState(null); const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState | null>(null); - const hiddenProviders = useHiddenProviderSet(preferences.hiddenProviders); + const hiddenProviders = new Set(preferences.hiddenProviders); const { days: windowDays, window } = windowSelection; const isPast24Hours = windowDays === 1; const { @@ -215,36 +178,10 @@ export function UsagePage() { const shownHourly = shownWindow.resolution === "hour"; const refreshingUsage = isRefreshing && !showingLimits; const showingKept = shown !== null && shown.window !== window; - const { loading, providersWithData, activeProviders, chartLoadingProviders } = useUsageProviders( - showingKept, - selectedEnvironments, - refreshingUsage, - hiddenProviders, - merged.providers, - ); - const isProviderLoading = (provider: UsageProviderKind) => - loading.everyProvider || loading.providers.has(provider); const presentations = useAtomValue(environmentPresentations.presentationsAtom); const cursorAccessEnvironments = hiddenProviders.has("cursor") ? [] : cursorKeychainAccessEnvironments(selectedEnvironments); - const sourceMessages = [ - ...new Set( - selectedEnvironments.flatMap( - (environment) => - environment.summary?.sources.flatMap((source) => - source.message && - !source.action && - !hiddenProviders.has(source.fingerprint.provider) && - (source.status === "partial" || - source.status === "failed" || - source.fingerprint.provider === "cursor") - ? [source.message] - : [], - ) ?? [], - ), - ), - ]; const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { reportFailure: false, }); @@ -253,35 +190,6 @@ export function UsagePage() { (environment) => environment.canReadDiagnostics, ); - const { days, hours } = useUsagePeriods(shownWindow); - const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = ( - shownHourly ? merged.hourly : merged.daily - ).toReversed(); - const breakdownModels = - breakdown === "model" && metric === "tokens" - ? sortModelsByTokens(merged.models) - : merged.models; - const selectedModel = - selectedModelKey === null - ? undefined - : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey); - const breakdownPeak = breakdownModels.reduce( - (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd), - 0, - ); - const summaryRows: Array< - | { readonly kind: "usage"; readonly provider: UsageProviderKind } - | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus } - > = activeProviders.map((provider) => ({ kind: "usage", provider })); - const cursorInsertAt = - Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1; - summaryRows.splice( - cursorInsertAt, - 0, - ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })), - ); - const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`; - const updatePreferences = (patch: Partial) => { const nextPreferences = { ...preferences, ...patch }; setPreferences(nextPreferences); @@ -390,6 +298,24 @@ export function UsagePage() { if (showingLimits && connectedLimitsEnvironments) autoRefreshLimits(); }, [showingLimits, connectedLimitsEnvironments]); + const days = enumerateDays(shownWindow.sinceDay, shownWindow.untilDay); + const hours = + shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined + ? [] + : enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime); + const selectedModel = + selectedModelKey === null + ? undefined + : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey); + + const showChatGptSharing = + !hiddenProviders.has("codex") && + [...presentations].some( + ([id, presentation]) => + (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) && + presentation.serverConfig?.providers.some(usesChatGptSharing), + ); + const windowLabel = shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined ? `${formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone)} to ${formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone)}` @@ -579,408 +505,24 @@ export function UsagePage() { ))}
) : ( -
- {sourceMessages.map((message) => ( -

- {message} -

- ))} -
-
-
- - {metric === "cost" - ? formatUsd(merged.costUsd) - : formatTokens(merged.totalTokens)} - - - - - {formatCount(merged.sessions)} sessions - - {metric === "cost" && " · API estimate"} - - {metric === "cost" && merged.costQuality.unpricedShare > 0 && ( - - } - aria-label="Unpriced usage details" - > - - - - API estimate excludes{" "} - {formatPercent(merged.costQuality.unpricedShare)} unpriced records. - - - )} - -
- - {!hiddenProviders.has("codex") && - [...presentations].some( - ([id, presentation]) => - (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) && - presentation.serverConfig?.providers.some(usesChatGptSharing), - ) ? ( -
- ChatGPT shared usage - -
- ) : null} - - {summaryRows.map((row) => { - if (row.kind === "enable") { - return ( - 1} - onEnabled={() => { - void refresh(); - void refreshLimits(false, true); - }} - /> - ); - } - const provider = row.provider; - const totals = merged.providers.find((entry) => entry.provider === provider); - const share = - metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0); - const providerSessions = totals?.sessions ?? 0; - const sessionLabel = `${formatCount(providerSessions)} ${ - providerSessions === 1 ? "session" : "sessions" - }`; - const providerLoading = isProviderLoading(provider); - const awaitingData = providerLoading && !providersWithData.includes(provider); - return ( -
-
- - - - - - {PROVIDER_PRESENTATION[provider].label} - - - {sessionLabel} - - - - - {awaitingData - ? "—" - : metric === "cost" - ? formatUsd(totals?.costUsd ?? 0) - : formatTokens(totals?.totalTokens ?? 0)} - -
- - {metric === "cost" - ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens` - : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`} - -
- ); - })} -
- -
-

- {shownHourly ? "Hourly" : "Daily"}{" "} - {metric === "tokens" ? "processed tokens" : "cost"} -

- -
-
- -
-

Totals

-
- - - - - -
-
- - {merged.totalTokens > 0 ? ( -
- {metric === "tokens" ? ( - - ) : ( - <> - - {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? ( - } - /> - ) : null} - - )} -
- ) : null} - -
-
-

Breakdown

- { - const value = next[0]; - if (value === "model" || value === "time") setBreakdown(value); - }} - > - {( - [ - { value: "model", label: "Model" }, - { value: "time", label: shownHourly ? "Hour" : "Day" }, - ] as const - ).map((option) => ( - - {option.label} - - ))} - -
- - {breakdown === "model" ? ( - - - - - - - - - - - - {breakdownModels.length === 0 ? ( - - - - ) : ( - breakdownModels.map((model, index) => { - const key = `${model.provider}:${model.model}`; - const value = metric === "tokens" ? model.totalTokens : model.costUsd; - const share = modelShare( - model, - metric === "tokens" ? "tokens" : "cost", - ); - const rowFigures = figureClass(isProviderLoading(model.provider)); - return ( - - - - - - - - ); - }) - )} - -
#ModelCostShareTokens
- No activity in this window. -
{index + 1} - -
-
0 && breakdownPeak > 0 - ? `max(0.5rem, ${(value / breakdownPeak) * 100}%)` - : 0, - backgroundColor: - PROVIDER_PRESENTATION[model.provider].color, - }} - /> -
-
- {isModelCostUnknown(model) ? ( - Unpriced - ) : ( - formatUsd(model.costUsd) - )} - - {share === null ? "" : formatPercent(share)} - - {formatTokens(model.totalTokens)} -
- ) : ( - - - - {activeProviders.map((provider) => ( - - ))} - - - - - - - {activeProviders.map((provider) => ( - - ))} - - - - - - {breakdownPeriods.length === 0 ? ( - - - - ) : ( - breakdownPeriods.map((period) => ( - - - {activeProviders.map((provider) => ( - - ))} - - - - )) - )} - -
{shownHourly ? "Hour" : "Day"} - {PROVIDER_PRESENTATION[provider].label} - TotalTokens
- No activity in this window. -
- {"hourStart" in period - ? formatHourShort(period.hourStart, shownWindow.timeZone) - : formatDayShort(period.day)} - - {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)} - - {formatUsd(period.costUsd)} - - {formatTokens(period.totalTokens)} -
- )} -
-
+ { + void refresh(); + void refreshLimits(false, true); + }} + onSelectModel={setSelectedModelKey} + /> )} @@ -1018,6 +560,480 @@ export function UsagePage() { ); } +function UsageOverview({ + merged, + shownWindow, + days, + hours, + showingKept, + metric, + selectedEnvironments, + hiddenProviders, + refreshingUsage, + cursorAccessEnvironments, + showChatGptSharing, + onCursorEnabled, + onSelectModel, +}: { + readonly merged: MergedUsage; + readonly shownWindow: UsageSummaryInput; + readonly days: readonly string[]; + readonly hours: readonly string[]; + readonly showingKept: boolean; + readonly metric: "tokens" | "cost"; + readonly selectedEnvironments: readonly EnvironmentUsageStatus[]; + readonly hiddenProviders: ReadonlySet; + readonly refreshingUsage: boolean; + readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[]; + readonly showChatGptSharing: boolean; + readonly onCursorEnabled: () => void; + readonly onSelectModel: (key: string) => void; +}) { + const [breakdown, setBreakdown] = useState<"model" | "time">("model"); + const shownHourly = shownWindow.resolution === "hour"; + const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders); + // A primitive copy: reading `loading.partial` in the JSX would keep `loading` alive + // across every derivation below and fold them into one cache scope. + const loadingPartial = loading.partial === true; + const loadingProviders = new Set( + PROVIDER_ORDER.filter((provider) => loading.everyProvider || loading.providers.has(provider)), + ); + const providersWithData = new Set(providersWithUsage(merged.providers)); + // `everyProvider` marks shown providers as loading; only `loading.providers`, which excludes + // hidden ones, may add a provider that has no data yet. + // Filtering a fresh copy, not the shared module array, lets the compiler cache this on its own. + const activeProviders = [...PROVIDER_ORDER].filter( + (provider) => providersWithData.has(provider) || loading.providers.has(provider), + ); + const chartLoadingProviders = new Set( + activeProviders.filter((provider) => loadingProviders.has(provider)), + ); + const sourceMessages = [ + ...new Set( + selectedEnvironments.flatMap( + (environment) => + environment.summary?.sources.flatMap((source) => + source.message && + !source.action && + !hiddenProviders.has(source.fingerprint.provider) && + (source.status === "partial" || + source.status === "failed" || + source.fingerprint.provider === "cursor") + ? [source.message] + : [], + ) ?? [], + ), + ), + ]; + const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = ( + shownHourly ? merged.hourly : merged.daily + ).toReversed(); + const breakdownModels = + breakdown === "model" && metric === "tokens" + ? sortModelsByTokens(merged.models) + : merged.models; + const breakdownPeak = breakdownModels.reduce( + (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd), + 0, + ); + const cursorInsertAt = + Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1; + const summaryRows: ReadonlyArray< + | { readonly kind: "usage"; readonly provider: UsageProviderKind } + | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus } + > = [ + ...activeProviders + .slice(0, cursorInsertAt) + .map((provider) => ({ kind: "usage" as const, provider })), + ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })), + ...activeProviders + .slice(cursorInsertAt) + .map((provider) => ({ kind: "usage" as const, provider })), + ]; + const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`; + + return ( +
+ {sourceMessages.map((message) => ( +

+ {message} +

+ ))} +
+
+
+ + {metric === "cost" ? formatUsd(merged.costUsd) : formatTokens(merged.totalTokens)} + + + + + {formatCount(merged.sessions)} sessions + + {metric === "cost" && " · API estimate"} + + {metric === "cost" && merged.costQuality.unpricedShare > 0 && ( + + } + aria-label="Unpriced usage details" + > + + + + API estimate excludes {formatPercent(merged.costQuality.unpricedShare)} unpriced + records. + + + )} + +
+ + {showChatGptSharing ? ( +
+ ChatGPT shared usage + +
+ ) : null} + + {summaryRows.map((row) => { + if (row.kind === "enable") { + return ( + 1} + onEnabled={onCursorEnabled} + /> + ); + } + const provider = row.provider; + const totals = merged.providers.find((entry) => entry.provider === provider); + const share = metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0); + const providerSessions = totals?.sessions ?? 0; + const sessionLabel = `${formatCount(providerSessions)} ${ + providerSessions === 1 ? "session" : "sessions" + }`; + const providerLoading = loadingProviders.has(provider); + const awaitingData = providerLoading && !providersWithData.has(provider); + return ( +
+
+ + + + + {PROVIDER_PRESENTATION[provider].label} + + {sessionLabel} + + + + + {awaitingData + ? "—" + : metric === "cost" + ? formatUsd(totals?.costUsd ?? 0) + : formatTokens(totals?.totalTokens ?? 0)} + +
+ + {metric === "cost" + ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens` + : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`} + +
+ ); + })} +
+ +
+

+ {shownHourly ? "Hourly" : "Daily"} {metric === "tokens" ? "processed tokens" : "cost"} +

+ +
+
+ +
+

Totals

+
+ + + + + +
+
+ + {merged.totalTokens > 0 ? ( +
+ {metric === "tokens" ? ( + + ) : ( + <> + + {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? ( + } + /> + ) : null} + + )} +
+ ) : null} + +
+
+

Breakdown

+ { + const value = next[0]; + if (value === "model" || value === "time") setBreakdown(value); + }} + > + {( + [ + { value: "model", label: "Model" }, + { value: "time", label: shownHourly ? "Hour" : "Day" }, + ] as const + ).map((option) => ( + + {option.label} + + ))} + +
+ + {breakdown === "model" ? ( + + + + + + + + + + + + {breakdownModels.length === 0 ? ( + + + + ) : ( + breakdownModels.map((model, index) => { + const key = `${model.provider}:${model.model}`; + const value = metric === "tokens" ? model.totalTokens : model.costUsd; + const share = modelShare(model, metric === "tokens" ? "tokens" : "cost"); + const rowFigures = figureClass(loadingProviders.has(model.provider)); + return ( + + + + + + + + ); + }) + )} + +
#ModelCostShareTokens
+ No activity in this window. +
{index + 1} + +
+
0 && breakdownPeak > 0 + ? `max(0.5rem, ${(value / breakdownPeak) * 100}%)` + : 0, + backgroundColor: PROVIDER_PRESENTATION[model.provider].color, + }} + /> +
+
+ {isModelCostUnknown(model) ? ( + Unpriced + ) : ( + formatUsd(model.costUsd) + )} + + {share === null ? "" : formatPercent(share)} + + {formatTokens(model.totalTokens)} +
+ ) : ( + + + + {activeProviders.map((provider) => ( + + ))} + + + + + + + {activeProviders.map((provider) => ( + + ))} + + + + + + {breakdownPeriods.length === 0 ? ( + + + + ) : ( + breakdownPeriods.map((period) => ( + + + {activeProviders.map((provider) => ( + + ))} + + + + )) + )} + +
{shownHourly ? "Hour" : "Day"} + {PROVIDER_PRESENTATION[provider].label} + TotalTokens
+ No activity in this window. +
+ {"hourStart" in period + ? formatHourShort(period.hourStart, shownWindow.timeZone) + : formatDayShort(period.day)} + + {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)} + + {formatUsd(period.costUsd)} + + {formatTokens(period.totalTokens)} +
+ )} +
+
+ ); +} + const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain."; function CursorEnableButton({ From f03378f70ac37f56276210e193769c970a759047 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:52:29 -0700 Subject: [PATCH 320/323] refactor(web): the hosted browser webview keeps its caching without "use memo" (#20824) Co-authored-by: Claude Opus 5.5 --- apps/web/src/browser/HostedBrowserWebview.tsx | 47 ++++++++----------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index e0a39fbd5306..616ed7969f11 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -13,12 +13,7 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; import { cn, isMacPlatform } from "~/lib/utils"; -import { - type BrowserSurfaceContentPresentation, - type BrowserSurfaceRect, - resolveBrowserSurfacePanelRect, - useBrowserSurfaceStore, -} from "./browserSurfaceStore"; +import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore"; import { useActiveBrowserRecordingTabIds } from "./browserRecording"; import { browserViewportSettingKey, @@ -224,8 +219,23 @@ export function HostedBrowserWebview(props: { const handleAspectRatioChange = (aspectRatio: number | null) => { setAspectRatioLocked(aspectRatio !== null); }; - const hiddenSize = useHiddenSize(viewport, normalizedZoomFactor, presentation.content, lastRect); - const containerSize = active && lastRect ? lastRect : hiddenSize; + const content = presentation.content; + const hiddenWidth = + viewport._tag !== "fill" + ? viewport.width * normalizedZoomFactor + : content + ? content.width / content.scale + : (lastRect?.width ?? 1280); + const hiddenHeight = + viewport._tag !== "fill" + ? viewport.height * normalizedZoomFactor + : content + ? content.height / content.scale + : (lastRect?.height ?? 800); + // Built from primitives on each side of the resize hook, so neither object is + // shared across it and both stay cached; the hook's layout keys the sync effect. + const containerSize = + active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight }; const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent; const { activeDrag, @@ -297,7 +307,7 @@ export function HostedBrowserWebview(props: { cornerRadius: presentation.cornerRadius, zIndex: presentation.zIndex, rect: lastRect, - hiddenSize, + hiddenSize: { width: hiddenWidth, height: hiddenHeight }, }); return ( @@ -313,7 +323,7 @@ export function HostedBrowserWebview(props: { {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? ( ); } - -// The size feeds useBrowserViewportResize, whose layout keys the content sync effect. -function useHiddenSize( - viewport: PreviewViewportSetting, - zoomFactor: number, - content: BrowserSurfaceContentPresentation | null, - lastRect: BrowserSurfaceRect | null, -) { - "use memo"; - if (viewport._tag !== "fill") { - return { width: viewport.width * zoomFactor, height: viewport.height * zoomFactor }; - } - return { - width: content ? content.width / content.scale : (lastRect?.width ?? 1280), - height: content ? content.height / content.scale : (lastRect?.height ?? 800), - }; -} From e6ced718a3bb35c58986b12fb9f84624974104c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 00:53:02 -0700 Subject: [PATCH 321/323] refactor(web): the command palette provider lookup keeps its caching without "use memo" (#20827) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/CommandPalette.tsx | 46 ++++++++-------------- 1 file changed, 17 insertions(+), 29 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index acfd522347d4..123e436a3b70 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -366,8 +366,9 @@ function notifyThemeSaveFailure(): void { ); } -// These run in their own hooks so the results stay cached across the palette's -// later hook calls; the thread and project items key on them. +// Kept as "use memo" hooks: inlined, each result reaches the dialog's returned +// through the action and thread item arrays built after +// the browse hooks, and the compiler leaves all of them uncached. function useThemeCards( customThemes: ReturnType, environmentThemes: ReturnType, @@ -386,29 +387,6 @@ function useThemeCards( ]; } -function useProviderEntryMap( - environments: ReturnType["environments"], - primaryEnvironmentId: ReturnType, - providers: Parameters[0], -) { - "use memo"; - const map = new Map(); - for (const environment of environments) { - const serverConfig = environment.serverConfig; - const environmentProviders = - serverConfig?.providers ?? - (environment.environmentId === primaryEnvironmentId ? providers : []); - const derived = deriveProviderInstanceEntries(environmentProviders); - const entries = serverConfig - ? applyProviderInstanceSettings(derived, serverConfig.settings, null) - : derived; - for (const entry of entries) { - map.set(`${environment.environmentId}:${entry.instanceId}`, entry); - } - } - return map; -} - function useThreadContentMatchByKey(matches: ReturnType["matches"]) { "use memo"; return new Map( @@ -828,10 +806,20 @@ function OpenCommandPaletteDialog(props: { const environmentThemes = useEnvironmentThemeDefinitions(); const themeCards = useThemeCards(customThemes, environmentThemes); const providers = useAtomValue(primaryServerProvidersAtom); - const providerEntryByEnvironmentAndInstanceId = useProviderEntryMap( - environments, - primaryEnvironmentId, - providers, + const providerEntryByEnvironmentAndInstanceId = new Map( + environments.flatMap((environment) => { + const serverConfig = environment.serverConfig; + const derived = deriveProviderInstanceEntries( + serverConfig?.providers ?? + (environment.environmentId === primaryEnvironmentId ? providers : []), + ); + const entries = serverConfig + ? applyProviderInstanceSettings(derived, serverConfig.settings, null) + : derived; + return entries.map( + (entry) => [`${environment.environmentId}:${entry.instanceId}`, entry] as const, + ); + }), ); const [viewStack, setViewStack] = useState([]); const currentView = viewStack.at(-1) ?? null; From 2fbd4318fc5b610c3e7fcfcbd5bbd80b73521d8f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 17 Oct 2026 01:03:12 -0700 Subject: [PATCH 322/323] chore(web): lint rejects "use memo" directives (#20843) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/CommandPalette.tsx | 12 +++++++++--- docs/internals/web-ui.md | 5 ++++- oxlint-plugin-t3code/rules/no-manual-memo.test.ts | 7 +++++++ oxlint-plugin-t3code/rules/no-manual-memo.ts | 12 +++++++++++- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 123e436a3b70..1564207a2d74 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -366,13 +366,15 @@ function notifyThemeSaveFailure(): void { ); } -// Kept as "use memo" hooks: inlined, each result reaches the dialog's returned -// through the action and thread item arrays built after -// the browse hooks, and the compiler leaves all of them uncached. +// These helpers keep "use memo" until the palette's item building moves out of this +// component: inlined, each result reaches the returned through +// the action and thread item arrays built after the browse hooks, and the compiler +// leaves all of them uncached. function useThemeCards( customThemes: ReturnType, environmentThemes: ReturnType, ) { + // oxlint-disable-next-line t3code/no-manual-memo -- Kept until the palette's item building moves out of this component (see above). "use memo"; const seen = new Set(); return [ @@ -388,6 +390,7 @@ function useThemeCards( } function useThreadContentMatchByKey(matches: ReturnType["matches"]) { + // oxlint-disable-next-line t3code/no-manual-memo -- Kept until the palette's item building moves out of this component (see above). "use memo"; return new Map( matches.flatMap((match) => @@ -399,6 +402,7 @@ function useThreadContentMatchByKey(matches: ReturnType[ } function useEnvironmentLookups(environments: ReturnType["environments"]) { + // oxlint-disable-next-line t3code/no-manual-memo -- Kept until the palette's item building moves out of this component (see above). "use memo"; const environmentLabelById = new Map( environments.map((environment) => [environment.environmentId, environment.label] as const), @@ -421,6 +425,7 @@ function useEnvironmentLookups(environments: ReturnType[ } function useProjectLookups(projects: ReturnType) { + // oxlint-disable-next-line t3code/no-manual-memo -- Kept until the palette's item building moves out of this component (see above). "use memo"; const projectCwdById = new Map( projects.map((project) => [project.id, project.workspaceRoot]), @@ -449,6 +454,7 @@ function useSortedProjectGroups({ readonly environmentLabelById: ReadonlyMap; readonly threads: ReturnType; }) { + // oxlint-disable-next-line t3code/no-manual-memo -- Kept until the palette's item building moves out of this component (see above). "use memo"; const projectGroupingSettings = selectProjectGroupingSettings(clientSettings); const orderedProjects = orderItemsByPreferredIds({ diff --git a/docs/internals/web-ui.md b/docs/internals/web-ui.md index 7e00521c2fa1..c1975a4f98e3 100644 --- a/docs/internals/web-ui.md +++ b/docs/internals/web-ui.md @@ -63,7 +63,10 @@ makes it skip the whole function without a build error. Lint reports each skip a Every file under `apps/web/src` must compile. Lint makes those rules errors there, and `t3code/no-manual-memo` rejects `useMemo` and `useCallback`, which the compiler makes redundant; -no upstream rule bans them outright. Lint misses some bailouts, notably `try` with `finally` and +no upstream rule bans them outright. It also rejects `"use memo"`. The compiler withholds a cache +scope when a value reaches plain function calls on both sides of a hook call. A `"use memo"` +helper forces one, but hides the ordering problem. Fix the order instead: plain uses of a value go +before the hook, or the helper is inlined. Lint misses some bailouts, notably `try` with `finally` and `throw` inside `try`, so [`reactCompilerCoverage.test.ts`](../../apps/web/src/reactCompilerCoverage.test.ts) compiles every file and fails on any skip. Async handlers rarely need `try`: an atom command settles into a result, so cleanup can follow the `await`. `useStableCallback` still diff --git a/oxlint-plugin-t3code/rules/no-manual-memo.test.ts b/oxlint-plugin-t3code/rules/no-manual-memo.test.ts index 8044d698998f..cd6d26dba1b1 100644 --- a/oxlint-plugin-t3code/rules/no-manual-memo.test.ts +++ b/oxlint-plugin-t3code/rules/no-manual-memo.test.ts @@ -13,6 +13,13 @@ describe("t3code/no-manual-memo", () => { rule.valid("allows other React members", `const ref = React.useRef(null);`); + rule.valid("allows other directives", `function Panel() { "use client"; return null; }`); + + rule.invalid( + 'reports a "use memo" directive', + `function useTotal(items) { "use memo"; return items.length; }`, + ); + rule.invalid("reports useMemo", `const total = useMemo(() => items.length, [items]);`); rule.invalid("reports useCallback", `const onClick = useCallback(() => save(), []);`); diff --git a/oxlint-plugin-t3code/rules/no-manual-memo.ts b/oxlint-plugin-t3code/rules/no-manual-memo.ts index 73cdf0fc8a48..fd8e61b653c6 100644 --- a/oxlint-plugin-t3code/rules/no-manual-memo.ts +++ b/oxlint-plugin-t3code/rules/no-manual-memo.ts @@ -24,11 +24,21 @@ export default defineRule({ type: "suggestion", docs: { description: - "Disallow useCallback and useMemo in files the React Compiler must compile; it memoizes them.", + 'Disallow useCallback, useMemo and "use memo" directives in files the React Compiler must compile; it memoizes them.', }, }, create(context) { return { + // A "use memo" helper only exists to force a cache scope the compiler withheld, + // which hides the ordering or structure problem that withheld it. + ExpressionStatement(node) { + if (node.directive !== "use memo") return; + context.report({ + node, + message: + 'Drop "use memo": restructure so the compiler caches this on its own, e.g. move plain uses of a value before the hook call that splits its scope, or inline the helper.', + }); + }, CallExpression(node) { const name = manualMemoHookName(node.callee); if (name === null) return; From ce51c55b6cf2f72b3d47a1a23697d049c66bad3c Mon Sep 17 00:00:00 2001 From: Henry Chu Date: Sat, 17 Oct 2026 13:58:09 -0400 Subject: [PATCH 323/323] Document stage 2 seams and the browser test project Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +++++++--- docs/internals/coder-only.md | 17 ++++++++++++----- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 342ed8b5a1d5..376fdd7dfa84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,9 +106,13 @@ pnpm --filter @t3tools/source-control-core --filter @t3tools/source-control-gitl pnpm build ``` -Backend boundary changes need focused tests; `apps/coder-gateway/src/boundaryGuard.test.ts` checks -the gateway's URLs, connections, and spawn targets. Do not launch browsers or use computer-control -tooling without explicit user permission. Do not test against or modify `~/.t3/userdata`. +`pnpm test:coder` includes upstream's web `browser` Vitest project, which runs headless Chromium +through Playwright on the development machine; install it once with +`pnpm --filter @t3tools/web exec playwright install chromium`. Backend boundary changes need +focused tests; `apps/coder-gateway/src/boundaryGuard.test.ts` checks the gateway's URLs, +connections, and spawn targets. Apart from that test project, do not launch browsers or use +computer-control tooling without explicit user permission. Do not test against or modify +`~/.t3/userdata`. ## Working practices diff --git a/docs/internals/coder-only.md b/docs/internals/coder-only.md index a66d14ed9532..ce423e12cdd9 100644 --- a/docs/internals/coder-only.md +++ b/docs/internals/coder-only.md @@ -474,7 +474,10 @@ listed here is drift to remove rather than fork behavior to keep. folder itself is ignored, #20062) has nothing to save and is not carried. `projects.createFile` serves upstream's proposed-plan "Save to workspace": it creates a new text file inside the verified root and never replaces an existing path, where upstream's - `writeFile` overwrites. `ProjectImages.ts` and `ScreenshotArtifacts.ts` are Coder-only. Path-only FFF errors and stale-write errors retain the fork's bounded-service + `writeFile` overwrites. Both write paths keep upstream's write-target hardening: the cwd must + be a `KnownWorkspaces` folder, the root resolves after `path.resolve`, and a target in a git + folder (`.git`, a bare repository, a linked worktree's git folder, as named or resolved) is + refused, with new files checked before any folder is made. `ProjectImages.ts` and `ScreenshotArtifacts.ts` are Coder-only. Path-only FFF errors and stale-write errors retain the fork's bounded-service error mapping. `coderWs.ts` wraps `ws.ts`'s upstream Files list, read, and write handlers in the root verification, so those handlers stay upstream's code. - Coder-only methods live in `coderWs.ts` (`CODER_WS_METHODS`): local ref status, managed @@ -959,8 +962,8 @@ listed here is drift to remove rather than fork behavior to keep. cfafb4bb54): merge requests between projects post to the source project with a numeric `target_project_id` instead of sending the repository text as `source_project_id`; merge - request URLs reach `glab` as ` --repo ` because older versions read URLs as branch - names; `mr checkout` honours `branch` and `force`. + request URLs reach `glab` as `--repo ... -- ` because older versions read URLs as + branch names (options stay before upstream's `--`); `mr checkout` honours `branch` and `force`. - GitLab implements upstream's `readChangeRequestTemplate` hook with `gitLabChangeRequestTemplate.ts`, upstream's GitHub template reader plus `.gitlab/merge_request_templates`, preferring `Default.md`. @@ -1126,7 +1129,8 @@ listed here is drift to remove rather than fork behavior to keep. macOS, where the temp directory is behind the `/var` symlink. `serverSettings.test.ts` omits upstream's source control host secret tests, and drops the host tokens from its shared secret-lifecycle test, because no carried host definition declares - settings. `ClaudeAdapterV2.test.ts` drives upstream's MCP control-channel + settings; it also omits the credential-migration test, which reads the uncarried Antigravity + and OpenCode settings schemas. `ClaudeAdapterV2.test.ts` drives upstream's MCP control-channel tests through a fake `claude` executable, since the CLI transport has no SDK spawn hook, and `ClaudeAgentSdkQueryRunner.test.ts` stubs the CLI transport's `query` shim rather than the Agent SDK's. `ProviderSessionManager.test.ts`'s parallel shutdown test waits briefly in real time @@ -1146,7 +1150,10 @@ listed here is drift to remove rather than fork behavior to keep. client-runtime's `threadShell.test.ts` omits upstream's switched-off environment test, because the Coder config owns registration and there is no per-environment switch. `pullRequestsRouteSearch.test.ts` runs under happy-dom, because the route module loads the diff - worker, which needs a browser `self`. + worker, which needs a browser `self`. Upstream's `*.browser.test.*` files run in headless + Chromium through Playwright as upstream's `browser` Vitest project, on the development machine + only; `reactCompilerCoverage.test.ts` skips four fork-only files the compiler bails on + (`CODER_UNCOMPILED_FILES`). - **Omitted surfaces.** Desktop, mobile, hosted web, browser preview, telemetry, OTLP and trace export, the diagnostics page, usage dashboards, and hosted providers other than GitLab. Without browser preview, `composerDraftStore.ts` does not keep an empty draft alive for an open page,