feat(chat): add scroll-to-latest button (#1031)

This commit is contained in:
paisley
2026-05-18 15:09:08 +08:00
committed by GitHub
parent fdc0b0d746
commit f4d6478f1c
7 changed files with 162 additions and 7 deletions

View File

@@ -0,0 +1,91 @@
import { closeElectronApp, expect, getStableWindow, installIpcMocks, test } from './fixtures/electron';
const SESSION_KEY = 'agent:main:main';
function stableStringify(value: unknown): string {
if (value == null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`;
const entries = Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`);
return `{${entries.join(',')}}`;
}
const seededHistory = Array.from({ length: 36 }, (_, idx) => ({
role: idx % 2 === 0 ? 'user' : 'assistant',
content: `${idx === 0 ? 'Very first message' : 'Chat history message'} ${idx + 1}`,
timestamp: Date.now() + idx,
}));
test.describe('ClawX chat scroll-to-latest affordance', () => {
test('shows a jump button when reading older messages and returns to the latest message', async ({ launchElectronApp }) => {
const app = await launchElectronApp({ skipSetup: true });
try {
await installIpcMocks(app, {
gatewayStatus: { state: 'running', port: 18789, pid: 12345 },
gatewayRpc: {
[stableStringify(['sessions.list', {}])]: {
success: true,
result: {
sessions: [{ key: SESSION_KEY, displayName: 'main' }],
},
},
[stableStringify(['chat.history', { sessionKey: SESSION_KEY, limit: 200 }])]: {
success: true,
result: { messages: seededHistory },
},
[stableStringify(['chat.history', { sessionKey: SESSION_KEY, limit: 1000 }])]: {
success: true,
result: { messages: seededHistory },
},
},
hostApi: {
[stableStringify(['/api/gateway/status', 'GET'])]: {
ok: true,
data: {
status: 200,
ok: true,
json: { state: 'running', port: 18789, pid: 12345 },
},
},
[stableStringify(['/api/agents', 'GET'])]: {
ok: true,
data: {
status: 200,
ok: true,
json: { success: true, agents: [{ id: 'main', name: 'main' }] },
},
},
},
});
const page = await getStableWindow(app);
try {
await page.reload();
} catch (error) {
if (!String(error).includes('ERR_FILE_NOT_FOUND')) {
throw error;
}
}
await expect(page.getByTestId('main-layout')).toBeVisible();
await expect(page.getByText('Chat history message 36')).toBeVisible({ timeout: 30_000 });
const scrollContainer = page.getByTestId('chat-scroll-container');
await scrollContainer.evaluate((element) => {
element.scrollTop = 0;
element.dispatchEvent(new Event('scroll', { bubbles: true }));
});
const jumpButton = page.getByTestId('chat-scroll-to-latest');
await expect(jumpButton).toBeVisible();
await jumpButton.click();
await expect(jumpButton).toBeHidden({ timeout: 10_000 });
await expect(page.getByText('Chat history message 36')).toBeVisible();
} finally {
await closeElectronApp(app);
}
});
});

View File

@@ -27,7 +27,8 @@ vi.mock('@/lib/host-api', () => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, params?: Record<string, unknown>) => {
t: (key: string, params?: Record<string, unknown> | string) => {
if (typeof params === 'string') return params;
if (key === 'executionGraph.collapsedSummary') {
return `collapsed ${String(params?.toolCount ?? '')} ${String(params?.processCount ?? '')}`.trim();
}
@@ -52,10 +53,12 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@/hooks/use-stick-to-bottom-instant', () => ({
useStickToBottomInstant: () => ({
useStickToBottomInstant: vi.fn(() => ({
contentRef: { current: null },
scrollRef: { current: null },
}),
scrollToBottom: vi.fn(),
isAtBottom: true,
})),
}));
vi.mock('@/hooks/use-min-loading', () => ({
@@ -258,6 +261,49 @@ describe('Chat execution graph lifecycle', () => {
expect(screen.getByText('-1')).toBeInTheDocument();
});
it('shows a scroll-to-latest button when the chat is scrolled away from the bottom', async () => {
const { useChatStore } = await import('@/stores/chat');
useChatStore.setState({
messages: Array.from({ length: 24 }, (_, idx) => ({
role: idx % 2 === 0 ? 'user' : 'assistant',
content: `Message ${idx + 1}`,
timestamp: Date.now() + idx,
})),
loading: false,
error: null,
runError: null,
sending: false,
activeRunId: null,
streamingText: '',
streamingMessage: null,
streamingTools: [],
pendingFinal: false,
lastUserMessageAt: Date.now(),
pendingToolImages: [],
sessions: [{ key: 'agent:main:main' }],
currentSessionKey: 'agent:main:main',
currentAgentId: 'main',
sessionLabels: {},
sessionLastActivity: {},
thinkingLevel: null,
});
const { useStickToBottomInstant } = await import('@/hooks/use-stick-to-bottom-instant');
vi.mocked(useStickToBottomInstant).mockReturnValue({
contentRef: { current: null },
scrollRef: { current: null },
scrollToBottom: vi.fn(),
isAtBottom: false,
} as ReturnType<typeof useStickToBottomInstant>);
const { Chat } = await import('@/pages/Chat/index');
render(<Chat />);
expect(await screen.findByTestId('chat-scroll-to-latest')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '跳转到最新对话' })).toBeInTheDocument();
});
it('stops showing trailing thinking and renders run error callout after terminal model error', async () => {
const { useChatStore } = await import('@/stores/chat');
useChatStore.setState({