feat: 前后端分离架构 — FastAPI SSE后端 + Vue 3前端

将单体 Streamlit 应用拆分为三层架构:
- api_server.py: FastAPI SSE 流式后端 (端口 8000)
- frontend/: Vue 3 + Vite + Pinia 聊天前端 (端口 5173)
- agent/graph.py: 新增 node_start 回调支持
- 更新启动脚本为三服务模式

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-21 20:04:27 +08:00
parent 2befd44430
commit 74f3f03d2c
29 changed files with 3668 additions and 72 deletions
+173
View File
@@ -0,0 +1,173 @@
<script setup lang="ts">
import { watch, nextTick, ref } from 'vue'
import { useChatStore } from './stores/chat'
import { useSessionStore } from './stores/session'
import { api } from './api/client'
import Sidebar from './components/Sidebar.vue'
import ChatMessages from './components/ChatMessages.vue'
import StreamingMessage from './components/StreamingMessage.vue'
import NodeProgress from './components/NodeProgress.vue'
import SummaryCard from './components/SummaryCard.vue'
import UnifiedInput from './components/UnifiedInput.vue'
const chat = useChatStore()
const session = useSessionStore()
const chatContainer = ref<HTMLElement | null>(null)
async function scrollToBottom() {
await nextTick()
if (chatContainer.value) {
chatContainer.value.scrollTop = chatContainer.value.scrollHeight
}
}
watch(
() => [chat.messages.length, chat.streamText],
() => scrollToBottom(),
{ flush: 'post' }
)
async function handleSend(text: string, files: File[]) {
if (!session.currentId) {
const sid = await session.createSession()
await session.switchSession(sid)
}
// Upload files first
const remoteIds: string[] = []
for (const f of files) {
try {
const info = await api.uploadFile(f, session.currentId)
remoteIds.push(info.file_id)
} catch (e) {
console.error('文件上传失败:', e)
chat.setError('文件上传失败')
return
}
}
chat.addMessage({ role: 'user', content: text || '[附加文件]' })
scrollToBottom()
chat.startStreaming()
try {
await api.chat(session.currentId, text, remoteIds, {
onNodeStart(data) {
chat.addNode(data)
},
onNodeComplete(data) {
chat.completeNode(data)
},
onStreamToken(data) {
chat.appendStreamToken(data.text)
scrollToBottom()
},
onAgentComplete(data) {
chat.finishStreaming({
intent: data.intent,
status: data.status,
jrxml_length: data.jrxml_length,
error_msg: data.error_msg,
natural_explanation: data.natural_explanation,
retry_count: data.retry_count,
ocr_extraction_result: data.ocr_extraction_result,
})
const streamContent = chat.streamText
if (data.status === 'pass') {
if (streamContent) {
chat.addMessage({ role: 'assistant', content: streamContent, type: 'jrxml' })
}
chat.addMessage({ role: 'assistant', content: 'JRXML 生成成功!可从侧边栏下载。', type: 'success' })
} else if (data.status && data.status !== 'pass') {
chat.addMessage({
role: 'assistant',
content: `经过 ${data.retry_count} 次重试后失败。\n\n错误: ${data.error_msg}${data.natural_explanation ? '\n\n原因: ' + data.natural_explanation : ''}`,
type: 'error',
})
} else if (data.intent === 'consult_question') {
if (streamContent) {
chat.addMessage({ role: 'assistant', content: streamContent, type: 'consult' })
}
} else {
if (streamContent) {
chat.addMessage({ role: 'assistant', content: streamContent, type: 'jrxml' })
}
}
// Refresh session sidebar data after a short delay
setTimeout(() => session.refreshFromState({}), 500)
},
onAgentError(data) {
chat.setError(data.error)
chat.addMessage({ role: 'assistant', content: `执行异常: ${data.error}`, type: 'error' })
},
})
} catch (e: any) {
chat.setError(e.message || '网络请求失败')
chat.addMessage({ role: 'assistant', content: `请求失败: ${e.message}`, type: 'error' })
}
}
</script>
<template>
<div class="app-layout">
<Sidebar />
<main class="main-area">
<div class="chat-container" ref="chatContainer">
<ChatMessages />
<StreamingMessage />
<NodeProgress />
<SummaryCard />
</div>
<UnifiedInput
:disabled="chat.streaming"
@send="handleSend"
/>
</main>
</div>
</template>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #11111b;
color: #cdd6f4;
}
#app {
width: 100vw;
height: 100vh;
}
.app-layout {
display: flex;
width: 100%;
height: 100%;
}
.main-area {
flex: 1;
display: flex;
flex-direction: column;
height: 100vh;
min-width: 0;
}
.chat-container {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
}
</style>
+145
View File
@@ -0,0 +1,145 @@
/** JSON fetch wrapper + SSE streaming helper. */
const BASE = '/api'
export interface SessionSummary {
session_id: string
session_name: string
created_at: string
updated_at: string
}
export interface SessionData extends SessionSummary {
agent_state: Record<string, any>
}
export interface FileInfo {
file_id: string
filename: string
content_type: string
size: number
}
export interface AgentCompleteData {
reason: string
intent: string
status: string
jrxml_length: number
error_msg: string
natural_explanation: string
retry_count: number
ocr_extraction_result: any
}
export interface SSECallbacks {
onNodeStart?: (data: { node: string; label: string }) => void
onNodeComplete?: (data: { node: string; label: string; detail: string }) => void
onStreamToken?: (data: { text: string; type: string }) => void
onAgentComplete?: (data: AgentCompleteData) => void
onAgentError?: (data: { error: string; traceback?: string }) => void
}
export const api = {
// ── Health ──
async health() {
const r = await fetch(`${BASE}/health`)
return r.json()
},
async config() {
const r = await fetch(`${BASE}/config`)
return r.json()
},
// ── Sessions ──
async createSession(): Promise<SessionSummary> {
const r = await fetch(`${BASE}/sessions`, { method: 'POST' })
return r.json()
},
async listSessions(): Promise<SessionSummary[]> {
const r = await fetch(`${BASE}/sessions`)
const data = await r.json()
return data.sessions
},
async getSession(sessionId: string): Promise<SessionData> {
const r = await fetch(`${BASE}/sessions/${sessionId}`)
if (!r.ok) throw new Error('会话不存在')
return r.json()
},
async deleteSession(sessionId: string): Promise<void> {
await fetch(`${BASE}/sessions/${sessionId}`, { method: 'DELETE' })
},
// ── Upload ──
async uploadFile(file: File, sessionId: string): Promise<FileInfo> {
const form = new FormData()
form.append('file', file)
const r = await fetch(`${BASE}/upload?session_id=${encodeURIComponent(sessionId)}`, {
method: 'POST',
body: form,
})
if (!r.ok) throw new Error('上传失败')
return r.json()
},
// ── Chat (SSE) ──
async chat(
sessionId: string,
text: string,
fileIds: string[],
callbacks: SSECallbacks,
): Promise<void> {
const r = await fetch(`${BASE}/sessions/${sessionId}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, file_ids: fileIds }),
})
if (!r.ok) {
const err = await r.json().catch(() => ({ detail: r.statusText }))
throw new Error(err.detail || '请求失败')
}
const reader = r.body!.getReader()
const decoder = new TextDecoder()
let buffer = ''
let currentEvent = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('event: ')) {
currentEvent = line.slice(7).trim()
} else if (line.startsWith('data: ')) {
const payload = JSON.parse(line.slice(6))
switch (currentEvent) {
case 'node_start':
callbacks.onNodeStart?.(payload)
break
case 'node_complete':
callbacks.onNodeComplete?.(payload)
break
case 'stream_token':
callbacks.onStreamToken?.(payload)
break
case 'agent_complete':
callbacks.onAgentComplete?.(payload)
break
case 'agent_error':
callbacks.onAgentError?.(payload)
break
}
}
}
}
},
}
+146
View File
@@ -0,0 +1,146 @@
<script setup lang="ts">
import { useChatStore, type Message } from '../stores/chat'
import { formatTime } from '../utils/format'
const chat = useChatStore()
function renderContent(msg: Message): { text: string; isXml: boolean } {
if (msg.type === 'jrxml') {
return { text: msg.content, isXml: true }
}
return { text: msg.content, isXml: false }
}
</script>
<template>
<div class="chat-messages" ref="scrollRef">
<div v-if="chat.messages.length === 0 && !chat.streaming" class="empty-state">
<div class="empty-icon">📋</div>
<p>开始对话 描述您需要的报表</p>
</div>
<div
v-for="msg in chat.messages"
:key="msg.id"
class="message"
:class="`msg-${msg.role}`"
>
<div class="msg-header">
<span class="msg-role">{{ msg.role === 'user' ? '您' : 'AI' }}</span>
<span class="msg-time">{{ formatTime(msg.timestamp) }}</span>
</div>
<div class="msg-body">
<template v-if="renderContent(msg).isXml">
<pre class="code-block">{{ renderContent(msg).text }}</pre>
</template>
<template v-else>
<div class="markdown-body" v-text="renderContent(msg).text"></div>
</template>
</div>
<div v-if="msg.type === 'error'" class="msg-tag error-tag">错误</div>
<div v-if="msg.type === 'success'" class="msg-tag success-tag">成功</div>
</div>
</div>
</template>
<style scoped>
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 20px 24px;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: #6c7086;
}
.empty-icon {
font-size: 48px;
margin-bottom: 12px;
}
.empty-state p {
font-size: 14px;
}
.message {
margin-bottom: 16px;
padding: 12px 16px;
border-radius: 12px;
max-width: 85%;
}
.msg-user {
margin-left: auto;
background: #313244;
}
.msg-assistant {
margin-right: auto;
background: #1e1e2e;
border: 1px solid #313244;
}
.msg-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.msg-role {
font-size: 12px;
font-weight: 600;
color: #cba6f7;
}
.msg-time {
font-size: 11px;
color: #6c7086;
}
.msg-body {
font-size: 14px;
line-height: 1.6;
color: #cdd6f4;
word-break: break-word;
}
.code-block {
background: #11111b;
padding: 12px;
border-radius: 8px;
font-size: 12px;
overflow-x: auto;
white-space: pre;
color: #a6e3a1;
}
.markdown-body {
white-space: pre-wrap;
}
.msg-tag {
display: inline-block;
margin-top: 6px;
padding: 2px 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
}
.error-tag {
background: #f38ba8;
color: #1e1e2e;
}
.success-tag {
background: #a6e3a1;
color: #1e1e2e;
}
</style>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { useChatStore } from '../stores/chat'
import { computed } from 'vue'
const chat = useChatStore()
const visibleNodes = computed(() =>
chat.nodes.filter(n => n.node !== 'load_session'
&& n.node !== 'process_input'
&& n.node !== 'manage_context'
&& n.node !== 'save_state_snapshot'
&& n.node !== 'save_session')
)
const currentLabel = computed(() => {
const running = visibleNodes.value.find(n => n.status === 'running')
return running ? running.label : null
})
</script>
<template>
<div v-if="chat.streaming && visibleNodes.length > 0" class="node-progress">
<div class="progress-label">
{{ currentLabel || '处理中...' }}
</div>
<div class="progress-dots">
<span
v-for="n in visibleNodes"
:key="n.node"
class="dot"
:class="{ done: n.status === 'done', active: n.status === 'running' }"
></span>
</div>
<div class="progress-detail" v-if="visibleNodes[visibleNodes.length - 1]?.detail">
{{ visibleNodes[visibleNodes.length - 1].detail }}
</div>
</div>
</template>
<style scoped>
.node-progress {
padding: 8px 16px;
margin: 0 24px 8px;
background: #181825;
border-radius: 8px;
border: 1px solid #313244;
}
.progress-label {
font-size: 12px;
font-weight: 600;
color: #89b4fa;
margin-bottom: 4px;
}
.progress-dots {
display: flex;
gap: 4px;
margin-bottom: 4px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #45475a;
}
.dot.active {
background: #f9e2af;
animation: pulse 1s infinite;
}
.dot.done {
background: #a6e3a1;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.progress-detail {
font-size: 11px;
color: #6c7086;
}
</style>
+215
View File
@@ -0,0 +1,215 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useSessionStore } from '../stores/session'
import { useChatStore } from '../stores/chat'
const session = useSessionStore()
const chat = useChatStore()
onMounted(() => {
session.loadSessions()
})
async function handleNew() {
const sid = await session.createSession()
await session.switchSession(sid)
chat.reset()
}
async function handleSwitch(sid: string) {
await session.switchSession(sid)
chat.reset()
}
async function handleDelete() {
if (!session.currentId) return
if (!confirm('确定要删除当前会话吗?')) return
await session.deleteCurrent()
chat.reset()
}
</script>
<template>
<aside class="sidebar">
<div class="sidebar-header">
<h2>JRXML Agent</h2>
</div>
<div class="sidebar-section">
<div class="section-title">
<span>会话列表</span>
<button class="btn-icon" @click="handleNew" title="新建会话">+</button>
</div>
<div class="session-list">
<div
v-for="s in session.sortedSessions"
:key="s.session_id"
class="session-item"
:class="{ active: s.session_id === session.currentId }"
@click="handleSwitch(s.session_id)"
>
<span class="session-name">{{ s.session_name }}</span>
<span class="session-time">{{ s.updated_at?.slice(0, 10) }}</span>
</div>
</div>
<button
v-if="session.currentId"
class="btn-delete"
@click="handleDelete"
>
删除当前会话
</button>
</div>
<div class="sidebar-section" v-if="session.currentJrxml">
<div class="section-title">下载</div>
<a
:href="`/api/sessions/${session.currentId}/download/latest`"
class="btn-download"
download
>
下载最新 JRXML
</a>
</div>
<div class="sidebar-footer">
<span>v5.0</span>
</div>
</aside>
</template>
<style scoped>
.sidebar {
width: 260px;
height: 100vh;
background: #1e1e2e;
color: #cdd6f4;
display: flex;
flex-direction: column;
border-right: 1px solid #313244;
flex-shrink: 0;
}
.sidebar-header {
padding: 20px 16px 12px;
border-bottom: 1px solid #313244;
}
.sidebar-header h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #cba6f7;
}
.sidebar-section {
padding: 12px 0;
border-bottom: 1px solid #313244;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px 8px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
color: #a6adc8;
letter-spacing: 0.5px;
}
.btn-icon {
width: 24px;
height: 24px;
border: none;
background: #313244;
color: #cdd6f4;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
line-height: 1;
}
.btn-icon:hover {
background: #45475a;
}
.session-list {
max-height: 300px;
overflow-y: auto;
}
.session-item {
padding: 8px 16px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
transition: background 0.15s;
}
.session-item:hover {
background: #313244;
}
.session-item.active {
background: #45475a;
border-left: 3px solid #cba6f7;
padding-left: 13px;
}
.session-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 150px;
}
.session-time {
font-size: 11px;
color: #6c7086;
flex-shrink: 0;
}
.btn-delete {
display: block;
width: calc(100% - 32px);
margin: 8px 16px 0;
padding: 6px 12px;
border: 1px solid #f38ba8;
background: transparent;
color: #f38ba8;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
}
.btn-delete:hover {
background: #f38ba8;
color: #1e1e2e;
}
.btn-download {
display: block;
padding: 8px 16px;
color: #a6e3a1;
text-decoration: none;
font-size: 13px;
}
.btn-download:hover {
background: #313244;
}
.sidebar-footer {
margin-top: auto;
padding: 12px 16px;
font-size: 11px;
color: #6c7086;
border-top: 1px solid #313244;
}
</style>
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { useChatStore } from '../stores/chat'
const chat = useChatStore()
</script>
<template>
<div v-if="chat.streaming" class="streaming-message">
<div class="stream-header">
<span class="stream-label">AI 正在生成...</span>
</div>
<pre class="stream-code" v-if="chat.streamText">{{ chat.streamText }}</pre>
<div v-else class="stream-waiting">
<span class="dot-pulse"></span>
</div>
</div>
</template>
<style scoped>
.streaming-message {
margin-bottom: 16px;
padding: 12px 16px;
border-radius: 12px;
background: #1e1e2e;
border: 1px solid #45475a;
max-width: 85%;
}
.stream-header {
margin-bottom: 8px;
}
.stream-label {
font-size: 12px;
font-weight: 600;
color: #f9e2af;
}
.stream-code {
background: #11111b;
padding: 12px;
border-radius: 8px;
font-size: 12px;
overflow-x: auto;
white-space: pre-wrap;
color: #a6e3a1;
max-height: 400px;
overflow-y: auto;
}
.stream-waiting {
padding: 20px 0;
text-align: center;
}
.dot-pulse::after {
content: '...';
animation: dots 1.5s steps(4, end) infinite;
}
@keyframes dots {
0%, 20% { content: '.'; }
40% { content: '..'; }
60%, 100% { content: '...'; }
}
</style>
+109
View File
@@ -0,0 +1,109 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useSessionStore } from '../stores/session'
import { useChatStore } from '../stores/chat'
const session = useSessionStore()
const chat = useChatStore()
const visible = computed(() =>
!chat.streaming && chat.summary.status !== ''
)
function downloadLatest() {
if (session.currentId) {
window.open(`/api/sessions/${session.currentId}/download/latest`, '_blank')
}
}
</script>
<template>
<div v-if="visible" class="summary-card">
<div v-if="chat.summary.status === 'pass'" class="card card-success">
<div class="card-title">JRXML 生成成功</div>
<div class="card-text">生成 {{ chat.summary.jrxml_length }} 字符</div>
<button class="card-btn" @click="downloadLatest">下载 JRXML</button>
</div>
<div v-else class="card card-error">
<div class="card-title">
经过 {{ chat.summary.retry_count }} 次重试后仍失败
</div>
<div class="card-text">{{ chat.summary.error_msg }}</div>
<div v-if="chat.summary.natural_explanation" class="card-reason">
{{ chat.summary.natural_explanation }}
</div>
<div class="card-hint">请继续描述修改需求系统会自动加载失败上下文</div>
</div>
</div>
</template>
<style scoped>
.summary-card {
margin: 12px 24px;
}
.card {
padding: 12px 16px;
border-radius: 10px;
border: 1px solid;
}
.card-success {
background: #1e1e2e;
border-color: #a6e3a1;
}
.card-error {
background: #1e1e2e;
border-color: #f38ba8;
}
.card-title {
font-size: 14px;
font-weight: 600;
margin-bottom: 8px;
}
.card-success .card-title {
color: #a6e3a1;
}
.card-error .card-title {
color: #f38ba8;
}
.card-text {
font-size: 13px;
color: #cdd6f4;
margin-bottom: 4px;
}
.card-reason {
font-size: 12px;
color: #a6adc8;
margin-bottom: 4px;
}
.card-hint {
font-size: 11px;
color: #6c7086;
margin-top: 8px;
}
.card-btn {
margin-top: 8px;
padding: 6px 16px;
background: #a6e3a1;
color: #1e1e2e;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
font-weight: 600;
}
.card-btn:hover {
background: #94e2d5;
}
</style>
+274
View File
@@ -0,0 +1,274 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { fileIcon } from '../utils/format'
const props = defineProps<{
disabled: boolean
}>()
const emit = defineEmits<{
send: [text: string, files: File[]]
}>()
const text = ref('')
const attachedFiles = ref<{ id: string; name: string; file: File }[]>([])
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const fileInputRef = ref<HTMLInputElement | null>(null)
const canSend = computed(() =>
!props.disabled && (text.value.trim() || attachedFiles.value.length > 0)
)
function triggerFileInput() {
fileInputRef.value?.click()
}
function handleFileSelect(e: Event) {
const input = e.target as HTMLInputElement
if (input.files) {
for (const f of input.files) {
attachedFiles.value.push({ id: crypto.randomUUID(), name: f.name, file: f })
}
}
input.value = ''
}
function removeFile(id: string) {
attachedFiles.value = attachedFiles.value.filter(f => f.id !== id)
}
function handleSend() {
if (!canSend.value) return
emit('send', text.value, attachedFiles.value.map(f => f.file))
text.value = ''
attachedFiles.value = []
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSend()
}
}
// Auto-resize textarea
function autoResize() {
const el = textareaRef.value
if (el) {
el.style.height = 'auto'
el.style.height = Math.min(el.scrollHeight, 120) + 'px'
}
}
// Drag & drop
function handleDrop(e: DragEvent) {
e.preventDefault()
if (e.dataTransfer?.files) {
for (const f of e.dataTransfer.files) {
attachedFiles.value.push({ id: crypto.randomUUID(), name: f.name, file: f })
}
}
}
function handleDragover(e: DragEvent) {
e.preventDefault()
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'copy'
}
}
// Paste support
function handlePaste(e: ClipboardEvent) {
const items = e.clipboardData?.items
if (!items) return
for (const item of items) {
if (item.kind === 'file') {
const f = item.getAsFile()
if (f) {
e.preventDefault()
attachedFiles.value.push({ id: crypto.randomUUID(), name: f.name || 'clipboard.png', file: f })
}
}
}
}
</script>
<template>
<div class="unified-input" @drop="handleDrop" @dragover="handleDragover">
<!-- File chips -->
<div v-if="attachedFiles.length > 0" class="file-chips">
<div v-for="f in attachedFiles" :key="f.id" class="chip">
<span class="chip-icon">{{ fileIcon(f.name) }}</span>
<span class="chip-name">{{ f.name }}</span>
<button class="chip-remove" @click="removeFile(f.id)">&times;</button>
</div>
</div>
<!-- Input row -->
<div class="input-row">
<button class="attach-btn" @click="triggerFileInput" title="附加文件">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/>
</svg>
</button>
<textarea
ref="textareaRef"
v-model="text"
class="text-input"
placeholder="描述您的报表需求... (Enter 发送, Shift+Enter 换行)"
:disabled="disabled"
@keydown="handleKeydown"
@input="autoResize"
@paste="handlePaste"
rows="1"
></textarea>
<button
class="send-btn"
:disabled="!canSend"
@click="handleSend"
title="发送"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
</svg>
</button>
</div>
<input
ref="fileInputRef"
type="file"
multiple
accept="image/*,.pdf,.docx,.doc,.xlsx,.xls,.txt,.csv"
style="display:none"
@change="handleFileSelect"
/>
</div>
</template>
<style scoped>
.unified-input {
border: 1px solid #45475a;
border-radius: 12px;
background: #1e1e2e;
margin: 0 24px 16px;
padding: 8px 12px;
transition: border-color 0.2s;
}
.unified-input:focus-within {
border-color: #cba6f7;
}
.file-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 8px;
}
.chip {
display: flex;
align-items: center;
gap: 4px;
background: #313244;
border-radius: 6px;
padding: 2px 8px;
font-size: 12px;
}
.chip-icon {
font-size: 14px;
}
.chip-name {
color: #cdd6f4;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chip-remove {
background: none;
border: none;
color: #6c7086;
cursor: pointer;
font-size: 16px;
padding: 0;
line-height: 1;
}
.chip-remove:hover {
color: #f38ba8;
}
.input-row {
display: flex;
align-items: flex-end;
gap: 8px;
}
.attach-btn {
flex-shrink: 0;
width: 36px;
height: 36px;
border: none;
background: #313244;
color: #a6adc8;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.attach-btn:hover {
background: #45475a;
color: #cdd6f4;
}
.text-input {
flex: 1;
background: transparent;
border: none;
color: #cdd6f4;
font-size: 14px;
font-family: inherit;
resize: none;
outline: none;
line-height: 1.5;
padding: 8px 0;
min-height: 36px;
max-height: 120px;
}
.text-input::placeholder {
color: #6c7086;
}
.send-btn {
flex-shrink: 0;
width: 36px;
height: 36px;
border: none;
background: #cba6f7;
color: #1e1e2e;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.send-btn:hover:not(:disabled) {
background: #b4befe;
}
.send-btn:disabled {
background: #45475a;
color: #6c7086;
cursor: not-allowed;
}
</style>
+7
View File
@@ -0,0 +1,7 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
+122
View File
@@ -0,0 +1,122 @@
/** Pinia store — chat messages + streaming state. */
import { defineStore } from 'pinia'
import { ref } from 'vue'
export interface Message {
id: string
role: 'user' | 'assistant'
content: string
type?: 'text' | 'jrxml' | 'error' | 'success' | 'consult'
timestamp: string
}
export interface NodeProgress {
node: string
label: string
detail?: string
status: 'running' | 'done'
}
export interface AgentSummary {
intent: string
status: string
jrxml_length: number
error_msg: string
natural_explanation: string
retry_count: number
}
export const useChatStore = defineStore('chat', () => {
const messages = ref<Message[]>([])
const streaming = ref(false)
const streamText = ref('')
const nodes = ref<NodeProgress[]>([])
const error = ref<string>('')
const ocrResult = ref<any>(null)
const summary = ref<AgentSummary>({
intent: '', status: '', jrxml_length: 0,
error_msg: '', natural_explanation: '', retry_count: 0,
})
function addMessage(msg: Omit<Message, 'id' | 'timestamp'>) {
messages.value.push({
...msg,
id: crypto.randomUUID(),
timestamp: new Date().toISOString(),
})
}
function startStreaming() {
streaming.value = true
streamText.value = ''
nodes.value = []
error.value = ''
summary.value = {
intent: '', status: '', jrxml_length: 0,
error_msg: '', natural_explanation: '', retry_count: 0,
}
}
function appendStreamToken(text: string) {
streamText.value += text
}
function addNode(node: { node: string; label: string }) {
nodes.value.push({ ...node, status: 'running' })
}
function completeNode(node: { node: string; label: string; detail: string }) {
const existing = nodes.value.find(n => n.node === node.node)
if (existing) {
existing.status = 'done'
existing.detail = node.detail
}
}
function finishStreaming(data?: {
intent?: string; status?: string; jrxml_length?: number
error_msg?: string; natural_explanation?: string; retry_count?: number
ocr_extraction_result?: any
}) {
streaming.value = false
nodes.value.forEach(n => { n.status = 'done' })
if (data) {
summary.value = {
intent: data.intent || '',
status: data.status || '',
jrxml_length: data.jrxml_length || 0,
error_msg: data.error_msg || '',
natural_explanation: data.natural_explanation || '',
retry_count: data.retry_count || 0,
}
if (data.ocr_extraction_result) {
ocrResult.value = data.ocr_extraction_result
}
}
}
function setError(err: string) {
error.value = err
streaming.value = false
}
function reset() {
messages.value = []
streamText.value = ''
nodes.value = []
error.value = ''
streaming.value = false
ocrResult.value = null
summary.value = {
intent: '', status: '', jrxml_length: 0,
error_msg: '', natural_explanation: '', retry_count: 0,
}
}
return {
messages, streaming, streamText, nodes, error, ocrResult, summary,
addMessage, startStreaming, appendStreamToken, addNode, completeNode,
finishStreaming, setError, reset,
}
})
+71
View File
@@ -0,0 +1,71 @@
/** Pinia store — session management. */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api, type SessionSummary } from '../api/client'
export const useSessionStore = defineStore('session', () => {
const sessions = ref<SessionSummary[]>([])
const currentId = ref<string>('')
const currentName = ref<string>('')
const versions = ref<any[]>([])
const currentJrxml = ref<string>('')
const sortedSessions = computed(() =>
[...sessions.value].sort((a, b) =>
new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
)
)
const currentSession = computed(() =>
sessions.value.find(s => s.session_id === currentId.value)
)
async function loadSessions() {
try {
sessions.value = await api.listSessions()
} catch (e) {
console.error('加载会话列表失败:', e)
}
}
async function createSession() {
const s = await api.createSession()
sessions.value.unshift(s)
return s.session_id
}
async function switchSession(sessionId: string) {
currentId.value = sessionId
try {
const data = await api.getSession(sessionId)
currentName.value = data.session_name
const state = data.agent_state
currentJrxml.value = state.current_jrxml || ''
versions.value = state.jrxml_versions || []
} catch (e) {
console.error('加载会话失败:', e)
}
}
async function deleteCurrent() {
if (!currentId.value) return
await api.deleteSession(currentId.value)
sessions.value = sessions.value.filter(s => s.session_id !== currentId.value)
currentId.value = ''
currentName.value = ''
currentJrxml.value = ''
versions.value = []
}
function refreshFromState(agentState: Record<string, any>) {
currentJrxml.value = agentState.current_jrxml || currentJrxml.value
versions.value = agentState.jrxml_versions || versions.value
}
return {
sessions, currentId, currentName, versions, currentJrxml,
sortedSessions, currentSession,
loadSessions, createSession, switchSession, deleteCurrent, refreshFromState,
}
})
+24
View File
@@ -0,0 +1,24 @@
/** Date formatting and text utilities. */
export function formatTime(iso: string): string {
if (!iso) return ''
const d = new Date(iso)
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
export function truncate(str: string, max: number): string {
if (!str) return ''
return str.length > max ? str.slice(0, max) + '...' : str
}
export function fileIcon(filename: string): string {
const ext = filename.split('.').pop()?.toLowerCase() || ''
const map: Record<string, string> = {
png: '🖼', jpg: '🖼', jpeg: '🖼', bmp: '🖼', webp: '🖼',
pdf: '📄', docx: '📝', doc: '📝',
xlsx: '📊', xls: '📊',
txt: '📃', csv: '📃',
}
return map[ext] || '📎'
}