Skip to content

Commit 104ab51

Browse files
committed
fix(desktop): fix sqlite disconnect warning issue
1 parent 7c1ac9e commit 104ab51

File tree

5 files changed

+74
-55
lines changed

5 files changed

+74
-55
lines changed

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
"db:migration:clean": "TS_NODE_PROJECT=tsconfig.commonjs.json ts-node ./node_modules/.bin/typeorm schema:drop -f ormconfig.ts",
3131
"db:diagram": "TS_NODE_PROJECT=tsconfig.commonjs.json ts-node ./node_modules/.bin/typeorm-uml ormconfig.ts -d ./src/database/database.png"
3232
},
33-
"main": "background.js",
3433
"engines": {
3534
"node": "18"
3635
},

src/background.ts

+23-11
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import 'reflect-metadata' // Required by TypoORM.
22
;('use strict')
33
import { app, protocol, BrowserWindow, ipcMain, shell, Menu } from 'electron'
44
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
5-
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
65
import { quitAndRenameLogger } from './utils/logger'
76
import { defaultWindowSize, restoreWindowState, saveWindowState } from './utils/windowStateManager'
87
import rebuildDatabase from './database/rebuildDatabase'
@@ -21,6 +20,7 @@ import ORMConfig from './database/database.config'
2120
import version from '@/version'
2221
import { initialize } from '@electron/remote/main'
2322
import { initMCPHandlers, cleanupMCPConnections } from './main/ai/mcp/MCPManager'
23+
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
2424

2525
declare const __static: string
2626

@@ -43,6 +43,9 @@ protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: tru
4343

4444
const { ConnectionInit, ConnectionDestroy } = useConnection()
4545

46+
// Flag to track if connections have been destroyed
47+
let connectionsDestroyed = false
48+
4649
function handleIpcMessages() {
4750
ipcMain.on('setting', (event: Electron.IpcMainEvent, ...args: any[]) => {
4851
event.sender.send('setting', ...args)
@@ -120,10 +123,16 @@ function handleIpcMessages() {
120123
function beforeAppQuit() {
121124
// close all log appender and rename log file with date
122125
quitAndRenameLogger()
123-
// close all SQLite connection
124-
ConnectionDestroy()
126+
127+
// close all SQLite connection - only if not already destroyed
128+
if (!connectionsDestroyed) {
129+
connectionsDestroyed = true
130+
ConnectionDestroy()
131+
}
132+
125133
// cleanup MCP connections
126134
cleanupMCPConnections()
135+
127136
// quit APP
128137
app.quit()
129138
}
@@ -246,14 +255,17 @@ async function createWindow() {
246255
// initialization and is ready to create browser windows.
247256
// Some APIs can only be used after this event occurs.
248257
app.on('ready', async () => {
249-
if (isDevelopment && !process.env.IS_TEST) {
250-
// Install Vue Devtools
251-
try {
252-
await installExtension(VUEJS_DEVTOOLS)
253-
} catch (e) {
254-
console.error('Vue Devtools failed to install:', e)
255-
}
256-
}
258+
// if (isDevelopment && !process.env.IS_TEST) {
259+
// // Install Vue Devtools - modified to handle errors better
260+
// try {
261+
// await installExtension(VUEJS_DEVTOOLS, {
262+
// loadExtensionOptions: { allowFileAccess: true },
263+
// })
264+
// } catch (e) {
265+
// console.error('Vue Devtools failed to install:', e)
266+
// // Continue without Vue Devtools if installation fails
267+
// }
268+
// }
257269
createWindow()
258270
})
259271

src/components/ai/Copilot.vue

+3-4
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ export default class Copilot extends Vue {
205205
const throttledScroll = throttle(() => this.scrollToBottom(), 100)
206206
207207
this.abortController = new AbortController()
208+
this.$log.info(`[Copilot] AI response stream started with provider: "${this.model}" from "${this.openAIAPIHost}"`)
208209
const { textStream } = streamText({
209210
model: getModelProvider({
210211
model: this.model,
@@ -226,8 +227,6 @@ export default class Copilot extends Vue {
226227
if (this.shouldProcessMCP) {
227228
const processedContent = await processMCPCalls(this.responseStreamText)
228229
responseMessage.content = processedContent
229-
// AI TOOL CALL RESULT
230-
console.log(processedContent)
231230
} else {
232231
responseMessage.content = this.responseStreamText
233232
}
@@ -372,7 +371,7 @@ export default class Copilot extends Vue {
372371
}
373372
@keyframes rightbarPop {
374373
from {
375-
right: -45%;
374+
right: -50%;
376375
}
377376
to {
378377
right: 0px;
@@ -382,7 +381,7 @@ export default class Copilot extends Vue {
382381
box-shadow: -2px 0px 8px 0px var(--color-shadow-leftlist);
383382
position: fixed;
384383
right: 0px;
385-
width: 45%;
384+
width: 50%;
386385
background: var(--color-bg-normal);
387386
border-radius: 0;
388387
top: 0;

src/database/useConnection.ts

+10-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,16 @@ const useConnection = () => {
2020
}
2121
async function ConnectionDestroy() {
2222
if (sqlConnection) {
23-
await sqlConnection.close()
23+
try {
24+
if (sqlConnection.isConnected) {
25+
await sqlConnection.close()
26+
}
27+
} catch (error) {
28+
console.error('[Database] Error closing database connection:', error)
29+
// Gracefully handle errors during connection close
30+
} finally {
31+
sqlConnection = undefined
32+
}
2433
}
2534
}
2635
return {

src/main/ai/mcp/MCPManager.ts

+38-38
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const activeClients: Map<string, MCPClient> = new Map()
1818
export function initMCPHandlers(): void {
1919
// Test connection to a server
2020
ipcMain.handle('mcp:test-connection', async (_, serverConfig: MCPServer, serverName: string) => {
21-
console.log(`Testing connection to MCP server: ${serverName}`)
21+
console.log(`[MCP] Testing connection to MCP server: ${serverName}`)
2222
try {
2323
const client = new MCPClient()
2424
const connected = await client.connectToServer(serverConfig)
@@ -60,16 +60,16 @@ export function initMCPHandlers(): void {
6060

6161
// Call a tool on a specific server
6262
ipcMain.handle('mcp:call-tool', async (_, serverName: string, toolName: string, toolArgs: any) => {
63-
console.log(`Calling tool ${toolName} on server ${serverName}`)
63+
console.log(`[MCP] Calling tool ${toolName} on server ${serverName}`)
6464

6565
try {
6666
const client = activeClients.get(serverName)
6767
if (!client) {
68-
// 如果服务器未连接,尝试自动连接
68+
// If server is not connected, try to auto-connect
6969
await autoConnectToServer(serverName)
7070
const reconnectedClient = activeClients.get(serverName)
7171
if (!reconnectedClient) {
72-
throw new Error(`No active connection to server: ${serverName} and auto-reconnect failed`)
72+
throw new Error(`[MCP] No active connection to server: ${serverName} and auto-reconnect failed`)
7373
}
7474

7575
const result = await reconnectedClient.callTool(toolName, toolArgs)
@@ -80,7 +80,7 @@ export function initMCPHandlers(): void {
8080
}
8181

8282
if (!client.isConnected()) {
83-
throw new Error(`Connection to server ${serverName} has been lost`)
83+
throw new Error(`[MCP] Connection to server ${serverName} has been lost`)
8484
}
8585

8686
const result = await client.callTool(toolName, toolArgs)
@@ -89,7 +89,7 @@ export function initMCPHandlers(): void {
8989
result,
9090
}
9191
} catch (error) {
92-
console.error(`Error calling tool ${toolName} on server ${serverName}:`, error)
92+
console.error(`[MCP] Error calling tool ${toolName} on server ${serverName}:`, error)
9393
return {
9494
success: false,
9595
message: error instanceof Error ? error.message : String(error),
@@ -99,7 +99,7 @@ export function initMCPHandlers(): void {
9999

100100
// Disconnect from a server
101101
ipcMain.handle('mcp:disconnect', async (_, serverName: string) => {
102-
console.log(`Disconnecting from MCP server: ${serverName}`)
102+
console.log(`[MCP] Disconnecting from MCP server: ${serverName}`)
103103

104104
try {
105105
const client = activeClients.get(serverName)
@@ -116,81 +116,81 @@ export function initMCPHandlers(): void {
116116
message: `No active connection to server: ${serverName}`,
117117
}
118118
} catch (error) {
119-
console.error(`Error disconnecting from MCP server: ${serverName}`, error)
119+
console.error(`[MCP] Error disconnecting from MCP server: ${serverName}`, error)
120120
return {
121121
success: false,
122122
message: error instanceof Error ? error.message : String(error),
123123
}
124124
}
125125
})
126126

127-
// 自动连接已启用的 MCP 服务器
127+
// Auto-connect to enabled MCP servers
128128
autoConnectToEnabledServers()
129129
}
130130

131131
/**
132-
* 自动连接到启用的 MCP 服务器
132+
* Automatically connect to enabled MCP servers
133133
*/
134134
async function autoConnectToEnabledServers(): Promise<void> {
135-
console.log('Checking for enabled MCP servers to auto-connect')
135+
console.log('[MCP] Checking for enabled MCP servers to auto-connect')
136136

137137
try {
138-
// 从本地存储中读取 MCP 配置
138+
// Read MCP configuration from local storage
139139
const Store = require('electron-store')
140140
const store = new Store()
141141

142-
// 检查 MCP 是否启用
142+
// Check if MCP is enabled
143143
const mcpEnabled = store.get('mcpEnabled')
144144
if (mcpEnabled !== 'true') {
145-
console.log('MCP is not enabled, skipping auto-connect')
145+
console.log('[MCP] MCP is not enabled, skipping auto-connect')
146146
return
147147
}
148148

149-
// 获取 MCP 配置
149+
// Get MCP configuration
150150
const mcpConfigStr = store.get('mcpConfig')
151151
if (!mcpConfigStr) {
152-
console.log('No MCP configuration found, skipping auto-connect')
152+
console.log('[MCP] No MCP configuration found, skipping auto-connect')
153153
return
154154
}
155155

156156
let mcpConfig
157157
try {
158158
mcpConfig = JSON.parse(mcpConfigStr)
159159
} catch (err) {
160-
console.error('Failed to parse MCP configuration:', err)
160+
console.error('[MCP] Failed to parse MCP configuration:', err)
161161
return
162162
}
163163

164164
if (!mcpConfig.mcpServers) {
165-
console.log('No MCP servers configured, skipping auto-connect')
165+
console.log('[MCP] No MCP servers configured, skipping auto-connect')
166166
return
167167
}
168168

169-
// 连接所有启用的服务器
169+
// Connect to all enabled servers
170170
for (const [serverName, serverConfig] of Object.entries(mcpConfig.mcpServers)) {
171171
const serverEnabled = store.get(`mcpServerEnabled:${serverName}`)
172172
if (serverEnabled === 'true') {
173173
await autoConnectToServer(serverName, serverConfig as MCPServer)
174174
}
175175
}
176176

177-
console.log(`Auto-connected to ${activeClients.size} MCP servers`)
177+
console.log(`[MCP] Auto-connected to ${activeClients.size} MCP servers`)
178178
} catch (error) {
179-
console.error('Error during MCP auto-connect:', error)
179+
console.error('[MCP] Error during MCP auto-connect:', error)
180180
}
181181
}
182182

183183
/**
184-
* 自动连接到指定的 MCP 服务器
184+
* Automatically connect to a specific MCP server
185185
*
186-
* @param serverName 服务器名称
187-
* @param serverConfig 服务器配置(可选)
186+
* @param serverName Server name
187+
* @param serverConfig Server configuration (optional)
188188
*/
189189
async function autoConnectToServer(serverName: string, serverConfig?: MCPServer): Promise<boolean> {
190-
console.log(`Auto-connecting to MCP server: ${serverName}`)
190+
console.log(`[MCP] Auto-connecting to MCP server: ${serverName}`)
191191

192192
try {
193-
// 如果没有提供服务器配置,从存储中获取
193+
// If server configuration is not provided, get it from storage
194194
if (!serverConfig) {
195195
const Store = require('electron-store')
196196
const store = new Store()
@@ -205,35 +205,35 @@ async function autoConnectToServer(serverName: string, serverConfig?: MCPServer)
205205
serverConfig = mcpConfig.mcpServers[serverName] as MCPServer
206206

207207
if (!serverConfig) {
208-
console.error(`Server configuration for ${serverName} not found`)
208+
console.error(`[MCP] Server configuration for ${serverName} not found`)
209209
return false
210210
}
211211
} catch (err) {
212-
console.error('Failed to parse MCP configuration:', err)
212+
console.error('[MCP] Failed to parse MCP configuration:', err)
213213
return false
214214
}
215215
}
216216

217-
// 检查是否已经有连接
217+
// Check if connection already exists
218218
if (activeClients.has(serverName)) {
219219
const existingClient = activeClients.get(serverName)
220220
if (existingClient && existingClient.isConnected()) {
221-
console.log(`Server ${serverName} is already connected`)
221+
console.log(`[MCP] Server ${serverName} is already connected`)
222222
return true
223223
}
224224

225-
// 如果存在但断开连接,先清理
225+
// If exists but disconnected, clean up first
226226
if (existingClient) {
227227
try {
228228
await existingClient.disconnect()
229229
} catch (err) {
230-
console.error(`Error disconnecting existing client for ${serverName}:`, err)
230+
console.error(`[MCP] Error disconnecting existing client for ${serverName}:`, err)
231231
}
232232
activeClients.delete(serverName)
233233
}
234234
}
235235

236-
// 创建并连接新客户端
236+
// Create and connect new client
237237
const client = new MCPClient()
238238
const connected = await client.connectToServer(serverConfig)
239239

@@ -245,11 +245,11 @@ async function autoConnectToServer(serverName: string, serverConfig?: MCPServer)
245245
activeClients.set(serverName, client)
246246
return true
247247
} else {
248-
console.error(`Failed to connect to MCP server: ${serverName}`)
248+
console.error(`[MCP] Failed to connect to MCP server: ${serverName}`)
249249
return false
250250
}
251251
} catch (error) {
252-
console.error(`Error auto-connecting to MCP server ${serverName}:`, error)
252+
console.error(`[MCP] Error auto-connecting to MCP server ${serverName}:`, error)
253253
return false
254254
}
255255
}
@@ -258,14 +258,14 @@ async function autoConnectToServer(serverName: string, serverConfig?: MCPServer)
258258
* Clean up all active connections
259259
*/
260260
export async function cleanupMCPConnections(): Promise<void> {
261-
console.log(`Cleaning up ${activeClients.size} MCP connections`)
261+
console.log(`[MCP] Cleaning up ${activeClients.size} MCP connections`)
262262

263263
for (const [name, client] of activeClients.entries()) {
264264
try {
265265
await client.disconnect()
266-
console.log(`Disconnected from MCP server: ${name}`)
266+
console.log(`[MCP] Disconnected from MCP server: ${name}`)
267267
} catch (error) {
268-
console.error(`Error disconnecting from MCP server: ${name}`, error)
268+
console.error(`[MCP] Error disconnecting from MCP server: ${name}`, error)
269269
}
270270
}
271271

0 commit comments

Comments
 (0)