diff --git a/components/ChatMinimap.tsx b/components/ChatMinimap.tsx index 2c4c4ef9f..013e3b8c4 100644 --- a/components/ChatMinimap.tsx +++ b/components/ChatMinimap.tsx @@ -1,72 +1,17 @@ "use client"; -import { memo, useEffect, useRef, useState, useCallback, useMemo, type RefObject } from "react"; +import { memo, useEffect, useRef, useState, useCallback, type RefObject } from "react"; import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion"; -import type { AgentMessage, TextContent } from "@/lib/types"; +import { extractPreviewText, useChatOutline, type NavNode } from "@/hooks/useChatOutline"; +import type { AgentMessage } from "@/lib/types"; + +export { extractPreviewText, type NavNode }; interface Props { messages: AgentMessage[]; scrollContainer: RefObject; messageRefs: RefObject<(HTMLDivElement | null)[]>; -} - -export interface NavNode { - id: string; - text: string; - messageIndex: number; - refIndex: number; - isUser: boolean; -} - -/** - * Extracts a concise, clean single-line preview string suitable for the - * floating context navigation pill (e.g. "move Explorer to right panel"). - */ -export function extractPreviewText(msg: AgentMessage | Partial): string { - let raw = ""; - - if (msg.role === "user") { - const content = msg.content; - if (typeof content === "string") { - raw = content; - } else if (Array.isArray(content)) { - raw = content - .filter((b): b is TextContent => Boolean(b && typeof b === "object" && "type" in b && b.type === "text" && "text" in b && typeof b.text === "string")) - .map((b) => b.text) - .join(" "); - } - } else if (msg.role === "assistant") { - const blocks = Array.isArray(msg.content) ? msg.content : []; - const text = blocks - .filter((b): b is TextContent => Boolean(b && typeof b === "object" && "type" in b && b.type === "text" && "text" in b && typeof b.text === "string")) - .map((b) => b.text) - .join(" "); - if (text) { - raw = text; - } else { - const toolNames = blocks - .filter((b) => Boolean(b && typeof b === "object" && "type" in b && b.type === "toolCall")) - .map((b) => (b && typeof b === "object" && "toolName" in b && typeof b.toolName === "string" ? b.toolName : "")); - if (toolNames.length) raw = toolNames.filter(Boolean).join(", "); - } - } - - // Strip markdown headers, code blocks, formatting, and flatten whitespace - let clean = raw - .replace(/```[\s\S]*?```/g, "") - .replace(/^#+\s+/gm, "") - .replace(/[*_`~[\]]/g, "") - .replace(/\s+/g, " ") - .trim(); - - if (!clean) { - clean = raw.replace(/\s+/g, " ").trim(); - } - - if (clean.length > 60) { - return clean.slice(0, 58) + "…"; - } - return clean; + onEnsureVisible?: (messageIndex: number, smooth?: boolean) => void; } /** @@ -126,177 +71,23 @@ export function railIndexForPointer(relY: number, railScrollTop: number, nodeCou return Math.max(0, Math.min(nodeCount - 1, index)); } -export const ChatMinimap = memo(function ChatMinimap({ messages, scrollContainer, messageRefs }: Props) { - const [activeIndex, setActiveIndex] = useState(0); +export const ChatMinimap = memo(function ChatMinimap({ messages, scrollContainer, messageRefs, onEnsureVisible }: Props) { + const { nodes, activeIndex, setActiveIndex, scrollToNode } = useChatOutline({ + messages, + scrollContainer, + messageRefs, + onEnsureVisible, + }); const [hoveredIndex, setHoveredIndex] = useState(null); const [isRailHovered, setIsRailHovered] = useState(false); const [railScrollTop, setRailScrollTop] = useState(0); const railRef = useRef(null); const draggingRef = useRef(false); - const scrollRafRef = useRef(null); - - // Extract navigation nodes: user prompts first (as the chapters of context), - // falling back to assistant messages if no user prompts exist yet. - const nodes = useMemo(() => { - const userNodes: NavNode[] = []; - let refIndex = 0; - - for (let i = 0; i < messages.length; i++) { - const msg = messages[i]; - if (msg.role !== "user" && msg.role !== "assistant") continue; - const currentRef = refIndex++; - if (msg.role === "user") { - const text = extractPreviewText(msg); - if (text) { - const id = msg && typeof msg === "object" && "id" in msg && typeof msg.id === "string" ? msg.id : `u-${i}`; - userNodes.push({ - id, - text, - messageIndex: i, - refIndex: currentRef, - isUser: true, - }); - } - } - } - - if (userNodes.length > 0) return userNodes; - - // Fallback: assistant messages - const assistantNodes: NavNode[] = []; - let aRef = 0; - for (let i = 0; i < messages.length; i++) { - const msg = messages[i]; - if (msg.role !== "user" && msg.role !== "assistant") continue; - const currentRef = aRef++; - if (msg.role === "assistant") { - const text = extractPreviewText(msg); - if (text) { - const id = msg && typeof msg === "object" && "id" in msg && typeof msg.id === "string" ? msg.id : `a-${i}`; - assistantNodes.push({ - id, - text, - messageIndex: i, - refIndex: currentRef, - isUser: false, - }); - } - } - } - return assistantNodes; - }, [messages]); - - // Smoothly scroll to the target message with multi-strategy element resolution const reducedMotion = usePrefersReducedMotion(); - const scrollToNode = useCallback((node: NavNode, smooth = true) => { - const scrollEl = scrollContainer.current; - if (!scrollEl) return; - let targetEl = messageRefs.current?.[node.refIndex]; - if (!targetEl) { - targetEl = scrollEl.querySelector(`[data-message-index="${node.messageIndex}"]`) as HTMLDivElement | null; - } - if (!targetEl && node.text) { - const cards = scrollEl.querySelectorAll(".chat-message-card"); - const sample = node.text.slice(0, 20); - for (const card of Array.from(cards)) { - if (card.textContent?.includes(sample)) { - targetEl = (card.closest("[data-message-index]") || card.parentElement || card) as HTMLDivElement; - break; - } - } - } - - const behavior: ScrollBehavior = smooth && !reducedMotion ? "smooth" : "auto"; - if (targetEl) { - const containerRect = scrollEl.getBoundingClientRect(); - const elRect = targetEl.getBoundingClientRect(); - const targetScroll = Math.max(0, scrollEl.scrollTop + (elRect.top - containerRect.top) - 16); - scrollEl.scrollTo({ top: targetScroll, behavior }); - } else { - const maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight; - if (maxScroll > 0) { - const targetScroll = Math.max(0, (node.messageIndex / Math.max(1, messages.length - 1)) * maxScroll); - scrollEl.scrollTo({ top: targetScroll, behavior }); - } - } - }, [scrollContainer, messageRefs, messages.length, reducedMotion]); - const scrollToNodeRef = useRef(scrollToNode); scrollToNodeRef.current = scrollToNode; - // Scroll-spy: identify which message node is currently in the viewport - const updateScroll = useCallback(() => { - const scrollEl = scrollContainer.current; - if (!scrollEl || nodes.length === 0) return; - - const { scrollTop, clientHeight, scrollHeight } = scrollEl; - - // Bottom reached -> last node active - if (scrollTop + clientHeight >= scrollHeight - 30) { - setActiveIndex(nodes.length - 1); - return; - } - - const containerRect = scrollEl.getBoundingClientRect(); - let bestIdx = 0; - - for (let i = 0; i < nodes.length; i++) { - const node = nodes[i]; - let el = messageRefs.current?.[node.refIndex]; - if (!el) { - el = scrollEl.querySelector(`[data-message-index="${node.messageIndex}"]`) as HTMLDivElement | null; - } - if (!el) continue; - const elRect = el.getBoundingClientRect(); - const relTop = elRect.top - containerRect.top; - if (relTop <= 120) { - bestIdx = i; - } else { - break; - } - } - - setActiveIndex(bestIdx); - }, [scrollContainer, messageRefs, nodes]); - - const updateScrollRef = useRef(updateScroll); - updateScrollRef.current = updateScroll; - - useEffect(() => { - const el = scrollContainer.current; - if (!el) return; - const handleScroll = () => { - if (scrollRafRef.current === null) { - scrollRafRef.current = requestAnimationFrame(() => { - scrollRafRef.current = null; - updateScrollRef.current(); - }); - } - }; - el.addEventListener("scroll", handleScroll, { passive: true }); - return () => { - el.removeEventListener("scroll", handleScroll); - if (scrollRafRef.current !== null) { - cancelAnimationFrame(scrollRafRef.current); - scrollRafRef.current = null; - } - }; - }, [scrollContainer]); - - // Observe resize to update visibility & active node - useEffect(() => { - const el = scrollContainer.current; - if (!el) return; - const ro = new ResizeObserver(() => { - updateScrollRef.current(); - }); - ro.observe(el); - if (el.firstElementChild) ro.observe(el.firstElementChild); - updateScrollRef.current(); - return () => ro.disconnect(); - }, [scrollContainer]); - - // Keep the active row visible after navigation and composer-panel resizes. + // Keep active row visible within the rail when the rail overflows useEffect(() => { const rail = railRef.current; if (!rail) return; @@ -344,7 +135,7 @@ export const ChatMinimap = memo(function ChatMinimap({ messages, scrollContainer window.addEventListener("mousemove", onMove); window.addEventListener("mouseup", onUp); - }, [nodes]); + }, [nodes, setActiveIndex]); // Interrupted drag cleanup on unmount useEffect(() => { diff --git a/components/ChatOutlineFab.test.mjs b/components/ChatOutlineFab.test.mjs new file mode 100644 index 000000000..6dacf21fc --- /dev/null +++ b/components/ChatOutlineFab.test.mjs @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + jsx: { runtime: "automatic" }, + tsconfigPaths: true, +}); +const { ChatOutlineFab } = await jiti.import("./ChatOutlineFab.tsx"); +const { extractPreviewText } = await jiti.import("./ChatMinimap.tsx"); + +test("ChatOutlineFab renders button when messages exist", () => { + const messages = [ + { role: "user", content: "first question" }, + { role: "assistant", content: [{ type: "text", text: "first answer" }] }, + ]; + const scrollContainer = { current: null }; + const messageRefs = { current: [] }; + + const html = renderToStaticMarkup( + React.createElement(ChatOutlineFab, { + messages, + scrollContainer, + messageRefs, + nearBottom: false, + isMobile: true, + }) + ); + + assert.match(html, /chat-outline-fab/); + assert.match(html, /bottom:\s*60px/); // sits above bottom jump button when not nearBottom + assert.match(html, /right:\s*16px/); // mobile right padding +}); + +test("ChatOutlineFab moves down to bottom: 16px when nearBottom is true", () => { + const messages = [ + { role: "user", content: "first question" }, + ]; + const scrollContainer = { current: null }; + const messageRefs = { current: [] }; + + const html = renderToStaticMarkup( + React.createElement(ChatOutlineFab, { + messages, + scrollContainer, + messageRefs, + nearBottom: true, + isMobile: false, + }) + ); + + assert.match(html, /chat-outline-fab/); + assert.match(html, /bottom:\s*16px/); // drops to bottom 16px when nearBottom + assert.match(html, /right:\s*48px/); // desktop right margin +}); + +test("ChatOutlineFab renders nothing when there are no messages", () => { + const scrollContainer = { current: null }; + const messageRefs = { current: [] }; + + const html = renderToStaticMarkup( + React.createElement(ChatOutlineFab, { + messages: [], + scrollContainer, + messageRefs, + nearBottom: true, + isMobile: true, + }) + ); + + assert.equal(html, ""); +}); + +test("extractPreviewText strips injected skill instructions and extracts real user query", () => { + const raw = `[IMPORTANT: User invoked the "donna-brain" skill; follow its instructions. Full skill below.]\n\n# Donna Brain — OKF capture\n\nUser: apa kabar donna?`; + const preview = extractPreviewText({ + role: "user", + content: raw, + }); + assert.equal(preview, "apa kabar donna?"); +}); diff --git a/components/ChatOutlineFab.tsx b/components/ChatOutlineFab.tsx new file mode 100644 index 000000000..c33cbb250 --- /dev/null +++ b/components/ChatOutlineFab.tsx @@ -0,0 +1,287 @@ +"use client"; + +import { memo, useEffect, useRef, useState, type RefObject } from "react"; +import { ListTree, X } from "lucide-react"; +import { useI18n } from "@/lib/i18n"; +import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion"; +import { useChatOutline } from "@/hooks/useChatOutline"; +import type { AgentMessage } from "@/lib/types"; + +interface Props { + messages: AgentMessage[]; + scrollContainer: RefObject; + messageRefs: RefObject<(HTMLDivElement | null)[]>; + nearBottom: boolean; + isMobile: boolean; + onEnsureVisible?: (messageIndex: number, smooth?: boolean) => void; +} + +export const ChatOutlineFab = memo(function ChatOutlineFab({ + messages, + scrollContainer, + messageRefs, + nearBottom, + isMobile, + onEnsureVisible, +}: Props) { + const { t } = useI18n(); + const reducedMotion = usePrefersReducedMotion(); + const [open, setOpen] = useState(false); + const popupRef = useRef(null); + const buttonRef = useRef(null); + + const { nodes, activeIndex, scrollToNode } = useChatOutline({ + messages, + scrollContainer, + messageRefs, + onEnsureVisible, + }); + + // Close on outside click + useEffect(() => { + if (!open) return; + const handlePointerDown = (e: MouseEvent | TouchEvent) => { + const target = e.target as Node | null; + if ( + popupRef.current && + !popupRef.current.contains(target) && + buttonRef.current && + !buttonRef.current.contains(target) + ) { + setOpen(false); + } + }; + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape" && !e.isComposing && e.keyCode !== 229) { + setOpen(false); + buttonRef.current?.focus(); + } + }; + + window.addEventListener("mousedown", handlePointerDown); + window.addEventListener("touchstart", handlePointerDown); + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("mousedown", handlePointerDown); + window.removeEventListener("touchstart", handlePointerDown); + window.removeEventListener("keydown", handleKeyDown); + }; + }, [open]); + + // Scroll active item into view inside popup when opened + useEffect(() => { + if (open && popupRef.current) { + const activeEl = popupRef.current.querySelector(`[data-outline-index="${activeIndex}"]`) as HTMLElement | null; + activeEl?.scrollIntoView({ block: "nearest", behavior: reducedMotion ? "auto" : "smooth" }); + } + }, [open, activeIndex, reducedMotion]); + + // If no turns exist yet, do not render FAB + if (nodes.length === 0) { + return null; + } + + // Dynamic bottom positioning: sits above jump-to-bottom FAB (height 36 + gap 8 = 44px higher) when !nearBottom + const fabBottomPx = nearBottom ? 16 : 60; + const popupBottomPx = nearBottom ? 58 : 102; + const rightPx = isMobile ? 16 : 48; + + const toggleLabel = t("chatOutline.toggleTitle") || "Conversation outline"; + + return ( + <> + {/* Floating Action Button - matching chat-scroll-bottom shape and style */} + + + {/* Floating Outline Popup Panel */} + {open && ( +
+ {/* Header */} +
+
+
+ +
+ + {/* List of prompt chapters */} +
+ {nodes.map((node, i) => { + const isActive = activeIndex === i; + return ( +
{ + scrollToNode(node); + setOpen(false); + }} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + scrollToNode(node); + setOpen(false); + } + }} + style={{ + display: "flex", + alignItems: "flex-start", + gap: 8, + padding: "8px 10px", + borderRadius: "var(--radius-control)", + background: isActive + ? "color-mix(in srgb, var(--accent) 15%, transparent)" + : "transparent", + border: isActive + ? "1px solid color-mix(in srgb, var(--accent) 30%, transparent)" + : "1px solid transparent", + cursor: "pointer", + textAlign: "left", + transition: "background var(--dur-fast), border-color var(--dur-fast)", + }} + > + + #{i + 1} + + + {node.text} + +
+ ); + })} +
+
+ )} + + ); +}); diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 9838cd986..22392d67b 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -13,6 +13,8 @@ import { ChatInput, type ChatInputHandle } from "./ChatInput"; import { ExtensionDialog } from "./ExtensionDialog"; import { SubagentTranscriptDialog } from "./SubagentTranscriptDialog"; import { ChatMinimap, useMessageRefs } from "./ChatMinimap"; +import { ChatOutlineFab } from "./ChatOutlineFab"; +import { useChatMinimapPreference } from "@/hooks/useChatMinimapPreference"; import { ComposerPanels } from "./ComposerPanels"; import { SkillDiagnosticsNotice } from "./SkillDiagnostics"; import { BtwHistoryDialog, type BtwPanelProps } from "./BtwPanel"; @@ -518,6 +520,9 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu : undefined, [onOpenWorkspaceFile, fileSource]); const { playDoneSound, unlockAudio } = useAudio(); const isMobile = useIsMobile(); + const { desktopMode: minimapDesktopMode, mobileFab: minimapMobileFab } = useChatMinimapPreference(); + const showDesktopRail = !isMobile && minimapDesktopMode === "rail"; + const showOutlineFab = isMobile ? minimapMobileFab : minimapDesktopMode === "fab"; const internalChatInputRef = useRef(null); const composerRef = chatInputRef ?? internalChatInputRef; const [composerIdentityMove, setComposerIdentityMove] = useState<{ from: string; to: string; sourceDraft?: ChatDraft }>(); @@ -871,6 +876,60 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu loadMoreModeRef.current = "click"; setVisibleCount((prev) => getNextVisibleCount(prev)); }, [scrollContainerRef]); + const transcriptRows = useMemo( + () => planTranscriptRows(messages, { hideThinking: hideThinkingBlock }), + [messages, hideThinkingBlock] + ); + + const pendingScrollTargetRef = useRef<{ index: number; smooth: boolean } | null>(null); + + const handleEnsureMessageVisible = useCallback((messageIndex: number, smooth = true) => { + const targetRowIdx = transcriptRows.findIndex((row) => + row.kind === "message" + ? row.index === messageIndex + : row.userIndex <= messageIndex && messageIndex < row.endIndex + ); + + if (targetRowIdx >= 0) { + const neededFromEnd = transcriptRows.length - targetRowIdx + 15; + if (neededFromEnd > visibleCount) { + pendingScrollTargetRef.current = { index: messageIndex, smooth }; + setVisibleCount(neededFromEnd); + return; + } + } + + const container = scrollContainerRef.current; + if (!container) return; + const targetEl = container.querySelector(`[data-message-index="${messageIndex}"]`) as HTMLDivElement | null; + if (targetEl) { + const containerRect = container.getBoundingClientRect(); + const elRect = targetEl.getBoundingClientRect(); + const targetScroll = Math.max(0, container.scrollTop + (elRect.top - containerRect.top) - 16); + const reduceMotion = typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + container.scrollTo({ top: targetScroll, behavior: smooth && !reduceMotion ? "smooth" : "auto" }); + } + }, [transcriptRows, visibleCount, scrollContainerRef]); + + useEffect(() => { + const pending = pendingScrollTargetRef.current; + if (pending === null) return; + const { index: targetIdx, smooth } = pending; + const container = scrollContainerRef.current; + if (!container) return; + + requestAnimationFrame(() => { + const targetEl = container.querySelector(`[data-message-index="${targetIdx}"]`) as HTMLDivElement | null; + if (targetEl) { + pendingScrollTargetRef.current = null; + const containerRect = container.getBoundingClientRect(); + const elRect = targetEl.getBoundingClientRect(); + const targetScroll = Math.max(0, container.scrollTop + (elRect.top - containerRect.top) - 16); + const reduceMotion = typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + container.scrollTo({ top: targetScroll, behavior: smooth && !reduceMotion ? "smooth" : "auto" }); + } + }); + }, [visibleCount, scrollContainerRef]); const generationSpeedKey = generationSpeed ? `${generationSpeed.current ?? "null"}|${generationSpeed.average ?? "null"}` @@ -1352,16 +1411,16 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu pointerEvents: "none", }} > -
+
{/* Hide the Firefox scrollbar on desktop only: ChatMinimap provides the position indicator there, but on mobile there is no minimap and users need the scrollbar (Chrome's overlay scrollbar still shows). */} -
+
-
+
{error && ( @@ -1504,12 +1563,23 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu
+ + + + + +