Compare commits
12 Commits
v0.3.5
...
5b0e6321cc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b0e6321cc | ||
|
|
8acef5e4e7 | ||
|
|
4f6ab39ed5 | ||
|
|
2a940534f2 | ||
|
|
136a5c186c | ||
|
|
41494ebad0 | ||
|
|
ce4a42eec2 | ||
|
|
ac951c31b1 | ||
|
|
f3150f06fa | ||
|
|
7de7877c64 | ||
|
|
15626ba9e1 | ||
|
|
c719b50285 |
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "ai-translate-client",
|
"name": "ai-translate-client",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.3.5",
|
"version": "0.3.7",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -19,7 +19,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ai-translate-client"
|
name = "ai-translate-client"
|
||||||
version = "0.3.5"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"reqwest 0.12.28",
|
"reqwest 0.12.28",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ai-translate-client"
|
name = "ai-translate-client"
|
||||||
version = "0.3.5"
|
version = "0.3.7"
|
||||||
description = "A client using AI models to translate"
|
description = "A client using AI models to translate"
|
||||||
authors = ["Julian"]
|
authors = ["Julian"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ struct OpenAIResponse {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Choice {
|
struct Choice {
|
||||||
message: Option<Message>,
|
// message: Option<Message>,
|
||||||
delta: Option<Delta>,
|
delta: Option<Delta>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,16 +56,17 @@ async fn translate(
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
if !payload.stream {
|
if !payload.stream {
|
||||||
let data = res.json::<OpenAIResponse>().await.map_err(|e| e.to_string())?;
|
let text = res.text().await.map_err(|e| e.to_string())?;
|
||||||
return Ok(data.choices.get(0).and_then(|c| c.message.as_ref()).map(|m| m.content.clone()).unwrap_or_default());
|
return Ok(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut stream = res.bytes_stream();
|
let mut stream = res.bytes_stream();
|
||||||
let mut full_response = String::new();
|
let mut raw_stream_log = String::new();
|
||||||
|
|
||||||
while let Some(item) = stream.next().await {
|
while let Some(item) = stream.next().await {
|
||||||
let chunk = item.map_err(|e| e.to_string())?;
|
let chunk = item.map_err(|e| e.to_string())?;
|
||||||
let text = String::from_utf8_lossy(&chunk);
|
let text = String::from_utf8_lossy(&chunk);
|
||||||
|
raw_stream_log.push_str(&text);
|
||||||
|
|
||||||
for line in text.lines() {
|
for line in text.lines() {
|
||||||
let line = line.trim();
|
let line = line.trim();
|
||||||
@@ -77,7 +78,6 @@ 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 {
|
||||||
full_response.push_str(content);
|
|
||||||
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,7 +87,7 @@ async fn translate(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(full_response)
|
Ok(raw_stream_log)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
|||||||
@@ -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.5",
|
"version": "0.3.7",
|
||||||
"identifier": "top.volan.ai-translate-client",
|
"identifier": "top.volan.ai-translate-client",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
14
src/App.vue
14
src/App.vue
@@ -6,7 +6,8 @@ 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';
|
||||||
@@ -14,6 +15,7 @@ import { cn } from './lib/utils';
|
|||||||
|
|
||||||
// Import newly separated views
|
// Import newly separated views
|
||||||
import TranslationView from './components/TranslationView.vue';
|
import TranslationView from './components/TranslationView.vue';
|
||||||
|
import ConversationView from './components/ConversationView.vue';
|
||||||
import SettingsView from './components/SettingsView.vue';
|
import SettingsView from './components/SettingsView.vue';
|
||||||
import LogsView from './components/LogsView.vue';
|
import LogsView from './components/LogsView.vue';
|
||||||
import HistoryView from './components/HistoryView.vue';
|
import HistoryView from './components/HistoryView.vue';
|
||||||
@@ -34,7 +36,7 @@ const toggleTheme = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Global Routing State
|
// Global Routing State
|
||||||
const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
const view = ref<'translate' | 'conversation' | 'settings' | 'logs' | 'history'>('translate');
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -55,6 +57,13 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
|||||||
<Sun v-if="settings.isDark" class="w-5 h-5" />
|
<Sun v-if="settings.isDark" class="w-5 h-5" />
|
||||||
<Moon v-else class="w-5 h-5" />
|
<Moon v-else class="w-5 h-5" />
|
||||||
</button>
|
</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
|
<button
|
||||||
@click="view = 'settings'"
|
@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')"
|
: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 +92,7 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
|||||||
<!-- Container for isolated views with keep-alive -->
|
<!-- Container for isolated views with keep-alive -->
|
||||||
<keep-alive>
|
<keep-alive>
|
||||||
<TranslationView v-if="view === 'translate'" />
|
<TranslationView v-if="view === 'translate'" />
|
||||||
|
<ConversationView v-else-if="view === 'conversation'" />
|
||||||
<SettingsView v-else-if="view === 'settings'" />
|
<SettingsView v-else-if="view === 'settings'" />
|
||||||
<LogsView v-else-if="view === 'logs'" />
|
<LogsView v-else-if="view === 'logs'" />
|
||||||
<HistoryView v-else-if="view === 'history'" />
|
<HistoryView v-else-if="view === 'history'" />
|
||||||
|
|||||||
890
src/components/ConversationView.vue
Normal file
890
src/components/ConversationView.vue
Normal file
@@ -0,0 +1,890 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue';
|
||||||
|
import {
|
||||||
|
Plus, Search, Trash2, Send, User, Type, ChevronDown, Check,
|
||||||
|
MessageSquare, Loader2, Copy,
|
||||||
|
X, Sparkles, Languages, Venus, Mars, CircleSlash,
|
||||||
|
ShieldCheck, TriangleAlert, AlertCircle
|
||||||
|
} from 'lucide-vue-next';
|
||||||
|
import {
|
||||||
|
useSettingsStore,
|
||||||
|
LANGUAGES,
|
||||||
|
SPEAKER_IDENTITY_OPTIONS,
|
||||||
|
TONE_REGISTER_OPTIONS,
|
||||||
|
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
|
||||||
|
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
|
||||||
|
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
|
||||||
|
type Participant
|
||||||
|
} from '../stores/settings';
|
||||||
|
import { cn } from '../lib/utils';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { listen } from '@tauri-apps/api/event';
|
||||||
|
import { useClipboard } from '../composables/useClipboard';
|
||||||
|
|
||||||
|
const settings = useSettingsStore();
|
||||||
|
const { activeCopyId, copyWithFeedback } = useClipboard();
|
||||||
|
|
||||||
|
// UI States
|
||||||
|
const searchQuery = ref('');
|
||||||
|
const isCreatingSession = ref(false);
|
||||||
|
const messageContainer = ref<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
// New Session Form
|
||||||
|
const newSessionMe = ref<Participant>({
|
||||||
|
name: '我',
|
||||||
|
gender: 'Male',
|
||||||
|
language: LANGUAGES[0],
|
||||||
|
tone: TONE_REGISTER_OPTIONS[3].value // 礼貌随和
|
||||||
|
});
|
||||||
|
const newSessionPartner = ref<Participant>({
|
||||||
|
name: '对方',
|
||||||
|
gender: 'Female',
|
||||||
|
language: LANGUAGES[4], // 西班牙语
|
||||||
|
tone: 'Auto-detect'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Custom Dropdown States for Modal
|
||||||
|
const meLangDropdownOpen = ref(false);
|
||||||
|
const meGenderDropdownOpen = ref(false);
|
||||||
|
const partnerLangDropdownOpen = ref(false);
|
||||||
|
const partnerGenderDropdownOpen = ref(false);
|
||||||
|
|
||||||
|
const closeAllModalDropdowns = () => {
|
||||||
|
meLangDropdownOpen.value = false;
|
||||||
|
meGenderDropdownOpen.value = false;
|
||||||
|
partnerLangDropdownOpen.value = false;
|
||||||
|
partnerGenderDropdownOpen.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Current active session
|
||||||
|
const activeSession = computed(() =>
|
||||||
|
settings.chatSessions.find(s => s.id === settings.activeSessionId) || null
|
||||||
|
);
|
||||||
|
|
||||||
|
const scrollToBottom = async (smooth = true) => {
|
||||||
|
await nextTick();
|
||||||
|
if (messageContainer.value) {
|
||||||
|
messageContainer.value.scrollTo({
|
||||||
|
top: messageContainer.value.scrollHeight,
|
||||||
|
behavior: smooth ? 'smooth' : 'auto'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Watch for session switch
|
||||||
|
watch(() => settings.activeSessionId, async (newVal) => {
|
||||||
|
if (newVal) {
|
||||||
|
// 切换会话时,先立即滚动到底部(非平滑),然后再等 DOM 渲染完成后尝试平滑滚动确保到位
|
||||||
|
await scrollToBottom(false);
|
||||||
|
setTimeout(() => scrollToBottom(true), 100);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const filteredSessions = computed(() => {
|
||||||
|
if (!searchQuery.value.trim()) return settings.chatSessions;
|
||||||
|
const q = searchQuery.value.toLowerCase();
|
||||||
|
return settings.chatSessions.filter(s =>
|
||||||
|
s.title.toLowerCase().includes(q) ||
|
||||||
|
s.partner.name.toLowerCase().includes(q)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Input States
|
||||||
|
const myInput = ref('');
|
||||||
|
const partnerInput = ref('');
|
||||||
|
const isTranslating = ref(false);
|
||||||
|
const currentStreamingMessageId = ref<string | null>(null);
|
||||||
|
|
||||||
|
// Dropdowns
|
||||||
|
const myToneDropdownOpen = ref(false);
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
const handleCreateSession = () => {
|
||||||
|
if (!newSessionPartner.value.name.trim()) return;
|
||||||
|
const id = settings.createSession({ ...newSessionMe.value }, { ...newSessionPartner.value });
|
||||||
|
isCreatingSession.value = false;
|
||||||
|
settings.activeSessionId = id;
|
||||||
|
};
|
||||||
|
|
||||||
|
let unlisten: (() => void) | null = null;
|
||||||
|
onMounted(async () => {
|
||||||
|
unlisten = await listen<string>('translation-chunk', (event) => {
|
||||||
|
if (activeSession.value && currentStreamingMessageId.value) {
|
||||||
|
settings.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, {
|
||||||
|
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload
|
||||||
|
});
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
onUnmounted(() => { if (unlisten) unlisten(); });
|
||||||
|
|
||||||
|
const generateCurl = (baseUrl: string, key: string, body: any) => {
|
||||||
|
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;
|
||||||
|
|
||||||
|
const text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim();
|
||||||
|
if (!text) return;
|
||||||
|
|
||||||
|
isTranslating.value = true;
|
||||||
|
|
||||||
|
// 1. Add message to session
|
||||||
|
const messageId = settings.addMessageToSession(activeSession.value.id, sender, text, '');
|
||||||
|
if (!messageId) {
|
||||||
|
isTranslating.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
currentStreamingMessageId.value = messageId;
|
||||||
|
|
||||||
|
if (sender === 'me') myInput.value = ''; else partnerInput.value = '';
|
||||||
|
await scrollToBottom();
|
||||||
|
|
||||||
|
// 2. Prepare Context
|
||||||
|
const historyLimit = 10;
|
||||||
|
const sessionMessages = activeSession.value.messages;
|
||||||
|
const recentMessages = sessionMessages.filter(m => m.id !== messageId).slice(-historyLimit);
|
||||||
|
|
||||||
|
const historyBlock = recentMessages.map(m => {
|
||||||
|
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
|
||||||
|
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
// 3. Prepare Prompt
|
||||||
|
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 myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
|
||||||
|
|
||||||
|
const systemPrompt = CONVERSATION_SYSTEM_PROMPT_TEMPLATE
|
||||||
|
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||||
|
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||||
|
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||||
|
.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 (This is the start of conversation)')
|
||||||
|
.replace(/{FROM_LANG}/g, fromLang.englishName)
|
||||||
|
.replace(/{TO_LANG}/g, toLang.englishName)
|
||||||
|
.replace(/{MY_TONE}/g, myToneLabel);
|
||||||
|
|
||||||
|
const requestBody = {
|
||||||
|
model: settings.modelName,
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: systemPrompt },
|
||||||
|
{ role: "user", content: text }
|
||||||
|
],
|
||||||
|
stream: settings.enableStreaming
|
||||||
|
};
|
||||||
|
|
||||||
|
settings.addLog('request', { type: 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await invoke<string>('translate', {
|
||||||
|
apiAddress: settings.apiBaseUrl,
|
||||||
|
apiKey: settings.apiKey,
|
||||||
|
payload: requestBody
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!settings.enableStreaming) {
|
||||||
|
const fullResponseJson = JSON.parse(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) {
|
||||||
|
const errorMsg = String(err);
|
||||||
|
settings.addLog('error', errorMsg);
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { translated: `Error: ${errorMsg}` });
|
||||||
|
} finally {
|
||||||
|
isTranslating.value = false;
|
||||||
|
currentStreamingMessageId.value = null;
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const evaluateMessage = async (messageId: string) => {
|
||||||
|
if (!activeSession.value) return;
|
||||||
|
const msg = activeSession.value.messages.find(m => m.id === messageId);
|
||||||
|
if (!msg || msg.isEvaluating) return;
|
||||||
|
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true });
|
||||||
|
|
||||||
|
const historyLimit = 10;
|
||||||
|
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
|
||||||
|
const historyBlock = recentMessages.map(m => {
|
||||||
|
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
|
||||||
|
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
// 动态确定目标语气约束
|
||||||
|
const targetTone = msg.sender === 'me'
|
||||||
|
? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和')
|
||||||
|
: '自动识别 (保留原作者原始语气和情绪)';
|
||||||
|
|
||||||
|
const systemPrompt = CONVERSATION_EVALUATION_PROMPT_TEMPLATE
|
||||||
|
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||||
|
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||||
|
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||||
|
.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(/{TARGET_TONE}/g, targetTone);
|
||||||
|
|
||||||
|
const userPrompt = `[Source Text]\n${msg.original}\n\n[Current Translation]\n${msg.translated}`;
|
||||||
|
|
||||||
|
const requestBody = {
|
||||||
|
model: settings.modelName,
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: systemPrompt },
|
||||||
|
{ role: "user", content: userPrompt }
|
||||||
|
],
|
||||||
|
stream: false
|
||||||
|
};
|
||||||
|
|
||||||
|
settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await invoke<string>('translate', {
|
||||||
|
apiAddress: settings.apiBaseUrl,
|
||||||
|
apiKey: settings.apiKey,
|
||||||
|
payload: requestBody
|
||||||
|
});
|
||||||
|
const fullResponseJson = JSON.parse(response);
|
||||||
|
settings.addLog('response', fullResponseJson);
|
||||||
|
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 {
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false });
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const refineMessage = async (messageId: string) => {
|
||||||
|
if (!activeSession.value) return;
|
||||||
|
const msg = activeSession.value.messages.find(m => m.id === messageId);
|
||||||
|
if (!msg || !msg.evaluation || msg.isRefining) return;
|
||||||
|
|
||||||
|
let evalData;
|
||||||
|
try {
|
||||||
|
evalData = JSON.parse(msg.evaluation);
|
||||||
|
} catch (e) { return; }
|
||||||
|
|
||||||
|
const suggestionsText = evalData.suggestions.map((s: any) => `- ${s.text} (Importance: ${s.importance})`).join('\n');
|
||||||
|
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' });
|
||||||
|
currentStreamingMessageId.value = messageId;
|
||||||
|
|
||||||
|
const historyLimit = 10;
|
||||||
|
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
|
||||||
|
const historyBlock = recentMessages.map(m => {
|
||||||
|
const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name;
|
||||||
|
return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`;
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
|
||||||
|
|
||||||
|
const systemPrompt = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE
|
||||||
|
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||||
|
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||||
|
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||||
|
.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 = {
|
||||||
|
model: settings.modelName,
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: systemPrompt },
|
||||||
|
{ role: "user", content: `Please refine the following original text: ${msg.original}` }
|
||||||
|
],
|
||||||
|
stream: settings.enableStreaming
|
||||||
|
};
|
||||||
|
|
||||||
|
settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await invoke<string>('translate', {
|
||||||
|
apiAddress: settings.apiBaseUrl,
|
||||||
|
apiKey: settings.apiKey,
|
||||||
|
payload: requestBody
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!settings.enableStreaming) {
|
||||||
|
const fullResponseJson = JSON.parse(response);
|
||||||
|
const refinedText = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { translated: refinedText });
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
settings.addLog('error', String(err));
|
||||||
|
} finally {
|
||||||
|
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined });
|
||||||
|
currentStreamingMessageId.value = null;
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseEvaluation = (evalStr?: string) => {
|
||||||
|
if (!evalStr) return null;
|
||||||
|
try {
|
||||||
|
// 1. 清洗数据:剔除 Markdown 代码块标记 (如 ```json ... ``` 或 ``` ...)
|
||||||
|
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) => {
|
||||||
|
if (importance >= 80) return 'text-red-500 bg-red-50 dark:bg-red-900/20 border-red-100 dark:border-red-900/30';
|
||||||
|
if (importance >= 40) return 'text-amber-500 bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-900/30';
|
||||||
|
return 'text-blue-500 bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/30';
|
||||||
|
};
|
||||||
|
|
||||||
|
const getSeverityIcon = (importance: number) => {
|
||||||
|
if (importance >= 80) return AlertCircle;
|
||||||
|
if (importance >= 40) return TriangleAlert;
|
||||||
|
return ShieldCheck;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGlobalClick = () => {
|
||||||
|
myToneDropdownOpen.value = false;
|
||||||
|
closeAllModalDropdowns();
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(() => window.addEventListener('click', handleGlobalClick));
|
||||||
|
onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex-1 flex overflow-hidden bg-slate-100/50 dark:bg-slate-950">
|
||||||
|
<!-- Sessions Sidebar -->
|
||||||
|
<div class="w-80 md:w-96 border-r dark:border-slate-800 flex flex-col bg-white/60 dark:bg-slate-900/40 shrink-0">
|
||||||
|
<div class="p-4 border-b dark:border-slate-800 space-y-4">
|
||||||
|
<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="isCreatingSession = true"
|
||||||
|
class="p-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all shadow-sm flex items-center gap-1 text-xs px-2.5"
|
||||||
|
>
|
||||||
|
<Plus class="w-3.5 h-3.5" />
|
||||||
|
新建会话
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="relative group">
|
||||||
|
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 group-focus-within:text-blue-500 transition-colors" />
|
||||||
|
<input
|
||||||
|
v-model="searchQuery"
|
||||||
|
type="text"
|
||||||
|
placeholder="搜索会话..."
|
||||||
|
class="w-full pl-9 pr-4 py-2 bg-slate-100 dark:bg-slate-800 border-none rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all dark:text-slate-200"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1">
|
||||||
|
<div v-if="filteredSessions.length === 0" class="py-20 text-center space-y-2">
|
||||||
|
<MessageSquare 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="session in filteredSessions"
|
||||||
|
:key="session.id"
|
||||||
|
@click="settings.activeSessionId = session.id"
|
||||||
|
:class="cn(
|
||||||
|
'w-full p-4 rounded-xl text-left transition-all border group relative cursor-pointer',
|
||||||
|
settings.activeSessionId === session.id
|
||||||
|
? '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'
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between mb-1.5">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<div class="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-xs">
|
||||||
|
{{ session.partner.name.charAt(0).toUpperCase() }}
|
||||||
|
</div>
|
||||||
|
<span class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate">{{ session.partner.name }}</span>
|
||||||
|
</div>
|
||||||
|
<span class="text-[10px] text-slate-400 font-mono">{{ session.lastActivity.split(' ')[1].substring(0, 5) }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="text-[11px] text-slate-500 dark:text-slate-400 line-clamp-1 italic">
|
||||||
|
{{ session.messages.length > 0 ? session.messages[session.messages.length - 1].translated : '开启新翻译对话...' }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click.stop="settings.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"
|
||||||
|
title="删除会话"
|
||||||
|
>
|
||||||
|
<Trash2 class="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Main Chat Area -->
|
||||||
|
<div class="flex-1 flex flex-col min-w-0 bg-white dark:bg-slate-900 relative">
|
||||||
|
<template v-if="activeSession">
|
||||||
|
<!-- Chat Header -->
|
||||||
|
<div class="h-16 border-b dark:border-slate-800 flex items-center justify-between px-6 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md z-10 shrink-0">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div class="flex -space-x-2">
|
||||||
|
<div class="w-8 h-8 rounded-full border-2 border-white dark:border-slate-900 bg-blue-600 flex items-center justify-center text-white text-[10px] font-bold">我</div>
|
||||||
|
<div class="w-8 h-8 rounded-full border-2 border-white dark:border-slate-900 bg-slate-200 dark:bg-slate-700 flex items-center justify-center text-slate-600 dark:text-slate-300 text-[10px] font-bold">
|
||||||
|
{{ activeSession.partner.name.charAt(0).toUpperCase() }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col">
|
||||||
|
<span class="text-sm font-bold dark:text-slate-200">{{ activeSession!.partner.name }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<div class="flex items-center gap-1.5 px-2.5 py-1 bg-slate-100 dark:bg-slate-800 rounded-full text-[10px] text-slate-500 font-medium">
|
||||||
|
<Sparkles class="w-3 h-3 text-blue-500" />
|
||||||
|
上下文模式已开启
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Messages Flow -->
|
||||||
|
<div
|
||||||
|
ref="messageContainer"
|
||||||
|
class="flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-slate-50/50 dark:bg-slate-950"
|
||||||
|
>
|
||||||
|
<div v-if="activeSession.messages.length === 0" class="flex flex-col items-center justify-center h-full opacity-30 space-y-4">
|
||||||
|
<MessageSquare class="w-16 h-16" />
|
||||||
|
<p class="text-sm font-medium">开始你的第一句翻译吧</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-for="msg in activeSession.messages"
|
||||||
|
:key="msg.id"
|
||||||
|
:class="cn('flex flex-col max-w-[85%]', msg.sender === 'me' ? 'ml-auto items-end' : 'mr-auto items-start')"
|
||||||
|
>
|
||||||
|
<!-- Sender Label (Optional) -->
|
||||||
|
<div class="flex items-center gap-2 mb-1 px-1">
|
||||||
|
<span class="text-[10px] font-bold text-slate-400 uppercase">{{ msg.sender === 'me' ? '我' : activeSession.partner.name }}</span>
|
||||||
|
<span class="text-[9px] text-slate-300 font-mono">{{ msg.timestamp.split(' ')[1].substring(0, 5) }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Bubble -->
|
||||||
|
<div
|
||||||
|
:class="cn(
|
||||||
|
'rounded-2xl px-4 py-3 shadow-sm border transition-all group relative',
|
||||||
|
msg.sender === 'me'
|
||||||
|
? 'bg-blue-600 dark:bg-blue-700 border-blue-500/50 dark:border-blue-800 rounded-tr-none'
|
||||||
|
: 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-tl-none'
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<!-- Original Text -->
|
||||||
|
<p :class="cn('text-[13px] mb-2 leading-snug', msg.sender === 'me' ? 'text-blue-100' : 'text-slate-500 dark:text-slate-400')">
|
||||||
|
{{ msg.original }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<!-- Translated Text -->
|
||||||
|
<div class="relative min-h-[1.5rem]">
|
||||||
|
<p :class="cn('text-base font-medium leading-relaxed', msg.sender === 'me' ? 'text-white' : 'text-slate-800 dark:text-slate-100')">
|
||||||
|
{{ msg.translated }}
|
||||||
|
<span v-if="isTranslating && currentStreamingMessageId === msg.id" class="inline-block w-1.5 h-4 bg-current animate-pulse ml-0.5 align-middle"></span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Action Tools (Copy, Evaluate, Refine) -->
|
||||||
|
<div :class="cn(
|
||||||
|
'absolute top-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center bg-white/90 dark:bg-slate-800/90 rounded-full shadow-lg border dark:border-slate-700 px-1 py-1 z-20',
|
||||||
|
msg.sender === 'me' ? '-left-24' : '-right-24'
|
||||||
|
)">
|
||||||
|
<button
|
||||||
|
@click="copyWithFeedback(msg.translated, msg.id)"
|
||||||
|
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors"
|
||||||
|
title="复制译文"
|
||||||
|
>
|
||||||
|
<Check v-if="activeCopyId === msg.id" class="w-3.5 h-3.5 text-green-600" />
|
||||||
|
<Copy v-else class="w-3.5 h-3.5 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="evaluateMessage(msg.id)"
|
||||||
|
:disabled="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="审计翻译"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="msg.isEvaluating" class="w-3.5 h-3.5 animate-spin text-blue-500" />
|
||||||
|
<ShieldCheck v-else class="w-3.5 h-3.5 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="msg.evaluation"
|
||||||
|
@click="refineMessage(msg.id)"
|
||||||
|
:disabled="msg.isRefining"
|
||||||
|
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
|
||||||
|
title="执行润色"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="msg.isRefining" class="w-3.5 h-3.5 animate-spin text-purple-500" />
|
||||||
|
<Sparkles v-else class="w-3.5 h-3.5 text-purple-400" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Evaluation Results -->
|
||||||
|
<transition
|
||||||
|
enter-active-class="transition duration-200 ease-out"
|
||||||
|
enter-from-class="transform -translate-y-2 opacity-0"
|
||||||
|
enter-to-class="transform translate-y-0 opacity-100"
|
||||||
|
>
|
||||||
|
<div v-if="msg.evaluation" class="mt-2 w-full max-w-sm">
|
||||||
|
<div class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm border border-slate-200 dark:border-slate-800 rounded-xl p-3 shadow-sm space-y-3">
|
||||||
|
<!-- Score & Analysis -->
|
||||||
|
<div class="flex items-start gap-2.5">
|
||||||
|
<div :class="cn(
|
||||||
|
'shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-xs font-black',
|
||||||
|
parseEvaluation(msg.evaluation).score >= 90 ? 'bg-green-100 text-green-600 dark:bg-green-900/30' :
|
||||||
|
parseEvaluation(msg.evaluation).score >= 75 ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30' :
|
||||||
|
'bg-red-100 text-red-600 dark:bg-red-900/30'
|
||||||
|
)">
|
||||||
|
{{ parseEvaluation(msg.evaluation).score }}
|
||||||
|
</div>
|
||||||
|
<p class="text-[11px] text-slate-600 dark:text-slate-400 leading-relaxed italic">
|
||||||
|
{{ parseEvaluation(msg.evaluation).analysis }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Suggestions with Severity -->
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<div
|
||||||
|
v-for="sug in parseEvaluation(msg.evaluation).suggestions"
|
||||||
|
:key="sug.id"
|
||||||
|
:class="cn('flex items-center gap-2 px-2 py-1.5 rounded-lg border text-[10px] font-medium transition-all', getSeverityColor(sug.importance))"
|
||||||
|
>
|
||||||
|
<component :is="getSeverityIcon(sug.importance)" class="w-3 h-3 shrink-0" />
|
||||||
|
<span class="flex-1">{{ sug.text }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Refine Action -->
|
||||||
|
<button
|
||||||
|
@click="refineMessage(msg.id)"
|
||||||
|
:disabled="msg.isRefining"
|
||||||
|
class="w-full py-1.5 bg-purple-50 hover:bg-purple-100 dark:bg-purple-900/20 dark:hover:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-lg text-[10px] font-bold transition-all flex items-center justify-center gap-1.5"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="msg.isRefining" class="w-3 h-3 animate-spin" />
|
||||||
|
<Sparkles v-else class="w-3 h-3" />
|
||||||
|
{{ msg.isRefining ? '正在润色...' : '根据建议执行润色' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Inputs Area -->
|
||||||
|
<div class="p-6 border-t dark:border-slate-800 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shrink-0">
|
||||||
|
<div class="grid grid-cols-2 gap-6">
|
||||||
|
<!-- Partner Input (Left) -->
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex items-center justify-between px-1 h-7">
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<!-- Name Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-[10px] font-bold text-slate-500 dark:text-slate-400">
|
||||||
|
<User class="w-3 h-3" />
|
||||||
|
{{ activeSession!.partner.name }}
|
||||||
|
</div>
|
||||||
|
<!-- Gender Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-[10px] font-bold text-slate-500 dark:text-slate-400">
|
||||||
|
<Venus v-if="activeSession!.partner.gender === 'Female'" class="w-3 h-3 text-pink-500" />
|
||||||
|
<Mars v-else-if="activeSession!.partner.gender === 'Male'" class="w-3 h-3 text-blue-500" />
|
||||||
|
<CircleSlash v-else class="w-3 h-3 text-slate-400" />
|
||||||
|
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === activeSession!.partner.gender)?.label }}
|
||||||
|
</div>
|
||||||
|
<!-- Language Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-[10px] font-bold text-slate-500 dark:text-slate-400">
|
||||||
|
<Languages class="w-3 h-3 text-emerald-500" />
|
||||||
|
{{ activeSession!.partner.language.displayName }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="text-[10px] text-slate-400 italic flex items-center h-full">自动识别语气</div>
|
||||||
|
</div>
|
||||||
|
<div class="relative group">
|
||||||
|
<textarea
|
||||||
|
v-model="partnerInput"
|
||||||
|
@keydown.enter.exact.prevent="translateMessage('partner')"
|
||||||
|
placeholder="粘贴对方说的话..."
|
||||||
|
class="w-full h-24 p-4 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50 transition-all text-sm resize-none dark:text-slate-200"
|
||||||
|
></textarea>
|
||||||
|
<button
|
||||||
|
@click="translateMessage('partner')"
|
||||||
|
:disabled="isTranslating || !partnerInput.trim()"
|
||||||
|
class="absolute right-3 bottom-3 p-2 bg-slate-200 dark:bg-slate-700 text-slate-500 dark:text-slate-400 rounded-lg hover:bg-blue-600 hover:text-white dark:hover:bg-blue-600 transition-all disabled:opacity-30 shadow-sm"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="isTranslating && currentStreamingMessageId" class="w-4 h-4 animate-spin" />
|
||||||
|
<Send v-else class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- My Input (Right) -->
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex items-center justify-between px-1 h-7">
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<!-- Name Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 dark:bg-blue-900/20 rounded text-[10px] font-bold text-blue-600 dark:text-blue-400">
|
||||||
|
<User class="w-3 h-3" />
|
||||||
|
{{ activeSession!.me.name }}
|
||||||
|
</div>
|
||||||
|
<!-- Gender Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 dark:bg-blue-900/20 rounded text-[10px] font-bold text-blue-600 dark:text-blue-400">
|
||||||
|
<Venus v-if="activeSession!.me.gender === 'Female'" class="w-3 h-3 text-pink-500" />
|
||||||
|
<Mars v-else-if="activeSession!.me.gender === 'Male'" class="w-3 h-3 text-blue-500" />
|
||||||
|
<CircleSlash v-else class="w-3 h-3 text-slate-400" />
|
||||||
|
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === activeSession!.me.gender)?.label }}
|
||||||
|
</div>
|
||||||
|
<!-- Language Badge -->
|
||||||
|
<div class="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 dark:bg-blue-900/20 rounded text-[10px] font-bold text-blue-600 dark:text-blue-400">
|
||||||
|
<Languages class="w-3 h-3 text-emerald-500" />
|
||||||
|
{{ activeSession!.me.language.displayName }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- My Tone Selector -->
|
||||||
|
<div class="relative flex items-center h-full">
|
||||||
|
<button
|
||||||
|
@click.stop="myToneDropdownOpen = !myToneDropdownOpen"
|
||||||
|
class="flex items-center gap-1 text-[10px] font-bold text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 px-2 py-1 rounded transition-colors"
|
||||||
|
>
|
||||||
|
<Type class="w-3 h-3" />
|
||||||
|
语气: {{ TONE_REGISTER_OPTIONS.find(o => o.value === activeSession?.me.tone)?.label || '随和' }}
|
||||||
|
<ChevronDown class="w-2.5 h-2.5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<transition
|
||||||
|
enter-active-class="transition duration-100 ease-out"
|
||||||
|
enter-from-class="transform scale-95 opacity-0"
|
||||||
|
enter-to-class="transform scale-100 opacity-100"
|
||||||
|
leave-active-class="transition duration-75 ease-in"
|
||||||
|
leave-from-class="transform scale-100 opacity-100"
|
||||||
|
leave-to-class="transform scale-95 opacity-0"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="myToneDropdownOpen"
|
||||||
|
class="absolute right-0 bottom-full mb-2 w-48 bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50 py-2 flex flex-col max-h-60 overflow-y-auto custom-scrollbar"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-for="opt in TONE_REGISTER_OPTIONS"
|
||||||
|
:key="opt.value"
|
||||||
|
@click="activeSession!.me.tone = opt.value; myToneDropdownOpen = false"
|
||||||
|
:class="cn(
|
||||||
|
'px-4 py-2 text-xs text-left transition-colors flex items-center justify-between',
|
||||||
|
activeSession!.me.tone === opt.value ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 font-bold' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700/50'
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
{{ opt.label }}
|
||||||
|
<Check v-if="activeSession!.me.tone === opt.value" class="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="relative group">
|
||||||
|
<textarea
|
||||||
|
v-model="myInput"
|
||||||
|
@keydown.enter.exact.prevent="translateMessage('me')"
|
||||||
|
placeholder="输入你想说的话..."
|
||||||
|
class="w-full h-24 p-4 rounded-xl bg-blue-50/30 dark:bg-blue-900/10 border border-blue-100 dark:border-blue-900/30 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50 transition-all text-sm resize-none dark:text-slate-200"
|
||||||
|
></textarea>
|
||||||
|
<button
|
||||||
|
@click="translateMessage('me')"
|
||||||
|
:disabled="isTranslating || !myInput.trim()"
|
||||||
|
class="absolute right-3 bottom-3 p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all disabled:opacity-30 shadow-md"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="isTranslating && currentStreamingMessageId" class="w-4 h-4 animate-spin" />
|
||||||
|
<Send v-else class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- No Active Session Placeholder -->
|
||||||
|
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-6">
|
||||||
|
<div class="w-24 h-24 rounded-full bg-slate-50 dark:bg-slate-800/50 flex items-center justify-center">
|
||||||
|
<MessageSquare class="w-12 h-12 opacity-20" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<h3 class="text-lg font-bold text-slate-400 dark:text-slate-600">选择或创建一个对话</h3>
|
||||||
|
<p class="text-sm">在左侧侧边栏管理你的翻译会话</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
@click="isCreatingSession = true"
|
||||||
|
class="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-xl font-medium transition-all shadow-lg"
|
||||||
|
>
|
||||||
|
<Plus class="w-5 h-5" />
|
||||||
|
开启新对话
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- New Session Modal -->
|
||||||
|
<transition
|
||||||
|
enter-active-class="transition duration-200 ease-out"
|
||||||
|
enter-from-class="opacity-0 scale-95"
|
||||||
|
enter-to-class="opacity-100 scale-100"
|
||||||
|
leave-active-class="transition duration-150 ease-in"
|
||||||
|
leave-from-class="opacity-100 scale-100"
|
||||||
|
leave-to-class="opacity-0 scale-95"
|
||||||
|
>
|
||||||
|
<div v-if="isCreatingSession" class="absolute inset-0 z-[100] flex items-center justify-center p-6 bg-slate-900/20 backdrop-blur-sm">
|
||||||
|
<div class="w-full max-w-lg bg-white dark:bg-slate-900 rounded-3xl shadow-2xl border dark:border-slate-800">
|
||||||
|
<div class="p-6 border-b dark:border-slate-800 flex items-center justify-between bg-slate-50 dark:bg-slate-950 rounded-t-3xl">
|
||||||
|
<h3 class="text-lg font-bold dark:text-slate-100 flex items-center gap-2">
|
||||||
|
<Plus class="w-5 h-5 text-blue-500" />
|
||||||
|
创建新会话
|
||||||
|
</h3>
|
||||||
|
<button @click="isCreatingSession = false" class="p-2 hover:bg-slate-200 dark:hover:bg-slate-800 rounded-full transition-colors">
|
||||||
|
<X class="w-5 h-5 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="p-8 space-y-8">
|
||||||
|
<!-- Me Config -->
|
||||||
|
<section class="space-y-4">
|
||||||
|
<h4 class="text-xs font-black text-blue-500 uppercase tracking-widest">我的身份设定</h4>
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">姓名</label>
|
||||||
|
<input v-model="newSessionMe.name" type="text" class="w-full px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl outline-none focus:ring-2 focus:ring-blue-500/20 text-sm dark:text-slate-200" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">使用语言</label>
|
||||||
|
<div class="relative">
|
||||||
|
<button
|
||||||
|
@click.stop="closeAllModalDropdowns(); meLangDropdownOpen = !meLangDropdownOpen"
|
||||||
|
class="w-full flex items-center justify-between px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl text-sm dark:text-slate-200"
|
||||||
|
>
|
||||||
|
{{ newSessionMe.language.displayName }}
|
||||||
|
<ChevronDown class="w-4 h-4 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<div v-if="meLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2 custom-scrollbar">
|
||||||
|
<button v-for="lang in LANGUAGES" :key="lang.code" @click="newSessionMe.language = lang; meLangDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
|
||||||
|
{{ lang.displayName }}
|
||||||
|
<Check v-if="newSessionMe.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">性别</label>
|
||||||
|
<div class="relative">
|
||||||
|
<button
|
||||||
|
@click.stop="closeAllModalDropdowns(); meGenderDropdownOpen = !meGenderDropdownOpen"
|
||||||
|
class="w-full flex items-center justify-between px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl text-sm dark:text-slate-200"
|
||||||
|
>
|
||||||
|
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionMe.gender)?.label }}
|
||||||
|
<ChevronDown class="w-4 h-4 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<div v-if="meGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2">
|
||||||
|
<button v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" @click="newSessionMe.gender = opt.value; meGenderDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
|
||||||
|
{{ opt.label }}
|
||||||
|
<Check v-if="newSessionMe.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Partner Config -->
|
||||||
|
<section class="space-y-4">
|
||||||
|
<h4 class="text-xs font-black text-slate-400 uppercase tracking-widest">对方身份设定</h4>
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">姓名</label>
|
||||||
|
<input v-model="newSessionPartner.name" type="text" placeholder="姓名" class="w-full px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl outline-none focus:ring-2 focus:ring-blue-500/20 text-sm dark:text-slate-200" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">使用语言</label>
|
||||||
|
<div class="relative">
|
||||||
|
<button
|
||||||
|
@click.stop="closeAllModalDropdowns(); partnerLangDropdownOpen = !partnerLangDropdownOpen"
|
||||||
|
class="w-full flex items-center justify-between px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl text-sm dark:text-slate-200"
|
||||||
|
>
|
||||||
|
{{ newSessionPartner.language.displayName }}
|
||||||
|
<ChevronDown class="w-4 h-4 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<div v-if="partnerLangDropdownOpen" class="absolute left-0 top-full mt-1 w-full max-h-60 overflow-y-auto bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2 custom-scrollbar">
|
||||||
|
<button v-for="lang in LANGUAGES" :key="lang.code" @click="newSessionPartner.language = lang; partnerLangDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
|
||||||
|
{{ lang.displayName }}
|
||||||
|
<Check v-if="newSessionPartner.language.code === lang.code" class="w-3.5 h-3.5 text-blue-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[10px] font-bold text-slate-400 uppercase">性别</label>
|
||||||
|
<div class="relative">
|
||||||
|
<button
|
||||||
|
@click.stop="closeAllModalDropdowns(); partnerGenderDropdownOpen = !partnerGenderDropdownOpen"
|
||||||
|
class="w-full flex items-center justify-between px-4 py-2.5 bg-slate-50 dark:bg-slate-800 border dark:border-slate-700 rounded-xl text-sm dark:text-slate-200"
|
||||||
|
>
|
||||||
|
{{ SPEAKER_IDENTITY_OPTIONS.find(o => o.value === newSessionPartner.gender)?.label }}
|
||||||
|
<ChevronDown class="w-4 h-4 text-slate-400" />
|
||||||
|
</button>
|
||||||
|
<div v-if="partnerGenderDropdownOpen" class="absolute left-0 top-full mt-1 w-full bg-white dark:bg-slate-800 border dark:border-slate-700 rounded-xl shadow-xl z-[110] py-2">
|
||||||
|
<button v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" @click="newSessionPartner.gender = opt.value; partnerGenderDropdownOpen = false" class="w-full px-4 py-2 text-sm text-left hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-slate-200 transition-colors flex items-center justify-between">
|
||||||
|
{{ opt.label }}
|
||||||
|
<Check v-if="newSessionPartner.gender === opt.value" class="w-3.5 h-3.5 text-blue-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="handleCreateSession"
|
||||||
|
:disabled="!newSessionPartner.name.trim()"
|
||||||
|
class="w-full 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"
|
||||||
|
>
|
||||||
|
开始会话
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.custom-scrollbar::-webkit-scrollbar {
|
||||||
|
width: 5px;
|
||||||
|
}
|
||||||
|
.custom-scrollbar::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||||
|
background: rgba(148, 163, 184, 0.2);
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: rgba(148, 163, 184, 0.4);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -19,9 +19,20 @@ watch(() => settings.logs, (newVal) => {
|
|||||||
}
|
}
|
||||||
}, { immediate: true });
|
}, { immediate: true });
|
||||||
|
|
||||||
|
const decodeUnicode = (str: string) => {
|
||||||
|
if (!str) return str;
|
||||||
|
try {
|
||||||
|
return str.replace(/\\u([0-9a-fA-F]{4})/g, (_match, grp) => {
|
||||||
|
return String.fromCharCode(parseInt(grp, 16));
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const getLogSummary = (log: any) => {
|
const getLogSummary = (log: any) => {
|
||||||
if (log.type === 'error') return String(log.content);
|
if (log.type === 'error') return String(log.content);
|
||||||
if (typeof log.content === 'string') return log.content;
|
if (typeof log.content === 'string') return decodeUnicode(log.content);
|
||||||
if (log.content && log.content.model) return `Model: ${log.content.model}`;
|
if (log.content && log.content.model) return `Model: ${log.content.model}`;
|
||||||
if (log.content && log.content.score) return `Score: ${log.content.score}`;
|
if (log.content && log.content.score) return `Score: ${log.content.score}`;
|
||||||
return 'JSON Data';
|
return 'JSON Data';
|
||||||
@@ -92,8 +103,18 @@ const getLogSummary = (log: any) => {
|
|||||||
)"
|
)"
|
||||||
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
<button
|
<button
|
||||||
@click="copyWithFeedback(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content), `log-${selectedLogItem.id}`)"
|
v-if="selectedLogItem.curl"
|
||||||
|
@click="copyWithFeedback(decodeUnicode(selectedLogItem.curl), `curl-${selectedLogItem.id}`)"
|
||||||
|
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/30 rounded-lg transition-colors border border-blue-100 dark:border-blue-900/50"
|
||||||
|
>
|
||||||
|
<Check v-if="activeCopyId === `curl-${selectedLogItem.id}`" class="w-4 h-4" />
|
||||||
|
<Copy v-else class="w-4 h-4" />
|
||||||
|
复制 cURL
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="copyWithFeedback(decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content)), `log-${selectedLogItem.id}`)"
|
||||||
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
||||||
>
|
>
|
||||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||||
@@ -101,9 +122,18 @@ const getLogSummary = (log: any) => {
|
|||||||
复制内容
|
复制内容
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar">
|
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar space-y-6">
|
||||||
<pre class="font-mono text-xs leading-relaxed text-slate-700 dark:text-slate-300 whitespace-pre-wrap break-all">{{ typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content }}</pre>
|
<div v-if="selectedLogItem.curl" class="space-y-2">
|
||||||
|
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">cURL 请求命令</h3>
|
||||||
|
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-blue-400 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(selectedLogItem.curl) }}</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">{{ selectedLogItem.type === 'request' ? 'Payload (JSON)' : 'Response Data' }}</h3>
|
||||||
|
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-slate-300 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content) }}</pre>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-4">
|
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-4">
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
<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 } from 'lucide-vue-next';
|
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 { useSettingsStore, DEFAULT_TEMPLATE, DEFAULT_EVALUATION_TEMPLATE, DEFAULT_REFINEMENT_TEMPLATE, type ApiProfile } from '../stores/settings';
|
||||||
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'>('api');
|
||||||
|
const showApiKey = ref(false);
|
||||||
|
|
||||||
const newProfileName = ref('');
|
const newProfileName = ref('');
|
||||||
const isSavingProfile = ref(false);
|
const isSavingProfile = ref(false);
|
||||||
@@ -34,6 +35,34 @@ const deleteProfile = (id: string) => {
|
|||||||
settings.profiles = settings.profiles.filter(p => p.id !== id);
|
settings.profiles = settings.profiles.filter(p => p.id !== id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const editingProfileId = ref<string | null>(null);
|
||||||
|
const editProfileForm = ref<ApiProfile | null>(null);
|
||||||
|
const showEditApiKey = ref(false);
|
||||||
|
|
||||||
|
const startEditProfile = (profile: ApiProfile) => {
|
||||||
|
editingProfileId.value = profile.id;
|
||||||
|
editProfileForm.value = { ...profile };
|
||||||
|
showEditApiKey.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelEditProfile = () => {
|
||||||
|
editingProfileId.value = null;
|
||||||
|
editProfileForm.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveEditProfile = () => {
|
||||||
|
if (!editProfileForm.value || !editingProfileId.value) return;
|
||||||
|
if (!editProfileForm.value.name.trim()) return;
|
||||||
|
|
||||||
|
const index = settings.profiles.findIndex(p => p.id === editingProfileId.value);
|
||||||
|
if (index !== -1) {
|
||||||
|
settings.profiles[index] = { ...editProfileForm.value };
|
||||||
|
}
|
||||||
|
|
||||||
|
editingProfileId.value = null;
|
||||||
|
editProfileForm.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
const evaluationProfileDropdownOpen = ref(false);
|
const evaluationProfileDropdownOpen = ref(false);
|
||||||
const toggleDropdown = (type: string) => {
|
const toggleDropdown = (type: string) => {
|
||||||
if (type === 'evaluationProfile') evaluationProfileDropdownOpen.value = !evaluationProfileDropdownOpen.value;
|
if (type === 'evaluationProfile') evaluationProfileDropdownOpen.value = !evaluationProfileDropdownOpen.value;
|
||||||
@@ -161,12 +190,22 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
</div>
|
</div>
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">API Key</label>
|
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">API Key</label>
|
||||||
|
<div class="relative">
|
||||||
<input
|
<input
|
||||||
v-model="settings.apiKey"
|
v-model="settings.apiKey"
|
||||||
type="password"
|
:type="showApiKey ? 'text' : 'password'"
|
||||||
class="w-full px-4 py-2.5 border dark:border-slate-700 rounded-xl bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
|
class="w-full pl-4 pr-12 py-2.5 border dark:border-slate-700 rounded-xl bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
|
||||||
placeholder="sk-..."
|
placeholder="sk-..."
|
||||||
/>
|
/>
|
||||||
|
<button
|
||||||
|
@click="showApiKey = !showApiKey"
|
||||||
|
type="button"
|
||||||
|
class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors focus:outline-none"
|
||||||
|
>
|
||||||
|
<Eye v-if="showApiKey" class="w-5 h-5" />
|
||||||
|
<EyeOff v-else class="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">Model Name</label>
|
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">Model Name</label>
|
||||||
@@ -189,8 +228,39 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
<div
|
<div
|
||||||
v-for="profile in settings.profiles"
|
v-for="profile in settings.profiles"
|
||||||
:key="profile.id"
|
:key="profile.id"
|
||||||
class="p-3 flex items-center justify-between group hover:bg-white dark:hover:bg-slate-800 transition-colors rounded-lg border border-transparent hover:border-slate-200 dark:hover:border-slate-700"
|
|
||||||
>
|
>
|
||||||
|
<!-- 编辑模式 -->
|
||||||
|
<div v-if="editingProfileId === profile.id && editProfileForm" class="p-4 bg-white dark:bg-slate-800/80 rounded-xl border border-blue-200 dark:border-blue-800/50 shadow-sm space-y-3 my-1">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">预设名称</label>
|
||||||
|
<input v-model="editProfileForm.name" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all text-sm text-slate-900 dark:text-slate-100" placeholder="预设名称" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">API Base URL</label>
|
||||||
|
<input v-model="editProfileForm.apiBaseUrl" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">API Key</label>
|
||||||
|
<div class="relative">
|
||||||
|
<input v-model="editProfileForm.apiKey" :type="showEditApiKey ? 'text' : 'password'" class="w-full pl-3 pr-10 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||||
|
<button @click="showEditApiKey = !showEditApiKey" type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors focus:outline-none p-1">
|
||||||
|
<Eye v-if="showEditApiKey" class="w-4 h-4" />
|
||||||
|
<EyeOff v-else class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">Model Name</label>
|
||||||
|
<input v-model="editProfileForm.modelName" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-end gap-2 pt-2">
|
||||||
|
<button @click="cancelEditProfile" class="px-4 py-2 text-xs font-medium text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 rounded-lg transition-colors">取消</button>
|
||||||
|
<button @click="saveEditProfile" :disabled="!editProfileForm.name.trim()" class="px-4 py-2 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors">保存修改</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 正常显示模式 -->
|
||||||
|
<div v-else class="p-3 flex items-center justify-between group hover:bg-white dark:hover:bg-slate-800 transition-colors rounded-lg border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
|
||||||
<div class="flex flex-col gap-1 min-w-0">
|
<div class="flex flex-col gap-1 min-w-0">
|
||||||
<span class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate">{{ profile.name }}</span>
|
<span class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate">{{ profile.name }}</span>
|
||||||
<div class="flex items-center gap-2 text-[10px] text-slate-500 dark:text-slate-400 font-mono bg-slate-100 dark:bg-slate-950 px-2 py-0.5 rounded w-fit">
|
<div class="flex items-center gap-2 text-[10px] text-slate-500 dark:text-slate-400 font-mono bg-slate-100 dark:bg-slate-950 px-2 py-0.5 rounded w-fit">
|
||||||
@@ -199,7 +269,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
<span class="truncate max-w-48">{{ profile.apiBaseUrl }}</span>
|
<span class="truncate max-w-48">{{ profile.apiBaseUrl }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
<div class="flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
<button
|
<button
|
||||||
@click="applyProfile(profile)"
|
@click="applyProfile(profile)"
|
||||||
class="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg transition-colors text-xs font-medium shadow-sm"
|
class="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg transition-colors text-xs font-medium shadow-sm"
|
||||||
@@ -207,6 +277,13 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
<Play class="w-3 h-3 fill-current" />
|
<Play class="w-3 h-3 fill-current" />
|
||||||
应用
|
应用
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
@click="startEditProfile(profile)"
|
||||||
|
class="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"
|
||||||
|
title="编辑"
|
||||||
|
>
|
||||||
|
<Pencil class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
@click="deleteProfile(profile.id)"
|
@click="deleteProfile(profile.id)"
|
||||||
class="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
|
class="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
|
||||||
@@ -216,7 +293,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div> </div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -361,7 +438,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
></textarea>
|
></textarea>
|
||||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
|
||||||
<div class="flex flex-wrap gap-1.5">
|
<div class="flex flex-wrap gap-1.5">
|
||||||
<span v-for="tag in ['{SOURCE_CODE}', '{TARGET_CODE}', '{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}']" :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>
|
<span v-for="tag in ['{SOURCE_CODE}', '{TARGET_CODE}', '{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}']" :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>
|
||||||
@@ -373,7 +449,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
<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="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="flex items-center gap-2">
|
||||||
<div class="w-2 h-2 rounded-full bg-amber-500"></div>
|
<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">质量审计指令 (JSON 输出)</h3>
|
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">质量审计指令</h3>
|
||||||
</div>
|
</div>
|
||||||
<button @click="settings.evaluationPromptTemplate = DEFAULT_EVALUATION_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
<button @click="settings.evaluationPromptTemplate = DEFAULT_EVALUATION_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -384,7 +460,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
></textarea>
|
></textarea>
|
||||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
|
||||||
<div class="flex flex-wrap gap-1.5">
|
<div class="flex flex-wrap gap-1.5">
|
||||||
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :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>
|
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :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>
|
||||||
@@ -407,7 +482,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
|||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
></textarea>
|
></textarea>
|
||||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
|
||||||
<div class="flex flex-wrap gap-1.5">
|
<div class="flex flex-wrap gap-1.5">
|
||||||
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :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>
|
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :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>
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ const sourceText = ref('');
|
|||||||
const context = ref('');
|
const context = ref('');
|
||||||
const targetText = ref('');
|
const targetText = ref('');
|
||||||
const isTranslating = ref(false);
|
const isTranslating = ref(false);
|
||||||
|
const currentHistoryId = ref<string | null>(null);
|
||||||
|
|
||||||
interface Suggestion { id: number; text: string; importance: number; }
|
interface Suggestion { id: number; text: string; importance: number; }
|
||||||
interface EvaluationResult { score: number; analysis: string; suggestions?: Suggestion[]; }
|
interface EvaluationResult { score: number; analysis: string; suggestions?: Suggestion[]; }
|
||||||
@@ -104,6 +105,15 @@ const clearSource = () => {
|
|||||||
evaluationResult.value = null;
|
evaluationResult.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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 evaluateTranslation = async () => {
|
const evaluateTranslation = async () => {
|
||||||
if (!targetText.value) return;
|
if (!targetText.value) return;
|
||||||
isEvaluating.value = true;
|
isEvaluating.value = true;
|
||||||
@@ -139,14 +149,18 @@ const evaluateTranslation = async () => {
|
|||||||
stream: false
|
stream: false
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', { type: 'evaluation', ...requestBody });
|
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 invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||||
try {
|
try {
|
||||||
const jsonStr = response.replace(/```json\s?|\s?```/g, '').trim();
|
// 解析 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);
|
evaluationResult.value = JSON.parse(jsonStr);
|
||||||
settings.addLog('response', { type: 'evaluation', content: evaluationResult.value });
|
|
||||||
} catch (parseErr) {
|
} catch (parseErr) {
|
||||||
console.error('Failed to parse evaluation result:', response);
|
console.error('Failed to parse evaluation result:', response);
|
||||||
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
||||||
@@ -196,17 +210,29 @@ const refineTranslation = async () => {
|
|||||||
stream: settings.enableStreaming
|
stream: settings.enableStreaming
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', { type: 'refinement', ...requestBody });
|
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 invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||||
if (!settings.enableStreaming) targetText.value = response;
|
|
||||||
|
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 (evaluationResult.value?.suggestions) {
|
if (evaluationResult.value?.suggestions) {
|
||||||
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
||||||
selectedSuggestionIds.value = [];
|
selectedSuggestionIds.value = [];
|
||||||
}
|
}
|
||||||
settings.addLog('response', 'Refinement completed');
|
|
||||||
|
if (currentHistoryId.value) {
|
||||||
|
settings.updateHistoryItem(currentHistoryId.value, {
|
||||||
|
targetText: targetText.value
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
const errorMsg = String(err);
|
const errorMsg = String(err);
|
||||||
settings.addLog('error', errorMsg);
|
settings.addLog('error', errorMsg);
|
||||||
@@ -220,6 +246,7 @@ const translate = async () => {
|
|||||||
if (!sourceText.value.trim() || isTranslating.value) return;
|
if (!sourceText.value.trim() || isTranslating.value) return;
|
||||||
|
|
||||||
isTranslating.value = true;
|
isTranslating.value = true;
|
||||||
|
currentHistoryId.value = null;
|
||||||
targetText.value = '';
|
targetText.value = '';
|
||||||
evaluationResult.value = null;
|
evaluationResult.value = null;
|
||||||
|
|
||||||
@@ -241,18 +268,27 @@ const translate = async () => {
|
|||||||
stream: settings.enableStreaming
|
stream: settings.enableStreaming
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', requestBody);
|
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 invoke<string>('translate', { apiAddress: settings.apiBaseUrl, apiKey: settings.apiKey, payload: requestBody });
|
||||||
if (!settings.enableStreaming) targetText.value = response;
|
|
||||||
settings.addLog('response', 'Translation completed');
|
|
||||||
|
|
||||||
settings.addHistory({
|
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;
|
||||||
|
targetText.value = finalTargetText;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentHistoryId.value = settings.addHistory({
|
||||||
sourceLang: { ...sourceLang.value },
|
sourceLang: { ...sourceLang.value },
|
||||||
targetLang: { ...targetLang.value },
|
targetLang: { ...targetLang.value },
|
||||||
sourceText: sourceText.value,
|
sourceText: sourceText.value,
|
||||||
targetText: settings.enableStreaming ? targetText.value : response,
|
targetText: finalTargetText,
|
||||||
context: context.value,
|
context: context.value,
|
||||||
speakerIdentity: settings.speakerIdentity,
|
speakerIdentity: settings.speakerIdentity,
|
||||||
toneRegister: settings.toneRegister,
|
toneRegister: settings.toneRegister,
|
||||||
|
|||||||
@@ -127,6 +127,113 @@ export interface HistoryItem {
|
|||||||
modelName: 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; // 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}
|
||||||
|
|
||||||
|
[Current Task]
|
||||||
|
Translate the incoming text from {FROM_LANG} to {TO_LANG}.
|
||||||
|
|
||||||
|
[Constraints]
|
||||||
|
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
|
||||||
|
2. Tone & Register:
|
||||||
|
- If translating for 'Me', strictly use the tone: {MY_TONE}.
|
||||||
|
- If translating for 'Partner', auto-detect and preserve their original tone/emotion.
|
||||||
|
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese".
|
||||||
|
4. Strictly avoid over-translation: Do not add extra information not present in the source text.
|
||||||
|
5. Output ONLY the translated text, no explanations.`;
|
||||||
|
|
||||||
|
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role
|
||||||
|
You are an expert Conversation Auditor. Your task is to evaluate if the [Current Translation] accurately reflects the [Source Text] within the specific flow of the [Conversation History].
|
||||||
|
|
||||||
|
# Context Info
|
||||||
|
- Me: {ME_NAME} ({ME_GENDER}, {ME_LANG})
|
||||||
|
- Partner: {PART_NAME} ({PART_GENDER}, {PART_LANG})
|
||||||
|
- Target Tone: {TARGET_TONE}
|
||||||
|
|
||||||
|
[Conversation History]
|
||||||
|
{HISTORY_BLOCK}
|
||||||
|
|
||||||
|
# Audit Priorities
|
||||||
|
1. **Contextual Accuracy**: Do pronouns (it, that, etc.) correctly point to objects/topics mentioned in the [Conversation History]?
|
||||||
|
2. **Relational Tone**: Does the translation match the [Target Tone]? (e.g., if set to 'Polite', is it too casual?)
|
||||||
|
3. **Consistency**: Are names, terms, or previously established facts handled consistently?
|
||||||
|
4. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment?
|
||||||
|
|
||||||
|
# Instructions
|
||||||
|
1. Analyze the [Source Text] and [Current Translation] against the history.
|
||||||
|
2. Scoring: 0-100.
|
||||||
|
3. Suggestions: Provide actionable improvements.
|
||||||
|
4. **Severity Level**: For each suggestion, assign an "importance" score (0-100).
|
||||||
|
- **80-100 (Critical)**: Misunderstanding meaning, wrong pronoun reference, or offensive tone.
|
||||||
|
- **40-79 (Moderate)**: Unnatural phrasing, minor tone mismatch.
|
||||||
|
- **0-39 (Minor)**: Polishing, stylistic preferences.
|
||||||
|
|
||||||
|
# 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 = `You are a professional conversation editor. Refine the [Current Translation] based on the [Audit Suggestions] and [Conversation History].
|
||||||
|
|
||||||
|
# Context Info
|
||||||
|
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}.
|
||||||
|
- Role B (Partner): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
|
||||||
|
- Target Tone: {TARGET_TONE}
|
||||||
|
|
||||||
|
[Conversation History]
|
||||||
|
{HISTORY_BLOCK}
|
||||||
|
|
||||||
|
[Current Translation]
|
||||||
|
{CURRENT_TRANSLATION}
|
||||||
|
|
||||||
|
[Audit Suggestions]
|
||||||
|
{SUGGESTIONS}
|
||||||
|
|
||||||
|
# Task
|
||||||
|
Produce a new, refined version of the translation that addresses the suggestions while remaining naturally integrated into the conversation flow.
|
||||||
|
|
||||||
|
# Constraints
|
||||||
|
1. Maintain semantic identity with the [Source Text].
|
||||||
|
2. Strictly follow the {TARGET_TONE}.
|
||||||
|
3. Output ONLY the refined translation text. No explanations.`;
|
||||||
|
|
||||||
export const useSettingsStore = defineStore('settings', () => {
|
export const useSettingsStore = defineStore('settings', () => {
|
||||||
const isDark = useLocalStorage('is-dark', false);
|
const isDark = useLocalStorage('is-dark', false);
|
||||||
const apiBaseUrl = useLocalStorage('api-base-url', 'http://localhost:11434/v1');
|
const apiBaseUrl = useLocalStorage('api-base-url', 'http://localhost:11434/v1');
|
||||||
@@ -159,10 +266,14 @@ 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 }[]>([]);
|
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any; curl?: string }[]>([]);
|
||||||
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
||||||
|
|
||||||
const addLog = (type: 'request' | 'response' | 'error', content: any) => {
|
// 对话模式状态
|
||||||
|
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 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 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')}`;
|
||||||
|
|
||||||
@@ -170,7 +281,8 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
timestamp,
|
timestamp,
|
||||||
type,
|
type,
|
||||||
content
|
content,
|
||||||
|
curl
|
||||||
});
|
});
|
||||||
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
||||||
};
|
};
|
||||||
@@ -178,10 +290,11 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
|
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
|
||||||
const now = new Date();
|
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 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({
|
history.value.unshift({
|
||||||
...item,
|
...item,
|
||||||
id: crypto.randomUUID(),
|
id,
|
||||||
timestamp
|
timestamp
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -189,6 +302,81 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
if (history.value.length > 100) {
|
if (history.value.length > 100) {
|
||||||
history.value = history.value.slice(0, 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 {
|
||||||
@@ -209,7 +397,14 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
toneRegister,
|
toneRegister,
|
||||||
logs,
|
logs,
|
||||||
history,
|
history,
|
||||||
|
chatSessions,
|
||||||
|
activeSessionId,
|
||||||
addLog,
|
addLog,
|
||||||
addHistory
|
addHistory,
|
||||||
|
updateHistoryItem,
|
||||||
|
createSession,
|
||||||
|
deleteSession,
|
||||||
|
addMessageToSession,
|
||||||
|
updateChatMessage
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user