Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧗 feat: Light the Fold Path to the Hovered Activity Row (#16722)
Danny Avila3dd0d06796bf
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsxindex 0962d5db9b..c183f17432 100644--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx@@ -20,7 +20,14 @@ import {LIVE_ACTIVITY_THROTTLE_MS,LIVE_REASONING_HOLD_MS,} from './live';-import { FoldRail, RailGlyph, FoldHeaderContext, revealFoldHeader, useRailHover } from './rail';+import {+ FoldRail,+ RailGlyph,+ useFoldPath,+ useRailHover,+ revealFoldHeader,+ FoldHeaderContext,+} from './rail';import { FailedRevealContext, FailedRevealPill, useFailedRevealTrigger } from './reveal';import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';@@ -625,6 +632,7 @@ export default function ActivityPhaseGroup({isExpanded,hasPendingApproval,);+ useFoldPath(rootRef, shouldRenderBody);const { value: revealValue, requestReveal } = useFailedRevealTrigger(isExpanded && shouldRenderBody,);@@ -811,7 +819,12 @@ export default function ActivityPhaseGroup({* groups it stands for, so it carries the same geometry: 16px glyph, 8px* gap, no inset. Boxing it was what put its text on a third left edge and* forced every folded row 13px sideways as the box materialized. */- <div className="mt-1 mb-2 w-full" ref={rootRef} data-testid="activity-phase-card">+ <div+ className="mt-1 mb-2 w-full"+ ref={rootRef}+ data-testid="activity-phase-card"+ data-fold-root=""+ ><span className="sr-only" role="status" data-testid="activity-phase-announcer">{announcement}</span>@@ -895,7 +908,11 @@ export default function ActivityPhaseGroup({data-testid="activity-phase-panel">{shouldRenderBody && (- <div className={cn('overflow-hidden', FOLD_RAIL_CLASSES)} ref={expandRef}>+ <div+ className={cn('overflow-hidden', FOLD_RAIL_CLASSES)}+ ref={expandRef}+ data-fold-panel=""+ ><FoldRail hover={railHover} expanded={isExpanded} onCollapse={handleRailCollapse} /><FoldHeaderContext.Provider value={railScope}><FailedRevealContext.Provider value={revealValue}>diff --git a/client/src/components/Chat/Messages/Content/ParallelContent.tsx b/client/src/components/Chat/Messages/Content/ParallelContent.tsxindex 5a156db3d8..f438b72850 100644--- a/client/src/components/Chat/Messages/Content/ParallelContent.tsx+++ b/client/src/components/Chat/Messages/Content/ParallelContent.tsx@@ -217,7 +217,8 @@ export const ParallelColumns = memo(function ParallelColumns({return (<divkey={`column-${messageId}-${groupId}-${agentId || colIdx}`}- className="min-w-0 flex-1 rounded-lg border border-border-light p-3"+ data-fold-column=""+ className="border-border-light min-w-0 flex-1 rounded-lg border p-3"><SiblingHeaderagentId={agentId}diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsxindex 06626817aa..02b2eb4418 100644--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx@@ -29,6 +29,7 @@ import { AttachmentGroup } from './Attachment';import { useToolCallIntent } from './intent';import { useFailedReveal } from '../reveal';import { cn, parseToolName } from '~/utils';+import { FOLD_GLYPH_CLASS } from '../rows';import { useLocalize } from '~/hooks';interface SubagentCallProps {@@ -414,6 +415,7 @@ export default function SubagentCall({<div className="text-text-primary flex items-center gap-2 text-sm font-medium"><divclassName={cn(+ FOLD_GLYPH_CLASS,'flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full',running && !subagentAgent && 'text-text-primary animate-pulse',)}diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsxindex 51f42d3772..9ab4124e92 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx@@ -25,6 +25,8 @@ import SubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall';import { MessageContext } from '~/Providers/MessageContext';import { FailedRevealContext } from '../../reveal';import { ChatSurfaceHarness } from 'test/harness';+import { FOLD_GLYPH_SELECTOR } from '../../rows';+import { litFoldPath } from '../../rail';const mockMCPServerNames: string[] = [];@@ -192,6 +194,35 @@ const event = (});describe('SubagentCall', () => {+ it('registers its existing header glyph for both containing fold rails', () => {+ renderWithState({ toolCallId: 'fold-glyph', initialProgress: 1 });+ const row = screen.getByRole('button', { name: 'Ran agent' }).cloneNode(true) as HTMLElement;+ const glyph = row.querySelector<HTMLElement>(FOLD_GLYPH_SELECTOR);+ expect(glyph).not.toBeNull();+ expect(glyph).toHaveClass('h-5', 'w-5');+ expect(glyph).not.toHaveClass('min-w-6');+ glyph!.getBoundingClientRect = () => ({ top: 150, height: 20 }) as DOMRect;+ const root = document.createElement('div');+ let parent = root;+ const rails: HTMLElement[] = [];+ for (const top of [40, 104]) {+ const panel = document.createElement('div');+ panel.setAttribute('data-fold-panel', '');+ const rail = document.createElement('button');+ rail.setAttribute('data-fold-rail', '');+ rail.getBoundingClientRect = () => ({ top }) as DOMRect;+ panel.append(rail);+ parent.append(panel);+ parent = panel;+ rails.push(rail);+ }+ parent.append(row);+ expect(litFoldPath(root, row, 155)).toEqual([+ { rail: rails[1], length: 54, end: true },+ { rail: rails[0], length: 118, end: false },+ ]);+ });+it('keeps the configured name and avatar after live progress is cleared', () => {const { setProgress } = renderWithState({toolCallId: 'identity',diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsxindex f21405de25..b28f2800e2 100644--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx@@ -14,6 +14,14 @@ import {getBatchActivityLabelPart,getActivityLabelText,} from '~/utils';+import {+ FoldRail,+ RailGlyph,+ useFoldPath,+ useRailHover,+ revealFoldHeader,+ FoldHeaderContext,+} from './rail';import {FailedRevealContext,FailedRevealPill,@@ -21,7 +29,6 @@ import {useFailedRevealTrigger,} from './reveal';import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';-import { FoldRail, RailGlyph, FoldHeaderContext, revealFoldHeader, useRailHover } from './rail';import { ASK_USER_QUESTION, getSubmittedAskAnswer } from '~/utils/approval';import { ToolAuthWarning, ToolAuthWarningContext } from './auth';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';@@ -312,6 +319,7 @@ export default function ToolCallGroup({);const [userOverride, setUserOverride] = useState(initialState != null);const [shouldRenderBody, setShouldRenderBody] = useState(isExpanded);+ useFoldPath(rootRef, shouldRenderBody);const previousIsExpandedRef = useRef(isExpanded);const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);const notifyLayoutChange = useCallback(() => {@@ -554,7 +562,7 @@ export default function ToolCallGroup({}, [hasActiveToolCall, userOverride, suppressAutoExpand]);return (- <div className="mt-1 mb-2" ref={rootRef}>+ <div className="mt-1 mb-2" ref={rootRef} data-fold-root=""><div className="flex w-full items-center gap-2" ref={headerRef}><buttontype="button"@@ -636,7 +644,11 @@ export default function ToolCallGroup({data-testid="tool-call-group-panel">{shouldRenderBody && (- <div className={cn('overflow-hidden', FOLD_RAIL_CLASSES)} ref={expandRef}>+ <div+ className={cn('overflow-hidden', FOLD_RAIL_CLASSES)}+ ref={expandRef}+ data-fold-panel=""+ ><FoldRailhover={railHover}expanded={isExpanded && (phaseHeader?.expanded ?? true)}diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsxindex b69f846547..b063139687 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx@@ -5,7 +5,10 @@ import { act, fireEvent, render, screen, within } from '@testing-library/react';import type { EventSubmission, TAttachment, TMessageContentParts } from 'librechat-data-provider';import useAttachmentHandler from '~/hooks/SSE/useAttachmentHandler';import useAttachments from '~/hooks/Messages/useAttachments';+import { ParallelColumns } from '../ParallelContent';import ContentParts from '../ContentParts';+import { FOLD_GLYPH_CLASS } from '../rows';+import { litFoldPath } from '../rail';import { Text } from '../Parts';jest.mock('~/hooks', () => ({@@ -2221,3 +2224,52 @@ describe('ContentParts — live activity fold', () => {);});});++describe('fold paths in parallel columns', () => {+ it('marks real lane boundaries and selects the header owning each output', () => {+ const { container } = render(+ <div data-fold-root="">+ <div data-fold-panel="">+ <button type="button" tabIndex={-1} aria-hidden="true" data-fold-rail="" />+ <ParallelColumns+ columns={[+ {+ agentId: 'left',+ parts: [{ idx: 0, part: { type: ContentTypes.TEXT, text: 'left' } }],+ },+ {+ agentId: 'right',+ parts: [{ idx: 1, part: { type: ContentTypes.TEXT, text: 'right' } }],+ },+ ]}+ groupId={1}+ messageId="parallel-fold"+ isSubmitting={false}+ lastContentIdx={1}+ renderPart={(_part, idx) => (+ <div key={idx}>+ <span className={FOLD_GLYPH_CLASS} data-testid={`lane-glyph-${idx}`} />+ <pre data-testid={`lane-output-${idx}`} />+ </div>+ )}+ />+ </div>+ </div>,+ );+ expect(container.querySelectorAll('[data-fold-column]')).toHaveLength(2);+ const root = container.querySelector('[data-fold-root]')!;+ const rail = container.querySelector<HTMLElement>('[data-fold-rail]')!;+ rail.getBoundingClientRect = () => ({ top: 40 }) as DOMRect;+ screen.getByTestId('lane-glyph-0').getBoundingClientRect = () =>+ ({ top: 300, height: 20 }) as DOMRect;+ screen.getByTestId('lane-glyph-1').getBoundingClientRect = () =>+ ({ top: 50, height: 20 }) as DOMRect;+ const cache = new WeakMap<Element, Element[]>();+ expect(litFoldPath(root, screen.getByTestId('lane-output-0'), 350, cache)).toEqual([+ { rail, length: 268, end: true },+ ]);+ expect(litFoldPath(root, screen.getByTestId('lane-output-1'), 350, cache)).toEqual([+ { rail, length: 18, end: true },+ ]);+ });+});diff --git a/client/src/components/Chat/Messages/Content/__tests__/rail.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/rail.test.tsxindex ccf3930ff3..0b10ff77b2 100644--- a/client/src/components/Chat/Messages/Content/__tests__/rail.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/rail.test.tsx@@ -1,6 +1,13 @@import React from 'react';import { render, renderHook, screen, fireEvent } from '@testing-library/react';-import { FoldRail, RailGlyph, revealFoldHeader, useRailHover } from '../rail';+import {+ FoldRail,+ RailGlyph,+ useFoldPath,+ litFoldPath,+ useRailHover,+ revealFoldHeader,+} from '../rail';function box(top: number, height = 28) {const el = document.createElement('div');@@ -128,3 +135,443 @@ describe('FoldRail', () => {expect(screen.getByTestId('fold-rail')).toBeDisabled();});});++/**+ * Two folds, one inside the other, laid out on a 32px row pitch:+ *+ * phase header glyph 10+ * panel A top 40+ * row glyph 50+ * group header glyph 82+ * panel B top 104+ * row glyph 114+ * row glyph 146+ * row glyph 178+ * row glyph 220+ */+function foldFixture() {+ const at = <T extends HTMLElement>(el: T, top: number, height = 20): T => {+ el.getBoundingClientRect = () => ({ top, height, bottom: top + height }) as DOMRect;+ return el;+ };+ const glyph = (top: number) => {+ const el = at(document.createElement('span'), top);+ el.className = 'fold-glyph';+ return el;+ };+ const panel = (top: number) => {+ const el = at(document.createElement('div'), top, 0);+ el.setAttribute('data-fold-panel', '');+ const rail = at(document.createElement('button'), top, 0);+ rail.setAttribute('data-fold-rail', '');+ el.append(rail);+ return { el, rail };+ };+ const root = document.createElement('div');+ root.setAttribute('data-fold-root', '');+ const outerHeader = glyph(10);+ const a = panel(40);+ const b = panel(104);+ const rows = {+ a1: glyph(50),+ header: glyph(82),+ b1: glyph(114),+ b2: glyph(146),+ b3: glyph(178),+ a2: glyph(220),+ };+ const group = document.createElement('div');+ group.append(rows.header, b.el);+ b.el.append(rows.b1, rows.b2, rows.b3);+ a.el.append(rows.a1, group, rows.a2);+ root.append(outerHeader, a.el);+ document.body.append(root);+ return { root, outerHeader, a, b, rows };+}++describe('litFoldPath', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('lights every fold that holds the row, innermost first, down to its center', () => {+ const { root, a, b, rows } = foldFixture();+ expect(litFoldPath(root, rows.b2, 150)).toEqual([+ { rail: b.rail, length: 156 - 104 - 2, end: true },+ { rail: a.rail, length: 156 - 40 - 2, end: false },+ ]);+ });++ it('ends a nested header at the fold that holds it', () => {+ const { root, a, rows } = foldFixture();+ expect(litFoldPath(root, rows.header, 90)).toEqual([+ { rail: a.rail, length: 92 - 40 - 2, end: true },+ ]);+ });++ it('counts the margin above a glyph as that row', () => {+ const { root, b, rows } = foldFixture();+ expect(litFoldPath(root, rows.b2, 141)[0]).toEqual({ rail: b.rail, length: 50, end: true });+ });++ it('points at the row above when the pointer is inside an open body', () => {+ const { root, b } = foldFixture();+ const body = document.createElement('pre');+ b.el.append(body);+ expect(litFoldPath(root, body, 205)[0]).toEqual({+ rail: b.rail,+ length: 188 - 104 - 2,+ end: true,+ });+ });++ it('searches only the hovered column when document order is not vertical order', () => {+ const { root, a, rows } = foldFixture();+ const left = document.createElement('div');+ const right = document.createElement('div');+ left.setAttribute('data-fold-column', '');+ right.setAttribute('data-fold-column', '');+ left.append(rows.a1, rows.a2);+ right.append(rows.header);+ a.el.replaceChildren(a.rail, left, right);+ const body = document.createElement('pre');+ left.append(body);+ const cache = new WeakMap<Element, Element[]>();+ expect(litFoldPath(root, rows.a2, 225, cache)).toEqual([+ { rail: a.rail, length: 188, end: true },+ ]);+ expect(litFoldPath(root, body, 260, cache)[0].length).toBe(188);+ expect(litFoldPath(root, rows.header, 90, cache)[0].length).toBe(50);+ expect(litFoldPath(root, a.el, 225, cache)).toEqual([]);+ });++ it('excludes nested columns but keeps a nested panel in its surrounding column', () => {+ const { root, a, b, rows } = foldFixture();+ const column = document.createElement('div');+ const nested = document.createElement('div');+ column.setAttribute('data-fold-column', '');+ nested.setAttribute('data-fold-column', '');+ nested.append(rows.b1);+ column.append(rows.a1, rows.a2, nested, b.el);+ a.el.replaceChildren(a.rail, column);+ expect(litFoldPath(root, rows.a2, 225)[0].length).toBe(188);+ expect(litFoldPath(root, rows.b1, 120)[0].length).toBe(82);+ expect(litFoldPath(root, rows.b2, 150)).toEqual([+ { rail: b.rail, length: 50, end: true },+ { rail: a.rail, length: 114, end: false },+ ]);+ });++ it('leaves the rails and the outermost header alone', () => {+ const { root, b, outerHeader } = foldFixture();+ expect(litFoldPath(root, b.rail, 150)).toEqual([]);+ expect(litFoldPath(root, outerHeader, 15)).toEqual([]);+ });+});++describe('useFoldPath', () => {+ let frames: FrameRequestCallback[] = [];+ let resize: ResizeObserverCallback;+ const observe = jest.fn();+ const disconnect = jest.fn();+ const flushFrames = () => {+ const pending = frames;+ frames = [];+ pending.forEach((callback) => callback(0));+ };+ /** Moves are coalesced into the next frame, as a browser would run them. */+ const pointer = (+ type: string,+ target: Element,+ clientY: number,+ pointerType = 'mouse',+ flush = true,+ ) => {+ const event = new Event(type, { bubbles: type !== 'pointerleave' });+ Object.assign(event, { clientX: 100, clientY, pointerType });+ target.dispatchEvent(event);+ if (flush) {+ flushFrames();+ }+ };++ beforeEach(() => {+ frames = [];+ jest.spyOn(window, 'ResizeObserver').mockImplementation((callback) => {+ resize = callback;+ return { observe, unobserve: jest.fn(), disconnect };+ });+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {+ frames.push(callback);+ return frames.length;+ });+ jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {+ frames = [];+ });+ });++ afterEach(() => {+ jest.restoreAllMocks();+ document.body.innerHTML = '';+ });++ it('paints the path onto the rails and clears it when the pointer leaves', () => {+ const { root, a, b, rows } = foldFixture();+ const { unmount } = renderHook(() => useFoldPath({ current: root }, true));++ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBe('end');+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('50px');+ expect(a.rail.dataset.foldLit).toBe('through');+ expect(a.rail.style.getPropertyValue('--fold-lit')).toBe('114px');++ pointer('pointermove', rows.a2, 225);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('');+ expect(a.rail.dataset.foldLit).toBe('end');++ pointer('pointerleave', root, 0);+ expect(a.rail.dataset.foldLit).toBeUndefined();+ unmount();+ });++ it('follows no touch, and drops the path on a press that may move the rows', () => {+ const { root, a, rows } = foldFixture();+ renderHook(() => useFoldPath({ current: root }, true));++ pointer('pointermove', rows.a1, 55, 'touch');+ expect(a.rail.dataset.foldLit).toBeUndefined();++ pointer('pointermove', rows.a1, 55);+ expect(a.rail.dataset.foldLit).toBe('end');+ pointer('pointerdown', rows.a1, 55);+ expect(a.rail.dataset.foldLit).toBeUndefined();+ });++ it('cancels a queued paint when the pointer presses before the frame', () => {+ const { root, a, b, rows } = foldFixture();+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150, 'mouse', false);+ expect(frames).toHaveLength(1);+ pointer('pointerdown', rows.b2, 150);+ expect(window.cancelAnimationFrame).toHaveBeenCalledWith(1);+ expect(frames).toHaveLength(0);+ expect(a.rail.dataset.foldLit).toBeUndefined();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ });++ it('reuses the panel glyph list across pointer frames', async () => {+ const { root, b, rows } = foldFixture();+ const query = jest.spyOn(b.el, 'querySelectorAll');+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b1, 120);+ await Promise.resolve();+ expect(b.rail.dataset.foldLit).toBe('end');+ pointer('pointermove', rows.b2, 150);+ pointer('pointermove', rows.b3, 180);+ expect(query).toHaveBeenCalledTimes(1);+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('82px');+ });++ it('clears on streamed text changes without relighting a queued frame', async () => {+ const { root, b, rows } = foldFixture();+ rows.b1.append(document.createTextNode('output'));+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ await Promise.resolve();+ pointer('pointermove', rows.b2, 150, 'mouse', false);+ rows.b1.firstChild!.textContent = 'growing output';+ await Promise.resolve();+ flushFrames();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('');+ });++ it('rebuilds cached glyphs after rows are inserted or removed', async () => {+ const { root, b, rows } = foldFixture();+ const query = jest.spyOn(b.el, 'querySelectorAll');+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b1, 120);+ const added = rows.b2.cloneNode() as HTMLElement;+ added.getBoundingClientRect = () => ({ top: 210, height: 20 }) as DOMRect;+ b.el.append(added);+ await Promise.resolve();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ pointer('pointermove', added, 215);+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('114px');+ added.remove();+ await Promise.resolve();+ pointer('pointermove', rows.b3, 180);+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('82px');+ expect(query).toHaveBeenCalledTimes(3);+ });++ it.each(['class', 'style', 'hidden', 'open'])(+ 'clears on a disclosure %s change',+ async (attribute) => {+ const { root, b, rows } = foldFixture();+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ rows.b1.setAttribute(attribute, 'changed');+ await Promise.resolve();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ },+ );++ it('clears when resizing or scrolling moves the hovered row', () => {+ const { root, b, rows } = foldFixture();+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ resize([], {} as ResizeObserver);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ pointer('pointermove', rows.b2, 150);+ root.dispatchEvent(new Event('scroll'));+ expect(b.rail.dataset.foldLit).toBeUndefined();+ pointer('pointermove', rows.b2, 150);+ window.dispatchEvent(new Event('resize'));+ expect(b.rail.dataset.foldLit).toBeUndefined();+ });++ it.each([false, true])(+ 'clears after a preceding message shifts the fold, with a queued paint=%s',+ (queued) => {+ const { root, a, b, rows } = foldFixture();+ const transcript = document.createElement('div');+ const previous = document.createElement('div');+ const message = document.createElement('div');+ message.className = 'message-render';+ message.append(root);+ transcript.append(previous, message);+ document.body.append(transcript);+ let offset = 0;+ root.getBoundingClientRect = message.getBoundingClientRect = () =>+ ({ top: offset, height: 250 }) as DOMRect;+ for (const element of [a.rail, b.rail, ...Object.values(rows)]) {+ const rect = element.getBoundingClientRect();+ element.getBoundingClientRect = () => ({ ...rect, top: rect.top + offset });+ }+ const query = jest.spyOn(b.el, 'querySelectorAll');+ const { unmount } = renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBe('end');+ if (queued) {+ pointer('pointermove', rows.b2, 150, 'mouse', false);+ }+ offset = 32;+ if (observe.mock.calls.some(([element]) => element === transcript)) {+ resize([], {} as ResizeObserver);+ }+ flushFrames();+ expect(root.getBoundingClientRect()).toMatchObject({ top: 32, height: 250 });+ expect(message.getBoundingClientRect()).toMatchObject({ top: 32, height: 250 });+ expect(a.rail.dataset.foldLit).toBeUndefined();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ expect(a.rail.style.getPropertyValue('--fold-lit')).toBe('');+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('');+ pointer('pointermove', rows.b1, 150);+ expect(b.rail.dataset.foldLit).toBe('end');+ expect(b.rail.style.getPropertyValue('--fold-lit')).toBe('18px');+ expect(query).toHaveBeenCalledTimes(1);+ unmount();+ expect(disconnect).toHaveBeenCalledTimes(1);+ },+ );++ it('re-hit-tests one queued paint after scrolling instead of discarding a fresh move', () => {+ const { root, a, b, rows } = foldFixture();+ rows.a2.getBoundingClientRect = () => ({ top: 140, height: 20 }) as DOMRect;+ const hit = jest.fn(() => rows.a2);+ Object.defineProperty(document, 'elementFromPoint', { configurable: true, value: hit });+ try {+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150, 'mouse', false);+ root.dispatchEvent(new Event('scroll'));+ root.dispatchEvent(new Event('scroll'));+ expect(frames).toHaveLength(1);+ expect(hit).not.toHaveBeenCalled();+ flushFrames();+ expect(hit).toHaveBeenCalledTimes(1);+ expect(hit).toHaveBeenCalledWith(100, 150);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ expect(a.rail.dataset.foldLit).toBe('end');+ expect(a.rail.style.getPropertyValue('--fold-lit')).toBe('108px');+ } finally {+ Reflect.deleteProperty(document, 'elementFromPoint');+ }+ });++ it.each([null, document.body])(+ 'clears a queued path when scrolling moves the pointer outside the fold (%p)',+ (target) => {+ const { root, a, b, rows } = foldFixture();+ Object.defineProperty(document, 'elementFromPoint', {+ configurable: true,+ value: jest.fn(() => target),+ });+ try {+ renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ pointer('pointermove', rows.b3, 180, 'mouse', false);+ root.dispatchEvent(new Event('scroll'));+ flushFrames();+ expect(a.rail.dataset.foldLit).toBeUndefined();+ expect(b.rail.dataset.foldLit).toBeUndefined();+ } finally {+ Reflect.deleteProperty(document, 'elementFromPoint');+ }+ },+ );++ it('disconnects observers and cancels pending work on unmount', async () => {+ const { root, b, rows } = foldFixture();+ const { unmount } = renderHook(() => useFoldPath({ current: root }, true));+ pointer('pointermove', rows.b2, 150);+ pointer('pointermove', rows.b3, 180, 'mouse', false);+ unmount();+ expect(disconnect).toHaveBeenCalledTimes(1);+ expect(frames).toHaveLength(0);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ rows.b1.remove();+ await Promise.resolve();+ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ });++ it('leaves a fold nested in another to the outer one', () => {+ const { root, b, rows } = foldFixture();+ const inner = document.createElement('div');+ inner.setAttribute('data-fold-root', '');+ root.append(inner);+ renderHook(() => useFoldPath({ current: inner }, true));++ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBeUndefined();+ });++ it('waits for the panel before listening', () => {+ const { root, b, rows } = foldFixture();+ const { rerender } = renderHook(({ hasBody }) => useFoldPath({ current: root }, hasBody), {+ initialProps: { hasBody: false },+ });+ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBeUndefined();++ rerender({ hasBody: true });+ pointer('pointermove', rows.b2, 150);+ expect(b.rail.dataset.foldLit).toBe('end');+ });+});++describe('FoldRail path segment', () => {+ it('draws the lit path inside the rail, hidden from assistive tech', () => {+ function Rail() {+ const hover = useRailHover();+ return <FoldRail hover={hover} expanded onCollapse={jest.fn()} />;+ }+ render(<Rail />);+ const rail = screen.getByTestId('fold-rail');+ expect(rail).toHaveAttribute('data-fold-rail');+ expect(rail).toHaveAttribute('aria-hidden', 'true');+ expect(rail).toContainElement(screen.getByTestId('fold-rail-path'));+ });+});diff --git a/client/src/components/Chat/Messages/Content/rail.tsx b/client/src/components/Chat/Messages/Content/rail.tsxindex 59d2e3e146..ff58e068a7 100644--- a/client/src/components/Chat/Messages/Content/rail.tsx+++ b/client/src/components/Chat/Messages/Content/rail.tsx@@ -1,7 +1,7 @@import { createContext, useEffect, useState, useSyncExternalStore } from 'react';import { CircleMinus } from 'lucide-react';import type { ReactNode, RefObject } from 'react';-import { ROW_GLYPH_SLOT } from './rows';+import { ROW_GLYPH_SLOT, FOLD_GLYPH_SELECTOR } from './rows';import { cn } from '~/utils';/**@@ -103,12 +103,240 @@ export function FoldRail({onCollapse();}}data-testid="fold-rail"+ data-fold-rail=""><span className="bg-border-medium group-hover/rail:bg-text-secondary absolute top-0.5 bottom-1.5 left-[11px] w-px transition-colors duration-150 motion-reduce:transition-none" />+ {/* The lit path (`useFoldPath`): from the header down to the hovered row, turning+ into that row when it is this fold's own. */}+ <span+ className="border-text-secondary pointer-events-none absolute top-0.5 left-[11px] h-(--fold-lit) border-l opacity-0 transition-opacity duration-150 group-data-fold-lit/rail:opacity-100 group-data-[fold-lit=end]/rail:w-2 group-data-[fold-lit=end]/rail:rounded-bl-md group-data-[fold-lit=end]/rail:border-b motion-reduce:transition-none"+ data-testid="fold-rail-path"+ /></button>);}+const FOLD_PANEL = '[data-fold-panel]';+const FOLD_RAIL = '[data-fold-rail]';+const FOLD_ROOT = '[data-fold-root]';+const FOLD_COLUMN = '[data-fold-column]';+/** A row's glyph is 20px tall inside a 32px line, so the pointer is on that row from+ * the margin above the glyph down to the next row's margin. */+const ROW_REACH = 6;++export type LitRail = { rail: HTMLElement; length: number; end: boolean };++/** The glyph at `y` in one panel or column, or the nearest above an open body.+ * Within that scope, document order is vertical order. */+function glyphAt(+ panel: Element,+ scope: Element,+ y: number,+ glyphsByPanel: WeakMap<Element, Element[]>,+): Element | null {+ let glyphs = glyphsByPanel.get(scope);+ if (glyphs == null) {+ glyphs = [];+ for (const glyph of scope.querySelectorAll(FOLD_GLYPH_SELECTOR)) {+ const column = glyph.closest(FOLD_COLUMN);+ const glyphScope = column != null && panel.contains(column) ? column : panel;+ if (glyph.closest(FOLD_PANEL) === panel && glyphScope === scope) {+ glyphs.push(glyph);+ }+ }+ glyphsByPanel.set(scope, glyphs);+ }+ let found: Element | null = null;+ let low = 0;+ let high = glyphs.length - 1;+ while (low <= high) {+ const mid = (low + high) >> 1;+ if (glyphs[mid].getBoundingClientRect().top - ROW_REACH <= y) {+ found = glyphs[mid];+ low = mid + 1;+ } else {+ high = mid - 1;+ }+ }+ return found;+}++/**+ * The rails to light for a pointer at `y` over `target`: one per fold that holds the+ * row under it, innermost first, each `length` px from its top to that row's center.+ * Empty over a rail itself, whose own hover shows what it collapses, and over any+ * header that no fold of `root` holds.+ */+export function litFoldPath(+ root: Element,+ target: Element,+ y: number,+ glyphsByPanel = new WeakMap<Element, Element[]>(),+): LitRail[] {+ if (target.closest(FOLD_RAIL) != null) {+ return [];+ }+ const innermost = target.closest(FOLD_PANEL);+ if (innermost == null || !root.contains(innermost)) {+ return [];+ }+ const column = target.closest(FOLD_COLUMN);+ const scope = column != null && innermost.contains(column) ? column : innermost;+ const glyph = glyphAt(innermost, scope, y, glyphsByPanel);+ if (glyph == null) {+ return [];+ }+ const { top, height } = glyph.getBoundingClientRect();+ const center = top + height / 2;+ const path: LitRail[] = [];+ let panel: Element | null = innermost;+ while (panel != null && root.contains(panel)) {+ const rail = panel.querySelector<HTMLElement>(`:scope > ${FOLD_RAIL}`);+ if (rail != null) {+ /** The path starts where the rail's own line does, 2px below the panel. */+ const length = Math.round(center - rail.getBoundingClientRect().top) - 2;+ path.push({ rail, length: Math.max(length, 0), end: path.length === 0 });+ }+ panel = panel.parentElement?.closest(FOLD_PANEL) ?? null;+ }+ return path;+}++function paintFoldPath(previous: LitRail[], next: LitRail[]) {+ for (const { rail } of previous) {+ if (!next.some((lit) => lit.rail === rail)) {+ delete rail.dataset.foldLit;+ rail.style.removeProperty('--fold-lit');+ }+ }+ for (const { rail, length, end } of next) {+ const kind = end ? 'end' : 'through';+ if (rail.dataset.foldLit !== kind) {+ rail.dataset.foldLit = kind;+ }+ const value = `${length}px`;+ if (rail.style.getPropertyValue('--fold-lit') !== value) {+ rail.style.setProperty('--fold-lit', value);+ }+ }+}++/**+ * Lights the path from every fold that holds the hovered row down to that row, so its+ * depth reads as the number of lit rails. One listener on the outermost fold, and the+ * rails are written to directly: moving the pointer repaints rails, never rows. A fold+ * nested in another leaves the work to that one. `hasBody` re-arms it once the fold's+ * panel, and with it the root, has rendered.+ */+export function useFoldPath(rootRef: RefObject<HTMLElement>, hasBody: boolean) {+ useEffect(() => {+ const root = rootRef.current;+ if (!hasBody || root == null || root.parentElement?.closest(FOLD_ROOT) != null) {+ return;+ }+ let glyphsByPanel = new WeakMap<Element, Element[]>();+ let lit: LitRail[] = [];+ let frame = 0;+ let rehit = false;+ let pointer: { target: Element; x: number; y: number } | null = null;+ const paint = () => {+ frame = 0;+ if (pointer == null) {+ return;+ }+ const target = rehit ? document.elementFromPoint(pointer.x, pointer.y) : pointer.target;+ rehit = false;+ if (target == null || !root.contains(target)) {+ clear();+ return;+ }+ const next = litFoldPath(root, target, pointer.y, glyphsByPanel);+ paintFoldPath(lit, next);+ lit = next;+ };+ const clear = () => {+ pointer = null;+ rehit = false;+ cancelAnimationFrame(frame);+ frame = 0;+ paintFoldPath(lit, []);+ lit = [];+ };+ const onMove = (event: PointerEvent) => {+ /** A tap has no hover to follow, and would leave the path lit under the finger. */+ if (event.pointerType === 'touch' || !(event.target instanceof Element)) {+ return;+ }+ pointer = { target: event.target, x: event.clientX, y: event.clientY };+ if (frame === 0) {+ frame = requestAnimationFrame(paint);+ }+ };+ const onScroll = () => {+ /** Scroll events can arrive after a fresh move but before its queued paint. */+ if (frame !== 0) {+ rehit = true;+ return;+ }+ clear();+ };+ const mutations = new MutationObserver((records) => {+ let changed = false;+ let structureChanged = false;+ for (const record of records) {+ /** Painting the rail's own style does not change row geometry. */+ if (+ record.type === 'attributes' &&+ record.attributeName === 'style' &&+ record.target instanceof Element &&+ record.target.matches(FOLD_RAIL)+ ) {+ continue;+ }+ changed = true;+ structureChanged ||= record.type === 'childList' || record.type === 'attributes';+ }+ if (structureChanged) {+ glyphsByPanel = new WeakMap();+ }+ if (changed) {+ clear();+ }+ });+ mutations.observe(root, {+ subtree: true,+ childList: true,+ characterData: true,+ attributes: true,+ attributeFilter: ['class', 'style', 'hidden', 'open', 'data-fold-panel', 'data-fold-column'],+ });+ const resize = new ResizeObserver(clear);+ /** Earlier messages can move this fold without resizing it. */+ for (+ let ancestor: HTMLElement | null = root;+ ancestor != null;+ ancestor = ancestor.parentElement+ ) {+ resize.observe(ancestor);+ }+ root.addEventListener('pointermove', onMove);+ root.addEventListener('pointerleave', clear);+ root.addEventListener('pointerdown', clear);+ window.addEventListener('scroll', onScroll, true);+ window.addEventListener('resize', clear);+ return () => {+ root.removeEventListener('pointermove', onMove);+ root.removeEventListener('pointerleave', clear);+ root.removeEventListener('pointerdown', clear);+ window.removeEventListener('scroll', onScroll, true);+ window.removeEventListener('resize', clear);+ mutations.disconnect();+ resize.disconnect();+ clear();+ };+ }, [rootRef, hasBody]);+}+/*** Collapsing from a rail far down a long fold would leave the reader below the* point where the fold now ends, so its header comes back into view first. Adiff --git a/client/src/components/Chat/Messages/Content/rows.ts b/client/src/components/Chat/Messages/Content/rows.tsindex 4d81d084ba..8f832c5ba5 100644--- a/client/src/components/Chat/Messages/Content/rows.ts+++ b/client/src/components/Chat/Messages/Content/rows.ts@@ -7,6 +7,9 @@*/export const TOOL_ROW_CLASSES = 'relative my-1.5 flex h-5 shrink-0 items-center gap-2.5';+/** Behavior hook for header glyphs, independent of their layout. */+export const FOLD_GLYPH_CLASS = 'fold-glyph';+/*** The leading glyph slot of a row: 24px wide, the width of the message* header's avatar, and the row's own 20px tall. A 16px tool icon, the 14px@@ -15,9 +18,13 @@ export const TOOL_ROW_CLASSES = 'relative my-1.5 flex h-5 shrink-0 items-center* starts where the header's name does. `min-w` rather than `w`, so a stacked* icon strip can run wider without overlapping its label; never taller than* `TOOL_ROW_CLASSES`, whose `ProgressText` content is absolutely positioned- * and would carry a taller slot 2px below the row's center.+ * and would carry a taller slot 2px below the row's center. `fold-glyph` is a+ * hook, not a style: see `FOLD_GLYPH_SELECTOR`.*/-export const ROW_GLYPH_SLOT = 'flex h-5 min-w-6 shrink-0 items-center justify-center';+export const ROW_GLYPH_SLOT = `${FOLD_GLYPH_CLASS} flex h-5 min-w-6 shrink-0 items-center justify-center`;++/** Shared by normal row slots and custom header glyphs. */+export const FOLD_GLYPH_SELECTOR = `.${FOLD_GLYPH_CLASS}`;/*** The panel under an open header: its rows step in by one glyph slot and adiff --git a/e2e/specs/mock/activity-fold.spec.ts b/e2e/specs/mock/activity-fold.spec.tsindex b42b663558..116dbd0ea7 100644--- a/e2e/specs/mock/activity-fold.spec.ts+++ b/e2e/specs/mock/activity-fold.spec.ts@@ -151,8 +151,103 @@ test.describe('activity fold', () => {const groupRail = groupPanel.locator('> div > [data-testid="fold-rail"]');const groupHeader = groupPanel.locator('xpath=preceding-sibling::div[1]').getByRole('button');const lineColor = (railLocator: typeof groupRail) =>- railLocator.locator('span').evaluate((line) => getComputedStyle(line).backgroundColor);+ railLocator+ .locator('span')+ .first()+ .evaluate((line) => getComputedStyle(line).backgroundColor);const restingLine = await lineColor(groupRail);++ /** A row two folds deep lights both rails down to it: the group's turns into+ * the row's glyph, the phase's runs on past the group's header. */+ const failedCall = groupPanel.getByTestId('tool-call').filter({ hasText: /^Failed:/ });+ const litLength = (railLocator: typeof groupRail) =>+ railLocator.evaluate((rail) => parseFloat(rail.style.getPropertyValue('--fold-lit')));+ await failedCall.scrollIntoViewIfNeeded();+ await failedCall.hover();+ await expect(groupRail).toHaveAttribute('data-fold-lit', 'end');+ await expect(phaseRail).toHaveAttribute('data-fold-lit', 'through');+ expect(await litLength(phaseRail)).toBeGreaterThan(await litLength(groupRail));+ const groupPath = groupRail.getByTestId('fold-rail-path');+ await expect(groupPath).toHaveCSS('opacity', '1');+ const [elbow, glyph] = await Promise.all([+ groupPath.boundingBox(),+ failedCall.locator('.fold-glyph').first().boundingBox(),+ ]);+ expect(elbow).not.toBeNull();+ expect(glyph).not.toBeNull();+ expect(Math.abs(elbow!.y + elbow!.height - (glyph!.y + glyph!.height / 2))).toBeLessThan(2);+ await shot(page, 'lit-path');++ await failedCall.evaluate((row) => {+ const { left, top, width, height } = row.getBoundingClientRect();+ const pointer = {+ bubbles: true,+ pointerType: 'mouse',+ pointerId: 1,+ isPrimary: true,+ clientX: left + width / 2,+ clientY: top + height / 2,+ };+ row.dispatchEvent(new PointerEvent('pointermove', pointer));+ row.dispatchEvent(new PointerEvent('pointerdown', { ...pointer, buttons: 1 }));+ row.dispatchEvent(new PointerEvent('pointerup', pointer));+ });+ await expect(groupRail).not.toHaveAttribute('data-fold-lit');+ await expect(phaseRail).not.toHaveAttribute('data-fold-lit');+ await failedCall.scrollIntoViewIfNeeded();+ await failedCall.hover();+ await expect(groupRail).toHaveAttribute('data-fold-lit', 'end');+ await groupPanel.locator('> div > div').evaluate((rows) => {+ (rows as HTMLElement).style.paddingTop = '12px';+ });+ await expect(groupRail).not.toHaveAttribute('data-fold-lit');+ await expect(phaseRail).not.toHaveAttribute('data-fold-lit');+ await groupPanel.locator('> div > div').evaluate((rows) => {+ (rows as HTMLElement).style.removeProperty('padding-top');+ });+ await page.mouse.move(0, 0);+ await expect(groupRail).not.toHaveAttribute('data-fold-lit');+ await expect(phaseRail).not.toHaveAttribute('data-fold-lit');++ /** An earlier message can shift this fold without resizing it or scrolling. */+ const transcript = messagesView(page).getByTestId('screenshot-target');+ const previousAnchor = await transcript.evaluate((content) => {+ const spacer = document.createElement('div');+ spacer.id = 'fold-layout-predecessor';+ spacer.style.height = '0px';+ content.prepend(spacer);+ const scroll = content.closest<HTMLElement>('.scrollbar-gutter-stable')!;+ const anchor = scroll.style.overflowAnchor;+ scroll.style.overflowAnchor = 'none';+ return anchor;+ });+ await failedCall.scrollIntoViewIfNeeded();+ await failedCall.hover();+ await expect(groupRail).toHaveAttribute('data-fold-lit', 'end');+ const shift = await failedCall.evaluate((row) => {+ const fold = row.closest<HTMLElement>('[data-testid="activity-phase-card"]')!;+ const message = row.closest<HTMLElement>('.message-render')!;+ const scroll = row.closest<HTMLElement>('.scrollbar-gutter-stable')!;+ const measure = () => ({+ top: fold.getBoundingClientRect().top,+ foldHeight: fold.getBoundingClientRect().height,+ messageHeight: message.getBoundingClientRect().height,+ scrollTop: scroll.scrollTop,+ });+ const before = measure();+ document.getElementById('fold-layout-predecessor')!.style.height = '32px';+ return { before, after: measure() };+ });+ expect(shift.after.top - shift.before.top).toBeCloseTo(32);+ expect(shift.after.foldHeight).toBe(shift.before.foldHeight);+ expect(shift.after.messageHeight).toBe(shift.before.messageHeight);+ expect(shift.after.scrollTop).toBe(shift.before.scrollTop);+ await expect(groupRail).not.toHaveAttribute('data-fold-lit');+ await expect(phaseRail).not.toHaveAttribute('data-fold-lit');+ await transcript.evaluate((content, anchor) => {+ content.querySelector('#fold-layout-predecessor')!.remove();+ content.closest<HTMLElement>('.scrollbar-gutter-stable')!.style.overflowAnchor = anchor;+ }, previousAnchor);await expect(knobs).toHaveCount(0);await groupRail.hover();await expect(knobs).toHaveCount(1);