The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 08:00 UTC
perf(web): stop re-rendering the conversation on streamed tokens, typing and server pushes (#20380)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:39 UTC
0912b24577ad39b8820000456f91f00b752b1012
8 files changed
+206
-88
apps/web/src/components/ChatMarkdown.test.tsx
+1
-1
@@ -528,7 +528,7 @@ describe("ChatMarkdown streaming", () => {
528
currentTarget: {
529
checked: true,
530
closest: () => ({
531
- dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
531
+ dataset: { listItemOffset: String(listItem.props["data-list-item-offset"]) },
532
}),
533
},
534
} as unknown as Parameters<typeof onChange>[0]);
apps/web/src/components/ChatMarkdown.tsx
+68
-37
@@ -49,7 +49,9 @@ import { Check, Copy, Maximize2, Minimize2 } from "lucide";
49
import {
50
AuthPreviewOperateScope,
51
type AssetResource,
52
+ type EditorId,
53
type EnvironmentId,
54
+ type ServerConfig,
55
type ScopedThreadRef,
56
type ServerProviderSkill,
57
type ThreadPullRequestKey,
@@ -2230,6 +2232,22 @@ function areMarkdownFileLinkPropsEqual(
2232
);
2233
}
2234
2235
+const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
2236
+
2237
+/** The server config fields markdown reads. */
2238
+function markdownServerConfigFields(config: ServerConfig | null) {
2239
+ return {
2240
+ pullRequestsEnabled: config?.environment.capabilities.pullRequests === true,
2241
+ availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS,
2242
+ revealInFileManagerLabel:
2243
+ config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager")
2244
+ ? config.shellRevealInFileManagerKind === undefined
2245
+ ? revealInFileExplorerLabelForOs(config.environment.platform.os)
2246
+ : revealInFileExplorerLabelForKind(config.shellRevealInFileManagerKind)
2247
+ : undefined,
2248
+ };
2249
+}
2250
+
2251
function useChatMarkdownState({
2252
text,
2253
cwd,
@@ -2319,23 +2337,27 @@ function useChatMarkdownState({
2337
},
2338
[createAssetUrl, cwd, expandMedia, preparedConnection, threadRef],
2339
);
2340
+ // Only the parts of the server config markdown reads. The config object itself
2341
+ // changes with every provider status push, which would re-render every
2342
+ // visible reply.
2343
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
2344
+ const nextConfigFields = markdownServerConfigFields(serverConfig);
2345
+ const [configFields, setConfigFields] = useState(nextConfigFields);
2346
+ if (
2347
+ configFields.pullRequestsEnabled !== nextConfigFields.pullRequestsEnabled ||
2348
+ configFields.availableEditors !== nextConfigFields.availableEditors ||
2349
+ configFields.revealInFileManagerLabel !== nextConfigFields.revealInFileManagerLabel
2350
+ ) {
2351
+ setConfigFields(nextConfigFields);
2352
+ }
2353
+ const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = configFields;
2354
const projects = useProjects();
2324
- const availableEditors = serverConfig?.availableEditors ?? [];
2355
const [preferredEditor] = usePreferredEditor(availableEditors);
2356
const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor);
2357
const openInPreferredEditor = useOpenInPreferredEditor(environmentId, availableEditors);
2358
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
2359
reportFailure: false,
2360
});
2331
- const revealInFileManagerLabel =
2332
- environmentId !== null &&
2333
- serverConfig?.shellRevealInFileManager === true &&
2334
- serverConfig.availableEditors.includes("file-manager")
2335
- ? serverConfig.shellRevealInFileManagerKind === undefined
2336
- ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os)
2337
- : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind)
2338
- : undefined;
2361
const revealFileInFileManager = useCallback(
2362
(filePath: string) => {
2363
if (environmentId === null) {
@@ -2665,9 +2687,8 @@ function useChatMarkdownState({
2687
linkedThreadPullRequestFor,
2688
resolveThreadPullRequest,
2689
resolvedTheme,
2668
- serverConfig,
2690
+ pullRequestsEnabled,
2691
skills,
2670
- text,
2692
threadRef,
2693
updateThreadPullRequestLink,
2694
}),
@@ -2698,9 +2719,8 @@ function useChatMarkdownState({
2719
linkedThreadPullRequestFor,
2720
resolveThreadPullRequest,
2721
resolvedTheme,
2701
- serverConfig,
2722
+ pullRequestsEnabled,
2723
skills,
2703
- text,
2724
threadRef,
2725
updateThreadPullRequestLink,
2726
],
@@ -2719,6 +2739,10 @@ const ChatMarkdownRendererContext = React.createContext<
2739
ReturnType<typeof useChatMarkdownState>["componentState"]
2740
>(null!);
2741
2742
+// The markdown source changes on every streamed delta. Only the renderers that
2743
+// slice it by node offset read it, so it sits apart from the renderer context.
2744
+const ChatMarkdownTextContext = React.createContext("");
2745
+
2746
function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) {
2747
const Tag = `h${level}` as const;
2748
return function MarkdownHeading({
@@ -2786,18 +2810,20 @@ const CHAT_MARKDOWN_COMPONENTS = {
2810
);
2811
},
2812
li: function MarkdownListItem({ node, children, ...props }) {
2789
- const { text, skills } = use(ChatMarkdownRendererContext);
2790
- const listItemStart = node?.position?.start.offset;
2791
- const markerOffset =
2792
- typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null;
2813
+ const { skills } = use(ChatMarkdownRendererContext);
2814
+ // The checkbox finds its marker from this offset when toggled, so list items
2815
+ // don't read the source text and re-render on every streamed token.
2816
+ // remark-gfm marks task items with this class; plain items carry no offset.
2817
+ const isTaskItem = String(props.className ?? "").includes("task-list-item");
2818
return (
2794
- <li {...props} data-task-marker-offset={markerOffset ?? undefined}>
2819
+ <li {...props} data-list-item-offset={isTaskItem ? node?.position?.start.offset : undefined}>
2820
{renderSkillInlineMarkdownChildren(children, skills)}
2821
</li>
2822
);
2823
},
2824
input: function MarkdownInput({ node: _node, type, checked, disabled: _disabled, ...props }) {
2825
const { onTaskListChange } = use(ChatMarkdownRendererContext);
2826
+ const text = use(ChatMarkdownTextContext);
2827
if (type !== "checkbox" || !onTaskListChange) {
2828
return (
2829
<input
@@ -2817,8 +2843,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
2843
aria-label="Toggle task"
2844
checked={checked}
2845
onChange={(event) => {
2820
- const markerOffset = Number(event.currentTarget.closest("li")?.dataset.taskMarkerOffset);
2821
- if (!Number.isSafeInteger(markerOffset)) return;
2846
+ const listItemStart = Number(event.currentTarget.closest("li")?.dataset.listItemOffset);
2847
+ if (!Number.isSafeInteger(listItemStart)) return;
2848
+ const markerOffset = findTaskListMarkerOffset(text, listItemStart);
2849
+ if (markerOffset === null) return;
2850
onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
2851
}}
2852
/>
@@ -2841,12 +2869,12 @@ const CHAT_MARKDOWN_COMPONENTS = {
2869
projects,
2870
linkedThreadPullRequestFor,
2871
resolveThreadPullRequest,
2844
- serverConfig,
2872
+ pullRequestsEnabled,
2873
updateThreadPullRequestLink,
2874
fileLinkChip,
2875
renderContextReference,
2848
- text,
2876
} = use(ChatMarkdownRendererContext);
2877
+ const text = use(ChatMarkdownTextContext);
2878
const citation = href ? parseAssistantCitationHref(href) : null;
2879
if (citation) return <AssistantCitationChip citation={citation} />;
2880
const linkedThreadId = href ? parseThreadLinkHref(href) : null;
@@ -2892,7 +2920,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
2920
? resolvePullRequestPreviewTarget({
2921
environmentId,
2922
projects,
2895
- pullRequestsEnabled: serverConfig?.environment.capabilities.pullRequests === true,
2923
+ pullRequestsEnabled,
2924
url: pullRequestCandidateUrl,
2925
})
2926
: null;
@@ -3249,9 +3277,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
3277
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
3278
},
3279
pre: function MarkdownPre({ node, children, ...props }) {
3252
- const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand, text } = use(
3280
+ const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use(
3281
ChatMarkdownRendererContext,
3282
);
3283
+ const text = use(ChatMarkdownTextContext);
3284
const codeBlock = extractCodeBlock(children);
3285
if (!codeBlock) {
3286
return <pre {...props}>{children}</pre>;
@@ -3352,19 +3381,21 @@ function ChatMarkdown({
3381
onCopy={handleCopy}
3382
>
3383
<ChatMarkdownRendererContext value={componentState}>
3355
- <ReactMarkdown
3356
- remarkPlugins={remarkPlugins}
3357
- rehypePlugins={
3358
- parseRawHtml
3359
- ? CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS
3360
- : CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS
3361
- }
3362
- skipHtml={false}
3363
- components={CHAT_MARKDOWN_COMPONENTS}
3364
- urlTransform={markdownUrlTransform}
3365
- >
3366
- {text}
3367
- </ReactMarkdown>
3384
+ <ChatMarkdownTextContext value={text}>
3385
+ <ReactMarkdown
3386
+ remarkPlugins={remarkPlugins}
3387
+ rehypePlugins={
3388
+ parseRawHtml
3389
+ ? CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS
3390
+ : CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS
3391
+ }
3392
+ skipHtml={false}
3393
+ components={CHAT_MARKDOWN_COMPONENTS}
3394
+ urlTransform={markdownUrlTransform}
3395
+ >
3396
+ {text}
3397
+ </ReactMarkdown>
3398
+ </ChatMarkdownTextContext>
3399
</ChatMarkdownRendererContext>
3400
{localMediaPreview ? (
3401
<ExpandedImageDialog
apps/web/src/components/ChatView.tsx
+61
-16
@@ -1324,12 +1324,13 @@ export default function ChatView(props: ChatViewProps) {
1324
);
1325
const timestampFormat = settings.timestampFormat;
1326
const navigate = useNavigate();
1327
- const citationLocation = useLocation({
1328
- select: (location) => ({
1329
- href: location.href,
1330
- key: location.state.assistantCitationActivation ?? location.state.__TSR_key,
1331
- }),
1327
+ // Selects primitives: an object here is new on every router store update, which
1328
+ // re-renders ChatView on unrelated navigation state changes.
1329
+ const citationHref = useLocation({ select: (location) => location.href });
1330
+ const citationKey = useLocation({
1331
+ select: (location) => location.state.assistantCitationActivation ?? location.state.__TSR_key,
1332
});
1333
+ const citationLocation = { href: citationHref, key: citationKey };
1334
const citationRequest = useMemo<AssistantCitationRequest | null>(() => {
1335
const citation = assistantCitationFromLocation(citationLocation.href);
1336
return citation && citation.environmentId === environmentId && citation.threadId === threadId
@@ -6054,9 +6055,46 @@ export default function ChatView(props: ChatViewProps) {
6055
isDesktop: isElectron,
6056
});
6057
const getShortcutContextStable = useStableCallback(getShortcutContext);
6057
- const timelineSkills = activeProviderStatus
6058
+ // Every provider status push carries a new skills array, even when nothing in
6059
+ // it changed. Timeline markdown only reads names, so it keeps one identity
6060
+ // until those change; otherwise each push re-renders every visible reply.
6061
+ const nextTimelineSkills = activeProviderStatus
6062
? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)
6063
: EMPTY_PROVIDER_SKILLS;
6064
+ const timelineSkillsKey = nextTimelineSkills
6065
+ .map((skill) => `${skill.name}\u0000${skill.displayName ?? ""}`)
6066
+ .join("\u0001");
6067
+ const [timelineSkillsState, setTimelineSkillsState] = useState({
6068
+ key: timelineSkillsKey,
6069
+ skills: nextTimelineSkills,
6070
+ });
6071
+ if (timelineSkillsState.key !== timelineSkillsKey) {
6072
+ setTimelineSkillsState({ key: timelineSkillsKey, skills: nextTimelineSkills });
6073
+ }
6074
+ const timelineSkills = timelineSkillsState.skills;
6075
+ // Same for providers: timeline rows show their names, icons and models, and
6076
+ // nothing else in a status push should re-render the conversation.
6077
+ const nextTimelineProviders =
6078
+ environmentById.get(
6079
+ displayedThreadRef?.environmentId ?? activeThread?.environmentId ?? environmentId,
6080
+ )?.serverConfig?.providers ?? EMPTY_PROVIDERS;
6081
+ const timelineProvidersKey = JSON.stringify(
6082
+ nextTimelineProviders.map((provider) => [
6083
+ provider.instanceId,
6084
+ provider.driver,
6085
+ provider.displayName,
6086
+ provider.iconUrl,
6087
+ provider.models.map((model) => [model.slug, model.name, model.shortName]),
6088
+ ]),
6089
+ );
6090
+ const [timelineProvidersState, setTimelineProvidersState] = useState({
6091
+ key: timelineProvidersKey,
6092
+ providers: nextTimelineProviders,
6093
+ });
6094
+ if (timelineProvidersState.key !== timelineProvidersKey) {
6095
+ setTimelineProvidersState({ key: timelineProvidersKey, providers: nextTimelineProviders });
6096
+ }
6097
+ const timelineProviders = timelineProvidersState.providers;
6098
const threadFindControlsRef = useRef<ThreadFindControls | null>(null);
6099
const [isThreadFindActive, setIsThreadFindActive] = useState(false);
6100
const openThreadFind = () => threadFindControlsRef.current?.open();
@@ -8201,20 +8239,31 @@ export default function ChatView(props: ChatViewProps) {
8239
};
8240
const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread);
8241
8242
+ // Keyed on the fields it reads: the thread and runtime objects change with
8243
+ // every streamed event, and a new function re-renders the whole model picker.
8244
+ const hasStartedSession = activeRuntime !== null;
8245
+ const runtimeProviderInstanceId = activeRuntime?.providerInstanceId ?? null;
8246
+ const currentModelSelection = activeThread?.modelSelection ?? null;
8247
const getModelDisabledReason = useMemo(
8248
() =>
8249
makeModelDisabledReason(
8207
- activeThread
8250
+ currentModelSelection
8251
? {
8252
providers: providerStatuses,
8210
- hasStartedSession: activeRuntime !== null,
8253
+ hasStartedSession,
8254
supportsProviderSwitchingViaHandoff,
8212
- currentModelSelection: activeThread.modelSelection,
8213
- currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null,
8255
+ currentModelSelection,
8256
+ currentProviderInstanceId: runtimeProviderInstanceId,
8257
}
8258
: null,
8259
),
8217
- [activeRuntime, activeThread, providerStatuses, supportsProviderSwitchingViaHandoff],
8260
+ [
8261
+ currentModelSelection,
8262
+ hasStartedSession,
8263
+ providerStatuses,
8264
+ runtimeProviderInstanceId,
8265
+ supportsProviderSwitchingViaHandoff,
8266
+ ],
8267
);
8268
8269
const onProviderModelSelect = (
@@ -8946,11 +8995,7 @@ export default function ChatView(props: ChatViewProps) {
8995
}
8996
listRef={legendListRef}
8997
timelineEntries={displayedTimeline.entries}
8949
- providerStatuses={
8950
- environmentById.get(
8951
- displayedThreadRef?.environmentId ?? activeThread.environmentId,
8952
- )?.serverConfig?.providers ?? EMPTY_PROVIDERS
8953
- }
8998
+ providerStatuses={timelineProviders}
8999
runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])}
9000
latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun}
9001
runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId}
apps/web/src/components/Sidebar.tsx
+39
-11
@@ -625,6 +625,12 @@ type SortableThreadRowBag = Pick<
625
"listeners" | "setNodeRef" | "transform" | "transition" | "isDragging"
626
>;
627
628
+const NO_DRAGGED_ORDER: readonly string[] = [];
629
+// useSortable memoizes on its `disabled` object, so a fresh one per render
630
+// re-renders every row and marker on each sidebar update.
631
+const SIDEBAR_SORTABLE_DRAG_DISABLED = { draggable: true } as const;
632
+const SIDEBAR_SORTABLE_DRAG_ENABLED = { draggable: false } as const;
633
+
634
function SortableThreadRow(props: {
635
id: string;
636
disabled: boolean;
@@ -635,7 +641,10 @@ function SortableThreadRow(props: {
641
const canOperateThread = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope);
642
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
643
id: props.id,
638
- disabled: { draggable: props.disabled || !canOperateThread },
644
+ disabled:
645
+ props.disabled || !canOperateThread
646
+ ? SIDEBAR_SORTABLE_DRAG_DISABLED
647
+ : SIDEBAR_SORTABLE_DRAG_ENABLED,
648
animateLayoutChanges: animateSidebarLayoutChanges,
649
});
650
// dnd-kit memoizes each field but not the bag, so the memoized row would
@@ -664,7 +673,7 @@ function SortableSidebarMarker(props: {
673
}) {
674
const { setNodeRef, transform, transition } = useSortable({
675
id: sidebarMarkerId(props.marker),
667
- disabled: { draggable: true },
676
+ disabled: SIDEBAR_SORTABLE_DRAG_DISABLED,
677
animateLayoutChanges: animateSidebarLayoutChanges,
678
});
679
return (
@@ -3191,6 +3200,11 @@ export default function Sidebar() {
3200
(args) => restrictBelowSidebarLabel(args, dragLabelOffsetRef.current),
3201
[],
3202
);
3203
+ // A new array re-renders DndContext and with it every sortable row.
3204
+ const dndModifiers = useMemo(
3205
+ () => [restrictToVerticalAxis, restrictBelowPins, restrictToFirstScrollableAncestor],
3206
+ [restrictBelowPins],
3207
+ );
3208
const listMotionRef = useRef<ReturnType<typeof createSidebarListMotion> | null>(null);
3209
const attachListMotionRef = useCallback((node: HTMLUListElement | null) => {
3210
threadListRef.current = node;
@@ -3268,15 +3282,19 @@ export default function Sidebar() {
3282
},
3283
[contextDragThreads, pointerOutsideThreadList],
3284
);
3271
- const dndSensors = useSensors(
3272
- useSensor(SidebarPointerSensor, {
3285
+ // useSensor memoizes on the options object; a fresh one each render rebuilds
3286
+ // the sensors, and with them DndContext and every sortable row.
3287
+ const pointerSensorOptions = useMemo(
3288
+ () => ({
3289
distance: SIDEBAR_DRAG_DISTANCE,
3290
onAttach: attachDragSensor,
3291
onFinish: finishThreadDrag,
3292
onMove: moveThreadContextDrag,
3293
onDrop: dropThreadContextDrag,
3294
}),
3295
+ [attachDragSensor, dropThreadContextDrag, finishThreadDrag, moveThreadContextDrag],
3296
);
3297
+ const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
3298
const sectionByThreadKey = useMemo(() => {
3299
const map = new Map<string, SidebarSection>();
3300
const add = (list: readonly EnvironmentThreadShell[], section: SidebarSection) => {
@@ -3507,7 +3525,7 @@ export default function Sidebar() {
3525
},
3526
[sectionByThreadKey],
3527
);
3510
- const sidebarListItems = useMemo((): readonly SidebarListItem[] => {
3528
+ const sidebarListItemsFresh = useMemo((): readonly SidebarListItem[] => {
3529
const rowsOf = (
3530
list: readonly EnvironmentThreadShell[],
3531
section: SidebarSection,
@@ -3556,6 +3574,18 @@ export default function Sidebar() {
3574
visibleWorkingThreads,
3575
workingThreads.length,
3576
]);
3577
+ // Thread shells update on every streamed event without moving rows. Keep the
3578
+ // list's identity until its order changes, so the sorting strategy, the
3579
+ // sortable context and every sortable row stay memoized meanwhile.
3580
+ const sidebarListItemsKey = sidebarListItemsFresh
3581
+ .map((item) => (item.kind === "thread" ? item.section + ":" + item.key : item.marker))
3582
+ .join("\n");
3583
+ const [sidebarListItems, setSidebarListItems] = useState(sidebarListItemsFresh);
3584
+ const [sidebarListItemsKeyState, setSidebarListItemsKeyState] = useState(sidebarListItemsKey);
3585
+ if (sidebarListItemsKeyState !== sidebarListItemsKey) {
3586
+ setSidebarListItemsKeyState(sidebarListItemsKey);
3587
+ setSidebarListItems(sidebarListItemsFresh);
3588
+ }
3589
useEffect(() => {
3590
if (
3591
dragState !== null &&
@@ -3603,7 +3633,9 @@ export default function Sidebar() {
3633
const sortableIds = useMemo(() => sidebarListItems.map(sidebarListItemId), [sidebarListItems]);
3634
const draggedSettledOrder = useMemo(() => {
3635
const thread = dragState === null ? undefined : threadByKey.get(dragState.activeKey);
3606
- if (dragState === null || thread === undefined) return [];
3636
+ // Outside a drag this must keep one identity: the sorting strategy, and with
3637
+ // it every sortable row, rebuilds when it changes.
3638
+ if (dragState === null || thread === undefined) return NO_DRAGGED_ORDER;
3639
const key = (candidate: EnvironmentThreadShell) =>
3640
scopedThreadKey(scopeThreadRef(candidate.environmentId, candidate.id));
3641
return sortSettledThreads([
@@ -4848,11 +4880,7 @@ export default function Sidebar() {
4880
sensors={dndSensors}
4881
autoScroll={!isContextDrag}
4882
collisionDetection={dndCollisionDetection}
4851
- modifiers={[
4852
- restrictToVerticalAxis,
4853
- restrictBelowPins,
4854
- restrictToFirstScrollableAncestor,
4855
- ]}
4883
+ modifiers={dndModifiers}
4884
onDragStart={handleThreadDragStart}
4885
onDragOver={handleThreadDragOver}
4886
onDragEnd={handleThreadDragEnd}
apps/web/src/components/chat/ChatComposer.tsx
+10
-5
@@ -5711,6 +5711,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5711
event.preventDefault();
5712
event.stopPropagation();
5713
};
5714
+ // The editor is memoized; fresh closures here re-render it on every parent
5715
+ // render, which during a stream is every delta.
5716
+ const onComposerPasteStable = useStableCallback(onComposerPaste);
5717
+ const onComposerCommandKeyStable = useStableCallback(onComposerCommandKey);
5718
+ const isPathQueryActiveStable = useStableCallback(
5719
+ () => resolveActiveComposerTrigger().trigger?.kind === "path",
5720
+ );
5721
5722
const insertComposerText = (
5723
text: string,
@@ -7106,9 +7113,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7113
editorRef={composerEditorRef}
7114
richTextEnabled={settings.composerRichTextEnabled}
7115
literalText={isLiteralPendingAnswer}
7109
- isPathQueryActive={() =>
7110
- resolveActiveComposerTrigger().trigger?.kind === "path"
7111
- }
7116
+ isPathQueryActive={isPathQueryActiveStable}
7117
value={
7118
isComposerApprovalState
7119
? ""
@@ -7134,13 +7139,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7139
)}
7140
onChange={onPromptChangeStable}
7141
onVisibleSelectionChange={expandComposerForEditorChangeStable}
7137
- onCommandKeyDown={onComposerCommandKey}
7142
+ onCommandKeyDown={onComposerCommandKeyStable}
7143
onPageScrollKeyDown={onPageScrollKeyDown}
7144
onPageScrollKeyUp={onPageScrollKeyUp}
7145
onPageScrollRelease={onPageScrollRelease}
7146
onCitationSubmitAndSend={submitCitationAndSendStable}
7147
onCitationDraftSave={saveCitationDraftToPromptStable}
7143
- onPaste={onComposerPaste}
7148
+ onPaste={onComposerPasteStable}
7149
placeholder={
7150
isComposerApprovalState
7151
? "Resolve this approval request to continue"
apps/web/src/components/chat/usePendingThreadRequests.ts
+14
-5
@@ -48,6 +48,9 @@ import { useOrchestrationCommand } from "../../state/use-orchestration-command";
48
import type { ChatComposerHandle } from "./ChatComposer";
49
50
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
51
+const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
52
+const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
53
+const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
54
55
/** Writes the custom answer for a question of the pending user input the making render saw. */
56
function makePendingCustomAnswerSetter(input: {
@@ -133,11 +136,17 @@ export function usePendingThreadRequests(input: {
136
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
137
useState<Record<string, number>>({});
138
const pendingRequests =
136
- serverProjection === null
137
- ? { approvals: [], userInputs: [] }
138
- : derivePendingThreadRequests(serverProjection);
139
- const pendingApprovals = derivePendingApprovals(pendingRequests.approvals);
140
- const pendingUserInputs = derivePendingUserInputs(pendingRequests.userInputs);
139
+ serverProjection === null ? NO_PENDING_REQUESTS : derivePendingThreadRequests(serverProjection);
140
+ // The projection changes on every streamed event, so shared empties keep the
141
+ // composer and approval panel from re-rendering while nothing is pending.
142
+ const pendingApprovals =
143
+ pendingRequests.approvals.length === 0
144
+ ? NO_PENDING_APPROVALS
145
+ : derivePendingApprovals(pendingRequests.approvals);
146
+ const pendingUserInputs =
147
+ pendingRequests.userInputs.length === 0
148
+ ? NO_PENDING_USER_INPUTS
149
+ : derivePendingUserInputs(pendingRequests.userInputs);
150
const activePendingUserInput = pendingUserInputs[0] ?? null;
151
const activePendingRequestKey = JSON.stringify([
152
environmentId,
apps/web/src/remoteOpen.ts
+9
-5
@@ -82,24 +82,28 @@ export function resolveRemoteOpenState(input: {
82
83
export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
84
const { presentation } = useEnvironmentPresentation(environmentId);
85
+ // The presentation changes with every server config push. Memoize on the
86
+ // pieces read here so callers keep a stable result across provider updates.
87
+ const entry = presentation?.entry ?? null;
88
+ const remoteOpenTargets = presentation?.serverConfig?.remoteOpenTargets;
89
90
return useMemo(() => {
87
- if (presentation === null) {
91
+ if (entry === null) {
92
return UNRESOLVED_REMOTE_OPEN;
93
}
90
- const profile = Option.getOrNull(presentation.entry.profile);
94
+ const profile = Option.getOrNull(entry.profile);
95
const sshAlias =
96
profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null;
97
return {
98
state: resolveRemoteOpenState({
95
- target: presentation.entry.target,
99
+ target: entry.target,
100
sshAlias,
97
- remoteOpenTargets: presentation.serverConfig?.remoteOpenTargets,
101
+ remoteOpenTargets,
102
isDesktopRenderer: window.desktopBridge !== undefined,
103
}),
104
isResolved: true,
105
};
102
- }, [presentation]);
106
+ }, [entry, remoteOpenTargets]);
107
}
108
109
export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
apps/web/src/routes/__root.tsx
+4
-8
@@ -145,17 +145,13 @@ function RootRouteView() {
145
const pathname = useLocation({ select: (location) => location.pathname });
146
const { authGateState } = Route.useRouteContext();
147
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
148
- const returningFromWelcomeRef = useRef(pathname === "/welcome");
148
+ // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
149
+ const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
150
+ if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
151
const hostedPromptLinkLanding = useHostedPromptLinkLanding(
152
authGateState.status === "hosted-static",
153
);
154
153
- useEffect(() => {
154
- if (pathname === "/welcome") {
155
- returningFromWelcomeRef.current = true;
156
- }
157
- }, [pathname]);
158
-
155
useEffect(() => {
156
const frame = window.requestAnimationFrame(() => {
157
syncBrowserChromeTheme();
@@ -256,7 +252,7 @@ function RootRouteView() {
252
<PullRequestGuideRunCoordinator />
253
<HostedStaticEnvironmentBootstrap />
254
{primaryEnvironmentAuthenticated ? (
259
- <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
255
+ <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
256
) : null}
257
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
258
{isElectron ? <DesktopUpdateLaunchNotice /> : null}