Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
239 changes: 15 additions & 224 deletions components/ChatMinimap.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLDivElement | null>;
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<AgentMessage>): 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;
}

/**
Expand Down Expand Up @@ -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<number | null>(null);
const [isRailHovered, setIsRailHovered] = useState(false);
const [railScrollTop, setRailScrollTop] = useState(0);
const railRef = useRef<HTMLDivElement>(null);
const draggingRef = useRef(false);
const scrollRafRef = useRef<number | null>(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;
Expand Down Expand Up @@ -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(() => {
Expand Down
83 changes: 83 additions & 0 deletions components/ChatOutlineFab.test.mjs
Original file line number Diff line number Diff line change
@@ -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?");
});
Loading
Loading