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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ version with its date and start a fresh empty `[Unreleased]` above it.

## [Unreleased]

### Fixed

- Auto-generated conversation titles, inline edits, and refined instructions
now follow the language of the user's request, falling back to the UI locale
when the language is unclear. Proper nouns, product names, file names, and
code identifiers are preserved.

## [1.0.20] - 2026-11-26

### Fixed
Expand Down
5 changes: 5 additions & 0 deletions src/qoder/prompt/generated-text-language.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { getLocale } from '../../i18n/i18n';

export function buildGeneratedTextLanguageRule(): string {
return `**Language**: Write the generated text in the same language as the user's request. If the request's language is unclear, use the UI locale (\`${getLocale()}\`). Keep proper nouns, product names, file names, paths, code identifiers, and code snippets unchanged; do not translate or rename them.`;
}
5 changes: 5 additions & 0 deletions src/qoder/prompt/inline-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
InlineEditResult,
} from '../../core/types/services';
import { appendContextFiles } from './context/prompt-context';
import { buildGeneratedTextLanguageRule } from './generated-text-language';

export function parseInlineEditResponse(responseText: string): InlineEditResult {
const replacementMatch = responseText.match(/<replacement>([\s\S]*?)<\/replacement>/);
Expand Down Expand Up @@ -88,6 +89,8 @@ You are **Qoderian**, an expert editor and writing assistant embedded in Obsidia
3. **Silent Execution**: Use tools (Read, WebSearch) silently. Your final output must be ONLY the result.
4. **No Fluff**: No pleasantries, no "Here is the text", no "I have updated...". Just the content.

${buildGeneratedTextLanguageRule()}

## Input Format

User messages have the instruction first, followed by XML context tags:
Expand Down Expand Up @@ -174,6 +177,8 @@ CORRECT: "This is a guide about..."

If the request is ambiguous, ask a clarifying question. Keep questions concise and specific.

The examples below illustrate formatting only. Always follow the language rule above for the generated text.

## Examples

### Selection Mode
Expand Down
8 changes: 7 additions & 1 deletion src/qoder/prompt/instruction-refine.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { buildGeneratedTextLanguageRule } from './generated-text-language';

export function buildRefineSystemPrompt(existingInstructions: string): string {
const existingSection = existingInstructions.trim()
? `\n\nEXISTING INSTRUCTIONS (already in the user's system prompt):
Expand All @@ -21,7 +23,7 @@ When refining the new instruction:
2. **Check Context**: Does this conflict with existing instructions?
- *No Conflict*: Add as new.
- *Conflict*: Propose a **merged instruction** that resolves the contradiction (or ask if unsure).
3. **Refine**: Draft a clear, positive instruction (e.g., "Do X" instead of "Don't do Y").
3. **Refine**: Draft a clear, positive instruction.
4. **Format**: Return *only* the Markdown snippet wrapped in \`<instruction>\` tags.

**Guidelines**:
Expand All @@ -31,12 +33,16 @@ When refining the new instruction:
- **No Header**: Do NOT include a top-level header like \`# Custom Instructions\`.
- **Conflict Handling**: If the new rule directly contradicts an existing one, rewrite the *new* one to override specific cases or ask for clarification.

${buildGeneratedTextLanguageRule()}

**Output Format**:
- **Success**: \`<instruction>...markdown content...</instruction>\`
- **Ambiguity**: Plain text question.

${existingSection}

The examples below illustrate formatting only. Always follow the language rule above for the generated text.

**Examples**:

Input: "typescript for code"
Expand Down
12 changes: 9 additions & 3 deletions src/qoder/prompt/title-generation.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import { buildGeneratedTextLanguageRule } from './generated-text-language';

const MAX_TITLE_INPUT_LENGTH = 500;
const MAX_TITLE_LENGTH = 50;

export const TITLE_GENERATION_SYSTEM_PROMPT = `You are a specialist in summarizing user intent.
export function getTitleGenerationSystemPrompt(): string {
return `You are a specialist in summarizing user intent.

**Task**: Generate a **concise, descriptive title** (max 50 chars) summarizing the user's task/request.

**Rules**:
1. **Format**: Sentence case. No periods/quotes.
2. **Structure**: Start with a **strong verb** (e.g., Create, Fix, Debug, Explain, Analyze).
2. **Structure**: Start with a **strong verb** appropriate to the output language.
3. **Forbidden**: "Conversation with...", "Help me...", "Question about...", "I need...".
4. **Tech Context**: Detect and include the primary language/framework if code is present (e.g., "Debug Python script", "Refactor React hook").
4. **Tech Context**: When code is present, include the primary language or framework, preserving product names and code identifiers exactly.

${buildGeneratedTextLanguageRule()}

**Output**: Return ONLY the raw title text.`;
}

export function buildTitleGenerationPrompt(userMessage: string): string {
const truncated = userMessage.length > MAX_TITLE_INPUT_LENGTH
Expand Down
39 changes: 8 additions & 31 deletions src/qoder/services/qoder-title-generation-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import type {
} from '../../core/types/services';
import { toQoderRuntimeModelId } from '../models/model-selection';
import { qoderModelConfig } from '../models/qoder-model-config';
import { TITLE_GENERATION_SYSTEM_PROMPT } from '../prompt/title-generation';
import {
buildTitleGenerationPrompt,
getTitleGenerationSystemPrompt,
parseTitleGenerationResponse,
} from '../prompt/title-generation';
import type { QoderHostContext } from '../qoder-host-context';
import { runColdStartQuery } from '../runtime/qoder-cold-start-query';

Expand Down Expand Up @@ -32,21 +36,20 @@ export class QoderTitleGenerationService {
const abortController = new AbortController();
this.activeGenerations.set(conversationId, abortController);

const truncatedUser = this.truncateText(userMessage, 500);
const prompt = `User's request:\n"""\n${truncatedUser}\n"""\n\nGenerate a title for this conversation:`;
const prompt = buildTitleGenerationPrompt(userMessage);

try {
const result = await runColdStartQuery({
plugin: this.plugin,
systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT,
systemPrompt: getTitleGenerationSystemPrompt(),
tools: [],
model: this.resolveTitleModel(),
thinking: { disabled: true },
persistSession: false,
abortController,
}, prompt);

const title = this.parseTitle(result.text);
const title = parseTitleGenerationResponse(result.text);
if (title) {
await this.safeCallback(callback, conversationId, { success: true, title });
} else {
Expand Down Expand Up @@ -82,32 +85,6 @@ export class QoderTitleGenerationService {
return 'auto';
}

private truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
}

private parseTitle(responseText: string): string | null {
const trimmed = responseText.trim();
if (!trimmed) return null;

let title = trimmed;
if (
(title.startsWith('"') && title.endsWith('"')) ||
(title.startsWith("'") && title.endsWith("'"))
) {
title = title.slice(1, -1);
}

title = title.replace(/[.!?:;,]+$/, '');

if (title.length > 50) {
title = title.substring(0, 47) + '...';
}

return title || null;
}

private async safeCallback(
callback: TitleGenerationCallback,
conversationId: string,
Expand Down
31 changes: 26 additions & 5 deletions tests/unit/qoder/prompt/inline-edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,21 @@ jest.mock('@/core/time/date', () => ({
getTodayDate: () => 'Mocked Date',
}));

import { getLocale, setLocale } from '@/i18n/i18n';
import { getInlineEditSystemPrompt } from '@/qoder/prompt/inline-edit';

describe('getInlineEditSystemPrompt', () => {
let previousLocale: ReturnType<typeof getLocale>;

beforeEach(() => {
previousLocale = getLocale();
setLocale('en');
});

afterEach(() => {
setLocale(previousLocale);
});

it('should include inline edit critical output rules', () => {
const prompt = getInlineEditSystemPrompt();
expect(prompt).toContain('ABSOLUTE RULE');
Expand All @@ -17,16 +29,25 @@ describe('getInlineEditSystemPrompt', () => {
expect(prompt).toContain('read-only');
});

it('should include example scenarios', () => {
it('should use the shared language rule while preserving formatting examples', () => {
const prompt = getInlineEditSystemPrompt();
expect(prompt).toContain('translate to French');
expect(prompt).toContain('Bonjour le monde');
expect(prompt).toContain('asking for clarification');

expect(prompt).toContain("same language as the user's request");
expect(prompt).toContain('UI locale (`en`)');
expect(prompt).toContain('proper nouns, product names, file names, paths, code identifiers, and code snippets unchanged');
expect(prompt).toContain('The examples below illustrate formatting only');
expect(prompt).toContain('<replacement>Bonjour le monde</replacement>');
expect(prompt.indexOf('**Language**')).toBeLessThan(prompt.indexOf('## Examples'));
});

it('should fall back to the current UI locale', () => {
setLocale('zh-CN');

expect(getInlineEditSystemPrompt()).toContain('UI locale (`zh-CN`)');
});

it('should include date from utils', () => {
const prompt = getInlineEditSystemPrompt();
expect(prompt).toContain('Mocked Date');
});

});
40 changes: 22 additions & 18 deletions tests/unit/qoder/prompt/instruction-refine.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import { getLocale, setLocale } from '@/i18n/i18n';
import { buildRefineSystemPrompt } from '@/qoder/prompt/instruction-refine';

describe('buildRefineSystemPrompt', () => {
let previousLocale: ReturnType<typeof getLocale>;

beforeEach(() => {
previousLocale = getLocale();
setLocale('en');
});

afterEach(() => {
setLocale(previousLocale);
});

describe('without existing instructions', () => {
it('should return base prompt when existing instructions is empty', () => {
const result = buildRefineSystemPrompt('');
Expand All @@ -10,7 +22,6 @@ describe('buildRefineSystemPrompt', () => {
expect(result).toContain('**Process**');
expect(result).toContain('**Guidelines**');
expect(result).toContain('**Output Format**');
expect(result).toContain('**Examples**');
});

it('should not include existing instructions section when empty', () => {
Expand Down Expand Up @@ -93,29 +104,22 @@ describe('buildRefineSystemPrompt', () => {
expect(result).toContain('**Ambiguity**');
});

it('should include examples', () => {
it('should use the shared language rule while preserving formatting examples', () => {
const result = buildRefineSystemPrompt('');

expect(result).toContain("same language as the user's request");
expect(result).toContain('UI locale (`en`)');
expect(result).toContain('proper nouns, product names, file names, paths, code identifiers, and code snippets unchanged');
expect(result).toContain('The examples below illustrate formatting only');
expect(result).toContain('Input: "typescript for code"');
expect(result).toContain('Input: "be concise"');
expect(result).toContain('Input: "organize coding style rules"');
expect(result).toContain('Input: "use that thing from before"');
expect(result).not.toContain('"Do X" instead of "Don\'t do Y"');
expect(result.indexOf('**Language**')).toBeLessThan(result.indexOf('**Examples**'));
});

it('should show example outputs with proper tag wrapping', () => {
const result = buildRefineSystemPrompt('');

expect(result).toContain('Output: <instruction>');
expect(result).toContain('**Code Language**');
expect(result).toContain('**Conciseness**');
expect(result).toContain('## Coding Standards');
});

it('should include ambiguity handling example', () => {
const result = buildRefineSystemPrompt('');
it('should fall back to the current UI locale', () => {
setLocale('zh-CN');

expect(result).toContain('I\'m not sure what you\'re referring to');
expect(result).toContain('Could you please clarify');
expect(buildRefineSystemPrompt('')).toContain('UI locale (`zh-CN`)');
});
});

Expand Down
61 changes: 54 additions & 7 deletions tests/unit/qoder/prompt/title-generation.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,67 @@
import { TITLE_GENERATION_SYSTEM_PROMPT } from '@/qoder/prompt/title-generation';
import { getLocale, setLocale } from '@/i18n/i18n';
import {
buildTitleGenerationPrompt,
getTitleGenerationSystemPrompt,
parseTitleGenerationResponse,
} from '@/qoder/prompt/title-generation';

describe('titleGeneration', () => {
let previousLocale: ReturnType<typeof getLocale>;

beforeEach(() => {
previousLocale = getLocale();
setLocale('en');
});

afterEach(() => {
setLocale(previousLocale);
});

it('exports a non-empty system prompt string', () => {
expect(typeof TITLE_GENERATION_SYSTEM_PROMPT).toBe('string');
expect(TITLE_GENERATION_SYSTEM_PROMPT.length).toBeGreaterThan(0);
const prompt = getTitleGenerationSystemPrompt();
expect(typeof prompt).toBe('string');
expect(prompt.length).toBeGreaterThan(0);
});

it('includes the max character constraint', () => {
expect(TITLE_GENERATION_SYSTEM_PROMPT).toContain('max 50 chars');
expect(getTitleGenerationSystemPrompt()).toContain('max 50 chars');
});

it('instructs to start with a strong verb', () => {
expect(TITLE_GENERATION_SYSTEM_PROMPT).toContain('strong verb');
it('instructs to start with a strong verb in the output language', () => {
expect(getTitleGenerationSystemPrompt()).toContain('strong verb');
expect(getTitleGenerationSystemPrompt()).toContain('output language');
});

it('instructs to return only the raw title text', () => {
expect(TITLE_GENERATION_SYSTEM_PROMPT).toContain('ONLY the raw title text');
expect(getTitleGenerationSystemPrompt()).toContain('ONLY the raw title text');
});

it('uses one language rule without English verb or title examples', () => {
const prompt = getTitleGenerationSystemPrompt();

expect(prompt).toContain("same language as the user's request");
expect(prompt).toContain('UI locale (`en`)');
expect(prompt).toContain('proper nouns, product names, file names, paths, code identifiers, and code snippets unchanged');
expect(prompt).not.toContain('Create, Fix, Debug, Explain, Analyze');
expect(prompt).not.toContain('Debug Python script');
expect(prompt).not.toContain('Refactor React hook');
});

it('falls back to the current UI locale', () => {
setLocale('zh-CN');

expect(getTitleGenerationSystemPrompt()).toContain('UI locale (`zh-CN`)');
});

it.each([
['Chinese', '请修复 useReducer 的状态更新'],
['English', 'Fix useReducer state updates'],
['mixed code identifiers', '请修复 Qoderian 中 notes/demo.md 的 useReducer'],
])('preserves %s request text and identifiers', (_language, request) => {
expect(buildTitleGenerationPrompt(request)).toContain(request);
});

it('preserves a Chinese title and its code identifiers', () => {
expect(parseTitleGenerationResponse('修复 Qoderian 的 useReducer')).toBe('修复 Qoderian 的 useReducer');
});
});
Loading