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

133
.junie/AGENTS.md Normal file
View File

@@ -0,0 +1,133 @@
# Zhiju AI Assistant — Developer Notes
## Project Overview
Electron desktop app (Electron Forge + Vite + Vue 3) that wraps a locally-spawned `opencode` binary (located in `resources/`). The renderer is a Vue 3 SPA; the main process manages the `opencode` child process and exposes IPC to the renderer via a preload script.
---
## Build & Configuration
### Prerequisites
- Node.js ≥ 18
- The `opencode` binary must exist at `resources/windows/x64/opencode.exe` (Windows) before packaging. It is **not** committed to the repo — obtain it separately.
### Install dependencies
```bash
npm install
```
### Run in development
```bash
npm start
```
This uses `electron-forge start`, which runs Vite for the renderer and launches Electron. Hot-reload is active for the renderer; changes to `src/main/index.js` or `src/preload/index.js` require a manual restart.
### Package / distribute
```bash
npm run make # builds installers for the current platform
npm run package # produces an unpackaged app directory
```
Packaged output lands in `out/`. The `opencode.exe` binary is bundled via `extraResource` in `forge.config.js` and unpacked from ASAR at runtime.
### Vite configs
| File | Purpose |
|---|---|
| `vite.main.config.mjs` | Main process bundle |
| `vite.preload.config.mjs` | Preload script bundle |
| `vite.renderer.config.mjs` | Renderer (Vue SPA), alias `@``src/renderer` |
---
## Architecture Notes
- **Main process** (`src/main/index.js`): spawns `opencode` binary, resolves a free port starting at `4096`, waits for TCP readiness, then injects `window.__opencodeBaseUrl` into the renderer via `executeJavaScript`. Also runs Bonjour service discovery.
- **Preload** (`src/preload/index.js`): bridges IPC between main and renderer using `contextBridge`.
- **Renderer** (`src/renderer/`): Vue 3 + Pinia + Vue Router. HTTP calls go through `src/renderer/http/` (axios-based). SSE streaming is handled in `src/renderer/http/sse.js`.
- **URL constants** (`src/renderer/http/url.js`): single source of truth for all API endpoint paths. `getBaseUrl()` reads `window.__opencodeBaseUrl` (injected by main) with fallback to `http://127.0.0.1:4096`.
- **Crypto** (`src/renderer/utils/crypto.js`): passwords are Base64-encoded then RSA-encrypted (public key hardcoded) before being sent to the login API.
---
## Testing
### Framework
[Vitest](https://vitest.dev/) — chosen for native Vite/ESM compatibility, zero extra config needed.
### Run all tests
```bash
npm test # vitest run (single pass, CI-friendly)
npm run test:watch # vitest watch mode (development)
```
Or directly:
```bash
npx vitest run
```
### Writing tests
- Place test files alongside the source file as `*.test.js` (Vitest picks them up automatically).
- For pure utility/logic modules (e.g. `url.js`, `crypto.js`) no additional setup is needed.
- Modules that depend on `window`, `electron`, or Pinia require mocking. Use `vi.stubGlobal` for `window` properties and `vi.mock` for module mocks.
### Example: testing `url.js`
```js
// src/renderer/http/url.test.js
import { describe, it, expect } from 'vitest';
import url from './url.js';
describe('url constants', () => {
it('session.detail returns correct path', () => {
expect(url.session.detail('abc123')).toBe('/session/abc123');
});
it('message.send returns correct path', () => {
expect(url.message.send('sess1')).toBe('/session/sess1/message');
});
});
```
Run with:
```bash
npx vitest run src/renderer/http/url.test.js
```
### Testing modules that use `window.__opencodeBaseUrl`
```js
import { vi, describe, it, expect, beforeEach } from 'vitest';
beforeEach(() => {
vi.stubGlobal('__opencodeBaseUrl', 'http://127.0.0.1:5000');
});
// import and test getBaseUrl() etc.
```
---
## Code Style
- **Formatter**: Prettier (config in `package.json` defaults). Run `npm run format` to auto-fix, `npm run format:check` for CI check.
- **Commit messages**: enforced by commitlint (`@commitlint/config-conventional`). Use conventional commits: `feat:`, `fix:`, `chore:`, etc.
- **Pre-commit hook**: husky + lint-staged runs Prettier on staged `*.js` and `*.vue` files automatically.
- **No ESLint** is configured — only Prettier for formatting.
- Vue components use the Composition API (`<script setup>` style in newer components, options-style `setup()` returning refs in stores).
- Pinia stores use the Setup Store pattern (function returning refs/actions), not the Options Store pattern.
- Chinese comments are common throughout the codebase — maintain them in Chinese when editing existing files.
---
## Key Dependencies
| Package | Role |
|---|---|
| `electron` v41 | Desktop shell |
| `electron-forge` v7 | Build/package toolchain |
| `vite` v5 + `@vitejs/plugin-vue` | Renderer bundler |
| `vue` v3 + `pinia` + `vue-router` | UI framework |
| `axios` | HTTP client (renderer) |
| `element-plus` | UI component library |
| `bonjour-service` | LAN service discovery |
| `jsencrypt` + `js-base64` | Password encryption before login |
| `unified` / `remark` / `rehype` | Markdown rendering pipeline |
| `katex` | Math formula rendering in chat |

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' http://*:* ws://*:*" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' http://*:* ws://*:*; img-src 'self' data: blob:" />
<title>My App</title>
</head>
<body>

1107
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,9 @@
"lint": "echo \"No linting configured\"",
"prepare": "husky",
"format": "prettier --write .",
"format:check": "prettier --check ."
"format:check": "prettier --check .",
"test": "vitest run",
"test:watch": "vitest"
},
"keywords": [],
"author": "zhiju.com.cn",
@@ -38,7 +40,8 @@
"postcss": "^8.5.9",
"prettier": "3.8.1",
"tailwindcss": "^3.4.19",
"vite": "^5.4.21"
"vite": "^5.4.21",
"vitest": "^4.1.4"
},
"dependencies": {
"await-to-js": "^3.0.0",

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;