feat: 对话功能,上传附件功能开发

This commit is contained in:
2026-04-13 00:25:50 +08:00
parent 8972dfe8e7
commit c1e934f2b2
6 changed files with 1491 additions and 44 deletions

View File

@@ -8,6 +8,16 @@
</div>
<div v-for="msg in messages" :key="msg.id" class="bubble-wrap" :class="msg.role">
<div class="bubble">
<!-- 用户消息中的文件附件 -->
<div v-if="msg.files && msg.files.length > 0" class="msg-files">
<div v-for="f in msg.files" :key="f.id" class="msg-file-item">
<img v-if="f.mime && f.mime.startsWith('image/')" :src="f.url" class="msg-file-img" :alt="f.filename" />
<div v-else class="msg-file-doc">
<el-icon :size="16"><Document /></el-icon>
<span class="msg-file-name">{{ f.filename }}</span>
</div>
</div>
</div>
<!-- 推理过程仅助手消息显示 -->
<div v-if="msg.parts?.filter((p) => p.type === 'reasoning').length > 0" class="reasoning-section">
<div class="reasoning-header" @click="msg.showReasoning = !msg.showReasoning">
@@ -59,7 +69,11 @@
<div v-if="p.state?.input?.command" class="tool-command">
<span class="tool-label">$ </span><code>{{ p.state.input.command }}</code>
</div>
<div v-if="p.state?.input?.filePath" class="tool-command">
<span class="tool-label">path: </span><code>{{ p.state.input.filePath }}</code>
</div>
<pre v-if="p.state?.output" class="tool-output">{{ p.state.output }}</pre>
<div v-if="p.state?.error" class="tool-error">{{ p.state.error }}</div>
<div v-if="p.state?.time" class="tool-time">耗时 {{ p.state.time.end - p.state.time.start }} ms</div>
</div>
</div>
@@ -72,6 +86,7 @@
(p) =>
p.type !== 'text' &&
p.type !== 'reasoning' &&
p.type !== 'file' &&
p.type !== 'tool' &&
p.type !== 'question' &&
p.type !== 'step-start' &&
@@ -108,8 +123,9 @@
import { ref, computed, onMounted, onUnmounted, nextTick, watch, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ChatDotRound, ArrowRight, ArrowDown } from '@element-plus/icons-vue';
import { ChatDotRound, ArrowRight, ArrowDown, Document } from '@element-plus/icons-vue';
import { useAppStore } from '@/stores/app.js';
import { useDraftStore } from '@/stores/draft.js';
import { sseManager } from '@/http/sse.js';
import axios from 'axios';
import MarkdownRender from '@/components/MarkdownRender/index.vue';
@@ -117,12 +133,19 @@ import MarkdownRender from '@/components/MarkdownRender/index.vue';
const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const draftStore = useDraftStore();
const isSending = ref(false);
const inputText = ref('');
const messages = ref([]);
const messagesRef = ref(null);
const currentSessionId = ref(null);
const localAssistantMessageIds = new Set();
const pendingFiles = ref([]); // 待发送的文件列表
// 生成唯一 ID
function generateId() {
return 'prt_' + Date.now() + Math.random().toString(36).substr(2, 9);
}
// 是否有正在等待回答的 question
const hasActiveQuestion = computed(() => {
@@ -166,20 +189,27 @@ async function loadHistoryMessages(sessionId) {
const { info, parts } = item;
if (!info || !parts) return;
// 过滤掉 synthetic 为 true 的 part
const filteredParts = parts.filter((p) => !p.synthetic);
// 提取文本内容(用于展示)
const text = parts
const text = filteredParts
.filter((p) => p.type === 'text')
.map((part) => part.text)
.join('');
// 为每个 part 初始化响应式字段
const normalizedParts = parts.map((p) => (p.type === 'tool' ? { ...p, _expanded: true, _freeInput: p.tool === 'question' ? '' : undefined } : p));
// 提取 question 类型 part来自 question.asked 事件,历史中可能存在)
if (text || info.role === 'assistant') {
// 提取文件列表
const files = filteredParts.filter((p) => p.type === 'file');
// 为每个 part 初始化响应式字段
const normalizedParts = filteredParts.map((p) => (p.type === 'tool' ? { ...p, _expanded: true, _freeInput: p.tool === 'question' ? '' : undefined } : p));
if (text || files.length > 0 || info.role === 'assistant') {
messages.value.push({
id: info.id,
role: info.role,
text: text,
files: files,
parts: normalizedParts,
showReasoning: true, // 默认展开推理过程
});
@@ -209,17 +239,16 @@ watch(
// 等待历史消息加载完毕,避免在 send 时 messages 被清空
await loadHistoryMessages(newSessionId);
// 处理从首页带过来的初始消息
const text = route.query.text;
if (text) {
inputText.value = text;
// 清除 query 中的 text防止刷新页面时重复发送
const query = { ...route.query };
delete query.text;
router.replace({ query });
// 处理从首页带过来的初始消息(从 draft store 获取)
if (draftStore.hasDraft()) {
const draft = draftStore.takeDraft();
inputText.value = draft.text;
pendingFiles.value = draft.files;
// 触发发送逻辑
send();
if (inputText.value.trim()) {
send();
}
}
// 确保 SSE 连接已建立
@@ -379,8 +408,26 @@ async function send() {
isSending.value = true;
scrollToBottom();
// 构建 parts 数组
const parts = [{ id: generateId(), type: 'text', text }];
// 如果有待发送的文件,追加到 parts 中
if (pendingFiles.value.length > 0) {
pendingFiles.value.forEach((file) => {
parts.push({
id: file.id,
type: 'file',
mime: file.mime,
url: file.url,
filename: file.filename,
});
});
pendingFiles.value = [];
}
try {
await window.opencode.promptAsync(currentSessionId.value, text);
const baseUrl = window.__opencodeBaseUrl || 'http://127.0.0.1:4096';
await axios.post(`${baseUrl}/session/${currentSessionId.value}/prompt_async`, { parts });
// 发送成功后等待 SSE 事件流推送 AI 响应isSending 由 session.idle 事件重置
} catch (err) {
console.error('发送指令失败:', err);
@@ -482,6 +529,47 @@ onUnmounted(() => {
font-family: inherit;
}
/* 消息中的文件附件 */
.msg-files {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 8px;
}
.msg-file-item {
max-width: 200px;
}
.msg-file-img {
max-width: 200px;
max-height: 150px;
border-radius: 6px;
object-fit: cover;
}
.msg-file-doc {
display: flex;
align-items: center;
gap: 4px;
padding: 4px 10px;
background: rgba(255, 255, 255, 0.15);
border-radius: 6px;
font-size: 12px;
max-width: 200px;
}
.msg-file-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.bubble-wrap.assistant .msg-file-doc {
background: rgba(0, 0, 0, 0.06);
color: #303133;
}
.reasoning-section {
margin-bottom: 8px;
border-radius: 6px;
@@ -614,6 +702,18 @@ onUnmounted(() => {
text-align: right;
}
.tool-error {
margin: 4px 0 0;
padding: 6px 8px;
background: rgba(243, 139, 168, 0.12);
border-left: 3px solid #f38ba8;
border-radius: 4px;
font-size: 12px;
color: #f38ba8;
white-space: pre-wrap;
word-break: break-all;
}
.question-part {
margin-top: 8px;
}

View File

@@ -42,6 +42,26 @@
<!-- 底部输入框 -->
<div class="input-section">
<div class="input-wrapper">
<!-- 文件预览区域 -->
<div v-if="selectedFiles.length > 0" class="file-preview-area">
<div v-for="file in selectedFiles" :key="file.id" class="file-preview-item">
<!-- 图片预览 -->
<img v-if="file.mime.startsWith('image/')" :src="file.url" class="preview-img" :alt="file.filename" />
<!-- 文本文件预览 -->
<div v-else-if="file.mime.startsWith('text/')" class="file-icon-preview">
<LucideIcon name="file-text" size="32"></LucideIcon>
<span class="file-name">{{ file.filename }}</span>
</div>
<!-- 其他文件类型显示图标和文件名 -->
<div v-else class="file-icon-preview">
<LucideIcon name="file-text" size="32"></LucideIcon>
<span class="file-name">{{ file.filename }}</span>
</div>
<button class="remove-file-btn" @click="removeFile(file.id)">
<LucideIcon name="x" size="12"></LucideIcon>
</button>
</div>
</div>
<textarea
v-model="inputText"
class="input-textarea"
@@ -58,9 +78,10 @@
<span>选择工作目录</span>
</button>
<el-tooltip content="添加文件或者文件夹作为上下文" placement="top" :show-arrow="false">
<button class="toolbar-btn icon-btn">
<label class="toolbar-btn icon-btn" style="cursor: pointer">
<input type="file" multiple style="display: none" @change="handleFilesSelected" />
<LucideIcon name="paperclip" size="16"></LucideIcon>
</button>
</label>
</el-tooltip>
<el-tooltip content="使用 / 调用技能" placement="top" :show-arrow="false">
<button class="toolbar-btn icon-btn">/</button>
@@ -85,6 +106,7 @@ import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAppStore } from '@/stores/app';
import { useHistoryStore } from '@/stores/history';
import { useDraftStore } from '@/stores/draft';
import { Document, Plus, Promotion, FolderOpened, Paperclip } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import LucideIcon from '@/components/base/LucideIcon.vue';
@@ -92,9 +114,16 @@ import LucideIcon from '@/components/base/LucideIcon.vue';
const router = useRouter();
const appStore = useAppStore();
const historyStore = useHistoryStore();
const draftStore = useDraftStore();
const inputText = ref('');
const isCreating = ref(false);
const textareaRef = ref(null);
const selectedFiles = ref([]);
// 生成唯一 ID
function generateId() {
return 'prt' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
function autoResize() {
const el = textareaRef.value;
@@ -119,14 +148,17 @@ async function handleSend() {
const session = await historyStore.createSession(text);
console.log('创建会话成功:', session);
// 清空输入框
inputText.value = '';
// 将文本和文件保存到 draft store
draftStore.setDraft(text, [...selectedFiles.value]);
// 跳转到对话页面,并将消息文本带入 query
// 清空输入框和文件
inputText.value = '';
selectedFiles.value = [];
// 跳转到对话页面
router.push({
name: 'Chat',
params: { id: session.id },
query: { text: text },
});
} catch (err) {
console.error('创建会话失败:', err);
@@ -143,6 +175,47 @@ function handleKeydown(e) {
handleSend();
}
}
// 处理文件选择
function handleFilesSelected(event) {
const files = event.target.files;
if (files.length > 0) {
Array.from(files).forEach((file) => {
const reader = new FileReader();
reader.onload = (e) => {
const fileItem = {
id: generateId(),
filename: file.name,
mime: file.type || 'application/octet-stream',
url: e.target.result,
type: file,
};
// 如果是文本文件,额外读取文本内容用于预览
if (file.type.startsWith('text/')) {
const textReader = new FileReader();
textReader.onload = (te) => {
fileItem.textContent = te.target.result;
selectedFiles.value.push(fileItem);
};
textReader.readAsText(file);
} else {
selectedFiles.value.push(fileItem);
}
};
reader.readAsDataURL(file);
});
}
// 清空 input 值,允许重复选择相同文件
event.target.value = '';
}
// 移除已选择的文件
function removeFile(id) {
const index = selectedFiles.value.findIndex((f) => f.id === id);
if (index > -1) {
selectedFiles.value.splice(index, 1);
}
}
</script>
<style scoped>
@@ -287,6 +360,75 @@ function handleKeydown(e) {
color: #c0c4cc;
}
/* 文件预览区域 */
.file-preview-area {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 12px 16px 0;
max-height: 120px;
overflow-y: auto;
}
.file-preview-item {
position: relative;
width: 80px;
height: 80px;
border-radius: 8px;
overflow: hidden;
border: 1px solid #e4e7ed;
background: #f5f6f7;
}
.preview-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.file-icon-preview {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
color: #606266;
}
.file-name {
font-size: 10px;
color: #606266;
max-width: 70px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 4px;
}
.remove-file-btn {
position: absolute;
top: 4px;
right: 4px;
width: 18px;
height: 18px;
border: none;
border-radius: 50%;
background: rgba(0, 0, 0, 0.5);
color: #fff;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
transition: background 0.2s ease;
}
.remove-file-btn:hover {
background: rgba(0, 0, 0, 0.7);
}
.input-toolbar {
height: 54px;
padding: 0 16px;