first commit

This commit is contained in:
2026-04-09 21:35:06 +08:00
commit 22fe6e069c
38 changed files with 12631 additions and 0 deletions

56
src/main.js Normal file
View File

@@ -0,0 +1,56 @@
import { app, BrowserWindow } from 'electron';
import path from 'node:path';
import started from 'electron-squirrel-startup';
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
// and load the index.html of the app.
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow();
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

218
src/main/index.js Normal file
View File

@@ -0,0 +1,218 @@
import { app, BrowserWindow, shell, ipcMain } from 'electron';
import path from 'node:path';
import fs from 'node:fs';
import net from 'node:net';
import { spawn } from 'node:child_process';
import started from 'electron-squirrel-startup';
if (started) app.quit();
// ========== OpenCode 服务管理 ==========
const DEFAULT_PORT = 4096;
let opencodeProcess = null;
let opencodePort = null;
let opencodeStarting = null;
function isPortAvailable(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.once('error', () => resolve(false));
server.once('listening', () => server.close(() => resolve(true)));
server.listen(port, '127.0.0.1');
});
}
async function resolvePort() {
let port = DEFAULT_PORT;
while (!(await isPortAvailable(port))) {
port++;
if (port > 65535) throw new Error('没有可用的端口');
}
return port;
}
function waitForReady(port, timeout = 15000) {
return new Promise((resolve, reject) => {
const start = Date.now();
const check = () => {
const socket = net.createConnection({ port, host: '127.0.0.1' });
socket.once('connect', () => { socket.end(); resolve(); });
socket.once('error', () => {
socket.destroy();
if (Date.now() - start >= timeout) return reject(new Error('OpenCode 服务启动超时'));
setTimeout(check, 300);
});
};
check();
});
}
function buildInfo() {
return {
running: !!opencodeProcess,
port: opencodePort,
url: opencodePort ? `http://127.0.0.1:${opencodePort}` : null,
};
}
function buildEnv(exeDir) {
const env = { ...process.env };
for (const key of Object.keys(env)) {
if (key.startsWith('npm_')) delete env[key];
}
env.INIT_CWD = exeDir;
env.PWD = exeDir;
return env;
}
function getExePath() {
// 开发模式__dirname = .vite/build往上两级到项目根
// 打包模式:用 process.resourcesPath
if (app.isPackaged) {
return path.join(process.resourcesPath, 'opencode.exe');
}
return path.join(__dirname, '..', '..', 'resources', 'windows', 'x64', 'opencode.exe');
}
async function startOpencode() {
if (opencodeProcess) return buildInfo();
if (opencodeStarting) return opencodeStarting;
opencodeStarting = (async () => {
const exePath = getExePath();
console.log('[opencode] exe path:', exePath);
const exeDir = path.dirname(exePath);
await fs.promises.access(exePath, fs.constants.F_OK);
opencodePort = await resolvePort();
opencodeProcess = spawn(exePath, ['serve', '--port', String(opencodePort)], {
cwd: exeDir,
windowsHide: true,
env: buildEnv(exeDir),
});
opencodeProcess.stdout?.on('data', (d) => console.log(`[opencode] ${d.toString().trim()}`));
opencodeProcess.stderr?.on('data', (d) => console.error(`[opencode error] ${d.toString().trim()}`));
opencodeProcess.once('error', (e) => console.error('[opencode spawn error]', e));
opencodeProcess.once('close', (code) => {
console.log(`[opencode exited] code=${code}`);
opencodeProcess = null;
opencodePort = null;
opencodeStarting = null;
});
await waitForReady(opencodePort);
return buildInfo();
})();
try {
return await opencodeStarting;
} catch (err) {
opencodeProcess?.kill();
opencodeProcess = null;
opencodePort = null;
opencodeStarting = null;
throw err;
}
}
function stopOpencode() {
opencodeProcess?.kill();
opencodeProcess = null;
opencodePort = null;
opencodeStarting = null;
}
// ========== IPC Handlers ==========
function registerIpcHandlers() {
ipcMain.handle('opencode:start', () => startOpencode());
ipcMain.handle('opencode:stop', () => { stopOpencode(); return buildInfo(); });
ipcMain.handle('opencode:info', () => buildInfo());
ipcMain.handle('opencode:port', () => opencodePort);
ipcMain.handle('opencode:health', async () => {
if (!opencodePort) throw new Error('OpenCode 服务未启动');
const res = await fetch(`http://127.0.0.1:${opencodePort}/global/health`);
if (!res.ok) throw new Error(`健康检查失败: ${res.status}`);
return res.json();
});
ipcMain.handle('opencode:session:create', async (_e, data) => {
if (!opencodePort) throw new Error('OpenCode 服务未启动');
const res = await fetch(`http://127.0.0.1:${opencodePort}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data ?? {}),
});
if (!res.ok) throw new Error(`创建会话失败: ${res.status}`);
return res.json();
});
ipcMain.handle('opencode:session:send', async (_e, sessionId, text) => {
if (!opencodePort) throw new Error('OpenCode 服务未启动');
const res = await fetch(`http://127.0.0.1:${opencodePort}/session/${sessionId}/message`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text }] }),
});
if (!res.ok) throw new Error(`发送消息失败: ${res.status}`);
return res.json();
});
}
// ========== 窗口 ==========
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 1280,
height: 800,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'index.js'),
contextIsolation: true,
nodeIntegration: false,
},
titleBarStyle: 'hiddenInset',
show: false,
});
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// 注入 baseUrl让渲染进程的 getBaseUrl() 能拿到正确端口
mainWindow.webContents.on('did-finish-load', () => {
if (opencodePort) {
mainWindow.webContents.executeJavaScript(
`window.__opencodeBaseUrl = 'http://127.0.0.1:${opencodePort}'`
);
}
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
mainWindow.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)
);
}
};
app.whenReady().then(() => {
registerIpcHandlers();
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
stopOpencode();
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => stopOpencode());

2
src/preload.js Normal file
View File

@@ -0,0 +1,2 @@
// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts

18
src/preload/index.js Normal file
View File

@@ -0,0 +1,18 @@
import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', {
// 通用 IPC保留原有
send: (channel, data) => ipcRenderer.send(channel, data),
on: (channel, callback) => ipcRenderer.on(channel, (_event, ...args) => callback(...args)),
invoke: (channel, data) => ipcRenderer.invoke(channel, data),
});
contextBridge.exposeInMainWorld('opencode', {
start: () => ipcRenderer.invoke('opencode:start'),
stop: () => ipcRenderer.invoke('opencode:stop'),
info: () => ipcRenderer.invoke('opencode:info'),
port: () => ipcRenderer.invoke('opencode:port'),
health: () => ipcRenderer.invoke('opencode:health'),
createSession: (data) => ipcRenderer.invoke('opencode:session:create', data),
sendMessage: (sessionId, text) => ipcRenderer.invoke('opencode:session:send', sessionId, text),
});

33
src/renderer.js Normal file
View File

@@ -0,0 +1,33 @@
/**
* This file will automatically be loaded by vite and run in the "renderer" context.
* To learn more about the differences between the "main" and the "renderer" context in
* Electron, visit:
*
* https://electronjs.org/docs/tutorial/process-model
*
* By default, Node.js integration in this file is disabled. When enabling Node.js integration
* in a renderer process, please be aware of potential security implications. You can read
* more about security risks here:
*
* https://electronjs.org/docs/tutorial/security
*
* To enable Node.js integration in this file, open up `main.js` and enable the `nodeIntegration`
* flag:
*
* ```
* // Create the browser window.
* mainWindow = new BrowserWindow({
* width: 800,
* height: 600,
* webPreferences: {
* nodeIntegration: true
* }
* });
* ```
*/
import './index.css';
console.log(
'👋 This message is being logged by "renderer.js", included via Vite',
);

7
src/renderer/App.vue Normal file
View File

@@ -0,0 +1,7 @@
<template>
<router-view />
</template>
<script setup>
// App 根组件,路由视图入口
</script>

20
src/renderer/http/api.js Normal file
View File

@@ -0,0 +1,20 @@
import { getAction, postAction, deleteAction } from './manage.js'
import url, { getBaseUrl } from './url.js'
// 健康检查
export const getHealthAction = () => getAction(url.health)
// 会话
export const createSessionAction = (data) => postAction(url.session.create, data)
export const getSessionAction = (id) => getAction(url.session.detail(id))
export const listSessionsAction = () => getAction(url.session.list)
export const deleteSessionAction = (id) => deleteAction(url.session.delete(id))
// 消息
export const sendMessageAction = (sessionId, data) => postAction(url.message.send(sessionId), data)
export const listMessagesAction = (sessionId) => getAction(url.message.list(sessionId))
// SSE 事件流(返回 EventSource 实例,由调用方管理生命周期)
export function createEventSource() {
return new EventSource(`${getBaseUrl()}${url.event}`)
}

View File

@@ -0,0 +1,38 @@
import { getBaseUrl } from './url.js'
import { ElMessage } from 'element-plus'
async function request(path, options = {}) {
const { headers = {}, silent = false, ...rest } = options
const url = `${getBaseUrl()}${path}`
const config = {
headers: {
'Content-Type': 'application/json',
...headers,
},
...rest,
}
try {
const res = await fetch(url, config)
if (!res.ok) {
const msg = await res.text().catch(() => '')
const errMsg = `请求失败: ${res.status}${msg ? ' - ' + msg : ''}`
if (!silent) ElMessage.error(errMsg)
return Promise.reject(new Error(errMsg))
}
// 空响应
const text = await res.text()
if (!text) return Promise.resolve(null)
const data = JSON.parse(text)
return Promise.resolve(data)
} catch (err) {
if (!silent) ElMessage.error(err.message || '网络连接失败')
return Promise.reject(err)
}
}
export default request

View File

@@ -0,0 +1,26 @@
import request from './index.js'
export function getAction(url, params) {
const query = params ? '?' + new URLSearchParams(params).toString() : ''
return request(`${url}${query}`, { method: 'GET' })
}
export function postAction(url, data, headers = {}) {
return request(url, {
method: 'POST',
body: JSON.stringify(data),
headers,
})
}
export function putAction(url, data) {
return request(url, {
method: 'PUT',
body: JSON.stringify(data),
})
}
export function deleteAction(url, params) {
const query = params ? '?' + new URLSearchParams(params).toString() : ''
return request(`${url}${query}`, { method: 'DELETE' })
}

28
src/renderer/http/url.js Normal file
View File

@@ -0,0 +1,28 @@
// OpenCode 服务地址由主进程动态分配端口,通过 getBaseUrl() 获取
export function getBaseUrl() {
return window.__opencodeBaseUrl || 'http://127.0.0.1:4096'
}
const url = {
// 健康检查
health: '/global/health',
// 会话
session: {
create: '/session',
detail: (id) => `/session/${id}`,
list: '/session',
delete: (id) => `/session/${id}`,
},
// 消息
message: {
send: (sessionId) => `/session/${sessionId}/message`,
list: (sessionId) => `/session/${sessionId}/message`,
},
// SSE 事件流
event: '/event',
}
export default url

View File

@@ -0,0 +1,77 @@
<template>
<div class="flex h-screen w-screen overflow-hidden bg-gray-50">
<!-- 侧边栏 -->
<aside
:class="[
'flex flex-col bg-white border-r border-gray-200 transition-all duration-300',
appStore.collapsed ? 'w-16' : 'w-56',
]"
>
<!-- Logo -->
<div class="flex items-center h-14 px-4 border-b border-gray-200 shrink-0">
<el-icon class="text-blue-500 text-xl shrink-0"><Monitor /></el-icon>
<span v-if="!appStore.collapsed" class="ml-2 font-semibold text-gray-800 truncate">
{{ appStore.title }}
</span>
</div>
<!-- 导航菜单 -->
<el-menu
:default-active="$route.path"
:collapse="appStore.collapsed"
:collapse-transition="false"
router
class="flex-1 border-none"
>
<el-menu-item index="/">
<el-icon><House /></el-icon>
<template #title>首页</template>
</el-menu-item>
<el-menu-item index="/chat">
<el-icon><ChatDotRound /></el-icon>
<template #title>OpenCode 对话</template>
</el-menu-item>
</el-menu>
<!-- 折叠按钮 -->
<div class="p-3 border-t border-gray-200">
<el-button
:icon="appStore.collapsed ? Expand : Fold"
circle
size="small"
@click="appStore.toggleSidebar"
/>
</div>
</aside>
<!-- 主内容区 -->
<div class="flex flex-col flex-1 overflow-hidden">
<!-- 顶部栏 -->
<header class="flex items-center justify-between h-14 px-6 bg-white border-b border-gray-200 shrink-0">
<h1 class="text-base font-medium text-gray-700">{{ currentTitle }}</h1>
<div class="flex items-center gap-2">
<el-avatar :size="32" class="bg-blue-500">U</el-avatar>
</div>
</header>
<!-- 页面内容 -->
<main class="flex-1 overflow-hidden p-6">
<div class="h-full overflow-auto">
<router-view />
</div>
</main>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { useAppStore } from '@/stores/app';
import { House, Monitor, Expand, Fold, Edit, ChatDotRound } from '@element-plus/icons-vue';
const route = useRoute();
const appStore = useAppStore();
const currentTitle = computed(() => route.meta?.title || appStore.title);
</script>

21
src/renderer/main.js Normal file
View File

@@ -0,0 +1,21 @@
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import 'element-plus/dist/index.css';
import router from './router';
import App from './App.vue';
import './style.css';
const app = createApp(App);
// 注册所有 Element Plus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
app.use(createPinia());
app.use(router);
app.use(ElementPlus);
app.mount('#app');

View File

@@ -0,0 +1,30 @@
import { createRouter, createWebHashHistory } from 'vue-router';
const routes = [
{
path: '/',
component: () => import('@/layouts/DefaultLayout.vue'),
children: [
{
path: '',
name: 'Home',
component: () => import('@/views/home/HomeView.vue'),
meta: { title: '首页' },
},
{
path: '/chat',
name: 'Chat',
component: () => import('@/views/chat/ChatView.vue'),
meta: { title: 'OpenCode 对话' },
},
],
},
];
const router = createRouter({
// Electron 中使用 hash 模式
history: createWebHashHistory(),
routes,
});
export default router;

View File

@@ -0,0 +1,13 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useAppStore = defineStore('app', () => {
const title = ref('My App');
const collapsed = ref(false);
function toggleSidebar() {
collapsed.value = !collapsed.value;
}
return { title, collapsed, toggleSidebar };
});

185
src/renderer/style.css Normal file
View File

@@ -0,0 +1,185 @@
@import "tailwindcss";
/* =====================
shadcn CSS 变量 (light)
===================== */
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 5.9% 10%;
--radius: 0.5rem;
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
}
/* =====================
Element Plus 主题覆盖
===================== */
:root {
/* 主色 */
--el-color-primary: hsl(var(--primary));
--el-color-primary-light-3: hsl(240 5.9% 30%);
--el-color-primary-light-5: hsl(240 5.9% 50%);
--el-color-primary-light-7: hsl(240 5.9% 70%);
--el-color-primary-light-8: hsl(240 5.9% 80%);
--el-color-primary-light-9: hsl(240 4.8% 95.9%);
--el-color-primary-dark-2: hsl(240 5.9% 8%);
/* 危险色 */
--el-color-danger: hsl(var(--destructive));
/* 背景 & 文字 */
--el-bg-color: hsl(var(--background));
--el-bg-color-page: hsl(var(--background));
--el-bg-color-overlay: hsl(var(--popover));
--el-text-color-primary: hsl(var(--foreground));
--el-text-color-regular: hsl(var(--muted-foreground));
--el-text-color-secondary: hsl(var(--muted-foreground));
--el-text-color-placeholder: hsl(240 3.8% 60%);
/* 边框 */
--el-border-color: hsl(var(--border));
--el-border-color-light: hsl(var(--border));
--el-border-color-lighter: hsl(var(--border));
--el-border-color-extra-light: hsl(var(--border));
/* 圆角 */
--el-border-radius-base: var(--radius);
--el-border-radius-small: calc(var(--radius) - 2px);
--el-border-radius-round: 9999px;
/* 阴影 — shadcn 风格几乎无阴影 */
--el-box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
--el-box-shadow-light: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--el-box-shadow-lighter: none;
--el-box-shadow-dark: 0 4px 6px -1px rgb(0 0 0 / 0.1);
/* 字体 */
--el-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--el-font-size-base: 14px;
}
/* =====================
全局基础样式
===================== */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
border-color: hsl(var(--border));
}
html,
body,
#app {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: var(--el-font-family);
background-color: hsl(var(--background));
color: hsl(var(--foreground));
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* =====================
Element Plus 组件微调
===================== */
/* Card — 去掉默认阴影,用细边框代替 */
.el-card {
--el-card-border-color: hsl(var(--border));
--el-card-border-radius: var(--radius);
--el-card-padding: 1.25rem;
box-shadow: none !important;
border: 1px solid hsl(var(--border));
}
/* Button — 更简洁的样式 */
.el-button {
--el-button-border-radius: var(--radius);
font-weight: 500;
}
.el-button--primary {
--el-button-bg-color: hsl(var(--primary));
--el-button-border-color: hsl(var(--primary));
--el-button-text-color: hsl(var(--primary-foreground));
--el-button-hover-bg-color: hsl(240 5.9% 20%);
--el-button-hover-border-color: hsl(240 5.9% 20%);
}
/* Input */
.el-input__wrapper {
border-radius: var(--radius);
box-shadow: 0 0 0 1px hsl(var(--border)) !important;
}
.el-input__wrapper:hover,
.el-input__wrapper.is-focus {
box-shadow: 0 0 0 1px hsl(var(--ring)) !important;
}
/* Select */
.el-select .el-input__wrapper {
box-shadow: 0 0 0 1px hsl(var(--border)) !important;
}
/* Menu — 侧边栏去掉右侧边框 */
.el-menu {
--el-menu-border-color: transparent;
--el-menu-hover-bg-color: hsl(var(--accent));
--el-menu-active-color: hsl(var(--accent-foreground));
}
.el-menu-item.is-active {
background-color: hsl(var(--accent));
border-radius: calc(var(--radius) - 2px);
color: hsl(var(--accent-foreground));
}
/* Dropdown / Popover */
.el-popper {
border: 1px solid hsl(var(--border)) !important;
box-shadow: var(--el-box-shadow) !important;
border-radius: var(--radius) !important;
}

View File

@@ -0,0 +1,314 @@
<template>
<div class="chat-page">
<!-- 服务状态栏 -->
<div class="status-bar">
<div class="status-indicator">
<span class="dot" :class="serviceStatus" />
<span class="status-text">{{ statusText }}</span>
</div>
<div class="status-actions">
<el-button v-if="!isRunning" size="small" type="primary" :loading="isStarting" @click="startService">
启动服务
</el-button>
<el-button v-else size="small" type="danger" plain @click="stopService">
停止服务
</el-button>
</div>
</div>
<!-- 消息列表 -->
<div ref="messagesRef" class="messages">
<div v-if="messages.length === 0" class="empty-hint">
<el-icon :size="40" color="#c0c4cc"><ChatDotRound /></el-icon>
<p>启动服务后开始对话</p>
</div>
<div
v-for="msg in messages"
:key="msg.id"
class="bubble-wrap"
:class="msg.role"
>
<div class="bubble">
<pre class="bubble-text">{{ msg.text }}</pre>
</div>
</div>
</div>
<!-- 输入区 -->
<div class="input-area">
<el-input
v-model="inputText"
type="textarea"
:autosize="{ minRows: 2, maxRows: 5 }"
placeholder="输入消息Ctrl+Enter 发送"
:disabled="!isRunning || isSending"
resize="none"
@keydown.ctrl.enter.prevent="send"
/>
<el-button
type="primary"
:disabled="!isRunning || isSending || !inputText.trim()"
:loading="isSending"
@click="send"
>
发送
</el-button>
</div>
</div>
</template>
<script setup>
import { ref, computed, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import { createEventSource } from '@/http/api.js'
const isRunning = ref(false)
const isStarting = ref(false)
const isSending = ref(false)
const inputText = ref('')
const messages = ref([])
const messagesRef = ref(null)
const currentSessionId = ref(null)
let eventSource = null
const serviceStatus = computed(() => {
if (isStarting.value) return 'starting'
return isRunning.value ? 'running' : 'stopped'
})
const statusText = computed(() => {
if (isStarting.value) return '正在启动...'
return isRunning.value ? '服务运行中' : '服务未启动'
})
function scrollToBottom() {
nextTick(() => {
if (messagesRef.value) {
messagesRef.value.scrollTop = messagesRef.value.scrollHeight
}
})
}
function upsertAssistantBubble(msgId, text) {
const existing = messages.value.find(m => m.id === msgId)
if (existing) {
existing.text = text
} else {
messages.value.push({ id: msgId, role: 'assistant', text })
}
scrollToBottom()
}
function connectSSE() {
if (eventSource) eventSource.close()
eventSource = createEventSource()
eventSource.onmessage = (e) => {
try {
const data = JSON.parse(e.data)
const props = data.properties || {}
if (data.type === 'message.part.updated') {
const part = props.part
if (!part || part.type !== 'text') return
if (part.sessionID !== currentSessionId.value) return
upsertAssistantBubble(part.messageID, part.text || '')
}
if (data.type === 'message.completed') {
isSending.value = false
}
} catch (_) {}
}
eventSource.onerror = () => {
isSending.value = false
}
}
async function startService() {
isStarting.value = true
try {
const info = await window.opencode.start()
isRunning.value = info.running
// 更新 baseUrl 供 http 层使用
if (info.url) window.__opencodeBaseUrl = info.url
connectSSE()
ElMessage.success('服务已启动')
} catch (err) {
ElMessage.error(`启动失败: ${err.message}`)
} finally {
isStarting.value = false
}
}
async function stopService() {
await window.opencode.stop()
isRunning.value = false
currentSessionId.value = null
messages.value = []
if (eventSource) { eventSource.close(); eventSource = null }
ElMessage.info('服务已停止')
}
async function send() {
const text = inputText.value.trim()
if (!text || isSending.value) return
// 首次发送时创建会话
if (!currentSessionId.value) {
try {
const session = await window.opencode.createSession()
currentSessionId.value = session.id
} catch (err) {
ElMessage.error(`创建会话失败: ${err.message}`)
return
}
}
messages.value.push({ id: Date.now(), role: 'user', text })
inputText.value = ''
isSending.value = true
scrollToBottom()
try {
await window.opencode.sendMessage(currentSessionId.value, text)
} catch (err) {
ElMessage.error(`发送失败: ${err.message}`)
isSending.value = false
}
}
// 初始化时同步服务状态
window.opencode?.info().then((info) => {
isRunning.value = info.running
if (info.running) {
if (info.url) window.__opencodeBaseUrl = info.url
connectSSE()
}
}).catch(() => {})
onUnmounted(() => {
if (eventSource) eventSource.close()
})
</script>
<style scoped>
.chat-page {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
gap: 12px;
}
.status-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 16px;
background: #fff;
border-radius: 10px;
border: 1px solid #e4e7ed;
}
.status-indicator {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #606266;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.dot.stopped { background: #c0c4cc; }
.dot.starting { background: #e6a23c; animation: pulse 1s infinite; }
.dot.running { background: #67c23a; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.messages {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 8px 4px;
display: flex;
flex-direction: column;
gap: 12px;
}
.empty-hint {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
color: #c0c4cc;
font-size: 14px;
margin: auto;
}
.bubble-wrap {
display: flex;
}
.bubble-wrap.user { justify-content: flex-end; }
.bubble-wrap.assistant { justify-content: flex-start; }
.bubble {
max-width: 75%;
padding: 10px 14px;
border-radius: 12px;
font-size: 14px;
line-height: 1.6;
}
.bubble-wrap.user .bubble {
background: #409eff;
color: #fff;
border-bottom-right-radius: 4px;
}
.bubble-wrap.assistant .bubble {
background: #f0f2f5;
color: #303133;
border-bottom-left-radius: 4px;
}
.bubble-text {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
}
.input-area {
display: flex;
gap: 10px;
align-items: flex-end;
padding: 12px 16px;
background: #fff;
border-radius: 10px;
border: 1px solid #e4e7ed;
}
.input-area .el-textarea {
flex: 1;
}
.input-area .el-button {
height: 60px;
padding: 0 20px;
}
</style>

View File

@@ -0,0 +1,425 @@
<template>
<div class="home-container">
<!-- 顶部欢迎区 -->
<div class="welcome-section">
<div class="welcome-content">
<h1 class="welcome-title">
<span class="greeting">你好开发者</span>
<span class="emoji">👋</span>
</h1>
<p class="welcome-subtitle">准备好开始今天的创作了吗</p>
</div>
</div>
<!-- 统计卡片区 -->
<el-row :gutter="16" class="stats-row">
<el-col :span="8" v-for="(stat, index) in stats" :key="index">
<el-card class="stat-card" shadow="hover">
<div class="stat-content">
<div class="stat-icon" :style="{ background: stat.color + '20' }">
<el-icon :size="24" :color="stat.color">
<component :is="stat.icon" />
</el-icon>
</div>
<div class="stat-info">
<p class="stat-value">{{ stat.value }}</p>
<p class="stat-label">{{ stat.label }}</p>
</div>
</div>
<div class="stat-trend" :class="stat.trend > 0 ? 'up' : 'down'">
<el-icon><component :is="stat.trend > 0 ? Top : Bottom" /></el-icon>
<span>{{ Math.abs(stat.trend) }}% 较上周</span>
</div>
</el-card>
</el-col>
</el-row>
<!-- 主要内容区 -->
<el-row :gutter="16" class="main-content">
<!-- 快捷操作区 -->
<el-col :span="12">
<el-card class="action-card" shadow="hover">
<template #header>
<div class="card-header">
<el-icon><Grid /></el-icon>
<span>快捷操作</span>
</div>
</template>
<div class="action-grid">
<div
v-for="action in actions"
:key="action.label"
class="action-item"
@click="action.onClick"
>
<div class="action-icon" :style="{ background: action.color + '20' }">
<el-icon :size="28" :color="action.color">
<component :is="action.icon" />
</el-icon>
</div>
<span class="action-label">{{ action.label }}</span>
</div>
</div>
</el-card>
</el-col>
<!-- 最近文件区 -->
<el-col :span="12">
<el-card class="recent-card" shadow="hover">
<template #header>
<div class="card-header">
<el-icon><Clock /></el-icon>
<span>最近访问</span>
</div>
</template>
<el-scrollbar height="280px">
<div class="recent-list">
<div
v-for="(item, index) in recents"
:key="index"
class="recent-item"
@click="handleFileClick(item)"
>
<div class="file-icon">
<el-icon :size="20"><Document /></el-icon>
</div>
<div class="file-info">
<p class="file-name">{{ item.name }}</p>
<p class="file-path">{{ item.path }}</p>
</div>
<span class="file-time">{{ item.time }}</span>
</div>
</div>
</el-scrollbar>
</el-card>
</el-col>
</el-row>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import {
Document,
Plus,
FolderOpened,
Setting,
Upload,
Top,
Bottom,
Grid,
Clock,
Timer,
VideoCamera
} from '@element-plus/icons-vue'
const router = useRouter()
const stats = [
{
label: '文件总数',
value: '128',
trend: 12,
icon: Document,
color: '#409EFF'
},
{
label: '今日编辑',
value: '24',
trend: -3,
icon: Timer,
color: '#67C23A'
},
{
label: '运行次数',
value: '56',
trend: 8,
icon: VideoCamera,
color: '#E6A23C'
},
]
const actions = [
{
label: '新建文件',
icon: Plus,
color: '#409EFF',
onClick: () => router.push('/editor')
},
{
label: '打开文件',
icon: FolderOpened,
color: '#67C23A',
onClick: () => {}
},
{
label: '导入项目',
icon: Upload,
color: '#E6A23C',
onClick: () => {}
},
{
label: '系统设置',
icon: Setting,
color: '#F56C6C',
onClick: () => {}
},
]
const recents = [
{ name: 'main.js', path: '/src/main', time: '2 分钟前' },
{ name: 'App.vue', path: '/src/renderer', time: '1 小时前' },
{ name: 'index.css', path: '/src/renderer', time: '昨天' },
{ name: 'forge.config.js', path: '/', time: '3 天前' },
{ name: 'package.json', path: '/', time: '5 天前' },
]
const handleFileClick = (item) => {
console.log('点击文件:', item)
}
</script>
<style scoped>
.home-container {
padding: 24px;
height: 100%;
display: flex;
flex-direction: column;
gap: 20px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
/* 欢迎区样式 */
.welcome-section {
margin-bottom: 8px;
}
.welcome-content {
display: inline-block;
}
.welcome-title {
font-size: 28px;
font-weight: 600;
color: #303133;
margin: 0;
display: flex;
align-items: center;
gap: 12px;
}
.greeting {
background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.emoji {
font-size: 32px;
}
.welcome-subtitle {
font-size: 14px;
color: #909399;
margin: 8px 0 0 0;
}
/* 统计卡片区 */
.stats-row {
margin-bottom: 8px;
}
.stat-card {
border-radius: 12px;
border: none;
transition: all 0.3s ease;
}
.stat-card:hover {
transform: translateY(-4px);
}
.stat-content {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 12px;
}
.stat-icon {
width: 56px;
height: 56px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.stat-info {
flex: 1;
}
.stat-value {
font-size: 32px;
font-weight: 700;
color: #303133;
margin: 0;
line-height: 1;
}
.stat-label {
font-size: 13px;
color: #909399;
margin: 6px 0 0 0;
}
.stat-trend {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
padding-top: 8px;
border-top: 1px solid #f0f0f0;
}
.stat-trend.up {
color: #67C23A;
}
.stat-trend.down {
color: #F56C6C;
}
/* 主要内容区 */
.main-content {
flex: 1;
min-height: 0;
}
.action-card,
.recent-card {
border-radius: 12px;
border: none;
height: 100%;
}
.card-header {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
font-size: 15px;
color: #303133;
}
/* 快捷操作区 */
.action-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 16px;
padding: 8px 0;
}
.action-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 20px 16px;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
background: #f5f7fa;
}
.action-item:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.action-icon {
width: 56px;
height: 56px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
transition: all 0.3s ease;
}
.action-item:hover .action-icon {
transform: scale(1.1);
}
.action-label {
font-size: 13px;
color: #606266;
font-weight: 500;
text-align: center;
}
/* 最近文件区 */
.recent-list {
padding: 8px 0;
}
.recent-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 4px;
}
.recent-item:hover {
background: #f5f7fa;
}
.file-icon {
width: 40px;
height: 40px;
border-radius: 8px;
background: #ecf5ff;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: #409EFF;
}
.file-info {
flex: 1;
min-width: 0;
}
.file-name {
font-size: 14px;
color: #303133;
margin: 0;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-path {
font-size: 12px;
color: #909399;
margin: 4px 0 0 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-time {
font-size: 12px;
color: #C0C4CC;
flex-shrink: 0;
}
</style>