refactor(webui): separate gateway mutations and UI state (#6727)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 22:22:51 +08:00
1 parent ce12bfdd0d
commit 5537bdabd3
70 files changed
+4058 -3650

No files matched your search

+5 -59
View File
@@ -32,6 +32,7 @@ import {
Unplug,
X,
} from "lucide-react";
import { useSidebarGroupMotion } from "@/hooks/useSidebarGroupMotion";
import { useTranslation } from "react-i18next";
import {
@@ -342,9 +343,6 @@ export const ChatList = memo(function ChatList({
observer?.disconnect();
};
}, [hasListHeader, loading, sessions.length, temporarySessions.length]);
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
const layoutAnimationsRef = useRef(new Map<string, Animation>());
const [collapsedPaneGroups, setCollapsedPaneGroups] = useState<Set<string>>(
readCollapsedPaneGroups,
);
@@ -551,19 +549,7 @@ export const ChatList = memo(function ChatList({
});
}, [loading, paneGroups]);
const measureLayoutRows = useCallback(() => {
const rects = new Map<string, DOMRect>();
for (const [key, row] of layoutRowRefs.current) {
rects.set(key, row.getBoundingClientRect());
}
return rects;
}, []);
const captureLayout = useCallback(() => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
layoutAnimationsRef.current.clear();
pendingLayoutRectsRef.current = measureLayoutRows();
}, [measureLayoutRows]);
const { registerRow, captureLayout } = useSidebarGroupMotion(collapsedGroups, collapsedPaneGroups);
const togglePaneGroup = useCallback((key: string) => {
captureLayout();
@@ -581,43 +567,6 @@ export const ChatList = memo(function ChatList({
onToggleGroup(key);
}, [captureLayout, onToggleGroup]);
useLayoutEffect(() => {
const previousRects = pendingLayoutRectsRef.current;
if (!previousRects) return;
pendingLayoutRectsRef.current = null;
const nextRects = measureLayoutRows();
const reduceMotion = typeof window.matchMedia === "function"
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (reduceMotion) return;
for (const [key, nextRect] of nextRects) {
const previousRect = previousRects.get(key);
const row = layoutRowRefs.current.get(key);
if (!previousRect || !row || typeof row.animate !== "function") continue;
const deltaY = previousRect.top - nextRect.top;
if (Math.abs(deltaY) < 0.5) continue;
const animation = row.animate(
[
{ transform: `translateY(${deltaY}px)` },
{ transform: "translateY(0)" },
],
{
duration: 180,
easing: "cubic-bezier(0.2, 0, 0, 1)",
},
);
layoutAnimationsRef.current.set(key, animation);
animation.addEventListener("finish", () => {
if (layoutAnimationsRef.current.get(key) === animation) {
layoutAnimationsRef.current.delete(key);
}
}, { once: true });
}
}, [collapsedGroups, collapsedPaneGroups, measureLayoutRows]);
useEffect(() => () => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
}, []);
if (initialLoading && sessions.length === 0 && temporarySessions.length === 0) {
return (
<SkeletonStatus label={t("chat.loading")} className="px-2 py-1.5">
@@ -796,8 +745,7 @@ export const ChatList = memo(function ChatList({
<div
ref={(element) => {
const key = `group:${group.id}`;
if (element) layoutRowRefs.current.set(key, element);
else layoutRowRefs.current.delete(key);
registerRow(key, element);
}}
data-sidebar-group-header={group.id}
>
@@ -866,8 +814,7 @@ export const ChatList = memo(function ChatList({
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
registerRow(s.key, element);
}}
data-sidebar-tab-group="true"
data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined}
@@ -1008,8 +955,7 @@ export const ChatList = memo(function ChatList({
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
registerRow(s.key, element);
}}
className="relative min-w-0"
>
+3 -1
View File
@@ -6,6 +6,7 @@ import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClass
import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useToast } from "@/components/ui/toast";
import { copyTextToClipboard } from "@/lib/clipboard";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -41,6 +42,7 @@ export function FileActions({
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);
const resolveMetadata = context?.resolveMetadata;
const portal = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const point = useRef({ x: 0, y: 0 });
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
const opener = useRef<HTMLElement | null>(null);
@@ -112,7 +114,7 @@ export function FileActions({
{children}
</span>
<Menu.Portal container={portal ?? undefined}>
<Menu.Content aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
<Menu.Content ref={surfaceRef} aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
align="start" sideOffset={4} collisionPadding={12}
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 origin-[var(--radix-popper-transform-origin)] rounded-control p-1 [&_[role=menuitem]]:py-1.5")}
onClick={(event) => event.stopPropagation()}
+3
View File
@@ -3,6 +3,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import type { UIImage } from "@/lib/types";
import { ZoomableImage } from "@/components/ZoomableImage";
@@ -38,6 +39,7 @@ export function ImageLightbox({
const total = images.length;
const current = index !== null ? images[index] : null;
const opener = useRef<HTMLElement | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const go = useCallback(
(delta: number) => {
@@ -93,6 +95,7 @@ export function ImageLightbox({
)}
/>
<DialogPrimitive.Content
ref={surfaceRef}
aria-label={current.name ?? t("lightbox.title")}
aria-describedby={undefined}
onOpenAutoFocus={() => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }}
+4 -3
View File
@@ -1,5 +1,5 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode, type Ref } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -11,7 +11,7 @@ import { cn } from "@/lib/utils";
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
/** One stable sidebar shell: switching targets never replays its opening animation. */
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, panelRef, onResizeStart, children }: {
tabs: PreviewTab[];
activeId: string;
width: number;
@@ -19,6 +19,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onSelect: (id: string) => void;
onCloseTab: (id: string) => void;
onClose: () => void;
panelRef?: Ref<HTMLElement>;
onResizeStart: (event: PointerEvent<HTMLButtonElement>) => void;
children: ReactNode;
}) {
@@ -46,7 +47,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onCloseTab(tab.id);
};
const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
return <SidebarPanel ref={panelRef} aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
header={<>
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+3 -2
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { StarLinkView, StarPromptView } from "@/components/StarPromptView";
import { starPromptAction } from "@/lib/api";
import { hasAnyDialogMounted } from "@/lib/dom-overlays";
import { useClient } from "@/providers/ClientProvider";
export function StarLink({ onSaved, fullWidth = false }: {
@@ -43,10 +44,10 @@ export function StarPrompt({ ready }: { ready: boolean }) {
if (status !== "open" || attempted.current) return;
attempted.current = true;
if (interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return;
|| hasAnyDialogMounted()) return;
void starPromptAction(client, "claim").then(({ show }) => {
if (cancelled || !show || interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return;
|| hasAnyDialogMounted()) return;
previousFocus.current = document.activeElement instanceof HTMLElement
? document.activeElement : null;
setOpen(true);
@@ -6,6 +6,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { PairingRequestInfo } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -27,6 +28,7 @@ export function PairingCodePopup({
const { t } = useTranslation();
const [value, setValue] = useState("");
const attemptedCode = useRef<string | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const normalizedCode = normalizePairingCode(value);
const matchedRequest = useMemo(
() => requests.find((request) => request.code === normalizedCode) ?? null,
@@ -74,6 +76,7 @@ export function PairingCodePopup({
return (
<div
ref={surfaceRef}
role="dialog"
aria-live="polite"
aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })}
@@ -12,6 +12,7 @@ import { useToast } from "@/components/ui/toast";
import { useClient } from "@/providers/ClientProvider";
import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";
import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
import { parseSSHAddress } from "@/lib/ssh-address";
import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./remote-context";
@@ -197,7 +198,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
if (reason instanceof Error && reason.message === "same_instance" && showToast
&& !editorOpen && !fingerprint && !detailsOpen && page.current
&& !page.current.closest("[hidden], [inert], [aria-hidden='true']")
&& !document.querySelector(":is([role='dialog'], [role='alertdialog']):not([data-state='closed'])")) {
&& !hasOpenDialogSurface()) {
showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" });
return;
}
@@ -1,4 +1,4 @@
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode, type Ref } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
@@ -30,6 +30,7 @@ export function ComposerUsagePopover({
showLabel = false,
compactLabel = false,
sidebarHost,
sidebarRef,
sessionKey,
children,
open: controlledOpen,
@@ -42,6 +43,7 @@ export function ComposerUsagePopover({
showLabel?: boolean;
compactLabel?: boolean;
sidebarHost?: HTMLElement | null;
sidebarRef?: Ref<HTMLElement>;
sessionKey?: string | null;
children?: (renderControl: ComposerUsageControl | undefined) => ReactNode;
open?: boolean;
@@ -196,7 +198,7 @@ export function ComposerUsagePopover({
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{inspector}
</DialogContent>
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}
</Dialog> : createPortal(<SidebarPanel ref={sidebarRef} open={open} width={420} floating={!sidebarHost} id={panelId}
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
{inspector}
</SidebarPanel>, sidebarHost ?? document.body))}
@@ -14,6 +14,7 @@ import {
import { fmtDateTime } from "@/lib/format-time";
import type { UIMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
interface PromptNavigatorProps {
messages: UIMessage[];
@@ -45,7 +46,7 @@ export function PromptNavigator({
const keyDown = (event: KeyboardEvent) => {
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || hasOpenDialogSurface())) return;
event.preventDefault();
setListTop(0); setOpen(true);
inputRef.current?.focus(); inputRef.current?.select();
+25 -118
View File
@@ -110,7 +110,7 @@ import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder";
import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput";
import type {
CliAppInfo,
ChatSummary,
@@ -144,6 +144,7 @@ import {
readDraggedSession,
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
@@ -155,10 +156,6 @@ import {
type QueuedPromptContent,
} from "@/components/thread/useQueuedPrompt";
const VOICE_SHORTCUT_CODE = "KeyD";
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
@@ -169,54 +166,6 @@ function utf8Bytes(value: string): number {
return new TextEncoder().encode(value).byteLength;
}
function isVoiceShortcutDown(event: KeyboardEvent): boolean {
return (
event.code === VOICE_SHORTCUT_CODE
&& event.ctrlKey
&& event.shiftKey
&& !event.altKey
&& !event.metaKey
);
}
function isVoiceShortcutRelease(event: KeyboardEvent): boolean {
return (
event.code === VOICE_SHORTCUT_CODE
|| event.key === "Control"
|| event.key === "Shift"
);
}
function getVoiceShortcutPlatform(): VoiceShortcutPlatform {
if (typeof navigator === "undefined") return "other";
const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } })
.userAgentData;
const platform = [
userAgentData?.platform,
navigator.platform,
navigator.userAgent,
].filter(Boolean).join(" ").toLowerCase();
const isIpadPretendingToBeMac =
navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
if (isIpadPretendingToBeMac || /mac|iphone|ipad|ipod/.test(platform)) return "apple";
if (/win/.test(platform)) return "windows";
if (/cros/.test(platform)) return "chromeos";
if (/linux|x11|android/.test(platform)) return "linux";
return "other";
}
function getVoiceShortcutLabel(): string {
switch (getVoiceShortcutPlatform()) {
case "apple":
return "⌃⇧D";
case "chromeos":
case "linux":
case "windows":
case "other":
return "Ctrl ⇧ D";
}
}
interface ThreadComposerProps {
onSend: (
content: string,
@@ -631,7 +580,6 @@ export function ThreadComposer({
end: number;
} | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null);
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
const showToast = useToast();
const [sendPending, setSendPending] = useState(false);
const [pathInspection, setPathInspection] = useState<{
@@ -797,9 +745,7 @@ export function ThreadComposer({
const fileInputRef = useRef<HTMLInputElement>(null);
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
const voiceShortcutDownRef = useRef(false);
const isHero = variant === "hero";
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
const projectPickerAvailable =
!workspaceProjectLocked
&& !!workspaceDefaultScope
@@ -1428,19 +1374,6 @@ export function ThreadComposer({
measureDraft();
}, [readingTextSize, customReadingTextSize, measureDraft]);
// Runs before paint so switching sessions never flashes stale draft text.
useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
previousPendingQueueKeyRef.current = pendingQueueKey;
setValue("");
setInlineError(null);
setVoiceSetupError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
clear();
}, [clear, pendingQueueKey]);
const appendTranscription = useCallback((text: string) => {
const transcript = text.trim();
if (!transcript) return;
@@ -1454,56 +1387,26 @@ export function ThreadComposer({
focusTextarea();
}, [focusTextarea]);
const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []);
const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => {
// Setup blockers carry instructions users may need to keep in view while fixing them.
if (key === "insecureContext" || key === "permission" || key === "notConfigured") {
setVoiceSetupError(key);
return;
}
showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" });
}, [showToast, t]);
const voiceRecorder = useVoiceRecorder({
disabled: interactionDisabled,
onClearError: clearVoiceSetupError,
onError: setVoiceError,
onTranscript: appendTranscription,
onTranscribeAudio,
const {
recorder: voiceRecorder, setupError: voiceSetupError, clearSetupError,
shortcutLabel: voiceShortcutLabel, shortcutAria, canSendQueuedPrompt,
} = useComposerVoiceInput({
disabled: interactionDisabled, onTranscribeAudio, onTranscript: appendTranscription,
wantsWav: transcriptionProvider === "xiaomi_mimo",
});
useEffect(() => {
if (!onTranscribeAudio) return;
function onKeyDown(event: KeyboardEvent): void {
if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return;
event.preventDefault();
voiceShortcutDownRef.current = true;
voiceRecorder.beginShortcutHold();
}
function onKeyUp(event: KeyboardEvent): void {
if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return;
event.preventDefault();
voiceShortcutDownRef.current = false;
voiceRecorder.endShortcutHold();
}
function onWindowBlur(): void {
if (!voiceShortcutDownRef.current) return;
voiceShortcutDownRef.current = false;
voiceRecorder.endShortcutHold();
}
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
window.addEventListener("blur", onWindowBlur);
return () => {
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("keyup", onKeyUp);
window.removeEventListener("blur", onWindowBlur);
};
}, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]);
// Runs before paint so switching sessions never flashes stale draft text.
useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
previousPendingQueueKeyRef.current = pendingQueueKey;
setValue("");
setInlineError(null);
clearSetupError();
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
clear();
}, [clear, clearSetupError, pendingQueueKey]);
const handleStop = useCallback(() => {
pauseQueue();
@@ -1890,7 +1793,7 @@ export function ThreadComposer({
&& !e.ctrlKey
&& !e.metaKey
) {
if (!e.repeat && voiceRecorder.state === "idle" && !voiceShortcutDownRef.current) {
if (!e.repeat && canSendQueuedPrompt()) {
sendQueuedPrompt(queuedPrompt);
}
return;
@@ -2371,7 +2274,7 @@ export function ThreadComposer({
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
: isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send")
}
aria-keyshortcuts={showVoiceButton ? VOICE_SHORTCUT_ARIA : undefined}
aria-keyshortcuts={showVoiceButton ? shortcutAria : undefined}
onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined}
onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined}
@@ -2653,6 +2556,7 @@ function CliAppMentionPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const groupedCandidates = (["session", "cli", "mcp"] as const)
.map((kind) => ({
kind,
@@ -2668,6 +2572,7 @@ function CliAppMentionPalette({
.filter((group) => group.items.length > 0);
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.mentions.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
@@ -2817,8 +2722,10 @@ function SlashCommandPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.slash.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
+25 -20
View File
@@ -8,6 +8,7 @@ import {
completedActivityDurationMs,
formatActivityDuration,
} from "@/components/thread/AgentActivityCluster";
import { sameHistoryRowIdentity, type HistoryRowIdentity, type HistoryRowSource } from "@/components/thread/history-row-identity";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
interface ThreadMessagesProps {
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
messages: UIMessage[];
beforeMessages?: ReactNode;
beforeUnit?: { key: string; content: ReactNode };
@@ -82,6 +84,7 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
}
export function ThreadMessages({
historyRows,
messages,
beforeMessages,
beforeUnit,
@@ -257,6 +260,7 @@ export function ThreadMessages({
key={unitKeys[index]}
unitKey={unitKeys[index]}
scrollAnchor={scrollAnchors[index]}
historyRows={historyRows}
unit={unit}
mobileActions={mobileActions}
marginTop={prelude ? "" : marginTop}
@@ -370,7 +374,8 @@ function pendingTurnProjection(
interface ThreadDisplayUnitProps {
mobileActions: boolean;
unitKey: string;
scrollAnchor: ScrollAnchorIdentity;
scrollAnchor: HistoryRowIdentity;
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
unit: DisplayUnit;
marginTop: string;
userPromptId?: string;
@@ -574,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mobileActions,
unitKey,
scrollAnchor,
historyRows,
unit,
marginTop,
userPromptId,
@@ -607,6 +613,12 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
}: ThreadDisplayUnitProps) {
const { t } = useTranslation();
const elementRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = elementRef.current;
if (!element || !historyRows) return;
historyRows.set(element, scrollAnchor);
return () => { historyRows.delete(element); };
}, [historyRows, scrollAnchor]);
const activityDetailsId = useId();
const heightRef = useRef(0);
const [nearViewport, setNearViewport] = useState(true);
@@ -699,8 +711,6 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
onContextBlockActiveChange(contextBlockKey ?? null);
}}
data-thread-display-unit={unitKey}
data-thread-scroll-sources={scrollAnchor.sources}
data-thread-scroll-fallback={scrollAnchor.fallback}
data-user-prompt-id={userPromptId}
data-message-context-block={contextBlockKey}
data-context-block-active={contextBlockActive || undefined}
@@ -793,8 +803,8 @@ function threadDisplayUnitPropsEqual(
): boolean {
return (
displayUnitsEqual(previous.unit, next.unit)
&& previous.scrollAnchor.sources === next.scrollAnchor.sources
&& previous.scrollAnchor.fallback === next.scrollAnchor.fallback
&& previous.historyRows === next.historyRows
&& sameHistoryRowIdentity(previous.scrollAnchor, next.scrollAnchor)
&& previous.mobileActions === next.mobileActions
&& previous.marginTop === next.marginTop
&& previous.userPromptId === next.userPromptId
@@ -956,39 +966,34 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
});
}
interface ScrollAnchorIdentity {
sources: string;
fallback?: string;
}
function scrollAnchorsForUnits(units: DisplayUnit[]): ScrollAnchorIdentity[] {
function scrollAnchorsForUnits(units: DisplayUnit[]): HistoryRowIdentity[] {
const sourceKeys = units.map((unit) => {
const messages = unit.type === "message" ? [unit.message] : unit.messages;
// Either edge of an activity cluster can survive when the other grows.
const edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages;
const streams: string[] = [];
const sequences: string[] = [];
const ids: string[] = [];
const streams: HistoryRowSource[] = [];
const sequences: HistoryRowSource[] = [];
const ids: HistoryRowSource[] = [];
for (const message of edges) {
const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId;
if (message.turnId && stream) streams.push(JSON.stringify([unit.type, "stream", message.turnId, stream]));
if (message.turnId && stream) streams.push({ kind: "stream", key: JSON.stringify([unit.type, "stream", message.turnId, stream]) });
const sequence = message.projectionStartSeq ?? message.turnSeq;
if (message.turnId && Number.isFinite(sequence)) {
sequences.push(JSON.stringify([unit.type, "sequence", message.turnId, sequence]));
sequences.push({ kind: "sequence", key: JSON.stringify([unit.type, "sequence", message.turnId, sequence]) });
}
ids.push(JSON.stringify([unit.type, "id", message.id]));
ids.push({ kind: "id", key: JSON.stringify([unit.type, "id", message.id]) });
}
return [...new Set([...streams, ...sequences, ...ids])];
return Array.from(new Map([...streams, ...sequences, ...ids].map((source) => [source.key, source])).values());
});
const sourceCounts = new Map<string, number>();
const bases = units.map(unitKeyBase);
const baseCounts = new Map<string, number>();
for (const sources of sourceKeys) for (const source of sources) {
sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1);
sourceCounts.set(source.key, (sourceCounts.get(source.key) ?? 0) + 1);
}
for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1);
return sourceKeys.map((sources, index) => ({
sources: JSON.stringify(sources.filter((source) => sourceCounts.get(source) === 1)),
sources: sources.filter((source) => sourceCounts.get(source.key) === 1),
// A sole turn/phase row can keep its live identity when replay replaces
// both its source id and sequence. Occurrence keys are unsafe otherwise.
...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1
+21 -117
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CSSProperties, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";
@@ -87,6 +87,8 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useFilePreviewResize } from "@/hooks/useFilePreviewResize";
import { hasAnyOverlayMounted } from "@/lib/dom-overlays";
import { composerContextSnapshots } from "@/lib/context-graph";
import { useClient } from "@/providers/ClientProvider";
@@ -187,10 +189,6 @@ function hasInlineDeliveryError(
));
}
const FILE_PREVIEW_DEFAULT_WIDTH = 544;
const FILE_PREVIEW_MIN_WIDTH = 360;
const FILE_PREVIEW_MAX_WIDTH = 860;
const FILE_PREVIEW_MIN_MAIN_WIDTH = 420;
const FILE_PREVIEW_CLOSE_ANIMATION_MS = 320;
type FilePreviewAvailabilityCacheEntry = {
@@ -199,20 +197,6 @@ type FilePreviewAvailabilityCacheEntry = {
revision: number;
};
function clampFilePreviewWidth(width: number, maxWidth: number): number {
return Math.min(Math.max(width, FILE_PREVIEW_MIN_WIDTH), maxWidth);
}
function maxFilePreviewWidth(containerWidth: number): number {
return Math.min(
containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH,
Math.max(
FILE_PREVIEW_MIN_WIDTH,
Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH),
),
);
}
const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};
interface ThreadShellProps {
@@ -498,6 +482,7 @@ export function ThreadShell({
}, [multiplePanes, previewSessionKey]);
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
const contextSidebarRef = useRef<HTMLElement>(null);
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -525,8 +510,6 @@ export function ThreadShell({
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
}, [composerDestination, composerMount, inlineComposer]);
useLayoutEffect(() => () => composerMount.remove(), [composerMount]);
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
const persistDraft = session ? !temporary : !temporaryChatEnabled;
const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null);
@@ -538,6 +521,9 @@ export function ThreadShell({
}, [draftKey]);
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
const shellRef = useRef<HTMLElement | null>(null);
const { width: filePreviewWidth, panelRef: previewPanelRef, startResize: handleFilePreviewResizeStart, cancelResize: cancelPreviewResize } = useFilePreviewResize(
shellRef, previewOpen, previewState.width, setFilePreviewWidth,
);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
const [composerSurface, setComposerSurface] = useState<HTMLDivElement | null>(null);
const alignSidebar = useCallback(() => {
@@ -556,9 +542,7 @@ export function ThreadShell({
observer.observe(composerSurface);
return () => observer.disconnect();
}, [alignSidebar, contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount, composerSurface]);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | null>(null);
const [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
@@ -647,18 +631,14 @@ export function ThreadShell({
}, [chatId, historyKey]);
useEffect(() => {
filePreviewWidthRef.current = filePreviewWidth;
}, [filePreviewWidth]);
useEffect(() => {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
setSubmittedViewportTurn(null);
}, [previewSessionKey]);
}, [cancelPreviewResize, previewSessionKey]);
useEffect(() => {
const retained = new Set(temporaryChatIds);
@@ -680,7 +660,6 @@ export function ThreadShell({
useEffect(() => {
return () => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
}
@@ -1133,7 +1112,7 @@ export function ThreadShell({
const handleCloseFilePreview = useCallback(() => {
if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return;
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
setClosingPreview({ key: previewSessionKey, state: previewState });
// Record the closed state immediately, even if navigation interrupts the animation.
closePreview();
@@ -1141,23 +1120,24 @@ export function ThreadShell({
filePreviewCloseTimerRef.current = null;
setClosingPreview(null);
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
}, [previewSessionKey, filePreviewClosing, previewState, closePreview]);
}, [cancelPreviewResize, previewSessionKey, filePreviewClosing, previewState, closePreview]);
const cancelPreviewClose = useCallback(() => {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
}, []);
}, [cancelPreviewResize]);
const handleOpenFilePreview = useCallback((path: string) => {
setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);
const outgoingSidebar = previewPanelRef.current ?? contextSidebarRef.current;
setSidebarEnterWidth(outgoingSidebar?.getBoundingClientRect().width ?? 0);
setContextSidebarOpen(false);
cancelPreviewClose();
openFile(path);
}, [cancelPreviewClose, openFile]);
}, [cancelPreviewClose, openFile, previewPanelRef]);
const handleContextSidebarOpenChange = useCallback((open: boolean) => {
if (open) {
@@ -1170,10 +1150,10 @@ export function ThreadShell({
const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview();
else {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
closeTab(id);
}
}, [previewState.tabs.length, handleCloseFilePreview, closeTab]);
}, [cancelPreviewResize, previewState.tabs.length, handleCloseFilePreview, closeTab]);
// Markdown blocks can retain rendered links while their text is unchanged.
// Keep their callback stable, but always act on the current pane/session state.
@@ -1203,7 +1183,7 @@ export function ThreadShell({
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
// Let a dialog/menu above the pane consume Escape without closing this preview.
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
if (hasAnyOverlayMounted()) return;
event.preventDefault();
handleCloseFilePreview();
};
@@ -1211,84 +1191,6 @@ export function ThreadShell({
return () => window.removeEventListener("keydown", onKeyDown);
}, [previewOpen, headerActive, handleCloseFilePreview]);
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
filePreviewResizeCleanupRef.current?.();
event.preventDefault();
event.stopPropagation();
const panel = event.currentTarget.closest<HTMLElement>("[data-file-preview-panel]");
const shellRect = shellRef.current?.getBoundingClientRect();
const rightEdge = shellRect?.right ?? window.innerWidth;
const maxWidth = maxFilePreviewWidth(shellRect?.width ?? window.innerWidth);
const originalBodyCursor = document.body.style.cursor;
const originalBodyUserSelect = document.body.style.userSelect;
const originalPanelTransition = panel?.style.transition ?? "";
const frameElement = panel?.querySelector("iframe");
const originalFramePointerEvents = frameElement?.style.pointerEvents ?? "";
let nextWidth = filePreviewWidthRef.current;
let frame: number | null = null;
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
if (panel) panel.style.transition = "none";
if (frameElement) frameElement.style.pointerEvents = "none";
const applyWidth = (clientX: number) => {
nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth);
filePreviewWidthRef.current = nextWidth;
if (frame !== null) return;
frame = window.requestAnimationFrame(() => {
frame = null;
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
});
};
const handlePointerMove = (moveEvent: PointerEvent) => {
moveEvent.preventDefault();
applyWidth(moveEvent.clientX);
};
const stopResize = (commit: boolean) => {
if (frame !== null) {
window.cancelAnimationFrame(frame);
frame = null;
}
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
if (panel) panel.style.transition = originalPanelTransition;
if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents;
if (commit) setFilePreviewWidth(nextWidth);
document.body.style.cursor = originalBodyCursor;
document.body.style.userSelect = originalBodyUserSelect;
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
filePreviewResizeCleanupRef.current = null;
};
const handlePointerUp = () => stopResize(true);
filePreviewResizeCleanupRef.current = () => stopResize(false);
applyWidth(event.clientX);
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
window.addEventListener("pointercancel", handlePointerUp);
}, [setFilePreviewWidth]);
useEffect(() => {
if (!previewOpen) return;
const clampToShell = () => {
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
const maxWidth = maxFilePreviewWidth(shellWidth);
setFilePreviewMaxWidth(maxWidth);
};
clampToShell();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell);
if (shellRef.current) observer?.observe(shellRef.current);
window.addEventListener("resize", clampToShell);
return () => {
observer?.disconnect();
window.removeEventListener("resize", clampToShell);
};
}, [previewOpen]);
const handleForkFromMessage = useCallback(
async (beforeUserIndex: number) => {
if (!chatId || !onForkChat) return;
@@ -1588,6 +1490,7 @@ export function ThreadShell({
rounds={composerRoundUsage}
snapshots={contextGraphSnapshots}
sidebarHost={contextSidebarHost}
sidebarRef={contextSidebarRef}
open={contextSidebarOpen}
onOpenChange={handleContextSidebarOpenChange}
onOpenFile={handleOpenFilePreview}
@@ -1615,6 +1518,7 @@ export function ThreadShell({
onSelect={selectTab}
onCloseTab={handleClosePreviewTab}
onClose={handleCloseFilePreview}
panelRef={previewPanelRef}
onResizeStart={handleFilePreviewResizeStart}
>
<FilePreviewPanel
+12 -44
View File
@@ -13,6 +13,7 @@ import { ArrowDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
import { matchHistoryRow, type HistoryRowIdentity } from "@/components/thread/history-row-identity";
import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import { DiffViewportContext } from "./activity/DiffViewportContext";
@@ -93,25 +94,13 @@ export const INITIAL_HISTORY_WINDOW = 120;
export const HISTORY_WINDOW_INCREMENT = 120;
interface HistoryScrollAnchor {
sources: string[];
fallback?: string;
identity: HistoryRowIdentity;
offsetTop: number;
scrollTop: number;
}
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
function scrollSourceKind(source: string): string {
return (JSON.parse(source) as string[])[1];
}
function scrollSourcesDisagree(left: string[], right: string[], kind: string): boolean {
const leftKeys = left.filter((source) => scrollSourceKind(source) === kind);
const rightKeys = right.filter((source) => scrollSourceKind(source) === kind);
return leftKeys.length > 0 && rightKeys.length > 0
&& !leftKeys.some((source) => rightKeys.includes(source));
}
function promptTopInset(scroller: HTMLElement): number {
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
@@ -333,6 +322,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const contentRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement | null>(null);
const messageContentRef = useRef<HTMLDivElement>(null);
const [historyRows] = useState(() => new WeakMap<HTMLElement, HistoryRowIdentity>());
const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []);
const emptyStateRef = useRef<HTMLDivElement>(null);
const composerDockRef = useRef<HTMLDivElement>(null);
@@ -558,26 +548,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
const viewport = scroller.getBoundingClientRect();
const element = visibleHistoryUnit(content, viewport);
if (!element?.dataset.threadScrollSources) {
historyScrollAnchorRef.current = null;
return false;
}
const sources = JSON.parse(element.dataset.threadScrollSources) as string[];
const fallback = element.dataset.threadScrollFallback;
if (sources.length === 0 && !fallback) {
const identity = element ? historyRows.get(element) : undefined;
if (!element || !identity || (identity.sources.length === 0 && !identity.fallback)) {
historyScrollAnchorRef.current = null;
return false;
}
historyScrollAnchorRef.current = {
sources,
fallback,
identity,
scrollTop: scroller.scrollTop,
// Normalize out the reveal lease, even when reading above its inline slot.
offsetTop: element.getBoundingClientRect().top - viewport.top
- (historySlotRef.current ? HISTORY_HOLD_PX : 0),
};
return true;
}, []);
}, [historyRows]);
const reconcileHistoryScrollAnchor = useCallback(() => {
const scroller = scrollRef.current;
@@ -588,26 +572,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (Math.abs(scroller.scrollTop - Math.min(anchor.scrollTop, maxScrollTop)) >= 0.5) {
return captureHistoryScrollAnchor();
}
const candidates = Array.from(content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR));
const bySource = new Map<string, { element: HTMLElement; sources: string[] }>();
for (const candidate of candidates) {
const sources = JSON.parse(candidate.dataset.threadScrollSources ?? "[]") as string[];
for (const source of sources) bySource.set(source, { element: candidate, sources });
}
let element: HTMLElement | undefined;
for (const source of anchor.sources) {
const candidate = bySource.get(source);
if (!candidate) continue;
const kind = scrollSourceKind(source);
// An index-generated replay id can be reused by a different message.
if (kind !== "stream" && scrollSourcesDisagree(anchor.sources, candidate.sources, "stream")) continue;
if (kind === "id" && scrollSourcesDisagree(anchor.sources, candidate.sources, "sequence")) continue;
element = candidate.element;
break;
}
if (!element && anchor.fallback) {
element = candidates.find((candidate) => candidate.dataset.threadScrollFallback === anchor.fallback);
}
const element = matchHistoryRow(
anchor.identity, content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR), historyRows,
);
if (!element) {
historyScrollAnchorRef.current = null;
return false;
@@ -626,7 +593,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
// A clamped layout is the new reading position, not space owed by a later prepend.
anchor.offsetTop += requestedTop - nextTop;
return true;
}, [captureHistoryScrollAnchor]);
}, [captureHistoryScrollAnchor, historyRows]);
const resetHistoryHeader = useCallback(() => {
setHistorySlotKey(null);
@@ -1342,6 +1309,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<DiffViewportContext.Provider value={diffViewport}>
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
historyRows={historyRows}
key={messagesKey}
messages={visibleMessages}
topInset={PROMPT_TOP_INSET_PX}
@@ -206,7 +206,7 @@ function FileUnifiedDiff({
const renderBody = () => (
<div
className="mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
className="file-edit-diff-surface mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
data-testid="file-edit-diff"
>
<DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} />
@@ -0,0 +1,45 @@
type HistorySourceKind = "stream" | "sequence" | "id";
export interface HistoryRowSource {
kind: HistorySourceKind;
key: string;
}
export interface HistoryRowIdentity {
sources: HistoryRowSource[];
fallback?: string;
}
export function sameHistoryRowIdentity(left: HistoryRowIdentity, right: HistoryRowIdentity): boolean {
return left.fallback === right.fallback && left.sources.length === right.sources.length
&& left.sources.every((source, index) => source.key === right.sources[index].key);
}
function sourcesDisagree(left: HistoryRowIdentity, right: HistoryRowIdentity, kind: HistorySourceKind): boolean {
const leftKeys = left.sources.filter((source) => source.kind === kind);
const rightKeys = right.sources.filter((source) => source.kind === kind);
return leftKeys.length > 0 && rightKeys.length > 0
&& !leftKeys.some((source) => rightKeys.some((other) => source.key === other.key));
}
export function matchHistoryRow(
anchor: HistoryRowIdentity, candidates: Iterable<HTMLElement>, rows: WeakMap<HTMLElement, HistoryRowIdentity>,
): HTMLElement | undefined {
const bySource = new Map<string, { element: HTMLElement; identity: HistoryRowIdentity }>();
let fallback: HTMLElement | undefined;
for (const element of candidates) {
const identity = rows.get(element);
if (!identity) continue;
for (const source of identity.sources) bySource.set(source.key, { element, identity });
if (!fallback && anchor.fallback && anchor.fallback === identity.fallback) fallback = element;
}
for (const source of anchor.sources) {
const candidate = bySource.get(source.key);
if (!candidate) continue;
// A replay-generated row id may be reused for a different message.
if (source.kind !== "stream" && sourcesDisagree(anchor, candidate.identity, "stream")) continue;
if (source.kind === "id" && sourcesDisagree(anchor, candidate.identity, "sequence")) continue;
return candidate.element;
}
return fallback;
}
+20 -16
View File
@@ -6,6 +6,7 @@ import {
modalOverlayClassName,
modalSurfaceClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
const AlertDialog = AlertDialogPrimitive.Root;
@@ -29,22 +30,25 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
modalSurfaceClassName,
"grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</div>
</AlertDialogPortal>
));
>(({ className, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<AlertDialogPrimitive.Content
ref={surfaceRef}
className={cn(
modalSurfaceClassName,
"grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</div>
</AlertDialogPortal>
);
});
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
+3 -1
View File
@@ -7,6 +7,7 @@ import {
modalOverlayClassName,
modalSurfaceClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { FloatingPortalContext } from "@/components/ui/floating-portal";
@@ -47,6 +48,7 @@ const DialogPositionedContent = React.forwardRef<
overlayClassName?: string;
}
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
const Overlay = contained ? "div" : DialogOverlay;
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
@@ -55,7 +57,7 @@ const DialogPositionedContent = React.forwardRef<
bottom: "auto",
...(contained ? { top: 0, height: "100%" } : positionerStyle),
}}>
<DialogPrimitive.Content ref={ref} {...props} />
<DialogPrimitive.Content ref={surfaceRef} {...props} />
</div>
</Overlay>;
});
+19 -14
View File
@@ -8,6 +8,7 @@ import {
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -29,10 +30,11 @@ const DropdownMenuContent = React.forwardRef<
DropdownMenuContentProps
>(({ className, sideOffset = 4, portalContainer, ...props }, ref) => {
const dialogContainer = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<DropdownMenuPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<DropdownMenuPrimitive.Content
ref={ref}
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
@@ -140,19 +142,22 @@ DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayNam
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, sideOffset = 6, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
"origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto",
className,
)}
{...props}
/>
));
>(({ className, sideOffset = 6, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<DropdownMenuPrimitive.SubContent
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
"origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto",
className,
)}
{...props}
/>
);
});
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
export {
+4 -1
View File
@@ -5,6 +5,7 @@ import {
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -23,10 +24,12 @@ const PopoverContent = React.forwardRef<
PopoverContentProps
>(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => {
const dialogContainer = useFloatingPortal();
// Radix renders Popover.Content as role="dialog".
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<PopoverPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<PopoverPrimitive.Content
ref={ref}
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
+3 -1
View File
@@ -4,6 +4,7 @@ import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { floatingSurfaceElevationClassName, floatingItemClassName } from "@/components/ui/floating-surface";
import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { ControlChevron } from "@/components/ui/control-chevron";
@@ -28,9 +29,10 @@ export function SelectContent({ children, ...props }: Pick<
"children" | "onPointerUpCapture" | "onPointerDownOutside" | "onKeyDownCapture" | "onEscapeKeyDown" | "onCloseAutoFocus"
>) {
const container = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return (
<SelectPrimitive.Portal container={container ?? undefined}>
<SelectPrimitive.Content {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}>
<SelectPrimitive.Content ref={surfaceRef} {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}>
<SelectPrimitive.ScrollUpButton className="flex h-6 items-center justify-center"><ChevronUp className="h-3.5 w-3.5" /></SelectPrimitive.ScrollUpButton>
<SelectPrimitive.Viewport className="p-1">
{children}
+3 -1
View File
@@ -4,6 +4,7 @@ import { X } from "lucide-react";
import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
@@ -84,11 +85,12 @@ const SheetContent = React.forwardRef<
ref,
) => {
const { t } = useTranslation();
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<SheetPortal>
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
<DialogPrimitive.Content
ref={ref}
ref={surfaceRef}
className={cn(
sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out",
+18 -14
View File
@@ -2,6 +2,7 @@ import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
function TooltipProvider({
@@ -16,20 +17,23 @@ const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
floatingSurfaceElevationClassName,
"z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none",
className,
)}
{...props}
/>
</TooltipPrimitive.Portal>
));
>(({ className, sideOffset = 4, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceElevationClassName,
"z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none",
className,
)}
{...props}
/>
</TooltipPrimitive.Portal>
);
});
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };