TypeScript
fix(web): terminal drawer no longer pushes the composer into the header (#19072)
Ryan Wible055a8418c12b
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex c56aa62f607..4d41e9b2701 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1414,6 +1414,9 @@ export default function ChatView(props: ChatViewProps) {const [composerTimelineInset, setComposerTimelineInset] = useState(0);const [composerOverlayHeight, setComposerOverlayHeight] = useState(0);const composerTimelineInsetRef = useRef(0);+ const [composerReservedHeight, setComposerReservedHeight] = useState(0);+ const composerReservedHeightRef = useRef(0);+ const composerExpandedHeightRef = useRef(0);const composerRestingRef = useRef(false);const composerMountedRef = useRef(true);const [scrollToEndClearance, setScrollToEndClearance] = useState(0);@@ -4751,6 +4754,28 @@ export default function ChatView(props: ChatViewProps) {composerTimelineInsetRef.current = nextInset;setComposerTimelineInset(nextInset);}+ // The terminal drawer and the empty placeholder lay out against the+ // expanded composer. The timeline inset already holds it through the+ // desktop resting row; remembering it while the mobile strip is collapsed+ // keeps both still when focus moves between the composer and the+ // terminal, instead of re-clamping the drawer against each intermediate+ // composer height. A collapsed strip can still grow (approvals, tasks), so+ // the reservation follows it up. A hero composer's overlay fills the pane,+ // so only its stack counts there.+ const stack = composerOverlayElement?.querySelector<HTMLElement>(+ '[data-chat-composer-stack="true"]',+ );+ const expandedComposerHeight =+ isDraftHeroState && stack ? Math.ceil(stack.getBoundingClientRect().height) : nextInset;+ const mobileCollapsed = Boolean(+ stack?.querySelector('[data-chat-composer-mobile-collapsed="true"]'),+ );+ if (!mobileCollapsed) composerExpandedHeightRef.current = expandedComposerHeight;+ const reservedHeight = Math.max(composerExpandedHeightRef.current, expandedComposerHeight);+ if (composerReservedHeightRef.current !== reservedHeight) {+ composerReservedHeightRef.current = reservedHeight;+ setComposerReservedHeight(reservedHeight);+ }const mainSurface = composerOverlayElement?.querySelector<HTMLElement>('[data-chat-composer-main-surface="true"]',);@@ -4784,6 +4809,8 @@ export default function ChatView(props: ChatViewProps) {useLayoutEffect(() => {if (!composerOverlayElement) return;composerTimelineInsetRef.current = 0;+ composerReservedHeightRef.current = 0;+ composerExpandedHeightRef.current = 0;publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);// oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch must re-measure the overlay for the new timeline.}, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeightStable]);@@ -4796,14 +4823,28 @@ export default function ChatView(props: ChatViewProps) {};updateHeight();- return observeResize(composerOverlayElement, updateHeight);+ // The hero overlay fills the pane, so the composer's own growth only shows on its stack.+ const stack = isDraftHeroState+ ? composerOverlayElement.querySelector<HTMLElement>('[data-chat-composer-stack="true"]')+ : null;+ return observeResize(+ stack ? [composerOverlayElement, stack] : composerOverlayElement,+ updateHeight,+ );+ }, [+ composerOverlayElement,+ isDraftHeroState,+ publishComposerOverlayHeightStable,// oxlint-disable-next-line react/exhaustive-effect-dependencies -- The scroll-to-bottom button changes the overlay's height without resizing the observed node first.- }, [composerOverlayElement, publishComposerOverlayHeightStable, showScrollToBottom]);+ showScrollToBottom,+ ]);useLayoutEffect(() => {if (composerMountedRef.current === composerMounted) return;composerMountedRef.current = composerMounted;if (!composerOverlayElement) return;composerTimelineInsetRef.current = 0;+ composerReservedHeightRef.current = 0;+ composerExpandedHeightRef.current = 0;publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);}, [composerMounted, composerOverlayElement, publishComposerOverlayHeightStable]);const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);@@ -7980,6 +8021,7 @@ export default function ChatView(props: ChatViewProps) {rightPanelMaximized ? "w-0 flex-none" : "flex-1",)}data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}+ data-chat-column><headerref={threadPanelPopoverAnchorRef}@@ -8197,6 +8239,7 @@ export default function ChatView(props: ChatViewProps) {onManualNavigation={cancelTimelineLiveFollowForUserNavigationStable}cancelPositionRestoreRef={cancelPositionRestoreRef}hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}+ emptyPlaceholderInset={composerReservedHeight}topFadeEnabled={!hasTimelineTopBanner}{...(paintOnlyDisplayedTimeline || threadHistoryControls === undefined? {}@@ -8650,6 +8693,7 @@ export default function ChatView(props: ChatViewProps) {threadRef={mountedThreadRef}threadId={mountedThreadRef.threadId}active={mountedThreadKey === activeThreadKey}+ composerHeight={mountedThreadKey === activeThreadKey ? composerReservedHeight : 0}launchContext={mountedThreadKey === activeThreadKey ? (activeTerminalLaunchContext ?? null) : null}diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsxindex f7658ba4193..7cd80449ee9 100644--- a/apps/web/src/components/PersistentThreadTerminals.tsx+++ b/apps/web/src/components/PersistentThreadTerminals.tsx@@ -81,6 +81,7 @@ interface PersistentThreadTerminalDrawerProps {threadRef: { environmentId: EnvironmentId; threadId: ThreadId };threadId: ThreadId;active: boolean;+ composerHeight: number;launchContext: PersistentTerminalLaunchContext | null;focusRequestId: number;splitShortcutLabel: string | undefined;@@ -95,6 +96,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermthreadRef,threadId,active,+ composerHeight,launchContext,focusRequestId,splitShortcutLabel,@@ -268,6 +270,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermruntimeEnv={runtimeEnv}visible={visible}height={terminalUiState.terminalHeight}+ composerHeight={composerHeight}// Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable.terminalIds={canOperateTerminal ? terminalUiState.terminalIds : serverOrderedTerminalIds}activeTerminalId={terminalUiState.activeTerminalId}diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.tsindex 66d0fb0ce71..95e6d8bdc35 100644--- a/apps/web/src/components/ThreadTerminalDrawer.test.ts+++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts@@ -8,6 +8,8 @@ import {} from "@t3tools/client-runtime/state/terminal";import {+ clampDrawerHeight,+ resolveTerminalDrawerMaxHeight,shouldClearTerminalSelectionAction,shouldHandleTerminalExit,terminalContextMenuItems,@@ -17,6 +19,40 @@ import {terminalThemeFromApp,} from "./ThreadTerminalDrawer";+describe("terminal drawer height", () => {+ it("shrinks to fit beside the header and composer while the phone keyboard is open, then restores the preferred height", () => {+ const controls = { headerHeight: 52, composerHeight: 108 };+ const keyboardOpenMax = resolveTerminalDrawerMaxHeight({+ ...controls,+ viewportHeight: 400,+ chatColumnHeight: 360,+ });+ const keyboardClosedMax = resolveTerminalDrawerMaxHeight({+ ...controls,+ viewportHeight: 800,+ chatColumnHeight: 760,+ });++ // 360 - 52 - 108 leaves 200px, so the drawer stops short of its 280px preference.+ expect(clampDrawerHeight(280, keyboardOpenMax)).toBe(200);+ expect(clampDrawerHeight(280, keyboardClosedMax)).toBe(280);+ });++ it("keeps the window cap for panel terminals and collapses to zero when the controls fill the column", () => {+ expect(clampDrawerHeight(900, resolveTerminalDrawerMaxHeight({ viewportHeight: 800 }))).toBe(+ 600,+ );++ const crowdedMax = resolveTerminalDrawerMaxHeight({+ viewportHeight: 200,+ chatColumnHeight: 160,+ headerHeight: 52,+ composerHeight: 120,+ });+ expect(clampDrawerHeight(280, crowdedMax)).toBe(0);+ });+});+describe("terminal selection menus", () => {it("omits Add to chat when the terminal has no chat target", () => {expect(terminalSelectionMenuItems().map(({ id }) => id)).toEqual(["add-to-chat", "copy"]);diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex e9af425afef..2a42f40554d 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -88,6 +88,7 @@ import { useEnvironmentScope } from "../state/session";import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";import { useAtomCommand } from "../state/use-atom-command";import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";+import { observeResize } from "../lib/observeResize";import {resolveTerminalFontPreference,resolveTerminalFontSizePreference,@@ -97,16 +98,46 @@ import {const MIN_DRAWER_HEIGHT = 180;const MAX_DRAWER_HEIGHT_RATIO = 0.75;-function maxDrawerHeight(): number {- if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;- return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));+interface DrawerLayout {+ viewportHeight: number;+ chatColumnHeight?: number;+ headerHeight?: number;+ composerHeight?: number;}-function clampDrawerHeight(height: number, maxHeight = maxDrawerHeight()): number {+export function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number {+ const windowCap = Math.max(+ MIN_DRAWER_HEIGHT,+ Math.floor(input.viewportHeight * MAX_DRAWER_HEIGHT_RATIO),+ );+ if (input.chatColumnHeight === undefined) return windowCap;+ // The composer overlays the timeline, so flex layout cannot reserve its+ // height; without this cap a tall drawer pushes it into the header.+ return Math.min(+ windowCap,+ Math.max(0, input.chatColumnHeight - (input.headerHeight ?? 0) - (input.composerHeight ?? 0)),+ );+}++export function clampDrawerHeight(height: number, maxHeight: number): number {const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);}+function chatColumnOf(drawer: HTMLElement | null): HTMLElement | null {+ return drawer?.closest<HTMLElement>("[data-chat-column]") ?? null;+}++function readDrawerLayout(column: HTMLElement | null): Omit<DrawerLayout, "composerHeight"> {+ const viewportHeight = typeof window === "undefined" ? 0 : window.innerHeight;+ if (!column) return { viewportHeight };+ return {+ viewportHeight,+ chatColumnHeight: column.clientHeight,+ headerHeight: column.querySelector<HTMLElement>("[data-chat-header]")?.offsetHeight ?? 0,+ };+}+function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string): void {terminal.write(`\r\n[terminal] ${message}\r\n`);}@@ -1123,6 +1154,8 @@ interface ThreadTerminalDrawerProps {runtimeEnv?: Record<string, string>;visible?: boolean;height: number;+ /** Space the chat column keeps for the composer overlay; only read in drawer mode. */+ composerHeight?: number;terminalIds: string[];activeTerminalId: string;terminalGroups: ThreadTerminalGroup[];@@ -1389,6 +1422,7 @@ export default function ThreadTerminalDrawer({runtimeEnv,visible = true,height,+ composerHeight = 0,terminalIds,activeTerminalId,terminalGroups,@@ -1417,14 +1451,16 @@ export default function ThreadTerminalDrawer({Schema.Boolean,);const controlledDrawerHeight = height;- const [windowMaxDrawerHeight, setWindowMaxDrawerHeight] = useState(maxDrawerHeight);+ const drawerRef = useRef<HTMLElement | null>(null);+ const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null));+ const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight });const [drawerHeightState, setDrawerHeightState] = useState(() => ({threadId,height: controlledDrawerHeight,}));const preferredDrawerHeight =drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight;- const drawerHeight = clampDrawerHeight(preferredDrawerHeight, windowMaxDrawerHeight);+ const drawerHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);const setDrawerHeight = (update: SetStateAction<number>) => {setDrawerHeightState((current) => {const currentHeight = current.threadId === threadId ? current.height : controlledDrawerHeight;@@ -1435,12 +1471,6 @@ export default function ThreadTerminalDrawer({});};const [resizeEpoch, setResizeEpoch] = useState(0);- const [shownVisible, setShownVisible] = useState(visible);- if (shownVisible !== visible) {- setShownVisible(visible);- // The window may have resized while the drawer was hidden and not listening.- if (visible) setWindowMaxDrawerHeight(maxDrawerHeight());- }const drawerHeightRef = useRef(drawerHeight);const lastSyncedHeightRef = useRef({ threadId, height: controlledDrawerHeight });const resizeStateRef = useRef<{@@ -1658,6 +1688,7 @@ export default function ThreadTerminalDrawer({event.preventDefault();const clampedHeight = clampDrawerHeight(resizeState.startHeight + (resizeState.startY - event.clientY),+ maxDrawerHeight,);if (clampedHeight === drawerHeightRef.current) {return;@@ -1675,11 +1706,11 @@ export default function ThreadTerminalDrawer({event.currentTarget.releasePointerCapture(event.pointerId);}// A drag that ends where it started keeps the stored preference, which may- // be taller than the window-capped height the drag started from.+ // be taller than the capped height the drag started from.if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) {// React skips the write when the rendered height did not change, so put- // back the preference as the current window caps it.- const renderedHeight = clampDrawerHeight(preferredDrawerHeight);+ // back the preference as the current layout caps it.+ const renderedHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);drawerHeightRef.current = renderedHeight;resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`);return;@@ -1689,26 +1720,53 @@ export default function ThreadTerminalDrawer({setResizeEpoch((value) => value + 1);};- useEffect(() => {- if (!visible) {- return;- }-- const onWindowResize = () => {+ const drawerLayoutRef = useRef(drawerLayout);+ const updateDrawerLayout = useEffectEvent(+ (column: HTMLElement | null, source: "window" | "column") => {+ const layout = readDrawerLayout(column);+ const previous = drawerLayoutRef.current;+ const heightBudgetChanged =+ layout.viewportHeight !== previous.viewportHeight ||+ layout.chatColumnHeight !== previous.chatColumnHeight ||+ layout.headerHeight !== previous.headerHeight;+ // The column also reports width-only changes, such as every frame of a+ // right panel drag; the surface refits itself for those.+ if (!heightBudgetChanged && source === "column") return;+ drawerLayoutRef.current = layout;const resizeState = resizeStateRef.current;- const liveHeight = clampDrawerHeight(drawerHeightRef.current);+ const liveHeight = clampDrawerHeight(+ drawerHeightRef.current,+ resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }),+ );if (resizeState && liveHeight !== drawerHeightRef.current) {drawerHeightRef.current = liveHeight;resizeState.drawer?.style.setProperty("height", `${liveHeight}px`);}- setWindowMaxDrawerHeight(maxDrawerHeight());+ if (heightBudgetChanged) setDrawerLayout(layout);setResizeEpoch((value) => value + 1);- };+ },+ );+ useLayoutEffect(() => {+ if (!visible) {+ return;+ }+ // The column and window may have resized while the drawer was hidden and+ // not listening, so measure before the first visible paint.+ const column = isPanel ? null : chatColumnOf(drawerRef.current);+ const onWindowResize = () => updateDrawerLayout(column, "window");+ onWindowResize();+ const header = column?.querySelector<HTMLElement>("[data-chat-header]");+ const stopObserving = column+ ? observeResize(header ? [column, header] : column, () =>+ updateDrawerLayout(column, "column"),+ )+ : undefined;window.addEventListener("resize", onWindowResize);return () => {+ stopObserving?.();window.removeEventListener("resize", onWindowResize);};- }, [visible]);+ }, [isPanel, visible]);const syncPreferredHeight = useEffectEvent(() => syncHeight(preferredDrawerHeight));useEffect(() => () => syncPreferredHeight(), []);@@ -1716,6 +1774,7 @@ export default function ThreadTerminalDrawer({if (normalizedTerminalIds.length === 0) {return (<aside+ ref={drawerRef}data-thread-terminal-drawerdata-terminal-owner={isPanel ? "right-panel" : "drawer"}className={cn(@@ -1751,6 +1810,7 @@ export default function ThreadTerminalDrawer({return (<aside+ ref={drawerRef}data-thread-terminal-drawerdata-terminal-owner={isPanel ? "right-panel" : "drawer"}className={cn(diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsxindex 734169da537..810c62d3246 100644--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx@@ -80,6 +80,7 @@ function baseProps(): Omit<TimelineProps, "timelineEntries"> {onAnchorReady: () => {},onAnchorSizeChanged: () => {},contentInsetEndAdjustment: 0,+ emptyPlaceholderInset: 0,liveFollowEnabled: true,onIsAtEndChange: () => {},onManualNavigation: () => {},diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 8cdd28652e9..8390ebdf811 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -516,6 +516,8 @@ interface MessagesTimelineProps {findOpen?: boolean;cancelPositionRestoreRef?: React.RefObject<(() => void) | null> | undefined;hideEmptyPlaceholder?: boolean;+ /** Composer space to center the empty state against; held steady through collapse. */+ emptyPlaceholderInset: number;topFadeEnabled?: boolean;historyControls?: MessagesTimelineHistoryControls | undefined;loadEarlier?: CitationHistoryPage | null;@@ -607,6 +609,7 @@ const ConversationTimeline = memo(function ConversationTimeline({onManualNavigation,cancelPositionRestoreRef,hideEmptyPlaceholder = false,+ emptyPlaceholderInset,topFadeEnabled = false,historyControls,loadEarlier = null,@@ -1454,7 +1457,7 @@ const ConversationTimeline = memo(function ConversationTimeline({return (<divclassName="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"- style={{ paddingBottom: contentInsetEndAdjustment }}+ style={{ paddingBottom: emptyPlaceholderInset }}><p className="text-sm text-muted-foreground/30">Send a message to start the conversation.