11 Commits

Author SHA1 Message Date
Julian Freeman
db848bed92 upgrade 2026-04-05 14:45:37 -04:00
Julian Freeman
280376a88e fix bug 2026-04-05 14:26:05 -04:00
Julian Freeman
984f5d73dd fix scroll action 2026-04-05 13:36:56 -04:00
Julian Freeman
732d1906f6 fix refine model 2026-04-05 13:05:52 -04:00
Julian Freeman
785df4c5a5 fix log bug 2026-04-05 12:59:53 -04:00
Julian Freeman
f8785f4395 optimize prompts 2026-04-05 12:55:50 -04:00
Julian Freeman
a8967809a2 add translate again and delete 2026-04-05 12:07:18 -04:00
Julian Freeman
e2b6340446 add chat sys prompts to settings 2026-04-05 12:01:54 -04:00
Julian Freeman
9dbce266b4 support eval again 2026-04-05 11:33:14 -04:00
Julian Freeman
bba1123176 fix model 2026-04-05 11:23:43 -04:00
Julian Freeman
939a0a46cd optimize chat audit 2026-04-05 11:19:02 -04:00
7 changed files with 470 additions and 161 deletions

View File

@@ -1,7 +1,7 @@
{
"name": "ai-translate-client",
"private": true,
"version": "0.3.7",
"version": "0.3.8",
"type": "module",
"scripts": {
"dev": "vite",

2
src-tauri/Cargo.lock generated
View File

@@ -19,7 +19,7 @@ dependencies = [
[[package]]
name = "ai-translate-client"
version = "0.3.7"
version = "0.3.8"
dependencies = [
"futures-util",
"reqwest 0.12.28",

View File

@@ -1,6 +1,6 @@
[package]
name = "ai-translate-client"
version = "0.3.7"
version = "0.3.8"
description = "A client using AI models to translate"
authors = ["Julian"]
edition = "2021"

View File

@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "ai-translate-client",
"version": "0.3.7",
"version": "0.3.8",
"identifier": "top.volan.ai-translate-client",
"build": {
"beforeDevCommand": "pnpm dev",

View File

@@ -4,16 +4,13 @@ import {
Plus, Search, Trash2, Send, User, Type, ChevronDown, Check,
MessageSquare, Loader2, Copy,
X, Sparkles, Languages, Venus, Mars, CircleSlash,
ShieldCheck, TriangleAlert, AlertCircle
ShieldCheck, RotateCcw
} from 'lucide-vue-next';
import {
useSettingsStore,
LANGUAGES,
SPEAKER_IDENTITY_OPTIONS,
TONE_REGISTER_OPTIONS,
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
type Participant
} from '../stores/settings';
import { cn } from '../lib/utils';
@@ -43,6 +40,16 @@ const newSessionPartner = ref<Participant>({
tone: 'Auto-detect'
});
// Audit Modal States
const isAuditModalOpen = ref(false);
const currentAuditMessageId = ref<string | null>(null);
const selectedSuggestionIds = ref<number[]>([]);
const activeAuditMessage = computed(() => {
if (!activeSession.value || !currentAuditMessageId.value) return null;
return activeSession.value.messages.find(m => m.id === currentAuditMessageId.value) || null;
});
// Custom Dropdown States for Modal
const meLangDropdownOpen = ref(false);
const meGenderDropdownOpen = ref(false);
@@ -113,7 +120,12 @@ onMounted(async () => {
settings.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, {
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload
});
scrollToBottom();
// 优化:只有当正在流式输出的消息是最后一条时,才自动滚动到底部
const lastMsg = activeSession.value.messages[activeSession.value.messages.length - 1];
if (lastMsg && lastMsg.id === currentStreamingMessageId.value) {
scrollToBottom();
}
}
});
});
@@ -125,33 +137,45 @@ const generateCurl = (baseUrl: string, key: string, body: any) => {
return `curl "${fullUrl}" \\\n -H "Content-Type: application/json" \\\n -H "Authorization: Bearer ${maskedKey}" \\\n -d '${JSON.stringify(body, null, 2)}'`;
};
const translateMessage = async (sender: 'me' | 'partner') => {
const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string) => {
if (!activeSession.value || isTranslating.value) return;
const text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim();
if (!text) return;
let text = '';
let messageId = '';
if (retranslateId) {
const msg = activeSession.value.messages.find(m => m.id === retranslateId);
if (!msg) return;
text = msg.original;
messageId = retranslateId;
settings.updateChatMessage(activeSession.value.id, messageId, { translated: '', evaluation: undefined });
} else {
text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim();
if (!text) return;
const newId = settings.addMessageToSession(activeSession.value.id, sender, text, '');
if (!newId) return;
messageId = newId;
if (sender === 'me') myInput.value = ''; else partnerInput.value = '';
}
isTranslating.value = true;
// 1. Add message to session
const messageId = settings.addMessageToSession(activeSession.value.id, sender, text, '');
if (!messageId) {
isTranslating.value = false;
return;
}
currentStreamingMessageId.value = messageId;
if (sender === 'me') myInput.value = ''; else partnerInput.value = '';
await scrollToBottom();
// 只有新消息才自动滚动到底部,重新翻译不滚动
if (!retranslateId) {
await scrollToBottom();
}
// 2. Prepare Context
const historyLimit = 10;
const sessionMessages = activeSession.value.messages;
// 重新翻译时,排除当前这条消息本身作为历史
const recentMessages = sessionMessages.filter(m => m.id !== messageId).slice(-historyLimit);
const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
return `${senderName}: "${m.original}"`;
}).join('\n');
// 3. Prepare Prompt
@@ -159,7 +183,7 @@ const translateMessage = async (sender: 'me' | 'partner') => {
const toLang = sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
const systemPrompt = CONVERSATION_SYSTEM_PROMPT_TEMPLATE
const systemPrompt = settings.chatSystemPromptTemplate
.replace(/{ME_NAME}/g, activeSession.value.me.name)
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
@@ -180,7 +204,7 @@ const translateMessage = async (sender: 'me' | 'partner') => {
stream: settings.enableStreaming
};
settings.addLog('request', { type: 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
settings.addLog('request', { type: retranslateId ? 'conversation-retranslate' : 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
try {
const response = await invoke<string>('translate', {
@@ -195,7 +219,7 @@ const translateMessage = async (sender: 'me' | 'partner') => {
const translatedText = fullResponseJson.choices?.[0]?.message?.content || response;
settings.updateChatMessage(activeSession.value.id, messageId, { translated: translatedText });
} else {
settings.addLog('response', '(Streaming output captured)');
settings.addLog('response', response);
}
} catch (err: any) {
const errorMsg = String(err);
@@ -204,30 +228,53 @@ const translateMessage = async (sender: 'me' | 'partner') => {
} finally {
isTranslating.value = false;
currentStreamingMessageId.value = null;
scrollToBottom();
// 只有新消息才滚动到底部
if (!retranslateId) {
scrollToBottom();
}
}
};
const evaluateMessage = async (messageId: string) => {
const deleteMessage = (messageId: string) => {
if (!activeSession.value) return;
settings.deleteChatMessage(activeSession.value.id, messageId);
};
const evaluateMessage = async (messageId: string, force = false) => {
if (!activeSession.value) return;
const msg = activeSession.value.messages.find(m => m.id === messageId);
if (!msg || msg.isEvaluating) return;
if (!msg) return;
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true });
currentAuditMessageId.value = messageId;
selectedSuggestionIds.value = [];
await nextTick();
isAuditModalOpen.value = true;
if (!force && (msg.evaluation || msg.isEvaluating)) return;
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true, evaluation: undefined });
const historyLimit = 10;
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
// 净化历史:只提供原文流
const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
return `${senderName}: "${m.original}"`;
}).join('\n');
// 动态确定语言方向
const fromLang = msg.sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
const toLang = msg.sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
const senderName = msg.sender === 'me' ? activeSession.value.me.name : activeSession.value.partner.name;
// 动态确定目标语气约束
const targetTone = msg.sender === 'me'
? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和')
: '自动识别 (保留原作者原始语气和情绪)';
const systemPrompt = CONVERSATION_EVALUATION_PROMPT_TEMPLATE
const systemPrompt = settings.chatEvaluationPromptTemplate
.replace(/{ME_NAME}/g, activeSession.value.me.name)
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
@@ -235,12 +282,31 @@ const evaluateMessage = async (messageId: string) => {
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None')
.replace(/{TARGET_TONE}/g, targetTone);
.replace(/{TARGET_TONE}/g, targetTone)
.replace(/{SENDER_NAME}/g, senderName)
.replace(/{FROM_LANG}/g, fromLang.englishName)
.replace(/{TO_LANG}/g, toLang.englishName)
.replace(/{ORIGINAL_TEXT}/g, msg.original)
.replace(/{CURRENT_TRANSLATION}/g, msg.translated);
const userPrompt = `[Source Text]\n${msg.original}\n\n[Current Translation]\n${msg.translated}`;
// 使用审计专用配置
let evalApiBaseUrl = settings.apiBaseUrl;
let evalApiKey = settings.apiKey;
let evalModelName = settings.modelName;
if (settings.evaluationProfileId) {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
if (profile) {
evalApiBaseUrl = profile.apiBaseUrl;
evalApiKey = profile.apiKey;
evalModelName = profile.modelName;
}
}
const requestBody = {
model: settings.modelName,
model: evalModelName,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt }
@@ -248,12 +314,12 @@ const evaluateMessage = async (messageId: string) => {
stream: false
};
settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(evalApiBaseUrl, evalApiKey, requestBody));
try {
const response = await invoke<string>('translate', {
apiAddress: settings.apiBaseUrl,
apiKey: settings.apiKey,
apiAddress: evalApiBaseUrl,
apiKey: evalApiKey,
payload: requestBody
});
const fullResponseJson = JSON.parse(response);
@@ -264,10 +330,15 @@ const evaluateMessage = async (messageId: string) => {
settings.addLog('error', String(err));
} finally {
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false });
scrollToBottom();
}
};
const toggleSuggestion = (id: number) => {
const index = selectedSuggestionIds.value.indexOf(id);
if (index > -1) selectedSuggestionIds.value.splice(index, 1);
else selectedSuggestionIds.value.push(id);
};
const refineMessage = async (messageId: string) => {
if (!activeSession.value) return;
const msg = activeSession.value.messages.find(m => m.id === messageId);
@@ -275,24 +346,37 @@ const refineMessage = async (messageId: string) => {
let evalData;
try {
evalData = JSON.parse(msg.evaluation);
evalData = parseEvaluation(msg.evaluation);
} catch (e) { return; }
const suggestionsText = evalData.suggestions.map((s: any) => `- ${s.text} (Importance: ${s.importance})`).join('\n');
// 仅使用选中的建议
const selectedSuggestions = evalData.suggestions.filter((s: any) => selectedSuggestionIds.value.includes(s.id));
if (selectedSuggestions.length === 0) return;
const suggestionsText = selectedSuggestions.map((s: any) => `- ${s.text}`).join('\n');
isAuditModalOpen.value = false; // 关闭弹窗开始润色
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' });
currentStreamingMessageId.value = messageId;
const historyLimit = 10;
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
// 净化历史:只提供原文流
const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
return `${senderName}: "${m.original}"`;
}).join('\n');
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
const systemPrompt = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE
// 确定目标语气
const targetTone = msg.sender === 'me' ? myToneLabel : '自动识别 (保持原作者原始语气和情绪)';
// 动态确定语言方向
const fromLang = msg.sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
const toLang = msg.sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
const systemPrompt = settings.chatRefinementPromptTemplate
.replace(/{ME_NAME}/g, activeSession.value.me.name)
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
@@ -300,12 +384,29 @@ const refineMessage = async (messageId: string) => {
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None')
.replace(/{ORIGINAL_TEXT}/g, msg.original)
.replace(/{CURRENT_TRANSLATION}/g, msg.translated)
.replace(/{SUGGESTIONS}/g, suggestionsText)
.replace(/{MY_TONE}/g, myToneLabel);
.replace(/{TARGET_TONE}/g, targetTone)
.replace(/{FROM_LANG}/g, fromLang.englishName)
.replace(/{TO_LANG}/g, toLang.englishName);
// 使用审计专用配置
let refineApiBaseUrl = settings.apiBaseUrl;
let refineApiKey = settings.apiKey;
let refineModelName = settings.modelName;
if (settings.evaluationProfileId) {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
if (profile) {
refineApiBaseUrl = profile.apiBaseUrl;
refineApiKey = profile.apiKey;
refineModelName = profile.modelName;
}
}
const requestBody = {
model: settings.modelName,
model: refineModelName,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: `Please refine the following original text: ${msg.original}` }
@@ -313,26 +414,34 @@ const refineMessage = async (messageId: string) => {
stream: settings.enableStreaming
};
settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(refineApiBaseUrl, refineApiKey, requestBody));
try {
const response = await invoke<string>('translate', {
apiAddress: settings.apiBaseUrl,
apiKey: settings.apiKey,
apiAddress: refineApiBaseUrl,
apiKey: refineApiKey,
payload: requestBody
});
if (!settings.enableStreaming) {
const fullResponseJson = JSON.parse(response);
settings.addLog('response', fullResponseJson);
const refinedText = fullResponseJson.choices?.[0]?.message?.content || response;
settings.updateChatMessage(activeSession.value.id, messageId, { translated: refinedText });
} else {
settings.addLog('response', response);
}
} catch (err: any) {
settings.addLog('error', String(err));
} finally {
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined });
currentStreamingMessageId.value = null;
scrollToBottom();
// 只有当润色的是最后一条消息时才滚动到底部
const lastMsg = activeSession.value.messages[activeSession.value.messages.length - 1];
if (lastMsg && lastMsg.id === messageId) {
scrollToBottom();
}
}
};
@@ -351,18 +460,6 @@ const parseEvaluation = (evalStr?: string) => {
}
};
const getSeverityColor = (importance: number) => {
if (importance >= 80) return 'text-red-500 bg-red-50 dark:bg-red-900/20 border-red-100 dark:border-red-900/30';
if (importance >= 40) return 'text-amber-500 bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-900/30';
return 'text-blue-500 bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/30';
};
const getSeverityIcon = (importance: number) => {
if (importance >= 80) return AlertCircle;
if (importance >= 40) return TriangleAlert;
return ShieldCheck;
};
const handleGlobalClick = () => {
myToneDropdownOpen.value = false;
closeAllModalDropdowns();
@@ -499,7 +596,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</p>
<!-- Translated Text -->
<div class="relative min-h-[1.5rem]">
<div class="relative min-h-6">
<p :class="cn('text-base font-medium leading-relaxed', msg.sender === 'me' ? 'text-white' : 'text-slate-800 dark:text-slate-100')">
{{ msg.translated }}
<span v-if="isTranslating && currentStreamingMessageId === msg.id" class="inline-block w-1.5 h-4 bg-current animate-pulse ml-0.5 align-middle"></span>
@@ -509,7 +606,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<!-- Action Tools (Copy, Evaluate, Refine) -->
<div :class="cn(
'absolute top-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center bg-white/90 dark:bg-slate-800/90 rounded-full shadow-lg border dark:border-slate-700 px-1 py-1 z-20',
msg.sender === 'me' ? '-left-24' : '-right-24'
msg.sender === 'me' ? '-left-32' : '-right-32'
)">
<button
@click="copyWithFeedback(msg.translated, msg.id)"
@@ -519,6 +616,15 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<Check v-if="activeCopyId === msg.id" class="w-3.5 h-3.5 text-green-600" />
<Copy v-else class="w-3.5 h-3.5 text-slate-400" />
</button>
<button
@click="translateMessage(msg.sender, msg.id)"
:disabled="isTranslating || msg.isEvaluating || msg.isRefining"
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
title="重新翻译"
>
<RotateCcw v-if="isTranslating && currentStreamingMessageId === msg.id" class="w-3.5 h-3.5 animate-spin text-blue-500" />
<RotateCcw v-else class="w-3.5 h-3.5 text-slate-400" />
</button>
<button
@click="evaluateMessage(msg.id)"
:disabled="msg.isEvaluating || msg.isRefining"
@@ -529,66 +635,14 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<ShieldCheck v-else class="w-3.5 h-3.5 text-slate-400" />
</button>
<button
v-if="msg.evaluation"
@click="refineMessage(msg.id)"
:disabled="msg.isRefining"
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
title="执行润色"
@click="deleteMessage(msg.id)"
class="p-1.5 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-full transition-colors group/del"
title="删除消息"
>
<Loader2 v-if="msg.isRefining" class="w-3.5 h-3.5 animate-spin text-purple-500" />
<Sparkles v-else class="w-3.5 h-3.5 text-purple-400" />
<Trash2 class="w-3.5 h-3.5 text-slate-400 group-hover/del:text-red-500" />
</button>
</div>
</div>
<!-- Evaluation Results -->
<transition
enter-active-class="transition duration-200 ease-out"
enter-from-class="transform -translate-y-2 opacity-0"
enter-to-class="transform translate-y-0 opacity-100"
>
<div v-if="msg.evaluation" class="mt-2 w-full max-w-sm">
<div class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm border border-slate-200 dark:border-slate-800 rounded-xl p-3 shadow-sm space-y-3">
<!-- Score & Analysis -->
<div class="flex items-start gap-2.5">
<div :class="cn(
'shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-xs font-black',
parseEvaluation(msg.evaluation).score >= 90 ? 'bg-green-100 text-green-600 dark:bg-green-900/30' :
parseEvaluation(msg.evaluation).score >= 75 ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30' :
'bg-red-100 text-red-600 dark:bg-red-900/30'
)">
{{ parseEvaluation(msg.evaluation).score }}
</div>
<p class="text-[11px] text-slate-600 dark:text-slate-400 leading-relaxed italic">
{{ parseEvaluation(msg.evaluation).analysis }}
</p>
</div>
<!-- Suggestions with Severity -->
<div class="space-y-1.5">
<div
v-for="sug in parseEvaluation(msg.evaluation).suggestions"
:key="sug.id"
:class="cn('flex items-center gap-2 px-2 py-1.5 rounded-lg border text-[10px] font-medium transition-all', getSeverityColor(sug.importance))"
>
<component :is="getSeverityIcon(sug.importance)" class="w-3 h-3 shrink-0" />
<span class="flex-1">{{ sug.text }}</span>
</div>
</div>
<!-- Refine Action -->
<button
@click="refineMessage(msg.id)"
:disabled="msg.isRefining"
class="w-full py-1.5 bg-purple-50 hover:bg-purple-100 dark:bg-purple-900/20 dark:hover:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-lg text-[10px] font-bold transition-all flex items-center justify-center gap-1.5"
>
<Loader2 v-if="msg.isRefining" class="w-3 h-3 animate-spin" />
<Sparkles v-else class="w-3 h-3" />
{{ msg.isRefining ? '正在润色...' : '根据建议执行润色' }}
</button>
</div>
</div>
</transition>
</div>
</div>
@@ -747,7 +801,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95"
>
<div v-if="isCreatingSession" class="absolute inset-0 z-[100] flex items-center justify-center p-6 bg-slate-900/20 backdrop-blur-sm">
<div v-if="isCreatingSession" class="absolute inset-0 z-100 flex items-center justify-center p-6 bg-slate-900/20 backdrop-blur-sm">
<div class="w-full max-w-lg bg-white dark:bg-slate-900 rounded-3xl shadow-2xl border dark:border-slate-800">
<div class="p-6 border-b dark:border-slate-800 flex items-center justify-between bg-slate-50 dark:bg-slate-950 rounded-t-3xl">
<h3 class="text-lg font-bold dark:text-slate-100 flex items-center gap-2">
@@ -778,7 +832,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ newSessionMe.language.displayName }}
<ChevronDown class="w-4 h-4 text-slate-400" />
</button>
<div v-if="meLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2 custom-scrollbar">
<div v-if="meLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-110 py-2 custom-scrollbar">
<button v-for="lang in LANGUAGES" :key="lang.code" @click="newSessionMe.language = lang; meLangDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
{{ lang.displayName }}
<Check v-if="newSessionMe.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
@@ -798,7 +852,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionMe.gender)?.label }}
<ChevronDown class="w-4 h-4 text-slate-400" />
</button>
<div v-if="meGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2">
<div v-if="meGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-110 py-2">
<button v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" @click="newSessionMe.gender = opt.value; meGenderDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
{{ opt.label }}
<Check v-if="newSessionMe.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
@@ -827,7 +881,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ newSessionPartner.language.displayName }}
<ChevronDown class="w-4 h-4 text-slate-400" />
</button>
<div v-if="partnerLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2 custom-scrollbar">
<div v-if="partnerLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-110 py-2 custom-scrollbar">
<button v-for="lang in LANGUAGES" :key="lang.code" @click="newSessionPartner.language = lang; partnerLangDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
{{ lang.displayName }}
<Check v-if="newSessionPartner.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
@@ -847,7 +901,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionPartner.gender)?.label }}
<ChevronDown class="w-4 h-4 text-slate-400" />
</button>
<div v-if="partnerGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2">
<div v-if="partnerGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-110 py-2">
<button v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" @click="newSessionPartner.gender = opt.value; partnerGenderDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
{{ opt.label }}
<Check v-if="newSessionPartner.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
@@ -869,7 +923,144 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div>
</div>
</transition>
</div>
<!-- Audit Modal -->
<transition
enter-active-class="transition duration-300 ease-out"
enter-from-class="opacity-0 scale-95"
enter-to-class="opacity-100 scale-100"
leave-active-class="transition duration-200 ease-in"
leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95"
>
<div v-if="isAuditModalOpen && activeAuditMessage" class="fixed inset-0 z-999 flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-md">
<div class="w-full max-w-xl bg-white dark:bg-slate-900 rounded-[2.5rem] shadow-2xl border dark:border-slate-800 flex flex-col max-h-[90vh] overflow-hidden">
<!-- Header -->
<div class="px-8 py-6 border-b dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-950/50 shrink-0">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-2xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600">
<ShieldCheck class="w-6 h-6" />
</div>
<div>
<h3 class="text-lg font-bold dark:text-slate-100">翻译质量审计</h3>
<p class="text-[10px] text-slate-400 font-bold uppercase tracking-widest">Quality Audit & Refinement</p>
</div>
</div>
<button @click="isAuditModalOpen = false" class="p-2.5 hover:bg-slate-200 dark:hover:bg-slate-800 rounded-full transition-colors">
<X class="w-5 h-5 text-slate-400" />
</button>
</div>
<!-- Content -->
<div class="flex-1 overflow-y-auto p-8 space-y-8 custom-scrollbar">
<!-- Score & Analysis -->
<section class="space-y-4">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<div :class="cn(
'w-2 h-2 rounded-full',
activeAuditMessage.isEvaluating ? 'bg-blue-400 animate-pulse' : (parseEvaluation(activeAuditMessage.evaluation)?.score >= 80 ? 'bg-green-500' : 'bg-red-500')
)"></div>
<h4 class="text-xs font-black text-slate-400 uppercase tracking-widest">总体评价</h4>
</div>
<div v-if="activeAuditMessage.evaluation" :class="cn(
'text-3xl font-black font-mono leading-none',
parseEvaluation(activeAuditMessage.evaluation).score >= 80 ? 'text-green-600' : 'text-red-600'
)">
{{ parseEvaluation(activeAuditMessage.evaluation).score }}<span class="text-sm font-normal opacity-30 ml-1">/ 100</span>
</div>
</div>
<div v-if="activeAuditMessage.isEvaluating" class="py-10 flex flex-col items-center justify-center space-y-4">
<Loader2 class="w-10 h-10 animate-spin text-blue-500" />
<p class="text-sm text-slate-400 font-medium animate-pulse">正在深度分析译文...</p>
</div>
<div v-else-if="activeAuditMessage.evaluation" class="bg-slate-50 dark:bg-slate-800/40 p-5 rounded-2xl border border-slate-100 dark:border-slate-800/60">
<p class="text-sm text-slate-600 dark:text-slate-300 leading-relaxed italic">
"{{ parseEvaluation(activeAuditMessage.evaluation).analysis }}"
</p>
</div>
</section>
<!-- Suggestions -->
<section v-if="parseEvaluation(activeAuditMessage.evaluation)?.suggestions?.length" class="space-y-4">
<div class="flex items-center gap-2">
<div class="w-2 h-2 rounded-full bg-blue-500"></div>
<h4 class="text-xs font-black text-slate-400 uppercase tracking-widest">修改建议 (点击勾选)</h4>
</div>
<div class="space-y-3">
<div
v-for="sug in parseEvaluation(activeAuditMessage.evaluation).suggestions"
:key="sug.id"
@click="toggleSuggestion(sug.id)"
:class="cn(
'flex items-start gap-4 p-4 rounded-2xl border transition-all cursor-pointer group',
selectedSuggestionIds.includes(sug.id)
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 ring-2 ring-blue-500/10'
: 'bg-white dark:bg-slate-800/40 border-slate-100 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700'
)"
>
<div :class="cn(
'w-5 h-5 rounded-lg border mt-0.5 shrink-0 flex items-center justify-center transition-all',
selectedSuggestionIds.includes(sug.id) ? 'bg-blue-600 border-blue-600 scale-110' : 'border-slate-300 dark:border-slate-600'
)">
<Check v-if="selectedSuggestionIds.includes(sug.id)" class="w-3.5 h-3.5 text-white" stroke-width="4" />
</div>
<div class="flex-1 space-y-2.5 min-w-0">
<p class="text-[13px] font-medium text-slate-700 dark:text-slate-200 leading-normal">{{ sug.text }}</p>
<!-- Importance Bar -->
<div class="flex items-center gap-3">
<div class="flex-1 h-1.5 bg-slate-100 dark:bg-slate-700/50 rounded-full overflow-hidden">
<div
class="h-full rounded-full transition-all duration-1000 ease-out"
:class="sug.importance >= 80 ? 'bg-red-500' : sug.importance >= 40 ? 'bg-amber-500' : 'bg-blue-500'"
:style="{ width: `${sug.importance}%` }"
></div>
</div>
<span class="text-[10px] font-black opacity-30 font-mono w-8 shrink-0">{{ sug.importance }}%</span>
</div>
</div>
</div>
</div>
</section>
</div>
<!-- Footer Action -->
<div class="p-8 border-t dark:border-slate-800 bg-slate-50/50 dark:bg-slate-950/50 flex items-center gap-4 shrink-0">
<button
v-if="activeAuditMessage.evaluation && !activeAuditMessage.isEvaluating"
@click="evaluateMessage(activeAuditMessage.id, true)"
class="p-4 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-500 dark:text-slate-400 rounded-2xl font-bold transition-all shrink-0"
title="重新审计"
>
<RotateCcw class="w-5 h-5" />
</button>
<button
@click="isAuditModalOpen = false"
class="flex-1 py-4 bg-slate-200 dark:bg-slate-800 hover:bg-slate-300 dark:hover:bg-slate-700 text-slate-600 dark:text-slate-300 rounded-2xl font-bold transition-all"
>
取消
</button>
<button
@click="refineMessage(activeAuditMessage.id)"
:disabled="activeAuditMessage.isRefining || activeAuditMessage.isEvaluating || selectedSuggestionIds.length === 0"
class="flex-2 py-4 bg-blue-600 hover:bg-blue-700 text-white rounded-2xl font-bold shadow-xl shadow-blue-500/20 transition-all disabled:opacity-50 disabled:shadow-none flex items-center justify-center gap-2"
>
<Loader2 v-if="activeAuditMessage.isRefining" class="w-5 h-5 animate-spin" />
<Sparkles v-else class="w-5 h-5" />
{{ activeAuditMessage.isRefining ? '正在润色...' : '应用选中建议并润色' }}
</button>
</div>
</div>
</div>
</transition>
</div>
</template>

View File

@@ -1,11 +1,20 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil } from 'lucide-vue-next';
import { useSettingsStore, DEFAULT_TEMPLATE, DEFAULT_EVALUATION_TEMPLATE, DEFAULT_REFINEMENT_TEMPLATE, type ApiProfile } from '../stores/settings';
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil, MessageSquare } from 'lucide-vue-next';
import {
useSettingsStore,
DEFAULT_TEMPLATE,
DEFAULT_EVALUATION_TEMPLATE,
DEFAULT_REFINEMENT_TEMPLATE,
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
type ApiProfile
} from '../stores/settings';
import { cn } from '../lib/utils';
const settings = useSettingsStore();
const settingsCategory = ref<'api' | 'general' | 'prompts'>('api');
const settingsCategory = ref<'api' | 'general' | 'prompts' | 'chat-prompts'>('api');
const showApiKey = ref(false);
const newProfileName = ref('');
@@ -129,6 +138,18 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div>
提示词工程
</button>
<button
@click="settingsCategory = 'chat-prompts'"
:class="cn(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors',
settingsCategory === 'chat-prompts' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800/50'
)"
>
<div :class="cn('p-1.5 rounded-md', settingsCategory === 'chat-prompts' ? 'bg-blue-100 dark:bg-blue-900/50' : 'bg-slate-100 dark:bg-slate-800')">
<MessageSquare class="w-4 h-4" />
</div>
对话提示词
</button>
</nav>
</div>
@@ -490,6 +511,82 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div>
</template>
<!-- Chat Prompt Engineering -->
<template v-if="settingsCategory === 'chat-prompts'">
<div class="mb-6 border-b dark:border-slate-800 pb-4">
<h1 class="text-2xl font-bold text-slate-800 dark:text-slate-100">对话提示词</h1>
<p class="text-sm text-slate-500 dark:text-slate-400 mt-1">专门针对对话模式优化的系统指令模板</p>
</div>
<div class="space-y-8">
<!-- Chat Translation Prompt -->
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
<div class="flex items-center gap-2">
<div class="w-2 h-2 rounded-full bg-blue-500"></div>
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话翻译指令</h3>
</div>
<button @click="settings.chatSystemPromptTemplate = CONVERSATION_SYSTEM_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
</div>
<textarea
v-model="settings.chatSystemPromptTemplate"
rows="10"
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
spellcheck="false"
></textarea>
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
<div class="flex flex-wrap gap-1.5">
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{FROM_LANG}', '{TO_LANG}', '{MY_TONE}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
</div>
</div>
</div>
<!-- Chat Evaluation Prompt -->
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
<div class="flex items-center gap-2">
<div class="w-2 h-2 rounded-full bg-amber-500"></div>
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话审计指令</h3>
</div>
<button @click="settings.chatEvaluationPromptTemplate = CONVERSATION_EVALUATION_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
</div>
<textarea
v-model="settings.chatEvaluationPromptTemplate"
rows="12"
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
spellcheck="false"
></textarea>
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
<div class="flex flex-wrap gap-1.5">
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
</div>
</div>
</div>
<!-- Chat Refinement Prompt -->
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
<div class="flex items-center gap-2">
<div class="w-2 h-2 rounded-full bg-green-500"></div>
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话润色指令</h3>
</div>
<button @click="settings.chatRefinementPromptTemplate = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
</div>
<textarea
v-model="settings.chatRefinementPromptTemplate"
rows="10"
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
spellcheck="false"
></textarea>
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
<div class="flex flex-wrap gap-1.5">
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}', '{SUGGESTIONS}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
</div>
</div>
</div>
</div>
</template>
</div>
</div>
</div>

View File

@@ -157,7 +157,7 @@ export interface ChatSession {
export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `You are a professional real-time conversation translator.
Current Context:
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}.
- Role B (Partner): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
- Role B (Other): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
[Conversation History]
{HISTORY_BLOCK}
@@ -169,36 +169,41 @@ Translate the incoming text from {FROM_LANG} to {TO_LANG}.
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
2. Tone & Register:
- If translating for 'Me', strictly use the tone: {MY_TONE}.
- If translating for 'Partner', auto-detect and preserve their original tone/emotion.
- If translating for 'Other', auto-detect and preserve their original tone/emotion.
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese".
4. Strictly avoid over-translation: Do not add extra information not present in the source text.
5. Output ONLY the translated text, no explanations.`;
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role
You are an expert Conversation Auditor. Your task is to evaluate if the [Current Translation] accurately reflects the [Source Text] within the specific flow of the [Conversation History].
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role: Expert Conversation Auditor
# Context Info
- Me: {ME_NAME} ({ME_GENDER}, {ME_LANG})
- Partner: {PART_NAME} ({PART_GENDER}, {PART_LANG})
- Target Tone: {TARGET_TONE}
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
[Conversation History]
# Recent Conversation Flow (Original Messages Only):
{HISTORY_BLOCK}
# Current Turn to Audit:
- Speaker: {SENDER_NAME}
- Direction: {FROM_LANG} -> {TO_LANG}
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
- Translation ({TO_LANG}): {CURRENT_TRANSLATION}
# Audit Priorities
1. **Contextual Accuracy**: Do pronouns (it, that, etc.) correctly point to objects/topics mentioned in the [Conversation History]?
2. **Relational Tone**: Does the translation match the [Target Tone]? (e.g., if set to 'Polite', is it too casual?)
3. **Consistency**: Are names, terms, or previously established facts handled consistently?
4. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment?
1. **Contextual Accuracy**: Does the translation correctly reflect the meaning based on the [Recent Conversation Flow]?
2. **Relational Tone**:
- If the Speaker is 'Me', does it match the target tone({TARGET_TONE})?
- If the Speaker is 'Other', does it preserve their original tone/emotion?
3. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment?
# Instructions
1. Analyze the [Source Text] and [Current Translation] against the history.
2. Scoring: 0-100.
3. Suggestions: Provide actionable improvements.
4. **Severity Level**: For each suggestion, assign an "importance" score (0-100).
- **80-100 (Critical)**: Misunderstanding meaning, wrong pronoun reference, or offensive tone.
- **40-79 (Moderate)**: Unnatural phrasing, minor tone mismatch.
- **0-39 (Minor)**: Polishing, stylistic preferences.
1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Priorities].
2. **Scoring Strategy**:
- **90-100**: Accurate, grammatically sound, and flows naturally.
- **75-89**: Accurate meaning, but suffers from "stiff" phrasing or minor flow issues that need adjustment.
- **Below 75**: Contains semantic errors, severe grammar issues, or tone mismatches.
3. **Analysis**: Provide a concise explanation in Simplified Chinese. Focus on *why* the error matters (e.g., "meaning is reversed" or "too awkward to read").
4. **Suggestions**: Provide a list of specific, actionable suggestions. For each, assign an "importance" from 0 to 100 (0 = unnecessary/optional, 100 = critical error).
# Output Format
Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese:
@@ -210,29 +215,30 @@ Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese:
]
}`;
export const CONVERSATION_REFINEMENT_PROMPT_TEMPLATE = `You are a professional conversation editor. Refine the [Current Translation] based on the [Audit Suggestions] and [Conversation History].
export const CONVERSATION_REFINEMENT_PROMPT_TEMPLATE = `# Role: Professional Conversation Editor
# Context Info
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}.
- Role B (Partner): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
- Target Tone: {TARGET_TONE}
# Context:
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
[Conversation History]
# Recent Conversation Flow (Original Messages Only):
{HISTORY_BLOCK}
[Current Translation]
{CURRENT_TRANSLATION}
# Current Turn to Refine:
- Speaker: {SENDER_NAME}
- Direction: {FROM_LANG} -> {TO_LANG}
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
- Current Translation ({TO_LANG}): {CURRENT_TRANSLATION}
[Audit Suggestions]
# Suggestions to Apply:
{SUGGESTIONS}
# Task
Produce a new, refined version of the translation that addresses the suggestions while remaining naturally integrated into the conversation flow.
# Constraints
1. Maintain semantic identity with the [Source Text].
2. Strictly follow the {TARGET_TONE}.
3. Output ONLY the refined translation text. No explanations.`;
# Instructions:
1. Carefully review the [Suggestions] and apply the requested improvements to the [Current Translation] while ensuring it fits naturally into the [Recent Conversation Flow].
2. Ensure that the refined translation remains semantically identical to the [Source Text].
3. If the Speaker is 'Me', strictly maintain the target tone({TARGET_TONE}); if the Speaker is 'Other', auto-detect and preserve their original tone/emotion.
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
5. Produce ONLY the refined {TO_LANG} translation, without any additional explanations, notes, or commentary.`;
export const useSettingsStore = defineStore('settings', () => {
const isDark = useLocalStorage('is-dark', false);
@@ -248,6 +254,10 @@ export const useSettingsStore = defineStore('settings', () => {
const evaluationProfileId = useLocalStorage<string | null>('evaluation-profile-id', null);
const refinementPromptTemplate = useLocalStorage('refinement-prompt-template', DEFAULT_REFINEMENT_TEMPLATE);
const chatSystemPromptTemplate = useLocalStorage('chat-system-prompt-template', CONVERSATION_SYSTEM_PROMPT_TEMPLATE);
const chatEvaluationPromptTemplate = useLocalStorage('chat-evaluation-prompt-template', CONVERSATION_EVALUATION_PROMPT_TEMPLATE);
const chatRefinementPromptTemplate = useLocalStorage('chat-refinement-prompt-template', CONVERSATION_REFINEMENT_PROMPT_TEMPLATE);
// 存储整个对象以保持一致性
const sourceLang = useLocalStorage<Language>('source-lang-v2', LANGUAGES[0]);
const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]);
@@ -379,6 +389,13 @@ export const useSettingsStore = defineStore('settings', () => {
}
};
const deleteChatMessage = (sessionId: string, messageId: string) => {
const session = chatSessions.value.find(s => s.id === sessionId);
if (session) {
session.messages = session.messages.filter(m => m.id !== messageId);
}
};
return {
isDark,
apiBaseUrl,
@@ -391,6 +408,9 @@ export const useSettingsStore = defineStore('settings', () => {
evaluationPromptTemplate,
evaluationProfileId,
refinementPromptTemplate,
chatSystemPromptTemplate,
chatEvaluationPromptTemplate,
chatRefinementPromptTemplate,
sourceLang,
targetLang,
speakerIdentity,
@@ -405,6 +425,7 @@ export const useSettingsStore = defineStore('settings', () => {
createSession,
deleteSession,
addMessageToSession,
updateChatMessage
updateChatMessage,
deleteChatMessage
};
});