Skip to content
Merged
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
147 changes: 147 additions & 0 deletions packages/cli/src/ui/hooks/useGeminiStream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import type { HistoryItem, SlashCommandProcessorResult } from '../types.js';
import { MessageType, StreamingState } from '../types.js';
import type { LoadedSettings } from '../../config/settings.js';
import { findLastSafeSplitPoint } from '../utils/markdownUtilities.js';

// --- MOCKS ---
const mockSendMessageStream = vi
Expand Down Expand Up @@ -148,6 +149,9 @@ describe('useGeminiStream', () => {

beforeEach(() => {
vi.clearAllMocks(); // Clear mocks before each test
vi.mocked(findLastSafeSplitPoint).mockImplementation(
(s: string) => s.length,
);

mockAddItem = vi.fn();
// Define the mock for getGeminiClient
Expand Down Expand Up @@ -1201,6 +1205,78 @@ describe('useGeminiStream', () => {
});
});

it('does not render leading blank content chunks as an empty assistant item', async () => {
vi.useFakeTimers();

let releaseNextChunk!: () => void;
const waitForNextChunk = new Promise<void>((resolve) => {
releaseNextChunk = resolve;
});
let releaseStream!: () => void;
const holdStream = new Promise<void>((resolve) => {
releaseStream = resolve;
});
vi.mocked(findLastSafeSplitPoint).mockImplementation((s: string) =>
s.startsWith('\n\n') ? 2 : s.length,
);

const mockStream = (async function* () {
yield {
type: ServerGeminiEventType.Content,
value: '\n\n',
};
await waitForNextChunk;
yield {
type: ServerGeminiEventType.Content,
value: '哈哈',
};
await holdStream;
})();
mockSendMessageStream.mockReturnValue(mockStream);

const { result } = renderTestHook();

act(() => {
void result.current.submitQuery('test query');
});

await act(async () => {
await Promise.resolve();
await Promise.resolve();
});

await act(async () => {
vi.advanceTimersByTime(60);
});

expect(result.current.pendingHistoryItems).toEqual([]);

await act(async () => {
releaseNextChunk();
await Promise.resolve();
await Promise.resolve();
});

await act(async () => {
vi.advanceTimersByTime(60);
});

expect(result.current.pendingHistoryItems).toEqual([
expect.objectContaining({
type: 'gemini',
text: '哈哈',
}),
]);

act(() => {
result.current.cancelOngoingRequest();
});

await act(async () => {
releaseStream();
});
});

it('buffers streamed thoughts until the throttle interval elapses', async () => {
vi.useFakeTimers();

Expand Down Expand Up @@ -1257,6 +1333,77 @@ describe('useGeminiStream', () => {
});
});

it('does not render leading blank thought chunks as an empty thought item', async () => {
vi.useFakeTimers();

let releaseNextChunk!: () => void;
const waitForNextChunk = new Promise<void>((resolve) => {
releaseNextChunk = resolve;
});
let releaseStream!: () => void;
const holdStream = new Promise<void>((resolve) => {
releaseStream = resolve;
});

const mockStream = (async function* () {
yield {
type: ServerGeminiEventType.Thought,
value: { description: '\n\n' },
};
await waitForNextChunk;
yield {
type: ServerGeminiEventType.Thought,
value: { description: 'Thinking' },
};
await holdStream;
})();
mockSendMessageStream.mockReturnValue(mockStream);

const { result } = renderTestHook();

act(() => {
void result.current.submitQuery('test query');
});

await act(async () => {
await Promise.resolve();
await Promise.resolve();
});

await act(async () => {
vi.advanceTimersByTime(60);
});

expect(result.current.pendingHistoryItems).toEqual([]);
expect(result.current.thought).toBeNull();

await act(async () => {
releaseNextChunk();
await Promise.resolve();
await Promise.resolve();
});

await act(async () => {
vi.advanceTimersByTime(60);
});

expect(result.current.pendingHistoryItems).toEqual([
expect.objectContaining({
type: 'gemini_thought',
text: 'Thinking',
}),
]);
expect(result.current.thought).toEqual({ description: 'Thinking' });

act(() => {
result.current.cancelOngoingRequest();
});

await act(async () => {
releaseStream();
});
});

it('flushes buffered content before cancellation', async () => {
vi.useFakeTimers();

Expand Down
20 changes: 18 additions & 2 deletions packages/cli/src/ui/hooks/useGeminiStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ function extractLastAssistantText(history: HistoryItem[]): string | undefined {
return undefined;
}

function stripLeadingBlankLines(text: string): string {
return text.replace(/^(?:[ \t]*\r?\n)+/, '');
}

/**
* Flatten `functionResponse` parts into a compact string for the summarizer.
* The summarizer itself truncates to 300 chars per field, so we just join
Expand Down Expand Up @@ -766,11 +770,14 @@ export const useGeminiStream = (
pendingHistoryItemRef.current?.type !== 'gemini' &&
pendingHistoryItemRef.current?.type !== 'gemini_content'
) {
if (newGeminiMessageBuffer.trim().length === 0) {
return newGeminiMessageBuffer;
}
if (pendingHistoryItemRef.current) {
addItem(pendingHistoryItemRef.current, userMessageTimestamp);
}
setPendingHistoryItem({ type: 'gemini', text: '' });
newGeminiMessageBuffer = eventValue;
newGeminiMessageBuffer = stripLeadingBlankLines(newGeminiMessageBuffer);
}
// Split large messages for better rendering performance. Ideally,
// we should maximize the amount of output sent to <Static />.
Expand Down Expand Up @@ -845,13 +852,22 @@ export const useGeminiStream = (
const isPendingThought =
pendingType === 'gemini_thought' ||
pendingType === 'gemini_thought_content';
let thoughtToMerge = eventValue;

// If we're not already showing a thought, start a new one
if (!isPendingThought) {
if (newThoughtBuffer.trim().length === 0) {
return newThoughtBuffer;
}
// If there's a pending non-thought item, finalize it first
if (pendingHistoryItemRef.current) {
addItem(pendingHistoryItemRef.current, userMessageTimestamp);
}
newThoughtBuffer = stripLeadingBlankLines(newThoughtBuffer);
thoughtToMerge = {
...eventValue,
description: newThoughtBuffer,
};
setPendingHistoryItem({ type: 'gemini_thought', text: '' });
}

Expand Down Expand Up @@ -888,7 +904,7 @@ export const useGeminiStream = (
}

// Also update the thought state for the loading indicator
mergeThought(eventValue);
mergeThought(thoughtToMerge);

return newThoughtBuffer;
},
Expand Down
Loading
Loading