Skip to content
TypeScript

perf(web): stop re-rendering the conversation on streamed tokens, typing and server pushes (#20380)

Julius Marminge0912b24577ad
diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsx
index 5b8e54af568..7fd7d7616d6 100644
--- a/apps/web/src/components/ChatMarkdown.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.test.tsx
@@ -528,7 +528,7 @@ describe("ChatMarkdown streaming", () => {
currentTarget: {
checked: true,
closest: () => ({
- dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
+ dataset: { listItemOffset: String(listItem.props["data-list-item-offset"]) },
}),
},
} as unknown as Parameters<typeof onChange>[0]);
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index fcf193a4559..94a3f0e0fa5 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -49,7 +49,9 @@ import { Check, Copy, Maximize2, Minimize2 } from "lucide";
import {
AuthPreviewOperateScope,
type AssetResource,
+ type EditorId,
type EnvironmentId,
+ type ServerConfig,
type ScopedThreadRef,
type ServerProviderSkill,
type ThreadPullRequestKey,
@@ -2230,6 +2232,22 @@ function areMarkdownFileLinkPropsEqual(
);
}
+const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
+
+/** The server config fields markdown reads. */
+function markdownServerConfigFields(config: ServerConfig | null) {
+ return {
+ pullRequestsEnabled: config?.environment.capabilities.pullRequests === true,
+ availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS,
+ revealInFileManagerLabel:
+ config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager")
+ ? config.shellRevealInFileManagerKind === undefined
+ ? revealInFileExplorerLabelForOs(config.environment.platform.os)
+ : revealInFileExplorerLabelForKind(config.shellRevealInFileManagerKind)
+ : undefined,
+ };
+}
+
function useChatMarkdownState({
text,
cwd,
@@ -2319,23 +2337,27 @@ function useChatMarkdownState({
},
[createAssetUrl, cwd, expandMedia, preparedConnection, threadRef],
);
+ // Only the parts of the server config markdown reads. The config object itself
+ // changes with every provider status push, which would re-render every
+ // visible reply.
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
+ const nextConfigFields = markdownServerConfigFields(serverConfig);
+ const [configFields, setConfigFields] = useState(nextConfigFields);
+ if (
+ configFields.pullRequestsEnabled !== nextConfigFields.pullRequestsEnabled ||
+ configFields.availableEditors !== nextConfigFields.availableEditors ||
+ configFields.revealInFileManagerLabel !== nextConfigFields.revealInFileManagerLabel
+ ) {
+ setConfigFields(nextConfigFields);
+ }
+ const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = configFields;
const projects = useProjects();
- const availableEditors = serverConfig?.availableEditors ?? [];
const [preferredEditor] = usePreferredEditor(availableEditors);
const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor);
const openInPreferredEditor = useOpenInPreferredEditor(environmentId, availableEditors);
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
- const revealInFileManagerLabel =
- environmentId !== null &&
- serverConfig?.shellRevealInFileManager === true &&
- serverConfig.availableEditors.includes("file-manager")
- ? serverConfig.shellRevealInFileManagerKind === undefined
- ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os)
- : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind)
- : undefined;
const revealFileInFileManager = useCallback(
(filePath: string) => {
if (environmentId === null) {
@@ -2665,9 +2687,8 @@ function useChatMarkdownState({
linkedThreadPullRequestFor,
resolveThreadPullRequest,
resolvedTheme,
- serverConfig,
+ pullRequestsEnabled,
skills,
- text,
threadRef,
updateThreadPullRequestLink,
}),
@@ -2698,9 +2719,8 @@ function useChatMarkdownState({
linkedThreadPullRequestFor,
resolveThreadPullRequest,
resolvedTheme,
- serverConfig,
+ pullRequestsEnabled,
skills,
- text,
threadRef,
updateThreadPullRequestLink,
],
@@ -2719,6 +2739,10 @@ const ChatMarkdownRendererContext = React.createContext<
ReturnType<typeof useChatMarkdownState>["componentState"]
>(null!);
+// The markdown source changes on every streamed delta. Only the renderers that
+// slice it by node offset read it, so it sits apart from the renderer context.
+const ChatMarkdownTextContext = React.createContext("");
+
function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) {
const Tag = `h${level}` as const;
return function MarkdownHeading({
@@ -2786,18 +2810,20 @@ const CHAT_MARKDOWN_COMPONENTS = {
);
},
li: function MarkdownListItem({ node, children, ...props }) {
- const { text, skills } = use(ChatMarkdownRendererContext);
- const listItemStart = node?.position?.start.offset;
- const markerOffset =
- typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null;
+ const { skills } = use(ChatMarkdownRendererContext);
+ // The checkbox finds its marker from this offset when toggled, so list items
+ // don't read the source text and re-render on every streamed token.
+ // remark-gfm marks task items with this class; plain items carry no offset.
+ const isTaskItem = String(props.className ?? "").includes("task-list-item");
return (
- <li {...props} data-task-marker-offset={markerOffset ?? undefined}>
+ <li {...props} data-list-item-offset={isTaskItem ? node?.position?.start.offset : undefined}>
{renderSkillInlineMarkdownChildren(children, skills)}
</li>
);
},
input: function MarkdownInput({ node: _node, type, checked, disabled: _disabled, ...props }) {
const { onTaskListChange } = use(ChatMarkdownRendererContext);
+ const text = use(ChatMarkdownTextContext);
if (type !== "checkbox" || !onTaskListChange) {
return (
<input
@@ -2817,8 +2843,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
aria-label="Toggle task"
checked={checked}
onChange={(event) => {
- const markerOffset = Number(event.currentTarget.closest("li")?.dataset.taskMarkerOffset);
- if (!Number.isSafeInteger(markerOffset)) return;
+ const listItemStart = Number(event.currentTarget.closest("li")?.dataset.listItemOffset);
+ if (!Number.isSafeInteger(listItemStart)) return;
+ const markerOffset = findTaskListMarkerOffset(text, listItemStart);
+ if (markerOffset === null) return;
onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
}}
/>
@@ -2841,12 +2869,12 @@ const CHAT_MARKDOWN_COMPONENTS = {
projects,
linkedThreadPullRequestFor,
resolveThreadPullRequest,
- serverConfig,
+ pullRequestsEnabled,
updateThreadPullRequestLink,
fileLinkChip,
renderContextReference,
- text,
} = use(ChatMarkdownRendererContext);
+ const text = use(ChatMarkdownTextContext);
const citation = href ? parseAssistantCitationHref(href) : null;
if (citation) return <AssistantCitationChip citation={citation} />;
const linkedThreadId = href ? parseThreadLinkHref(href) : null;
@@ -2892,7 +2920,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
? resolvePullRequestPreviewTarget({
environmentId,
projects,
- pullRequestsEnabled: serverConfig?.environment.capabilities.pullRequests === true,
+ pullRequestsEnabled,
url: pullRequestCandidateUrl,
})
: null;
@@ -3249,9 +3277,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
},
pre: function MarkdownPre({ node, children, ...props }) {
- const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand, text } = use(
+ const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use(
ChatMarkdownRendererContext,
);
+ const text = use(ChatMarkdownTextContext);
const codeBlock = extractCodeBlock(children);
if (!codeBlock) {
return <pre {...props}>{children}</pre>;
@@ -3352,19 +3381,21 @@ function ChatMarkdown({
onCopy={handleCopy}
>
<ChatMarkdownRendererContext value={componentState}>
- <ReactMarkdown
- remarkPlugins={remarkPlugins}
- rehypePlugins={
- parseRawHtml
- ? CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS
- : CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS
- }
- skipHtml={false}
- components={CHAT_MARKDOWN_COMPONENTS}
- urlTransform={markdownUrlTransform}
- >
- {text}
- </ReactMarkdown>
+ <ChatMarkdownTextContext value={text}>
+ <ReactMarkdown
+ remarkPlugins={remarkPlugins}
+ rehypePlugins={
+ parseRawHtml
+ ? CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS
+ : CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS
+ }
+ skipHtml={false}
+ components={CHAT_MARKDOWN_COMPONENTS}
+ urlTransform={markdownUrlTransform}
+ >
+ {text}
+ </ReactMarkdown>
+ </ChatMarkdownTextContext>
</ChatMarkdownRendererContext>
{localMediaPreview ? (
<ExpandedImageDialog
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 2cd504501c6..4b2592b9258 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -1324,12 +1324,13 @@ export default function ChatView(props: ChatViewProps) {
);
const timestampFormat = settings.timestampFormat;
const navigate = useNavigate();
- const citationLocation = useLocation({
- select: (location) => ({
- href: location.href,
- key: location.state.assistantCitationActivation ?? location.state.__TSR_key,
- }),
+ // Selects primitives: an object here is new on every router store update, which
+ // re-renders ChatView on unrelated navigation state changes.
+ const citationHref = useLocation({ select: (location) => location.href });
+ const citationKey = useLocation({
+ select: (location) => location.state.assistantCitationActivation ?? location.state.__TSR_key,
});
+ const citationLocation = { href: citationHref, key: citationKey };
const citationRequest = useMemo<AssistantCitationRequest | null>(() => {
const citation = assistantCitationFromLocation(citationLocation.href);
return citation && citation.environmentId === environmentId && citation.threadId === threadId
@@ -6054,9 +6055,46 @@ export default function ChatView(props: ChatViewProps) {
isDesktop: isElectron,
});
const getShortcutContextStable = useStableCallback(getShortcutContext);
- const timelineSkills = activeProviderStatus
+ // Every provider status push carries a new skills array, even when nothing in
+ // it changed. Timeline markdown only reads names, so it keeps one identity
+ // until those change; otherwise each push re-renders every visible reply.
+ const nextTimelineSkills = activeProviderStatus
? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)
: EMPTY_PROVIDER_SKILLS;
+ const timelineSkillsKey = nextTimelineSkills
+ .map((skill) => `${skill.name}\u0000${skill.displayName ?? ""}`)
+ .join("\u0001");
+ const [timelineSkillsState, setTimelineSkillsState] = useState({
+ key: timelineSkillsKey,
+ skills: nextTimelineSkills,
+ });
+ if (timelineSkillsState.key !== timelineSkillsKey) {
+ setTimelineSkillsState({ key: timelineSkillsKey, skills: nextTimelineSkills });
+ }
+ const timelineSkills = timelineSkillsState.skills;
+ // Same for providers: timeline rows show their names, icons and models, and
+ // nothing else in a status push should re-render the conversation.
+ const nextTimelineProviders =
+ environmentById.get(
+ displayedThreadRef?.environmentId ?? activeThread?.environmentId ?? environmentId,
+ )?.serverConfig?.providers ?? EMPTY_PROVIDERS;
+ const timelineProvidersKey = JSON.stringify(
+ nextTimelineProviders.map((provider) => [
+ provider.instanceId,
+ provider.driver,
+ provider.displayName,
+ provider.iconUrl,
+ provider.models.map((model) => [model.slug, model.name, model.shortName]),
+ ]),
+ );
+ const [timelineProvidersState, setTimelineProvidersState] = useState({
+ key: timelineProvidersKey,
+ providers: nextTimelineProviders,
+ });
+ if (timelineProvidersState.key !== timelineProvidersKey) {
+ setTimelineProvidersState({ key: timelineProvidersKey, providers: nextTimelineProviders });
+ }
+ const timelineProviders = timelineProvidersState.providers;
const threadFindControlsRef = useRef<ThreadFindControls | null>(null);
const [isThreadFindActive, setIsThreadFindActive] = useState(false);
const openThreadFind = () => threadFindControlsRef.current?.open();
@@ -8201,20 +8239,31 @@ export default function ChatView(props: ChatViewProps) {
};
const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread);
+ // Keyed on the fields it reads: the thread and runtime objects change with
+ // every streamed event, and a new function re-renders the whole model picker.
+ const hasStartedSession = activeRuntime !== null;
+ const runtimeProviderInstanceId = activeRuntime?.providerInstanceId ?? null;
+ const currentModelSelection = activeThread?.modelSelection ?? null;
const getModelDisabledReason = useMemo(
() =>
makeModelDisabledReason(
- activeThread
+ currentModelSelection
? {
providers: providerStatuses,
- hasStartedSession: activeRuntime !== null,
+ hasStartedSession,
supportsProviderSwitchingViaHandoff,
- currentModelSelection: activeThread.modelSelection,
- currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null,
+ currentModelSelection,
+ currentProviderInstanceId: runtimeProviderInstanceId,
}
: null,
),
- [activeRuntime, activeThread, providerStatuses, supportsProviderSwitchingViaHandoff],
+ [
+ currentModelSelection,
+ hasStartedSession,
+ providerStatuses,
+ runtimeProviderInstanceId,
+ supportsProviderSwitchingViaHandoff,
+ ],
);
const onProviderModelSelect = (
@@ -8946,11 +8995,7 @@ export default function ChatView(props: ChatViewProps) {
}
listRef={legendListRef}
timelineEntries={displayedTimeline.entries}
- providerStatuses={
- environmentById.get(
- displayedThreadRef?.environmentId ?? activeThread.environmentId,
- )?.serverConfig?.providers ?? EMPTY_PROVIDERS
- }
+ providerStatuses={timelineProviders}
runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])}
latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun}
runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index f59084188ac..27550680a9f 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -625,6 +625,12 @@ type SortableThreadRowBag = Pick<
"listeners" | "setNodeRef" | "transform" | "transition" | "isDragging"
>;
+const NO_DRAGGED_ORDER: readonly string[] = [];
+// useSortable memoizes on its `disabled` object, so a fresh one per render
+// re-renders every row and marker on each sidebar update.
+const SIDEBAR_SORTABLE_DRAG_DISABLED = { draggable: true } as const;
+const SIDEBAR_SORTABLE_DRAG_ENABLED = { draggable: false } as const;
+
function SortableThreadRow(props: {
id: string;
disabled: boolean;
@@ -635,7 +641,10 @@ function SortableThreadRow(props: {
const canOperateThread = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope);
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: props.id,
- disabled: { draggable: props.disabled || !canOperateThread },
+ disabled:
+ props.disabled || !canOperateThread
+ ? SIDEBAR_SORTABLE_DRAG_DISABLED
+ : SIDEBAR_SORTABLE_DRAG_ENABLED,
animateLayoutChanges: animateSidebarLayoutChanges,
});
// dnd-kit memoizes each field but not the bag, so the memoized row would
@@ -664,7 +673,7 @@ function SortableSidebarMarker(props: {
}) {
const { setNodeRef, transform, transition } = useSortable({
id: sidebarMarkerId(props.marker),
- disabled: { draggable: true },
+ disabled: SIDEBAR_SORTABLE_DRAG_DISABLED,
animateLayoutChanges: animateSidebarLayoutChanges,
});
return (
@@ -3191,6 +3200,11 @@ export default function Sidebar() {
(args) => restrictBelowSidebarLabel(args, dragLabelOffsetRef.current),
[],
);
+ // A new array re-renders DndContext and with it every sortable row.
+ const dndModifiers = useMemo(
+ () => [restrictToVerticalAxis, restrictBelowPins, restrictToFirstScrollableAncestor],
+ [restrictBelowPins],
+ );
const listMotionRef = useRef<ReturnType<typeof createSidebarListMotion> | null>(null);
const attachListMotionRef = useCallback((node: HTMLUListElement | null) => {
threadListRef.current = node;
@@ -3268,15 +3282,19 @@ export default function Sidebar() {
},
[contextDragThreads, pointerOutsideThreadList],
);
- const dndSensors = useSensors(
- useSensor(SidebarPointerSensor, {
+ // useSensor memoizes on the options object; a fresh one each render rebuilds
+ // the sensors, and with them DndContext and every sortable row.
+ const pointerSensorOptions = useMemo(
+ () => ({
distance: SIDEBAR_DRAG_DISTANCE,
onAttach: attachDragSensor,
onFinish: finishThreadDrag,
onMove: moveThreadContextDrag,
onDrop: dropThreadContextDrag,
}),
+ [attachDragSensor, dropThreadContextDrag, finishThreadDrag, moveThreadContextDrag],
);
+ const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
const sectionByThreadKey = useMemo(() => {
const map = new Map<string, SidebarSection>();
const add = (list: readonly EnvironmentThreadShell[], section: SidebarSection) => {
@@ -3507,7 +3525,7 @@ export default function Sidebar() {
},
[sectionByThreadKey],
);
- const sidebarListItems = useMemo((): readonly SidebarListItem[] => {
+ const sidebarListItemsFresh = useMemo((): readonly SidebarListItem[] => {
const rowsOf = (
list: readonly EnvironmentThreadShell[],
section: SidebarSection,
@@ -3556,6 +3574,18 @@ export default function Sidebar() {
visibleWorkingThreads,
workingThreads.length,
]);
+ // Thread shells update on every streamed event without moving rows. Keep the
+ // list's identity until its order changes, so the sorting strategy, the
+ // sortable context and every sortable row stay memoized meanwhile.
+ const sidebarListItemsKey = sidebarListItemsFresh
+ .map((item) => (item.kind === "thread" ? item.section + ":" + item.key : item.marker))
+ .join("\n");
+ const [sidebarListItems, setSidebarListItems] = useState(sidebarListItemsFresh);
+ const [sidebarListItemsKeyState, setSidebarListItemsKeyState] = useState(sidebarListItemsKey);
+ if (sidebarListItemsKeyState !== sidebarListItemsKey) {
+ setSidebarListItemsKeyState(sidebarListItemsKey);
+ setSidebarListItems(sidebarListItemsFresh);
+ }
useEffect(() => {
if (
dragState !== null &&
@@ -3603,7 +3633,9 @@ export default function Sidebar() {
const sortableIds = useMemo(() => sidebarListItems.map(sidebarListItemId), [sidebarListItems]);
const draggedSettledOrder = useMemo(() => {
const thread = dragState === null ? undefined : threadByKey.get(dragState.activeKey);
- if (dragState === null || thread === undefined) return [];
+ // Outside a drag this must keep one identity: the sorting strategy, and with
+ // it every sortable row, rebuilds when it changes.
+ if (dragState === null || thread === undefined) return NO_DRAGGED_ORDER;
const key = (candidate: EnvironmentThreadShell) =>
scopedThreadKey(scopeThreadRef(candidate.environmentId, candidate.id));
return sortSettledThreads([
@@ -4848,11 +4880,7 @@ export default function Sidebar() {
sensors={dndSensors}
autoScroll={!isContextDrag}
collisionDetection={dndCollisionDetection}
- modifiers={[
- restrictToVerticalAxis,
- restrictBelowPins,
- restrictToFirstScrollableAncestor,
- ]}
+ modifiers={dndModifiers}
onDragStart={handleThreadDragStart}
onDragOver={handleThreadDragOver}
onDragEnd={handleThreadDragEnd}
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 41648e526e3..d46eabae8f2 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -5711,6 +5711,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
event.preventDefault();
event.stopPropagation();
};
+ // The editor is memoized; fresh closures here re-render it on every parent
+ // render, which during a stream is every delta.
+ const onComposerPasteStable = useStableCallback(onComposerPaste);
+ const onComposerCommandKeyStable = useStableCallback(onComposerCommandKey);
+ const isPathQueryActiveStable = useStableCallback(
+ () => resolveActiveComposerTrigger().trigger?.kind === "path",
+ );
const insertComposerText = (
text: string,
@@ -7106,9 +7113,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
editorRef={composerEditorRef}
richTextEnabled={settings.composerRichTextEnabled}
literalText={isLiteralPendingAnswer}
- isPathQueryActive={() =>
- resolveActiveComposerTrigger().trigger?.kind === "path"
- }
+ isPathQueryActive={isPathQueryActiveStable}
value={
isComposerApprovalState
? ""
@@ -7134,13 +7139,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
onChange={onPromptChangeStable}
onVisibleSelectionChange={expandComposerForEditorChangeStable}
- onCommandKeyDown={onComposerCommandKey}
+ onCommandKeyDown={onComposerCommandKeyStable}
onPageScrollKeyDown={onPageScrollKeyDown}
onPageScrollKeyUp={onPageScrollKeyUp}
onPageScrollRelease={onPageScrollRelease}
onCitationSubmitAndSend={submitCitationAndSendStable}
onCitationDraftSave={saveCitationDraftToPromptStable}
- onPaste={onComposerPaste}
+ onPaste={onComposerPasteStable}
placeholder={
isComposerApprovalState
? "Resolve this approval request to continue"
diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.ts
index 52406fbca0f..f1aa3c08141 100644
--- a/apps/web/src/components/chat/usePendingThreadRequests.ts
+++ b/apps/web/src/components/chat/usePendingThreadRequests.ts
@@ -48,6 +48,9 @@ import { useOrchestrationCommand } from "../../state/use-orchestration-command";
import type { ChatComposerHandle } from "./ChatComposer";
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
+const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
+const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
+const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
/** Writes the custom answer for a question of the pending user input the making render saw. */
function makePendingCustomAnswerSetter(input: {
@@ -133,11 +136,17 @@ export function usePendingThreadRequests(input: {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const pendingRequests =
- serverProjection === null
- ? { approvals: [], userInputs: [] }
- : derivePendingThreadRequests(serverProjection);
- const pendingApprovals = derivePendingApprovals(pendingRequests.approvals);
- const pendingUserInputs = derivePendingUserInputs(pendingRequests.userInputs);
+ serverProjection === null ? NO_PENDING_REQUESTS : derivePendingThreadRequests(serverProjection);
+ // The projection changes on every streamed event, so shared empties keep the
+ // composer and approval panel from re-rendering while nothing is pending.
+ const pendingApprovals =
+ pendingRequests.approvals.length === 0
+ ? NO_PENDING_APPROVALS
+ : derivePendingApprovals(pendingRequests.approvals);
+ const pendingUserInputs =
+ pendingRequests.userInputs.length === 0
+ ? NO_PENDING_USER_INPUTS
+ : derivePendingUserInputs(pendingRequests.userInputs);
const activePendingUserInput = pendingUserInputs[0] ?? null;
const activePendingRequestKey = JSON.stringify([
environmentId,
diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.ts
index 0e1ba6fefab..2c8df512808 100644
--- a/apps/web/src/remoteOpen.ts
+++ b/apps/web/src/remoteOpen.ts
@@ -82,24 +82,28 @@ export function resolveRemoteOpenState(input: {
export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
const { presentation } = useEnvironmentPresentation(environmentId);
+ // The presentation changes with every server config push. Memoize on the
+ // pieces read here so callers keep a stable result across provider updates.
+ const entry = presentation?.entry ?? null;
+ const remoteOpenTargets = presentation?.serverConfig?.remoteOpenTargets;
return useMemo(() => {
- if (presentation === null) {
+ if (entry === null) {
return UNRESOLVED_REMOTE_OPEN;
}
- const profile = Option.getOrNull(presentation.entry.profile);
+ const profile = Option.getOrNull(entry.profile);
const sshAlias =
profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null;
return {
state: resolveRemoteOpenState({
- target: presentation.entry.target,
+ target: entry.target,
sshAlias,
- remoteOpenTargets: presentation.serverConfig?.remoteOpenTargets,
+ remoteOpenTargets,
isDesktopRenderer: window.desktopBridge !== undefined,
}),
isResolved: true,
};
- }, [presentation]);
+ }, [entry, remoteOpenTargets]);
}
export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 7bde1ecfd19..f8826276d76 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -145,17 +145,13 @@ function RootRouteView() {
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
- const returningFromWelcomeRef = useRef(pathname === "/welcome");
+ // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
+ const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
+ if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
const hostedPromptLinkLanding = useHostedPromptLinkLanding(
authGateState.status === "hosted-static",
);
- useEffect(() => {
- if (pathname === "/welcome") {
- returningFromWelcomeRef.current = true;
- }
- }, [pathname]);
-
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
syncBrowserChromeTheme();
@@ -256,7 +252,7 @@ function RootRouteView() {
<PullRequestGuideRunCoordinator />
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? (
- <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
+ <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
) : null}
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
{isElectron ? <DesktopUpdateLaunchNotice /> : null}