fix(gemini): prepend empty user placeholder and normalize role alternation

This commit is contained in:
tyuXX 2026-11-03 17:07:03 +00:00
parent a27c781dd9
commit 19ea81e449
2 changed files with 87 additions and 5 deletions

View file

@ -102,6 +102,52 @@ async function runTests() {
assert.strictEqual(maskedShort, '****');
console.log(' ✓ Key masking security verified.');
// TEST 5: Gemini Message Normalization & Empty Placeholder Prepending
console.log('\n5. Testing Gemini message normalization & role alternation...');
// 5a. Assistant first with system instruction
const conv1 = engine.convertToGeminiContent([
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'assistant', content: 'Hello! How can I help you today?' },
{ role: 'user', content: 'What is 2+2?' }
]);
assert.strictEqual(conv1.systemInstruction, 'You are a helpful assistant.');
assert.strictEqual(conv1.geminiMessages.length, 3);
assert.strictEqual(conv1.geminiMessages[0].role, 'user', 'First message must be normalized to user role');
assert.strictEqual(conv1.geminiMessages[0].parts[0].text, '', 'Leading placeholder user message should be empty');
assert.strictEqual(conv1.geminiMessages[1].role, 'model');
assert.strictEqual(conv1.geminiMessages[1].parts[0].text, 'Hello! How can I help you today?');
assert.strictEqual(conv1.geminiMessages[2].role, 'user');
assert.strictEqual(conv1.geminiMessages[2].parts[0].text, 'What is 2+2?');
// 5b. Consecutive assistant messages merged, consecutive user messages merged
const conv2 = engine.convertToGeminiContent([
{ role: 'assistant', content: 'Part 1' },
{ role: 'assistant', content: 'Part 2' },
{ role: 'user', content: 'Question 1' },
{ role: 'user', content: 'Question 2' }
]);
assert.strictEqual(conv2.geminiMessages.length, 3);
assert.strictEqual(conv2.geminiMessages[0].role, 'user');
assert.strictEqual(conv2.geminiMessages[0].parts[0].text, '');
assert.strictEqual(conv2.geminiMessages[1].role, 'model');
assert.strictEqual(conv2.geminiMessages[1].parts[0].text, 'Part 1\n\nPart 2');
assert.strictEqual(conv2.geminiMessages[2].role, 'user');
assert.strictEqual(conv2.geminiMessages[2].parts[0].text, 'Question 1\n\nQuestion 2');
// 5c. Conversation ending with an assistant turn ensures trailing user turn
const conv3 = engine.convertToGeminiContent([
{ role: 'user', content: 'Tell a story' },
{ role: 'assistant', content: 'Once upon a time' }
]);
assert.strictEqual(conv3.geminiMessages.length, 3);
assert.strictEqual(conv3.geminiMessages[0].role, 'user');
assert.strictEqual(conv3.geminiMessages[1].role, 'model');
assert.strictEqual(conv3.geminiMessages[2].role, 'user');
assert.strictEqual(conv3.geminiMessages[2].parts[0].text, '');
console.log(' ✓ Empty placeholder prepending and turn alternation normalization verified.');
// Clean up test file
if (fs.existsSync(testConfigPath)) {
fs.unlinkSync(testConfigPath);