Compare commits
5 Commits
eb65197e23
...
fix-error
| Author | SHA1 | Date | |
|---|---|---|---|
| b4ab2f5ab7 | |||
| c1e934f2b2 | |||
| 8972dfe8e7 | |||
|
|
1879f5ce32 | ||
| fa013e597e |
133
.junie/AGENTS.md
Normal file
133
.junie/AGENTS.md
Normal 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 |
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<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>
|
<title>My App</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
1107
package-lock.json
generated
1107
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -13,7 +13,9 @@
|
|||||||
"lint": "echo \"No linting configured\"",
|
"lint": "echo \"No linting configured\"",
|
||||||
"prepare": "husky",
|
"prepare": "husky",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"format:check": "prettier --check ."
|
"format:check": "prettier --check .",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "zhiju.com.cn",
|
"author": "zhiju.com.cn",
|
||||||
@@ -38,7 +40,8 @@
|
|||||||
"postcss": "^8.5.9",
|
"postcss": "^8.5.9",
|
||||||
"prettier": "3.8.1",
|
"prettier": "3.8.1",
|
||||||
"tailwindcss": "^3.4.19",
|
"tailwindcss": "^3.4.19",
|
||||||
"vite": "^5.4.21"
|
"vite": "^5.4.21",
|
||||||
|
"vitest": "^4.1.4"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"await-to-js": "^3.0.0",
|
"await-to-js": "^3.0.0",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron';
|
import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
import net from 'node:net';
|
import net from 'node:net';
|
||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
import started from 'electron-squirrel-startup';
|
import started from 'electron-squirrel-startup';
|
||||||
@@ -225,6 +226,48 @@ function registerIpcHandlers() {
|
|||||||
// Bonjour
|
// Bonjour
|
||||||
ipcMain.handle('bonjour:get-services', () => getDiscoveredServices());
|
ipcMain.handle('bonjour:get-services', () => getDiscoveredServices());
|
||||||
|
|
||||||
|
// opencode 配置写入
|
||||||
|
ipcMain.handle('opencode:write-config', async (_e, { modelInfo, deviceHost, devicePort }) => {
|
||||||
|
const configDir = path.join(os.homedir(), '.config', 'opencode');
|
||||||
|
const configPath = path.join(configDir, 'opencode.json');
|
||||||
|
|
||||||
|
await fs.promises.mkdir(configDir, { recursive: true });
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
$schema: 'https://opencode.ai/config.json',
|
||||||
|
provider: {
|
||||||
|
zhiju: {
|
||||||
|
name: 'Zhiju AI',
|
||||||
|
env: ['ZHIJU_API_KEY'],
|
||||||
|
options: {
|
||||||
|
baseURL: `http://${deviceHost}:${modelInfo.port}/v1`,
|
||||||
|
apiKey: `${modelInfo.apiKey}`,
|
||||||
|
},
|
||||||
|
models: {
|
||||||
|
[modelInfo.model_name]: {
|
||||||
|
name: modelInfo.model_name,
|
||||||
|
family: 'openai',
|
||||||
|
status: modelInfo.status || 'beta',
|
||||||
|
capabilities: modelInfo.capabilities || {
|
||||||
|
reasoning: false,
|
||||||
|
attachment: true,
|
||||||
|
toolcall: true,
|
||||||
|
input: { text: true, audio: false, image: true, video: false, pdf: true },
|
||||||
|
output: { text: true, audio: false, image: false, video: false, pdf: false },
|
||||||
|
},
|
||||||
|
limit: modelInfo.limit || { context: 128000, output: 4096 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
model: `zhiju/${modelInfo.model_name}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||||
|
console.log('[opencode] config written to:', configPath);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
// 窗口控制
|
// 窗口控制
|
||||||
ipcMain.on('window:minimize', (event) => {
|
ipcMain.on('window:minimize', (event) => {
|
||||||
const win = BrowserWindow.fromWebContents(event.sender);
|
const win = BrowserWindow.fromWebContents(event.sender);
|
||||||
|
|||||||
@@ -26,3 +26,7 @@ contextBridge.exposeInMainWorld('bonjour', {
|
|||||||
return () => ipcRenderer.removeListener('bonjour:services-updated', listener);
|
return () => ipcRenderer.removeListener('bonjour:services-updated', listener);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
contextBridge.exposeInMainWorld('opencodeConfig', {
|
||||||
|
write: (params) => ipcRenderer.invoke('opencode:write-config', params),
|
||||||
|
});
|
||||||
|
|||||||
@@ -80,8 +80,8 @@
|
|||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
<el-avatar :size="32" />
|
<el-avatar :size="32" />
|
||||||
<div v-show="!appStore.collapsed" class="ml-3">
|
<div v-show="!appStore.collapsed" class="ml-3">
|
||||||
<div class="text-sm font-medium">123</div>
|
<div class="text-sm font-medium">{{ userStore.nickname }}</div>
|
||||||
<div class="text-xs text-gray-500">12321</div>
|
<div class="text-xs text-gray-500">{{ userStore.email }}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<LucideIcon v-show="!appStore.collapsed" name="bolt" color="#808080" size="18"></LucideIcon>
|
<LucideIcon v-show="!appStore.collapsed" name="bolt" color="#808080" size="18"></LucideIcon>
|
||||||
@@ -111,6 +111,7 @@ import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
|
|||||||
import { useRoute } from 'vue-router';
|
import { useRoute } from 'vue-router';
|
||||||
import { useAppStore } from '@/stores/app';
|
import { useAppStore } from '@/stores/app';
|
||||||
import { useHistoryStore } from '@/stores/history';
|
import { useHistoryStore } from '@/stores/history';
|
||||||
|
import { useUserStore } from '@/stores/user';
|
||||||
import { House, Monitor, Expand, Fold, ChatDotRound, Search, Collection, Clock } from '@element-plus/icons-vue';
|
import { House, Monitor, Expand, Fold, ChatDotRound, Search, Collection, Clock } from '@element-plus/icons-vue';
|
||||||
import router from '@/router';
|
import router from '@/router';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
@@ -118,6 +119,7 @@ import axios from 'axios';
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const appStore = useAppStore();
|
const appStore = useAppStore();
|
||||||
const historyStore = useHistoryStore();
|
const historyStore = useHistoryStore();
|
||||||
|
const userStore = useUserStore();
|
||||||
|
|
||||||
const statusLabel = computed(() => {
|
const statusLabel = computed(() => {
|
||||||
switch (appStore.serviceStatus) {
|
switch (appStore.serviceStatus) {
|
||||||
|
|||||||
@@ -67,9 +67,11 @@ import { ref, watch } from 'vue';
|
|||||||
import { User } from '@element-plus/icons-vue';
|
import { User } from '@element-plus/icons-vue';
|
||||||
import { ElMessage } from 'element-plus';
|
import { ElMessage } from 'element-plus';
|
||||||
import { useSparkStore } from '@/stores/spark';
|
import { useSparkStore } from '@/stores/spark';
|
||||||
import { loginAction } from '@/http/api.js';
|
import { loginAction, getUserInfoAction } from '@/http/api.js';
|
||||||
|
import { useUserStore } from '@/stores/user';
|
||||||
|
|
||||||
const sparkStore = useSparkStore();
|
const sparkStore = useSparkStore();
|
||||||
|
const userStore = useUserStore();
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: {
|
||||||
@@ -115,13 +117,38 @@ async function handleLogin() {
|
|||||||
const device = sparkStore.devices.find((d) => d.name === form.value.sparkDevice);
|
const device = sparkStore.devices.find((d) => d.name === form.value.sparkDevice);
|
||||||
if (device) sparkStore.selectDevice(device);
|
if (device) sparkStore.selectDevice(device);
|
||||||
|
|
||||||
const url = sparkStore.selectedDeviceUrl;
|
const selectedDevice = sparkStore.selectedDevice;
|
||||||
console.log('[Login] spark device:', device);
|
console.log('[Login] spark device:', selectedDevice);
|
||||||
console.log('[Login] target url:', url);
|
console.log('[Login] target url:', sparkStore.selectedDeviceUrl);
|
||||||
|
|
||||||
await loginAction({ email: form.value.username, password: form.value.password });
|
await loginAction({ email: form.value.username, password: form.value.password });
|
||||||
ElMessage.success(`登录成功 | ${url ?? '未选择设备'}`);
|
|
||||||
emit('login-success', { username: form.value.username, device });
|
// 登录成功后获取用户信息并保存
|
||||||
|
const userRes = await getUserInfoAction();
|
||||||
|
const modelInfo = userRes.data?.xuanjian_model_info;
|
||||||
|
userStore.setUserInfo({ nickname: userRes.data?.nickname, email: userRes.data?.email });
|
||||||
|
|
||||||
|
// 写入 opencode 配置文件
|
||||||
|
if (modelInfo && selectedDevice) {
|
||||||
|
try {
|
||||||
|
const deviceHost = selectedDevice.host;
|
||||||
|
console.log('[Config] modelInfo:', modelInfo);
|
||||||
|
console.log('[Config] deviceHost:', deviceHost, 'port:', selectedDevice.port);
|
||||||
|
await window.opencodeConfig.write({
|
||||||
|
modelInfo,
|
||||||
|
deviceHost: selectedDevice.host,
|
||||||
|
devicePort: selectedDevice.port,
|
||||||
|
});
|
||||||
|
console.log('[Config] 写入成功');
|
||||||
|
} catch (configErr) {
|
||||||
|
console.error('[Config] 写入失败:', configErr);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('[Config] 跳过写入,modelInfo:', modelInfo, 'selectedDevice:', selectedDevice);
|
||||||
|
}
|
||||||
|
|
||||||
|
ElMessage.success(`登录成功 | ${sparkStore.selectedDeviceUrl ?? '未选择设备'}`);
|
||||||
|
emit('login-success', { username: form.value.username, device: selectedDevice });
|
||||||
visible.value = false;
|
visible.value = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
ElMessage.error('登录失败,请重试');
|
ElMessage.error('登录失败,请重试');
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ export const getHealthAction = () => getAction(url.health);
|
|||||||
// 用户登录
|
// 用户登录
|
||||||
export const loginAction = (data) => postAction(url.user.login, { email: data.email, password: encryptPassword(data.password) });
|
export const loginAction = (data) => postAction(url.user.login, { email: data.email, password: encryptPassword(data.password) });
|
||||||
|
|
||||||
|
// 获取用户信息
|
||||||
|
export const getUserInfoAction = () => getAction(url.user.getUserInfo);
|
||||||
|
|
||||||
// 会话
|
// 会话
|
||||||
export const createSessionAction = (data) => postAction(url.session.create, data);
|
export const createSessionAction = (data) => postAction(url.session.create, data);
|
||||||
export const getSessionAction = (id) => getAction(url.session.detail(id));
|
export const getSessionAction = (id) => getAction(url.session.detail(id));
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ const url = {
|
|||||||
// 用户
|
// 用户
|
||||||
user: {
|
user: {
|
||||||
login: '/v1/user/login',
|
login: '/v1/user/login',
|
||||||
|
// 获取用户信息接口
|
||||||
|
getUserInfo: '/v1/user/info',
|
||||||
},
|
},
|
||||||
|
|
||||||
// SSE 事件流
|
// SSE 事件流
|
||||||
|
|||||||
66
src/renderer/stores/draft.js
Normal file
66
src/renderer/stores/draft.js
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { defineStore } from 'pinia';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 草稿消息 Store
|
||||||
|
* 用于在页面间传递待发送的消息内容(文本和文件)
|
||||||
|
*/
|
||||||
|
export const useDraftStore = defineStore('draft', () => {
|
||||||
|
// 待发送的文本内容
|
||||||
|
const text = ref('');
|
||||||
|
|
||||||
|
// 待发送的文件列表
|
||||||
|
// 格式: [{ id, filename, mime, type: File, url }]
|
||||||
|
// url: 图片为 base64 (data:image/...),文本文件为 data:text/plain;base64,... 等
|
||||||
|
const files = ref([]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置草稿内容
|
||||||
|
* @param {string} content - 文本内容
|
||||||
|
* @param {Array} fileList - 文件列表
|
||||||
|
*/
|
||||||
|
function setDraft(content, fileList = []) {
|
||||||
|
text.value = content;
|
||||||
|
files.value = fileList;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取草稿内容并清空
|
||||||
|
* @returns {{text: string, files: Array}}
|
||||||
|
*/
|
||||||
|
function takeDraft() {
|
||||||
|
const result = {
|
||||||
|
text: text.value,
|
||||||
|
files: [...files.value],
|
||||||
|
};
|
||||||
|
// 清空草稿
|
||||||
|
text.value = '';
|
||||||
|
files.value = [];
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空草稿
|
||||||
|
*/
|
||||||
|
function clearDraft() {
|
||||||
|
text.value = '';
|
||||||
|
files.value = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否有草稿内容
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function hasDraft() {
|
||||||
|
return text.value.trim().length > 0 || files.value.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
files,
|
||||||
|
setDraft,
|
||||||
|
takeDraft,
|
||||||
|
clearDraft,
|
||||||
|
hasDraft,
|
||||||
|
};
|
||||||
|
});
|
||||||
25
src/renderer/stores/user.js
Normal file
25
src/renderer/stores/user.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { defineStore } from 'pinia';
|
||||||
|
import { ref, computed } from 'vue';
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'user_info';
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const userInfo = ref(JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null'));
|
||||||
|
|
||||||
|
const nickname = computed(() => userInfo.value?.nickname || '');
|
||||||
|
const email = computed(() => userInfo.value?.email || '');
|
||||||
|
const isLoggedIn = computed(() => !!userInfo.value);
|
||||||
|
|
||||||
|
function setUserInfo(info) {
|
||||||
|
userInfo.value = info;
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(info));
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearUserInfo() {
|
||||||
|
userInfo.value = null;
|
||||||
|
localStorage.removeItem(STORAGE_KEY);
|
||||||
|
localStorage.removeItem('Authorization');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { userInfo, nickname, email, isLoggedIn, setUserInfo, clearUserInfo };
|
||||||
|
});
|
||||||
@@ -8,6 +8,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div v-for="msg in messages" :key="msg.id" class="bubble-wrap" :class="msg.role">
|
<div v-for="msg in messages" :key="msg.id" class="bubble-wrap" :class="msg.role">
|
||||||
<div class="bubble">
|
<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 v-if="msg.parts?.filter((p) => p.type === 'reasoning').length > 0" class="reasoning-section">
|
||||||
<div class="reasoning-header" @click="msg.showReasoning = !msg.showReasoning">
|
<div class="reasoning-header" @click="msg.showReasoning = !msg.showReasoning">
|
||||||
@@ -22,21 +32,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<!-- 文本内容 -->
|
<!-- 文本内容 -->
|
||||||
<MarkdownRender v-if="msg.text" :content="msg.text"></MarkdownRender>
|
<MarkdownRender v-if="msg.text" :content="msg.text"></MarkdownRender>
|
||||||
<!-- question 类型 part 展示 -->
|
|
||||||
<template v-if="msg.parts">
|
|
||||||
<div v-for="(p, idx) in msg.parts.filter((p) => p.type === 'question')" :key="'question-' + idx" class="question-part">
|
|
||||||
<div v-for="(q, qi) in p.questions" :key="qi" class="question-item">
|
|
||||||
<div class="question-header">{{ q.header }}</div>
|
|
||||||
<div class="question-text">{{ q.question }}</div>
|
|
||||||
<div class="question-options">
|
|
||||||
<div v-for="(opt, oi) in q.options" :key="oi" class="question-option" @click="sendAnswer(p.id, opt.label)">
|
|
||||||
<span class="option-label">{{ opt.label }}</span>
|
|
||||||
<span v-if="opt.description" class="option-desc">{{ opt.description }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<!-- tool 类型 part 展示 -->
|
<!-- tool 类型 part 展示 -->
|
||||||
<template v-if="msg.parts">
|
<template v-if="msg.parts">
|
||||||
<template v-for="(p, idx) in msg.parts.filter((p) => p.type === 'tool')" :key="'tool-' + idx">
|
<template v-for="(p, idx) in msg.parts.filter((p) => p.type === 'tool')" :key="'tool-' + idx">
|
||||||
@@ -74,7 +69,11 @@
|
|||||||
<div v-if="p.state?.input?.command" class="tool-command">
|
<div v-if="p.state?.input?.command" class="tool-command">
|
||||||
<span class="tool-label">$ </span><code>{{ p.state.input.command }}</code>
|
<span class="tool-label">$ </span><code>{{ p.state.input.command }}</code>
|
||||||
</div>
|
</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>
|
<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 v-if="p.state?.time" class="tool-time">耗时 {{ p.state.time.end - p.state.time.start }} ms</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -87,6 +86,7 @@
|
|||||||
(p) =>
|
(p) =>
|
||||||
p.type !== 'text' &&
|
p.type !== 'text' &&
|
||||||
p.type !== 'reasoning' &&
|
p.type !== 'reasoning' &&
|
||||||
|
p.type !== 'file' &&
|
||||||
p.type !== 'tool' &&
|
p.type !== 'tool' &&
|
||||||
p.type !== 'question' &&
|
p.type !== 'question' &&
|
||||||
p.type !== 'step-start' &&
|
p.type !== 'step-start' &&
|
||||||
@@ -123,8 +123,9 @@
|
|||||||
import { ref, computed, onMounted, onUnmounted, nextTick, watch, reactive } from 'vue';
|
import { ref, computed, onMounted, onUnmounted, nextTick, watch, reactive } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import { ElMessage } from 'element-plus';
|
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 { useAppStore } from '@/stores/app.js';
|
||||||
|
import { useDraftStore } from '@/stores/draft.js';
|
||||||
import { sseManager } from '@/http/sse.js';
|
import { sseManager } from '@/http/sse.js';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import MarkdownRender from '@/components/MarkdownRender/index.vue';
|
import MarkdownRender from '@/components/MarkdownRender/index.vue';
|
||||||
@@ -132,12 +133,19 @@ import MarkdownRender from '@/components/MarkdownRender/index.vue';
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const appStore = useAppStore();
|
const appStore = useAppStore();
|
||||||
|
const draftStore = useDraftStore();
|
||||||
const isSending = ref(false);
|
const isSending = ref(false);
|
||||||
const inputText = ref('');
|
const inputText = ref('');
|
||||||
const messages = ref([]);
|
const messages = ref([]);
|
||||||
const messagesRef = ref(null);
|
const messagesRef = ref(null);
|
||||||
const currentSessionId = ref(null);
|
const currentSessionId = ref(null);
|
||||||
const localAssistantMessageIds = new Set();
|
const localAssistantMessageIds = new Set();
|
||||||
|
const pendingFiles = ref([]); // 待发送的文件列表
|
||||||
|
|
||||||
|
// 生成唯一 ID
|
||||||
|
function generateId() {
|
||||||
|
return 'prt_' + Date.now() + Math.random().toString(36).substr(2, 9);
|
||||||
|
}
|
||||||
|
|
||||||
// 是否有正在等待回答的 question
|
// 是否有正在等待回答的 question
|
||||||
const hasActiveQuestion = computed(() => {
|
const hasActiveQuestion = computed(() => {
|
||||||
@@ -145,7 +153,6 @@ const hasActiveQuestion = computed(() => {
|
|||||||
if (!msg.parts) continue;
|
if (!msg.parts) continue;
|
||||||
for (const p of msg.parts) {
|
for (const p of msg.parts) {
|
||||||
if (p.type === 'tool' && p.tool === 'question' && p.state?.status === 'running' && p._questionId) return true;
|
if (p.type === 'tool' && p.tool === 'question' && p.state?.status === 'running' && p._questionId) return true;
|
||||||
if (p.type === 'question') return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -182,20 +189,27 @@ async function loadHistoryMessages(sessionId) {
|
|||||||
const { info, parts } = item;
|
const { info, parts } = item;
|
||||||
if (!info || !parts) return;
|
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')
|
.filter((p) => p.type === 'text')
|
||||||
.map((part) => part.text)
|
.map((part) => part.text)
|
||||||
.join('');
|
.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({
|
messages.value.push({
|
||||||
id: info.id,
|
id: info.id,
|
||||||
role: info.role,
|
role: info.role,
|
||||||
text: text,
|
text: text,
|
||||||
|
files: files,
|
||||||
parts: normalizedParts,
|
parts: normalizedParts,
|
||||||
showReasoning: true, // 默认展开推理过程
|
showReasoning: true, // 默认展开推理过程
|
||||||
});
|
});
|
||||||
@@ -225,18 +239,17 @@ watch(
|
|||||||
// 等待历史消息加载完毕,避免在 send 时 messages 被清空
|
// 等待历史消息加载完毕,避免在 send 时 messages 被清空
|
||||||
await loadHistoryMessages(newSessionId);
|
await loadHistoryMessages(newSessionId);
|
||||||
|
|
||||||
// 处理从首页带过来的初始消息
|
// 处理从首页带过来的初始消息(从 draft store 获取)
|
||||||
const text = route.query.text;
|
if (draftStore.hasDraft()) {
|
||||||
if (text) {
|
const draft = draftStore.takeDraft();
|
||||||
inputText.value = text;
|
inputText.value = draft.text;
|
||||||
// 清除 query 中的 text,防止刷新页面时重复发送
|
pendingFiles.value = draft.files;
|
||||||
const query = { ...route.query };
|
|
||||||
delete query.text;
|
|
||||||
router.replace({ query });
|
|
||||||
|
|
||||||
// 触发发送逻辑
|
// 触发发送逻辑
|
||||||
|
if (inputText.value.trim()) {
|
||||||
send();
|
send();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 确保 SSE 连接已建立
|
// 确保 SSE 连接已建立
|
||||||
if (!appStore.sseConnected) {
|
if (!appStore.sseConnected) {
|
||||||
@@ -327,13 +340,7 @@ function registerSSEListeners() {
|
|||||||
const msgId = props.tool?.messageID;
|
const msgId = props.tool?.messageID;
|
||||||
const callId = props.tool?.callID;
|
const callId = props.tool?.callID;
|
||||||
if (!msgId) return;
|
if (!msgId) return;
|
||||||
// 将 question 作为一个 part 插入对应消息
|
// 将 question id 关联到对应的 tool part(通过 callID 匹配)
|
||||||
upsertAssistantPart(msgId, {
|
|
||||||
id: props.id,
|
|
||||||
type: 'question',
|
|
||||||
questions: props.questions || [],
|
|
||||||
});
|
|
||||||
// 同时将 question id 关联到对应的 tool part(通过 callID 匹配)
|
|
||||||
if (callId) {
|
if (callId) {
|
||||||
const msg = messages.value.find((m) => m.id === msgId);
|
const msg = messages.value.find((m) => m.id === msgId);
|
||||||
if (msg && msg.parts) {
|
if (msg && msg.parts) {
|
||||||
@@ -361,9 +368,16 @@ function unregisterSSEListeners() {
|
|||||||
|
|
||||||
async function sendAnswer(questionId, label) {
|
async function sendAnswer(questionId, label) {
|
||||||
if (!currentSessionId.value) return;
|
if (!currentSessionId.value) return;
|
||||||
messages.value.push({ id: Date.now(), role: 'user', text: label });
|
|
||||||
isSending.value = true;
|
isSending.value = true;
|
||||||
scrollToBottom();
|
// 将对应 tool part 标记为已回答,使输入框在等待响应期间可见
|
||||||
|
for (const msg of messages.value) {
|
||||||
|
if (!msg.parts) continue;
|
||||||
|
for (const p of msg.parts) {
|
||||||
|
if (p.type === 'tool' && p.tool === 'question' && p._questionId === questionId) {
|
||||||
|
if (p.state) p.state.status = 'answered';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const baseUrl = window.__opencodeBaseUrl || 'http://127.0.0.1:4096';
|
const baseUrl = window.__opencodeBaseUrl || 'http://127.0.0.1:4096';
|
||||||
await axios.post(`${baseUrl}/question/${questionId}/reply`, { answers: [[label]] });
|
await axios.post(`${baseUrl}/question/${questionId}/reply`, { answers: [[label]] });
|
||||||
@@ -394,8 +408,26 @@ async function send() {
|
|||||||
isSending.value = true;
|
isSending.value = true;
|
||||||
scrollToBottom();
|
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 {
|
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 事件重置
|
// 发送成功后等待 SSE 事件流推送 AI 响应,isSending 由 session.idle 事件重置
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('发送指令失败:', err);
|
console.error('发送指令失败:', err);
|
||||||
@@ -468,19 +500,23 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
.bubble {
|
.bubble {
|
||||||
max-width: 75%;
|
max-width: 75%;
|
||||||
|
min-width: 48px;
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bubble-wrap.user .bubble {
|
.bubble-wrap.user .bubble {
|
||||||
|
width: fit-content;
|
||||||
background: #409eff;
|
background: #409eff;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
border-bottom-right-radius: 4px;
|
border-bottom-right-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bubble-wrap.assistant .bubble {
|
.bubble-wrap.assistant .bubble {
|
||||||
|
width: 75%;
|
||||||
background: #f0f2f5;
|
background: #f0f2f5;
|
||||||
color: #303133;
|
color: #303133;
|
||||||
border-bottom-left-radius: 4px;
|
border-bottom-left-radius: 4px;
|
||||||
@@ -493,6 +529,47 @@ onUnmounted(() => {
|
|||||||
font-family: inherit;
|
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 {
|
.reasoning-section {
|
||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
@@ -625,6 +702,18 @@ onUnmounted(() => {
|
|||||||
text-align: right;
|
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 {
|
.question-part {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,25 +42,57 @@
|
|||||||
<!-- 底部:输入框 -->
|
<!-- 底部:输入框 -->
|
||||||
<div class="input-section">
|
<div class="input-section">
|
||||||
<div class="input-wrapper">
|
<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
|
<textarea
|
||||||
v-model="inputText"
|
v-model="inputText"
|
||||||
class="input-textarea"
|
class="input-textarea"
|
||||||
placeholder="描述任务,/ 调用技能与工具,@调用知识库"
|
placeholder="输入 / 调用技能,输入 @ 调用知识库"
|
||||||
:disabled="isCreating"
|
:disabled="isCreating"
|
||||||
@keydown="handleKeydown"
|
@keydown="handleKeydown"
|
||||||
|
@input="autoResize"
|
||||||
|
ref="textareaRef"
|
||||||
></textarea>
|
></textarea>
|
||||||
<div class="input-toolbar">
|
<div class="input-toolbar">
|
||||||
<div class="toolbar-left">
|
<div class="toolbar-left">
|
||||||
<button class="toolbar-btn file-btn">
|
<button class="dir-btn">
|
||||||
<el-icon><Plus /></el-icon>
|
<LucideIcon name="folder-input" size="16"></LucideIcon>
|
||||||
<span>添加文件</span>
|
<span>选择工作目录</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="toolbar-btn symbol-btn">/</button>
|
<el-tooltip content="添加文件或者文件夹作为上下文" placement="top" :show-arrow="false">
|
||||||
<button class="toolbar-btn symbol-btn">@</button>
|
<label class="toolbar-btn icon-btn" style="cursor: pointer">
|
||||||
|
<input type="file" multiple style="display: none" @change="handleFilesSelected" />
|
||||||
|
<LucideIcon name="paperclip" size="16"></LucideIcon>
|
||||||
|
</label>
|
||||||
|
</el-tooltip>
|
||||||
|
<el-tooltip content="使用 / 调用技能" placement="top" :show-arrow="false">
|
||||||
|
<button class="toolbar-btn icon-btn">/</button>
|
||||||
|
</el-tooltip>
|
||||||
|
<el-tooltip content="使用 @ 调用知识库" placement="top" :show-arrow="false">
|
||||||
|
<button class="toolbar-btn icon-btn">@</button>
|
||||||
|
</el-tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div class="toolbar-right">
|
<div class="toolbar-right">
|
||||||
<button class="send-btn" :disabled="!inputText.trim() || isCreating" @click="handleSend">
|
<button class="send-btn" :disabled="!inputText.trim() || isCreating" @click="handleSend">
|
||||||
<el-icon><Promotion /></el-icon>
|
<LucideIcon name="arrow-up"></LucideIcon>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -74,14 +106,31 @@ import { ref } from 'vue';
|
|||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
import { useAppStore } from '@/stores/app';
|
import { useAppStore } from '@/stores/app';
|
||||||
import { useHistoryStore } from '@/stores/history';
|
import { useHistoryStore } from '@/stores/history';
|
||||||
import { Document, Plus, Promotion } from '@element-plus/icons-vue';
|
import { useDraftStore } from '@/stores/draft';
|
||||||
|
import { Document, Plus, Promotion, FolderOpened, Paperclip } from '@element-plus/icons-vue';
|
||||||
import { ElMessage } from 'element-plus';
|
import { ElMessage } from 'element-plus';
|
||||||
|
import LucideIcon from '@/components/base/LucideIcon.vue';
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const appStore = useAppStore();
|
const appStore = useAppStore();
|
||||||
const historyStore = useHistoryStore();
|
const historyStore = useHistoryStore();
|
||||||
|
const draftStore = useDraftStore();
|
||||||
const inputText = ref('');
|
const inputText = ref('');
|
||||||
const isCreating = ref(false);
|
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;
|
||||||
|
if (!el) return;
|
||||||
|
el.style.height = 'auto';
|
||||||
|
el.style.height = Math.min(el.scrollHeight, 323) + 'px';
|
||||||
|
}
|
||||||
|
|
||||||
// 处理发送消息
|
// 处理发送消息
|
||||||
async function handleSend() {
|
async function handleSend() {
|
||||||
@@ -99,14 +148,17 @@ async function handleSend() {
|
|||||||
const session = await historyStore.createSession(text);
|
const session = await historyStore.createSession(text);
|
||||||
console.log('创建会话成功:', session);
|
console.log('创建会话成功:', session);
|
||||||
|
|
||||||
// 清空输入框
|
// 将文本和文件保存到 draft store
|
||||||
inputText.value = '';
|
draftStore.setDraft(text, [...selectedFiles.value]);
|
||||||
|
|
||||||
// 跳转到对话页面,并将消息文本带入 query
|
// 清空输入框和文件
|
||||||
|
inputText.value = '';
|
||||||
|
selectedFiles.value = [];
|
||||||
|
|
||||||
|
// 跳转到对话页面
|
||||||
router.push({
|
router.push({
|
||||||
name: 'Chat',
|
name: 'Chat',
|
||||||
params: { id: session.id },
|
params: { id: session.id },
|
||||||
query: { text: text },
|
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('创建会话失败:', err);
|
console.error('创建会话失败:', err);
|
||||||
@@ -123,6 +175,47 @@ function handleKeydown(e) {
|
|||||||
handleSend();
|
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>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@@ -234,26 +327,28 @@ function handleKeydown(e) {
|
|||||||
.input-section {
|
.input-section {
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
padding-top: 24px;
|
padding-top: 24px;
|
||||||
|
padding-bottom: 32px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-wrapper {
|
.input-wrapper {
|
||||||
width: 760px;
|
width: 760px;
|
||||||
height: 114px;
|
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
border: 1px solid #dcdfe6;
|
border: 1px solid #dee0e4;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
background: #ffffff;
|
background: #ffffff;
|
||||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
|
box-shadow: 0px 1px 20px 0px #00000008;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-textarea {
|
.input-textarea {
|
||||||
width: 758px;
|
width: 758px;
|
||||||
height: 60px;
|
min-height: 60px;
|
||||||
|
max-height: 323px;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
border: none;
|
border: none;
|
||||||
outline: none;
|
outline: none;
|
||||||
resize: none;
|
resize: none;
|
||||||
|
overflow-y: auto;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
line-height: 20px;
|
line-height: 20px;
|
||||||
color: #303133;
|
color: #303133;
|
||||||
@@ -265,13 +360,81 @@ function handleKeydown(e) {
|
|||||||
color: #c0c4cc;
|
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 {
|
.input-toolbar {
|
||||||
height: 54px;
|
height: 54px;
|
||||||
padding: 0 16px;
|
padding: 0 16px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
border-top: 1px solid #ebeef5;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.toolbar-left {
|
.toolbar-left {
|
||||||
@@ -296,20 +459,33 @@ function handleKeydown(e) {
|
|||||||
color: #409eff;
|
color: #409eff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-btn {
|
.dir-btn {
|
||||||
width: 84px;
|
|
||||||
height: 28px;
|
height: 28px;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
padding: 0 8px;
|
padding: 0 8px;
|
||||||
border-radius: 6px;
|
background: #f5f6f7;
|
||||||
|
border-radius: 28px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 16px;
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
color: #606266;
|
||||||
|
}
|
||||||
|
.dir-btn:hover {
|
||||||
|
background: #eeeff2;
|
||||||
}
|
}
|
||||||
|
|
||||||
.symbol-btn {
|
.icon-btn {
|
||||||
width: 28px;
|
width: 28px;
|
||||||
height: 28px;
|
height: 28px;
|
||||||
padding: 0;
|
padding: 0 7px;
|
||||||
border-radius: 6px;
|
border-radius: 9999px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
@@ -323,8 +499,8 @@ function handleKeydown(e) {
|
|||||||
width: 32px;
|
width: 32px;
|
||||||
height: 32px;
|
height: 32px;
|
||||||
border: none;
|
border: none;
|
||||||
background: #409eff;
|
background: #1a1a1a;
|
||||||
border-radius: 8px;
|
border-radius: 32px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -334,6 +510,11 @@ function handleKeydown(e) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.send-btn:hover {
|
.send-btn:hover {
|
||||||
background: #66b1ff;
|
background: #333333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-btn:disabled {
|
||||||
|
background: #8c8c8c;
|
||||||
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
Reference in New Issue
Block a user