19 Commits

Author SHA1 Message Date
ac5e7f26c6 op 6 2026-04-20 13:36:16 -04:00
53f078154e fix 5 2026-04-20 13:14:43 -04:00
17b91d6ac8 fix 5 2026-04-20 13:08:51 -04:00
f50a176252 fix 4 2026-04-20 13:03:29 -04:00
505c7e612c fix 3 2026-04-20 13:01:00 -04:00
bdad27d6ac fix 2 2026-04-20 12:45:00 -04:00
fbd1728aee fix 1 2026-04-20 12:40:24 -04:00
Julian Freeman
2e7789df63 optimize chat prompts 2026-04-05 17:58:34 -04:00
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
20 changed files with 1316 additions and 650 deletions

View File

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

View File

@@ -1,6 +1,7 @@
# Generated by Cargo # Generated by Cargo
# will have compiled files and executables # will have compiled files and executables
/target/ /target/
/target*/
# Generated by Tauri # Generated by Tauri
# will have schema files for capabilities auto-completion # will have schema files for capabilities auto-completion

2
src-tauri/Cargo.lock generated
View File

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

View File

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

View File

@@ -32,12 +32,19 @@ struct Delta {
content: Option<String>, content: Option<String>,
} }
#[derive(Serialize, Clone)]
struct TranslationChunkEvent {
request_id: String,
chunk: String,
}
#[tauri::command] #[tauri::command]
async fn translate( async fn translate(
app: AppHandle, app: AppHandle,
api_address: String, api_address: String,
api_key: String, api_key: String,
payload: TranslationPayload, payload: TranslationPayload,
request_id: String,
) -> Result<String, String> { ) -> Result<String, String> {
let client = Client::new(); let client = Client::new();
// Ensure URL doesn't have double slashes if api_address ends with / // Ensure URL doesn't have double slashes if api_address ends with /
@@ -55,6 +62,12 @@ async fn translate(
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let status = res.status();
if !status.is_success() {
let error_text = res.text().await.unwrap_or_else(|_| format!("HTTP {}", status));
return Err(format!("HTTP {}: {}", status, error_text));
}
if !payload.stream { if !payload.stream {
let text = res.text().await.map_err(|e| e.to_string())?; let text = res.text().await.map_err(|e| e.to_string())?;
return Ok(text); return Ok(text);
@@ -78,7 +91,11 @@ async fn translate(
if let Some(choice) = json.choices.get(0) { if let Some(choice) = json.choices.get(0) {
if let Some(delta) = &choice.delta { if let Some(delta) = &choice.delta {
if let Some(content) = &delta.content { if let Some(content) = &delta.content {
app.emit("translation-chunk", content).map_err(|e| e.to_string())?; let event = TranslationChunkEvent {
request_id: request_id.clone(),
chunk: content.clone(),
};
app.emit("translation-chunk", event).map_err(|e| e.to_string())?;
} }
} }
} }

View File

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

View File

@@ -6,8 +6,7 @@ import {
FileText, FileText,
Sun, Sun,
Moon, Moon,
Clock, Clock
MessageSquare
} from 'lucide-vue-next'; } from 'lucide-vue-next';
import { useSettingsStore } from './stores/settings'; import { useSettingsStore } from './stores/settings';
import pkg from '../package.json'; import pkg from '../package.json';
@@ -48,6 +47,20 @@ const view = ref<'translate' | 'conversation' | 'settings' | 'logs' | 'history'>
<Languages class="w-6 h-6 text-blue-600 group-hover:scale-110 transition-transform" /> <Languages class="w-6 h-6 text-blue-600 group-hover:scale-110 transition-transform" />
<h1 class="font-semibold text-lg tracking-tight">AI 翻译</h1> <h1 class="font-semibold text-lg tracking-tight">AI 翻译</h1>
</div> </div>
<nav class="flex items-center gap-1 rounded-full bg-slate-200/60 dark:bg-slate-800/70 p-1">
<button
@click="view = 'translate'"
:class="cn('px-4 py-1.5 rounded-full text-sm font-medium transition-colors', view === 'translate' ? 'bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-slate-100' : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200')"
>
单轮翻译
</button>
<button
@click="view = 'conversation'"
:class="cn('px-4 py-1.5 rounded-full text-sm font-medium transition-colors', view === 'conversation' ? 'bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-slate-100' : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200')"
>
多轮翻译
</button>
</nav>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<button <button
@click="toggleTheme" @click="toggleTheme"

View File

@@ -4,24 +4,40 @@ import {
Plus, Search, Trash2, Send, User, Type, ChevronDown, Check, Plus, Search, Trash2, Send, User, Type, ChevronDown, Check,
MessageSquare, Loader2, Copy, MessageSquare, Loader2, Copy,
X, Sparkles, Languages, Venus, Mars, CircleSlash, X, Sparkles, Languages, Venus, Mars, CircleSlash,
ShieldCheck, TriangleAlert, AlertCircle ShieldCheck, RotateCcw
} from 'lucide-vue-next'; } from 'lucide-vue-next';
import { import {
useSettingsStore, useSettingsStore,
} from '../stores/settings';
import {
LANGUAGES, LANGUAGES,
SPEAKER_IDENTITY_OPTIONS, SPEAKER_IDENTITY_OPTIONS,
TONE_REGISTER_OPTIONS, TONE_REGISTER_OPTIONS,
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
type Participant type Participant
} from '../stores/settings'; } from '../domain/translation';
import { useConversationStore } from '../stores/conversation';
import { useLogsStore } from '../stores/logs';
import { cn } from '../lib/utils'; import { cn } from '../lib/utils';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
import { useClipboard } from '../composables/useClipboard'; import { useClipboard } from '../composables/useClipboard';
import {
buildConversationEvaluationUserPrompt,
buildConversationRefinementUserPrompt,
buildConversationSystemPrompt,
buildConversationTranslationUserPrompt,
} from '../lib/prompt-builders';
import {
executeTranslationRequest,
extractAssistantContent,
resolveModelConfig,
tryParseEvaluationResult,
type TranslationChunkEvent,
type TranslationPayload,
} from '../lib/translation-service';
const settings = useSettingsStore(); const settings = useSettingsStore();
const conversationStore = useConversationStore();
const logsStore = useLogsStore();
const { activeCopyId, copyWithFeedback } = useClipboard(); const { activeCopyId, copyWithFeedback } = useClipboard();
// UI States // UI States
@@ -43,6 +59,16 @@ const newSessionPartner = ref<Participant>({
tone: 'Auto-detect' 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 // Custom Dropdown States for Modal
const meLangDropdownOpen = ref(false); const meLangDropdownOpen = ref(false);
const meGenderDropdownOpen = ref(false); const meGenderDropdownOpen = ref(false);
@@ -58,7 +84,7 @@ const closeAllModalDropdowns = () => {
// Current active session // Current active session
const activeSession = computed(() => const activeSession = computed(() =>
settings.chatSessions.find(s => s.id === settings.activeSessionId) || null conversationStore.chatSessions.find(s => s.id === conversationStore.activeSessionId) || null
); );
const scrollToBottom = async (smooth = true) => { const scrollToBottom = async (smooth = true) => {
@@ -72,7 +98,7 @@ const scrollToBottom = async (smooth = true) => {
}; };
// Watch for session switch // Watch for session switch
watch(() => settings.activeSessionId, async (newVal) => { watch(() => conversationStore.activeSessionId, async (newVal) => {
if (newVal) { if (newVal) {
// 切换会话时,先立即滚动到底部(非平滑),然后再等 DOM 渲染完成后尝试平滑滚动确保到位 // 切换会话时,先立即滚动到底部(非平滑),然后再等 DOM 渲染完成后尝试平滑滚动确保到位
await scrollToBottom(false); await scrollToBottom(false);
@@ -81,9 +107,9 @@ watch(() => settings.activeSessionId, async (newVal) => {
}); });
const filteredSessions = computed(() => { const filteredSessions = computed(() => {
if (!searchQuery.value.trim()) return settings.chatSessions; if (!searchQuery.value.trim()) return conversationStore.chatSessions;
const q = searchQuery.value.toLowerCase(); const q = searchQuery.value.toLowerCase();
return settings.chatSessions.filter(s => return conversationStore.chatSessions.filter(s =>
s.title.toLowerCase().includes(q) || s.title.toLowerCase().includes(q) ||
s.partner.name.toLowerCase().includes(q) s.partner.name.toLowerCase().includes(q)
); );
@@ -94,6 +120,7 @@ const myInput = ref('');
const partnerInput = ref(''); const partnerInput = ref('');
const isTranslating = ref(false); const isTranslating = ref(false);
const currentStreamingMessageId = ref<string | null>(null); const currentStreamingMessageId = ref<string | null>(null);
const activeStreamRequestId = ref<string | null>(null);
// Dropdowns // Dropdowns
const myToneDropdownOpen = ref(false); const myToneDropdownOpen = ref(false);
@@ -101,146 +128,188 @@ const myToneDropdownOpen = ref(false);
// Methods // Methods
const handleCreateSession = () => { const handleCreateSession = () => {
if (!newSessionPartner.value.name.trim()) return; if (!newSessionPartner.value.name.trim()) return;
const id = settings.createSession({ ...newSessionMe.value }, { ...newSessionPartner.value }); const id = conversationStore.createSession({ ...newSessionMe.value }, { ...newSessionPartner.value });
isCreatingSession.value = false; isCreatingSession.value = false;
settings.activeSessionId = id; conversationStore.activeSessionId = id;
}; };
let unlisten: (() => void) | null = null; let unlisten: (() => void) | null = null;
onMounted(async () => { onMounted(async () => {
unlisten = await listen<string>('translation-chunk', (event) => { unlisten = await listen<TranslationChunkEvent>('translation-chunk', (event) => {
if (activeSession.value && currentStreamingMessageId.value) { if (
settings.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, { activeSession.value &&
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload currentStreamingMessageId.value &&
event.payload.request_id === activeStreamRequestId.value
) {
conversationStore.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, {
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload.chunk
}); });
scrollToBottom();
// 优化:只有当正在流式输出的消息是最后一条时,才自动滚动到底部
const lastMsg = activeSession.value.messages[activeSession.value.messages.length - 1];
if (lastMsg && lastMsg.id === currentStreamingMessageId.value) {
scrollToBottom();
}
} }
}); });
}); });
onUnmounted(() => { if (unlisten) unlisten(); }); onUnmounted(() => { if (unlisten) unlisten(); });
const generateCurl = (baseUrl: string, key: string, body: any) => { const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string) => {
const fullUrl = `${baseUrl.replace(/\/$/, '')}/chat/completions`;
const maskedKey = key ? `${key.slice(0, 6)}...${key.slice(-4)}` : 'YOUR_API_KEY';
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') => {
if (!activeSession.value || isTranslating.value) return; if (!activeSession.value || isTranslating.value) return;
const text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim(); let text = '';
if (!text) return; let messageId = '';
if (retranslateId) {
const msg = activeSession.value.messages.find(m => m.id === retranslateId);
if (!msg) return;
text = msg.original;
messageId = retranslateId;
conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: '', evaluation: undefined });
} else {
text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim();
if (!text) return;
const newId = conversationStore.addMessageToSession(activeSession.value.id, sender, text, '');
if (!newId) return;
messageId = newId;
if (sender === 'me') myInput.value = ''; else partnerInput.value = '';
}
isTranslating.value = true; 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; currentStreamingMessageId.value = messageId;
if (sender === 'me') myInput.value = ''; else partnerInput.value = ''; // 只有新消息才自动滚动到底部,重新翻译不滚动
await scrollToBottom(); if (!retranslateId) {
await scrollToBottom();
}
// 2. Prepare Context // 2. Prepare Context
const historyLimit = 10; const historyLimit = 10;
const sessionMessages = activeSession.value.messages; const sessionMessages = activeSession.value.messages;
// 重新翻译时,排除当前这条消息本身作为历史
const recentMessages = sessionMessages.filter(m => m.id !== messageId).slice(-historyLimit); const recentMessages = sessionMessages.filter(m => m.id !== messageId).slice(-historyLimit);
const historyBlock = recentMessages.map(m => { const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name; 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'); }).join('\n');
// 3. Prepare Prompt // 3. Prepare Prompt
const fromLang = sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language; const fromLang = sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
const toLang = sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language; 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 targetTone = sender === 'me'
? TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational'
: 'Auto-detect';
const senderName = sender === 'me' ? activeSession.value.me.name : activeSession.value.partner.name;
const systemPrompt = CONVERSATION_SYSTEM_PROMPT_TEMPLATE const systemPrompt = buildConversationSystemPrompt(settings.chatSystemPromptTemplate, {
.replace(/{ME_NAME}/g, activeSession.value.me.name) me: activeSession.value.me,
.replace(/{ME_GENDER}/g, activeSession.value.me.gender) partner: activeSession.value.partner,
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName) historyBlock,
.replace(/{PART_NAME}/g, activeSession.value.partner.name) senderName,
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender) fromLang,
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName) toLang,
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None (This is the start of conversation)') targetTone,
.replace(/{FROM_LANG}/g, fromLang.englishName) }, 'None (This is the start of conversation)');
.replace(/{TO_LANG}/g, toLang.englishName)
.replace(/{MY_TONE}/g, myToneLabel);
const requestBody = { const requestBody: TranslationPayload = {
model: settings.modelName, model: settings.modelName,
messages: [ messages: [
{ role: "system", content: systemPrompt }, { role: "system", content: systemPrompt },
{ role: "user", content: text } { role: "user", content: buildConversationTranslationUserPrompt(text) }
], ],
stream: settings.enableStreaming stream: settings.enableStreaming
}; };
settings.addLog('request', { type: 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { const response = await executeTranslationRequest({
apiAddress: settings.apiBaseUrl, apiAddress: settings.apiBaseUrl,
apiKey: settings.apiKey, apiKey: settings.apiKey,
payload: requestBody payload: requestBody,
logger: logsStore,
logType: retranslateId ? 'conversation-retranslate' : 'conversation',
onStreamStart: (requestId) => {
activeStreamRequestId.value = requestId;
},
}); });
if (!settings.enableStreaming) { if (!settings.enableStreaming) {
const fullResponseJson = JSON.parse(response); conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: extractAssistantContent(response) });
settings.addLog('response', fullResponseJson);
const translatedText = fullResponseJson.choices?.[0]?.message?.content || response;
settings.updateChatMessage(activeSession.value.id, messageId, { translated: translatedText });
} else {
settings.addLog('response', '(Streaming output captured)');
} }
} catch (err: any) { } catch (err: any) {
const errorMsg = String(err); conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: `Error: ${String(err)}` });
settings.addLog('error', errorMsg);
settings.updateChatMessage(activeSession.value.id, messageId, { translated: `Error: ${errorMsg}` });
} finally { } finally {
isTranslating.value = false; isTranslating.value = false;
currentStreamingMessageId.value = null; currentStreamingMessageId.value = null;
scrollToBottom(); activeStreamRequestId.value = null;
// 只有新消息才滚动到底部
if (!retranslateId) {
scrollToBottom();
}
} }
}; };
const evaluateMessage = async (messageId: string) => { const deleteMessage = (messageId: string) => {
if (!activeSession.value) return;
conversationStore.deleteChatMessage(activeSession.value.id, messageId);
};
const evaluateMessage = async (messageId: string, force = false) => {
if (!activeSession.value) return; if (!activeSession.value) return;
const msg = activeSession.value.messages.find(m => m.id === messageId); 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;
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true, evaluation: undefined });
const historyLimit = 10; const historyLimit = 10;
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit); const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
// 净化历史:只提供原文流
const historyBlock = recentMessages.map(m => { const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name; 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'); }).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' const targetTone = msg.sender === 'me'
? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和') ? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational')
: '自动识别 (保留原作者原始语气和情绪)'; : 'Auto-detect';
const systemPrompt = CONVERSATION_EVALUATION_PROMPT_TEMPLATE const systemPrompt = buildConversationSystemPrompt(settings.chatEvaluationPromptTemplate, {
.replace(/{ME_NAME}/g, activeSession.value.me.name) me: activeSession.value.me,
.replace(/{ME_GENDER}/g, activeSession.value.me.gender) partner: activeSession.value.partner,
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName) historyBlock,
.replace(/{PART_NAME}/g, activeSession.value.partner.name) senderName,
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender) fromLang,
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName) toLang,
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None') targetTone,
.replace(/{TARGET_TONE}/g, targetTone); }, 'None');
const userPrompt = `[Source Text]\n${msg.original}\n\n[Current Translation]\n${msg.translated}`; const userPrompt = buildConversationEvaluationUserPrompt(msg.original, msg.translated);
const requestBody = { const modelConfig = resolveModelConfig({
model: settings.modelName, apiBaseUrl: settings.apiBaseUrl,
apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
const requestBody: TranslationPayload = {
model: modelConfig.modelName,
messages: [ messages: [
{ role: "system", content: systemPrompt }, { role: "system", content: systemPrompt },
{ role: "user", content: userPrompt } { role: "user", content: userPrompt }
@@ -248,120 +317,118 @@ const evaluateMessage = async (messageId: string) => {
stream: false stream: false
}; };
settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { const response = await executeTranslationRequest({
apiAddress: settings.apiBaseUrl, apiAddress: modelConfig.apiBaseUrl,
apiKey: settings.apiKey, apiKey: modelConfig.apiKey,
payload: requestBody payload: requestBody,
logger: logsStore,
logType: 'conversation-eval',
}); });
const fullResponseJson = JSON.parse(response); conversationStore.updateChatMessage(activeSession.value.id, messageId, { evaluation: extractAssistantContent(response) });
settings.addLog('response', fullResponseJson); } catch {
const evaluationJson = fullResponseJson.choices?.[0]?.message?.content || response;
settings.updateChatMessage(activeSession.value.id, messageId, { evaluation: evaluationJson });
} catch (err: any) {
settings.addLog('error', String(err));
} finally { } finally {
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false }); conversationStore.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) => { const refineMessage = async (messageId: string) => {
if (!activeSession.value) return; if (!activeSession.value) return;
const msg = activeSession.value.messages.find(m => m.id === messageId); const msg = activeSession.value.messages.find(m => m.id === messageId);
if (!msg || !msg.evaluation || msg.isRefining) return; if (!msg || !msg.evaluation || msg.isRefining) return;
let evalData; const parsedEvaluation = tryParseEvaluationResult(msg.evaluation);
try { const evalData = parsedEvaluation.result;
evalData = JSON.parse(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;
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' }); const currentTranslation = msg.translated;
isAuditModalOpen.value = false; // 关闭弹窗开始润色
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' });
currentStreamingMessageId.value = messageId; currentStreamingMessageId.value = messageId;
const historyLimit = 10; const historyLimit = 10;
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit); const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
// 净化历史:只提供原文流
const historyBlock = recentMessages.map(m => { const historyBlock = recentMessages.map(m => {
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name; 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'); }).join('\n');
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和'; // 确定目标语气
const targetTone = msg.sender === 'me'
? TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational'
: 'Auto-detect';
const systemPrompt = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE // 动态确定语言方向
.replace(/{ME_NAME}/g, activeSession.value.me.name) const fromLang = msg.sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
.replace(/{ME_GENDER}/g, activeSession.value.me.gender) const toLang = msg.sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName) const senderName = msg.sender === 'me' ? activeSession.value.me.name : activeSession.value.partner.name;
.replace(/{PART_NAME}/g, activeSession.value.partner.name)
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None')
.replace(/{CURRENT_TRANSLATION}/g, msg.translated)
.replace(/{SUGGESTIONS}/g, suggestionsText)
.replace(/{MY_TONE}/g, myToneLabel);
const requestBody = { const systemPrompt = buildConversationSystemPrompt(settings.chatRefinementPromptTemplate, {
model: settings.modelName, me: activeSession.value.me,
partner: activeSession.value.partner,
historyBlock,
senderName,
fromLang,
toLang,
targetTone,
}, 'None');
const modelConfig = resolveModelConfig({
apiBaseUrl: settings.apiBaseUrl,
apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
const requestBody: TranslationPayload = {
model: modelConfig.modelName,
messages: [ messages: [
{ role: "system", content: systemPrompt }, { role: "system", content: systemPrompt },
{ role: "user", content: `Please refine the following original text: ${msg.original}` } { role: "user", content: buildConversationRefinementUserPrompt(msg.original, currentTranslation, selectedSuggestions.map((s: any) => s.text)) }
], ],
stream: settings.enableStreaming stream: settings.enableStreaming
}; };
settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { const response = await executeTranslationRequest({
apiAddress: settings.apiBaseUrl, apiAddress: modelConfig.apiBaseUrl,
apiKey: settings.apiKey, apiKey: modelConfig.apiKey,
payload: requestBody payload: requestBody,
logger: logsStore,
logType: 'conversation-refine',
onStreamStart: (requestId) => {
activeStreamRequestId.value = requestId;
},
}); });
if (!settings.enableStreaming) { if (!settings.enableStreaming) {
const fullResponseJson = JSON.parse(response); conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: extractAssistantContent(response) });
const refinedText = fullResponseJson.choices?.[0]?.message?.content || response;
settings.updateChatMessage(activeSession.value.id, messageId, { translated: refinedText });
} }
} catch (err: any) { } catch {
settings.addLog('error', String(err));
} finally { } finally {
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined }); conversationStore.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined });
currentStreamingMessageId.value = null; currentStreamingMessageId.value = null;
scrollToBottom(); activeStreamRequestId.value = null;
}
};
const parseEvaluation = (evalStr?: string) => { // 只有当润色的是最后一条消息时才滚动到底部
if (!evalStr) return null; const lastMsg = activeSession.value.messages[activeSession.value.messages.length - 1];
try { if (lastMsg && lastMsg.id === messageId) {
// 1. 清洗数据:剔除 Markdown 代码块标记 (如 ```json ... ``` 或 ``` ...) scrollToBottom();
let cleanStr = evalStr.trim();
if (cleanStr.startsWith('```')) {
cleanStr = cleanStr.replace(/^```[a-zA-Z]*\n?/, '').replace(/\n?```$/, '').trim();
} }
return JSON.parse(cleanStr);
} catch (e) {
console.error('Failed to parse evaluation JSON:', e, 'Raw string:', evalStr);
return { score: 0, analysis: '无法解析审计结果,请查看日志', suggestions: [] };
} }
}; };
const getSeverityColor = (importance: number) => { const parseEvaluation = (evalStr?: string) => tryParseEvaluationResult(evalStr).result;
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 = () => { const handleGlobalClick = () => {
myToneDropdownOpen.value = false; myToneDropdownOpen.value = false;
@@ -407,10 +474,10 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<div <div
v-for="session in filteredSessions" v-for="session in filteredSessions"
:key="session.id" :key="session.id"
@click="settings.activeSessionId = session.id" @click="conversationStore.activeSessionId = session.id"
:class="cn( :class="cn(
'w-full p-4 rounded-xl text-left transition-all border group relative cursor-pointer', 'w-full p-4 rounded-xl text-left transition-all border group relative cursor-pointer',
settings.activeSessionId === session.id conversationStore.activeSessionId === session.id
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/50 shadow-sm' ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/50 shadow-sm'
: 'hover:bg-slate-100 dark:hover:bg-slate-800/50 border-transparent' : 'hover:bg-slate-100 dark:hover:bg-slate-800/50 border-transparent'
)" )"
@@ -429,7 +496,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</p> </p>
<button <button
@click.stop="settings.deleteSession(session.id)" @click.stop="conversationStore.deleteSession(session.id)"
class="absolute right-2 bottom-2 p-1.5 rounded-md text-red-400 opacity-0 group-hover:opacity-100 hover:bg-red-50 dark:hover:bg-red-900/30 transition-all" class="absolute right-2 bottom-2 p-1.5 rounded-md text-red-400 opacity-0 group-hover:opacity-100 hover:bg-red-50 dark:hover:bg-red-900/30 transition-all"
title="删除会话" title="删除会话"
> >
@@ -499,7 +566,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</p> </p>
<!-- Translated Text --> <!-- 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')"> <p :class="cn('text-base font-medium leading-relaxed', msg.sender === 'me' ? 'text-white' : 'text-slate-800 dark:text-slate-100')">
{{ msg.translated }} {{ 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> <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 +576,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<!-- Action Tools (Copy, Evaluate, Refine) --> <!-- Action Tools (Copy, Evaluate, Refine) -->
<div :class="cn( <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', '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 <button
@click="copyWithFeedback(msg.translated, msg.id)" @click="copyWithFeedback(msg.translated, msg.id)"
@@ -519,6 +586,15 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<Check v-if="activeCopyId === msg.id" class="w-3.5 h-3.5 text-green-600" /> <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" /> <Copy v-else class="w-3.5 h-3.5 text-slate-400" />
</button> </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 <button
@click="evaluateMessage(msg.id)" @click="evaluateMessage(msg.id)"
:disabled="msg.isEvaluating || msg.isRefining" :disabled="msg.isEvaluating || msg.isRefining"
@@ -529,66 +605,14 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
<ShieldCheck v-else class="w-3.5 h-3.5 text-slate-400" /> <ShieldCheck v-else class="w-3.5 h-3.5 text-slate-400" />
</button> </button>
<button <button
v-if="msg.evaluation" @click="deleteMessage(msg.id)"
@click="refineMessage(msg.id)" class="p-1.5 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-full transition-colors group/del"
:disabled="msg.isRefining" title="删除消息"
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
title="执行润色"
> >
<Loader2 v-if="msg.isRefining" class="w-3.5 h-3.5 animate-spin text-purple-500" /> <Trash2 class="w-3.5 h-3.5 text-slate-400 group-hover/del:text-red-500" />
<Sparkles v-else class="w-3.5 h-3.5 text-purple-400" />
</button> </button>
</div> </div>
</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>
</div> </div>
@@ -747,7 +771,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
leave-from-class="opacity-100 scale-100" leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95" 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="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"> <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"> <h3 class="text-lg font-bold dark:text-slate-100 flex items-center gap-2">
@@ -778,7 +802,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ newSessionMe.language.displayName }} {{ newSessionMe.language.displayName }}
<ChevronDown class="w-4 h-4 text-slate-400" /> <ChevronDown class="w-4 h-4 text-slate-400" />
</button> </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"> <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 }} {{ lang.displayName }}
<Check v-if="newSessionMe.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" /> <Check v-if="newSessionMe.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
@@ -798,7 +822,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionMe.gender)?.label }} {{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionMe.gender)?.label }}
<ChevronDown class="w-4 h-4 text-slate-400" /> <ChevronDown class="w-4 h-4 text-slate-400" />
</button> </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"> <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 }} {{ opt.label }}
<Check v-if="newSessionMe.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" /> <Check v-if="newSessionMe.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
@@ -827,7 +851,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ newSessionPartner.language.displayName }} {{ newSessionPartner.language.displayName }}
<ChevronDown class="w-4 h-4 text-slate-400" /> <ChevronDown class="w-4 h-4 text-slate-400" />
</button> </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"> <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 }} {{ lang.displayName }}
<Check v-if="newSessionPartner.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" /> <Check v-if="newSessionPartner.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
@@ -847,7 +871,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionPartner.gender)?.label }} {{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionPartner.gender)?.label }}
<ChevronDown class="w-4 h-4 text-slate-400" /> <ChevronDown class="w-4 h-4 text-slate-400" />
</button> </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"> <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 }} {{ opt.label }}
<Check v-if="newSessionPartner.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" /> <Check v-if="newSessionPartner.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
@@ -869,7 +893,144 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div> </div>
</div> </div>
</transition> </transition>
</div> </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> </div>
</template> </template>

View File

@@ -1,27 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch } from 'vue'; import { ref, computed, watch } from 'vue';
import { Clock, Search, ArrowRightLeft, Trash2, User, Type, Copy, Check, FileText } from 'lucide-vue-next'; import { Clock, Search, ArrowRightLeft, Trash2, User, Type, Copy, Check, FileText } from 'lucide-vue-next';
import { useSettingsStore, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../stores/settings'; import { useHistoryStore } from '../stores/history';
import { SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../domain/translation';
import { cn } from '../lib/utils'; import { cn } from '../lib/utils';
import { useClipboard } from '../composables/useClipboard'; import { useClipboard } from '../composables/useClipboard';
const settings = useSettingsStore(); const historyStore = useHistoryStore();
const { activeCopyId, copyWithFeedback } = useClipboard(); const { activeCopyId, copyWithFeedback } = useClipboard();
const searchQuery = ref(''); const searchQuery = ref('');
const selectedHistoryId = ref<string | null>(null); const selectedHistoryId = ref<string | null>(null);
const filteredHistory = computed(() => { const filteredHistory = computed(() => {
if (!searchQuery.value.trim()) return settings.history; if (!searchQuery.value.trim()) return historyStore.history;
const q = searchQuery.value.toLowerCase(); const q = searchQuery.value.toLowerCase();
return settings.history.filter(h => return historyStore.history.filter(h =>
h.sourceText.toLowerCase().includes(q) || h.sourceText.toLowerCase().includes(q) ||
h.targetText.toLowerCase().includes(q) h.targetText.toLowerCase().includes(q)
); );
}); });
const selectedHistoryItem = computed(() => const selectedHistoryItem = computed(() =>
settings.history.find(h => h.id === selectedHistoryId.value) || null historyStore.history.find(h => h.id === selectedHistoryId.value) || null
); );
watch(filteredHistory, (newVal) => { watch(filteredHistory, (newVal) => {
@@ -31,7 +32,7 @@ watch(filteredHistory, (newVal) => {
}, { immediate: true }); }, { immediate: true });
const deleteHistoryItem = (id: string) => { const deleteHistoryItem = (id: string) => {
settings.history = settings.history.filter(h => h.id !== id); historyStore.deleteHistoryItem(id);
if (selectedHistoryId.value === id) { if (selectedHistoryId.value === id) {
selectedHistoryId.value = filteredHistory.value[0]?.id || null; selectedHistoryId.value = filteredHistory.value[0]?.id || null;
} }
@@ -55,7 +56,7 @@ const deleteHistoryItem = (id: string) => {
<div class="flex items-center justify-between px-1"> <div class="flex items-center justify-between px-1">
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider"> {{ filteredHistory.length }} 条记录</span> <span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider"> {{ filteredHistory.length }} 条记录</span>
<button <button
@click="settings.history = []" @click="historyStore.clearHistory()"
class="text-[11px] text-red-500 hover:underline font-medium" class="text-[11px] text-red-500 hover:underline font-medium"
>清空全部</button> >清空全部</button>
</div> </div>

View File

@@ -1,19 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch } from 'vue'; import { ref, computed, watch } from 'vue';
import { FileText, Check, Copy } from 'lucide-vue-next'; import { FileText, Check, Copy } from 'lucide-vue-next';
import { useSettingsStore } from '../stores/settings'; import { useLogsStore } from '../stores/logs';
import { cn } from '../lib/utils'; import { cn } from '../lib/utils';
import { useClipboard } from '../composables/useClipboard'; import { useClipboard } from '../composables/useClipboard';
const settings = useSettingsStore(); const logsStore = useLogsStore();
const { activeCopyId, copyWithFeedback } = useClipboard(); const { activeCopyId, copyWithFeedback } = useClipboard();
const selectedLogId = ref<string | null>(null); const selectedLogId = ref<string | null>(null);
const selectedLogItem = computed(() => const selectedLogItem = computed(() =>
settings.logs.find(l => l.id === selectedLogId.value) || null logsStore.logs.find(l => l.id === selectedLogId.value) || null
); );
watch(() => settings.logs, (newVal) => { watch(() => logsStore.logs, (newVal) => {
if (newVal.length > 0 && !selectedLogId.value) { if (newVal.length > 0 && !selectedLogId.value) {
selectedLogId.value = newVal[0].id; selectedLogId.value = newVal[0].id;
} }
@@ -47,7 +47,7 @@ const getLogSummary = (log: any) => {
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">系统日志</h2> <h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">系统日志</h2>
<button <button
@click="settings.logs = []" @click="logsStore.clearLogs()"
class="text-[11px] text-red-500 hover:underline font-medium flex items-center gap-1" class="text-[11px] text-red-500 hover:underline font-medium flex items-center gap-1"
> >
清空全部 清空全部
@@ -56,12 +56,12 @@ const getLogSummary = (log: any) => {
</div> </div>
<div class="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1"> <div class="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1">
<div v-if="settings.logs.length === 0" class="py-20 text-center space-y-2"> <div v-if="logsStore.logs.length === 0" class="py-20 text-center space-y-2">
<FileText class="w-10 h-10 text-slate-200 dark:text-slate-800 mx-auto" /> <FileText class="w-10 h-10 text-slate-200 dark:text-slate-800 mx-auto" />
<p class="text-sm text-slate-400 italic">暂无日志记录</p> <p class="text-sm text-slate-400 italic">暂无日志记录</p>
</div> </div>
<div <div
v-for="log in settings.logs" v-for="log in logsStore.logs"
:key="log.id" :key="log.id"
@click="selectedLogId = log.id" @click="selectedLogId = log.id"
:class="cn( :class="cn(

View File

@@ -1,11 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'; import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil } from 'lucide-vue-next'; 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, type ApiProfile } from '../stores/settings'; import {
useSettingsStore,
DEFAULT_TEMPLATE,
DEFAULT_EVALUATION_TEMPLATE,
DEFAULT_REFINEMENT_TEMPLATE,
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE
} from '../stores/settings';
import type { ApiProfile } from '../domain/translation';
import { cn } from '../lib/utils'; import { cn } from '../lib/utils';
const settings = useSettingsStore(); const settings = useSettingsStore();
const settingsCategory = ref<'api' | 'general' | 'prompts'>('api'); const settingsCategory = ref<'api' | 'general' | 'prompts' | 'chat-prompts'>('api');
const showApiKey = ref(false); const showApiKey = ref(false);
const newProfileName = ref(''); const newProfileName = ref('');
@@ -129,6 +138,18 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div> </div>
提示词工程 提示词工程
</button> </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> </nav>
</div> </div>
@@ -490,6 +511,82 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
</div> </div>
</template> </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}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_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}', '{HISTORY_BLOCK}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_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 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}', '{HISTORY_BLOCK}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_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>
</div>
</template>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,14 +1,50 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'; import { ref, computed, onMounted, onUnmounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ChevronDown, Check, ArrowRightLeft, Trash2, FileText, Plus, Loader2, Send, User, Type, Copy, Save } from 'lucide-vue-next'; import { ChevronDown, Check, ArrowRightLeft, Trash2, FileText, Plus, Loader2, Send, User, Type, Copy, Save } from 'lucide-vue-next';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
import { useSettingsStore, LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../stores/settings'; import { LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../domain/translation';
import { useSettingsStore } from '../stores/settings';
import { useHistoryStore } from '../stores/history';
import { useLogsStore } from '../stores/logs';
import { useTranslationWorkspaceStore } from '../stores/translation-workspace';
import { cn } from '../lib/utils'; import { cn } from '../lib/utils';
import { useClipboard } from '../composables/useClipboard'; import { useClipboard } from '../composables/useClipboard';
import {
buildSingleEvaluationSystemPrompt,
buildSingleEvaluationUserPrompt,
buildSingleRefinementSystemPrompt,
buildSingleRefinementUserPrompt,
buildSingleTranslationSystemPrompt,
buildSingleTranslationUserPrompt,
} from '../lib/prompt-builders';
import {
executeTranslationRequest,
extractAssistantContent,
resolveModelConfig,
tryParseEvaluationResult,
type TranslationChunkEvent,
type TranslationPayload,
} from '../lib/translation-service';
const settings = useSettingsStore(); const settings = useSettingsStore();
const historyStore = useHistoryStore();
const logsStore = useLogsStore();
const workspaceStore = useTranslationWorkspaceStore();
const { activeCopyId, copyWithFeedback } = useClipboard(); const { activeCopyId, copyWithFeedback } = useClipboard();
const {
sourceText,
context,
targetText,
isTranslating,
currentHistoryId,
evaluationResult,
isEvaluating,
isRefining,
selectedSuggestionIds,
appliedSuggestionIds,
activeStreamRequestId,
} = storeToRefs(workspaceStore);
const sourceDropdownOpen = ref(false); const sourceDropdownOpen = ref(false);
const targetDropdownOpen = ref(false); const targetDropdownOpen = ref(false);
@@ -45,33 +81,11 @@ const handleGlobalClick = (e: MouseEvent) => {
onMounted(() => window.addEventListener('click', handleGlobalClick)); onMounted(() => window.addEventListener('click', handleGlobalClick));
onUnmounted(() => window.removeEventListener('click', handleGlobalClick)); onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
const sourceText = ref('');
const context = ref('');
const targetText = ref('');
const isTranslating = ref(false);
const currentHistoryId = ref<string | null>(null);
interface Suggestion { id: number; text: string; importance: number; }
interface EvaluationResult { score: number; analysis: string; suggestions?: Suggestion[]; }
const evaluationResult = ref<EvaluationResult | null>(null);
const isEvaluating = ref(false);
const isRefining = ref(false);
const selectedSuggestionIds = ref<number[]>([]);
const appliedSuggestionIds = ref<number[]>([]);
const toggleSuggestion = (id: number) => {
if (!selectedSuggestionIds.value) selectedSuggestionIds.value = [];
const index = selectedSuggestionIds.value.indexOf(id);
if (index > -1) selectedSuggestionIds.value.splice(index, 1);
else selectedSuggestionIds.value.push(id);
};
let unlisten: (() => void) | null = null; let unlisten: (() => void) | null = null;
onMounted(async () => { onMounted(async () => {
unlisten = await listen<string>('translation-chunk', (event) => { unlisten = await listen<TranslationChunkEvent>('translation-chunk', (event) => {
if (isTranslating.value || isRefining.value) { if ((isTranslating.value || isRefining.value) && event.payload.request_id === activeStreamRequestId.value) {
targetText.value += event.payload; targetText.value += event.payload.chunk;
} }
}); });
}); });
@@ -100,73 +114,55 @@ const swapLanguages = () => {
}; };
const clearSource = () => { const clearSource = () => {
sourceText.value = ''; workspaceStore.clearWorkspace();
targetText.value = '';
evaluationResult.value = null;
}; };
const generateCurl = (apiBaseUrl: string, apiKey: string, body: any) => { const toggleSuggestion = (id: number) => {
const fullUrl = `${apiBaseUrl.replace(/\/$/, '')}/chat/completions`; workspaceStore.toggleSuggestion(id);
const maskedKey = apiKey ? `${apiKey.slice(0, 6)}...${apiKey.slice(-4)}` : 'YOUR_API_KEY';
return `curl "${fullUrl}" \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer ${maskedKey}" \\
-d '${JSON.stringify(body, null, 2)}'`;
}; };
const evaluateTranslation = async () => { const evaluateTranslation = async () => {
if (!targetText.value) return; if (!targetText.value) return;
isEvaluating.value = true; isEvaluating.value = true;
evaluationResult.value = null; workspaceStore.resetEvaluationState();
selectedSuggestionIds.value = [];
appliedSuggestionIds.value = [];
let apiBaseUrl = settings.apiBaseUrl; const modelConfig = resolveModelConfig({
let apiKey = settings.apiKey; apiBaseUrl: settings.apiBaseUrl,
let modelName = settings.modelName; apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
if (settings.evaluationProfileId) { const evaluationSystemPrompt = buildSingleEvaluationSystemPrompt(settings.evaluationPromptTemplate, {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId); sourceLang: sourceLang.value,
if (profile) { targetLang: targetLang.value,
apiBaseUrl = profile.apiBaseUrl; speakerIdentity: settings.speakerIdentity,
apiKey = profile.apiKey; toneRegister: settings.toneRegister,
modelName = profile.modelName; context: context.value,
} });
}
const evaluationSystemPrompt = settings.evaluationPromptTemplate const evaluationUserPrompt = buildSingleEvaluationUserPrompt(sourceText.value, targetText.value);
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
.replace(/{TONE_REGISTER}/g, settings.toneRegister)
.replace(/{CONTEXT}/g, context.value || 'None');
const evaluationUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Translated Text]\n${targetText.value}`; const requestBody: TranslationPayload = {
model: modelConfig.modelName,
const requestBody = {
model: modelName,
messages: [ { role: "system", content: evaluationSystemPrompt }, { role: "user", content: evaluationUserPrompt } ], messages: [ { role: "system", content: evaluationSystemPrompt }, { role: "user", content: evaluationUserPrompt } ],
stream: false stream: false
}; };
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody }); const response = await executeTranslationRequest({
try { apiAddress: modelConfig.apiBaseUrl,
// 解析 API 的原始响应 JSON apiKey: modelConfig.apiKey,
const fullResponseJson = JSON.parse(response); payload: requestBody,
settings.addLog('response', fullResponseJson); logger: logsStore,
logType: 'evaluation',
const content = fullResponseJson.choices?.[0]?.message?.content || response; });
const jsonStr = content.replace(/```json\s?|\s?```/g, '').trim(); const parsedEvaluation = tryParseEvaluationResult(extractAssistantContent(response));
evaluationResult.value = JSON.parse(jsonStr); if (!parsedEvaluation.ok) {
} catch (parseErr) { console.error(parsedEvaluation.error, response);
console.error('Failed to parse evaluation result:', response); logsStore.addLog('error', `Evaluation parsing error: ${response}`);
settings.addLog('error', `Evaluation parsing error: ${response}`);
} }
} catch (err: any) { evaluationResult.value = parsedEvaluation.result;
settings.addLog('error', `Evaluation error: ${String(err)}`); } catch {
} finally { } finally {
isEvaluating.value = false; isEvaluating.value = false;
} }
@@ -181,47 +177,41 @@ const refineTranslation = async () => {
const originalTranslation = targetText.value; const originalTranslation = targetText.value;
targetText.value = ''; targetText.value = '';
let apiBaseUrl = settings.apiBaseUrl; const modelConfig = resolveModelConfig({
let apiKey = settings.apiKey; apiBaseUrl: settings.apiBaseUrl,
let modelName = settings.modelName; apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
if (settings.evaluationProfileId) { const refinementSystemPrompt = buildSingleRefinementSystemPrompt(settings.refinementPromptTemplate, {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId); sourceLang: sourceLang.value,
if (profile) { targetLang: targetLang.value,
apiBaseUrl = profile.apiBaseUrl; speakerIdentity: settings.speakerIdentity,
apiKey = profile.apiKey; toneRegister: settings.toneRegister,
modelName = profile.modelName; context: context.value,
} });
}
const refinementSystemPrompt = settings.refinementPromptTemplate const refinementUserPrompt = buildSingleRefinementUserPrompt(sourceText.value, originalTranslation, selectedTexts);
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
.replace(/{TONE_REGISTER}/g, settings.toneRegister)
.replace(/{CONTEXT}/g, context.value || 'None');
const formattedSuggestions = selectedTexts.map((text, i) => `${i + 1}. ${text}`).join('\n'); const requestBody: TranslationPayload = {
const refinementUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Current Translation]\n${originalTranslation}\n\n[User Feedback]\n${formattedSuggestions}`; model: modelConfig.modelName,
const requestBody = {
model: modelName,
messages: [ { role: "system", content: refinementSystemPrompt }, { role: "user", content: refinementUserPrompt } ], messages: [ { role: "system", content: refinementSystemPrompt }, { role: "user", content: refinementUserPrompt } ],
stream: settings.enableStreaming stream: settings.enableStreaming
}; };
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody }); const response = await executeTranslationRequest({
apiAddress: modelConfig.apiBaseUrl,
apiKey: modelConfig.apiKey,
payload: requestBody,
logger: logsStore,
logType: 'refinement',
onStreamStart: (requestId) => {
activeStreamRequestId.value = requestId;
},
});
if (settings.enableStreaming) { if (!settings.enableStreaming) targetText.value = extractAssistantContent(response);
settings.addLog('response', targetText.value);
} else {
const fullResponseJson = JSON.parse(response);
settings.addLog('response', fullResponseJson);
targetText.value = fullResponseJson.choices?.[0]?.message?.content || response;
}
if (evaluationResult.value?.suggestions) { if (evaluationResult.value?.suggestions) {
appliedSuggestionIds.value.push(...selectedSuggestionIds.value); appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
@@ -229,16 +219,15 @@ const refineTranslation = async () => {
} }
if (currentHistoryId.value) { if (currentHistoryId.value) {
settings.updateHistoryItem(currentHistoryId.value, { historyStore.updateHistoryItem(currentHistoryId.value, {
targetText: targetText.value targetText: targetText.value
}); });
} }
} catch (err: any) { } catch (err: any) {
const errorMsg = String(err); targetText.value = `Error: ${String(err)}`;
settings.addLog('error', errorMsg);
targetText.value = `Error: ${errorMsg}`;
} finally { } finally {
isRefining.value = false; isRefining.value = false;
activeStreamRequestId.value = null;
} }
}; };
@@ -250,41 +239,41 @@ const translate = async () => {
targetText.value = ''; targetText.value = '';
evaluationResult.value = null; evaluationResult.value = null;
const systemMessage = settings.systemPromptTemplate const systemMessage = buildSingleTranslationSystemPrompt(settings.systemPromptTemplate, {
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName) sourceLang: sourceLang.value,
.replace(/{SOURCE_CODE}/g, sourceLang.value.code) targetLang: targetLang.value,
.replace(/{TARGET_LANG}/g, targetLang.value.englishName) speakerIdentity: settings.speakerIdentity,
.replace(/{TARGET_CODE}/g, targetLang.value.code) toneRegister: settings.toneRegister,
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity) });
.replace(/{TONE_REGISTER}/g, settings.toneRegister);
const userMessage = context.value const userMessage = buildSingleTranslationUserPrompt(sourceText.value, context.value);
? `[Context]\n${context.value}\n\n[Text to Translate]\n${sourceText.value}`
: `[Text to Translate]\n${sourceText.value}`;
const requestBody = { const requestBody: TranslationPayload = {
model: settings.modelName, model: settings.modelName,
messages: [ { role: "system", content: systemMessage }, { role: "user", content: userMessage } ], messages: [ { role: "system", content: systemMessage }, { role: "user", content: userMessage } ],
stream: settings.enableStreaming stream: settings.enableStreaming
}; };
settings.addLog('request', requestBody, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
try { try {
const response = await invoke<string>('translate', { apiAddress: settings.apiBaseUrl, apiKey: settings.apiKey, payload: requestBody }); const response = await executeTranslationRequest({
apiAddress: settings.apiBaseUrl,
apiKey: settings.apiKey,
payload: requestBody,
logger: logsStore,
onStreamStart: (requestId) => {
activeStreamRequestId.value = requestId;
},
});
let finalTargetText = ''; let finalTargetText = '';
if (settings.enableStreaming) { if (settings.enableStreaming) {
finalTargetText = targetText.value; finalTargetText = targetText.value;
settings.addLog('response', response);
} else { } else {
const fullResponseJson = JSON.parse(response); finalTargetText = extractAssistantContent(response);
settings.addLog('response', fullResponseJson);
finalTargetText = fullResponseJson.choices?.[0]?.message?.content || response;
targetText.value = finalTargetText; targetText.value = finalTargetText;
} }
currentHistoryId.value = settings.addHistory({ currentHistoryId.value = historyStore.addHistory({
sourceLang: { ...sourceLang.value }, sourceLang: { ...sourceLang.value },
targetLang: { ...targetLang.value }, targetLang: { ...targetLang.value },
sourceText: sourceText.value, sourceText: sourceText.value,
@@ -295,11 +284,10 @@ const translate = async () => {
modelName: settings.modelName modelName: settings.modelName
}); });
} catch (err: any) { } catch (err: any) {
const errorMsg = String(err); targetText.value = `Error: ${String(err)}`;
settings.addLog('error', errorMsg);
targetText.value = `Error: ${errorMsg}`;
} finally { } finally {
isTranslating.value = false; isTranslating.value = false;
activeStreamRequestId.value = null;
} }
if (settings.enableEvaluation) await evaluateTranslation(); if (settings.enableEvaluation) await evaluateTranslation();

89
src/domain/translation.ts Normal file
View File

@@ -0,0 +1,89 @@
export interface Language {
displayName: string;
englishName: string;
code: string;
}
export const LANGUAGES: Language[] = [
{ displayName: '中文(简体)', englishName: 'Simplified Chinese', code: 'zh-Hans' },
{ displayName: '中文(繁体)', englishName: 'Traditional Chinese', code: 'zh-Hant' },
{ displayName: '英语(美国)', englishName: 'American English', code: 'en-US' },
{ displayName: '英语(英国)', englishName: 'British English', code: 'en-GB' },
{ displayName: '西班牙语', englishName: 'Spanish', code: 'es' },
{ displayName: '葡萄牙语', englishName: 'Portuguese', code: 'pt' },
{ displayName: '日语', englishName: 'Japanese', code: 'ja' },
{ displayName: '韩语', englishName: 'Korean', code: 'ko' },
{ displayName: '法语', englishName: 'French', code: 'fr' },
{ displayName: '德语', englishName: 'German', code: 'de' },
{ displayName: '意大利语', englishName: 'Italian', code: 'it' },
{ displayName: '俄语', englishName: 'Russian', code: 'ru' },
{ displayName: '越南语', englishName: 'Vietnamese', code: 'vi' },
{ displayName: '泰语', englishName: 'Thai', code: 'th' },
{ displayName: '阿拉伯语', englishName: 'Arabic', code: 'ar' },
];
export const SPEAKER_IDENTITY_OPTIONS = [
{ label: '男性', value: 'Male' },
{ label: '女性', value: 'Female' },
{ label: '中性', value: 'Gender-neutral' },
] as const;
export const TONE_REGISTER_OPTIONS = [
{ label: '自动识别', value: 'Auto-detect', description: '分析并保持原文的语气、情绪和礼貌程度' },
{ label: '正式专业', value: 'Formal & Professional', description: '商务邮件、法律合同、官方报告' },
{ label: '礼貌客气', value: 'Polite & Respectful', description: '与长辈、客户或初次见面的人交流' },
{ label: '礼貌随和', value: 'Polite & Conversational', description: '得体但不刻板的日常对话' },
{ label: '中性标准', value: 'Neutral & Standard', description: '维基百科、说明书、客观的新闻报道' },
{ label: '非正式', value: 'Casual & Informal', description: '朋友聊天、社交媒体、非正式简讯' },
{ label: '亲切友好', value: 'Warm & Friendly', description: '社区信函、给朋友的建议、温馨提示' },
{ label: '严谨权威', value: 'Strict & Authoritative', description: '警示标志、强制规定、上级指令' },
{ label: '热情生动', value: 'Enthusiastic & Vivid', description: '广告文案、旅游推荐、博主推文' },
] as const;
export interface ApiProfile {
id: string;
name: string;
apiBaseUrl: string;
apiKey: string;
modelName: string;
}
export interface HistoryItem {
id: string;
timestamp: string;
sourceLang: Language;
targetLang: Language;
sourceText: string;
targetText: string;
context: string;
speakerIdentity: string;
toneRegister: string;
modelName: string;
}
export interface Participant {
name: string;
gender: string;
language: Language;
tone: string;
}
export interface ChatMessage {
id: string;
sender: 'me' | 'partner';
original: string;
translated: string;
timestamp: string;
evaluation?: string;
isEvaluating?: boolean;
isRefining?: boolean;
}
export interface ChatSession {
id: string;
title: string;
me: Participant;
partner: Participant;
messages: ChatMessage[];
lastActivity: string;
}

103
src/lib/prompt-builders.ts Normal file
View File

@@ -0,0 +1,103 @@
import type { Language, Participant } from '../domain/translation';
interface SingleTranslationPromptContext {
sourceLang: Language;
targetLang: Language;
speakerIdentity: string;
toneRegister: string;
context: string;
}
interface ConversationPromptContext {
me: Participant;
partner: Participant;
historyBlock: string;
senderName: string;
fromLang: Language;
toLang: Language;
targetTone: string;
}
function replaceTokens(template: string, values: Record<string, string>) {
return Object.entries(values).reduce(
(result, [key, value]) => result.replace(new RegExp(`\\{${key}\\}`, 'g'), value),
template,
);
}
export function buildSingleTranslationSystemPrompt(
template: string,
context: Omit<SingleTranslationPromptContext, 'context'>,
) {
return replaceTokens(template, {
SOURCE_LANG: context.sourceLang.englishName,
SOURCE_CODE: context.sourceLang.code,
TARGET_LANG: context.targetLang.englishName,
TARGET_CODE: context.targetLang.code,
SPEAKER_IDENTITY: context.speakerIdentity,
TONE_REGISTER: context.toneRegister,
});
}
export function buildSingleEvaluationSystemPrompt(
template: string,
context: SingleTranslationPromptContext,
) {
return replaceTokens(template, {
SOURCE_LANG: context.sourceLang.englishName,
TARGET_LANG: context.targetLang.englishName,
SPEAKER_IDENTITY: context.speakerIdentity,
TONE_REGISTER: context.toneRegister,
CONTEXT: context.context || 'None',
});
}
export function buildSingleRefinementSystemPrompt(
template: string,
context: SingleTranslationPromptContext,
) {
return buildSingleEvaluationSystemPrompt(template, context);
}
export function buildSingleTranslationUserPrompt(sourceText: string, context: string) {
return context
? `[Context]\n${context}\n\n[Text to Translate]\n${sourceText}`
: `[Text to Translate]\n${sourceText}`;
}
export function buildSingleEvaluationUserPrompt(sourceText: string, targetText: string) {
return `[Source Text]\n${sourceText}\n\n[Translated Text]\n${targetText}`;
}
export function buildSingleRefinementUserPrompt(sourceText: string, currentTranslation: string, suggestions: string[]) {
const formattedSuggestions = suggestions.map((text, index) => `${index + 1}. ${text}`).join('\n');
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}\n\n[User Feedback]\n${formattedSuggestions}`;
}
export function buildConversationSystemPrompt(template: string, context: ConversationPromptContext, emptyHistoryFallback: string) {
return replaceTokens(template, {
ME_NAME: context.me.name,
ME_GENDER: context.me.gender,
ME_LANG: context.me.language.englishName,
PART_NAME: context.partner.name,
PART_GENDER: context.partner.gender,
PART_LANG: context.partner.language.englishName,
HISTORY_BLOCK: context.historyBlock || emptyHistoryFallback,
SENDER_NAME: context.senderName,
FROM_LANG: context.fromLang.englishName,
TO_LANG: context.toLang.englishName,
TARGET_TONE: context.targetTone,
});
}
export function buildConversationTranslationUserPrompt(text: string) {
return `[Text to Translate]\n${text}`;
}
export function buildConversationEvaluationUserPrompt(sourceText: string, currentTranslation: string) {
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}`;
}
export function buildConversationRefinementUserPrompt(sourceText: string, currentTranslation: string, suggestions: string[]) {
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}\n\n[Suggestions]\n${suggestions.map((text) => `- ${text}`).join('\n')}`;
}

View File

@@ -0,0 +1,164 @@
import { invoke } from '@tauri-apps/api/core';
import type { ApiProfile } from '../domain/translation';
interface Message {
role: string;
content: string;
}
export interface TranslationPayload {
model: string;
messages: Message[];
stream: boolean;
}
export interface TranslationChunkEvent {
request_id: string;
chunk: string;
}
export interface EvaluationSuggestion {
id: number;
text: string;
importance: number;
}
export interface EvaluationResult {
score: number;
analysis: string;
suggestions: EvaluationSuggestion[];
}
export interface ModelConfig {
apiBaseUrl: string;
apiKey: string;
modelName: string;
}
type LogType = 'request' | 'response' | 'error';
interface Logger {
addLog: (type: LogType, content: any, curl?: string) => void;
}
interface ExecuteTranslationRequestOptions {
apiAddress: string;
apiKey: string;
payload: TranslationPayload;
logger: Logger;
logType?: string;
onStreamStart?: (requestId: string) => void;
}
const FALLBACK_EVALUATION_RESULT: EvaluationResult = {
score: 0,
analysis: '无法解析审计结果,请查看日志',
suggestions: [],
};
export function resolveModelConfig(
primary: ModelConfig,
profiles: ApiProfile[],
profileId: string | null,
): ModelConfig {
if (!profileId) return primary;
const profile = profiles.find((item) => item.id === profileId);
if (!profile) return primary;
return {
apiBaseUrl: profile.apiBaseUrl,
apiKey: profile.apiKey,
modelName: profile.modelName,
};
}
export function generateCurl(apiBaseUrl: string, apiKey: string, body: TranslationPayload) {
const fullUrl = `${apiBaseUrl.replace(/\/$/, '')}/chat/completions`;
const maskedKey = apiKey ? `${apiKey.slice(0, 6)}...${apiKey.slice(-4)}` : 'YOUR_API_KEY';
return `curl "${fullUrl}" \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer ${maskedKey}" \\
-d '${JSON.stringify(body, null, 2)}'`;
}
export async function executeTranslationRequest({
apiAddress,
apiKey,
payload,
logger,
logType,
onStreamStart,
}: ExecuteTranslationRequestOptions) {
const requestId = crypto.randomUUID();
const requestLog = logType ? { type: logType, ...payload } : payload;
logger.addLog('request', requestLog, generateCurl(apiAddress, apiKey, payload));
try {
if (payload.stream) onStreamStart?.(requestId);
const response = await invoke<string>('translate', {
apiAddress,
apiKey,
payload,
requestId,
});
logger.addLog('response', payload.stream ? response : safeParseJson(response) ?? response);
return response;
} catch (error) {
logger.addLog('error', String(error));
throw error;
}
}
export function safeParseJson(value: string) {
try {
return JSON.parse(value);
} catch {
return null;
}
}
export function extractAssistantContent(response: string) {
const parsed = safeParseJson(response);
if (parsed && typeof parsed === 'object') {
return (parsed as any).choices?.[0]?.message?.content || response;
}
return response;
}
export function tryParseEvaluationResult(raw?: string) {
if (!raw) {
return {
ok: false as const,
error: 'Evaluation result is empty',
result: FALLBACK_EVALUATION_RESULT,
};
}
try {
let cleanStr = raw.trim();
if (cleanStr.startsWith('```')) {
cleanStr = cleanStr.replace(/^```[a-zA-Z]*\n?/, '').replace(/\n?```$/, '').trim();
}
const parsed = JSON.parse(cleanStr);
return {
ok: true as const,
result: {
score: Number(parsed.score) || 0,
analysis: typeof parsed.analysis === 'string' ? parsed.analysis : '',
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions : [],
} satisfies EvaluationResult,
};
} catch (error) {
return {
ok: false as const,
error: `Failed to parse evaluation JSON: ${String(error)}`,
result: FALLBACK_EVALUATION_RESULT,
};
}
}

View File

@@ -0,0 +1,86 @@
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';
import type { ChatMessage, ChatSession, Participant } from '../domain/translation';
function formatTimestamp() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
}
export const useConversationStore = defineStore('conversation', () => {
const chatSessions = useLocalStorage<ChatSession[]>('chat-sessions-v1', []);
const activeSessionId = useLocalStorage<string | null>('active-session-id-v1', null);
const createSession = (me: Participant, partner: Participant) => {
const id = crypto.randomUUID();
const timestamp = formatTimestamp();
const newSession: ChatSession = {
id,
title: `${partner.name} 的对话`,
me,
partner,
messages: [],
lastActivity: timestamp,
};
chatSessions.value.unshift(newSession);
activeSessionId.value = id;
return id;
};
const deleteSession = (id: string) => {
chatSessions.value = chatSessions.value.filter((session) => session.id !== id);
if (activeSessionId.value === id) {
activeSessionId.value = chatSessions.value[0]?.id || null;
}
};
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated = '') => {
const session = chatSessions.value.find((item) => item.id === sessionId);
if (!session) return null;
const timestamp = formatTimestamp();
const newMessage: ChatMessage = {
id: crypto.randomUUID(),
sender,
original,
translated,
timestamp,
};
session.messages.push(newMessage);
session.lastActivity = timestamp;
const index = chatSessions.value.findIndex((item) => item.id === sessionId);
if (index > 0) {
const [current] = chatSessions.value.splice(index, 1);
chatSessions.value.unshift(current);
}
return newMessage.id;
};
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
const session = chatSessions.value.find((item) => item.id === sessionId);
const message = session?.messages.find((item) => item.id === messageId);
if (message) Object.assign(message, updates);
};
const deleteChatMessage = (sessionId: string, messageId: string) => {
const session = chatSessions.value.find((item) => item.id === sessionId);
if (session) {
session.messages = session.messages.filter((item) => item.id !== messageId);
}
};
return {
chatSessions,
activeSessionId,
createSession,
deleteSession,
addMessageToSession,
updateChatMessage,
deleteChatMessage,
};
});

51
src/stores/history.ts Normal file
View File

@@ -0,0 +1,51 @@
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';
import type { HistoryItem } from '../domain/translation';
function formatTimestamp() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
}
export const useHistoryStore = defineStore('history', () => {
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
const id = crypto.randomUUID();
history.value.unshift({
...item,
id,
timestamp: formatTimestamp(),
});
if (history.value.length > 100) {
history.value = history.value.slice(0, 100);
}
return id;
};
const updateHistoryItem = (id: string, updates: Partial<HistoryItem>) => {
const index = history.value.findIndex((item) => item.id === id);
if (index !== -1) {
history.value[index] = { ...history.value[index], ...updates };
}
};
const deleteHistoryItem = (id: string) => {
history.value = history.value.filter((item) => item.id !== id);
};
const clearHistory = () => {
history.value = [];
};
return {
history,
addHistory,
updateHistoryItem,
deleteHistoryItem,
clearHistory,
};
});

41
src/stores/logs.ts Normal file
View File

@@ -0,0 +1,41 @@
import { ref } from 'vue';
import { defineStore } from 'pinia';
export interface LogEntry {
id: string;
timestamp: string;
type: 'request' | 'response' | 'error';
content: any;
curl?: string;
}
function createTimestamp() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
}
export const useLogsStore = defineStore('logs', () => {
const logs = ref<LogEntry[]>([]);
const addLog = (type: LogEntry['type'], content: any, curl?: string) => {
logs.value.unshift({
id: crypto.randomUUID(),
timestamp: createTimestamp(),
type,
content,
curl,
});
if (logs.value.length > 50) logs.value.pop();
};
const clearLogs = () => {
logs.value = [];
};
return {
logs,
addLog,
clearLogs,
};
});

View File

@@ -1,48 +1,7 @@
import { ref, computed } from 'vue'; import { computed } from 'vue';
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core'; import { useLocalStorage } from '@vueuse/core';
import { LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS, type ApiProfile, type Language } from '../domain/translation';
export interface Language {
displayName: string; // UI 显示的中文名,如 "英语(英国)"
englishName: string; // 文件中的第二列,用于 {SOURCE_LANG}
code: string; // 文件中的第一列,用于 {SOURCE_CODE}
}
export const LANGUAGES: Language[] = [
{ displayName: '中文(简体)', englishName: 'Simplified Chinese', code: 'zh-Hans' },
{ displayName: '中文(繁体)', englishName: 'Traditional Chinese', code: 'zh-Hant' },
{ displayName: '英语(美国)', englishName: 'American English', code: 'en-US' },
{ displayName: '英语(英国)', englishName: 'British English', code: 'en-GB' },
{ displayName: '西班牙语', englishName: 'Spanish', code: 'es' },
{ displayName: '葡萄牙语', englishName: 'Portuguese', code: 'pt' },
{ displayName: '日语', englishName: 'Japanese', code: 'ja' },
{ displayName: '韩语', englishName: 'Korean', code: 'ko' },
{ displayName: '法语', englishName: 'French', code: 'fr' },
{ displayName: '德语', englishName: 'German', code: 'de' },
{ displayName: '意大利语', englishName: 'Italian', code: 'it' },
{ displayName: '俄语', englishName: 'Russian', code: 'ru' },
{ displayName: '越南语', englishName: 'Vietnamese', code: 'vi' },
{ displayName: '泰语', englishName: 'Thai', code: 'th' },
{ displayName: '阿拉伯语', englishName: 'Arabic', code: 'ar' },
];
export const SPEAKER_IDENTITY_OPTIONS = [
{ label: '男性', value: 'Male' },
{ label: '女性', value: 'Female' },
{ label: '中性', value: 'Gender-neutral' },
];
export const TONE_REGISTER_OPTIONS = [
{ label: '自动识别', value: 'Auto-detect', description: '分析并保持原文的语气、情绪和礼貌程度' },
{ label: '正式专业', value: 'Formal & Professional', description: '商务邮件、法律合同、官方报告' },
{ label: '礼貌客气', value: 'Polite & Respectful', description: '与长辈、客户或初次见面的人交流' },
{ label: '礼貌随和', value: 'Polite & Conversational', description: '得体但不刻板的日常对话' },
{ label: '中性标准', value: 'Neutral & Standard', description: '维基百科、说明书、客观的新闻报道' },
{ label: '非正式', value: 'Casual & Informal', description: '朋友聊天、社交媒体、非正式简讯' },
{ label: '亲切友好', value: 'Warm & Friendly', description: '社区信函、给朋友的建议、温馨提示' },
{ label: '严谨权威', value: 'Strict & Authoritative', description: '警示标志、强制规定、上级指令' },
{ label: '热情生动', value: 'Enthusiastic & Vivid', description: '广告文案、旅游推荐、博主推文' },
];
export const DEFAULT_TEMPLATE = `You are a professional {SOURCE_LANG} ({SOURCE_CODE}) to {TARGET_LANG} ({TARGET_CODE}) translator. Your goal is to accurately convey the meaning and nuances of the original {SOURCE_LANG} text while adhering to {TARGET_LANG} grammar, vocabulary, and cultural sensitivities. export const DEFAULT_TEMPLATE = `You are a professional {SOURCE_LANG} ({SOURCE_CODE}) to {TARGET_LANG} ({TARGET_CODE}) translator. Your goal is to accurately convey the meaning and nuances of the original {SOURCE_LANG} text while adhering to {TARGET_LANG} grammar, vocabulary, and cultural sensitivities.
@@ -106,99 +65,60 @@ export const DEFAULT_REFINEMENT_TEMPLATE = `You are a senior translation editor.
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement. 4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
5. Produce ONLY the refined {TARGET_LANG} translation, without any additional explanations, notes, or commentary.`; 5. Produce ONLY the refined {TARGET_LANG} translation, without any additional explanations, notes, or commentary.`;
export interface ApiProfile { export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `# Role: Professional Real-time Conversation Translator
id: string;
name: string;
apiBaseUrl: string;
apiKey: string;
modelName: string;
}
export interface HistoryItem { # Participants:
id: string; - Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
timestamp: string; - Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
sourceLang: Language;
targetLang: Language;
sourceText: string;
targetText: string;
context: string;
speakerIdentity: string;
toneRegister: string;
modelName: string;
}
export interface Participant { # Recent Conversation Flow:
name: string;
gender: string;
language: Language;
tone: string;
}
export interface ChatMessage {
id: string;
sender: 'me' | 'partner';
original: string;
translated: string;
timestamp: string;
evaluation?: string; // AI 审计结果 (JSON 字符串)
isEvaluating?: boolean; // 审计状态
isRefining?: boolean; // 润色状态
}
export interface ChatSession {
id: string;
title: string;
me: Participant;
partner: Participant;
messages: ChatMessage[];
lastActivity: string;
}
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}.
[Conversation History]
{HISTORY_BLOCK} {HISTORY_BLOCK}
[Current Task] # Current Turn to Translate:
Translate the incoming text from {FROM_LANG} to {TO_LANG}. - Speaker: {SENDER_NAME}
- Source Language: {FROM_LANG}
- Target Language: {TO_LANG}
- Intended Tone/Register: {TARGET_TONE}
[Constraints] # Constraints
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency. 1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
2. Tone & Register: 2. Personalization & Tone: Ensure all grammatical agreements and self-referential terms reflect speaker's gender. Faithfully replicate the intended tone, maintaining the formality, emotional nuance, and unique style of the source text without neutralizing it.
- If translating for 'Me', strictly use the tone: {MY_TONE}.
- If translating for 'Partner', auto-detect and preserve their original tone/emotion.
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese". 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. 4. Strictly avoid over-translation: Do not add extra information not present in the source text.
5. Output ONLY the translated text, no explanations.`; 5. Output ONLY the translated text, no explanations.`;
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role: Expert Conversation Auditor
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].
# Context Info # Participants:
- Me: {ME_NAME} ({ME_GENDER}, {ME_LANG}) - Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
- Partner: {PART_NAME} ({PART_GENDER}, {PART_LANG}) - Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
- Target Tone: {TARGET_TONE}
[Conversation History] # Recent Conversation Flow:
{HISTORY_BLOCK} {HISTORY_BLOCK}
# Audit Priorities # Current Turn to Audit:
1. **Contextual Accuracy**: Do pronouns (it, that, etc.) correctly point to objects/topics mentioned in the [Conversation History]? - Speaker: {SENDER_NAME}
2. **Relational Tone**: Does the translation match the [Target Tone]? (e.g., if set to 'Polite', is it too casual?) - Source Language: {FROM_LANG}
3. **Consistency**: Are names, terms, or previously established facts handled consistently? - Target Language: {TO_LANG}
4. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment? - Intended Tone/Register: {TARGET_TONE}
# Audit Criteria
1. **Contextual Inaccuracy**: Failure to correctly reflect the meaning based on the [Recent Conversation Flow]
2. **Semantic Error**: Objective misalignment with the source meaning or complete hallucinations.
3. **Grammatical Error**: Clear violations of target language grammar or syntax rules.
4. **Tone Failure**: A tone that is the opposite or significantly different from the [Intended Tone/Register].
5. **Poor Readability**: The phrasing is so stiff, unnatural, or convoluted that it hinders smooth comprehension (e.g., obvious "translationese" or broken logic).
**Note**: Do NOT penalize if the translation is simply "not the most elegant" or if there's a subjective preference for a different synonym. If it's natural enough for a native speaker to understand without effort, it's acceptable.
# Instructions # Instructions
1. Analyze the [Source Text] and [Current Translation] against the history. 1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Criteria].
2. Scoring: 0-100. 2. **Scoring Strategy**:
3. Suggestions: Provide actionable improvements. - **90-100**: Accurate, grammatically sound, and flows naturally.
4. **Severity Level**: For each suggestion, assign an "importance" score (0-100). - **75-89**: Accurate meaning, but suffers from "stiff" phrasing or minor flow issues that need adjustment.
- **80-100 (Critical)**: Misunderstanding meaning, wrong pronoun reference, or offensive tone. - **Below 75**: Contains semantic errors, severe grammar issues, or tone mismatches.
- **40-79 (Moderate)**: Unnatural phrasing, minor tone mismatch. 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").
- **0-39 (Minor)**: Polishing, stylistic preferences. 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 # Output Format
Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese: Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese:
@@ -210,29 +130,27 @@ 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 # Participants:
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}. - Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
- Role B (Partner): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}. - Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
- Target Tone: {TARGET_TONE}
[Conversation History] # Recent Conversation Flow:
{HISTORY_BLOCK} {HISTORY_BLOCK}
[Current Translation] # Current Turn to Refine:
{CURRENT_TRANSLATION} - Speaker: {SENDER_NAME}
- Source Language: {FROM_LANG}
- Target Language: {TO_LANG}
- Intended Tone/Register: {TARGET_TONE}
[Audit Suggestions] # Instructions:
{SUGGESTIONS} 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].
# Task 3. Maintain the speaker's gender and [Intended Tone/Register] as specified.
Produce a new, refined version of the translation that addresses the suggestions while remaining naturally integrated into the conversation flow. 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.`;
# Constraints
1. Maintain semantic identity with the [Source Text].
2. Strictly follow the {TARGET_TONE}.
3. Output ONLY the refined translation text. No explanations.`;
export const useSettingsStore = defineStore('settings', () => { export const useSettingsStore = defineStore('settings', () => {
const isDark = useLocalStorage('is-dark', false); const isDark = useLocalStorage('is-dark', false);
@@ -248,6 +166,10 @@ export const useSettingsStore = defineStore('settings', () => {
const evaluationProfileId = useLocalStorage<string | null>('evaluation-profile-id', null); const evaluationProfileId = useLocalStorage<string | null>('evaluation-profile-id', null);
const refinementPromptTemplate = useLocalStorage('refinement-prompt-template', DEFAULT_REFINEMENT_TEMPLATE); 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 sourceLang = useLocalStorage<Language>('source-lang-v2', LANGUAGES[0]);
const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]); const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]);
@@ -266,119 +188,6 @@ export const useSettingsStore = defineStore('settings', () => {
set: (val) => { toneRegisterMap.value[sourceLang.value.code] = val; } set: (val) => { toneRegisterMap.value[sourceLang.value.code] = val; }
}); });
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any; curl?: string }[]>([]);
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
// 对话模式状态
const chatSessions = useLocalStorage<ChatSession[]>('chat-sessions-v1', []);
const activeSessionId = useLocalStorage<string | null>('active-session-id-v1', null);
const addLog = (type: 'request' | 'response' | 'error', content: any, curl?: string) => {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
logs.value.unshift({
id: crypto.randomUUID(),
timestamp,
type,
content,
curl
});
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
};
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
const id = crypto.randomUUID();
history.value.unshift({
...item,
id,
timestamp
});
// 限制 100 条
if (history.value.length > 100) {
history.value = history.value.slice(0, 100);
}
return id;
};
const updateHistoryItem = (id: string, updates: Partial<HistoryItem>) => {
const index = history.value.findIndex(h => h.id === id);
if (index !== -1) {
history.value[index] = { ...history.value[index], ...updates };
}
};
// 对话模式方法
const createSession = (me: Participant, partner: Participant) => {
const id = crypto.randomUUID();
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
const newSession: ChatSession = {
id,
title: `${partner.name} 的对话`,
me,
partner,
messages: [],
lastActivity: timestamp
};
chatSessions.value.unshift(newSession);
activeSessionId.value = id;
return id;
};
const deleteSession = (id: string) => {
chatSessions.value = chatSessions.value.filter(s => s.id !== id);
if (activeSessionId.value === id) {
activeSessionId.value = chatSessions.value[0]?.id || null;
}
};
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated: string = '') => {
const session = chatSessions.value.find(s => s.id === sessionId);
if (session) {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
const newMessage: ChatMessage = {
id: crypto.randomUUID(),
sender,
original,
translated,
timestamp
};
session.messages.push(newMessage);
session.lastActivity = timestamp;
// 将活跃会话移至顶部
const index = chatSessions.value.findIndex(s => s.id === sessionId);
if (index > 0) {
const [s] = chatSessions.value.splice(index, 1);
chatSessions.value.unshift(s);
}
return newMessage.id;
}
return null;
};
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
const session = chatSessions.value.find(s => s.id === sessionId);
if (session) {
const message = session.messages.find(m => m.id === messageId);
if (message) {
Object.assign(message, updates);
}
}
};
return { return {
isDark, isDark,
apiBaseUrl, apiBaseUrl,
@@ -391,20 +200,12 @@ export const useSettingsStore = defineStore('settings', () => {
evaluationPromptTemplate, evaluationPromptTemplate,
evaluationProfileId, evaluationProfileId,
refinementPromptTemplate, refinementPromptTemplate,
chatSystemPromptTemplate,
chatEvaluationPromptTemplate,
chatRefinementPromptTemplate,
sourceLang, sourceLang,
targetLang, targetLang,
speakerIdentity, speakerIdentity,
toneRegister, toneRegister,
logs,
history,
chatSessions,
activeSessionId,
addLog,
addHistory,
updateHistoryItem,
createSession,
deleteSession,
addMessageToSession,
updateChatMessage
}; };
}); });

View File

@@ -0,0 +1,53 @@
import { ref } from 'vue';
import { defineStore } from 'pinia';
import type { EvaluationResult } from '../lib/translation-service';
export const useTranslationWorkspaceStore = defineStore('translationWorkspace', () => {
const sourceText = ref('');
const context = ref('');
const targetText = ref('');
const isTranslating = ref(false);
const currentHistoryId = ref<string | null>(null);
const evaluationResult = ref<EvaluationResult | null>(null);
const isEvaluating = ref(false);
const isRefining = ref(false);
const selectedSuggestionIds = ref<number[]>([]);
const appliedSuggestionIds = ref<number[]>([]);
const activeStreamRequestId = ref<string | null>(null);
const resetEvaluationState = () => {
evaluationResult.value = null;
selectedSuggestionIds.value = [];
appliedSuggestionIds.value = [];
};
const clearWorkspace = () => {
sourceText.value = '';
targetText.value = '';
resetEvaluationState();
};
const toggleSuggestion = (id: number) => {
const index = selectedSuggestionIds.value.indexOf(id);
if (index > -1) selectedSuggestionIds.value.splice(index, 1);
else selectedSuggestionIds.value.push(id);
};
return {
sourceText,
context,
targetText,
isTranslating,
currentHistoryId,
evaluationResult,
isEvaluating,
isRefining,
selectedSuggestionIds,
appliedSuggestionIds,
activeStreamRequestId,
resetEvaluationState,
clearWorkspace,
toggleSuggestion,
};
});