Skip to content
TypeScript

fix(web): stop the resting composer layout loop (#9393)

Theo Browne044ea8e347d9
diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts
index e49584bcf3f..0577f5e8dd1 100644
--- a/apps/web/src/components/BranchToolbar.logic.ts
+++ b/apps/web/src/components/BranchToolbar.logic.ts
@@ -68,6 +68,20 @@ export function shouldShowComposerContextStrip(input: {
);
}
+// Labels collapse to icons when the strip's content no longer fits. A small
+// hysteresis on the way back out keeps the boundary from flapping.
+const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
+
+export function resolveContextStripLabelsCompact(input: {
+ compact: boolean;
+ neededWidth: number;
+ availableWidth: number;
+}): boolean {
+ return input.compact
+ ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
+ : input.neededWidth > input.availableWidth;
+}
+
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx
index faf042209de..0496bef06ef 100644
--- a/apps/web/src/components/BranchToolbar.tsx
+++ b/apps/web/src/components/BranchToolbar.tsx
@@ -15,6 +15,7 @@ import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/e
import {
type EnvMode,
type EnvironmentOption,
+ resolveContextStripLabelsCompact,
resolveCurrentWorkspaceLabel,
resolveEnvModeLabel,
resolveEffectiveEnvMode,
@@ -39,6 +40,8 @@ import {
} from "./ui/menu";
import { Separator } from "./ui/separator";
import { ComposerSurface } from "./chat/ComposerSurface";
+import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement";
+import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout";
import { cn } from "~/lib/utils";
interface BranchToolbarProps {
@@ -236,7 +239,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
* the expanded width without remembered values that could go stale or latch
* the strip compact. A small hysteresis keeps the boundary from flapping.
*/
-const COMPACT_EXPAND_HYSTERESIS_PX = 16;
const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
const COMPOSER_CONTEXT_CONTROL_SELECTOR = "[data-composer-context-control]";
@@ -282,12 +284,20 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
let groups = 0;
for (const child of current.children) {
if (!(child instanceof HTMLElement)) continue;
- // The host itself flexes into all remaining room. Measure the controls
- // inside it so Git labels compact before squeezing out the model picker.
+ // The host itself flexes into all remaining room. Reserve the natural
+ // width of the controls inside it, blocks in overflow included, so Git
+ // labels compact before squeezing out the model picker. Reserving only
+ // the visible controls would let the labels expand into room the
+ // composer just freed, shrink the host, and hide the controls again.
const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
: null;
- const width = hostedControls ? contentWidth(hostedControls) : contentWidth(child);
+ const hostedMeasurement = hostedControls
+ ? measureRestingComposerControls(hostedControls)
+ : null;
+ const width = hostedMeasurement
+ ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
+ : contentWidth(hostedControls ?? child);
if (width <= 1) continue;
groups += 1;
needed += width;
@@ -311,9 +321,11 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
needed += Math.max(0, textWidth - label.clientWidth);
}
}
- const nextOverflows = compact
- ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX
- : needed > available;
+ const nextOverflows = resolveContextStripLabelsCompact({
+ compact,
+ neededWidth: needed,
+ availableWidth: available,
+ });
if (nextOverflows !== compact) {
pendingControlRectsRef.current = new Map(
Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_CONTROL_SELECTOR)).map(
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 3ee85f73ef5..26957cd423e 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -150,6 +150,7 @@ import {
shouldUseCompactComposerFooter,
shouldUseRestingComposerLayout,
} from "../composerFooterLayout";
+import { measureRestingComposerControls } from "./restingComposerControlsMeasurement";
import { observeResponsiveBreakpointFade, usePanelAnimationSettings } from "../../panelAnimations";
import { type ComposerPromptEditorHandle, ComposerPromptEditor } from "../ComposerPromptEditor";
import { ProviderModelPicker } from "./ProviderModelPicker";
@@ -852,44 +853,6 @@ const terminalContextIdListsEqual = (
): boolean =>
contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]);
-function elementOuterWidth(element: HTMLElement): number {
- const width = element.getBoundingClientRect().width;
- if (width === 0) return 0;
- const style = getComputedStyle(element);
- return (
- width +
- (Number.parseFloat(style.marginInlineStart) || 0) +
- (Number.parseFloat(style.marginInlineEnd) || 0)
- );
-}
-
-function elementInlineMarginWidth(element: HTMLElement): number {
- const style = getComputedStyle(element);
- return (
- (Number.parseFloat(style.marginInlineStart) || 0) +
- (Number.parseFloat(style.marginInlineEnd) || 0)
- );
-}
-
-function providerModelPickerNaturalWidth(picker: HTMLElement): number {
- const renderedWidth = picker.getBoundingClientRect().width;
- if (renderedWidth === 0) return 0;
- const style = getComputedStyle(picker);
- const label = picker.querySelector<HTMLElement>('[data-chat-provider-model-picker-label="true"]');
- const hiddenLabelWidth = label ? Math.max(0, label.scrollWidth - label.clientWidth) : 0;
- const maxWidth = Number.parseFloat(style.maxWidth);
- const naturalWidth = Math.min(
- renderedWidth + hiddenLabelWidth,
- Number.isFinite(maxWidth) ? maxWidth : Number.POSITIVE_INFINITY,
- );
- return naturalWidth + elementInlineMarginWidth(picker);
-}
-
-function providerModelPickerMinimumWidth(picker: HTMLElement): number {
- const minWidth = Number.parseFloat(getComputedStyle(picker).minWidth) || 0;
- return minWidth + elementInlineMarginWidth(picker);
-}
-
function useRestingComposerControlsLayout(host: HTMLDivElement | null) {
const controlsRef = useRef<HTMLDivElement>(null);
const hostRef = useRef(host);
@@ -903,41 +866,12 @@ function useRestingComposerControlsLayout(host: HTMLDivElement | null) {
// composer pays no layout reads here despite the every-render effect.
if (currentHost === null || !controls) return;
- const blocks = Array.from(controls.querySelectorAll<HTMLElement>("[data-resting-block]"));
-
- // Hidden blocks and the unused overflow trigger stay mounted out of flow
- // at full size. The picker is the one flexible item: recover its intended
- // width from the truncated label, then let it contract only after all
- // trailing blocks have moved into overflow.
- const gap = Number.parseFloat(getComputedStyle(controls).columnGap) || 0;
- const picker = controls.querySelector<HTMLElement>("[data-chat-provider-model-picker]");
- const leadingControl =
- picker ?? controls.querySelector<HTMLElement>('[data-chat-provider-unavailable="true"]');
- if (!leadingControl) return;
- // Separators are display:none on phone widths; a hidden one takes no gap.
- const separator = controls.querySelector<HTMLElement>("[data-resting-controls-separator]");
- const separatorWidth = separator ? elementOuterWidth(separator) : 0;
- const overflow = controls.querySelector<HTMLElement>("[data-resting-controls-overflow]");
- const separatorAndGapWidth = separatorWidth > 0 ? separatorWidth + gap : 0;
- const naturalFixedWidth =
- (picker ? providerModelPickerNaturalWidth(picker) : elementOuterWidth(leadingControl)) +
- separatorAndGapWidth;
- const minimumFixedWidth =
- (picker ? providerModelPickerMinimumWidth(picker) : elementOuterWidth(leadingControl)) +
- separatorAndGapWidth;
- const blockWidths = blocks.map(elementOuterWidth);
- const overflowWidth = overflow ? elementOuterWidth(overflow) : 0;
+ const measurement = measureRestingComposerControls(controls);
+ if (!measurement) return;
const hostWidth = currentHost.clientWidth;
setLayout((current) => {
- const next = resolveRestingComposerControlsLayout({
- hostWidth,
- gap,
- naturalFixedWidth,
- minimumFixedWidth,
- blockWidths,
- overflowWidth,
- });
+ const next = resolveRestingComposerControlsLayout({ ...measurement, hostWidth });
return next.hiddenCount === current.hiddenCount && next.visible === current.visible
? current
: next;
@@ -3921,7 +3855,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const hidden = index >= restingBlockDefs.length - restingHiddenBlockCount;
return (
<div
- key={`${def.id}:${hidden ? "hidden" : "visible"}`}
+ key={def.id}
data-resting-block={def.id}
aria-hidden={hidden || undefined}
inert={hidden || undefined}
@@ -3936,7 +3870,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
})}
{composerControlsInStrip ? (
<div
- key={hiddenRestingBlockIds.length > 0 ? "overflow:visible" : "overflow:hidden"}
data-resting-controls-overflow
aria-hidden={hiddenRestingBlockIds.length === 0 || undefined}
inert={hiddenRestingBlockIds.length === 0 || undefined}
@@ -3949,6 +3882,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
interactionMode={interactionMode}
runtimeMode={runtimeMode}
size="xs"
+ hidden={hiddenRestingBlockIds.length === 0}
showInteractionModeToggle={
composerProviderControls.showInteractionModeToggle &&
hiddenRestingBlockIds.includes("mode")
diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx
index 6781b0f66c2..aa6544bea8e 100644
--- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx
+++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx
@@ -1,5 +1,5 @@
import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
-import { memo, type ReactNode } from "react";
+import { memo, type ReactNode, useState } from "react";
import { EllipsisIcon } from "lucide-react";
import {
Menu,
@@ -18,13 +18,29 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
showInteractionModeToggle: boolean;
traitsMenuContent?: ReactNode;
size?: "sm" | "xs";
+ /**
+ * The resting strip keeps this menu mounted out of flow while every block
+ * fits inline. Its portaled popup would outlive that transition, so an
+ * open menu closes when its trigger hides.
+ */
+ hidden?: boolean;
onToggleInteractionMode: () => void;
onRuntimeModeChange: (mode: RuntimeMode) => void;
}) {
const size = props.size ?? "sm";
+ const [open, setOpen] = useState(false);
+ const hidden = props.hidden ?? false;
+ // Base UI does not report a close it did not initiate, so clear the state
+ // when the trigger hides or the menu would reopen by itself when the
+ // trigger returns.
+ const [wasHidden, setWasHidden] = useState(hidden);
+ if (hidden !== wasHidden) {
+ setWasHidden(hidden);
+ if (hidden) setOpen(false);
+ }
return (
- <Menu>
+ <Menu open={open && !hidden} onOpenChange={setOpen}>
<MenuTrigger
render={
<ComposerControl
diff --git a/apps/web/src/components/chat/restingComposerControlsMeasurement.ts b/apps/web/src/components/chat/restingComposerControlsMeasurement.ts
new file mode 100644
index 00000000000..3bd4242d457
--- /dev/null
+++ b/apps/web/src/components/chat/restingComposerControlsMeasurement.ts
@@ -0,0 +1,77 @@
+import type { RestingComposerControlsMeasurement } from "../composerFooterLayout";
+
+function elementOuterWidth(element: HTMLElement): number {
+ const width = element.getBoundingClientRect().width;
+ if (width === 0) return 0;
+ const style = getComputedStyle(element);
+ return (
+ width +
+ (Number.parseFloat(style.marginInlineStart) || 0) +
+ (Number.parseFloat(style.marginInlineEnd) || 0)
+ );
+}
+
+function elementInlineMarginWidth(element: HTMLElement): number {
+ const style = getComputedStyle(element);
+ return (
+ (Number.parseFloat(style.marginInlineStart) || 0) +
+ (Number.parseFloat(style.marginInlineEnd) || 0)
+ );
+}
+
+function providerModelPickerNaturalWidth(picker: HTMLElement): number {
+ const renderedWidth = picker.getBoundingClientRect().width;
+ if (renderedWidth === 0) return 0;
+ const style = getComputedStyle(picker);
+ const label = picker.querySelector<HTMLElement>('[data-chat-provider-model-picker-label="true"]');
+ const hiddenLabelWidth = label ? Math.max(0, label.scrollWidth - label.clientWidth) : 0;
+ const maxWidth = Number.parseFloat(style.maxWidth);
+ const naturalWidth = Math.min(
+ renderedWidth + hiddenLabelWidth,
+ Number.isFinite(maxWidth) ? maxWidth : Number.POSITIVE_INFINITY,
+ );
+ return naturalWidth + elementInlineMarginWidth(picker);
+}
+
+function providerModelPickerMinimumWidth(picker: HTMLElement): number {
+ const minWidth = Number.parseFloat(getComputedStyle(picker).minWidth) || 0;
+ return minWidth + elementInlineMarginWidth(picker);
+}
+
+/**
+ * Read the natural widths of the resting composer controls from the DOM.
+ *
+ * Both the composer (deciding which blocks move into overflow) and the
+ * context strip (deciding whether its labels may expand) read the same
+ * numbers, so neither decision depends on what the other one hid last render.
+ *
+ * Hidden blocks and the unused overflow trigger stay mounted out of flow at
+ * full size. The picker is the one flexible item: its intended width is
+ * recovered from the truncated label.
+ */
+export function measureRestingComposerControls(
+ controls: HTMLElement,
+): RestingComposerControlsMeasurement | null {
+ const gap = Number.parseFloat(getComputedStyle(controls).columnGap) || 0;
+ const picker = controls.querySelector<HTMLElement>("[data-chat-provider-model-picker]");
+ const leadingControl =
+ picker ?? controls.querySelector<HTMLElement>('[data-chat-provider-unavailable="true"]');
+ if (!leadingControl) return null;
+ // Separators are display:none on phone widths; a hidden one takes no gap.
+ const separator = controls.querySelector<HTMLElement>("[data-resting-controls-separator]");
+ const separatorWidth = separator ? elementOuterWidth(separator) : 0;
+ const overflow = controls.querySelector<HTMLElement>("[data-resting-controls-overflow]");
+ const separatorAndGapWidth = separatorWidth > 0 ? separatorWidth + gap : 0;
+ const blocks = Array.from(controls.querySelectorAll<HTMLElement>("[data-resting-block]"));
+ return {
+ gap,
+ naturalFixedWidth:
+ (picker ? providerModelPickerNaturalWidth(picker) : elementOuterWidth(leadingControl)) +
+ separatorAndGapWidth,
+ minimumFixedWidth:
+ (picker ? providerModelPickerMinimumWidth(picker) : elementOuterWidth(leadingControl)) +
+ separatorAndGapWidth,
+ blockWidths: blocks.map(elementOuterWidth),
+ overflowWidth: overflow ? elementOuterWidth(overflow) : 0,
+ };
+}
diff --git a/apps/web/src/components/composerFooterLayout.test.ts b/apps/web/src/components/composerFooterLayout.test.ts
index 09a2744a754..926816508ec 100644
--- a/apps/web/src/components/composerFooterLayout.test.ts
+++ b/apps/web/src/components/composerFooterLayout.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it } from "vite-plus/test";
+import { resolveContextStripLabelsCompact } from "./BranchToolbar.logic";
import {
COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX,
COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX,
getRestingComposerImagePreviewCounts,
resolveRestingComposerControlsLayout,
+ resolveRestingComposerControlsNaturalWidth,
shouldAnimateComposerRestingTransition,
shouldUseCompactComposerPrimaryActions,
shouldUseCompactComposerFooter,
@@ -213,3 +215,65 @@ describe("resolveRestingComposerControlsLayout", () => {
).toEqual({ hiddenCount: 0, visible: false });
});
});
+
+describe("context strip labels and resting composer controls", () => {
+ // Widths captured from a desktop renderer that crashed with React error
+ // 185. The strip is 724px wide. Its expanded labels need 327px, and the
+ // rest of its chrome needs 125px. The composer controls sit in the host
+ // that takes whatever is left.
+ const stripWidth = 724;
+ const labelWidth = 327;
+ const chromeWidth = 125;
+ const measurement = {
+ gap: 4,
+ naturalFixedWidth: 96.3828125 + 5 + 4,
+ minimumFixedWidth: 52 + 5 + 4,
+ blockWidths: [130.6953125, 119.671875],
+ overflowWidth: 28,
+ };
+ const naturalWidth = resolveRestingComposerControlsNaturalWidth(measurement);
+
+ function hostWidth(compact: boolean): number {
+ return stripWidth - chromeWidth - (compact ? 0 : labelWidth);
+ }
+
+ it("keeps the labels compact when the full controls only fit beside compact labels", () => {
+ // Compact labels leave 599px, so the composer shows every block.
+ const layout = resolveRestingComposerControlsLayout({
+ ...measurement,
+ hostWidth: hostWidth(true),
+ });
+ expect(layout).toEqual({ hiddenCount: 0, visible: true });
+
+ // The strip reserves the natural controls width, so expanding the
+ // labels is off the table: 125 + 327 + 364 > 724.
+ const compact = resolveContextStripLabelsCompact({
+ compact: true,
+ neededWidth: chromeWidth + labelWidth + naturalWidth,
+ availableWidth: stripWidth,
+ });
+ expect(compact).toBe(true);
+
+ // The next pass sees the same inputs and lands on the same answer.
+ expect(
+ resolveRestingComposerControlsLayout({ ...measurement, hostWidth: hostWidth(compact) }),
+ ).toEqual(layout);
+ });
+
+ it("does not settle when the strip only reserves the visible controls", () => {
+ // Regression guard for the alternating layout. Reserving only the
+ // controls left visible after two blocks moved into overflow makes the
+ // strip expand its labels, which shrinks the host below what the full
+ // controls need, which hides the blocks again.
+ const hiddenControlsWidth = 137;
+ const expands = !resolveContextStripLabelsCompact({
+ compact: true,
+ neededWidth: chromeWidth + labelWidth + hiddenControlsWidth,
+ availableWidth: stripWidth,
+ });
+ expect(expands).toBe(true);
+ expect(
+ resolveRestingComposerControlsLayout({ ...measurement, hostWidth: hostWidth(false) }),
+ ).toEqual({ hiddenCount: 2, visible: true });
+ });
+});
diff --git a/apps/web/src/components/composerFooterLayout.ts b/apps/web/src/components/composerFooterLayout.ts
index d82fddd535a..2ab3b36a1b9 100644
--- a/apps/web/src/components/composerFooterLayout.ts
+++ b/apps/web/src/components/composerFooterLayout.ts
@@ -63,6 +63,43 @@ export function shouldUseCompactComposerPrimaryActions(
return width !== null && width < COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX;
}
+export interface RestingComposerControlsMeasurement {
+ gap: number;
+ naturalFixedWidth: number;
+ minimumFixedWidth: number;
+ blockWidths: readonly number[];
+ overflowWidth: number;
+}
+
+function restingComposerControlsWidth(
+ input: RestingComposerControlsMeasurement,
+ hiddenCount: number,
+ fixedWidth = input.naturalFixedWidth,
+): number {
+ const { blockWidths, gap } = input;
+ const visibleCount = blockWidths.length - hiddenCount;
+ return (
+ fixedWidth +
+ blockWidths.slice(0, visibleCount).reduce((sum, width) => sum + width, 0) +
+ (hiddenCount > 0 ? input.overflowWidth : 0) +
+ gap * (visibleCount + (hiddenCount > 0 ? 1 : 0))
+ );
+}
+
+/**
+ * The width the resting controls take with nothing moved into overflow.
+ *
+ * The context strip reserves this much for the composer before deciding
+ * whether its own labels may expand. Judging against the currently visible
+ * controls instead lets the strip expand into space the composer just gave
+ * up, which shrinks the host, hides the controls again, and repeats.
+ */
+export function resolveRestingComposerControlsNaturalWidth(
+ input: RestingComposerControlsMeasurement,
+): number {
+ return restingComposerControlsWidth(input, 0);
+}
+
/**
* Decide how many trailing resting control blocks move into the overflow
* menu, and whether the cluster can show at all, from natural widths.
@@ -71,29 +108,18 @@ export function shouldUseCompactComposerPrimaryActions(
* the overflow menu, the picker may contract to its minimum readable width;
* below that the whole cluster hides rather than clipping.
*/
-export function resolveRestingComposerControlsLayout(input: {
- hostWidth: number;
- gap: number;
- naturalFixedWidth: number;
- minimumFixedWidth: number;
- blockWidths: readonly number[];
- overflowWidth: number;
-}): { hiddenCount: number; visible: boolean } {
- const { blockWidths, gap, hostWidth } = input;
- const widthWithHidden = (hidden: number, fixedWidth = input.naturalFixedWidth) => {
- const visibleCount = blockWidths.length - hidden;
- return (
- fixedWidth +
- blockWidths.slice(0, visibleCount).reduce((sum, width) => sum + width, 0) +
- (hidden > 0 ? input.overflowWidth : 0) +
- gap * (visibleCount + (hidden > 0 ? 1 : 0))
- );
- };
-
+export function resolveRestingComposerControlsLayout(
+ input: RestingComposerControlsMeasurement & { hostWidth: number },
+): { hiddenCount: number; visible: boolean } {
+ const { blockWidths, hostWidth } = input;
let hiddenCount = 0;
- while (hiddenCount < blockWidths.length && widthWithHidden(hiddenCount) > hostWidth) {
+ while (
+ hiddenCount < blockWidths.length &&
+ restingComposerControlsWidth(input, hiddenCount) > hostWidth
+ ) {
hiddenCount += 1;
}
- const visible = widthWithHidden(hiddenCount, input.minimumFixedWidth) <= hostWidth;
+ const visible =
+ restingComposerControlsWidth(input, hiddenCount, input.minimumFixedWidth) <= hostWidth;
return { hiddenCount, visible };
}