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
149 changes: 149 additions & 0 deletions src/web-ui/src/flow_chat/components/modern/FlowChatHeader.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// @vitest-environment jsdom

import React, { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FlowChatHeader, type FlowChatHeaderProps } from './FlowChatHeader';

globalThis.IS_REACT_ACT_ENVIRONMENT = true;

vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => {
if (key === 'flowChatHeader.turnBadge') {
return `Turn ${values?.current ?? ''}`;
}
return key;
},
}),
}));

vi.mock('@/component-library', async () => {
const ReactModule = await import('react');

return {
Tooltip: ({ children }: { children: React.ReactNode }) => (
<ReactModule.Fragment>{children}</ReactModule.Fragment>
),
IconButton: ({
children,
size,
tooltip,
variant,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & {
size?: string;
tooltip?: string;
variant?: string;
}) => (
<button type="button" title={tooltip} {...props}>
{children}
</button>
),
Input: ReactModule.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>((props, ref) => (
<input ref={ref} {...props} />
)),
};
});

vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({
useWorkspaceContext: () => ({
currentWorkspace: { rootPath: '/workspace' },
}),
}));

vi.mock('@/shared/utils/tabUtils', () => ({
createReviewPlatformTab: vi.fn(),
}));

vi.mock('./SessionFilesBadge', () => ({
SessionFilesBadge: () => <div data-testid="session-files-badge" />,
}));

function createProps(overrides: Partial<FlowChatHeaderProps> = {}): FlowChatHeaderProps {
return {
currentTurn: 1,
totalTurns: 2,
currentUserMessage: 'First prompt',
visible: true,
turns: [
{ turnId: 'turn-1', turnIndex: 1, title: 'First prompt' },
{ turnId: 'turn-2', turnIndex: 2, title: 'Second prompt' },
],
onJumpToTurn: vi.fn(),
...overrides,
};
}

describe('FlowChatHeader', () => {
let container: HTMLDivElement;
let root: Root;

beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
});

afterEach(() => {
act(() => {
root.unmount();
});
container.remove();
});

it('keeps the turn list open until the selected turn becomes current', () => {
const onJumpToTurn = vi.fn();
const initialProps = createProps({ onJumpToTurn });

act(() => {
root.render(<FlowChatHeader {...initialProps} />);
});

const turnListButton = container.querySelector<HTMLButtonElement>('[data-testid="flowchat-header-turn-list"]');
expect(turnListButton).not.toBeNull();

act(() => {
turnListButton?.click();
});

expect(container.querySelector('[role="dialog"]')).not.toBeNull();

const turnItems = Array.from(container.querySelectorAll<HTMLButtonElement>('.flowchat-header__turn-list-item'));
expect(turnItems).toHaveLength(2);

act(() => {
turnItems[1]?.click();
});

expect(onJumpToTurn).toHaveBeenCalledWith('turn-2');
expect(container.querySelector('[role="dialog"]')).not.toBeNull();

act(() => {
root.render(<FlowChatHeader {...initialProps} currentTurn={2} />);
});

expect(container.querySelector('[role="dialog"]')).toBeNull();
});

it('closes the turn list and notifies the container when selecting the current turn', () => {
const onJumpToTurn = vi.fn();

act(() => {
root.render(<FlowChatHeader {...createProps({ onJumpToTurn })} />);
});

const turnListButton = container.querySelector<HTMLButtonElement>('[data-testid="flowchat-header-turn-list"]');
act(() => {
turnListButton?.click();
});

const currentTurnItem = container.querySelector<HTMLButtonElement>('.flowchat-header__turn-list-item');
act(() => {
currentTurnItem?.click();
});

expect(onJumpToTurn).toHaveBeenCalledWith('turn-1');
expect(container.querySelector('[role="dialog"]')).toBeNull();
});
});
9 changes: 7 additions & 2 deletions src/web-ui/src/flow_chat/components/modern/FlowChatHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,14 @@ export const FlowChatHeader: React.FC<FlowChatHeaderProps> = ({

const handleTurnSelect = (turnId: string) => {
if (!onJumpToTurn) return;
const selectedTurn = displayTurns.find(turn => turn.turnId === turnId);
if (selectedTurn?.turnIndex === currentTurn) {
onJumpToTurn(turnId);
setIsTurnListOpen(false);
return;
}

onJumpToTurn(turnId);
setIsTurnListOpen(false);
};

const handleSubagentSelect = (sessionId: string) => {
Expand Down Expand Up @@ -908,4 +914,3 @@ export const FlowChatHeader: React.FC<FlowChatHeaderProps> = ({
};

FlowChatHeader.displayName = 'FlowChatHeader';

Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,68 @@ describe('ModernFlowChatContainer historical empty state', () => {
});
});

it('retries header turn selection without advancing header state until the virtual list accepts it', async () => {
stateMocks.activeSession = createSession({
isHistorical: false,
historyState: 'ready',
dialogTurns: [
createTurn('turn-1', 'Older prompt'),
createTurn('turn-2', 'Latest prompt'),
],
} as Partial<Session>);
stateMocks.virtualItems = [
{ type: 'user-message', turnId: 'turn-1', data: { id: 'user-turn-1', content: 'Older prompt' } },
{ type: 'user-message', turnId: 'turn-2', data: { id: 'user-turn-2', content: 'Latest prompt' } },
];
stateMocks.visibleTurnInfo = {
turnId: 'turn-2',
turnIndex: 2,
totalTurns: 2,
userMessage: 'Latest prompt',
};
virtualListMock.pinTurnToTop.mockReturnValue(false);

await act(async () => {
root.render(<ModernFlowChatContainer />);
});

expect(headerPropsMock.latest).toMatchObject({
currentTurn: 2,
totalTurns: 2,
});

await act(async () => {
(headerPropsMock.latest?.onJumpToTurn as ((turnId: string) => void) | undefined)?.('turn-1');
});

expect(virtualListMock.pinTurnToTop).toHaveBeenLastCalledWith('turn-1', {
behavior: 'smooth',
pinMode: 'transient',
});
expect(headerPropsMock.latest).toMatchObject({
currentTurn: 2,
totalTurns: 2,
});

virtualListMock.pinTurnToTop.mockReturnValue(true);
stateMocks.virtualItems = [
...stateMocks.virtualItems,
];

await act(async () => {
root.render(<ModernFlowChatContainer />);
});

expect(virtualListMock.pinTurnToTop).toHaveBeenLastCalledWith('turn-1', {
behavior: 'smooth',
pinMode: 'transient',
});
expect(headerPropsMock.latest).toMatchObject({
currentTurn: 1,
totalTurns: 2,
});
});

it('does not expose previous navigation before the loaded tail range in partial history', async () => {
stateMocks.activeSession = createSession({
isHistorical: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ export const ModernFlowChatContainer: React.FC<ModernFlowChatContainerProps> = (
const activeSession = useActiveSession();
const visibleTurnInfo = useVisibleTurnInfo();
const [pendingHeaderTurnId, setPendingHeaderTurnId] = useState<string | null>(null);
const [queuedHeaderTurnPinId, setQueuedHeaderTurnPinId] = useState<string | null>(null);
const [pendingHistoryOpenSession, setPendingHistoryOpenSession] = useState<HistorySessionOpenIntentDetail | null>(null);
const [searchOpenRequest, setSearchOpenRequest] = useState(0);
// Track whether a slash-command or @-mention popup is open in ChatInput.
Expand Down Expand Up @@ -663,6 +664,47 @@ export const ModernFlowChatContainer: React.FC<ModernFlowChatContainerProps> = (
}
}, [pendingHeaderTurnId, turnSummaries, visibleTurnInfo?.turnId]);

const requestHeaderTurnPin = useCallback((turnId: string) => {
const isLatestTurn = turnSummaries[turnSummaries.length - 1]?.turnId === turnId;
const targetTurn = findDialogTurn(activeSession?.dialogTurns, turnId);
const pinMode = isLatestTurn && shouldUseStickyLatestPin(targetTurn)
? 'sticky-latest'
: 'transient';

return virtualListRef.current?.pinTurnToTop(turnId, {
behavior: 'smooth',
pinMode,
}) ?? false;
}, [activeSession?.dialogTurns, turnSummaries]);

useEffect(() => {
if (!queuedHeaderTurnPinId) return;

if (visibleTurnInfo?.turnId === queuedHeaderTurnPinId) {
setQueuedHeaderTurnPinId(null);
return;
}

const targetStillExists = turnSummaries.some(turn => turn.turnId === queuedHeaderTurnPinId);
if (!targetStillExists) {
setQueuedHeaderTurnPinId(null);
setPendingHeaderTurnId(null);
return;
}

const accepted = requestHeaderTurnPin(queuedHeaderTurnPinId);
if (!accepted) return;

setQueuedHeaderTurnPinId(null);
setPendingHeaderTurnId(queuedHeaderTurnPinId);
}, [
queuedHeaderTurnPinId,
requestHeaderTurnPin,
turnSummaries,
virtualItems,
visibleTurnInfo?.turnId,
]);

useLayoutEffect(() => {
autoPinnedTurnKeyRef.current = null;
releasedHistoryCompletionKeyRef.current = null;
Expand All @@ -672,6 +714,7 @@ export const ModernFlowChatContainer: React.FC<ModernFlowChatContainerProps> = (
setHistoryInitialContentReadyKey(null);
setHistoryInitialContentPostPaintKey(null);
setPendingHeaderTurnId(null);
setQueuedHeaderTurnPinId(null);
}, [activeSession?.sessionId]);

useLayoutEffect(() => {
Expand Down Expand Up @@ -969,19 +1012,23 @@ export const ModernFlowChatContainer: React.FC<ModernFlowChatContainerProps> = (
const handleJumpToTurn = useCallback((turnId: string) => {
if (!turnId) return;

const isLatestTurn = turnSummaries[turnSummaries.length - 1]?.turnId === turnId;
const targetTurn = findDialogTurn(activeSession?.dialogTurns, turnId);
const pinMode = isLatestTurn && shouldUseStickyLatestPin(targetTurn)
? 'sticky-latest'
: 'transient';
const targetStillExists = turnSummaries.some(turn => turn.turnId === turnId);
if (!targetStillExists) {
setQueuedHeaderTurnPinId(null);
setPendingHeaderTurnId(null);
return;
}

const accepted = virtualListRef.current?.pinTurnToTop(turnId, {
behavior: 'smooth',
pinMode,
}) ?? false;
const accepted = requestHeaderTurnPin(turnId);
if (accepted) {
setQueuedHeaderTurnPinId(null);
setPendingHeaderTurnId(turnId);
return;
}

setPendingHeaderTurnId(accepted ? turnId : null);
}, [activeSession?.dialogTurns, turnSummaries]);
setQueuedHeaderTurnPinId(turnId);
setPendingHeaderTurnId(null);
}, [requestHeaderTurnPin, turnSummaries]);

const handleJumpToPreviousTurn = useCallback(() => {
if (!navigationVisibleTurnInfo || navigationVisibleTurnInfo.turnIndex <= 1) return;
Expand Down
Loading