Skip to content
Closed
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
18 changes: 14 additions & 4 deletions src/i18n/llmLocale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,28 @@ const LANGUAGE_NAMES_FOR_LLM: Record<SupportedLocale, string> = {
* while keeping code, paths, and technical identifiers in English.
*/
export function buildLocaleInstruction(locale: SupportedLocale): string {
// No instruction needed for English (default)
const languageName = LANGUAGE_NAMES_FOR_LLM[locale];
// English is stated too: with no instruction, a remembered or inferred language
// preference would be the only language guidance the model sees.
const precedence = `This configured language overrides any remembered language preference. Switch languages only when the user explicitly asks in the current conversation.`;

if (locale === 'en') {
return '';
}
return `
## Response Language Preference

const languageName = LANGUAGE_NAMES_FOR_LLM[locale];
The user has configured their preferred language as **English**. Respond in English.

${precedence}
`;
}

return `
## Response Language Preference

The user has configured their preferred language as **${languageName}**.

${precedence}

Please respond in ${languageName} when providing:
- Explanations and descriptions
- Summaries and overviews
Expand Down
17 changes: 17 additions & 0 deletions src/memory/extractSessionMemories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Rules:
- Be concise: each memory should be 1-2 sentences max
- Prefer updating/refining durable memories over restating obvious session facts
- Skip trivial, one-off, or context-specific observations
- Never save which language to respond in; the response language is a user setting (/language), not a memory
- If nothing is worth saving, return an empty array

Return ONLY a JSON array (no markdown, no explanation):
Expand Down Expand Up @@ -126,6 +127,21 @@ function stripCodeFences(raw: string): string {
return match ? match[1].trim() : trimmed;
}

const LANGUAGE_NAMES = 'english|portuguese|portugu[eê]s|spanish|espa[nñ]ol|french|german|italian|japanese|korean|chinese|russian|turkish|polish|czech|hungarian|hindi|indonesian';
const RESPONSE_LANGUAGE_PATTERN = new RegExp(
`\\b(respond|reply|answer|communicat\\w*|speak\\w*|write|writes|talk\\w*)\\b[^.;]{0,60}\\b(${LANGUAGE_NAMES})\\b`,
'i',
);

/**
* Response language is a setting (`ui.locale`). A memory that pins a reply language
* outlives the session that suggested it and silently overrides the setting.
*/
function isResponseLanguageMemory(memory: ExtractedMemory): boolean {
if (memory.tags?.some((tag) => /^(language|locale)$/i.test(tag))) return true;
return RESPONSE_LANGUAGE_PATTERN.test(memory.content);
}

/** Validate and type-narrow a single parsed entry */
function isValidMemory(entry: unknown): entry is ExtractedMemory {
if (typeof entry !== 'object' || entry === null) return false;
Expand Down Expand Up @@ -220,6 +236,7 @@ export async function extractAndSaveSessionMemories(
level: raw.level,
tags: normaliseTags(rawObj.tags),
};
if (isResponseLanguageMemory(memory)) continue;

try {
if (memory.level === 'project' && expectedProjectScope !== undefined
Expand Down
22 changes: 13 additions & 9 deletions tests/i18n/llmLocale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@ import type { SupportedLocale } from '../../src/i18n/localeDetector';
describe('llmLocale', () => {
describe('buildLocaleInstruction', () => {
describe('English locale', () => {
it('should return empty string for English', () => {
it('states English explicitly so a remembered language cannot take over', () => {
const result = buildLocaleInstruction('en');
expect(result).toBe('');
expect(result).toContain('## Response Language Preference');
expect(result).toContain('Respond in English');
expect(result).toContain('overrides any remembered language preference');
});
});

describe('non-English locales', () => {
it('makes the configured language override remembered language preferences', () => {
expect(buildLocaleInstruction('fr')).toContain('overrides any remembered language preference');
});

it('should include language preference header for French', () => {
const result = buildLocaleInstruction('fr');
expect(result).toContain('## Response Language Preference');
Expand Down Expand Up @@ -194,9 +200,10 @@ describe('llmLocale', () => {
const basePrompt = 'You are a helpful coding assistant.\n\n## Tools\n\nYou have access to the following tools:';

describe('English locale', () => {
it('should return original prompt unchanged for English', () => {
it('appends an explicit English instruction', () => {
const result = injectLocaleIntoPrompt(basePrompt, 'en');
expect(result).toBe(basePrompt);
expect(result).toContain(basePrompt);
expect(result).toContain('Respond in English');
});
});

Expand Down Expand Up @@ -246,11 +253,8 @@ describe('llmLocale', () => {
it.each(allLocales)('should handle %s locale correctly', (locale) => {
const result = injectLocaleIntoPrompt(basePrompt, locale);

// English should return unchanged
if (locale === 'en') {
expect(result).toBe(basePrompt);
} else {
// All others should have the locale instruction
// Every locale, English included, states the response language
{
expect(result).toContain(basePrompt);
expect(result).toContain('## Response Language Preference');
expect(result.length).toBeGreaterThan(basePrompt.length);
Expand Down
25 changes: 25 additions & 0 deletions tests/memory/extractSessionMemories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,31 @@ describe('extractAndSaveSessionMemories', () => {
});

// 3. Returns empty array when LLM returns empty array
it('never saves a response-language preference, which belongs to the language setting', async () => {
const llmPayload: ExtractedMemory[] = [
{
content: 'Igor communicates in Portuguese; respond in Portuguese by default unless requested otherwise.',
level: 'user',
tags: ['language', 'communication'],
},
{ content: 'Reply in Spanish for project explanations.', level: 'user', tags: ['communication'] },
{ content: 'Prefers tabs over spaces', level: 'user', tags: ['style'] },
];
const provider = createMockProvider(JSON.stringify(llmPayload));

const result = await extractAndSaveSessionMemories({
llm: provider,
memoryManager,
conversationHistory: buildHistory(3),
workspaceRoot: '/workspace',
});

expect(result.map((memory) => memory.content)).toEqual(['Prefers tabs over spaces']);
expect(memoryManager.store).toHaveBeenCalledTimes(1);
const prompt = JSON.stringify((provider.complete as ReturnType<typeof vi.fn>).mock.calls[0]);
expect(prompt).toContain('Never save which language to respond in');
});

it('returns empty array when LLM returns empty array', async () => {
const provider = createMockProvider('[]');
const deps: ExtractionDeps = {
Expand Down
Loading