Compare commits

3 Commits

Author SHA1 Message Date
157c8914b0 feat(devices): 实现局域网mDNS设备发现功能 2026-04-10 10:48:01 +08:00
houakang
44c581dd44 chore: 将 husky 钩子中的 pnpm 替换为 npm 并更新 commitlint 配置格式
将 husky 的 pre-commit 和 commit-msg 钩子中的包管理器从 pnpm 改为 npm,以统一使用 npm 执行脚本
2026-04-10 10:42:39 +08:00
houakang
c738e638cf refactor: 统一代码风格并更新依赖配置
- 统一使用单引号替代双引号
- 移除不必要的分号
- 更新prettier配置使用更宽松的格式
- 添加eslint配置文件和相关依赖
- 更新package.json中的脚本和依赖版本
2026-04-10 10:39:41 +08:00
18 changed files with 1224 additions and 485 deletions

View File

@@ -1,11 +1,9 @@
{ {
"printWidth": 100, "$schema": "https://json.schemastore.org/prettierrc",
"tabWidth": 2, "semi": false,
"useTabs": false,
"semi": true,
"singleQuote": true, "singleQuote": true,
"trailingComma": "es5", "printWidth": 160,
"bracketSpacing": true, "objectWrap": "preserve",
"arrowParens": "always", "bracketSameLine": true,
"endOfLine": "lf" "trailingComma": "all"
} }

View File

@@ -1,4 +1,4 @@
module.exports = { export default {
extends: ['@commitlint/config-conventional'], extends: ['@commitlint/config-conventional'],
rules: { rules: {
'type-enum': [ 'type-enum': [
@@ -24,4 +24,4 @@ module.exports = {
'subject-full-stop': [2, 'never', '.'], 'subject-full-stop': [2, 'never', '.'],
'header-max-length': [2, 'always', 100], 'header-max-length': [2, 'always', 100],
}, },
}; }

106
eslint.config.js Normal file
View File

@@ -0,0 +1,106 @@
import { defineConfig, globalIgnores } from 'eslint/config'
import vitest from 'eslint-plugin-vitest'
import globals from 'globals'
import js from '@eslint/js'
import pluginVue from 'eslint-plugin-vue'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
export default defineConfig([
{
name: 'app/files-to-lint',
files: ['**/*.{js,mjs,jsx,vue}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**', '**/cypress/**', '**/public/**']),
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
// Electron globals
process: 'readonly',
__dirname: 'readonly',
// Vite globals
MAIN_WINDOW_VITE_DEV_SERVER_URL: 'readonly',
MAIN_WINDOW_VITE_NAME: 'readonly',
// Allow using Vue Composition API and <script setup> macros without explicit imports
// because unplugin-auto-import injects them at build time, while ESLint works on source text.
// Mark as read-only to prevent accidental reassignment warnings.
// Composition API
ref: 'readonly',
shallowRef: 'readonly',
computed: 'readonly',
reactive: 'readonly',
shallowReactive: 'readonly',
readonly: 'readonly',
unref: 'readonly',
toRef: 'readonly',
toRefs: 'readonly',
toRaw: 'readonly',
markRaw: 'readonly',
isRef: 'readonly',
isReactive: 'readonly',
isReadonly: 'readonly',
isProxy: 'readonly',
watch: 'readonly',
watchEffect: 'readonly',
watchPostEffect: 'readonly',
watchSyncEffect: 'readonly',
// Lifecycle
onMounted: 'readonly',
onUpdated: 'readonly',
onUnmounted: 'readonly',
onBeforeMount: 'readonly',
onBeforeUpdate: 'readonly',
onBeforeUnmount: 'readonly',
onActivated: 'readonly',
onDeactivated: 'readonly',
onErrorCaptured: 'readonly',
onRenderTracked: 'readonly',
onRenderTriggered: 'readonly',
// Misc
nextTick: 'readonly',
getCurrentInstance: 'readonly',
inject: 'readonly',
provide: 'readonly',
// Vue 3.5+ template ref helper
useTemplateRef: 'readonly',
// <script setup> compiler macros
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly',
withDefaults: 'readonly',
},
},
},
// Enable Vitest globals and rules for test files
{
name: 'app/tests-vitest',
files: ['tests/**/*.{test,spec}.{js,jsx,ts,tsx}'],
plugins: { vitest },
rules: {
// Apply Vitest recommended rules
...(vitest.configs?.recommended?.rules ?? {}),
},
languageOptions: {
// Register Vitest testing globals so ESLint doesn't flag them as undefined
globals: (vitest.environments && vitest.environments.env && vitest.environments.env.globals) || {
describe: 'readonly',
test: 'readonly',
it: 'readonly',
expect: 'readonly',
vi: 'readonly',
beforeAll: 'readonly',
afterAll: 'readonly',
beforeEach: 'readonly',
afterEach: 'readonly',
},
},
},
js.configs.recommended,
...pluginVue.configs['flat/essential'],
skipFormatting,
])

808
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,22 +5,22 @@
"description": "My Electron application description", "description": "My Electron application description",
"main": ".vite/build/main.js", "main": ".vite/build/main.js",
"private": true, "private": true,
"type": "module",
"scripts": { "scripts": {
"start": "electron-forge start", "start": "electron-forge start",
"package": "electron-forge package", "package": "electron-forge package",
"make": "electron-forge make", "make": "electron-forge make",
"publish": "electron-forge publish", "publish": "electron-forge publish",
"lint": "echo \"No linting configured\"", "lint": "eslint . --fix --cache",
"prepare": "husky", "prepare": "husky",
"format": "prettier --write .", "format": "prettier --write src/"
"format:check": "prettier --check ."
}, },
"keywords": [], "keywords": [],
"author": "houakang", "author": "houakang",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^20.5.0", "@commitlint/cli": "^20.1.0",
"@commitlint/config-conventional": "^20.5.0", "@commitlint/config-conventional": "^20.0.0",
"@electron-forge/cli": "^7.11.1", "@electron-forge/cli": "^7.11.1",
"@electron-forge/maker-deb": "^7.11.1", "@electron-forge/maker-deb": "^7.11.1",
"@electron-forge/maker-rpm": "^7.11.1", "@electron-forge/maker-rpm": "^7.11.1",
@@ -30,20 +30,25 @@
"@electron-forge/plugin-fuses": "^7.11.1", "@electron-forge/plugin-fuses": "^7.11.1",
"@electron-forge/plugin-vite": "^7.11.1", "@electron-forge/plugin-vite": "^7.11.1",
"@electron/fuses": "^1.8.0", "@electron/fuses": "^1.8.0",
"@eslint/js": "^9.37.0",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
"@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue": "^6.0.5",
"@vue/eslint-config-prettier": "^10.2.0",
"electron": "^41.2.0", "electron": "^41.2.0",
"eslint-config-prettier": "^10.1.8", "eslint": "^9.37.0",
"eslint-plugin-prettier": "^5.5.5", "eslint-plugin-vitest": "^0.5.4",
"eslint-plugin-vue": "~10.5.0",
"globals": "^16.4.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"lint-staged": "^16.4.0", "lint-staged": "^16.2.6",
"prettier": "3.8.1", "prettier": "3.6.2",
"tailwindcss": "^4.2.2", "tailwindcss": "^4.2.2",
"vite": "^5.4.21" "vite": "^5.4.21"
}, },
"dependencies": { "dependencies": {
"await-to-js": "^3.0.0", "await-to-js": "^3.0.0",
"axios": "^1.13.2", "axios": "^1.13.2",
"bonjour-service": "^1.3.0",
"electron-squirrel-startup": "^1.0.1", "electron-squirrel-startup": "^1.0.1",
"element-plus": "^2.13.6", "element-plus": "^2.13.6",
"pinia": "^3.0.4", "pinia": "^3.0.4",

View File

@@ -1,56 +0,0 @@
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.

View File

@@ -1,50 +1,57 @@
import { app, BrowserWindow, shell, ipcMain } from 'electron'; import { app, BrowserWindow, shell, ipcMain } from 'electron'
import path from 'node:path'; import path from 'node:path'
import fs from 'node:fs'; import fs from 'node:fs'
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'
import Bonjour from 'bonjour-service'
if (started) app.quit(); if (started) app.quit()
const bonjour = new Bonjour()
const devices = new Map()
// ========== OpenCode 服务管理 ========== // ========== OpenCode 服务管理 ==========
const DEFAULT_PORT = 4096; const DEFAULT_PORT = 4096
let opencodeProcess = null; let opencodeProcess = null
let opencodePort = null; let opencodePort = null
let opencodeStarting = null; let opencodeStarting = null
function isPortAvailable(port) { function isPortAvailable(port) {
return new Promise((resolve) => { return new Promise((resolve) => {
const server = net.createServer(); const server = net.createServer()
server.once('error', () => resolve(false)); server.once('error', () => resolve(false))
server.once('listening', () => server.close(() => resolve(true))); server.once('listening', () => server.close(() => resolve(true)))
server.listen(port, '127.0.0.1'); server.listen(port, '127.0.0.1')
}); })
} }
async function resolvePort() { async function resolvePort() {
let port = DEFAULT_PORT; let port = DEFAULT_PORT
while (!(await isPortAvailable(port))) { while (!(await isPortAvailable(port))) {
port++; port++
if (port > 65535) throw new Error('没有可用的端口'); if (port > 65535) throw new Error('没有可用的端口')
} }
return port; return port
} }
function waitForReady(port, timeout = 15000) { function waitForReady(port, timeout = 15000) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const start = Date.now(); const start = Date.now()
const check = () => { const check = () => {
const socket = net.createConnection({ port, host: '127.0.0.1' }); const socket = net.createConnection({ port, host: '127.0.0.1' })
socket.once('connect', () => { socket.end(); resolve(); }); socket.once('connect', () => {
socket.end()
resolve()
})
socket.once('error', () => { socket.once('error', () => {
socket.destroy(); socket.destroy()
if (Date.now() - start >= timeout) return reject(new Error('OpenCode 服务启动超时')); if (Date.now() - start >= timeout) return reject(new Error('OpenCode 服务启动超时'))
setTimeout(check, 300); setTimeout(check, 300)
}); })
}; }
check(); check()
}); })
} }
function buildInfo() { function buildInfo() {
@@ -52,112 +59,134 @@ function buildInfo() {
running: !!opencodeProcess, running: !!opencodeProcess,
port: opencodePort, port: opencodePort,
url: opencodePort ? `http://127.0.0.1:${opencodePort}` : null, url: opencodePort ? `http://127.0.0.1:${opencodePort}` : null,
}; }
} }
function buildEnv(exeDir) { function buildEnv(exeDir) {
const env = { ...process.env }; const env = { ...process.env }
for (const key of Object.keys(env)) { for (const key of Object.keys(env)) {
if (key.startsWith('npm_')) delete env[key]; if (key.startsWith('npm_')) delete env[key]
} }
env.INIT_CWD = exeDir; env.INIT_CWD = exeDir
env.PWD = exeDir; env.PWD = exeDir
return env; return env
} }
function getExePath() { function getExePath() {
// 开发模式__dirname = .vite/build往上两级到项目根 // 开发模式__dirname = .vite/build往上两级到项目根
// 打包模式:用 process.resourcesPath // 打包模式:用 process.resourcesPath
if (app.isPackaged) { if (app.isPackaged) {
return path.join(process.resourcesPath, 'opencode.exe'); return path.join(process.resourcesPath, 'opencode.exe')
} }
return path.join(__dirname, '..', '..', 'resources', 'windows', 'x64', 'opencode.exe'); return path.join(__dirname, '..', '..', 'resources', 'windows', 'x64', 'opencode.exe')
} }
async function startOpencode() { async function startOpencode() {
if (opencodeProcess) return buildInfo(); if (opencodeProcess) return buildInfo()
if (opencodeStarting) return opencodeStarting; if (opencodeStarting) return opencodeStarting
opencodeStarting = (async () => { opencodeStarting = (async () => {
const exePath = getExePath(); const exePath = getExePath()
console.log('[opencode] exe path:', exePath); console.log('[opencode] exe path:', exePath)
const exeDir = path.dirname(exePath); const exeDir = path.dirname(exePath)
await fs.promises.access(exePath, fs.constants.F_OK); await fs.promises.access(exePath, fs.constants.F_OK)
opencodePort = await resolvePort(); opencodePort = await resolvePort()
opencodeProcess = spawn(exePath, ['serve', '--port', String(opencodePort)], { opencodeProcess = spawn(exePath, ['serve', '--port', String(opencodePort)], {
cwd: exeDir, cwd: exeDir,
windowsHide: true, windowsHide: true,
env: buildEnv(exeDir), env: buildEnv(exeDir),
}); })
opencodeProcess.stdout?.on('data', (d) => console.log(`[opencode] ${d.toString().trim()}`)); opencodeProcess.stdout?.on('data', (d) => console.log(`[opencode] ${d.toString().trim()}`))
opencodeProcess.stderr?.on('data', (d) => console.error(`[opencode error] ${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('error', (e) => console.error('[opencode spawn error]', e))
opencodeProcess.once('close', (code) => { opencodeProcess.once('close', (code) => {
console.log(`[opencode exited] code=${code}`); console.log(`[opencode exited] code=${code}`)
opencodeProcess = null; opencodeProcess = null
opencodePort = null; opencodePort = null
opencodeStarting = null; opencodeStarting = null
}); })
await waitForReady(opencodePort); await waitForReady(opencodePort)
return buildInfo(); return buildInfo()
})(); })()
try { try {
return await opencodeStarting; return await opencodeStarting
} catch (err) { } catch (err) {
opencodeProcess?.kill(); opencodeProcess?.kill()
opencodeProcess = null; opencodeProcess = null
opencodePort = null; opencodePort = null
opencodeStarting = null; opencodeStarting = null
throw err; throw err
} }
} }
function stopOpencode() { function stopOpencode() {
opencodeProcess?.kill(); opencodeProcess?.kill()
opencodeProcess = null; opencodeProcess = null
opencodePort = null; opencodePort = null
opencodeStarting = null; opencodeStarting = null
} }
// ========== IPC Handlers ========== // ========== IPC Handlers ==========
function registerIpcHandlers() { function registerIpcHandlers() {
ipcMain.handle('opencode:start', () => startOpencode()); ipcMain.handle('opencode:start', () => startOpencode())
ipcMain.handle('opencode:stop', () => { stopOpencode(); return buildInfo(); }); ipcMain.handle('opencode:stop', () => {
ipcMain.handle('opencode:info', () => buildInfo()); stopOpencode()
ipcMain.handle('opencode:port', () => opencodePort); return buildInfo()
})
ipcMain.handle('opencode:info', () => buildInfo())
ipcMain.handle('opencode:port', () => opencodePort)
ipcMain.handle('opencode:health', async () => { ipcMain.handle('opencode:health', async () => {
if (!opencodePort) throw new Error('OpenCode 服务未启动'); if (!opencodePort) throw new Error('OpenCode 服务未启动')
const res = await fetch(`http://127.0.0.1:${opencodePort}/global/health`); const res = await fetch(`http://127.0.0.1:${opencodePort}/global/health`)
if (!res.ok) throw new Error(`健康检查失败: ${res.status}`); if (!res.ok) throw new Error(`健康检查失败: ${res.status}`)
return res.json(); return res.json()
}); })
ipcMain.handle('opencode:session:create', async (_e, data) => { ipcMain.handle('opencode:session:create', async (_e, data) => {
if (!opencodePort) throw new Error('OpenCode 服务未启动'); if (!opencodePort) throw new Error('OpenCode 服务未启动')
const res = await fetch(`http://127.0.0.1:${opencodePort}/session`, { const res = await fetch(`http://127.0.0.1:${opencodePort}/session`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data ?? {}), body: JSON.stringify(data ?? {}),
}); })
if (!res.ok) throw new Error(`创建会话失败: ${res.status}`); if (!res.ok) throw new Error(`创建会话失败: ${res.status}`)
return res.json(); return res.json()
}); })
ipcMain.handle('opencode:session:send', async (_e, sessionId, text) => { ipcMain.handle('opencode:session:send', async (_e, sessionId, text) => {
if (!opencodePort) throw new Error('OpenCode 服务未启动'); if (!opencodePort) throw new Error('OpenCode 服务未启动')
const res = await fetch(`http://127.0.0.1:${opencodePort}/session/${sessionId}/message`, { const res = await fetch(`http://127.0.0.1:${opencodePort}/session/${sessionId}/message`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text }] }), body: JSON.stringify({ parts: [{ type: 'text', text }] }),
}); })
if (!res.ok) throw new Error(`发送消息失败: ${res.status}`); if (!res.ok) throw new Error(`发送消息失败: ${res.status}`)
return res.json(); return res.json()
}); })
// ========== Bonjour 设备发现 IPC ==========
ipcMain.handle('get-devices', () => {
return Array.from(devices.values())
})
ipcMain.on('refresh-devices', () => {
// 重新扫描逻辑
// const allWindows = BrowserWindow.getAllWindows();
// const mainWindow = allWindows[0]; // 假设第一个是主窗口
// 停止并重新开始搜索
// 注意:这里需要访问 browser 实例,我们可以在 registerIpcHandlers 外层定义或在应用启动时初始化
if (global.bonjourBrowser) {
global.bonjourBrowser.stop()
devices.clear()
global.bonjourBrowser.start()
}
})
} }
// ========== 窗口 ========== // ========== 窗口 ==========
@@ -174,45 +203,67 @@ const createWindow = () => {
}, },
titleBarStyle: 'hiddenInset', titleBarStyle: 'hiddenInset',
show: false, show: false,
}); })
mainWindow.once('ready-to-show', () => mainWindow.show()); mainWindow.once('ready-to-show', () => mainWindow.show())
// Setup Bonjour discovery
const browser = bonjour.find({})
global.bonjourBrowser = browser
browser.on('up', (service) => {
console.log('Found device:', service.name)
const device = {
id: service.fqdn,
name: service.name,
type: service.type,
port: service.port,
addresses: service.addresses,
txt: service.txt,
host: service.host,
referer: service.referer,
}
devices.set(device.id, device)
mainWindow.webContents.send('device-found', device)
})
browser.on('down', (service) => {
console.log('Lost device:', service.name)
devices.delete(service.fqdn)
mainWindow.webContents.send('device-lost', service.fqdn)
})
mainWindow.webContents.setWindowOpenHandler(({ url }) => { mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url); shell.openExternal(url)
return { action: 'deny' }; return { action: 'deny' }
}); })
// 注入 baseUrl让渲染进程的 getBaseUrl() 能拿到正确端口 // 注入 baseUrl让渲染进程的 getBaseUrl() 能拿到正确端口
mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.on('did-finish-load', () => {
if (opencodePort) { if (opencodePort) {
mainWindow.webContents.executeJavaScript( mainWindow.webContents.executeJavaScript(`window.__opencodeBaseUrl = 'http://127.0.0.1:${opencodePort}'`)
`window.__opencodeBaseUrl = 'http://127.0.0.1:${opencodePort}'`
);
} }
}); })
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL)
} else { } else {
mainWindow.loadFile( mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`))
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`) }
);
} }
};
app.whenReady().then(() => { app.whenReady().then(() => {
registerIpcHandlers(); registerIpcHandlers()
createWindow(); createWindow()
app.on('activate', () => { app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow(); if (BrowserWindow.getAllWindows().length === 0) createWindow()
}); })
}); })
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
stopOpencode(); stopOpencode()
if (process.platform !== 'darwin') app.quit(); if (process.platform !== 'darwin') app.quit()
}); })
app.on('before-quit', () => stopOpencode()); app.on('before-quit', () => stopOpencode())

View File

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

View File

@@ -1,11 +1,17 @@
import { contextBridge, ipcRenderer } from 'electron'; import { contextBridge, ipcRenderer } from 'electron'
contextBridge.exposeInMainWorld('electronAPI', { contextBridge.exposeInMainWorld('electronAPI', {
// 通用 IPC保留原有 // 通用 IPC保留原有
send: (channel, data) => ipcRenderer.send(channel, data), send: (channel, data) => ipcRenderer.send(channel, data),
on: (channel, callback) => ipcRenderer.on(channel, (_event, ...args) => callback(...args)), on: (channel, callback) => ipcRenderer.on(channel, (_event, ...args) => callback(...args)),
invoke: (channel, data) => ipcRenderer.invoke(channel, data), invoke: (channel, data) => ipcRenderer.invoke(channel, data),
});
// Bonjour 设备发现 API
onDeviceFound: (callback) => ipcRenderer.on('device-found', (_event, value) => callback(value)),
onDeviceLost: (callback) => ipcRenderer.on('device-lost', (_event, value) => callback(value)),
getDevices: () => ipcRenderer.invoke('get-devices'),
refreshDevices: () => ipcRenderer.send('refresh-devices'),
})
contextBridge.exposeInMainWorld('opencode', { contextBridge.exposeInMainWorld('opencode', {
start: () => ipcRenderer.invoke('opencode:start'), start: () => ipcRenderer.invoke('opencode:start'),
@@ -15,4 +21,4 @@ contextBridge.exposeInMainWorld('opencode', {
health: () => ipcRenderer.invoke('opencode:health'), health: () => ipcRenderer.invoke('opencode:health'),
createSession: (data) => ipcRenderer.invoke('opencode:session:create', data), createSession: (data) => ipcRenderer.invoke('opencode:session:create', data),
sendMessage: (sessionId, text) => ipcRenderer.invoke('opencode:session:send', sessionId, text), sendMessage: (sessionId, text) => ipcRenderer.invoke('opencode:session:send', sessionId, text),
}); })

View File

@@ -26,8 +26,6 @@
* ``` * ```
*/ */
import './index.css'; import './index.css'
console.log( console.log('👋 This message is being logged by "renderer.js", included via Vite')
'👋 This message is being logged by "renderer.js", included via Vite',
);

View File

@@ -1,12 +1,7 @@
<template> <template>
<div class="flex h-screen w-screen overflow-hidden bg-gray-50"> <div class="flex h-screen w-screen overflow-hidden bg-gray-50">
<!-- 侧边栏 --> <!-- 侧边栏 -->
<aside <aside :class="['flex flex-col bg-white border-r border-gray-200 transition-all duration-300', appStore.collapsed ? 'w-16' : 'w-56']">
:class="[
'flex flex-col bg-white border-r border-gray-200 transition-all duration-300',
appStore.collapsed ? 'w-16' : 'w-56',
]"
>
<!-- Logo --> <!-- Logo -->
<div class="flex items-center h-14 px-4 border-b border-gray-200 shrink-0"> <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> <el-icon class="text-blue-500 text-xl shrink-0"><Monitor /></el-icon>
@@ -16,13 +11,7 @@
</div> </div>
<!-- 导航菜单 --> <!-- 导航菜单 -->
<el-menu <el-menu :default-active="$route.path" :collapse="appStore.collapsed" :collapse-transition="false" router class="flex-1 border-none">
:default-active="$route.path"
:collapse="appStore.collapsed"
:collapse-transition="false"
router
class="flex-1 border-none"
>
<el-menu-item index="/"> <el-menu-item index="/">
<el-icon><House /></el-icon> <el-icon><House /></el-icon>
<template #title>首页</template> <template #title>首页</template>
@@ -31,16 +20,15 @@
<el-icon><ChatDotRound /></el-icon> <el-icon><ChatDotRound /></el-icon>
<template #title>OpenCode 对话</template> <template #title>OpenCode 对话</template>
</el-menu-item> </el-menu-item>
<el-menu-item index="/devices">
<el-icon><Monitor /></el-icon>
<template #title>发现设备</template>
</el-menu-item>
</el-menu> </el-menu>
<!-- 折叠按钮 --> <!-- 折叠按钮 -->
<div class="p-3 border-t border-gray-200"> <div class="p-3 border-t border-gray-200">
<el-button <el-button :icon="appStore.collapsed ? Expand : Fold" circle size="small" @click="appStore.toggleSidebar" />
:icon="appStore.collapsed ? Expand : Fold"
circle
size="small"
@click="appStore.toggleSidebar"
/>
</div> </div>
</aside> </aside>
@@ -65,13 +53,13 @@
</template> </template>
<script setup> <script setup>
import { computed } from 'vue'; import { computed } from 'vue'
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'; import { useAppStore } from '@/stores/app'
import { House, Monitor, Expand, Fold, Edit, ChatDotRound } from '@element-plus/icons-vue'; import { House, Monitor, Expand, Fold, ChatDotRound } from '@element-plus/icons-vue'
const route = useRoute(); const route = useRoute()
const appStore = useAppStore(); const appStore = useAppStore()
const currentTitle = computed(() => route.meta?.title || appStore.title); const currentTitle = computed(() => route.meta?.title || appStore.title)
</script> </script>

View File

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

View File

@@ -1,4 +1,4 @@
import { createRouter, createWebHashHistory } from 'vue-router'; import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [ const routes = [
{ {
@@ -17,14 +17,20 @@ const routes = [
component: () => import('@/views/chat/ChatView.vue'), component: () => import('@/views/chat/ChatView.vue'),
meta: { title: 'OpenCode 对话' }, meta: { title: 'OpenCode 对话' },
}, },
{
path: '/devices',
name: 'Devices',
component: () => import('@/views/devices/DevicesView.vue'),
meta: { title: '发现设备' },
},
], ],
}, },
]; ]
const router = createRouter({ const router = createRouter({
// Electron 中使用 hash 模式 // Electron 中使用 hash 模式
history: createWebHashHistory(), history: createWebHashHistory(),
routes, routes,
}); })
export default router; export default router

View File

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

View File

@@ -1,4 +1,4 @@
@import "tailwindcss"; @import 'tailwindcss';
/* ===================== /* =====================
shadcn CSS 变量 (light) shadcn CSS 变量 (light)

View File

@@ -7,12 +7,8 @@
<span class="status-text">{{ statusText }}</span> <span class="status-text">{{ statusText }}</span>
</div> </div>
<div class="status-actions"> <div class="status-actions">
<el-button v-if="!isRunning" size="small" type="primary" :loading="isStarting" @click="startService"> <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>
</el-button>
<el-button v-else size="small" type="danger" plain @click="stopService">
停止服务
</el-button>
</div> </div>
</div> </div>
@@ -22,12 +18,7 @@
<el-icon :size="40" color="#c0c4cc"><ChatDotRound /></el-icon> <el-icon :size="40" color="#c0c4cc"><ChatDotRound /></el-icon>
<p>启动服务后开始对话</p> <p>启动服务后开始对话</p>
</div> </div>
<div <div v-for="msg in messages" :key="msg.id" class="bubble-wrap" :class="msg.role">
v-for="msg in messages"
:key="msg.id"
class="bubble-wrap"
:class="msg.role"
>
<div class="bubble"> <div class="bubble">
<pre class="bubble-text">{{ msg.text }}</pre> <pre class="bubble-text">{{ msg.text }}</pre>
</div> </div>
@@ -43,16 +34,8 @@
placeholder="输入消息Ctrl+Enter 发送" placeholder="输入消息Ctrl+Enter 发送"
:disabled="!isRunning || isSending" :disabled="!isRunning || isSending"
resize="none" resize="none"
@keydown.ctrl.enter.prevent="send" @keydown.ctrl.enter.prevent="send" />
/> <el-button type="primary" :disabled="!isRunning || isSending || !inputText.trim()" :loading="isSending" @click="send"> 发送 </el-button>
<el-button
type="primary"
:disabled="!isRunning || isSending || !inputText.trim()"
:loading="isSending"
@click="send"
>
发送
</el-button>
</div> </div>
</div> </div>
</template> </template>
@@ -91,7 +74,7 @@ function scrollToBottom() {
} }
function upsertAssistantBubble(msgId, text) { function upsertAssistantBubble(msgId, text) {
const existing = messages.value.find(m => m.id === msgId) const existing = messages.value.find((m) => m.id === msgId)
if (existing) { if (existing) {
existing.text = text existing.text = text
} else { } else {
@@ -119,7 +102,10 @@ function connectSSE() {
if (data.type === 'message.completed') { if (data.type === 'message.completed') {
isSending.value = false isSending.value = false
} }
} catch (_) {} } catch (_) {
console.error('解析 SSE 消息失败', _)
return
}
} }
eventSource.onerror = () => { eventSource.onerror = () => {
@@ -148,7 +134,10 @@ async function stopService() {
isRunning.value = false isRunning.value = false
currentSessionId.value = null currentSessionId.value = null
messages.value = [] messages.value = []
if (eventSource) { eventSource.close(); eventSource = null } if (eventSource) {
eventSource.close()
eventSource = null
}
ElMessage.info('服务已停止') ElMessage.info('服务已停止')
} }
@@ -181,13 +170,16 @@ async function send() {
} }
// 初始化时同步服务状态 // 初始化时同步服务状态
window.opencode?.info().then((info) => { window.opencode
?.info()
.then((info) => {
isRunning.value = info.running isRunning.value = info.running
if (info.running) { if (info.running) {
if (info.url) window.__opencodeBaseUrl = info.url if (info.url) window.__opencodeBaseUrl = info.url
connectSSE() connectSSE()
} }
}).catch(() => {}) })
.catch(() => {})
onUnmounted(() => { onUnmounted(() => {
if (eventSource) eventSource.close() if (eventSource) eventSource.close()
@@ -228,13 +220,25 @@ onUnmounted(() => {
flex-shrink: 0; flex-shrink: 0;
} }
.dot.stopped { background: #c0c4cc; } .dot.stopped {
.dot.starting { background: #e6a23c; animation: pulse 1s infinite; } background: #c0c4cc;
.dot.running { background: #67c23a; } }
.dot.starting {
background: #e6a23c;
animation: pulse 1s infinite;
}
.dot.running {
background: #67c23a;
}
@keyframes pulse { @keyframes pulse {
0%, 100% { opacity: 1; } 0%,
50% { opacity: 0.3; } 100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
} }
.messages { .messages {
@@ -263,8 +267,12 @@ onUnmounted(() => {
display: flex; display: flex;
} }
.bubble-wrap.user { justify-content: flex-end; } .bubble-wrap.user {
.bubble-wrap.assistant { justify-content: flex-start; } justify-content: flex-end;
}
.bubble-wrap.assistant {
justify-content: flex-start;
}
.bubble { .bubble {
max-width: 75%; max-width: 75%;

View File

@@ -0,0 +1,109 @@
<template>
<div class="h-full flex flex-col">
<div class="mb-4 flex justify-between items-center">
<div>
<h2 class="text-xl font-bold text-gray-800">发现设备</h2>
<p class="text-sm text-gray-500">局域网内已发现的 mDNS 设备</p>
</div>
<el-button type="primary" :icon="Refresh" @click="refreshDevices" :loading="loading"> 重新扫描 </el-button>
</div>
<div v-if="devices.length === 0" class="flex-1 flex items-center justify-center">
<el-empty description="未发现设备,正在扫描中..." />
</div>
<div v-else class="flex-1 overflow-auto">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<el-card v-for="device in devices" :key="device.id" shadow="hover" class="device-card">
<template #header>
<div class="flex items-center justify-between">
<span class="font-bold truncate" :title="device.name">{{ device.name }}</span>
<el-tag size="small">{{ device.type }}</el-tag>
</div>
</template>
<div class="space-y-2 text-sm">
<div class="flex items-start">
<span class="text-gray-400 w-16 shrink-0">地址:</span>
<span class="text-gray-700 break-all">{{ device.addresses.join(', ') }}</span>
</div>
<div class="flex items-center">
<span class="text-gray-400 w-16 shrink-0">端口:</span>
<span class="text-gray-700">{{ device.port }}</span>
</div>
<div class="flex items-center">
<span class="text-gray-400 w-16 shrink-0">主机名:</span>
<span class="text-gray-700 truncate" :title="device.host">{{ device.host }}</span>
</div>
<div v-if="Object.keys(device.txt || {}).length > 0" class="mt-2 pt-2 border-t border-gray-100">
<div class="text-xs font-semibold text-gray-500 mb-1">额外信息 (TXT):</div>
<div v-for="(val, key) in device.txt" :key="key" class="flex items-start text-xs">
<span class="text-gray-400 w-16 shrink-0">{{ key }}:</span>
<span class="text-gray-600 break-all">{{ val }}</span>
</div>
</div>
</div>
</el-card>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const devices = ref([])
const loading = ref(false)
const loadDevices = async () => {
try {
const list = await window.electronAPI.getDevices()
devices.value = list
} catch (err) {
console.error('Failed to get devices:', err)
}
}
const refreshDevices = () => {
loading.value = true
devices.value = []
window.electronAPI.refreshDevices()
setTimeout(() => {
loading.value = false
loadDevices()
ElMessage.success('刷新指令已发送')
}, 1000)
}
onMounted(() => {
loadDevices()
window.electronAPI.onDeviceFound((device) => {
const index = devices.value.findIndex((d) => d.id === device.id)
if (index === -1) {
devices.value.push(device)
} else {
devices.value[index] = device
}
})
window.electronAPI.onDeviceLost((deviceId) => {
devices.value = devices.value.filter((d) => d.id !== deviceId)
})
})
onUnmounted(() => {
// IPC 监听在渲染进程中可能需要清理,但在 Electron contextBridge 中
// 如果是简单的 `on` 监听,关闭页面通常会自动处理,或者这里需要实现更复杂的移除逻辑
})
</script>
<style scoped>
.device-card :deep(.el-card__header) {
padding: 10px 16px;
}
.device-card :deep(.el-card__body) {
padding: 12px 16px;
}
</style>

View File

@@ -46,12 +46,7 @@
</div> </div>
</template> </template>
<div class="action-grid"> <div class="action-grid">
<div <div v-for="action in actions" :key="action.label" class="action-item" @click="action.onClick">
v-for="action in actions"
:key="action.label"
class="action-item"
@click="action.onClick"
>
<div class="action-icon" :style="{ background: action.color + '20' }"> <div class="action-icon" :style="{ background: action.color + '20' }">
<el-icon :size="28" :color="action.color"> <el-icon :size="28" :color="action.color">
<component :is="action.icon" /> <component :is="action.icon" />
@@ -74,12 +69,7 @@
</template> </template>
<el-scrollbar height="280px"> <el-scrollbar height="280px">
<div class="recent-list"> <div class="recent-list">
<div <div v-for="(item, index) in recents" :key="index" class="recent-item" @click="handleFileClick(item)">
v-for="(item, index) in recents"
:key="index"
class="recent-item"
@click="handleFileClick(item)"
>
<div class="file-icon"> <div class="file-icon">
<el-icon :size="20"><Document /></el-icon> <el-icon :size="20"><Document /></el-icon>
</div> </div>
@@ -99,19 +89,7 @@
<script setup> <script setup>
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { import { Document, Plus, FolderOpened, Setting, Upload, Top, Bottom, Grid, Clock, Timer, VideoCamera } from '@element-plus/icons-vue'
Document,
Plus,
FolderOpened,
Setting,
Upload,
Top,
Bottom,
Grid,
Clock,
Timer,
VideoCamera
} from '@element-plus/icons-vue'
const router = useRouter() const router = useRouter()
@@ -121,21 +99,21 @@ const stats = [
value: '128', value: '128',
trend: 12, trend: 12,
icon: Document, icon: Document,
color: '#409EFF' color: '#409EFF',
}, },
{ {
label: '今日编辑', label: '今日编辑',
value: '24', value: '24',
trend: -3, trend: -3,
icon: Timer, icon: Timer,
color: '#67C23A' color: '#67C23A',
}, },
{ {
label: '运行次数', label: '运行次数',
value: '56', value: '56',
trend: 8, trend: 8,
icon: VideoCamera, icon: VideoCamera,
color: '#E6A23C' color: '#E6A23C',
}, },
] ]
@@ -144,25 +122,25 @@ const actions = [
label: '新建文件', label: '新建文件',
icon: Plus, icon: Plus,
color: '#409EFF', color: '#409EFF',
onClick: () => router.push('/editor') onClick: () => router.push('/editor'),
}, },
{ {
label: '打开文件', label: '打开文件',
icon: FolderOpened, icon: FolderOpened,
color: '#67C23A', color: '#67C23A',
onClick: () => {} onClick: () => {},
}, },
{ {
label: '导入项目', label: '导入项目',
icon: Upload, icon: Upload,
color: '#E6A23C', color: '#E6A23C',
onClick: () => {} onClick: () => {},
}, },
{ {
label: '系统设置', label: '系统设置',
icon: Setting, icon: Setting,
color: '#F56C6C', color: '#F56C6C',
onClick: () => {} onClick: () => {},
}, },
] ]
@@ -209,7 +187,7 @@ const handleFileClick = (item) => {
} }
.greeting { .greeting {
background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%); background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
-webkit-background-clip: text; -webkit-background-clip: text;
-webkit-text-fill-color: transparent; -webkit-text-fill-color: transparent;
background-clip: text; background-clip: text;
@@ -285,11 +263,11 @@ const handleFileClick = (item) => {
} }
.stat-trend.up { .stat-trend.up {
color: #67C23A; color: #67c23a;
} }
.stat-trend.down { .stat-trend.down {
color: #F56C6C; color: #f56c6c;
} }
/* 主要内容区 */ /* 主要内容区 */
@@ -390,7 +368,7 @@ const handleFileClick = (item) => {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
flex-shrink: 0; flex-shrink: 0;
color: #409EFF; color: #409eff;
} }
.file-info { .file-info {
@@ -419,7 +397,7 @@ const handleFileClick = (item) => {
.file-time { .file-time {
font-size: 12px; font-size: 12px;
color: #C0C4CC; color: #c0c4cc;
flex-shrink: 0; flex-shrink: 0;
} }
</style> </style>