🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: refactor implement for desktop
Innei27f101f51e5e
diff --git a/packages/database/package.json b/packages/database/package.jsonindex 0383b902756..3422a13688f 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -14,6 +14,7 @@"test:server-db": "vitest run --config vitest.config.server.mts"},"dependencies": {+ "@lobechat/builtin-agents": "workspace:*","@lobechat/const": "workspace:*","@lobechat/types": "workspace:*","@lobechat/utils": "workspace:*",diff --git a/packages/database/src/core/db-adaptor.ts b/packages/database/src/core/db-adaptor.tsindex 1f1e184edf7..8972a0d031b 100644--- a/packages/database/src/core/db-adaptor.ts+++ b/packages/database/src/core/db-adaptor.ts@@ -1,7 +1,4 @@-import { isDesktop } from '@lobechat/const';-import { LobeChatDatabase } from '../type';-import { getPgliteInstance } from './electron';import { getDBInstance } from './web-server';/**@@ -16,7 +13,7 @@ export const getServerDB = async (): Promise<LobeChatDatabase> => {try {// Select the appropriate database instance based on the environment- cachedDB = isDesktop ? await getPgliteInstance() : getDBInstance();+ cachedDB = getDBInstance();return cachedDB;} catch (error) {console.error('❌ Failed to initialize database:', error);diff --git a/packages/database/src/core/electron.ts b/packages/database/src/core/electron.tsdeleted file mode 100644index 207248573e5..00000000000--- a/packages/database/src/core/electron.ts+++ /dev/null@@ -1,317 +0,0 @@-import { PGlite } from '@electric-sql/pglite';-import { vector } from '@electric-sql/pglite/vector';-import type { MigrationTableItem } from '@lobechat/types';-import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';-import fs from 'node:fs';-import { Md5 } from 'ts-md5';--import { electronIpcClient } from '@/server/modules/ElectronIPCClient';--import { DrizzleMigrationModel } from '../models/drizzleMigration';-import * as schema from '../schemas';-import { LobeChatDatabase } from '../type';-import migrations from './migrations.json';--// Global object for instance management-interface LobeGlobal {- pgDB?: LobeChatDatabase;- pgDBInitPromise?: Promise<LobeChatDatabase>;- pgDBLock?: {- acquired: boolean;- lockPath: string;- };-}--// Ensure globalThis has our namespace-declare global {- // eslint-disable-next-line no-var- var __LOBE__: LobeGlobal;-}--if (!globalThis.__LOBE__) {- globalThis.__LOBE__ = {};-}--/**- * Attempt to create a file lock to ensure singleton pattern- * Returns true if lock acquired successfully, false if another instance is already running- */-const acquireLock = async (dbPath: string): Promise<boolean> => {- try {- // Database lock file path- const lockPath = `${dbPath}.lock`;-- // Attempt to create lock file- if (!fs.existsSync(lockPath)) {- // Create lock file and write current process ID- fs.writeFileSync(lockPath, process.pid.toString(), 'utf8');-- // Save lock information to global object- if (!globalThis.__LOBE__.pgDBLock) {- globalThis.__LOBE__.pgDBLock = {- acquired: true,- lockPath,- };- }-- console.log(`✅ Successfully acquired database lock: ${lockPath}`);- return true;- }-- // Check if lock file has expired (not updated for over 5 minutes)- const stats = fs.statSync(lockPath);- const currentTime = Date.now();- const modifiedTime = stats.mtime.getTime();-- // If lock file hasn't been updated for over 5 minutes, consider it expired- if (currentTime - modifiedTime > 5 * 60 * 1000) {- // Delete expired lock file- fs.unlinkSync(lockPath);- // Recreate lock file- fs.writeFileSync(lockPath, process.pid.toString(), 'utf8');-- // Save lock information to global object- if (!globalThis.__LOBE__.pgDBLock) {- globalThis.__LOBE__.pgDBLock = {- acquired: true,- lockPath,- };- }-- console.log(`✅ Removed stale lock and acquired new lock: ${lockPath}`);- return true;- }-- console.warn(`⚠️ Another process has already locked the database: ${lockPath}`);- return false;- } catch (error) {- console.error('❌ Failed to acquire database lock:', error);- return false;- }-};--/**- * Release file lock- */-const releaseLock = () => {- if (globalThis.__LOBE__.pgDBLock?.acquired && globalThis.__LOBE__.pgDBLock.lockPath) {- try {- fs.unlinkSync(globalThis.__LOBE__.pgDBLock.lockPath);- globalThis.__LOBE__.pgDBLock.acquired = false;- console.log(`✅ Released database lock: ${globalThis.__LOBE__.pgDBLock.lockPath}`);- } catch (error) {- console.error('❌ Failed to release database lock:', error);- }- }-};--// Release lock on process exit-process.on('exit', releaseLock);-process.on('SIGINT', () => {- releaseLock();- process.exit(0);-});--process.on('uncaughtException', (error) => {- // ignore ECONNRESET error- if ((error as any).code === 'ECONNRESET') return;-- console.error('Uncaught exception:', error);- releaseLock();-});--const migrateDatabase = async (db: LobeChatDatabase): Promise<void> => {- try {- let hash: string | undefined;- const cacheHash = await electronIpcClient.getDatabaseSchemaHash();-- hash = Md5.hashStr(JSON.stringify(migrations));-- console.log('schemaHash:', hash);-- // If hash is the same, check if all tables exist- if (hash === cacheHash) {- try {- const drizzleMigration = new DrizzleMigrationModel(db);-- // Check if tables exist in the database- const tableCount = await drizzleMigration.getTableCounts();-- // If table count is greater than 0, assume database is properly initialized- if (tableCount > 0) {- console.log('✅ Electron DB schema already synced');- return;- }- } catch (error) {- console.warn('Error checking table existence, proceeding with migration:');- console.warn(error);- }- }-- const start = Date.now();- console.log('🚀 Starting Electron DB migration...');-- try {- // Execute migration- // @ts-expect-error- await db.dialect.migrate(migrations, db.session, {});-- await electronIpcClient.setDatabaseSchemaHash(hash);-- console.info(`✅ Electron DB migration success, took ${Date.now() - start}ms`);- } catch (error) {- console.error('❌ Electron database schema migration failed', error);-- // Attempt to query migration table data- let migrationsTableData: MigrationTableItem[] = [];- try {- // Attempt to query migration table- const drizzleMigration = new DrizzleMigrationModel(db);- migrationsTableData = await drizzleMigration.getMigrationList();- } catch (queryError) {- console.error('Failed to query migrations table:', queryError);- }-- throw {- error: error as Error,- migrationTableItems: migrationsTableData,- };- }- } catch (error) {- console.error('❌ Electron database migration failed:', error);- throw error;- }-};--/**- * Check if there's an active database instance and attempt to close it if exists- */-const checkAndCleanupExistingInstance = async () => {- if (globalThis.__LOBE__.pgDB) {- try {- // Attempt to close existing PGlite instance (if client has close method)- // @ts-expect-error- const client = globalThis.__LOBE__.pgDB?.dialect?.client;-- if (client && typeof client.close === 'function') {- await client.close();- console.log('✅ Successfully closed previous PGlite instance');- }-- // Reset global reference- globalThis.__LOBE__.pgDB = undefined;- } catch (error) {- console.error('❌ Failed to close previous PGlite instance:', error);- // Continue execution and create new instance- }- }-};--let isInitializing = false;--export const getPgliteInstance = async (): Promise<LobeChatDatabase> => {- try {- console.log(- 'Getting PGlite instance, state:',- JSON.stringify({- hasExistingDB: !!globalThis.__LOBE__.pgDB,- hasPromise: !!globalThis.__LOBE__.pgDBInitPromise,- isInitializing,- }),- );-- // Already initialized, return instance directly- if (globalThis.__LOBE__.pgDB) return globalThis.__LOBE__.pgDB;-- // Initialization promise in progress, wait for it to complete- if (globalThis.__LOBE__.pgDBInitPromise) {- console.log('Waiting for existing initialization promise to complete');- return globalThis.__LOBE__.pgDBInitPromise;- }-- // Prevent race conditions from multiple calls- if (isInitializing) {- console.log('Already initializing, waiting for result');- // Create new Promise to wait for initialization to complete- return new Promise((resolve, reject) => {- const checkInterval = setInterval(() => {- if (globalThis.__LOBE__.pgDB) {- clearInterval(checkInterval);- resolve(globalThis.__LOBE__.pgDB);- } else if (!isInitializing) {- clearInterval(checkInterval);- reject(new Error('Initialization failed or was canceled'));- }- }, 100);- });- }-- isInitializing = true;-- // Create and save initialization Promise- globalThis.__LOBE__.pgDBInitPromise = (async () => {- // Check again in case another call succeeded during wait- if (globalThis.__LOBE__.pgDB) return globalThis.__LOBE__.pgDB;-- // Get database path first- let dbPath: string = '';- try {- dbPath = await electronIpcClient.getDatabasePath();- } catch {- /* empty */- }-- console.log('Database path:', dbPath);- try {- // Attempt to acquire database lock- const lockAcquired = await acquireLock(dbPath);- if (!lockAcquired) {- throw new Error('Cannot acquire database lock. Another instance might be using it.');- }-- // Check and cleanup any existing old instances- await checkAndCleanupExistingInstance();-- // Create new PGlite instance- console.log('Creating new PGlite instance');- const client = new PGlite(dbPath, {- extensions: { vector },- // Add options to improve stability- relaxedDurability: true,- });-- // Wait for database to be ready- await client.waitReady;- console.log('PGlite state:', client.ready);-- // Create Drizzle database instance- const db = pgliteDrizzle({ client, schema }) as unknown as LobeChatDatabase;-- // Execute migration- await migrateDatabase(db);-- // Save instance reference- globalThis.__LOBE__.pgDB = db;-- console.log('✅ PGlite instance successfully initialized');-- return db;- } catch (error) {- console.error('❌ Failed to initialize PGlite instance:', error);- // Clear initialization Promise to allow retry next time- globalThis.__LOBE__.pgDBInitPromise = undefined;- // Release potentially acquired lock- releaseLock();- throw error;- } finally {- isInitializing = false;- }- })();-- return globalThis.__LOBE__.pgDBInitPromise;- } catch (error) {- console.error('❌ Unexpected error in getPgliteInstance:', error);- isInitializing = false;- throw error;- }-};diff --git a/packages/desktop-bridge/package.json b/packages/desktop-bridge/package.jsonnew file mode 100644index 00000000000..53efd704ac4--- /dev/null+++ b/packages/desktop-bridge/package.json@@ -0,0 +1,10 @@+{+ "name": "@lobechat/desktop-bridge",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts",+ "types": "./src/index.ts"+}diff --git a/packages/desktop-bridge/src/index.ts b/packages/desktop-bridge/src/index.tsnew file mode 100644index 00000000000..7d3b730ec4e--- /dev/null+++ b/packages/desktop-bridge/src/index.ts@@ -0,0 +1,11 @@+// Shared routing/locale utilities for desktop and web (centralized here)+export {+ DEFAULT_LANG,+ DEFAULT_VARIANTS,+ type IRouteVariants,+ LOBE_LOCALE_COOKIE,+ LOBE_THEME_APPEARANCE,+ type Locales,+ locales,+ RouteVariants,+} from './routeVariants';diff --git a/packages/desktop-bridge/src/routeVariants.ts b/packages/desktop-bridge/src/routeVariants.tsnew file mode 100644index 00000000000..59ce41bf78b--- /dev/null+++ b/packages/desktop-bridge/src/routeVariants.ts@@ -0,0 +1,75 @@+// Shared route variants utilities for desktop and web builds++export const LOBE_LOCALE_COOKIE = 'LOBE_LOCALE';+export const LOBE_THEME_APPEARANCE = 'LOBE_THEME_APPEARANCE';+export const DEFAULT_LANG = 'en-US';++// Supported locales (keep aligned with web resources)+export const locales = [+ 'ar',+ 'bg-BG',+ 'de-DE',+ 'en-US',+ 'es-ES',+ 'fr-FR',+ 'ja-JP',+ 'ko-KR',+ 'pt-BR',+ 'ru-RU',+ 'tr-TR',+ 'zh-CN',+ 'zh-TW',+ 'vi-VN',+ 'fa-IR',+ 'it-IT',+ 'pl-PL',+ 'nl-NL',+] as const;++export type Locales = (typeof locales)[number];++export interface IRouteVariants {+ isMobile: boolean;+ locale: Locales;+ neutralColor?: string;+ primaryColor?: string;+ theme: 'dark' | 'light';+}++const SUPPORTED_THEMES = ['dark', 'light'] as const;++export const DEFAULT_VARIANTS: IRouteVariants = {+ isMobile: false,+ locale: DEFAULT_LANG,+ theme: 'light',+};++const SPLITTER = '__';++export class RouteVariants {+ static serializeVariants = (variants: IRouteVariants): string =>+ [variants.locale, Number(variants.isMobile), variants.theme].join(SPLITTER);++ static deserializeVariants = (serialized: string): IRouteVariants => {+ try {+ const [locale, isMobile, theme] = serialized.split(SPLITTER);++ return {+ isMobile: isMobile === '1',+ locale: RouteVariants.isValidLocale(locale) ? (locale as Locales) : DEFAULT_VARIANTS.locale,+ theme: RouteVariants.isValidTheme(theme) ? (theme as any) : DEFAULT_VARIANTS.theme,+ };+ } catch {+ return { ...DEFAULT_VARIANTS };+ }+ };++ static createVariants = (options: Partial<IRouteVariants> = {}): IRouteVariants => ({+ ...DEFAULT_VARIANTS,+ ...options,+ });++ private static isValidLocale = (locale: string): boolean => locales.includes(locale as any);++ private static isValidTheme = (theme: string): boolean => SUPPORTED_THEMES.includes(theme as any);+}diff --git a/packages/electron-client-ipc/src/events/index.ts b/packages/electron-client-ipc/src/events/index.tsindex 9682fdd1474..7340677d970 100644--- a/packages/electron-client-ipc/src/events/index.ts+++ b/packages/electron-client-ipc/src/events/index.ts@@ -1,50 +1,17 @@-import { LocalSystemDispatchEvents } from './localSystem';-import { MenuDispatchEvents } from './menu';-import { NotificationDispatchEvents } from './notification';-import { ProtocolBroadcastEvents, ProtocolDispatchEvents } from './protocol';-import {-- RemoteServerBroadcastEvents,- RemoteServerDispatchEvents,-} from './remoteServer';-import { DesktopSettingsDispatchEvents } from './settings';-import { ShortcutDispatchEvents } from './shortcut';-import { SystemBroadcastEvents, SystemDispatchEvents } from './system';-import { TrayDispatchEvents } from './tray';-import { AutoUpdateBroadcastEvents, AutoUpdateDispatchEvents } from './update';-import { UploadFilesDispatchEvents } from './upload';-import { WindowsDispatchEvents } from './windows';--/**- * renderer -> main dispatch events- */-// eslint-disable-next-line @typescript-eslint/no-empty-interface-export interface ClientDispatchEvents- extends WindowsDispatchEvents,- SystemDispatchEvents,- MenuDispatchEvents,- LocalSystemDispatchEvents,- AutoUpdateDispatchEvents,- ShortcutDispatchEvents,- RemoteServerDispatchEvents,- UploadFilesDispatchEvents,- TrayDispatchEvents,- DesktopSettingsDispatchEvents,- NotificationDispatchEvents,- ProtocolDispatchEvents {}--export type ClientDispatchEventKey = keyof ClientDispatchEvents;--export type ClientEventReturnType<T extends ClientDispatchEventKey> = ReturnType<- ClientDispatchEvents[T]->;+import { NavigationBroadcastEvents } from './navigation';+import { ProtocolBroadcastEvents } from './protocol';+import { RemoteServerBroadcastEvents } from './remoteServer';+import { SystemBroadcastEvents } from './system';+import { AutoUpdateBroadcastEvents } from './update';/*** main -> render broadcast events*/// eslint-disable-next-line @typescript-eslint/no-empty-interfaceexport interface MainBroadcastEvents- extends AutoUpdateBroadcastEvents,+ extends+ AutoUpdateBroadcastEvents,+ NavigationBroadcastEvents,RemoteServerBroadcastEvents,SystemBroadcastEvents,ProtocolBroadcastEvents {}diff --git a/packages/electron-client-ipc/src/events/localSystem.ts b/packages/electron-client-ipc/src/events/localSystem.tsdeleted file mode 100644index 6da4fe436fd..00000000000--- a/packages/electron-client-ipc/src/events/localSystem.ts+++ /dev/null@@ -1,49 +0,0 @@-import {- EditLocalFileParams,- EditLocalFileResult,- GetCommandOutputParams,- GetCommandOutputResult,- GlobFilesParams,- GlobFilesResult,- GrepContentParams,- GrepContentResult,- KillCommandParams,- KillCommandResult,- ListLocalFileParams,- LocalFileItem,- LocalMoveFilesResultItem,- LocalReadFileParams,- LocalReadFileResult,- LocalReadFilesParams,- LocalSearchFilesParams,- MoveLocalFilesParams,- OpenLocalFileParams,- OpenLocalFolderParams,- RenameLocalFileParams,- RenameLocalFileResult,- RunCommandParams,- RunCommandResult,- WriteLocalFileParams,-} from '../types';--/* eslint-disable typescript-sort-keys/interface */-export interface LocalSystemDispatchEvents {- // File Operations- editLocalFile: (params: EditLocalFileParams) => EditLocalFileResult;- moveLocalFiles: (params: MoveLocalFilesParams) => LocalMoveFilesResultItem[];- openLocalFile: (params: OpenLocalFileParams) => void;- openLocalFolder: (params: OpenLocalFolderParams) => void;- readLocalFile: (params: LocalReadFileParams) => LocalReadFileResult;- readLocalFiles: (params: LocalReadFilesParams) => LocalReadFileResult[];- renameLocalFile: (params: RenameLocalFileParams) => RenameLocalFileResult;- writeLocalFile: (params: WriteLocalFileParams) => RenameLocalFileResult;- // Shell Commands- runCommand: (params: RunCommandParams) => RunCommandResult;- getCommandOutput: (params: GetCommandOutputParams) => GetCommandOutputResult;- killCommand: (params: KillCommandParams) => KillCommandResult;- // Search & Find- listLocalFiles: (params: ListLocalFileParams) => LocalFileItem[];- grepContent: (params: GrepContentParams) => GrepContentResult;- globLocalFiles: (params: GlobFilesParams) => GlobFilesResult;- searchLocalFiles: (params: LocalSearchFilesParams) => LocalFileItem[];-}diff --git a/packages/electron-client-ipc/src/events/menu.ts b/packages/electron-client-ipc/src/events/menu.tsdeleted file mode 100644index d2a2df95c35..00000000000--- a/packages/electron-client-ipc/src/events/menu.ts+++ /dev/null@@ -1,5 +0,0 @@-export interface MenuDispatchEvents {- refreshAppMenu: () => { success: boolean };- setDevMenuVisibility: (visible: boolean) => { success: boolean };- showContextMenu: (params: { data?: any; type: string }) => { success: boolean };-}diff --git a/packages/electron-client-ipc/src/events/navigation.ts b/packages/electron-client-ipc/src/events/navigation.tsnew file mode 100644index 00000000000..7355dbc7945--- /dev/null+++ b/packages/electron-client-ipc/src/events/navigation.ts@@ -0,0 +1,6 @@+export interface NavigationBroadcastEvents {+ /**+ * Ask renderer to navigate within the SPA without reloading the whole page.+ */+ navigate: (data: { path: string; replace?: boolean }) => void;+}diff --git a/packages/electron-client-ipc/src/events/notification.ts b/packages/electron-client-ipc/src/events/notification.tsdeleted file mode 100644index 7e4be74af72..00000000000--- a/packages/electron-client-ipc/src/events/notification.ts+++ /dev/null@@ -1,6 +0,0 @@-import { DesktopNotificationResult, ShowDesktopNotificationParams } from '../types';--export interface NotificationDispatchEvents {- isMainWindowHidden: () => boolean;- showDesktopNotification: (params: ShowDesktopNotificationParams) => DesktopNotificationResult;-}diff --git a/packages/electron-client-ipc/src/events/protocol.ts b/packages/electron-client-ipc/src/events/protocol.tsindex f6108b35e2b..f117afb5ac6 100644--- a/packages/electron-client-ipc/src/events/protocol.ts+++ b/packages/electron-client-ipc/src/events/protocol.ts@@ -17,13 +17,3 @@ export interface ProtocolBroadcastEvents {schema: McpInstallSchema;}) => void;}--/**- * 协议处理相关的 Dispatch 事件(渲染进程 -> 主进程)- */-export interface ProtocolDispatchEvents {- /**- * 通知主进程协议URL已被处理- */- protocolUrlHandled: (data: { error?: string; success: boolean; url: string }) => Promise<void>;-}diff --git a/packages/electron-client-ipc/src/events/remoteServer.ts b/packages/electron-client-ipc/src/events/remoteServer.tsindex fbdf8bf6e18..8825f8273c0 100644--- a/packages/electron-client-ipc/src/events/remoteServer.ts+++ b/packages/electron-client-ipc/src/events/remoteServer.ts@@ -1,37 +1,7 @@-import { DataSyncConfig } from '../types/dataSync';-import { ProxyTRPCRequestParams, ProxyTRPCRequestResult } from '../types/proxyTRPCRequest';-export interface MarketAuthorizationParams {authUrl: string;}-/**- * 远程服务器配置相关的事件- */-export interface RemoteServerDispatchEvents {- clearRemoteServerConfig: () => boolean;- getRemoteServerConfig: () => DataSyncConfig;- /**- * Proxy a tRPC request to the remote server.- * @param args - Request arguments.- * @returns Promise resolving with the response details.- */- proxyTRPCRequest: (args: ProxyTRPCRequestParams) => ProxyTRPCRequestResult;- refreshAccessToken: () => {- error?: string;- success: boolean;- };- requestAuthorization: (config: DataSyncConfig) => {- error?: string;- success: boolean;- };- requestMarketAuthorization: (params: MarketAuthorizationParams) => {- error?: string;- success: boolean;- };- setRemoteServerConfig: (config: DataSyncConfig) => boolean;-}-/*** 从主进程广播的远程服务器相关事件*/diff --git a/packages/electron-client-ipc/src/events/settings.ts b/packages/electron-client-ipc/src/events/settings.tsdeleted file mode 100644index 54ae890d803..00000000000--- a/packages/electron-client-ipc/src/events/settings.ts+++ /dev/null@@ -1,12 +0,0 @@-import { NetworkProxySettings } from '../types';--export interface DesktopSettingsDispatchEvents {- getProxySettings: () => NetworkProxySettings;- setProxySettings: (settings: Partial<NetworkProxySettings>) => void;- testProxyConfig: (data: { config: NetworkProxySettings; testUrl?: string }) => Promise<{- message?: string;- responseTime?: number;- success: boolean;- }>;- testProxyConnection: (url: string) => Promise<{ message?: string; success: boolean }>;-}diff --git a/packages/electron-client-ipc/src/events/shortcut.ts b/packages/electron-client-ipc/src/events/shortcut.tsdeleted file mode 100644index 8a54fb8f4a4..00000000000--- a/packages/electron-client-ipc/src/events/shortcut.ts+++ /dev/null@@ -1,6 +0,0 @@-import { ShortcutUpdateResult } from '../types';--export interface ShortcutDispatchEvents {- getShortcutsConfig: () => Record<string, string>;- updateShortcutConfig: (params: { accelerator: string; id: string }) => ShortcutUpdateResult;-}diff --git a/packages/electron-client-ipc/src/events/system.ts b/packages/electron-client-ipc/src/events/system.tsindex b06d052c8aa..5d59cb82e08 100644--- a/packages/electron-client-ipc/src/events/system.ts+++ b/packages/electron-client-ipc/src/events/system.ts@@ -1,19 +1,4 @@-import { ElectronAppState, ThemeAppearance, ThemeMode } from '../types';--export interface SystemDispatchEvents {- checkSystemAccessibility: () => boolean | undefined;- closeWindow: () => void;- getDesktopAppState: () => ElectronAppState;- maximizeWindow: () => void;- minimizeWindow: () => void;- openExternalLink: (url: string) => void;- /**- * 更新应用语言设置- * @param locale 语言设置- */- updateLocale: (locale: string) => { success: boolean };- updateThemeMode: (themeMode: ThemeMode) => void;-}+import { ThemeAppearance, ThemeMode } from '../types';export interface SystemBroadcastEvents {localeChanged: (data: { locale: string }) => void;diff --git a/packages/electron-client-ipc/src/events/tray.ts b/packages/electron-client-ipc/src/events/tray.tsdeleted file mode 100644index 42f9417ab64..00000000000--- a/packages/electron-client-ipc/src/events/tray.ts+++ /dev/null@@ -1,31 +0,0 @@-import {- ShowTrayNotificationParams,- UpdateTrayIconParams,- UpdateTrayTooltipParams,-} from '../types';--export interface TrayDispatchEvents {- /**- * 显示托盘通知- * @param params 通知参数- * @returns 操作结果- */- showTrayNotification: (params: ShowTrayNotificationParams) => {- error?: string;- success: boolean;- };-- /**- * 更新托盘图标- * @param params 图标参数- * @returns 操作结果- */- updateTrayIcon: (params: UpdateTrayIconParams) => { error?: string; success: boolean };-- /**- * 更新托盘提示文本- * @param params 提示文本参数- * @returns 操作结果- */- updateTrayTooltip: (params: UpdateTrayTooltipParams) => { error?: string; success: boolean };-}diff --git a/packages/electron-client-ipc/src/events/update.ts b/packages/electron-client-ipc/src/events/update.tsindex c57b01e2a39..d9f20ba8fbd 100644--- a/packages/electron-client-ipc/src/events/update.ts+++ b/packages/electron-client-ipc/src/events/update.ts@@ -1,13 +1,5 @@import { ProgressInfo, UpdateInfo } from '../types';-export interface AutoUpdateDispatchEvents {- checkUpdate: () => void;- downloadUpdate: () => void;- installLater: () => void;- installNow: () => void;- installUpdate: () => void;-}-export interface AutoUpdateBroadcastEvents {manualUpdateAvailable: (info: UpdateInfo) => void;manualUpdateCheckStart: () => void;diff --git a/packages/electron-client-ipc/src/events/upload.ts b/packages/electron-client-ipc/src/events/upload.tsdeleted file mode 100644index 106b1e9de07..00000000000--- a/packages/electron-client-ipc/src/events/upload.ts+++ /dev/null@@ -1,5 +0,0 @@-import { FileMetadata, UploadFileParams } from '../types';--export interface UploadFilesDispatchEvents {- createFile: (params: UploadFileParams) => { metadata: FileMetadata; success: boolean };-}diff --git a/packages/electron-client-ipc/src/events/windows.ts b/packages/electron-client-ipc/src/events/windows.tsindex fd9506c43e8..52a328e5ec4 100644--- a/packages/electron-client-ipc/src/events/windows.ts+++ b/packages/electron-client-ipc/src/events/windows.ts@@ -1,69 +1,15 @@-import { InterceptRouteParams, InterceptRouteResponse } from '../types/route';-export interface OpenSettingsWindowOptions {/**- * Query parameters that should be appended to the settings URL.+ * Direct path to navigate to (e.g., '/settings/provider/openai').+ * Takes precedence over tab and searchParams if provided.*/- searchParams?: Record<string, string | undefined>;- /**- * Settings page tab path or identifier.- */- tab?: string;-}--export interface CreateMultiInstanceWindowParams {- path: string;- templateId: string;- uniqueId?: string;-}--export interface CreateMultiInstanceWindowResponse {- error?: string;- success: boolean;- windowId?: string;-}--export interface GetWindowsByTemplateResponse {- error?: string;- success: boolean;- windowIds?: string[];-}--export interface WindowsDispatchEvents {+ path?: string;/**- * Close all windows by template- * @param templateId Template identifier- * @returns Operation result+ * @deprecated Use `path` instead. Query parameters that should be appended to the settings URL.*/- closeWindowsByTemplate: (templateId: string) => { error?: string; success: boolean };-- /**- * Create a new multi-instance window- * @param params Window creation parameters- * @returns Creation result- */- createMultiInstanceWindow: (- params: CreateMultiInstanceWindowParams,- ) => CreateMultiInstanceWindowResponse;-- /**- * Get all windows by template- * @param templateId Template identifier- * @returns List of window identifiers- */- getWindowsByTemplate: (templateId: string) => GetWindowsByTemplateResponse;-- /**- * 拦截客户端路由导航请求- * @param params 包含路径和来源信息的参数对象- * @returns 路由拦截结果- */- interceptRoute: (params: InterceptRouteParams) => InterceptRouteResponse;-+ searchParams?: Record<string, string | undefined>;/**- * open the LobeHub Devtools+ * @deprecated Use `path` instead. Settings page tab path or identifier.*/- openDevtools: () => void;-- openSettingsWindow: (options?: OpenSettingsWindowOptions | string) => void;+ tab?: string;}diff --git a/packages/electron-client-ipc/src/ipc.ts b/packages/electron-client-ipc/src/ipc.tsindex 08f753a22bd..9491f78c9be 100644--- a/packages/electron-client-ipc/src/ipc.ts+++ b/packages/electron-client-ipc/src/ipc.ts@@ -1,6 +1,7 @@/* eslint-disable @typescript-eslint/no-empty-interface */-import type { DispatchInvoke } from './types/dispatch';-import type { ProxyTRPCRequestParams } from './types/proxyTRPCRequest';+import type { StreamInvokeRequestParams } from './types';++type IpcInvoke = <T = unknown>(event: string, ...data: unknown[]) => Promise<T>;interface StreamerCallbacks {onData: (chunk: Uint8Array) => void;@@ -17,7 +18,7 @@ export interface DesktopIpcServicesMap {}export type DesktopIpcServices = DesktopIpcServicesMap;export type ElectronDesktopIpc = DesktopIpcServices | null;-const createInvokeProxy = <IpcServices>(invoke: DispatchInvoke): IpcServices =>+const createInvokeProxy = <IpcServices>(invoke: IpcInvoke): IpcServices =>new Proxy({},{@@ -45,8 +46,8 @@ let cachedProxy: DesktopIpcServices | null = null;declare global {interface Window {electronAPI?: {- invoke?: DispatchInvoke;- onStreamInvoke: (params: ProxyTRPCRequestParams, callbacks: StreamerCallbacks) => () => void;+ invoke?: IpcInvoke;+ onStreamInvoke: (params: StreamInvokeRequestParams, callbacks: StreamerCallbacks) => () => void;};}}diff --git a/packages/electron-client-ipc/src/streamInvoke.ts b/packages/electron-client-ipc/src/streamInvoke.tsindex 3ee9d925741..49698c8ad28 100644--- a/packages/electron-client-ipc/src/streamInvoke.ts+++ b/packages/electron-client-ipc/src/streamInvoke.ts@@ -1,4 +1,4 @@-import { ProxyTRPCRequestParams } from './types';+import type { ProxyTRPCStreamRequestParams } from './types';import { headersToRecord } from './utils/headers';import { getRequestBody } from './utils/request';@@ -11,10 +11,15 @@ export const streamInvoke = async (input: RequestInfo | URL, init?: RequestInit)const headers = headersToRecord(init?.headers);const body = await getRequestBody(init?.body);- const params: ProxyTRPCRequestParams = {+ const requestId =+ globalThis.crypto?.randomUUID?.() ??+ `stream_${Date.now()}_${Math.random().toString(16).slice(2)}`;++ const params: ProxyTRPCStreamRequestParams = {body,headers,method,+ requestId,urlPath,};diff --git a/packages/electron-client-ipc/src/types/dataSync.ts b/packages/electron-client-ipc/src/types/dataSync.tsindex 5f174150fc1..51462491f1d 100644--- a/packages/electron-client-ipc/src/types/dataSync.ts+++ b/packages/electron-client-ipc/src/types/dataSync.ts@@ -1,7 +1,6 @@export type StorageMode = 'local' | 'cloud' | 'selfHost';export enum StorageModeEnum {Cloud = 'cloud',- Local = 'local',SelfHost = 'selfHost',}diff --git a/packages/electron-client-ipc/src/types/dispatch.ts b/packages/electron-client-ipc/src/types/dispatch.tsdeleted file mode 100644index ca36c74199d..00000000000--- a/packages/electron-client-ipc/src/types/dispatch.ts+++ /dev/null@@ -1 +0,0 @@-export type DispatchInvoke = <T = unknown>(event: string, ...data: any[]) => Promise<T>;diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.tsindex 1dea0ec5ca9..8897a5194c7 100644--- a/packages/electron-client-ipc/src/types/index.ts+++ b/packages/electron-client-ipc/src/types/index.ts@@ -1,5 +1,4 @@export * from './dataSync';-export * from './dispatch';export * from './localSystem';export * from './mcpInstall';export * from './notification';diff --git a/packages/electron-client-ipc/src/types/proxyTRPCRequest.ts b/packages/electron-client-ipc/src/types/proxyTRPCRequest.tsindex 46f6f603a54..79dbccca990 100644--- a/packages/electron-client-ipc/src/types/proxyTRPCRequest.ts+++ b/packages/electron-client-ipc/src/types/proxyTRPCRequest.ts@@ -1,26 +1,17 @@-export type ProxyTRPCRequestParams = {- /** Request body (can be string, ArrayBuffer, or null/undefined) */+export interface StreamInvokeRequestParams {body?: string | ArrayBuffer;- /** Request headers */headers: Record<string, string>;- /** The HTTP method (e.g., 'GET', 'POST') */method: string;- /** The path and query string of the request (e.g., '/trpc/lambda/...') */urlPath: string;-};--export interface ProxyTRPCStreamRequestParams extends Omit<ProxyTRPCRequestParams, 'body'> {- body?: ArrayBuffer;- requestId: string;+ /**+ * Optional client-generated request id.+ *+ * In desktop, the preload layer will generate and override its own `requestId`+ * when forwarding to the main process, so this is optional at the API boundary.+ */+ requestId?: string;}-export interface ProxyTRPCRequestResult {- /** Response body (likely as ArrayBuffer or string) */- body: ArrayBuffer | string;- /** Response headers */- headers: Record<string, string>;- /** Response status code */- status: number;- /** Response status text */- statusText: string;+export interface ProxyTRPCStreamRequestParams extends StreamInvokeRequestParams {+ requestId: string;}diff --git a/packages/electron-server-ipc/src/events/database.ts b/packages/electron-server-ipc/src/events/database.tsdeleted file mode 100644index 8a373379d6c..00000000000--- a/packages/electron-server-ipc/src/events/database.ts+++ /dev/null@@ -1,4 +0,0 @@-export interface DatabaseDispatchEvents {- getDatabaseSchemaHash: () => string | undefined;- setDatabaseSchemaHash: (hash: string) => void;-}diff --git a/packages/electron-server-ipc/src/events/file.ts b/packages/electron-server-ipc/src/events/file.tsdeleted file mode 100644index b9c5e966735..00000000000--- a/packages/electron-server-ipc/src/events/file.ts+++ /dev/null@@ -1,8 +0,0 @@-import { CreateFileParams, DeleteFilesResponse, FileMetadata } from '../types/file';--export interface FileDispatchEvents {- deleteFiles: (paths: string[]) => DeleteFilesResponse;- getStaticFilePath: (id: string) => string;- getFileHTTPURL: (path: string) => string;- createFile: (param: CreateFileParams) => { metadata: FileMetadata; success: boolean };-}diff --git a/packages/electron-server-ipc/src/events/index.ts b/packages/electron-server-ipc/src/events/index.tsdeleted file mode 100644index a3eb1a80d1d..00000000000--- a/packages/electron-server-ipc/src/events/index.ts+++ /dev/null@@ -1,29 +0,0 @@-/* eslint-disable typescript-sort-keys/interface, sort-keys-fix/sort-keys-fix */-import { DatabaseDispatchEvents } from './database';-import { FileDispatchEvents } from './file';-import { StoragePathDispatchEvents } from './storagePath';--/**- * next server -> main dispatch events- */-// eslint-disable-next-line @typescript-eslint/no-empty-interface-export interface ServerDispatchEvents- extends StoragePathDispatchEvents,- DatabaseDispatchEvents,- FileDispatchEvents {}--export type ServerDispatchEventKey = keyof ServerDispatchEvents;--export type ServerEventReturnType<T extends ServerDispatchEventKey> = ReturnType<- ServerDispatchEvents[T]->;--export type ServerEventParams<T extends ServerDispatchEventKey> = Parameters<- ServerDispatchEvents[T]->[0];--export type IPCServerEventHandler = {- [key in ServerDispatchEventKey]: (- params: ServerEventParams<key>,- ) => Promise<ServerEventReturnType<key>>;-};diff --git a/packages/electron-server-ipc/src/events/storagePath.ts b/packages/electron-server-ipc/src/events/storagePath.tsdeleted file mode 100644index c1f2d1761ea..00000000000--- a/packages/electron-server-ipc/src/events/storagePath.ts+++ /dev/null@@ -1,4 +0,0 @@-export interface StoragePathDispatchEvents {- getDatabasePath: () => string;- getUserDataPath: () => string;-}diff --git a/packages/electron-server-ipc/src/index.ts b/packages/electron-server-ipc/src/index.tsindex de55e5655f8..52f9a0bfc6a 100644--- a/packages/electron-server-ipc/src/index.ts+++ b/packages/electron-server-ipc/src/index.ts@@ -1,4 +1,3 @@-export * from './events';export * from './ipcClient';export * from './ipcServer';export * from './types';diff --git a/packages/file-loaders/src/utils/parser-utils.ts b/packages/file-loaders/src/utils/parser-utils.tsindex f30faa5e891..4b6dbb2f4fa 100644--- a/packages/file-loaders/src/utils/parser-utils.ts+++ b/packages/file-loaders/src/utils/parser-utils.ts@@ -1,6 +1,5 @@import { DOMParser } from '@xmldom/xmldom';import concat from 'concat-stream';-import { Buffer } from 'node:buffer';import yauzl from 'yauzl';// Define basic error messagesdiff --git a/src/app/desktop/devtools/page.tsx b/src/app/desktop/devtools/page.tsxdeleted file mode 100644index f08fb838cce..00000000000--- a/src/app/desktop/devtools/page.tsx+++ /dev/null@@ -1,89 +0,0 @@-'use client';--import { ActionIcon, SideNav } from '@lobehub/ui';-import { Cog, DatabaseIcon } from 'lucide-react';-import { memo, useState } from 'react';-import { Flexbox } from 'react-layout-kit';--import { BRANDING_NAME } from '@/const/branding';-import PostgresViewer from '@/features/DevPanel/PostgresViewer';-import SystemInspector from '@/features/DevPanel/SystemInspector';-import { useStyles } from '@/features/DevPanel/features/FloatPanel';-import { electronStylish } from '@/styles/electron';--const DevTools = memo(() => {- const { styles, theme, cx } = useStyles();-- const items = [- {- children: <PostgresViewer />,- icon: <DatabaseIcon size={16} />,- key: 'Postgres Viewer',- },- {- children: <SystemInspector />,- icon: <Cog size={16} />,- key: 'System Status',- },- ];-- const [tab, setTab] = useState<string>(items[0].key);-- return (- <Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>- <Flexbox- align={'center'}- className={cx(`panel-drag-handle`, styles.header, electronStylish.draggable)}- horizontal- justify={'center'}- >- <Flexbox align={'baseline'} gap={6} horizontal>- <b>{BRANDING_NAME} Dev Tools</b>- <span style={{ color: theme.colorTextDescription }}>/</span>- <span style={{ color: theme.colorTextDescription }}>{tab}</span>- </Flexbox>- </Flexbox>- <Flexbox- height={'100%'}- horizontal- style={{ background: theme.colorBgLayout, overflow: 'hidden', position: 'relative' }}- width={'100%'}- >- <SideNav- bottomActions={[]}- style={{- background: 'transparent',- width: 48,- }}- topActions={items.map((item) => (- <ActionIcon- active={tab === item.key}- icon={item.icon}- key={item.key}- onClick={() => setTab(item.key)}- title={item.key}- tooltipProps={{- placement: 'right',- }}- />- ))}- />- {items.map((item) => (- <Flexbox- flex={1}- height={'100%'}- key={item.key}- style={{- display: tab === item.key ? 'flex' : 'none',- overflow: 'hidden',- }}- >- {item.children}- </Flexbox>- ))}- </Flexbox>- </Flexbox>- );-});--export default DevTools;\ No newline at end of filediff --git a/src/app/desktop/layout.tsx b/src/app/desktop/layout.tsxdeleted file mode 100644index 4797c236f46..00000000000--- a/src/app/desktop/layout.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { notFound } from 'next/navigation';-import { NuqsAdapter } from 'nuqs/adapters/next/app';-import { ReactNode } from 'react';--import { isDesktop } from '@/const/version';-import GlobalLayout from '@/layout/GlobalProvider';-import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';--interface RootLayoutProps {- children: ReactNode;-}--const RootLayout = async ({ children }: RootLayoutProps) => {- if (!isDesktop) return notFound();-- return (- <html dir="ltr" suppressHydrationWarning>- <body>- <NuqsAdapter>- <ServerConfigStoreProvider>- <GlobalLayout appearance={'auto'} isMobile={false} locale={''}>- {children}- </GlobalLayout>- </ServerConfigStoreProvider>- </NuqsAdapter>- </body>- </html>- );-};--export default RootLayout;\ No newline at end of filediff --git a/src/styles/global.ts b/src/styles/global.tsindex 4cf41a437de..3c517d33d40 100644--- a/src/styles/global.ts+++ b/src/styles/global.ts@@ -51,4 +51,8 @@ export default ({ token }: { prefixCls: string; token: Theme }) => css`background-color: transparent;}}++ button {+ -webkit-app-region: no-drag;+ }`;diff --git a/src/styles/react-diff-view.dark.css b/src/styles/react-diff-view.dark.cssnew file mode 100644index 00000000000..9cd5031b675--- /dev/null+++ b/src/styles/react-diff-view.dark.css@@ -0,0 +1,43 @@+/* react-diff-view doesn't ship a dark theme.+ * We override its CSS variables when the app is in dark mode.+ *+ * NOTE:+ * - ThemeProvider (antd-style / @lobehub/ui) sets a `data-theme="dark"` attribute at runtime.+ * - Keep this file purely as variable overrides to minimize drift with upstream styles.+ */++[data-theme='dark'] .diff {+ /* base */+ --diff-background-color: transparent;+ --diff-text-color: #c9d1d9;+ --diff-font-family:+ ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',+ monospace;++ /* selection */+ --diff-selection-background-color: rgba(56, 139, 253, 0.35);+ --diff-selection-text-color: var(--diff-text-color);++ /* gutter */+ --diff-gutter-insert-background-color: rgba(46, 160, 67, 0.22);+ --diff-gutter-insert-text-color: var(--diff-text-color);+ --diff-gutter-delete-background-color: rgba(248, 81, 73, 0.22);+ --diff-gutter-delete-text-color: var(--diff-text-color);+ --diff-gutter-selected-background-color: rgba(187, 128, 9, 0.28);+ --diff-gutter-selected-text-color: var(--diff-text-color);++ /* code */+ --diff-code-insert-background-color: rgba(46, 160, 67, 0.14);+ --diff-code-insert-text-color: var(--diff-text-color);+ --diff-code-delete-background-color: rgba(248, 81, 73, 0.14);+ --diff-code-delete-text-color: var(--diff-text-color);+ --diff-code-insert-edit-background-color: rgba(46, 160, 67, 0.28);+ --diff-code-insert-edit-text-color: var(--diff-text-color);+ --diff-code-delete-edit-background-color: rgba(248, 81, 73, 0.28);+ --diff-code-delete-edit-text-color: var(--diff-text-color);+ --diff-code-selected-background-color: rgba(187, 128, 9, 0.28);+ --diff-code-selected-text-color: var(--diff-text-color);++ /* omit marker */+ --diff-omit-gutter-line-color: rgba(248, 81, 73, 0.7);+}diff --git a/src/utils/electron/autoOidc.ts b/src/utils/electron/autoOidc.tsnew file mode 100644index 00000000000..9e19cf80714--- /dev/null+++ b/src/utils/electron/autoOidc.ts@@ -0,0 +1,34 @@+export const DESKTOP_AUTO_OIDC_FIRST_OPEN_STORAGE_KEY = 'lobechat:desktop:auto-oidc:first-open:v1';++/**+ * Whether the "desktop auto OIDC on first open" flow has been handled.+ *+ * - If localStorage is unavailable, treat it as handled to avoid repeated prompts.+ */+export const getDesktopAutoOidcFirstOpenHandled = () => {+ if (typeof window === 'undefined') return true;++ try {+ return window.localStorage.getItem(DESKTOP_AUTO_OIDC_FIRST_OPEN_STORAGE_KEY) === '1';+ } catch {+ return true;+ }+};++/**+ * Mark the "desktop auto OIDC on first open" flow as handled.+ *+ * - Returns false if localStorage is unavailable.+ */+export const setDesktopAutoOidcFirstOpenHandled = () => {+ if (typeof window === 'undefined') return false;++ try {+ window.localStorage.setItem(DESKTOP_AUTO_OIDC_FIRST_OPEN_STORAGE_KEY, '1');+ return true;+ } catch {+ return false;+ }+};++diff --git a/src/utils/electron/desktopRemoteRPCFetch.ts b/src/utils/electron/desktopRemoteRPCFetch.tsdeleted file mode 100644index 62b61cf6e6a..00000000000--- a/src/utils/electron/desktopRemoteRPCFetch.ts+++ /dev/null@@ -1,88 +0,0 @@-import { isDesktop } from '@lobechat/const';-import { ProxyTRPCRequestParams, streamInvoke } from '@lobechat/electron-client-ipc';-import { getRequestBody, headersToRecord } from '@lobechat/fetch-sse';-import debug from 'debug';--import { getElectronStoreState } from '@/store/electron';-import { electronSyncSelectors } from '@/store/electron/selectors';-import { ensureElectronIpc } from '@/utils/electron/ipc';--const log = debug('utils:desktopRemoteRPCFetch');--// eslint-disable-next-line no-undef-export const desktopRemoteRPCFetch = async (input: string, init?: RequestInit) => {- const isSyncActive = electronSyncSelectors.isSyncActive(getElectronStoreState());- log('isSyncActive:', isSyncActive);-- if (isSyncActive) {- log('Using IPC proxy for tRPC request');- const url = input as string;- try {- const parsedUrl = new URL(url, window.location.origin);- const urlPath = parsedUrl.pathname + parsedUrl.search;- const method = init?.method?.toUpperCase() || 'GET';- const headers = headersToRecord(init?.headers);- const body = await getRequestBody(init?.body);-- const params: ProxyTRPCRequestParams = {- body,- headers,- method,- urlPath,- };-- const ipcResult = await ensureElectronIpc().remoteServerSync.proxyTRPCRequest(params);-- log(`Received ${url} IPC proxy response:`, { status: ipcResult.status });- const response = new Response(ipcResult.body, {- headers: ipcResult.headers,- status: ipcResult.status,- statusText: ipcResult.statusText,- });-- if (!response.ok) {- console.warn(- `[lambda] ${url} IPC proxy response indicates an error:`,- response.status,- response.statusText,- );- }-- return response;- } catch (error) {- console.error(`[lambda] Error during ${url} IPC proxy call:`, error);- return new Response(- `IPC Proxy Error: ${error instanceof Error ? error.message : 'Unknown error'}`,- {- status: 500,- statusText: 'IPC Proxy Error',- },- );- }- }-};--// eslint-disable-next-line no-undef-export const fetchWithDesktopRemoteRPC = (async (input: RequestInfo | URL, init?: RequestInit) => {- if (isDesktop) {- const res = await desktopRemoteRPCFetch(input as string, init);- if (res) return res;- }-- return fetch(input, init);-}) as typeof fetch;--// eslint-disable-next-line no-undef-export const fetchWithInvokeStream = async (input: RequestInfo | URL, init?: RequestInit) => {- if (isDesktop) {- const isSyncActive = electronSyncSelectors.isSyncActive(getElectronStoreState());- log('isSyncActive:', isSyncActive);- if (isSyncActive) {- log('Using IPC stream proxy for request to:', input);-- return streamInvoke(input, init);- }- }-- return fetch(input, init);-};