support chat mode

This commit is contained in:
Julian Freeman
2026-04-03 18:36:12 -04:00
parent ce4a42eec2
commit 41494ebad0
3 changed files with 691 additions and 3 deletions

View File

@@ -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'" />

View File

@@ -0,0 +1,558 @@
<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue';
import {
Plus, Search, Trash2, Send, User, Type, ChevronDown, Check,
MessageSquare, Loader2, Copy,
X, Sparkles
} from 'lucide-vue-next';
import { useSettingsStore, LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS, CONVERSATION_SYSTEM_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'
});
// Current active session
const activeSession = computed(() =>
settings.chatSessions.find(s => s.id === settings.activeSessionId) || null
);
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;
};
const scrollToBottom = async () => {
await nextTick();
if (messageContainer.value) {
messageContainer.value.scrollTo({
top: messageContainer.value.scrollHeight,
behavior: 'smooth'
});
}
};
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 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
};
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)}'`;
};
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 handleGlobalClick = () => {
myToneDropdownOpen.value = false;
};
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>
<span class="text-[10px] text-slate-400">正在与你说 {{ activeSession.partner.language.displayName }} 的同事对话</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) -->
<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-12' : '-right-12'
)">
<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>
</div>
</div>
</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.5 text-[10px] font-bold text-slate-400 uppercase">
<User class="w-3 h-3" />
{{ activeSession.partner.name }} ({{ activeSession.partner.language.displayName }})
</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.5 text-[10px] font-bold text-slate-400 uppercase">
<User class="w-3 h-3 text-blue-500" />
{{ activeSession.me.name }} ({{ activeSession.me.language.displayName }})
</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 overflow-hidden">
<div class="p-6 border-b dark:border-slate-800 flex items-center justify-between bg-slate-50 dark:bg-slate-950">
<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>
<select v-model="newSessionMe.language" 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 appearance-none">
<option v-for="lang in LANGUAGES" :key="lang.code" :value="lang">{{ lang.displayName }}</option>
</select>
</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>
<select v-model="newSessionMe.gender" 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 appearance-none">
<option v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</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>
<select v-model="newSessionPartner.language" 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 appearance-none">
<option v-for="lang in LANGUAGES" :key="lang.code" :value="lang">{{ lang.displayName }}</option>
</select>
</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>
<select v-model="newSessionPartner.gender" 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 appearance-none">
<option v-for="opt in SPEAKER_IDENTITY_OPTIONS" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</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>

View File

@@ -127,6 +127,50 @@ 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;
}
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 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');
@@ -162,6 +206,10 @@ export const useSettingsStore = defineStore('settings', () => {
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any; curl?: string }[]>([]); 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 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 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')}`;
@@ -202,6 +250,72 @@ export const useSettingsStore = defineStore('settings', () => {
} }
}; };
// 对话模式方法
const createSession = (me: Participant, partner: Participant) => {
const id = crypto.randomUUID();
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
const newSession: ChatSession = {
id,
title: `${partner.name} 的对话`,
me,
partner,
messages: [],
lastActivity: timestamp
};
chatSessions.value.unshift(newSession);
activeSessionId.value = id;
return id;
};
const deleteSession = (id: string) => {
chatSessions.value = chatSessions.value.filter(s => s.id !== id);
if (activeSessionId.value === id) {
activeSessionId.value = chatSessions.value[0]?.id || null;
}
};
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated: string = '') => {
const session = chatSessions.value.find(s => s.id === sessionId);
if (session) {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
const newMessage: ChatMessage = {
id: crypto.randomUUID(),
sender,
original,
translated,
timestamp
};
session.messages.push(newMessage);
session.lastActivity = timestamp;
// 将活跃会话移至顶部
const index = chatSessions.value.findIndex(s => s.id === sessionId);
if (index > 0) {
const [s] = chatSessions.value.splice(index, 1);
chatSessions.value.unshift(s);
}
return newMessage.id;
}
return null;
};
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
const session = chatSessions.value.find(s => s.id === sessionId);
if (session) {
const message = session.messages.find(m => m.id === messageId);
if (message) {
Object.assign(message, updates);
}
}
};
return { return {
isDark, isDark,
apiBaseUrl, apiBaseUrl,
@@ -220,8 +334,14 @@ export const useSettingsStore = defineStore('settings', () => {
toneRegister, toneRegister,
logs, logs,
history, history,
chatSessions,
activeSessionId,
addLog, addLog,
addHistory, addHistory,
updateHistoryItem updateHistoryItem,
createSession,
deleteSession,
addMessageToSession,
updateChatMessage
}; };
}); });