🤯 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
⬆️ chore: upgrade Vite to 8.0.0 (#12720)
Innei31d76ccb90ee
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.tsindex 53b3f348750..9cf6ead27c9 100644--- a/apps/desktop/electron.vite.config.ts+++ b/apps/desktop/electron.vite.config.ts@@ -92,6 +92,8 @@ const updateChannel = process.env.UPDATE_CHANNEL;const desktopPackageJson = JSON.parse(readFileSync(path.resolve(__dirname, 'package.json'), 'utf8'),) as { version: string };+const electronRuntimeExternals = ['electron'];+const mainProcessRuntimeExternals = [...electronRuntimeExternals, 'node-mac-permissions'];console.info(`[electron-vite.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}`);@@ -100,10 +102,15 @@ export default defineConfig({build: {minify: !isDev,outDir: 'dist/main',- rollupOptions: {+ rolldownOptions: {// Native modules must be externalized to work correctly.// bufferutil and utf-8-validate are optional peer deps of ws that may not be installed.- external: [...getExternalDependencies(), 'bufferutil', 'utf-8-validate'],+ external: [+ ...mainProcessRuntimeExternals,+ ...getExternalDependencies(),+ 'bufferutil',+ 'utf-8-validate',+ ],output: {// Prevent debug package from being bundled into index.js to avoid side-effect pollutionmanualChunks(id) {@@ -137,6 +144,9 @@ export default defineConfig({build: {minify: !isDev,outDir: 'dist/preload',+ rolldownOptions: {+ external: electronRuntimeExternals,+ },sourcemap: isDev ? 'inline' : false,},resolve: {@@ -150,7 +160,7 @@ export default defineConfig({root: ROOT_DIR,build: {outDir: path.resolve(__dirname, 'dist/renderer'),- rollupOptions: {+ rolldownOptions: {input: {main: path.resolve(__dirname, 'index.html'),popup: path.resolve(__dirname, 'popup.html'),diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 10f1e1f75f5..163b2fe9437 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -76,7 +76,7 @@"electron-log": "^5.4.3","electron-store": "^8.2.0","electron-updater": "^6.6.2",- "electron-vite": "^5.0.0",+ "electron-vite": "6.0.0-beta.1","electron-window-state": "^5.0.3","es-toolkit": "^1.43.0","eslint": "10.0.0",@@ -102,7 +102,7 @@"typescript": "^5.9.3","undici": "^7.16.0","uuid": "^13.0.0",- "vite": "^7.3.1",+ "vite": "^8.0.9","vitest": "^3.2.4","zod": "^3.25.76"},diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex d441ee29fda..d63bfb41b55 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -1,4 +1,6 @@packages:+ - '../cli'+ - '../../packages/agent-gateway-client'- '../../packages/const'- '../../packages/electron-server-ipc'- '../../packages/electron-client-ipc'diff --git a/apps/desktop/src/main/const/env.ts b/apps/desktop/src/main/const/env.tsindex be8083a857d..4b204bb2e44 100644--- a/apps/desktop/src/main/const/env.ts+++ b/apps/desktop/src/main/const/env.ts@@ -1,16 +1,16 @@import os from 'node:os';-import { dev, linux, macOS, windows } from 'electron-is';+import * as electronIs from 'electron-is';import { getDesktopEnv } from '@/env';-export const isDev = dev();+export const isDev = electronIs.dev();export const OFFICIAL_CLOUD_SERVER = getDesktopEnv().OFFICIAL_CLOUD_SERVER;-export const isMac = macOS();-export const isWindows = windows();-export const isLinux = linux();+export const isMac = electronIs.macOS();+export const isWindows = electronIs.windows();+export const isLinux = electronIs.linux();function getIsMacTahoe(): boolean {if (!isMac) return false;diff --git a/apps/desktop/src/main/controllers/NotificationCtr.ts b/apps/desktop/src/main/controllers/NotificationCtr.tsindex a189558f120..b0362cd0685 100644--- a/apps/desktop/src/main/controllers/NotificationCtr.ts+++ b/apps/desktop/src/main/controllers/NotificationCtr.ts@@ -3,7 +3,7 @@ import type {ShowDesktopNotificationParams,} from '@lobechat/electron-client-ipc';import { app, Notification } from 'electron';-import { linux, macOS, windows } from 'electron-is';+import * as electronIs from 'electron-is';import { getIpcContext } from '@/utils/ipc';import { createLogger } from '@/utils/logger';@@ -20,7 +20,7 @@ export default class NotificationCtr extends ControllerModule {if (!Notification.isSupported()) return 'denied';// Keep a stable status string for renderer-side UI mapping.// Screen3 expects macOS to return 'authorized' when granted.- if (!macOS()) return 'authorized';+ if (!electronIs.macOS()) return 'authorized';// Electron 38 no longer exposes `systemPreferences.getNotificationSettings()` in types,// and some runtimes don't provide it at all. Use the renderer's Notification.permission@@ -43,7 +43,7 @@ export default class NotificationCtr extends ControllerModule {// On macOS, ask permission via Web Notification API first when possible.// This helps keep `Notification.permission` in sync for subsequent status checks.- if (macOS()) {+ if (electronIs.macOS()) {try {const mainWindow = this.app.browserManager.getMainWindow().browserWindow;await mainWindow.webContents.executeJavaScript('Notification.requestPermission()', true);@@ -83,12 +83,12 @@ export default class NotificationCtr extends ControllerModule {}// On macOS, we may need to explicitly request notification permissions- if (macOS()) {+ if (electronIs.macOS()) {logger.debug('macOS detected, notification permissions should be handled by system');}// Set app user model ID on Windows- if (windows()) {+ if (electronIs.windows()) {app.setAppUserModelId('com.lobehub.chat');logger.debug('Set Windows App User Model ID for notifications');}@@ -136,7 +136,7 @@ export default class NotificationCtr extends ControllerModule {// due to heavy gnome-shell processing. Using 'low' urgency routes notifications to the// message tray instead, preventing the banner's X button from being shown.// The urgency option is ignored on macOS and Windows.- urgency: linux() ? 'low' : 'normal',+ urgency: electronIs.linux() ? 'low' : 'normal',});// Add more event listeners for debugging@@ -192,7 +192,7 @@ export default class NotificationCtr extends ControllerModule {try {const next = Math.max(0, Math.floor(count));app.setBadgeCount(next);- if (macOS() && app.dock) {+ if (electronIs.macOS() && app.dock) {app.dock.setBadge(next > 0 ? String(next) : '');}} catch (error) {diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex 45fbac299d6..a969b57bb20 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -2,7 +2,7 @@ import process from 'node:process';import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';import { app, dialog, nativeTheme, shell } from 'electron';-import { macOS } from 'electron-is';+import * as electronIs from 'electron-is';import { pathExists, readdir } from 'fs-extra';import { legacyLocalDbDir } from '@/const/dir';@@ -103,7 +103,7 @@ export default class SystemController extends ControllerModule {return 'granted';}- if (!macOS()) {+ if (!electronIs.macOS()) {logger.info('[FullDiskAccess] Not macOS, returning granted');return 'granted';}diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex 23159e2759f..0b0d98cf3c3 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -1,11 +1,11 @@import os from 'node:os';-import { join } from 'node:path';+import path from 'node:path';import type { ElectronIPCEventHandler } from '@lobechat/electron-server-ipc';import { ElectronIPCServer } from '@lobechat/electron-server-ipc';import { app, nativeTheme, protocol } from 'electron';import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';-import { macOS, windows } from 'electron-is';+import * as electronIs from 'electron-is';import { name } from '@/../../package.json';import { binDir, buildDir } from '@/const/dir';@@ -258,7 +258,7 @@ export class App {this.isQuiting = false;app.on('window-all-closed', () => {- if (windows() || process.platform === 'linux') {+ if (electronIs.windows() || process.platform === 'linux') {logger.info(`All windows closed, quitting application (${process.platform})`);app.quit();}@@ -420,8 +420,8 @@ export class App {logger.debug('Setting up dev branding');app.setName('lobehub-desktop-dev');- if (macOS()) {- app.dock!.setIcon(join(buildDir, 'icon-dev.png'));+ if (electronIs.macOS()) {+ app.dock!.setIcon(path.join(buildDir, 'icon-dev.png'));}};diff --git a/apps/desktop/src/main/global.d.ts b/apps/desktop/src/main/global.d.tsindex 7bc0f72a1ce..eae27f4da81 100644--- a/apps/desktop/src/main/global.d.ts+++ b/apps/desktop/src/main/global.d.ts@@ -1,4 +1,4 @@-import 'vite/client';+/// <reference types="vite/client" />/*** `node-mac-permissions` is a macOS-only native module.@@ -30,5 +30,3 @@ declare module 'node-mac-permissions' {export function askForScreenCaptureAccess(openPreferences?: boolean): void;export function askForFullDiskAccess(): void;}--export {};diff --git a/apps/desktop/src/main/utils/permissions.ts b/apps/desktop/src/main/utils/permissions.tsindex 1bb5622e790..3a02f875dad 100644--- a/apps/desktop/src/main/utils/permissions.ts+++ b/apps/desktop/src/main/utils/permissions.ts@@ -6,7 +6,8 @@* It must be dynamically imported to prevent loading errors on Windows/Linux.*/import { shell } from 'electron';-import { macOS } from 'electron-is';+import * as electronIs from 'electron-is';+import type * as MacPermissions from 'node-mac-permissions';import { createLogger } from './logger';@@ -27,33 +28,31 @@ type AuthType =type PermissionType = 'authorized' | 'denied' | 'not determined' | 'restricted';+type MacPermissionsModule = typeof MacPermissions;+// Lazy-loaded module cache-// @ts-ignore - node-mac-permissions is optional and only available on macOS-let macPermissionsModule: typeof import('node-mac-permissions') | null = null;+let macPermissionsModule: MacPermissionsModule | null = null;// Test injection override (set via __setMacPermissionsModule for testing)-// @ts-ignore - node-mac-permissions is optional and only available on macOS-let testModuleOverride: typeof import('node-mac-permissions') | null = null;+let testModuleOverride: MacPermissionsModule | null = null;/*** Lazily load the node-mac-permissions module (macOS only)* Returns null on non-macOS platforms*/-// @ts-ignore - node-mac-permissions is optional and only available on macOS-function getMacPermissionsModule(): typeof import('node-mac-permissions') | null {+function getMacPermissionsModule(): MacPermissionsModule | null {// Allow test injection to override the moduleif (testModuleOverride) {return testModuleOverride;}- if (!macOS()) {+ if (!electronIs.macOS()) {return null;}if (!macPermissionsModule) {// Dynamic require to prevent module loading on non-macOS platforms-- macPermissionsModule = require('node-mac-permissions');+ macPermissionsModule = require('node-mac-permissions') as MacPermissionsModule;}return macPermissionsModule;@@ -72,10 +71,7 @@ export function __resetMacPermissionsModuleCache(): void {* Set the mac permissions module (for testing purposes)* @internal*/-export function __setMacPermissionsModule(- // @ts-ignore - node-mac-permissions is optional and only available on macOS- module: typeof import('node-mac-permissions') | null,-): void {+export function __setMacPermissionsModule(module: MacPermissionsModule | null): void {testModuleOverride = module;}@@ -300,7 +296,7 @@ export function requestFullDiskAccess(): void {* Alternative method using shell.openExternal*/export async function openFullDiskAccessSettings(): Promise<void> {- if (!macOS()) {+ if (!electronIs.macOS()) {logger.info('[FullDiskAccess] Not macOS, skipping');return;}@@ -350,7 +346,7 @@ export function getInputMonitoringStatus(): PermissionStatus {* Maps 'microphone' and 'screen' to corresponding permission checks*/export function getMediaAccessStatus(mediaType: 'microphone' | 'screen'): string {- if (!macOS()) return 'granted';+ if (!electronIs.macOS()) return 'granted';const status = getPermissionStatus(mediaType === 'microphone' ? 'microphone' : 'screen');diff --git a/package.json b/package.jsonindex 92199ce7871..757b8ea9b3e 100644--- a/package.json+++ b/package.json@@ -313,6 +313,7 @@"better-auth-harmony": "^1.2.5","better-call": "1.1.8","brotli-wasm": "^3.0.1",+ "buffer": "^6.0.3","chat": "^4.23.0","chroma-js": "^3.2.0","class-variance-authority": "^0.7.1",@@ -527,8 +528,7 @@"typescript": "^5.9.3","unified": "^11.0.5","unist-util-visit": "^5.1.0",- "vite": "^7.3.1",- "vite-plugin-node-polyfills": "^0.25.0",+ "vite": "^8.0.9","vite-plugin-pwa": "^1.2.0","vite-tsconfig-paths": "^6.1.1","vitest": "^3.2.4"@@ -553,6 +553,10 @@"lexical": "0.42.0","pdfjs-dist": "5.4.530","stylelint-config-clean-order": "7.0.0"+ },+ "patchedDependencies": {+ "@code-inspector/[email protected]": "patches/@[email protected]",+ "@upstash/qstash": "patches/@upstash__qstash.patch"}}}diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.tsindex 70452fdc040..5ad5d840211 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -1,4 +1,5 @@import { imageUrlToBase64, videoUrlToBase64 } from '@lobechat/utils';+import { Buffer } from 'buffer/';import type OpenAI from 'openai';import { toFile } from 'openai';diff --git a/packages/model-runtime/src/providers/replicate/index.ts b/packages/model-runtime/src/providers/replicate/index.tsindex 5e26203244e..70e04d78976 100644--- a/packages/model-runtime/src/providers/replicate/index.ts+++ b/packages/model-runtime/src/providers/replicate/index.ts@@ -1,3 +1,4 @@+import { Buffer } from 'buffer/';import Replicate from 'replicate';import type { LobeRuntimeAI } from '../../core/BaseAI';@@ -139,7 +140,7 @@ export class LobeReplicateAI implements LobeRuntimeAI {const isPrivate192Range = hostname.startsWith('192.168.');// 172.16.0.0 – 172.31.255.255- const isPrivate172Range = /^172\.(1[6-9]|2\d|3[01])\./.test(hostname);+ const isPrivate172Range = /^172\.(?:1[6-9]|2\d|3[01])\./.test(hostname);const isLocalTld = hostname.endsWith('.local');@@ -186,7 +187,9 @@ export class LobeReplicateAI implements LobeRuntimeAI {this.debugLog('[Replicate createImage] Mapped to', imageParamName, 'as Buffer');} catch (fetchError: any) {this.debugLog('[Replicate createImage] Error fetching local image:', fetchError);- throw new Error(`Failed to fetch local image: ${fetchError.message}`);+ throw new Error(`Failed to fetch local image: ${fetchError.message}`, {+ cause: fetchError,+ });}} else {// Public URL - use directly@@ -416,7 +419,7 @@ export class LobeReplicateAI implements LobeRuntimeAI {if (!isReplicateDebug) return;- console.log(...args);+ console.info(...args);}}diff --git a/packages/utils/src/base64.ts b/packages/utils/src/base64.tsindex 21c59429fdc..5671efca46a 100644--- a/packages/utils/src/base64.ts+++ b/packages/utils/src/base64.ts@@ -3,6 +3,8 @@* Works in both browser and Node.js environments*/+import { Buffer } from 'buffer/';+/*** Encode a string to base64* @param input - The string to encodediff --git a/packages/utils/src/imageToBase64.ts b/packages/utils/src/imageToBase64.tsindex 5ee39688e07..a45ce930e0f 100644--- a/packages/utils/src/imageToBase64.ts+++ b/packages/utils/src/imageToBase64.ts@@ -1,3 +1,5 @@+import { Buffer } from 'buffer/';+export const imageToBase64 = ({size,img,diff --git a/packages/utils/src/trace.ts b/packages/utils/src/trace.tsindex 69a41b19c96..d78e4d30862 100644--- a/packages/utils/src/trace.ts+++ b/packages/utils/src/trace.ts@@ -1,5 +1,6 @@import type { TracePayload } from '@lobechat/const';import { LOBE_CHAT_TRACE_HEADER, LOBE_CHAT_TRACE_ID } from '@lobechat/const';+import { Buffer } from 'buffer/';export const getTracePayload = (req: Request): TracePayload | undefined => {const header = req.headers.get(LOBE_CHAT_TRACE_HEADER);diff --git a/patches/@[email protected] b/patches/@[email protected]new file mode 100644index 00000000000..79bbf5fe8cd--- /dev/null+++ b/patches/@[email protected]@@ -0,0 +1,103 @@+diff --git a/dist/index.js b/dist/index.js+index 8af93709d555a42d3bee2942771c9f826778b35f..09b4bc2a3baf43abbd1841541bc8a4489fa173f2 100644+--- a/dist/index.js++++ b/dist/index.js+@@ -1 +1 @@+-"use strict";var j=Object.defineProperty,w=Object.defineProperties;var P=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var k=(e,n,i)=>n in e?j(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i,f=(e,n)=>{for(var i in n||(n={}))W.call(n,i)&&k(e,i,n[i]);if(h)for(var i of h(n))q.call(n,i)&&k(e,i,n[i]);return e},m=(e,n)=>w(e,P(n));var v=(e,n,i)=>new Promise((t,a)=>{var c=l=>{try{u(i.next(l))}catch(r){a(r)}},s=l=>{try{u(i.throw(l))}catch(r){a(r)}},u=l=>l.done?t(l.value):Promise.resolve(l.value).then(c,s);u((i=i.apply(e,n)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@code-inspector/core"),d=require("chalk"),y="@code-inspector/vite",C=[{name:"vite:react-babel",package:"@vitejs/plugin-react"},{name:"vite:react-swc",package:"@vitejs/plugin-react-swc"},{name:"vite:react-oxc:config",package:"@vitejs/plugin-react-oxc"},{name:"solid",package:"vite-plugin-solid"},{name:"vite-plugin-qwik",package:"qwikVite"},{name:"vite-plugin-qwik-city",package:"qwikCity"},{name:"vite-plugin-qwik-react",package:"qwikReact"},{name:"vite:preact-jsx",package:"@preact/preset-vite"},{name:"vite-plugin-svelte",package:"@sveltejs/vite-plugin-svelte"}],I=["isJsx","isTsx","lang.jsx","lang.tsx"];function b(e=[]){const n=e.findIndex(i=>i.name===y);C.forEach(i=>{const t=e.findIndex(a=>a.name===i.name);if(t!==-1&&t<n){const a=[d.yellow("[WARNING]"),"You need to put",d.green("code-inspector-plugin"),"before",d.green(i.package),"in the vite config file."];console.log(a.join(" "))}})}function T(e){const n={port:0,entry:"",output:e.output,envDir:""};return m(f({name:y},e.enforcePre===!1?{}:{enforce:"pre"}),{apply(t,{command:a}){return!e.close&&o.isDev(e.dev,a==="serve")},configResolved(t){n.envDir=t.envDir||t.root,n.root=t.root},transform(t,a){return v(this,null,function*(){if(o.isExcludedFile(a,e))return t;t=yield o.getCodeWithWebComponent({options:e,file:a,code:t,record:n});const{escapeTags:c=[],mappings:s}=e,[u,l]=a.split("?",2);let r=o.normalizePath(u);r=o.getMappingFilePath(r,s);const g=new URLSearchParams(l);if(e.match&&!e.match.test(r))return t;let p="";return o.isJsTypeFile(r)||r.endsWith(".vue")&&(I.some(x=>g.get(x)!==null)||g.get("lang")==="tsx"||g.get("lang")==="jsx")?p="jsx":r.endsWith(".html")&&g.get("type")==="template"&&g.has("vue")||r.endsWith(".vue")&&g.get("type")!=="style"&&g.get("raw")===null?p="vue":r.endsWith(".svelte")&&(p="svelte"),p?o.transformCode({content:t,filePath:r,fileType:p,escapeTags:c,pathType:e.pathType}):t})},transformIndexHtml(t){return v(this,null,function*(){var c,s;if((s=(c=e.skipSnippets)==null?void 0:c.includes)!=null&&s.call(c,"htmlScript"))return t;const a=yield o.getCodeWithWebComponent({options:m(f({},e),{importClient:"code"}),file:"main.js",code:"",record:n,inject:!0});return t.replace("<head>",'<head><script type="module">\n'.concat(a,"\n<\/script>"))})},configureServer(t){const a=t.config.logger.info;t.config.logger.info=function(c,s){a.call(this,c,s),b(t.config.plugins),t.config.logger.info=a}}})}exports.ViteCodeInspectorPlugin=T;++"use strict";var j=Object.defineProperty,w=Object.defineProperties;var P=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var k=(e,n,i)=>n in e?j(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i,f=(e,n)=>{for(var i in n||(n={}))W.call(n,i)&&k(e,i,n[i]);if(h)for(var i of h(n))q.call(n,i)&&k(e,i,n[i]);return e},m=(e,n)=>w(e,P(n));var v=(e,n,i)=>new Promise((t,a)=>{var c=s=>{try{r(i.next(s))}catch(u){a(u)}},l=s=>{try{r(i.throw(s))}catch(u){a(u)}},r=s=>s.done?t(s.value):Promise.resolve(s.value).then(c,l);r((i=i.apply(e,n)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@code-inspector/core"),d=require("chalk"),y="@code-inspector/vite",C=[{name:"vite:react-babel",package:"@vitejs/plugin-react"},{name:"vite:react-swc",package:"@vitejs/plugin-react-swc"},{name:"vite:react-oxc:config",package:"@vitejs/plugin-react-oxc"},{name:"solid",package:"vite-plugin-solid"},{name:"vite-plugin-qwik",package:"qwikVite"},{name:"vite-plugin-qwik-city",package:"qwikCity"},{name:"vite-plugin-qwik-react",package:"qwikReact"},{name:"vite:preact-jsx",package:"@preact/preset-vite"},{name:"vite-plugin-svelte",package:"@sveltejs/vite-plugin-svelte"}],I=["isJsx","isTsx","lang.jsx","lang.tsx"];function b(e=[]){const n=e.findIndex(i=>i.name===y);C.forEach(i=>{const t=e.findIndex(a=>a.name===i.name);if(t!==-1&&t<n){const a=[d.yellow("[WARNING]"),"You need to put",d.green("code-inspector-plugin"),"before",d.green(i.package),"in the vite config file."];console.log(a.join(" "))}})}function T(e){const n={port:0,entry:"",output:e.output,envDir:""};return m(f({name:y},e.enforcePre===!1?{}:{enforce:"pre"}),{apply(t,{command:a}){return!e.close&&o.isDev(e.dev,a==="serve")},configResolved(t){n.envDir=t.envDir||t.root,n.root=t.root},transform(t,a){return v(this,null,function*(){if(o.isExcludedFile(a,e))return t;const[c,l]=a.split("?",2);let r=o.normalizePath(c);if(r.endsWith(".html")&&!l)return t;t=yield o.getCodeWithWebComponent({options:e,file:a,code:t,record:n});const{escapeTags:s=[],mappings:u}=e;r=o.getMappingFilePath(r,u);const g=new URLSearchParams(l);if(e.match&&!e.match.test(r))return t;let p="";return o.isJsTypeFile(r)||r.endsWith(".vue")&&(I.some(x=>g.get(x)!==null)||g.get("lang")==="tsx"||g.get("lang")==="jsx")?p="jsx":r.endsWith(".html")&&g.get("type")==="template"&&g.has("vue")||r.endsWith(".vue")&&g.get("type")!=="style"&&g.get("raw")===null?p="vue":r.endsWith(".svelte")&&(p="svelte"),p?o.transformCode({content:t,filePath:r,fileType:p,escapeTags:s,pathType:e.pathType}):t})},transformIndexHtml(t){return v(this,null,function*(){var c,l;if((l=(c=e.skipSnippets)==null?void 0:c.includes)!=null&&l.call(c,"htmlScript"))return t;const a=yield o.getCodeWithWebComponent({options:m(f({},e),{importClient:"code"}),file:"main.js",code:"",record:n,inject:!0});return t.replace("<head>",'<head><script type="module">\n'.concat(a,"\n<\/script>"))})},configureServer(t){const a=t.config.logger.info;t.config.logger.info=function(c,l){a.call(this,c,l),b(t.config.plugins),t.config.logger.info=a}}})}exports.ViteCodeInspectorPlugin=T;+diff --git a/dist/index.mjs b/dist/index.mjs+index 29bb1c1c91d947cac0f3c74906e12a017a6daacf..a37019fbdfab22fbd9e8724e8837116399e32af6 100644+--- a/dist/index.mjs++++ b/dist/index.mjs+@@ -11,22 +11,22 @@ var h = (e, n, i) => n in e ? w(e, n, { enumerable: !0, configurable: !0, writab+ return e;+ }, f = (e, n) => j(e, P(n));+ var m = (e, n, i) => new Promise((t, a) => {+- var c = (l) => {++ var l = (s) => {+ try {+- p(i.next(l));+- } catch (r) {+- a(r);++ r(i.next(s));++ } catch (p) {++ a(p);+ }+- }, s = (l) => {++ }, c = (s) => {+ try {+- p(i.throw(l));+- } catch (r) {+- a(r);++ r(i.throw(s));++ } catch (p) {++ a(p);+ }+- }, p = (l) => l.done ? t(l.value) : Promise.resolve(l.value).then(c, s);+- p((i = i.apply(e, n)).next());++ }, r = (s) => s.done ? t(s.value) : Promise.resolve(s.value).then(l, c);++ r((i = i.apply(e, n)).next());+ });+-import { isDev as I, isExcludedFile as C, getCodeWithWebComponent as k, normalizePath as T, getMappingFilePath as b, isJsTypeFile as D, transformCode as R } from "@code-inspector/core";++import { isDev as I, isExcludedFile as C, normalizePath as T, getCodeWithWebComponent as k, getMappingFilePath as b, isJsTypeFile as D, transformCode as R } from "@code-inspector/core";+ import v from "chalk";+ const x = "@code-inspector/vite", S = [+ {+@@ -103,24 +103,27 @@ function J(e) {+ return m(this, null, function* () {+ if (C(a, e))+ return t;++ const [l, c] = a.split("?", 2);++ let r = T(l);++ if (r.endsWith(".html") && !c)++ return t;+ t = yield k({+ options: e,+ file: a,+ code: t,+ record: n+ });+- const { escapeTags: c = [], mappings: s } = e, [p, l] = a.split("?", 2);+- let r = T(p);+- r = b(r, s);+- const o = new URLSearchParams(l);++ const { escapeTags: s = [], mappings: p } = e;++ r = b(r, p);++ const g = new URLSearchParams(c);+ if (e.match && !e.match.test(r))+ return t;+- let g = "";+- return D(r) || r.endsWith(".vue") && (F.some((y) => o.get(y) !== null) || o.get("lang") === "tsx" || o.get("lang") === "jsx") ? g = "jsx" : r.endsWith(".html") && o.get("type") === "template" && o.has("vue") || r.endsWith(".vue") && o.get("type") !== "style" && o.get("raw") === null ? g = "vue" : r.endsWith(".svelte") && (g = "svelte"), g ? R({++ let o = "";++ return D(r) || r.endsWith(".vue") && (F.some((y) => g.get(y) !== null) || g.get("lang") === "tsx" || g.get("lang") === "jsx") ? o = "jsx" : r.endsWith(".html") && g.get("type") === "template" && g.has("vue") || r.endsWith(".vue") && g.get("type") !== "style" && g.get("raw") === null ? o = "vue" : r.endsWith(".svelte") && (o = "svelte"), o ? R({+ content: t,+ filePath: r,+- fileType: g,+- escapeTags: c,++ fileType: o,++ escapeTags: s,+ pathType: e.pathType+ }) : t;+ });+@@ -128,8 +131,8 @@ function J(e) {+ // 追加到 html 中,适配 MPA 项目+ transformIndexHtml(t) {+ return m(this, null, function* () {+- var c, s;+- if ((s = (c = e.skipSnippets) == null ? void 0 : c.includes) != null && s.call(c, "htmlScript"))++ var l, c;++ if ((c = (l = e.skipSnippets) == null ? void 0 : l.includes) != null && c.call(l, "htmlScript"))+ return t;+ const a = yield k({+ options: f(u({}, e), { importClient: "code" }),+@@ -146,8 +149,8 @@ function J(e) {+ },+ configureServer(t) {+ const a = t.config.logger.info;+- t.config.logger.info = function(c, s) {+- a.call(this, c, s), L(t.config.plugins), t.config.logger.info = a;++ t.config.logger.info = function(l, c) {++ a.call(this, l, c), L(t.config.plugins), t.config.logger.info = a;+ };+ }+ });diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.tsindex 31fa999c146..923abb89319 100644--- a/plugins/vite/sharedRendererConfig.ts+++ b/plugins/vite/sharedRendererConfig.ts@@ -1,7 +1,5 @@import react from '@vitejs/plugin-react';import { codeInspectorPlugin } from 'code-inspector-plugin';-import { nodePolyfills } from 'vite-plugin-node-polyfills';-import tsconfigPaths from 'vite-tsconfig-paths';import { viteEmotionSpeedy } from './emotionSpeedy';import { viteMarkdownImport } from './markdownImport';@@ -9,7 +7,7 @@ import { viteNodeModuleStub } from './nodeModuleStub';import { vitePlatformResolve } from './platformResolve';/**- * Shared manualChunks — groups leaf-node modules to reduce chunk file count.+ * Shared manual chunk naming — groups leaf-node modules to reduce chunk file count.* Only targets pure data modules (no downstream dependents) to avoid facade chunk issues.*//** Large i18n namespaces that get their own per-locale chunk instead of merging into the locale bundle */@@ -101,16 +99,34 @@ function sharedManualChunks(id: string): string | undefined {if (id.includes('/motion/') || id.includes('framer-motion')) return 'vendor-motion';}+const sharedChunkFileNames = (chunkInfo: { name: string }) => {+ const { name } = chunkInfo;+ if (name.startsWith('i18n-')) return 'i18n/[name]-[hash].js';+ if (name.startsWith('vendor-')) return 'vendor/[name]-[hash].js';+ return 'assets/[name]-[hash].js';+};+export const sharedRollupOutput = {- chunkFileNames: (chunkInfo: { name: string }) => {- const { name } = chunkInfo;- if (name.startsWith('i18n-')) return 'i18n/[name]-[hash].js';- if (name.startsWith('vendor-')) return 'vendor/[name]-[hash].js';- return 'assets/[name]-[hash].js';- },+ chunkFileNames: sharedChunkFileNames,manualChunks: sharedManualChunks,};+interface SharedRolldownOutputOptions {+ strictExecutionOrder?: boolean;+}++export const createSharedRolldownOutput = (options: SharedRolldownOutputOptions = {}) => ({+ chunkFileNames: sharedChunkFileNames,+ strictExecutionOrder: options.strictExecutionOrder ?? true,+ codeSplitting: {+ groups: [+ {+ name: (moduleId: string) => sharedManualChunks(moduleId) ?? null,+ },+ ],+ },+});+type Platform = 'web' | 'mobile' | 'desktop';const isDev = process.env.NODE_ENV !== 'production';@@ -121,14 +137,12 @@ interface SharedRendererOptions {}export function sharedRendererPlugins(options: SharedRendererOptions) {- const defaultTsconfigPaths = options.tsconfigPaths ?? true;return [viteEmotionSpeedy(),viteMarkdownImport(),- nodePolyfills({ include: ['buffer'] }),viteNodeModuleStub(),vitePlatformResolve(options.platform),- defaultTsconfigPaths && tsconfigPaths({ projects: ['.'] }),+isDev &&codeInspectorPlugin({bundler: 'vite',diff --git a/scripts/devStartupSequence.mts b/scripts/devStartupSequence.mtsindex b87c194d11a..bb7475a3df5 100644--- a/scripts/devStartupSequence.mts+++ b/scripts/devStartupSequence.mts@@ -67,8 +67,10 @@ const waitForNextReady = async () => {};const prewarmNextRootCompile = async () => {+ const startedAt = Date.now();const response = await fetch(NEXT_ROOT_URL, { signal: AbortSignal.timeout(120_000) });- console.log(`✅ Next prewarm request finished (${response.status}) ${NEXT_ROOT_URL}`);+ const elapsed = ((Date.now() - startedAt) / 1000).toFixed(2);+ console.log(`✅ Next prewarm request finished (${response.status}) in ${elapsed}s ${NEXT_ROOT_URL}`);};const runNextBackgroundTasks = () => {diff --git a/src/features/DevPanel/CacheViewer/schema.ts b/src/features/DevPanel/CacheViewer/schema.tsindex 8e34ee46b8d..63dc6836fc0 100644--- a/src/features/DevPanel/CacheViewer/schema.ts+++ b/src/features/DevPanel/CacheViewer/schema.ts@@ -1,3 +1,4 @@+import { Buffer } from 'buffer/';import { z } from 'zod';const unstableCacheFileSchema = z.object({diff --git a/src/initialize.ts b/src/initialize.tsindex 325a96699b1..18601b77b3f 100644--- a/src/initialize.ts+++ b/src/initialize.ts@@ -20,8 +20,10 @@ dayjs.extend(isYesterday);// Global fallback: catch async chunk-load failures that escape Error Boundariesif (typeof window !== 'undefined') {window.addEventListener('vite:preloadError', (event) => {- event.preventDefault();- notifyChunkError();+ if (isChunkLoadError((event as any).payload)) {+ event.preventDefault();+ notifyChunkError();+ }});window.addEventListener('unhandledrejection', (event) => {diff --git a/src/libs/next/dynamic.tsx b/src/libs/next/dynamic.tsxindex 9ba588c13f4..1e5e3e18e93 100644--- a/src/libs/next/dynamic.tsx+++ b/src/libs/next/dynamic.tsx@@ -24,6 +24,11 @@ function dynamic<P = NonNullable<unknown>>(): ComponentType<P> {const LazyComponent = lazy(async () => {const mod = await loader();+ if (mod == null) {+ throw new Error(+ 'Dynamic import resolved to undefined. This usually means a chunk failed to load.',+ );+ }if (typeof mod === 'function') {return { default: mod as ComponentType<P> };}diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex bb9c8fd9315..f4961eca3d6 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -53,6 +53,14 @@ import {} from './mecha';import { type FetchOptions } from './types';+const defaultProvider = ModelProvider.OpenAI;+const providersWithDeploymentName = new Set<string>([+ ModelProvider.Azure,+ ModelProvider.AzureAI,+ ModelProvider.KimiCodingPlan,+ ModelProvider.Qwen,+ ModelProvider.Volcengine,+]);interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {agentId?: string;groupId?: string;diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 96464e1270a..203b1dd5804 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -1,5 +1,6 @@import { type ChatContextContent } from '@lobechat/types';import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';+import { Buffer } from 'buffer/';import { t } from 'i18next';import { notification } from '@/components/AntdStaticMethods';diff --git a/src/utils/router.tsx b/src/utils/router.tsxindex 08de965388c..74808c14313 100644--- a/src/utils/router.tsx+++ b/src/utils/router.tsx@@ -25,6 +25,11 @@ async function importModule<T>(importFn: () => Promise<T>): Promise<T> {}function resolveLazyModule<P>(module: { default: ComponentType<P> } | ComponentType<P>) {+ if (module == null) {+ throw new Error(+ 'Dynamic import resolved to undefined. This usually means a chunk failed to load.',+ );+ }if (typeof module === 'function') {return { default: module };}diff --git a/vite.config.ts b/vite.config.tsindex 48f89e0f2eb..1b2dfaa1226 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,4 +1,6 @@-import { resolve } from 'node:path';+import { execFile } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';import type { PluginOption, ViteDevServer } from 'vite';import { defineConfig, loadEnv } from 'vite';@@ -6,10 +8,10 @@ import { VitePWA } from 'vite-plugin-pwa';import { viteEnvRestartKeys } from './plugins/vite/envRestartKeys';import {+ createSharedRolldownOutput,sharedOptimizeDeps,sharedRendererDefine,sharedRendererPlugins,- sharedRollupOutput,} from './plugins/vite/sharedRendererConfig';import { vercelSkewProtection } from './plugins/vite/vercelSkewProtection';@@ -21,17 +23,77 @@ Object.assign(process.env, loadEnv(mode, process.cwd(), ''));const isDev = process.env.NODE_ENV !== 'production';const platform = isMobile ? 'mobile' : 'web';+const resolveCommandExecutable = (cmd: string) => {+ const pathValue = process.env.PATH;+ if (!pathValue) return;++ if (process.platform === 'win32') {+ const pathExt = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD')+ .split(';')+ .filter(Boolean)+ .map((ext) => ext.toLowerCase());+ const candidateNames = cmd.includes('.') ? [cmd] : pathExt.map((ext) => `${cmd}${ext}`);++ for (const entry of pathValue.split(path.delimiter).filter(Boolean)) {+ for (const candidate of candidateNames) {+ const resolved = path.win32.join(entry, candidate);+ if (fs.existsSync(resolved)) return resolved;+ }+ }++ return;+ }++ for (const entry of pathValue.split(path.delimiter).filter(Boolean)) {+ const resolved = path.join(entry, cmd);+ if (fs.existsSync(resolved)) return resolved;+ }+};++const openExternalBrowser = async (url: string) => {+ const command =+ process.platform === 'win32'+ ? {+ args: ['url.dll,FileProtocolHandler', url],+ cmd: 'rundll32',+ }+ : {+ args: [url],+ cmd: process.platform === 'darwin' ? 'open' : 'xdg-open',+ };++ return new Promise<boolean>((resolve) => {+ const executable = resolveCommandExecutable(command.cmd);+ if (!executable) {+ resolve(false);+ return;+ }++ try {+ execFile(executable, command.args, (error) => resolve(!error));+ } catch {+ resolve(false);+ }+ });+};+export default defineConfig({base: isDev ? '/' : process.env.VITE_CDN_BASE || '/_spa/',build: {outDir: isMobile ? 'dist/mobile' : 'dist/desktop',reportCompressedSize: false,- rollupOptions: {- input: resolve(__dirname, isMobile ? 'index.mobile.html' : 'index.html'),- output: sharedRollupOutput,+ rolldownOptions: {+ input: path.resolve(__dirname, isMobile ? 'index.mobile.html' : 'index.html'),+ output: createSharedRolldownOutput({ strictExecutionOrder: isDev }),},},define: sharedRendererDefine({ isMobile, isElectron: false }),+ experimental: {+ bundledDev: true,+ },+ resolve: {+ tsconfigPaths: true,+ },optimizeDeps: sharedOptimizeDeps,plugins: [vercelSkewProtection(),@@ -48,15 +110,110 @@ export default defineConfig({cyan: (s: string) => `\x1B[36m${s}\x1B[0m`,};const { info } = server.config.logger;+ const isBundledDev = (server.config.experimental as any)?.bundledDev;++ const getProxyUrl = () => {+ const urls = server.resolvedUrls;+ if (!urls?.local?.[0]) return;+ const localHost = urls.local[0].replace(/\/$/, '');+ return `${ONLINE_HOST}/_dangerous_local_dev_proxy?debug-host=${encodeURIComponent(localHost)}`;+ };+ const printProxyUrl = () => {+ const proxyUrl = getProxyUrl();+ if (!proxyUrl) return;+ const colorUrl = (url: string) =>+ c.cyan(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));+ info(` ${c.green('➜')} ${c.bold('Debug Proxy')}: ${colorUrl(proxyUrl)}`);+ };+ const openProxyUrl = async () => {+ const proxyUrl = getProxyUrl();+ if (!proxyUrl) return;++ const opened = await openExternalBrowser(proxyUrl);++ if (!opened) {+ server.config.logger.warn(`Failed to open Debug Proxy automatically: ${proxyUrl}`);+ }+ };++ if (isBundledDev) {+ // Disable Vite's built-in browser opening. We always open the debug+ // proxy URL after the first bundled compile finishes instead.+ server.openBrowser = () => {};++ const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];+ let spinnerIdx = 0;+ let spinnerTimer: NodeJS.Timeout | null = null;+ const formatElapsed = (ms: number) =>+ ms < 1000 ? `${Math.max(0, Math.round(ms))}ms` : `${(ms / 1000).toFixed(1)}s`;++ const startSpinner = (msg: string, since: number) => {+ spinnerIdx = 0;+ spinnerTimer = setInterval(() => {+ const elapsed = formatElapsed(Date.now() - since);+ process.stdout.write(`\r${c.cyan(spinnerFrames[spinnerIdx])} ${msg} (${elapsed})`);+ spinnerIdx = (spinnerIdx + 1) % spinnerFrames.length;+ }, 80);+ };+ const stopSpinner = (clearLine = true) => {+ if (spinnerTimer) {+ clearInterval(spinnerTimer);+ spinnerTimer = null;+ }+ if (clearLine) process.stdout.write('\r\x1B[K');+ };++ server.httpServer?.once('listening', () => {+ void (async () => {+ const rootUrl =+ server.resolvedUrls?.local?.[0] ||+ `http://localhost:${String(server.config.server.port || 9876)}/`;+ const startedAt = Date.now();+ const timeout = 180_000;+ const interval = 400;+ let ready = false;++ startSpinner('Vite: compile and bundle...', startedAt);++ try {+ while (Date.now() - startedAt < timeout) {+ try {+ const res = await fetch(rootUrl, { signal: AbortSignal.timeout(5_000) });+ const text = await res.text();+ if (text.includes('Bundling in progress')) {+ await new Promise((r) => setTimeout(r, interval));+ continue;+ }+ ready = true;+ stopSpinner();+ info(+ ` ${c.green('✅')} Vite: compile and bundle finished (${res.status}) ${rootUrl}`,+ );+ void openProxyUrl();+ break;+ } catch {+ await new Promise((r) => setTimeout(r, interval));+ }+ }+ } catch (e) {+ stopSpinner();+ console.warn('⚠️ Vite: could not wait for compile and bundle:', e);+ }++ if (!ready && spinnerTimer) {+ stopSpinner();+ console.warn(`⚠️ Vite: compile and bundle timed out after ${timeout / 1000}s`);+ }++ printProxyUrl();+ })();+ });+ }+return () => {server.printUrls = () => {- const urls = server.resolvedUrls;- if (!urls?.local?.[0]) return;- const localHost = urls.local[0].replace(/\/$/, '');- const proxyUrl = `${ONLINE_HOST}/_dangerous_local_dev_proxy?debug-host=${encodeURIComponent(localHost)}`;- const colorUrl = (url: string) =>- c.cyan(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));- info(` ${c.green('➜')} ${c.bold('Debug Proxy')}: ${colorUrl(proxyUrl)}`);+ if (isBundledDev) return;+ printProxyUrl();};};},@@ -106,8 +263,8 @@ export default defineConfig({server: {cors: true,- port: 9876,host: true,+ port: 9876,proxy: {'/api': `http://localhost:${process.env.PORT || 3010}`,'/oidc': `http://localhost:${process.env.PORT || 3010}`,