Skip to content

🤯 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.

✨ feat: support double-click to open multi agent window on the desktop (#9331)

Shinji-Lia060901c65e3
diff --git a/apps/desktop/src/main/appBrowsers.ts b/apps/desktop/src/main/appBrowsers.ts
index b11357c9424..551faaf1f11 100644
--- a/apps/desktop/src/main/appBrowsers.ts
+++ b/apps/desktop/src/main/appBrowsers.ts
@@ -46,4 +46,55 @@ export const appBrowsers = {
},
} satisfies Record<string, BrowserWindowOpts>;
+// Window templates for multi-instance windows
+export interface WindowTemplate {
+ allowMultipleInstances: boolean;
+ // Include common BrowserWindow options
+ autoHideMenuBar?: boolean;
+ baseIdentifier: string;
+ basePath: string;
+ devTools?: boolean;
+ height?: number;
+ keepAlive?: boolean;
+ minWidth?: number;
+ parentIdentifier?: string;
+ showOnInit?: boolean;
+ title?: string;
+ titleBarStyle?: 'hidden' | 'default' | 'hiddenInset' | 'customButtonsOnHover';
+ vibrancy?:
+ | 'appearance-based'
+ | 'content'
+ | 'fullscreen-ui'
+ | 'header'
+ | 'hud'
+ | 'menu'
+ | 'popover'
+ | 'selection'
+ | 'sheet'
+ | 'sidebar'
+ | 'titlebar'
+ | 'tooltip'
+ | 'under-page'
+ | 'under-window'
+ | 'window';
+ width?: number;
+}
+
+export const windowTemplates = {
+ chatSingle: {
+ allowMultipleInstances: true,
+ autoHideMenuBar: true,
+ baseIdentifier: 'chatSingle',
+ basePath: '/chat',
+ height: 600,
+ keepAlive: false, // Multi-instance windows don't need to stay alive
+ minWidth: 400,
+ parentIdentifier: 'chat',
+ titleBarStyle: 'hidden',
+ vibrancy: 'under-window',
+ width: 900,
+ },
+} satisfies Record<string, WindowTemplate>;
+
export type AppBrowsersIdentifiers = keyof typeof appBrowsers;
+export type WindowTemplateIdentifiers = keyof typeof windowTemplates;
diff --git a/apps/desktop/src/main/controllers/BrowserWindowsCtr.ts b/apps/desktop/src/main/controllers/BrowserWindowsCtr.ts
index 51ae339ee92..96e7affe015 100644
--- a/apps/desktop/src/main/controllers/BrowserWindowsCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserWindowsCtr.ts
@@ -1,7 +1,7 @@
import { InterceptRouteParams } from '@lobechat/electron-client-ipc';
import { extractSubPath, findMatchingRoute } from '~common/routes';
-import { AppBrowsersIdentifiers, BrowsersIdentifiers } from '@/appBrowsers';
+import { AppBrowsersIdentifiers, BrowsersIdentifiers, WindowTemplateIdentifiers } from '@/appBrowsers';
import { IpcClientEventSender } from '@/types/ipcClientEvent';
import { ControllerModule, ipcClientEvent, shortcut } from './index';
@@ -100,6 +100,77 @@ export default class BrowserWindowsCtr extends ControllerModule {
}
}
+ /**
+ * Create a new multi-instance window
+ */
+ @ipcClientEvent('createMultiInstanceWindow')
+ async createMultiInstanceWindow(params: {
+ templateId: WindowTemplateIdentifiers;
+ path: string;
+ uniqueId?: string;
+ }) {
+ try {
+ console.log('[BrowserWindowsCtr] Creating multi-instance window:', params);
+
+ const result = this.app.browserManager.createMultiInstanceWindow(
+ params.templateId,
+ params.path,
+ params.uniqueId,
+ );
+
+ // Show the window
+ result.browser.show();
+
+ return {
+ success: true,
+ windowId: result.identifier,
+ };
+ } catch (error) {
+ console.error('[BrowserWindowsCtr] Failed to create multi-instance window:', error);
+ return {
+ error: error.message,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Get all windows by template
+ */
+ @ipcClientEvent('getWindowsByTemplate')
+ async getWindowsByTemplate(templateId: string) {
+ try {
+ const windowIds = this.app.browserManager.getWindowsByTemplate(templateId);
+ return {
+ success: true,
+ windowIds,
+ };
+ } catch (error) {
+ console.error('[BrowserWindowsCtr] Failed to get windows by template:', error);
+ return {
+ error: error.message,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Close all windows by template
+ */
+ @ipcClientEvent('closeWindowsByTemplate')
+ async closeWindowsByTemplate(templateId: string) {
+ try {
+ this.app.browserManager.closeWindowsByTemplate(templateId);
+ return { success: true };
+ } catch (error) {
+ console.error('[BrowserWindowsCtr] Failed to close windows by template:', error);
+ return {
+ error: error.message,
+ success: false,
+ };
+ }
+ }
+
/**
* Open target window and navigate to specified sub-path
*/
diff --git a/apps/desktop/src/main/core/browser/BrowserManager.ts b/apps/desktop/src/main/core/browser/BrowserManager.ts
index ad75dafd849..11323a6cd29 100644
--- a/apps/desktop/src/main/core/browser/BrowserManager.ts
+++ b/apps/desktop/src/main/core/browser/BrowserManager.ts
@@ -3,7 +3,7 @@ import { WebContents } from 'electron';
import { createLogger } from '@/utils/logger';
-import { AppBrowsersIdentifiers, appBrowsers } from '../../appBrowsers';
+import { AppBrowsersIdentifiers, appBrowsers, WindowTemplate, WindowTemplateIdentifiers, windowTemplates } from '../../appBrowsers';
import type { App } from '../App';
import type { BrowserWindowOpts } from './Browser';
import Browser from './Browser';
@@ -14,9 +14,9 @@ const logger = createLogger('core:BrowserManager');
export class BrowserManager {
app: App;
- browsers: Map<AppBrowsersIdentifiers, Browser> = new Map();
+ browsers: Map<string, Browser> = new Map();
- private webContentsMap = new Map<WebContents, AppBrowsersIdentifiers>();
+ private webContentsMap = new Map<WebContents, string>();
constructor(app: App) {
logger.debug('Initializing BrowserManager');
@@ -51,12 +51,12 @@ export class BrowserManager {
};
broadcastToWindow = <T extends MainBroadcastEventKey>(
- identifier: AppBrowsersIdentifiers,
+ identifier: string,
event: T,
data: MainBroadcastParams<T>,
) => {
logger.debug(`Broadcasting event ${event} to window: ${identifier}`);
- this.browsers.get(identifier).broadcast(event, data);
+ this.browsers.get(identifier)?.broadcast(event, data);
};
/**
@@ -87,13 +87,21 @@ export class BrowserManager {
* @param identifier Window identifier
* @param subPath Sub-path, such as 'agent', 'about', etc.
*/
- async redirectToPage(identifier: AppBrowsersIdentifiers, subPath?: string) {
+ async redirectToPage(identifier: string, subPath?: string) {
try {
// Ensure window is retrieved or created
const browser = this.retrieveByIdentifier(identifier);
browser.hide();
- const baseRoute = appBrowsers[identifier].path;
+ // Handle both static and dynamic windows
+ let baseRoute: string;
+ if (identifier in appBrowsers) {
+ baseRoute = appBrowsers[identifier as AppBrowsersIdentifiers].path;
+ } else {
+ // For dynamic windows, extract base route from the browser options
+ const browserOptions = browser.options;
+ baseRoute = browserOptions.path;
+ }
// Build complete URL path
const fullPath = subPath ? `${baseRoute}/${subPath}` : baseRoute;
@@ -114,13 +122,75 @@ export class BrowserManager {
/**
* get Browser by identifier
*/
- retrieveByIdentifier(identifier: AppBrowsersIdentifiers) {
+ retrieveByIdentifier(identifier: string) {
const browser = this.browsers.get(identifier);
if (browser) return browser;
- logger.debug(`Browser ${identifier} not found, initializing new instance`);
- return this.retrieveOrInitialize(appBrowsers[identifier]);
+ // Check if it's a static browser
+ if (identifier in appBrowsers) {
+ logger.debug(`Browser ${identifier} not found, initializing new instance`);
+ return this.retrieveOrInitialize(appBrowsers[identifier as AppBrowsersIdentifiers]);
+ }
+
+ throw new Error(`Browser ${identifier} not found and is not a static browser`);
+ }
+
+ /**
+ * Create a multi-instance window from template
+ * @param templateId Template identifier
+ * @param path Full path with query parameters
+ * @param uniqueId Optional unique identifier, will be generated if not provided
+ * @returns The window identifier and Browser instance
+ */
+ createMultiInstanceWindow(templateId: WindowTemplateIdentifiers, path: string, uniqueId?: string) {
+ const template = windowTemplates[templateId];
+ if (!template) {
+ throw new Error(`Window template ${templateId} not found`);
+ }
+
+ // Generate unique identifier
+ const windowId = uniqueId || `${template.baseIdentifier}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+
+ // Create browser options from template
+ const browserOpts: BrowserWindowOpts = {
+ ...template,
+ identifier: windowId,
+ path: path,
+ };
+
+ logger.debug(`Creating multi-instance window: ${windowId} with path: ${path}`);
+
+ const browser = this.retrieveOrInitialize(browserOpts);
+
+ return {
+ identifier: windowId,
+ browser: browser,
+ };
+ }
+
+ /**
+ * Get all windows based on template
+ * @param templateId Template identifier
+ * @returns Array of window identifiers matching the template
+ */
+ getWindowsByTemplate(templateId: string): string[] {
+ const prefix = `${templateId}_`;
+ return Array.from(this.browsers.keys()).filter(id => id.startsWith(prefix));
+ }
+
+ /**
+ * Close all windows based on template
+ * @param templateId Template identifier
+ */
+ closeWindowsByTemplate(templateId: string): void {
+ const windowIds = this.getWindowsByTemplate(templateId);
+ windowIds.forEach(id => {
+ const browser = this.browsers.get(id);
+ if (browser) {
+ browser.close();
+ }
+ });
}
/**
@@ -144,7 +214,7 @@ export class BrowserManager {
* @param options Browser window options
*/
private retrieveOrInitialize(options: BrowserWindowOpts) {
- let browser = this.browsers.get(options.identifier as AppBrowsersIdentifiers);
+ let browser = this.browsers.get(options.identifier);
if (browser) {
logger.debug(`Retrieved existing browser: ${options.identifier}`);
return browser;
@@ -153,7 +223,7 @@ export class BrowserManager {
logger.debug(`Creating new browser: ${options.identifier}`);
browser = new Browser(options, this.app);
- const identifier = options.identifier as AppBrowsersIdentifiers;
+ const identifier = options.identifier;
this.browsers.set(identifier, browser);
// 记录 WebContents 和 identifier 的映射
@@ -166,32 +236,32 @@ export class BrowserManager {
browser.browserWindow.on('show', () => {
if (browser.webContents)
- this.webContentsMap.set(browser.webContents, browser.identifier as AppBrowsersIdentifiers);
+ this.webContentsMap.set(browser.webContents, browser.identifier);
});
return browser;
}
closeWindow(identifier: string) {
- const browser = this.browsers.get(identifier as AppBrowsersIdentifiers);
+ const browser = this.browsers.get(identifier);
browser?.close();
}
minimizeWindow(identifier: string) {
- const browser = this.browsers.get(identifier as AppBrowsersIdentifiers);
+ const browser = this.browsers.get(identifier);
browser?.browserWindow.minimize();
}
maximizeWindow(identifier: string) {
- const browser = this.browsers.get(identifier as AppBrowsersIdentifiers);
- if (browser.browserWindow.isMaximized()) {
+ const browser = this.browsers.get(identifier);
+ if (browser?.browserWindow.isMaximized()) {
browser?.browserWindow.unmaximize();
} else {
browser?.browserWindow.maximize();
}
}
- getIdentifierByWebContents(webContents: WebContents): AppBrowsersIdentifiers | null {
+ getIdentifierByWebContents(webContents: WebContents): string | null {
return this.webContentsMap.get(webContents) || null;
}
diff --git a/packages/electron-client-ipc/src/events/windows.ts b/packages/electron-client-ipc/src/events/windows.ts
index 68f4963a46f..14191590a99 100644
--- a/packages/electron-client-ipc/src/events/windows.ts
+++ b/packages/electron-client-ipc/src/events/windows.ts
@@ -1,5 +1,23 @@
import { InterceptRouteParams, InterceptRouteResponse } from '../types/route';
+export interface CreateMultiInstanceWindowParams {
+ templateId: string;
+ path: string;
+ uniqueId?: string;
+}
+
+export interface CreateMultiInstanceWindowResponse {
+ success: boolean;
+ windowId?: string;
+ error?: string;
+}
+
+export interface GetWindowsByTemplateResponse {
+ success: boolean;
+ windowIds?: string[];
+ error?: string;
+}
+
export interface WindowsDispatchEvents {
/**
* 拦截客户端路由导航请求
@@ -14,4 +32,25 @@ export interface WindowsDispatchEvents {
openDevtools: () => void;
openSettingsWindow: (tab?: string) => void;
+
+ /**
+ * 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;
+
+ /**
+ * Close all windows by template
+ * @param templateId Template identifier
+ * @returns Operation result
+ */
+ closeWindowsByTemplate: (templateId: string) => { success: boolean; error?: string };
}
diff --git a/src/app/[variants]/(main)/_layout/Desktop/DesktopLayoutContainer.tsx b/src/app/[variants]/(main)/_layout/Desktop/DesktopLayoutContainer.tsx
index 92c73d1f214..f063d832098 100644
--- a/src/app/[variants]/(main)/_layout/Desktop/DesktopLayoutContainer.tsx
+++ b/src/app/[variants]/(main)/_layout/Desktop/DesktopLayoutContainer.tsx
@@ -1,6 +1,6 @@
import { useTheme } from 'antd-style';
import { usePathname } from 'next/navigation';
-import { PropsWithChildren, memo } from 'react';
+import { PropsWithChildren, Suspense, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import SideBar from './SideBar';
@@ -11,7 +11,9 @@ const DesktopLayoutContainer = memo<PropsWithChildren>(({ children }) => {
const hideSideBar = pathname.startsWith('/settings');
return (
<>
- {!hideSideBar && <SideBar />}
+ <Suspense>
+ {!hideSideBar && <SideBar />}
+ </Suspense>
<Flexbox
style={{
background: theme.colorBgLayout,
diff --git a/src/app/[variants]/(main)/_layout/Desktop/SideBar/index.tsx b/src/app/[variants]/(main)/_layout/Desktop/SideBar/index.tsx
index a2e4edc70c7..7af50e18eb8 100644
--- a/src/app/[variants]/(main)/_layout/Desktop/SideBar/index.tsx
+++ b/src/app/[variants]/(main)/_layout/Desktop/SideBar/index.tsx
@@ -6,6 +6,7 @@ import { Suspense, memo } from 'react';
import { isDesktop } from '@/const/version';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
+import { useIsSingleMode } from '@/hooks/useIsSingleMode';
import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -26,11 +27,12 @@ const Top = () => {
const Nav = memo(() => {
const theme = useTheme();
+ const isSingleMode = useIsSingleMode()
const inZenMode = useGlobalStore(systemStatusSelectors.inZenMode);
const { showPinList } = useServerConfigStore(featureFlagsSelectors);
return (
- !inZenMode && (
+ !inZenMode && !isSingleMode && (
<SideNav
avatar={
<div className={electronStylish.nodrag}>
diff --git a/src/app/[variants]/(main)/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/_layout/Desktop/index.tsx
index 841d4336ac3..ef9ea9f38bd 100644
--- a/src/app/[variants]/(main)/_layout/Desktop/index.tsx
+++ b/src/app/[variants]/(main)/_layout/Desktop/index.tsx
@@ -48,7 +48,9 @@ const Layout = memo<PropsWithChildren>(({ children }) => {
<DesktopLayoutContainer>{children}</DesktopLayoutContainer>
) : (
<>
- <SideBar />
+ <Suspense>
+ <SideBar />
+ </Suspense>
{children}
</>
)}
diff --git a/src/app/[variants]/(main)/chat/(workspace)/@topic/features/TopicListContent/TopicItem/TopicContent.tsx b/src/app/[variants]/(main)/chat/(workspace)/@topic/features/TopicListContent/TopicItem/TopicContent.tsx
index 2e191809be7..4cfc6dfc48a 100644
--- a/src/app/[variants]/(main)/chat/(workspace)/@topic/features/TopicListContent/TopicItem/TopicContent.tsx
+++ b/src/app/[variants]/(main)/chat/(workspace)/@topic/features/TopicListContent/TopicItem/TopicContent.tsx
@@ -2,6 +2,7 @@ import { ActionIcon, Dropdown, EditableText, Icon, type MenuProps, Text } from '
import { App } from 'antd';
import { createStyles } from 'antd-style';
import {
+ ExternalLink,
LucideCopy,
LucideLoader2,
MoreVertical,
@@ -16,8 +17,10 @@ import { Flexbox } from 'react-layout-kit';
import BubblesLoading from '@/components/BubblesLoading';
import { LOADING_FLAT } from '@/const/message';
+import { isDesktop } from '@/const/version';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
const useStyles = createStyles(({ css }) => ({
content: css`
@@ -45,6 +48,8 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
const mobile = useIsMobile();
+ const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
+
const [
editing,
favoriteTopic,
@@ -53,6 +58,7 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
autoRenameTopicTitle,
duplicateTopic,
isLoading,
+ activeId,
] = useChatStore((s) => [
s.topicRenamingId === id,
s.favoriteTopic,
@@ -61,6 +67,7 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
s.autoRenameTopicTitle,
s.duplicateTopic,
s.topicLoadingIds.includes(id),
+ s.activeId,
]);
const { styles, theme } = useStyles();
@@ -88,6 +95,18 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
toggleEditing(true);
},
},
+ ...(isDesktop
+ ? [
+ {
+ icon: <Icon icon={ExternalLink} />,
+ key: 'openInNewWindow',
+ label: '单独打开页面',
+ onClick: () => {
+ openTopicInNewWindow(activeId, id);
+ },
+ },
+ ]
+ : []),
{
type: 'divider',
},
@@ -134,7 +153,7 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
},
},
],
- [],
+ [id, activeId, autoRenameTopicTitle, duplicateTopic, removeTopic, t, toggleEditing, openTopicInNewWindow],
);
return (
@@ -169,6 +188,11 @@ const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
<Text
className={styles.title}
ellipsis={{ rows: 1, tooltip: { placement: 'left', title } }}
+ onDoubleClick={() => {
+ if (isDesktop) {
+ openTopicInNewWindow(activeId, id)
+ }
+ }}
style={{ margin: 0 }}
>
{title}
diff --git a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
index 00fe82d4768..77c081cb1d1 100644
--- a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
+++ b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
@@ -5,6 +5,7 @@ import { ItemType } from 'antd/es/menu/interface';
import isEqual from 'fast-deep-equal';
import {
Check,
+ ExternalLink,
HardDriveDownload,
ListTree,
LucideCopy,
@@ -17,8 +18,9 @@ import {
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { isServerMode } from '@/const/version';
+import { isDesktop, isServerMode } from '@/const/version';
import { configService } from '@/services/config';
+import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { sessionHelpers } from '@/store/session/helpers';
import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
@@ -41,6 +43,8 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, setOpen })
const { styles } = useStyles();
const { t } = useTranslation('chat');
+ const openSessionInNewWindow = useGlobalStore((s) => s.openSessionInNewWindow);
+
const sessionCustomGroups = useSessionStore(sessionGroupSelectors.sessionGroupItems, isEqual);
const [pin, removeSession, pinSession, duplicateSession, updateSessionGroup] = useSessionStore(
(s) => {
@@ -82,6 +86,19 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, setOpen })
duplicateSession(id);
},
},
+ ...(isDesktop
+ ? [
+ {
+ icon: <Icon icon={ExternalLink} />,
+ key: 'openInNewWindow',
+ label: '单独打开页面',
+ onClick: ({ domEvent }: { domEvent: Event }) => {
+ domEvent.stopPropagation();
+ openSessionInNewWindow(id);
+ },
+ },
+ ]
+ : []),
{
type: 'divider',
},
@@ -167,7 +184,7 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, setOpen })
},
] as ItemType[]
).filter(Boolean),
- [id, pin],
+ [id, pin, openSessionInNewWindow],
);
return (
diff --git a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
index e968d39003b..edbef13a74b 100644
--- a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
+++ b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
@@ -1,12 +1,14 @@
import { ModelTag } from '@lobehub/icons';
-import { memo, useMemo, useState } from 'react';
+import React, { memo, useMemo, useState } from 'react';
import { Flexbox } from 'react-layout-kit';
import { shallow } from 'zustand/shallow';
+import { isDesktop } from '@/const/version';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { chatSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { sessionHelpers } from '@/store/session/helpers';
import { sessionMetaSelectors, sessionSelectors } from '@/store/session/selectors';
@@ -24,6 +26,8 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
const [createGroupModalOpen, setCreateGroupModalOpen] = useState(false);
const [defaultModel] = useAgentStore((s) => [agentSelectors.inboxAgentModel(s)]);
+ const openSessionInNewWindow = useGlobalStore((s) => s.openSessionInNewWindow);
+
const [active] = useSessionStore((s) => [s.activeId === id]);
const [loading] = useChatStore((s) => [chatSelectors.isAIGenerating(s) && id === s.activeId]);
@@ -46,6 +50,24 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
const showModel = model !== defaultModel;
+ const handleDoubleClick = () => {
+ if (isDesktop) {
+ openSessionInNewWindow(id);
+ }
+ };
+
+ const handleDragStart = (e: React.DragEvent) => {
+ // Set drag data to identify the session being dragged
+ e.dataTransfer.setData('text/plain', id);
+ };
+
+ const handleDragEnd = (e: React.DragEvent) => {
+ // If drag ends without being dropped in a valid target, open in new window
+ if (isDesktop && e.dataTransfer.dropEffect === 'none') {
+ openSessionInNewWindow(id);
+ }
+ };
+
const actions = useMemo(
() => (
<Actions
@@ -78,8 +100,12 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
avatarBackground={avatarBackground}
date={updateAt?.valueOf()}
description={description}
+ draggable={isDesktop}
key={id}
loading={loading}
+ onDoubleClick={handleDoubleClick}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
pin={pin}
showAction={open}
styles={{
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx b/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx
index 468dc0d1348..c8a74fd3719 100644
--- a/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx
@@ -7,6 +7,7 @@ import { PropsWithChildren, memo, useEffect, useMemo, useState } from 'react';
import { withSuspense } from '@/components/withSuspense';
import { FOLDER_WIDTH } from '@/const/layoutTokens';
+import { useIsSingleMode } from '@/hooks/useIsSingleMode';
import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -33,11 +34,14 @@ export const useStyles = createStyles(({ css, token }) => ({
}));
const SessionPanel = memo<PropsWithChildren>(({ children }) => {
+ const isSingleMode = useIsSingleMode();
+
const { md = true } = useResponsive();
const [isPinned] = usePinnedAgentState();
const { styles } = useStyles();
+
const [sessionsWidth, sessionExpandable, updatePreference] = useGlobalStore((s) => [
systemStatusSelectors.sessionWidth(s),
systemStatusSelectors.showSessionPanel(s),
@@ -72,6 +76,12 @@ const SessionPanel = memo<PropsWithChildren>(({ children }) => {
const { appearance } = useThemeMode();
const SessionPanel = useMemo(() => {
+ if (isSingleMode) {
+ // 在单一模式下,仍然渲染 children 以确保 SessionHydration 等逻辑组件正常工作
+ // 但使用隐藏样式而不是 return null
+ return <div style={{ display: 'none' }}>{children}</div>;
+ }
+
return (
<DraggablePanel
className={styles.panel}
@@ -92,7 +102,7 @@ const SessionPanel = memo<PropsWithChildren>(({ children }) => {
</DraggablePanelContainer>
</DraggablePanel>
);
- }, [sessionsWidth, md, isPinned, sessionExpandable, tmpWidth, appearance]);
+ }, [sessionsWidth, md, isPinned, sessionExpandable, tmpWidth, appearance, isSingleMode]);
return SessionPanel;
});
diff --git a/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx b/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx
index 626f6abdf9f..bfedf3c37ff 100644
--- a/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx
+++ b/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx
@@ -6,6 +6,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useIsSingleMode } from '@/hooks/useIsSingleMode';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
@@ -15,6 +16,7 @@ import { HotkeyEnum } from '@/types/hotkey';
export const TOOGLE_PANEL_BUTTON_ID = 'toggle-panel-button';
const TogglePanelButton = memo(() => {
+ const isSingleMode = useIsSingleMode();
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleLeftPanel));
const { t } = useTranslation(['chat', 'hotkey']);
@@ -22,6 +24,10 @@ const TogglePanelButton = memo(() => {
const showSessionPanel = useGlobalStore(systemStatusSelectors.showSessionPanel);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ if (isSingleMode) {
+ return null
+ }
+
return (
<Tooltip hotkey={hotkey} title={t('toggleLeftPanel.title', { ns: 'hotkey' })}>
<ActionIcon
diff --git a/src/features/ElectronTitlebar/Connection/index.tsx b/src/features/ElectronTitlebar/Connection/index.tsx
index dea8f6c44d0..06c1db46789 100644
--- a/src/features/ElectronTitlebar/Connection/index.tsx
+++ b/src/features/ElectronTitlebar/Connection/index.tsx
@@ -20,7 +20,6 @@ const useStyles = createStyles(({ css }) => {
const Connection = () => {
const { styles, theme } = useStyles();
-
const [isOpen, setIsOpen] = useState(false);
const [isWaiting, setWaiting] = useState(false);
diff --git a/src/hooks/useIsSingleMode.test.ts b/src/hooks/useIsSingleMode.test.ts
new file mode 100644
index 00000000000..ad3b0de2cef
--- /dev/null
+++ b/src/hooks/useIsSingleMode.test.ts
@@ -0,0 +1,66 @@
+import { renderHook } from '@testing-library/react';
+import { ReadonlyURLSearchParams } from 'next/navigation';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useIsSingleMode } from './useIsSingleMode';
+
+// Mock next/navigation
+const mockUseSearchParams = vi.hoisted(() => vi.fn());
+vi.mock('next/navigation', () => ({
+ useSearchParams: mockUseSearchParams,
+}));
+
+describe('useIsSingleMode', () => {
+
+ it('should return false initially (during SSR)', () => {
+ const mockSearchParams = {
+ get: vi.fn(() => 'single'),
+ } as unknown as ReadonlyURLSearchParams;
+
+ mockUseSearchParams.mockReturnValue(mockSearchParams);
+
+ const { result } = renderHook(() => useIsSingleMode());
+
+ // In test environment, useEffect runs synchronously, so it will immediately detect single mode
+ expect(result.current).toBe(true);
+ });
+
+ it('should return true when mode=single', () => {
+ const mockSearchParams = {
+ get: vi.fn((key: string) => (key === 'mode' ? 'single' : null)),
+ } as unknown as ReadonlyURLSearchParams;
+
+ mockUseSearchParams.mockReturnValue(mockSearchParams);
+
+ const { result } = renderHook(() => useIsSingleMode());
+
+ // Should immediately detect single mode in test environment
+ expect(result.current).toBe(true);
+ });
+
+ it('should return false when mode is not single', () => {
+ const mockSearchParams = {
+ get: vi.fn((key: string) => (key === 'mode' ? 'normal' : null)),
+ } as unknown as ReadonlyURLSearchParams;
+
+ mockUseSearchParams.mockReturnValue(mockSearchParams);
+
+ const { result } = renderHook(() => useIsSingleMode());
+
+ // Should return false for non-single mode
+ expect(result.current).toBe(false);
+ });
+
+ it('should return false when no mode parameter exists', () => {
+ const mockSearchParams = {
+ get: vi.fn(() => null),
+ } as unknown as ReadonlyURLSearchParams;
+
+ mockUseSearchParams.mockReturnValue(mockSearchParams);
+
+ const { result } = renderHook(() => useIsSingleMode());
+
+ // Should return false when no mode parameter
+ expect(result.current).toBe(false);
+ });
+});
\ No newline at end of file
diff --git a/src/hooks/useIsSingleMode.ts b/src/hooks/useIsSingleMode.ts
new file mode 100644
index 00000000000..156fefe7f72
--- /dev/null
+++ b/src/hooks/useIsSingleMode.ts
@@ -0,0 +1,29 @@
+'use client';
+
+import { useSearchParams } from 'next/navigation';
+import { useEffect, useState } from 'react';
+
+/**
+ * Hook to check if the current page is in single mode
+ * Single mode is used for standalone windows in desktop app
+ * @returns boolean indicating if the current page is in single mode
+ */
+export const useIsSingleMode = (): boolean => {
+ const [isSingleMode, setIsSingleMode] = useState(false);
+ const [mounted, setMounted] = useState(false);
+
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+
+ const searchParams = useSearchParams();
+
+ useEffect(() => {
+ if (mounted) {
+ setIsSingleMode(searchParams.get('mode') === 'single');
+ }
+ }, [searchParams, mounted]);
+
+ // Return false during SSR or before hydration
+ return mounted ? isSingleMode : false;
+};
\ No newline at end of file
diff --git a/src/store/global/actions/general.ts b/src/store/global/actions/general.ts
index 371fab6a863..5c4404fa04c 100644
--- a/src/store/global/actions/general.ts
+++ b/src/store/global/actions/general.ts
@@ -20,6 +20,8 @@ import type { GlobalStore } from '../store';
const n = setNamespace('g');
export interface GlobalGeneralAction {
+ openSessionInNewWindow: (sessionId: string) => Promise<void>;
+ openTopicInNewWindow: (sessionId: string, topicId: string) => Promise<void>;
switchLocale: (locale: LocaleMode) => void;
switchThemeMode: (themeMode: ThemeMode, params?: { skipBroadcast?: boolean }) => void;
updateSystemStatus: (status: Partial<SystemStatus>, action?: any) => void;
@@ -33,6 +35,50 @@ export const generalActionSlice: StateCreator<
[],
GlobalGeneralAction
> = (set, get) => ({
+ openSessionInNewWindow: async (sessionId: string) => {
+ if (!isDesktop) return;
+
+ try {
+ const { dispatch } = await import('@lobechat/electron-client-ipc');
+
+ const url = `/chat?session=${sessionId}&mode=single`;
+
+ const result = await dispatch('createMultiInstanceWindow', {
+ path: url,
+ templateId: 'chatSingle',
+ uniqueId: `chat_${sessionId}`,
+ });
+
+ if (!result.success) {
+ console.error('Failed to open session in new window:', result.error);
+ }
+ } catch (error) {
+ console.error('Error opening session in new window:', error);
+ }
+ },
+
+ openTopicInNewWindow: async (sessionId: string, topicId: string) => {
+ if (!isDesktop) return;
+
+ try {
+ const { dispatch } = await import('@lobechat/electron-client-ipc');
+
+ const url = `/chat?session=${sessionId}&topic=${topicId}&mode=single`;
+
+ const result = await dispatch('createMultiInstanceWindow', {
+ path: url,
+ templateId: 'chatSingle',
+ uniqueId: `chat_${sessionId}_${topicId}`,
+ });
+
+ if (!result.success) {
+ console.error('Failed to open topic in new window:', result.error);
+ }
+ } catch (error) {
+ console.error('Error opening topic in new window:', error);
+ }
+ },
+
switchLocale: (locale) => {
get().updateSystemStatus({ language: locale });