25 Commits
v0.3.7 ... main

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
Julian Freeman
5b0e6321cc add check and refine 2026-04-03 20:03:03 -04:00
Julian Freeman
8acef5e4e7 fix prediction 2026-04-03 19:37:57 -04:00
Julian Freeman
4f6ab39ed5 fix label ui 2026-04-03 19:30:44 -04:00
Julian Freeman
2a940534f2 auto scroll 2026-04-03 19:22:56 -04:00
Julian Freeman
136a5c186c fix select ui 2026-04-03 19:02:04 -04:00
Julian Freeman
41494ebad0 support chat mode 2026-04-03 18:52:08 -04:00
20 changed files with 2021 additions and 272 deletions

View File

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

View File

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

2
src-tauri/Cargo.lock generated
View File

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

View File

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

View File

@@ -32,12 +32,19 @@ struct Delta {
content: Option<String>,
}
#[derive(Serialize, Clone)]
struct TranslationChunkEvent {
request_id: String,
chunk: String,
}
#[tauri::command]
async fn translate(
app: AppHandle,
api_address: String,
api_key: String,
payload: TranslationPayload,
request_id: String,
) -> Result<String, String> {
let client = Client::new();
// Ensure URL doesn't have double slashes if api_address ends with /
@@ -55,6 +62,12 @@ async fn translate(
.await
.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 {
let text = res.text().await.map_err(|e| e.to_string())?;
return Ok(text);
@@ -78,7 +91,11 @@ async fn translate(
if let Some(choice) = json.choices.get(0) {
if let Some(delta) = &choice.delta {
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",
"productName": "ai-translate-client",
"version": "0.3.7",
"version": "0.3.8",
"identifier": "top.volan.ai-translate-client",
"build": {
"beforeDevCommand": "pnpm dev",

View File

@@ -14,6 +14,7 @@ import { cn } from './lib/utils';
// Import newly separated views
import TranslationView from './components/TranslationView.vue';
import ConversationView from './components/ConversationView.vue';
import SettingsView from './components/SettingsView.vue';
import LogsView from './components/LogsView.vue';
import HistoryView from './components/HistoryView.vue';
@@ -34,7 +35,7 @@ const toggleTheme = () => {
};
// Global Routing State
const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
const view = ref<'translate' | 'conversation' | 'settings' | 'logs' | 'history'>('translate');
</script>
@@ -46,6 +47,20 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
<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>
</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">
<button
@click="toggleTheme"
@@ -55,6 +70,13 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
<Sun v-if="settings.isDark" class="w-5 h-5" />
<Moon v-else class="w-5 h-5" />
</button>
<button
@click="view = 'conversation'"
:class="cn('p-2 rounded-full transition-colors', view === 'conversation' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-200/50 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
title="对话模拟"
>
<MessageSquare class="w-5 h-5" />
</button>
<button
@click="view = 'settings'"
:class="cn('p-2 rounded-full transition-colors', view === 'settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-200/50 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
@@ -83,6 +105,7 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
<!-- Container for isolated views with keep-alive -->
<keep-alive>
<TranslationView v-if="view === 'translate'" />
<ConversationView v-else-if="view === 'conversation'" />
<SettingsView v-else-if="view === 'settings'" />
<LogsView v-else-if="view === 'logs'" />
<HistoryView v-else-if="view === 'history'" />

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,19 +1,19 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { FileText, Check, Copy } from 'lucide-vue-next';
import { useSettingsStore } from '../stores/settings';
import { useLogsStore } from '../stores/logs';
import { cn } from '../lib/utils';
import { useClipboard } from '../composables/useClipboard';
const settings = useSettingsStore();
const logsStore = useLogsStore();
const { activeCopyId, copyWithFeedback } = useClipboard();
const selectedLogId = ref<string | null>(null);
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) {
selectedLogId.value = newVal[0].id;
}
@@ -47,7 +47,7 @@ const getLogSummary = (log: any) => {
<div class="flex items-center justify-between">
<h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">系统日志</h2>
<button
@click="settings.logs = []"
@click="logsStore.clearLogs()"
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 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" />
<p class="text-sm text-slate-400 italic">暂无日志记录</p>
</div>
<div
v-for="log in settings.logs"
v-for="log in logsStore.logs"
:key="log.id"
@click="selectedLogId = log.id"
:class="cn(

View File

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

View File

@@ -1,14 +1,50 @@
<script setup lang="ts">
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 { invoke } from '@tauri-apps/api/core';
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 { 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 historyStore = useHistoryStore();
const logsStore = useLogsStore();
const workspaceStore = useTranslationWorkspaceStore();
const { activeCopyId, copyWithFeedback } = useClipboard();
const {
sourceText,
context,
targetText,
isTranslating,
currentHistoryId,
evaluationResult,
isEvaluating,
isRefining,
selectedSuggestionIds,
appliedSuggestionIds,
activeStreamRequestId,
} = storeToRefs(workspaceStore);
const sourceDropdownOpen = ref(false);
const targetDropdownOpen = ref(false);
@@ -45,33 +81,11 @@ const handleGlobalClick = (e: MouseEvent) => {
onMounted(() => window.addEventListener('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;
onMounted(async () => {
unlisten = await listen<string>('translation-chunk', (event) => {
if (isTranslating.value || isRefining.value) {
targetText.value += event.payload;
unlisten = await listen<TranslationChunkEvent>('translation-chunk', (event) => {
if ((isTranslating.value || isRefining.value) && event.payload.request_id === activeStreamRequestId.value) {
targetText.value += event.payload.chunk;
}
});
});
@@ -100,73 +114,55 @@ const swapLanguages = () => {
};
const clearSource = () => {
sourceText.value = '';
targetText.value = '';
evaluationResult.value = null;
workspaceStore.clearWorkspace();
};
const generateCurl = (apiBaseUrl: string, apiKey: string, body: any) => {
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)}'`;
const toggleSuggestion = (id: number) => {
workspaceStore.toggleSuggestion(id);
};
const evaluateTranslation = async () => {
if (!targetText.value) return;
isEvaluating.value = true;
evaluationResult.value = null;
selectedSuggestionIds.value = [];
appliedSuggestionIds.value = [];
workspaceStore.resetEvaluationState();
let apiBaseUrl = settings.apiBaseUrl;
let apiKey = settings.apiKey;
let modelName = settings.modelName;
const modelConfig = resolveModelConfig({
apiBaseUrl: settings.apiBaseUrl,
apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
if (settings.evaluationProfileId) {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
if (profile) {
apiBaseUrl = profile.apiBaseUrl;
apiKey = profile.apiKey;
modelName = profile.modelName;
}
}
const evaluationSystemPrompt = buildSingleEvaluationSystemPrompt(settings.evaluationPromptTemplate, {
sourceLang: sourceLang.value,
targetLang: targetLang.value,
speakerIdentity: settings.speakerIdentity,
toneRegister: settings.toneRegister,
context: context.value,
});
const evaluationSystemPrompt = settings.evaluationPromptTemplate
.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 = buildSingleEvaluationUserPrompt(sourceText.value, targetText.value);
const evaluationUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Translated Text]\n${targetText.value}`;
const requestBody = {
model: modelName,
const requestBody: TranslationPayload = {
model: modelConfig.modelName,
messages: [ { role: "system", content: evaluationSystemPrompt }, { role: "user", content: evaluationUserPrompt } ],
stream: false
};
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
try {
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
try {
// 解析 API 的原始响应 JSON
const fullResponseJson = JSON.parse(response);
settings.addLog('response', fullResponseJson);
const content = fullResponseJson.choices?.[0]?.message?.content || response;
const jsonStr = content.replace(/```json\s?|\s?```/g, '').trim();
evaluationResult.value = JSON.parse(jsonStr);
} catch (parseErr) {
console.error('Failed to parse evaluation result:', response);
settings.addLog('error', `Evaluation parsing error: ${response}`);
const response = await executeTranslationRequest({
apiAddress: modelConfig.apiBaseUrl,
apiKey: modelConfig.apiKey,
payload: requestBody,
logger: logsStore,
logType: 'evaluation',
});
const parsedEvaluation = tryParseEvaluationResult(extractAssistantContent(response));
if (!parsedEvaluation.ok) {
console.error(parsedEvaluation.error, response);
logsStore.addLog('error', `Evaluation parsing error: ${response}`);
}
} catch (err: any) {
settings.addLog('error', `Evaluation error: ${String(err)}`);
evaluationResult.value = parsedEvaluation.result;
} catch {
} finally {
isEvaluating.value = false;
}
@@ -181,47 +177,41 @@ const refineTranslation = async () => {
const originalTranslation = targetText.value;
targetText.value = '';
let apiBaseUrl = settings.apiBaseUrl;
let apiKey = settings.apiKey;
let modelName = settings.modelName;
const modelConfig = resolveModelConfig({
apiBaseUrl: settings.apiBaseUrl,
apiKey: settings.apiKey,
modelName: settings.modelName,
}, settings.profiles, settings.evaluationProfileId);
if (settings.evaluationProfileId) {
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
if (profile) {
apiBaseUrl = profile.apiBaseUrl;
apiKey = profile.apiKey;
modelName = profile.modelName;
}
}
const refinementSystemPrompt = buildSingleRefinementSystemPrompt(settings.refinementPromptTemplate, {
sourceLang: sourceLang.value,
targetLang: targetLang.value,
speakerIdentity: settings.speakerIdentity,
toneRegister: settings.toneRegister,
context: context.value,
});
const refinementSystemPrompt = settings.refinementPromptTemplate
.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 refinementUserPrompt = buildSingleRefinementUserPrompt(sourceText.value, originalTranslation, selectedTexts);
const formattedSuggestions = selectedTexts.map((text, i) => `${i + 1}. ${text}`).join('\n');
const refinementUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Current Translation]\n${originalTranslation}\n\n[User Feedback]\n${formattedSuggestions}`;
const requestBody = {
model: modelName,
const requestBody: TranslationPayload = {
model: modelConfig.modelName,
messages: [ { role: "system", content: refinementSystemPrompt }, { role: "user", content: refinementUserPrompt } ],
stream: settings.enableStreaming
};
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
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) {
settings.addLog('response', targetText.value);
} else {
const fullResponseJson = JSON.parse(response);
settings.addLog('response', fullResponseJson);
targetText.value = fullResponseJson.choices?.[0]?.message?.content || response;
}
if (!settings.enableStreaming) targetText.value = extractAssistantContent(response);
if (evaluationResult.value?.suggestions) {
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
@@ -229,16 +219,15 @@ const refineTranslation = async () => {
}
if (currentHistoryId.value) {
settings.updateHistoryItem(currentHistoryId.value, {
historyStore.updateHistoryItem(currentHistoryId.value, {
targetText: targetText.value
});
}
} catch (err: any) {
const errorMsg = String(err);
settings.addLog('error', errorMsg);
targetText.value = `Error: ${errorMsg}`;
targetText.value = `Error: ${String(err)}`;
} finally {
isRefining.value = false;
activeStreamRequestId.value = null;
}
};
@@ -250,41 +239,41 @@ const translate = async () => {
targetText.value = '';
evaluationResult.value = null;
const systemMessage = settings.systemPromptTemplate
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
.replace(/{SOURCE_CODE}/g, sourceLang.value.code)
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
.replace(/{TARGET_CODE}/g, targetLang.value.code)
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
.replace(/{TONE_REGISTER}/g, settings.toneRegister);
const systemMessage = buildSingleTranslationSystemPrompt(settings.systemPromptTemplate, {
sourceLang: sourceLang.value,
targetLang: targetLang.value,
speakerIdentity: settings.speakerIdentity,
toneRegister: settings.toneRegister,
});
const userMessage = context.value
? `[Context]\n${context.value}\n\n[Text to Translate]\n${sourceText.value}`
: `[Text to Translate]\n${sourceText.value}`;
const userMessage = buildSingleTranslationUserPrompt(sourceText.value, context.value);
const requestBody = {
const requestBody: TranslationPayload = {
model: settings.modelName,
messages: [ { role: "system", content: systemMessage }, { role: "user", content: userMessage } ],
stream: settings.enableStreaming
};
settings.addLog('request', requestBody, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
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 = '';
if (settings.enableStreaming) {
finalTargetText = targetText.value;
settings.addLog('response', response);
} else {
const fullResponseJson = JSON.parse(response);
settings.addLog('response', fullResponseJson);
finalTargetText = fullResponseJson.choices?.[0]?.message?.content || response;
finalTargetText = extractAssistantContent(response);
targetText.value = finalTargetText;
}
currentHistoryId.value = settings.addHistory({
currentHistoryId.value = historyStore.addHistory({
sourceLang: { ...sourceLang.value },
targetLang: { ...targetLang.value },
sourceText: sourceText.value,
@@ -295,11 +284,10 @@ const translate = async () => {
modelName: settings.modelName
});
} catch (err: any) {
const errorMsg = String(err);
settings.addLog('error', errorMsg);
targetText.value = `Error: ${errorMsg}`;
targetText.value = `Error: ${String(err)}`;
} finally {
isTranslating.value = false;
activeStreamRequestId.value = null;
}
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 { useLocalStorage } from '@vueuse/core';
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: '广告文案、旅游推荐、博主推文' },
];
import { LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS, type ApiProfile, type Language } from '../domain/translation';
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,26 +65,92 @@ 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.
5. Produce ONLY the refined {TARGET_LANG} translation, without any additional explanations, notes, or commentary.`;
export interface ApiProfile {
id: string;
name: string;
apiBaseUrl: string;
apiKey: string;
modelName: string;
}
export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `# Role: Professional Real-time Conversation Translator
export interface HistoryItem {
id: string;
timestamp: string;
sourceLang: Language;
targetLang: Language;
sourceText: string;
targetText: string;
context: string;
speakerIdentity: string;
toneRegister: string;
modelName: string;
}
# Participants:
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
# Recent Conversation Flow:
{HISTORY_BLOCK}
# Current Turn to Translate:
- Speaker: {SENDER_NAME}
- Source Language: {FROM_LANG}
- Target Language: {TO_LANG}
- Intended Tone/Register: {TARGET_TONE}
# Constraints
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
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.
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese".
4. Strictly avoid over-translation: Do not add extra information not present in the source text.
5. Output ONLY the translated text, no explanations.`;
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role: Expert Conversation Auditor
# Participants:
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
# Recent Conversation Flow:
{HISTORY_BLOCK}
# Current Turn to Audit:
- Speaker: {SENDER_NAME}
- Source Language: {FROM_LANG}
- Target Language: {TO_LANG}
- 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
1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Criteria].
2. **Scoring Strategy**:
- **90-100**: Accurate, grammatically sound, and flows naturally.
- **75-89**: Accurate meaning, but suffers from "stiff" phrasing or minor flow issues that need adjustment.
- **Below 75**: Contains semantic errors, severe grammar issues, or tone mismatches.
3. **Analysis**: Provide a concise explanation in Simplified Chinese. Focus on *why* the error matters (e.g., "meaning is reversed" or "too awkward to read").
4. **Suggestions**: Provide a list of specific, actionable suggestions. For each, assign an "importance" from 0 to 100 (0 = unnecessary/optional, 100 = critical error).
# Output Format
Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese:
{
"score": number,
"analysis": "string",
"suggestions": [
{ "id": 1, "text": "suggestion text", "importance": number }
]
}`;
export const CONVERSATION_REFINEMENT_PROMPT_TEMPLATE = `# Role: Professional Conversation Editor
# Participants:
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
# Recent Conversation Flow:
{HISTORY_BLOCK}
# Current Turn to Refine:
- Speaker: {SENDER_NAME}
- Source Language: {FROM_LANG}
- Target Language: {TO_LANG}
- Intended Tone/Register: {TARGET_TONE}
# Instructions:
1. Carefully review the [Suggestions] and apply the requested improvements to the [Current Translation] while ensuring it fits naturally into the [Recent Conversation Flow].
2. Ensure that the refined translation remains semantically identical to the [Source Text].
3. Maintain the speaker's gender and [Intended Tone/Register] as specified.
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
5. Produce ONLY the refined {TO_LANG} translation, without any additional explanations, notes, or commentary.`;
export const useSettingsStore = defineStore('settings', () => {
const isDark = useLocalStorage('is-dark', false);
@@ -141,6 +166,10 @@ export const useSettingsStore = defineStore('settings', () => {
const evaluationProfileId = useLocalStorage<string | null>('evaluation-profile-id', null);
const refinementPromptTemplate = useLocalStorage('refinement-prompt-template', DEFAULT_REFINEMENT_TEMPLATE);
const chatSystemPromptTemplate = useLocalStorage('chat-system-prompt-template', CONVERSATION_SYSTEM_PROMPT_TEMPLATE);
const chatEvaluationPromptTemplate = useLocalStorage('chat-evaluation-prompt-template', CONVERSATION_EVALUATION_PROMPT_TEMPLATE);
const chatRefinementPromptTemplate = useLocalStorage('chat-refinement-prompt-template', CONVERSATION_REFINEMENT_PROMPT_TEMPLATE);
// 存储整个对象以保持一致性
const sourceLang = useLocalStorage<Language>('source-lang-v2', LANGUAGES[0]);
const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]);
@@ -159,49 +188,6 @@ export const useSettingsStore = defineStore('settings', () => {
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 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 };
}
};
return {
isDark,
apiBaseUrl,
@@ -214,14 +200,12 @@ export const useSettingsStore = defineStore('settings', () => {
evaluationPromptTemplate,
evaluationProfileId,
refinementPromptTemplate,
chatSystemPromptTemplate,
chatEvaluationPromptTemplate,
chatRefinementPromptTemplate,
sourceLang,
targetLang,
speakerIdentity,
toneRegister,
logs,
history,
addLog,
addHistory,
updateHistoryItem
};
});

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,
};
});