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.

🐛 fix(mobile): use agents directly instead of legacy sessions (#21323)

Bryan7910b3ca9fa0
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7c619e19c2f..129044a6ef9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2060,6 +2060,9 @@
"sender.unknownMember": "Member",
"sessionGroup.config": "Category Management",
"sessionGroup.confirmRemoveGroupAlert": "This category is about to be deleted. After deletion, the agents in this category will be moved to the default list. Please confirm your operation.",
+ "sessionGroup.createAgentFailed": "Couldn't create the agent. Please try again.",
+ "sessionGroup.createAgentPinFailed": "Agent created, but pinning failed. You can pin it from the list.",
+ "sessionGroup.createAgentRefreshFailed": "Agent created, but the list couldn't refresh. Refresh the list to see it.",
"sessionGroup.createAgentSuccess": "Agent created successfully",
"sessionGroup.createGroup": "Add New Category",
"sessionGroup.createGroupFailed": "Failed to create category",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 617d79c9db4..aaff2ca590e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2060,6 +2060,9 @@
"sender.unknownMember": "成员",
"sessionGroup.config": "分类管理",
"sessionGroup.confirmRemoveGroupAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
+ "sessionGroup.createAgentFailed": "助理创建失败,请重试。",
+ "sessionGroup.createAgentPinFailed": "助理已创建,但置顶失败。可在列表中重新置顶。",
+ "sessionGroup.createAgentRefreshFailed": "助理已创建,但列表刷新失败。请刷新列表查看。",
"sessionGroup.createAgentSuccess": "助理创建成功",
"sessionGroup.createGroup": "添加新分类",
"sessionGroup.createGroupFailed": "分类创建失败",
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index a5eecedab05..8e5e5bf4e6b 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -94,6 +94,7 @@ export class HomeRepository {
description: agents.description,
id: agents.id,
name: agents.name,
+ model: agents.model,
pinned: agents.pinned,
slug: agents.slug,
title: agents.title,
@@ -290,6 +291,7 @@ export class HomeRepository {
description: string | null;
id: string;
name: string | null;
+ model: string | null;
pinned: boolean | null;
sessionGroupId: string | null;
slug: string | null;
@@ -350,6 +352,7 @@ export class HomeRepository {
isPrivate: visibility === 'private',
labels: agentLabelsMap.get(a.id),
name: a.name,
+ model: a.model,
pinned: a.pinned ?? false,
slug: a.slug,
title: meta.title,
@@ -410,19 +413,23 @@ export class HomeRepository {
for (const item of allItems) {
const { groupId, isPrivate, ...sidebarItem } = item;
- const cleanedItem = cleanObject(sidebarItem) as SidebarAgentItem;
+ const validGroupIds = isPrivate ? privateGroupIds : groupIds;
+ const categoryId = groupId && validGroupIds.has(groupId) ? groupId : null;
+ const cleanedItem = {
+ ...cleanObject(sidebarItem),
+ groupId: categoryId,
+ } as SidebarAgentItem;
if (item.pinned) {
(isPrivate ? privatePinned : pinned).push(cleanedItem);
continue;
}
- const validGroupIds = isPrivate ? privateGroupIds : groupIds;
- if (groupId && validGroupIds.has(groupId)) {
+ if (categoryId) {
const bucket = isPrivate ? privateGroupedMap : groupedMap;
- const existing = bucket.get(groupId) || [];
+ const existing = bucket.get(categoryId) || [];
existing.push(cleanedItem);
- bucket.set(groupId, existing);
+ bucket.set(categoryId, existing);
} else if (isPrivate) {
privateUngrouped.push(cleanedItem);
} else {
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 9791c4256cf..969a8980a1e 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1699,6 +1699,11 @@ export default {
'sessionGroup.manageCategory': 'Manage Category',
'sessionGroup.confirmRemoveGroupAlert':
'This category is about to be deleted. After deletion, the agents in this category will be moved to the default list. Please confirm your operation.',
+ 'sessionGroup.createAgentFailed': "Couldn't create the agent. Please try again.",
+ 'sessionGroup.createAgentPinFailed':
+ 'Agent created, but pinning failed. You can pin it from the list.',
+ 'sessionGroup.createAgentRefreshFailed':
+ "Agent created, but the list couldn't refresh. Refresh the list to see it.",
'sessionGroup.createAgentSuccess': 'Agent created successfully',
'sessionGroup.createGroup': 'Add New Category',
'sessionGroup.createGroupFailed': 'Failed to create category',
diff --git a/packages/types/src/agentGroup/index.ts b/packages/types/src/agentGroup/index.ts
index 746a4c40229..4d1e7f9284a 100644
--- a/packages/types/src/agentGroup/index.ts
+++ b/packages/types/src/agentGroup/index.ts
@@ -98,6 +98,8 @@ export interface NewChatGroup {
pinned?: boolean | null;
title?: string | null;
userId: string;
+ /** Visibility forwarded to the existing group creation API. */
+ visibility?: 'private' | 'public';
}
// Chat Group Item type (independent from schema)
diff --git a/packages/types/src/home.ts b/packages/types/src/home.ts
index 1cbf4747f9e..47f5063c772 100644
--- a/packages/types/src/home.ts
+++ b/packages/types/src/home.ts
@@ -61,6 +61,8 @@ export interface SidebarAgentItem {
* Only present for chat groups (type === 'group')
*/
groupAvatar?: string | null;
+ /** Sidebar category ID, independent of chat-group identity; null means ungrouped. */
+ groupId?: string | null;
/**
* Heterogeneous agent runtime type (e.g. `claude-code`) when the agent is
* driven by an external CLI. `null` / absent means it's a regular LobeHub
@@ -74,6 +76,8 @@ export interface SidebarAgentItem {
* agents). Used by the agents list to render label tags and group by label.
*/
labels?: SidebarAgentLabel[];
+ /** Model shown on mobile list rows. */
+ model?: string | null;
/**
* The agent's personal name. Absent for chat groups and for agents created
* before names existed — resolve the label with `agentDisplayName(item)`.
diff --git a/src/components/MemberSelectionModal/MemberSelectionModal.tsx b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
index 927e1393293..c94ea4c4915 100644
--- a/src/components/MemberSelectionModal/MemberSelectionModal.tsx
+++ b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
@@ -1,6 +1,6 @@
'use client';
-import { agentDisplayName } from '@lobechat/types';
+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';
import {
ActionIcon,
Avatar,
@@ -28,12 +28,13 @@ import { DEFAULT_AVATAR } from '@/const/meta';
import AgentSelectionEmpty from '@/features/AgentSelectionEmpty';
import ModelSelect from '@/features/ModelSelect';
import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
-import { useSessionStore } from '@/store/session';
-import { type LobeAgentSession } from '@/types/session';
-import { LobeSessionType } from '@/types/session';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
const AvailableAgentItem = memo<{
- agent: LobeAgentSession;
+ agent: SidebarAgentItem;
cx: any;
isSelected: boolean;
onToggle: (_agentId: string) => void;
@@ -43,11 +44,11 @@ const AvailableAgentItem = memo<{
const ref = useRef<HTMLDivElement>(null);
const isHovering = useHover(ref);
- const _agentId = agent.config?.id;
- const title = agentDisplayName(agent.meta, t('defaultSession', { ns: 'common' }));
- const description = agent.meta?.description || '';
- const avatar = agent.meta?.avatar || DEFAULT_AVATAR;
- const avatarBackground = agent.meta?.backgroundColor;
+ const _agentId = agent.id;
+ const title = agentDisplayName(agent, t('defaultSession', { ns: 'common' }));
+ const description = agent.description || '';
+ const avatar = typeof agent.avatar === 'string' ? agent.avatar : DEFAULT_AVATAR;
+ const avatarBackground = agent.backgroundColor || undefined;
if (!_agentId) return null;
@@ -81,7 +82,7 @@ const AvailableAgentItem = memo<{
);
});
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = createStaticStyles(({ css, cssVar, responsive }) => ({
container: css`
display: flex;
flex-direction: row;
@@ -89,6 +90,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
height: 500px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadius};
+
+ ${responsive.sm} {
+ flex-direction: column;
+ height: min(500px, calc(100dvh - 160px));
+ }
`,
description: css`
font-size: 11px;
@@ -102,6 +108,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
border-radius: ${cssVar.borderRadiusLG};
background: ${cssVar.colorFillTertiary};
+
+ ${responsive.sm} {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ `,
+ hostModelSelect: css`
+ ${responsive.sm} {
+ flex: 1;
+ min-width: 0;
+ }
`,
leftColumn: css`
user-select: none;
@@ -112,6 +129,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-block: ${cssVar.paddingSM} 0;
padding-inline: ${cssVar.paddingSM};
border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ ${responsive.sm} {
+ min-height: 0;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ border-inline-end: 0;
+ }
`,
listItem: css`
cursor: pointer;
@@ -135,6 +158,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
overflow-y: auto;
flex: 1;
padding: ${cssVar.paddingSM};
+
+ ${responsive.sm} {
+ min-height: 0;
+ }
`,
selectedItem: css`
opacity: 0.6;
@@ -220,15 +247,12 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
},
);
- const agentSessions = useSessionStore((s) => {
- const allSessions = s.sessions || [];
- return allSessions.filter(
- (session): session is LobeAgentSession =>
- session.type === LobeSessionType.Agent && !session.config?.virtual,
- );
- });
-
- const currentSessionId = useSessionStore((s) => s.activeId);
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const useFetchAgentList = useHomeStore((s) => s.useFetchAgentList);
+ useFetchAgentList(open && isLogin);
+ const agents = useHomeStore((s) =>
+ homeAgentListSelectors.allAgents(s).filter((item) => item.type === 'agent'),
+ );
const handleAgentToggle = (agentId: string) => {
setSelectedAgents((prev) =>
@@ -256,23 +280,20 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
const availableAgents = useMemo(() => {
if (mode === 'create') {
// When creating a new group, all agents are available
- return agentSessions;
+ return agents;
} else {
- // When adding to existing group, filter out the current session and existing members
- return agentSessions.filter(
- (agent) =>
- agent.id !== currentSessionId && !existingMembers.includes(agent.config?.id || ''),
- );
+ // Existing members already belong to the group and cannot be selected again.
+ return agents.filter((agent) => !existingMembers.includes(agent.id || ''));
}
- }, [agentSessions, currentSessionId, mode, existingMembers]);
+ }, [agents, mode, existingMembers]);
// Filter available agents based on search term
const filteredAvailableAgents = useMemo(() => {
if (!searchTerm.trim()) return availableAgents;
return availableAgents.filter((agent) => {
- const title = agentDisplayName(agent.meta) ?? '';
- const description = agent.meta?.description || '';
+ const title = agentDisplayName(agent) ?? '';
+ const description = agent.description || '';
const searchLower = searchTerm.toLowerCase();
return (
@@ -285,13 +306,13 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
const selectedAgentListItems = useMemo(() => {
return selectedAgents
.map((agentId) => {
- const agent = agentSessions.find((session) => session.config.id === agentId);
+ const agent = agents.find((agent) => agent.id === agentId);
if (!agent) return null;
- const title = agentDisplayName(agent.meta, t('defaultSession', { ns: 'common' }));
- const avatar = agent.meta?.avatar || DEFAULT_AVATAR;
- const avatarBackground = agent.meta?.backgroundColor;
- const description = agent.meta?.description || '';
+ const title = agentDisplayName(agent, t('defaultSession', { ns: 'common' }));
+ const avatar = typeof agent.avatar === 'string' ? agent.avatar : DEFAULT_AVATAR;
+ const avatarBackground = agent.backgroundColor || undefined;
+ const description = agent.description || '';
return {
actions: (
@@ -312,7 +333,7 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
};
})
.filter((item): item is NonNullable<typeof item> => item !== null);
- }, [selectedAgents, agentSessions, t, handleRemoveAgent]);
+ }, [selectedAgents, agents, t, handleRemoveAgent]);
const handleReset = () => {
setSelectedAgents(preSelectedAgents);
@@ -409,7 +430,7 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
/>
) : (
filteredAvailableAgents.map((agent) => {
- const agentId = agent.config?.id;
+ const agentId = agent.id;
if (!agentId) return null;
return (
@@ -450,11 +471,15 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
</Flexbox>
<Flexbox horizontal align="center" gap={12}>
<div
- className={cx(isHostRemoved && styles.modelSelectDisabled)}
style={{ opacity: isHostRemoved ? 0.6 : 1 }}
+ className={cx(
+ styles.hostModelSelect,
+ isHostRemoved && styles.modelSelectDisabled,
+ )}
>
<ModelSelect
requiredAbilities={['functionCall']}
+ style={{ maxWidth: '100%', minWidth: 'min(200px, 100%)' }}
value={normalizedHostModelConfig}
onChange={handleHostModelChange}
/>
diff --git a/src/features/MobileGroupChat/Header.tsx b/src/features/MobileGroupChat/Header.tsx
new file mode 100644
index 00000000000..30dca7c92a6
--- /dev/null
+++ b/src/features/MobileGroupChat/Header.tsx
@@ -0,0 +1,60 @@
+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import { ChatHeader } from '@lobehub/ui/mobile';
+import { ChevronDown } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';
+import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import ShareButton from '@/routes/(main)/group/features/Conversation/Header/ShareButton';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+
+export const MobileGroupHeader = () => {
+ const { t } = useTranslation(['chat', 'topic']);
+ const { gid } = useParams<{ gid: string }>();
+ const router = useQueryRoute();
+ const [open, setOpen] = useState(false);
+ const title = useAgentGroupStore((s) => (gid ? s.groupMap[gid]?.title : undefined));
+ const topic = useChatStore(topicSelectors.currentActiveTopic);
+ const toggleMobileTopic = useGlobalStore((s) => s.toggleMobileTopic);
+
+ useFetchChatTopics();
+ useFetchActiveTopicDetail();
+
+ return (
+ <ChatHeader
+ showBackButton
+ right={<ShareButton mobile open={open} setOpen={setOpen} />}
+ style={{ width: '100%' }}
+ center={
+ <ChatHeader.Title
+ desc={
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Text ellipsis style={{ maxWidth: '50vw' }}>
+ {topic?.title || t('title', { ns: 'topic' })}
+ </Text>
+ <ActionIcon
+ aria-label={t('title', { ns: 'topic' })}
+ icon={ChevronDown}
+ size={'small'}
+ title={t('title', { ns: 'topic' })}
+ onClick={() => toggleMobileTopic(true)}
+ />
+ </Flexbox>
+ }
+ title={
+ <Text ellipsis style={{ maxWidth: '60vw' }}>
+ {title || t('untitledGroup')}
+ </Text>
+ }
+ />
+ }
+ onBackClick={() => router.push('/group', { replace: true })}
+ />
+ );
+};
diff --git a/src/features/MobileGroupChat/Layout.tsx b/src/features/MobileGroupChat/Layout.tsx
new file mode 100644
index 00000000000..979da96e2ed
--- /dev/null
+++ b/src/features/MobileGroupChat/Layout.tsx
@@ -0,0 +1,23 @@
+import { Outlet } from 'react-router';
+
+import MobileContentLayout from '@/components/server/MobileNavLayout';
+import { GroupNotFoundGuard } from '@/features/GroupNotFound';
+import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';
+import GroupIdSync from '@/routes/(main)/group/_layout/GroupIdSync';
+
+import { MobileGroupHeader } from './Header';
+
+export const MobileGroupLayout = () => {
+ useInitGroupConfig();
+
+ return (
+ <>
+ <MobileContentLayout header={<MobileGroupHeader />} style={{ overflowY: 'hidden' }}>
+ <GroupNotFoundGuard>
+ <Outlet />
+ </GroupNotFoundGuard>
+ </MobileContentLayout>
+ <GroupIdSync />
+ </>
+ );
+};
diff --git a/src/features/MobileGroupChat/Topics.tsx b/src/features/MobileGroupChat/Topics.tsx
new file mode 100644
index 00000000000..cbeff0833d5
--- /dev/null
+++ b/src/features/MobileGroupChat/Topics.tsx
@@ -0,0 +1,55 @@
+import { Flexbox, Modal } from '@lobehub/ui';
+import { MessageSquarePlusIcon } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { OverlayContainerContext } from '@/features/NavPanel/OverlayContainer';
+import Actions from '@/routes/(main)/group/_layout/Sidebar/Topic/Actions';
+import TopicList from '@/routes/(main)/group/_layout/Sidebar/Topic/List';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+export const MobileGroupTopics = () => {
+ const { t } = useTranslation('topic');
+ const [showTopics, toggleMobileTopic] = useGlobalStore((s) => [
+ systemStatusSelectors.mobileShowTopic(s),
+ s.toggleMobileTopic,
+ ]);
+ const switchToNewTopic = useAgentGroupStore((s) => s.switchToNewTopic);
+ const [overlayContainer, setOverlayContainer] = useState<HTMLDivElement | null>(null);
+
+ useEffect(() => () => toggleMobileTopic(false), [toggleMobileTopic]);
+
+ return (
+ <OverlayContainerContext value={overlayContainer}>
+ {/* Keep topic navigation in the route tree, like the mobile conversation portal. */}
+ <Modal
+ allowFullscreen
+ footer={null}
+ open={showTopics}
+ styles={{ body: { padding: 0 } }}
+ title={t('title')}
+ onCancel={() => toggleMobileTopic(false)}
+ >
+ <div ref={setOverlayContainer}>
+ <Flexbox gap={8} padding={8} style={{ maxHeight: '70dvh', overflowY: 'auto' }}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <NavItem
+ icon={MessageSquarePlusIcon}
+ title={t('actions.addNewTopic')}
+ onClick={() => {
+ switchToNewTopic();
+ toggleMobileTopic(false);
+ }}
+ />
+ <Actions />
+ </Flexbox>
+ <TopicList showEmptyAction={false} />
+ </Flexbox>
+ </div>
+ </Modal>
+ </OverlayContainerContext>
+ );
+};
diff --git a/src/features/MobileGroupChat/index.tsx b/src/features/MobileGroupChat/index.tsx
new file mode 100644
index 00000000000..a14d25b6077
--- /dev/null
+++ b/src/features/MobileGroupChat/index.tsx
@@ -0,0 +1,14 @@
+import PortalPanel from '@/routes/(main)/agent/features/Portal/features/PortalPanel';
+import ConversationArea from '@/routes/(main)/group/features/Conversation/ConversationArea';
+import TelemetryNotification from '@/routes/(main)/group/features/TelemetryNotification';
+
+import { MobileGroupTopics } from './Topics';
+
+export const MobileGroupChat = () => (
+ <>
+ <ConversationArea mobile />
+ <MobileGroupTopics />
+ <PortalPanel mobile />
+ <TelemetryNotification mobile />
+ </>
+);
diff --git a/src/features/MobileHome/Layout/AgentSearchContext.tsx b/src/features/MobileHome/Layout/AgentSearchContext.tsx
new file mode 100644
index 00000000000..11b7f9cb7c4
--- /dev/null
+++ b/src/features/MobileHome/Layout/AgentSearchContext.tsx
@@ -0,0 +1,17 @@
+import { createContext, type PropsWithChildren, use, useState } from 'react';
+
+const AgentSearchContext = createContext<{
+ keywords: string;
+ setKeywords: (keywords: string) => void;
+} | null>(null);
+
+export const AgentSearchProvider = ({ children }: PropsWithChildren) => {
+ const [keywords, setKeywords] = useState('');
+ return <AgentSearchContext value={{ keywords, setKeywords }}>{children}</AgentSearchContext>;
+};
+
+export const useAgentSearch = () => {
+ const context = use(AgentSearchContext);
+ if (!context) throw new Error('AgentSearchProvider is required');
+ return context;
+};
diff --git a/src/features/MobileHome/Layout/SessionHeader.tsx b/src/features/MobileHome/Layout/SessionHeader.tsx
index 661a421632d..ae7957284d9 100644
--- a/src/features/MobileHome/Layout/SessionHeader.tsx
+++ b/src/features/MobileHome/Layout/SessionHeader.tsx
@@ -4,18 +4,20 @@ import { ActionIcon, Flexbox } from '@lobehub/ui';
import { ChatHeader } from '@lobehub/ui/mobile';
import { MessageSquarePlus } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router';
import { ProductLogo } from '@/components/Branding';
import { MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import UserAvatar from '@/features/User/UserAvatar';
-import { useSessionStore } from '@/store/session';
import { mobileHeaderSticky } from '@/styles/mobileHeader';
+import { useCreateAgent } from '../useCreateAgent';
import { styles } from './SessionHeader/style';
const Header = memo(() => {
- const [createSession] = useSessionStore((s) => [s.createSession]);
+ const { t } = useTranslation('chat');
+ const { allowed, create, loading, reason } = useCreateAgent();
const navigate = useNavigate();
return (
@@ -29,9 +31,14 @@ const Header = memo(() => {
}
right={
<ActionIcon
+ aria-description={reason}
+ aria-label={t('newAgent')}
+ disabled={!allowed || loading}
icon={MessageSquarePlus}
+ loading={loading}
size={MOBILE_HEADER_ICON_SIZE}
- onClick={() => createSession()}
+ title={reason ?? t('newAgent')}
+ onClick={() => create()}
/>
}
/>
diff --git a/src/features/MobileHome/Layout/SessionHydration.tsx b/src/features/MobileHome/Layout/SessionHydration.tsx
deleted file mode 100644
index 3062fef9a88..00000000000
--- a/src/features/MobileHome/Layout/SessionHydration.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-'use client';
-
-import { memo, useEffect } from 'react';
-import { createStoreUpdater } from 'zustand-utils';
-
-import { parseAsString, useQueryParam } from '@/hooks/useQueryParam';
-import { useChatStore } from '@/store/chat';
-import { useSessionStore } from '@/store/session';
-
-const THROTTLE_DELAY = 50;
-
-// sync outside state to useSessionStore
-const SessionHydration = memo(() => {
- const useStoreUpdater = createStoreUpdater(useSessionStore);
- const useChatStoreUpdater = createStoreUpdater(useChatStore);
- const [switchTopic] = useChatStore((s) => [s.switchTopic]);
-
- // two-way bindings the url and session store
- const [session, setSession] = useQueryParam('session', parseAsString.withDefault('inbox'), {
- history: 'replace',
- throttleMs: THROTTLE_DELAY,
- });
-
- useStoreUpdater('activeId', session);
- useChatStoreUpdater('activeAgentId', session);
-
- useEffect(() => {
- const unsubscribe = useSessionStore.subscribe(
- (s) => s.activeId,
- (state) => {
- switchTopic();
- setSession(state);
- },
- );
-
- return () => {
- unsubscribe();
- };
- }, []);
-
- return null;
-});
-
-export default SessionHydration;
diff --git a/src/features/MobileHome/Layout/SessionSearchBar.tsx b/src/features/MobileHome/Layout/SessionSearchBar.tsx
index 2a604df74a6..028a549eaf6 100644
--- a/src/features/MobileHome/Layout/SessionSearchBar.tsx
+++ b/src/features/MobileHome/Layout/SessionSearchBar.tsx
@@ -7,19 +7,17 @@ import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useHomeStore } from '@/store/home';
-import { useSessionStore } from '@/store/session';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
+import { useAgentSearch } from './AgentSearchContext';
+
const SessionSearchBar = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation('chat');
const isLoaded = useUserStore((s) => s.isLoaded);
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.Search));
- const [keywords, updateSearchKeywords] = useSessionStore((s) => [
- s.sessionSearchKeywords,
- s.updateSearchKeywords,
- ]);
+ const { keywords, setKeywords: updateSearchKeywords } = useAgentSearch();
const useSearchAgents = useHomeStore((s) => s.useSearchAgents);
const { isValidating } = useSearchAgents(keywords?.trim() || undefined);
diff --git a/src/features/MobileHome/Layout/index.tsx b/src/features/MobileHome/Layout/index.tsx
index 05f81a780c1..003172b5e9c 100644
--- a/src/features/MobileHome/Layout/index.tsx
+++ b/src/features/MobileHome/Layout/index.tsx
@@ -1,18 +1,14 @@
-import { type FC } from 'react';
import { Outlet } from 'react-router';
-import MobileLayout from '@/features/MobileHome/Layout/MobileLayout';
-import SessionHydration from '@/features/MobileHome/Layout/SessionHydration';
+import { AgentSearchProvider } from './AgentSearchContext';
+import MobileLayout from './MobileLayout';
-const Layout: FC = () => {
- return (
- <>
- <MobileLayout>
- <Outlet />
- </MobileLayout>
- <SessionHydration />
- </>
- );
-};
+const Layout = () => (
+ <AgentSearchProvider>
+ <MobileLayout>
+ <Outlet />
+ </MobileLayout>
+ </AgentSearchProvider>
+);
export default Layout;
diff --git a/src/features/MobileHome/SessionListContent/AgentSearchList.tsx b/src/features/MobileHome/SessionListContent/AgentSearchList.tsx
index 1da888dad41..cc6a0aa3f33 100644
--- a/src/features/MobileHome/SessionListContent/AgentSearchList.tsx
+++ b/src/features/MobileHome/SessionListContent/AgentSearchList.tsx
@@ -10,6 +10,7 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useServerConfigStore } from '@/store/serverConfig';
import ListItem from './ListItem';
+import { useListNavigation } from './useListNavigation';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -26,10 +27,14 @@ interface AgentSearchListProps {
export const AgentSearchList = memo<AgentSearchListProps>(({ dataSource }) => {
const { t } = useTranslation('chat');
+ const onNavigate = useListNavigation('search');
const isMobile = useServerConfigStore((s) => s.isMobile);
return dataSource?.map((item) => {
- const title = agentDisplayName(item, t('untitledAgent'));
+ const title = agentDisplayName(
+ item,
+ t(item.type === 'group' ? 'untitledGroup' : 'untitledAgent'),
+ );
return (
<LazyLoad className={styles.container} key={item.id}>
@@ -37,6 +42,7 @@ export const AgentSearchList = memo<AgentSearchListProps>(({ dataSource }) => {
aria-label={title}
className={styles.link}
to={item.type === 'group' ? GROUP_CHAT_URL(item.id) : AGENT_CHAT_URL(item.id, isMobile)}
+ onClick={(event) => onNavigate(event, item)}
>
<ListItem
avatar={item.avatar || DEFAULT_AVATAR}
@@ -49,7 +55,7 @@ export const AgentSearchList = memo<AgentSearchListProps>(({ dataSource }) => {
},
content: {
gap: 6,
- maskImage: `linear-gradient(90deg, #000 90%, transparent)`,
+ maskImage: `linear-gradient(90deg, black 90%, transparent)`,
},
}}
/>
diff --git a/src/features/MobileHome/SessionListContent/CollapseGroup/Actions.tsx b/src/features/MobileHome/SessionListContent/CollapseGroup/Actions.tsx
index 2ba99dab9f4..e7db80b24a3 100644
--- a/src/features/MobileHome/SessionListContent/CollapseGroup/Actions.tsx
+++ b/src/features/MobileHome/SessionListContent/CollapseGroup/Actions.tsx
@@ -4,47 +4,41 @@ import {
type MenuInfo,
type MenuItemType,
} from '@lobehub/ui';
-import {
- ActionIcon,
- confirmModal,
- createStaticStyles,
- DropdownMenu,
- Icon,
- toast,
-} from '@lobehub/ui';
+import { ActionIcon, confirmModal, DropdownMenu, Icon, toast } from '@lobehub/ui';
import { MoreVertical, PencilLine, Plus, Settings2, Trash, UsersRound } from 'lucide-react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { MemberSelectionModal } from '@/components/MemberSelectionModal';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
-import { useSessionStore } from '@/store/session';
+import { useHomeStore } from '@/store/home';
+
+import { useCreateAgent } from '../../useCreateAgent';
-const styles = createStaticStyles(({ css }) => ({
- modalRoot: css`
- z-index: 2000;
- `,
-}));
interface ActionsProps extends Pick<DropdownMenuProps, 'onOpenChange'> {
id?: string;
isCustomGroup?: boolean;
isPinned?: boolean;
openConfigModal: () => void;
openRenameModal?: () => void;
+ visibility?: 'private' | 'public';
}
const Actions = memo<ActionsProps>(
- ({ id, openRenameModal, openConfigModal, onOpenChange, isCustomGroup, isPinned }) => {
+ ({ id, visibility, openRenameModal, openConfigModal, onOpenChange, isCustomGroup, isPinned }) => {
const { t } = useTranslation(['chat', 'common']);
const isMobile = useIsMobile();
const [isGroupModalOpen, setIsGroupModalOpen] = useState(false);
const [isCreatingGroup, setIsCreatingGroup] = useState(false);
- const [createSession, removeSessionGroup] = useSessionStore((s) => [
- s.createSession,
- s.removeSessionGroup,
+ const { create, loading, allowed: canCreate, reason: createReason } = useCreateAgent();
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const [removeSessionGroup, refreshAgentList] = useHomeStore((s) => [
+ s.removeGroup,
+ s.refreshAgentList,
]);
const [createGroup] = useAgentGroupStore((s) => [s.createGroup]);
@@ -61,26 +55,30 @@ const Actions = memo<ActionsProps>(
const newAgentPublicItem: MenuItemType = {
icon: <Icon icon={Plus} />,
+ disabled: !canCreate || loading,
key: 'newAgent',
label: t('newAgent'),
+ title: createReason,
onClick: async ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
const creatingToast = toast.loading(t('sessionGroup.creatingAgent'));
-
- await createSession({ group: id, pinned: isPinned });
-
- creatingToast.close();
- toast.success(t('sessionGroup.createAgentSuccess'));
+ try {
+ const result = await create({ groupId: id, pinned: isPinned, visibility });
+ if (result && !result.hasWarnings) toast.success(t('sessionGroup.createAgentSuccess'));
+ } finally {
+ creatingToast.close();
+ }
},
};
const newGroupChatItem: MenuItemType = {
icon: <Icon icon={UsersRound} />,
+ disabled: !canCreate,
key: 'newGroupChat',
label: t('newGroupChat'),
onClick: ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
- setIsGroupModalOpen(true);
+ if (canCreate) setIsGroupModalOpen(true);
},
};
@@ -90,6 +88,7 @@ const Actions = memo<ActionsProps>(
enableSupervisor?: boolean,
) => {
try {
+ if (!canCreate || isCreatingGroup) return;
setIsCreatingGroup(true);
const config: any = {};
@@ -107,9 +106,13 @@ const Actions = memo<ActionsProps>(
{
config: Object.keys(config).length > 0 ? config : undefined,
title: 'New Group Chat',
+ groupId: id,
+ pinned: isPinned,
+ visibility,
},
selectedAgents,
);
+ await refreshAgentList();
setIsGroupModalOpen(false);
} catch (error) {
console.error('Failed to create group:', error);
@@ -123,55 +126,50 @@ const Actions = memo<ActionsProps>(
setIsGroupModalOpen(false);
};
- const customGroupItems: DropdownItem[] = useMemo(
- () => [
- {
- icon: <Icon icon={PencilLine} />,
- key: 'rename',
- label: t('sessionGroup.rename'),
- onClick: ({ domEvent }: MenuInfo) => {
- domEvent.stopPropagation();
- openRenameModal?.();
- },
+ const customGroupItems: DropdownItem[] = [
+ {
+ icon: <Icon icon={PencilLine} />,
+ disabled: !canEdit,
+ key: 'rename',
+ label: t('sessionGroup.rename'),
+ onClick: ({ domEvent }: MenuInfo) => {
+ domEvent.stopPropagation();
+ openRenameModal?.();
},
- sessionGroupConfigPublicItem,
- {
- type: 'divider',
- },
- {
- danger: true,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: ({ domEvent }: MenuInfo) => {
- domEvent.stopPropagation();
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('sessionGroup.confirmRemoveGroupAlert'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
- if (!id) return;
- await removeSessionGroup(id);
- },
- title: t('delete', { ns: 'common' }),
- });
- },
+ },
+ sessionGroupConfigPublicItem,
+ {
+ type: 'divider',
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ disabled: !canEdit,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: ({ domEvent }: MenuInfo) => {
+ domEvent.stopPropagation();
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('sessionGroup.confirmRemoveGroupAlert'),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ if (!id) return;
+ await removeSessionGroup(id);
+ },
+ title: t('delete', { ns: 'common' }),
+ });
},
- ],
- [],
- );
-
- const defaultItems: DropdownItem[] = useMemo(() => [sessionGroupConfigPublicItem], []);
-
- const tailItems = useMemo(
- () => (isCustomGroup ? customGroupItems : defaultItems),
- [isCustomGroup, customGroupItems, defaultItems],
- );
-
- const menuItems = useMemo(() => {
- return [newAgentPublicItem, newGroupChatItem, { type: 'divider' as const }, ...tailItems];
- }, [newAgentPublicItem, newGroupChatItem, tailItems]);
+ },
+ ];
+ const tailItems = isCustomGroup ? customGroupItems : [sessionGroupConfigPublicItem];
+ const menuItems: DropdownItem[] = [
+ newAgentPublicItem,
+ newGroupChatItem,
+ { type: 'divider' },
+ ...tailItems,
+ ];
return (
<>
@@ -182,6 +180,7 @@ const Actions = memo<ActionsProps>(
loading={isCreatingGroup}
size={{ blockSize: 22, size: 16 }}
style={{ background: isMobile ? 'transparent' : '', marginRight: -8 }}
+ title={t('more', { ns: 'common' })}
onClick={(e) => {
e.stopPropagation();
}}
diff --git a/src/features/MobileHome/SessionListContent/DefaultMode.tsx b/src/features/MobileHome/SessionListContent/DefaultMode.tsx
index 7d28da99a9f..acfa3194973 100644
--- a/src/features/MobileHome/SessionListContent/DefaultMode.tsx
+++ b/src/features/MobileHome/SessionListContent/DefaultMode.tsx
@@ -1,17 +1,19 @@
import isEqual from 'fast-deep-equal';
-import { memo, useMemo, useState } from 'react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import { useFetchSessions } from '@/hooks/useFetchSessions';
+import {
+ useAgentList,
+ useKeepSidebarListed,
+} from '@/features/HomeSidebar/Body/Agent/List/useAgentList';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { serverConfigSelectors } from '@/store/serverConfig/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-import { type LobeAgentSession, type LobeSessions } from '@/types/session';
-import { LobeSessionType, SessionDefaultGroup } from '@/types/session';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+import { SessionDefaultGroup } from '@/types/session';
import CollapseGroup, { type CollapseGroupItem } from './CollapseGroup';
import Actions from './CollapseGroup/Actions';
@@ -23,36 +25,26 @@ import { openRenameGroupModal } from './Modals/RenameGroupModal';
const DefaultMode = memo(() => {
const { t } = useTranslation('chat');
- const [configGroupModalOpen, setConfigGroupModalOpen] = useState(false);
-
- useFetchSessions();
-
- const isMobile = useServerConfigStore(serverConfigSelectors.isMobile);
-
- const defaultSessions = useSessionStore(sessionSelectors.defaultSessions, isEqual);
- const customSessionGroups = useSessionStore(sessionSelectors.customSessionGroups, isEqual);
- const pinnedSessions = useSessionStore(sessionSelectors.pinnedSessions, isEqual);
-
- const shouldHideSession = (session: LobeSessions[0]) =>
- !isMobile &&
- session.type === LobeSessionType.Agent &&
- Boolean((session as LobeAgentSession).config?.virtual);
-
- const filterSessionsForView = (sessions: LobeSessions): LobeSessions => {
- const filteredForDevice = isMobile
- ? sessions.filter((session) => session.type !== LobeSessionType.Group)
- : sessions;
-
- if (isMobile) return filteredForDevice;
-
- return filteredForDevice.filter((session) => !shouldHideSession(session));
- };
-
- const filteredDefaultSessions = filterSessionsForView(defaultSessions);
- const filteredPinnedSessions = filterSessionsForView(pinnedSessions);
- const filteredCustomSessionGroups = customSessionGroups?.map((group) => ({
+ const [configGroupModal, setConfigGroupModal] = useState<{
+ open: boolean;
+ scope: 'private' | 'public';
+ }>({ open: false, scope: 'public' });
+
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const useFetchAgentList = useHomeStore((s) => s.useFetchAgentList);
+ useFetchAgentList(isLogin);
+ const { defaultList, pinnedList, customList, privateGroupList, privateUngroupedList } =
+ useAgentList(false);
+ const keep = useKeepSidebarListed();
+ const privatePinned = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
+ const filteredDefaultSessions = [...defaultList, ...privateUngroupedList];
+ const filteredPinnedSessions = [...pinnedList, ...keep(privatePinned)];
+ const filteredCustomSessionGroups = [
+ ...customList,
+ ...privateGroupList.map((group) => ({ ...group, visibility: 'private' as const })),
+ ].map((group) => ({
...group,
- children: filterSessionsForView(group.children),
+ children: group.items,
}));
const activeWorkspaceId = useActiveWorkspaceId();
@@ -61,38 +53,42 @@ const DefaultMode = memo(() => {
);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const items = useMemo(
- () =>
- [
- filteredPinnedSessions &&
- filteredPinnedSessions.length > 0 && {
- children: <SessionList dataSource={filteredPinnedSessions} />,
- extra: <Actions isPinned openConfigModal={() => setConfigGroupModalOpen(true)} />,
- key: SessionDefaultGroup.Pinned,
- label: t('pin'),
- },
- ...(filteredCustomSessionGroups || []).map(({ id, name, children }) => ({
- children: <SessionList dataSource={children} groupId={id} />,
- extra: (
- <Actions
- isCustomGroup
- id={id}
- openConfigModal={() => setConfigGroupModalOpen(true)}
- openRenameModal={() => openRenameGroupModal(id)}
- />
- ),
- key: id,
- label: name,
- })),
- {
- children: <SessionList dataSource={filteredDefaultSessions || []} />,
- extra: <Actions openConfigModal={() => setConfigGroupModalOpen(true)} />,
- key: SessionDefaultGroup.Default,
- label: t('defaultList'),
- },
- ].filter(Boolean) as CollapseGroupItem[],
- [t, filteredCustomSessionGroups, filteredPinnedSessions, filteredDefaultSessions],
- );
+ const items = [
+ filteredPinnedSessions &&
+ filteredPinnedSessions.length > 0 && {
+ children: <SessionList dataSource={filteredPinnedSessions} />,
+ extra: (
+ <Actions
+ isPinned
+ openConfigModal={() => setConfigGroupModal({ open: true, scope: 'public' })}
+ />
+ ),
+ key: SessionDefaultGroup.Pinned,
+ label: t('pin'),
+ },
+ ...(filteredCustomSessionGroups || []).map(({ id, name, children, visibility }) => ({
+ children: <SessionList dataSource={children} groupId={id} visibility={visibility} />,
+ extra: (
+ <Actions
+ isCustomGroup
+ id={id}
+ openConfigModal={() => setConfigGroupModal({ open: true, scope: visibility ?? 'public' })}
+ openRenameModal={() => openRenameGroupModal(id)}
+ visibility={visibility}
+ />
+ ),
+ key: id,
+ label: name,
+ })),
+ {
+ children: <SessionList dataSource={filteredDefaultSessions || []} groupId={null} />,
+ extra: (
+ <Actions openConfigModal={() => setConfigGroupModal({ open: true, scope: 'public' })} />
+ ),
+ key: SessionDefaultGroup.Default,
+ label: t('defaultList'),
+ },
+ ].filter(Boolean) as CollapseGroupItem[];
return (
<>
@@ -103,8 +99,9 @@ const DefaultMode = memo(() => {
onChange={(expandSessionGroupKeys) => updateSystemStatus({ expandSessionGroupKeys })}
/>
<ConfigGroupModal
- open={configGroupModalOpen}
- onCancel={() => setConfigGroupModalOpen(false)}
+ open={configGroupModal.open}
+ scope={configGroupModal.scope}
+ onCancel={() => setConfigGroupModal((state) => ({ ...state, open: false }))}
/>
</>
);
diff --git a/src/features/MobileHome/SessionListContent/Inbox/index.tsx b/src/features/MobileHome/SessionListContent/Inbox/index.tsx
index 6f8ed90742d..10fd2767866 100644
--- a/src/features/MobileHome/SessionListContent/Inbox/index.tsx
+++ b/src/features/MobileHome/SessionListContent/Inbox/index.tsx
@@ -1,27 +1,26 @@
import { AGENT_CHAT_URL } from '@lobechat/const';
import { memo } from 'react';
-import { Link } from 'react-router';
import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
import { resolveInboxAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
import ListItem from '../ListItem';
const Inbox = memo(() => {
const mobile = useServerConfigStore((s) => s.isMobile);
- const isInboxActive = useSessionStore(sessionSelectors.isInboxSession);
const navigateToAgent = useNavigateToAgent();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const inboxRouteAgentId = resolveInboxAgentRouteId(inboxAgentId);
+ const isInboxActive = useAgentStore((s) => s.activeAgentId === inboxAgentId);
+
return (
- <Link
+ <WorkspaceLink
aria-label={'Lobe AI'}
to={AGENT_CHAT_URL(inboxRouteAgentId, mobile)}
onClick={(e) => {
@@ -44,7 +43,7 @@ const Inbox = memo(() => {
},
}}
/>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/features/MobileHome/SessionListContent/List/AddButton.tsx b/src/features/MobileHome/SessionListContent/List/AddButton.tsx
index f685deb83ed..76306ee4a0e 100644
--- a/src/features/MobileHome/SessionListContent/List/AddButton.tsx
+++ b/src/features/MobileHome/SessionListContent/List/AddButton.tsx
@@ -1,37 +1,35 @@
-import { Button, Flexbox } from '@lobehub/ui';
+import { Button, Flexbox, Tooltip } from '@lobehub/ui';
import { Plus } from 'lucide-react';
-import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActionSWR } from '@/libs/swr';
-import { sessionKeys } from '@/libs/swr/keys';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
+import { useCreateAgent } from '../../useCreateAgent';
-const AddButton = memo<{ groupId?: string }>(({ groupId }) => {
+const AddButton = ({
+ groupId,
+ visibility,
+}: {
+ groupId?: string;
+ visibility?: 'private' | 'public';
+}) => {
const { t } = useTranslation('chat');
- const createSession = useSessionStore((s) => s.createSession);
- const mobile = useServerConfigStore((s) => s.isMobile);
- const { mutate, isValidating } = useActionSWR(sessionKeys.createSession(groupId), () => {
- return createSession({ group: groupId });
- });
-
+ const { allowed, create, loading, reason } = useCreateAgent();
return (
- <Flexbox flex={1} padding={mobile ? 16 : 0}>
- <Button
- block
- icon={Plus}
- loading={isValidating}
- type={'fill'}
- style={{
- marginTop: 8,
- }}
- onClick={() => mutate()}
- >
- {t('newAgent')}
- </Button>
+ <Flexbox flex={1} padding={16}>
+ <Tooltip title={reason}>
+ <Button
+ block
+ aria-description={reason}
+ disabled={!allowed || loading}
+ icon={Plus}
+ loading={loading}
+ style={{ marginTop: 8 }}
+ type={'fill'}
+ onClick={() => create({ groupId, visibility })}
+ >
+ {t('newAgent')}
+ </Button>
+ </Tooltip>
</Flexbox>
);
-});
-
+};
export default AddButton;
diff --git a/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx b/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
index 3740bc685c7..45486591bea 100644
--- a/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
+++ b/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
@@ -1,234 +1,189 @@
-import type { ItemType } from '@lobehub/ui';
-import { ActionIcon, confirmModal, DropdownMenu, Icon, toast } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import {
- Check,
- ExternalLink,
- ListTree,
- LucideCopy,
- LucidePlus,
- MoreVertical,
- Pin,
- PinOff,
- Trash,
-} from 'lucide-react';
-import { memo, useMemo } from 'react';
+import { type SidebarAgentItem } from '@lobechat/types';
+import { type DropdownItem, Icon, toast } from '@lobehub/ui';
+import { ActionIcon, confirmModal, DropdownMenu } from '@lobehub/ui';
+import { Check, Copy, ListTree, MoreVertical, Pin, PinOff, Plus, Trash } from 'lucide-react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { isDesktop } from '@/const/index';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
-import { useGlobalStore } from '@/store/global';
+import { useResourceManageable } from '@/hooks/useResourceManageable';
+import { chatGroupService } from '@/services/chatGroup';
import { useHomeStore } from '@/store/home';
-import { useSessionStore } from '@/store/session';
-import { sessionHelpers } from '@/store/session/helpers';
-import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
-import { SessionDefaultGroup } from '@/types/index';
+import { homeAgentListSelectors } from '@/store/home/selectors';
import { getDeleteErrorMessageKey } from '@/utils/forbiddenError';
-interface ActionProps {
- group: string | undefined;
- id: string;
- openCreateGroupModal: () => void;
- parentType: 'agent' | 'group';
- setOpen: (open: boolean) => void;
-}
+import { openCreateGroupModal } from '../../Modals/CreateGroupModal';
-const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType, setOpen }) => {
- const { t } = useTranslation('chat');
+const Actions = ({
+ item,
+ groupId,
+ setOpen,
+}: {
+ item: SidebarAgentItem;
+ groupId?: string | null;
+ setOpen: (open: boolean) => void;
+}) => {
+ const navigate = useWorkspaceAwareNavigate();
+ const { t } = useTranslation(['chat', 'common']);
const { allowed: canCreate, reason: createReason } = usePermission('create_content');
const { allowed: canEdit, reason: editReason } = usePermission('edit_own_content');
-
- const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
-
- const sessionCustomGroups = useSessionStore(sessionGroupSelectors.sessionGroupItems, isEqual);
- const [pin, removeSession, pinSession, sessionType, duplicateSession, updateSessionGroup] =
- useSessionStore((s) => {
- const session = sessionSelectors.getSessionById(id)(s);
- return [
- sessionHelpers.getSessionPinned(session),
- s.removeSession,
- s.pinSession,
- session.type,
- s.duplicateSession,
- s.updateSessionGroupId,
- ];
- });
-
- const [pinAgentGroup, removeAgentGroup] = useHomeStore((s) => [
+ const access = useResourceAccess(item.type === 'group' ? 'agentGroup' : 'agent', item.id);
+ const manageable = useResourceManageable(item.userId);
+ const editable = canEdit && access.isAccessResolved && access.canEditResource;
+ const groups = useHomeStore(
+ item.visibility === 'private'
+ ? homeAgentListSelectors.privateAgentGroups
+ : homeAgentListSelectors.agentGroups,
+ );
+ const [
+ pinAgent,
+ pinAgentGroup,
+ duplicateAgent,
+ duplicateAgentGroup,
+ removeAgent,
+ removeAgentGroup,
+ updateAgentGroup,
+ refreshAgentList,
+ ] = useHomeStore((s) => [
+ s.pinAgent,
s.pinAgentGroup,
+ s.duplicateAgent,
+ s.duplicateAgentGroup,
+ s.removeAgent,
s.removeAgentGroup,
+ s.updateAgentGroup,
+ s.refreshAgentList,
]);
-
- const isDefault = group === SessionDefaultGroup.Default;
-
- const items = useMemo(
- () =>
- (
- [
- {
- disabled: !canEdit,
- icon: <Icon icon={pin ? PinOff : Pin} />,
- key: 'pin',
- label: t(pin ? 'pinOff' : 'pin'),
- title: editReason,
- onClick: () => {
- if (!canEdit) return;
- if (parentType === 'group') {
- pinAgentGroup(id, !pin);
- } else {
- pinSession(id, !pin);
+ const [loading, setLoading] = useState(false);
+ const run = async (action: () => Promise<void>) => {
+ if (loading) return;
+ setLoading(true);
+ try {
+ await action();
+ } finally {
+ setLoading(false);
+ }
+ };
+ const move = (target: string | null) =>
+ run(async () => {
+ if (item.type === 'group') {
+ await chatGroupService.updateGroup(item.id, { groupId: target });
+ await refreshAgentList();
+ } else await updateAgentGroup(item.id, target);
+ });
+ const items: DropdownItem[] = [
+ {
+ key: 'pin',
+ title: editReason,
+ disabled: !editable,
+ icon: <Icon icon={item.pinned ? PinOff : Pin} />,
+ label: t(item.pinned ? 'pinOff' : 'pin'),
+ onClick: () =>
+ run(() => (item.type === 'group' ? pinAgentGroup : pinAgent)(item.id, !item.pinned)),
+ },
+ {
+ key: 'duplicate',
+ title: createReason,
+ disabled:
+ !canCreate ||
+ !access.isAccessResolved ||
+ !(item.type === 'group' ? access.canEditResource : access.canUseResource),
+ icon: <Icon icon={Copy} />,
+ label: t('duplicate', { ns: 'common' }),
+ onClick: () =>
+ run(async () => {
+ const id = await (item.type === 'group' ? duplicateAgentGroup : duplicateAgent)(item.id);
+ if (id) navigate(`/${item.type === 'group' ? 'group' : 'agent'}/${id}`);
+ }),
+ },
+ { type: 'divider' },
+ {
+ key: 'moveGroup',
+ title: editReason,
+ disabled: !editable,
+ icon: <Icon icon={ListTree} />,
+ label: t('sessionGroup.moveGroup'),
+ children: [
+ ...groups.map((group) => ({
+ key: group.id,
+ icon: group.id === groupId ? <Icon icon={Check} /> : undefined,
+ label: group.name,
+ onClick: () => move(group.id),
+ })),
+ {
+ key: 'default',
+ icon: groupId === null ? <Icon icon={Check} /> : undefined,
+ label: t('defaultList'),
+ onClick: () => move(null),
+ },
+ { type: 'divider' },
+ {
+ key: 'createGroup',
+ title: createReason,
+ disabled: !canCreate,
+ icon: <Icon icon={Plus} />,
+ label: t('sessionGroup.createGroup'),
+ onClick: () => openCreateGroupModal(item.id, item.type, item.visibility),
+ },
+ ],
+ },
+ { type: 'divider' },
+ {
+ key: 'delete',
+ title: editReason,
+ danger: true,
+ disabled: !editable || !manageable || !access.canManageResource,
+ icon: <Icon icon={Trash} />,
+ label: t('delete', { ns: 'common' }),
+ onClick: () =>
+ confirmModal({
+ title: t('delete', { ns: 'common' }),
+ content: t(
+ item.type === 'group'
+ ? 'confirmRemoveChatGroupItemAlert'
+ : 'confirmRemoveSessionItemAlert',
+ ),
+ okText: t('delete', { ns: 'common' }),
+ okButtonProps: { danger: true },
+ onOk: () =>
+ run(async () => {
+ try {
+ await (item.type === 'group' ? removeAgentGroup : removeAgent)(item.id);
+ toast.success(
+ t(
+ item.type === 'group'
+ ? 'confirmRemoveGroupSuccess'
+ : 'confirmRemoveSessionSuccess',
+ ),
+ );
+ } catch (error) {
+ toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
}
- },
- },
- {
- disabled: !canCreate,
- icon: <Icon icon={LucideCopy} />,
- key: 'duplicate',
- label: t('duplicate', { ns: 'common' }),
- title: createReason,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- if (!canCreate) return;
-
- duplicateSession(id);
- },
- },
- ...(isDesktop
- ? [
- {
- icon: <Icon icon={ExternalLink} />,
- key: 'openInNewWindow',
- label: t('openInNewWindow'),
- onClick: ({ domEvent }: { domEvent: Event }) => {
- domEvent.stopPropagation();
- openAgentInNewWindow(id);
- },
- },
- ]
- : []),
- {
- type: 'divider',
- },
- {
- children: [
- ...sessionCustomGroups.map(({ id: groupId, name }) => ({
- disabled: !canEdit,
- icon: group === groupId ? <Icon icon={Check} /> : <div />,
- key: groupId,
- label: name,
- title: editReason,
- onClick: () => {
- if (!canEdit) return;
- updateSessionGroup(id, groupId);
- },
- })),
- {
- disabled: !canEdit,
- icon: isDefault ? <Icon icon={Check} /> : <div />,
- key: 'defaultList',
- label: t('defaultList'),
- title: editReason,
- onClick: () => {
- if (!canEdit) return;
- updateSessionGroup(id, SessionDefaultGroup.Default);
- },
- },
- {
- type: 'divider',
- },
- {
- disabled: !canCreate,
- icon: <Icon icon={LucidePlus} />,
- key: 'createGroup',
- label: <div>{t('sessionGroup.createGroup')}</div>,
- title: createReason,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- if (!canCreate) return;
- openCreateGroupModal();
- },
- },
- ],
- disabled: !canEdit,
- icon: <Icon icon={ListTree} />,
- key: 'moveGroup',
- label: t('sessionGroup.moveGroup'),
- title: editReason,
- },
- {
- type: 'divider',
- },
- {
- danger: true,
- disabled: !canEdit,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- title: editReason,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- if (!canEdit) return;
- confirmModal({
- okButtonProps: { danger: true },
- onOk: async () => {
- try {
- if (parentType === 'group') {
- await removeAgentGroup(id);
- toast.success(t('confirmRemoveGroupSuccess'));
- } else {
- await removeSession(id);
- toast.success(t('confirmRemoveSessionSuccess'));
- }
- } catch (error) {
- toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
- }
- },
- content:
- sessionType === 'group'
- ? t('confirmRemoveChatGroupItemAlert')
- : t('confirmRemoveSessionItemAlert'),
- okText: t('delete', { ns: 'common' }),
- title: t('delete', { ns: 'common' }),
- });
- },
- },
- ] as ItemType[]
- ).filter(Boolean),
- [
- canCreate,
- canEdit,
- createReason,
- duplicateSession,
- editReason,
- group,
- id,
- isDefault,
- openAgentInNewWindow,
- openCreateGroupModal,
- parentType,
- pin,
- pinAgentGroup,
- pinSession,
- removeAgentGroup,
- removeSession,
- sessionCustomGroups,
- sessionType,
- t,
- updateSessionGroup,
- ],
- );
-
+ }),
+ }),
+ },
+ ];
return (
- <DropdownMenu items={items} onOpenChange={setOpen}>
- <ActionIcon
- icon={MoreVertical}
- size={{
- blockSize: 28,
- size: 16,
- }}
- />
- </DropdownMenu>
+ <div
+ role="presentation"
+ onClick={(e) => {
+ if (e.currentTarget.contains(e.target as Node)) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }}
+ >
+ <DropdownMenu items={items} onOpenChange={setOpen}>
+ <ActionIcon
+ icon={MoreVertical}
+ loading={loading}
+ size={{ blockSize: 28, size: 16 }}
+ title={t('more', { ns: 'common' })}
+ />
+ </DropdownMenu>
+ </div>
);
-});
-
+};
export default Actions;
diff --git a/src/features/MobileHome/SessionListContent/List/Item/index.tsx b/src/features/MobileHome/SessionListContent/List/Item/index.tsx
index 126059cfba7..248ce633ec4 100644
--- a/src/features/MobileHome/SessionListContent/List/Item/index.tsx
+++ b/src/features/MobileHome/SessionListContent/List/Item/index.tsx
@@ -1,149 +1,53 @@
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import React, { memo, useMemo, useState } from 'react';
-import { shallow } from 'zustand/shallow';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
import { ModelTag } from '@/components/LobeIcons';
-import { DEFAULT_AVATAR } from '@/const/meta';
-import { INBOX_SESSION_ID } from '@/const/session';
-import { isDesktop } from '@/const/version';
+import { useAgentStore } from '@/store/agent';
+import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import { operationSelectors } 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';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-import { type LobeGroupSession } from '@/types/session';
import ListItem from '../../ListItem';
-import { openCreateGroupModal } from '../../Modals/CreateGroupModal';
import Actions from './Actions';
-interface SessionItemProps {
- id: string;
-}
-
-const SessionItem = memo<SessionItemProps>(({ id }) => {
+const AgentItem = ({ item, groupId }: { item: SidebarAgentItem; groupId?: string | null }) => {
+ const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
-
- const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
-
- const [active] = useSessionStore((s) => [s.activeId === id]);
- const [loading] = useChatStore((s) => [
- operationSelectors.isAgentRuntimeVisiblyRunning(s) && id === s.activeAgentId,
- ]);
-
- const [pin, title, avatar, avatarBackground, updateAt, members, model, group, sessionType] =
- useSessionStore((s) => {
- const session = sessionSelectors.getSessionById(id)(s);
- const meta = session.meta;
-
- return [
- sessionHelpers.getSessionPinned(session),
- sessionMetaSelectors.getTitle(meta),
- sessionMetaSelectors.getAvatar(meta),
- meta.backgroundColor,
- session?.updatedAt,
- (session as LobeGroupSession).members,
- session.type === 'agent' ? (session as any).model : undefined,
- session?.group,
- session.type,
- ];
- });
-
- // Only hide the model tag for the inbox session itself (Lobe AI)
- const showModel = sessionType === 'agent' && model && id !== INBOX_SESSION_ID;
-
- const handleDoubleClick = () => {
- if (isDesktop) {
- openAgentInNewWindow(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') {
- openAgentInNewWindow(id);
- }
- };
-
- const actions = useMemo(
- () => (
- <Actions
- group={group}
- id={id}
- openCreateGroupModal={() => openCreateGroupModal(id)}
- parentType={sessionType}
- setOpen={setOpen}
- />
- ),
- [group, id],
- );
-
- const addon = useMemo(
- () =>
- !showModel ? undefined : (
- <Flexbox horizontal gap={4} style={{ flexWrap: 'wrap' }}>
- <ModelTag model={model} />
- </Flexbox>
- ),
- [showModel, model],
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
+ const loading = useChatStore(
+ item.type === 'group'
+ ? operationSelectors.isGroupVisiblyRunning(item.id)
+ : operationSelectors.isAgentVisiblyRunning(item.id),
);
-
- const currentUser = useUserStore((s) => ({
- avatar: userProfileSelectors.userAvatar(s),
- name: userProfileSelectors.displayUserName(s) || userProfileSelectors.nickName(s) || 'You',
- }));
-
- const sessionAvatar: string | { avatar: string; background?: string }[] =
- sessionType === 'group'
- ? [
- {
- avatar: currentUser.avatar || DEFAULT_AVATAR,
- background: undefined,
- },
- ...(members?.map((member) => ({
- avatar: member.avatar || DEFAULT_AVATAR,
- background: member.backgroundColor || undefined,
- })) || []),
- ]
- : avatar;
-
return (
<ListItem
- actions={actions}
- active={active}
- addon={addon}
- avatar={sessionAvatar as any} // Fix: Bypass complex intersection type ReactNode & avatar type
- avatarBackground={avatarBackground}
- date={updateAt?.valueOf()}
- draggable={isDesktop}
- key={id}
+ actions={<Actions groupId={groupId} item={item} setOpen={setOpen} />}
+ active={item.type === 'group' ? activeGroupId === item.id : activeAgentId === item.id}
+ avatar={item.avatar || DEFAULT_AVATAR}
+ avatarBackground={item.backgroundColor || undefined}
+ date={item.updatedAt?.valueOf()}
+ key={item.id}
loading={loading}
- pin={pin}
+ pin={item.pinned}
showAction={open}
- title={title}
- type={sessionType}
+ title={agentDisplayName(item, t(item.type === 'group' ? 'untitledGroup' : 'untitledAgent'))}
+ type={item.type}
+ addon={
+ item.type === 'agent' && item.model ? (
+ <Flexbox horizontal gap={4} style={{ flexWrap: 'wrap' }}>
+ <ModelTag model={item.model} />
+ </Flexbox>
+ ) : undefined
+ }
styles={{
- container: {
- gap: 12,
- },
- content: {
- gap: 6,
- maskImage: `linear-gradient(90deg, #000 90%, transparent)`,
- },
+ container: { gap: 12 },
+ content: { gap: 6, maskImage: 'linear-gradient(90deg, black 90%, transparent)' },
}}
- onDoubleClick={handleDoubleClick}
- onDragEnd={handleDragEnd}
- onDragStart={handleDragStart}
/>
);
-}, shallow);
-
-export default SessionItem;
+};
+export default AgentItem;
diff --git a/src/features/MobileHome/SessionListContent/List/index.tsx b/src/features/MobileHome/SessionListContent/List/index.tsx
index 09c5e40c712..8cd88d4b7a3 100644
--- a/src/features/MobileHome/SessionListContent/List/index.tsx
+++ b/src/features/MobileHome/SessionListContent/List/index.tsx
@@ -1,90 +1,50 @@
+import { AGENT_CHAT_URL, GROUP_CHAT_URL } from '@lobechat/const';
+import { type SidebarAgentItem } from '@lobechat/types';
import { createStaticStyles } from '@lobehub/ui';
-import { memo } from 'react';
import LazyLoad from 'react-lazy-load';
-import { Link } from 'react-router';
-import { AGENT_CHAT_URL } from '@/const/index';
-import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';
-import { useAnalytics } from '@/libs/analytics/client';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { getSessionStoreState, useSessionStore } from '@/store/session';
-import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
-import { getUserStoreState } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-import { type LobeSessions } from '@/types/session';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
import SkeletonList from '../../SkeletonList';
+import { useListNavigation } from '../useListNavigation';
import AddButton from './AddButton';
-import SessionItem from './Item';
+import AgentItem from './Item';
const styles = createStaticStyles(
({ css }) => css`
min-height: 70px;
`,
);
-interface SessionListProps {
- dataSource?: LobeSessions;
- groupId?: string;
+
+interface AgentListProps {
+ dataSource: SidebarAgentItem[];
+ groupId?: string | null;
showAddButton?: boolean;
+ visibility?: 'private' | 'public';
}
-const SessionList = memo<SessionListProps>(({ dataSource, groupId, showAddButton = true }) => {
- const { analytics } = useAnalytics();
-
- const isInit = useSessionStore(sessionSelectors.isSessionListInit);
- const mobile = useServerConfigStore((s) => s.isMobile);
-
- const navigateToAgent = useNavigateToAgent();
-
- const isEmpty = !dataSource || dataSource.length === 0;
- return !isInit ? (
- <SkeletonList />
- ) : !isEmpty ? (
- dataSource.map(({ id, ...res }) => (
- <LazyLoad className={styles} key={id}>
- <Link
- aria-label={id}
- to={AGENT_CHAT_URL((res as any).config?.id, mobile)}
- onClick={(e) => {
- e.preventDefault();
- navigateToAgent((res as any).config?.id);
-
- // Enhanced analytics tracking
- if (analytics) {
- const userStore = getUserStoreState();
- const sessionStore = getSessionStoreState();
-
- const userId = userProfileSelectors.userId(userStore);
- const session = sessionSelectors.getSessionById(id)(sessionStore);
-
- if (session) {
- const sessionGroupId = session.group || 'default';
- const group = sessionGroupSelectors.getGroupById(sessionGroupId)(sessionStore);
- const groupName =
- group?.name || (sessionGroupId === 'default' ? 'Default' : 'Unknown');
-
- analytics?.track({
- name: 'switch_session',
- properties: {
- assistant_name: session.meta?.title || 'Untitled Agent',
- assistant_tags: session.meta?.tags || [],
- group_id: sessionGroupId,
- group_name: groupName,
- session_id: id,
- spm: 'homepage.chat.session_list_item.click',
- user_id: userId || 'anonymous',
- },
- });
- }
- }
- }}
- >
- <SessionItem id={id} />
- </Link>
- </LazyLoad>
- ))
- ) : (
- showAddButton && <AddButton groupId={groupId} />
- );
-});
-
-export default SessionList;
+const AgentList = ({ dataSource, groupId, visibility, showAddButton = true }: AgentListProps) => {
+ const onNavigate = useListNavigation('list');
+ const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
+ if (!isInit) return <SkeletonList />;
+ return dataSource.length
+ ? dataSource.map((item) => {
+ const categoryId = groupId === undefined ? (item.groupId ?? null) : groupId;
+ return (
+ <LazyLoad className={styles} key={item.id}>
+ <WorkspaceLink
+ aria-label={item.id}
+ key={item.id}
+ to={item.type === 'group' ? GROUP_CHAT_URL(item.id) : AGENT_CHAT_URL(item.id, true)}
+ onClick={(event) => onNavigate(event, item, categoryId)}
+ >
+ <AgentItem groupId={categoryId} item={item} />
+ </WorkspaceLink>
+ </LazyLoad>
+ );
+ })
+ : showAddButton && <AddButton groupId={groupId ?? undefined} visibility={visibility} />;
+};
+
+export default AgentList;
diff --git a/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx b/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
index 08697a44aac..c30deaa71ac 100644
--- a/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
+++ b/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
@@ -10,8 +10,8 @@ import { PencilLine, Trash } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useSessionStore } from '@/store/session';
-import { type SessionGroupItem } from '@/types/session';
+import { useHomeStore } from '@/store/home';
+import { type SessionGroupItemBase } from '@/types/session';
const styles = createStaticStyles(({ css }) => ({
content: css`
@@ -27,7 +27,7 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface GroupItemProps extends SessionGroupItem {
+interface GroupItemProps extends SessionGroupItemBase {
disabled?: boolean;
}
@@ -35,9 +35,9 @@ const GroupItem = memo<GroupItemProps>(({ id, name, disabled = false }) => {
const { t } = useTranslation(['chat', 'common']);
const [editing, setEditing] = useState(false);
- const [updateSessionGroupName, removeSessionGroup] = useSessionStore((s) => [
- s.updateSessionGroupName,
- s.removeSessionGroup,
+ const [updateSessionGroupName, removeSessionGroup] = useHomeStore((s) => [
+ s.updateGroupName,
+ s.removeGroup,
]);
return (
diff --git a/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/index.tsx b/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/index.tsx
index c70dd98a5f9..5b34fade133 100644
--- a/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/index.tsx
+++ b/src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/index.tsx
@@ -6,9 +6,9 @@ import { useTranslation } from 'react-i18next';
import ImperativeModal from '@/components/ImperativeModal';
import { usePermission } from '@/hooks/usePermission';
-import { useSessionStore } from '@/store/session';
-import { sessionGroupSelectors } from '@/store/session/selectors';
-import { type SessionGroupItem } from '@/types/session';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { type SessionGroupItemBase } from '@/types/session';
import GroupItem from './GroupItem';
@@ -25,14 +25,27 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const ConfigGroupModal = memo<{ onCancel?: () => void; open?: boolean }>(({ open, onCancel }) => {
+interface ConfigGroupModalProps {
+ onCancel?: () => void;
+ open?: boolean;
+ scope?: 'private' | 'public';
+}
+
+const ConfigGroupModal = memo<ConfigGroupModalProps>(({ open, onCancel, scope = 'public' }) => {
const { t } = useTranslation('chat');
const { allowed: canCreate, reason: createReason } = usePermission('create_content');
const { allowed: canEdit } = usePermission('edit_own_content');
- const sessionGroupItems = useSessionStore(sessionGroupSelectors.sessionGroupItems, isEqual);
- const [addSessionGroup, updateSessionGroupSort] = useSessionStore((s) => [
- s.addSessionGroup,
- s.updateSessionGroupSort,
+ const sessionGroupItems = useHomeStore(
+ (s) =>
+ (scope === 'private'
+ ? homeAgentListSelectors.privateAgentGroups(s)
+ : homeAgentListSelectors.agentGroups(s)
+ ).map(({ id, name, sort }) => ({ id, name, sort })),
+ isEqual,
+ );
+ const [addSessionGroup, updateSessionGroupSort] = useHomeStore((s) => [
+ s.addGroup,
+ s.updateGroupSort,
]);
const [loading, setLoading] = useState(false);
@@ -48,7 +61,7 @@ const ConfigGroupModal = memo<{ onCancel?: () => void; open?: boolean }>(({ open
<Flexbox>
<SortableList
items={sessionGroupItems}
- renderItem={(item: SessionGroupItem) => (
+ renderItem={(item: SessionGroupItemBase) => (
<SortableList.Item
horizontal
align={'center'}
@@ -60,7 +73,7 @@ const ConfigGroupModal = memo<{ onCancel?: () => void; open?: boolean }>(({ open
<GroupItem {...item} disabled={!canEdit} />
</SortableList.Item>
)}
- onChange={(items: SessionGroupItem[]) => {
+ onChange={(items: SessionGroupItemBase[]) => {
if (!canEdit) return;
updateSessionGroupSort(items);
}}
@@ -74,8 +87,11 @@ const ConfigGroupModal = memo<{ onCancel?: () => void; open?: boolean }>(({ open
onClick={async () => {
if (!canCreate) return;
setLoading(true);
- await addSessionGroup(t('sessionGroup.newGroup'));
- setLoading(false);
+ try {
+ await addSessionGroup(t('sessionGroup.newGroup'), scope);
+ } finally {
+ setLoading(false);
+ }
}}
>
{t('sessionGroup.createGroup')}
diff --git a/src/features/MobileHome/SessionListContent/Modals/CreateGroupModal.tsx b/src/features/MobileHome/SessionListContent/Modals/CreateGroupModal.tsx
index fce4f257fbd..11e6c991f4a 100644
--- a/src/features/MobileHome/SessionListContent/Modals/CreateGroupModal.tsx
+++ b/src/features/MobileHome/SessionListContent/Modals/CreateGroupModal.tsx
@@ -12,23 +12,23 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
+import { chatGroupService } from '@/services/chatGroup';
import { useGlobalStore } from '@/store/global';
-import { useSessionStore } from '@/store/session';
+import { useHomeStore } from '@/store/home';
interface CreateGroupContentProps {
id: string;
+ itemType: 'agent' | 'group';
+ visibility?: 'private' | 'public';
}
-const CreateGroupContent = memo<CreateGroupContentProps>(({ id }) => {
+const CreateGroupContent = memo<CreateGroupContentProps>(({ id, itemType, visibility }) => {
const { t } = useTranslation(['chat', 'common']);
const { close } = useModalContext();
const { allowed: canCreate } = usePermission('create_content');
const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);
- const [updateSessionGroup, addCustomGroup] = useSessionStore((s) => [
- s.updateSessionGroupId,
- s.addSessionGroup,
- ]);
+ const [updateAgentGroup, addCustomGroup] = useHomeStore((s) => [s.updateAgentGroup, s.addGroup]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
@@ -36,15 +36,18 @@ const CreateGroupContent = memo<CreateGroupContentProps>(({ id }) => {
const handleCreate = async () => {
// Enter fires as fast as the user repeats it — a second pass while
// `addCustomGroup` is in flight would create a second group and move the
- // session into whichever request settles last.
+ // item into whichever request settles last.
if (!canCreate || loading) return;
if (input.length === 0 || input.length > 20 || input.trim() === '')
return toast.warning(t('sessionGroup.tooLong'));
setLoading(true);
try {
- const groupId = await addCustomGroup(input);
- await updateSessionGroup(id, groupId);
+ const groupId = await addCustomGroup(input, visibility);
+ if (itemType === 'group') {
+ await chatGroupService.updateGroup(id, { groupId });
+ await useHomeStore.getState().refreshAgentList();
+ } else await updateAgentGroup(id, groupId);
toggleExpandSessionGroup(groupId, true);
toast.success(t('sessionGroup.createSuccess'));
close();
@@ -77,9 +80,13 @@ const CreateGroupContent = memo<CreateGroupContentProps>(({ id }) => {
CreateGroupContent.displayName = 'MobileCreateGroupContent';
-export const openCreateGroupModal = (id: string) =>
+export const openCreateGroupModal = (
+ id: string,
+ itemType: 'agent' | 'group',
+ visibility?: 'private' | 'public',
+) =>
createModal({
- content: <CreateGroupContent id={id} />,
+ content: <CreateGroupContent id={id} itemType={itemType} visibility={visibility} />,
footer: null,
styles: { content: { padding: 0 } },
title: translate('sessionGroup.createGroup', { ns: 'chat' }),
diff --git a/src/features/MobileHome/SessionListContent/Modals/RenameGroupModal.tsx b/src/features/MobileHome/SessionListContent/Modals/RenameGroupModal.tsx
index 2fa90db6095..465c2c7cc01 100644
--- a/src/features/MobileHome/SessionListContent/Modals/RenameGroupModal.tsx
+++ b/src/features/MobileHome/SessionListContent/Modals/RenameGroupModal.tsx
@@ -12,8 +12,8 @@ import { t as translate } from 'i18next';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useSessionStore } from '@/store/session';
-import { sessionGroupSelectors } from '@/store/session/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
interface RenameGroupContentProps {
id: string;
@@ -23,8 +23,15 @@ const RenameGroupContent = memo<RenameGroupContentProps>(({ id }) => {
const { t } = useTranslation(['chat', 'common']);
const { close } = useModalContext();
- const updateSessionGroupName = useSessionStore((s) => s.updateSessionGroupName);
- const group = useSessionStore((s) => sessionGroupSelectors.getGroupById(id)(s), isEqual);
+ const updateSessionGroupName = useHomeStore((s) => s.updateGroupName);
+ const group = useHomeStore(
+ (s) =>
+ [
+ ...homeAgentListSelectors.agentGroups(s),
+ ...homeAgentListSelectors.privateAgentGroups(s),
+ ].find((group) => group.id === id),
+ isEqual,
+ );
const [input, setInput] = useState<string>(group?.name ?? '');
const [loading, setLoading] = useState(false);
diff --git a/src/features/MobileHome/SessionListContent/SearchMode.tsx b/src/features/MobileHome/SessionListContent/SearchMode.tsx
index 24b3c7a9ea1..0c8763f2e20 100644
--- a/src/features/MobileHome/SessionListContent/SearchMode.tsx
+++ b/src/features/MobileHome/SessionListContent/SearchMode.tsx
@@ -1,24 +1,18 @@
import { memo } from 'react';
import { useHomeStore } from '@/store/home';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { serverConfigSelectors } from '@/store/serverConfig/selectors';
-import { useSessionStore } from '@/store/session';
+import { useAgentSearch } from '../Layout/AgentSearchContext';
import SkeletonList from '../SkeletonList';
import { AgentSearchList } from './AgentSearchList';
-import { getVisibleAgentSearchResults } from './agentSearchResults';
const SearchMode = memo(() => {
- const sessionSearchKeywords = useSessionStore((s) => s.sessionSearchKeywords);
+ const { keywords: sessionSearchKeywords } = useAgentSearch();
const useSearchAgents = useHomeStore((s) => s.useSearchAgents);
- const isMobile = useServerConfigStore(serverConfigSelectors.isMobile);
-
const { data, isLoading } = useSearchAgents(sessionSearchKeywords?.trim() || undefined);
- const filteredData = getVisibleAgentSearchResults(data, isMobile);
- return isLoading ? <SkeletonList /> : <AgentSearchList dataSource={filteredData} />;
+ return isLoading ? <SkeletonList /> : <AgentSearchList dataSource={data} />;
});
SearchMode.displayName = 'SessionSearchMode';
diff --git a/src/features/MobileHome/SessionListContent/agentSearchResults.test.ts b/src/features/MobileHome/SessionListContent/agentSearchResults.test.ts
deleted file mode 100644
index a12fdb28e3e..00000000000
--- a/src/features/MobileHome/SessionListContent/agentSearchResults.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { SidebarAgentItem } from '@lobechat/types';
-import { describe, expect, it } from 'vitest';
-
-import { getVisibleAgentSearchResults } from './agentSearchResults';
-
-const createSearchResult = (overrides: Partial<SidebarAgentItem> = {}): SidebarAgentItem => ({
- id: 'agent-1',
- pinned: false,
- title: 'Social Agent',
- type: 'agent',
- updatedAt: new Date('2026-08-29T00:00:00.000Z'),
- ...overrides,
-});
-
-describe('getVisibleAgentSearchResults', () => {
- it('keeps mobile agent results', () => {
- const agent = createSearchResult();
-
- expect(getVisibleAgentSearchResults([agent], true)).toEqual([agent]);
- });
-
- it('hides chat groups only on the mobile home', () => {
- const agent = createSearchResult();
- const group = createSearchResult({ id: 'group-1', type: 'group' });
-
- expect(getVisibleAgentSearchResults([agent, group], true)).toEqual([agent]);
- expect(getVisibleAgentSearchResults([agent, group], false)).toEqual([agent, group]);
- });
-});
diff --git a/src/features/MobileHome/SessionListContent/agentSearchResults.ts b/src/features/MobileHome/SessionListContent/agentSearchResults.ts
deleted file mode 100644
index 80588b89744..00000000000
--- a/src/features/MobileHome/SessionListContent/agentSearchResults.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { SidebarAgentItem } from '@lobechat/types';
-
-export const getVisibleAgentSearchResults = (
- results: SidebarAgentItem[] | undefined,
- isMobile: boolean,
-): SidebarAgentItem[] | undefined => {
- if (!results || !isMobile) return results;
-
- return results.filter((item) => item.type === 'agent');
-};
diff --git a/src/features/MobileHome/SessionListContent/index.tsx b/src/features/MobileHome/SessionListContent/index.tsx
index 97f658ac4e7..8bbc2854f34 100644
--- a/src/features/MobileHome/SessionListContent/index.tsx
+++ b/src/features/MobileHome/SessionListContent/index.tsx
@@ -2,13 +2,13 @@
import { memo } from 'react';
-import { useSessionStore } from '@/store/session';
-
+import { useAgentSearch } from '../Layout/AgentSearchContext';
import DefaultMode from './DefaultMode';
import SearchMode from './SearchMode';
const SessionListContent = memo(() => {
- const isSearching = useSessionStore((s) => s.isSearching);
+ const { keywords } = useAgentSearch();
+ const isSearching = !!keywords.trim();
return isSearching ? <SearchMode /> : <DefaultMode />;
});
diff --git a/src/features/MobileHome/SessionListContent/useListNavigation.ts b/src/features/MobileHome/SessionListContent/useListNavigation.ts
new file mode 100644
index 00000000000..35add5c2bd6
--- /dev/null
+++ b/src/features/MobileHome/SessionListContent/useListNavigation.ts
@@ -0,0 +1,70 @@
+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';
+import type { MouseEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
+import { useChatStore } from '@/store/chat';
+import { useHomeStore } from '@/store/home';
+import { getUserStoreState } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+export const useListNavigation = (source: 'list' | 'search') => {
+ const { t } = useTranslation('chat');
+
+ return (
+ event: MouseEvent<HTMLAnchorElement>,
+ item: SidebarAgentItem,
+ groupId?: string | null,
+ ) => {
+ if (
+ event.defaultPrevented ||
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey ||
+ (event.currentTarget.target && event.currentTarget.target !== '_self')
+ )
+ return;
+
+ useChatStore.getState().clearPortalStack();
+
+ const home = useHomeStore.getState();
+ const groups = [...home.agentGroups, ...home.privateAgentGroups];
+ const pinnedItem = [...home.pinnedAgents, ...home.privatePinnedAgents].find(
+ (child) => child.id === item.id && child.type === item.type,
+ );
+ const categoryId = groupId === undefined ? (item.groupId ?? pinnedItem?.groupId) : groupId;
+ const group = groups.find((group) =>
+ categoryId
+ ? group.id === categoryId
+ : group.items.some((child) => child.id === item.id && child.type === item.type),
+ );
+ const isUngrouped =
+ categoryId === null ||
+ [...home.ungroupedAgents, ...home.privateUngroupedAgents].some(
+ (child) => child.id === item.id && child.type === item.type,
+ );
+
+ void trackProductUsageEvent({
+ name: 'switch_session',
+ properties: {
+ agent_id: item.type === 'agent' ? item.id : undefined,
+ assistant_name: agentDisplayName(
+ item,
+ t(item.type === 'group' ? 'untitledGroup' : 'untitledAgent'),
+ ),
+ chat_group_id: item.type === 'group' ? item.id : undefined,
+ group_id: group?.id ?? (isUngrouped ? 'default' : undefined),
+ group_name: group?.name ?? (isUngrouped ? 'Default' : undefined),
+ resource_id: item.id,
+ resource_type: item.type,
+ spm:
+ source === 'list'
+ ? 'homepage.chat.session_list_item.click'
+ : 'homepage.chat.search_result.click',
+ user_id: userProfileSelectors.userId(getUserStoreState()) || 'anonymous',
+ },
+ });
+ };
+};
diff --git a/src/features/MobileHome/useCreateAgent.ts b/src/features/MobileHome/useCreateAgent.ts
new file mode 100644
index 00000000000..4ffcb2e5565
--- /dev/null
+++ b/src/features/MobileHome/useCreateAgent.ts
@@ -0,0 +1,66 @@
+import { toast } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
+import { agentService } from '@/services/agent';
+import { useAgentStore } from '@/store/agent';
+import { useHomeStore } from '@/store/home';
+
+export const useCreateAgent = () => {
+ const { t } = useTranslation('chat');
+ const { allowed, reason } = usePermission('create_content');
+ const createAgent = useAgentStore((s) => s.createAgent);
+ const fetchAgentList = useHomeStore((s) => s.fetchAgentList);
+ const navigate = useWorkspaceAwareNavigate();
+ const [loading, setLoading] = useState(false);
+
+ const create = async (options?: {
+ groupId?: string;
+ pinned?: boolean;
+ visibility?: 'private' | 'public';
+ }) => {
+ if (!allowed || loading) return;
+ setLoading(true);
+ try {
+ let agentId: string;
+ try {
+ ({ agentId } = await createAgent({
+ groupId: options?.groupId,
+ visibility: options?.visibility,
+ }));
+ } catch (error) {
+ console.error('Failed to create agent:', error);
+ toast.error(t('sessionGroup.createAgentFailed'));
+ return;
+ }
+
+ navigate(`/agent/${agentId}`);
+ let hasWarnings = false;
+
+ if (options?.pinned) {
+ try {
+ await agentService.updateAgentPinned(agentId, true);
+ } catch (error) {
+ hasWarnings = true;
+ console.error('Failed to pin the created agent:', error);
+ toast.warning(t('sessionGroup.createAgentPinFailed'));
+ }
+ }
+
+ try {
+ await fetchAgentList();
+ } catch (error) {
+ hasWarnings = true;
+ console.error('Failed to refresh the list after creating an agent:', error);
+ toast.warning(t('sessionGroup.createAgentRefreshFailed'));
+ }
+
+ return { agentId, hasWarnings };
+ } finally {
+ setLoading(false);
+ }
+ };
+ return { allowed, create, loading, reason };
+};
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
index adc3b717a0a..de8e2127653 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
@@ -19,7 +19,7 @@ import AllTopicsDrawer from '../AllTopicsDrawer';
import ByTimeMode from '../TopicListContent/ByTimeMode';
import FlatMode from '../TopicListContent/FlatMode';
-const TopicList = memo(() => {
+const TopicList = memo<{ showEmptyAction?: boolean }>(({ showEmptyAction = true }) => {
const { t } = useTranslation('topic');
const router = useQueryRoute();
const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
@@ -40,7 +40,7 @@ const TopicList = memo(() => {
return (
<>
- {topicLength === 0 && activeGroupId && (
+ {showEmptyAction && topicLength === 0 && activeGroupId && (
<EmptyNavItem
title={t('actions.addNewTopic')}
onClick={() => {
diff --git a/src/routes/(main)/group/_layout/index.tsx b/src/routes/(main)/group/_layout/index.tsx
index f05baace3b9..a412f2efb00 100644
--- a/src/routes/(main)/group/_layout/index.tsx
+++ b/src/routes/(main)/group/_layout/index.tsx
@@ -18,7 +18,7 @@ const Layout: FC = () => {
return (
<>
<Sidebar />
- <Flexbox className={styles.mainContainer} flex={1} height={'100%'}>
+ <Flexbox className={styles.mainContainer} flex={1} height={'100%'} width={'100%'}>
{/* Keep the sidebar interactive when the routed group is gone (deleted
or made private) — only the content area collapses to the 404 card. */}
<GroupNotFoundGuard>
diff --git a/src/routes/(mobile)/chat/settings/index.tsx b/src/routes/(mobile)/chat/settings/index.tsx
index b98b101c241..c9c030aa918 100644
--- a/src/routes/(mobile)/chat/settings/index.tsx
+++ b/src/routes/(mobile)/chat/settings/index.tsx
@@ -6,19 +6,20 @@ import { memo, useState } from 'react';
import MobileContentLayout from '@/components/server/MobileNavLayout';
import { useCategory } from '@/features/AgentSetting/AgentCategory/useCategory';
import AgentSettings from '@/features/AgentSetting/AgentSettings';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import Footer from '@/features/Setting/Footer';
import { usePermission } from '@/hooks/usePermission';
import MobileHeader from '@/routes/(mobile)/chat/settings/_layout/Header';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
-import { useSessionStore } from '@/store/session';
export default memo(() => {
const [tab, setTab] = useState(ChatSettingsTabs.Prompt);
const cateItems = useCategory();
- const id = useSessionStore((s) => s.activeId);
+ const id = useAgentStore((s) => s.activeAgentId);
const { allowed: canEdit } = usePermission('edit_own_content');
+ const { canEditResource, isAccessResolved } = useResourceAccess('agent', id);
const [updateAgentConfig, updateAgentMeta, config, meta] = useAgentStore((s) => [
s.updateAgentConfig,
@@ -41,7 +42,7 @@ export default memo(() => {
/>
<AgentSettings
config={config}
- disabled={!canEdit}
+ disabled={!canEdit || !isAccessResolved || !canEditResource}
id={id}
loading={isLoading}
meta={meta}
diff --git a/src/routes/(mobile)/group/_layout/index.tsx b/src/routes/(mobile)/group/_layout/index.tsx
new file mode 100644
index 00000000000..f9d4f789a0c
--- /dev/null
+++ b/src/routes/(mobile)/group/_layout/index.tsx
@@ -0,0 +1 @@
+export { MobileGroupLayout as default } from '@/features/MobileGroupChat/Layout';
diff --git a/src/routes/(mobile)/group/index.tsx b/src/routes/(mobile)/group/index.tsx
new file mode 100644
index 00000000000..6733b47d966
--- /dev/null
+++ b/src/routes/(mobile)/group/index.tsx
@@ -0,0 +1 @@
+export { MobileGroupChat as default } from '@/features/MobileGroupChat';
diff --git a/src/routes/(mobile)/settings/_layout/Header.test.tsx b/src/routes/(mobile)/settings/_layout/Header.test.tsx
index 99ebf3c6092..076b859597b 100644
--- a/src/routes/(mobile)/settings/_layout/Header.test.tsx
+++ b/src/routes/(mobile)/settings/_layout/Header.test.tsx
@@ -13,8 +13,8 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
vi.mock('@/hooks/useShowMobileWorkspace', () => ({ useShowMobileWorkspace: () => false }));
-vi.mock('@/store/session', () => ({
- useSessionStore: (selector: (state: { activeId?: string }) => unknown) => selector({}),
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: { activeAgentId?: string }) => unknown) => selector({}),
}));
const renderHeader = (tab: string) =>
diff --git a/src/routes/(mobile)/settings/_layout/Header.tsx b/src/routes/(mobile)/settings/_layout/Header.tsx
index d2eb1ce94cf..204df9f38a8 100644
--- a/src/routes/(mobile)/settings/_layout/Header.tsx
+++ b/src/routes/(mobile)/settings/_layout/Header.tsx
@@ -8,8 +8,8 @@ import { useMatch, useParams, useSearchParams } from 'react-router';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';
+import { useAgentStore } from '@/store/agent';
import { SettingsTabs } from '@/store/global/initialState';
-import { useSessionStore } from '@/store/session';
import { mobileHeaderSticky } from '@/styles/mobileHeader';
// Explicit tab → i18n key map. Covers:
@@ -44,7 +44,7 @@ const Header = memo(() => {
const [searchParams] = useSearchParams();
const workspaceSettingsMatch = useMatch('/:workspaceSlug/settings/:workspaceTab/*');
- const isSessionActive = useSessionStore((s) => !!s.activeId);
+ const isAgentActive = useAgentStore((s) => !!s.activeAgentId);
// Personal provider details carry the id in the path; the workspace provider
// page canonicalizes it into the `provider` query param instead.
const queryProvider = searchParams.get('provider');
@@ -53,7 +53,7 @@ const Header = memo(() => {
const isProvider = providerId && providerId !== 'all';
const handleBackClick = () => {
- if (isSessionActive && showMobileWorkspace) {
+ if (isAgentActive && showMobileWorkspace) {
navigate('/agent');
} else if (params.providerId && params.providerId !== 'all') {
navigate('/settings/provider/all', { escape: true });
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 4716ffa728c..3b7f7e2e748 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -14,8 +14,10 @@ import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';
import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';
import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
+import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
+import { agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';
import { routeMeta } from '@/spa/router/routeMeta';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
@@ -73,6 +75,40 @@ export const sharedMainAreaChildren: RouteObject[] = [
path: 'agent',
},
+ {
+ path: 'group',
+ children: [
+ { index: true, element: redirectElement('..') },
+ {
+ path: ':gid',
+ loader: agentGroupAccessLoader,
+ element: dynamicLayout(
+ () => import('@/routes/(mobile)/group/_layout'),
+ 'Mobile > Group > Layout',
+ { preloadId: 'mobile-group' },
+ ),
+ handle: { meta: groupRouteMeta },
+ errorElement: <ErrorBoundary />,
+ children: [
+ {
+ index: true,
+ element: dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/group')),
+ 'Mobile > Group',
+ ),
+ },
+ {
+ path: ':topicId',
+ element: dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/group')),
+ 'Mobile > Group > Topic',
+ ),
+ },
+ ],
+ },
+ ],
+ },
+
// Discover routes with nested structure
{
children: [
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index c7e3abdde7d..3bfe0ff9435 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -490,6 +490,23 @@ const isAgentVisiblyRunning =
return false;
};
+/** Check visible runtime loading across all agents and topics in a chat group. */
+const isGroupVisiblyRunning =
+ (groupId: string) =>
+ (s: ChatStoreState): boolean => {
+ for (const type of AI_RUNTIME_OPERATION_TYPES) {
+ const operationIds = s.operationsByType[type] || [];
+ if (
+ operationIds.some((id) => {
+ const op = s.operations[id];
+ return op && isVisiblyRunningOperation(op) && op.context.groupId === groupId;
+ })
+ )
+ return true;
+ }
+ return false;
+ };
+
/**
* Whether a turn is visibly in progress for a topic on THIS client — the whole
* send → run pipeline (see TOPIC_VISIBLY_RUNNING_OPERATION_TYPES), matched by
@@ -1017,6 +1034,7 @@ export const operationSelectors = {
isAgentRunning,
isAgentVisiblyRunning,
+ isGroupVisiblyRunning,
isAgentRuntimeRunning,
isAgentRuntimeVisiblyRunning,
isAgentUnreadCompleted,
diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.ts
index 912df568b53..81db87c0c10 100644
--- a/src/store/home/slices/agentList/action.ts
+++ b/src/store/home/slices/agentList/action.ts
@@ -124,6 +124,11 @@ export class AgentListActionImpl {
await this.#agentList.revalidate(AGENT_LIST_KEY);
};
+ fetchAgentList = async (): Promise<void> => {
+ getAgentStoreState().invalidateAvailableAgents();
+ await this.#agentList.fetch(LIST_PARAMS, { fresh: true });
+ };
+
/** Rename / re-avatar an agent: the sidebar row changes now, rolls back on failure. */
updateAgentMeta = async (id: string, patch: SidebarAgentMetaPatch): Promise<void> => {
await this.#agents.optimistic(
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index 04815bf8d78..03e407545cc 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -28,7 +28,7 @@ export class SidebarUIActionImpl {
this.#get = get;
}
- duplicateAgent = async (agentId: string, newTitle?: string): Promise<void> => {
+ duplicateAgent = async (agentId: string, newTitle?: string): Promise<string | undefined> => {
const loadingToast = toast.loading(t('duplicateSession.loading', { ns: 'chat' }));
const result = await agentService.duplicateAgent(agentId, newTitle);
@@ -46,9 +46,10 @@ export class SidebarUIActionImpl {
// Switch to the new agent
const agentStore = getAgentStoreState();
agentStore.setActiveAgentId(result.agentId);
+ return result.agentId;
};
- duplicateAgentGroup = async (groupId: string, newTitle?: string): Promise<void> => {
+ duplicateAgentGroup = async (groupId: string, newTitle?: string): Promise<string | undefined> => {
const loadingToast = toast.loading(t('duplicateSession.loading', { ns: 'chat' }));
const result = await chatGroupService.duplicateGroup(groupId, newTitle);
@@ -66,6 +67,7 @@ export class SidebarUIActionImpl {
// Switch to the new group (using supervisor agent id)
const agentStore = getAgentStoreState();
agentStore.setActiveAgentId(result.supervisorAgentId);
+ return result.groupId;
};
// Pinning is part of the SHARED sidebar arrangement in workspace mode — it