Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

feat: support workspace lobehub (#13977)

Rdmclin2e8e4b2e82259
diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbml
index c07df45c5a6..bff5481879a 100644
--- a/docs/development/database-schema.dbml
+++ b/docs/development/database-schema.dbml
@@ -128,6 +128,7 @@ table agent_cron_jobs {
agent_id [name: 'agent_cron_jobs_agent_id_idx']
group_id [name: 'agent_cron_jobs_group_id_idx']
user_id [name: 'agent_cron_jobs_user_id_idx']
+ workspace_id [name: 'agent_cron_jobs_workspace_id_idx']
enabled [name: 'agent_cron_jobs_enabled_idx']
remaining_executions [name: 'agent_cron_jobs_remaining_executions_idx']
last_executed_at [name: 'agent_cron_jobs_last_executed_at_idx']
@@ -379,6 +380,7 @@ table agent_operations {
indexes {
user_id [name: 'agent_operations_user_id_idx']
+ workspace_id [name: 'agent_operations_workspace_id_idx']
agent_id [name: 'agent_operations_agent_id_idx']
topic_id [name: 'agent_operations_topic_id_idx']
thread_id [name: 'agent_operations_thread_id_idx']
@@ -461,7 +463,8 @@ table ai_models {
updated_at "timestamp with time zone" [not null, default: `now()`]
indexes {
- (id, provider_id, user_id) [pk]
+ (id, provider_id, user_id) [name: 'ai_models_id_provider_id_user_id_unique', unique]
+ (id, provider_id, user_id, workspace_id) [name: 'ai_models_id_provider_id_user_id_workspace_id_unique', unique]
user_id [name: 'ai_models_user_id_idx']
workspace_id [name: 'ai_models_workspace_id_idx']
}
@@ -488,7 +491,8 @@ table ai_providers {
updated_at "timestamp with time zone" [not null, default: `now()`]
indexes {
- (id, user_id) [pk]
+ (id, user_id) [name: 'ai_providers_id_user_id_unique', unique]
+ (id, user_id, workspace_id) [name: 'ai_providers_id_user_id_workspace_id_unique', unique]
user_id [name: 'ai_providers_user_id_idx']
workspace_id [name: 'ai_providers_workspace_id_idx']
}
@@ -778,6 +782,7 @@ table document_histories {
indexes {
document_id [name: 'document_histories_document_id_idx']
user_id [name: 'document_histories_user_id_idx']
+ workspace_id [name: 'document_histories_workspace_id_idx']
saved_at [name: 'document_histories_saved_at_idx']
workspace_id [name: 'document_histories_workspace_id_idx']
}
@@ -1027,6 +1032,7 @@ table llm_generation_tracing {
user_id [name: 'llm_generation_tracing_user_id_idx']
agent_id [name: 'llm_generation_tracing_agent_id_idx']
topic_id [name: 'llm_generation_tracing_topic_id_idx']
+ workspace_id [name: 'llm_generation_tracing_workspace_id_idx']
provider [name: 'llm_generation_tracing_provider_idx']
model [name: 'llm_generation_tracing_model_idx']
success [name: 'llm_generation_tracing_success_idx']
@@ -1793,6 +1799,7 @@ table file_chunks {
indexes {
(file_id, chunk_id) [pk]
user_id [name: 'file_chunks_user_id_idx']
+ workspace_id [name: 'file_chunks_workspace_id_idx']
file_id [name: 'file_chunks_file_id_idx']
chunk_id [name: 'file_chunks_chunk_id_idx']
workspace_id [name: 'file_chunks_workspace_id_idx']
@@ -1808,6 +1815,7 @@ table files_to_sessions {
indexes {
(file_id, session_id) [pk]
user_id [name: 'files_to_sessions_user_id_idx']
+ workspace_id [name: 'files_to_sessions_workspace_id_idx']
file_id [name: 'files_to_sessions_file_id_idx']
session_id [name: 'files_to_sessions_session_id_idx']
workspace_id [name: 'files_to_sessions_workspace_id_idx']
@@ -2169,8 +2177,8 @@ table topics {
provider [name: 'topics_provider_idx']
(user_id, completed_at) [name: 'topics_user_id_completed_at_idx']
sender_id [name: 'topics_sender_id_idx']
- () [name: 'topics_extract_status_gin_idx']
workspace_id [name: 'topics_workspace_id_idx']
+ () [name: 'topics_extract_status_gin_idx']
}
}
diff --git a/packages/business-server/src/lambda-routers/workspace.ts b/packages/business-server/src/lambda-routers/workspace.ts
index 844d43eb8d6..e77c78f626e 100644
--- a/packages/business-server/src/lambda-routers/workspace.ts
+++ b/packages/business-server/src/lambda-routers/workspace.ts
@@ -1,4 +1,17 @@
-import { router } from '@/libs/trpc/lambda';
+import { TRPCError } from '@trpc/server';
+
+import { authedProcedure, router } from '@/libs/trpc/lambda';
// Cloud overrides this at the same path with the real workspaceRouter backed by cloudDB.
-export const workspaceRouter = router({});
+// Only the procedures consumed by submodule (open-source) UI are declared here as
+// typed no-op stubs so the contract type-checks; cloud supplies the real implementations.
+export const workspaceRouter = router({
+ ensureMarketOrganization: authedProcedure.mutation(
+ async (): Promise<{ marketAccountId: number }> => {
+ throw new TRPCError({
+ code: 'NOT_IMPLEMENTED',
+ message: 'Workspace market organization is a cloud-only feature.',
+ });
+ },
+ ),
+});
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index 3bfaee9aac1..5d39b2b12e8 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -124,6 +124,12 @@ const linkOptions = {
// Only include provider in JWT for image operations
// For other operations (like knowledge base embedding), let server use its own config
const headers = await createHeaderWithAuth(provider ? { provider } : undefined);
+
+ // Let business layer contribute extra headers (e.g. workspace context in Cloud).
+ // Community ships an empty stub at this slot.
+ const { getBusinessTrpcHeaders } = await import('@/business/client/trpc-headers');
+ Object.assign(headers as Record<string, string>, await getBusinessTrpcHeaders());
+
log('Headers: %O', headers);
return headers;
},
diff --git a/packages/trpc/src/client/tools.ts b/packages/trpc/src/client/tools.ts
index 8c0121a3424..9e1700dac70 100644
--- a/packages/trpc/src/client/tools.ts
+++ b/packages/trpc/src/client/tools.ts
@@ -66,7 +66,13 @@ export const toolsClient = createTRPCClient<ToolsRouter>({
// dynamic import to avoid circular dependency
const { createHeaderWithAuth } = await import('@/services/_auth');
- return createHeaderWithAuth();
+ const headers = await createHeaderWithAuth();
+
+ // Let business layer contribute extra headers (e.g. workspace context in Cloud).
+ const { getBusinessTrpcHeaders } = await import('@/business/client/trpc-headers');
+ Object.assign(headers as Record<string, string>, await getBusinessTrpcHeaders());
+
+ return headers;
},
maxURLLength: 2083,
transformer: superjson,
diff --git a/src/business/client/BusinessKnowledgeBaseImportAction.tsx b/src/business/client/BusinessKnowledgeBaseImportAction.tsx
new file mode 100644
index 00000000000..8254aadcb5f
--- /dev/null
+++ b/src/business/client/BusinessKnowledgeBaseImportAction.tsx
@@ -0,0 +1,7 @@
+export interface BusinessKnowledgeBaseImportActionProps {
+ knowledgeBaseId: string;
+}
+
+const BusinessKnowledgeBaseImportAction = (_props: BusinessKnowledgeBaseImportActionProps) => null;
+
+export default BusinessKnowledgeBaseImportAction;
diff --git a/src/business/client/BusinessSettingPages/WorkspaceBillingBilling.tsx b/src/business/client/BusinessSettingPages/WorkspaceBillingBilling.tsx
new file mode 100644
index 00000000000..b420182a283
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceBillingBilling.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceBillingBilling() {
+ return null;
+}
diff --git a/src/business/client/BusinessSettingPages/WorkspaceBillingCredits.tsx b/src/business/client/BusinessSettingPages/WorkspaceBillingCredits.tsx
new file mode 100644
index 00000000000..dabc17ba94e
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceBillingCredits.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceBillingCredits() {
+ return null;
+}
diff --git a/src/business/client/BusinessSettingPages/WorkspaceBillingPlans.tsx b/src/business/client/BusinessSettingPages/WorkspaceBillingPlans.tsx
new file mode 100644
index 00000000000..b98003df111
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceBillingPlans.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceBillingPlans() {
+ return null;
+}
diff --git a/src/business/client/BusinessSettingPages/WorkspaceBillingUsage.tsx b/src/business/client/BusinessSettingPages/WorkspaceBillingUsage.tsx
new file mode 100644
index 00000000000..5079c086f0b
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceBillingUsage.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceBillingUsage() {
+ return null;
+}
diff --git a/src/business/client/BusinessSettingPages/WorkspaceGeneral.tsx b/src/business/client/BusinessSettingPages/WorkspaceGeneral.tsx
new file mode 100644
index 00000000000..35370a8a9bc
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceGeneral.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceGeneral() {
+ return null;
+}
diff --git a/src/business/client/BusinessSettingPages/WorkspaceMembers.tsx b/src/business/client/BusinessSettingPages/WorkspaceMembers.tsx
new file mode 100644
index 00000000000..fbb41d5e034
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceMembers.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceMembers() {
+ return null;
+}
diff --git a/src/business/client/WorkspaceContextSlot.tsx b/src/business/client/WorkspaceContextSlot.tsx
new file mode 100644
index 00000000000..7618238b51d
--- /dev/null
+++ b/src/business/client/WorkspaceContextSlot.tsx
@@ -0,0 +1,5 @@
+import { type PropsWithChildren } from 'react';
+
+export default function WorkspaceContextSlot({ children }: PropsWithChildren) {
+ return <>{children}</>;
+}
diff --git a/src/business/client/features/User/UserPanelWorkspaceSection.tsx b/src/business/client/features/User/UserPanelWorkspaceSection.tsx
new file mode 100644
index 00000000000..2886da6367e
--- /dev/null
+++ b/src/business/client/features/User/UserPanelWorkspaceSection.tsx
@@ -0,0 +1,7 @@
+interface UserPanelWorkspaceSectionProps {
+ onSwitch?: () => void;
+}
+
+export default function UserPanelWorkspaceSection(_props: UserPanelWorkspaceSectionProps) {
+ return null;
+}
diff --git a/src/business/client/hooks/useActiveIdentity.ts b/src/business/client/hooks/useActiveIdentity.ts
new file mode 100644
index 00000000000..0481f0c9b9f
--- /dev/null
+++ b/src/business/client/hooks/useActiveIdentity.ts
@@ -0,0 +1,13 @@
+/**
+ * Active identity shown in the user button / panel header. In the open-source
+ * build there's only one identity (the signed-in user), so this stub returns
+ * `null` everywhere — callers fall back to user data. Cloud overrides this
+ * hook to return the active workspace's avatar / name when a team workspace
+ * is selected, so the header reflects the current context.
+ */
+export interface ActiveIdentity {
+ avatar?: string | null;
+ name?: string | null;
+}
+
+export const useActiveIdentity = (): ActiveIdentity | null => null;
diff --git a/src/business/client/hooks/useActiveWorkspace.ts b/src/business/client/hooks/useActiveWorkspace.ts
new file mode 100644
index 00000000000..d1486c24373
--- /dev/null
+++ b/src/business/client/hooks/useActiveWorkspace.ts
@@ -0,0 +1,5 @@
+import type { WorkspaceItem } from '@lobechat/database/schemas';
+
+export type WorkspaceListItem = WorkspaceItem & { plan?: 'hobby' | 'pro'; role?: string };
+
+export const useActiveWorkspace = (): WorkspaceListItem | null => null;
diff --git a/src/business/client/hooks/useActiveWorkspaceId.ts b/src/business/client/hooks/useActiveWorkspaceId.ts
new file mode 100644
index 00000000000..bb65ffacb11
--- /dev/null
+++ b/src/business/client/hooks/useActiveWorkspaceId.ts
@@ -0,0 +1,3 @@
+export const getActiveWorkspaceId = (): string | null => null;
+
+export const useActiveWorkspaceId = (): string | null => null;
diff --git a/src/business/client/hooks/useActiveWorkspaceSlug.ts b/src/business/client/hooks/useActiveWorkspaceSlug.ts
new file mode 100644
index 00000000000..383deee0ee8
--- /dev/null
+++ b/src/business/client/hooks/useActiveWorkspaceSlug.ts
@@ -0,0 +1,3 @@
+export const getActiveWorkspaceSlug = (): string | null => null;
+
+export const useActiveWorkspaceSlug = (): string | null => null;
diff --git a/src/business/client/hooks/useAgentGroupTransferMenuItem.ts b/src/business/client/hooks/useAgentGroupTransferMenuItem.ts
new file mode 100644
index 00000000000..338e52f7ff4
--- /dev/null
+++ b/src/business/client/hooks/useAgentGroupTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import type { ItemType } from 'antd/es/menu/interface';
+
+export const useAgentGroupTransferMenuItem = (_groupId?: string): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useAgentTransferMenuItem.ts b/src/business/client/hooks/useAgentTransferMenuItem.ts
new file mode 100644
index 00000000000..c54c8c52aa1
--- /dev/null
+++ b/src/business/client/hooks/useAgentTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useAgentTransferMenuItem = (_agentId?: string): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useAuthorInfo.ts b/src/business/client/hooks/useAuthorInfo.ts
new file mode 100644
index 00000000000..a99bcf8f6c2
--- /dev/null
+++ b/src/business/client/hooks/useAuthorInfo.ts
@@ -0,0 +1,6 @@
+export interface AuthorInfo {
+ avatar?: string | null;
+ fullName?: string | null;
+}
+
+export const useAuthorInfo = (_userId?: string): AuthorInfo | undefined => undefined;
diff --git a/src/business/client/hooks/useBusinessAgentImportMenuItem.ts b/src/business/client/hooks/useBusinessAgentImportMenuItem.ts
new file mode 100644
index 00000000000..50d62316d17
--- /dev/null
+++ b/src/business/client/hooks/useBusinessAgentImportMenuItem.ts
@@ -0,0 +1,3 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useBusinessAgentImportMenuItem = (_agentId?: string): ItemType | null => null;
diff --git a/src/business/client/hooks/useCommunityWorkspaceMembers.ts b/src/business/client/hooks/useCommunityWorkspaceMembers.ts
new file mode 100644
index 00000000000..e2d2c1d13f1
--- /dev/null
+++ b/src/business/client/hooks/useCommunityWorkspaceMembers.ts
@@ -0,0 +1,25 @@
+'use client';
+
+export interface CommunityWorkspaceMember {
+ accountId: number;
+ avatarUrl: string | null;
+ createdAt: string;
+ displayName: string | null;
+ namespace: string | null;
+ role: 'admin' | 'member';
+ userName: string | null;
+}
+
+export interface CommunityWorkspaceMembersState {
+ canSync: boolean;
+ isLoading: boolean;
+ members: CommunityWorkspaceMember[];
+ refresh: () => Promise<void>;
+}
+
+export const useCommunityWorkspaceMembers = (): CommunityWorkspaceMembersState => ({
+ canSync: false,
+ isLoading: false,
+ members: [],
+ refresh: async () => {},
+});
diff --git a/src/business/client/hooks/useCommunityWorkspaceProfile.ts b/src/business/client/hooks/useCommunityWorkspaceProfile.ts
new file mode 100644
index 00000000000..d24db9d2785
--- /dev/null
+++ b/src/business/client/hooks/useCommunityWorkspaceProfile.ts
@@ -0,0 +1,36 @@
+'use client';
+
+export interface CommunityWorkspaceMarketOrganizationProfile {
+ accountId: number;
+ avatarUrl: string | null;
+ bannerUrl: string | null;
+ description: string | null;
+ displayName: string | null;
+ namespace: string;
+ websiteUrl: string | null;
+}
+
+export interface CommunityWorkspaceProfileState {
+ avatarUrl?: string | null;
+ bannerUrl?: string | null;
+ canEdit: boolean;
+ description?: string | null;
+ displayName?: string | null;
+ isLoading: boolean;
+ isWorkspaceScope: boolean;
+ profile: CommunityWorkspaceMarketOrganizationProfile | null;
+ refresh: () => Promise<void>;
+ username?: string;
+}
+
+export const useCommunityWorkspaceProfile = (): CommunityWorkspaceProfileState => ({
+ avatarUrl: null,
+ bannerUrl: null,
+ canEdit: false,
+ description: null,
+ displayName: null,
+ isLoading: false,
+ isWorkspaceScope: false,
+ profile: null,
+ refresh: async () => {},
+});
diff --git a/src/business/client/hooks/useDocumentTransferMenuItem.ts b/src/business/client/hooks/useDocumentTransferMenuItem.ts
new file mode 100644
index 00000000000..642cf61425d
--- /dev/null
+++ b/src/business/client/hooks/useDocumentTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useDocumentTransferMenuItem = (_documentId?: string): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useFetchWorkspaceMembers.ts b/src/business/client/hooks/useFetchWorkspaceMembers.ts
new file mode 100644
index 00000000000..231e2f535a7
--- /dev/null
+++ b/src/business/client/hooks/useFetchWorkspaceMembers.ts
@@ -0,0 +1,7 @@
+export interface FetchWorkspaceMembersOptions {
+ includeDeleted?: boolean;
+}
+
+export const useFetchWorkspaceMembers = (_options: FetchWorkspaceMembersOptions = {}) => ({
+ data: [],
+});
diff --git a/src/business/client/hooks/useFileBatchTransferActions.ts b/src/business/client/hooks/useFileBatchTransferActions.ts
new file mode 100644
index 00000000000..912c40dd3ac
--- /dev/null
+++ b/src/business/client/hooks/useFileBatchTransferActions.ts
@@ -0,0 +1,12 @@
+import type { LucideIcon } from 'lucide-react';
+
+export interface FileBatchTransferAction {
+ icon: LucideIcon;
+ key: string;
+ label: string;
+ onClick: () => void;
+}
+
+export const useFileBatchTransferActions = (
+ _selectCount: number,
+): FileBatchTransferAction[] | null => null;
diff --git a/src/business/client/hooks/useFileTransferMenuItem.ts b/src/business/client/hooks/useFileTransferMenuItem.ts
new file mode 100644
index 00000000000..5e50e265d08
--- /dev/null
+++ b/src/business/client/hooks/useFileTransferMenuItem.ts
@@ -0,0 +1,6 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useFileTransferMenuItem = (
+ _id?: string,
+ _entityType?: 'document' | 'file' | 'folder',
+): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useHasActiveWorkspace.ts b/src/business/client/hooks/useHasActiveWorkspace.ts
new file mode 100644
index 00000000000..f375420bf37
--- /dev/null
+++ b/src/business/client/hooks/useHasActiveWorkspace.ts
@@ -0,0 +1 @@
+export const useHasActiveWorkspace = (): boolean => false;
diff --git a/src/business/client/hooks/useHasWorkspace.ts b/src/business/client/hooks/useHasWorkspace.ts
new file mode 100644
index 00000000000..1c0de71e818
--- /dev/null
+++ b/src/business/client/hooks/useHasWorkspace.ts
@@ -0,0 +1 @@
+export const useHasWorkspace = (): boolean => false;
diff --git a/src/business/client/hooks/useIsWorkspaceLoading.ts b/src/business/client/hooks/useIsWorkspaceLoading.ts
new file mode 100644
index 00000000000..f1ecc8bd140
--- /dev/null
+++ b/src/business/client/hooks/useIsWorkspaceLoading.ts
@@ -0,0 +1 @@
+export const useIsWorkspaceLoading = (): boolean => false;
diff --git a/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts b/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts
new file mode 100644
index 00000000000..a28bb3fe955
--- /dev/null
+++ b/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useKnowledgeBaseTransferMenuItem = (_id?: string): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useShowWorkspaceApiKey.ts b/src/business/client/hooks/useShowWorkspaceApiKey.ts
new file mode 100644
index 00000000000..12e11ca5556
--- /dev/null
+++ b/src/business/client/hooks/useShowWorkspaceApiKey.ts
@@ -0,0 +1 @@
+export const useShowWorkspaceApiKey = (): boolean => true;
diff --git a/src/business/client/hooks/useSwitchWorkspace.ts b/src/business/client/hooks/useSwitchWorkspace.ts
new file mode 100644
index 00000000000..2389fce7b03
--- /dev/null
+++ b/src/business/client/hooks/useSwitchWorkspace.ts
@@ -0,0 +1,11 @@
+export interface SwitchWorkspaceActions {
+ switchToPersonal: () => Promise<void>;
+ switchWorkspace: (id: string) => Promise<void>;
+}
+
+const noop = async (): Promise<void> => {};
+
+export const useSwitchWorkspace = (): SwitchWorkspaceActions => ({
+ switchToPersonal: noop,
+ switchWorkspace: noop,
+});
diff --git a/src/business/client/hooks/useTaskTransferMenuItem.ts b/src/business/client/hooks/useTaskTransferMenuItem.ts
new file mode 100644
index 00000000000..277d424247b
--- /dev/null
+++ b/src/business/client/hooks/useTaskTransferMenuItem.ts
@@ -0,0 +1,3 @@
+import { type ItemType } from 'antd/es/menu/interface';
+
+export const useTaskTransferMenuItem = (_taskId?: string): ItemType[] | null => null;
diff --git a/src/business/client/hooks/useTransferAgentsFormItem.ts b/src/business/client/hooks/useTransferAgentsFormItem.ts
new file mode 100644
index 00000000000..8838e616f0f
--- /dev/null
+++ b/src/business/client/hooks/useTransferAgentsFormItem.ts
@@ -0,0 +1,3 @@
+import type { FormGroupItemType } from '@lobehub/ui';
+
+export const useTransferAgentsFormItem = (): FormGroupItemType['children'] | null => null;
diff --git a/src/business/client/hooks/useWorkspaceMembers.ts b/src/business/client/hooks/useWorkspaceMembers.ts
new file mode 100644
index 00000000000..1b557dea0f6
--- /dev/null
+++ b/src/business/client/hooks/useWorkspaceMembers.ts
@@ -0,0 +1,3 @@
+import type { WorkspaceMemberItem } from '@lobechat/database/schemas';
+
+export const useWorkspaceMembers = (): WorkspaceMemberItem[] => [];
diff --git a/src/business/client/hooks/useWorkspaces.ts b/src/business/client/hooks/useWorkspaces.ts
new file mode 100644
index 00000000000..006ef92e018
--- /dev/null
+++ b/src/business/client/hooks/useWorkspaces.ts
@@ -0,0 +1,3 @@
+import type { WorkspaceListItem } from './useActiveWorkspace';
+
+export const useWorkspaces = (): WorkspaceListItem[] => [];
diff --git a/src/business/client/services/communityWorkspaceProfile.ts b/src/business/client/services/communityWorkspaceProfile.ts
new file mode 100644
index 00000000000..d756a6f62ec
--- /dev/null
+++ b/src/business/client/services/communityWorkspaceProfile.ts
@@ -0,0 +1,29 @@
+export interface UpdateCommunityWorkspaceProfileInput {
+ avatarUrl?: string | null;
+ bannerUrl?: string | null;
+ description?: string;
+ displayName?: string;
+ namespace?: string;
+ websiteUrl?: string;
+}
+
+export interface SetupCommunityWorkspaceProfileInput extends UpdateCommunityWorkspaceProfileInput {
+ displayName: string;
+ namespace: string;
+}
+
+export const setupCommunityWorkspaceProfile = async (
+ _input: SetupCommunityWorkspaceProfileInput,
+): Promise<void> => {};
+
+export const updateCommunityWorkspaceProfile = async (
+ _input: UpdateCommunityWorkspaceProfileInput,
+): Promise<void> => {};
+
+export const syncCommunityWorkspaceMembers = async (): Promise<void> => {};
+
+export const checkCommunityWorkspaceNamespaceAvailable = async (
+ _namespace: string,
+): Promise<boolean> => true;
+
+export const isCommunityWorkspaceNamespaceTakenError = (_error: unknown): boolean => false;
diff --git a/src/business/client/trpc-headers.ts b/src/business/client/trpc-headers.ts
new file mode 100644
index 00000000000..d0980ed4d8e
--- /dev/null
+++ b/src/business/client/trpc-headers.ts
@@ -0,0 +1 @@
+export const getBusinessTrpcHeaders = async (): Promise<Record<string, string>> => ({});
diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.ts
index 09fb6991d01..fd2f1368fae 100644
--- a/src/components/DragUploadZone/useUploadFiles.ts
+++ b/src/components/DragUploadZone/useUploadFiles.ts
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
+import { usePermission } from '@/hooks/usePermission';
import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useFileStore } from '@/store/file';
@@ -20,9 +21,12 @@ export const useUploadFiles = (options: UseUploadFilesOptions = {}) => {
const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
const uploadFiles = useFileStore((s) => s.uploadChatFiles);
+ const { allowed: canUpload } = usePermission('create_content');
const handleUploadFiles = useCallback(
async (files: File[]) => {
+ if (!canUpload) return;
+
// Filter out visual files if the model cannot receive them directly or via fallback.
const filteredFiles = files.filter((file) => {
if (file.type.startsWith('image')) return canUploadImage;
@@ -34,7 +38,7 @@ export const useUploadFiles = (options: UseUploadFilesOptions = {}) => {
uploadFiles(filteredFiles);
}
},
- [canUploadImage, canUploadVideo, uploadFiles],
+ [canUpload, canUploadImage, canUploadVideo, uploadFiles],
);
return { canUploadImage, canUploadVideo, handleUploadFiles };
diff --git a/src/components/InstantSwitch/index.tsx b/src/components/InstantSwitch/index.tsx
index 2cd4c2c853b..1489b1b0d2a 100644
--- a/src/components/InstantSwitch/index.tsx
+++ b/src/components/InstantSwitch/index.tsx
@@ -3,16 +3,18 @@ import { Switch } from 'antd';
import { memo, useState } from 'react';
interface InstantSwitchProps {
+ disabled?: boolean;
enabled: boolean;
onChange: (enabled: boolean) => Promise<void>;
size?: SwitchProps['size'];
}
-const InstantSwitch = memo<InstantSwitchProps>(({ enabled, onChange, size }) => {
+const InstantSwitch = memo<InstantSwitchProps>(({ disabled, enabled, onChange, size }) => {
const [value, setValue] = useState(enabled);
const [loading, setLoading] = useState(false);
return (
<Switch
+ disabled={disabled}
loading={loading}
size={size}
value={value}
diff --git a/src/components/InvalidAPIKey/Bedrock.tsx b/src/components/InvalidAPIKey/Bedrock.tsx
index 64452a5c212..4f26a335338 100644
--- a/src/components/InvalidAPIKey/Bedrock.tsx
+++ b/src/components/InvalidAPIKey/Bedrock.tsx
@@ -7,10 +7,12 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FormAction } from '@/features/Conversation/Error/style';
+import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
const BedrockForm = memo<{ description: string }>(({ description }) => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const [showRegion, setShow] = useState(false);
const [showSessionToken, setShowSessionToken] = useState(false);
@@ -26,38 +28,50 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
>
<InputPassword
autoComplete={'new-password'}
+ disabled={!canManageProvider}
placeholder={'Aws Access Key Id'}
value={accessKeyId}
variant={'filled'}
onChange={(e) => {
+ if (!canManageProvider) return;
+
setConfig(ModelProvider.Bedrock, { keyVaults: { accessKeyId: e.target.value } });
}}
/>
<InputPassword
autoComplete={'new-password'}
+ disabled={!canManageProvider}
placeholder={'Aws Secret Access Key'}
value={secretAccessKey}
variant={'filled'}
onChange={(e) => {
+ if (!canManageProvider) return;
+
setConfig(ModelProvider.Bedrock, { keyVaults: { secretAccessKey: e.target.value } });
}}
/>
{showSessionToken ? (
<InputPassword
autoComplete={'new-password'}
+ disabled={!canManageProvider}
placeholder={'Aws Session Token'}
value={sessionToken}
variant={'filled'}
onChange={(e) => {
+ if (!canManageProvider) return;
+
setConfig(ModelProvider.Bedrock, { keyVaults: { sessionToken: e.target.value } });
}}
/>
) : (
<Button
block
+ disabled={!canManageProvider}
icon={ShieldPlus}
type={'text'}
onClick={() => {
+ if (!canManageProvider) return;
+
setShowSessionToken(true);
}}
>
@@ -66,6 +80,7 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
)}
{showRegion ? (
<Select
+ disabled={!canManageProvider}
placeholder={'https://api.openai.com/v1'}
style={{ width: '100%' }}
value={region}
@@ -74,15 +89,20 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
value: i,
}))}
onChange={(region) => {
+ if (!canManageProvider) return;
+
setConfig('bedrock', { keyVaults: { region } });
}}
/>
) : (
<Button
block
+ disabled={!canManageProvider}
icon={<Icon icon={Network} />}
type={'text'}
onClick={() => {
+ if (!canManageProvider) return;
+
setShow(true);
}}
>
diff --git a/src/components/InvalidAPIKey/ComfyUIForm.tsx b/src/components/InvalidAPIKey/ComfyUIForm.tsx
index 486f2716ba6..85f8f3add3e 100644
--- a/src/components/InvalidAPIKey/ComfyUIForm.tsx
+++ b/src/components/InvalidAPIKey/ComfyUIForm.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import { FormInput, FormPassword } from '@/components/FormInput';
import KeyValueEditor from '@/components/KeyValueEditor';
import { FormAction } from '@/features/Conversation/Error/style';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import { type ComfyUIKeyVault } from '@/types/user/settings';
@@ -43,6 +44,7 @@ const styles = createStaticStyles(({ css }) => ({
const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
const { t } = useTranslation('error');
const { t: s } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
// Use aiInfraStore for updating config (same as settings page)
const updateAiProviderConfig = useAiInfraStore((s) => s.updateAiProviderConfig);
@@ -103,6 +105,8 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
];
const handleValueChange = async (field: string, value: any) => {
+ if (!canManageProvider) return;
+
const newValues = {
...formValues,
[field]: value,
@@ -148,6 +152,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<Flexbox gap={4}>
<div style={{ fontSize: 14, fontWeight: 500 }}>{s('comfyui.baseURL.title')}</div>
<FormInput
+ disabled={!canManageProvider}
placeholder={s('comfyui.baseURL.placeholder')}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={formValues.baseURL}
@@ -156,6 +161,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
</Flexbox>
) : (
<Button
+ disabled={!canManageProvider}
icon={<Icon icon={Network} />}
type={'text'}
onClick={() => setShowBaseURL(true)}
@@ -169,6 +175,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<div style={{ fontSize: 14, fontWeight: 500 }}>{s('comfyui.authType.title')}</div>
<Select
allowClear={false}
+ disabled={!canManageProvider}
options={authTypeOptions}
placeholder={s('comfyui.authType.placeholder')}
value={formValues.authType}
@@ -183,6 +190,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<div style={{ fontSize: 14, fontWeight: 500 }}>{s('comfyui.username.title')}</div>
<FormInput
autoComplete="username"
+ disabled={!canManageProvider}
placeholder={s('comfyui.username.placeholder')}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={formValues.username}
@@ -193,6 +201,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<div style={{ fontSize: 14, fontWeight: 500 }}>{s('comfyui.password.title')}</div>
<FormPassword
autoComplete="new-password"
+ disabled={!canManageProvider}
placeholder={s('comfyui.password.placeholder')}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={formValues.password}
@@ -208,6 +217,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<div style={{ fontSize: 14, fontWeight: 500 }}>{s('comfyui.apiKey.title')}</div>
<FormPassword
autoComplete="new-password"
+ disabled={!canManageProvider}
placeholder={s('comfyui.apiKey.placeholder')}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={formValues.apiKey}
@@ -228,6 +238,7 @@ const ComfyUIForm = memo<ComfyUIFormProps>(({ description }) => {
<KeyValueEditor
addButtonText={s('comfyui.customHeaders.addButton')}
deleteTooltip={s('comfyui.customHeaders.deleteTooltip')}
+ disabled={!canManageProvider}
duplicateKeyErrorText={s('comfyui.customHeaders.duplicateKeyError')}
keyPlaceholder={s('comfyui.customHeaders.keyPlaceholder')}
value={formValues.customHeaders}
diff --git a/src/components/InvalidAPIKey/ProviderApiKeyForm.tsx b/src/components/InvalidAPIKey/ProviderApiKeyForm.tsx
index 95145443aeb..c68a30715f6 100644
--- a/src/components/InvalidAPIKey/ProviderApiKeyForm.tsx
+++ b/src/components/InvalidAPIKey/ProviderApiKeyForm.tsx
@@ -27,7 +27,7 @@ const ProviderApiKeyForm = memo<ProviderApiKeyFormProps>(
const { t: errorT } = useTranslation('error');
const [showProxy, setShow] = useState(false);
- const { apiKey, baseURL, setConfig } = useApiKey(provider);
+ const { apiKey, baseURL, canManageProvider, setConfig } = useApiKey(provider);
const { showOpenAIProxyUrl } = useServerConfigStore(featureFlagsSelectors);
const providerName = useProviderName(provider);
const { loading } = use(LoadingContext);
@@ -40,6 +40,7 @@ const ProviderApiKeyForm = memo<ProviderApiKeyFormProps>(
>
<FormPassword
autoComplete={'new-password'}
+ disabled={!canManageProvider}
placeholder={apiKeyPlaceholder || 'sk-***********************'}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={apiKey}
@@ -52,6 +53,7 @@ const ProviderApiKeyForm = memo<ProviderApiKeyFormProps>(
showOpenAIProxyUrl &&
(showProxy ? (
<FormInput
+ disabled={!canManageProvider}
placeholder={'https://api.openai.com/v1'}
suffix={<div>{loading && <Icon spin icon={Loader2Icon} />}</div>}
value={baseURL}
@@ -61,6 +63,7 @@ const ProviderApiKeyForm = memo<ProviderApiKeyFormProps>(
/>
) : (
<Button
+ disabled={!canManageProvider}
icon={<Icon icon={Network} />}
type={'text'}
onClick={() => {
diff --git a/src/components/InvalidAPIKey/useApiKey.ts b/src/components/InvalidAPIKey/useApiKey.ts
index cc5b393a36b..9b07a99d98a 100644
--- a/src/components/InvalidAPIKey/useApiKey.ts
+++ b/src/components/InvalidAPIKey/useApiKey.ts
@@ -1,19 +1,24 @@
import isEqual from 'fast-deep-equal';
import { useContext } from 'react';
+import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { LoadingContext } from './LoadingContext';
export const useApiKey = (provider: string) => {
const { setLoading } = useContext(LoadingContext);
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const updateAiProviderConfig = useAiInfraStore((s) => s.updateAiProviderConfig);
const data = useAiInfraStore(aiProviderSelectors.providerConfigById(provider), isEqual);
return {
apiKey: data?.keyVaults.apiKey,
baseURL: data?.keyVaults?.baseURL,
+ canManageProvider,
setConfig: async (id: string, params: Record<string, string>) => {
+ if (!canManageProvider) return;
+
const next = { ...data?.keyVaults, ...params };
if (isEqual(data?.keyVaults, next)) return;
diff --git a/src/components/KeyValueEditor/index.tsx b/src/components/KeyValueEditor/index.tsx
index 8dd7ad91a34..04b71105951 100644
--- a/src/components/KeyValueEditor/index.tsx
+++ b/src/components/KeyValueEditor/index.tsx
@@ -41,6 +41,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export interface KeyValueEditorProps {
addButtonText?: string;
deleteTooltip?: string;
+ disabled?: boolean;
duplicateKeyErrorText?: string;
keyPlaceholder?: string;
onChange?: (value: Record<string, string>) => void;
@@ -58,6 +59,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
addButtonText,
duplicateKeyErrorText,
deleteTooltip,
+ disabled,
style,
}) => {
const { t } = useTranslation('components');
@@ -73,6 +75,8 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
}, [value]);
const triggerChange = (newItems: KeyValueItem[]) => {
+ if (disabled) return;
+
const keysCount: Record<string, number> = {};
newItems.forEach((item) => {
const trimmedKey = item.key.trim();
@@ -89,21 +93,29 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
};
const handleAdd = () => {
+ if (disabled) return;
+
const newItems = [...items, { id: uuidv4(), key: '', value: '' }];
triggerChange(newItems);
};
const handleRemove = (id: string) => {
+ if (disabled) return;
+
const newItems = items.filter((item) => item.id !== id);
triggerChange(newItems);
};
const handleKeyChange = (id: string, newKey: string) => {
+ if (disabled) return;
+
const newItems = items.map((item) => (item.id === id ? { ...item, key: newKey } : item));
triggerChange(newItems);
};
const handleValueChange = (id: string, newValue: string) => {
+ if (disabled) return;
+
const newItems = items.map((item) => (item.id === id ? { ...item, value: newValue } : item));
triggerChange(newItems);
};
@@ -147,6 +159,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
<Flexbox flex={1} style={{ position: 'relative' }}>
<FormInput
className={styles.input}
+ disabled={disabled}
placeholder={keyPlaceholder || t('KeyValueEditor.keyPlaceholder')}
status={isDuplicate ? 'error' : undefined}
value={item.key}
@@ -169,6 +182,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
<Flexbox flex={2}>
<FormInput
className={styles.input}
+ disabled={disabled}
placeholder={valuePlaceholder || t('KeyValueEditor.valuePlaceholder')}
value={item.value}
variant={'filled'}
@@ -176,6 +190,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
/>
</Flexbox>
<ActionIcon
+ disabled={disabled}
icon={LucideTrash}
size={'small'}
style={{ marginTop: 4 }}
@@ -187,6 +202,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(
})}
<Button
block
+ disabled={disabled}
icon={<Icon icon={LucidePlus} />}
size={'small'}
style={{ marginTop: items.length > 0 ? 16 : 8 }}
diff --git a/src/features/AgentBuilder/AgentBuilderConversation.tsx b/src/features/AgentBuilder/AgentBuilderConversation.tsx
index 1f1d539b4ee..ba4b785307f 100644
--- a/src/features/AgentBuilder/AgentBuilderConversation.tsx
+++ b/src/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -4,6 +4,7 @@ import { memo } from 'react';
import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
import { type ActionKeys } from '@/features/ChatInput';
import { ChatInput, ChatList } from '@/features/Conversation';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -25,13 +26,18 @@ const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
const { handleUploadFiles } = useUploadFiles({ model, provider });
+ const { allowed: canCreate } = usePermission('create_content');
return (
- <DragUploadZone style={{ flex: 1, height: '100%' }} onUploadFiles={handleUploadFiles}>
+ <DragUploadZone
+ disabled={!canCreate}
+ style={{ flex: 1, height: '100%' }}
+ onUploadFiles={handleUploadFiles}
+ >
<Flexbox flex={1} height={'100%'}>
- <TopicSelector agentId={agentId} />
+ <TopicSelector agentId={agentId} disabled={!canCreate} />
<Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <ChatList welcome={<AgentBuilderWelcome />} />
+ <ChatList welcome={<AgentBuilderWelcome disabled={!canCreate} />} />
</Flexbox>
<ChatInput leftActions={actions} rightActions={rightActions} showControlBar={false} />
</Flexbox>
diff --git a/src/features/AgentBuilder/AgentBuilderWelcome.tsx b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
index fca861003fe..ecabc566740 100644
--- a/src/features/AgentBuilder/AgentBuilderWelcome.tsx
+++ b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
@@ -12,10 +12,11 @@ import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
interface AgentBuilderWelcomeProps {
+ disabled?: boolean;
mode?: SuggestMode;
}
-const AgentBuilderWelcome = memo<AgentBuilderWelcomeProps>(({ mode = 'agent' }) => {
+const AgentBuilderWelcome = memo<AgentBuilderWelcomeProps>(({ disabled, mode = 'agent' }) => {
const { t } = useTranslation('chat');
const agentId = useConversationStore(conversationSelectors.agentId);
const agent = useAgentStore(agentByIdSelectors.getAgentConfigById(agentId));
@@ -37,7 +38,7 @@ const AgentBuilderWelcome = memo<AgentBuilderWelcomeProps>(({ mode = 'agent' })
<Markdown fontSize={14} variant={'chat'}>
{t('agentBuilder.welcome')}
</Markdown>
- <SuggestQuestions count={3} mode={mode} />
+ <SuggestQuestions count={3} disabled={disabled} mode={mode} />
</Flexbox>
</>
);
diff --git a/src/features/AgentBuilder/TopicSelector.test.tsx b/src/features/AgentBuilder/TopicSelector.test.tsx
new file mode 100644
index 00000000000..56fcbced3ee
--- /dev/null
+++ b/src/features/AgentBuilder/TopicSelector.test.tsx
@@ -0,0 +1,84 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TopicSelector from './TopicSelector';
+
+const switchTopic = vi.fn();
+const useFetchTopics = vi.fn();
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ disabled, onClick, title }: any) => (
+ <button disabled={disabled} type="button" onClick={onClick}>
+ {title}
+ </button>
+ ),
+ DropdownMenu: ({ children }: any) => <div>{children}</div>,
+ Flexbox: ({ children }: any) => <div>{children}</div>,
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({
+ time: 'time',
+ title: 'title',
+ }),
+}));
+
+vi.mock('dayjs', () => {
+ const dayjs = () => ({
+ diff: () => 0,
+ format: () => '2026-05-24',
+ fromNow: () => 'now',
+ });
+ return { default: dayjs };
+});
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/const/layoutTokens', () => ({
+ DESKTOP_HEADER_ICON_SMALL_SIZE: 24,
+}));
+
+vi.mock('@/features/NavHeader', () => ({
+ default: ({ left, right }: any) => (
+ <div>
+ {left}
+ {right}
+ </div>
+ ),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: any) =>
+ selector({
+ activeTopicId: 'topic-1',
+ switchTopic,
+ topics: [{ id: 'topic-1', title: 'First topic', updatedAt: new Date() }],
+ useFetchTopics,
+ }),
+}));
+
+vi.mock('@/store/chat/slices/topic/selectors', () => ({
+ topicSelectors: {
+ getTopicsByAgentId: () => (s: any) => s.topics,
+ },
+}));
+
+describe('AgentBuilder TopicSelector', () => {
+ beforeEach(() => {
+ switchTopic.mockReset();
+ useFetchTopics.mockReset();
+ });
+
+ it('does not create a new topic when disabled', () => {
+ render(<TopicSelector disabled agentId="agent-builder" />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopic' }));
+
+ expect(switchTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentBuilder/TopicSelector.tsx b/src/features/AgentBuilder/TopicSelector.tsx
index 1fc8b2bbd69..9c87c3f6643 100644
--- a/src/features/AgentBuilder/TopicSelector.tsx
+++ b/src/features/AgentBuilder/TopicSelector.tsx
@@ -29,9 +29,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface TopicSelectorProps {
agentId: string;
+ disabled?: boolean;
}
-const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
+const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {
const { t } = useTranslation('topic');
// Fetch topics for the agent builder
@@ -70,6 +71,7 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
</Flexbox>
),
onCheckedChange: (checked) => {
+ if (disabled) return;
if (checked) {
switchTopic(topic.id);
}
@@ -90,18 +92,23 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
right={
<>
<ActionIcon
+ disabled={disabled}
icon={PlusIcon}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
title={t('actions.addNewTopic')}
- onClick={() => switchTopic()}
+ onClick={() => {
+ if (disabled) return;
+
+ switchTopic();
+ }}
/>
<DropdownMenu
items={items}
placement="bottomRight"
popupProps={{ style: { maxHeight: 400, minWidth: 280, overflowY: 'auto' } }}
- triggerProps={{ disabled: isEmpty }}
+ triggerProps={{ disabled: disabled || isEmpty }}
>
- <ActionIcon disabled={isEmpty} icon={Clock3Icon} />
+ <ActionIcon disabled={disabled || isEmpty} icon={Clock3Icon} />
</DropdownMenu>
</>
}
diff --git a/src/features/AgentHome/RecentTopics.tsx b/src/features/AgentHome/RecentTopics.tsx
index 268f8ce2adb..bc401a692da 100644
--- a/src/features/AgentHome/RecentTopics.tsx
+++ b/src/features/AgentHome/RecentTopics.tsx
@@ -5,10 +5,11 @@ import { cssVar } from 'antd-style';
import { BotMessageSquareIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
import useSWR from 'swr';
import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { topicService } from '@/services/topic';
import SectionHeader from './SectionHeader';
@@ -35,7 +36,7 @@ const AgentRecentTopics = memo(() => {
/>
<Flexbox horizontal gap={12} style={{ overflowX: 'auto', paddingBottom: 4 }}>
{topics.map((topic) => (
- <Link
+ <WorkspaceLink
key={topic.id}
style={{ color: 'inherit', flexShrink: 0, textDecoration: 'none' }}
to={SESSION_CHAT_TOPIC_URL(aid!, topic.id)}
@@ -60,7 +61,7 @@ const AgentRecentTopics = memo(() => {
</Text>
</Flexbox>
</Block>
- </Link>
+ </WorkspaceLink>
))}
</Flexbox>
</Flexbox>
diff --git a/src/features/AgentHome/SectionHeader.tsx b/src/features/AgentHome/SectionHeader.tsx
index 285f68495de..ea4a0c0be47 100644
--- a/src/features/AgentHome/SectionHeader.tsx
+++ b/src/features/AgentHome/SectionHeader.tsx
@@ -4,7 +4,8 @@ import { Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { type LucideIcon } from 'lucide-react';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
interface SectionHeaderProps {
actionLabel?: string;
@@ -21,11 +22,11 @@ const SectionHeader = memo<SectionHeaderProps>(({ icon, title, actionLabel, acti
<Text color={cssVar.colorTextSecondary}>{title}</Text>
</Flexbox>
{actionLabel && actionUrl && (
- <Link to={actionUrl} style={{ color: 'inherit', textDecoration: 'none' }}>
+ <WorkspaceLink style={{ color: 'inherit', textDecoration: 'none' }} to={actionUrl}>
<Text fontSize={12} type={'secondary'}>
{actionLabel}
</Text>
- </Link>
+ </WorkspaceLink>
)}
</Flexbox>
);
diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsx
index deb5a7a8ca9..f54a4144ffb 100644
--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx
+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx
@@ -8,10 +8,10 @@ import { createStaticStyles } from 'antd-style';
import { BookOpen, FileText, Settings } from 'lucide-react';
import { memo, type PropsWithChildren, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import useSWR from 'swr';
import ModelSelect from '@/features/ModelSelect';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { agentService } from '@/services/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -71,7 +71,7 @@ interface AgentProfilePopupProps extends PropsWithChildren {
const AgentProfilePopup = memo<AgentProfilePopupProps>(
({ agent, agentId, groupId, children, trigger = 'click' }) => {
const { t } = useTranslation('chat');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
diff --git a/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx b/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
index 4bfaa3016e4..16449fd4ba0 100644
--- a/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
+++ b/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
@@ -11,6 +11,7 @@ import { globalGeneralSelectors } from '@/store/global/selectors';
export interface AutoGenerateAvatarProps {
background?: string;
canAutoGenerate?: boolean;
+ disabled?: boolean;
loading?: boolean;
onChange?: (value: string) => void;
onGenerate?: () => void;
@@ -18,7 +19,7 @@ export interface AutoGenerateAvatarProps {
}
const AutoGenerateAvatar = memo<AutoGenerateAvatarProps>(
- ({ loading, background, value, onChange, onGenerate, canAutoGenerate }) => {
+ ({ loading, background, value, onChange, onGenerate, canAutoGenerate, disabled }) => {
const { t } = useTranslation('common');
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
@@ -45,11 +46,16 @@ const AutoGenerateAvatar = memo<AutoGenerateAvatarProps>(
value={value}
style={{
background: cssVar.colorFillTertiary,
+ opacity: disabled ? 0.5 : 1,
+ }}
+ onChange={(next) => {
+ if (disabled) return;
+
+ onChange?.(next);
}}
- onChange={onChange}
/>
<ActionIcon
- disabled={!canAutoGenerate}
+ disabled={disabled || !canAutoGenerate}
icon={Wand2}
loading={loading}
size="small"
diff --git a/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx b/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
index c6a255550e1..55497f8d46a 100644
--- a/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
+++ b/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
@@ -6,11 +6,19 @@ import { useTranslation } from 'react-i18next';
import { DEFAULT_BACKGROUND_COLOR } from '@/const/meta';
interface BackgroundSwatchesProps extends Omit<ColorSwatchesProps, 'colors'> {
+ disabled?: boolean;
onValuesChange?: ColorSwatchesProps['onChange'];
}
const BackgroundSwatches = memo<BackgroundSwatchesProps>(
- ({ defaultValue = DEFAULT_BACKGROUND_COLOR, value, onChange, onValuesChange, ...rest }) => {
+ ({
+ defaultValue = DEFAULT_BACKGROUND_COLOR,
+ value,
+ onChange,
+ onValuesChange,
+ disabled,
+ ...rest
+ }) => {
const { t } = useTranslation('color');
const colors = useMemo(
@@ -77,7 +85,15 @@ const BackgroundSwatches = memo<BackgroundSwatchesProps>(
colors={colors}
defaultValue={defaultValue}
value={value}
+ style={{
+ cursor: disabled ? 'not-allowed' : undefined,
+ opacity: disabled ? 0.5 : undefined,
+ pointerEvents: disabled ? 'none' : undefined,
+ ...rest.style,
+ }}
onChange={(v) => {
+ if (disabled) return;
+
onChange?.(v);
onValuesChange?.(v);
}}
diff --git a/src/features/AgentSetting/AgentMeta/index.tsx b/src/features/AgentSetting/AgentMeta/index.tsx
index 5340777e029..0d00b0df13f 100644
--- a/src/features/AgentSetting/AgentMeta/index.tsx
+++ b/src/features/AgentSetting/AgentMeta/index.tsx
@@ -22,12 +22,15 @@ const AgentMeta = memo(() => {
const { t } = useTranslation('setting');
const [form] = Form.useForm();
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
- const [hasSystemRole, updateMeta, autocompleteMeta, autocompleteAllMeta] = useStore((s) => [
- !!s.config.systemRole,
- s.setAgentMeta,
- s.autocompleteMeta,
- s.autocompleteAllMeta,
- ]);
+ const [hasSystemRole, disabled, updateMeta, autocompleteMeta, autocompleteAllMeta] = useStore(
+ (s) => [
+ !!s.config.systemRole,
+ s.disabled,
+ s.setAgentMeta,
+ s.autocompleteMeta,
+ s.autocompleteAllMeta,
+ ],
+ );
const [isInbox, loadingState] = useStore((s) => [s.id === INBOX_SESSION_ID, s.loadingState]);
const meta = useStore(selectors.currentMetaConfig, isEqual);
const [background, setBackground] = useState(meta.backgroundColor);
@@ -66,10 +69,13 @@ const AgentMeta = memo(() => {
return {
children: (
<AutoGenerate
- canAutoGenerate={hasSystemRole}
+ canAutoGenerate={hasSystemRole && !disabled}
+ disabled={disabled}
loading={loadingState?.[item.key]}
placeholder={item.placeholder}
onGenerate={() => {
+ if (disabled) return;
+
autocompleteMeta(item.key as keyof typeof meta);
}}
/>
@@ -85,9 +91,14 @@ const AgentMeta = memo(() => {
children: (
<AutoGenerateAvatar
background={background}
- canAutoGenerate={hasSystemRole}
+ canAutoGenerate={hasSystemRole && !disabled}
+ disabled={disabled}
loading={loadingState?.['avatar']}
- onGenerate={() => autocompleteMeta('avatar')}
+ onGenerate={() => {
+ if (disabled) return;
+
+ autocompleteMeta('avatar');
+ }}
/>
),
label: t('settingAgent.avatar.title'),
@@ -96,7 +107,9 @@ const AgentMeta = memo(() => {
name: 'avatar',
},
{
- children: <BackgroundSwatches onValuesChange={(c) => setBackground(c)} />,
+ children: (
+ <BackgroundSwatches disabled={disabled} onValuesChange={(c) => setBackground(c)} />
+ ),
label: t('settingAgent.backgroundColor.title'),
minWidth: undefined,
name: 'backgroundColor',
@@ -112,7 +125,7 @@ const AgentMeta = memo(() => {
}
>
<Button
- disabled={!hasSystemRole}
+ disabled={disabled || !hasSystemRole}
icon={Wand2}
iconPlacement={'end'}
loading={Object.values(loadingState as any).some((i) => !!i)}
@@ -122,6 +135,8 @@ const AgentMeta = memo(() => {
}}
onClick={(e: any) => {
e.stopPropagation();
+ if (disabled) return;
+
autocompleteAllMeta(true);
}}
>
@@ -134,14 +149,18 @@ const AgentMeta = memo(() => {
return (
<Form
- disabled={!isAgentEditable}
+ disabled={disabled || !isAgentEditable}
footer={<Form.SubmitFooter />}
form={form}
initialValues={meta}
items={[metaData]}
itemsType={'group'}
variant={'borderless'}
- onFinish={updateMeta}
+ onFinish={(values) => {
+ if (disabled) return;
+
+ updateMeta(values);
+ }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx b/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
index 122455f476a..f65bccf6ba5 100644
--- a/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
+++ b/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
@@ -28,22 +28,26 @@ const OpeningMessage = memo(() => {
const { t } = useTranslation('setting');
const openingMessage = useStore(selectors.openingMessage);
- const updateConfig = useStore((s) => s.setAgentConfig);
+ const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setAgentConfig]);
const setOpeningMessage = useCallback(
(message: string) => {
+ if (disabled) return;
+
updateConfig({ openingMessage: message });
},
- [updateConfig],
+ [disabled, updateConfig],
);
const [editing, setEditing] = useState(false);
const handleEdit = useCallback(() => {
+ if (disabled) return;
+
setEditing(true);
- }, []);
+ }, [disabled]);
- const editIconButton = !editing && openingMessage && (
- <Button size={'small'} onClick={handleEdit}>
+ const editIconButton = !editing && openingMessage && !disabled && (
+ <Button disabled={disabled} size={'small'} onClick={handleEdit}>
<PencilLine size={16} />
</Button>
);
@@ -52,11 +56,11 @@ const OpeningMessage = memo(() => {
<div className={styles.wrapper}>
<Flexbox direction={'horizontal'}>
<EditableMessage
- showEditWhenEmpty
editButtonSize={'small'}
editing={editing}
height={'auto'}
placeholder={t('settingOpening.openingMessage.placeholder')}
+ showEditWhenEmpty={!disabled}
value={openingMessage ?? ''}
variant={'borderless'}
classNames={{
@@ -67,7 +71,11 @@ const OpeningMessage = memo(() => {
confirm: t('ok', { ns: 'common' }),
}}
onChange={setOpeningMessage}
- onEditingChange={setEditing}
+ onEditingChange={(next) => {
+ if (disabled) return;
+
+ setEditing(next);
+ }}
/>
{editIconButton}
</Flexbox>
diff --git a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
index 04bbf2afdd2..7453273b69f 100644
--- a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
+++ b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
@@ -43,11 +43,15 @@ const OpeningQuestions = memo(() => {
const [questionInput, setQuestionInput] = useState('');
const openingQuestions = useStore(selectors.openingQuestions);
- const updateConfig = useStore((s) => s.setAgentConfig);
+ const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setAgentConfig]);
// Optimistic update to avoid jitter
const [questions, setQuestions] = useMergeState(openingQuestions, {
- onChange: (questions: string[]) => updateConfig({ openingQuestions: questions }),
+ onChange: (questions: string[]) => {
+ if (disabled) return;
+
+ updateConfig({ openingQuestions: questions });
+ },
value: openingQuestions,
});
@@ -59,28 +63,33 @@ const OpeningQuestions = memo(() => {
}, [questions]);
const addQuestion = useCallback(() => {
+ if (disabled) return;
if (!questionInput.trim()) return;
setQuestions([...openingQuestions, questionInput.trim()]);
setQuestionInput('');
- }, [openingQuestions, questionInput, setQuestions]);
+ }, [disabled, openingQuestions, questionInput, setQuestions]);
const removeQuestion = useCallback(
(content: string) => {
+ if (disabled) return;
+
const newQuestions = [...openingQuestions];
const index = newQuestions.indexOf(content);
newQuestions.splice(index, 1);
setQuestions(newQuestions);
},
- [openingQuestions, setQuestions],
+ [disabled, openingQuestions, setQuestions],
);
// Handle logic after drag-and-drop sorting
const handleSortEnd = useCallback(
(items: QuestionItem[]) => {
+ if (disabled) return;
+
setQuestions(items.map((item) => item.content));
},
- [setQuestions],
+ [disabled, setQuestions],
);
const isRepeat = openingQuestions.includes(questionInput.trim());
@@ -90,6 +99,7 @@ const OpeningQuestions = memo(() => {
<Flexbox gap={4} width={'100%'}>
<Space.Compact style={{ width: '100%' }}>
<Input
+ disabled={disabled}
placeholder={t('settingOpening.openingQuestions.placeholder')}
style={{ flex: 1 }}
value={questionInput}
@@ -98,7 +108,7 @@ const OpeningQuestions = memo(() => {
/>
<Button
// don't allow repeat
- disabled={openingQuestions.includes(questionInput.trim())}
+ disabled={disabled || openingQuestions.includes(questionInput.trim())}
icon={PlusIcon}
onClick={addQuestion}
/>
@@ -119,9 +129,10 @@ const OpeningQuestions = memo(() => {
id={item.id}
variant={'filled'}
>
- <SortableList.DragHandle />
+ {!disabled && <SortableList.DragHandle />}
<div className={styles.questionItemContent}>{item.content}</div>
<ActionIcon
+ disabled={disabled}
icon={Trash}
size={'small'}
onClick={() => removeQuestion(item.content)}
diff --git a/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx b/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
index d158ec10602..0294f745536 100644
--- a/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
+++ b/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
@@ -9,8 +9,11 @@ import DevModal from '@/features/PluginDevModal';
import { useAgentStore } from '@/store/agent';
import { useToolStore } from '@/store/tool';
+import { useStore } from '../store';
+
const AddPluginButton = ({ ref, ...props }: ButtonProps & { ref?: Ref<HTMLButtonElement> }) => {
const { t } = useTranslation('setting');
+ const disabled = useStore((s) => s.disabled);
const [showModal, setModal] = useState(false);
const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
const [installCustomPlugin, updateNewDevPlugin] = useToolStore((s) => [
@@ -25,19 +28,29 @@ const AddPluginButton = ({ ref, ...props }: ButtonProps & { ref?: Ref<HTMLButton
}}
>
<DevModal
- open={showModal}
- onOpenChange={setModal}
+ open={!disabled && showModal}
onValueChange={updateNewDevPlugin}
+ onOpenChange={(next) => {
+ if (disabled) return;
+
+ setModal(next);
+ }}
onSave={async (devPlugin) => {
+ if (disabled) return;
+
await installCustomPlugin(devPlugin);
toggleAgentPlugin(devPlugin.identifier);
}}
/>
<Button
+ {...props}
+ disabled={disabled}
icon={Grid2x2Plus}
ref={ref}
size={'small'}
onClick={() => {
+ if (disabled) return;
+
setModal(true);
}}
>
diff --git a/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx b/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
index ee7a0bcce87..9dc3b7d22b7 100644
--- a/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
+++ b/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
@@ -5,14 +5,21 @@ import { memo } from 'react';
import { useStore } from '../store';
const MarketList = memo<{ id: string }>(({ id }) => {
- const [toggleAgentPlugin, hasPlugin] = useStore((s) => [s.toggleAgentPlugin, !!s.config.plugins]);
+ const [toggleAgentPlugin, hasPlugin, disabled] = useStore((s) => [
+ s.toggleAgentPlugin,
+ !!s.config.plugins,
+ s.disabled,
+ ]);
const plugins = useStore((s) => s.config.plugins || []);
return (
<Flexbox horizontal align={'center'} gap={8}>
<Switch
checked={!hasPlugin ? false : plugins.includes(id)}
+ disabled={disabled}
onChange={() => {
+ if (disabled) return;
+
toggleAgentPlugin(id);
}}
/>
diff --git a/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx b/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
index 9ad6c80a683..f0c8d1ca74f 100644
--- a/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
@@ -9,15 +9,17 @@ import { useStore } from '../../store';
const PluginSwitch = memo<{ identifier: string }>(({ identifier }) => {
const pluginManifestLoading = useToolStore((s) => s.pluginInstallLoading, isEqual);
- const [userEnabledPlugins, hasPlugin, toggleAgentPlugin] = useStore((s) => [
+ const [userEnabledPlugins, hasPlugin, disabled, toggleAgentPlugin] = useStore((s) => [
s.config.plugins || [],
!!s.config.plugins,
+ s.disabled,
s.toggleAgentPlugin,
]);
return (
<Flexbox horizontal align={'center'} gap={8}>
<Switch
+ disabled={disabled}
loading={pluginManifestLoading[identifier]}
checked={
// If loading, it means it's activated
@@ -26,6 +28,8 @@ const PluginSwitch = memo<{ identifier: string }>(({ identifier }) => {
: userEnabledPlugins.includes(identifier)
}
onChange={() => {
+ if (disabled) return;
+
toggleAgentPlugin(identifier);
}}
/>
diff --git a/src/features/AgentSetting/AgentPlugin/index.tsx b/src/features/AgentSetting/AgentPlugin/index.tsx
index 1dfdb6912e5..5e5665b49fa 100644
--- a/src/features/AgentSetting/AgentPlugin/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/index.tsx
@@ -7,12 +7,13 @@ import isEqual from 'fast-deep-equal';
import { BlocksIcon, LucideTrash2, Store } from 'lucide-react';
import { memo, useCallback } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import PluginTag from '@/components/Plugins/PluginTag';
import { FORM_STYLE } from '@/const/layoutTokens';
import { createSkillStoreModal } from '@/features/SkillStore';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { pluginHelpers, useToolStore } from '@/store/tool';
@@ -27,14 +28,15 @@ import PluginAction from './PluginAction';
const AgentPlugin = memo(() => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleOpenStore = useCallback(() => {
createSkillStoreModal();
}, []);
- const [userEnabledPlugins, toggleAgentPlugin] = useStore((s) => [
+ const [userEnabledPlugins, disabled, toggleAgentPlugin] = useStore((s) => [
s.config.plugins || [],
+ s.disabled,
s.toggleAgentPlugin,
]);
@@ -79,7 +81,10 @@ const AgentPlugin = memo(() => {
children: (
<Switch
checked={true}
+ disabled={disabled}
onChange={() => {
+ if (disabled) return;
+
toggleAgentPlugin(id);
}}
/>
@@ -105,10 +110,13 @@ const AgentPlugin = memo(() => {
{hasDeprecated ? (
<Tooltip title={t('plugin.clearDeprecated')}>
<Button
+ disabled={disabled}
icon={LucideTrash2}
size={'small'}
onClick={(e) => {
e.stopPropagation();
+ if (disabled) return;
+
for (const i of deprecatedList) {
toggleAgentPlugin(i.tag as string);
}
@@ -140,7 +148,7 @@ const AgentPlugin = memo(() => {
description={
<Trans i18nKey={'plugin.empty'} ns={'setting'}>
暂无安装插件,
- <Link
+ <WorkspaceLink
to={'/community/mcp'}
onClick={(e) => {
e.stopPropagation();
@@ -150,7 +158,7 @@ const AgentPlugin = memo(() => {
}}
>
前往插件市场
- </Link>
+ </WorkspaceLink>
安装
</Trans>
}
diff --git a/src/features/AgentSetting/AgentPrompt/index.tsx b/src/features/AgentSetting/AgentPrompt/index.tsx
index b3a689e8461..3d7c8785b90 100644
--- a/src/features/AgentSetting/AgentPrompt/index.tsx
+++ b/src/features/AgentSetting/AgentPrompt/index.tsx
@@ -16,9 +16,13 @@ const AgentPrompt = memo(() => {
const { t } = useTranslation('setting');
const isMobile = useServerConfigStore((s) => s.isMobile);
const [editing, setEditing] = useState(false);
- const [systemRole, updateConfig] = useStore((s) => [s.config.systemRole, s.setAgentConfig]);
+ const [systemRole, disabled, updateConfig] = useStore((s) => [
+ s.config.systemRole,
+ s.disabled,
+ s.setAgentConfig,
+ ]);
- const editButton = !editing && !!systemRole && (
+ const editButton = !editing && !!systemRole && !disabled && (
<Button
icon={PenLineIcon}
iconPlacement={'end'}
@@ -45,10 +49,10 @@ const AgentPrompt = memo(() => {
children: (
<Flexbox paddingBlock={isMobile ? 16 : 0}>
<EditableMessage
- showEditWhenEmpty
editing={editing}
height={'auto'}
placeholder={t('settingAgent.prompt.placeholder')}
+ showEditWhenEmpty={!disabled}
value={systemRole}
variant={'borderless'}
markdownProps={{
@@ -58,10 +62,16 @@ const AgentPrompt = memo(() => {
cancel: t('cancel', { ns: 'common' }),
confirm: t('ok', { ns: 'common' }),
}}
- onEditingChange={setEditing}
onChange={(e) => {
+ if (disabled) return;
+
updateConfig({ systemRole: e });
}}
+ onEditingChange={(next) => {
+ if (disabled) return;
+
+ setEditing(next);
+ }}
/>
{!editing && !!systemRole && <Tokens value={systemRole} />}
</Flexbox>
diff --git a/src/features/AgentSetting/AgentSelfIteration/index.tsx b/src/features/AgentSetting/AgentSelfIteration/index.tsx
index 567403cbf99..db64b2a6115 100644
--- a/src/features/AgentSetting/AgentSelfIteration/index.tsx
+++ b/src/features/AgentSetting/AgentSelfIteration/index.tsx
@@ -16,7 +16,7 @@ import { selectors, useStore } from '../store';
const AgentSelfIteration = memo(() => {
const { t } = useTranslation('setting');
const [form] = Form.useForm();
- const updateConfig = useStore((s) => s.setChatConfig);
+ const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setChatConfig]);
const config = useStore(selectors.currentChatConfig, isEqual);
const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
@@ -45,13 +45,18 @@ const AgentSelfIteration = memo(() => {
return (
<Form
+ disabled={disabled}
footer={isInbox ? undefined : <Form.SubmitFooter />}
form={form}
initialValues={config}
items={[selfIteration]}
itemsType={'group'}
variant={'borderless'}
- onFinish={updateConfig}
+ onFinish={(values) => {
+ if (disabled) return;
+
+ updateConfig(values);
+ }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/AgentSetting/AgentTTS/index.tsx b/src/features/AgentSetting/AgentTTS/index.tsx
index 7a13e869b63..7b1582e7d69 100644
--- a/src/features/AgentSetting/AgentTTS/index.tsx
+++ b/src/features/AgentSetting/AgentTTS/index.tsx
@@ -28,7 +28,7 @@ const AgentTTS = memo(() => {
return (all?: boolean) => new VoiceList(all ? undefined : locale);
});
const config = useStore(selectors.currentTtsConfig, isEqual);
- const updateConfig = useStore((s) => s.setAgentConfig);
+ const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setAgentConfig]);
const { edgeVoiceOptions, microsoftVoiceOptions } = useMemo(
() => voiceList(config.showAllLocaleVoice),
@@ -96,6 +96,7 @@ const AgentTTS = memo(() => {
return (
<Form
+ disabled={disabled}
footer={<Form.SubmitFooter />}
form={form}
items={[tts]}
@@ -104,7 +105,11 @@ const AgentTTS = memo(() => {
initialValues={{
[TTS_SETTING_KEY]: config,
}}
- onFinish={updateConfig}
+ onFinish={(values) => {
+ if (disabled) return;
+
+ updateConfig(values);
+ }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/AgentSetting/StoreUpdater.tsx b/src/features/AgentSetting/StoreUpdater.tsx
index 6a0658c1e68..6bdd1661e3f 100644
--- a/src/features/AgentSetting/StoreUpdater.tsx
+++ b/src/features/AgentSetting/StoreUpdater.tsx
@@ -10,13 +10,13 @@ import { type State } from './store';
import { useStoreApi } from './store';
export interface StoreUpdaterProps extends Partial<
- Pick<State, 'onMetaChange' | 'onConfigChange' | 'meta' | 'config' | 'id' | 'loading'>
+ Pick<State, 'onMetaChange' | 'onConfigChange' | 'meta' | 'config' | 'disabled' | 'id' | 'loading'>
> {
instanceRef?: ForwardedRef<AgentSettingsInstance> | null;
}
const StoreUpdater = memo<StoreUpdaterProps>(
- ({ onConfigChange, instanceRef, id, onMetaChange, meta, config, loading }) => {
+ ({ onConfigChange, instanceRef, id, onMetaChange, meta, config, disabled, loading }) => {
const storeApi = useStoreApi();
const useStoreUpdater = createStoreUpdater(storeApi);
@@ -24,6 +24,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('config', config!);
useStoreUpdater('onConfigChange', onConfigChange);
useStoreUpdater('onMetaChange', onMetaChange);
+ useStoreUpdater('disabled', disabled);
useStoreUpdater('loading', loading);
useStoreUpdater('id', id);
diff --git a/src/features/AgentSetting/store/initialState.ts b/src/features/AgentSetting/store/initialState.ts
index 3900a32d0ed..4723d658499 100644
--- a/src/features/AgentSetting/store/initialState.ts
+++ b/src/features/AgentSetting/store/initialState.ts
@@ -8,6 +8,7 @@ export type SaveStatus = 'idle' | 'saving' | 'saved';
export interface State {
config: LobeAgentConfig;
+ disabled?: boolean;
id?: string;
lastUpdatedTime?: Date | null;
loading?: boolean;
@@ -20,6 +21,7 @@ export interface State {
export const initialState: State = {
config: DEFAULT_AGENT_CONFIG,
+ disabled: false,
lastUpdatedTime: null,
loading: true,
loadingState: {
diff --git a/src/features/AgentSkillEdit/SkillEditForm.tsx b/src/features/AgentSkillEdit/SkillEditForm.tsx
index d26929afb00..7ba5057a8fe 100644
--- a/src/features/AgentSkillEdit/SkillEditForm.tsx
+++ b/src/features/AgentSkillEdit/SkillEditForm.tsx
@@ -48,108 +48,116 @@ export interface SkillEditFormValues {
}
interface SkillEditFormProps {
+ disabled?: boolean;
form: FormInstance;
initialValues: SkillEditFormValues;
name?: string;
onSubmit: (values: SkillEditFormValues) => void;
}
-const SkillEditForm = memo<SkillEditFormProps>(({ name, form, initialValues, onSubmit }) => {
- const { t } = useTranslation('setting');
- const editor = useEditor();
- const currentValueRef = useRef(initialValues.content);
+const SkillEditForm = memo<SkillEditFormProps>(
+ ({ name, disabled, form, initialValues, onSubmit }) => {
+ const { t } = useTranslation('setting');
+ const editor = useEditor();
+ const currentValueRef = useRef(initialValues.content);
- useEffect(() => {
- form.setFieldsValue(initialValues);
- }, [initialValues]);
+ useEffect(() => {
+ form.setFieldsValue(initialValues);
+ }, [initialValues]);
- useEffect(() => {
- currentValueRef.current = initialValues.content;
- }, [initialValues.content]);
+ useEffect(() => {
+ currentValueRef.current = initialValues.content;
+ }, [initialValues.content]);
- useEffect(() => {
- if (!editor) return;
- try {
- setTimeout(() => {
- if (initialValues.content) {
+ useEffect(() => {
+ if (!editor) return;
+ try {
+ setTimeout(() => {
+ if (initialValues.content) {
+ editor.setDocument('markdown', initialValues.content);
+ }
+ }, 100);
+ } catch {
+ setTimeout(() => {
editor.setDocument('markdown', initialValues.content);
- }
- }, 100);
- } catch {
- setTimeout(() => {
- editor.setDocument('markdown', initialValues.content);
- }, 100);
- }
- }, [editor, initialValues.content]);
-
- const handleContentChange = useCallback(
- (e: any) => {
- const nextContent = (e.getDocument('markdown') as unknown as string) || '';
- if (nextContent !== currentValueRef.current) {
- currentValueRef.current = nextContent;
- form.setFieldValue('content', nextContent);
+ }, 100);
}
- },
- [form],
- );
+ }, [editor, initialValues.content]);
+
+ const handleContentChange = useCallback(
+ (e: any) => {
+ if (disabled) return;
+ const nextContent = (e.getDocument('markdown') as unknown as string) || '';
+ if (nextContent !== currentValueRef.current) {
+ currentValueRef.current = nextContent;
+ form.setFieldValue('content', nextContent);
+ }
+ },
+ [disabled, form],
+ );
- const items: FormItemProps[] = [
- {
- children: <Input disabled readOnly value={name} />,
- desc: t('agentSkillEdit.nameDesc'),
- label: t('settingAgent.name.title'),
- },
- {
- children: (
- <Input.TextArea
- autoSize={{ maxRows: 4, minRows: 2 }}
- placeholder={t('agentSkillModal.descriptionPlaceholder')}
- />
- ),
- desc: t('agentSkillEdit.descriptionDesc'),
- label: t('agentSkillModal.description'),
- name: 'description',
- },
- {
- children: (
- <div className={styles.editorWrapper}>
- <Editor
- content={''}
- editor={editor}
- lineEmptyPlaceholder={t('agentSkillEdit.instructionsPlaceholder')}
- placeholder={t('agentSkillEdit.instructionsPlaceholder')}
- plugins={PLUGINS}
- style={{ paddingBottom: 48 }}
- type={'text'}
- variant={'chat'}
- onTextChange={handleContentChange}
+ const items: FormItemProps[] = [
+ {
+ children: <Input disabled readOnly value={name} />,
+ desc: t('agentSkillEdit.nameDesc'),
+ label: t('settingAgent.name.title'),
+ },
+ {
+ children: (
+ <Input.TextArea
+ autoSize={{ maxRows: 4, minRows: 2 }}
+ disabled={disabled}
+ placeholder={t('agentSkillModal.descriptionPlaceholder')}
/>
- </div>
- ),
- desc: t('agentSkillEdit.instructionsDesc'),
- label: t('agentSkillEdit.instructions'),
- },
- ];
+ ),
+ desc: t('agentSkillEdit.descriptionDesc'),
+ label: t('agentSkillModal.description'),
+ name: 'description',
+ },
+ {
+ children: (
+ <div
+ className={styles.editorWrapper}
+ style={{ pointerEvents: disabled ? 'none' : undefined }}
+ >
+ <Editor
+ content={''}
+ editor={editor}
+ lineEmptyPlaceholder={t('agentSkillEdit.instructionsPlaceholder')}
+ placeholder={t('agentSkillEdit.instructionsPlaceholder')}
+ plugins={PLUGINS}
+ style={{ paddingBottom: 48 }}
+ type={'text'}
+ variant={'chat'}
+ onTextChange={handleContentChange}
+ />
+ </div>
+ ),
+ desc: t('agentSkillEdit.instructionsDesc'),
+ label: t('agentSkillEdit.instructions'),
+ },
+ ];
- return (
- <div className={styles.wrapper}>
- <Form
- form={form}
- gap={0}
- initialValues={initialValues}
- items={items}
- itemsType={'flat'}
- layout={'vertical'}
- variant={'borderless'}
- onFinish={onSubmit}
- >
- <AForm.Item hidden name="content">
- <Input type="hidden" />
- </AForm.Item>
- </Form>
- </div>
- );
-});
+ return (
+ <div className={styles.wrapper}>
+ <Form
+ form={form}
+ gap={0}
+ initialValues={initialValues}
+ items={items}
+ itemsType={'flat'}
+ layout={'vertical'}
+ variant={'borderless'}
+ onFinish={onSubmit}
+ >
+ <AForm.Item hidden name="content">
+ <Input type="hidden" />
+ </AForm.Item>
+ </Form>
+ </div>
+ );
+ },
+);
SkillEditForm.displayName = 'SkillEditForm';
diff --git a/src/features/AgentSkillEdit/index.tsx b/src/features/AgentSkillEdit/index.tsx
index 934ec81d61f..9242ad7aec2 100644
--- a/src/features/AgentSkillEdit/index.tsx
+++ b/src/features/AgentSkillEdit/index.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';
import FileTree from '@/features/FileTree';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import SkillEditForm, { type SkillEditFormValues } from './SkillEditForm';
@@ -60,6 +61,7 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
const { t: tp } = useTranslation('plugin');
const { t: tc } = useTranslation('common');
const { message } = App.useApp();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [selectedFile, setSelectedFile] = useState('SKILL.md');
const [saving, setSaving] = useState(false);
@@ -84,6 +86,7 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
);
const handleSubmit = async (values: SkillEditFormValues) => {
+ if (!canEdit) return;
setSaving(true);
try {
await updateAgentSkill({
@@ -99,6 +102,7 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
};
const handleDelete = async () => {
+ if (!canEdit) return;
await deleteAgentSkill(skillId);
message.success(tp('dev.deleteSuccess'));
onClose();
@@ -114,15 +118,19 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
title={tp('dev.confirmDeleteDevPlugin')}
okButtonProps={{
danger: true,
+ disabled: !canEdit,
type: 'primary',
}}
onConfirm={handleDelete}
>
- <Button danger>{tc('delete')}</Button>
+ <Button danger disabled={!canEdit}>
+ {tc('delete')}
+ </Button>
</Popconfirm>
<Flexbox horizontal gap={12}>
<Button onClick={onClose}>{tc('cancel')}</Button>
<Button
+ disabled={!canEdit}
loading={saving}
type={'primary'}
onClick={() => {
@@ -181,6 +189,7 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
}}
>
<SkillEditForm
+ disabled={!canEdit}
form={form}
initialValues={initialValues}
name={skillDetail?.name}
diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
index 0619cda60da..a306e7fd4a4 100644
--- a/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
@@ -11,6 +11,7 @@ import {
insertFilesIntoEditor,
} from '@/features/EditorCanvas/editorAttachments';
import { useEnterToSend } from '@/hooks/useEnterToSend';
+import { usePermission } from '@/hooks/usePermission';
import { useUserAvatar } from '@/hooks/useUserAvatar';
import { useTaskStore } from '@/store/task';
@@ -18,6 +19,7 @@ import { styles } from '../shared/style';
const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
const { t } = useTranslation('chat');
+ const { allowed: canEditTask } = usePermission('create_content');
const editor = useEditor();
const addComment = useTaskStore((s) => s.addComment);
const userAvatar = useUserAvatar();
@@ -46,7 +48,7 @@ const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
);
const handleSubmit = useCallback(async () => {
- if (submitting) return;
+ if (!canEditTask || submitting) return;
const json = editor?.getDocument?.('json') as unknown;
const markdown = String(editor?.getDocument?.('markdown') ?? '').trim();
const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;
@@ -61,7 +63,7 @@ const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
} finally {
setSubmitting(false);
}
- }, [taskId, editor, addComment, submitting]);
+ }, [canEditTask, taskId, editor, addComment, submitting]);
return (
<Flexbox className={styles.commentInputCard} gap={6}>
@@ -75,6 +77,7 @@ const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
style={{ fontSize: 14, minHeight: 24, paddingBlock: 0 }}
onContentChange={handleContentChange}
onPressEnter={({ event }) => {
+ if (!canEditTask) return true;
if (shouldSendOnEnter(event)) {
handleSubmit();
return true;
@@ -85,7 +88,7 @@ const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
<Flexbox horizontal align={'center'} gap={4} style={{ flexShrink: 0 }}>
<AttachmentUploadButton onFiles={handleAttach} />
<SendButton
- disabled={!canSubmit && !submitting}
+ disabled={!canEditTask || (!canSubmit && !submitting)}
loading={submitting}
shape={'round'}
type={'text'}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
new file mode 100644
index 00000000000..3950b340023
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TaskDetailHeaderActions from './TaskDetailHeaderActions';
+
+interface MenuItem {
+ key?: string;
+ label?: ReactNode;
+ type?: string;
+}
+
+const mocks = vi.hoisted(() => ({
+ deleteTask: vi.fn(),
+ dropdownItems: [] as MenuItem[],
+ messageSuccess: vi.fn(),
+ modalConfirm: vi.fn(),
+ navigate: vi.fn(),
+ taskState: {
+ activeTaskId: 'T-1' as string | undefined,
+ taskDetailMap: {} as Record<string, unknown>,
+ },
+ transferItems: [
+ { key: 'transfer-task', label: 'Transfer to...' },
+ { key: 'copy-task', label: 'Copy to...' },
+ ] as MenuItem[],
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ title }: { title?: string }) => <button type="button">{title}</button>,
+ DropdownMenu: ({ children, items }: { children?: ReactNode; items: MenuItem[] }) => {
+ mocks.dropdownItems = items;
+ return <>{children}</>;
+ },
+ Icon: () => <span />,
+ copyToClipboard: vi.fn(),
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: { success: mocks.messageSuccess },
+ modal: { confirm: mocks.modalConfirm },
+ }),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/business/client/hooks/useTaskTransferMenuItem', () => ({
+ useTaskTransferMenuItem: vi.fn(() => mocks.transferItems),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://example.com',
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true }),
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (
+ selector: (state: { activeTaskId?: string; deleteTask: typeof mocks.deleteTask }) => unknown,
+ ) => selector({ ...mocks.taskState, deleteTask: mocks.deleteTask }),
+}));
+
+describe('TaskDetailHeaderActions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.dropdownItems = [];
+ mocks.taskState.activeTaskId = 'T-1';
+ });
+
+ it('includes task transfer and copy actions in the detail menu', () => {
+ render(<TaskDetailHeaderActions />);
+
+ expect(mocks.dropdownItems.map((item) => item?.key)).toContain('transfer-task');
+ expect(mocks.dropdownItems.map((item) => item?.key)).toContain('copy-task');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
index cd7c6e15142..0b16db05794 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
@@ -4,9 +4,11 @@ import { App } from 'antd';
import { CopyIcon, LinkIcon, MoreHorizontal, Trash } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferMenuItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -15,13 +17,16 @@ import { taskDetailPath } from '../shared/taskDetailPath';
const TaskDetailHeaderActions = memo(() => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const appOrigin = useAppOrigin();
+ const { allowed: canEditTask } = usePermission('create_content');
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const taskAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
const deleteTask = useTaskStore((s) => s.deleteTask);
+ const transferItems = useTaskTransferMenuItem(taskId) as DropdownItem[] | null;
const triggerDelete = useCallback(() => {
+ if (!canEditTask) return;
if (!taskId) return;
confirmModal({
content: t('taskDetail.deleteConfirm.content'),
@@ -33,14 +38,14 @@ const TaskDetailHeaderActions = memo(() => {
},
title: t('taskDetail.deleteConfirm.title'),
});
- }, [taskId, t, deleteTask, navigate]);
+ }, [canEditTask, taskId, t, deleteTask, navigate]);
const menuItems = useMemo<DropdownItem[]>(() => {
if (!taskId) return [];
const taskUrl = `${appOrigin}${taskDetailPath(taskId, taskAgentId ?? undefined)}`;
- return [
+ const baseItems: DropdownItem[] = [
{
icon: <Icon icon={CopyIcon} />,
key: 'copyId',
@@ -62,13 +67,18 @@ const TaskDetailHeaderActions = memo(() => {
{ type: 'divider' },
{
danger: true,
+ disabled: !canEditTask,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: triggerDelete,
},
];
- }, [taskId, taskAgentId, appOrigin, t, message, triggerDelete]);
+
+ if (!transferItems || transferItems.length === 0) return baseItems;
+
+ return [...baseItems.slice(0, 3), ...transferItems, { type: 'divider' }, ...baseItems.slice(3)];
+ }, [taskId, taskAgentId, appOrigin, t, message, triggerDelete, canEditTask, transferItems]);
if (!taskId) return null;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
index 8aa1d9c7a83..44b78d1c81a 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
@@ -5,6 +5,7 @@ import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import StopLoadingIcon from '@/components/StopLoading';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
@@ -25,6 +26,7 @@ const formatCountdown = (msRemaining: number): string => {
const TaskDetailRunPauseAction = memo(() => {
const { t } = useTranslation('chat');
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const canRun = useTaskStore(taskDetailSelectors.canRunActiveTask);
const canPause = useTaskStore(taskDetailSelectors.canPauseActiveTask);
@@ -47,6 +49,7 @@ const TaskDetailRunPauseAction = memo(() => {
const [isRunningNow, setIsRunningNow] = useState(false);
const handleRunOrPause = useCallback(async () => {
+ if (!canEditTask) return;
if (!taskId) return;
if (canPause) {
await updateTaskStatus(taskId, 'paused');
@@ -71,9 +74,11 @@ const TaskDetailRunPauseAction = memo(() => {
runTask,
updateTask,
updateTaskStatus,
+ canEditTask,
]);
const handleRunNow = useCallback(async () => {
+ if (!canEditTask) return;
if (!taskId) return;
setIsRunningNow(true);
try {
@@ -84,9 +89,10 @@ const TaskDetailRunPauseAction = memo(() => {
} finally {
setIsRunningNow(false);
}
- }, [taskId, assigneeAgentId, inboxAgentId, runTask, updateTask]);
+ }, [canEditTask, taskId, assigneeAgentId, inboxAgentId, runTask, updateTask]);
const handleCancelSchedule = useCallback(async () => {
+ if (!canEditTask) return;
if (!taskId) return;
setIsCancellingSchedule(true);
try {
@@ -97,7 +103,7 @@ const TaskDetailRunPauseAction = memo(() => {
} finally {
setIsCancellingSchedule(false);
}
- }, [taskId, setAutomationMode, updateTaskStatus, status]);
+ }, [canEditTask, taskId, setAutomationMode, updateTaskStatus, status]);
const isScheduled = status === 'scheduled';
@@ -133,9 +139,10 @@ const TaskDetailRunPauseAction = memo(() => {
<Flexbox horizontal align={'center'} gap={12}>
<Space.Compact>
<Button
- disabled={isRunningNow}
+ disabled={!canEditTask || isRunningNow}
icon={CalendarOffIcon}
loading={isCancellingSchedule}
+ title={canEditTask ? undefined : reason}
onClick={handleCancelSchedule}
>
{t('taskDetail.cancelSchedule')}
@@ -143,7 +150,7 @@ const TaskDetailRunPauseAction = memo(() => {
<DropdownMenu
items={[
{
- disabled: isRunningNow || isCancellingSchedule,
+ disabled: !canEditTask || isRunningNow || isCancellingSchedule,
icon: PlayIcon,
key: 'runNow',
label: t('taskDetail.runNow'),
@@ -151,7 +158,12 @@ const TaskDetailRunPauseAction = memo(() => {
},
]}
>
- <Button disabled={isCancellingSchedule} icon={ChevronDown} loading={isRunningNow} />
+ <Button
+ disabled={!canEditTask || isCancellingSchedule}
+ icon={ChevronDown}
+ loading={isRunningNow}
+ title={canEditTask ? undefined : reason}
+ />
</DropdownMenu>
</Space.Compact>
{countdownText && (
@@ -176,7 +188,12 @@ const TaskDetailRunPauseAction = memo(() => {
if (canPause) {
return (
- <Button icon={StopLoadingIcon} onClick={handleRunOrPause}>
+ <Button
+ disabled={!canEditTask}
+ icon={StopLoadingIcon}
+ title={reason}
+ onClick={handleRunOrPause}
+ >
{t('taskDetail.stopTask')}
</Button>
);
@@ -186,7 +203,13 @@ const TaskDetailRunPauseAction = memo(() => {
const runIcon = isRerun ? RotateCcwIcon : PlayIcon;
return (
- <Button icon={runIcon} type={'primary'} onClick={handleRunOrPause}>
+ <Button
+ disabled={!canEditTask}
+ icon={runIcon}
+ title={canEditTask ? undefined : reason}
+ type={'primary'}
+ onClick={handleRunOrPause}
+ >
{runLabel}
</Button>
);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput.tsx
index 344ae65ffa6..c3db7322751 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput.tsx
@@ -3,6 +3,7 @@ import { Input } from 'antd';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -12,6 +13,7 @@ const DEBOUNCE_MS = 300;
const TaskDetailTitleInput = memo(() => {
const { t } = useTranslation('chat');
+ const { allowed: canEditTask } = usePermission('create_content');
const name = useTaskStore(taskDetailSelectors.activeTaskName);
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const updateTask = useTaskStore((s) => s.updateTask);
@@ -24,6 +26,7 @@ const TaskDetailTitleInput = memo(() => {
const { run: debouncedSave } = useDebounceFn(
(value: string) => {
+ if (!canEditTask) return;
if (taskId) updateTask(taskId, { name: value });
},
{ wait: DEBOUNCE_MS },
@@ -41,6 +44,7 @@ const TaskDetailTitleInput = memo(() => {
<Input.TextArea
autoSize={{ minRows: 1 }}
className={styles.titleInput}
+ disabled={!canEditTask}
placeholder={t('taskDetail.titlePlaceholder')}
value={localName}
variant={'borderless'}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
index adbdf4f4a26..0d67a40cba8 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import { EditorCanvas } from '@/features/EditorCanvas';
import { seedAttachments } from '@/features/EditorCanvas/attachmentRegistry';
import { pickAndInsertAttachments } from '@/features/EditorCanvas/editorAttachments';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -14,6 +15,7 @@ const DEBOUNCE_MS = 300;
const TaskInstruction = memo(() => {
const { t } = useTranslation('chat');
+ const { allowed: canEditTask } = usePermission('create_content');
const instruction = useTaskStore(taskDetailSelectors.activeTaskInstruction);
const persistedEditorData = useTaskStore(taskDetailSelectors.activeTaskEditorData);
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
@@ -47,6 +49,7 @@ const TaskInstruction = memo(() => {
}, [taskId]);
const handleContentChange = useCallback(() => {
+ if (!canEditTask) return;
if (!editor || !taskId) return;
if (debounceRef.current) clearTimeout(debounceRef.current);
@@ -61,7 +64,7 @@ const TaskInstruction = memo(() => {
console.error('[TaskInstruction] Failed to save:', e);
});
}, DEBOUNCE_MS);
- }, [editor, taskId, updateTask]);
+ }, [canEditTask, editor, taskId, updateTask]);
const handleAttach = useCallback(() => {
pickAndInsertAttachments(editor);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskModelConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskModelConfig.tsx
index ce0177af1b3..f0fefbf155d 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskModelConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskModelConfig.tsx
@@ -1,12 +1,14 @@
import { memo, useCallback } from 'react';
import ModelSelect from '@/features/ModelSelect';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
const TaskModelConfig = memo(() => {
+ const { allowed: canEditTask } = usePermission('create_content');
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const taskModel = useTaskStore(taskDetailSelectors.activeTaskModel);
const taskProvider = useTaskStore(taskDetailSelectors.activeTaskProvider);
@@ -20,15 +22,17 @@ const TaskModelConfig = memo(() => {
const handleChange = useCallback(
async (params: { model: string; provider: string }) => {
+ if (!canEditTask) return;
if (!taskId) return;
await updateTaskModelConfig(taskId, params);
},
- [taskId, updateTaskModelConfig],
+ [canEditTask, taskId, updateTaskModelConfig],
);
return (
<ModelSelect
initialWidth
+ disabled={!canEditTask}
popupWidth={400}
value={{ model, provider }}
onChange={handleChange}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
index f34790524fc..357c778cf39 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
@@ -2,8 +2,8 @@ import type { TaskDetailData, TaskDetailSubtask } from '@lobechat/types';
import { Button, Flexbox, Text } from '@lobehub/ui';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { taskService } from '@/services/task';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -28,7 +28,7 @@ const toTaskStatus = (status?: string): TaskStatus =>
const TaskParentBar = memo(() => {
const { t } = useTranslation('chat');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const parent = useTaskStore(taskDetailSelectors.activeTaskParent);
const currentIdentifier = useTaskStore(taskDetailSelectors.activeTaskDetail)?.identifier;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
index e23af8a1f96..79cba44ee2e 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
@@ -19,6 +19,7 @@ import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -55,10 +56,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface IntervalTabProps {
currentInterval: number;
+ disabled?: boolean;
taskId?: string;
}
-const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
+const IntervalTab = memo<IntervalTabProps>(({ currentInterval, disabled, taskId }) => {
const { t } = useTranslation('chat');
const updatePeriodicInterval = useTaskStore((s) => s.updatePeriodicInterval);
@@ -98,23 +100,25 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
normalized = val;
}
setLocalValue(normalized);
+ if (disabled) return;
if (!taskId) return;
const seconds = toSeconds(normalized ?? null, localUnit);
updatePeriodicInterval(taskId, seconds);
},
- [taskId, localUnit, updatePeriodicInterval],
+ [disabled, taskId, localUnit, updatePeriodicInterval],
);
const handleUnitChange = useCallback(
(u: IntervalUnit) => {
setLocalUnit(u);
+ if (disabled) return;
if (!taskId || !localValue) return;
const clamped = u === 'minutes' ? Math.max(MIN_MINUTES, localValue) : localValue;
if (clamped !== localValue) setLocalValue(clamped);
const seconds = toSeconds(clamped, u);
updatePeriodicInterval(taskId, seconds);
},
- [taskId, localValue, updatePeriodicInterval],
+ [disabled, taskId, localValue, updatePeriodicInterval],
);
return (
@@ -123,6 +127,7 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
<Flexbox horizontal align="center" gap={8}>
<Text type="secondary">{t('taskSchedule.every')}</Text>
<InputNumber
+ disabled={disabled}
min={localUnit === 'minutes' ? MIN_MINUTES : 1}
placeholder={localUnit === 'minutes' ? String(MIN_MINUTES) : '1'}
style={{ width: 100 }}
@@ -131,6 +136,7 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
onChange={handleValueChange}
/>
<Select
+ disabled={disabled}
style={{ flex: 1 }}
value={localUnit}
variant="filled"
@@ -147,10 +153,11 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
});
interface SchedulerTabProps {
+ disabled?: boolean;
taskId?: string;
}
-const SchedulerTab = memo<SchedulerTabProps>(({ taskId }) => {
+const SchedulerTab = memo<SchedulerTabProps>(({ disabled, taskId }) => {
const updateSchedule = useTaskStore((s) => s.updateSchedule);
const pattern = useTaskStore(taskDetailSelectors.activeTaskSchedulePattern);
const timezone = useTaskStore(taskDetailSelectors.activeTaskScheduleTimezone);
@@ -158,10 +165,11 @@ const SchedulerTab = memo<SchedulerTabProps>(({ taskId }) => {
const handleChange = useCallback(
(change: SchedulerFormChange) => {
+ if (disabled) return;
if (!taskId) return;
updateSchedule(taskId, change);
},
- [taskId, updateSchedule],
+ [disabled, taskId, updateSchedule],
);
return (
@@ -187,6 +195,7 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
taskId,
}: TaskScheduleConfigProps) {
const { t, i18n } = useTranslation('chat');
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const activeTaskId = useTaskStore(taskDetailSelectors.activeTaskId);
const activeTaskInterval = useTaskStore(taskDetailSelectors.activeTaskPeriodicInterval);
const automationMode = useTaskStore(taskDetailSelectors.activeTaskAutomationMode);
@@ -263,23 +272,26 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
const handleEnableChange = useCallback(
(checked: boolean) => {
+ if (!canEditTask) return;
if (!finalTaskId) return;
// Schedule (cron) is the more common, predictable choice; users who want
// a fixed interval can switch to the heartbeat tab from there.
setAutomationMode(finalTaskId, checked ? 'schedule' : null);
},
- [finalTaskId, setAutomationMode],
+ [canEditTask, finalTaskId, setAutomationMode],
);
const handleModeChange = useCallback(
(value: string | number) => {
+ if (!canEditTask) return;
if (!finalTaskId) return;
setAutomationMode(finalTaskId, value as TaskAutomationMode);
},
- [finalTaskId, setAutomationMode],
+ [canEditTask, finalTaskId, setAutomationMode],
);
const handleStartScheduling = useCallback(async () => {
+ if (!canEditTask) return;
if (!finalTaskId) return;
setIsStartingSchedule(true);
try {
@@ -287,7 +299,7 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
} finally {
setIsStartingSchedule(false);
}
- }, [finalTaskId, updateTaskStatus]);
+ }, [canEditTask, finalTaskId, updateTaskStatus]);
const content = (
<Flexbox gap={16} style={{ padding: 4, width: 440 }} onClick={(e) => e.stopPropagation()}>
@@ -309,7 +321,7 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
</Text>
)}
</Flexbox>
- <Switch checked={enabled} onChange={handleEnableChange} />
+ <Switch checked={enabled} disabled={!canEditTask} onChange={handleEnableChange} />
</Flexbox>
{enabled && nextRunText && (
@@ -326,6 +338,7 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
<>
<Segmented
block
+ disabled={!canEditTask}
value={automationMode ?? 'heartbeat'}
options={[
{
@@ -350,12 +363,19 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
onChange={handleModeChange}
/>
{automationMode === 'heartbeat' && (
- <IntervalTab currentInterval={finalCurrentInterval} taskId={finalTaskId} />
+ <IntervalTab
+ currentInterval={finalCurrentInterval}
+ disabled={!canEditTask}
+ taskId={finalTaskId}
+ />
+ )}
+ {automationMode === 'schedule' && (
+ <SchedulerTab disabled={!canEditTask} taskId={finalTaskId} />
)}
- {automationMode === 'schedule' && <SchedulerTab taskId={finalTaskId} />}
{canStartSchedule && (
<Button
block
+ disabled={!canEditTask}
icon={CalendarClockIcon}
loading={isStartingSchedule}
type="primary"
@@ -370,11 +390,20 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
);
return (
- <Popover className={styles.popover} content={content} placement="bottomRight" trigger="click">
+ <Popover
+ className={styles.popover}
+ content={content}
+ disabled={!canEditTask}
+ placement="bottomRight"
+ trigger="click"
+ >
{children ? (
- <div onClick={(e) => e.stopPropagation()}>{children}</div>
+ <div title={canEditTask ? undefined : reason} onClick={(e) => e.stopPropagation()}>
+ {children}
+ </div>
) : (
<ActionIcon
+ disabled={!canEditTask}
icon={TimerIcon}
size="small"
title={t('taskSchedule.title')}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index daa67d04b72..b44e08e0d7d 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -8,8 +8,9 @@ import { ChevronDown, ListTodoIcon, PlayCircle, Plus } from 'lucide-react';
import type { Key, MouseEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { taskService } from '@/services/task';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -129,7 +130,8 @@ const toTreeData = (tree: TaskTreeNode[]): DataNode[] => {
const TaskSubtasks = memo(() => {
const { t } = useTranslation('chat');
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const agentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
const subtasks = useTaskStore(taskDetailSelectors.activeTaskSubtasks);
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
@@ -168,6 +170,7 @@ const TaskSubtasks = memo(() => {
const handleRightClick = useCallback(
({ event, node }: { event: MouseEvent; node: { key: Key } }) => {
+ if (!canEditTask) return;
const subtask = subtaskMap.get(String(node.key));
if (!subtask) return;
event.preventDefault();
@@ -186,12 +189,16 @@ const TaskSubtasks = memo(() => {
status: subtask.status,
});
},
- [subtaskMap, buildItems, installKeyboardHandlers],
+ [canEditTask, subtaskMap, buildItems, installKeyboardHandlers],
);
- const toggleCreating = useCallback(() => setIsCreating((prev) => !prev), []);
+ const toggleCreating = useCallback(() => {
+ if (!canEditTask) return;
+ setIsCreating((prev) => !prev);
+ }, [canEditTask]);
const handleRunAll = useCallback(async () => {
+ if (!canEditTask) return;
if (!taskId || isPlanning) return;
setIsPlanning(true);
try {
@@ -241,7 +248,7 @@ const TaskSubtasks = memo(() => {
} finally {
setIsPlanning(false);
}
- }, [taskId, isPlanning, message, t, runReadySubtasks]);
+ }, [canEditTask, taskId, isPlanning, message, t, runReadySubtasks]);
if (!taskId) return null;
@@ -281,17 +288,18 @@ const TaskSubtasks = memo(() => {
</Flexbox>
<Flexbox horizontal align="center" gap={4}>
<ActionIcon
- disabled={isPlanning}
+ disabled={!canEditTask || isPlanning}
icon={PlayCircle}
loading={isPlanning}
size="small"
- title={t('taskDetail.runAll')}
+ title={canEditTask ? t('taskDetail.runAll') : reason}
onClick={handleRunAll}
/>
<ActionIcon
+ disabled={!canEditTask}
icon={Plus}
size="small"
- title={t('taskDetail.addSubtask')}
+ title={canEditTask ? t('taskDetail.addSubtask') : reason}
onClick={toggleCreating}
/>
</Flexbox>
@@ -337,6 +345,7 @@ const TaskSubtasks = memo(() => {
paddingBlock={4}
paddingInline={8}
style={{ width: 'fit-content' }}
+ title={canEditTask ? undefined : reason}
variant="borderless"
onClick={toggleCreating}
>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
index 41e36d12ae1..03d63b475c9 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
@@ -15,6 +15,10 @@ const mocks = vi.hoisted(() => ({
dbMessagesMap: {} as Record<string, unknown[]>,
replaceMessages: vi.fn(),
},
+ permission: {
+ allowed: true,
+ reason: 'requires member',
+ },
serverConfigState: {
serverConfig: {
enableBusinessFeatures: false,
@@ -49,10 +53,38 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => <button onClick={onClick} />,
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button disabled={disabled} title={title} onClick={onClick}>
+ {title}
+ </button>
+ ),
copyToClipboard: vi.fn(),
- Drawer: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
- open ? <div data-testid="topic-drawer">{children}</div> : null,
+ Drawer: ({
+ children,
+ extra,
+ open,
+ title,
+ }: {
+ children?: ReactNode;
+ extra?: ReactNode;
+ open?: boolean;
+ title?: ReactNode;
+ }) =>
+ open ? (
+ <div data-testid="topic-drawer">
+ {title}
+ {extra}
+ {children}
+ </div>
+ ) : null,
DropdownMenu: ({ children }: { children?: ReactNode }) => <>{children}</>,
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Freeze: ({ children }: { children?: ReactNode; frozen?: boolean }) => <>{children}</>,
@@ -102,6 +134,10 @@ vi.mock('@/hooks/useOperationState', () => ({
useOperationState: () => undefined,
}));
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),
+}));
+
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState),
@@ -142,6 +178,8 @@ describe('TopicChatDrawer', () => {
mocks.chatState.replaceMessages.mockClear();
mocks.taskState.closeTopicDrawer.mockClear();
mocks.taskState.activeTopicDrawerTopicId = 'topic-1';
+ mocks.permission.allowed = true;
+ mocks.serverConfigState.serverConfig.enableBusinessFeatures = false;
});
it('hydrates the task assignee agent config for drawer messages', () => {
@@ -149,4 +187,13 @@ describe('TopicChatDrawer', () => {
expect(mocks.agentState.useHydrateAgentConfig).toHaveBeenCalledWith(true, 'agt_assignee');
});
+
+ it('disables topic sharing for workspace viewers', () => {
+ mocks.permission.allowed = false;
+ mocks.serverConfigState.serverConfig.enableBusinessFeatures = true;
+
+ const { getByTitle } = render(<TopicChatDrawer />);
+
+ expect(getByTitle('requires member')).toBeDisabled();
+ });
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
index 937ce411ed7..739a3f590ab 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
@@ -22,6 +22,7 @@ import { useShareModal } from '@/features/ShareModal';
import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -114,6 +115,7 @@ const TopicChatDrawer = memo(() => {
const closeTopicDrawer = useTaskStore((s) => s.closeTopicDrawer);
const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
+ const { allowed: canShare, reason } = usePermission('edit_own_content');
// Hydrate task detail when the drawer is opened outside of TaskDetailPage
// (e.g. from a brief on home) so the header has agentId / status / seq.
@@ -175,15 +177,16 @@ const TopicChatDrawer = memo(() => {
const shareIcon = (
<ActionIcon
+ disabled={!canShare}
icon={Share2}
size={'small'}
- title={t('share', { ns: 'common' })}
- onClick={enableTopicLinkShare ? undefined : openShareModal}
+ title={canShare ? t('share', { ns: 'common' }) : reason}
+ onClick={enableTopicLinkShare || !canShare ? undefined : openShareModal}
/>
);
const extra = topicId ? (
- enableTopicLinkShare ? (
+ enableTopicLinkShare && canShare ? (
<SharePopover topicId={topicId} onOpenModal={openShareModal}>
{shareIcon}
</SharePopover>
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
index 68ecdc14f42..ef263976591 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
@@ -1,8 +1,31 @@
import { describe, expect, it } from 'vitest';
+import { getTaskCreateActionBehavior } from './AgentTasksPage';
import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';
describe('AgentTasksPage', () => {
+ describe('getTaskCreateActionBehavior', () => {
+ it('should allow workspace viewers to reopen the collapsed inline entry in list view', () => {
+ expect(
+ getTaskCreateActionBehavior({
+ canCreateTask: false,
+ inlineCollapsed: true,
+ viewMode: 'list',
+ }),
+ ).toEqual({ disabled: false, mode: 'inline' });
+ });
+
+ it('should keep the modal create action disabled for workspace viewers in kanban view', () => {
+ expect(
+ getTaskCreateActionBehavior({
+ canCreateTask: false,
+ inlineCollapsed: false,
+ viewMode: 'kanban',
+ }),
+ ).toEqual({ disabled: true, mode: 'modal' });
+ });
+ });
+
describe('shouldRenderTaskAgentPanelToggle', () => {
it('should render the task agent panel toggle on desktop layouts', () => {
expect(shouldRenderTaskAgentPanelToggle(false)).toBe(true);
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 1eb6d1ca7f8..2c815a4de31 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -1,17 +1,19 @@
import { ActionIcon, Flexbox } from '@lobehub/ui';
import { Plus } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import WideScreenContainer from '@/features/WideScreenContainer';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
+import type { TaskViewMode } from '@/store/task/slices/list/initialState';
import { createTaskModal } from '../CreateTaskModal';
import Breadcrumb from '../shared/Breadcrumb';
@@ -25,9 +27,29 @@ import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';
import TaskList from './TaskList';
import TasksGroupConfig from './TasksGroupConfig';
+interface TaskCreateActionBehaviorParams {
+ canCreateTask: boolean;
+ inlineCollapsed: boolean;
+ viewMode: TaskViewMode;
+}
+
+export const getTaskCreateActionBehavior = ({
+ canCreateTask,
+ inlineCollapsed,
+ viewMode,
+}: TaskCreateActionBehaviorParams) => {
+ const shouldExpandInline = inlineCollapsed && viewMode === 'list';
+
+ return {
+ disabled: shouldExpandInline ? false : !canCreateTask,
+ mode: shouldExpandInline ? 'inline' : 'modal',
+ } as const;
+};
+
const AgentTasksPage = memo(() => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const isMobile = useIsMobile();
+ const { allowed: canCreateTask, reason } = usePermission('create_content');
const viewMode = useTaskStore(taskListSelectors.viewMode);
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
useFetchTaskList({ allAgents: true });
@@ -48,13 +70,29 @@ const AgentTasksPage = memo(() => {
[updateSystemStatus, viewOptions],
);
+ const createActionBehavior = useMemo(
+ () =>
+ getTaskCreateActionBehavior({
+ canCreateTask,
+ inlineCollapsed,
+ viewMode,
+ }),
+ [canCreateTask, inlineCollapsed, viewMode],
+ );
+
const handleCreateTask = useCallback(() => {
+ if (createActionBehavior.mode === 'inline') {
+ updateSystemStatus({ taskCreateInlineCollapsed: false }, 'expandTaskCreateInline');
+ return;
+ }
+
+ if (!canCreateTask) return;
createTaskModal({
onCreated: (task) => {
navigate(taskDetailPath(task.identifier, task.agentId));
},
});
- }, [navigate]);
+ }, [canCreateTask, createActionBehavior.mode, navigate, updateSystemStatus]);
const handleShowHiddenCompleted = useCallback(() => {
setViewOptions((prev) => ({ ...prev, hideCompleted: false }));
@@ -70,8 +108,10 @@ const AgentTasksPage = memo(() => {
<Flexbox horizontal align={'center'} gap={4}>
{(inlineCollapsed || viewMode === 'kanban') && (
<ActionIcon
+ disabled={createActionBehavior.disabled}
icon={Plus}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={createActionBehavior.disabled ? reason : undefined}
onClick={handleCreateTask}
/>
)}
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
new file mode 100644
index 00000000000..7ca8b3b94ad
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -0,0 +1,88 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import CreateTaskInlineEntry from './CreateTaskInlineEntry';
+
+const permissionMock = vi.hoisted(() => ({
+ allowed: true,
+}));
+
+const focusMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/editor/react', () => ({
+ useEditor: () => ({
+ cleanDocument: vi.fn(),
+ focus: focusMock,
+ getLexicalEditor: () => undefined,
+ }),
+}));
+
+vi.mock('@/features/EditorCanvas', () => ({
+ EditorCanvas: ({ disabled }: { disabled?: boolean }) => (
+ <div data-disabled={String(!!disabled)} data-testid="task-editor" />
+ ),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({
+ allowed: permissionMock.allowed,
+ reason: permissionMock.allowed ? '' : 'requires member',
+ }),
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ createTask: vi.fn(),
+ isCreatingTask: false,
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ updateSystemStatus: vi.fn(),
+ }),
+}));
+
+vi.mock('../features/TaskPriorityTag', () => ({
+ default: ({ children }: { children?: ReactNode }) => (
+ <div data-testid="priority">{children ?? 'priority'}</div>
+ ),
+}));
+
+vi.mock('../features/AssigneeAgentSelector', () => ({
+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('../features/AssigneeAvatar', () => ({
+ default: () => <div />,
+}));
+
+vi.mock('../shared/useAgentDisplayMeta', () => ({
+ useAgentDisplayMeta: () => undefined,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('CreateTaskInlineEntry', () => {
+ beforeEach(() => {
+ permissionMock.allowed = true;
+ focusMock.mockReset();
+ });
+
+ it('renders the task editor as disabled when the user cannot create content', () => {
+ permissionMock.allowed = false;
+
+ render(<CreateTaskInlineEntry variant="hero" />);
+
+ expect(screen.getByTestId('task-editor')).toHaveAttribute('data-disabled', 'true');
+ expect(focusMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index 2c39c4971ae..4174dd03078 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -14,6 +14,7 @@ import {
getAttachmentFileIdsFromEditor,
pickAndInsertAttachments,
} from '@/features/EditorCanvas/editorAttachments';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useTaskStore } from '@/store/task';
@@ -48,6 +49,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
} = props;
const isHero = variant === 'hero';
const { t } = useTranslation('chat');
+ const { allowed: canCreateTask, reason } = usePermission('create_content');
const createTask = useTaskStore((s) => s.createTask);
const isCreating = useTaskStore((s) => s.isCreatingTask);
@@ -63,8 +65,9 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const assigneeMeta = useAgentDisplayMeta(assigneeAgentId);
useEffect(() => {
+ if (!canCreateTask) return;
if (autoFocus || isHero) editor?.focus?.();
- }, [autoFocus, editor, isHero]);
+ }, [autoFocus, canCreateTask, editor, isHero]);
const handleCollapse = useCallback(() => {
if (onCollapse) {
@@ -75,19 +78,21 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
}, [onCollapse, updateSystemStatus]);
const handleContentChange = useCallback(() => {
+ if (!canCreateTask) return;
const lexicalEditor = editor?.getLexicalEditor?.();
if (!lexicalEditor) return;
lexicalEditor.getEditorState().read(() => {
setInstruction($getRoot().getTextContent());
});
setHasAttachments(getAttachmentFileIdsFromEditor(editor).length > 0);
- }, [editor]);
+ }, [canCreateTask, editor]);
const handleAttach = useCallback(() => {
pickAndInsertAttachments(editor);
}, [editor]);
const handleSubmit = useCallback(async () => {
+ if (!canCreateTask) return;
const markdown = String(editor?.getDocument?.('markdown') ?? '').trim();
const trimmedText = instruction.trim();
const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;
@@ -133,6 +138,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
onCreated,
parentTaskId,
priority,
+ canCreateTask,
]);
const handleSubmitRef = useRef(handleSubmit);
@@ -170,6 +176,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
}}
>
<EditorCanvas
+ disabled={!canCreateTask}
editor={editor}
floatingToolbar={false}
placeholder={placeholder ?? t('createTask.instructionPlaceholder')}
@@ -248,10 +255,11 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
</Flexbox>
<Button
- disabled={isCreating || (!instruction.trim() && !hasAttachments)}
+ disabled={!canCreateTask || isCreating || (!instruction.trim() && !hasAttachments)}
loading={isCreating}
shape={'round'}
size={'small'}
+ title={canCreateTask ? undefined : reason}
type={'primary'}
onClick={handleSubmit}
>
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index d0226cbad65..92831ee6202 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -14,8 +14,9 @@ import { createStaticStyles } from 'antd-style';
import { ClipboardCheckIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
@@ -75,7 +76,8 @@ const optimisticMoveTask = (
const KanbanBoard = memo(() => {
const { t } = useTranslation('chat');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canEditTask } = usePermission('create_content');
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
useFetchTaskGroupList({ allAgents: true });
@@ -95,14 +97,19 @@ const KanbanBoard = memo(() => {
useSensor(KeyboardSensor),
);
- const handleDragStart = useCallback((event: DragStartEvent) => {
- const task = event.active.data.current?.task as TaskListItem | undefined;
- setActiveTask(task ?? null);
- }, []);
+ const handleDragStart = useCallback(
+ (event: DragStartEvent) => {
+ if (!canEditTask) return;
+ const task = event.active.data.current?.task as TaskListItem | undefined;
+ setActiveTask(task ?? null);
+ },
+ [canEditTask],
+ );
const handleDragEnd = useCallback(
async (event: DragEndEvent) => {
setActiveTask(null);
+ if (!canEditTask) return;
const { active, over } = event;
if (!over) return;
@@ -126,7 +133,7 @@ const KanbanBoard = memo(() => {
useTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/revertMove');
}
},
- [updateTaskStatus],
+ [canEditTask, updateTaskStatus],
);
const handleDragCancel = useCallback(() => {
@@ -134,13 +141,14 @@ const KanbanBoard = memo(() => {
}, []);
const handleCreateTask = useCallback(() => {
+ if (!canEditTask) return;
createTaskModal({
onCreated: (task) => {
navigate(taskDetailPath(task.identifier, task.agentId));
},
showInlineToggle: false,
});
- }, [navigate]);
+ }, [canEditTask, navigate]);
const handleHideColumn = useCallback(
(columnKey: string) => {
@@ -213,7 +221,7 @@ const KanbanBoard = memo(() => {
return (
<DndContext
collisionDetection={pointerWithin}
- sensors={sensors}
+ sensors={canEditTask ? sensors : []}
onDragCancel={handleDragCancel}
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
@@ -224,7 +232,7 @@ const KanbanBoard = memo(() => {
return (
<KanbanColumn
columnKey={col.key}
- droppable={col.droppable}
+ droppable={canEditTask && col.droppable}
key={col.key}
tasks={(group?.tasks ?? []) as TaskListItem[]}
total={group?.total ?? 0}
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 830be95ce30..0b11a1af18f 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -14,6 +14,7 @@ import {
getAttachmentFileIdsFromEditor,
pickAndInsertAttachments,
} from '@/features/EditorCanvas/editorAttachments';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useTaskStore } from '@/store/task';
@@ -36,6 +37,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
({ agentId, onCreated, showInlineToggle = true }) => {
const { t } = useTranslation('chat');
const { close } = useModalContext();
+ const { allowed: canCreateTask, reason } = usePermission('create_content');
const createTask = useTaskStore((s) => s.createTask);
const isCreating = useTaskStore((s) => s.isCreatingTask);
@@ -56,15 +58,17 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
}, [close, updateSystemStatus]);
const handleContentChange = useCallback(() => {
+ if (!canCreateTask) return;
if (!editor) return;
instructionRef.current = String(editor.getDocument('markdown') ?? '');
- }, [editor]);
+ }, [canCreateTask, editor]);
const handleAttach = useCallback(() => {
pickAndInsertAttachments(editor);
}, [editor]);
const handleSubmit = useCallback(async () => {
+ if (!canCreateTask) return;
const instruction = instructionRef.current.trim();
const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;
if (!instruction && !title.trim() && !hasFiles) return;
@@ -86,7 +90,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
identifier: result.identifier,
});
}
- }, [assigneeAgentId, close, createTask, editor, onCreated, priority, title]);
+ }, [assigneeAgentId, canCreateTask, close, createTask, editor, onCreated, priority, title]);
const handleSubmitRef = useRef(handleSubmit);
useEffect(() => {
@@ -106,7 +110,8 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
<Flexbox horizontal style={{ padding: '16px 24px 0' }}>
<Flexbox flex={1} style={{ minHeight: 180 }}>
<input
- autoFocus
+ autoFocus={canCreateTask}
+ disabled={!canCreateTask}
placeholder={t('createTask.titlePlaceholder')}
value={title}
style={{
@@ -124,6 +129,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
onChange={(e) => setTitle(e.target.value)}
/>
<EditorCanvas
+ disabled={!canCreateTask}
editor={editor}
floatingToolbar={false}
placeholder={t('createTask.instructionPlaceholder')}
@@ -205,10 +211,11 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
</Flexbox>
<Button
- disabled={isCreating}
+ disabled={!canCreateTask || isCreating}
loading={isCreating}
shape={'round'}
size={'small'}
+ title={canCreateTask ? undefined : reason}
type={'primary'}
onClick={handleSubmit}
>
diff --git a/src/features/AgentTasks/features/AgentTaskCardList.tsx b/src/features/AgentTasks/features/AgentTaskCardList.tsx
index 412fe985169..075dd6b9eef 100644
--- a/src/features/AgentTasks/features/AgentTaskCardList.tsx
+++ b/src/features/AgentTasks/features/AgentTaskCardList.tsx
@@ -1,8 +1,8 @@
import { Block, Flexbox } from '@lobehub/ui';
import { Divider } from 'antd';
import { Fragment, memo, useCallback, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
@@ -13,7 +13,7 @@ import TaskListHeader from './TaskListHeader';
const AgentTaskCardList = memo(() => {
const agentId = useAgentStore((s) => s.activeAgentId);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
useFetchTaskList({ agentId });
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 2a934f2c6af..9d6ffcd4375 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -2,8 +2,8 @@ import type { TaskStatus } from '@lobechat/types';
import { Block, ContextMenuTrigger, Flexbox, Text } from '@lobehub/ui';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useTaskStore } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
@@ -47,7 +47,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
const taskDetail = useTaskStore((s) => s.taskDetailMap[task.identifier]);
const { items: contextMenuItems, onContextMenu: handleContextMenuOpen } =
useTaskItemContextMenu(task);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const time = formatTaskItemDate(task.updatedAt || task.createdAt, {
formatOtherYear: t('time.formatOtherYear'),
diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
index 10432d5d183..0c4edbbecc0 100644
--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import AgentItem from '@/features/PageEditor/Copilot/AgentSelector/AgentItem';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useHomeStore } from '@/store/home';
@@ -53,6 +54,7 @@ const triggerStyle: CSSProperties = {
const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
({ children, currentAgentId, disabled, onChange, taskIdentifier }) => {
const { t } = useTranslation(['chat', 'common']);
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const [key, setKey] = useState(0);
const [search, setSearch] = useState('');
const [activeIndex, setActiveIndex] = useState(0);
@@ -108,6 +110,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
const handleAgentChange = useCallback(
(agentId: string) => {
+ if (!canEditTask) return;
if (agentId === currentAgentId) return;
setKey((k) => k + 1);
setSearch('');
@@ -119,7 +122,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
void updateTask(taskIdentifier, { assigneeAgentId: agentId });
}
},
- [currentAgentId, onChange, taskIdentifier, updateTask],
+ [canEditTask, currentAgentId, onChange, taskIdentifier, updateTask],
);
const handleSearchKeyDown = useCallback(
@@ -148,8 +151,9 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
active?.scrollIntoView({ block: 'nearest' });
}, [activeIndex]);
- const trigger = disabled ? (
- <Tooltip title={t('taskDetail.reassignDisabled', { ns: 'chat' })}>
+ const blocked = disabled || !canEditTask;
+ const trigger = blocked ? (
+ <Tooltip title={disabled ? t('taskDetail.reassignDisabled', { ns: 'chat' }) : reason}>
<div
style={{ ...triggerStyle, cursor: 'not-allowed', opacity: 0.5 }}
onClick={(e) => e.stopPropagation()}
@@ -165,7 +169,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
return (
<Popover
- disabled={disabled}
+ disabled={blocked}
key={key}
placement="bottomLeft"
styles={{ content: { padding: 0, width: 260 } }}
diff --git a/src/features/AgentTasks/features/TaskPriorityTag.tsx b/src/features/AgentTasks/features/TaskPriorityTag.tsx
index 7e5dcf742aa..f66ef488e71 100644
--- a/src/features/AgentTasks/features/TaskPriorityTag.tsx
+++ b/src/features/AgentTasks/features/TaskPriorityTag.tsx
@@ -6,6 +6,7 @@ import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import PriorityHighIcon from './icons/PriorityHighIcon';
@@ -53,6 +54,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
color: ${cssVar.orange};
`,
+ triggerDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ &:hover {
+ color: ${cssVar.colorTextDescription};
+ filter: none;
+ }
+ `,
}));
interface TaskPriorityTagProps {
@@ -69,6 +79,7 @@ const TaskPriorityTag = memo<TaskPriorityTagProps>(
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const { t } = useTranslation('chat');
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const updateTask = useTaskStore((s) => s.updateTask);
const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
@@ -77,6 +88,7 @@ const TaskPriorityTag = memo<TaskPriorityTagProps>(
const handlePriorityChange = useCallback(
async (nextPriority: number) => {
+ if (!canEditTask) return;
if (nextPriority === currentLevel) return;
if (onChange) {
onChange(nextPriority);
@@ -88,7 +100,7 @@ const TaskPriorityTag = memo<TaskPriorityTagProps>(
await refreshTaskList();
setLoading(false);
},
- [currentLevel, onChange, refreshTaskList, taskIdentifier, updateTask],
+ [canEditTask, currentLevel, onChange, refreshTaskList, taskIdentifier, updateTask],
);
const handlePriorityChangeRef = useRef(handlePriorityChange);
@@ -156,6 +168,19 @@ const TaskPriorityTag = memo<TaskPriorityTagProps>(
if (disableDropdown) return <>{triggerNode}</>;
+ if (!canEditTask)
+ return (
+ <Tooltip title={reason}>
+ <span
+ className={styles.triggerDisabled}
+ style={{ display: 'inline-flex' }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ {triggerNode}
+ </span>
+ </Tooltip>
+ );
+
return (
<DropdownMenu items={menuItems} open={open} onOpenChange={setOpen}>
{triggerNode}
diff --git a/src/features/AgentTasks/features/TaskStatusTag.tsx b/src/features/AgentTasks/features/TaskStatusTag.tsx
index e49fe4297bb..1d09b260798 100644
--- a/src/features/AgentTasks/features/TaskStatusTag.tsx
+++ b/src/features/AgentTasks/features/TaskStatusTag.tsx
@@ -16,6 +16,7 @@ import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { renderMenuExtra } from './menuExtra';
@@ -90,6 +91,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
filter: brightness(0.85);
}
`,
+ triggerDisabled: css`
+ cursor: not-allowed;
+ display: inline-flex;
+ opacity: 0.5;
+
+ &:hover {
+ filter: none;
+ }
+ `,
}));
interface TaskStatusTagProps {
@@ -106,6 +116,7 @@ const TaskStatusTag = memo<TaskStatusTagProps>(
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const { t } = useTranslation('chat');
+ const { allowed: canEditTask, reason } = usePermission('create_content');
const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);
const displayStatus = status ?? 'backlog';
@@ -113,6 +124,7 @@ const TaskStatusTag = memo<TaskStatusTagProps>(
const handleStatusChange = useCallback(
async (nextStatus: TaskStatus) => {
+ if (!canEditTask) return;
if (nextStatus === displayStatus) return;
if (onChange) {
onChange(nextStatus);
@@ -127,7 +139,7 @@ const TaskStatusTag = memo<TaskStatusTagProps>(
setLoading(false);
}
},
- [displayStatus, onChange, taskIdentifier, updateTaskStatus],
+ [canEditTask, displayStatus, onChange, taskIdentifier, updateTaskStatus],
);
const handleStatusChangeRef = useRef(handleStatusChange);
@@ -182,6 +194,15 @@ const TaskStatusTag = memo<TaskStatusTagProps>(
if (disableDropdown) return <>{triggerNode}</>;
+ if (!canEditTask)
+ return (
+ <Tooltip title={reason}>
+ <span className={styles.triggerDisabled} onClick={(e) => e.stopPropagation()}>
+ {triggerNode}
+ </span>
+ </Tooltip>
+ );
+
return (
<DropdownMenu items={menuItems} open={open} onOpenChange={setOpen}>
{triggerNode}
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
new file mode 100644
index 00000000000..e72aff28904
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
@@ -0,0 +1,111 @@
+import { renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import React from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskItemContextMenu } from './useTaskItemContextMenu';
+
+const mocks = vi.hoisted(() => ({
+ copyToClipboard: vi.fn(),
+ deleteTask: vi.fn(),
+ messageSuccess: vi.fn(),
+ modalConfirm: vi.fn(),
+ refreshTaskList: vi.fn(),
+ runTask: vi.fn(),
+ transferItems: [
+ { key: 'transfer-task', label: 'Transfer to...' },
+ { key: 'copy-task', label: 'Copy to...' },
+ ],
+ updateTask: vi.fn(),
+ updateTaskStatus: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ closeContextMenu: vi.fn(),
+ copyToClipboard: mocks.copyToClipboard,
+ Flexbox: ({ children }: { children?: ReactNode }) => React.createElement('div', {}, children),
+ Icon: ({ icon: Icon }: { icon?: React.ComponentType }) =>
+ Icon ? React.createElement(Icon) : React.createElement('span'),
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: { success: mocks.messageSuccess },
+ modal: { confirm: mocks.modalConfirm },
+ }),
+ },
+}));
+
+vi.mock('@/business/client/hooks/useTaskTransferMenuItem', () => ({
+ useTaskTransferMenuItem: () => mocks.transferItems,
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://example.com',
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: { inboxAgentId: string }) => unknown) =>
+ selector({ inboxAgentId: 'inbox-agent' }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: {
+ inboxAgentId: (state: { inboxAgentId: string }) => state.inboxAgentId,
+ },
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (
+ selector: (state: {
+ deleteTask: typeof mocks.deleteTask;
+ refreshTaskList: typeof mocks.refreshTaskList;
+ runTask: typeof mocks.runTask;
+ updateTask: typeof mocks.updateTask;
+ updateTaskStatus: typeof mocks.updateTaskStatus;
+ }) => unknown,
+ ) =>
+ selector({
+ deleteTask: mocks.deleteTask,
+ refreshTaskList: mocks.refreshTaskList,
+ runTask: mocks.runTask,
+ updateTask: mocks.updateTask,
+ updateTaskStatus: mocks.updateTaskStatus,
+ }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { defaultValue?: ReactNode; ns?: string }) =>
+ options?.defaultValue ?? key,
+ }),
+}));
+
+describe('useTaskItemContextMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('does not render adjacent dividers around transfer actions', () => {
+ const { result } = renderHook(() =>
+ useTaskItemContextMenu({
+ identifier: 'T-1',
+ priority: 0,
+ status: 'backlog',
+ }),
+ );
+
+ const itemTypes = result.current.items.map((item) =>
+ item && typeof item === 'object' && 'type' in item ? item.type : 'item',
+ );
+
+ expect(
+ itemTypes.some((type, index) => type === 'divider' && itemTypes[index + 1] === 'divider'),
+ ).toBe(false);
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
index 27dc66e4378..875f46450dd 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
@@ -21,7 +21,9 @@ import {
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferMenuItem';
import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
@@ -58,6 +60,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
const appOrigin = useAppOrigin();
+ const { allowed: canEditTask } = usePermission('create_content');
const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);
const updateTask = useTaskStore((s) => s.updateTask);
@@ -73,6 +76,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
return useMemo<TaskContextMenuActions>(() => {
const triggerDelete = (identifier: string) => {
+ if (!canEditTask) return;
confirmModal({
content: t('taskDetail.deleteConfirm.content'),
okButtonProps: { danger: true },
@@ -96,8 +100,10 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
icon: <Icon color={meta.color} icon={meta.icon} />,
key: `status-${status}`,
label: t(`taskDetail.status.${status}`, { defaultValue: meta.label }),
+ disabled: !canEditTask,
onClick: ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
+ if (!canEditTask) return;
if (status === currentStatus) return;
void updateTaskStatus(task.identifier, status);
},
@@ -116,8 +122,10 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
),
key: `priority-${level}`,
label: t(`taskDetail.${meta.labelKey}` as never, { defaultValue: meta.label }),
+ disabled: !canEditTask,
onClick: async ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
+ if (!canEditTask) return;
if (level === currentPriority) return;
await updateTask(task.identifier, { priority: level });
await refreshTaskList();
@@ -138,8 +146,10 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
icon: <Icon icon={PlayIcon} />,
key: 'runNow',
label: t('taskList.contextMenu.runNow'),
+ disabled: !canEditTask,
onClick: async ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
+ if (!canEditTask) return;
if (!task.assigneeAgentId && inboxAgentId) {
await updateTask(task.identifier, { assigneeAgentId: inboxAgentId });
}
@@ -151,6 +161,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
: []),
{
children: statusChildren,
+ disabled: !canEditTask,
icon: <Icon icon={CircleDashedIcon} />,
key: 'status',
label: t('taskList.contextMenu.status'),
@@ -160,6 +171,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
},
{
children: priorityChildren,
+ disabled: !canEditTask,
icon: <Icon icon={BarChart3Icon} />,
key: 'priority',
label: t('taskList.contextMenu.priority'),
@@ -191,11 +203,13 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
{ type: 'divider' },
{
danger: true,
+ disabled: !canEditTask,
icon: <Icon icon={Trash2Icon} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
+ if (!canEditTask) return;
triggerDelete(task.identifier);
},
},
@@ -203,6 +217,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
};
const installKeyboardHandlers = (task: TaskContextMenuTarget) => {
+ if (!canEditTask) return;
cleanupRef.current?.();
activeSubmenuRef.current = null;
@@ -276,6 +291,7 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
return { buildItems, installKeyboardHandlers };
}, [
+ canEditTask,
message,
t,
appOrigin,
@@ -290,7 +306,39 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
export const useTaskItemContextMenu = (task: TaskContextMenuTarget): TaskItemContextMenu => {
const { buildItems, installKeyboardHandlers } = useTaskContextMenuActions();
- const items = useMemo(() => buildItems(task), [buildItems, task]);
+ const transferItems = useTaskTransferMenuItem(task.identifier) as ContextMenuItem[] | null;
+ const items = useMemo(() => {
+ const base = buildItems(task);
+ if (!transferItems || transferItems.length === 0) return base;
+
+ // Insert transfer/copy entries above the final divider + delete pair so
+ // they sit next to the other lifecycle actions but kept distinct from
+ // in-place state changes.
+ const deleteAnchor = base.findIndex(
+ (item) =>
+ item !== null &&
+ typeof item === 'object' &&
+ 'key' in item &&
+ (item as { key?: string }).key === 'delete',
+ );
+ if (deleteAnchor === -1) return [...base, ...transferItems];
+
+ const insertAt =
+ deleteAnchor > 0 &&
+ base[deleteAnchor - 1] !== null &&
+ typeof base[deleteAnchor - 1] === 'object' &&
+ 'type' in (base[deleteAnchor - 1] as object) &&
+ (base[deleteAnchor - 1] as { type?: string }).type === 'divider'
+ ? deleteAnchor - 1
+ : deleteAnchor;
+
+ return [
+ ...base.slice(0, insertAt),
+ ...transferItems,
+ { type: 'divider' } as ContextMenuItem,
+ ...base.slice(deleteAnchor),
+ ];
+ }, [buildItems, task, transferItems]);
const onContextMenu = useCallback(
() => installKeyboardHandlers(task),
[installKeyboardHandlers, task],
diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsx
index 4837825aafa..36570f2ea13 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx
@@ -3,9 +3,9 @@ import { Breadcrumb as AntBreadcrumb } from 'antd';
import { ChevronRight } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import { useShallow } from 'zustand/react/shallow';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useTaskStore } from '@/store/task';
import { styles } from './style';
@@ -49,11 +49,11 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
const ancestorCrumbs = ancestors.map(({ identifier, agentId }) => ({
key: identifier,
title: (
- <Link to={taskDetailPath(identifier, agentId ?? undefined)}>
+ <WorkspaceLink to={taskDetailPath(identifier, agentId ?? undefined)}>
<Text color={'inherit'} weight={500}>
{identifier}
</Text>
- </Link>
+ </WorkspaceLink>
),
}));
@@ -100,7 +100,11 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
separator={<Icon icon={ChevronRight} />}
items={[
{
- title: taskId ? <Link to={'/tasks'}>{allTasksLabel}</Link> : allTasksLabel,
+ title: taskId ? (
+ <WorkspaceLink to={'/tasks'}>{allTasksLabel}</WorkspaceLink>
+ ) : (
+ allTasksLabel
+ ),
},
...ancestorCrumbs,
...(currentTaskCrumb ? [currentTaskCrumb] : []),
diff --git a/src/features/ChangelogModal/index.tsx b/src/features/ChangelogModal/index.tsx
index f44c3155c7c..00118043c72 100644
--- a/src/features/ChangelogModal/index.tsx
+++ b/src/features/ChangelogModal/index.tsx
@@ -1,8 +1,8 @@
'use client';
import { memo, useEffect, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { lambdaClient } from '@/libs/trpc/client';
import { useGlobalStore } from '@/store/global';
@@ -11,7 +11,7 @@ const ChangelogModal = memo<{ currentId?: string }>(({ currentId: propCurrentId
s.status.latestChangelogId,
s.updateSystemStatus,
]);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [currentId, setCurrentId] = useState(propCurrentId);
useEffect(() => {
diff --git a/src/features/ChatInput/ActionBar/AgentMode/index.tsx b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
index e65ead5f3b4..68829a1538a 100644
--- a/src/features/ChatInput/ActionBar/AgentMode/index.tsx
+++ b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
import { useBusinessAgentModeSync } from '@/business/client/hooks/useBusinessAgentMode';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -65,6 +66,15 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillSecondary};
}
`,
+ buttonDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
option: css`
cursor: pointer;
@@ -111,6 +121,7 @@ const AgentMode = memo(() => {
const toggleAgentMode = useToggleAgentMode();
useBusinessAgentModeSync(agentId);
const [open, setOpen] = useState(false);
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
@@ -119,10 +130,21 @@ const AgentMode = memo(() => {
const handleSelect = useCallback(
async (mode: 'chat' | 'agent') => {
+ if (!canCreateContent) return;
+
setOpen(false);
await toggleAgentMode(mode === 'agent');
},
- [toggleAgentMode],
+ [canCreateContent, toggleAgentMode],
+ );
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!canCreateContent) return;
+
+ setOpen(nextOpen);
+ },
+ [canCreateContent],
);
const agentTooltip = (
@@ -188,23 +210,30 @@ const AgentMode = memo(() => {
);
const button = (
- <div className={styles.button}>
+ <div className={cx(styles.button, !canCreateContent && styles.buttonDisabled)}>
<Icon icon={CurrentIcon} size={14} />
<span>{t(`chatMode.${currentMode}`)}</span>
<Icon icon={ChevronDownIcon} size={12} />
</div>
);
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div>{button}</div>
+ </Tooltip>
+ );
+
return (
<Popover
content={popoverContent}
- open={open}
+ open={canCreateContent && open}
placement="bottomLeft"
trigger="click"
styles={{
content: { border: `1px solid ${cssVar.colorBorderSecondary}`, padding: 4 },
}}
- onOpenChange={setOpen}
+ onOpenChange={handleOpenChange}
>
<div>
{open ? (
diff --git a/src/features/ChatInput/ActionBar/Clear/index.tsx b/src/features/ChatInput/ActionBar/Clear/index.tsx
index 1f120012c09..a081d3dc9f7 100644
--- a/src/features/ChatInput/ActionBar/Clear/index.tsx
+++ b/src/features/ChatInput/ActionBar/Clear/index.tsx
@@ -4,6 +4,7 @@ import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
@@ -25,6 +26,7 @@ const Clear = memo(() => {
const clearCurrentMessages = useClearCurrentMessages();
const [confirmOpened, updateConfirmOpened] = useState(false);
const mobile = useIsMobile();
+ const { allowed: canCreate } = usePermission('create_content');
const actionTitle: any = confirmOpened ? void 0 : t('clearCurrentMessages', { ns: 'chat' });
@@ -33,7 +35,7 @@ const Clear = memo(() => {
return (
<Popconfirm
arrow={false}
- okButtonProps={{ danger: true, type: 'primary' }}
+ okButtonProps={{ danger: true, disabled: !canCreate, type: 'primary' }}
open={confirmOpened}
placement={popconfirmPlacement}
title={
@@ -41,8 +43,14 @@ const Clear = memo(() => {
{t('confirmClearCurrentMessages', { ns: 'chat' })}
</div>
}
- onConfirm={clearCurrentMessages}
- onOpenChange={updateConfirmOpened}
+ onConfirm={() => {
+ if (!canCreate) return;
+ clearCurrentMessages();
+ }}
+ onOpenChange={(open) => {
+ if (!canCreate && open) return;
+ updateConfirmOpened(open);
+ }}
>
<Action
icon={Eraser}
diff --git a/src/features/ChatInput/ActionBar/Memory/Controls.tsx b/src/features/ChatInput/ActionBar/Memory/Controls.tsx
index f6574800068..1e8baa70e48 100644
--- a/src/features/ChatInput/ActionBar/Memory/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Memory/Controls.tsx
@@ -9,6 +9,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import LevelSlider from '@/features/ModelSwitchPanel/components/ControlsForm/LevelSlider';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -63,6 +64,7 @@ const ToggleItem = memo<ToggleOption>(({ value, description, icon, label }) => {
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const isEnabled = useMemoryEnabled(agentId);
+ const { allowed: canCreate } = usePermission('create_content');
const isActive = value === 'on' ? isEnabled : !isEnabled;
@@ -72,7 +74,12 @@ const ToggleItem = memo<ToggleOption>(({ value, description, icon, label }) => {
align={'flex-start'}
className={cx(styles.option, isActive && styles.active)}
gap={12}
+ style={{
+ cursor: canCreate ? undefined : 'not-allowed',
+ opacity: canCreate ? undefined : 0.5,
+ }}
onClick={async () => {
+ if (!canCreate) return;
await updateAgentChatConfig({ memory: { enabled: value === 'on' } });
}}
>
@@ -92,6 +99,7 @@ const Controls = memo(() => {
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const isEnabled = useMemoryEnabled(agentId);
+ const { allowed: canCreate } = usePermission('create_content');
const effort = useAgentStore((s) => chatConfigByIdSelectors.getMemoryToolEffortById(agentId)(s));
const toggleOptions: ToggleOption[] = [
@@ -122,7 +130,13 @@ const Controls = memo(() => {
<div className={styles.title}>{t('memory.effort.title')}</div>
<div className={styles.description}>{t('memory.effort.desc')}</div>
</Flexbox>
- <Flexbox flex={1}>
+ <Flexbox
+ flex={1}
+ style={{
+ opacity: canCreate ? undefined : 0.5,
+ pointerEvents: canCreate ? undefined : 'none',
+ }}
+ >
<LevelSlider<UserMemoryEffort>
defaultValue="medium"
levels={MEMORY_EFFORT_LEVELS}
@@ -133,6 +147,7 @@ const Controls = memo(() => {
2: t('memory.effort.high.title'),
}}
onChange={async (value) => {
+ if (!canCreate) return;
await updateAgentChatConfig({ memory: { effort: value, enabled: true } });
}}
/>
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index b2640dc4c4a..ff69cf1b698 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -1,10 +1,11 @@
import { ModelIcon } from '@lobehub/icons';
-import { Center } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
+import { Center, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
import { memo, useCallback } from 'react';
import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -15,6 +16,20 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
icon: css`
transition: scale 400ms cubic-bezier(0.215, 0.61, 0.355, 1);
`,
+ modelDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ :hover {
+ background: transparent;
+ }
+
+ :active {
+ div {
+ scale: 1;
+ }
+ }
+ `,
model: css`
cursor: pointer;
border-radius: 24px;
@@ -35,6 +50,7 @@ const ModelSwitch = memo(() => {
const { actionSize, dropdownPlacement } = useActionBarContext();
const blockSize = actionSize?.blockSize ?? 32;
const iconSize = actionSize?.size ?? 20;
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const agentId = useAgentId();
const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
@@ -46,11 +62,32 @@ const ModelSwitch = memo(() => {
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
+ if (!canCreateContent) return;
+
await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));
},
- [agentId, applyBusinessModelModeConfig, updateAgentConfigById],
+ [agentId, applyBusinessModelModeConfig, canCreateContent, updateAgentConfigById],
);
+ const trigger = (
+ <Center
+ className={cx(styles.model, !canCreateContent && styles.modelDisabled)}
+ height={blockSize}
+ width={blockSize}
+ >
+ <div className={styles.icon}>
+ <ModelIcon model={model} size={iconSize} />
+ </div>
+ </Center>
+ );
+
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div>{trigger}</div>
+ </Tooltip>
+ );
+
return (
<ModelSwitchPanel
model={model}
@@ -58,11 +95,7 @@ const ModelSwitch = memo(() => {
provider={provider}
onModelChange={handleModelChange}
>
- <Center className={styles.model} height={blockSize} width={blockSize}>
- <div className={styles.icon}>
- <ModelIcon model={model} size={iconSize} />
- </div>
- </Center>
+ {trigger}
</ModelSwitchPanel>
);
});
diff --git a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
index 10c7bd716dd..5def6d1dff4 100644
--- a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
+++ b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
@@ -1,10 +1,11 @@
-import { Center, Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
+import { Center, Flexbox, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -34,10 +35,19 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillTertiary};
}
`,
+ triggerDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ :hover {
+ background: transparent;
+ }
+ `,
}));
const ModelLabel = memo(() => {
const { dropdownPlacement } = useActionBarContext();
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const agentId = useAgentId();
const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
@@ -52,11 +62,34 @@ const ModelLabel = memo(() => {
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
+ if (!canCreateContent) return;
+
await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));
},
- [agentId, applyBusinessModelModeConfig, updateAgentConfigById],
+ [agentId, applyBusinessModelModeConfig, canCreateContent, updateAgentConfigById],
);
+ const trigger = (
+ <Center
+ horizontal
+ className={cx(styles.trigger, !canCreateContent && styles.triggerDisabled)}
+ height={28}
+ paddingInline={6}
+ >
+ <Flexbox horizontal align={'center'} gap={2}>
+ <span className={styles.name}>{displayName}</span>
+ <ChevronDownIcon className={styles.chevron} size={12} />
+ </Flexbox>
+ </Center>
+ );
+
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div>{trigger}</div>
+ </Tooltip>
+ );
+
return (
<ModelSwitchPanel
model={model}
@@ -65,12 +98,7 @@ const ModelLabel = memo(() => {
provider={provider}
onModelChange={handleModelChange}
>
- <Center horizontal className={styles.trigger} height={28} paddingInline={6}>
- <Flexbox horizontal align={'center'} gap={2}>
- <span className={styles.name}>{displayName}</span>
- <ChevronDownIcon className={styles.chevron} size={12} />
- </Flexbox>
- </Center>
+ {trigger}
</ModelSwitchPanel>
);
});
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index d3140f1a5ec..b81724b1da3 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -13,6 +13,7 @@ import type { PartialDeep } from 'type-fest';
import InfoTooltip from '@/components/InfoTooltip';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -476,17 +477,19 @@ const SectionHeader = memo<SectionHeaderProps>(({ onToggle, open, title }) => (
));
interface SliderFieldProps extends SliderConfig {
+ disabled?: boolean;
inputWidth?: number;
onChange: (value: number) => void;
value?: number;
}
const SliderField = memo<SliderFieldProps>(
- ({ value, onChange, min, max, step, unlimitedInput, inputWidth = 56 }) => (
+ ({ value, disabled, onChange, min, max, step, unlimitedInput, inputWidth = 56 }) => (
<SliderWithInput
changeOnWheel
className={styles.slider}
controls={false}
+ disabled={disabled}
gap={10}
max={max}
min={min}
@@ -509,6 +512,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
const { t } = useTranslation(['setting', 'components']);
const agentId = useAgentId();
const { updateAgentConfig } = useUpdateAgentConfig();
+ const { allowed: canCreate } = usePermission('create_content');
const config = useAgentStore(
(s) => agentByIdSelectors.getAgentConfigById(agentId)(s) || DEFAULT_AGENT_CONFIG,
@@ -613,6 +617,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
const handleToggle = useCallback(
async (key: ParamKey, enabled: boolean) => {
+ if (!canCreate) return;
const namePath = PARAM_NAME_MAP[key];
let newValue: number | undefined;
@@ -663,12 +668,13 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
setUpdating(false);
}
},
- [form, refreshFormValues, setUpdating, updateAgentConfig],
+ [canCreate, form, refreshFormValues, setUpdating, updateAgentConfig],
);
const handleValuesChange = useMemo(
() =>
debounce(async (values: PartialDeep<LobeAgentConfig>) => {
+ if (!canCreate) return;
setUpdating(true);
try {
await updateAgentConfig(values);
@@ -676,11 +682,12 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
setUpdating(false);
}
}, 500),
- [updateAgentConfig, setUpdating],
+ [canCreate, updateAgentConfig, setUpdating],
);
const handleFieldChange = useCallback(
(namePath: (string | number)[], value: boolean | number | string) => {
+ if (!canCreate) return;
form.setFieldValue(namePath, value);
if (
namePath[0] === 'params' &&
@@ -693,7 +700,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
refreshFormValues((current) => current + 1);
handleValuesChange(form.getFieldsValue(true) as PartialDeep<LobeAgentConfig>);
},
- [form, handleValuesChange, refreshFormValues],
+ [canCreate, form, handleValuesChange, refreshFormValues],
);
const handleAdvancedOpenChange = useCallback(() => {
@@ -732,6 +739,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
action={
<Switch
checked={Boolean(enableContextCompression)}
+ disabled={!canCreate}
size={'small'}
onChange={(checked) => {
handleFieldChange(['chatConfig', 'enableContextCompression'], checked);
@@ -746,6 +754,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
action={
<Switch
checked={Boolean(enableHistoryCount)}
+ disabled={!canCreate}
size={'small'}
onChange={(checked) => {
handleFieldChange(['chatConfig', 'enableHistoryCount'], checked);
@@ -756,6 +765,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
{enableHistoryCount && (
<SliderField
unlimitedInput
+ disabled={!canCreate}
inputWidth={56}
max={20}
min={0}
@@ -840,6 +850,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
{modelConfigOpen && (
<div className={styles.modelConfigSection}>
<ControlsForm
+ disabled={!canCreate}
model={agentModel}
provider={agentProvider}
onUpdatingChange={setUpdating}
@@ -872,6 +883,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
action={
<Switch
checked={enabled}
+ disabled={!canCreate}
size={'small'}
onChange={(checked) => {
handleToggle(key, checked);
@@ -881,6 +893,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
>
{enabled && (
<SliderField
+ disabled={!canCreate}
value={form.getFieldValue(PARAM_NAME_MAP[key])}
onChange={(value) => {
handleFieldChange(PARAM_NAME_MAP[key], value);
@@ -898,6 +911,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
action={
<Switch
checked={Boolean(enableMaxTokens)}
+ disabled={!canCreate}
size={'small'}
onChange={(checked) => {
if (checked && typeof maxTokensValue !== 'number') {
@@ -911,6 +925,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
{enableMaxTokens && (
<SliderField
unlimitedInput
+ disabled={!canCreate}
inputWidth={64}
max={32_000}
min={0}
diff --git a/src/features/ChatInput/ActionBar/SaveTopic/index.tsx b/src/features/ChatInput/ActionBar/SaveTopic/index.tsx
index 7475aad4c78..e578185737a 100644
--- a/src/features/ChatInput/ActionBar/SaveTopic/index.tsx
+++ b/src/features/ChatInput/ActionBar/SaveTopic/index.tsx
@@ -1,11 +1,12 @@
import { HotkeyEnum } from '@lobechat/const/hotkeys';
-import { ActionIcon, Flexbox, Hotkey } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Hotkey, Tooltip } from '@lobehub/ui';
import { Popconfirm } from 'antd';
import { LucideGalleryVerticalEnd, LucideMessageSquarePlus } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { useActionSWR } from '@/libs/swr';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
@@ -14,6 +15,7 @@ import { settingsSelectors } from '@/store/user/selectors';
const SaveTopic = memo(() => {
const { t } = useTranslation('chat');
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SaveTopic));
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const [hasTopic, openNewTopicOrSaveTopic] = useChatStore((s) => [
!!s.activeTopicId,
s.openNewTopicOrSaveTopic,
@@ -28,12 +30,27 @@ const SaveTopic = memo(() => {
const icon = hasTopic ? LucideMessageSquarePlus : LucideGalleryVerticalEnd;
const desc = t(hasTopic ? 'topic.openNewTopic' : 'topic.saveCurrentMessages');
+ const handleMutate = useCallback(() => {
+ if (!canCreateContent) return;
+
+ mutate();
+ }, [canCreateContent, mutate]);
+
+ const handleConfirmOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!canCreateContent) return;
+
+ setConfirmOpened(nextOpen);
+ },
+ [canCreateContent],
+ );
+
if (mobile) {
return (
<Popconfirm
arrow={false}
okButtonProps={{ danger: false, type: 'primary' }}
- open={confirmOpened}
+ open={canCreateContent && confirmOpened}
placement={'top'}
title={
<Flexbox horizontal align={'center'} style={{ marginBottom: 8 }}>
@@ -43,30 +60,36 @@ const SaveTopic = memo(() => {
<Hotkey keys={hotkey} />
</Flexbox>
}
- onConfirm={() => mutate()}
- onOpenChange={setConfirmOpened}
+ onConfirm={handleMutate}
+ onOpenChange={handleConfirmOpenChange}
>
- <ActionIcon
- aria-label={desc}
- icon={icon}
- loading={isValidating}
- onClick={() => setConfirmOpened(true)}
- />
+ <Tooltip title={canCreateContent ? desc : reason}>
+ <div>
+ <ActionIcon
+ aria-label={desc}
+ disabled={!canCreateContent}
+ icon={icon}
+ loading={isValidating}
+ onClick={() => handleConfirmOpenChange(true)}
+ />
+ </div>
+ </Tooltip>
</Popconfirm>
);
} else {
return (
<ActionIcon
aria-label={desc}
+ disabled={!canCreateContent}
icon={icon}
loading={isValidating}
size={{ blockSize: 32, size: 16, strokeWidth: 2.3 }}
- title={desc}
+ title={canCreateContent ? desc : reason}
variant={'outlined'}
tooltipProps={{
hotkey,
}}
- onClick={() => mutate()}
+ onClick={handleMutate}
/>
);
}
diff --git a/src/features/ChatInput/ActionBar/Search/Controls.tsx b/src/features/ChatInput/ActionBar/Search/Controls.tsx
index e04cd8928cd..38cb67b254f 100644
--- a/src/features/ChatInput/ActionBar/Search/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Search/Controls.tsx
@@ -7,6 +7,7 @@ import { SparkleIcon } from 'lucide-react';
import { memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -68,6 +69,7 @@ const Item = memo<NetworkOption>(({ value, description, icon, label }) => {
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const mode = useAgentStore((s) => chatConfigByIdSelectors.getSearchModeById(agentId)(s));
+ const { allowed: canCreate } = usePermission('create_content');
return (
<Flexbox
@@ -76,7 +78,12 @@ const Item = memo<NetworkOption>(({ value, description, icon, label }) => {
className={cx(styles.option, mode === value && styles.active)}
gap={12}
key={value}
+ style={{
+ cursor: canCreate ? undefined : 'not-allowed',
+ opacity: canCreate ? undefined : 0.5,
+ }}
onClick={async () => {
+ if (!canCreate) return;
await updateAgentChatConfig({ searchMode: value });
}}
>
@@ -95,6 +102,7 @@ const Controls = memo(() => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const { allowed: canCreate } = usePermission('create_content');
const [model, provider, useModelBuiltinSearch, searchMode] = useAgentStore((s) => [
agentByIdSelectors.getAgentModelById(agentId)(s),
@@ -118,10 +126,11 @@ const Controls = memo(() => {
);
useEffect(() => {
+ if (!canCreate) return;
if (isModelBuiltinSearchInternal && (searchMode ?? 'auto') === 'off') {
updateAgentChatConfig({ searchMode: 'auto' });
}
- }, [isModelBuiltinSearchInternal, searchMode, updateAgentChatConfig]);
+ }, [canCreate, isModelBuiltinSearchInternal, searchMode, updateAgentChatConfig]);
const options: NetworkOption[] = isModelBuiltinSearchInternal
? [
@@ -164,8 +173,8 @@ const Controls = memo(() => {
<Item {...option} key={option.value} />
))}
{showDivider && <Divider style={{ margin: 0 }} />}
- {showModelBuiltinSearch && <ModelBuiltinSearch />}
- {showFCSearchModel && <FCSearchModel />}
+ {showModelBuiltinSearch && <ModelBuiltinSearch disabled={!canCreate} />}
+ {showFCSearchModel && <FCSearchModel disabled={!canCreate} />}
</Flexbox>
);
});
diff --git a/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx b/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
index 8a2e8578246..6719770cf00 100644
--- a/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
+++ b/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
@@ -33,7 +33,11 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const FCSearchModel = memo(() => {
+interface FCSearchModelProps {
+ disabled?: boolean;
+}
+
+const FCSearchModel = memo<FCSearchModelProps>(({ disabled }) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
@@ -47,12 +51,14 @@ const FCSearchModel = memo(() => {
<InfoTooltip title={t('search.searchModel.desc')} />
</Flexbox>
<FunctionCallingModelSelect
+ disabled={disabled}
value={searchFCModel}
style={{
maxWidth: 160,
width: 160,
}}
onChange={async (value) => {
+ if (disabled) return;
await updateAgentChatConfig({ searchFCModel: value });
}}
/>
diff --git a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
index 0cdb9502814..01e1b73dfbc 100644
--- a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
+++ b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
@@ -32,7 +32,11 @@ const SearchEngineIcon = ({ icon }: SearchEngineIconProps) => {
}
};
-const ModelBuiltinSearch = memo(() => {
+interface ModelBuiltinSearchProps {
+ disabled?: boolean;
+}
+
+const ModelBuiltinSearch = memo<ModelBuiltinSearchProps>(({ disabled }) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
@@ -51,8 +55,13 @@ const ModelBuiltinSearch = memo(() => {
align={'center'}
justify={'space-between'}
padding={'8px 12px'}
- style={{ cursor: 'pointer', userSelect: 'none' }}
+ style={{
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.5 : undefined,
+ userSelect: 'none',
+ }}
onClick={async () => {
+ if (disabled) return;
setLoading(true);
await updateAgentChatConfig({ useModelBuiltinSearch: !checked });
setLoading(false);
@@ -62,7 +71,7 @@ const ModelBuiltinSearch = memo(() => {
<SearchEngineIcon icon={modelCard?.settings?.searchProvider} />
{t('search.mode.useModelBuiltin')}
</Flexbox>
- <Switch checked={checked} loading={isLoading} size={'small'} />
+ <Switch checked={checked} disabled={disabled} loading={isLoading} size={'small'} />
</Flexbox>
);
});
diff --git a/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
index a5a8e41c5b7..09f76574ffe 100644
--- a/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
@@ -3,6 +3,7 @@ import { Loader2, SquareArrowOutUpRight } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useToolStore } from '@/store/tool';
@@ -39,6 +40,8 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
const [isConnecting, setIsConnecting] = useState(false);
const [isToggling, setIsToggling] = useState(false);
const [isWaitingAuth, setIsWaitingAuth] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const oauthWindowRef = useRef<Window | null>(null);
const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -192,7 +195,7 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
);
const handleConnect = async () => {
- if (!userId) {
+ if (!canCreate || !canEdit || !userId) {
return;
}
@@ -229,7 +232,7 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
};
const handleToggle = async () => {
- if (!server) return;
+ if (!canEdit || !server) return;
setIsToggling(true);
await togglePlugin(pluginId);
setIsToggling(false);
@@ -253,9 +256,10 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
horizontal
align="center"
gap={4}
- style={{ cursor: 'pointer', opacity: 0.65 }}
+ style={{ cursor: canCreate && canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
onClick={(e) => {
e.stopPropagation();
+ if (!canCreate || !canEdit) return;
handleConnect();
}}
>
@@ -275,8 +279,10 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
return (
<Checkbox
checked={checked}
+ disabled={!canEdit}
onClick={(e) => {
e.stopPropagation();
+ if (!canEdit) return;
handleToggle();
}}
/>
@@ -296,9 +302,10 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
horizontal
align="center"
gap={4}
- style={{ cursor: 'pointer', opacity: 0.65 }}
+ style={{ cursor: canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
onClick={(e) => {
e.stopPropagation();
+ if (!canEdit) return;
// Click to reopen OAuth window
if (server.oauthUrl) {
openOAuthWindow(server.oauthUrl, server.identifier);
@@ -332,7 +339,7 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
onClick={(e) => {
e.stopPropagation();
// If connected, clicking the row toggles state
- if (server?.status === KlavisServerStatus.CONNECTED) {
+ if (canEdit && server?.status === KlavisServerStatus.CONNECTED) {
handleToggle();
}
}}
diff --git a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
index be1ccf6cf20..ad4a75dd441 100644
--- a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
@@ -3,6 +3,7 @@ import { Loader2, SquareArrowOutUpRight } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useToolStore } from '@/store/tool';
@@ -33,6 +34,8 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
const [isConnecting, setIsConnecting] = useState(false);
const [isToggling, setIsToggling] = useState(false);
const [isWaitingAuth, setIsWaitingAuth] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const oauthWindowRef = useRef<Window | null>(null);
const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -182,7 +185,7 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState())
?.plugins || [];
const isAlreadyEnabled = currentAgentPlugins.includes(newPluginId);
- if (!isAlreadyEnabled) {
+ if (canEdit && !isAlreadyEnabled) {
console.info('[LobehubSkill] Auto-enabling plugin:', newPluginId);
togglePlugin(newPluginId);
}
@@ -192,9 +195,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
- }, [provider, cleanup, checkStatus, togglePlugin, effectiveAgentId]);
+ }, [canEdit, provider, cleanup, checkStatus, togglePlugin, effectiveAgentId]);
const handleConnect = async () => {
+ if (!canCreate || !canEdit) return;
// Only block reconnection when already connected
if (server?.isConnected) return;
@@ -215,7 +219,7 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
};
const handleToggle = async () => {
- if (!server) return;
+ if (!canEdit || !server) return;
setIsToggling(true);
await togglePlugin(pluginId);
setIsToggling(false);
@@ -236,9 +240,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
horizontal
align="center"
gap={4}
- style={{ cursor: 'pointer', opacity: 0.65 }}
+ style={{ cursor: canCreate && canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
onClick={(e) => {
e.stopPropagation();
+ if (!canCreate || !canEdit) return;
handleConnect();
}}
>
@@ -256,8 +261,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
return (
<Checkbox
checked={checked}
+ disabled={!canEdit}
onClick={(e) => {
e.stopPropagation();
+ if (!canEdit) return;
handleToggle();
}}
/>
@@ -276,9 +283,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
horizontal
align="center"
gap={4}
- style={{ cursor: 'pointer', opacity: 0.65 }}
+ style={{ cursor: canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
onClick={async (e) => {
e.stopPropagation();
+ if (!canEdit) return;
try {
const redirectUri = window.location.protocol.startsWith('http')
? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider)}`
@@ -301,9 +309,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
horizontal
align="center"
gap={4}
- style={{ cursor: 'pointer', opacity: 0.65 }}
+ style={{ cursor: canCreate && canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
onClick={(e) => {
e.stopPropagation();
+ if (!canCreate || !canEdit) return;
handleConnect();
}}
>
@@ -333,7 +342,7 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
justify={'space-between'}
onClick={(e) => {
e.stopPropagation();
- if (server?.status === LobehubSkillStatus.CONNECTED) {
+ if (canEdit && server?.status === LobehubSkillStatus.CONNECTED) {
handleToggle();
}
}}
diff --git a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
index 0702c0e232a..04663361caa 100644
--- a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
@@ -4,7 +4,8 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { Pin, Settings, Store, Zap } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { ScrollSignalProvider } from './ScrollSignalContext';
import SkillActivateMode from './SkillActivateMode';
@@ -124,7 +125,7 @@ interface PopoverContentProps {
const PopoverContent = memo<PopoverContentProps>(
({ autoCount, items, onOpenStore, pinnedCount }) => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [searchKeyword, setSearchKeyword] = useState('');
const { close: closePopover } = usePopoverContext();
diff --git a/src/features/ChatInput/ActionBar/Tools/ToolItem.tsx b/src/features/ChatInput/ActionBar/Tools/ToolItem.tsx
index 6cb71d7ba87..5ac95ad8dda 100644
--- a/src/features/ChatInput/ActionBar/Tools/ToolItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/ToolItem.tsx
@@ -6,11 +6,12 @@ import DebugNode from '@/components/DebugNode';
import type { CheckboxItemProps } from '../components/CheckboxWithLoading';
import CheckboxItem from '../components/CheckboxWithLoading';
-const ToolItem = memo<CheckboxItemProps>(({ id, onUpdate, label, checked }) => {
+const ToolItem = memo<CheckboxItemProps>(({ id, onUpdate, label, checked, disabled }) => {
return (
<Suspense fallback={<DebugNode trace="ActionBar/Tools/ToolItem" />}>
<CheckboxItem
checked={checked}
+ disabled={disabled}
hasPadding={false}
id={id}
label={
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index d73112326ed..f50ebb78ca5 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -28,12 +28,13 @@ import {
import type { ReactNode } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import DevModal from '@/features/PluginDevModal';
import { createSkillStoreModal } from '@/features/SkillStore';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -194,6 +195,12 @@ const styles = createStaticStyles(({ css }) => ({
color: ${cssVar.colorTextSecondary};
background: ${cssVar.colorFillTertiary};
}
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ background: transparent;
+ }
`,
deleteButton: css`
cursor: pointer;
@@ -220,6 +227,12 @@ const styles = createStaticStyles(({ css }) => ({
&:hover {
background: ${cssVar.colorErrorBg};
}
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ background: transparent;
+ }
`,
deleteDivider: css`
height: 1px;
@@ -266,6 +279,12 @@ const styles = createStaticStyles(({ css }) => ({
&:hover {
background: ${cssVar.colorFillTertiary};
}
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ background: transparent;
+ }
`,
policyItemIcon: css`
display: flex;
@@ -381,13 +400,14 @@ const styles = createStaticStyles(({ css }) => ({
export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } = {}) => {
const { t } = useTranslation('setting');
const agentId = useAgentId();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const [pinnedOpen, setPinnedOpen] = useState(true);
const [autoOpen, setAutoOpen] = useState(true);
const [policyOpenId, setPolicyOpenId] = useState<string | null>(null);
const [searchKeyword, setSearchKeyword] = useState('');
const [autoModeLoading, setAutoModeLoading] = useState(false);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
const [
uninstallPlugin,
@@ -441,12 +461,13 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const updateSkillPolicy = useCallback(
async (id: string, mode: SkillPolicyMode) => {
+ if (!canEdit) return;
const shouldPin = mode === 'pinned';
if (checkedSet.has(id) === shouldPin) return;
await togglePlugin(id, shouldPin);
},
- [checkedSet, togglePlugin],
+ [canEdit, checkedSet, togglePlugin],
);
const openSkillPolicyMenu = useCallback((id: string) => {
@@ -471,9 +492,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const renderPolicyItem = (value: SkillPolicyMode, icon: ReactNode) => (
<button
className={cx(styles.policyItem)}
+ disabled={!canEdit}
type="button"
onClick={async (event) => {
event.stopPropagation();
+ if (!canEdit) return;
setPolicyOpenId(null);
await updateSkillPolicy(id, value);
}}
@@ -510,9 +533,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
{configureConfig && (
<button
className={cx(styles.policyItem)}
+ disabled={!canEdit}
type="button"
onClick={(event) => {
event.stopPropagation();
+ if (!canEdit) return;
setPolicyOpenId(null);
configureConfig.onConfigure();
}}
@@ -526,9 +551,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
{deleteConfig && (
<button
className={cx(styles.deleteButton)}
+ disabled={!canEdit}
type="button"
onClick={(event) => {
event.stopPropagation();
+ if (!canEdit) return;
setPolicyOpenId(null);
confirmModal({
content: t('tools.builtins.uninstallConfirm.desc', {
@@ -567,6 +594,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
<button
aria-label={t('tools.skillActivateMode.title')}
className={cx(styles.policyButton)}
+ disabled={!canEdit}
type="button"
onClick={(event) => {
event.stopPropagation();
@@ -596,7 +624,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
</Popover>
);
},
- [checkedSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
+ [canEdit, checkedSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
);
const renderToolLabel = useCallback(
@@ -1350,11 +1378,13 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
>
<Switch
checked={isAutoSkillMode}
+ disabled={!canEdit}
loading={autoModeLoading}
size="small"
onClick={(_, event) => event.stopPropagation()}
onChange={async (checked, event) => {
event?.stopPropagation?.();
+ if (!canEdit) return;
setAutoModeLoading(true);
try {
await updateAgentChatConfig({
@@ -1482,9 +1512,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={item.identifier}
label={item.meta?.title}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(item.identifier);
}}
/>
@@ -1541,9 +1573,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(skill.identifier);
}}
/>
@@ -1612,9 +1646,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={item.identifier}
label={item.title}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(item.identifier);
}}
/>
@@ -1657,9 +1693,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={item.identifier}
label={item.title}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(item.identifier);
}}
/>
@@ -1698,9 +1736,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(skill.identifier);
}}
/>
@@ -1735,9 +1775,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: (
<ToolItem
checked={true}
+ disabled={!canEdit}
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
+ if (!canEdit) return;
await togglePlugin(skill.identifier);
}}
/>
@@ -1776,6 +1818,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
lobehubSkillItems,
checked,
togglePlugin,
+ canEdit,
t,
]);
@@ -1786,6 +1829,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
value={editingCustomPlugin}
onValueChange={updateNewCustomPlugin}
onDelete={() => {
+ if (!canEdit) return;
if (editingPluginId) uninstallPlugin(editingPluginId);
setEditingPluginId(null);
}}
@@ -1793,6 +1837,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
if (!open) setEditingPluginId(null);
}}
onSave={async (devPlugin) => {
+ if (!canEdit) return;
await installCustomPlugin(devPlugin);
setEditingPluginId(null);
}}
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index f570d054718..dfdde978285 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -13,6 +13,7 @@ import FileIcon from '@/components/FileIcon';
import RepoIcon from '@/components/LibIcon';
import TipGuide from '@/components/TipGuide';
import { openAttachKnowledgeModal } from '@/features/LibraryModal';
+import { usePermission } from '@/hooks/usePermission';
import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -75,8 +76,22 @@ const FileUpload = memo(() => {
s.toggleKnowledgeBase,
]);
+ // Viewer doesn't have `file:upload` permission — backend would 403.
+ // Render the disabled paperclip with a tooltip so the entry stays visible
+ // (per disabled-not-hidden UX rule), but block the dropdown which would
+ // otherwise let users trigger the upload anyway.
+ const { allowed: canUpload, reason } = usePermission('create_content');
+
if (!enableKnowledgeBase) return null;
+ if (!canUpload) {
+ return (
+ <Tooltip title={reason}>
+ <Action disabled icon={Paperclip} showTooltip={false} title={t('upload.action.tooltip')} />
+ </Tooltip>
+ );
+ }
+
const uploadItems: ActionDropdownMenuItems = [
{
closeOnClick: false,
diff --git a/src/features/ChatInput/ActionBar/components/Action.tsx b/src/features/ChatInput/ActionBar/components/Action.tsx
index b91f586afcd..96e4c625b28 100644
--- a/src/features/ChatInput/ActionBar/components/Action.tsx
+++ b/src/features/ChatInput/ActionBar/components/Action.tsx
@@ -6,6 +6,7 @@ import { isUndefined } from 'es-toolkit/compat';
import { memo } from 'react';
import useMergeState from 'use-merge-value';
+import { usePermission } from '@/hooks/usePermission';
import { useServerConfigStore } from '@/store/serverConfig';
import { useActionBarContext } from '../context';
@@ -45,19 +46,28 @@ const Action = memo<ActionProps>(
});
const mobile = useServerConfigStore((s) => s.isMobile);
const { actionSize, dropdownPlacement } = useActionBarContext();
+ const { allowed: canUseChatInputAction, reason } = usePermission('create_content');
+ const blocked = disabled || !canUseChatInputAction;
+ const tooltipTitle = canUseChatInputAction ? title : reason;
const iconNode = (
<ActionIcon
- disabled={disabled}
+ disabled={blocked}
icon={icon}
loading={loading}
title={
- isUndefined(showTooltip) ? (mobile ? undefined : title) : showTooltip ? title : undefined
+ isUndefined(showTooltip)
+ ? mobile
+ ? undefined
+ : tooltipTitle
+ : showTooltip
+ ? tooltipTitle
+ : undefined
}
tooltipProps={{
placement: 'bottom',
}}
onClick={(e) => {
- if (disabled || loading) return;
+ if (blocked || loading) return;
if (onClick) return onClick(e);
setShow(true);
}}
@@ -72,7 +82,7 @@ const Action = memo<ActionProps>(
/>
);
- if (disabled) return iconNode;
+ if (blocked) return iconNode;
if (dropdown)
return (
diff --git a/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx b/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
index d9829a826db..fe9490448aa 100644
--- a/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
+++ b/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
@@ -5,6 +5,7 @@ import { memo, useState } from 'react';
export interface CheckboxItemProps {
checked?: boolean;
+ disabled?: boolean;
hasPadding?: boolean;
id: string;
label?: ReactNode;
@@ -13,11 +14,13 @@ export interface CheckboxItemProps {
}
const CheckboxItem = memo<CheckboxItemProps>(
- ({ id, onUpdate, label, checked, hasPadding = true, labelMaxWidth }) => {
+ ({ id, onUpdate, label, checked, disabled, hasPadding = true, labelMaxWidth }) => {
const [loading, setLoading] = useState(false);
const labelContent = label || id;
const updateState = async () => {
+ if (disabled) return;
+
setLoading(true);
await onUpdate(id, !checked);
setLoading(false);
@@ -39,6 +42,8 @@ const CheckboxItem = memo<CheckboxItemProps>(
}
onClick={async (e) => {
e.stopPropagation();
+ if (disabled) return;
+
updateState();
}}
>
@@ -61,8 +66,11 @@ const CheckboxItem = memo<CheckboxItemProps>(
) : (
<Checkbox
checked={checked}
+ disabled={disabled}
onClick={async (e) => {
e.stopPropagation();
+ if (disabled) return;
+
await updateState();
}}
/>
diff --git a/src/features/ChatInput/ControlBar/ApprovalMode.tsx b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
index 78e092710d5..1465ae8bcec 100644
--- a/src/features/ChatInput/ControlBar/ApprovalMode.tsx
+++ b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
@@ -6,6 +6,7 @@ import { type LucideIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { type ApprovalMode } from '@/store/user/slices/settings/selectors';
@@ -25,6 +26,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-size: ${cssVar.fontSizeSM};
color: ${cssVar.colorTextSecondary};
`,
+ modeButtonDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+ `,
title: css`
font-size: 14px;
font-weight: 500;
@@ -54,6 +59,7 @@ const ModeItemLabel = memo<{ desc: string; icon: LucideIcon; title: string }>(
const ModeSelector = memo(() => {
const { t } = useTranslation('chat');
const [dropdownOpen, setDropdownOpen] = useState(false);
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const updateHumanIntervention = useUserStore((s) => s.updateHumanIntervention);
@@ -68,9 +74,20 @@ const ModeSelector = memo(() => {
const handleModeChange = useCallback(
async (mode: ApprovalMode) => {
+ if (!canCreateContent) return;
+
await updateHumanIntervention({ approvalMode: mode });
},
- [updateHumanIntervention],
+ [canCreateContent, updateHumanIntervention],
+ );
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!canCreateContent) return;
+
+ setDropdownOpen(nextOpen);
+ },
+ [canCreateContent],
);
const menuItems = useMemo<MenuProps['items']>(
@@ -119,6 +136,7 @@ const ModeSelector = memo(() => {
<Button
className={styles.modeButton}
color={'default'}
+ disabled={!canCreateContent}
icon={ChevronDown}
iconPlacement="end"
size="small"
@@ -128,12 +146,19 @@ const ModeSelector = memo(() => {
</Button>
);
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div className={styles.modeButtonDisabled}>{button}</div>
+ </Tooltip>
+ );
+
return (
<DropdownMenu
items={menuItems}
- open={dropdownOpen}
+ open={canCreateContent && dropdownOpen}
placement="bottomRight"
- onOpenChange={setDropdownOpen}
+ onOpenChange={handleOpenChange}
>
<div className={styles.trigger}>
{dropdownOpen ? (
diff --git a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
index 648d954d30e..67d8166c2a9 100644
--- a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
@@ -1,12 +1,13 @@
'use client';
import { Github } from '@lobehub/icons';
-import { Flexbox, Icon, Popover } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
import { CheckIcon, ChevronDownIcon, SquircleDashed } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -34,6 +35,14 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillTertiary};
}
`,
+ buttonDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ &:hover {
+ background: transparent;
+ }
+ `,
checkIndicator: css`
display: flex;
flex: none;
@@ -101,6 +110,7 @@ interface CloudRepoSwitcherProps {
const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
// Incremented to trigger re-renders when the module-singleton pending selection changes.
const [, forceUpdate] = useState(0);
@@ -129,6 +139,8 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
const toggleRepo = useCallback(
async (repo: string) => {
+ if (!canCreateContent) return;
+
if (!activeTopicId) {
// No topic yet — buffer in the module singleton keyed by agentId.
// gateway.ts will read and consume this when the first message creates a topic.
@@ -152,7 +164,23 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
await updateTopicMetadata(activeTopicId, patch);
},
- [agentId, activeTopicId, currentWorkingDirectory, topicRepos, updateTopicMetadata],
+ [
+ agentId,
+ activeTopicId,
+ canCreateContent,
+ currentWorkingDirectory,
+ topicRepos,
+ updateTopicMetadata,
+ ],
+ );
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!canCreateContent) return;
+
+ setOpen(nextOpen);
+ },
+ [canCreateContent],
);
if (availableRepos.length === 0) return null;
@@ -201,20 +229,31 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
</Flexbox>
);
+ const button = (
+ <div className={cx(styles.button, !canCreateContent && styles.buttonDisabled)}>
+ {displayRepos.length > 0 ? <Github size={14} /> : <Icon icon={SquircleDashed} size={14} />}
+ <span>{buttonLabel}</span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
+
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div>{button}</div>
+ </Tooltip>
+ );
+
return (
<Popover
content={content}
- open={open}
+ open={canCreateContent && open}
placement="bottomLeft"
styles={{ content: { padding: 4 } }}
trigger="click"
- onOpenChange={setOpen}
+ onOpenChange={handleOpenChange}
>
- <div className={styles.button}>
- {displayRepos.length > 0 ? <Github size={14} /> : <Icon icon={SquircleDashed} size={14} />}
- <span>{buttonLabel}</span>
- <Icon icon={ChevronDownIcon} size={12} />
- </div>
+ {button}
</Popover>
);
});
diff --git a/src/features/ChatInput/ControlBar/ModeSelector.tsx b/src/features/ChatInput/ControlBar/ModeSelector.tsx
index e3cf2cfdb10..e97c35b638b 100644
--- a/src/features/ChatInput/ControlBar/ModeSelector.tsx
+++ b/src/features/ChatInput/ControlBar/ModeSelector.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
import { useBusinessAgentModeSync } from '@/business/client/hooks/useBusinessAgentMode';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -65,6 +66,15 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillSecondary};
}
`,
+ buttonDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: transparent;
+ }
+ `,
option: css`
cursor: pointer;
@@ -111,6 +121,7 @@ const ModeSelector = memo(() => {
const toggleAgentMode = useToggleAgentMode();
useBusinessAgentModeSync(agentId);
const [open, setOpen] = useState(false);
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
@@ -119,10 +130,21 @@ const ModeSelector = memo(() => {
const handleSelect = useCallback(
async (mode: 'chat' | 'agent') => {
+ if (!canCreateContent) return;
+
setOpen(false);
await toggleAgentMode(mode === 'agent');
},
- [toggleAgentMode],
+ [canCreateContent, toggleAgentMode],
+ );
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!canCreateContent) return;
+
+ setOpen(nextOpen);
+ },
+ [canCreateContent],
);
const agentTooltip = (
@@ -188,23 +210,30 @@ const ModeSelector = memo(() => {
);
const button = (
- <div className={styles.button}>
+ <div className={cx(styles.button, !canCreateContent && styles.buttonDisabled)}>
<Icon icon={CurrentIcon} size={14} />
<span>{t(`chatMode.${currentMode}`)}</span>
<Icon icon={ChevronDownIcon} size={12} />
</div>
);
+ if (!canCreateContent)
+ return (
+ <Tooltip title={reason}>
+ <div>{button}</div>
+ </Tooltip>
+ );
+
return (
<Popover
content={popoverContent}
- open={open}
+ open={canCreateContent && open}
placement="topLeft"
trigger="click"
styles={{
content: { border: `1px solid ${cssVar.colorBorderSecondary}`, padding: 4 },
}}
- onOpenChange={setOpen}
+ onOpenChange={handleOpenChange}
>
<div>
{open ? (
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
new file mode 100644
index 00000000000..ed76a4ce624
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -0,0 +1,168 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import InputEditor from './index';
+
+const permission = vi.hoisted(() => ({
+ allowed: false,
+}));
+
+type StoreSelector<T = unknown> = (state: Record<PropertyKey, unknown>) => T;
+
+vi.mock('@lobechat/const', () => ({ isDesktop: false }));
+vi.mock('@lobechat/const/hotkeys', () => ({
+ HotkeyEnum: { AddUserMessage: 'add-user-message' },
+ KeyEnum: { Alt: 'alt', Enter: 'enter' },
+}));
+vi.mock('@lobechat/heterogeneous-agents', () => ({ HETEROGENEOUS_TYPE_LABELS: {} }));
+vi.mock('@lobechat/prompts', () => ({
+ chainInputCompletion: vi.fn(),
+ escapeXmlAttr: (value: string) => value,
+}));
+vi.mock('@lobechat/utils', () => ({
+ isCommandPressed: vi.fn(() => false),
+ merge: vi.fn((...args) => Object.assign({}, ...args)),
+}));
+vi.mock('@lobehub/editor', () => ({
+ INSERT_MENTION_COMMAND: 'insert-mention',
+ ReactAutoCompletePlugin: vi.fn(),
+ ReactMathPlugin: vi.fn(),
+}));
+vi.mock('@lobehub/editor/react', () => {
+ const Editor = Object.assign(
+ vi.fn(({ editable }: { editable?: boolean }) => (
+ <div data-editable={String(editable)} data-testid="mock-editor" />
+ )),
+ {
+ withProps: vi.fn((plugin, props) => [plugin, props]),
+ },
+ );
+
+ return {
+ Editor,
+ FloatMenu: vi.fn(() => null),
+ useEditorState: vi.fn(() => ({ isEmpty: true })),
+ };
+});
+vi.mock('@lobehub/ui', () => ({ combineKeys: vi.fn(() => 'alt+enter') }));
+vi.mock('fuse.js', () => ({
+ default: class Fuse {
+ search() {
+ return [];
+ }
+ },
+}));
+vi.mock('lexical', () => ({ KEY_ESCAPE_COMMAND: 'escape' }));
+vi.mock('react-hotkeys-hook', () => ({
+ useHotkeysContext: () => ({
+ disableScope: vi.fn(),
+ enableScope: vi.fn(),
+ }),
+}));
+
+vi.mock('@/components/DragUploadZone', () => ({
+ usePasteFile: vi.fn(),
+ useUploadFiles: () => ({ handleUploadFiles: vi.fn() }),
+}));
+vi.mock('@/hooks/useEnterToSend', () => ({ useEnterToSend: () => vi.fn(() => false) }));
+vi.mock('@/hooks/useIMECompositionEvent', () => ({
+ useIMECompositionEvent: () => ({
+ compositionProps: {
+ onCompositionEnd: vi.fn(),
+ onCompositionStart: vi.fn(),
+ },
+ isComposingRef: { current: false },
+ }),
+}));
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: permission.allowed, reason: '' }),
+}));
+vi.mock('@/services/chat', () => ({ chatService: { fetchPresetTaskResult: vi.fn() } }));
+vi.mock('@/services/aiChat', () => ({ aiChatService: new Proxy({}, { get: () => vi.fn() }) }));
+vi.mock('@/store/chat', () => ({
+ useChatStore: Object.assign(<T,>(selector: StoreSelector<T>) => selector({}), {
+ getState: () => ({ activeTopicId: undefined }),
+ }),
+}));
+vi.mock('../hooks/useChatInputDraft', () => ({
+ useChatInputDraft: () => ({ restoreDraft: vi.fn(), saveDraftDebounced: vi.fn() }),
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: <T,>(selector: StoreSelector<T>) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => undefined,
+ getAgentModelById: () => () => undefined,
+ getAgentModelProviderById: () => () => undefined,
+ },
+}));
+vi.mock('@/store/user', () => {
+ const useUserStore = Object.assign(<T,>(selector: StoreSelector<T>) => selector({}), {
+ getState: () => ({}),
+ });
+
+ return { useUserStore };
+});
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableInputMarkdown: () => false },
+ settingsSelectors: { getHotkeyById: () => () => 'alt+enter' },
+ systemAgentSelectors: {
+ inputCompletion: () => ({ enabled: false }),
+ },
+}));
+
+vi.mock('../hooks/useAgentId', () => ({ useAgentId: () => 'agent-id' }));
+vi.mock('../store', () => {
+ const editor = {
+ dispatchCommand: vi.fn(),
+ };
+ const state = {
+ disableMention: true,
+ disableSlash: true,
+ editor,
+ expand: false,
+ handleSendButton: vi.fn(),
+ slashMenuRef: { current: null },
+ slashPlacement: 'top',
+ updateMarkdownContent: vi.fn(),
+ };
+
+ return {
+ useChatInputStore: <T,>(selector: StoreSelector<T>) => selector(state),
+ useStoreApi: () => ({
+ getState: () => ({ getMessages: vi.fn() }),
+ subscribe: vi.fn(() => vi.fn()),
+ }),
+ };
+});
+vi.mock('./ActionTag', () => ({
+ INSERT_ACTION_TAG_COMMAND: 'insert-action-tag',
+ useSlashActionItems: () => [],
+}));
+vi.mock('./MentionMenu', () => ({ createMentionMenu: vi.fn(() => vi.fn(() => null)) }));
+vi.mock('./Placeholder', () => ({
+ default: () => <span>placeholder</span>,
+}));
+vi.mock('./plugins', () => ({
+ CHAT_INPUT_EMBED_PLUGINS: [],
+ createChatInputRichPlugins: () => [],
+}));
+vi.mock('./ReferTopic', () => ({ INSERT_REFER_TOPIC_COMMAND: 'insert-refer-topic' }));
+vi.mock('./useLocalFileMention', () => ({
+ useLocalFileMention: () => ({
+ enableLocalFileMention: false,
+ searchLocalFiles: vi.fn(async () => []),
+ }),
+}));
+vi.mock('./useMentionCategories', () => ({ useMentionCategories: () => [] }));
+
+describe('ChatInput InputEditor', () => {
+ it('renders as read-only when create-content permission is denied', () => {
+ permission.allowed = false;
+
+ render(<InputEditor />);
+
+ expect(screen.getByTestId('mock-editor')).toHaveAttribute('data-editable', 'false');
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 1dc1263919b..d9cdc69020f 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -21,6 +21,7 @@ import { useHotkeysContext } from 'react-hotkeys-hook';
import { usePasteFile, useUploadFiles } from '@/components/DragUploadZone';
import { useEnterToSend } from '@/hooks/useEnterToSend';
import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';
+import { usePermission } from '@/hooks/usePermission';
import { aiChatService } from '@/services/aiChat';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -89,6 +90,7 @@ const InputEditor = memo<{
const { restoreDraft, saveDraftDebounced } = useChatInputDraft();
const restoredDraftEditorRef = useRef<IEditor | null>(null);
const state = useEditorState(editor);
+ const { allowed: canCreateContent } = usePermission('create_content');
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
const { enableScope, disableScope } = useHotkeysContext();
@@ -453,6 +455,7 @@ const InputEditor = memo<{
pasteAsPlainText
className={className}
content={''}
+ editable={canCreateContent}
editor={editor}
{...{ slashPlacement }}
{...richRenderProps}
diff --git a/src/features/ChatInput/SendArea/ExpandButton.tsx b/src/features/ChatInput/SendArea/ExpandButton.tsx
index 21dfcfbed0d..4472c9b036f 100644
--- a/src/features/ChatInput/SendArea/ExpandButton.tsx
+++ b/src/features/ChatInput/SendArea/ExpandButton.tsx
@@ -4,20 +4,26 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatInputStore } from '@/features/ChatInput/store';
+import { usePermission } from '@/hooks/usePermission';
const ExpandButton = memo(() => {
const { t } = useTranslation('editor');
const [expand, setExpand, editor] = useChatInputStore((s) => [s.expand, s.setExpand, s.editor]);
+ const { allowed: canUseChatInputAction, reason } = usePermission('create_content');
return (
<ActionIcon
className="show-on-hover"
+ disabled={!canUseChatInputAction}
icon={expand ? Minimize2Icon : Maximize2Icon}
size={{ blockSize: 32, size: 16, strokeWidth: 2.3 }}
- title={t(expand ? 'actions.expand.off' : 'actions.expand.on')}
style={{
zIndex: 10,
}}
+ title={
+ canUseChatInputAction ? t(expand ? 'actions.expand.off' : 'actions.expand.on') : reason
+ }
onClick={() => {
+ if (!canUseChatInputAction) return;
setExpand?.(!expand);
editor?.focus();
}}
diff --git a/src/features/ChatInput/SendArea/SendButton.tsx b/src/features/ChatInput/SendArea/SendButton.tsx
index 8d59f3a54bb..dc2d908a392 100644
--- a/src/features/ChatInput/SendArea/SendButton.tsx
+++ b/src/features/ChatInput/SendArea/SendButton.tsx
@@ -1,7 +1,10 @@
import { SendButton as Send } from '@lobehub/editor/react';
+import { Tooltip } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import { selectors, useChatInputStore } from '../store';
const SendButton = memo(() => {
@@ -11,19 +14,26 @@ const SendButton = memo(() => {
const { generating, disabled } = useChatInputStore(selectors.sendButtonProps, isEqual);
const [send, handleStop] = useChatInputStore((s) => [s.handleSendButton, s.handleStop]);
- return (
+ // Workspace viewer doesn't have `message:create` → backend would 403.
+ // OR the permission gate into the existing disabled prop so the button
+ // visibly grays out and a tooltip explains why.
+ const { allowed: canCreate, reason } = usePermission('create_content');
+
+ const button = (
<Send
- disabled={disabled}
+ disabled={disabled || !canCreate}
generating={generating}
- menu={sendMenu as any}
+ menu={canCreate ? (sendMenu as any) : undefined}
placement={'topRight'}
shape={shape}
size={size}
trigger={['hover']}
- onClick={generating ? undefined : () => send()}
+ onClick={generating || !canCreate ? undefined : () => send()}
onStop={() => handleStop()}
/>
);
+
+ return canCreate ? button : <Tooltip title={reason}>{button}</Tooltip>;
});
SendButton.displayName = 'SendButton';
diff --git a/src/features/CommandMenu/AskAIMenu.tsx b/src/features/CommandMenu/AskAIMenu.tsx
index 0862a898aa4..e5e6ad237c2 100644
--- a/src/features/CommandMenu/AskAIMenu.tsx
+++ b/src/features/CommandMenu/AskAIMenu.tsx
@@ -5,8 +5,8 @@ import { Command } from 'cmdk';
import { Bot, Image } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
@@ -17,7 +17,7 @@ import { useCommandMenu } from './useCommandMenu';
const AskAIMenu = memo(() => {
const { t } = useTranslation(['common', 'chat', 'home']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { handleAskLobeAI, handleAIPainting, closeCommandMenu } = useCommandMenu();
const { search } = useCommandMenuContext();
diff --git a/src/features/CommandMenu/MainMenu.tsx b/src/features/CommandMenu/MainMenu.tsx
index 7ca09f8dd0e..24228bb4e6d 100644
--- a/src/features/CommandMenu/MainMenu.tsx
+++ b/src/features/CommandMenu/MainMenu.tsx
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next';
import { openFeedbackModal } from '@/components/FeedbackModal';
import { getNavigableRoutes, getRouteById } from '@/config/routes';
import { FEEDBACK } from '@/const/url';
+import { usePermission } from '@/hooks/usePermission';
import { useCommandMenuContext } from './CommandMenuContext';
import { CommandItem } from './components';
@@ -25,6 +26,7 @@ import { useCommandMenu } from './useCommandMenu';
const MainMenu = memo(() => {
const { pathname, menuContext, setPages, pages } = useCommandMenuContext();
const { t } = useTranslation('common');
+ const { allowed: canCreate } = usePermission('create_content');
const {
handleCreateSession,
@@ -42,6 +44,7 @@ const MainMenu = memo(() => {
<Command.Group>
<CommandItem
+ disabled={!canCreate}
icon={<Bot />}
unpinned={menuContext === 'agent' || menuContext === 'page'}
value="create new agent assistant"
@@ -51,6 +54,7 @@ const MainMenu = memo(() => {
</CommandItem>
<CommandItem
+ disabled={!canCreate}
icon={<Bot />}
unpinned={menuContext === 'agent' || menuContext === 'page'}
value="create new agent team"
@@ -61,6 +65,7 @@ const MainMenu = memo(() => {
{menuContext === 'agent' && (
<CommandItem
+ disabled={!canCreate}
icon={<MessageSquarePlusIcon />}
unpinned={menuContext !== 'agent'}
value="create new topic"
@@ -70,11 +75,17 @@ const MainMenu = memo(() => {
</CommandItem>
)}
- <CommandItem icon={<FilePen />} value="create new page" onSelect={handleCreatePage}>
+ <CommandItem
+ disabled={!canCreate}
+ icon={<FilePen />}
+ value="create new page"
+ onSelect={handleCreatePage}
+ >
{t('cmdk.newPage')}
</CommandItem>
<CommandItem
+ disabled={!canCreate}
icon={<LibraryBig />}
unpinned={menuContext !== 'resource'}
value="create new library"
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index 1e317192be5..ad22ce84c3d 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -18,11 +18,11 @@ import {
} from 'lucide-react';
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { type SearchResult } from '@/database/repositories/search';
import { useCommandMenuContext } from '@/features/CommandMenu/CommandMenuContext';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useImageStore } from '@/store/image';
import { generationTopicSelectors as imageGenerationTopicSelectors } from '@/store/image/slices/generationTopic/selectors';
import { useVideoStore } from '@/store/video';
@@ -57,7 +57,7 @@ const SearchResults = memo<SearchResultsProps>(
const { t } = useTranslation('common');
const { t: tImage } = useTranslation('image');
const { t: tVideo } = useTranslation('video');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { menuContext } = useCommandMenuContext();
const imageTopics = useImageStore(imageGenerationTopicSelectors.generationTopics);
const activeImageTopicId = useImageStore((s) => s.activeGenerationTopicId);
diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.ts
index 33c6b352221..41f1f7d92ed 100644
--- a/src/features/CommandMenu/useCommandMenu.ts
+++ b/src/features/CommandMenu/useCommandMenu.ts
@@ -1,12 +1,13 @@
import { useDebounce } from 'ahooks';
import { useTheme as useNextThemesTheme } from 'next-themes';
import { useCallback, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
import useSWR from 'swr';
import { isDesktop } from '@/const/version';
import { type SearchResult } from '@/database/repositories/search';
import { useCreateNewModal } from '@/features/LibraryModal';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useGroupWizard } from '@/layout/GlobalProvider/GroupWizardProvider';
import { lambdaClient } from '@/libs/trpc/client';
import { useCreateMenuItems } from '@/routes/(main)/home/_layout/hooks';
@@ -42,7 +43,8 @@ export const useCommandMenu = () => {
activeAgentId: agentId,
} = useCommandMenuContext();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canCreate } = usePermission('create_content');
const { setTheme } = useNextThemesTheme();
const createAgent = useAgentStore((s) => s.createAgent);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
@@ -152,6 +154,8 @@ export const useCommandMenu = () => {
}, [selectedAgent, search, navigate, setSelectedAgent, onClose]);
const handleCreateSession = useCallback(async () => {
+ if (!canCreate) return;
+
const result = await createAgent({});
await refreshAgentList();
@@ -161,30 +165,38 @@ export const useCommandMenu = () => {
}
onClose();
- }, [createAgent, refreshAgentList, navigate, onClose]);
+ }, [canCreate, createAgent, refreshAgentList, navigate, onClose]);
const openNewTopicOrSaveTopic = useChatStore((s) => s.openNewTopicOrSaveTopic);
const handleCreateTopic = useCallback(() => {
+ if (!canCreate) return;
+
openNewTopicOrSaveTopic();
onClose();
- }, [openNewTopicOrSaveTopic, onClose]);
+ }, [canCreate, openNewTopicOrSaveTopic, onClose]);
const handleCreateLibrary = useCallback(() => {
+ if (!canCreate) return;
+
onClose();
openCreateLibraryModal({
onSuccess: (id) => {
navigate(`/resource/library/${id}`);
},
});
- }, [onClose, openCreateLibraryModal, navigate]);
+ }, [canCreate, onClose, openCreateLibraryModal, navigate]);
const handleCreatePage = useCallback(async () => {
+ if (!canCreate) return;
+
await createPage();
onClose();
- }, [createPage, onClose]);
+ }, [canCreate, createPage, onClose]);
const handleCreateAgentTeam = useCallback(() => {
+ if (!canCreate) return;
+
onClose();
openGroupWizard({
onCreateCustom: async (selectedAgents) => {
@@ -194,7 +206,7 @@ export const useCommandMenu = () => {
await createGroupFromTemplate(templateId, selectedMemberTitles);
},
});
- }, [onClose, openGroupWizard, createGroupWithMembers, createGroupFromTemplate]);
+ }, [canCreate, onClose, openGroupWizard, createGroupWithMembers, createGroupFromTemplate]);
return {
closeCommandMenu,
diff --git a/src/features/CommunityWorkspaceSettings/index.tsx b/src/features/CommunityWorkspaceSettings/index.tsx
new file mode 100644
index 00000000000..8eebc74775c
--- /dev/null
+++ b/src/features/CommunityWorkspaceSettings/index.tsx
@@ -0,0 +1,674 @@
+'use client';
+
+import { OFFICIAL_URL } from '@lobechat/const';
+import {
+ Avatar,
+ Block,
+ Button,
+ Center,
+ Flexbox,
+ Icon,
+ Input,
+ Tabs,
+ Tag,
+ Text,
+ TextArea,
+ Tooltip,
+} from '@lobehub/ui';
+import type { TableColumnsType, UploadProps } from 'antd';
+import { App, Input as AntInput, Table, Upload } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ ArrowLeft,
+ CircleHelp,
+ Globe,
+ ImagePlus,
+ RefreshCw,
+ Settings,
+ Trash2,
+ Users,
+} from 'lucide-react';
+import {
+ memo,
+ type PropsWithChildren,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ type CommunityWorkspaceMember,
+ useCommunityWorkspaceMembers,
+} from '@/business/client/hooks/useCommunityWorkspaceMembers';
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import {
+ isCommunityWorkspaceNamespaceTakenError,
+ syncCommunityWorkspaceMembers,
+ updateCommunityWorkspaceProfile,
+} from '@/business/client/services/communityWorkspaceProfile';
+import EmojiPicker from '@/components/EmojiPicker';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
+import { useFileStore } from '@/store/file';
+
+const MAX_FILE_SIZE = 2 * 1024 * 1024;
+const NAMESPACE_MAX = 32;
+const NAMESPACE_MIN = 3;
+const DESCRIPTION_MAX = 200;
+const DISPLAY_NAME_MAX = 50;
+const ORGANIZATION_URL_PREFIX = `${OFFICIAL_URL.replace(/^https?:\/\//, '')}/community/org/`;
+const NAMESPACE_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ footer: css`
+ padding-block: 12px;
+ padding-inline: 20px;
+ border-block-start: 1px solid ${cssVar.colorFillTertiary};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ hint: css`
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+interface SettingCardProps {
+ action?: ReactNode;
+ children?: ReactNode;
+ description?: ReactNode;
+ hint?: ReactNode;
+ title: ReactNode;
+}
+
+const SettingCard = memo<SettingCardProps>(({ title, description, children, hint, action }) => (
+ <Block variant="outlined">
+ <Flexbox gap={12} padding={20}>
+ <Flexbox gap={4}>
+ <Text strong as="h3" style={{ fontSize: 16, margin: 0 }}>
+ {title}
+ </Text>
+ {description && (
+ <Text style={{ fontSize: 13 }} type="secondary">
+ {description}
+ </Text>
+ )}
+ </Flexbox>
+ {children}
+ </Flexbox>
+ {(hint || action) && (
+ <Flexbox horizontal align="center" className={styles.footer} gap={12} justify="space-between">
+ <span className={styles.hint}>{hint ?? ''}</span>
+ {action}
+ </Flexbox>
+ )}
+ </Block>
+));
+
+SettingCard.displayName = 'CommunityWorkspaceSettingCard';
+
+const PageContainer = memo<PropsWithChildren>(({ children }) => (
+ <Flexbox height="100%" style={{ overflowX: 'hidden', overflowY: 'auto' }} width="100%">
+ <Flexbox
+ gap={16}
+ padding={24}
+ style={{ boxSizing: 'border-box', margin: '0 auto', maxWidth: 1200, width: '100%' }}
+ >
+ {children}
+ </Flexbox>
+ </Flexbox>
+));
+
+PageContainer.displayName = 'CommunityWorkspaceSettingsPageContainer';
+
+const MembersCard = memo<{ canManage: boolean }>(({ canManage }) => {
+ const { t } = useTranslation('discover');
+ const { message } = App.useApp();
+ const { canSync, isLoading, members, refresh } = useCommunityWorkspaceMembers();
+ const [syncing, setSyncing] = useState(false);
+
+ const canTriggerSync = canManage && canSync;
+
+ const handleSync = useCallback(async () => {
+ setSyncing(true);
+ try {
+ await syncCommunityWorkspaceMembers();
+ await refresh();
+ message.success(t('user.workspaceProfile.settings.members.syncSuccess'));
+ } catch (error) {
+ message.error(
+ (error as Error).message || t('user.workspaceProfile.settings.members.syncFailed'),
+ );
+ } finally {
+ setSyncing(false);
+ }
+ }, [message, refresh, t]);
+
+ const columns = useMemo<TableColumnsType<CommunityWorkspaceMember>>(
+ () => [
+ {
+ dataIndex: 'displayName',
+ render: (_, member) => {
+ const name =
+ member.displayName || member.userName || member.namespace || `#${member.accountId}`;
+ return (
+ <Flexbox horizontal align="center" gap={12}>
+ <Avatar avatar={member.avatarUrl || undefined} size={36} title={name} />
+ <Flexbox gap={2}>
+ <Text strong style={{ fontSize: 14 }}>
+ {name}
+ </Text>
+ {member.namespace && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ @{member.namespace}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+ title: t('user.workspaceProfile.settings.members.column.member'),
+ },
+ {
+ align: 'right',
+ dataIndex: 'role',
+ render: (role: CommunityWorkspaceMember['role']) => (
+ <Tag>
+ {role === 'admin'
+ ? t('user.workspaceProfile.settings.members.role.admin')
+ : t('user.workspaceProfile.settings.members.role.member')}
+ </Tag>
+ ),
+ title: t('user.workspaceProfile.settings.members.column.role'),
+ width: 120,
+ },
+ ],
+ [t],
+ );
+
+ return (
+ <SettingCard
+ description={t('user.workspaceProfile.settings.members.description')}
+ hint={t('user.workspaceProfile.settings.members.syncHint')}
+ title={t('user.workspaceProfile.settings.members.title')}
+ action={
+ <Button disabled={!canTriggerSync} icon={RefreshCw} loading={syncing} onClick={handleSync}>
+ {t('user.workspaceProfile.settings.members.sync')}
+ </Button>
+ }
+ >
+ <Table
+ columns={columns}
+ dataSource={members}
+ loading={isLoading && members.length === 0}
+ pagination={false}
+ rowKey={'accountId'}
+ size={'middle'}
+ locale={{
+ emptyText: (
+ <Text style={{ fontSize: 13 }} type="secondary">
+ {t('user.workspaceProfile.settings.members.empty')}
+ </Text>
+ ),
+ }}
+ />
+ </SettingCard>
+ );
+});
+
+MembersCard.displayName = 'CommunityWorkspaceMembersCard';
+
+const trimOptional = (value: string | undefined) => {
+ const trimmed = value?.trim();
+ return trimmed || undefined;
+};
+
+const isValidUrl = (value: string) => {
+ if (!value.trim()) return true;
+ try {
+ const { protocol } = new URL(value.trim());
+ return protocol === 'http:' || protocol === 'https:';
+ } catch {
+ return false;
+ }
+};
+
+const CommunityWorkspaceSettings = memo(() => {
+ const { t } = useTranslation('discover');
+ const { message } = App.useApp();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canManageSettings, reason: permissionReason } = usePermission('manage_settings');
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const {
+ avatarUrl: remoteAvatarUrl,
+ bannerUrl: remoteBannerUrl,
+ canEdit: canEditCommunityProfile,
+ description: remoteDescription,
+ displayName: remoteDisplayName,
+ isLoading,
+ profile,
+ refresh,
+ username,
+ } = useCommunityWorkspaceProfile();
+
+ const canEdit = canManageSettings && canEditCommunityProfile && !!profile;
+ const disabledReason = !canManageSettings
+ ? permissionReason
+ : t('user.workspaceProfile.settings.noPermission');
+
+ const [displayName, setDisplayName] = useState(remoteDisplayName ?? '');
+ const [namespace, setNamespace] = useState(username ?? '');
+ const [description, setDescription] = useState(remoteDescription ?? '');
+ const [websiteUrl, setWebsiteUrl] = useState(profile?.websiteUrl ?? '');
+ const [avatarUrl, setAvatarUrl] = useState<string | null>(remoteAvatarUrl ?? null);
+ const [bannerUrl, setBannerUrl] = useState<string | null>(remoteBannerUrl ?? null);
+ const [savingField, setSavingField] = useState<string | null>(null);
+ const [avatarUploading, setAvatarUploading] = useState(false);
+ const [bannerUploading, setBannerUploading] = useState(false);
+ const [namespaceError, setNamespaceError] = useState<string | undefined>();
+ const [websiteError, setWebsiteError] = useState<string | undefined>();
+ const [activeTab, setActiveTab] = useState<'members' | 'profile'>('profile');
+
+ const handleBack = useCallback(() => {
+ if (window.history.length > 1) {
+ navigate(-1);
+ return;
+ }
+
+ navigate('/community/workspace');
+ }, [navigate]);
+
+ const renderHeader = () => (
+ <Flexbox horizontal align="center" gap={8}>
+ <Button icon={ArrowLeft} type="text" onClick={handleBack}>
+ {t('user.workspaceProfile.settings.back')}
+ </Button>
+ </Flexbox>
+ );
+
+ useEffect(() => {
+ setDisplayName(remoteDisplayName ?? '');
+ setNamespace(username ?? '');
+ setDescription(remoteDescription ?? '');
+ setWebsiteUrl(profile?.websiteUrl ?? '');
+ setAvatarUrl(remoteAvatarUrl ?? null);
+ setBannerUrl(remoteBannerUrl ?? null);
+ setNamespaceError(undefined);
+ setWebsiteError(undefined);
+ }, [
+ profile?.accountId,
+ profile?.websiteUrl,
+ remoteAvatarUrl,
+ remoteBannerUrl,
+ remoteDescription,
+ remoteDisplayName,
+ username,
+ ]);
+
+ const updateProfile = useCallback(
+ async (field: string, input: Parameters<typeof updateCommunityWorkspaceProfile>[0]) => {
+ if (!canEdit) return;
+ setSavingField(field);
+ try {
+ await updateCommunityWorkspaceProfile(input);
+ await refresh();
+ message.success(t('user.workspaceProfile.settings.updateSuccess'));
+ } catch (error) {
+ if (field === 'namespace' && isCommunityWorkspaceNamespaceTakenError(error)) {
+ setNamespaceError(t('user.workspaceProfile.settings.namespaceTaken'));
+ } else {
+ message.error(
+ (error as Error).message || t('user.workspaceProfile.settings.updateFailed'),
+ );
+ }
+ } finally {
+ setSavingField(null);
+ }
+ },
+ [canEdit, message, refresh, t],
+ );
+
+ const buildSaveButton = (field: string, disabled: boolean, onClick: () => void) => {
+ const button = (
+ <Button
+ disabled={!canEdit || disabled || isLoading}
+ loading={savingField === field}
+ type="primary"
+ onClick={onClick}
+ >
+ {t('user.workspaceProfile.save')}
+ </Button>
+ );
+
+ if (canEdit) return button;
+
+ return (
+ <Tooltip title={disabledReason}>
+ <span>{button}</span>
+ </Tooltip>
+ );
+ };
+
+ const namespaceValidation = useMemo(() => {
+ const value = namespace.trim();
+ if (!value) return t('user.workspaceProfile.errors.namespace.required');
+ if (value.length < NAMESPACE_MIN || value.length > NAMESPACE_MAX)
+ return t('user.workspaceProfile.errors.namespace.length');
+ if (!NAMESPACE_PATTERN.test(value)) return t('user.workspaceProfile.errors.namespace.pattern');
+ return namespaceError;
+ }, [namespace, namespaceError, t]);
+
+ const handleAvatarUpload = useCallback(
+ async (file: File) => {
+ if (file.size > MAX_FILE_SIZE) {
+ message.error(t('user.workspaceProfile.errors.fileTooLarge'));
+ return;
+ }
+
+ setAvatarUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) {
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ return;
+ }
+ setAvatarUrl(
+ result.url.startsWith('/') ? `${window.location.origin}${result.url}` : result.url,
+ );
+ } catch (error) {
+ console.error('[CommunityWorkspaceSettings] Avatar upload failed:', error);
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ } finally {
+ setAvatarUploading(false);
+ }
+ },
+ [message, t, uploadWithProgress],
+ );
+
+ const handleBannerUpload: UploadProps['customRequest'] = useCallback(
+ async (options: Parameters<NonNullable<UploadProps['customRequest']>>[0]) => {
+ const file = options.file as File;
+
+ if (file.size > MAX_FILE_SIZE) {
+ message.error(t('user.workspaceProfile.errors.fileTooLarge'));
+ options.onError?.(new Error('File too large'));
+ return;
+ }
+
+ setBannerUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) {
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ options.onError?.(new Error('Upload failed'));
+ return;
+ }
+ const url = result.url.startsWith('/')
+ ? `${window.location.origin}${result.url}`
+ : result.url;
+ setBannerUrl(url);
+ options.onSuccess?.(result);
+ } catch (error) {
+ console.error('[CommunityWorkspaceSettings] Banner upload failed:', error);
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ options.onError?.(error as Error);
+ } finally {
+ setBannerUploading(false);
+ }
+ },
+ [message, t, uploadWithProgress],
+ );
+
+ if (!profile) {
+ return <PageContainer>{renderHeader()}</PageContainer>;
+ }
+
+ const displayNameDirty = displayName.trim() !== (remoteDisplayName ?? '');
+ const namespaceDirty = namespace.trim() !== (username ?? '');
+ const descriptionDirty = description.trim() !== (remoteDescription ?? '');
+ const websiteDirty = websiteUrl.trim() !== (profile.websiteUrl ?? '');
+ const avatarDirty = avatarUrl !== (remoteAvatarUrl ?? null);
+ const bannerDirty = bannerUrl !== (remoteBannerUrl ?? null);
+
+ return (
+ <PageContainer>
+ {renderHeader()}
+
+ <Tabs
+ activeKey={activeTab}
+ items={[
+ {
+ icon: <Icon icon={Settings} size={16} />,
+ key: 'profile',
+ label: t('user.workspaceProfile.settings.tabs.profile'),
+ },
+ {
+ icon: <Icon icon={Users} size={16} />,
+ key: 'members',
+ label: t('user.workspaceProfile.settings.tabs.members'),
+ },
+ ]}
+ onChange={(key) => setActiveTab(key as 'members' | 'profile')}
+ />
+
+ {activeTab === 'members' && <MembersCard canManage={canManageSettings} />}
+
+ {activeTab === 'profile' && (
+ <>
+ <SettingCard
+ description={t('user.workspaceProfile.settings.displayName.description')}
+ hint={t('user.workspaceProfile.fields.displayName.maxLength')}
+ title={t('user.workspaceProfile.fields.displayName')}
+ action={buildSaveButton('displayName', !displayNameDirty || !displayName.trim(), () =>
+ updateProfile('displayName', { displayName: displayName.trim() }),
+ )}
+ >
+ <Input
+ showCount
+ disabled={!canEdit}
+ maxLength={DISPLAY_NAME_MAX}
+ style={{ maxWidth: 420 }}
+ value={displayName}
+ onChange={(e) => setDisplayName(e.target.value)}
+ />
+ </SettingCard>
+
+ <SettingCard
+ description={t('user.workspaceProfile.settings.namespace.description')}
+ title={t('user.workspaceProfile.fields.namespace')}
+ action={buildSaveButton('namespace', !namespaceDirty || !!namespaceValidation, () =>
+ updateProfile('namespace', { namespace: namespace.trim() }),
+ )}
+ hint={
+ namespaceValidation ||
+ t('user.workspaceProfile.settings.namespace.hint', {
+ max: NAMESPACE_MAX,
+ })
+ }
+ >
+ <AntInput
+ showCount
+ addonBefore={ORGANIZATION_URL_PREFIX}
+ disabled={!canEdit}
+ maxLength={NAMESPACE_MAX}
+ status={namespaceValidation ? 'error' : undefined}
+ style={{ maxWidth: 560 }}
+ value={namespace}
+ onChange={(e) => {
+ setNamespace(e.target.value);
+ setNamespaceError(undefined);
+ }}
+ />
+ </SettingCard>
+
+ <SettingCard
+ description={t('user.workspaceProfile.settings.description.description')}
+ hint={t('user.workspaceProfile.fields.description.maxLength')}
+ title={t('user.workspaceProfile.fields.description')}
+ action={buildSaveButton('description', !descriptionDirty, () =>
+ updateProfile('description', { description: trimOptional(description) }),
+ )}
+ >
+ <TextArea
+ showCount
+ disabled={!canEdit}
+ maxLength={DESCRIPTION_MAX}
+ rows={3}
+ style={{ maxWidth: 560 }}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </SettingCard>
+
+ <SettingCard
+ description={t('user.workspaceProfile.settings.website.description')}
+ hint={websiteError || t('user.workspaceProfile.settings.website.hint')}
+ title={t('user.workspaceProfile.fields.websiteUrl')}
+ action={buildSaveButton('websiteUrl', !websiteDirty || !!websiteError, () =>
+ updateProfile('websiteUrl', { websiteUrl: trimOptional(websiteUrl) }),
+ )}
+ >
+ <Input
+ disabled={!canEdit}
+ status={websiteError ? 'error' : undefined}
+ style={{ maxWidth: 560 }}
+ value={websiteUrl}
+ prefix={
+ <Icon color={cssVar.colorTextSecondary} icon={Globe} style={{ marginRight: 8 }} />
+ }
+ onChange={(e) => {
+ const next = e.target.value;
+ setWebsiteUrl(next);
+ setWebsiteError(
+ isValidUrl(next) ? undefined : t('user.workspaceProfile.errors.url'),
+ );
+ }}
+ />
+ </SettingCard>
+
+ <SettingCard
+ description={t('user.workspaceProfile.settings.avatar.description')}
+ hint={t('user.workspaceProfile.settings.avatar.hint')}
+ title={t('user.workspaceProfile.fields.avatar')}
+ action={buildSaveButton('avatarUrl', !avatarDirty || avatarUploading, () =>
+ updateProfile('avatarUrl', { avatarUrl }),
+ )}
+ >
+ <EmojiPicker
+ allowDelete={canEdit && !!avatarUrl}
+ allowUpload={canEdit ? { enableEmoji: true } : false}
+ loading={avatarUploading}
+ shape="square"
+ size={80}
+ value={avatarUrl || undefined}
+ onDelete={canEdit ? () => setAvatarUrl(null) : undefined}
+ onUpload={canEdit ? handleAvatarUpload : undefined}
+ onChange={
+ canEdit
+ ? (next) => {
+ if (!next.startsWith('data:')) setAvatarUrl(next || null);
+ }
+ : undefined
+ }
+ />
+ </SettingCard>
+
+ <SettingCard
+ description={t('user.workspaceProfile.settings.banner.description')}
+ hint={t('user.workspaceProfile.fields.bannerUrl.tooltip')}
+ action={buildSaveButton('bannerUrl', !bannerDirty || bannerUploading, () =>
+ updateProfile('bannerUrl', { bannerUrl }),
+ )}
+ title={
+ <Flexbox horizontal align="center" gap={4}>
+ {t('user.workspaceProfile.fields.bannerUrl')}
+ <Tooltip title={t('user.workspaceProfile.fields.bannerUrl.tooltip')}>
+ <CircleHelp size={14} style={{ cursor: 'help', opacity: 0.5 }} />
+ </Tooltip>
+ </Flexbox>
+ }
+ >
+ <Flexbox gap={8} width="100%">
+ <Upload
+ accept="image/*"
+ customRequest={handleBannerUpload}
+ disabled={!canEdit}
+ maxCount={1}
+ showUploadList={false}
+ style={{ display: 'block', width: '100%' }}
+ >
+ <div
+ style={{
+ backgroundColor: bannerUrl ? undefined : cssVar.colorFillTertiary,
+ backgroundImage: bannerUrl ? `url(${bannerUrl})` : undefined,
+ backgroundPosition: 'center',
+ backgroundSize: 'cover',
+ borderRadius: cssVar.borderRadiusLG,
+ cursor: canEdit ? 'pointer' : 'not-allowed',
+ height: 160,
+ maxWidth: 560,
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ >
+ <Center
+ style={{
+ background: bannerUrl ? 'rgba(0,0,0,0.4)' : 'transparent',
+ height: '100%',
+ opacity: bannerUrl ? 0 : 1,
+ transition: 'opacity 0.2s',
+ width: '100%',
+ }}
+ onMouseEnter={(e) => {
+ if (canEdit) e.currentTarget.style.opacity = '1';
+ }}
+ onMouseLeave={(e) => {
+ if (canEdit && bannerUrl) e.currentTarget.style.opacity = '0';
+ }}
+ >
+ <Flexbox align="center" gap={8}>
+ <ImagePlus
+ size={24}
+ style={{ color: bannerUrl ? '#fff' : cssVar.colorTextSecondary }}
+ />
+ <Text
+ style={{
+ color: bannerUrl ? '#fff' : cssVar.colorTextSecondary,
+ fontSize: 12,
+ }}
+ >
+ {bannerUploading
+ ? t('user.workspaceProfile.fields.bannerUrl.uploading')
+ : t('user.workspaceProfile.fields.bannerUrl.clickToUpload')}
+ </Text>
+ </Flexbox>
+ </Center>
+ </div>
+ </Upload>
+ {canEdit && bannerUrl && (
+ <Flexbox horizontal align="center" gap={8} justify="flex-start">
+ <Button
+ danger
+ icon={<Trash2 size={12} />}
+ size="small"
+ type="text"
+ onClick={() => setBannerUrl(null)}
+ >
+ {t('user.workspaceProfile.fields.bannerUrl.remove')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </SettingCard>
+ </>
+ )}
+ </PageContainer>
+ );
+});
+
+CommunityWorkspaceSettings.displayName = 'CommunityWorkspaceSettings';
+
+export default CommunityWorkspaceSettings;
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
index 479ffdd1eee..5c18506d89c 100644
--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
@@ -9,6 +9,7 @@ import {
messageStateSelectors,
useConversationStore,
} from '@/features/Conversation/store';
+import { usePermission } from '@/hooks/usePermission';
import dynamic from '@/libs/next/dynamic';
import { type ChatItemProps } from '../../type';
@@ -89,10 +90,15 @@ const MessageContent = memo<MessageContentProps>(
});
const { t } = useTranslation('common');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const onEditingChange = useCallback(
- (edit: boolean) => toggleMessageEditing(id, edit),
- [id, toggleMessageEditing],
+ (edit: boolean) => {
+ if (!canEdit && edit) return;
+ toggleMessageEditing(id, edit);
+ },
+ [canEdit, id, toggleMessageEditing],
);
return (
@@ -120,6 +126,7 @@ const MessageContent = memo<MessageContentProps>(
value={message ? String(message) : ''}
onCancel={() => onEditingChange(false)}
onConfirm={async (value, newEditorData) => {
+ if (!canEdit) return;
onEditingChange(false);
// updateMessageContent does an optimistic state update synchronously before
// awaiting the DB round trip. Kick off regenerate in parallel so the old
@@ -127,7 +134,7 @@ const MessageContent = memo<MessageContentProps>(
const save = updateMessageContent(id, value, {
editorData: newEditorData as Record<string, any> | undefined,
});
- if (shouldSendOnConfirm) {
+ if (canCreate && shouldSendOnConfirm) {
await regenerateUserMessage(id);
}
await save;
diff --git a/src/features/Conversation/Error/ChatInvalidApiKey.tsx b/src/features/Conversation/Error/ChatInvalidApiKey.tsx
index f861de87fe9..ee730d2f190 100644
--- a/src/features/Conversation/Error/ChatInvalidApiKey.tsx
+++ b/src/features/Conversation/Error/ChatInvalidApiKey.tsx
@@ -3,9 +3,9 @@ import { Button } from '@lobehub/ui';
import { ModelProvider } from 'model-bank';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useProviderName } from '@/hooks/useProviderName';
import { type GlobalLLMProviderKey } from '@/types/user/settings/modelProvider';
@@ -18,7 +18,7 @@ interface ChatInvalidAPIKeyProps {
}
const ChatInvalidAPIKey = memo<ChatInvalidAPIKeyProps>(({ id, provider }) => {
const { t } = useTranslation(['modelProvider', 'error']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [deleteMessage] = useConversationStore((s) => [s.deleteMessage]);
const providerName = useProviderName(provider as GlobalLLMProviderKey);
diff --git a/src/features/Conversation/Error/ExceededContextWindowError.tsx b/src/features/Conversation/Error/ExceededContextWindowError.tsx
index b1b4e82d313..a82d88c02ef 100644
--- a/src/features/Conversation/Error/ExceededContextWindowError.tsx
+++ b/src/features/Conversation/Error/ExceededContextWindowError.tsx
@@ -4,6 +4,7 @@ import { Minimize2 } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useConversationStore } from '../store';
@@ -16,6 +17,7 @@ interface ExceededContextWindowErrorProps {
const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }) => {
const { t } = useTranslation('error');
const [loading, setLoading] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
const context = useConversationStore((s) => s.context);
const regenerateUserMessage = useConversationStore((s) => s.regenerateUserMessage);
@@ -24,7 +26,7 @@ const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }
);
const handleCompact = useCallback(async () => {
- if (!context.topicId || !parentId) return;
+ if (!canCreate || !context.topicId || !parentId) return;
setLoading(true);
try {
@@ -33,7 +35,7 @@ const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }
} finally {
setLoading(false);
}
- }, [context, parentId, regenerateUserMessage]);
+ }, [canCreate, context, parentId, regenerateUserMessage]);
return (
<BaseErrorForm
@@ -42,7 +44,7 @@ const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }
title={t('exceededContext.title')}
action={
<Button
- disabled={!context.topicId}
+ disabled={!canCreate || !context.topicId}
loading={loading}
type={'primary'}
onClick={handleCompact}
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index f5d7b5c56af..d65fd683780 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -8,7 +8,6 @@ import { type AlertProps } from '@lobehub/ui';
import { Block, Highlighter, Skeleton } from '@lobehub/ui';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import useBusinessErrorAlertConfig from '@/business/client/hooks/useBusinessErrorAlertConfig';
import useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorContent';
@@ -16,6 +15,8 @@ import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useR
import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
import { useConversationStore } from '@/features/Conversation/store';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useProviderName } from '@/hooks/useProviderName';
import dynamic from '@/libs/next/dynamic';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -179,22 +180,24 @@ interface ErrorExtraProps {
const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRegenerate }) => {
const error = data.error;
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
+ const { allowed: canCreate } = usePermission('create_content');
const sessionErrorBody = error?.body;
const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;
const regenerateAssistantMessage = useConversationStore((s) => s.regenerateAssistantMessage);
const deleteMessage = useConversationStore((s) => s.deleteMessage);
const handleRetryAgentMessage = useCallback(() => {
+ if (!canCreate) return;
if (onRegenerate) {
onRegenerate();
return;
}
regenerateAssistantMessage(data.id);
if (data.error) deleteMessage(data.id);
- }, [data.error, data.id, deleteMessage, onRegenerate, regenerateAssistantMessage]);
+ }, [canCreate, data.error, data.id, deleteMessage, onRegenerate, regenerateAssistantMessage]);
if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {
return (
@@ -250,7 +253,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRe
</Highlighter>
) : undefined,
}}
- onRegenerate={onRegenerate}
+ onRegenerate={canCreate ? onRegenerate : undefined}
/>
);
});
diff --git a/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx
index 3252329c840..fcc25a7a419 100644
--- a/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx
+++ b/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx
@@ -5,7 +5,8 @@ import { Avatar, Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { ArrowRight } from 'lucide-react';
import { memo, useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { type MarkdownElementProps } from '../../type';
@@ -62,7 +63,7 @@ interface LobeAgentsProps extends MarkdownElementProps {
const Render = memo<LobeAgentsProps>(
({ identifier, title, description, avatar, backgroundColor }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleClick = useCallback(() => {
if (!identifier) return;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/index.tsx
index 44f7665ceae..af7a6a61253 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/index.tsx
@@ -3,6 +3,8 @@ import { LayoutPanelTop, LogsIcon, LucideBug, LucideBugOff, Trash2 } from 'lucid
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { useConversationStore } from '../../../../store';
import Settings from './Settings';
@@ -30,6 +32,7 @@ const Actions = memo<ActionsProps>(
toolRemoval,
}) => {
const { t } = useTranslation('plugin');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [deleteAssistantMessage, removeToolFromMessage] = useConversationStore((s) => [
s.deleteAssistantMessage,
s.removeToolFromMessage,
@@ -54,20 +57,24 @@ const Actions = memo<ActionsProps>(
title={t(showDebug ? 'debug.off' : 'debug.on')}
onClick={() => setShowDebug?.(!showDebug)}
/>
- <Settings id={identifier} />
- <ActionIcon
- danger
- icon={Trash2}
- size={'small'}
- title={t('inspector.delete')}
- onClick={() => {
- if (toolRemoval) {
- void removeToolFromMessage(toolRemoval.messageId, toolRemoval.toolCallId);
- } else {
- void deleteAssistantMessage(assistantMessageId);
- }
- }}
- />
+ {canEdit && (
+ <>
+ <Settings id={identifier} />
+ <ActionIcon
+ danger
+ icon={Trash2}
+ size={'small'}
+ title={t('inspector.delete')}
+ onClick={() => {
+ if (toolRemoval) {
+ void removeToolFromMessage(toolRemoval.messageId, toolRemoval.toolCallId);
+ } else {
+ void deleteAssistantMessage(assistantMessageId);
+ }
+ }}
+ />
+ </>
+ )}
</>
);
},
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx b/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx
index baaac2e1f9e..08982618be1 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx
@@ -2,6 +2,8 @@ import { Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import { useConversationStore } from '../../../store';
import ContentBlock from './ContentBlock';
import type { RenderableAssistantContentBlock } from './types';
@@ -15,12 +17,13 @@ interface GroupItemProps extends RenderableAssistantContentBlock {
const GroupItem = memo<GroupItemProps>(
({ contentId, disableEditing, error, assistantId, ...item }) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);
return item.id === contentId ? (
<Flexbox
onDoubleClick={(e) => {
- if (disableEditing || error || !e.altKey) return;
+ if (!canEdit || disableEditing || error || !e.altKey) return;
toggleMessageEditing(item.id, true);
}}
>
diff --git a/src/features/Conversation/Messages/Tool/index.tsx b/src/features/Conversation/Messages/Tool/index.tsx
index 8c1a2578d8d..1deeeb0e0db 100644
--- a/src/features/Conversation/Messages/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Tool/index.tsx
@@ -4,6 +4,8 @@ import isEqual from 'fast-deep-equal';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { dataSelectors, useConversationStore } from '../../store';
import Tool from './Tool';
@@ -15,6 +17,7 @@ interface ToolMessageProps {
const ToolMessage = memo<ToolMessageProps>(({ disableEditing, id, index }) => {
const { t } = useTranslation('plugin');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const item = useConversationStore(dataSelectors.getDbMessageById(id), isEqual) as UIChatMessage;
const deleteToolMessage = useConversationStore((s) => s.deleteToolMessage);
const [loading, setLoading] = useState(false);
@@ -30,7 +33,7 @@ const ToolMessage = memo<ToolMessageProps>(({ disableEditing, id, index }) => {
return (
<Flexbox gap={4} paddingBlock={12}>
- {!disableEditing && (
+ {canEdit && !disableEditing && (
<Alert
title={t('inspector.orphanedToolCall')}
type={'secondary'}
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
new file mode 100644
index 00000000000..04ae8363880
--- /dev/null
+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
@@ -0,0 +1,63 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { UIChatMessage } from '@lobechat/types';
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { MessageActionBar } from './index';
+
+const permissionMock = vi.hoisted(() => ({
+ canEdit: true,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIconGroup: ({
+ items,
+ menu,
+ }: {
+ items: { key?: string }[];
+ menu?: { key?: string; type?: string }[];
+ }) => (
+ <div
+ data-items={items.map((item) => item.key).join(',')}
+ data-menu={menu?.map((item) => item.key || item.type).join(',') ?? ''}
+ data-testid="action-group"
+ />
+ ),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: permissionMock.canEdit, reason: '' }),
+}));
+
+vi.mock('./useBuildActions', () => ({
+ useBuildActions: () => ({
+ copy: { key: 'copy', label: 'Copy' },
+ del: { key: 'del', label: 'Delete' },
+ edit: { key: 'edit', label: 'Edit' },
+ regenerate: { key: 'regenerate', label: 'Regenerate' },
+ }),
+}));
+
+describe('MessageActionBar', () => {
+ it('limits workspace viewers to copy only', () => {
+ permissionMock.canEdit = false;
+
+ render(
+ <MessageActionBar
+ bar={['edit', 'copy', 'regenerate']}
+ menu={['edit', 'copy', 'del']}
+ ctx={{
+ data: { content: 'hello', role: 'assistant' } as UIChatMessage,
+ id: 'message-1',
+ role: 'assistant',
+ }}
+ />,
+ );
+
+ const group = screen.getByTestId('action-group');
+ expect(group).toHaveAttribute('data-items', 'copy');
+ expect(group).toHaveAttribute('data-menu', '');
+ });
+});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
index 5df7beecb0c..d37d0ae3e85 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
@@ -2,11 +2,14 @@ import type { ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui'
import { ActionIconGroup } from '@lobehub/ui';
import { memo, useCallback, useMemo } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import { type MessageActionItem, type MessageActionItemOrDivider } from '../../../types';
import { DIVIDER_KEY, type MessageActionContext, type MessageActionSlot } from './types';
import { useBuildActions } from './useBuildActions';
const DIVIDER: MessageActionItemOrDivider = { type: 'divider' };
+const VIEWER_BAR: MessageActionSlot[] = ['copy'];
const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {
if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;
@@ -74,9 +77,16 @@ interface MessageActionBarProps {
*/
export const MessageActionBar = memo<MessageActionBarProps>(({ ctx, bar, menu }) => {
const built = useBuildActions(ctx);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ const effectiveBar = canEdit ? bar : VIEWER_BAR;
+ const effectiveMenu = canEdit ? menu : undefined;
- const barItems = useMemo(() => resolveSlots(bar, built), [bar, built]);
- const menuItems = useMemo(() => (menu ? resolveSlots(menu, built) : undefined), [menu, built]);
+ const barItems = useMemo(() => resolveSlots(effectiveBar, built), [effectiveBar, built]);
+ const menuItems = useMemo(
+ () => (effectiveMenu ? resolveSlots(effectiveMenu, built) : undefined),
+ [effectiveMenu, built],
+ );
const items = useMemo(
() => barItems.filter((item) => !('disabled' in item && item.disabled)).map(stripHandleClick),
diff --git a/src/features/Conversation/components/Reaction/ReactionDisplay.tsx b/src/features/Conversation/components/Reaction/ReactionDisplay.tsx
index 5457ebe3b2d..d5117c744e6 100644
--- a/src/features/Conversation/components/Reaction/ReactionDisplay.tsx
+++ b/src/features/Conversation/components/Reaction/ReactionDisplay.tsx
@@ -5,6 +5,8 @@ import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import ReactionPicker from './ReactionPicker';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -66,6 +68,8 @@ interface ReactionDisplayProps {
const ReactionDisplay = memo<ReactionDisplayProps>(
({ reactions, onReactionClick, messageId, isActive }) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
if (reactions.length === 0) return null;
return (
@@ -74,13 +78,14 @@ const ReactionDisplay = memo<ReactionDisplayProps>(
<div
className={cx(styles.reactionTag, isActive?.(reaction.emoji) && styles.active)}
key={reaction.emoji}
- onClick={() => onReactionClick?.(reaction.emoji)}
+ style={{ cursor: canEdit ? undefined : 'default' }}
+ onClick={canEdit ? () => onReactionClick?.(reaction.emoji) : undefined}
>
<span>{reaction.emoji}</span>
{reaction.count > 1 && <span className={styles.count}>{reaction.count}</span>}
</div>
))}
- {messageId && <ReactionPicker messageId={messageId} />}
+ {canEdit && messageId && <ReactionPicker messageId={messageId} />}
</Flexbox>
);
},
diff --git a/src/features/Conversation/components/Reaction/ReactionPicker.tsx b/src/features/Conversation/components/Reaction/ReactionPicker.tsx
index 9aa891d5a99..c86897581c8 100644
--- a/src/features/Conversation/components/Reaction/ReactionPicker.tsx
+++ b/src/features/Conversation/components/Reaction/ReactionPicker.tsx
@@ -9,6 +9,7 @@ import { PlusIcon, SmilePlus } from 'lucide-react';
import { type FC, memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
@@ -70,11 +71,14 @@ interface ReactionPickerProps {
const ReactionPicker: FC<ReactionPickerProps> = memo(({ messageId, trigger }) => {
const { t } = useTranslation('chat');
const theme = useTheme();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const addReaction = useConversationStore((s) => s.addReaction);
const [open, setOpen] = useState(false);
const [showFullPicker, setShowFullPicker] = useState(false);
+ if (!canEdit) return null;
+
const handleSelect = (emoji: string) => {
addReaction(messageId, emoji);
setOpen(false);
diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
index d3d79635624..3688f11e3ff 100644
--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx
+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
@@ -12,6 +12,7 @@ import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { MSG_CONTENT_CLASSNAME } from '@/features/Conversation/ChatItem/components/MessageContent';
+import { usePermission } from '@/hooks/usePermission';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
@@ -54,6 +55,8 @@ export const useChatItemContextMenu = ({
const contextMenuMode = useUserStore(userGeneralSettingsSelectors.contextMenuMode);
const { message } = App.useApp();
const { t } = useTranslation('common');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const selectedTextRef = useRef<string | undefined>(undefined);
@@ -127,9 +130,27 @@ export const useChatItemContextMenu = ({
tts,
} = actionsBar;
+ const withPermission = (items: MenuItem[]) =>
+ !canEdit
+ ? items.filter((item) => 'key' in item && item.key === 'copy')
+ : items.map((item) => {
+ if ('type' in item && item.type === 'divider') return item;
+ if (['edit', 'del'].includes(String(item.key))) return { ...item, disabled: !canEdit };
+ if (
+ ['branching', 'delAndRegenerate', 'regenerate', 'translate', 'tts'].includes(
+ String(item.key),
+ )
+ ) {
+ return { ...item, disabled: !canCreate };
+ }
+ return item;
+ });
+
if (role === 'assistant') {
if (error) {
- return [edit, copy, divider, del, divider, regenerate].filter(Boolean) as MenuItem[];
+ return withPermission(
+ [edit, copy, divider, del, divider, regenerate].filter(Boolean) as MenuItem[],
+ );
}
const collapseAction = isCollapsed ? expand : collapse;
@@ -149,12 +170,14 @@ export const useChatItemContextMenu = ({
del,
);
- return list.filter(Boolean) as MenuItem[];
+ return withPermission(list.filter(Boolean) as MenuItem[]);
}
if (role === 'assistantGroup') {
if (error) {
- return [edit, copy, divider, del, divider, regenerate].filter(Boolean) as MenuItem[];
+ return withPermission(
+ [edit, copy, divider, del, divider, regenerate].filter(Boolean) as MenuItem[],
+ );
}
const collapseAction = isCollapsed ? expand : collapse;
@@ -169,7 +192,7 @@ export const useChatItemContextMenu = ({
del,
];
- return list.filter(Boolean) as MenuItem[];
+ return withPermission(list.filter(Boolean) as MenuItem[]);
}
if (role === 'user') {
@@ -179,11 +202,21 @@ export const useChatItemContextMenu = ({
list.push(divider, tts, translate, divider, regenerate, del);
- return list.filter(Boolean) as MenuItem[];
+ return withPermission(list.filter(Boolean) as MenuItem[]);
}
return [];
- }, [actionsBar, error, inThread, isCollapsed, isDevMode, isGroupSession, role]);
+ }, [
+ actionsBar,
+ canCreate,
+ canEdit,
+ error,
+ inThread,
+ isCollapsed,
+ isDevMode,
+ isGroupSession,
+ role,
+ ]);
const handleShare = useCallback(() => {
const item = getMessage();
@@ -218,6 +251,7 @@ export const useChatItemContextMenu = ({
switch (action.key) {
case 'edit': {
+ if (!canEdit) break;
toggleMessageEditing(id, true);
break;
}
@@ -228,10 +262,12 @@ export const useChatItemContextMenu = ({
}
case 'expand':
case 'collapse': {
+ if (!canEdit) break;
toggleMessageCollapsed(id);
break;
}
case 'branching': {
+ if (!canCreate) break;
if (!topic) {
message.warning(t('branchingRequiresSavedTopic'));
break;
@@ -240,10 +276,12 @@ export const useChatItemContextMenu = ({
break;
}
case 'del': {
+ if (!canEdit) break;
deleteMessage(id);
break;
}
case 'regenerate': {
+ if (!canCreate) break;
if (inPortalThread) {
resendThreadMessage(id);
} else if (role === 'assistant') {
@@ -256,6 +294,7 @@ export const useChatItemContextMenu = ({
break;
}
case 'delAndRegenerate': {
+ if (!canCreate) break;
if (inPortalThread) {
delAndResendThreadMessage(id);
} else {
@@ -264,22 +303,27 @@ export const useChatItemContextMenu = ({
break;
}
case 'tts': {
+ if (!canCreate) break;
ttsMessage(id);
break;
}
case 'share': {
+ if (!canEdit) break;
handleShare();
break;
}
}
if (action.keyPath?.[0] === 'translate') {
+ if (!canCreate) return;
const lang = action.keyPath.at(-1);
if (lang) translateMessage(id, lang);
}
},
[
copyMessage,
+ canCreate,
+ canEdit,
deleteMessage,
delAndRegenerateMessage,
delAndResendThreadMessage,
diff --git a/src/features/Conversation/hooks/useDoubleClickEdit.ts b/src/features/Conversation/hooks/useDoubleClickEdit.ts
index 927b297f0c0..9120cdd40cd 100644
--- a/src/features/Conversation/hooks/useDoubleClickEdit.ts
+++ b/src/features/Conversation/hooks/useDoubleClickEdit.ts
@@ -1,6 +1,8 @@
import { type MouseEventHandler } from 'react';
import { useCallback } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import { useConversationStore } from '../store';
interface UseDoubleClickEditProps {
@@ -16,11 +18,13 @@ export const useDoubleClickEdit = ({
error,
id,
}: UseDoubleClickEditProps) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);
return useCallback<MouseEventHandler<HTMLDivElement>>(
(e) => {
if (
+ !canEdit ||
disableEditing ||
error ||
id === 'default' ||
@@ -31,6 +35,6 @@ export const useDoubleClickEdit = ({
toggleMessageEditing(id, true);
},
- [role, disableEditing, toggleMessageEditing, id],
+ [role, canEdit, disableEditing, error, toggleMessageEditing, id],
);
};
diff --git a/src/features/DailyBrief/BriefCard.tsx b/src/features/DailyBrief/BriefCard.tsx
index 5c3d872e183..3208a6a6252 100644
--- a/src/features/DailyBrief/BriefCard.tsx
+++ b/src/features/DailyBrief/BriefCard.tsx
@@ -5,10 +5,10 @@ import { cssVar } from 'antd-style';
import { Check, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Time from '@/routes/(main)/home/features/components/Time';
import BriefCardActions from './BriefCardActions';
@@ -48,7 +48,7 @@ interface BriefCardProps {
const BriefCard = memo<BriefCardProps>(
({ brief, enableNavigation = true, onAfterResolve, onAfterAddComment }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('home');
const isResolved = Boolean(brief.resolvedAction);
const [expanded, setExpanded] = useState(false);
diff --git a/src/features/DailyBrief/index.tsx b/src/features/DailyBrief/index.tsx
index 70136e4069e..18ff1a251ab 100644
--- a/src/features/DailyBrief/index.tsx
+++ b/src/features/DailyBrief/index.tsx
@@ -2,11 +2,11 @@ import { Button, Flexbox } from '@lobehub/ui';
import { Newspaper } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import TopicChatDrawer from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';
import DocumentPreviewModal from '@/features/DocumentModal/Preview';
import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import GroupBlock from '@/routes/(main)/home/features/components/GroupBlock';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors } from '@/store/brief/selectors';
@@ -18,7 +18,7 @@ import { BriefCardSkeleton } from './BriefCardSkeleton';
const DailyBrief = memo(() => {
const { t } = useTranslation('home');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const isLogin = useUserStore(authSelectors.isLogin);
const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
useFetchBriefs(isLogin);
diff --git a/src/features/DesktopFileMenuBridge/index.tsx b/src/features/DesktopFileMenuBridge/index.tsx
index aa00fabf079..cb6e01b6e7e 100644
--- a/src/features/DesktopFileMenuBridge/index.tsx
+++ b/src/features/DesktopFileMenuBridge/index.tsx
@@ -3,8 +3,8 @@
import { SESSION_CHAT_URL } from '@lobechat/const';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCreateMenuItems } from '@/routes/(main)/home/_layout/hooks/useCreateMenuItems';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
@@ -16,7 +16,7 @@ import { useChatStore } from '@/store/chat';
*/
const DesktopFileMenuBridge = () => {
const { createAgent, createEmptyGroup, createPage } = useCreateMenuItems();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
diff --git a/src/features/DesktopNavigationBridge/index.tsx b/src/features/DesktopNavigationBridge/index.tsx
index aa04bde7fef..0750847ce20 100644
--- a/src/features/DesktopNavigationBridge/index.tsx
+++ b/src/features/DesktopNavigationBridge/index.tsx
@@ -2,10 +2,11 @@
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { memo, useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
const DesktopNavigationBridge = memo(() => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleNavigate = useCallback(
({ path, replace }: { path: string; replace?: boolean }) => {
diff --git a/src/features/DevPanel/RenderGallery/index.tsx b/src/features/DevPanel/RenderGallery/index.tsx
index aee5182e919..3e432d8c474 100644
--- a/src/features/DevPanel/RenderGallery/index.tsx
+++ b/src/features/DevPanel/RenderGallery/index.tsx
@@ -3,8 +3,9 @@
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { useEffect } from 'react';
-import { Outlet, useNavigate, useParams } from 'react-router-dom';
+import { Outlet, useParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -42,7 +43,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const DevtoolsLayout = () => {
const { menuItems } = useDevtoolsEntries();
const { identifier } = useParams<{ identifier: string }>();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
useEffect(() => {
const previousGroupState = useAgentGroupStore.getState();
diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsx
index 1c2ce9a5dce..c691cbb56bf 100644
--- a/src/features/EditorCanvas/EditorCanvas.tsx
+++ b/src/features/EditorCanvas/EditorCanvas.tsx
@@ -42,6 +42,8 @@ export interface EditorCanvasProps {
*/
autoSave?: boolean;
+ disabled?: boolean;
+
/**
* Document ID to load from server.
* When provided, component will use useSWR to fetch document data.
diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
new file mode 100644
index 00000000000..c2b0c05acd4
--- /dev/null
+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
@@ -0,0 +1,70 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { type IEditor } from '@lobehub/editor';
+import { render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import InternalEditor from './InternalEditor';
+
+const editorProps = vi.hoisted(() => ({
+ last: undefined as any,
+}));
+
+vi.mock('@lobehub/editor/react', () => ({
+ Editor: Object.assign(
+ vi.fn((props: any) => {
+ editorProps.last = props;
+ return <div data-testid="editor" />;
+ }),
+ { withProps: (plugin: unknown) => plugin },
+ ),
+ useEditorState: () => ({}),
+}));
+
+vi.mock('@lobehub/editor', () => ({
+ ReactImagePlugin: vi.fn(),
+ ReactLinkPlugin: vi.fn(),
+ ReactLiteXmlPlugin: vi.fn(),
+ ReactTablePlugin: vi.fn(),
+ ReactToolbarPlugin: vi.fn(),
+}));
+
+vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({
+ createChatInputRichPlugins: () => [],
+}));
+
+vi.mock('./InlineToolbar', () => ({
+ default: () => <div />,
+}));
+
+vi.mock('./useImageUpload', () => ({
+ useFileUpload: () => vi.fn(),
+ useImageUpload: () => vi.fn(),
+}));
+
+vi.mock('@lobechat/const', () => ({
+ isDesktop: false,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('InternalEditor readonly state', () => {
+ const editor = {
+ getDocument: vi.fn(),
+ getLexicalEditor: vi.fn(() => undefined),
+ setDocument: vi.fn(),
+ } as unknown as IEditor;
+
+ beforeEach(() => {
+ editorProps.last = undefined;
+ });
+
+ it('passes editable=false to the editor when disabled', () => {
+ render(<InternalEditor disabled editor={editor} />);
+
+ expect(editorProps.last?.editable).toBe(false);
+ });
+});
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index b9461fa1c91..2945fa006c9 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -98,6 +98,7 @@ export interface InternalEditorProps extends EditorCanvasProps {
const InternalEditor = memo<InternalEditorProps>(
({
contentChangeLockRef,
+ disabled,
editable = true,
editor,
extraPlugins,
@@ -272,6 +273,7 @@ const InternalEditor = memo<InternalEditorProps>(
// During document hydration (e.g. route switch), we only advance snapshot
// and skip external change callback to avoid false dirty checks.
if (contentChangeLockRef?.current) return;
+ if (disabled) return;
onContentChangeRef.current?.();
}
@@ -280,10 +282,13 @@ const InternalEditor = memo<InternalEditorProps>(
return () => {
unregister();
};
- }, [contentChangeLockRef, editor]); // Only depend on stable refs and editor
+ }, [contentChangeLockRef, disabled, editor]); // Only depend on stable refs and editor
return (
<div
+ style={
+ disabled ? { cursor: 'not-allowed', opacity: 0.65, pointerEvents: 'none' } : undefined
+ }
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
@@ -291,7 +296,7 @@ const InternalEditor = memo<InternalEditorProps>(
>
<Editor
content={''}
- editable={editable}
+ editable={editable && !disabled}
editor={editor}
placeholder={finalPlaceholder}
plugins={plugins}
diff --git a/src/features/Electron/navigation/useNavigationHistory.ts b/src/features/Electron/navigation/useNavigationHistory.ts
index b28cae26503..cff029a1677 100644
--- a/src/features/Electron/navigation/useNavigationHistory.ts
+++ b/src/features/Electron/navigation/useNavigationHistory.ts
@@ -3,16 +3,17 @@
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
import { matchRouteMeta } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';
import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { desktopRoutes } from '@/spa/router/desktopRouter.config';
import { useElectronStore } from '@/store/electron';
export const useNavigationHistory = () => {
const { t } = useTranslation('electron');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
const isNavigatingHistory = useElectronStore((s) => s.isNavigatingHistory);
diff --git a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx
index d59888396ab..46383b0cbee 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx
+++ b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx
@@ -5,8 +5,9 @@ import { cx } from 'antd-style';
import { Pin, PinOff } from 'lucide-react';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useElectronStore } from '@/store/electron';
import { type ResolvedTab } from '../TabBar/hooks/useResolvedTabs';
@@ -21,7 +22,7 @@ interface PageItemProps {
const PageItem = memo<PageItemProps>(({ item, isPinned, onClose }) => {
const { t } = useTranslation('electron');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
const styles = useStyles;
diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsx
index 65e3afd59af..3953e22d119 100644
--- a/src/features/Electron/titlebar/TabBar/index.tsx
+++ b/src/features/Electron/titlebar/TabBar/index.tsx
@@ -6,8 +6,9 @@ import { cx } from 'antd-style';
import { Plus } from 'lucide-react';
import { startTransition, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { electronSystemService } from '@/services/electron/system';
import { desktopRoutes } from '@/spa/router/desktopRouter.config';
import { type NewTabAction } from '@/spa/router/routeMeta';
@@ -30,8 +31,9 @@ const DEFAULT_NEW_TAB_ACTION: NewTabAction = {
const TabBar = () => {
const styles = useStyles;
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('electron');
+ const { allowed: canCreate, reason } = usePermission('create_content');
const viewportRef = useRef<HTMLDivElement>(null);
const { tabs, activeTabId } = useResolvedTabs();
const activateTab = useElectronStore((s) => s.activateTab);
@@ -123,14 +125,15 @@ const TabBar = () => {
}
}, [activeTabId, tabs]);
- const newTabAction: NewTabAction = useMemo(() => {
+ const newTabAction: NewTabAction | null = useMemo(() => {
+ if (!canCreate) return null;
if (!activeTabId) return DEFAULT_NEW_TAB_ACTION;
const activeTab = tabs.find((tab) => tab.tab.id === activeTabId);
if (!activeTab) return DEFAULT_NEW_TAB_ACTION;
const matched = matchRouteMeta(desktopRoutes, activeTab.tab.url);
return matched.meta?.createNewTab?.(matched.params) ?? DEFAULT_NEW_TAB_ACTION;
- }, [activeTabId, tabs]);
+ }, [activeTabId, tabs, canCreate]);
useWatchBroadcast('closeCurrentTabOrWindow', () => {
if (tabs.length > 1 && activeTabId) {
@@ -141,6 +144,8 @@ const TabBar = () => {
});
const handleNewTab = useCallback(async () => {
+ if (!canCreate) return;
+ if (!newTabAction) return;
let result;
try {
result = await newTabAction.onCreate();
@@ -152,7 +157,7 @@ const TabBar = () => {
addTab(result.url, result.cached, true);
startTransition(() => navigate(result.url));
- }, [newTabAction, addTab, navigate]);
+ }, [canCreate, newTabAction, addTab, navigate]);
useWatchBroadcast('createNewTab', () => {
void handleNewTab();
@@ -182,13 +187,16 @@ const TabBar = () => {
onCloseRight={handleCloseRight}
/>
))}
- <ActionIcon
- className={cx(electronStylish.nodrag, styles.newTabButton)}
- icon={Plus}
- size="small"
- title={t('tab.newTab')}
- onClick={handleNewTab}
- />
+ {(newTabAction || !canCreate) && (
+ <ActionIcon
+ className={cx(electronStylish.nodrag, styles.newTabButton)}
+ disabled={!canCreate}
+ icon={Plus}
+ size="small"
+ title={canCreate ? t('tab.newTab') : reason}
+ onClick={canCreate ? handleNewTab : undefined}
+ />
+ )}
</ScrollArea>
);
};
diff --git a/src/features/Messenger/AgentSelect.tsx b/src/features/Messenger/AgentSelect.tsx
index dc58cac7f5f..7b5f9bffc61 100644
--- a/src/features/Messenger/AgentSelect.tsx
+++ b/src/features/Messenger/AgentSelect.tsx
@@ -2,7 +2,7 @@
import { Avatar, Flexbox, Text } from '@lobehub/ui';
import { Select, type SelectProps } from '@lobehub/ui/base-ui';
-import { memo, useMemo } from 'react';
+import { memo, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
@@ -10,49 +10,79 @@ import { DEFAULT_AVATAR } from '@/const/meta';
import { messengerService } from '@/services/messenger';
interface AgentSelectProps extends Omit<SelectProps<string>, 'options' | 'value' | 'onChange'> {
+ /**
+ * When nothing is selected, auto-select the scope's inbox (LobeAI) agent once
+ * the list resolves. Used when the user switches scope so the active agent
+ * falls back to that scope's inbox instead of going empty.
+ */
+ defaultToInbox?: boolean;
onChange?: (agentId: string | undefined) => void;
value?: string;
+ /** Scope to list agents for: a workspace id, or null/undefined for personal. */
+ workspaceId?: string | null;
}
-const AgentSelect = memo<AgentSelectProps>(({ value, onChange, ...rest }) => {
- const { t: tCommon } = useTranslation('common');
- const agentsSWR = useSWR('messenger:agentsForBinding', () =>
- messengerService.listAgentsForBinding(),
- );
-
- const defaultAgentTitle = tCommon('defaultSession');
- const options = useMemo(
- () =>
- (agentsSWR.data ?? []).map((agent) => {
- const title = agent.title || defaultAgentTitle;
- return {
- label: (
- <Flexbox horizontal align={'center'} gap={8}>
- <Avatar
- avatar={agent.avatar || DEFAULT_AVATAR}
- background={agent.backgroundColor ?? undefined}
- size={20}
- />
- <Text ellipsis>{title}</Text>
- </Flexbox>
- ),
- title,
- value: agent.id,
- };
- }),
- [agentsSWR.data, defaultAgentTitle],
- );
-
- return (
- <Select
- showSearch
- options={options}
- value={value ?? null}
- onChange={(next) => onChange?.((next as string | null) ?? undefined)}
- {...rest}
- />
- );
-});
+const AgentSelect = memo<AgentSelectProps>(
+ ({ value, onChange, workspaceId, defaultToInbox, ...rest }) => {
+ const { t: tCommon } = useTranslation('common');
+ // Cascading fetch: agents are scoped to the selected `workspaceId` (or
+ // personal when null). The scope is part of the SWR key so switching scope
+ // refetches the right list.
+ const agentsSWR = useSWR(['messenger:agentsForBinding', workspaceId ?? null], () =>
+ messengerService.listAgentsForBinding(workspaceId),
+ );
+
+ const defaultAgentTitle = tCommon('defaultSession');
+ const options = useMemo(
+ () =>
+ (agentsSWR.data ?? []).map((agent) => {
+ const title = agent.title || defaultAgentTitle;
+ return {
+ label: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Avatar
+ avatar={agent.avatar || DEFAULT_AVATAR}
+ background={agent.backgroundColor ?? undefined}
+ size={20}
+ />
+ <Text ellipsis>{title}</Text>
+ </Flexbox>
+ ),
+ title,
+ value: agent.id,
+ };
+ }),
+ [agentsSWR.data, defaultAgentTitle],
+ );
+
+ // Inbox (LobeAI) agent of the current scope, pinned to the top server-side.
+ const inboxAgentId = useMemo(
+ () => (agentsSWR.data ?? []).find((agent) => agent.isInbox)?.id,
+ [agentsSWR.data],
+ );
+
+ // When asked to default to the scope's inbox and nothing is selected, select
+ // it once the list resolves. Persists through the same onChange the dropdown
+ // uses. Deps stay stable across the persist round-trip, so this fires once
+ // per scope rather than looping.
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+ useEffect(() => {
+ if (!defaultToInbox || value || !inboxAgentId) return;
+ onChangeRef.current?.(inboxAgentId);
+ }, [defaultToInbox, value, inboxAgentId]);
+
+ return (
+ <Select
+ loading={agentsSWR.isLoading}
+ options={options}
+ value={value ?? null}
+ onChange={(next) => onChange?.((next as string | null) ?? undefined)}
+ {...rest}
+ />
+ );
+ },
+);
AgentSelect.displayName = 'MessengerAgentSelect';
diff --git a/src/features/Messenger/IntegrationDetail/Discord.tsx b/src/features/Messenger/IntegrationDetail/Discord.tsx
index 74bb23d4397..f7efe53cb37 100644
--- a/src/features/Messenger/IntegrationDetail/Discord.tsx
+++ b/src/features/Messenger/IntegrationDetail/Discord.tsx
@@ -5,6 +5,8 @@ import { LinkIcon, ServerIcon, Trash2Icon, UserIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { buildDiscordOpenBotUrl } from '../constants';
import { createMessengerLinkModal } from '../LinkModal';
import {
@@ -32,6 +34,8 @@ interface DiscordDetailProps {
// (`messenger.discord.connections.*`) makes that distinction explicit.
const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBack }) => {
const { t } = useTranslation('messenger');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const data = useMessengerData('discord');
const { handleSetActive, handleUnlink } = useLinkActions({
@@ -46,6 +50,7 @@ const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBa
});
const handleDisconnectInstallation = (id: string) =>
+ canEdit &&
disconnectInstallation(id, {
confirm: t('messenger.discord.connections.disconnectConfirm'),
failedKey: 'messenger.discord.connections.disconnectFailed',
@@ -65,6 +70,7 @@ const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBa
const headerAction = (
<Button
+ disabled={!canCreate || !canEdit}
icon={<Icon icon={LinkIcon} />}
type={hasInstallations ? 'default' : 'primary'}
onClick={handleOpenLink}
@@ -116,6 +122,7 @@ const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBa
status="pending"
action={
<Button
+ disabled={!canCreate || !canEdit}
href={buildDiscordOpenBotUrl(appId)}
icon={<Icon icon={LinkIcon} />}
size="small"
diff --git a/src/features/Messenger/IntegrationDetail/Slack.tsx b/src/features/Messenger/IntegrationDetail/Slack.tsx
index 8cc576f9bcc..c94734c1c39 100644
--- a/src/features/Messenger/IntegrationDetail/Slack.tsx
+++ b/src/features/Messenger/IntegrationDetail/Slack.tsx
@@ -5,6 +5,8 @@ import { BriefcaseIcon, LinkIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { createMessengerLinkModal } from '../LinkModal';
import {
ConnectionRow,
@@ -26,6 +28,8 @@ interface SlackDetailProps {
const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }) => {
const { t } = useTranslation('messenger');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const data = useMessengerData('slack');
const { handleSetActive, handleUnlink } = useLinkActions({
@@ -43,6 +47,7 @@ const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }
// dispatch is token-gated, so removing the install effectively kills the
// workspace integration even though the bot user remains in Slack.
const handleDisconnectInstallation = (id: string) =>
+ canEdit &&
disconnectInstallation(id, {
confirm: t('messenger.slack.connections.disconnectConfirm'),
failedKey: 'messenger.slack.connections.disconnectFailed',
@@ -61,6 +66,7 @@ const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }
const headerAction = (
<Button
+ disabled={!canCreate || !canEdit}
icon={<Icon icon={LinkIcon} />}
type={hasInstallations ? 'default' : 'primary'}
onClick={handleOpenLink}
@@ -94,6 +100,7 @@ const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }
action={
<Button
danger
+ disabled={!canEdit}
icon={<Icon icon={Trash2Icon} />}
size="small"
onClick={() => handleDisconnectInstallation(install.id)}
diff --git a/src/features/Messenger/IntegrationDetail/Telegram.tsx b/src/features/Messenger/IntegrationDetail/Telegram.tsx
index f6ae0c36e0a..c703483c7b5 100644
--- a/src/features/Messenger/IntegrationDetail/Telegram.tsx
+++ b/src/features/Messenger/IntegrationDetail/Telegram.tsx
@@ -5,6 +5,8 @@ import { LinkIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { createMessengerLinkModal } from '../LinkModal';
import {
DetailLayout,
@@ -27,6 +29,8 @@ interface TelegramDetailProps {
// header.
const TelegramDetail = memo<TelegramDetailProps>(({ appId, botUsername, name, onBack }) => {
const { t } = useTranslation('messenger');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const data = useMessengerData('telegram');
const { handleSetActive, handleUnlink } = useLinkActions({
@@ -46,11 +50,24 @@ const TelegramDetail = memo<TelegramDetailProps>(({ appId, botUsername, name, on
createMessengerLinkModal({ appId, botUsername, name, platform: 'telegram' });
const headerAction = hasLinks ? (
- <Button danger icon={<Icon icon={Trash2Icon} />} onClick={() => handleUnlink('')}>
+ <Button
+ danger
+ disabled={!canEdit}
+ icon={<Icon icon={Trash2Icon} />}
+ onClick={() => {
+ if (!canEdit) return;
+ handleUnlink('');
+ }}
+ >
{t('messenger.unlinkCta')}
</Button>
) : (
- <Button icon={<Icon icon={LinkIcon} />} type="primary" onClick={handleOpenLink}>
+ <Button
+ disabled={!canCreate || !canEdit}
+ icon={<Icon icon={LinkIcon} />}
+ type="primary"
+ onClick={handleOpenLink}
+ >
{t('messenger.linkCta')}
</Button>
);
diff --git a/src/features/Messenger/IntegrationDetail/shared.test.tsx b/src/features/Messenger/IntegrationDetail/shared.test.tsx
new file mode 100644
index 00000000000..fd971dcd4c1
--- /dev/null
+++ b/src/features/Messenger/IntegrationDetail/shared.test.tsx
@@ -0,0 +1,142 @@
+import { render, screen, within } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { UserAgentConnection } from './shared';
+
+const userState = {
+ isSignedIn: true,
+ user: {
+ avatar: 'user-avatar',
+ email: '[email protected]',
+ fullName: 'Demo Name',
+ username: 'demo-user',
+ },
+};
+
+vi.mock('@lobehub/ui', () => ({
+ Avatar: ({ avatar }: { avatar?: string }) => <span data-avatar={avatar} />,
+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Button: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (
+ <button onClick={onClick}>{children}</button>
+ ),
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Icon: () => <span />,
+ Skeleton: () => <span />,
+ Tag: ({ children }: { children?: ReactNode }) => (
+ <span data-testid="personal-tag">{children}</span>
+ ),
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Select: ({
+ classNames,
+ options,
+ }: {
+ classNames?: { value?: string };
+ options: { label: ReactNode; value: string }[];
+ }) => (
+ <div data-testid="scope-select" data-value-class={classNames?.value}>
+ {options.map((option) => (
+ <div data-testid={`scope-option-${option.value}`} key={option.value}>
+ {option.label}
+ </div>
+ ))}
+ </div>
+ ),
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({ message: { error: vi.fn(), success: vi.fn() } }),
+ },
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({
+ backButton: 'backButton',
+ card: 'card',
+ emptyRow: 'emptyRow',
+ rowIcon: 'rowIcon',
+ scopeValue: 'scopeValue',
+ }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { defaultValue?: string }) =>
+ ({
+ 'messenger.activeAgent': 'Active agent',
+ 'messenger.activeAgentPlaceholder': 'Select agent',
+ 'messenger.detail.connections.userLabel': 'User',
+ 'messenger.detail.disconnect': 'Disconnect',
+ 'messenger.scope': 'Scope',
+ 'messenger.scopePersonal': '个人',
+ })[key] ??
+ options?.defaultValue ??
+ key,
+ }),
+}));
+
+vi.mock('swr', () => ({
+ default: (key: string) => ({
+ data:
+ key === 'messenger:bindingScopes'
+ ? [{ avatar: 'workspace-avatar', id: 'workspace-1', name: 'love' }]
+ : undefined,
+ isLoading: false,
+ }),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true }),
+}));
+
+vi.mock('@/services/messenger', () => ({
+ messengerService: {
+ listBindingScopes: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: {
+ enableBusinessFeatures: () => true,
+ },
+ useServerConfigStore: (
+ selector: (state: { featureFlags: { enableWorkspace: boolean } }) => unknown,
+ ) => selector({ featureFlags: { enableWorkspace: true } }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: typeof userState) => unknown) => selector(userState),
+}));
+
+vi.mock('../AgentSelect', () => ({
+ default: () => <div data-testid="agent-select" />,
+}));
+
+describe('Messenger UserAgentConnection', () => {
+ it('uses the signed-in full name for the personal scope and shows the personal tag', () => {
+ render(
+ <UserAgentConnection
+ link={{
+ activeAgentId: null,
+ platformUserId: 'platform-user',
+ platformUsername: 'platform-name',
+ workspaceId: null,
+ }}
+ onSetActive={vi.fn()}
+ onUnlink={vi.fn()}
+ />,
+ );
+
+ const personalOption = screen.getByTestId('scope-option-personal');
+
+ expect(within(personalOption).getByText('Demo Name')).toBeInTheDocument();
+ expect(within(personalOption).queryByText('demo-user')).not.toBeInTheDocument();
+ expect(within(personalOption).getByTestId('personal-tag')).toHaveTextContent('personal');
+ expect(within(personalOption).queryByText('个人')).not.toBeInTheDocument();
+ expect(screen.getByTestId('scope-select')).toHaveAttribute('data-value-class', 'scopeValue');
+ });
+});
diff --git a/src/features/Messenger/IntegrationDetail/shared.tsx b/src/features/Messenger/IntegrationDetail/shared.tsx
index 707cd9148e5..4b4614a77f4 100644
--- a/src/features/Messenger/IntegrationDetail/shared.tsx
+++ b/src/features/Messenger/IntegrationDetail/shared.tsx
@@ -1,20 +1,30 @@
'use client';
import { Block, Button, Flexbox, Icon, Skeleton, Tag, Text } from '@lobehub/ui';
-import { confirmModal } from '@lobehub/ui/base-ui';
+import { confirmModal, Select } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles } from 'antd-style';
import { ArrowLeftIcon, CheckCircle2Icon, Trash2Icon, UserIcon } from 'lucide-react';
import type { ReactNode } from 'react';
-import { memo } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
+import { usePermission } from '@/hooks/usePermission';
import { messengerService } from '@/services/messenger';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import AgentSelect from '../AgentSelect';
import { type MessengerPlatform, PlatformAvatar } from '../constants';
import { getMessengerErrorMessage, type MessengerTranslationKey } from '../i18n';
+import {
+ buildMessengerScopeOptions,
+ messengerScopeSelectClassNames,
+ PERSONAL_SCOPE,
+ resolvePersonalScopeLabel,
+} from '../scopeOptions';
export const styles = createStaticStyles(({ css, cssVar }) => ({
backButton: css`
@@ -214,6 +224,8 @@ interface UserLinkLike {
activeAgentId: string | null;
platformUserId: string;
platformUsername: string | null;
+ /** Active scope of this link: a workspace id, or null for personal. */
+ workspaceId: string | null;
}
export const formatUserHandle = (link: UserLinkLike): string =>
@@ -222,16 +234,89 @@ export const formatUserHandle = (link: UserLinkLike): string =>
interface UserAgentConnectionProps {
extraLabel?: string;
link: UserLinkLike;
- onSetActive: (agentId: string | null) => void;
+ onSetActive: (agentId: string | null) => Promise<boolean>;
onUnlink: () => void;
}
export const UserAgentConnection = memo<UserAgentConnectionProps>(
({ extraLabel, link, onSetActive, onUnlink }) => {
const { t } = useTranslation('messenger');
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const enableWorkspaceScopes = useServerConfigStore(
+ (s) =>
+ serverConfigSelectors.enableBusinessFeatures(s) && s.featureFlags.enableWorkspace === true,
+ );
const handle = formatUserHandle(link);
const name = extraLabel ? `${handle} · ${extraLabel}` : handle;
+ // First-level "scope" selector — personal plus every workspace the user
+ // belongs to. The bot is a single shared bot; which LobeHub context a
+ // conversation runs in is the active agent's scope, so picking a scope just
+ // filters the agent list below. The active scope is persisted server-side
+ // only when an agent is chosen (it derives the workspace from the agent).
+ // `PERSONAL_SCOPE` is the sentinel for personal (null).
+ const scopesSWR = useSWR(enableWorkspaceScopes ? 'messenger:bindingScopes' : null, () =>
+ messengerService.listBindingScopes(),
+ );
+ const [scope, setScope] = useState<string>(
+ enableWorkspaceScopes ? (link.workspaceId ?? PERSONAL_SCOPE) : PERSONAL_SCOPE,
+ );
+ const userAvatar = useUserStore(userProfileSelectors.userAvatar);
+ const userDisplayName = useUserStore(userProfileSelectors.displayUserName);
+ const userFullName = useUserStore(userProfileSelectors.fullName);
+
+ // Mirror the Agent Transfer scope picker: each row is an avatar + name.
+ // Personal uses the user's avatar; workspaces use their own avatar.
+ const scopeOptions = useMemo(() => {
+ const personalLabel = resolvePersonalScopeLabel({
+ fallbackLabel: userDisplayName || t('messenger.scopePersonal'),
+ fullName: userFullName,
+ });
+
+ return buildMessengerScopeOptions({
+ personalAvatar: userAvatar,
+ personalLabel,
+ personalTagLabel: t('messenger.scopePersonalTag', { defaultValue: 'personal' }),
+ workspaces: scopesSWR.data,
+ });
+ }, [scopesSWR.data, t, userAvatar, userDisplayName, userFullName]);
+
+ const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;
+ const linkIsActiveScope = scopeWorkspaceId === (link.workspaceId ?? null);
+
+ useEffect(() => {
+ if (enableWorkspaceScopes || scope === PERSONAL_SCOPE) return;
+ setScope(PERSONAL_SCOPE);
+ }, [enableWorkspaceScopes, scope]);
+
+ // Optimistic selection for the currently-selected scope. Persisting the
+ // active agent does a server round-trip plus a `linksMutate()` refetch, so
+ // without this the dropdown only reflects the new pick once both finish.
+ // `pending` mirrors the user's choice immediately and is cleared once the
+ // link data catches up. Scoped by workspace so it only applies while the
+ // scope it was made in is selected.
+ const [pending, setPending] = useState<{
+ agentId: string | null;
+ workspaceId: string | null;
+ } | null>(null);
+ const pendingForScope = pending && pending.workspaceId === scopeWorkspaceId ? pending : null;
+
+ useEffect(() => {
+ if (!pending) return;
+ if (
+ (link.workspaceId ?? null) === pending.workspaceId &&
+ (link.activeAgentId ?? null) === pending.agentId
+ ) {
+ setPending(null);
+ }
+ }, [link.workspaceId, link.activeAgentId, pending]);
+
+ const activeAgentId = pendingForScope
+ ? pendingForScope.agentId
+ : linkIsActiveScope
+ ? (link.activeAgentId ?? null)
+ : null;
+
return (
<ConnectionRow
icon={<Icon icon={UserIcon} size="small" />}
@@ -239,20 +324,57 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(
name={name}
status="connected"
action={
- <Button danger icon={<Icon icon={Trash2Icon} />} size="small" onClick={onUnlink}>
+ <Button
+ danger
+ disabled={!canEdit}
+ icon={<Icon icon={Trash2Icon} />}
+ size="small"
+ onClick={() => {
+ if (!canEdit) return;
+ onUnlink();
+ }}
+ >
{t('messenger.detail.disconnect')}
</Button>
}
>
- <Flexbox gap={6}>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t('messenger.activeAgent')}
- </Text>
- <AgentSelect
- placeholder={t('messenger.activeAgentPlaceholder')}
- value={link.activeAgentId ?? undefined}
- onChange={(agentId) => onSetActive((agentId ?? null) as string | null)}
- />
+ <Flexbox horizontal align="flex-end" gap={12}>
+ <Flexbox flex={1} gap={6}>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('messenger.scope')}
+ </Text>
+ <Select
+ classNames={messengerScopeSelectClassNames}
+ disabled={!canEdit}
+ options={scopeOptions}
+ value={scope}
+ onChange={(next) => setScope((next as string | null) ?? PERSONAL_SCOPE)}
+ />
+ </Flexbox>
+ <Flexbox flex={1} gap={6}>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('messenger.activeAgent')}
+ </Text>
+ <AgentSelect
+ // Default to the scope's inbox agent when the selected scope has no
+ // agent yet (neither an optimistic pick nor a persisted one),
+ // rather than leaving the dropdown empty.
+ defaultToInbox={canEdit && !pendingForScope && !linkIsActiveScope}
+ disabled={!canEdit}
+ placeholder={t('messenger.activeAgentPlaceholder')}
+ value={activeAgentId ?? undefined}
+ workspaceId={scopeWorkspaceId}
+ onChange={async (agentId) => {
+ if (!canEdit) return;
+ const next = (agentId ?? null) as string | null;
+ // Reflect the pick immediately, then persist in the background.
+ setPending({ agentId: next, workspaceId: scopeWorkspaceId });
+ const ok = await onSetActive(next);
+ // Roll back to the persisted value if the update failed.
+ if (!ok) setPending(null);
+ }}
+ />
+ </Flexbox>
</Flexbox>
</ConnectionRow>
);
@@ -288,16 +410,16 @@ interface UseLinkActionsArgs {
platform: MessengerPlatform;
}
-export const useLinkActions = ({
- installationsMutate,
- linksMutate,
- name,
- platform,
-}: UseLinkActionsArgs) => {
+export const useLinkActions = ({ linksMutate, name, platform }: UseLinkActionsArgs) => {
const { t } = useTranslation('messenger');
const { message } = App.useApp();
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ // Returns whether the update succeeded so the caller can roll back its
+ // optimistic selection on failure.
+ const handleSetActive = async (tenantId: string, agentId: string | null): Promise<boolean> => {
+ if (!canEdit) return false;
- const handleSetActive = async (tenantId: string, agentId: string | null) => {
try {
await messengerService.setActiveAgent({
agentId,
@@ -306,12 +428,16 @@ export const useLinkActions = ({
});
await linksMutate();
message.success(t('messenger.setActiveSuccess'));
+ return true;
} catch (error) {
message.error(getMessengerErrorMessage(error, t, 'messenger.setActiveFailed'));
+ return false;
}
};
const handleUnlink = (tenantId: string) => {
+ if (!canEdit) return;
+
confirmModal({
content: t('messenger.unlinkConfirm', { platform: name }),
okButtonProps: { danger: true },
@@ -361,8 +487,11 @@ export const useDisconnectInstallation = ({
}: UseDisconnectInstallationArgs) => {
const { t } = useTranslation('messenger');
const { message } = App.useApp();
+ const { allowed: canEdit } = usePermission('edit_own_content');
return (id: string, copy: DisconnectInstallationCopy) => {
+ if (!canEdit) return;
+
confirmModal({
content: copy.confirm,
okButtonProps: { danger: true },
diff --git a/src/features/Messenger/LinkModal/Discord.tsx b/src/features/Messenger/LinkModal/Discord.tsx
index 7eb689b2330..f67d2bd299b 100644
--- a/src/features/Messenger/LinkModal/Discord.tsx
+++ b/src/features/Messenger/LinkModal/Discord.tsx
@@ -9,11 +9,12 @@ import { PlatformAvatar } from '../constants';
interface DiscordLinkBodyProps {
appId?: string;
+ disabled?: boolean;
/** Brand-name label (e.g. `"Discord"`) sourced from the registry. */
name: string;
}
-const DiscordLinkBody = memo<DiscordLinkBodyProps>(({ appId, name }) => {
+const DiscordLinkBody = memo<DiscordLinkBodyProps>(({ appId, disabled, name }) => {
const { t } = useTranslation('messenger');
// Route Discord installs through the LobeHub install endpoint so the OAuth
@@ -45,7 +46,8 @@ const DiscordLinkBody = memo<DiscordLinkBodyProps>(({ appId, name }) => {
</Flexbox>
<Button
block
- href="/api/agent/messenger/discord/install"
+ disabled={disabled}
+ href={disabled ? undefined : '/api/agent/messenger/discord/install'}
size="large"
target="_blank"
type="primary"
diff --git a/src/features/Messenger/LinkModal/Slack.tsx b/src/features/Messenger/LinkModal/Slack.tsx
index 92b7ec08caf..9ee9839362a 100644
--- a/src/features/Messenger/LinkModal/Slack.tsx
+++ b/src/features/Messenger/LinkModal/Slack.tsx
@@ -6,7 +6,11 @@ import { useTranslation } from 'react-i18next';
import { PlatformAvatar } from '../constants';
-const SlackLinkBody = memo(() => {
+interface SlackLinkBodyProps {
+ disabled?: boolean;
+}
+
+const SlackLinkBody = memo<SlackLinkBodyProps>(({ disabled }) => {
const { t } = useTranslation('messenger');
return (
@@ -22,7 +26,8 @@ const SlackLinkBody = memo(() => {
</Flexbox>
<Button
block
- href="/api/agent/messenger/slack/install"
+ disabled={disabled}
+ href={disabled ? undefined : '/api/agent/messenger/slack/install'}
size="large"
target="_blank"
type="primary"
diff --git a/src/features/Messenger/LinkModal/Telegram.tsx b/src/features/Messenger/LinkModal/Telegram.tsx
index eabf6e83e10..89ef54412c3 100644
--- a/src/features/Messenger/LinkModal/Telegram.tsx
+++ b/src/features/Messenger/LinkModal/Telegram.tsx
@@ -37,11 +37,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface TelegramLinkBodyProps {
botUsername?: string;
+ disabled?: boolean;
/** Brand-name label (e.g. `"Telegram"`) sourced from the registry. */
name: string;
}
-const TelegramLinkBody = memo<TelegramLinkBodyProps>(({ botUsername, name }) => {
+const TelegramLinkBody = memo<TelegramLinkBodyProps>(({ botUsername, disabled, name }) => {
const { t } = useTranslation('messenger');
if (!botUsername) {
@@ -72,7 +73,14 @@ const TelegramLinkBody = memo<TelegramLinkBodyProps>(({ botUsername, name }) =>
{t('messenger.linkModal.scanHint', { platform: name })}
</Text>
</Flexbox>
- <Button block href={deepLink} size="large" target="_blank" type="primary">
+ <Button
+ block
+ disabled={disabled}
+ href={disabled ? undefined : deepLink}
+ size="large"
+ target="_blank"
+ type="primary"
+ >
{t('messenger.linkModal.openCta', { platform: name })}
</Button>
</>
diff --git a/src/features/Messenger/Verify/Body/Discord.tsx b/src/features/Messenger/Verify/Body/Discord.tsx
index 84da11ff58a..bb401a06384 100644
--- a/src/features/Messenger/Verify/Body/Discord.tsx
+++ b/src/features/Messenger/Verify/Body/Discord.tsx
@@ -21,10 +21,11 @@ interface DiscordBodyProps {
randomId: string;
signInUrl: string;
tokenData?: PeekedToken | null;
+ userAvatar?: string | null;
}
const DiscordBody = memo<DiscordBodyProps>(
- ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData }) => {
+ ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData, userAvatar }) => {
const { t } = useTranslation('messenger');
const [done, setDone] = useState(false);
@@ -60,6 +61,7 @@ const DiscordBody = memo<DiscordBodyProps>(
infoRows={infoRows}
platform="discord"
randomId={randomId}
+ userAvatar={userAvatar}
blockingNotice={
rebindBlocked
? {
diff --git a/src/features/Messenger/Verify/Body/Slack.tsx b/src/features/Messenger/Verify/Body/Slack.tsx
index 5b69045005f..bf87a9c8fd7 100644
--- a/src/features/Messenger/Verify/Body/Slack.tsx
+++ b/src/features/Messenger/Verify/Body/Slack.tsx
@@ -21,10 +21,11 @@ interface SlackBodyProps {
randomId: string;
signInUrl: string;
tokenData?: PeekedToken | null;
+ userAvatar?: string | null;
}
const SlackBody = memo<SlackBodyProps>(
- ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData }) => {
+ ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData, userAvatar }) => {
const { t } = useTranslation('messenger');
const [done, setDone] = useState(false);
@@ -63,6 +64,7 @@ const SlackBody = memo<SlackBodyProps>(
infoRows={infoRows}
platform="slack"
randomId={randomId}
+ userAvatar={userAvatar}
blockingNotice={
rebindBlocked
? {
diff --git a/src/features/Messenger/Verify/Body/Telegram.tsx b/src/features/Messenger/Verify/Body/Telegram.tsx
index 33609b38afa..0d66830ee2b 100644
--- a/src/features/Messenger/Verify/Body/Telegram.tsx
+++ b/src/features/Messenger/Verify/Body/Telegram.tsx
@@ -21,10 +21,11 @@ interface TelegramBodyProps {
randomId: string;
signInUrl: string;
tokenData?: PeekedToken | null;
+ userAvatar?: string | null;
}
const TelegramBody = memo<TelegramBodyProps>(
- ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData }) => {
+ ({ existingLink, lobeAccount, platformMeta, randomId, signInUrl, tokenData, userAvatar }) => {
const { t } = useTranslation('messenger');
const [done, setDone] = useState(false);
@@ -58,6 +59,7 @@ const TelegramBody = memo<TelegramBodyProps>(
infoRows={infoRows}
platform="telegram"
randomId={randomId}
+ userAvatar={userAvatar}
blockingNotice={
rebindBlocked
? {
diff --git a/src/features/Messenger/Verify/Body/index.tsx b/src/features/Messenger/Verify/Body/index.tsx
index 801c144ba36..b6714548db9 100644
--- a/src/features/Messenger/Verify/Body/index.tsx
+++ b/src/features/Messenger/Verify/Body/index.tsx
@@ -16,6 +16,7 @@ interface BodyProps {
randomId: string;
signInUrl: string;
tokenData?: PeekedToken | null;
+ userAvatar?: string | null;
}
const Body = memo<BodyProps>(({ platform, ...rest }) => {
diff --git a/src/features/Messenger/Verify/Body/shared.tsx b/src/features/Messenger/Verify/Body/shared.tsx
index b8fac4a131c..ef37377c088 100644
--- a/src/features/Messenger/Verify/Body/shared.tsx
+++ b/src/features/Messenger/Verify/Body/shared.tsx
@@ -1,19 +1,29 @@
'use client';
import { Block, Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Select } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles } from 'antd-style';
import { AlertTriangleIcon, CheckCircle2Icon, LinkIcon } from 'lucide-react';
-import { memo, useEffect, useState } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import { ProductLogo } from '@/components/Branding';
import { messengerService } from '@/services/messenger';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import AgentSelect from '../../AgentSelect';
import { type MessengerPlatform, PlatformBrandIcon } from '../../constants';
import { getMessengerErrorMessage } from '../../i18n';
+import {
+ buildMessengerScopeOptions,
+ messengerScopeSelectClassNames,
+ PERSONAL_SCOPE,
+ resolvePersonalScopeLabel,
+} from '../../scopeOptions';
export const styles = createStaticStyles(({ css, cssVar }) => ({
bubble: css`
@@ -145,26 +155,73 @@ export interface ConfirmCardProps {
onSuccess: () => void;
platform: MessengerPlatform;
randomId: string;
+ /** Current user's avatar, used to label the "personal" scope option. */
+ userAvatar?: string | null;
}
export const ConfirmCard = memo<ConfirmCardProps>(
- ({ blockingNotice, infoRows, onSuccess, platform, randomId }) => {
+ ({ blockingNotice, infoRows, onSuccess, platform, randomId, userAvatar }) => {
const { t } = useTranslation('messenger');
const { message } = App.useApp();
-
- const agentsSWR = useSWR('messenger:agentsForBinding', () =>
- messengerService.listAgentsForBinding(),
+ const enableWorkspaceScopes = useServerConfigStore(
+ (s) =>
+ serverConfigSelectors.enableBusinessFeatures(s) && s.featureFlags.enableWorkspace === true,
);
+ // First-level scope selector — personal plus every workspace the user
+ // belongs to. Picking a scope just filters the agent list below; the
+ // backend derives the binding's workspace from the chosen agent on confirm.
+ const scopesSWR = useSWR(enableWorkspaceScopes ? 'messenger:bindingScopes' : null, () =>
+ messengerService.listBindingScopes(),
+ );
+ const [scope, setScope] = useState<string>(PERSONAL_SCOPE);
const [selectedAgentId, setSelectedAgentId] = useState<string | undefined>(undefined);
+ const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;
+ const userDisplayName = useUserStore(userProfileSelectors.displayUserName);
+ const userFullName = useUserStore(userProfileSelectors.fullName);
+
+ useEffect(() => {
+ if (enableWorkspaceScopes || scope === PERSONAL_SCOPE) return;
+ setScope(PERSONAL_SCOPE);
+ setSelectedAgentId(undefined);
+ }, [enableWorkspaceScopes, scope]);
+
+ // Scope-aware agent list. The SWR key matches AgentSelect's so the fetch is
+ // shared (single request per scope) and stays in sync as the scope changes.
+ const agentsSWR = useSWR(['messenger:agentsForBinding', scopeWorkspaceId], () =>
+ messengerService.listAgentsForBinding(scopeWorkspaceId),
+ );
+
const [confirming, setConfirming] = useState(false);
- // Default-select the first agent once loaded; user can change before confirming.
+ // Default-select the first agent (inbox is pinned to the top) once a scope's
+ // list loads. Resetting selectedAgentId on scope change re-triggers this so
+ // it re-defaults to the new scope's inbox.
useEffect(() => {
if (selectedAgentId || !agentsSWR.data?.length) return;
setSelectedAgentId(agentsSWR.data[0].id);
}, [agentsSWR.data, selectedAgentId]);
+ // Mirror the Messenger connection card's scope picker: avatar + name per row.
+ // Personal uses the user's avatar; workspaces use their own.
+ const scopeOptions = useMemo(() => {
+ const personalLabel = resolvePersonalScopeLabel({
+ fallbackLabel: userDisplayName || t('messenger.scopePersonal'),
+ fullName: userFullName,
+ });
+
+ return buildMessengerScopeOptions({
+ personalAvatar: userAvatar,
+ personalLabel,
+ personalTagLabel: t('messenger.scopePersonalTag', { defaultValue: 'personal' }),
+ workspaces: scopesSWR.data,
+ });
+ }, [scopesSWR.data, t, userAvatar, userDisplayName, userFullName]);
+
+ // Personal-only deployments (OSS) return no workspaces — hide the scope
+ // selector entirely so the experience is unchanged there.
+ const hasWorkspaces = enableWorkspaceScopes && (scopesSWR.data?.length ?? 0) > 0;
+
const isBlocked = !!blockingNotice;
const handleConfirm = async () => {
@@ -217,20 +274,38 @@ export const ConfirmCard = memo<ConfirmCardProps>(
)}
{!isBlocked && (
- <Flexbox gap={8} style={{ width: '100%' }}>
- <Text strong>{t('verify.confirm.defaultAgent')}</Text>
- {agentsSWR.data?.length === 0 ? (
- <Text type="warning">{t('verify.confirm.noAgents')}</Text>
- ) : (
- <AgentSelect
- placeholder={t('verify.confirm.defaultAgentPlaceholder')}
- value={selectedAgentId}
- onChange={setSelectedAgentId}
- />
+ <Flexbox gap={16} style={{ width: '100%' }}>
+ {hasWorkspaces && (
+ <Flexbox gap={8}>
+ <Text strong>{t('messenger.scope')}</Text>
+ <Select
+ classNames={messengerScopeSelectClassNames}
+ options={scopeOptions}
+ value={scope}
+ onChange={(next) => {
+ setScope((next as string | null) ?? PERSONAL_SCOPE);
+ // Re-default to the new scope's inbox agent.
+ setSelectedAgentId(undefined);
+ }}
+ />
+ </Flexbox>
)}
- <Text style={{ fontSize: 12 }} type="secondary">
- {t('verify.confirm.defaultAgentHint')}
- </Text>
+ <Flexbox gap={8}>
+ <Text strong>{t('verify.confirm.defaultAgent')}</Text>
+ {agentsSWR.data?.length === 0 ? (
+ <Text type="warning">{t('verify.confirm.noAgents')}</Text>
+ ) : (
+ <AgentSelect
+ placeholder={t('verify.confirm.defaultAgentPlaceholder')}
+ value={selectedAgentId}
+ workspaceId={scopeWorkspaceId}
+ onChange={setSelectedAgentId}
+ />
+ )}
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('verify.confirm.defaultAgentHint')}
+ </Text>
+ </Flexbox>
</Flexbox>
)}
diff --git a/src/features/Messenger/Verify/index.tsx b/src/features/Messenger/Verify/index.tsx
index 70c2f4b708e..6c6506906e9 100644
--- a/src/features/Messenger/Verify/index.tsx
+++ b/src/features/Messenger/Verify/index.tsx
@@ -156,6 +156,7 @@ const MessengerVerifyPage = memo(() => {
platform),
);
const lobeAccount = session?.user?.email ?? session?.user?.name ?? '';
+ const userAvatar = session?.user?.image ?? undefined;
return (
<Body
@@ -166,6 +167,7 @@ const MessengerVerifyPage = memo(() => {
randomId={randomId}
signInUrl={signInUrl}
tokenData={activeToken}
+ userAvatar={userAvatar}
/>
);
});
diff --git a/src/features/Messenger/index.tsx b/src/features/Messenger/index.tsx
index 6312c2109fc..de732cb9cdd 100644
--- a/src/features/Messenger/index.tsx
+++ b/src/features/Messenger/index.tsx
@@ -5,9 +5,10 @@ import { App } from 'antd';
import { createStaticStyles } from 'antd-style';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
import useSWR from 'swr';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { messengerService } from '@/services/messenger';
import { type MessengerPlatform, PlatformAvatar } from './constants';
@@ -45,7 +46,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const MessengerSettings = memo(() => {
const { t, ready } = useTranslation('messenger');
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ sub?: string }>();
const selected: MessengerPlatform | null = isMessengerPlatform(params.sub) ? params.sub : null;
// Tenant name from `?workspace=...` plus the platform it belongs to. When
diff --git a/src/features/Messenger/scopeOptions.tsx b/src/features/Messenger/scopeOptions.tsx
new file mode 100644
index 00000000000..08a69d1834e
--- /dev/null
+++ b/src/features/Messenger/scopeOptions.tsx
@@ -0,0 +1,107 @@
+import { Avatar, Flexbox, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+
+export const PERSONAL_SCOPE = 'personal';
+
+const styles = createStaticStyles(({ css }) => ({
+ personalTag: css`
+ cursor: default;
+ flex: none;
+ margin-block: 0;
+ margin-inline: auto 0;
+ `,
+ scopeName: css`
+ flex: 0 1 auto;
+ min-width: 0;
+ `,
+ scopeOption: css`
+ flex: 1 1 auto;
+ width: 100%;
+ min-width: 0;
+ `,
+ scopeTitle: css`
+ flex: 1;
+ min-width: 0;
+ `,
+ scopeValue: css`
+ > span {
+ display: flex;
+ width: 100%;
+ min-width: 0;
+ }
+ `,
+}));
+
+export const messengerScopeSelectClassNames = { value: styles.scopeValue };
+
+interface ResolvePersonalScopeLabelParams {
+ fallbackLabel: string;
+ fullName?: string | null;
+}
+
+export const resolvePersonalScopeLabel = ({
+ fallbackLabel,
+ fullName,
+}: ResolvePersonalScopeLabelParams): string => fullName?.trim() || fallbackLabel;
+
+interface ScopeWorkspace {
+ avatar?: string | null;
+ id: string;
+ name: string;
+}
+
+interface BuildMessengerScopeOptionsParams {
+ personalAvatar?: string | null;
+ personalLabel: string;
+ personalTagLabel: string;
+ workspaces?: ScopeWorkspace[];
+}
+
+const renderScopeOption = ({
+ avatar,
+ isPersonal,
+ label,
+ personalTagLabel,
+}: {
+ avatar?: string | null;
+ isPersonal?: boolean;
+ label: string;
+ personalTagLabel?: string;
+}) => (
+ <Flexbox horizontal align="center" className={styles.scopeOption} gap={8}>
+ <Avatar avatar={avatar || label} shape="square" size={20} />
+ <Flexbox horizontal align="center" className={styles.scopeTitle} gap={6}>
+ <Text ellipsis className={styles.scopeName}>
+ {label}
+ </Text>
+ </Flexbox>
+ {isPersonal && personalTagLabel && (
+ <Tag className={styles.personalTag} variant="filled">
+ {personalTagLabel}
+ </Tag>
+ )}
+ </Flexbox>
+);
+
+export const buildMessengerScopeOptions = ({
+ personalAvatar,
+ personalLabel,
+ personalTagLabel,
+ workspaces = [],
+}: BuildMessengerScopeOptionsParams) => [
+ {
+ label: renderScopeOption({
+ avatar: personalAvatar,
+ isPersonal: true,
+ label: personalLabel,
+ personalTagLabel,
+ }),
+ title: personalLabel,
+ value: PERSONAL_SCOPE,
+ },
+ ...workspaces.map((workspace) => ({
+ label: renderScopeOption({ avatar: workspace.avatar, label: workspace.name }),
+ title: workspace.name,
+ value: workspace.id,
+ })),
+];
diff --git a/src/features/ModelSelect/index.tsx b/src/features/ModelSelect/index.tsx
index afea4231d5b..8c3a6fa07e8 100644
--- a/src/features/ModelSelect/index.tsx
+++ b/src/features/ModelSelect/index.tsx
@@ -35,7 +35,10 @@ interface ModelOption {
value: string;
}
-interface ModelSelectProps extends Pick<SelectProps, 'loading' | 'size' | 'style' | 'variant'> {
+interface ModelSelectProps extends Pick<
+ SelectProps,
+ 'disabled' | 'loading' | 'size' | 'style' | 'variant'
+> {
defaultValue?: { model: string; provider?: string };
initialWidth?: boolean;
onChange?: (props: { model: string; provider: string }) => void;
@@ -52,6 +55,7 @@ const ModelSelect = memo<ModelSelectProps>(
showAbility = true,
requiredAbilities,
loading,
+ disabled,
size,
style,
variant,
@@ -108,6 +112,7 @@ const ModelSelect = memo<ModelSelectProps>(
<Select
className={styles.select}
defaultValue={`${value?.provider}/${value?.model}`}
+ disabled={disabled}
loading={loading}
options={options}
popupClassName={styles.popup}
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
index cb6cce47dd2..7b63009e96b 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
@@ -2,13 +2,15 @@ import { Switch } from 'antd';
import { memo } from 'react';
interface ContextCachingSwitchProps {
+ disabled?: boolean;
onChange?: (value: boolean) => void;
value?: boolean;
}
-const ContextCachingSwitch = memo<ContextCachingSwitchProps>(({ value, onChange }) => {
+const ContextCachingSwitch = memo<ContextCachingSwitchProps>(({ disabled, value, onChange }) => {
return (
<Switch
+ disabled={disabled}
size={'small'}
value={!value}
onChange={(checked) => {
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
index e6949a5773c..25f4fae0050 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
@@ -43,6 +43,7 @@ import ThinkingLevelSlider from './ThinkingLevelSlider';
import ThinkingSlider from './ThinkingSlider';
interface ControlsFormProps {
+ disabled?: boolean;
model?: string;
onUpdatingChange?: (updating: boolean) => void;
provider?: string;
@@ -63,7 +64,7 @@ const resolveEnableReasoningInitialValue = (config: LobeAgentChatConfig) => {
};
const ControlsForm = memo<ControlsFormProps>(
- ({ model: modelProp, onUpdatingChange, provider: providerProp }) => {
+ ({ disabled, model: modelProp, onUpdatingChange, provider: providerProp }) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
@@ -111,7 +112,7 @@ const ControlsForm = memo<ControlsFormProps>(
const items = [
{
- children: <ContextCachingSwitch />,
+ children: <ContextCachingSwitch disabled={disabled} />,
desc: (
<span style={isNarrow ? descNarrow : descWide}>
<Trans i18nKey={'extendParams.disableContextCaching.desc'} ns={'chat'}>
@@ -133,7 +134,7 @@ const ControlsForm = memo<ControlsFormProps>(
name: 'disableContextCaching',
},
{
- children: <Switch size={'small'} />,
+ children: <Switch disabled={disabled} size={'small'} />,
desc: (
<span style={isNarrow ? descNarrow : descWide}>
<Trans i18nKey={'extendParams.enableReasoning.desc'} ns={'chat'}>
@@ -147,7 +148,7 @@ const ControlsForm = memo<ControlsFormProps>(
name: 'enableReasoning',
},
{
- children: <Switch size={'small'} />,
+ children: <Switch disabled={disabled} size={'small'} />,
desc: isNarrow ? (
<span style={descNarrow}>{t('extendParams.preserveThinking.desc')}</span>
) : (
@@ -373,7 +374,7 @@ const ControlsForm = memo<ControlsFormProps>(
tag: 'thinkingBudget',
},
{
- children: <Switch size={'small'} />,
+ children: <Switch disabled={disabled} size={'small'} />,
desc: isNarrow ? (
<span style={descNarrow}>{t('extendParams.urlContext.desc')}</span>
) : (
@@ -487,27 +488,35 @@ const ControlsForm = memo<ControlsFormProps>(
].filter(Boolean) as FormItemProps[];
return (
- <Form
- form={form}
- initialValues={initialValues}
- itemsType={'flat'}
- size={'small'}
- style={{ fontSize: 12 }}
- variant={'borderless'}
- items={
- (modelExtendParams || [])
- .map((item: any) => items.find((i) => i.name === item))
- .filter(Boolean) as FormItemProps[]
- }
- onValuesChange={async (values) => {
- onUpdatingChange?.(true);
- try {
- await updateAgentChatConfig(values);
- } finally {
- onUpdatingChange?.(false);
- }
+ <div
+ style={{
+ opacity: disabled ? 0.5 : undefined,
+ pointerEvents: disabled ? 'none' : undefined,
}}
- />
+ >
+ <Form
+ form={form}
+ initialValues={initialValues}
+ itemsType={'flat'}
+ size={'small'}
+ style={{ fontSize: 12 }}
+ variant={'borderless'}
+ items={
+ (modelExtendParams || [])
+ .map((item: any) => items.find((i) => i.name === item))
+ .filter(Boolean) as FormItemProps[]
+ }
+ onValuesChange={async (values) => {
+ if (disabled) return;
+ onUpdatingChange?.(true);
+ try {
+ await updateAgentChatConfig(values);
+ } finally {
+ onUpdatingChange?.(false);
+ }
+ }}
+ />
+ </div>
);
},
);
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
index 1c78e921f06..5abbcb540c0 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
@@ -89,6 +89,7 @@ export interface LevelSliderProps<T extends string = string> {
* Default value when uncontrolled
*/
defaultValue?: T;
+ disabled?: boolean;
/**
* Ordered array of level values (left to right on slider)
*/
@@ -150,6 +151,7 @@ function LevelSlider<T extends string = string>({
onChange,
marks: customMarks,
style,
+ disabled,
}: LevelSliderProps<T>) {
const defaultLevel = defaultValue ?? levels[Math.floor(levels.length / 2)];
@@ -173,6 +175,8 @@ function LevelSlider<T extends string = string>({
const { minWidth: customMinWidth, ...restStyle } = style ?? {};
const handleChange = (index: number) => {
+ if (disabled) return;
+
const newLevel = levels[index];
if (newLevel !== undefined) {
setCurrentLevel(newLevel);
@@ -192,6 +196,7 @@ function LevelSlider<T extends string = string>({
<div className={styles.slider}>
<Slider
dots
+ disabled={disabled}
max={levels.length - 1}
min={0}
step={1}
@@ -211,10 +216,12 @@ function LevelSlider<T extends string = string>({
<button
aria-current={selected ? 'true' : undefined}
className={cx(styles.label, selected && styles.selectedLabel)}
+ disabled={disabled}
key={option.value}
style={option.style}
type="button"
onClick={() => {
+ if (disabled) return;
setCurrentLevel(option.value);
}}
>
diff --git a/src/features/ModelSwitchPanel/components/Footer.tsx b/src/features/ModelSwitchPanel/components/Footer.tsx
index 5bed7a50495..5c493cc89ef 100644
--- a/src/features/ModelSwitchPanel/components/Footer.tsx
+++ b/src/features/ModelSwitchPanel/components/Footer.tsx
@@ -3,7 +3,8 @@ import { cssVar } from 'antd-style';
import { LucideArrowRight, LucideBolt } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { styles } from '../styles';
@@ -13,7 +14,7 @@ interface FooterProps {
export const Footer: FC<FooterProps> = ({ onClose }) => {
const { t } = useTranslation('components');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return (
<Flexbox className={styles.footer} padding={4}>
diff --git a/src/features/ModelSwitchPanel/components/List/GenerationListItemRenderer.tsx b/src/features/ModelSwitchPanel/components/List/GenerationListItemRenderer.tsx
index 9af4f79a275..2bcc53af21d 100644
--- a/src/features/ModelSwitchPanel/components/List/GenerationListItemRenderer.tsx
+++ b/src/features/ModelSwitchPanel/components/List/GenerationListItemRenderer.tsx
@@ -16,15 +16,17 @@ import { LucideArrowRight, LucideBolt } from 'lucide-react';
import type { ComponentType } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { ProviderItemRender } from '@/components/ModelSelect';
import type { PricingMode } from '@/features/ModelSwitchPanel/components/ModelDetailPanel';
import ModelDetailPanel from '@/features/ModelSwitchPanel/components/ModelDetailPanel';
import { styles as modelSwitchPanelStyles } from '@/features/ModelSwitchPanel/styles';
import type { ListItem } from '@/features/ModelSwitchPanel/types';
import { menuKey } from '@/features/ModelSwitchPanel/utils';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import type { EnabledProviderWithModels } from '@/types/index';
import GenerationMultipleProvidersItem from './GenerationMultipleProvidersItem';
@@ -42,7 +44,8 @@ export interface GenerationListItemRendererProps {
const GenerationListItemRenderer = memo<GenerationListItemRendererProps>(
({ item, activeKey, onClose, onModelChange, enabledList, ModelItemComponent, pricingMode }) => {
const { t } = useTranslation('components');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const activeSlug = useActiveWorkspaceSlug();
const [detailOpen, setDetailOpen] = useState(false);
switch (item.type) {
@@ -89,7 +92,7 @@ const GenerationListItemRenderer = memo<GenerationListItemRendererProps>(
e.stopPropagation();
const url = urlJoin('/settings/provider', item.provider.id || 'all');
if (e.ctrlKey || e.metaKey) {
- window.open(url, '_blank');
+ window.open(buildWorkspaceAwarePath(url, activeSlug), '_blank');
} else {
navigate(url);
}
diff --git a/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx b/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
index 2a42167ea85..cc9c7dfacdb 100644
--- a/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
+++ b/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
@@ -14,10 +14,12 @@ import { cssVar, cx } from 'antd-style';
import { LucideArrowRight, LucideBolt } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { ModelItemRender, ProviderItemRender } from '@/components/ModelSelect';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
@@ -53,7 +55,8 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
subscribeScroll,
}) => {
const { t } = useTranslation('components');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const activeSlug = useActiveWorkspaceSlug();
const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
const [detailOpen, setDetailOpen] = useState(false);
@@ -109,7 +112,7 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
e.stopPropagation();
const url = urlJoin('/settings/provider', item.provider.id || 'all');
if (e.ctrlKey || e.metaKey) {
- window.open(url, '_blank');
+ window.open(buildWorkspaceAwarePath(url, activeSlug), '_blank');
} else {
navigate(url);
}
diff --git a/src/features/ModelSwitchPanel/hooks/usePanelHandlers.ts b/src/features/ModelSwitchPanel/hooks/usePanelHandlers.ts
index d0bcd7ab420..51cd946012e 100644
--- a/src/features/ModelSwitchPanel/hooks/usePanelHandlers.ts
+++ b/src/features/ModelSwitchPanel/hooks/usePanelHandlers.ts
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
interface UsePanelHandlersProps {
@@ -11,6 +12,7 @@ export const usePanelHandlers = ({
onModelChange: onModelChangeProp,
onOpenChange,
}: UsePanelHandlersProps) => {
+ const { allowed: canCreateContent } = usePermission('create_content');
const updateAgentConfig = useAgentStore((s) => s.updateAgentConfig);
const handleModelChange = useCallback(
@@ -18,6 +20,8 @@ export const usePanelHandlers = ({
// Defer store update so the panel close animation completes
// before React re-renders with new data (prevents detail panel flash).
setTimeout(() => {
+ if (!canCreateContent) return;
+
const params = { model: modelId, provider: providerId };
if (onModelChangeProp) {
onModelChangeProp(params);
@@ -26,7 +30,7 @@ export const usePanelHandlers = ({
}
}, 150);
},
- [onModelChangeProp, updateAgentConfig],
+ [canCreateContent, onModelChangeProp, updateAgentConfig],
);
const handleClose = useCallback(() => {
diff --git a/src/features/NavPanel/SideBarHeaderLayout.tsx b/src/features/NavPanel/SideBarHeaderLayout.tsx
index 9a6071e3684..15a120be067 100644
--- a/src/features/NavPanel/SideBarHeaderLayout.tsx
+++ b/src/features/NavPanel/SideBarHeaderLayout.tsx
@@ -8,9 +8,9 @@ import { ChevronRightIcon, HomeIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import { memo } from 'react';
import { flushSync } from 'react-dom';
-import { useNavigate } from 'react-router-dom';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { isModifierClick } from '@/utils/navigation';
import BackButton from './components/BackButton';
@@ -43,9 +43,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+type BreadcrumbItem = NonNullable<BreadcrumbProps['items']>[number];
+
interface SideBarHeaderLayoutProps {
backTo?: string;
breadcrumb?: BreadcrumbProps['items'];
+ /** Override the leading home breadcrumb item (defaults to home icon → `/`). */
+ homeItem?: BreadcrumbItem;
left?: ReactNode;
right?: ReactNode;
showBack?: boolean;
@@ -59,9 +63,10 @@ const SideBarHeaderLayout = memo<SideBarHeaderLayoutProps>(
backTo = '/',
showBack = true,
breadcrumb = [],
+ homeItem,
showTogglePanelButton = true,
}) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const leftContent = left ? (
<Flexbox
horizontal
@@ -87,7 +92,7 @@ const SideBarHeaderLayout = memo<SideBarHeaderLayoutProps>(
className={styles.breadcrumb}
separator={<Icon icon={ChevronRightIcon} />}
items={[
- {
+ homeItem ?? {
href: '/',
title: <Icon icon={HomeIcon} />,
},
diff --git a/src/features/NavPanel/components/BackButton.tsx b/src/features/NavPanel/components/BackButton.tsx
index 61fe0aa4812..a501c5bbad7 100644
--- a/src/features/NavPanel/components/BackButton.tsx
+++ b/src/features/NavPanel/components/BackButton.tsx
@@ -4,14 +4,19 @@ import { ChevronLeftIcon } from 'lucide-react';
import { memo } from 'react';
import { Link } from 'react-router-dom';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
export const BACK_BUTTON_ID = 'lobe-back-button';
const BackButton = memo<ActionIconProps & { to?: string }>(({ to = '/', onClick, ...rest }) => {
+ const activeSlug = useActiveWorkspaceSlug();
+ const resolvedTo = buildWorkspaceAwarePath(to, activeSlug);
+
return (
// @ts-expect-error
- <Link to={to} onClick={onClick}>
+ <Link to={resolvedTo} onClick={onClick}>
<ActionIcon
icon={ChevronLeftIcon}
id={BACK_BUTTON_ID}
diff --git a/src/features/NavPanel/components/BackNav.tsx b/src/features/NavPanel/components/BackNav.tsx
index 15bfeaf98be..f5cbf8aeb8a 100644
--- a/src/features/NavPanel/components/BackNav.tsx
+++ b/src/features/NavPanel/components/BackNav.tsx
@@ -4,9 +4,10 @@ import { ChevronLeftIcon } from 'lucide-react';
import { type MouseEvent, type PropsWithChildren, type ReactNode, useCallback } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+import { Link } from 'react-router-dom';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { isModifierClick } from '@/utils/navigation';
import ToggleLeftPanelButton from '../ToggleLeftPanelButton';
@@ -25,7 +26,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const BackLink = ({ children }: { children: ReactNode }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleClick = useCallback(
(e: MouseEvent) => {
if (isModifierClick(e)) return;
diff --git a/src/features/NavPanel/components/EmptyNavItem.tsx b/src/features/NavPanel/components/EmptyNavItem.tsx
index 961c71c27f6..e34ef0cc865 100644
--- a/src/features/NavPanel/components/EmptyNavItem.tsx
+++ b/src/features/NavPanel/components/EmptyNavItem.tsx
@@ -4,22 +4,24 @@ import { memo } from 'react';
interface EmptyStatusProps {
className?: string;
+ disabled?: boolean;
onClick: () => void;
title: string;
}
-const EmptyNavItem = memo<EmptyStatusProps>(({ title, onClick, className }) => {
+const EmptyNavItem = memo<EmptyStatusProps>(({ title, onClick, className, disabled }) => {
return (
<Block
- clickable
horizontal
align={'center'}
className={className}
+ clickable={!disabled}
gap={8}
height={32}
paddingInline={2}
+ style={disabled ? { cursor: 'not-allowed', opacity: 0.5 } : undefined}
variant={'borderless'}
- onClick={onClick}
+ onClick={disabled ? undefined : onClick}
>
<Center flex={'none'} height={28} width={28}>
<Icon icon={PlusIcon} size={'small'} />
diff --git a/src/features/NavPanel/index.test.tsx b/src/features/NavPanel/index.test.tsx
new file mode 100644
index 00000000000..03f1939f4d4
--- /dev/null
+++ b/src/features/NavPanel/index.test.tsx
@@ -0,0 +1,224 @@
+import { render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+let pathname = '/lobe-team/settings/general';
+
+interface WorkspaceMock {
+ activeWorkspaceId: string;
+ workspaces: { id: string; slug: string }[];
+}
+
+interface NavPanelDraggableMockProps {
+ activeContent: {
+ key: string;
+ node: ReactNode;
+ };
+}
+
+const workspaceState: WorkspaceMock = {
+ activeWorkspaceId: 'workspace-1',
+ workspaces: [{ id: 'workspace-1', slug: 'lobe-team' }],
+};
+
+vi.mock('react-router-dom', () => ({
+ useLocation: () => ({ pathname }),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () =>
+ workspaceState.workspaces.find((workspace) => workspace.id === workspaceState.activeWorkspaceId)
+ ?.slug ?? null,
+}));
+
+vi.mock('@/routes/(main)/home/_layout/SidebarContent', () => ({
+ default: () => <div>Home sidebar</div>,
+}));
+
+vi.mock('@/features/WorkspaceSetting/SideBar/Content', () => ({
+ default: () => <div>Workspace settings sidebar</div>,
+}));
+
+vi.mock('@/routes/(main)/settings/_layout/SidebarContent', () => ({
+ default: () => <div>Personal settings sidebar</div>,
+}));
+
+vi.mock('@/routes/(main)/agent/_layout/Sidebar/Content', () => ({
+ default: () => <div>Agent sidebar</div>,
+}));
+
+vi.mock('@/routes/(main)/group/_layout/Sidebar/Content', () => ({
+ default: () => <div>Group sidebar</div>,
+}));
+
+vi.mock('@/routes/(main)/community/_layout/Sidebar/Content', () => ({
+ default: () => <div>Community sidebar</div>,
+}));
+
+vi.mock('./components/NavPanelDraggable', () => ({
+ NavPanelDraggable: ({ activeContent }: NavPanelDraggableMockProps) => (
+ <div data-nav-key={activeContent.key} data-testid="nav-panel">
+ {activeContent.node}
+ </div>
+ ),
+}));
+
+describe('NavPanel', () => {
+ beforeEach(() => {
+ pathname = '/lobe-team/settings/general';
+ });
+
+ it('uses workspace settings sidebar instead of a stale home snapshot on workspace settings routes', async () => {
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Stale home snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('Workspace settings sidebar')).toBeInTheDocument();
+ });
+ expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ });
+
+ it('uses personal settings sidebar instead of a stale home snapshot on user settings routes', async () => {
+ pathname = '/settings/profile';
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Stale home snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('Personal settings sidebar')).toBeInTheDocument();
+ });
+ expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ });
+
+ it('uses agent sidebar instead of a stale home snapshot on workspace agent routes', async () => {
+ pathname = '/lobe-team/agent/agent-1';
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Stale home snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'agent');
+ });
+ expect(screen.getByText('Agent sidebar')).toBeInTheDocument();
+ expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ });
+
+ it.each([
+ '/lobe-team/resource',
+ '/lobe-team/community',
+ '/lobe-team/memory',
+ '/lobe-team/page',
+ '/lobe-team/image',
+ '/lobe-team/video',
+ '/lobe-team/eval',
+ '/lobe-team/group/group-1',
+ ])('does not keep a stale home snapshot on %s', async (route) => {
+ pathname = route;
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Stale home snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ });
+ expect(screen.getByTestId('nav-panel')).not.toHaveAttribute('data-nav-key', 'home');
+ });
+
+ it.each(['/group/group-1', '/group/group-1/profile', '/lobe-team/group/group-1/profile'])(
+ 'uses the group sidebar fallback instead of a stale home snapshot on %s',
+ async (route) => {
+ pathname = route;
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Stale home snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'group');
+ });
+ expect(screen.getByText('Group sidebar')).toBeInTheDocument();
+ expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ },
+ );
+
+ it('uses the group sidebar fallback before its route portal registers', async () => {
+ pathname = '/group/group-1/profile';
+ const { default: NavPanel } = await import('./index');
+
+ render(<NavPanel />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'group');
+ });
+ expect(screen.getByText('Group sidebar')).toBeInTheDocument();
+ });
+
+ it('uses the community sidebar fallback before its route portal registers', async () => {
+ pathname = '/lobe-team/community';
+ const { default: NavPanel } = await import('./index');
+
+ render(<NavPanel />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'discover');
+ });
+ expect(screen.getByText('Community sidebar')).toBeInTheDocument();
+ });
+
+ it.each(['/lobe-team/tasks', '/lobe-team/task/task-1'])(
+ 'keeps the home sidebar on %s because it has no route sidebar',
+ async (route) => {
+ pathname = route;
+ const { default: NavPanel, NavPanelPortal } = await import('./index');
+
+ render(
+ <>
+ <NavPanelPortal navKey="home">
+ <div>Home navigation snapshot</div>
+ </NavPanelPortal>
+ <NavPanel />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('Home navigation snapshot')).toBeInTheDocument();
+ });
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'home');
+ },
+ );
+});
diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsx
index 03db988a96b..359258d26b0 100644
--- a/src/features/NavPanel/index.tsx
+++ b/src/features/NavPanel/index.tsx
@@ -1,9 +1,16 @@
'use client';
import { type PropsWithChildren, type ReactNode } from 'react';
-import { memo, useLayoutEffect, useSyncExternalStore } from 'react';
+import { memo, useLayoutEffect, useRef, useSyncExternalStore } from 'react';
+import { useLocation } from 'react-router-dom';
-import Sidebar from '@/routes/(main)/home/_layout/Sidebar';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import WorkspaceSettingsSideBarContent from '@/features/WorkspaceSetting/SideBar/Content';
+import AgentSidebarContent from '@/routes/(main)/agent/_layout/Sidebar/Content';
+import CommunitySidebarContent from '@/routes/(main)/community/_layout/Sidebar/Content';
+import GroupSidebarContent from '@/routes/(main)/group/_layout/Sidebar/Content';
+import SidebarContent from '@/routes/(main)/home/_layout/SidebarContent';
+import SettingsSidebarContent from '@/routes/(main)/settings/_layout/SidebarContent';
import { NavPanelDraggable } from './components/NavPanelDraggable';
@@ -35,21 +42,123 @@ export const resetNavPanel = () => {
};
const FALLBACK_NAV_KEY = 'home';
+const AGENT_NAV_KEY = 'agent';
+const GROUP_NAV_KEY = 'group';
+const COMMUNITY_NAV_KEY = 'discover';
+const EMPTY_NAV_KEY = 'empty';
+const SETTINGS_NAV_KEY = 'settings';
+const WORKSPACE_SETTINGS_NAV_KEY = 'workspace-settings';
+
+const DEDICATED_ROUTE_NAV_SEGMENTS = new Set([
+ 'community',
+ 'eval',
+ 'group',
+ 'image',
+ 'memory',
+ 'page',
+ 'resource',
+ 'video',
+]);
const getActiveNavKey = () => currentSnapshot?.key ?? FALLBACK_NAV_KEY;
export const useActiveNavKey = () =>
useSyncExternalStore(subscribeNavPanel, getActiveNavKey, getActiveNavKey);
+const getMainRouteSegment = (pathname: string, activeSlug: string | null) => {
+ const segments = pathname.split('/').filter(Boolean);
+ if (activeSlug && segments[0] === activeSlug) return segments[1];
+ return segments[0];
+};
+
const NavPanel = memo(() => {
+ const { pathname } = useLocation();
+ const activeSlug = useActiveWorkspaceSlug();
const panelContent = useSyncExternalStore(
subscribeNavPanel,
getNavPanelSnapshot,
getNavPanelSnapshot,
);
- // Use home Content as fallback when no portal content is provided
- const activeContent = panelContent || { key: FALLBACK_NAV_KEY, node: <Sidebar /> };
+ const isWorkspaceSettingsRoute =
+ !!activeSlug &&
+ (pathname === `/${activeSlug}/settings` || pathname.startsWith(`/${activeSlug}/settings/`));
+ const isHomeRoute =
+ pathname === '/' ||
+ (!!activeSlug && (pathname === `/${activeSlug}` || pathname === `/${activeSlug}/`));
+ const isPersonalSettingsRoute = pathname === '/settings' || pathname.startsWith('/settings/');
+ const isWorkspaceAgentRoute =
+ !!activeSlug &&
+ (pathname === `/${activeSlug}/agent` || pathname.startsWith(`/${activeSlug}/agent/`));
+ const isPersonalAgentRoute = pathname === '/agent' || pathname.startsWith('/agent/');
+ const isWorkspaceGroupRoute =
+ !!activeSlug &&
+ (pathname === `/${activeSlug}/group` || pathname.startsWith(`/${activeSlug}/group/`));
+ const isPersonalGroupRoute = pathname === '/group' || pathname.startsWith('/group/');
+
+ const agentFallback =
+ isWorkspaceAgentRoute || isPersonalAgentRoute
+ ? {
+ key: AGENT_NAV_KEY,
+ node: <AgentSidebarContent />,
+ }
+ : null;
+
+ const groupFallback =
+ isWorkspaceGroupRoute || isPersonalGroupRoute
+ ? {
+ key: GROUP_NAV_KEY,
+ node: <GroupSidebarContent />,
+ }
+ : null;
+
+ const workspaceSettingsFallback = isWorkspaceSettingsRoute
+ ? {
+ key: WORKSPACE_SETTINGS_NAV_KEY,
+ node: <WorkspaceSettingsSideBarContent />,
+ }
+ : null;
+ const personalSettingsFallback = isPersonalSettingsRoute
+ ? {
+ key: SETTINGS_NAV_KEY,
+ node: <SettingsSidebarContent />,
+ }
+ : null;
+ const mainRouteSegment = getMainRouteSegment(pathname, activeSlug);
+ const communityFallback =
+ mainRouteSegment === 'community'
+ ? {
+ key: COMMUNITY_NAV_KEY,
+ node: <CommunitySidebarContent />,
+ }
+ : null;
+ const routeFallback =
+ agentFallback ||
+ groupFallback ||
+ workspaceSettingsFallback ||
+ personalSettingsFallback ||
+ communityFallback;
+ const hasDedicatedRouteNavPanel = DEDICATED_ROUTE_NAV_SEGMENTS.has(mainRouteSegment ?? '');
+ const isStaleHomeSnapshot =
+ panelContent?.key === FALLBACK_NAV_KEY && hasDedicatedRouteNavPanel && !isHomeRoute;
+
+ const resolvedPanelContent =
+ routeFallback && panelContent?.key === FALLBACK_NAV_KEY
+ ? routeFallback
+ : isStaleHomeSnapshot
+ ? null
+ : panelContent;
+
+ // Fallback renders the home sidebar's content directly — using `<Sidebar />`
+ // (the portal wrapper) here loops with the portal's unmount cleanup:
+ // mount fallback → portal sets snapshot → fallback unmounts → cleanup
+ // clears snapshot → mount fallback → …
+ const activeContent =
+ resolvedPanelContent ||
+ routeFallback ||
+ (isHomeRoute || !hasDedicatedRouteNavPanel
+ ? ({ key: FALLBACK_NAV_KEY, node: <SidebarContent /> } satisfies NavPanelSnapshot)
+ : ({ key: EMPTY_NAV_KEY, node: null } satisfies NavPanelSnapshot));
return (
<>
@@ -78,6 +187,9 @@ interface NavPanelPortalProps extends PropsWithChildren {
}
export const NavPanelPortal = memo<NavPanelPortalProps>(({ children, navKey = 'default' }) => {
+ const navKeyRef = useRef(navKey);
+ navKeyRef.current = navKey;
+
useLayoutEffect(() => {
if (!children) return;
@@ -85,8 +197,22 @@ export const NavPanelPortal = memo<NavPanelPortalProps>(({ children, navKey = 'd
key: navKey,
node: children,
});
- // Intentionally keep previous content until new one mounts.
}, [children, navKey]);
+ // Clear the snapshot on unmount if this portal still owns it. Without this,
+ // a route transition where the next layout's portal effect doesn't fire in
+ // the same commit (concurrent transitions, lazy boundaries, Fragment-key
+ // remounts) leaves the previous owner's snapshot in place — visible as a
+ // stale sidebar that may render empty under its new state (e.g. workspace
+ // settings sidebar after the active workspace is deleted).
+ useLayoutEffect(
+ () => () => {
+ if (currentSnapshot?.key === navKeyRef.current) {
+ setNavPanelSnapshot(null);
+ }
+ },
+ [],
+ );
+
return null;
});
diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsx
index 814446e3d9a..30e1d528917 100644
--- a/src/features/Onboarding/Agent/index.tsx
+++ b/src/features/Onboarding/Agent/index.tsx
@@ -10,13 +10,13 @@ import { Drawer } from 'antd';
import { History } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import Loading from '@/components/Loading/BrandTextLoading';
import { ONBOARDING_PRODUCTION_DEFAULT_MODEL } from '@/const/onboarding';
import { type ConversationHooks } from '@/features/Conversation/types';
import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';
import ModeSwitch from '@/features/Onboarding/components/ModeSwitch';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useOnboardingAgentTemplates } from '@/hooks/useOnboardingAgentTemplates';
import { useClientDataSWR, useOnlyFetchOnceSWR } from '@/libs/swr';
import OnboardingContainer from '@/routes/onboarding/_layout';
@@ -47,7 +47,7 @@ import { useOnboardingFollowUp } from './useOnboardingFollowUp';
const CLASSIC_ONBOARDING_PATH = '/onboarding/classic';
const RedirectToClassicOnboarding = memo(() => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
useEffect(() => {
navigate(CLASSIC_ONBOARDING_PATH, { replace: true });
diff --git a/src/features/Onboarding/components/ModeSwitch.tsx b/src/features/Onboarding/components/ModeSwitch.tsx
index 175da4a44fb..f1037492e9f 100644
--- a/src/features/Onboarding/components/ModeSwitch.tsx
+++ b/src/features/Onboarding/components/ModeSwitch.tsx
@@ -8,8 +8,9 @@ import { ChevronLeft, ChevronRight } from 'lucide-react';
import type { CSSProperties, ReactNode } from 'react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useServerConfigStore } from '@/store/serverConfig';
const COLLAPSED_STORAGE_KEY = 'LOBE_ONBOARDING_MODE_SWITCH_COLLAPSED';
@@ -66,7 +67,7 @@ interface ModeSwitchProps {
const ModeSwitch = memo<ModeSwitchProps>(({ actions, className, showLabel = false, style }) => {
const { t } = useTranslation('onboarding');
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const enableAgentOnboarding = useServerConfigStore((s) => s.featureFlags.enableAgentOnboarding);
const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);
diff --git a/src/features/PageEditor/Copilot/AgentSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/AgentSelector/useDropdownMenu.tsx
index 2dbb5ab8f58..d18236fb4f6 100644
--- a/src/features/PageEditor/Copilot/AgentSelector/useDropdownMenu.tsx
+++ b/src/features/PageEditor/Copilot/AgentSelector/useDropdownMenu.tsx
@@ -5,6 +5,7 @@ import { Trash2 } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useHomeStore } from '@/store/home';
interface UseDropdownMenuProps {
@@ -21,8 +22,11 @@ export const useDropdownMenu = ({
}: UseDropdownMenuProps): MenuProps['items'] => {
const { t } = useTranslation(['common', 'chat']);
const removeAgent = useHomeStore((s) => s.removeAgent);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const handleDelete = () => {
+ if (!canEdit) return;
+
confirmModal({
cancelText: t('cancel'),
content: t('confirmRemoveSessionItemAlert', { ns: 'chat' }),
@@ -42,11 +46,12 @@ export const useDropdownMenu = ({
return [
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'delete',
label: t('delete'),
onClick: handleDelete,
},
].filter(Boolean) as MenuProps['items'];
- }, [t, isBuiltinAgent, handleDelete]);
+ }, [canEdit, t, isBuiltinAgent, handleDelete]);
};
diff --git a/src/features/PageEditor/Copilot/CopilotModelSelect.tsx b/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
index 6ff1c34873d..da125041d31 100644
--- a/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
+++ b/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
@@ -7,6 +7,7 @@ import ActionPopover from '@/features/ChatInput/ActionBar/components/ActionPopov
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -37,6 +38,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const CopilotModelSelect = memo(() => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [settingsOpen, setSettingsOpen] = useState(false);
const agentId = useConversationStore(conversationSelectors.agentId);
@@ -55,9 +57,11 @@ const CopilotModelSelect = memo(() => {
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
+ if (!canEdit) return;
+
await updateAgentConfigById(agentId, params);
},
- [agentId, updateAgentConfigById],
+ [canEdit, agentId, updateAgentConfigById],
);
return (
@@ -68,7 +72,15 @@ const CopilotModelSelect = memo(() => {
provider={provider}
onModelChange={handleModelChange}
>
- <Center horizontal className={styles.trigger} height={28} paddingInline={6}>
+ <Center
+ horizontal
+ className={styles.trigger}
+ height={28}
+ paddingInline={6}
+ style={
+ canEdit ? undefined : { cursor: 'not-allowed', opacity: 0.5, pointerEvents: 'none' }
+ }
+ >
<Flexbox horizontal align={'center'} gap={2}>
<span className={styles.name}>{displayName}</span>
<ChevronDownIcon className={styles.chevron} size={12} />
@@ -77,17 +89,26 @@ const CopilotModelSelect = memo(() => {
</ModelSwitchPanel>
{isModelHasExtendParams && (
<ActionPopover
- content={<ControlsForm />}
+ content={<ControlsForm disabled={!canEdit} />}
minWidth={350}
open={settingsOpen}
placement={'topRight'}
trigger={'click'}
- onOpenChange={setSettingsOpen}
+ onOpenChange={(open) => {
+ if (!canEdit) return;
+
+ setSettingsOpen(open);
+ }}
>
<ActionIcon
+ disabled={!canEdit}
icon={Settings2Icon}
size={{ blockSize: 28, size: 16 }}
- onClick={() => setSettingsOpen(true)}
+ onClick={() => {
+ if (!canEdit) return;
+
+ setSettingsOpen(true);
+ }}
/>
</ActionPopover>
)}
diff --git a/src/features/PageEditor/EditorCanvas/index.tsx b/src/features/PageEditor/EditorCanvas/index.tsx
index 052f76d7fa1..b3663dff266 100644
--- a/src/features/PageEditor/EditorCanvas/index.tsx
+++ b/src/features/PageEditor/EditorCanvas/index.tsx
@@ -7,6 +7,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';
+import { usePermission } from '@/hooks/usePermission';
import { usePageEditorStore } from '../store';
import { useAskCopilotItem } from './useAskCopilotItem';
@@ -19,6 +20,7 @@ interface EditorCanvasProps {
const EditorCanvas = memo<EditorCanvasProps>(({ placeholder, style }) => {
const { t } = useTranslation(['file', 'ui']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const editor = usePageEditorStore((s) => s.editor);
const documentId = usePageEditorStore((s) => s.documentId);
@@ -33,6 +35,7 @@ const EditorCanvas = memo<EditorCanvasProps>(({ placeholder, style }) => {
return (
<SharedEditorCanvas
+ disabled={!canEdit}
documentId={documentId}
editor={editor}
extraPlugins={extraPlugins}
diff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsx
new file mode 100644
index 00000000000..95d90a47335
--- /dev/null
+++ b/src/features/PageEditor/Header/useMenu.test.tsx
@@ -0,0 +1,128 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useMenu } from './useMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobechat/const', () => ({
+ isDesktop: false,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: {
+ error: vi.fn(),
+ success: vi.fn(),
+ },
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('antd-style', () => ({
+ cssVar: {
+ colorTextTertiary: 'colorTextTertiary',
+ },
+ useResponsive: () => ({ lg: true }),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/document', () => ({
+ useDocumentStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/document/slices/editor', () => ({
+ editorSelectors: {
+ lastUpdatedTime: () => () => null,
+ },
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ duplicateDocument: vi.fn() }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ togglePageAgentPanel: vi.fn(),
+ toggleWideScreen: vi.fn(),
+ wideScreen: false,
+ }),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ wideScreen: (state: { wideScreen: boolean }) => state.wideScreen,
+ },
+}));
+
+vi.mock('../store', () => ({
+ usePageEditorStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ documentId: 'doc-1',
+ setRightPanelMode: vi.fn(),
+ }),
+ useStoreApi: () => ({
+ getState: () => ({
+ editor: {
+ getDocument: () => '# Hello',
+ },
+ handleCopyLink: vi.fn(),
+ handleDelete: vi.fn(),
+ title: 'Hello',
+ }),
+ }),
+}));
+
+const getMenuItem = (items: ReturnType<typeof useMenu>['menuItems'], key: string) =>
+ items.find((item) => item && 'key' in item && item.key === key);
+
+describe('PageEditor header menu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables mutating page actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() => useMenu());
+ const items = result.current.menuItems;
+
+ expect(getMenuItem(items, 'duplicate')).toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'delete')).toMatchObject({ disabled: true });
+
+ expect(getMenuItem(items, 'full-width')).not.toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'copy-link')).not.toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'version-history')).not.toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'export')).not.toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsx
index 02a10887a7c..3d006c55558 100644
--- a/src/features/PageEditor/Header/useMenu.tsx
+++ b/src/features/PageEditor/Header/useMenu.tsx
@@ -8,6 +8,8 @@ import { Clock3Icon, CopyPlus, Download, Link2, Maximize2, Trash2 } from 'lucide
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocumentTransferMenuItem';
+import { usePermission } from '@/hooks/usePermission';
import { useDocumentStore } from '@/store/document';
import { editorSelectors } from '@/store/document/slices/editor';
import { useFileStore } from '@/store/file';
@@ -26,6 +28,8 @@ export const useMenu = (): { menuItems: any[] } => {
const { lg = true } = useResponsive();
const documentId = usePageEditorStore((s) => s.documentId);
+ const { allowed: canCreatePage } = usePermission('create_content');
+ const { allowed: canEditPage } = usePermission('edit_own_content');
// Get lastUpdatedTime from DocumentStore
const lastUpdatedTime = useDocumentStore((s) =>
@@ -34,6 +38,7 @@ export const useMenu = (): { menuItems: any[] } => {
const duplicateDocument = useFileStore((s) => s.duplicateDocument);
const setRightPanelMode = usePageEditorStore((s) => s.setRightPanelMode);
+ const transferMenuItems = useDocumentTransferMenuItem(documentId) as DropdownItem[] | null;
const [togglePageAgentPanel, wideScreen, toggleWideScreen] = useGlobalStore((s) => [
s.togglePageAgentPanel,
@@ -45,6 +50,7 @@ export const useMenu = (): { menuItems: any[] } => {
const showViewModeSwitch = lg;
const handleDuplicate = async () => {
+ if (!canCreatePage) return;
if (!documentId) return;
try {
await duplicateDocument(documentId);
@@ -107,6 +113,7 @@ export const useMenu = (): { menuItems: any[] } => {
]
: []),
{
+ disabled: !canCreatePage,
icon: <Icon icon={CopyPlus} />,
key: 'duplicate',
label: t('pageList.duplicate'),
@@ -132,10 +139,12 @@ export const useMenu = (): { menuItems: any[] } => {
},
{
danger: true,
+ disabled: !canEditPage,
icon: <Icon icon={Trash2} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: async () => {
+ if (!canEditPage) return;
const state = storeApi.getState();
await state.handleDelete(t as any, message, state.onDelete);
},
@@ -143,6 +152,7 @@ export const useMenu = (): { menuItems: any[] } => {
{
type: 'divider' as const,
},
+ ...((transferMenuItems ?? []) as DropdownItem[]),
{
children: [
{
@@ -182,6 +192,8 @@ export const useMenu = (): { menuItems: any[] } => {
return items;
}, [
lastUpdatedTime,
+ canCreatePage,
+ canEditPage,
storeApi,
t,
message,
@@ -192,6 +204,7 @@ export const useMenu = (): { menuItems: any[] } => {
showViewModeSwitch,
handleDuplicate,
handleExportMarkdown,
+ transferMenuItems,
]);
return { menuItems };
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 15d6e4cf1ce..dd3c5241f0d 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -8,8 +8,10 @@ import { memo } from 'react';
import { CONVERSATION_MIN_WIDTH } from '@/const/layoutTokens';
import DiffAllToolbar from '@/features/EditorCanvas/DiffAllToolbar';
+import PageMetaBar from '@/features/PageEditor/PageMetaBar';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { usePageStore } from '@/store/page';
@@ -97,6 +99,7 @@ interface PageEditorCanvasProps {
}
const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader }) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const editor = usePageEditorStore((s) => s.editor);
const documentId = usePageEditorStore((s) => s.documentId);
const wideScreen = useGlobalStore(systemStatusSelectors.wideScreen);
@@ -118,9 +121,17 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader
<Flexbox flex={1} height={'100%'} style={styles.editorContainer}>
{!fullWidthHeader && headerSlot}
<Flexbox horizontal height={'100%'} style={styles.contentWrapper} width={'100%'}>
- <WideScreenContainer wrapperStyle={{ cursor: 'text' }} onClick={() => editor?.focus()}>
+ <WideScreenContainer
+ wrapperStyle={{ cursor: canEdit ? 'text' : 'not-allowed' }}
+ onClick={() => {
+ if (!canEdit) return;
+
+ editor?.focus();
+ }}
+ >
<Flexbox className={overrideStyles.editorContent} flex={1} style={editorContentStyle}>
<TitleSection />
+ <PageMetaBar />
<EditorCanvas />
</Flexbox>
</WideScreenContainer>
@@ -172,6 +183,7 @@ export const PageEditor: FC<PageEditorProps> = ({
title,
emoji,
}) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const deletePage = usePageStore((s) => s.deletePage);
return (
@@ -183,11 +195,27 @@ export const PageEditor: FC<PageEditorProps> = ({
pageId={pageId}
title={title}
onBack={onBack}
- onDelete={() => deletePage(pageId || '')}
onDocumentIdChange={onDocumentIdChange}
- onEmojiChange={onEmojiChange}
- onSave={onSave}
- onTitleChange={onTitleChange}
+ onDelete={() => {
+ if (!canEdit) return;
+
+ deletePage(pageId || '');
+ }}
+ onEmojiChange={(emoji) => {
+ if (!canEdit) return;
+
+ onEmojiChange?.(emoji);
+ }}
+ onSave={() => {
+ if (!canEdit) return;
+
+ onSave?.();
+ }}
+ onTitleChange={(nextTitle) => {
+ if (!canEdit) return;
+
+ onTitleChange?.(nextTitle);
+ }}
>
<PageEditorCanvas fullWidthHeader={fullWidthHeader} header={header} />
</PageEditorProvider>
diff --git a/src/features/PageEditor/PageMetaBar.tsx b/src/features/PageEditor/PageMetaBar.tsx
new file mode 100644
index 00000000000..f1e21357646
--- /dev/null
+++ b/src/features/PageEditor/PageMetaBar.tsx
@@ -0,0 +1,5 @@
+import { memo } from 'react';
+
+const PageMetaBar = memo(() => null);
+
+export default PageMetaBar;
diff --git a/src/features/PageEditor/TitleSection.tsx b/src/features/PageEditor/TitleSection.tsx
index e6949843bf7..e37ff5d1c7e 100644
--- a/src/features/PageEditor/TitleSection.tsx
+++ b/src/features/PageEditor/TitleSection.tsx
@@ -7,6 +7,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import EmojiPicker from '@/components/EmojiPicker';
+import { usePermission } from '@/hooks/usePermission';
import { useDocumentStore } from '@/store/document';
import { editorSelectors } from '@/store/document/slices/editor';
import { useGlobalStore } from '@/store/global';
@@ -17,6 +18,7 @@ import { usePageEditorStore } from './store';
const TitleSection = memo(() => {
const { t } = useTranslation('file');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const documentId = usePageEditorStore((s) => s.documentId);
@@ -56,14 +58,20 @@ const TitleSection = memo(() => {
title={t('pageEditor.chooseIcon')}
value={emoji}
onChange={(e) => {
+ if (!canEdit) return;
+
setEmoji(e);
setShowEmojiPicker(false);
}}
onDelete={() => {
+ if (!canEdit) return;
+
setEmoji(undefined);
setShowEmojiPicker(false);
}}
onOpenChange={(open) => {
+ if (!canEdit) return;
+
setShowEmojiPicker(open);
}}
/>
@@ -72,6 +80,7 @@ const TitleSection = memo(() => {
{/* Choose Icon button - only shown when no emoji */}
{!emoji && !showEmojiPicker && (
<Button
+ disabled={!canEdit}
icon={<Icon icon={SmilePlus} />}
size="small"
type="text"
@@ -81,6 +90,8 @@ const TitleSection = memo(() => {
width: 'fit-content',
}}
onClick={() => {
+ if (!canEdit) return;
+
setEmoji('📄');
setShowEmojiPicker(true);
}}
@@ -95,6 +106,7 @@ const TitleSection = memo(() => {
) : (
<TextArea
autoSize={{ minRows: 1 }}
+ disabled={!canEdit}
placeholder={t('pageEditor.titlePlaceholder')}
value={title}
variant={'borderless'}
@@ -108,9 +120,13 @@ const TitleSection = memo(() => {
}}
onChange={(e) => {
const truncated = truncateByWeightedLength(e.target.value, 100);
+ if (!canEdit) return;
+
setTitle(truncated);
}}
onKeyDown={(e) => {
+ if (!canEdit) return;
+
if (e.key === 'Enter') {
e.preventDefault();
handleTitleSubmit();
diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
index 6689f7e1aa8..140ce4c3767 100644
--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx
+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
@@ -12,6 +12,7 @@ import GuideModal from '@/components/GuideModal';
import GuideVideo from '@/components/GuideVideo';
import NavHeader from '@/features/NavHeader';
import useNotionImport from '@/features/ResourceManager/components/Header/hooks/useNotionImport';
+import { usePermission } from '@/hooks/usePermission';
import { useFileStore } from '@/store/file';
import { usePageStore } from '@/store/page';
import { DocumentSourceType } from '@/types/document';
@@ -77,6 +78,7 @@ interface PageExplorerPlaceholderProps {
const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
({ hasPages = false, knowledgeBaseId }) => {
const { t } = useTranslation(['file', 'common']);
+ const { allowed: canCreate } = usePermission('create_content');
const [isUploading, setIsUploading] = useState(false);
// Page-specific operations from pageStore
@@ -109,10 +111,14 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
const handleNotionImportWithLocalUpdate = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
+ if (!canCreate) return;
+
await notionImport.handleNotionImport(event);
};
const handleCreateDocument = async (content: string, title: string) => {
+ if (!canCreate) return;
+
if (!content) {
// For empty pages, use createNewPage which handles optimistic updates
await createNewPage(title);
@@ -165,6 +171,8 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
};
const handleUploadFile = async (file: File) => {
+ if (!canCreate) return false;
+
try {
setIsUploading(true);
@@ -259,6 +267,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
<Flexbox
className={styles.card}
padding={16}
+ style={canCreate ? undefined : { cursor: 'not-allowed', opacity: 0.5 }}
onClick={() => handleCreateDocument('', t('pageList.untitled'))}
>
<span className={styles.actionTitle}>{t('pageEditor.empty.createNewDocument')}</span>
@@ -276,14 +285,17 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
<Upload
accept=".md,.markdown,.pdf,.docx"
beforeUpload={handleUploadFile}
- disabled={isUploading}
+ disabled={!canCreate || isUploading}
multiple={false}
showUploadList={false}
>
<Flexbox
className={styles.card}
padding={16}
- style={{ opacity: isUploading ? 0.5 : 1 }}
+ style={{
+ cursor: canCreate ? undefined : 'not-allowed',
+ opacity: !canCreate || isUploading ? 0.5 : 1,
+ }}
>
<span className={styles.actionTitle}>
{isUploading ? 'Uploading...' : t('pageEditor.empty.uploadFiles')}
@@ -303,7 +315,12 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
<Flexbox
className={styles.card}
padding={16}
- onClick={notionImport.handleOpenNotionGuide}
+ style={canCreate ? undefined : { cursor: 'not-allowed', opacity: 0.5 }}
+ onClick={() => {
+ if (!canCreate) return;
+
+ notionImport.handleOpenNotionGuide();
+ }}
>
<span className={styles.actionTitle}>{t('pageEditor.empty.importNotion')}</span>
<div className={styles.glow} style={{ background: cssVar.geekblue }} />
diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..f873c9f1f16
--- /dev/null
+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx
@@ -0,0 +1,96 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useDropdownMenu } from './useDropdownMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: {
+ error: vi.fn(),
+ success: vi.fn(),
+ },
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('@/const/version', () => ({
+ isDesktop: false,
+}));
+
+vi.mock('@/features/Electron/titlebar/RecentlyViewed/plugins', () => ({
+ pluginRegistry: {
+ parseUrl: vi.fn(),
+ },
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ addTab: vi.fn() }),
+}));
+
+vi.mock('@/store/page', () => ({
+ usePageStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ duplicatePage: vi.fn(),
+ removePage: vi.fn(),
+ }),
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<ReturnType<typeof useDropdownMenu>>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('Page list item dropdown menu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables page management actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() =>
+ useDropdownMenu({ pageId: 'page-1', toggleEditing: vi.fn() }),
+ );
+ const items = result.current();
+
+ expect(getMenuItem(items, 'rename')).toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'duplicate')).toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'delete')).toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
index 02575a3cb8a..dd5bda22b87 100644
--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
@@ -5,9 +5,11 @@ import { App } from 'antd';
import { CopyPlus, PanelTop, Pencil, Trash2 } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocumentTransferMenuItem';
import { isDesktop } from '@/const/version';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useElectronStore } from '@/store/electron';
import { usePageStore } from '@/store/page';
@@ -22,12 +24,17 @@ export const useDropdownMenu = ({
}: ActionProps): (() => MenuProps['items']) => {
const { t } = useTranslation(['common', 'file']);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canCreatePage } = usePermission('create_content');
+ const { allowed: canEditPage } = usePermission('edit_own_content');
const addTab = useElectronStore((s) => s.addTab);
const removePage = usePageStore((s) => s.removePage);
const duplicatePage = usePageStore((s) => s.duplicatePage);
+ const transferMenuItems = useDocumentTransferMenuItem(pageId);
const handleDelete = () => {
+ if (!canEditPage) return;
+
confirmModal({
cancelText: t('cancel'),
content: t('pageEditor.deleteConfirm.content', { ns: 'file' }),
@@ -47,6 +54,8 @@ export const useDropdownMenu = ({
};
const handleDuplicate = async () => {
+ if (!canCreatePage) return;
+
try {
await duplicatePage(pageId);
} catch (error) {
@@ -73,26 +82,44 @@ export const useDropdownMenu = ({
]
: []),
{
+ disabled: !canEditPage,
icon: <Icon icon={Pencil} />,
key: 'rename',
label: t('rename'),
- onClick: () => toggleEditing(true),
+ onClick: () => {
+ if (!canEditPage) return;
+ toggleEditing(true);
+ },
},
{
+ disabled: !canCreatePage,
icon: <Icon icon={CopyPlus} />,
key: 'duplicate',
label: t('pageList.duplicate', { ns: 'file' }),
onClick: handleDuplicate,
},
+ ...(transferMenuItems ?? []),
{ type: 'divider' },
{
danger: true,
+ disabled: !canEditPage,
icon: <Icon icon={Trash2} />,
key: 'delete',
label: t('delete'),
onClick: handleDelete,
},
].filter(Boolean) as MenuProps['items'],
- [t, toggleEditing, handleDuplicate, handleDelete, pageId, addTab, navigate],
+ [
+ t,
+ toggleEditing,
+ handleDuplicate,
+ handleDelete,
+ canCreatePage,
+ canEditPage,
+ pageId,
+ addTab,
+ navigate,
+ transferMenuItems,
+ ],
);
};
diff --git a/src/features/Pages/PageLayout/DataSync.tsx b/src/features/Pages/PageLayout/DataSync.tsx
index 1a6b34f4e14..48b0bdb5a0e 100644
--- a/src/features/Pages/PageLayout/DataSync.tsx
+++ b/src/features/Pages/PageLayout/DataSync.tsx
@@ -1,12 +1,12 @@
-import { useNavigate } from 'react-router-dom';
import { createStoreUpdater } from 'zustand-utils';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePageStore } from '@/store/page';
const DataSync = () => {
const usePageStoreUpdater = createStoreUpdater(usePageStore);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
usePageStoreUpdater('navigate', navigate);
return null;
diff --git a/src/features/Pages/PageLayout/Header/AddButton.tsx b/src/features/Pages/PageLayout/Header/AddButton.tsx
index c815cea22ad..bb715ce978e 100644
--- a/src/features/Pages/PageLayout/Header/AddButton.tsx
+++ b/src/features/Pages/PageLayout/Header/AddButton.tsx
@@ -5,20 +5,25 @@ import { SquarePenIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { usePageStore } from '@/store/page';
const AddButton = memo(() => {
const { t } = useTranslation('file');
+ const { allowed: canCreate } = usePermission('create_content');
const createNewPage = usePageStore((s) => s.createNewPage);
const handleNewDocument = () => {
+ if (!canCreate) return;
+
const untitledTitle = t('pageList.untitled');
createNewPage(untitledTitle);
};
return (
<ActionIcon
+ disabled={!canCreate}
icon={SquarePenIcon}
title={t('header.newPageButton')}
size={{
diff --git a/src/features/PlanIcon/index.tsx b/src/features/PlanIcon/index.tsx
index abbdedf74c7..b6d9ef167c7 100644
--- a/src/features/PlanIcon/index.tsx
+++ b/src/features/PlanIcon/index.tsx
@@ -1,5 +1,5 @@
import { Plans } from '@lobechat/types';
-import { Center, Flexbox, Icon, Tag } from '@lobehub/ui';
+import { Center, Flexbox, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { Atom, Box, CircleSlash, Sparkle, Zap } from 'lucide-react';
import { type CSSProperties, type MouseEvent } from 'react';
@@ -47,11 +47,15 @@ export const themes = {
const styles = createStaticStyles(({ css }) => ({
icon: css`
flex: none;
- border-radius: ${cssVar.borderRadiusLG};
box-shadow: 0 0 0 1px ${cssVar.colorFillSecondary};
`,
}));
+const getPlanIconMetrics = (size: number) => ({
+ glyphSize: Math.max(12, Math.round(size / 2)),
+ radius: Math.max(8, Math.round(size / 3)),
+});
+
interface PlanIconProps {
className?: string;
mono?: boolean;
@@ -64,11 +68,12 @@ interface PlanIconProps {
const PlanIcon = memo<PlanIconProps>(
({ type = 'icon', plan, size = 36, mono, style, className, onClick }) => {
- const { icon, theme } = themes[plan];
+ const { icon: IconComponent, theme } = themes[plan];
const { t } = useTranslation('subscription');
const isTag = type === 'tag';
const isCombine = type === 'combine';
const isFree = plan === Plans.Free;
+ const { glyphSize, radius } = getPlanIconMetrics(size);
if (isTag) {
return (
@@ -91,19 +96,30 @@ const PlanIcon = memo<PlanIconProps>(
);
}
+ const iconStyle = {
+ ...(mono
+ ? null
+ : {
+ ...theme,
+ border: isFree ? undefined : `2px solid ${theme.color}`,
+ }),
+ alignItems: 'center',
+ borderRadius: radius,
+ display: 'flex',
+ justifyContent: 'center',
+ lineHeight: 0,
+ ...style,
+ } satisfies CSSProperties;
+
const iconContent = (
<Center
className={styles.icon}
height={size}
+ style={iconStyle}
width={size}
- style={
- mono
- ? style
- : { ...theme, border: isFree ? undefined : `2px solid ${theme.color}`, ...style }
- }
onClick={onClick}
>
- <Icon color={mono ? undefined : theme.color} icon={icon} size={size / 2} />
+ <IconComponent color={mono ? undefined : theme.color} size={glyphSize} />
</Center>
);
diff --git a/src/features/Portal/LocalFile/Header.tsx b/src/features/Portal/LocalFile/Header.tsx
index c471a76a838..d456125e15d 100644
--- a/src/features/Portal/LocalFile/Header.tsx
+++ b/src/features/Portal/LocalFile/Header.tsx
@@ -4,10 +4,11 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
import { ActionIcon } from '@lobehub/ui';
import { ArrowLeft, X } from 'lucide-react';
import { Fragment, memo } from 'react';
-import { useLocation, useNavigate, useParams } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
import NavHeader from '@/features/NavHeader';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -15,7 +16,7 @@ import TabStrip from './TabStrip';
const Header = memo(() => {
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ aid?: string; topicId?: string }>();
const [canGoBack, goBack, clearPortalStack] = useChatStore((s) => [
chatPortalSelectors.canGoBack(s),
diff --git a/src/features/Portal/components/Header.tsx b/src/features/Portal/components/Header.tsx
index 150fd98535f..35ed002f892 100644
--- a/src/features/Portal/components/Header.tsx
+++ b/src/features/Portal/components/Header.tsx
@@ -5,16 +5,17 @@ import { ActionIcon, Flexbox } from '@lobehub/ui';
import { ArrowLeft, X } from 'lucide-react';
import { Fragment, type ReactNode } from 'react';
import { memo } from 'react';
-import { useLocation, useNavigate, useParams } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
import NavHeader from '@/features/NavHeader';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
const Header = memo<{ rightExtra?: ReactNode; title: ReactNode }>(({ title, rightExtra }) => {
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ aid?: string; topicId?: string }>();
const [canGoBack, goBack, clearPortalStack] = useChatStore((s) => [
chatPortalSelectors.canGoBack(s),
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index 57faf28ef3b..9ba778feccf 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -25,6 +25,7 @@ import { createSkillStoreModal } from '@/features/SkillStore';
import { USER_HIDDEN_BUILTIN_SKILLS } from '@/helpers/skillFilters';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -71,6 +72,7 @@ export interface AgentToolProps {
const AgentTool = memo<AgentToolProps>(
({ agentId, showWebBrowsing = false, filterAvailableInWeb = false, useAllMetaList = false }) => {
const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const effectiveAgentId = agentId || activeAgentId || '';
const config = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId), isEqual);
@@ -143,14 +145,16 @@ const AgentTool = memo<AgentToolProps>(
// Toggle web browsing via searchMode - use byId action
const toggleWebBrowsing = useCallback(async () => {
+ if (!canEdit) return;
if (!effectiveAgentId) return;
const nextMode = isSearchEnabled ? 'off' : 'auto';
await updateAgentChatConfigById(effectiveAgentId, { searchMode: nextMode });
- }, [isSearchEnabled, updateAgentChatConfigById, effectiveAgentId]);
+ }, [canEdit, isSearchEnabled, updateAgentChatConfigById, effectiveAgentId]);
// Toggle a plugin - use byId action
const togglePlugin = useCallback(
async (pluginId: string, state?: boolean) => {
+ if (!canEdit) return;
if (!effectiveAgentId) return;
const currentPlugins = plugins;
const hasPlugin = currentPlugins.includes(pluginId);
@@ -167,7 +171,7 @@ const AgentTool = memo<AgentToolProps>(
await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
},
- [effectiveAgentId, plugins, updateAgentConfigById],
+ [canEdit, effectiveAgentId, plugins, updateAgentConfigById],
);
// Check if a tool is enabled (handles web browsing specially)
@@ -184,13 +188,15 @@ const AgentTool = memo<AgentToolProps>(
// Toggle a tool (handles web browsing specially)
const handleToggleTool = useCallback(
async (identifier: string) => {
+ if (!canEdit) return;
+
if (showWebBrowsing && identifier === WEB_BROWSING_IDENTIFIER) {
await toggleWebBrowsing();
} else {
await togglePlugin(identifier);
}
},
- [toggleWebBrowsing, togglePlugin, showWebBrowsing],
+ [canEdit, toggleWebBrowsing, togglePlugin, showWebBrowsing],
);
// Set default tab based on installed plugins (only on first load)
@@ -330,6 +336,8 @@ const AgentTool = memo<AgentToolProps>(
async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
+ if (!canEdit) return;
+
const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
if (showWebBrowsing && identifier === WEB_BROWSING_IDENTIFIER) {
if (!effectiveAgentId) return;
@@ -955,6 +963,7 @@ const AgentTool = memo<AgentToolProps>(
const button = (
<Button
+ disabled={!canEdit}
icon={PlusIcon}
loading={updating}
size={'small'}
@@ -1019,7 +1028,11 @@ const AgentTool = memo<AgentToolProps>(
typeof document === 'undefined' ? undefined : document.documentElement,
positionMethod: 'fixed',
}}
- onOpenChange={setDropdownOpen}
+ onOpenChange={(next) => {
+ if (!canEdit) return;
+
+ setDropdownOpen(next);
+ }}
>
{button}
</ActionDropdown>
@@ -1028,6 +1041,7 @@ const AgentTool = memo<AgentToolProps>(
{allEnabledTools.map((pluginId) => {
return (
<PluginTag
+ disabled={!canEdit}
key={pluginId}
pluginId={pluginId}
showDesktopOnlyLabel={filterAvailableInWeb}
diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsx
index 31752a3c662..6475d8075e8 100644
--- a/src/features/ProfileEditor/PluginTag.tsx
+++ b/src/features/ProfileEditor/PluginTag.tsx
@@ -77,6 +77,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
export interface PluginTagProps {
+ disabled?: boolean;
onRemove: (e: React.MouseEvent) => void;
pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> };
/**
@@ -92,7 +93,7 @@ export interface PluginTagProps {
}
const PluginTag = memo<PluginTagProps>(
- ({ pluginId, onRemove, showDesktopOnlyLabel = false, useAllMetaList = false }) => {
+ ({ pluginId, onRemove, disabled, showDesktopOnlyLabel = false, useAllMetaList = false }) => {
const isDarkMode = useIsDark();
const { t } = useTranslation('setting');
@@ -264,8 +265,8 @@ const PluginTag = memo<PluginTagProps>(
return (
<Tag
- closable
className={styles.tag}
+ closable={!disabled}
closeIcon={<X size={12} />}
color={showErrorState ? 'error' : undefined}
icon={renderIcon()}
@@ -275,7 +276,11 @@ const PluginTag = memo<PluginTagProps>(
? t('tools.notInstalledWarning', { defaultValue: 'This tool is not installed' })
: undefined
}
- onClose={onRemove}
+ onClose={(e) => {
+ if (disabled) return;
+
+ onRemove(e);
+ }}
>
{getDisplayText()}
</Tag>
diff --git a/src/features/ProfileEditor/PopoverContent.tsx b/src/features/ProfileEditor/PopoverContent.tsx
index 3ea8c358d2f..d9525be7a96 100644
--- a/src/features/ProfileEditor/PopoverContent.tsx
+++ b/src/features/ProfileEditor/PopoverContent.tsx
@@ -4,10 +4,10 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronRight, ExternalLink, Settings, Store } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { ScrollSignalProvider } from '@/features/ChatInput/ActionBar/Tools/ScrollSignalContext';
import ToolsList, { toolsListStyles } from '@/features/ChatInput/ActionBar/Tools/ToolsList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Empty from './Empty';
@@ -45,7 +45,7 @@ interface PopoverContentProps {
const PopoverContent = memo<PopoverContentProps>(
({ activeTab, onTabChange, allTabItems, installedTabItems, onOpenStore, onClose }) => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const currentItems = activeTab === 'all' ? allTabItems : installedTabItems;
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx
index d44a42a732c..77bc7ed6788 100644
--- a/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import PluginTag from '@/components/Plugins/PluginTag';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useToolStore } from '@/store/tool';
import { mcpStoreSelectors } from '@/store/tool/selectors';
@@ -28,6 +29,8 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(
const { message } = App.useApp();
const { t } = useTranslation('plugin');
const [loading, setLoading] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
// Track config updates
const [updatedConfig, setUpdatedConfig] = useState<{
@@ -57,7 +60,7 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(
}, [installRequest]);
const handleConfirm = useCallback(async () => {
- if (!installRequest || !schema) return;
+ if (!canCreate || !canEdit || !installRequest || !schema) return;
setLoading(true);
try {
@@ -116,6 +119,8 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(
}
}, [
installRequest,
+ canCreate,
+ canEdit,
schema,
updatedConfig,
onComplete,
@@ -176,6 +181,7 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(
<Modal
open
confirmLoading={loading || testState.loading}
+ okButtonProps={{ disabled: !canCreate || !canEdit }}
okText={okText}
title={modalTitle}
width={680}
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
index 9faf55425ae..8b50e421d0a 100644
--- a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
@@ -6,6 +6,7 @@ import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import DetailLoading from '@/features/MCP/MCPDetail/Loading';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useDiscoverStore } from '@/store/discover';
import { useToolStore } from '@/store/tool';
@@ -24,6 +25,8 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
const { message } = App.useApp();
const { t } = useTranslation(['plugin', 'common']);
const [loading, setLoading] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
// Fetch MCP plugin details
const useMcpDetail = useDiscoverStore((s) => s.useFetchMcpDetail);
@@ -39,7 +42,7 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
const { data, isLoading } = useMcpDetail({ identifier });
const handleConfirm = useCallback(async () => {
- if (!installRequest || !data) return;
+ if (!canCreate || !canEdit || !installRequest || !data) return;
setLoading(true);
try {
@@ -55,7 +58,18 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
message.error(t('protocolInstall.messages.installError'));
setLoading(false);
}
- }, [installRequest, data]);
+ }, [
+ canCreate,
+ canEdit,
+ installRequest,
+ data,
+ installMCPPlugin,
+ identifier,
+ togglePlugin,
+ message,
+ t,
+ onComplete,
+ ]);
if (!installRequest) return null;
@@ -85,7 +99,7 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
title={t('protocolInstall.official.title')}
width={800}
okButtonProps={{
- disabled: installed || isLoading,
+ disabled: installed || isLoading || !canCreate || !canEdit,
type: installed ? 'default' : 'primary',
}}
okText={
diff --git a/src/features/RecommendTaskTemplates/SkillAuthRow.test.tsx b/src/features/RecommendTaskTemplates/SkillAuthRow.test.tsx
new file mode 100644
index 00000000000..2d062f8c06c
--- /dev/null
+++ b/src/features/RecommendTaskTemplates/SkillAuthRow.test.tsx
@@ -0,0 +1,44 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SkillAuthRow } from './SkillAuthRow';
+
+const connectMock = vi.hoisted(() => vi.fn());
+
+vi.mock('./useSkillConnection', () => ({
+ SkillConnectionPopupBlockedError: class SkillConnectionPopupBlockedError extends Error {},
+ useSkillConnection: () => ({
+ connect: connectMock,
+ isAllConnected: false,
+ isConnecting: false,
+ }),
+}));
+
+vi.mock('./providerMeta', () => ({
+ getProviderMeta: () => ({ icon: 'https://example.com/icon.png', label: 'HubSpot' }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('SkillAuthRow', () => {
+ beforeEach(() => {
+ connectMock.mockReset();
+ });
+
+ it('disables provider connection when template actions are disabled', () => {
+ render(
+ <SkillAuthRow disabled spec={{ provider: 'hubspot', source: 'klavis' }} onError={vi.fn()} />,
+ );
+
+ const connectButton = screen.getByRole('button', { name: 'action.connect.short' });
+ expect(connectButton).toBeDisabled();
+
+ fireEvent.click(connectButton);
+ expect(connectMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/RecommendTaskTemplates/SkillAuthRow.tsx b/src/features/RecommendTaskTemplates/SkillAuthRow.tsx
index 7486f994f9a..6ca350e3500 100644
--- a/src/features/RecommendTaskTemplates/SkillAuthRow.tsx
+++ b/src/features/RecommendTaskTemplates/SkillAuthRow.tsx
@@ -8,6 +8,7 @@ import { getProviderMeta } from './providerMeta';
import { SkillConnectionPopupBlockedError, useSkillConnection } from './useSkillConnection';
interface SkillAuthRowProps {
+ disabled?: boolean;
onError: (error: unknown) => void;
spec: TaskTemplateSkillRequirement;
}
@@ -17,19 +18,20 @@ interface SkillAuthRowProps {
* Renders `null` once the provider is connected so the caller can collapse the
* surrounding container without extra bookkeeping.
*/
-export const SkillAuthRow = memo<SkillAuthRowProps>(({ spec, onError }) => {
+export const SkillAuthRow = memo<SkillAuthRowProps>(({ disabled, spec, onError }) => {
const { t } = useTranslation('taskTemplate');
const specs = useMemo(() => [spec], [spec]);
const meta = useMemo(() => getProviderMeta(spec), [spec]);
const { connect, isAllConnected, isConnecting } = useSkillConnection(specs);
const handleConnect = useCallback(async () => {
+ if (disabled) return;
try {
await connect();
} catch (error) {
onError(error);
}
- }, [connect, onError]);
+ }, [connect, disabled, onError]);
if (!meta || isAllConnected) return null;
@@ -45,7 +47,13 @@ export const SkillAuthRow = memo<SkillAuthRowProps>(({ spec, onError }) => {
{meta.label}
</Text>
</Flexbox>
- <Button loading={isConnecting} size={'small'} variant={'text'} onClick={handleConnect}>
+ <Button
+ disabled={disabled}
+ loading={isConnecting}
+ size={'small'}
+ variant={'text'}
+ onClick={handleConnect}
+ >
{t('action.connect.short')}
</Button>
</Flexbox>
diff --git a/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx b/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx
index a2a80fa7e75..b707b70afb6 100644
--- a/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx
+++ b/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx
@@ -135,6 +135,7 @@ export const TaskTemplateCard = memo<TaskTemplateCardProps>(
<Flexbox gap={6} onClick={(e) => e.stopPropagation()}>
{visibleAuthSpecs.map((spec) => (
<SkillAuthRow
+ disabled={disabled}
key={`${spec.source}:${spec.provider}`}
spec={spec}
onError={handleConnectError}
diff --git a/src/features/RecommendTaskTemplates/TaskTemplateDetailModal.tsx b/src/features/RecommendTaskTemplates/TaskTemplateDetailModal.tsx
index 2dc35e8f10f..9b49032d316 100644
--- a/src/features/RecommendTaskTemplates/TaskTemplateDetailModal.tsx
+++ b/src/features/RecommendTaskTemplates/TaskTemplateDetailModal.tsx
@@ -84,6 +84,7 @@ const TaskTemplateDetailContent = memo<TaskTemplateDetailContentProps>(
<Flexbox gap={6}>
{visibleAuthSpecs.map((spec) => (
<SkillAuthRow
+ disabled={disabled}
key={`${spec.source}:${spec.provider}`}
spec={spec}
onError={handleConnectError}
diff --git a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
index 2342200ff16..bfa3bfdd028 100644
--- a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
+++ b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
@@ -2,9 +2,10 @@ import type { TaskTemplate } from '@lobechat/const';
import { App } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { taskTemplateService } from '@/services/taskTemplate';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
@@ -37,14 +38,16 @@ export const useTaskTemplateCreate = ({
}: UseTaskTemplateCreateOptions): UseTaskTemplateCreateResult => {
const { t } = useTranslation('taskTemplate');
const { message } = App.useApp();
+ const { allowed: canCreateTask } = usePermission('create_content');
const [loading, setLoading] = useState(false);
const [created, setCreated] = useState(false);
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const createTask = useTaskStore((s) => s.createTask);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const requiredConnection = useSkillConnection(template.requiresSkills);
const handleCreate = useCallback(async () => {
+ if (!canCreateTask) return;
if (!inboxAgentId) return;
setLoading(true);
try {
@@ -85,6 +88,7 @@ export const useTaskTemplateCreate = ({
template.cronPattern,
template.id,
title,
+ canCreateTask,
]);
const handleConnectError = useCallback(
@@ -124,13 +128,14 @@ export const useTaskTemplateCreate = ({
}, [pendingCreate, requiredConnection.isConnecting, requiredConnection.needsConnect]);
const handleAddTask = useCallback(() => {
+ if (!canCreateTask) return;
if (created || !inboxAgentId) return;
if (requiredConnection.needsConnect) {
setPendingCreate(true);
return;
}
void handleCreate();
- }, [created, inboxAgentId, requiredConnection.needsConnect, handleCreate]);
+ }, [canCreateTask, created, inboxAgentId, requiredConnection.needsConnect, handleCreate]);
const primaryButtonLabel = loading
? t('action.creating')
@@ -140,7 +145,7 @@ export const useTaskTemplateCreate = ({
return {
created,
- disabled: created || !inboxAgentId,
+ disabled: !canCreateTask || created || !inboxAgentId,
handleAddTask,
handleConnectError,
loading,
diff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx
new file mode 100644
index 00000000000..9052e05f7ae
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx
@@ -0,0 +1,65 @@
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import EmptyPlaceholder from './EmptyPlaceholder';
+
+const mockOpen = vi.fn();
+const mockPushDockFileList = vi.fn();
+let canCreate = true;
+let libraryId: string | undefined;
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/features/LibraryModal', () => ({
+ useCreateNewModal: () => ({ open: mockOpen }),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: canCreate, reason: '' }),
+}));
+
+vi.mock('@/routes/(main)/resource/features/hooks/useCurrentFolderId', () => ({
+ useCurrentFolderId: () => undefined,
+}));
+
+vi.mock('@/routes/(main)/resource/features/store', () => ({
+ useResourceManagerStore: (selector: (state: { libraryId?: string }) => unknown) =>
+ selector({ libraryId }),
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (state: { pushDockFileList: typeof mockPushDockFileList }) => unknown) =>
+ selector({ pushDockFileList: mockPushDockFileList }),
+}));
+
+describe('EmptyPlaceholder', () => {
+ beforeEach(() => {
+ canCreate = true;
+ libraryId = undefined;
+ vi.clearAllMocks();
+ });
+
+ it('should render create actions when the user can create resources', () => {
+ render(<EmptyPlaceholder />);
+
+ expect(screen.getByText('FileManager.emptyStatus.actions.knowledgeBase')).toBeInTheDocument();
+ expect(screen.getByText('FileManager.emptyStatus.actions.file')).toBeInTheDocument();
+ expect(screen.getByText('FileManager.emptyStatus.actions.folder')).toBeInTheDocument();
+ });
+
+ it('should hide create actions when the user cannot create resources', () => {
+ canCreate = false;
+
+ render(<EmptyPlaceholder />);
+
+ expect(
+ screen.queryByText('FileManager.emptyStatus.actions.knowledgeBase'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('FileManager.emptyStatus.actions.file')).not.toBeInTheDocument();
+ expect(screen.queryByText('FileManager.emptyStatus.actions.folder')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx
index 22e53d5dfa8..dbfda9f43c3 100644
--- a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx
+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx
@@ -5,6 +5,7 @@ import { ArrowUpIcon, PlusIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useCreateNewModal } from '@/features/LibraryModal';
+import { usePermission } from '@/hooks/usePermission';
import { useCurrentFolderId } from '@/routes/(main)/resource/features/hooks/useCurrentFolderId';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useFileStore } from '@/store/file';
@@ -70,6 +71,15 @@ const EmptyPlaceholder = () => {
const currentFolderId = useCurrentFolderId();
const { open } = useCreateNewModal();
+ const { allowed: canCreate } = usePermission('create_content');
+
+ if (!canCreate) {
+ return (
+ <Center height={'100%'} style={{ paddingBottom: 100 }} width={'100%'}>
+ <Text as={'h4'}>{t('FileManager.emptyStatus.title')}</Text>
+ </Center>
+ );
+ }
return (
<Center gap={24} height={'100%'} style={{ paddingBottom: 100 }} width={'100%'}>
diff --git a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
index d94ed590365..4905297a5d8 100644
--- a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
+++ b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
@@ -2,8 +2,9 @@ import { Flexbox, Skeleton } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate, useSearchParams } from 'react-router-dom';
+import { useSearchParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFolderPath } from '@/routes/(main)/resource/features/hooks/useFolderPath';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useFileStore } from '@/store/file';
@@ -47,7 +48,7 @@ interface FolderCrumb {
const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
const { t } = useTranslation('file');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [searchParams] = useSearchParams();
const { currentFolderSlug, knowledgeBaseId: currentKnowledgeBaseId } = useFolderPath();
diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsx
index 3b27aba5313..149c1078206 100644
--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx
@@ -8,7 +8,9 @@ import { BookMinusIcon, FileBoxIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useFileBatchTransferActions } from '@/business/client/hooks/useFileBatchTransferActions';
import NavHeader from '@/features/NavHeader';
+import { usePermission } from '@/hooks/usePermission';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { getExplorerSelectedCount } from '@/routes/(main)/resource/features/store/selectors';
import { useFileStore } from '@/store/file';
@@ -37,6 +39,7 @@ const Header = memo(() => {
s.selectAllState,
s.selectedFileIds,
]);
+ const { allowed: canEditResources, reason } = usePermission('edit_own_content');
const total = useFileStore((s) => s.total);
const selectCount = getExplorerSelectedCount({
selectAllState,
@@ -44,15 +47,18 @@ const Header = memo(() => {
total,
});
const hasSelected = selectAllState === 'all' || selectCount > 0;
+ const batchTransferActions = useFileBatchTransferActions(selectCount);
// If no libraryId, show category name or "Resource" for All
const leftContent = hasSelected ? (
<Flexbox horizontal align={'center'} gap={8} style={{ marginLeft: 0 }}>
{libraryId ? (
<ActionIcon
+ disabled={!canEditResources}
icon={BookMinusIcon}
- title={t('FileManager.actions.removeFromLibrary')}
+ title={canEditResources ? t('FileManager.actions.removeFromLibrary') : reason}
onClick={() => {
+ if (!canEditResources) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('FileManager.actions.confirmRemoveFromLibrary', {
@@ -73,17 +79,34 @@ const Header = memo(() => {
) : null}
<ActionIcon
+ disabled={!canEditResources}
icon={FileBoxIcon}
- title={t('FileManager.actions.batchChunking')}
+ title={canEditResources ? t('FileManager.actions.batchChunking') : reason}
onClick={async () => {
+ if (!canEditResources) return;
await onActionClick('batchChunking');
}}
/>
+ {batchTransferActions?.map((action) => (
+ <ActionIcon
+ disabled={!canEditResources}
+ icon={action.icon}
+ key={action.key}
+ title={canEditResources ? action.label : reason}
+ onClick={() => {
+ if (!canEditResources) return;
+ action.onClick();
+ }}
+ />
+ ))}
+
<ActionIcon
+ disabled={!canEditResources}
icon={Trash2Icon}
- title={t('delete', { ns: 'common' })}
+ title={canEditResources ? t('delete', { ns: 'common' }) : reason}
onClick={() => {
+ if (!canEditResources) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t(
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 7ac80faf023..b7d0c9c0dee 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -20,6 +20,7 @@ import RepoIcon from '@/components/LibIcon';
import { useKnowledgeBaseListContext } from '@/features/ResourceManager/components/KnowledgeBaseListProvider';
import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';
import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { usePermission } from '@/hooks/usePermission';
import { documentService } from '@/services/document';
import { useFileStore } from '@/store/file';
import { useKnowledgeBaseStore } from '@/store/library';
@@ -58,6 +59,7 @@ export const useFileItemDropdown = ({
const { t } = useTranslation(['components', 'common', 'knowledgeBase']);
const { message } = App.useApp();
const appOrigin = useAppOrigin();
+ const { allowed: canEditResources } = usePermission('edit_own_content');
const { deleteResource, moveResource, refreshFileList } = useFileStore(
(s) => ({
@@ -157,48 +159,50 @@ export const useFileItemDropdown = ({
}));
const libraryRelatedActions = (
- isInLibrary
- ? [
- availableKnowledgeBases.length > 0 && {
- children: moveToKnowledgeBaseSubmenu,
- icon: <Icon icon={BookPlusIcon} />,
- key: 'moveToOtherLibrary',
- label: t('FileManager.actions.moveToOtherLibrary'),
- },
- {
- icon: <Icon icon={BookMinusIcon} />,
- key: 'removeFromLibrary',
- label: t('FileManager.actions.removeFromLibrary'),
- onClick: async ({ domEvent }) => {
- domEvent.stopPropagation();
+ !canEditResources
+ ? []
+ : isInLibrary
+ ? [
+ availableKnowledgeBases.length > 0 && {
+ children: moveToKnowledgeBaseSubmenu,
+ icon: <Icon icon={BookPlusIcon} />,
+ key: 'moveToOtherLibrary',
+ label: t('FileManager.actions.moveToOtherLibrary'),
+ },
+ {
+ icon: <Icon icon={BookMinusIcon} />,
+ key: 'removeFromLibrary',
+ label: t('FileManager.actions.removeFromLibrary'),
+ onClick: async ({ domEvent }) => {
+ domEvent.stopPropagation();
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('FileManager.actions.confirmRemoveFromLibrary', {
- count: 1,
- }),
- okButtonProps: {
- danger: true,
- },
- okText: t('FileManager.actions.removeFromLibrary'),
- onOk: async () => {
- await removeFilesFromKnowledgeBase(libraryId, [id]);
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('FileManager.actions.confirmRemoveFromLibrary', {
+ count: 1,
+ }),
+ okButtonProps: {
+ danger: true,
+ },
+ okText: t('FileManager.actions.removeFromLibrary'),
+ onOk: async () => {
+ await removeFilesFromKnowledgeBase(libraryId, [id]);
- message.success(t('FileManager.actions.removeFromLibrarySuccess'));
- },
- title: t('FileManager.actions.removeFromLibrary'),
- });
+ message.success(t('FileManager.actions.removeFromLibrarySuccess'));
+ },
+ title: t('FileManager.actions.removeFromLibrary'),
+ });
+ },
},
- },
- ]
- : [
- availableKnowledgeBases.length > 0 && {
- children: addToKnowledgeBaseSubmenu,
- icon: <Icon icon={BookPlusIcon} />,
- key: 'addToLibrary',
- label: t('FileManager.actions.addToLibrary'),
- },
- ]
+ ]
+ : [
+ availableKnowledgeBases.length > 0 && {
+ children: addToKnowledgeBaseSubmenu,
+ icon: <Icon icon={BookPlusIcon} />,
+ key: 'addToLibrary',
+ label: t('FileManager.actions.addToLibrary'),
+ },
+ ]
) as ItemType[];
const hasKnowledgeBaseActions = libraryRelatedActions.some(Boolean);
@@ -209,28 +213,30 @@ export const useFileItemDropdown = ({
hasKnowledgeBaseActions && {
type: 'divider',
},
- isInLibrary && {
- icon: <Icon icon={FolderInputIcon} />,
- key: 'moveToFolder',
- label: t('FileManager.actions.moveToFolder'),
- onClick: async ({ domEvent }) => {
- domEvent.stopPropagation();
+ canEditResources &&
+ isInLibrary && {
+ icon: <Icon icon={FolderInputIcon} />,
+ key: 'moveToFolder',
+ label: t('FileManager.actions.moveToFolder'),
+ onClick: async ({ domEvent }) => {
+ domEvent.stopPropagation();
- createRawModal(MoveToFolderModal, {
- fileId: id,
- knowledgeBaseId: libraryId,
- });
+ createRawModal(MoveToFolderModal, {
+ fileId: id,
+ knowledgeBaseId: libraryId,
+ });
+ },
},
- },
- isFolder && {
- icon: <Icon icon={PencilIcon} />,
- key: 'rename',
- label: t('FileManager.actions.rename'),
- onClick: async ({ domEvent }) => {
- domEvent.stopPropagation();
- onRenameStart?.();
+ canEditResources &&
+ isFolder && {
+ icon: <Icon icon={PencilIcon} />,
+ key: 'rename',
+ label: t('FileManager.actions.rename'),
+ onClick: async ({ domEvent }) => {
+ domEvent.stopPropagation();
+ onRenameStart?.();
+ },
},
- },
{
icon: <Icon icon={LinkIcon} />,
key: 'copyUrl',
@@ -298,10 +304,10 @@ export const useFileItemDropdown = ({
message.destroy(key);
},
},
- {
+ canEditResources && {
type: 'divider',
},
- {
+ canEditResources && {
danger: true,
icon: <Icon icon={Trash} />,
key: 'delete',
@@ -334,6 +340,7 @@ export const useFileItemDropdown = ({
}, [
addFilesToKnowledgeBase,
appOrigin,
+ canEditResources,
deleteResource,
filename,
id,
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
new file mode 100644
index 00000000000..5b8fb49383f
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
@@ -0,0 +1,66 @@
+import { render } from '@testing-library/react';
+import type { ItemType } from 'antd/es/menu/interface';
+import React from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import FileListItemActions, { appendTransferMenuItemsBeforeDelete } from './FileListItemActions';
+
+const mocks = vi.hoisted(() => ({
+ useFileTransferMenuItem: vi.fn(),
+}));
+
+vi.mock('@/business/client/hooks/useFileTransferMenuItem', () => ({
+ useFileTransferMenuItem: mocks.useFileTransferMenuItem,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true }),
+}));
+
+vi.mock('../../ItemDropdown/DropdownMenu', () => ({
+ default: () => null,
+}));
+
+describe('appendTransferMenuItemsBeforeDelete', () => {
+ it('keeps delete as the final menu action', () => {
+ const baseItems = [
+ { key: 'copyUrl' },
+ { key: 'download' },
+ { type: 'divider' },
+ { key: 'delete' },
+ ] as ItemType[];
+ const transferItems = [{ key: 'transfer' }, { key: 'copy' }] as ItemType[];
+
+ const result = appendTransferMenuItemsBeforeDelete(baseItems, transferItems);
+
+ expect(result.map((item) => item && ('key' in item ? item.key : item.type))).toEqual([
+ 'copyUrl',
+ 'download',
+ 'transfer',
+ 'copy',
+ 'divider',
+ 'delete',
+ ]);
+ });
+});
+
+describe('FileListItemActions', () => {
+ const baseProps = {
+ id: 'resource-1',
+ isCreatingFileParseTask: false,
+ isFolder: false,
+ isPage: false,
+ isSupportedForChunking: false,
+ menuItems: [],
+ parseFiles: vi.fn(),
+ t: (key: string) => key,
+ };
+
+ it('passes document entity type for page resources', () => {
+ mocks.useFileTransferMenuItem.mockReturnValue([]);
+
+ render(React.createElement(FileListItemActions, { ...baseProps, isPage: true }));
+
+ expect(mocks.useFileTransferMenuItem).toHaveBeenCalledWith('resource-1', 'document');
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
index bd8d4fe8e73..95ef6ecbe3a 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
@@ -3,6 +3,10 @@ import { Button, Flexbox, stopPropagation } from '@lobehub/ui';
import type { ItemType } from 'antd/es/menu/interface';
import { isNull } from 'es-toolkit/compat';
import { FileBoxIcon } from 'lucide-react';
+import { useMemo } from 'react';
+
+import { useFileTransferMenuItem } from '@/business/client/hooks/useFileTransferMenuItem';
+import { usePermission } from '@/hooks/usePermission';
import DropdownMenu from '../../ItemDropdown/DropdownMenu';
import ChunksBadge from './ChunkTag';
@@ -25,6 +29,33 @@ interface FileListItemActionsProps {
t: any;
}
+const isDeleteMenuItem = (item: ItemType) =>
+ item !== null && 'key' in item && item.key === 'delete';
+
+const isDividerMenuItem = (item: ItemType) =>
+ item !== null && 'type' in item && item.type === 'divider';
+
+export const appendTransferMenuItemsBeforeDelete = (
+ baseItems: ItemType[],
+ transferMenuItems: ItemType[] | null,
+) => {
+ if (!transferMenuItems || transferMenuItems.length === 0) return baseItems;
+
+ const deleteIndex = baseItems.findIndex(isDeleteMenuItem);
+ if (deleteIndex === -1) return [...baseItems, ...transferMenuItems];
+
+ const insertIndex =
+ deleteIndex > 0 && isDividerMenuItem(baseItems[deleteIndex - 1])
+ ? deleteIndex - 1
+ : deleteIndex;
+
+ return [
+ ...baseItems.slice(0, insertIndex),
+ ...transferMenuItems,
+ ...baseItems.slice(insertIndex),
+ ];
+};
+
const FileListItemActions = ({
chunkCount,
chunkingError,
@@ -40,58 +71,73 @@ const FileListItemActions = ({
menuItems,
parseFiles,
t,
-}: FileListItemActionsProps) => (
- <Flexbox
- horizontal
- align={'center'}
- gap={8}
- paddingInline={8}
- onClick={stopPropagation}
- onPointerDown={stopPropagation}
- >
- {!isFolder &&
- !isPage &&
- (isCreatingFileParseTask || isNull(chunkingStatus) || !chunkingStatus ? (
- <div
- className={isCreatingFileParseTask ? undefined : styles.hover}
- title={t(
- isSupportedForChunking
- ? 'FileManager.actions.chunkingTooltip'
- : 'FileManager.actions.chunkingUnsupported',
- )}
- >
- <Button
- disabled={!isSupportedForChunking}
- icon={FileBoxIcon}
- loading={isCreatingFileParseTask}
- size={'small'}
- type={'text'}
- onClick={() => {
- parseFiles([id]);
- }}
- >
- {t(
- isCreatingFileParseTask
- ? 'FileManager.actions.createChunkingTask'
- : 'FileManager.actions.chunking',
- )}
- </Button>
- </div>
- ) : (
- <div style={{ cursor: 'default' }}>
- <ChunksBadge
- chunkCount={chunkCount}
- chunkingError={chunkingError}
- chunkingStatus={chunkingStatus as any}
- embeddingError={embeddingError}
- embeddingStatus={embeddingStatus as any}
- finishEmbedding={finishEmbedding}
- id={id}
- />
- </div>
- ))}
- <DropdownMenu className={styles.hover} items={menuItems} />
- </Flexbox>
-);
+}: FileListItemActionsProps) => {
+ const { allowed: canEditResources } = usePermission('edit_own_content');
+ const transferMenuItems = useFileTransferMenuItem(
+ id,
+ isPage ? 'document' : isFolder ? 'folder' : 'file',
+ );
+
+ const mergedMenuItems = useMemo(() => {
+ const baseItems = typeof menuItems === 'function' ? menuItems() : menuItems;
+ return appendTransferMenuItemsBeforeDelete(baseItems, transferMenuItems);
+ }, [menuItems, transferMenuItems]);
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ paddingInline={8}
+ onClick={stopPropagation}
+ onPointerDown={stopPropagation}
+ >
+ {!isFolder &&
+ !isPage &&
+ (isCreatingFileParseTask || isNull(chunkingStatus) || !chunkingStatus ? (
+ canEditResources && (
+ <div
+ className={isCreatingFileParseTask ? undefined : styles.hover}
+ title={t(
+ isSupportedForChunking
+ ? 'FileManager.actions.chunkingTooltip'
+ : 'FileManager.actions.chunkingUnsupported',
+ )}
+ >
+ <Button
+ disabled={!isSupportedForChunking}
+ icon={FileBoxIcon}
+ loading={isCreatingFileParseTask}
+ size={'small'}
+ type={'text'}
+ onClick={() => {
+ parseFiles([id]);
+ }}
+ >
+ {t(
+ isCreatingFileParseTask
+ ? 'FileManager.actions.createChunkingTask'
+ : 'FileManager.actions.chunking',
+ )}
+ </Button>
+ </div>
+ )
+ ) : (
+ <div style={{ cursor: 'default' }}>
+ <ChunksBadge
+ chunkCount={chunkCount}
+ chunkingError={chunkingError}
+ chunkingStatus={chunkingStatus as any}
+ embeddingError={embeddingError}
+ embeddingStatus={embeddingStatus as any}
+ finishEmbedding={finishEmbedding}
+ id={id}
+ />
+ </div>
+ ))}
+ <DropdownMenu className={styles.hover} items={mergedMenuItems} />
+ </Flexbox>
+ );
+};
export default FileListItemActions;
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index a705ffce010..45f39aca1e5 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -138,6 +138,7 @@ const FileListItem = ({
slug,
sourceType,
url,
+ userId,
}: FileListItemProps) => {
const { t } = useTranslation(['components', 'file']);
const fileStoreState = useFileStore(
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
index 52b03fbd27e..683c74953d9 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
@@ -1,5 +1,5 @@
import { type DropdownItem } from '@lobehub/ui';
-import { DropdownMenu, Icon } from '@lobehub/ui';
+import { DropdownMenu, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import {
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next';
import RepoIcon from '@/components/LibIcon';
import { useKnowledgeBaseListContext } from '@/features/ResourceManager/components/KnowledgeBaseListProvider';
+import { usePermission } from '@/hooks/usePermission';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useKnowledgeBaseStore } from '@/store/library';
@@ -43,11 +44,14 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
]);
const addFilesToKnowledgeBase = useKnowledgeBaseStore((s) => s.addFilesToKnowledgeBase);
const knowledgeBases = useKnowledgeBaseListContext();
+ const { allowed: canEditResources, reason } = usePermission('edit_own_content');
const menuItems = useMemo<DropdownItem[]>(() => {
const items: DropdownItem[] = [];
// Show delete library option only when in a knowledge base and no files selected
+ if (!canEditResources) return items;
+
if (libraryId && selectCount === 0) {
items.push({
danger: true,
@@ -189,14 +193,18 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
t,
message,
knowledgeBases,
+ canEditResources,
]);
return (
<DropdownMenu items={menuItems} placement="bottomLeft">
- <ActionIconWithChevron
- icon={CircleEllipsisIcon}
- title={t('FileManager.actions.batchActions', 'Batch actions')}
- />
+ <Tooltip title={canEditResources ? undefined : reason}>
+ <ActionIconWithChevron
+ disabled={!canEditResources}
+ icon={CircleEllipsisIcon}
+ title={t('FileManager.actions.batchActions', 'Batch actions')}
+ />
+ </Tooltip>
</DropdownMenu>
);
});
diff --git a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
index 18a7b68adf8..00eb0d12219 100644
--- a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
+++ b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
-import { useNavigate, useSearchParams } from 'react-router-dom';
+import { useSearchParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
export interface UseFileItemClickOptions {
@@ -23,7 +24,7 @@ export const useFileItemClick = ({
isPage,
onOpen,
}: UseFileItemClickOptions) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const setMode = useResourceManagerStore((s) => s.setMode);
const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);
@@ -72,7 +73,19 @@ export const useFileItemClick = ({
// Call onOpen if provided for backwards compatibility
onOpen?.(id);
}
- }, [isFolder, slug, id, libraryId, isPage, navigate, searchParams, setSearchParams, setMode, setCurrentViewItemId, onOpen]);
+ }, [
+ isFolder,
+ slug,
+ id,
+ libraryId,
+ isPage,
+ navigate,
+ searchParams,
+ setSearchParams,
+ setMode,
+ setCurrentViewItemId,
+ onOpen,
+ ]);
return handleClick;
};
diff --git a/src/features/ResourceManager/components/Explorer/index.test.tsx b/src/features/ResourceManager/components/Explorer/index.test.tsx
new file mode 100644
index 00000000000..2171e661942
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/index.test.tsx
@@ -0,0 +1,99 @@
+import { render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FilesTabs, SortType } from '@/types/files';
+
+import ResourceExplorer from './index';
+
+const mocks = vi.hoisted(() => ({
+ resourceManagerState: {
+ category: 'all' as FilesTabs,
+ libraryId: undefined as string | undefined,
+ searchQuery: null as string | null,
+ sorter: 'createdAt' as const,
+ sortType: 'desc' as SortType,
+ viewMode: 'list' as const,
+ },
+ useFetchResources: vi.fn(),
+}));
+
+vi.mock('@/routes/(main)/resource/features/hooks/useFolderPath', () => ({
+ useFolderPath: () => ({ currentFolderSlug: null }),
+}));
+
+vi.mock('@/routes/(main)/resource/features/hooks/useResourceManagerUrlSync', () => ({
+ useResourceManagerUrlSync: vi.fn(),
+}));
+
+vi.mock('@/routes/(main)/resource/features/store', () => ({
+ useResourceManagerStore: (selector: (state: typeof mocks.resourceManagerState) => unknown) =>
+ selector(mocks.resourceManagerState),
+}));
+
+vi.mock('@/routes/(main)/resource/features/store/selectors', () => ({
+ sortFileList: (items: unknown[]) => items,
+}));
+
+vi.mock('@/store/file/slices/resource/hooks', () => ({
+ useFetchResources: mocks.useFetchResources,
+ useResourceStore: () => ({ resourceList: [] }),
+}));
+
+vi.mock('../KnowledgeBaseListProvider', () => ({
+ KnowledgeBaseListProvider: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock('./EmptyPlaceholder', () => ({
+ default: () => <div data-testid="empty" />,
+}));
+
+vi.mock('./Header', () => ({
+ default: () => <div data-testid="header" />,
+}));
+
+vi.mock('./hooks/useResetSelectionOnQueryChange', () => ({
+ useResetSelectionOnQueryChange: vi.fn(),
+}));
+
+vi.mock('./ListView', () => ({
+ default: () => <div data-testid="list" />,
+}));
+
+vi.mock('./MasonryView', () => ({
+ default: () => <div data-testid="masonry" />,
+}));
+
+vi.mock('./SearchResultsOverlay', () => ({
+ default: () => null,
+}));
+
+vi.mock('./useCheckTaskStatus', () => ({
+ useCheckTaskStatus: vi.fn(),
+}));
+
+describe('ResourceExplorer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.resourceManagerState.category = FilesTabs.All;
+ mocks.resourceManagerState.libraryId = undefined;
+ mocks.resourceManagerState.searchQuery = null;
+ mocks.resourceManagerState.sorter = 'createdAt';
+ mocks.resourceManagerState.sortType = SortType.Desc;
+ mocks.resourceManagerState.viewMode = 'list';
+ mocks.useFetchResources.mockReturnValue({ isLoading: false, isValidating: false });
+ });
+
+ it('keeps library contents excluded from the All resource query', () => {
+ render(<ResourceExplorer />);
+
+ expect(mocks.useFetchResources).toHaveBeenCalledWith(
+ expect.objectContaining({
+ category: FilesTabs.All,
+ libraryId: undefined,
+ parentId: null,
+ showFilesInKnowledgeBase: false,
+ }),
+ );
+ });
+});
diff --git a/src/features/ResourceManager/components/Header/AddButton.tsx b/src/features/ResourceManager/components/Header/AddButton.tsx
index 93899a80482..44c30149514 100644
--- a/src/features/ResourceManager/components/Header/AddButton.tsx
+++ b/src/features/ResourceManager/components/Header/AddButton.tsx
@@ -8,7 +8,7 @@ import {
} from '@lobechat/const';
import { Notion } from '@lobehub/icons';
import { type MenuProps } from '@lobehub/ui';
-import { Button, DropdownMenu, Icon } from '@lobehub/ui';
+import { Button, DropdownMenu, Icon, Tooltip } from '@lobehub/ui';
import { Upload } from 'antd';
import { FilePenLine, FileUp, FolderIcon, FolderUp, Link, Plus } from 'lucide-react';
import { type ChangeEvent } from 'react';
@@ -18,6 +18,7 @@ import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
import GuideModal from '@/components/GuideModal';
import GuideVideo from '@/components/GuideVideo';
+import { usePermission } from '@/hooks/usePermission';
import { useCurrentFolderId } from '@/routes/(main)/resource/features/hooks/useCurrentFolderId';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useFileStore } from '@/store/file';
@@ -53,6 +54,7 @@ const AddButton = () => {
const createResourceAndSync = useFileStore((s) => s.createResourceAndSync);
const [menuOpen, setMenuOpen] = useState(false);
const currentFolderId = useCurrentFolderId();
+ const { allowed: canCreate, reason } = usePermission('create_content');
// TODO: Migrate Notion import to use createResource
// Keep old functions temporarily for components not yet migrated
@@ -262,15 +264,20 @@ const AddButton = () => {
return (
<>
<DropdownMenu
- items={items}
+ items={canCreate ? items : []}
open={menuOpen}
placement="bottomRight"
trigger="both"
- onOpenChange={setMenuOpen}
+ onOpenChange={(open) => {
+ if (!canCreate) return;
+ setMenuOpen(open);
+ }}
>
- <Button data-no-highlight icon={Plus} type="primary">
- {t('addLibrary')}
- </Button>
+ <Tooltip title={reason}>
+ <Button data-no-highlight disabled={!canCreate} icon={Plus} type="primary">
+ {t('addLibrary')}
+ </Button>
+ </Tooltip>
</DropdownMenu>
<GuideModal
cancelText={t('header.actions.notionGuide.cancel')}
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index ae6fa1ef7cc..f641b236e0f 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -8,10 +8,10 @@ import { cx } from 'antd-style';
import { FileText, FolderIcon, FolderOpenIcon } from 'lucide-react';
import * as m from 'motion/react-m';
import React, { memo, useCallback, useMemo, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
import FileIcon from '@/components/FileIcon';
import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
getTransparentDragImage,
useDragActive,
@@ -37,7 +37,7 @@ interface HierarchyNodeProps {
export const HierarchyNode = memo<HierarchyNodeProps>(
({ item, level = 0, isExpanded, isLoading, onToggle, selectedKey, parentKey }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { message } = App.useApp();
const [setMode, libraryId] = useResourceManagerStore((s) => [s.setMode, s.libraryId]);
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index a4ee0d8ca42..222a8b4e97e 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -7,6 +7,7 @@ import { useSearchParams } from 'react-router-dom';
import DragUploadZone from '@/components/DragUploadZone';
import { PageEditor } from '@/features/PageEditor';
+import { usePermission } from '@/hooks/usePermission';
import dynamic from '@/libs/next/dynamic';
import { useCurrentFolderId } from '@/routes/(main)/resource/features/hooks/useCurrentFolderId';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
@@ -72,10 +73,14 @@ const ResourceManager = memo(() => {
const currentDocument = useFileStore(documentSelectors.getDocumentById(currentViewItemId));
const pushDockFileList = useFileStore((s) => s.pushDockFileList);
const updateDocumentOptimistically = useFileStore((s) => s.updateDocumentOptimistically);
+ const { allowed: canUpload } = usePermission('create_content');
const handleUploadFiles = useCallback(
- (files: File[]) => pushDockFileList(files, libraryId, currentFolderId ?? undefined),
- [currentFolderId, libraryId, pushDockFileList],
+ (files: File[]) => {
+ if (!canUpload) return;
+ pushDockFileList(files, libraryId, currentFolderId ?? undefined);
+ },
+ [canUpload, currentFolderId, libraryId, pushDockFileList],
);
const cssVariables = useMemo<Record<string, string>>(
@@ -133,7 +138,11 @@ const ResourceManager = memo(() => {
return (
<>
- <DragUploadZone enabledFiles style={{ height: '100%' }} onUploadFiles={handleUploadFiles}>
+ <DragUploadZone
+ enabledFiles={canUpload}
+ style={{ height: '100%' }}
+ onUploadFiles={handleUploadFiles}
+ >
<Flexbox className={styles.container} height={'100%'} style={cssVariables}>
{/* Explorer is always rendered to preserve its state */}
<Explorer />
diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsx
index a75fa5221db..8fda96653f1 100644
--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx
+++ b/src/features/ServiceModel/ModelAssignmentsForm.tsx
@@ -1,7 +1,7 @@
'use client';
import type { FormGroupItemType, FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form, Icon, InputNumber, Skeleton } from '@lobehub/ui';
+import { Flexbox, Form, Icon, InputNumber, Skeleton, Tooltip } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
import { ConfigProvider } from 'antd';
import isEqual from 'fast-deep-equal';
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
import ModelSelect from '@/features/ModelSelect';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import type { SystemAgentItem, UserServiceModelConfigKey } from '@/types/user/settings';
@@ -44,6 +45,7 @@ const MEMORY_MODEL_ITEMS: SystemAgentModelItem[] = [
const ModelAssignmentsForm = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
const [defaultAgent, systemAgentSettings] = useUserStore(
(s) => [settingsSelectors.defaultAgent(s), settingsSelectors.currentSystemAgent(s)],
isEqual,
@@ -68,6 +70,8 @@ const ModelAssignmentsForm = memo(() => {
model: string;
provider: string;
}) => {
+ if (!canManageServiceModel) return;
+
setLoadingKey('defaultAgent');
try {
await updateDefaultAgent({ config: { model, provider } });
@@ -80,6 +84,8 @@ const ModelAssignmentsForm = memo(() => {
key: UserServiceModelConfigKey,
value: Partial<SystemAgentItem>,
) => {
+ if (!canManageServiceModel) return;
+
setLoadingKey(key);
try {
await updateSystemAgent(key, value);
@@ -90,14 +96,22 @@ const ModelAssignmentsForm = memo(() => {
const defaultAgentItem: FormItemProps = {
children: (
- <Flexbox align="center" direction="horizontal" gap={12} style={{ width: 448 }}>
- <ModelSelect
- showAbility={false}
- style={{ minWidth: 0, width: '100%' }}
- value={defaultAgent.config}
- onChange={updateDefaultAgentModel}
- />
- </Flexbox>
+ <Tooltip title={reason}>
+ <Flexbox
+ align="center"
+ direction="horizontal"
+ gap={12}
+ style={{ width: 'min(100%, 448px)' }}
+ >
+ <ModelSelect
+ disabled={!canManageServiceModel}
+ showAbility={false}
+ style={{ minWidth: 0, width: '100%' }}
+ value={defaultAgent.config}
+ onChange={updateDefaultAgentModel}
+ />
+ </Flexbox>
+ </Tooltip>
),
desc: t('defaultAgent.model.desc'),
label: t('defaultAgent.title'),
@@ -108,14 +122,22 @@ const ModelAssignmentsForm = memo(() => {
return {
children: (
- <Flexbox align="center" direction="horizontal" gap={12} style={{ width: 448 }}>
- <ModelSelect
- showAbility={false}
- style={{ minWidth: 0, width: '100%' }}
- value={value}
- onChange={(props) => updateSystemAgentModel(key, props)}
- />
- </Flexbox>
+ <Tooltip title={reason}>
+ <Flexbox
+ align="center"
+ direction="horizontal"
+ gap={12}
+ style={{ width: 'min(100%, 448px)' }}
+ >
+ <ModelSelect
+ disabled={!canManageServiceModel}
+ showAbility={false}
+ style={{ minWidth: 0, width: '100%' }}
+ value={value}
+ onChange={(props) => updateSystemAgentModel(key, props)}
+ />
+ </Flexbox>
+ </Tooltip>
),
desc: t(`systemAgent.${key}.modelDesc`),
label: t(`systemAgent.${key}.title`),
@@ -158,31 +180,41 @@ const ModelAssignmentsForm = memo(() => {
const optionalFeatureItems: FormItemProps[] = OPTIONAL_FEATURE_ITEMS.map(({ key }) => {
const value = systemAgentSettings[key];
- const disabled = value.enabled === false;
+ const featureDisabled = value.enabled === false;
return {
children: (
- <Flexbox direction="vertical" gap={8} style={{ width: 448 }}>
- <Switch
- checked={value.enabled}
- loading={loadingKey === key}
- style={{ alignSelf: 'flex-end' }}
- title={t(`systemAgent.${key}.title`)}
- onChange={(enabled) => updateSystemAgentModel(key, { enabled })}
- />
- <ModelSelect
- showAbility={false}
- style={{ minWidth: 0, width: '100%' }}
- value={value}
- onChange={(props) => updateSystemAgentModel(key, props)}
- />
- </Flexbox>
+ <Tooltip title={reason}>
+ <Flexbox
+ align="center"
+ direction="horizontal"
+ gap={12}
+ style={{ width: 'min(100%, 448px)' }}
+ >
+ <ModelSelect
+ disabled={!canManageServiceModel}
+ showAbility={false}
+ style={{ minWidth: 0, width: '100%' }}
+ value={value}
+ onChange={(props) => updateSystemAgentModel(key, props)}
+ />
+ <Flexbox align="center" direction="horizontal" gap={8}>
+ <Switch
+ aria-label={t(`systemAgent.${key}.title`)}
+ checked={value.enabled}
+ disabled={!canManageServiceModel}
+ loading={loadingKey === key}
+ onChange={(enabled) => updateSystemAgentModel(key, { enabled })}
+ />
+ </Flexbox>
+ </Flexbox>
+ </Tooltip>
),
desc: t(`systemAgent.${key}.modelDesc`),
label: (
<span
style={{
- opacity: disabled ? 0.45 : 1,
+ opacity: featureDisabled || !canManageServiceModel ? 0.45 : 1,
}}
>
{t(`systemAgent.${key}.title`)}
diff --git a/src/features/SharePopover/index.tsx b/src/features/SharePopover/index.tsx
index d27698168a1..da86acf7d35 100644
--- a/src/features/SharePopover/index.tsx
+++ b/src/features/SharePopover/index.tsx
@@ -20,6 +20,7 @@ import useSWR from 'swr';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { topicService } from '@/services/topic';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
@@ -41,6 +42,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal, topic
const { close } = usePopoverContext();
const containerRef = useRef<HTMLDivElement>(null);
const appOrigin = useAppOrigin();
+ const { allowed: canShare, reason } = usePermission('edit_own_content');
const chatActiveTopicId = useChatStore((s) => s.activeTopicId);
const activeTopicId = topicId ?? chatActiveTopicId;
@@ -54,17 +56,17 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal, topic
isLoading,
mutate,
} = useSWR(
- activeTopicId ? ['topic-share-info', activeTopicId] : null,
+ activeTopicId && canShare ? ['topic-share-info', activeTopicId] : null,
() => topicService.getShareInfo(activeTopicId!),
{ revalidateOnFocus: false },
);
// Auto-create share record if not exists
useEffect(() => {
- if (!isLoading && !shareInfo && activeTopicId) {
+ if (!isLoading && !shareInfo && activeTopicId && canShare) {
topicService.enableSharing(activeTopicId, 'private').then(() => mutate());
}
- }, [isLoading, shareInfo, activeTopicId, mutate]);
+ }, [isLoading, shareInfo, activeTopicId, canShare, mutate]);
const shareUrl = shareInfo?.id ? `${appOrigin}/share/t/${shareInfo.id}` : '';
const currentVisibility = (shareInfo?.visibility as Visibility) || 'private';
@@ -126,13 +128,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal, topic
updateVisibility(visibility);
}
},
- [
- currentVisibility,
- hideTopicSharePrivacyWarning,
- t,
- updateSystemStatus,
- updateVisibility,
- ],
+ [currentVisibility, hideTopicSharePrivacyWarning, t, updateSystemStatus, updateVisibility],
);
const handleCopyLink = useCallback(async () => {
@@ -146,6 +142,15 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal, topic
onOpenModal?.();
}, [close, onOpenModal]);
+ if (!canShare) {
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ <Text strong>{t('share', { ns: 'common' })}</Text>
+ <Text type="secondary">{reason}</Text>
+ </Flexbox>
+ );
+ }
+
// Loading state
if (isLoading || !shareInfo) {
return (
diff --git a/src/features/SkillStore/SkillDetail/Header.tsx b/src/features/SkillStore/SkillDetail/Header.tsx
index a00ce4b7998..a0685b57354 100644
--- a/src/features/SkillStore/SkillDetail/Header.tsx
+++ b/src/features/SkillStore/SkillDetail/Header.tsx
@@ -1,6 +1,6 @@
'use client';
-import { Avatar, Flexbox, Icon, Text, useModalContext } from '@lobehub/ui';
+import { Avatar, Flexbox, Icon, Text, Tooltip, useModalContext } from '@lobehub/ui';
import { Button } from 'antd';
import { cssVar } from 'antd-style';
import { Loader2, Plus, SquareArrowOutUpRight } from 'lucide-react';
@@ -8,6 +8,7 @@ import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useSkillConnect } from '@/features/SkillStore/SkillList/LobeHub/useSkillConnect';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import { builtinToolSelectors } from '@/store/tool/selectors';
@@ -31,6 +32,8 @@ interface HeaderProps {
const Header = memo<HeaderProps>(({ type }) => {
const { t } = useTranslation(['setting']);
const { close } = useModalContext();
+ const { allowed: canCreate, reason: createReason } = usePermission('create_content');
+ const { allowed: canEdit, reason: editReason } = usePermission('edit_own_content');
const { identifier, serverName, icon, label, localizedDescription, isConnected } =
useDetailContext();
@@ -53,6 +56,8 @@ const Header = memo<HeaderProps>(({ type }) => {
]);
const handleBuiltinInstall = async () => {
+ if (!canCreate || !canEdit) return;
+
await installBuiltinTool(identifier);
close();
};
@@ -66,6 +71,8 @@ const Header = memo<HeaderProps>(({ type }) => {
}, [hookIsConnected, close, isBuiltin]);
const handleConnectWithTracking = async () => {
+ if (!canCreate || !canEdit) return;
+
hasTriggeredConnectRef.current = true;
await handleConnect();
};
@@ -93,9 +100,16 @@ const Header = memo<HeaderProps>(({ type }) => {
if (isBuiltinInstalled) return null;
return (
- <Button icon={<Icon icon={Plus} />} type="primary" onClick={handleBuiltinInstall}>
- {t('tools.builtins.install')}
- </Button>
+ <Tooltip title={!canCreate ? createReason : editReason}>
+ <Button
+ disabled={!canCreate || !canEdit}
+ icon={<Icon icon={Plus} />}
+ type="primary"
+ onClick={handleBuiltinInstall}
+ >
+ {t('tools.builtins.install')}
+ </Button>
+ </Tooltip>
);
}
@@ -111,13 +125,16 @@ const Header = memo<HeaderProps>(({ type }) => {
}
return (
- <Button
- icon={<Icon icon={SquareArrowOutUpRight} />}
- type="primary"
- onClick={handleConnectWithTracking}
- >
- {t('tools.klavis.connect', { defaultValue: 'Connect' })}
- </Button>
+ <Tooltip title={!canCreate ? createReason : editReason}>
+ <Button
+ disabled={!canCreate || !canEdit}
+ icon={<Icon icon={SquareArrowOutUpRight} />}
+ type="primary"
+ onClick={handleConnectWithTracking}
+ >
+ {t('tools.klavis.connect', { defaultValue: 'Connect' })}
+ </Button>
+ </Tooltip>
);
};
diff --git a/src/features/SkillStore/SkillList/AddSkillButton.tsx b/src/features/SkillStore/SkillList/AddSkillButton.tsx
index 4ccb722489c..f8552cd53fe 100644
--- a/src/features/SkillStore/SkillList/AddSkillButton.tsx
+++ b/src/features/SkillStore/SkillList/AddSkillButton.tsx
@@ -5,6 +5,7 @@ import { type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
import DevModal from '@/features/PluginDevModal';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useToolStore } from '@/store/tool';
@@ -27,6 +28,8 @@ const AddSkillButton = () => {
const [showUrlModal, setUrlModal] = useState(false);
const [showGithubModal, setGithubModal] = useState(false);
const [showUploadModal, setUploadModal] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [installCustomPlugin, updateNewDevPlugin] = useToolStore((s) => [
s.installCustomPlugin,
@@ -45,6 +48,7 @@ const AddSkillButton = () => {
onOpenChange={setMcpModal}
onValueChange={updateNewDevPlugin}
onSave={async (devPlugin) => {
+ if (!canCreate || !canEdit) return;
await installCustomPlugin(devPlugin);
await togglePlugin(devPlugin.identifier);
}}
@@ -57,35 +61,51 @@ const AddSkillButton = () => {
placement="bottomRight"
items={[
{
+ disabled: !canCreate,
icon: <Icon icon={Link} />,
key: 'importUrl',
label: <MenuLabel desc={t('tab.importFromUrl.desc')} title={t('tab.importFromUrl')} />,
- onClick: () => setUrlModal(true),
+ onClick: () => {
+ if (!canCreate) return;
+ setUrlModal(true);
+ },
},
{
+ disabled: !canCreate,
icon: <Icon icon={GithubIcon} />,
key: 'importGithub',
label: (
<MenuLabel desc={t('tab.importFromGithub.desc')} title={t('tab.importFromGithub')} />
),
- onClick: () => setGithubModal(true),
+ onClick: () => {
+ if (!canCreate) return;
+ setGithubModal(true);
+ },
},
{
+ disabled: !canCreate,
icon: <Icon icon={FileArchive} />,
key: 'uploadZip',
label: <MenuLabel desc={t('tab.uploadZip.desc')} title={t('tab.uploadZip')} />,
- onClick: () => setUploadModal(true),
+ onClick: () => {
+ if (!canCreate) return;
+ setUploadModal(true);
+ },
},
{ type: 'divider' as const },
{
+ disabled: !canCreate || !canEdit,
icon: <Icon icon={PenLine} />,
key: 'customMcp',
label: <MenuLabel desc={t('tab.addCustomMcp.desc')} title={t('tab.addCustomMcp')} />,
- onClick: () => setMcpModal(true),
+ onClick: () => {
+ if (!canCreate || !canEdit) return;
+ setMcpModal(true);
+ },
},
]}
>
- <Button icon={Grid2x2Plus}>
+ <Button disabled={!canCreate} icon={Grid2x2Plus}>
{t('tab.addCustomSkill')}
<Icon icon={ChevronDown} size={14} />
</Button>
diff --git a/src/features/SkillStore/SkillList/AgentSkillItem.tsx b/src/features/SkillStore/SkillList/AgentSkillItem.tsx
index 6b7ce071cb3..d9653792286 100644
--- a/src/features/SkillStore/SkillList/AgentSkillItem.tsx
+++ b/src/features/SkillStore/SkillList/AgentSkillItem.tsx
@@ -9,6 +9,7 @@ import { lazy, memo, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
import SkillAvatar from '@/components/SkillAvatar';
+import { usePermission } from '@/hooks/usePermission';
import { agentSkillService } from '@/services/skill';
import { useToolStore } from '@/store/tool';
import { type SkillListItem } from '@/types/index';
@@ -47,6 +48,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {
const [detailOpen, setDetailOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [loading, setLoading] = useState(false);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);
const handleDownload = async () => {
@@ -64,6 +66,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {
};
const handleDelete = () => {
+ if (!canEdit) return;
confirmModal({
cancelText: tc('cancel'),
content: t('store.actions.confirmUninstall'),
@@ -102,6 +105,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {
<Flexbox horizontal>
{skill.source === 'user' && (
<ActionIcon
+ disabled={!canEdit}
icon={PackageSearch}
title={t('store.actions.manifest')}
onClick={() => setEditOpen(true)}
@@ -124,6 +128,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {
: []),
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall'),
@@ -131,7 +136,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {
},
]}
>
- <ActionIcon icon={MoreVerticalIcon} loading={loading} />
+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} loading={loading} />
</DropdownMenu>
</Flexbox>
</Block>
diff --git a/src/features/SkillStore/SkillList/Builtin/Item.tsx b/src/features/SkillStore/SkillList/Builtin/Item.tsx
index f410c2e40c8..45050dfa865 100644
--- a/src/features/SkillStore/SkillList/Builtin/Item.tsx
+++ b/src/features/SkillStore/SkillList/Builtin/Item.tsx
@@ -14,6 +14,7 @@ import { MoreVerticalIcon, Plus, Trash2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import { builtinToolSelectors } from '@/store/tool/selectors';
@@ -30,6 +31,8 @@ interface ItemProps {
const Item = memo<ItemProps>(({ avatar, description, identifier, onOpenDetail, title }) => {
const { t } = useTranslation(['setting', 'plugin', 'common']);
const styles = itemStyles;
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [installBuiltinTool, uninstallBuiltinTool, isInstalled] = useToolStore((s) => [
s.installBuiltinTool,
@@ -38,10 +41,12 @@ const Item = memo<ItemProps>(({ avatar, description, identifier, onOpenDetail, t
]);
const handleInstall = async () => {
+ if (!canCreate) return;
await installBuiltinTool(identifier);
};
const handleUninstall = () => {
+ if (!canEdit) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('store.actions.confirmUninstall', { ns: 'plugin' }),
@@ -63,6 +68,7 @@ const Item = memo<ItemProps>(({ avatar, description, identifier, onOpenDetail, t
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall', { ns: 'plugin' }),
@@ -70,12 +76,19 @@ const Item = memo<ItemProps>(({ avatar, description, identifier, onOpenDetail, t
},
]}
>
- <ActionIcon icon={MoreVerticalIcon} />
+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} />
</DropdownMenu>
);
}
- return <ActionIcon icon={Plus} title={t('tools.builtins.install')} onClick={handleInstall} />;
+ return (
+ <ActionIcon
+ disabled={!canCreate}
+ icon={Plus}
+ title={t('tools.builtins.install')}
+ onClick={handleInstall}
+ />
+ );
};
return (
diff --git a/src/features/SkillStore/SkillList/Community/Item.tsx b/src/features/SkillStore/SkillList/Community/Item.tsx
index 7f1b7cfdab2..abb77242593 100644
--- a/src/features/SkillStore/SkillList/Community/Item.tsx
+++ b/src/features/SkillStore/SkillList/Community/Item.tsx
@@ -21,6 +21,7 @@ import PluginAvatar from '@/components/Plugins/PluginAvatar';
import McpDetail from '@/features/MCP/MCPDetail';
import McpDetailLoading from '@/features/MCP/MCPDetail/Loading';
import MCPInstallProgress from '@/features/MCP/MCPInstallProgress';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -34,6 +35,8 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>
const styles = itemStyles;
const { t } = useTranslation('plugin');
const [detailOpen, setDetailOpen] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [installed, installing, installMCPPlugin, cancelInstallMCPPlugin, unInstallPlugin, plugin] =
useToolStore((s) => [
@@ -59,6 +62,7 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>
const isCloudMcp = !!((plugin as any)?.cloudEndPoint || (plugin as any)?.haveCloudEndpoint);
const handleInstall = async () => {
+ if (!canCreate || !canEdit) return;
if (isCloudMcp && !isAuthenticated) {
try {
await signIn('mcp');
@@ -87,10 +91,12 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall'),
onClick: () => {
+ if (!canEdit) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -118,7 +124,14 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>
);
}
- return <ActionIcon icon={Plus} title={t('store.actions.install')} onClick={handleInstall} />;
+ return (
+ <ActionIcon
+ disabled={!canCreate || !canEdit}
+ icon={Plus}
+ title={t('store.actions.install')}
+ onClick={handleInstall}
+ />
+ );
};
return (
diff --git a/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx b/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx
index dc675a028df..aefa9469bc3 100644
--- a/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx
+++ b/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx
@@ -8,6 +8,7 @@ import { DownloadIcon, Loader2, MoreVerticalIcon, Plus, Trash2 } from 'lucide-re
import { lazy, memo, Suspense, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { agentSkillService } from '@/services/skill';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
@@ -42,6 +43,8 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
const [detailOpen, setDetailOpen] = useState(false);
const [installing, setInstalling] = useState(false);
const [loading, setLoading] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const installed = useToolStore(agentSkillsSelectors.isAgentSkill(identifier));
const installedSkill = useToolStore(agentSkillsSelectors.getAgentSkillByIdentifier(identifier));
@@ -51,7 +54,7 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
]);
const handleInstall = useCallback(async () => {
- if (installing || installed) return;
+ if (!canCreate || installing || installed) return;
setInstalling(true);
try {
await agentSkillService.importFromMarket(identifier);
@@ -61,10 +64,10 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
} finally {
setInstalling(false);
}
- }, [identifier, installing, installed, refreshAgentSkills]);
+ }, [canCreate, identifier, installing, installed, refreshAgentSkills]);
const handleUninstall = useCallback(() => {
- if (!installedSkill) return;
+ if (!canEdit || !installedSkill) return;
confirmModal({
cancelText: tc('cancel'),
content: t('store.actions.confirmUninstall'),
@@ -75,7 +78,7 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
},
title: t('store.actions.uninstall'),
});
- }, [installedSkill, deleteAgentSkill, t, tc]);
+ }, [canEdit, installedSkill, deleteAgentSkill, t, tc]);
const handleDownload = useCallback(async () => {
if (!installedSkill?.zipFileHash) return;
@@ -110,6 +113,7 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
: []),
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall'),
@@ -117,14 +121,21 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden
},
]}
>
- <ActionIcon icon={MoreVerticalIcon} loading={loading} />
+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} loading={loading} />
</DropdownMenu>
);
}
if (installing) return <ActionIcon loading icon={Loader2} />;
- return <ActionIcon icon={Plus} title={t('store.actions.install')} onClick={handleInstall} />;
+ return (
+ <ActionIcon
+ disabled={!canCreate}
+ icon={Plus}
+ title={t('store.actions.install')}
+ onClick={handleInstall}
+ />
+ );
};
return (
diff --git a/src/features/SkillStore/SkillList/Custom/Item.tsx b/src/features/SkillStore/SkillList/Custom/Item.tsx
index 7138098a9af..dca579b034b 100644
--- a/src/features/SkillStore/SkillList/Custom/Item.tsx
+++ b/src/features/SkillStore/SkillList/Custom/Item.tsx
@@ -11,6 +11,7 @@ import MCPTag from '@/components/Plugins/MCPTag';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import PluginDetailModal from '@/features/PluginDetailModal';
import DevModal from '@/features/PluginDevModal';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useToolStore } from '@/store/tool';
@@ -47,6 +48,7 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
const { t } = useTranslation('plugin');
const [configOpen, setConfigOpen] = useState(false);
const [detailOpen, setDetailOpen] = useState(false);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [customPlugin, uninstallPlugin, updateCustomPlugin, pluginManifest] = useToolStore((s) => [
pluginSelectors.getCustomPluginById(identifier)(s),
@@ -61,6 +63,7 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
]);
const handleDelete = () => {
+ if (!canEdit) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -96,6 +99,7 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
</Flexbox>
<Flexbox horizontal>
<ActionIcon
+ disabled={!canEdit}
icon={PackageSearch}
title={t('store.actions.manifest')}
onClick={() => setConfigOpen(true)}
@@ -106,6 +110,7 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall'),
@@ -113,7 +118,7 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
},
]}
>
- <ActionIcon icon={MoreVerticalIcon} />
+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} />
</DropdownMenu>
</Flexbox>
</Block>
@@ -125,12 +130,14 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {
value={customPlugin}
onOpenChange={setConfigOpen}
onDelete={async () => {
+ if (!canEdit) return;
if (isPluginEnabledInAgent) {
await togglePlugin(identifier, false);
}
await uninstallPlugin(identifier);
}}
onSave={async (value) => {
+ if (!canEdit) return;
await updateCustomPlugin(identifier, value);
}}
/>
diff --git a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
index a8398f1e426..747d5bda6ce 100644
--- a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
+++ b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
@@ -7,6 +7,7 @@ import { ArrowLeftRight, Sparkles } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
interface ImportFromGithubModalProps {
@@ -21,6 +22,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [url, setUrl] = useState('');
+ const { allowed: canCreate } = usePermission('create_content');
const handleClose = () => {
onOpenChange(false);
@@ -30,7 +32,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
const handleImport = async () => {
const trimmed = url.trim();
- if (!trimmed) return;
+ if (!canCreate || !trimmed) return;
setLoading(true);
setError(null);
@@ -77,6 +79,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
<Flexbox gap={8}>
<Typography.Text strong>URL</Typography.Text>
<Input
+ disabled={!canCreate}
placeholder={t('agentSkillModal.github.urlPlaceholder')}
value={url}
onPressEnter={handleImport}
@@ -87,7 +90,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
/>
</Flexbox>
- <Button block loading={loading} type="primary" onClick={handleImport}>
+ <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
{t('common:import')}
</Button>
</Flexbox>
diff --git a/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
index 02812e07956..1cdbc4cbb72 100644
--- a/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
+++ b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
@@ -6,6 +6,7 @@ import { ArrowLeftRight, Link, Sparkles } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
interface ImportFromUrlModalProps {
@@ -20,6 +21,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [url, setUrl] = useState('');
+ const { allowed: canCreate } = usePermission('create_content');
const handleClose = () => {
onOpenChange(false);
@@ -29,7 +31,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
const handleImport = async () => {
const trimmed = url.trim();
- if (!trimmed) return;
+ if (!canCreate || !trimmed) return;
setLoading(true);
setError(null);
@@ -74,6 +76,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
<Flexbox gap={8}>
<Typography.Text strong>URL</Typography.Text>
<Input
+ disabled={!canCreate}
placeholder={t('agentSkillModal.url.urlPlaceholder')}
value={url}
onPressEnter={handleImport}
@@ -84,7 +87,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
/>
</Flexbox>
- <Button block loading={loading} type="primary" onClick={handleImport}>
+ <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
{t('common:import')}
</Button>
</Flexbox>
diff --git a/src/features/SkillStore/SkillList/LobeHub/Item.tsx b/src/features/SkillStore/SkillList/LobeHub/Item.tsx
index cc00344c97d..4a1aaa6ecd6 100644
--- a/src/features/SkillStore/SkillList/LobeHub/Item.tsx
+++ b/src/features/SkillStore/SkillList/LobeHub/Item.tsx
@@ -8,6 +8,8 @@ import { Loader2, MoreVerticalIcon, Plus, Unplug } from 'lucide-react';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { itemStyles } from '../style';
import { useSkillConnect } from './useSkillConnect';
@@ -26,6 +28,8 @@ const Item = memo<ItemProps>(
({ description, icon, identifier, label, onOpenDetail, serverName, type }) => {
const { t } = useTranslation('setting');
const styles = itemStyles;
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const { handleConnect, handleDisconnect, isConnected, isConnecting } = useSkillConnect({
identifier,
@@ -41,6 +45,7 @@ const Item = memo<ItemProps>(
});
const confirmDisconnect = () => {
+ if (!canEdit) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('tools.lobehubSkill.disconnectConfirm.desc', { name: label }),
@@ -71,6 +76,7 @@ const Item = memo<ItemProps>(
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Unplug} />,
key: 'disconnect',
label: t('tools.lobehubSkill.disconnect'),
@@ -78,13 +84,21 @@ const Item = memo<ItemProps>(
},
]}
>
- <ActionIcon icon={MoreVerticalIcon} />
+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} />
</DropdownMenu>
);
}
return (
- <ActionIcon icon={Plus} title={t('tools.lobehubSkill.connect')} onClick={handleConnect} />
+ <ActionIcon
+ disabled={!canCreate || !canEdit}
+ icon={Plus}
+ title={t('tools.lobehubSkill.connect')}
+ onClick={() => {
+ if (!canCreate || !canEdit) return;
+ handleConnect();
+ }}
+ />
);
};
diff --git a/src/features/SkillStore/SkillList/UploadSkillModal.tsx b/src/features/SkillStore/SkillList/UploadSkillModal.tsx
index 86d4e54cee3..d60a692d602 100644
--- a/src/features/SkillStore/SkillList/UploadSkillModal.tsx
+++ b/src/features/SkillStore/SkillList/UploadSkillModal.tsx
@@ -8,6 +8,7 @@ import { ArrowLeftRight, InboxIcon, Sparkles, Upload as UploadIcon } from 'lucid
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaClient } from '@/libs/trpc/client/lambda';
import { uploadService } from '@/services/upload';
import { useToolStore } from '@/store/tool';
@@ -23,6 +24,7 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
const importAgentSkillFromZip = useToolStore((s) => s.importAgentSkillFromZip);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const { allowed: canCreate } = usePermission('create_content');
const handleClose = () => {
onOpenChange(false);
@@ -30,6 +32,7 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
};
const handleUploadFile = async (file: File) => {
+ if (!canCreate) return;
setLoading(true);
setError(null);
@@ -96,9 +99,10 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
<Upload.Dragger
accept=".zip,.skill"
- disabled={loading}
+ disabled={loading || !canCreate}
showUploadList={false}
beforeUpload={(file) => {
+ if (!canCreate) return false;
handleUploadFile(file);
return false;
}}
diff --git a/src/features/SuggestQuestions/Item.test.tsx b/src/features/SuggestQuestions/Item.test.tsx
new file mode 100644
index 00000000000..019788cd44c
--- /dev/null
+++ b/src/features/SuggestQuestions/Item.test.tsx
@@ -0,0 +1,36 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import Item from './Item';
+
+const setDocument = vi.fn();
+const focus = vi.fn();
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: any) =>
+ selector({
+ mainInputEditor: {
+ focus,
+ instance: { setDocument },
+ },
+ }),
+}));
+
+describe('SuggestQuestions Item', () => {
+ beforeEach(() => {
+ focus.mockReset();
+ setDocument.mockReset();
+ });
+
+ it('does not write to the input when disabled', () => {
+ render(<Item disabled description="Prompt description" prompt="Prompt" title="Prompt title" />);
+
+ fireEvent.click(screen.getByText('Prompt title'));
+
+ expect(setDocument).not.toHaveBeenCalled();
+ expect(focus).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/SuggestQuestions/Item.tsx b/src/features/SuggestQuestions/Item.tsx
index a6c2aac3270..e06b5e517bc 100644
--- a/src/features/SuggestQuestions/Item.tsx
+++ b/src/features/SuggestQuestions/Item.tsx
@@ -8,25 +8,29 @@ import { useChatStore } from '@/store/chat';
interface ItemProps {
description: string;
+ disabled?: boolean;
prompt: string;
title: string;
}
-const Item = memo<ItemProps>(({ title, description, prompt }) => {
+const Item = memo<ItemProps>(({ title, description, disabled, prompt }) => {
const mainInputEditor = useChatStore((s) => s.mainInputEditor);
const handleClick = useCallback(() => {
+ if (disabled) return;
+
mainInputEditor?.instance?.setDocument('markdown', prompt);
mainInputEditor?.focus();
- }, [prompt, mainInputEditor]);
+ }, [disabled, prompt, mainInputEditor]);
return (
<Block
- clickable
+ clickable={!disabled}
variant={'outlined'}
style={{
borderRadius: cssVar.borderRadiusLG,
- cursor: 'pointer',
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.65 : undefined,
}}
onClick={handleClick}
>
diff --git a/src/features/SuggestQuestions/List.tsx b/src/features/SuggestQuestions/List.tsx
index c1b51a21ab2..08121f1bc2b 100644
--- a/src/features/SuggestQuestions/List.tsx
+++ b/src/features/SuggestQuestions/List.tsx
@@ -12,10 +12,11 @@ import { useRandomQuestions } from './useRandomQuestions';
interface ListProps {
count?: number;
+ disabled?: boolean;
mode: SuggestMode;
}
-const List = memo<ListProps>(({ mode, count = 3 }) => {
+const List = memo<ListProps>(({ mode, count = 3, disabled }) => {
const { t } = useTranslation('suggestQuestions');
const { t: tCommon } = useTranslation('common');
const { questions, refresh } = useRandomQuestions(mode, count);
@@ -32,6 +33,7 @@ const List = memo<ListProps>(({ mode, count = 3 }) => {
return (
<Item
description={prompt}
+ disabled={disabled}
key={item.id}
prompt={prompt}
title={t(item.titleKey as any)}
@@ -39,8 +41,21 @@ const List = memo<ListProps>(({ mode, count = 3 }) => {
);
})}
</Flexbox>
- <Flexbox horizontal align={'center'} gap={4} style={{ cursor: 'pointer' }} onClick={refresh}>
- <ActionIcon icon={RefreshCw} size={'small'} />
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={{
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.65 : undefined,
+ }}
+ onClick={() => {
+ if (disabled) return;
+
+ refresh();
+ }}
+ >
+ <ActionIcon disabled={disabled} icon={RefreshCw} size={'small'} />
<Text color={cssVar.colorTextSecondary} fontSize={12}>
{tCommon('switch')}
</Text>
diff --git a/src/features/SuggestQuestions/index.test.tsx b/src/features/SuggestQuestions/index.test.tsx
new file mode 100644
index 00000000000..89e1df491b8
--- /dev/null
+++ b/src/features/SuggestQuestions/index.test.tsx
@@ -0,0 +1,47 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import SuggestQuestions from './index';
+
+const permissionMock = vi.hoisted(() => ({
+ allowed: true,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({
+ allowed: permissionMock.allowed,
+ reason: '',
+ }),
+}));
+
+vi.mock('./List', () => ({
+ default: ({ disabled }: { disabled?: boolean }) => (
+ <div data-disabled={String(!!disabled)}>suggest list</div>
+ ),
+}));
+
+vi.mock('./Skeleton', () => ({
+ default: () => <div>loading</div>,
+}));
+
+describe('SuggestQuestions', () => {
+ beforeEach(() => {
+ permissionMock.allowed = true;
+ });
+
+ it('disables question clicks when the user cannot create content', () => {
+ permissionMock.allowed = false;
+
+ render(<SuggestQuestions mode="write" />);
+
+ expect(screen.getByText('suggest list')).toHaveAttribute('data-disabled', 'true');
+ });
+});
diff --git a/src/features/SuggestQuestions/index.tsx b/src/features/SuggestQuestions/index.tsx
index dc76e519c54..816770fe3cf 100644
--- a/src/features/SuggestQuestions/index.tsx
+++ b/src/features/SuggestQuestions/index.tsx
@@ -3,20 +3,26 @@
import { Flexbox } from '@lobehub/ui';
import { memo, Suspense } from 'react';
+import { usePermission } from '@/hooks/usePermission';
+
import List from './List';
import Skeleton from './Skeleton';
import { type SuggestMode } from './useRandomQuestions';
interface SuggestQuestionsProps {
count?: number;
+ disabled?: boolean;
mode: SuggestMode;
}
-const SuggestQuestions = memo<SuggestQuestionsProps>(({ mode, count = 3 }) => {
+const SuggestQuestions = memo<SuggestQuestionsProps>(({ mode, count = 3, disabled }) => {
+ const { allowed: canCreateContent } = usePermission('create_content');
+ const isDisabled = disabled || !canCreateContent;
+
return (
<Flexbox width={'100%'}>
<Suspense fallback={<Skeleton count={count} />}>
- <List count={count} mode={mode} />
+ <List count={count} disabled={isDisabled} mode={mode} />
</Suspense>
</Flexbox>
);
diff --git a/src/features/TopicCanvas/TopicMetaBar.tsx b/src/features/TopicCanvas/TopicMetaBar.tsx
new file mode 100644
index 00000000000..73fa2d1dc4f
--- /dev/null
+++ b/src/features/TopicCanvas/TopicMetaBar.tsx
@@ -0,0 +1,9 @@
+import { memo } from 'react';
+
+interface TopicMetaBarProps {
+ topicId?: string | null;
+}
+
+const TopicMetaBar = memo<TopicMetaBarProps>(() => null);
+
+export default TopicMetaBar;
diff --git a/src/features/User/AccountPanel/AccountHeader.tsx b/src/features/User/AccountPanel/AccountHeader.tsx
new file mode 100644
index 00000000000..96a26e73e82
--- /dev/null
+++ b/src/features/User/AccountPanel/AccountHeader.tsx
@@ -0,0 +1,55 @@
+'use client';
+
+import { ActionIcon, Block, Flexbox, Text } from '@lobehub/ui';
+import { Settings2 } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+interface AccountHeaderProps {
+ onNavigate?: () => void;
+}
+
+const AccountHeader = memo<AccountHeaderProps>(({ onNavigate }) => {
+ const { t } = useTranslation('common');
+ const [nickname, username, email] = useUserStore((s) => [
+ userProfileSelectors.nickName(s),
+ userProfileSelectors.username(s),
+ userProfileSelectors.email(s),
+ ]);
+
+ const displayName = nickname || username || '';
+
+ return (
+ <Link style={{ color: 'inherit', display: 'block' }} to={'/settings'} onClick={onNavigate}>
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ gap={12}
+ paddingBlock={12}
+ paddingInline={12}
+ variant={'borderless'}
+ >
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <Text ellipsis style={{ lineHeight: 1.4 }} weight={'bold'}>
+ {displayName}
+ </Text>
+ {email && (
+ <Text ellipsis fontSize={12} style={{ lineHeight: 1.4 }} type={'secondary'}>
+ {email}
+ </Text>
+ )}
+ </Flexbox>
+ <ActionIcon icon={Settings2} size={'small'} tabIndex={-1} title={t('userPanel.setting')} />
+ </Block>
+ </Link>
+ );
+});
+
+AccountHeader.displayName = 'AccountHeader';
+
+export default AccountHeader;
diff --git a/src/features/User/AccountPanel/AccountTrigger.tsx b/src/features/User/AccountPanel/AccountTrigger.tsx
new file mode 100644
index 00000000000..df99dedb23b
--- /dev/null
+++ b/src/features/User/AccountPanel/AccountTrigger.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { ActionIcon, Block, type MenuProps, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { MoreHorizontal } from 'lucide-react';
+import { memo, type ReactNode, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import UserAvatar from '@/features/User/UserAvatar';
+import UpgradeBadge from '@/features/User/UserPanel/UpgradeBadge';
+import { useNewVersion } from '@/features/User/UserPanel/useNewVersion';
+import { useUserStore } from '@/store/user';
+import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
+
+import AccountPanel from '.';
+
+const styles = createStaticStyles(({ css }) => ({
+ trigger: css`
+ &:hover:not(:has(.account-trigger-actions:hover)) .account-trigger-more {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+}));
+
+interface AccountTriggerProps {
+ actions?: ReactNode;
+ extraItems?: MenuProps['items'];
+}
+
+const AccountTrigger = memo<AccountTriggerProps>(({ actions, extraItems }) => {
+ const { t } = useTranslation('common');
+ const isSignedIn = useUserStore(authSelectors.isLogin);
+ const [nickname, username] = useUserStore((s) => [
+ userProfileSelectors.nickName(s),
+ userProfileSelectors.username(s),
+ ]);
+ const hasNewVersion = useNewVersion();
+
+ const stopPropagation = useCallback((event: React.MouseEvent) => {
+ event.stopPropagation();
+ }, []);
+
+ if (!isSignedIn) return null;
+
+ const displayName = nickname || username || '';
+
+ return (
+ <UpgradeBadge showBadge={hasNewVersion}>
+ <AccountPanel extraItems={extraItems}>
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ aria-label={t('userPanel.profile')}
+ className={styles.trigger}
+ flex={1}
+ gap={8}
+ title={t('userPanel.profile')}
+ variant={'borderless'}
+ style={{
+ height: 36,
+ minWidth: 0,
+ paddingBlock: 4,
+ paddingInline: 6,
+ }}
+ >
+ <UserAvatar background={cssVar.colorFill} clickable={false} size={24} />
+ {displayName && (
+ <Text
+ ellipsis
+ fontSize={13}
+ style={{ flex: 1, lineHeight: 1, minWidth: 0 }}
+ weight={500}
+ >
+ {displayName}
+ </Text>
+ )}
+ <ActionIcon
+ className={'account-trigger-more'}
+ icon={MoreHorizontal}
+ size={'small'}
+ tabIndex={-1}
+ />
+ {actions && (
+ <div
+ className={'account-trigger-actions'}
+ style={{ display: 'flex', flex: 'none' }}
+ onClick={stopPropagation}
+ onPointerDown={stopPropagation}
+ >
+ {actions}
+ </div>
+ )}
+ </Block>
+ </AccountPanel>
+ </UpgradeBadge>
+ );
+});
+
+AccountTrigger.displayName = 'AccountTrigger';
+
+export default AccountTrigger;
diff --git a/src/features/User/AccountPanel/PanelContent.tsx b/src/features/User/AccountPanel/PanelContent.tsx
new file mode 100644
index 00000000000..4824b16238a
--- /dev/null
+++ b/src/features/User/AccountPanel/PanelContent.tsx
@@ -0,0 +1,56 @@
+import { Flexbox, type MenuProps } from '@lobehub/ui';
+import { type FC } from 'react';
+
+import Menu, { type MenuProps as AntdMenuProps } from '@/components/Menu';
+import { isDesktop } from '@/const/version';
+import LangButton from '@/features/User/UserPanel/LangButton';
+import { navigateToDesktopOnboarding } from '@/routes/(desktop)/desktop-onboarding/navigation';
+import { DesktopOnboardingScreen } from '@/routes/(desktop)/desktop-onboarding/types';
+import { useUserStore } from '@/store/user';
+
+import AccountHeader from './AccountHeader';
+import { useAccountMenu } from './useMenu';
+
+interface PanelContentProps {
+ closePopover: () => void;
+ extraItems?: MenuProps['items'];
+}
+
+const PanelContent: FC<PanelContentProps> = ({ closePopover, extraItems }) => {
+ const signOut = useUserStore((s) => s.logout);
+ const { mainItems, logoutItems } = useAccountMenu();
+
+ const handleSignOut = async () => {
+ if (isDesktop) {
+ closePopover();
+
+ try {
+ const { remoteServerService } = await import('@/services/electron/remoteServer');
+ await remoteServerService.clearRemoteServerConfig();
+ } catch (error) {
+ console.error(error);
+ } finally {
+ signOut();
+ navigateToDesktopOnboarding(DesktopOnboardingScreen.Login);
+ }
+ return;
+ }
+
+ signOut();
+ closePopover();
+ };
+
+ return (
+ <Flexbox gap={2} style={{ minWidth: 260, width: '100%' }}>
+ <AccountHeader onNavigate={closePopover} />
+ {extraItems && extraItems.length > 0 && (
+ <Menu items={extraItems as AntdMenuProps['items']} onClick={closePopover} />
+ )}
+ <Menu items={mainItems} onClick={closePopover} />
+ <LangButton placement={'right' as any} />
+ <Menu items={logoutItems} onClick={handleSignOut} />
+ </Flexbox>
+ );
+};
+
+export default PanelContent;
diff --git a/src/features/User/AccountPanel/index.tsx b/src/features/User/AccountPanel/index.tsx
new file mode 100644
index 00000000000..5dfdbc46fb3
--- /dev/null
+++ b/src/features/User/AccountPanel/index.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { type MenuProps, Popover } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { type PropsWithChildren } from 'react';
+import { memo, Suspense, useEffect, useRef, useState } from 'react';
+
+import { isDesktop } from '@/const/version';
+
+import PanelContent from './PanelContent';
+
+const styles = createStaticStyles(({ css }) => {
+ return {
+ popover: css`
+ inset-block-end: ${isDesktop ? 16 : 8}px;
+ inset-inline-start: 8px !important;
+ border-radius: 10px;
+ `,
+ popoverContent: css`
+ padding: 0;
+ `,
+ };
+});
+
+interface AccountPanelProps extends PropsWithChildren {
+ extraItems?: MenuProps['items'];
+}
+
+const AccountPanel = memo<AccountPanelProps>(({ children, extraItems }) => {
+ const [open, setOpen] = useState(false);
+ const triggerRef = useRef<HTMLDivElement>(null);
+ const [triggerWidth, setTriggerWidth] = useState<number>();
+
+ useEffect(() => {
+ const node = triggerRef.current;
+ if (!node) return;
+
+ const update = () => setTriggerWidth(node.getBoundingClientRect().width);
+ update();
+
+ const observer = new ResizeObserver(update);
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, []);
+
+ return (
+ <Suspense fallback={children}>
+ <Popover
+ arrow={false}
+ content={<PanelContent closePopover={() => setOpen(false)} extraItems={extraItems} />}
+ open={open}
+ placement="topLeft"
+ styles={triggerWidth ? { content: { minWidth: triggerWidth } } : undefined}
+ trigger="click"
+ classNames={{
+ root: styles.popover,
+ content: styles.popoverContent,
+ }}
+ onOpenChange={setOpen}
+ >
+ <div ref={triggerRef} style={{ display: 'flex', flex: 1, minWidth: 0 }}>
+ {children}
+ </div>
+ </Popover>
+ </Suspense>
+ );
+});
+
+AccountPanel.displayName = 'AccountPanel';
+
+export default AccountPanel;
diff --git a/src/features/User/AccountPanel/useMenu.tsx b/src/features/User/AccountPanel/useMenu.tsx
new file mode 100644
index 00000000000..88d2e94afda
--- /dev/null
+++ b/src/features/User/AccountPanel/useMenu.tsx
@@ -0,0 +1,56 @@
+import { DOWNLOAD_URL, isDesktop } from '@lobechat/const';
+import { Icon } from '@lobehub/ui';
+import { Download, LogOut } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type MenuProps } from '@/components/Menu';
+import { usePlatform } from '@/hooks/usePlatform';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+export const useAccountMenu = () => {
+ const { t } = useTranslation(['common', 'auth']);
+ const isLoginWithAuth = useUserStore(authSelectors.isLoginWithAuth);
+ const { isIOS, isAndroid } = usePlatform();
+
+ const downloadUrl = useMemo(() => {
+ if (isIOS) return DOWNLOAD_URL.ios;
+ if (isAndroid) return DOWNLOAD_URL.android;
+ return DOWNLOAD_URL.default;
+ }, [isIOS, isAndroid]);
+
+ // Settings is reached via the gear icon in the AccountHeader; the menu only
+ // covers items that don't have a dedicated entry point.
+ const mainItems: MenuProps['items'] = isDesktop
+ ? []
+ : [
+ {
+ type: 'divider',
+ },
+ {
+ icon: <Icon icon={Download} />,
+ key: 'get-desktop-app',
+ label: (
+ <a href={downloadUrl} rel="noopener noreferrer" target="_blank">
+ {t('getDesktopApp')}
+ </a>
+ ),
+ },
+ ];
+
+ const logoutItems: MenuProps['items'] = isLoginWithAuth
+ ? [
+ {
+ type: 'divider',
+ },
+ {
+ icon: <Icon icon={LogOut} />,
+ key: 'logout',
+ label: <span>{t('signout', { ns: 'auth' })}</span>,
+ },
+ ]
+ : [];
+
+ return { logoutItems, mainItems };
+};
diff --git a/src/features/User/UserAvatar.tsx b/src/features/User/UserAvatar.tsx
index 87af0b79408..25f642ef9ff 100644
--- a/src/features/User/UserAvatar.tsx
+++ b/src/features/User/UserAvatar.tsx
@@ -46,7 +46,15 @@ const styles = createStaticStyles(({ css }) => ({
}));
export interface UserAvatarProps extends AvatarProps {
+ /**
+ * Override the avatar URL/emoji — used when the component is acting as a
+ * generic "active identity" avatar (e.g. showing the active team workspace
+ * in the header). Falls back to the signed-in user's avatar when omitted.
+ */
+ avatarOverride?: string;
clickable?: boolean;
+ /** Override the alt text / fallback initial. */
+ nameOverride?: string;
}
const UserAvatar = ({
@@ -56,6 +64,8 @@ const UserAvatar = ({
clickable,
className,
style,
+ avatarOverride,
+ nameOverride,
...rest
}: UserAvatarProps & { ref?: React.RefObject<HTMLDivElement | null> }) => {
const [avatar, nickName, username] = useUserStore((s) => [
@@ -68,7 +78,7 @@ const UserAvatar = ({
const remoteServerUrl = useElectronStore(electronSyncSelectors.remoteServerUrl);
// Process avatar URL for desktop environment
- const avatarUrl = useMemo(() => {
+ const userAvatarUrl = useMemo(() => {
if (!isSignedIn) return DEFAULT_USER_AVATAR_URL;
if (!avatar) return;
@@ -80,10 +90,19 @@ const UserAvatar = ({
return avatar;
}, [isSignedIn, avatar, remoteServerUrl]);
+ // When a `nameOverride` is provided, the component is in "non-user identity"
+ // mode (e.g. active team workspace). Stay inside that identity — don't fall
+ // through to the signed-in user's avatar/name, or the icon and the label
+ // will disagree. When `nameOverride` is absent, keep the original user flow.
+ const avatarValue = nameOverride
+ ? avatarOverride || nameOverride
+ : avatarOverride || userAvatarUrl || nickName || username;
+ const altText = nameOverride || (isSignedIn ? nickName || username || 'User' : BRANDING_NAME);
+
return (
<Avatar
- alt={isSignedIn ? nickName || username || 'User' : BRANDING_NAME}
- avatar={avatarUrl || nickName || username}
+ alt={altText}
+ avatar={avatarValue}
background={background}
className={clickable ? styles.clickable : className}
ref={ref}
diff --git a/src/features/User/UserPanel/PanelContent.tsx b/src/features/User/UserPanel/PanelContent.tsx
index c901807e664..c594392f1c5 100644
--- a/src/features/User/UserPanel/PanelContent.tsx
+++ b/src/features/User/UserPanel/PanelContent.tsx
@@ -1,70 +1,47 @@
import { Flexbox } from '@lobehub/ui';
import { type FC } from 'react';
-import { Link } from 'react-router-dom';
import BusinessPanelContent from '@/business/client/features/User/BusinessPanelContent';
+import UserPanelWorkspaceSection from '@/business/client/features/User/UserPanelWorkspaceSection';
import Menu from '@/components/Menu';
import { isDesktop } from '@/const/version';
import UserInfo from '@/features/User/UserInfo';
-import { navigateToDesktopOnboarding } from '@/routes/(desktop)/desktop-onboarding/navigation';
-import { DesktopOnboardingScreen } from '@/routes/(desktop)/desktop-onboarding/types';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import DataStatistics from '../DataStatistics';
import UserLoginOrSignup from '../UserLoginOrSignup';
-import LangButton from './LangButton';
import { useMenu } from './useMenu';
const PanelContent: FC<{ closePopover: () => void }> = ({ closePopover }) => {
const isLoginWithAuth = useUserStore(authSelectors.isLoginWithAuth);
- const [openSignIn, signOut] = useUserStore((s) => [s.openLogin, s.logout]);
+ const openSignIn = useUserStore((s) => s.openLogin);
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
- const { mainItems, logoutItems } = useMenu();
+ const { mainItems } = useMenu();
const handleSignIn = () => {
openSignIn();
closePopover();
};
- const handleSignOut = async () => {
- if (isDesktop) {
- closePopover();
-
- try {
- const { remoteServerService } = await import('@/services/electron/remoteServer');
- await remoteServerService.clearRemoteServerConfig();
- } catch (error) {
- console.error(error);
- } finally {
- signOut();
- navigateToDesktopOnboarding(DesktopOnboardingScreen.Login);
- }
- return;
- }
-
- signOut();
- closePopover();
- };
-
return (
<Flexbox gap={2} style={{ minWidth: 300 }}>
{isDesktop || isLoginWithAuth ? (
<>
<UserInfo avatarProps={{ clickable: false }} />
- <Link style={{ color: 'inherit' }} to={'/settings/stats'}>
+ <WorkspaceLink style={{ color: 'inherit' }} to={'/settings/stats'}>
<DataStatistics />
- </Link>
+ </WorkspaceLink>
{enableBusinessFeatures && <BusinessPanelContent />}
+ <UserPanelWorkspaceSection onSwitch={closePopover} />
</>
) : (
<UserLoginOrSignup onClick={handleSignIn} />
)}
<Menu items={mainItems} onClick={closePopover} />
- <LangButton placement={'right' as any} />
- <Menu items={logoutItems} onClick={handleSignOut} />
</Flexbox>
);
};
diff --git a/src/features/User/UserPanel/ThemeRow.tsx b/src/features/User/UserPanel/ThemeRow.tsx
new file mode 100644
index 00000000000..978b18c3726
--- /dev/null
+++ b/src/features/User/UserPanel/ThemeRow.tsx
@@ -0,0 +1,39 @@
+import { Flexbox } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ThemeButton from './ThemeButton';
+
+const ThemeRow = memo(() => {
+ const { t } = useTranslation('setting');
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ justify={'space-between'}
+ style={{
+ borderRadius: 8,
+ cursor: 'default',
+ marginInline: 4,
+ paddingBlock: 6,
+ paddingInline: 12,
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background = cssVar.colorFillTertiary as string;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = 'transparent';
+ }}
+ >
+ <span>{t('settingCommon.themeMode.title')}</span>
+ <ThemeButton placement={'right'} size={16} />
+ </Flexbox>
+ );
+});
+
+ThemeRow.displayName = 'ThemeRow';
+
+export default ThemeRow;
diff --git a/src/features/User/UserPanel/index.tsx b/src/features/User/UserPanel/index.tsx
index 9c8d6c908d9..68d2f700579 100644
--- a/src/features/User/UserPanel/index.tsx
+++ b/src/features/User/UserPanel/index.tsx
@@ -9,8 +9,6 @@ import { isDesktop } from '@/const/version';
import PanelContent from './PanelContent';
import PanelContentSkeleton from './PanelContentSkeleton';
-import UpgradeBadge from './UpgradeBadge';
-import { useNewVersion } from './useNewVersion';
const styles = createStaticStyles(({ css }) => {
return {
@@ -26,31 +24,28 @@ const styles = createStaticStyles(({ css }) => {
});
const UserPanel = memo<PropsWithChildren>(({ children }) => {
- const hasNewVersion = useNewVersion();
const [open, setOpen] = useState(false);
return (
<Suspense fallback={children}>
- <UpgradeBadge showBadge={hasNewVersion}>
- <Popover
- arrow={false}
- open={open}
- placement="topLeft"
- trigger="click"
- classNames={{
- root: styles.popover,
- content: styles.popoverContent,
- }}
- content={
- <Suspense fallback={<PanelContentSkeleton />}>
- <PanelContent closePopover={() => setOpen(false)} />
- </Suspense>
- }
- onOpenChange={setOpen}
- >
- {children}
- </Popover>
- </UpgradeBadge>
+ <Popover
+ arrow={false}
+ open={open}
+ placement="topLeft"
+ trigger="click"
+ classNames={{
+ root: styles.popover,
+ content: styles.popoverContent,
+ }}
+ content={
+ <Suspense fallback={<PanelContentSkeleton />}>
+ <PanelContent closePopover={() => setOpen(false)} />
+ </Suspense>
+ }
+ onOpenChange={setOpen}
+ >
+ {children}
+ </Popover>
</Suspense>
);
});
diff --git a/src/features/User/UserPanel/useMenu.tsx b/src/features/User/UserPanel/useMenu.tsx
index d39ffc821ac..cfb11fb0381 100644
--- a/src/features/User/UserPanel/useMenu.tsx
+++ b/src/features/User/UserPanel/useMenu.tsx
@@ -1,105 +1,61 @@
import { LOBE_CHAT_CLOUD, UTM_SOURCE } from '@lobechat/business-const';
-import { DOWNLOAD_URL, isDesktop } from '@lobechat/const';
-import { Flexbox, Hotkey, Icon, Tag } from '@lobehub/ui';
+import { isDesktop } from '@lobechat/const';
+import { Hotkey, Icon } from '@lobehub/ui';
import { type ItemType } from 'antd/es/menu/interface';
-import { BrainCircuit, Cloudy, Download, HardDriveDownload, LogOut, Settings2 } from 'lucide-react';
-import { type PropsWithChildren } from 'react';
-import { memo, useMemo } from 'react';
+import { BrainCircuit, Cloudy, HardDriveDownload, Settings2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import useBusinessMenuItems from '@/business/client/features/User/useBusinessMenuItems';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { type MenuProps } from '@/components/Menu';
import { DEFAULT_DESKTOP_HOTKEY_CONFIG } from '@/const/desktop';
import { OFFICIAL_URL } from '@/const/url';
import DataImporter from '@/features/DataImporter';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useNavLayout } from '@/hooks/useNavLayout';
-import { usePlatform } from '@/hooks/usePlatform';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-import { useNewVersion } from './useNewVersion';
-
-const NewVersionBadge = memo(
- ({
- children,
- showBadge,
- onClick,
- }: PropsWithChildren & { onClick?: () => void; showBadge?: boolean }) => {
- const { t } = useTranslation('common');
- if (!showBadge)
- return (
- <Flexbox flex={1} onClick={onClick}>
- {children}
- </Flexbox>
- );
- return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} width={'100%'} onClick={onClick}>
- {children}
- <Tag color={'info'} size={'small'} style={{ borderRadius: 16, paddingInline: 8 }}>
- {t('upgradeVersion.hasNew')}
- </Tag>
- </Flexbox>
- );
- },
-);
-
export const useMenu = () => {
- const hasNewVersion = useNewVersion();
- const { t } = useTranslation(['common', 'setting', 'auth']);
+ const { t } = useTranslation(['common', 'setting']);
const { showCloudPromotion, hideDocs } = useServerConfigStore(featureFlagsSelectors);
- const [isLogin, isLoginWithAuth] = useUserStore((s) => [
- authSelectors.isLogin(s),
- authSelectors.isLoginWithAuth(s),
- ]);
+ const isLogin = useUserStore(authSelectors.isLogin);
const { userPanel } = useNavLayout();
const businessMenuItems = useBusinessMenuItems(isLogin);
- const { isIOS, isAndroid } = usePlatform();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const downloadUrl = useMemo(() => {
- if (isIOS) return DOWNLOAD_URL.ios;
- if (isAndroid) return DOWNLOAD_URL.android;
- return DOWNLOAD_URL.default;
- }, [isIOS, isAndroid]);
+ // In workspace context, route Settings to the workspace's settings root —
+ // the route's index redirect (`/:slug/settings → /:slug/settings/general`)
+ // handles tab landing, keeping this hook URL-agnostic. Personal context
+ // falls back to user settings.
+ const settingsHref = activeWorkspaceSlug ? `/${activeWorkspaceSlug}/settings` : '/settings';
- const settings: MenuProps['items'] = [
- {
- extra: isDesktop ? (
- <div>
- <Hotkey keys={DEFAULT_DESKTOP_HOTKEY_CONFIG.openSettings} />
- </div>
- ) : undefined,
- icon: <Icon icon={Settings2} />,
- key: 'setting',
- label: (
- <Link to="/settings">
- <NewVersionBadge showBadge={hasNewVersion}>{t('userPanel.setting')}</NewVersionBadge>
- </Link>
- ),
- },
- ...(userPanel.showMemory
- ? [
- {
- icon: <Icon icon={BrainCircuit} />,
- key: 'memory',
- label: <Link to="/memory">{t('tab.memory')}</Link>,
- },
- ]
- : []),
- ];
+ const settings: MenuProps['items'] = isLogin
+ ? [
+ {
+ extra: isDesktop ? (
+ <div>
+ <Hotkey keys={DEFAULT_DESKTOP_HOTKEY_CONFIG.openSettings} />
+ </div>
+ ) : undefined,
+ icon: <Icon icon={Settings2} />,
+ key: 'setting',
+ label: <Link to={settingsHref}>{t('userPanel.setting')}</Link>,
+ },
+ ]
+ : [];
- const getDesktopApp: MenuProps['items'] = [
- {
- icon: <Icon icon={Download} />,
- key: 'get-desktop-app',
- label: (
- <a href={downloadUrl} rel="noopener noreferrer" target="_blank">
- {t('getDesktopApp')}
- </a>
- ),
- },
- ];
+ const memoryItems: MenuProps['items'] = userPanel.showMemory
+ ? [
+ {
+ icon: <Icon icon={BrainCircuit} />,
+ key: 'memory',
+ label: <WorkspaceLink to="/memory">{t('tab.memory')}</WorkspaceLink>,
+ },
+ ]
+ : [];
const helps: MenuProps['items'] = [
showCloudPromotion && {
@@ -121,10 +77,9 @@ export const useMenu = () => {
{
type: 'divider',
},
-
- ...(isLogin ? settings : []),
+ ...settings,
+ ...memoryItems,
...businessMenuItems,
- ...(!isDesktop ? [{ type: 'divider' as const }, ...getDesktopApp] : []),
...(userPanel.showDataImporter && isLogin
? [
{
@@ -147,18 +102,5 @@ export const useMenu = () => {
return !(isDivider(item) && isDivider(arr[index - 1]));
}) as MenuProps['items'];
- const logoutItems: MenuProps['items'] = isLoginWithAuth
- ? [
- {
- icon: <Icon icon={LogOut} />,
- key: 'logout',
- label: <span>{t('signout', { ns: 'auth' })}</span>,
- },
- {
- type: 'divider',
- },
- ]
- : [];
-
- return { logoutItems, mainItems };
+ return { mainItems };
};
diff --git a/src/features/User/__tests__/PanelContent.test.tsx b/src/features/User/__tests__/PanelContent.test.tsx
index e04b1999424..42584ac8d06 100644
--- a/src/features/User/__tests__/PanelContent.test.tsx
+++ b/src/features/User/__tests__/PanelContent.test.tsx
@@ -38,7 +38,6 @@ vi.mock('../UserInfo', () => ({
vi.mock('../UserPanel/useMenu', () => ({
useMenu: vi.fn(() => ({
- logoutItems: [{ key: 'logout', label: 'Logout' }],
mainItems: [
{ key: 'item1', label: 'Main Item 1' },
{ key: 'item2', label: 'Main Item 2' },
@@ -103,14 +102,14 @@ describe('PanelContent', () => {
expect(screen.queryByText('Mocked UserInfo')).not.toBeInTheDocument();
});
- it('should render logout items when user is signed in', () => {
+ it('should render the main menu when user is signed in', () => {
act(() => {
useUserStore.setState({ isSignedIn: true });
});
renderWithRouter(<PanelContent closePopover={closePopover} />);
- expect(screen.getAllByText('Mocked Menu').length).toBe(2);
+ expect(screen.getAllByText('Mocked Menu').length).toBe(1);
});
it('should render SignInBlock when user is not signed in', () => {
diff --git a/src/features/User/__tests__/useMenu.test.tsx b/src/features/User/__tests__/useMenu.test.tsx
index 114d4748cf3..f1a559e8441 100644
--- a/src/features/User/__tests__/useMenu.test.tsx
+++ b/src/features/User/__tests__/useMenu.test.tsx
@@ -40,12 +40,8 @@ vi.mock('@/services/config', () => ({
},
}));
-vi.mock('./useNewVersion', () => ({
- useNewVersion: vi.fn(() => false),
-}));
-
describe('useMenu', () => {
- it('should provide correct menu items when user is logged in with auth', () => {
+ it('should keep workspace-aware Settings and drop Account-Panel-only items', () => {
act(() => {
useUserStore.setState({ isSignedIn: true });
});
@@ -53,16 +49,18 @@ describe('useMenu', () => {
const { result } = renderHook(() => useMenu(), { wrapper });
act(() => {
- const { mainItems, logoutItems } = result.current;
- // 'setting' and 'memory' are shown when logged in
+ const { mainItems } = result.current;
+ // Settings stays in the Workspace Panel so workspace-context Settings
+ // is reachable in one click.
expect(mainItems?.some((item) => item?.key === 'setting')).toBe(true);
- expect(mainItems?.some((item) => item?.key === 'memory')).toBe(true);
- // 'logout' is shown when isLoginWithAuth is true
- expect(logoutItems.some((item) => item?.key === 'logout')).toBe(true);
+ // Account-only items have moved to the Account Panel and must not
+ // appear in the Workspace Panel menu.
+ expect(mainItems?.some((item) => item?.key === 'get-desktop-app')).toBe(false);
+ expect(mainItems?.some((item) => item?.key === 'logout')).toBe(false);
});
});
- it('should provide correct menu items when user is not logged in', () => {
+ it('should hide Settings when not logged in', () => {
act(() => {
useUserStore.setState({ isSignedIn: false });
});
@@ -70,11 +68,8 @@ describe('useMenu', () => {
const { result } = renderHook(() => useMenu(), { wrapper });
act(() => {
- const { mainItems, logoutItems } = result.current;
- // When not logged in, setting and memory should not be shown
+ const { mainItems } = result.current;
expect(mainItems?.some((item) => item?.key === 'setting')).toBe(false);
- expect(mainItems?.some((item) => item?.key === 'memory')).toBe(false);
- expect(logoutItems.some((item) => item?.key === 'logout')).toBe(false);
});
});
diff --git a/src/features/Workspace/WorkspaceLink.tsx b/src/features/Workspace/WorkspaceLink.tsx
new file mode 100644
index 00000000000..eda81a11f9a
--- /dev/null
+++ b/src/features/Workspace/WorkspaceLink.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { type AnchorHTMLAttributes, type Ref } from 'react';
+import { Link, type LinkProps } from 'react-router-dom';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+
+import { buildWorkspaceAwarePath } from './workspaceAwarePath';
+
+export interface WorkspaceLinkProps extends Omit<LinkProps, 'to' | 'ref'> {
+ /** When true, do not apply the workspace prefix. */
+ escape?: boolean;
+ /**
+ * Widened to `HTMLElement` so existing sidebar callsites passing a
+ * `useState<HTMLElement | null>` setter work without changes.
+ */
+ ref?: Ref<HTMLElement>;
+ /** Same semantics as `<Link to>` but auto-prefixed with the active workspace slug. */
+ to: string;
+}
+
+const WorkspaceLink = ({ ref, to, escape, ...rest }: WorkspaceLinkProps) => {
+ const activeSlug = useActiveWorkspaceSlug();
+ const target = buildWorkspaceAwarePath(to, activeSlug, { escape });
+ return (
+ <Link
+ ref={ref as Ref<HTMLAnchorElement>}
+ to={target}
+ {...(rest as AnchorHTMLAttributes<HTMLAnchorElement>)}
+ />
+ );
+};
+
+WorkspaceLink.displayName = 'WorkspaceLink';
+
+export default WorkspaceLink;
diff --git a/src/features/Workspace/WorkspaceSlugBoundary.tsx b/src/features/Workspace/WorkspaceSlugBoundary.tsx
new file mode 100644
index 00000000000..b8865202191
--- /dev/null
+++ b/src/features/Workspace/WorkspaceSlugBoundary.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Button, Center } from '@lobehub/ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Outlet, useNavigate } from 'react-router-dom';
+
+import { useWorkspaceFromSlug } from './useWorkspaceFromSlug';
+
+/**
+ * Layout boundary for the `/:workspaceSlug` subtree.
+ *
+ * - Calls `useWorkspaceFromSlug` to resolve the slug → status.
+ * - Renders a 404-style empty state when the slug doesn't match any workspace.
+ * - Renders `<Outlet />` when the workspace is found (or still loading).
+ */
+const WorkspaceSlugBoundary: FC = () => {
+ const { t } = useTranslation('error');
+ const navigate = useNavigate();
+ const result = useWorkspaceFromSlug();
+
+ // Workspaces are still being fetched — render nothing so the parent layout
+ // spinner shows through instead of flashing a false 404.
+ if (result.status === 'loading') return null;
+
+ if (result.status === 'not-found') {
+ return (
+ <Center gap={16} height={'100%'} style={{ flexDirection: 'column' }} width={'100%'}>
+ <div style={{ fontSize: 48 }}>🔍</div>
+ <div style={{ fontWeight: 600, fontSize: 20 }}>{t('notFound.title')}</div>
+ <div style={{ opacity: 0.6 }}>{t('notFound.check')}</div>
+ <Button onClick={() => navigate('/')}>{t('notFound.backHome')}</Button>
+ </Center>
+ );
+ }
+
+ return <Outlet />;
+};
+
+export default WorkspaceSlugBoundary;
diff --git a/src/features/Workspace/__tests__/stableWorkspaceAwareNavigate.test.ts b/src/features/Workspace/__tests__/stableWorkspaceAwareNavigate.test.ts
new file mode 100644
index 00000000000..e1ba74c9579
--- /dev/null
+++ b/src/features/Workspace/__tests__/stableWorkspaceAwareNavigate.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as activeWorkspaceSlugModule from '@/business/client/hooks/useActiveWorkspaceSlug';
+import * as stableNavigateModule from '@/utils/stableNavigate';
+
+import { stableWorkspaceAwareNavigate } from '../stableWorkspaceAwareNavigate';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('stableWorkspaceAwareNavigate', () => {
+ it('prefixes the path with the active workspace slug', () => {
+ const navigate = vi.fn();
+ vi.spyOn(stableNavigateModule, 'getStableNavigate').mockReturnValue(navigate);
+ vi.spyOn(activeWorkspaceSlugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');
+
+ stableWorkspaceAwareNavigate('/group/group-1');
+
+ expect(navigate).toHaveBeenCalledWith('/acme/group/group-1');
+ });
+
+ it('leaves the path unchanged in personal mode (no active workspace)', () => {
+ const navigate = vi.fn();
+ vi.spyOn(stableNavigateModule, 'getStableNavigate').mockReturnValue(navigate);
+ // default mock: activeWorkspace() === null
+
+ stableWorkspaceAwareNavigate('/group/group-1');
+
+ expect(navigate).toHaveBeenCalledWith('/group/group-1');
+ });
+
+ it('bypasses prefixing when escape is set', () => {
+ const navigate = vi.fn();
+ vi.spyOn(stableNavigateModule, 'getStableNavigate').mockReturnValue(navigate);
+ vi.spyOn(activeWorkspaceSlugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');
+
+ stableWorkspaceAwareNavigate('/group/group-1', { escape: true });
+
+ expect(navigate).toHaveBeenCalledWith('/group/group-1');
+ });
+
+ it('no-ops when the navigate ref is not yet registered', () => {
+ vi.spyOn(stableNavigateModule, 'getStableNavigate').mockReturnValue(null);
+ const getActiveWorkspaceSlug = vi.spyOn(activeWorkspaceSlugModule, 'getActiveWorkspaceSlug');
+
+ expect(() => stableWorkspaceAwareNavigate('/group/group-1')).not.toThrow();
+ expect(getActiveWorkspaceSlug).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
new file mode 100644
index 00000000000..3cc5116b257
--- /dev/null
+++ b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildWorkspaceAwarePath } from '../workspaceAwarePath';
+
+describe('buildWorkspaceAwarePath', () => {
+ it('returns the path unchanged when no active workspace slug exists', () => {
+ expect(buildWorkspaceAwarePath('/memory', null)).toBe('/memory');
+ expect(buildWorkspaceAwarePath('/memory', undefined)).toBe('/memory');
+ });
+
+ it('prefixes absolute paths with the active workspace slug', () => {
+ expect(buildWorkspaceAwarePath('/memory', 'acme')).toBe('/acme/memory');
+ expect(buildWorkspaceAwarePath('/agent/inbox', 'acme')).toBe('/acme/agent/inbox');
+ expect(buildWorkspaceAwarePath('/community/agent/jailbreak', 'acme')).toBe(
+ '/acme/community/agent/jailbreak',
+ );
+ expect(buildWorkspaceAwarePath('/group/group-1', 'acme')).toBe('/acme/group/group-1');
+ });
+
+ it('bypasses the prefix when `escape` is true', () => {
+ expect(buildWorkspaceAwarePath('/settings/profile', 'acme', { escape: true })).toBe(
+ '/settings/profile',
+ );
+ expect(buildWorkspaceAwarePath('/settings/plans', 'acme', { escape: true })).toBe(
+ '/settings/plans',
+ );
+ });
+
+ it('does not double-prefix when the path is already under the active slug', () => {
+ expect(buildWorkspaceAwarePath('/acme', 'acme')).toBe('/acme');
+ expect(buildWorkspaceAwarePath('/acme/memory', 'acme')).toBe('/acme/memory');
+ });
+
+ it('leaves relative paths alone (router resolves them)', () => {
+ expect(buildWorkspaceAwarePath('memory', 'acme')).toBe('memory');
+ expect(buildWorkspaceAwarePath('../tasks', 'acme')).toBe('../tasks');
+ });
+
+ it('skips prefix for personal-only top-level paths', () => {
+ expect(buildWorkspaceAwarePath('/onboarding/agent', 'acme')).toBe('/onboarding/agent');
+ expect(buildWorkspaceAwarePath('/me/profile', 'acme')).toBe('/me/profile');
+ expect(buildWorkspaceAwarePath('/share/t/foo', 'acme')).toBe('/share/t/foo');
+ expect(buildWorkspaceAwarePath('/devtools', 'acme')).toBe('/devtools');
+ });
+
+ it('prefixes settings sub-paths that have a workspace mirror', () => {
+ expect(buildWorkspaceAwarePath('/settings/general', 'acme')).toBe('/acme/settings/general');
+ expect(buildWorkspaceAwarePath('/settings/members', 'acme')).toBe('/acme/settings/members');
+ expect(buildWorkspaceAwarePath('/settings/plans', 'acme')).toBe('/acme/settings/plans');
+ expect(buildWorkspaceAwarePath('/settings/billing', 'acme')).toBe('/acme/settings/billing');
+ expect(buildWorkspaceAwarePath('/settings/credits', 'acme')).toBe('/acme/settings/credits');
+ expect(buildWorkspaceAwarePath('/settings/usage', 'acme')).toBe('/acme/settings/usage');
+ expect(buildWorkspaceAwarePath('/settings/skill', 'acme')).toBe('/acme/settings/skill');
+ expect(buildWorkspaceAwarePath('/settings/messenger', 'acme')).toBe('/acme/settings/messenger');
+ expect(buildWorkspaceAwarePath('/settings/creds', 'acme')).toBe('/acme/settings/creds');
+ expect(buildWorkspaceAwarePath('/settings/provider/openai', 'acme')).toBe(
+ '/acme/settings/provider/openai',
+ );
+ });
+
+ it('skips prefix for personal-only settings sub-paths', () => {
+ expect(buildWorkspaceAwarePath('/settings/profile', 'acme')).toBe('/settings/profile');
+ expect(buildWorkspaceAwarePath('/settings/llm', 'acme')).toBe('/settings/llm');
+ expect(buildWorkspaceAwarePath('/settings/memory', 'acme')).toBe('/settings/memory');
+ expect(buildWorkspaceAwarePath('/settings/referral', 'acme')).toBe('/settings/referral');
+ expect(buildWorkspaceAwarePath('/settings/system-tools', 'acme')).toBe(
+ '/settings/system-tools',
+ );
+ });
+
+ it('prefixes the `/settings` index — both personal and workspace have a meaningful redirect', () => {
+ expect(buildWorkspaceAwarePath('/settings', 'acme')).toBe('/acme/settings');
+ expect(buildWorkspaceAwarePath('/settings/', 'acme')).toBe('/acme/settings/');
+ expect(buildWorkspaceAwarePath('/settings?foo=bar', 'acme')).toBe('/acme/settings?foo=bar');
+ });
+});
diff --git a/src/features/Workspace/__tests__/workspaceSlugHooks.test.tsx b/src/features/Workspace/__tests__/workspaceSlugHooks.test.tsx
new file mode 100644
index 00000000000..92fdef2b45f
--- /dev/null
+++ b/src/features/Workspace/__tests__/workspaceSlugHooks.test.tsx
@@ -0,0 +1,149 @@
+import { renderHook } from '@testing-library/react';
+import { type ReactNode } from 'react';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as useActiveWorkspaceIdModule from '@/business/client/hooks/useActiveWorkspaceId';
+import * as useIsWorkspaceLoadingModule from '@/business/client/hooks/useIsWorkspaceLoading';
+import * as useSwitchWorkspaceModule from '@/business/client/hooks/useSwitchWorkspace';
+import * as useWorkspacesModule from '@/business/client/hooks/useWorkspaces';
+
+import { useWorkspaceFromSlug } from '../useWorkspaceFromSlug';
+import { useWorkspaceUrlSync } from '../useWorkspaceUrlSync';
+
+interface WorkspaceStateMock {
+ activeWorkspaceId: null | string;
+ isWorkspaceLoading: boolean;
+ switchToPersonal: () => void;
+ switchWorkspace: (id: string) => void;
+ workspaces: { id: string; slug: string }[];
+}
+
+const createState = (overrides: Partial<WorkspaceStateMock> = {}): WorkspaceStateMock => ({
+ activeWorkspaceId: null,
+ isWorkspaceLoading: false,
+ switchToPersonal: vi.fn(),
+ switchWorkspace: vi.fn(),
+ workspaces: [{ id: 'ws-1', slug: 'acme' }],
+ ...overrides,
+});
+
+const mockWorkspaceStore = (state: WorkspaceStateMock) => {
+ vi.spyOn(useWorkspacesModule, 'useWorkspaces').mockReturnValue(state.workspaces as any);
+ vi.spyOn(useIsWorkspaceLoadingModule, 'useIsWorkspaceLoading').mockReturnValue(
+ state.isWorkspaceLoading,
+ );
+ vi.spyOn(useActiveWorkspaceIdModule, 'useActiveWorkspaceId').mockReturnValue(
+ state.activeWorkspaceId,
+ );
+ vi.spyOn(useSwitchWorkspaceModule, 'useSwitchWorkspace').mockReturnValue({
+ switchToPersonal: state.switchToPersonal as any,
+ switchWorkspace: state.switchWorkspace as any,
+ });
+};
+
+const createRouteWrapper =
+ (initialEntry: string, path = '/:workspaceSlug/*') =>
+ ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={[initialEntry]}>
+ <Routes>
+ <Route element={children} path={path} />
+ </Routes>
+ </MemoryRouter>
+ );
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('useWorkspaceFromSlug', () => {
+ it('returns ok when the URL slug matches a workspace', () => {
+ mockWorkspaceStore(createState());
+
+ const { result } = renderHook(() => useWorkspaceFromSlug(), {
+ wrapper: createRouteWrapper('/acme/settings'),
+ });
+
+ expect(result.current).toEqual({ slug: 'acme', status: 'ok', workspaceId: 'ws-1' });
+ });
+
+ it('returns loading for an unknown slug while workspaces are loading', () => {
+ mockWorkspaceStore(createState({ isWorkspaceLoading: true, workspaces: [] }));
+
+ const { result } = renderHook(() => useWorkspaceFromSlug(), {
+ wrapper: createRouteWrapper('/acme/settings'),
+ });
+
+ expect(result.current).toEqual({ slug: 'acme', status: 'loading' });
+ });
+
+ it('returns not-found for an unknown slug after loading completes', () => {
+ mockWorkspaceStore(createState({ workspaces: [] }));
+
+ const { result } = renderHook(() => useWorkspaceFromSlug(), {
+ wrapper: createRouteWrapper('/missing/settings'),
+ });
+
+ expect(result.current).toEqual({ slug: 'missing', status: 'not-found' });
+ });
+
+ it('returns no-slug outside the workspace route tree', () => {
+ mockWorkspaceStore(createState());
+
+ const { result } = renderHook(() => useWorkspaceFromSlug(), {
+ wrapper: createRouteWrapper('/settings/profile', '/settings/*'),
+ });
+
+ expect(result.current).toEqual({ status: 'no-slug' });
+ });
+});
+
+describe('useWorkspaceUrlSync', () => {
+ it('switches to the workspace when the first segment is a known slug', () => {
+ const state = createState();
+ mockWorkspaceStore(state);
+
+ renderHook(() => useWorkspaceUrlSync(), {
+ wrapper: createRouteWrapper('/acme/agent/inbox', '*'),
+ });
+
+ expect(state.switchWorkspace).toHaveBeenCalledWith('ws-1');
+ expect(state.switchToPersonal).not.toHaveBeenCalled();
+ });
+
+ it('does not switch while the workspace list is loading', () => {
+ const state = createState({ isWorkspaceLoading: true });
+ mockWorkspaceStore(state);
+
+ renderHook(() => useWorkspaceUrlSync(), {
+ wrapper: createRouteWrapper('/acme/agent/inbox', '*'),
+ });
+
+ expect(state.switchWorkspace).not.toHaveBeenCalled();
+ expect(state.switchToPersonal).not.toHaveBeenCalled();
+ });
+
+ it('leaves the current workspace untouched for an unknown slug', () => {
+ const state = createState({ activeWorkspaceId: 'ws-1' });
+ mockWorkspaceStore(state);
+
+ renderHook(() => useWorkspaceUrlSync(), {
+ wrapper: createRouteWrapper('/unknown/agent/inbox', '*'),
+ });
+
+ expect(state.switchWorkspace).not.toHaveBeenCalled();
+ expect(state.switchToPersonal).not.toHaveBeenCalled();
+ });
+
+ it('switches to personal mode on reserved personal routes', () => {
+ const state = createState({ activeWorkspaceId: 'ws-1' });
+ mockWorkspaceStore(state);
+
+ renderHook(() => useWorkspaceUrlSync(), {
+ wrapper: createRouteWrapper('/settings/profile', '*'),
+ });
+
+ expect(state.switchToPersonal).toHaveBeenCalled();
+ expect(state.switchWorkspace).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Workspace/stableWorkspaceAwareNavigate.ts b/src/features/Workspace/stableWorkspaceAwareNavigate.ts
new file mode 100644
index 00000000000..c37250f2869
--- /dev/null
+++ b/src/features/Workspace/stableWorkspaceAwareNavigate.ts
@@ -0,0 +1,30 @@
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { getStableNavigate } from '@/utils/stableNavigate';
+
+import { buildWorkspaceAwarePath, type WorkspaceAwareNavigateOptions } from './workspaceAwarePath';
+
+/**
+ * Non-React counterpart of {@link useWorkspaceAwareNavigate}. Reads the active
+ * workspace slug imperatively from the store and prefixes absolute path strings
+ * before forwarding to the stable navigate ref. Use from store actions and other
+ * non-component call sites where hooks are unavailable — otherwise creating an
+ * entity inside a workspace navigates to the personal (unprefixed) route.
+ *
+ * Pass `{ escape: true }` to bypass prefixing for personal-only destinations.
+ */
+export const stableWorkspaceAwareNavigate = (
+ to: string,
+ options?: WorkspaceAwareNavigateOptions,
+): void => {
+ const navigate = getStableNavigate();
+ if (!navigate) return;
+
+ const activeSlug = getActiveWorkspaceSlug();
+ const target = buildWorkspaceAwarePath(to, activeSlug, options);
+
+ const { escape: _escape, ...rest } = options ?? {};
+ void _escape;
+ // Transparent drop-in: only forward a second arg when real options remain.
+ if (Object.keys(rest).length > 0) navigate(target, rest);
+ else navigate(target);
+};
diff --git a/src/features/Workspace/useWorkspaceAwareNavigate.ts b/src/features/Workspace/useWorkspaceAwareNavigate.ts
new file mode 100644
index 00000000000..8d29c04cd4f
--- /dev/null
+++ b/src/features/Workspace/useWorkspaceAwareNavigate.ts
@@ -0,0 +1,56 @@
+'use client';
+
+import { useCallback } from 'react';
+import {
+ type NavigateFunction,
+ type NavigateOptions,
+ type To,
+ useNavigate,
+} from 'react-router-dom';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+
+import { buildWorkspaceAwarePath, type WorkspaceAwareNavigateOptions } from './workspaceAwarePath';
+
+export type { WorkspaceAwareNavigateOptions } from './workspaceAwarePath';
+
+/**
+ * `useNavigate` from react-router-dom, extended with an `escape` option for
+ * skipping workspace-prefix logic on personal-only destinations.
+ */
+export interface WorkspaceAwareNavigateFunction extends NavigateFunction {
+ (to: To, options?: WorkspaceAwareNavigateOptions): void;
+ (delta: number): void;
+}
+
+/**
+ * Drop-in replacement for `useNavigate` that auto-prefixes absolute path
+ * strings with the active workspace slug. Numeric deltas (`navigate(-1)`),
+ * `Partial<Path>` objects, and relative path strings pass through unchanged.
+ *
+ * Pass `{ escape: true }` to bypass prefixing for personal-only destinations.
+ */
+export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {
+ const navigate = useNavigate();
+ const activeSlug = useActiveWorkspaceSlug();
+
+ return useCallback(
+ ((to: To | number, options?: WorkspaceAwareNavigateOptions) => {
+ if (typeof to === 'number') {
+ return navigate(to);
+ }
+ if (typeof to !== 'string') {
+ // `Partial<Path>` object — pass through unchanged.
+ return navigate(to, options as NavigateOptions | undefined);
+ }
+ const target = buildWorkspaceAwarePath(to, activeSlug, options);
+ const { escape: _escape, ...rest } = options ?? {};
+ void _escape;
+ // Stay a transparent drop-in for `useNavigate`: only forward a second arg
+ // when real react-router options remain, so `navigate(path)` calls don't
+ // turn into `navigate(path, {})`.
+ return Object.keys(rest).length > 0 ? navigate(target, rest) : navigate(target);
+ }) as WorkspaceAwareNavigateFunction,
+ [navigate, activeSlug],
+ );
+};
diff --git a/src/features/Workspace/useWorkspaceFromSlug.ts b/src/features/Workspace/useWorkspaceFromSlug.ts
new file mode 100644
index 00000000000..9010a5ca2ff
--- /dev/null
+++ b/src/features/Workspace/useWorkspaceFromSlug.ts
@@ -0,0 +1,33 @@
+'use client';
+
+import { useParams } from 'react-router-dom';
+
+import { useIsWorkspaceLoading } from '@/business/client/hooks/useIsWorkspaceLoading';
+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';
+
+export type WorkspaceSlugStatus =
+ | { status: 'no-slug' }
+ | { status: 'loading'; slug: string }
+ | { status: 'not-found'; slug: string }
+ | { status: 'ok'; workspaceId: string; slug: string };
+
+/**
+ * Reads the `:workspaceSlug` URL param and resolves it to a status used by
+ * `WorkspaceSlugBoundary` for the 404 screen.
+ *
+ * Store synchronisation (URL → activeWorkspaceId) lives in
+ * `useWorkspaceUrlSync`, which is mounted globally — this hook is purely
+ * read-side.
+ */
+export const useWorkspaceFromSlug = (): WorkspaceSlugStatus => {
+ const { workspaceSlug } = useParams<{ workspaceSlug: string }>();
+ const workspaces = useWorkspaces();
+ const isLoading = useIsWorkspaceLoading();
+
+ const matched = workspaceSlug ? (workspaces.find((w) => w.slug === workspaceSlug) ?? null) : null;
+
+ if (!workspaceSlug) return { status: 'no-slug' };
+ if (matched) return { status: 'ok', workspaceId: matched.id, slug: workspaceSlug };
+ if (isLoading) return { status: 'loading', slug: workspaceSlug };
+ return { status: 'not-found', slug: workspaceSlug };
+};
diff --git a/src/features/Workspace/useWorkspaceUrlSync.ts b/src/features/Workspace/useWorkspaceUrlSync.ts
new file mode 100644
index 00000000000..59c622ee539
--- /dev/null
+++ b/src/features/Workspace/useWorkspaceUrlSync.ts
@@ -0,0 +1,90 @@
+'use client';
+
+import { useLayoutEffect } from 'react';
+import { useLocation } from 'react-router-dom';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useIsWorkspaceLoading } from '@/business/client/hooks/useIsWorkspaceLoading';
+import { useSwitchWorkspace } from '@/business/client/hooks/useSwitchWorkspace';
+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';
+
+/**
+ * Top-level route segments that share the namespace with `:workspaceSlug`.
+ * Anything starting with one of these is NOT a workspace slug — even if the
+ * first segment happens to resemble one.
+ *
+ * Kept in sync with `sharedMainAreaChildren` (paths) + the personal-only list
+ * in router configs. If you add a new root path segment, add it here too.
+ */
+const RESERVED_FIRST_SEGMENTS = new Set([
+ // Shared (mirrored under /:workspaceSlug too):
+ 'agent',
+ 'group',
+ 'community',
+ 'memory',
+ 'page',
+ 'resource',
+ 'image',
+ 'video',
+ 'eval',
+ 'tasks',
+ 'task',
+ // Personal-only:
+ 'settings',
+ 'onboarding',
+ 'me',
+ 'share',
+ 'devtools',
+ 'desktop-onboarding',
+]);
+
+const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;
+
+const parseFirstSegment = (pathname: string): string | null => {
+ const match = pathname.match(FIRST_SEGMENT_REGEX);
+ return match ? match[1] : null;
+};
+
+/**
+ * URL is the source of truth for workspace context.
+ *
+ * - `/{slug}/...` where `slug` is a known workspace → activate that workspace
+ * - `/` or `/agent/...` / `/settings/...` etc. (or any non-slug surface) → personal
+ * - `/{unknown}/...` (slug not in workspaces) → leave store alone so
+ * `WorkspaceSlugBoundary` can render its 404
+ */
+export const useWorkspaceUrlSync = (): void => {
+ const { pathname } = useLocation();
+ const workspaces = useWorkspaces();
+ const activeId = useActiveWorkspaceId();
+ const isLoading = useIsWorkspaceLoading();
+ const { switchWorkspace, switchToPersonal } = useSwitchWorkspace();
+
+ // `useLayoutEffect` (not `useEffect`) so the workspace switch is scheduled
+ // before the browser paints. With `useEffect` there is one paintable frame
+ // between `isWorkspaceLoading: false` and `switchWorkspace()` running, which
+ // causes downstream consumers (e.g. `WorkspaceContextSlot`) to briefly see
+ // `isContextReady === true` and unhide stale children before the splash
+ // re-asserts itself.
+ useLayoutEffect(() => {
+ // Defer until the workspace list has loaded so we don't briefly flip the
+ // store to "personal" on first paint of a `/{slug}` URL.
+ if (isLoading) return;
+
+ const first = parseFirstSegment(pathname);
+
+ if (first && !RESERVED_FIRST_SEGMENTS.has(first)) {
+ const ws = workspaces.find((w) => w.slug === first);
+ if (ws) {
+ if (activeId !== ws.id) void switchWorkspace(ws.id);
+ return;
+ }
+ // Unknown slug — let `WorkspaceSlugBoundary` show 404; don't touch the
+ // active workspace.
+ return;
+ }
+
+ // URL has no workspace slug → personal context.
+ if (activeId !== null) void switchToPersonal();
+ }, [pathname, workspaces, isLoading, activeId, switchWorkspace, switchToPersonal]);
+};
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
new file mode 100644
index 00000000000..421d51d72fe
--- /dev/null
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -0,0 +1,85 @@
+import type { NavigateOptions } from 'react-router-dom';
+
+export interface WorkspaceAwareNavigateOptions extends NavigateOptions {
+ /** When true, navigate to the literal `to` path without applying the workspace prefix. */
+ escape?: boolean;
+}
+
+/**
+ * Top-level path segments that are never mirrored under `/:workspaceSlug`.
+ *
+ * Kept in sync with `sharedMainAreaChildren` in the router configs and with
+ * the `PERSONAL_PATH_REGEX` in `scripts/codemodWorkspaceNav.ts`. If you add
+ * a new top-level personal-only route, append it here.
+ *
+ * `/settings` is handled separately via {@link WORKSPACE_SETTINGS_TABS} —
+ * sub-paths in the allowlist get auto-prefixed; everything else (profile,
+ * llm, referral, system-tools, etc.) stays personal.
+ */
+const PERSONAL_PATH_REGEX = /^\/(?:onboarding|me|share|devtools|desktop-onboarding)(?:[/?#]|$)/;
+
+const isPersonalPath = (to: string): boolean => PERSONAL_PATH_REGEX.test(to);
+
+/**
+ * Settings sub-paths that have a `/:workspaceSlug/settings/<tab>` mirror in
+ * the SPA routers. Kept in sync with the workspace settings subtree in
+ * `src/spa/router/{desktopRouter.config,desktopRouter.config.desktop,mobileRouter.config}.tsx`
+ * and with `SHARED_SETTINGS_TABS` in `scripts/codemodWorkspaceNav.ts`.
+ *
+ * Tabs absent from this set (profile, llm, referral, system-tools, security,
+ * sync, plugin, tts, hotkey, agent, about, common, system-agent, ...) are
+ * personal-only and never prefixed.
+ */
+export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set([
+ 'apikey',
+ 'billing',
+ 'creds',
+ 'credits',
+ 'general',
+ 'members',
+ 'messenger',
+ 'plans',
+ 'provider',
+ 'service-model',
+ 'skill',
+ 'stats',
+ 'usage',
+]);
+
+const SETTINGS_PREFIX_REGEX = /^\/settings\/([^/?#]+)/;
+
+/**
+ * Returns `true` for `/settings/<tab>` where `<tab>` is NOT in
+ * {@link WORKSPACE_SETTINGS_TABS} (profile, llm, referral, system-tools, …).
+ * `/settings` index (or with query/hash) gets prefixed too — workspace
+ * `/${slug}/settings` redirects to `/${slug}/settings/general`, personal
+ * `/settings` redirects to `/settings/profile`.
+ */
+const isPersonalSettingsPath = (to: string): boolean => {
+ const match = SETTINGS_PREFIX_REGEX.exec(to);
+ if (!match) return false;
+ return !WORKSPACE_SETTINGS_TABS.has(match[1]);
+};
+
+/**
+ * Prefix an absolute path with `/${slug}` unless the path is already prefixed,
+ * the path targets a personal-only surface, `escape` is set, or no active slug
+ * exists. Returns the path unchanged when `to` is a relative path (so
+ * `react-router` can resolve it itself).
+ *
+ * Pure function — extracted so it can be unit-tested without pulling in the
+ * Zustand store / React tree.
+ */
+export const buildWorkspaceAwarePath = (
+ to: string,
+ activeSlug: string | null | undefined,
+ options?: WorkspaceAwareNavigateOptions,
+): string => {
+ if (options?.escape) return to;
+ if (!activeSlug) return to;
+ if (!to.startsWith('/')) return to;
+ if (isPersonalPath(to)) return to;
+ if (isPersonalSettingsPath(to)) return to;
+ if (to === `/${activeSlug}` || to.startsWith(`/${activeSlug}/`)) return to;
+ return `/${activeSlug}${to}`;
+};
diff --git a/src/features/WorkspaceSetting/Container/index.tsx b/src/features/WorkspaceSetting/Container/index.tsx
new file mode 100644
index 00000000000..9c62bee7447
--- /dev/null
+++ b/src/features/WorkspaceSetting/Container/index.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { Flexbox, type FlexboxProps } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo, type PropsWithChildren, type ReactNode } from 'react';
+
+interface WorkspaceSettingsContainerProps extends FlexboxProps {
+ addonAfter?: ReactNode;
+ addonBefore?: ReactNode;
+ maxWidth?: number | string;
+}
+
+const WorkspaceSettingsContainer = memo<PropsWithChildren<WorkspaceSettingsContainerProps>>(
+ ({ maxWidth = 1024, children, addonAfter, addonBefore, style, ...rest }) => {
+ return (
+ <Flexbox
+ align={'center'}
+ height={'100%'}
+ width={'100%'}
+ style={{
+ background: cssVar.colorBgContainer,
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ ...style,
+ }}
+ {...rest}
+ >
+ {addonBefore}
+ <Flexbox flex={1} gap={36} style={{ maxWidth }} width={'100%'}>
+ {children}
+ </Flexbox>
+ {addonAfter}
+ </Flexbox>
+ );
+ },
+);
+
+export default WorkspaceSettingsContainer;
diff --git a/src/features/WorkspaceSetting/Layout.tsx b/src/features/WorkspaceSetting/Layout.tsx
new file mode 100644
index 00000000000..60a81276f38
--- /dev/null
+++ b/src/features/WorkspaceSetting/Layout.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { type FC, memo } from 'react';
+import { Outlet } from 'react-router-dom';
+
+import Container from './Container';
+import SideBar from './SideBar';
+
+/**
+ * Bare workspace settings shell — sidebar + outlet, no content padding.
+ * Use this when a child route owns its own full-bleed layout (e.g. Provider).
+ */
+const WorkspaceSettingsLayout: FC = memo(() => {
+ return (
+ <>
+ <SideBar />
+ <Outlet />
+ </>
+ );
+});
+
+WorkspaceSettingsLayout.displayName = 'WorkspaceSettingsLayout';
+
+/**
+ * Padded content layout — wraps the outlet in a centered, max-width
+ * `WorkspaceSettingsContainer`. Mount this above routes that follow the
+ * standard "header + form" page pattern (general, members, billing, etc.).
+ */
+const WorkspaceSettingsContentLayout: FC = memo(() => {
+ return (
+ <Container maxWidth={1024} paddingBlock={'24px 128px'} paddingInline={24}>
+ <Outlet />
+ </Container>
+ );
+});
+
+WorkspaceSettingsContentLayout.displayName = 'WorkspaceSettingsContentLayout';
+
+export { WorkspaceSettingsContentLayout };
+
+export default WorkspaceSettingsLayout;
diff --git a/src/features/WorkspaceSetting/SideBar/Body.tsx b/src/features/WorkspaceSetting/SideBar/Body.tsx
new file mode 100644
index 00000000000..b0b14761b89
--- /dev/null
+++ b/src/features/WorkspaceSetting/SideBar/Body.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+import { Link, useLocation } from 'react-router-dom';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { DEFAULT_WORKSPACE_SETTINGS_TAB, WorkspaceSettingsTabs } from '@/types/workspaceSettings';
+import { isModifierClick } from '@/utils/navigation';
+
+import { useWorkspaceSettingCategory, WorkspaceSettingsGroupKey } from '../hooks/useCategory';
+
+const Body = memo(() => {
+ const navigate = useWorkspaceAwareNavigate();
+ const location = useLocation();
+ const slug = useActiveWorkspaceSlug();
+ const groups = useWorkspaceSettingCategory();
+
+ const activeTab = useMemo(() => {
+ if (!slug) return DEFAULT_WORKSPACE_SETTINGS_TAB;
+ const parts = location.pathname.split('/').filter(Boolean);
+ const tab = parts[2];
+ return tab && (Object.values(WorkspaceSettingsTabs) as string[]).includes(tab)
+ ? (tab as WorkspaceSettingsTabs)
+ : DEFAULT_WORKSPACE_SETTINGS_TAB;
+ }, [location.pathname, slug]);
+
+ if (!slug) return null;
+
+ return (
+ <Flexbox paddingInline={4}>
+ <Accordion
+ gap={8}
+ defaultExpandedKeys={[
+ WorkspaceSettingsGroupKey.General,
+ WorkspaceSettingsGroupKey.Subscription,
+ WorkspaceSettingsGroupKey.Agent,
+ WorkspaceSettingsGroupKey.Admin,
+ ]}
+ >
+ {groups.map((group) => (
+ <AccordionItem
+ itemKey={group.key}
+ key={group.key}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {group.title}
+ </Text>
+ }
+ >
+ <Flexbox gap={1} paddingBlock={1}>
+ {group.items.map((item) => {
+ const url = `/${slug}/settings/${item.key}`;
+ return (
+ <Link
+ key={item.key}
+ to={url}
+ onClick={(e) => {
+ if (isModifierClick(e)) return;
+ e.preventDefault();
+ navigate(url);
+ }}
+ >
+ <NavItem active={activeTab === item.key} icon={item.icon} title={item.label} />
+ </Link>
+ );
+ })}
+ </Flexbox>
+ </AccordionItem>
+ ))}
+ </Accordion>
+ </Flexbox>
+ );
+});
+
+export default Body;
diff --git a/src/features/WorkspaceSetting/SideBar/Content.tsx b/src/features/WorkspaceSetting/SideBar/Content.tsx
new file mode 100644
index 00000000000..e2d69026eb7
--- /dev/null
+++ b/src/features/WorkspaceSetting/SideBar/Content.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo } from 'react';
+
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Body from './Body';
+import Header from './Header';
+
+const WorkspaceSettingsSideBarContent = memo(() => (
+ <SideBarLayout body={<Body />} header={<Header />} />
+));
+
+WorkspaceSettingsSideBarContent.displayName = 'WorkspaceSettingsSideBarContent';
+
+export default WorkspaceSettingsSideBarContent;
diff --git a/src/features/WorkspaceSetting/SideBar/Header.tsx b/src/features/WorkspaceSetting/SideBar/Header.tsx
new file mode 100644
index 00000000000..2b9fb227865
--- /dev/null
+++ b/src/features/WorkspaceSetting/SideBar/Header.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { HomeIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspace } from '@/business/client/hooks/useActiveWorkspace';
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+const Header = memo(() => {
+ const { t } = useTranslation('setting');
+ const activeWorkspace = useActiveWorkspace();
+ const slug = activeWorkspace?.slug;
+ const name = activeWorkspace?.name ?? slug;
+
+ if (!slug) return null;
+
+ return (
+ <SideBarHeaderLayout
+ breadcrumb={[
+ {
+ href: `/${slug}/settings`,
+ title: t('workspaceSetting.breadcrumb.settings'),
+ },
+ ]}
+ homeItem={{
+ href: `/${slug}`,
+ title: (
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={HomeIcon} size={14} />
+ <span>{name}</span>
+ </Flexbox>
+ ),
+ }}
+ />
+ );
+});
+
+export default Header;
diff --git a/src/features/WorkspaceSetting/SideBar/index.tsx b/src/features/WorkspaceSetting/SideBar/index.tsx
new file mode 100644
index 00000000000..489b70ae603
--- /dev/null
+++ b/src/features/WorkspaceSetting/SideBar/index.tsx
@@ -0,0 +1,17 @@
+'use client';
+
+import { memo } from 'react';
+
+import { NavPanelPortal } from '@/features/NavPanel';
+
+import WorkspaceSettingsSideBarContent from './Content';
+
+const SideBar = memo(() => {
+ return (
+ <NavPanelPortal navKey={'workspace-settings'}>
+ <WorkspaceSettingsSideBarContent />
+ </NavPanelPortal>
+ );
+});
+
+export default SideBar;
diff --git a/src/features/WorkspaceSetting/Storage/index.tsx b/src/features/WorkspaceSetting/Storage/index.tsx
new file mode 100644
index 00000000000..a72646ffcc5
--- /dev/null
+++ b/src/features/WorkspaceSetting/Storage/index.tsx
@@ -0,0 +1,100 @@
+'use client';
+
+import { BRANDING_NAME } from '@lobechat/business-const';
+import { Button, Form, type FormGroupItemType, Icon } from '@lobehub/ui';
+import { Switch } from 'antd';
+import { HardDriveDownload, HardDriveUpload } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTransferAgentsFormItem } from '@/business/client/hooks/useTransferAgentsFormItem';
+import { FORM_STYLE } from '@/const/layoutTokens';
+
+const WorkspaceStorageContent = memo(() => {
+ const { t } = useTranslation('setting');
+ const transferAgentsFormItems = useTransferAgentsFormItem();
+
+ const analytics: FormGroupItemType = {
+ children: [
+ {
+ children: <Switch disabled />,
+ desc: t('workspaceSetting.storage.telemetry.desc', { appName: BRANDING_NAME }),
+ label: t('workspaceSetting.storage.telemetry.title'),
+ minWidth: undefined,
+ valuePropName: 'checked',
+ },
+ ],
+ title: t('analytics.title'),
+ };
+
+ const system: FormGroupItemType = {
+ children: [
+ {
+ children: (
+ <Button disabled icon={<Icon icon={HardDriveDownload} />}>
+ {t('storage.actions.import.button')}
+ </Button>
+ ),
+ desc: t('workspaceSetting.storage.comingSoon'),
+ label: t('storage.actions.import.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ },
+ {
+ children: (
+ <Button disabled icon={<Icon icon={HardDriveUpload} />}>
+ {t('storage.actions.export.button')}
+ </Button>
+ ),
+ desc: t('workspaceSetting.storage.comingSoon'),
+ label: t('storage.actions.export.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ },
+ {
+ children: (
+ <Button danger disabled type={'primary'}>
+ {t('danger.clear.action')}
+ </Button>
+ ),
+ desc: t('workspaceSetting.storage.danger.clear.desc'),
+ label: t('workspaceSetting.storage.danger.clear.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ },
+ {
+ children: (
+ <Button danger disabled type={'primary'}>
+ {t('danger.reset.action')}
+ </Button>
+ ),
+ desc: t('workspaceSetting.storage.danger.reset.desc'),
+ label: t('workspaceSetting.storage.danger.reset.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ },
+ ],
+ title: t('storage.actions.title'),
+ };
+
+ const dataMigration: FormGroupItemType | undefined = transferAgentsFormItems
+ ? {
+ children: transferAgentsFormItems,
+ title: t('storage.migration.title'),
+ }
+ : undefined;
+
+ return (
+ <Form
+ collapsible={false}
+ items={[analytics, ...(dataMigration ? [dataMigration] : []), system]}
+ itemsType={'group'}
+ variant={'filled'}
+ {...FORM_STYLE}
+ />
+ );
+});
+
+WorkspaceStorageContent.displayName = 'WorkspaceStorageContent';
+
+export default WorkspaceStorageContent;
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsx
new file mode 100644
index 00000000000..c2e9bdf9cb8
--- /dev/null
+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx
@@ -0,0 +1,144 @@
+import { SkillsIcon } from '@lobehub/ui/icons';
+import {
+ Brain,
+ Building2,
+ ChartColumnBigIcon,
+ Coins,
+ CreditCard,
+ Database,
+ KeyIcon,
+ KeyRound,
+ Map,
+ Sparkles,
+ Users,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useShowWorkspaceApiKey } from '@/business/client/hooks/useShowWorkspaceApiKey';
+import { WorkspaceSettingsTabs } from '@/types/workspaceSettings';
+
+export enum WorkspaceSettingsGroupKey {
+ Admin = 'admin',
+ Agent = 'agent',
+ General = 'general',
+ Subscription = 'subscription',
+}
+
+export interface WorkspaceSettingCategoryItem {
+ icon: any;
+ key: WorkspaceSettingsTabs;
+ label: string;
+}
+
+export interface WorkspaceSettingCategoryGroup {
+ items: WorkspaceSettingCategoryItem[];
+ key: WorkspaceSettingsGroupKey;
+ title: string;
+}
+
+export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] => {
+ const { t } = useTranslation('setting');
+ const { t: tAuth } = useTranslation('auth');
+ const showApiKey = useShowWorkspaceApiKey();
+
+ return useMemo(
+ () => [
+ {
+ items: [
+ {
+ icon: Building2,
+ key: WorkspaceSettingsTabs.General,
+ label: t('workspaceSetting.tab.general'),
+ },
+ {
+ icon: Users,
+ key: WorkspaceSettingsTabs.Members,
+ label: t('workspaceSetting.tab.members'),
+ },
+ {
+ icon: ChartColumnBigIcon,
+ key: WorkspaceSettingsTabs.Stats,
+ label: tAuth('tab.stats'),
+ },
+ ],
+ key: WorkspaceSettingsGroupKey.General,
+ title: t('workspaceSetting.group.general'),
+ },
+ {
+ items: [
+ {
+ icon: Map,
+ key: WorkspaceSettingsTabs.Plans,
+ label: t('workspaceSetting.tab.plans'),
+ },
+ {
+ icon: ChartColumnBigIcon,
+ key: WorkspaceSettingsTabs.Usage,
+ label: t('workspaceSetting.tab.usage'),
+ },
+ {
+ icon: Coins,
+ key: WorkspaceSettingsTabs.Credits,
+ label: t('workspaceSetting.tab.credits'),
+ },
+ {
+ icon: CreditCard,
+ key: WorkspaceSettingsTabs.Billing,
+ label: t('workspaceSetting.tab.billing'),
+ },
+ ],
+ key: WorkspaceSettingsGroupKey.Subscription,
+ title: t('workspaceSetting.group.subscription'),
+ },
+ {
+ items: [
+ {
+ icon: Brain,
+ key: WorkspaceSettingsTabs.Provider,
+ label: t('tab.provider'),
+ },
+ {
+ icon: Sparkles,
+ key: WorkspaceSettingsTabs.ServiceModel,
+ label: t('tab.serviceModel'),
+ },
+ {
+ icon: SkillsIcon,
+ key: WorkspaceSettingsTabs.Skill,
+ label: t('workspaceSetting.tab.skill'),
+ },
+ {
+ icon: KeyRound,
+ key: WorkspaceSettingsTabs.Creds,
+ label: t('tab.creds'),
+ },
+ // Messenger (聊天平台) is intentionally omitted from workspace
+ // settings: the System Bot binding is a per-user/personal identity
+ // (the link is owned by `userId`, not the workspace), and reaching a
+ // workspace's agents happens via the scope selector on the *personal*
+ // Messenger page. There is nothing workspace-level to configure here.
+ ],
+ key: WorkspaceSettingsGroupKey.Agent,
+ title: t('workspaceSetting.group.agent'),
+ },
+ {
+ items: [
+ {
+ icon: Database,
+ key: WorkspaceSettingsTabs.Storage,
+ label: t('tab.storage'),
+ },
+ showApiKey && {
+ icon: KeyIcon,
+ key: WorkspaceSettingsTabs.APIKey,
+ label: tAuth('tab.apikey'),
+ },
+ ].filter(Boolean) as WorkspaceSettingCategoryItem[],
+ key: WorkspaceSettingsGroupKey.Admin,
+ title: t('workspaceSetting.group.admin'),
+ },
+ ],
+ [t, tAuth, showApiKey],
+ );
+};
diff --git a/src/features/WorkspaceSetting/index.ts b/src/features/WorkspaceSetting/index.ts
new file mode 100644
index 00000000000..0d3d6ebbe84
--- /dev/null
+++ b/src/features/WorkspaceSetting/index.ts
@@ -0,0 +1,3 @@
+export { default as WorkspaceSettingsContainer } from './Container';
+export { WorkspaceSettingsContentLayout, default as WorkspaceSettingsLayout } from './Layout';
+export { default as WorkspaceSettingsSideBar } from './SideBar';
diff --git a/src/hooks/useCommunityPublishGuard.tsx b/src/hooks/useCommunityPublishGuard.tsx
new file mode 100644
index 00000000000..0375d7e50a1
--- /dev/null
+++ b/src/hooks/useCommunityPublishGuard.tsx
@@ -0,0 +1,43 @@
+import { App } from 'antd';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import { message } from '@/components/AntdStaticMethods';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+/**
+ * Guards Community publishing inside a workspace. A workspace can only publish
+ * to the Community after its owner has set up the workspace's Community
+ * organization identity. Returns a checker that surfaces an actionable prompt
+ * and returns `false` when setup is still required.
+ *
+ * Outside a workspace (`isWorkspaceScope` is false) the checker is always a
+ * no-op that returns `true`, so open-source builds are unaffected.
+ */
+export const useCommunityPublishGuard = () => {
+ const { t } = useTranslation('setting');
+ const { modal } = App.useApp();
+ const navigate = useWorkspaceAwareNavigate();
+ const { canEdit, isLoading, isWorkspaceScope, profile } = useCommunityWorkspaceProfile();
+
+ return useCallback((): boolean => {
+ // Not in a workspace, still loading, or the org identity already exists.
+ if (!isWorkspaceScope || isLoading || profile) return true;
+
+ if (canEdit) {
+ modal.confirm({
+ centered: true,
+ content: t('marketPublish.validation.communitySetupRequired.desc'),
+ okButtonProps: { type: 'primary' },
+ okText: t('marketPublish.validation.communitySetupRequired.action'),
+ onOk: () => navigate('/community/workspace'),
+ title: t('marketPublish.validation.communitySetupRequired.title'),
+ });
+ } else {
+ message.warning(t('marketPublish.validation.communitySetupRequired.memberHint'));
+ }
+
+ return false;
+ }, [canEdit, isLoading, isWorkspaceScope, profile, modal, navigate, t]);
+};
diff --git a/src/hooks/useCreateHeteroAgent.ts b/src/hooks/useCreateHeteroAgent.ts
index b45d8095a0d..ec456219ab2 100644
--- a/src/hooks/useCreateHeteroAgent.ts
+++ b/src/hooks/useCreateHeteroAgent.ts
@@ -1,7 +1,7 @@
import { type HeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';
import { useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
@@ -18,7 +18,7 @@ export interface CreateHeteroAgentOptions {
export const useCreateHeteroAgent = () => {
const storeCreateAgent = useAgentStore((s) => s.createAgent);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return useCallback(
async (definition: HeterogeneousAgentClientConfig, options?: CreateHeteroAgentOptions) => {
diff --git a/src/hooks/useInterceptingRoutes.ts b/src/hooks/useInterceptingRoutes.ts
index 23b8462bf21..9a267547c4a 100644
--- a/src/hooks/useInterceptingRoutes.ts
+++ b/src/hooks/useInterceptingRoutes.ts
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAgentStore } from '@/store/agent';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -9,7 +10,7 @@ export const useOpenChatSettings = (tab: ChatSettingsTabs = ChatSettingsTabs.Ope
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const isMobile = useIsMobile();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
return useMemo(() => {
diff --git a/src/hooks/useNavLayout.test.tsx b/src/hooks/useNavLayout.test.tsx
new file mode 100644
index 00000000000..39e4971b676
--- /dev/null
+++ b/src/hooks/useNavLayout.test.tsx
@@ -0,0 +1,65 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+interface GlobalStateMock {
+ toggleCommandMenu: () => void;
+}
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceSlug: null as string | null,
+ showMarket: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/config/routes', () => ({
+ getRouteById: (id: string) => ({
+ icon: () => id,
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: GlobalStateMock) => unknown) =>
+ selector({ toggleCommandMenu: vi.fn() }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ featureFlagsSelectors: {},
+ useServerConfigStore: () => ({
+ hideGitHub: false,
+ showMarket: mocks.showMarket,
+ }),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.activeWorkspaceSlug,
+}));
+
+describe('useNavLayout', () => {
+ beforeEach(() => {
+ mocks.activeWorkspaceSlug = null;
+ mocks.showMarket = true;
+ });
+
+ it('keeps Memory visible in personal mode', async () => {
+ const { useNavLayout } = await import('./useNavLayout');
+ const { result } = renderHook(() => useNavLayout());
+
+ const memoryItem = result.current.bottomMenuItems.find((item) => item.key === 'memory');
+
+ expect(memoryItem?.hidden).not.toBe(true);
+ });
+
+ it('hides Memory in workspace mode', async () => {
+ mocks.activeWorkspaceSlug = 'lobe-team';
+
+ const { useNavLayout } = await import('./useNavLayout');
+ const { result } = renderHook(() => useNavLayout());
+
+ const memoryItem = result.current.bottomMenuItems.find((item) => item.key === 'memory');
+
+ expect(memoryItem?.hidden).toBe(true);
+ });
+});
diff --git a/src/hooks/useNavLayout.ts b/src/hooks/useNavLayout.ts
index c159b42d093..5bbfac94f84 100644
--- a/src/hooks/useNavLayout.ts
+++ b/src/hooks/useNavLayout.ts
@@ -2,6 +2,7 @@ import { HomeIcon, SearchIcon } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { getRouteById } from '@/config/routes';
import { useGlobalStore } from '@/store/global';
import { SidebarTabKey } from '@/store/global/initialState';
@@ -36,6 +37,7 @@ export const useNavLayout = (): NavLayout => {
const { t } = useTranslation('common');
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const { showMarket, hideGitHub } = useServerConfigStore(featureFlagsSelectors);
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
const topNavItems = useMemo(
() =>
@@ -91,13 +93,14 @@ export const useNavLayout = (): NavLayout => {
url: '/resource',
},
{
+ hidden: !!activeWorkspaceSlug,
icon: getRouteById('memory')!.icon,
key: SidebarTabKey.Memory,
title: t('tab.memory'),
url: '/memory',
},
] as NavItem[],
- [t, showMarket],
+ [t, showMarket, activeWorkspaceSlug],
);
const footer = useMemo(
@@ -113,7 +116,9 @@ export const useNavLayout = (): NavLayout => {
const userPanel = useMemo(
() => ({
showDataImporter: false,
- showMemory: true,
+ // Memory now appears in the sidebar by default; drop the duplicate entry
+ // from the user dropdown to keep that menu focused on account / settings.
+ showMemory: false,
}),
[],
);
diff --git a/src/hooks/usePermission.ts b/src/hooks/usePermission.ts
new file mode 100644
index 00000000000..079260a9c15
--- /dev/null
+++ b/src/hooks/usePermission.ts
@@ -0,0 +1,9 @@
+export interface Permission {
+ allowed: boolean;
+ reason: string;
+}
+
+export const usePermission = (_action: string): Permission => ({
+ allowed: true,
+ reason: '',
+});
diff --git a/src/hooks/useQueryRoute.ts b/src/hooks/useQueryRoute.ts
index 136439b3116..13352c340b0 100644
--- a/src/hooks/useQueryRoute.ts
+++ b/src/hooks/useQueryRoute.ts
@@ -2,7 +2,8 @@ import { isOnServerSide } from '@lobechat/utils';
import { type ParsedQuery } from 'query-string';
import qs from 'query-string';
import { useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface QueryRouteOptions {
hash?: string;
@@ -31,7 +32,7 @@ const genHref = ({ hash, replace, url, prevQuery = {}, query = {} }: GenHrefOpti
};
export const useQueryRoute = () => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return useMemo(
() => ({
diff --git a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx
index d0e6823a9f8..7452abfdc40 100644
--- a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx
+++ b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx
@@ -7,6 +7,7 @@ import { Package, Wrench } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaClient } from '@/libs/trpc/client';
import { type ClaimableResource, type ClaimableResources } from './useSocialConnect';
@@ -22,6 +23,7 @@ export const ClaimResourcesModal = memo<ClaimResourcesModalProps>(
({ open, onClose, resources, onSuccess }) => {
const { t } = useTranslation('marketAuth');
const { message } = App.useApp();
+ const { allowed: canCreate } = usePermission('create_content');
const [selectedPlugins, setSelectedPlugins] = useState<Set<string>>(new Set());
const [selectedSkills, setSelectedSkills] = useState<Set<string>>(new Set());
@@ -63,6 +65,7 @@ export const ClaimResourcesModal = memo<ClaimResourcesModalProps>(
}, []);
const handleClaim = useCallback(async () => {
+ if (!canCreate) return;
const pluginIds = [...selectedPlugins];
const skillIds = [...selectedSkills];
@@ -97,7 +100,7 @@ export const ClaimResourcesModal = memo<ClaimResourcesModalProps>(
} finally {
setIsClaiming(false);
}
- }, [selectedPlugins, selectedSkills, message, t, onSuccess, onClose]);
+ }, [canCreate, selectedPlugins, selectedSkills, message, t, onSuccess, onClose]);
const totalSelected = selectedPlugins.size + selectedSkills.size;
@@ -139,6 +142,7 @@ export const ClaimResourcesModal = memo<ClaimResourcesModalProps>(
centered
cancelText={t('claimResources.skip', { defaultValue: 'Skip' })}
confirmLoading={isClaiming}
+ okButtonProps={{ disabled: !canCreate }}
okText={t('claimResources.claim', { defaultValue: 'Claim Selected' })}
open={open}
title={false}
diff --git a/src/layout/GlobalProvider/useUserStateRedirect.test.ts b/src/layout/GlobalProvider/useUserStateRedirect.test.ts
new file mode 100644
index 00000000000..4589e8470c6
--- /dev/null
+++ b/src/layout/GlobalProvider/useUserStateRedirect.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldDeferOnboardingRedirect } from './useUserStateRedirect';
+
+describe('shouldDeferOnboardingRedirect', () => {
+ it('defers on invite routes so invited users can accept before onboarding', () => {
+ expect(shouldDeferOnboardingRedirect('/invite/abc')).toBe(true);
+ expect(shouldDeferOnboardingRedirect('/invite/abc/')).toBe(true);
+ });
+
+ it('defers on possible workspace slug routes', () => {
+ expect(shouldDeferOnboardingRedirect('/acme')).toBe(true);
+ expect(shouldDeferOnboardingRedirect('/acme/settings/members')).toBe(true);
+ });
+
+ it('does not defer on personal app routes', () => {
+ expect(shouldDeferOnboardingRedirect('/')).toBe(false);
+ expect(shouldDeferOnboardingRedirect('/agent')).toBe(false);
+ expect(shouldDeferOnboardingRedirect('/settings/profile')).toBe(false);
+ });
+});
diff --git a/src/layout/GlobalProvider/useUserStateRedirect.ts b/src/layout/GlobalProvider/useUserStateRedirect.ts
index 6eeb520ec24..92bd5b33d62 100644
--- a/src/layout/GlobalProvider/useUserStateRedirect.ts
+++ b/src/layout/GlobalProvider/useUserStateRedirect.ts
@@ -7,6 +7,57 @@ import { onboardingSelectors } from '@/store/user/selectors';
import { type UserInitializationState } from '@/types/user';
import { buildOnboardingRedirectUrl } from '@/utils/onboardingRedirect';
+const DEFER_REDIRECT_PREFIXES = ['/invite'];
+
+const RESERVED_FIRST_SEGMENTS = new Set([
+ 'agent',
+ 'community',
+ 'desktop-onboarding',
+ 'devtools',
+ 'eval',
+ 'group',
+ 'image',
+ 'me',
+ 'memory',
+ 'next-auth',
+ 'onboarding',
+ 'page',
+ 'resource',
+ 'settings',
+ 'share',
+ 'signin',
+ 'signup',
+ 'subscription',
+ 'task',
+ 'tasks',
+ 'video',
+]);
+
+const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;
+
+const isPathUnder = (pathname: string, prefix: string): boolean =>
+ pathname === prefix || pathname.startsWith(`${prefix}/`);
+
+const parseFirstSegment = (pathname: string): string | null => {
+ const match = pathname.match(FIRST_SEGMENT_REGEX);
+ return match ? match[1] : null;
+};
+
+/**
+ * Defer the onboarding redirect when the path is a workspace-scoped route
+ * (first segment is a workspace slug, i.e. not one of the reserved app
+ * segments) or an explicitly deferred prefix like `/invite`. Reserved
+ * first segments (e.g. `/agent`, `/settings`) fall through to the normal
+ * onboarding check.
+ */
+export const shouldDeferOnboardingRedirect = (pathname: string): boolean => {
+ if (DEFER_REDIRECT_PREFIXES.some((prefix) => isPathUnder(pathname, prefix))) return true;
+
+ const first = parseFirstSegment(pathname);
+
+ return !!first && !RESERVED_FIRST_SEGMENTS.has(first);
+};
+
const redirectToOnboarding = (currentPath: string, search: string) => {
if (!currentPath.startsWith('/onboarding')) {
// Thread the page the user was on so onboarding finish points return there
@@ -25,6 +76,7 @@ export const useWebUserStateRedirect = () =>
const { pathname, search } = window.location;
if (!onboardingSelectors.needsOnboarding(state)) return;
+ if (shouldDeferOnboardingRedirect(pathname)) return;
redirectToOnboarding(pathname, search);
}, []);
diff --git a/src/libs/swr/index.ts b/src/libs/swr/index.ts
index f4cfc4a05db..e0bd1e0a170 100644
--- a/src/libs/swr/index.ts
+++ b/src/libs/swr/index.ts
@@ -1,6 +1,29 @@
import { type SWRHook } from 'swr';
import useSWR from 'swr';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+
+/**
+ * Append the active workspace id to the SWR cache key so workspace-scoped
+ * fetches never collide across contexts. Personal mode (no active workspace)
+ * leaves the key unchanged so existing personal caches keep their identity.
+ *
+ * - `null` / `undefined` / `false` keys (SWR's "skip" signals) pass through.
+ * - String / number keys are wrapped into a tuple `[key, wsId]`.
+ * - Array keys get `wsId` appended.
+ * - Other shapes (object keys, etc.) are wrapped into a tuple too.
+ *
+ * Combined with the `key={activeWorkspaceId}` remount at the top of the SPA
+ * tree, this gives true SWR isolation per workspace without per-feature
+ * registration.
+ */
+const augmentKey = (key: unknown, workspaceId: string | null | undefined): unknown => {
+ if (workspaceId == null) return key;
+ if (key == null || key === false) return key;
+ if (Array.isArray(key)) return [...key, workspaceId];
+ return [key, workspaceId];
+};
+
/**
* This type of request method is for relatively flexible data, which will be triggered on the first time.
*
@@ -11,8 +34,9 @@ import useSWR from 'swr';
* Suitable for messages, topics, sessions, and other data that users will interact with on the client.
*/
// @ts-ignore
-export const useClientDataSWR: SWRHook = (key, fetch, config) =>
- useSWR(key, fetch, {
+export const useClientDataSWR: SWRHook = (key, fetch, config) => {
+ const workspaceId = useActiveWorkspaceId();
+ return useSWR(augmentKey(key, workspaceId) as any, fetch, {
// default is 2000ms ,it makes the user's quick switch don't work correctly.
// Cause issue like this: https://github.com/lobehub/lobe-chat/issues/532
// we need to set it to 0.
@@ -36,6 +60,7 @@ export const useClientDataSWR: SWRHook = (key, fetch, config) =>
revalidateOnReconnect: true,
...config,
});
+};
/**
* This type of request method is a relatively "static" request mode, which will only be triggered on the first request.
diff --git a/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx b/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx
new file mode 100644
index 00000000000..d70855f268d
--- /dev/null
+++ b/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx
@@ -0,0 +1,63 @@
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it, vi } from 'vitest';
+
+import CreateGenerationPage from './CreateGenerationPage';
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('motion/react', () => ({
+ AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ m: {
+ div: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ },
+}));
+
+vi.mock('@/features/NavHeader', () => ({
+ default: () => <div data-testid="nav-header" />,
+}));
+
+vi.mock('@/features/WideScreenContainer', () => ({
+ default: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('@/features/WideScreenContainer/WideScreenButton', () => ({
+ default: () => <button type="button">wide</button>,
+}));
+
+vi.mock('@/hooks/useQueryParam', () => ({
+ useQueryState: () => [null],
+}));
+
+const PromptInput = () => <div data-testid="prompt-input" />;
+const Workspace = () => <div data-testid="generation-workspace" />;
+
+const renderPage = (path: string, entry: string) =>
+ render(
+ <MemoryRouter initialEntries={[entry]}>
+ <CreateGenerationPage PromptInput={PromptInput} Workspace={Workspace} path={path} />
+ </MemoryRouter>,
+ );
+
+describe('CreateGenerationPage', () => {
+ it.each([
+ ['/image', '/image'],
+ ['/video', '/video'],
+ ])('renders %s on the personal generation path', (path, entry) => {
+ renderPage(path, entry);
+
+ expect(screen.getByTestId('prompt-input')).toBeInTheDocument();
+ });
+
+ it.each([
+ ['/image', '/hug/image'],
+ ['/video', '/hug/video'],
+ ])('renders %s on the workspace generation path', (path, entry) => {
+ renderPage(path, entry);
+
+ expect(screen.getByTestId('prompt-input')).toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/(create)/features/CreateGenerationPage.tsx b/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
index 3e864dbb937..9f92c91b843 100644
--- a/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
+++ b/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
@@ -18,11 +18,12 @@ interface CreateGenerationPageProps {
}
const CreateGenerationPage = memo<CreateGenerationPageProps>(({ path, Workspace, PromptInput }) => {
- const isCurrent = useMatch({ path, end: true });
+ const isPersonalPath = useMatch({ end: true, path });
+ const isWorkspacePath = useMatch({ end: true, path: `/:workspaceSlug${path}` });
const [topic] = useQueryState('topic');
const isHome = !topic;
- if (!isCurrent) return null;
+ if (!isPersonalPath && !isWorkspacePath) return null;
return (
<>
diff --git a/src/routes/(main)/(create)/features/GenerationInput/GenerationInvalidAPIKey.tsx b/src/routes/(main)/(create)/features/GenerationInput/GenerationInvalidAPIKey.tsx
index 03745e59857..b8572600a1e 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/GenerationInvalidAPIKey.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/GenerationInvalidAPIKey.tsx
@@ -5,10 +5,10 @@ import { Button } from '@lobehub/ui';
import { ModelProvider } from 'model-bank';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import BaseErrorForm from '@/features/Conversation/Error/BaseErrorForm';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useProviderName } from '@/hooks/useProviderName';
import { type GlobalLLMProviderKey } from '@/types/user/settings/modelProvider';
@@ -19,7 +19,7 @@ interface GenerationInvalidAPIKeyProps {
const GenerationInvalidAPIKey = memo<GenerationInvalidAPIKeyProps>(({ provider, onNavigate }) => {
const { t } = useTranslation(['modelProvider', 'error']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const providerName = useProviderName(provider as GlobalLLMProviderKey);
return (
diff --git a/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx b/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx
index b0f9bf53aca..cda11488bc8 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx
@@ -6,7 +6,8 @@ import { createStaticStyles } from 'antd-style';
import { ImageIcon, Video } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
export interface GenerationMediaModeSegmentProps {
/** `hero`: large inline headline select (cyan, borderless). `toolbar`: compact control in the input bar. */
@@ -33,7 +34,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const GenerationMediaModeSegment = memo<GenerationMediaModeSegmentProps>(
({ mode, layout = 'toolbar' }) => {
const { t } = useTranslation('common');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const isHero = layout === 'hero';
const options = useMemo<SelectProps['options']>(
diff --git a/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptInput.tsx b/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptInput.tsx
index 34875afa410..9500a4f7298 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptInput.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptInput.tsx
@@ -9,6 +9,7 @@ import { memo } from 'react';
interface GenerationPromptInputProps {
centerActions?: ReactNode;
className?: string;
+ disabled?: boolean;
disableGenerate?: boolean;
generateLabel: string;
generatingLabel: string;
@@ -50,6 +51,7 @@ const GenerationPromptInput = memo<GenerationPromptInputProps>(
generateLabel,
generatingLabel,
disableGenerate,
+ disabled,
minRows = 3,
maxRows = 6,
}) => {
@@ -57,7 +59,7 @@ const GenerationPromptInput = memo<GenerationPromptInputProps>(
if (e.key !== 'Enter' || e.shiftKey || e.nativeEvent.isComposing) return;
e.preventDefault();
- if (disableGenerate || isCreating || !value?.trim()) return;
+ if (disabled || disableGenerate || isCreating || !value?.trim()) return;
await onGenerate();
};
@@ -66,11 +68,16 @@ const GenerationPromptInput = memo<GenerationPromptInputProps>(
<TextArea
autoSize={{ maxRows, minRows }}
className={styles.textarea}
+ disabled={disabled}
placeholder={placeholder}
value={value}
variant={'borderless'}
- onChange={(e) => onValueChange(e.target.value)}
onKeyDown={handleKeyDown}
+ onChange={(e) => {
+ if (disabled) return;
+
+ onValueChange(e.target.value);
+ }}
/>
);
@@ -103,10 +110,14 @@ const GenerationPromptInput = memo<GenerationPromptInputProps>(
>
{rightActions}
<SendButton
- disabled={disableGenerate || !value}
+ disabled={disabled || disableGenerate || !value}
loading={isCreating}
title={isCreating ? generatingLabel : generateLabel}
- onClick={onGenerate}
+ onClick={() => {
+ if (disabled) return;
+
+ onGenerate();
+ }}
/>
</Flexbox>
</Flexbox>
@@ -117,10 +128,14 @@ const GenerationPromptInput = memo<GenerationPromptInputProps>(
<Flexbox horizontal align={'center'} gap={8}>
{rightActions}
<SendButton
- disabled={disableGenerate || !value}
+ disabled={disabled || disableGenerate || !value}
loading={isCreating}
title={isCreating ? generatingLabel : generateLabel}
- onClick={onGenerate}
+ onClick={() => {
+ if (disabled) return;
+
+ onGenerate();
+ }}
/>
</Flexbox>
}
diff --git a/src/routes/(main)/(create)/features/GenerationLayout/Header/AddButton.tsx b/src/routes/(main)/(create)/features/GenerationLayout/Header/AddButton.tsx
index 67376a131e2..66c89ccadd6 100644
--- a/src/routes/(main)/(create)/features/GenerationLayout/Header/AddButton.tsx
+++ b/src/routes/(main)/(create)/features/GenerationLayout/Header/AddButton.tsx
@@ -5,22 +5,30 @@ import { SquarePenIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import type { GenerationLayoutCommonProps } from '../types';
const AddButton = memo<Pick<GenerationLayoutCommonProps, 'namespace' | 'useStore'>>((props) => {
const { namespace, useStore } = props;
const { t } = useTranslation(namespace);
+ const { allowed: canCreate } = usePermission('create_content');
const openNewGenerationTopic = useStore((s: any) => s.openNewGenerationTopic);
return (
<ActionIcon
+ disabled={!canCreate}
icon={SquarePenIcon}
title={t('topic.createNew')}
size={{
blockSize: 32,
size: 18,
}}
- onClick={openNewGenerationTopic}
+ onClick={() => {
+ if (!canCreate) return;
+
+ openNewGenerationTopic();
+ }}
/>
);
});
diff --git a/src/routes/(main)/(create)/image/features/ConfigPanel/components/ModelSelect/index.tsx b/src/routes/(main)/(create)/image/features/ConfigPanel/components/ModelSelect/index.tsx
index 5c80dd3e55a..8d77d70f3ca 100644
--- a/src/routes/(main)/(create)/image/features/ConfigPanel/components/ModelSelect/index.tsx
+++ b/src/routes/(main)/(create)/image/features/ConfigPanel/components/ModelSelect/index.tsx
@@ -4,9 +4,9 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { LucideArrowRight, LucideBolt } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { ProviderItemRender } from '@/components/ModelSelect';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiProviderSelectors } from '@/store/aiInfra/slices/aiProvider/selectors';
import { useImageStore } from '@/store/image';
@@ -43,7 +43,7 @@ interface ModelOption {
const ModelSelect = memo(() => {
const { t } = useTranslation('components');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [currentModel, currentProvider] = useImageStore((s) => [
imageGenerationConfigSelectors.model(s),
diff --git a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
index 31ddb910722..277532948f4 100644
--- a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
@@ -13,6 +13,7 @@ import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import PromptTransformAction from '@/features/PromptTransform/PromptTransformAction';
import { useFetchAiImageConfig } from '@/hooks/useFetchAiImageConfig';
import { useIsDark } from '@/hooks/useIsDark';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryState } from '@/hooks/useQueryParam';
import {
ConfigAction,
@@ -57,18 +58,28 @@ interface SwitchItemProps {
}
const SwitchItem = memo<SwitchItemProps>(({ label, paramName }) => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useGenerationConfigParam(paramName);
return (
<Flexbox horizontal align="center" justify="space-between" padding={'0 2px'}>
<Text weight={500}>{label}</Text>
- <Switch checked={!!value} onChange={(checked) => setValue(checked as any)} />
+ <Switch
+ checked={!!value}
+ disabled={!canCreate}
+ onChange={(checked) => {
+ if (!canCreate) return;
+
+ setValue(checked as any);
+ }}
+ />
</Flexbox>
);
});
const PromptExtendItem = memo(() => {
const { t } = useTranslation('image');
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, enumValues } = useGenerationConfigParam('promptExtend');
if (enumValues && enumValues.length > 0) {
@@ -79,11 +90,16 @@ const PromptExtendItem = memo(() => {
<Text weight={500}>{t('config.promptExtend.label')}</Text>
<Segmented
block
+ disabled={!canCreate}
options={options}
style={{ width: '100%' }}
value={value as string}
variant="filled"
- onChange={(next) => setValue(String(next) as any)}
+ onChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(String(next) as any);
+ }}
/>
</Flexbox>
);
@@ -92,7 +108,15 @@ const PromptExtendItem = memo(() => {
return (
<Flexbox horizontal align="center" justify="space-between" padding={'0 2px'}>
<Text weight={500}>{t('config.promptExtend.label')}</Text>
- <Switch checked={!!value} onChange={(checked) => setValue(checked as any)} />
+ <Switch
+ checked={!!value}
+ disabled={!canCreate}
+ onChange={(checked) => {
+ if (!canCreate) return;
+
+ setValue(checked as any);
+ }}
+ />
</Flexbox>
);
});
@@ -100,6 +124,7 @@ const PromptExtendItem = memo(() => {
const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isDarkMode = useIsDark();
const { t } = useTranslation('image');
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useGenerationConfigParam('prompt');
const { value: imageUrl, setValue: setImageUrl } = useGenerationConfigParam('imageUrl');
const {
@@ -139,6 +164,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const hasProcessedModel = useRef(false);
const handleGenerate = async () => {
+ if (!canCreate) return;
+
if (!isLogin) {
loginRequired.redirect({ timeout: 2000 });
return;
@@ -165,7 +192,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
}, [modelParam, isInit, enabledImageModelList, setModelAndProviderOnSelect, setModelParam]);
useEffect(() => {
- if (promptParam && !hasProcessedPrompt.current && isLogin) {
+ if (promptParam && !hasProcessedPrompt.current && isLogin && canCreate) {
const decodedPrompt = decodeURIComponent(promptParam);
setValue(decodedPrompt);
hasProcessedPrompt.current = true;
@@ -179,7 +206,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
window.clearTimeout(timeoutId);
};
}
- }, [promptParam, isLogin, setValue, setPromptParam, createImage]);
+ }, [promptParam, isLogin, canCreate, setValue, setPromptParam, createImage]);
const imagePreviewUrls = useMemo(
() => [imageUrl, ...(imageUrls ?? [])].filter(Boolean) as string[],
@@ -188,6 +215,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const handleAddImage = useCallback(
(data: string | { dimensions?: { height: number; width: number }; url: string }) => {
+ if (!canCreate) return;
+
const { url, dimensions } = extractUrlAndDimensions(data);
if (!url) return;
@@ -212,18 +241,21 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
setImageUrls,
autoSetDimensions,
extractUrlAndDimensions,
+ canCreate,
],
);
const handleRemoveImage = useCallback(
(url: string) => {
+ if (!canCreate) return;
+
if (url === imageUrl) {
setImageUrl(null);
} else {
setImageUrls((imageUrls ?? []).filter((item) => item !== url) as any);
}
},
- [imageUrl, imageUrls, setImageUrl, setImageUrls],
+ [canCreate, imageUrl, imageUrls, setImageUrl, setImageUrls],
);
const showInlineRef = isSupportImageUrl || isSupportImageUrls;
@@ -241,6 +273,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
{showTitle && <PromptTitle />}
<GenerationPromptInput
disableGenerate={!isInit}
+ disabled={!canCreate}
generateLabel={t('generation.actions.generate')}
generatingLabel={t('generation.status.generating')}
isCreating={isCreating}
@@ -258,7 +291,12 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
) : undefined
}
leftActions={
- <Flexbox horizontal align={'center'} gap={4}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={canCreate ? undefined : { opacity: 0.5, pointerEvents: 'none' }}
+ >
<GenerationMediaModeSegment mode={'image'} />
<ModelSwitchPanel
ModelItemComponent={ImageModelItem}
@@ -269,6 +307,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
pricingMode="image"
provider={currentProvider ?? undefined}
onModelChange={async ({ model, provider }) => {
+ if (!canCreate) return;
+
setModelAndProviderOnSelect(model, provider);
}}
>
@@ -350,7 +390,15 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
hasRefImages ? t('config.prompt.placeholderWithRef') : t('config.prompt.placeholder')
}
rightActions={
- <PromptTransformAction mode={'image'} prompt={value} onPromptChange={setValue as any} />
+ <PromptTransformAction
+ mode={'image'}
+ prompt={value}
+ onPromptChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(next as any);
+ }}
+ />
}
onGenerate={handleGenerate}
onValueChange={setValue}
diff --git a/src/routes/(main)/(create)/video/features/ConfigPanel/components/ModelSelect/index.tsx b/src/routes/(main)/(create)/video/features/ConfigPanel/components/ModelSelect/index.tsx
index 21bf88d0187..274d9b164ec 100644
--- a/src/routes/(main)/(create)/video/features/ConfigPanel/components/ModelSelect/index.tsx
+++ b/src/routes/(main)/(create)/video/features/ConfigPanel/components/ModelSelect/index.tsx
@@ -4,9 +4,9 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { LucideArrowRight, LucideBolt } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { ProviderItemRender } from '@/components/ModelSelect';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiProviderSelectors } from '@/store/aiInfra/slices/aiProvider/selectors';
import { useVideoStore } from '@/store/video';
@@ -43,7 +43,7 @@ interface ModelOption {
const ModelSelect = memo(() => {
const { t } = useTranslation('components');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [currentModel, currentProvider] = useVideoStore((s) => [
videoGenerationConfigSelectors.model(s),
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
index bc7659c45db..37b03b31041 100644
--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
@@ -14,6 +14,7 @@ import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import PromptTransformAction from '@/features/PromptTransform/PromptTransformAction';
import { useFetchAiVideoConfig } from '@/hooks/useFetchAiVideoConfig';
import { useIsDark } from '@/hooks/useIsDark';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryState } from '@/hooks/useQueryParam';
import {
ConfigAction,
@@ -42,6 +43,7 @@ interface PromptInputProps {
const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam;
const AspectRatioItem = memo(() => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, enumValues } = useVideoGenerationConfigParam('aspectRatio');
const options = useMemo(
() => (enumValues ?? []).map((v) => ({ label: v, value: v })),
@@ -50,10 +52,21 @@ const AspectRatioItem = memo(() => {
if (options.length === 0) return null;
- return <AspectRatioSelect options={options} value={value} onChange={(v) => setValue(v as any)} />;
+ return (
+ <AspectRatioSelect
+ options={options}
+ value={value}
+ onChange={(v) => {
+ if (!canCreate) return;
+
+ setValue(v as any);
+ }}
+ />
+ );
});
const SizeItem = memo(() => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, enumValues } = useVideoGenerationConfigParam('size');
const options = useMemo(
@@ -67,10 +80,21 @@ const SizeItem = memo(() => {
if (options.length === 0) return null;
- return <Select options={options} value={value} onChange={setValue} />;
+ return (
+ <Select
+ options={options}
+ value={value}
+ onChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(next);
+ }}
+ />
+ );
});
const ResolutionItem = memo(() => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, enumValues } = useVideoGenerationConfigParam('resolution');
const options = useMemo(
() => (enumValues ?? []).map((v) => ({ label: v, value: v })),
@@ -82,16 +106,22 @@ const ResolutionItem = memo(() => {
return (
<Segmented
block
+ disabled={!canCreate}
options={options}
style={{ width: '100%' }}
value={value}
variant="filled"
- onChange={(v) => setValue(String(v) as any)}
+ onChange={(v) => {
+ if (!canCreate) return;
+
+ setValue(String(v) as any);
+ }}
/>
);
});
const DurationItem = memo(() => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, min, max, step, enumValues } = useVideoGenerationConfigParam('duration');
const options = useMemo(
@@ -109,45 +139,68 @@ const DurationItem = memo(() => {
return (
<Segmented
block
+ disabled={!canCreate}
options={options}
style={{ width: '100%' }}
value={value ?? min}
variant="filled"
- onChange={(v) => setValue(Number(v) as any)}
+ onChange={(v) => {
+ if (!canCreate) return;
+
+ setValue(Number(v) as any);
+ }}
/>
);
}
return (
<SliderWithInput
+ disabled={!canCreate}
max={max}
min={min}
step={step ?? 1}
value={value ?? min}
- onChange={(v) => setValue(v as any)}
+ onChange={(v) => {
+ if (!canCreate) return;
+
+ setValue(v as any);
+ }}
/>
);
});
const SeedItem = memo(() => {
const { t } = useTranslation('video');
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useVideoGenerationConfigParam('seed');
const handleRandomize = useCallback(() => {
+ if (!canCreate) return;
+
setValue(generateUniqueSeeds(1)[0] as any);
- }, [setValue]);
+ }, [canCreate, setValue]);
return (
<Flexbox horizontal gap={4}>
<InputNumber
+ disabled={!canCreate}
min={0}
placeholder={t('config.seed.random')}
step={1}
style={{ width: '100%' }}
value={value}
- onChange={(v) => setValue(v as any)}
+ onChange={(v) => {
+ if (!canCreate) return;
+
+ setValue(v as any);
+ }}
+ />
+ <Action
+ disabled={!canCreate}
+ icon={Dices}
+ title={t('config.seed.random')}
+ onClick={handleRandomize}
/>
- <Action icon={Dices} title={t('config.seed.random')} onClick={handleRandomize} />
</Flexbox>
);
});
@@ -158,18 +211,28 @@ interface SwitchItemProps {
}
const SwitchItem = memo<SwitchItemProps>(({ label, paramName }) => {
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useVideoGenerationConfigParam(paramName);
return (
<Flexbox horizontal align="center" justify="space-between" padding={'0 2px'}>
<Text weight={500}>{label}</Text>
- <Switch checked={!!value} onChange={(checked) => setValue(checked as any)} />
+ <Switch
+ checked={!!value}
+ disabled={!canCreate}
+ onChange={(checked) => {
+ if (!canCreate) return;
+
+ setValue(checked as any);
+ }}
+ />
</Flexbox>
);
});
const PromptExtendItem = memo(() => {
const { t } = useTranslation('video');
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue, enumValues } = useVideoGenerationConfigParam('promptExtend');
const options = enumValues?.map((item) => ({ label: item, value: item })) ?? [];
@@ -180,11 +243,16 @@ const PromptExtendItem = memo(() => {
<Text weight={500}>{t('config.promptExtend.label')}</Text>
<Segmented
block
+ disabled={!canCreate}
options={options}
style={{ width: '100%' }}
value={value as string}
variant="filled"
- onChange={(next) => setValue(String(next) as any)}
+ onChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(String(next) as any);
+ }}
/>
</Flexbox>
);
@@ -193,7 +261,15 @@ const PromptExtendItem = memo(() => {
return (
<Flexbox horizontal align="center" justify="space-between" padding={'0 2px'}>
<Text weight={500}>{t('config.promptExtend.label')}</Text>
- <Switch checked={!!value} onChange={(checked) => setValue(checked as any)} />
+ <Switch
+ checked={!!value}
+ disabled={!canCreate}
+ onChange={(checked) => {
+ if (!canCreate) return;
+
+ setValue(checked as any);
+ }}
+ />
</Flexbox>
);
});
@@ -201,6 +277,7 @@ const PromptExtendItem = memo(() => {
const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isDarkMode = useIsDark();
const { t } = useTranslation('video');
+ const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useVideoGenerationConfigParam('prompt');
const { value: imageUrl, setValue: setImageUrl } = useVideoGenerationConfigParam('imageUrl');
const {
@@ -243,6 +320,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const hasProcessedModel = useRef(false);
const handleGenerate = async () => {
+ if (!canCreate) return;
+
if (!isLogin) {
loginRequired.redirect({ timeout: 2000 });
return;
@@ -270,7 +349,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
// Auto-fill and auto-send when prompt query parameter is present
useEffect(() => {
- if (promptParam && !hasProcessedPrompt.current && isLogin) {
+ if (promptParam && !hasProcessedPrompt.current && isLogin && canCreate) {
const decodedPrompt = decodeURIComponent(promptParam);
setValue(decodedPrompt);
@@ -287,7 +366,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
window.clearTimeout(timeoutId);
};
}
- }, [promptParam, isLogin, setValue, setPromptParam, createVideo]);
+ }, [promptParam, isLogin, canCreate, setValue, setPromptParam, createVideo]);
const showInlineFrames = isSupportImageUrl || isSupportImageUrls || isSupportEndImageUrl;
const framePreviewUrls = useMemo(
@@ -304,6 +383,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const handleAddImage = useCallback(
(data: string | { dimensions?: { height: number; width: number }; url: string }) => {
+ if (!canCreate) return;
+
const url = typeof data === 'string' ? data : data?.url;
if (!url) return;
if (framePreviewUrls.length >= maxCount) return;
@@ -325,22 +406,27 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
setImageUrls,
framePreviewUrls.length,
maxCount,
+ canCreate,
],
);
const handleRemoveImage = useCallback(
(url: string) => {
+ if (!canCreate) return;
+
if (url === imageUrl) {
setImageUrl(null);
} else {
setImageUrls((imageUrls ?? []).filter((item) => item !== url) as any);
}
},
- [imageUrl, imageUrls, setImageUrl, setImageUrls],
+ [canCreate, imageUrl, imageUrls, setImageUrl, setImageUrls],
);
const handleEndImageChange = useCallback(
(data: string | { dimensions?: { height: number; width: number }; url: string } | null) => {
+ if (!canCreate) return;
+
if (data === null) {
setEndImageUrl(null as any);
return;
@@ -348,7 +434,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const url = typeof data === 'string' ? data : data?.url;
setEndImageUrl((url ?? null) as any);
},
- [setEndImageUrl],
+ [canCreate, setEndImageUrl],
);
return (
@@ -357,6 +443,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
<Flexbox gap={8}>
<GenerationPromptInput
disableGenerate={!isInit}
+ disabled={!canCreate}
generateLabel={t('generation.actions.generate')}
generatingLabel={t('generation.status.generating')}
isCreating={isCreating}
@@ -385,7 +472,12 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
) : undefined
}
leftActions={
- <Flexbox horizontal align={'center'} gap={4}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={canCreate ? undefined : { opacity: 0.5, pointerEvents: 'none' }}
+ >
<GenerationMediaModeSegment mode={'video'} />
<ModelSwitchPanel
ModelItemComponent={VideoModelItem}
@@ -396,6 +488,8 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
pricingMode="video"
provider={currentProvider ?? undefined}
onModelChange={async ({ model, provider }) => {
+ if (!canCreate) return;
+
setModelAndProviderOnSelect(model, provider);
}}
>
@@ -479,7 +573,15 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
hasRefImages ? t('config.prompt.placeholderWithRef') : t('config.prompt.placeholder')
}
rightActions={
- <PromptTransformAction mode={'video'} prompt={value} onPromptChange={setValue as any} />
+ <PromptTransformAction
+ mode={'video'}
+ prompt={value}
+ onPromptChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(next as any);
+ }}
+ />
}
onGenerate={handleGenerate}
onValueChange={setValue}
diff --git a/src/routes/(main)/[workspaceSlug]/_layout/index.tsx b/src/routes/(main)/[workspaceSlug]/_layout/index.tsx
new file mode 100644
index 00000000000..25f12408524
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/_layout/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceSlugBoundary from '@/features/Workspace/WorkspaceSlugBoundary';
+
+export default WorkspaceSlugBoundary;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/_content-layout/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/_content-layout/index.tsx
new file mode 100644
index 00000000000..7ca01cfdefb
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/_content-layout/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import { WorkspaceSettingsContentLayout } from '@/features/WorkspaceSetting';
+
+export default WorkspaceSettingsContentLayout;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/_layout/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/_layout/index.tsx
new file mode 100644
index 00000000000..8f72069c31d
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/_layout/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import { WorkspaceSettingsLayout } from '@/features/WorkspaceSetting';
+
+export default WorkspaceSettingsLayout;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx
new file mode 100644
index 00000000000..fe4911a3318
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import Page from '@/routes/(main)/settings/apikey';
+
+const WorkspaceApiKeySetting = () => <Page />;
+
+WorkspaceApiKeySetting.displayName = 'WorkspaceApiKeySetting';
+
+export default WorkspaceApiKeySetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/billing/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/billing/index.tsx
new file mode 100644
index 00000000000..65ed4c321b5
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/billing/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceBillingBilling from '@/business/client/BusinessSettingPages/WorkspaceBillingBilling';
+
+export default WorkspaceBillingBilling;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/credits/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/credits/index.tsx
new file mode 100644
index 00000000000..baa23695b1a
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/credits/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceBillingCredits from '@/business/client/BusinessSettingPages/WorkspaceBillingCredits';
+
+export default WorkspaceBillingCredits;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx
new file mode 100644
index 00000000000..6a573b8dc4e
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { useMemo } from 'react';
+
+import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';
+import Page from '@/routes/(main)/settings/creds';
+import {
+ type CredsApi,
+ CredsApiProvider,
+} from '@/routes/(main)/settings/creds/features/useCredsApi';
+
+/**
+ * Workspace credential management.
+ *
+ * Reuses the personal `<Page />` shell but rebinds every CredsApi consumer
+ * to the cloud `workspaceCreds.*` tRPC namespace via {@link CredsApiProvider}.
+ * `workspaceCreds` resolves the active workspace to its Market organization
+ * mirror and acts on the org's credential set so every workspace member sees
+ * the same shared creds.
+ */
+const WorkspaceCredsSetting = () => {
+ const workspaceCredsApi = useMemo<CredsApi>(
+ () => ({
+ // The workspaceCreds router is a structural mirror of market.creds, but
+ // strict typeof equality breaks because workspaceCreds is registered in
+ // the cloud lambda namespace. Cast at the boundary; downstream consumers
+ // only touch overlapping members (list/get/createKV/createOAuth/
+ // createFile/update/delete/uploadFile/listOAuthConnections).
+ client: lambdaClient.workspaceCreds as unknown as CredsApi['client'],
+ query: lambdaQuery.workspaceCreds as unknown as CredsApi['query'],
+ }),
+ [],
+ );
+
+ return (
+ <CredsApiProvider value={workspaceCredsApi}>
+ <Page />
+ </CredsApiProvider>
+ );
+};
+
+WorkspaceCredsSetting.displayName = 'WorkspaceCredsSetting';
+
+export default WorkspaceCredsSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/general/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/general/index.tsx
new file mode 100644
index 00000000000..dbbb571e113
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/general/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceGeneral from '@/business/client/BusinessSettingPages/WorkspaceGeneral';
+
+export default WorkspaceGeneral;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/index.tsx
new file mode 100644
index 00000000000..f882e8ceff4
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/index.tsx
@@ -0,0 +1,10 @@
+'use client';
+
+import { memo } from 'react';
+import { Navigate } from 'react-router-dom';
+
+import { DEFAULT_WORKSPACE_SETTINGS_TAB } from '@/types/workspaceSettings';
+
+const WorkspaceSettingsIndex = memo(() => <Navigate replace to={DEFAULT_WORKSPACE_SETTINGS_TAB} />);
+
+export default WorkspaceSettingsIndex;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/members/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/members/index.tsx
new file mode 100644
index 00000000000..8268f3395f3
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/members/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceMembers from '@/business/client/BusinessSettingPages/WorkspaceMembers';
+
+export default WorkspaceMembers;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/plans/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/plans/index.tsx
new file mode 100644
index 00000000000..742cbfdfe59
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/plans/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceBillingPlans from '@/business/client/BusinessSettingPages/WorkspaceBillingPlans';
+
+export default WorkspaceBillingPlans;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/provider/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/provider/index.tsx
new file mode 100644
index 00000000000..453c2000a80
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/provider/index.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import Page from '@/routes/(main)/settings/provider/(list)';
+
+const WorkspaceProviderSetting = () => <Page />;
+
+WorkspaceProviderSetting.displayName = 'WorkspaceProviderSetting';
+
+export default WorkspaceProviderSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/service-model/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/service-model/index.tsx
new file mode 100644
index 00000000000..aa3904c6446
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/service-model/index.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import Page from '@/routes/(main)/settings/service-model';
+
+const WorkspaceServiceModelSetting = () => <Page />;
+
+WorkspaceServiceModelSetting.displayName = 'WorkspaceServiceModelSetting';
+
+export default WorkspaceServiceModelSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/skill/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/skill/index.tsx
new file mode 100644
index 00000000000..c66e41eebaf
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/skill/index.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import Page from '@/routes/(main)/settings/skill';
+
+const WorkspaceSkillSetting = () => <Page />;
+
+WorkspaceSkillSetting.displayName = 'WorkspaceSkillSetting';
+
+export default WorkspaceSkillSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/stats/index.test.tsx b/src/routes/(main)/[workspaceSlug]/settings/stats/index.test.tsx
new file mode 100644
index 00000000000..779c1df2187
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/stats/index.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import WorkspaceStatsSetting from './index';
+
+const useFetchWorkspaceMembersMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/business/client/hooks/useFetchWorkspaceMembers', () => ({
+ useFetchWorkspaceMembers: useFetchWorkspaceMembersMock,
+}));
+
+vi.mock('@/routes/(main)/settings/stats/features/overview/WorkspaceWelcome', () => ({
+ default: () => <div>Workspace Welcome</div>,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { name?: string }) =>
+ key === 'usage.activeModels.removedUserName' ? `${options?.name} (Removed)` : key,
+ }),
+}));
+
+vi.mock('@/routes/(main)/settings/stats', () => ({
+ default: ({
+ resolveUser,
+ }: {
+ resolveUser: (userId: string) => { avatar?: string | null; name: string };
+ }) => {
+ const activeUser = resolveUser('user-1');
+ const removedUser = resolveUser('user-2');
+ const noAvatarUser = resolveUser('user-3');
+
+ return (
+ <div>
+ <span>{activeUser.name}</span>
+ <span>{activeUser.avatar}</span>
+ <span>{removedUser.name}</span>
+ <span>{noAvatarUser.name}</span>
+ </div>
+ );
+ },
+}));
+
+const workspaceMembers = [
+ {
+ deletedAt: null,
+ user: {
+ avatar: 'https://example.com/avatar.png',
+ email: '[email protected]',
+ fullName: 'Ada Lovelace',
+ username: 'ada',
+ },
+ userId: 'user-1',
+ },
+ {
+ deletedAt: new Date('2026-05-27T00:00:00.000Z'),
+ user: {
+ avatar: null,
+ email: null,
+ fullName: null,
+ username: 'grace',
+ },
+ userId: 'user-2',
+ },
+ {
+ deletedAt: null,
+ user: {
+ avatar: null,
+ email: null,
+ fullName: null,
+ username: 'alan',
+ },
+ userId: 'user-3',
+ },
+];
+
+describe('WorkspaceStatsSetting', () => {
+ it('fetches deleted workspace members for user display resolution', () => {
+ useFetchWorkspaceMembersMock.mockReturnValue({ data: workspaceMembers });
+
+ render(<WorkspaceStatsSetting />);
+
+ expect(useFetchWorkspaceMembersMock).toHaveBeenCalledWith({ includeDeleted: true });
+ expect(screen.getByText('Ada Lovelace')).toBeInTheDocument();
+ expect(screen.getByText('https://example.com/avatar.png')).toBeInTheDocument();
+ expect(screen.getByText('grace (Removed)')).toBeInTheDocument();
+ expect(screen.getByText('alan')).toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/[workspaceSlug]/settings/stats/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/stats/index.tsx
new file mode 100644
index 00000000000..8bea1f81e7a
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/stats/index.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useFetchWorkspaceMembers } from '@/business/client/hooks/useFetchWorkspaceMembers';
+import Page from '@/routes/(main)/settings/stats';
+import WorkspaceWelcome from '@/routes/(main)/settings/stats/features/overview/WorkspaceWelcome';
+import { type UserDisplay } from '@/routes/(main)/settings/stats/types';
+
+interface WorkspaceStatsMemberProfile {
+ avatar?: string | null;
+ email?: string | null;
+ fullName?: string | null;
+ username?: string | null;
+}
+
+interface WorkspaceStatsMember {
+ deletedAt?: Date | string | null;
+ user?: WorkspaceStatsMemberProfile | null;
+ userId: string;
+}
+
+const WorkspaceStatsSetting = () => {
+ const { t } = useTranslation('auth');
+
+ const { data: members = [] } = useFetchWorkspaceMembers({ includeDeleted: true });
+
+ const memberMap = useMemo(() => {
+ const map = new Map<string, UserDisplay>();
+ for (const m of members) {
+ const member = m as WorkspaceStatsMember;
+ const profile = member.user;
+ const name = profile?.fullName || profile?.username || profile?.email || member.userId;
+ map.set(member.userId, {
+ avatar: profile?.avatar ?? null,
+ name: member.deletedAt ? t('usage.activeModels.removedUserName', { name }) : name,
+ });
+ }
+ return map;
+ }, [members, t]);
+
+ const resolveUser = useCallback(
+ (userId: string): UserDisplay => memberMap.get(userId) ?? { avatar: null, name: userId },
+ [memberMap],
+ );
+
+ return <Page enableUserDimension headerNode={<WorkspaceWelcome />} resolveUser={resolveUser} />;
+};
+
+WorkspaceStatsSetting.displayName = 'WorkspaceStatsSetting';
+
+export default WorkspaceStatsSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/storage/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/storage/index.tsx
new file mode 100644
index 00000000000..cfa0755f10e
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/storage/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useTranslation } from 'react-i18next';
+
+import WorkspaceStorageContent from '@/features/WorkspaceSetting/Storage';
+import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';
+
+const WorkspaceStorageSetting = () => {
+ const { t } = useTranslation('setting');
+ return (
+ <>
+ <SettingHeader title={t('tab.storage')} />
+ <WorkspaceStorageContent />
+ </>
+ );
+};
+
+WorkspaceStorageSetting.displayName = 'WorkspaceStorageSetting';
+
+export default WorkspaceStorageSetting;
diff --git a/src/routes/(main)/[workspaceSlug]/settings/usage/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/usage/index.tsx
new file mode 100644
index 00000000000..f73aa7854bd
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/usage/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceBillingUsage from '@/business/client/BusinessSettingPages/WorkspaceBillingUsage';
+
+export default WorkspaceBillingUsage;
diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsx
index 32978ffc7cf..38b8ed6be3f 100644
--- a/src/routes/(main)/_layout/index.tsx
+++ b/src/routes/(main)/_layout/index.tsx
@@ -9,6 +9,7 @@ import { Suspense } from 'react';
import { HotkeysProvider } from 'react-hotkeys-hook';
import { Outlet } from 'react-router-dom';
+import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';
import Loading from '@/components/Loading/BrandTextLoading';
import { isDesktop } from '@/const/version';
import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';
@@ -46,52 +47,54 @@ const Layout: FC = () => {
return (
<HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>
- <RouteMetaBridge />
- {isDesktop && <TabCacheBridges />}
- <Suspense fallback={null}>
- {isDesktop && <DesktopAutoOidcOnFirstOpen />}
- {isDesktop && <DesktopNavigationBridge />}
- {isDesktop && <DesktopFileMenuBridge />}
- {isDesktop && <OverlaySnapshotPublisher />}
- {isDesktop && <OverlayCaptureUploader />}
- {isDesktop && <OverlayMessageDispatcher />}
- {showCloudPromotion && <CloudBanner />}
- </Suspense>
- {isDesktop && <AuthRequiredModal />}
- {isDesktop && <ZoomHUD />}
+ <WorkspaceContextSlot>
+ <RouteMetaBridge />
+ {isDesktop && <TabCacheBridges />}
+ <Suspense fallback={null}>
+ {isDesktop && <DesktopAutoOidcOnFirstOpen />}
+ {isDesktop && <DesktopNavigationBridge />}
+ {isDesktop && <DesktopFileMenuBridge />}
+ {isDesktop && <OverlaySnapshotPublisher />}
+ {isDesktop && <OverlayCaptureUploader />}
+ {isDesktop && <OverlayMessageDispatcher />}
+ {showCloudPromotion && <CloudBanner />}
+ </Suspense>
+ {isDesktop && <AuthRequiredModal />}
+ {isDesktop && <ZoomHUD />}
- <Suspense fallback={null}>{isDesktop && <TitleBar />}</Suspense>
- <DndContextWrapper>
- <Flexbox
- horizontal
- className={cx(isPWA ? styles.mainContainerPWA : styles.mainContainer)}
- width={'100%'}
- height={
- isDesktop
- ? `calc(100% - ${TITLE_BAR_HEIGHT}px)`
- : showCloudPromotion
- ? `calc(100% - ${BANNER_HEIGHT}px)`
- : '100%'
- }
- >
- <NavPanel />
- <DesktopLayoutContainer>
- <MarketAuthProvider isDesktop={isDesktop}>
- <DesktopHomeLayout>
- <DesktopHome />
- </DesktopHomeLayout>
- <Suspense fallback={<Loading debugId="DesktopMainLayout > Outlet" />}>
- <Outlet />
- </Suspense>
- </MarketAuthProvider>
- </DesktopLayoutContainer>
- </Flexbox>
- </DndContextWrapper>
- <Suspense fallback={null}>
- <HotkeyHelperPanel />
- <RegisterHotkeys />
- <CmdkLazy />
- </Suspense>
+ <Suspense fallback={null}>{isDesktop && <TitleBar />}</Suspense>
+ <DndContextWrapper>
+ <Flexbox
+ horizontal
+ className={cx(isPWA ? styles.mainContainerPWA : styles.mainContainer)}
+ width={'100%'}
+ height={
+ isDesktop
+ ? `calc(100% - ${TITLE_BAR_HEIGHT}px)`
+ : showCloudPromotion
+ ? `calc(100% - ${BANNER_HEIGHT}px)`
+ : '100%'
+ }
+ >
+ <NavPanel />
+ <DesktopLayoutContainer>
+ <MarketAuthProvider isDesktop={isDesktop}>
+ <DesktopHomeLayout>
+ <DesktopHome />
+ </DesktopHomeLayout>
+ <Suspense fallback={<Loading debugId="DesktopMainLayout > Outlet" />}>
+ <Outlet />
+ </Suspense>
+ </MarketAuthProvider>
+ </DesktopLayoutContainer>
+ </Flexbox>
+ </DndContextWrapper>
+ <Suspense fallback={null}>
+ <HotkeyHelperPanel />
+ <RegisterHotkeys />
+ <CmdkLazy />
+ </Suspense>
+ </WorkspaceContextSlot>
</HotkeysProvider>
);
};
diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
index 2c9b80507e5..8e60b1b576a 100644
--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx
+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
@@ -1,8 +1,9 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { useMount, usePrevious, useUnmount } from 'ahooks';
import { useEffect, useMemo, useRef } from 'react';
-import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { useLocation, useParams, useSearchParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -17,7 +18,7 @@ const AgentIdSync = () => {
const [searchParams] = useSearchParams();
const searchParamsRef = useRef(searchParams);
searchParamsRef.current = searchParams;
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
// Resolve builtin agent slug to real agent ID
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Content.tsx b/src/routes/(main)/agent/_layout/Sidebar/Content.tsx
new file mode 100644
index 00000000000..27867f07831
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Content.tsx
@@ -0,0 +1,14 @@
+import React, { memo } from 'react';
+
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Body from './Body';
+import Header from './Header';
+
+const AgentSidebarContent = memo(() => {
+ return <SideBarLayout body={<Body />} header={<Header />} />;
+});
+
+AgentSidebarContent.displayName = 'AgentSidebarContent';
+
+export default AgentSidebarContent;
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
index b3b1a4ce197..091989d17a8 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
@@ -2,9 +2,9 @@ import { Flexbox, Popover } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { type PropsWithChildren } from 'react';
import { memo, Suspense, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import AgentListContent from '@/routes/(main)/home/_layout/Body/Agent/List/AgentListContent';
import { AgentModalProvider } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';
@@ -17,7 +17,7 @@ const styles = createStaticStyles(({ cssVar, css }) => ({
}));
const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const content = useMemo(
() => (
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
index abe91e9b1c5..47f4bb96c5e 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
@@ -14,6 +14,9 @@ const switchTopicMock = vi.hoisted(() => vi.fn());
const toggleCommandMenuMock = vi.hoisted(() => vi.fn());
const useParamsMock = vi.hoisted(() => vi.fn());
const usePathnameMock = vi.hoisted(() => vi.fn());
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+}));
vi.mock('@lobehub/ui', () => ({
Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
@@ -55,14 +58,16 @@ vi.mock('@/const/url', () => ({
vi.mock('@/features/NavPanel/components/NavItem', () => ({
default: ({
active,
+ disabled,
onClick,
title,
}: {
active?: boolean;
+ disabled?: boolean;
onClick?: () => void;
title: ReactNode;
}) => (
- <button data-active={String(active)} type="button" onClick={onClick}>
+ <button data-active={String(active)} disabled={disabled} type="button" onClick={onClick}>
{title}
</button>
),
@@ -84,6 +89,13 @@ vi.mock('@/libs/swr', () => ({
}),
}));
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content') => ({
+ allowed: permissionMock[action],
+ reason: permissionMock[action] ? '' : 'requires member',
+ }),
+}));
+
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: unknown) => unknown) => selector({}),
}));
@@ -129,6 +141,7 @@ describe('Agent sidebar header nav', () => {
toggleCommandMenuMock.mockReset();
useParamsMock.mockReset();
usePathnameMock.mockReset();
+ permissionMock.create_content = true;
useParamsMock.mockReturnValue({ aid: 'agt_eH4zL98zBx5u', topicId: 'tpc_2FCHvjS7d4CA' });
});
@@ -156,4 +169,19 @@ describe('Agent sidebar header nav', () => {
expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u');
expect(mutateMock).toHaveBeenCalledTimes(1);
});
+
+ it('disables starting a new topic for workspace viewers', () => {
+ permissionMock.create_content = false;
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u/channel');
+
+ render(<Nav />);
+
+ const startButton = screen.getByRole('button', { name: 'actions.addNewTopic' });
+ expect(startButton).toBeDisabled();
+
+ fireEvent.click(startButton);
+
+ expect(pushMock).not.toHaveBeenCalled();
+ expect(mutateMock).not.toHaveBeenCalled();
+ });
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index 5cf40e7bc12..c489e5f2576 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -14,6 +14,7 @@ import { useParams } from 'react-router-dom';
import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
import { useActionSWR } from '@/libs/swr';
@@ -35,6 +36,7 @@ const Nav = memo(() => {
// pathname.includes('/topics') — anchor to end to avoid that false positive.
const isTopicsActive = pathname.endsWith('/topics');
const router = useQueryRoute();
+ const { allowed: canCreateTopic } = usePermission('create_content');
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const heterogeneousProviderType = useAgentStore(
@@ -49,6 +51,7 @@ const Nav = memo(() => {
const { mutate } = useActionSWR('openNewTopicOrSaveTopic', openNewTopicOrSaveTopic);
const handleNewTopic = () => {
+ if (!canCreateTopic) return;
// Always navigate to the bare agent chat URL — drops any sub-route
// (/profile, /channel, /page, /cron/:cronId, …) and any `:topicId`
// segment so the new topic isn't conflated with the previous URL.
@@ -61,6 +64,7 @@ const Nav = memo(() => {
return (
<Flexbox gap={1} paddingInline={4}>
<NavItem
+ disabled={!canCreateTopic}
icon={MessageSquarePlusIcon}
title={tTopic('actions.addNewTopic')}
onClick={handleNewTopic}
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
index f3ce3b214a7..612bdac53b1 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
@@ -57,12 +57,15 @@ vi.mock('@/const/url', () => ({
SESSION_CHAT_TOPIC_URL: (agentId: string, topicId: string) => `/agent/${agentId}/${topicId}`,
}));
vi.mock('@/features/NavPanel/components/NavItem', () => ({
- default: ({ active, title }: { active?: boolean; title?: ReactNode }) => (
- <div data-active={String(active)} data-testid="nav-item">
+ default: ({ active, href, title }: { active?: boolean; href?: string; title?: ReactNode }) => (
+ <div data-active={String(active)} data-href={href} data-testid="nav-item">
{title}
</div>
),
}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => 'team',
+}));
vi.mock('@/routes/(main)/agent/channel/const', () => ({
getPlatformIcon: () => null,
}));
@@ -134,4 +137,20 @@ describe('TopicItem active state', () => {
expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'false');
expect(screen.queryByTestId('topic-thread-list')).not.toBeInTheDocument();
});
+
+ it('prefixes the cmd-click href with the active workspace slug', () => {
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ render(<TopicItem id="tpc_test" title="Topic" />);
+
+ expect(screen.getByTestId('nav-item')).toHaveAttribute(
+ 'data-href',
+ '/team/agent/agt_test/tpc_test',
+ );
+ });
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index 4b6a235ff57..e635c4767d4 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -5,12 +5,14 @@ import { CheckCircle2, Hand, HashIcon, MessageSquareDashed, TriangleAlert } from
import { memo, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import DotsLoading from '@/components/DotsLoading';
import RingLoadingIcon from '@/components/RingLoading';
import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { isDesktop } from '@/const/version';
import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -109,6 +111,7 @@ const TopicItem = memo<TopicItemProps>(
const { t } = useTranslation('topic');
const { isDarkMode } = useTheme();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
// Heterogeneous agents (Claude Code, Codex, …) don't have the chat-style
// topic semantics, so skip the default `#` placeholder icon for their rows.
const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
@@ -121,8 +124,8 @@ const TopicItem = memo<TopicItemProps>(
// Construct href for cmd+click support
const href = useMemo(() => {
if (!activeAgentId || !id) return undefined;
- return SESSION_CHAT_TOPIC_URL(activeAgentId, id);
- }, [activeAgentId, id]);
+ return buildWorkspaceAwarePath(SESSION_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug);
+ }, [activeAgentId, activeWorkspaceSlug, id]);
const [editing, isLoading] = useChatStore((s) => [
id ? s.topicRenamingId === id : false,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..56c6ed3410a
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
@@ -0,0 +1,133 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicItemDropdownMenu } from './useDropdownMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: {
+ success: vi.fn(),
+ },
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('@/components/RenameModal', () => ({
+ openRenameModal: vi.fn(),
+}));
+
+vi.mock('@/const/version', () => ({
+ isDesktop: false,
+}));
+
+vi.mock('@/features/Electron/titlebar/RecentlyViewed/plugins', () => ({
+ pluginRegistry: {
+ parseUrl: vi.fn(),
+ },
+}));
+
+vi.mock('@/features/ShareModal', () => ({
+ openShareModal: vi.fn(),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://example.com',
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ activeAgentId: 'agent-1' }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ autoRenameTopicTitle: vi.fn(),
+ duplicateTopic: vi.fn(),
+ favoriteTopic: vi.fn(),
+ markTopicCompleted: vi.fn(),
+ removeTopic: vi.fn(),
+ unmarkTopicCompleted: vi.fn(),
+ updateTopicTitle: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ addTab: vi.fn() }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ openTopicInNewWindow: vi.fn() }),
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<ReturnType<typeof useTopicItemDropdownMenu>['dropdownMenu']>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('useTopicItemDropdownMenu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables topic management actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
+ );
+ const items = result.current.dropdownMenu();
+
+ for (const key of [
+ 'markCompleted',
+ 'favorite',
+ 'autoRename',
+ 'rename',
+ 'duplicate',
+ 'share',
+ 'delete',
+ ]) {
+ expect(getMenuItem(items, key)).toMatchObject({ disabled: true });
+ }
+
+ expect(getMenuItem(items, 'copySessionId')).not.toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'copyLink')).not.toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index db25e338ce2..f7c28b62d43 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -19,13 +19,14 @@ import {
} from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { openRenameModal } from '@/components/RenameModal';
import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { isDesktop } from '@/const/version';
import { openShareModal } from '@/features/ShareModal';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
@@ -46,7 +47,9 @@ export const useTopicItemDropdownMenu = ({
}: TopicItemDropdownMenuProps) => {
const { t } = useTranslation(['topic', 'common']);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canCreateTopic } = usePermission('create_content');
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
@@ -83,6 +86,7 @@ export const useTopicItemDropdownMenu = ({
return [
{
+ disabled: !canEditTopic,
icon: <Icon icon={isCompleted ? Circle : CheckCircle2} />,
key: 'markCompleted',
label: isCompleted ? t('actions.unmarkCompleted') : t('actions.markCompleted'),
@@ -98,6 +102,7 @@ export const useTopicItemDropdownMenu = ({
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Star} />,
key: 'favorite',
label: fav ? t('actions.unfavorite') : t('actions.favorite'),
@@ -109,6 +114,7 @@ export const useTopicItemDropdownMenu = ({
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Wand2} />,
key: 'autoRename',
label: t('actions.autoRename'),
@@ -117,6 +123,7 @@ export const useTopicItemDropdownMenu = ({
},
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={PencilLine} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -181,6 +188,7 @@ export const useTopicItemDropdownMenu = ({
},
},
{
+ disabled: !canCreateTopic,
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('actions.duplicate'),
@@ -192,6 +200,7 @@ export const useTopicItemDropdownMenu = ({
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Share2} />,
key: 'share',
label: t('share', { ns: 'common' }),
@@ -202,6 +211,7 @@ export const useTopicItemDropdownMenu = ({
},
{
danger: true,
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
@@ -224,6 +234,8 @@ export const useTopicItemDropdownMenu = ({
fav,
isCompleted,
title,
+ canCreateTopic,
+ canEditTopic,
activeAgentId,
appOrigin,
autoRenameTopicTitle,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.test.tsx
new file mode 100644
index 00000000000..622171eb651
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.test.tsx
@@ -0,0 +1,138 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TopicList from './index';
+
+const pushMock = vi.hoisted(() => vi.fn());
+const closeAllTopicsDrawerMock = vi.hoisted(() => vi.fn());
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+}));
+
+vi.mock('@/features/NavPanel/components/EmptyNavItem', () => ({
+ default: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick: () => void;
+ title: string;
+ }) => (
+ <button disabled={disabled} type="button" onClick={disabled ? undefined : onClick}>
+ {title}
+ </button>
+ ),
+}));
+
+vi.mock('@/features/NavPanel/components/SkeletonList', () => ({
+ default: () => <div data-testid="skeleton-list" />,
+}));
+
+vi.mock('@/hooks/useFetchChatTopics', () => ({
+ useFetchChatTopics: vi.fn(),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content') => ({
+ allowed: permissionMock[action],
+ reason: permissionMock[action] ? '' : 'requires member',
+ }),
+}));
+
+vi.mock('@/hooks/useQueryRoute', () => ({
+ useQueryRoute: () => ({
+ push: pushMock,
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (
+ selector: (state: {
+ activeAgentId: string;
+ allTopicsDrawerOpen: boolean;
+ closeAllTopicsDrawer: () => void;
+ isUndefinedTopics: boolean;
+ topicLength: number;
+ }) => unknown,
+ ) =>
+ selector({
+ activeAgentId: 'agent-1',
+ allTopicsDrawerOpen: false,
+ closeAllTopicsDrawer: closeAllTopicsDrawerMock,
+ isUndefinedTopics: false,
+ topicLength: 0,
+ }),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ currentTopicLength: (state: { topicLength: number }) => state.topicLength,
+ isUndefinedTopics: (state: { isUndefinedTopics: boolean }) => state.isUndefinedTopics,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('../AllTopicsDrawer', () => ({
+ default: ({ open }: { open: boolean }) => (
+ <div data-open={String(open)} data-testid="all-topics-drawer" />
+ ),
+}));
+
+vi.mock('../hooks/useAgentTopicGroupMode', () => ({
+ useAgentTopicGroupMode: () => ({ topicGroupMode: 'flat' }),
+}));
+
+vi.mock('../TopicListContent/ByProjectMode', () => ({
+ default: () => <div data-testid="by-project-mode" />,
+}));
+
+vi.mock('../TopicListContent/ByTimeMode', () => ({
+ default: () => <div data-testid="by-time-mode" />,
+}));
+
+vi.mock('../TopicListContent/FlatMode', () => ({
+ default: () => <div data-testid="flat-mode" />,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+}));
+
+describe('Agent topic list', () => {
+ beforeEach(() => {
+ pushMock.mockReset();
+ closeAllTopicsDrawerMock.mockReset();
+ permissionMock.create_content = true;
+ });
+
+ it('opens the agent chat route from the empty start topic entry', () => {
+ render(<TopicList />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopic' }));
+
+ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1');
+ });
+
+ it('disables the empty start topic entry for workspace viewers', () => {
+ permissionMock.create_content = false;
+
+ render(<TopicList />);
+
+ const startButton = screen.getByRole('button', { name: 'actions.addNewTopic' });
+ expect(startButton).toBeDisabled();
+
+ fireEvent.click(startButton);
+
+ expect(pushMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
index 3bef621a781..b589704d662 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
@@ -7,6 +7,7 @@ import urlJoin from 'url-join';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -20,6 +21,7 @@ import FlatMode from '../TopicListContent/FlatMode';
const TopicList = memo(() => {
const { t } = useTranslation('topic');
const router = useQueryRoute();
+ const { allowed: canCreateTopic } = usePermission('create_content');
const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
const isUndefinedTopics = useChatStore((s) => topicSelectors.isUndefinedTopics(s));
@@ -40,8 +42,10 @@ const TopicList = memo(() => {
<>
{topicLength === 0 && (
<EmptyNavItem
+ disabled={!canCreateTopic}
title={t('actions.addNewTopic')}
onClick={() => {
+ if (!canCreateTopic) return;
router.push(urlJoin('/agent', agentId));
}}
/>
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..4ffa06979ce
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
@@ -0,0 +1,56 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useThreadItemDropdownMenu } from './useDropdownMenu';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({
+ allowed: false,
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ removeThread: vi.fn() }),
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<ReturnType<typeof useThreadItemDropdownMenu>>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('useThreadItemDropdownMenu', () => {
+ it('disables thread management actions for workspace viewers', () => {
+ const { result } = renderHook(() =>
+ useThreadItemDropdownMenu({ id: 'thread-1', toggleEditing: vi.fn() }),
+ );
+ const items = result.current();
+
+ expect(getMenuItem(items, 'rename')).toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'delete')).toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
index 986799d602c..83fc3c0a4a2 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -5,6 +5,7 @@ import { PencilLine, Trash } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
interface ThreadItemDropdownMenuProps {
@@ -17,12 +18,14 @@ export const useThreadItemDropdownMenu = ({
toggleEditing,
}: ThreadItemDropdownMenuProps): (() => MenuProps['items']) => {
const { t } = useTranslation(['thread', 'common']);
+ const { allowed: canEditThread } = usePermission('edit_own_content');
const [removeThread] = useChatStore((s) => [s.removeThread]);
return useCallback(() => {
return [
{
+ disabled: !canEditThread,
icon: <Icon icon={PencilLine} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -35,6 +38,7 @@ export const useThreadItemDropdownMenu = ({
},
{
danger: true,
+ disabled: !canEditThread,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
@@ -52,5 +56,5 @@ export const useThreadItemDropdownMenu = ({
},
},
].filter(Boolean) as MenuProps['items'];
- }, [id, removeThread, toggleEditing, t]);
+ }, [id, canEditThread, removeThread, toggleEditing, t]);
};
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
index 4b62faed541..6622b89fcb7 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
@@ -7,6 +7,7 @@ import urlJoin from 'url-join';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -21,6 +22,7 @@ import SearchResult from './SearchResult';
const TopicListContent = memo(() => {
const { t } = useTranslation('topic');
const router = useQueryRoute();
+ const { allowed: canCreateTopic } = usePermission('create_content');
const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
const [agentId, isUndefinedTopics, isInSearchMode] = useChatStore((s) => [
s.activeAgentId,
@@ -41,8 +43,10 @@ const TopicListContent = memo(() => {
<>
{topicLength === 0 && (
<EmptyNavItem
+ disabled={!canCreateTopic}
title={t('actions.addNewTopic')}
onClick={() => {
+ if (!canCreateTopic) return;
router.push(urlJoin('/agent', agentId));
}}
/>
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
index 5f309c796a8..b3de20a80d9 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
@@ -16,6 +16,10 @@ const chatStoreStateMock = vi.hoisted(() => ({
activeTopicId: undefined as string | undefined,
switchTopic: undefined as unknown,
}));
+const workspaceStoreStateMock = vi.hoisted(() => ({
+ activeWorkspaceId: null as string | null,
+ workspaces: [{ id: 'workspace-1', slug: 'team' }],
+}));
vi.mock('@/features/TopicPopupGuard/useTopicPopupsRegistry', () => ({
useFocusTopicPopup: () => focusTopicPopupMock,
@@ -43,6 +47,13 @@ vi.mock('@/store/global', () => ({
}),
}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () =>
+ workspaceStoreStateMock.workspaces.find(
+ (workspace) => workspace.id === workspaceStoreStateMock.activeWorkspaceId,
+ )?.slug ?? null,
+}));
+
describe('useTopicNavigation', () => {
beforeEach(() => {
pathnameMock.mockReset();
@@ -53,6 +64,7 @@ describe('useTopicNavigation', () => {
chatStoreStateMock.activeAgentId = 'agent-1';
chatStoreStateMock.activeTopicId = undefined;
chatStoreStateMock.switchTopic = switchTopicMock;
+ workspaceStoreStateMock.activeWorkspaceId = null;
});
it('focuses the popup and still navigates back to the chat route when the topic is detached', async () => {
@@ -120,4 +132,22 @@ describe('useTopicNavigation', () => {
expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-click');
expect(switchTopicMock).not.toHaveBeenCalled();
});
+
+ it('routes back to chat from a workspace-prefixed profile sub-route', async () => {
+ workspaceStoreStateMock.activeWorkspaceId = 'workspace-1';
+ pathnameMock.mockReturnValue('/team/agent/agent-1/profile');
+ focusTopicPopupMock.mockResolvedValue(false);
+
+ const { result } = renderHook(() => useTopicNavigation());
+
+ expect(result.current.isInAgentSubRoute).toBe(true);
+
+ await act(async () => {
+ await result.current.navigateToTopic('topic-workspace');
+ });
+
+ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-workspace');
+ expect(switchTopicMock).not.toHaveBeenCalled();
+ expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);
+ });
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
index 47b21bed84f..f84a5aea382 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
@@ -1,8 +1,10 @@
import { useCallback } from 'react';
import { useParams } from 'react-router-dom';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';
import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
import { useChatStore } from '@/store/chat';
@@ -23,6 +25,7 @@ export const useTopicNavigation = () => {
const router = useQueryRoute();
const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
const switchTopic = useChatStore((s) => s.switchTopic);
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
const routeAgentId = params.aid ?? activeAgentId;
// URL is the source of truth. Sidebar mounts at `/agent/:aid` so `params.topicId`
// is undefined here — fall back to parsing pathname directly so consumers can compare
@@ -30,11 +33,19 @@ export const useTopicNavigation = () => {
const urlTopicId = params.topicId;
const routeTopicId = params.topicId ?? activeTopicId ?? undefined;
const topicBasePath =
- routeAgentId && routeTopicId ? SESSION_CHAT_TOPIC_URL(routeAgentId, routeTopicId) : undefined;
+ routeAgentId && routeTopicId
+ ? buildWorkspaceAwarePath(
+ SESSION_CHAT_TOPIC_URL(routeAgentId, routeTopicId),
+ activeWorkspaceSlug,
+ )
+ : undefined;
const urlTopicBasePath =
routeAgentId && params.topicId
- ? SESSION_CHAT_TOPIC_URL(routeAgentId, params.topicId)
+ ? buildWorkspaceAwarePath(
+ SESSION_CHAT_TOPIC_URL(routeAgentId, params.topicId),
+ activeWorkspaceSlug,
+ )
: undefined;
const focusTopicPopup = useFocusTopicPopup({ agentId: activeAgentId });
@@ -50,7 +61,9 @@ export const useTopicNavigation = () => {
const isInAgentSubRoute = useCallback(() => {
if (!routeAgentId) return false;
- const agentBasePath = urlTopicBasePath ?? SESSION_CHAT_URL(routeAgentId);
+ const agentBasePath =
+ urlTopicBasePath ??
+ buildWorkspaceAwarePath(SESSION_CHAT_URL(routeAgentId), activeWorkspaceSlug);
// If pathname has more segments after /agent/:aid (or the active topic), it's a sub-route
return (
@@ -58,7 +71,7 @@ export const useTopicNavigation = () => {
pathname !== agentBasePath &&
pathname !== `${agentBasePath}/`
);
- }, [pathname, routeAgentId, urlTopicBasePath]);
+ }, [activeWorkspaceSlug, pathname, routeAgentId, urlTopicBasePath]);
const navigateToTopic = useCallback(
async (topicId?: string, options?: NavigateToTopicOptions) => {
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..2e029f86bfc
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
@@ -0,0 +1,90 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => {
+ return {
+ App: {
+ useApp: () => ({
+ modal: {
+ confirm: vi.fn(),
+ error: vi.fn(),
+ },
+ }),
+ },
+ Upload: ({ children }: { children: ReactNode }) => <>{children}</>,
+ };
+});
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ importTopic: vi.fn(),
+ removeSessionTopics: vi.fn(),
+ removeUnstarredTopic: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ topicPageSize: 20,
+ updateSystemStatus: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ topicPageSize: (s: { topicPageSize: number }) => s.topicPageSize,
+ },
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<typeof useTopicActionsDropdownMenu>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('useTopicActionsDropdownMenu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables topic write management actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() => useTopicActionsDropdownMenu());
+
+ expect(getMenuItem(result.current!, 'import')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current!, 'deleteUnstarred')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current!, 'deleteAll')).toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
index 073830b876a..fdf275cf6c6 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -7,6 +7,7 @@ import { Hash, Import, LucideCheck, Trash } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -30,6 +31,8 @@ export const useTopicActionsDropdownMenu = (
const { t } = useTranslation(['topic', 'common']);
const { modal } = App.useApp();
const { onUploadClose } = options;
+ const { allowed: canCreateTopic } = usePermission('create_content');
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
const [removeUnstarredTopic, removeAllTopic, importTopic] = useChatStore((s) => [
s.removeUnstarredTopic,
@@ -84,10 +87,16 @@ export const useTopicActionsDropdownMenu = (
type: 'divider' as const,
},
{
+ disabled: !canCreateTopic,
icon: <Icon icon={Import} />,
key: 'import',
label: (
- <Upload accept=".json" beforeUpload={handleImport} showUploadList={false}>
+ <Upload
+ accept=".json"
+ beforeUpload={handleImport}
+ disabled={!canCreateTopic}
+ showUploadList={false}
+ >
<div className={cx(hotArea)}>{t('actions.import')}</div>
</Upload>
),
@@ -97,6 +106,7 @@ export const useTopicActionsDropdownMenu = (
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteUnstarred',
label: t('actions.removeUnstarred'),
@@ -112,6 +122,7 @@ export const useTopicActionsDropdownMenu = (
},
{
danger: true,
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteAll',
label: t('actions.removeAll'),
@@ -130,6 +141,8 @@ export const useTopicActionsDropdownMenu = (
topicPageSize,
updateSystemStatus,
handleImport,
+ canCreateTopic,
+ canEditTopic,
onUploadClose,
removeUnstarredTopic,
removeAllTopic,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/index.tsx
index db1183cf640..caa56a4c087 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/index.tsx
@@ -1,15 +1,13 @@
import React, { memo } from 'react';
import { NavPanelPortal } from '@/features/NavPanel';
-import SideBarLayout from '@/features/NavPanel/SideBarLayout';
-import Body from './Body';
-import Header from './Header';
+import AgentSidebarContent from './Content';
const Sidebar = memo(() => {
return (
<NavPanelPortal navKey="agent">
- <SideBarLayout body={<Body />} header={<Header />} />
+ <AgentSidebarContent />
</NavPanelPortal>
);
});
diff --git a/src/routes/(main)/agent/channel/MessengerPromo.tsx b/src/routes/(main)/agent/channel/MessengerPromo.tsx
index 64b4ef9915e..48b69f2f37a 100644
--- a/src/routes/(main)/agent/channel/MessengerPromo.tsx
+++ b/src/routes/(main)/agent/channel/MessengerPromo.tsx
@@ -6,8 +6,8 @@ import { createStaticStyles } from 'antd-style';
import { X } from 'lucide-react';
import React, { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -66,7 +66,7 @@ const ICON_SIZE = 16;
const MessengerPromo = memo(() => {
const { t } = useTranslation('agent');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const isDismissed = useGlobalStore(systemStatusSelectors.isBannerDismissed(MESSENGER_PROMO_ID));
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index 1ae0432a465..0f011f30dd7 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -70,12 +70,13 @@ function buildRules(field: FieldSchema, t: (key: string) => string) {
// --------------- Single field component (memo'd) ---------------
interface SchemaFieldProps {
+ disabled?: boolean;
divider?: boolean;
field: FieldSchema;
parentKey: string;
}
-const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
+const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider, disabled }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
@@ -106,7 +107,15 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
// Array of objects (e.g. user / channel allowlist) — needs Form.List, can't
// be expressed as a single control inside a name-bound FormItem.
if (field.type === 'array' && field.items?.type === 'object') {
- return <ObjectListField divider={divider} field={field} label={label} parentKey={parentKey} />;
+ return (
+ <ObjectListField
+ disabled={disabled}
+ divider={divider}
+ field={field}
+ label={label}
+ parentKey={parentKey}
+ />
+ );
}
let children: React.ReactNode;
@@ -115,19 +124,21 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
children = (
<FormPassword
autoComplete="new-password"
+ disabled={disabled}
placeholder={field.placeholder ? t(field.placeholder) : undefined}
/>
);
break;
}
case 'boolean': {
- children = <Switch />;
+ children = <Switch disabled={disabled} />;
break;
}
case 'number':
case 'integer': {
children = (
<InputNumber
+ disabled={disabled}
max={field.maximum}
min={field.minimum}
placeholder={field.placeholder ? t(field.placeholder) : undefined}
@@ -141,6 +152,7 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
const hasDescriptions = field.enumDescriptions?.some(Boolean);
children = (
<Select
+ disabled={disabled}
placeholder={field.placeholder ? t(field.placeholder) : undefined}
optionRender={
hasDescriptions
@@ -165,14 +177,20 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
);
} else {
children = (
- <FormInput placeholder={field.placeholder ? t(field.placeholder) : t(field.label)} />
+ <FormInput
+ disabled={disabled}
+ placeholder={field.placeholder ? t(field.placeholder) : t(field.label)}
+ />
);
}
break;
}
default: {
children = (
- <FormInput placeholder={field.placeholder ? t(field.placeholder) : t(field.label)} />
+ <FormInput
+ disabled={disabled}
+ placeholder={field.placeholder ? t(field.placeholder) : t(field.label)}
+ />
);
}
}
@@ -198,119 +216,130 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
// --------------- Object-list field (e.g. allowFrom: [{id, name?}]) ---------------
interface ObjectListFieldProps {
+ disabled?: boolean;
divider?: boolean;
field: FieldSchema;
label: React.ReactNode;
parentKey: string;
}
-const ObjectListField = memo<ObjectListFieldProps>(({ field, parentKey, divider, label }) => {
- const { t: _t } = useTranslation('agent');
- const t = _t as (key: string) => string;
-
- // The runtime ignores anything beyond `id`, but the editor renders every
- // declared property so future additions (e.g. a per-row note tag) flow
- // through without code changes here.
- const itemProps = field.items?.type === 'object' ? (field.items.properties ?? []) : [];
-
- // Convention: the schema field key drives the per-list copy keys
- // (`allowFrom` → `channel.allowFromAdd` / `channel.allowFromEmpty`).
- // Avoids overloading FieldSchema with cosmetic strings while keeping each
- // list's "Add user" / "Add channel" wording distinct.
- const addLabel = t(`${field.label}Add` as 'channel.allowFromAdd');
- const emptyLabel = t(`${field.label}Empty` as 'channel.allowFromEmpty');
- const removeLabel = t('channel.allowListRemove');
-
- return (
- <FormItem
- desc={field.description ? t(field.description) : undefined}
- divider={divider}
- label={label}
- minWidth={'max(50%, 400px)'}
- tag={isDev ? field.key : undefined}
- variant="borderless"
- >
- <AntdForm.List initialValue={field.default as unknown[]} name={[parentKey, field.key]}>
- {(rows, { add, remove }) => (
- <Flexbox gap={8} style={{ width: '100%' }}>
- {rows.length === 0 && (
- <Flexbox style={{ fontSize: 12, opacity: 0.6, paddingBlock: 4 }}>
- {emptyLabel}
- </Flexbox>
- )}
- {rows.map(({ key, name }) => (
- <Flexbox horizontal align="center" gap={8} key={key}>
- {itemProps.map((sub) => (
- // `noStyle` skips the antd FormItem chrome that the parent
- // form's 50%-width override targets — without it each cell
- // collapses to half the row, leaving a wide gap between
- // the id and name inputs. The flex:1 wrapper takes over
- // sizing, and `minWidth:0` lets the input actually shrink.
- <div key={sub.key} style={{ flex: 1, minWidth: 0 }}>
- <AntdForm.Item
- noStyle
- name={[name, sub.key]}
- rules={
- sub.required
- ? [{ message: t(sub.label), required: true, whitespace: true }]
- : undefined
- }
- >
- <FormInput
- placeholder={
- sub.placeholder
- ? t(sub.placeholder as 'channel.allowFromIdPlaceholder')
- : t(sub.label)
+const ObjectListField = memo<ObjectListFieldProps>(
+ ({ field, parentKey, divider, label, disabled }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ // The runtime ignores anything beyond `id`, but the editor renders every
+ // declared property so future additions (e.g. a per-row note tag) flow
+ // through without code changes here.
+ const itemProps = field.items?.type === 'object' ? (field.items.properties ?? []) : [];
+
+ // Convention: the schema field key drives the per-list copy keys
+ // (`allowFrom` → `channel.allowFromAdd` / `channel.allowFromEmpty`).
+ // Avoids overloading FieldSchema with cosmetic strings while keeping each
+ // list's "Add user" / "Add channel" wording distinct.
+ const addLabel = t(`${field.label}Add` as 'channel.allowFromAdd');
+ const emptyLabel = t(`${field.label}Empty` as 'channel.allowFromEmpty');
+ const removeLabel = t('channel.allowListRemove');
+
+ return (
+ <FormItem
+ desc={field.description ? t(field.description) : undefined}
+ divider={divider}
+ label={label}
+ minWidth={'max(50%, 400px)'}
+ tag={isDev ? field.key : undefined}
+ variant="borderless"
+ >
+ <AntdForm.List initialValue={field.default as unknown[]} name={[parentKey, field.key]}>
+ {(rows, { add, remove }) => (
+ <Flexbox gap={8} style={{ width: '100%' }}>
+ {rows.length === 0 && (
+ <Flexbox style={{ fontSize: 12, opacity: 0.6, paddingBlock: 4 }}>
+ {emptyLabel}
+ </Flexbox>
+ )}
+ {rows.map(({ key, name }) => (
+ <Flexbox horizontal align="center" gap={8} key={key}>
+ {itemProps.map((sub) => (
+ // `noStyle` skips the antd FormItem chrome that the parent
+ // form's 50%-width override targets — without it each cell
+ // collapses to half the row, leaving a wide gap between
+ // the id and name inputs. The flex:1 wrapper takes over
+ // sizing, and `minWidth:0` lets the input actually shrink.
+ <div key={sub.key} style={{ flex: 1, minWidth: 0 }}>
+ <AntdForm.Item
+ noStyle
+ name={[name, sub.key]}
+ rules={
+ sub.required
+ ? [{ message: t(sub.label), required: true, whitespace: true }]
+ : undefined
}
- />
- </AntdForm.Item>
- </div>
- ))}
- <Button
- aria-label={removeLabel}
- icon={<Trash2 size={14} />}
- type="text"
- onClick={() => remove(name)}
- />
- </Flexbox>
- ))}
- <Button
- block
- icon={<Plus size={14} />}
- type="dashed"
- onClick={() => add({ id: '', name: '' })}
- >
- {addLabel}
- </Button>
- </Flexbox>
- )}
- </AntdForm.List>
- </FormItem>
- );
-});
+ >
+ <FormInput
+ disabled={disabled}
+ placeholder={
+ sub.placeholder
+ ? t(sub.placeholder as 'channel.allowFromIdPlaceholder')
+ : t(sub.label)
+ }
+ />
+ </AntdForm.Item>
+ </div>
+ ))}
+ <Button
+ aria-label={removeLabel}
+ disabled={disabled}
+ icon={<Trash2 size={14} />}
+ type="text"
+ onClick={() => remove(name)}
+ />
+ </Flexbox>
+ ))}
+ <Button
+ block
+ disabled={disabled}
+ icon={<Plus size={14} />}
+ type="dashed"
+ onClick={() => add({ id: '', name: '' })}
+ >
+ {addLabel}
+ </Button>
+ </Flexbox>
+ )}
+ </AntdForm.List>
+ </FormItem>
+ );
+ },
+);
// --------------- ApplicationId field (standalone, not nested) ---------------
-const ApplicationIdField = memo<{ divider?: boolean; field: FieldSchema }>(({ field, divider }) => {
- const { t: _t } = useTranslation('agent');
- const t = _t as (key: string) => string;
-
- return (
- <FormItem
- desc={field.description ? t(field.description) : undefined}
- divider={divider}
- initialValue={field.default}
- label={t(field.label)}
- minWidth={'max(50%, 400px)'}
- name="applicationId"
- rules={field.required ? [{ message: t(field.label), required: true }] : undefined}
- tag={isDev ? 'applicationId' : undefined}
- variant="borderless"
- >
- <FormInput placeholder={field.placeholder ? t(field.placeholder) : t(field.label)} />
- </FormItem>
- );
-});
+const ApplicationIdField = memo<{ disabled?: boolean; divider?: boolean; field: FieldSchema }>(
+ ({ field, divider, disabled }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ return (
+ <FormItem
+ desc={field.description ? t(field.description) : undefined}
+ divider={divider}
+ initialValue={field.default}
+ label={t(field.label)}
+ minWidth={'max(50%, 400px)'}
+ name="applicationId"
+ rules={field.required ? [{ message: t(field.label), required: true }] : undefined}
+ tag={isDev ? 'applicationId' : undefined}
+ variant="borderless"
+ >
+ <FormInput
+ disabled={disabled}
+ placeholder={field.placeholder ? t(field.placeholder) : t(field.label)}
+ />
+ </FormItem>
+ );
+ },
+);
// --------------- Helper: flatten fields from schema ---------------
@@ -345,6 +374,7 @@ interface BodyProps {
credentials: Record<string, string>;
settings?: Record<string, unknown> | null;
};
+ disabled?: boolean;
form: FormInstance<ChannelFormValues>;
hasConfig?: boolean;
onAuthenticated?: (params: {
@@ -354,122 +384,145 @@ interface BodyProps {
platformDef: SerializedPlatformDefinition;
}
-const Body = memo<BodyProps>(({ platformDef, form, hasConfig, currentConfig, onAuthenticated }) => {
- const { t: _t } = useTranslation('agent');
- const t = _t as (key: string) => string;
+const Body = memo<BodyProps>(
+ ({ platformDef, form, hasConfig, currentConfig, onAuthenticated, disabled }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
- const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
- const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
-
- const credentialFields = useMemo(
- () => getFields(platformDef.schema, 'credentials'),
- [platformDef.schema],
- );
+ const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
+ const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
- const settingsFields = useMemo(
- () => getFields(platformDef.schema, 'settings'),
- [platformDef.schema],
- );
+ const credentialFields = useMemo(
+ () => getFields(platformDef.schema, 'credentials'),
+ [platformDef.schema],
+ );
- // Auto-expand the settings group on mount when an already-saved bot is
- // missing its operator User ID, so operators land directly on the field
- // the Footer alert is asking them to fill in. Driven off the saved value
- // (not the form watch) because `defaultActive` is mount-only — the form
- // hasn't hydrated yet at this point — and skipped on platforms without
- // a `userId` field in their schema (e.g. WeChat).
- const userIdInitiallyMissing = useMemo(() => {
- if (!hasConfig) return false;
- const hasUserIdField = settingsFields.some((f) => f.key === 'userId');
- if (!hasUserIdField) return false;
- const savedUserId = currentConfig?.settings?.userId;
- return !(typeof savedUserId === 'string' && savedUserId.trim());
- }, [hasConfig, settingsFields, currentConfig?.settings]);
- const [settingsActive, setSettingsActive] = useState(userIdInitiallyMissing);
-
- const handleResetSettings = useCallback(() => {
- form.setFieldsValue({
- settings: extractSettingsDefaults(platformDef.schema) as Record<string, {} | undefined>,
- });
- }, [form, platformDef.schema]);
+ const settingsFields = useMemo(
+ () => getFields(platformDef.schema, 'settings'),
+ [platformDef.schema],
+ );
- return (
- <Form
- className={styles.form}
- form={form}
- gap={0}
- itemMinWidth={'max(50%, 400px)'}
- requiredMark={false}
- style={{ maxWidth: 1024, padding: '16px 0', width: '100%' }}
- variant={'borderless'}
- >
- {CustomCredentialBody ? (
- <CustomCredentialBody
- currentConfig={currentConfig}
- hasConfig={hasConfig}
- onAuthenticated={onAuthenticated}
- />
- ) : (
- <>
- {/* Render top-level sections in schema order so each platform controls
+ // Auto-expand the settings group on mount when an already-saved bot is
+ // missing its operator User ID, so operators land directly on the field
+ // the Footer alert is asking them to fill in. Driven off the saved value
+ // (not the form watch) because `defaultActive` is mount-only — the form
+ // hasn't hydrated yet at this point — and skipped on platforms without
+ // a `userId` field in their schema (e.g. WeChat).
+ const userIdInitiallyMissing = useMemo(() => {
+ if (!hasConfig) return false;
+ const hasUserIdField = settingsFields.some((f) => f.key === 'userId');
+ if (!hasUserIdField) return false;
+ const savedUserId = currentConfig?.settings?.userId;
+ return !(typeof savedUserId === 'string' && savedUserId.trim());
+ }, [hasConfig, settingsFields, currentConfig?.settings]);
+ const [settingsActive, setSettingsActive] = useState(userIdInitiallyMissing);
+
+ const handleResetSettings = useCallback(() => {
+ form.setFieldsValue({
+ settings: extractSettingsDefaults(platformDef.schema) as Record<string, {} | undefined>,
+ });
+ }, [form, platformDef.schema]);
+
+ return (
+ <Form
+ className={styles.form}
+ form={form}
+ gap={0}
+ itemMinWidth={'max(50%, 400px)'}
+ requiredMark={false}
+ style={{ maxWidth: 1024, padding: '16px 0', width: '100%' }}
+ variant={'borderless'}
+ >
+ {CustomCredentialBody ? (
+ <CustomCredentialBody
+ currentConfig={currentConfig}
+ disabled={disabled}
+ hasConfig={hasConfig}
+ onAuthenticated={onAuthenticated}
+ />
+ ) : (
+ <>
+ {/* Render top-level sections in schema order so each platform controls
its own field ordering. LINE places `credentials` before `applicationId`
because the operator must enter the channel access token before the
"Fetch from LINE" button (rendered after applicationId) can auto-fill
the destination user ID; Discord/Slack/QQ/Feishu place `applicationId`
first as a primary identifier. */}
- {platformDef.schema
- .filter((section) => section.key === 'applicationId' || section.key === 'credentials')
- .map((section, sectionIndex) => {
- const needsDivider = sectionIndex > 0;
- if (section.key === 'applicationId') {
+ {platformDef.schema
+ .filter((section) => section.key === 'applicationId' || section.key === 'credentials')
+ .map((section, sectionIndex) => {
+ const needsDivider = sectionIndex > 0;
+ if (section.key === 'applicationId') {
+ return (
+ <ApplicationIdField
+ disabled={disabled}
+ divider={needsDivider}
+ field={section}
+ key="applicationId"
+ />
+ );
+ }
return (
- <ApplicationIdField divider={needsDivider} field={section} key="applicationId" />
+ <Fragment key="credentials">
+ {credentialFields.map((field, i) => (
+ <SchemaField
+ disabled={disabled}
+ divider={needsDivider || i !== 0}
+ field={field}
+ key={field.key}
+ parentKey="credentials"
+ />
+ ))}
+ </Fragment>
);
- }
- return (
- <Fragment key="credentials">
- {credentialFields.map((field, i) => (
- <SchemaField
- divider={needsDivider || i !== 0}
- field={field}
- key={field.key}
- parentKey="credentials"
- />
- ))}
- </Fragment>
- );
- })}
- {/* Platform-specific helpers (e.g. LINE's "Fetch from LINE" button)
+ })}
+ {/* Platform-specific helpers (e.g. LINE's "Fetch from LINE" button)
render after the credential + applicationId block so the button
sits next to the field it acts on. */}
- {CredentialExtras && <CredentialExtras />}
- </>
- )}
- {settingsFields.length > 0 && (
- <FormGroup
- collapsible
- defaultActive={userIdInitiallyMissing}
- keyValue={`settings-${platformDef.id}`}
- style={{ marginBlockStart: 16 }}
- title={<SettingsTitle schema={platformDef.schema} />}
- variant="borderless"
- extra={
- settingsActive ? (
- <Popconfirm title={t('channel.settingsResetConfirm')} onConfirm={handleResetSettings}>
- <Button icon={<RotateCcw size={14} />} size="small" type="default">
- {t('channel.settingsResetDefault')}
- </Button>
- </Popconfirm>
- ) : undefined
- }
- onCollapse={setSettingsActive}
- >
- {settingsFields.map((field, i) => (
- <SchemaField divider={i !== 0} field={field} key={field.key} parentKey="settings" />
- ))}
- </FormGroup>
- )}
- </Form>
- );
-});
+ {CredentialExtras && <CredentialExtras disabled={disabled} />}
+ </>
+ )}
+ {settingsFields.length > 0 && (
+ <FormGroup
+ collapsible
+ defaultActive={userIdInitiallyMissing}
+ keyValue={`settings-${platformDef.id}`}
+ style={{ marginBlockStart: 16 }}
+ title={<SettingsTitle schema={platformDef.schema} />}
+ variant="borderless"
+ extra={
+ settingsActive ? (
+ <Popconfirm
+ title={t('channel.settingsResetConfirm')}
+ onConfirm={disabled ? undefined : handleResetSettings}
+ >
+ <Button
+ disabled={disabled}
+ icon={<RotateCcw size={14} />}
+ size="small"
+ type="default"
+ >
+ {t('channel.settingsResetDefault')}
+ </Button>
+ </Popconfirm>
+ ) : undefined
+ }
+ onCollapse={setSettingsActive}
+ >
+ {settingsFields.map((field, i) => (
+ <SchemaField
+ disabled={disabled}
+ divider={i !== 0}
+ field={field}
+ key={field.key}
+ parentKey="settings"
+ />
+ ))}
+ </FormGroup>
+ )}
+ </Form>
+ );
+ },
+);
export default Body;
diff --git a/src/routes/(main)/agent/channel/detail/Footer.tsx b/src/routes/(main)/agent/channel/detail/Footer.tsx
index 5ca79fb1a3e..c11c3804e58 100644
--- a/src/routes/(main)/agent/channel/detail/Footer.tsx
+++ b/src/routes/(main)/agent/channel/detail/Footer.tsx
@@ -51,6 +51,7 @@ interface FooterProps {
connecting: boolean;
connectResult?: TestResult;
currentConfig?: CurrentConfig;
+ disabled?: boolean;
form: FormInstance<ChannelFormValues>;
hasConfig: boolean;
onCopied: () => void;
@@ -72,6 +73,7 @@ const Footer = memo<FooterProps>(
hasConfig,
connectResult,
connecting,
+ disabled,
saveResult,
saving,
testing,
@@ -127,7 +129,7 @@ const Footer = memo<FooterProps>(
{hasConfig ? (
<Button
danger
- disabled={saving || connecting}
+ disabled={disabled || saving || connecting}
icon={<Trash2 size={16} />}
type="primary"
onClick={onDelete}
@@ -140,7 +142,7 @@ const Footer = memo<FooterProps>(
<Flexbox horizontal gap={12}>
{hasConfig && (
<Button
- disabled={saving || connecting}
+ disabled={disabled || saving || connecting}
icon={<RefreshCw size={16} />}
loading={testing}
onClick={onTestConnection}
@@ -149,6 +151,7 @@ const Footer = memo<FooterProps>(
</Button>
)}
<Button
+ disabled={disabled}
icon={<Save size={16} />}
loading={saving || connecting}
type="primary"
diff --git a/src/routes/(main)/agent/channel/detail/Header.tsx b/src/routes/(main)/agent/channel/detail/Header.tsx
index 9a45c1d4450..ae1739c324b 100644
--- a/src/routes/(main)/agent/channel/detail/Header.tsx
+++ b/src/routes/(main)/agent/channel/detail/Header.tsx
@@ -14,6 +14,7 @@ import { getPlatformIcon } from '../const';
interface HeaderProps {
currentConfig?: { enabled: boolean };
+ disabled?: boolean;
enabledValue?: boolean;
onRefreshStatus?: () => void;
onToggleEnable: (enabled: boolean) => void;
@@ -35,6 +36,7 @@ const Header = memo<HeaderProps>(
({
platformDef,
currentConfig,
+ disabled,
enabledValue,
onRefreshStatus,
onToggleEnable,
@@ -97,6 +99,7 @@ const Header = memo<HeaderProps>(
)}
{onRefreshStatus && currentConfig?.enabled && (
<ActionIcon
+ disabled={disabled}
icon={RefreshCw}
loading={refreshingStatus}
size={'small'}
@@ -129,6 +132,7 @@ const Header = memo<HeaderProps>(
</span>
<Switch
checked={effectiveEnabled}
+ disabled={disabled}
loading={toggleLoading}
onChange={onToggleEnable}
/>
diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsx
index bd166db4ea9..7118d2f5c19 100644
--- a/src/routes/(main)/agent/channel/detail/index.tsx
+++ b/src/routes/(main)/agent/channel/detail/index.tsx
@@ -6,6 +6,7 @@ import { createStaticStyles } from 'antd-style';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
import { agentBotProviderService } from '@/services/agentBotProvider';
import { useAgentStore } from '@/store/agent';
@@ -64,15 +65,18 @@ export interface TestResult {
interface PlatformDetailProps {
agentId: string;
currentConfig?: CurrentConfig;
+ disabled?: boolean;
platformDef: SerializedPlatformDefinition;
runtimeStatus?: BotRuntimeStatus;
}
const PlatformDetail = memo<PlatformDetailProps>(
- ({ platformDef, agentId, currentConfig, runtimeStatus }) => {
+ ({ platformDef, agentId, currentConfig, disabled, runtimeStatus }) => {
const { t } = useTranslation('agent');
const { message: msg } = App.useApp();
const [form] = Form.useForm<ChannelFormValues>();
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const readOnly = disabled || !canEdit;
const [
createBotProvider,
@@ -212,6 +216,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
);
const handleRefreshStatus = useCallback(async () => {
+ if (readOnly) return;
if (!currentConfig?.enabled) return;
setRefreshingStatus(true);
try {
@@ -232,7 +237,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
} finally {
setRefreshingStatus(false);
}
- }, [agentId, currentConfig, mapRuntimeStatusToResult, msg, refreshBotRuntimeStatus]);
+ }, [agentId, readOnly, currentConfig, mapRuntimeStatusToResult, msg, refreshBotRuntimeStatus]);
// Reset form and status when switching platforms. Must NOT depend on
// runtimeStatus — otherwise background status refreshes would wipe
@@ -292,6 +297,8 @@ const PlatformDetail = memo<PlatformDetailProps>(
}, [currentConfig, stopConnectPolling, syncRuntimeStatus]);
const handleSave = useCallback(async () => {
+ if (readOnly) return;
+
try {
await form.validateFields();
const values = form.getFieldsValue(true) as ChannelFormValues;
@@ -363,10 +370,13 @@ const PlatformDetail = memo<PlatformDetailProps>(
createBotProvider,
updateBotProvider,
connectCurrentBot,
+ readOnly,
]);
const handleExternalAuth = useCallback(
async (params: { applicationId: string; credentials: Record<string, string> }) => {
+ if (readOnly) return;
+
setSaving(true);
setSaveResult(undefined);
setConnectResult(undefined);
@@ -413,12 +423,14 @@ const PlatformDetail = memo<PlatformDetailProps>(
createBotProvider,
updateBotProvider,
connectCurrentBot,
+ readOnly,
msg,
t,
],
);
const handleDelete = useCallback(async () => {
+ if (readOnly) return;
if (!currentConfig) return;
confirmModal({
@@ -435,10 +447,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
},
title: t('channel.deleteConfirm'),
});
- }, [currentConfig, agentId, deleteBotProvider, msg, t, form]);
+ }, [readOnly, currentConfig, agentId, deleteBotProvider, msg, t, form]);
const handleToggleEnable = useCallback(
async (enabled: boolean) => {
+ if (readOnly) return;
if (!currentConfig) return;
try {
setPendingEnabled(enabled);
@@ -454,10 +467,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
msg.error(t('channel.updateFailed'));
}
},
- [currentConfig, agentId, updateBotProvider, connectCurrentBot, msg, t],
+ [readOnly, currentConfig, agentId, updateBotProvider, connectCurrentBot, msg, t],
);
const handleTestConnection = useCallback(async () => {
+ if (readOnly) return;
if (!currentConfig) {
msg.warning(t('channel.saveFirstWarning'));
return;
@@ -479,13 +493,14 @@ const PlatformDetail = memo<PlatformDetailProps>(
} finally {
setTesting(false);
}
- }, [currentConfig, platformDef.id, testConnection, msg, t]);
+ }, [readOnly, currentConfig, platformDef.id, testConnection, msg, t]);
return (
<ChannelPostSaveContext value={postSaveRegistry}>
<main className={styles.main}>
<Header
currentConfig={currentConfig}
+ disabled={readOnly}
enabledValue={pendingEnabled}
platformDef={platformDef}
refreshingStatus={refreshingStatus}
@@ -496,6 +511,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
/>
<Body
currentConfig={currentConfig}
+ disabled={readOnly}
form={form}
hasConfig={!!currentConfig}
platformDef={platformDef}
@@ -505,6 +521,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
connectResult={connectResult}
connecting={connecting}
currentConfig={currentConfig}
+ disabled={readOnly}
form={form}
hasConfig={!!currentConfig}
platformDef={platformDef}
diff --git a/src/routes/(main)/agent/channel/detail/permission.test.tsx b/src/routes/(main)/agent/channel/detail/permission.test.tsx
new file mode 100644
index 00000000000..149e9cd7cfa
--- /dev/null
+++ b/src/routes/(main)/agent/channel/detail/permission.test.tsx
@@ -0,0 +1,225 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import { Form } from 'antd';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+
+import Body from './Body';
+import Footer from './Footer';
+import Header from './Header';
+
+vi.mock('react-i18next', () => ({
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://example.test',
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button aria-label={title} disabled={disabled} onClick={onClick}>
+ {title}
+ </button>
+ ),
+ Alert: ({ message, title }: { message?: ReactNode; title?: ReactNode }) => (
+ <div>{title || message}</div>
+ ),
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ Form: ({
+ children,
+ form,
+ }: {
+ children?: ReactNode;
+ form?: ReturnType<typeof Form.useForm>[0];
+ }) => <Form form={form}>{children}</Form>,
+ FormGroup: ({
+ children,
+ extra,
+ title,
+ }: {
+ children?: ReactNode;
+ extra?: ReactNode;
+ title?: ReactNode;
+ }) => (
+ <section>
+ <h2>{title}</h2>
+ {extra}
+ {children}
+ </section>
+ ),
+ FormItem: ({
+ children,
+ label,
+ name,
+ rules,
+ valuePropName,
+ }: {
+ children?: ReactNode;
+ label?: ReactNode;
+ name?: string | string[];
+ rules?: unknown[];
+ valuePropName?: string;
+ }) => (
+ <Form.Item label={label} name={name} rules={rules as never} valuePropName={valuePropName}>
+ {children}
+ </Form.Item>
+ ),
+ Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('@/components/FormInput', () => ({
+ FormInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+ FormPassword: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+vi.mock('@/components/InfoTooltip', () => ({
+ default: ({ title }: { title?: string }) => <span>{title}</span>,
+}));
+
+vi.mock('../const', () => ({
+ getPlatformIcon: () => null,
+}));
+
+const platformDef = {
+ documentation: {},
+ id: 'discord',
+ name: 'Discord',
+ schema: [
+ {
+ description: 'channel.applicationIdHint',
+ key: 'applicationId',
+ label: 'channel.applicationId',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'credentials',
+ label: 'channel.credentials',
+ properties: [
+ {
+ key: 'botToken',
+ label: 'channel.botToken',
+ required: true,
+ type: 'password',
+ },
+ ],
+ type: 'object',
+ },
+ {
+ key: 'settings',
+ label: 'channel.settings',
+ properties: [
+ {
+ default: 2000,
+ key: 'charLimit',
+ label: 'channel.charLimit',
+ type: 'integer',
+ },
+ {
+ key: 'userId',
+ label: 'channel.userId',
+ type: 'string',
+ },
+ ],
+ type: 'object',
+ },
+ ],
+} as SerializedPlatformDefinition;
+
+const currentConfig = {
+ applicationId: 'app-id',
+ credentials: { botToken: 'token' },
+ enabled: true,
+ id: 'provider-id',
+ platform: 'discord',
+ settings: { charLimit: 2000 },
+};
+
+const BodyHarness = ({ disabled }: { disabled?: boolean }) => {
+ const [form] = Form.useForm();
+
+ return (
+ <Body
+ hasConfig
+ currentConfig={currentConfig}
+ disabled={disabled}
+ form={form}
+ platformDef={platformDef}
+ />
+ );
+};
+
+const FooterHarness = ({ disabled }: { disabled?: boolean }) => {
+ const [form] = Form.useForm();
+
+ return (
+ <Footer
+ hasConfig
+ connecting={false}
+ currentConfig={currentConfig}
+ disabled={disabled}
+ form={form}
+ platformDef={platformDef}
+ saving={false}
+ testing={false}
+ onCopied={vi.fn()}
+ onDelete={vi.fn()}
+ onSave={vi.fn()}
+ onTestConnection={vi.fn()}
+ />
+ );
+};
+
+describe('Agent channel permission gates', () => {
+ it('renders channel credentials as read-only when editing is denied', () => {
+ render(<BodyHarness disabled />);
+
+ expect(screen.getByRole('textbox', { name: 'channel.applicationId' })).toBeDisabled();
+ expect(screen.getByLabelText('channel.botToken')).toBeDisabled();
+ expect(screen.getByRole('spinbutton', { name: 'channel.charLimit' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.settingsResetDefault' })).toBeDisabled();
+ });
+
+ it('disables mutating channel actions when editing is denied', () => {
+ render(<FooterHarness disabled />);
+
+ expect(screen.getByRole('button', { name: 'channel.removeChannel' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.testConnection' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.save' })).toBeDisabled();
+ });
+
+ it('disables the channel enable switch and status refresh when editing is denied', () => {
+ render(
+ <Header
+ disabled
+ currentConfig={currentConfig}
+ platformDef={platformDef}
+ runtimeStatus="connected"
+ onRefreshStatus={vi.fn()}
+ onToggleEnable={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole('switch')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.refreshStatus' })).toBeDisabled();
+ });
+});
diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsx
index b73a78a79c0..3bf16c71ac5 100644
--- a/src/routes/(main)/agent/channel/index.tsx
+++ b/src/routes/(main)/agent/channel/index.tsx
@@ -7,6 +7,7 @@ import { useParams } from 'react-router-dom';
import Loading from '@/components/Loading/BrandTextLoading';
import NavHeader from '@/features/NavHeader';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
@@ -31,6 +32,7 @@ const styles = createStaticStyles(({ css }) => ({
const ChannelPage = memo(() => {
const { aid } = useParams<{ aid?: string }>();
const [activeProviderId, setActiveProviderId] = useState<string>('');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const { data: platforms, isLoading: platformsLoading } = useAgentStore((s) =>
s.useFetchPlatformDefinitions(),
@@ -45,8 +47,9 @@ const ChannelPage = memo(() => {
// from cached statuses immediately; SWR revalidates once Redis is updated.
useEffect(() => {
if (!aid) return;
+ if (!canEdit) return;
triggerRefreshAllBotStatuses(aid);
- }, [aid, triggerRefreshAllBotStatuses]);
+ }, [aid, canEdit, triggerRefreshAllBotStatuses]);
const isLoading = platformsLoading || providersLoading;
@@ -104,6 +107,7 @@ const ChannelPage = memo(() => {
<PlatformList
activeId={effectiveActiveId}
agentId={aid}
+ disabled={!canEdit}
platforms={allPlatforms}
providers={providers}
runtimeStatuses={platformRuntimeStatuses}
@@ -115,6 +119,7 @@ const ChannelPage = memo(() => {
<PlatformDetail
agentId={aid}
currentConfig={currentConfig}
+ disabled={!canEdit}
platformDef={activePlatformDef}
runtimeStatus={platformRuntimeStatuses.get(activePlatformDef.id)}
/>
diff --git a/src/routes/(main)/agent/channel/list.tsx b/src/routes/(main)/agent/channel/list.tsx
index 158966f7a0b..5e81d2a09f8 100644
--- a/src/routes/(main)/agent/channel/list.tsx
+++ b/src/routes/(main)/agent/channel/list.tsx
@@ -79,6 +79,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface PlatformListProps {
activeId: string;
agentId: string;
+ disabled?: boolean;
onSelect: (id: string) => void;
platforms: ChannelPlatformDefinition[];
providers?: BotProviderItem[];
@@ -86,7 +87,7 @@ interface PlatformListProps {
}
const PlatformList = memo<PlatformListProps>(
- ({ platforms, activeId, agentId, onSelect, providers, runtimeStatuses }) => {
+ ({ platforms, activeId, agentId, disabled, onSelect, providers, runtimeStatuses }) => {
const { t } = useTranslation('agent');
const theme = useTheme();
const { message } = App.useApp();
@@ -102,12 +103,17 @@ const PlatformList = memo<PlatformListProps>(
}, [providers, agentId]);
const handleImport = useCallback(() => {
+ if (disabled) return;
fileInputRef.current?.click();
- }, []);
+ }, [disabled]);
const handleFileChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
+ if (disabled) {
+ e.target.value = '';
+ return;
+ }
if (!file) return;
try {
@@ -150,10 +156,11 @@ const PlatformList = memo<PlatformListProps>(
e.target.value = '';
}
},
- [agentId, connectBot, createBotProvider, message, t],
+ [agentId, connectBot, createBotProvider, disabled, message, t],
);
const handleDeleteAll = useCallback(() => {
+ if (disabled) return;
if (!providers?.length) return;
confirmModal({
content: t('channel.deleteAllConfirmDesc'),
@@ -169,7 +176,7 @@ const PlatformList = memo<PlatformListProps>(
},
title: t('channel.deleteAllConfirm'),
});
- }, [agentId, deleteAllBotProviders, message, providers, t]);
+ }, [agentId, deleteAllBotProviders, disabled, message, providers, t]);
const hasProviders = !!providers?.length;
const menuItems: MenuProps['items'] = [
@@ -183,13 +190,14 @@ const PlatformList = memo<PlatformListProps>(
{
icon: <Icon icon={Upload} size={'small'} />,
key: 'import',
+ disabled,
label: t('channel.importConfig'),
onClick: handleImport,
},
{ type: 'divider' },
{
danger: true,
- disabled: !hasProviders,
+ disabled: disabled || !hasProviders,
icon: <Icon icon={Trash2} size={'small'} />,
key: 'deleteAll',
label: t('channel.deleteAllChannels'),
diff --git a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
index 1b59cd8fd66..442f436cf21 100644
--- a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
+++ b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
@@ -7,7 +7,9 @@ import { useTranslation } from 'react-i18next';
import { useAgentStore } from '@/store/agent';
-const CredentialExtras = memo(() => {
+import type { PlatformCredentialExtrasProps } from '../types';
+
+const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
const { message } = App.useApp();
@@ -20,6 +22,8 @@ const CredentialExtras = memo(() => {
const lineFetchBotInfo = useAgentStore((s) => s.lineFetchBotInfo);
const handleFetch = async () => {
+ if (disabled) return;
+
const token = channelAccessToken?.trim();
if (!token) {
message.warning(t('channel.line.fetchBotInfoMissingToken'));
@@ -47,7 +51,7 @@ const CredentialExtras = memo(() => {
return (
<Button
- disabled={!channelAccessToken?.trim()}
+ disabled={disabled || !channelAccessToken?.trim()}
icon={<Download size={14} />}
loading={loading}
size="small"
diff --git a/src/routes/(main)/agent/channel/platform/registry.ts b/src/routes/(main)/agent/channel/platform/registry.ts
index e3cd1a11a8a..ad58b6a6310 100644
--- a/src/routes/(main)/agent/channel/platform/registry.ts
+++ b/src/routes/(main)/agent/channel/platform/registry.ts
@@ -2,7 +2,7 @@ import type { ComponentType } from 'react';
import ImessageCredentialExtras from './imessage/CredentialExtras';
import LineCredentialExtras from './line/CredentialExtras';
-import type { PlatformCredentialBodyProps } from './types';
+import type { PlatformCredentialBodyProps, PlatformCredentialExtrasProps } from './types';
import WechatCredentialBody from './wechat/CredentialBody';
export const platformCredentialBodyMap: Record<
@@ -19,7 +19,10 @@ export const platformCredentialBodyMap: Record<
* /v2/bot/info" button — anything that augments the auto-generated form
* without replacing it wholesale.
*/
-export const platformCredentialExtrasMap: Record<string, ComponentType> = {
+export const platformCredentialExtrasMap: Record<
+ string,
+ ComponentType<PlatformCredentialExtrasProps>
+> = {
imessage: ImessageCredentialExtras,
line: LineCredentialExtras,
};
diff --git a/src/routes/(main)/agent/channel/platform/types.ts b/src/routes/(main)/agent/channel/platform/types.ts
index 0f00101b6fd..fb7a70f026e 100644
--- a/src/routes/(main)/agent/channel/platform/types.ts
+++ b/src/routes/(main)/agent/channel/platform/types.ts
@@ -3,9 +3,14 @@ export interface PlatformCredentialBodyProps {
applicationId: string;
credentials: Record<string, string>;
};
+ disabled?: boolean;
hasConfig?: boolean;
onAuthenticated?: (params: {
applicationId: string;
credentials: Record<string, string>;
}) => void;
}
+
+export interface PlatformCredentialExtrasProps {
+ disabled?: boolean;
+}
diff --git a/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
index ef3807d169e..ba8f2253782 100644
--- a/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
+++ b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
@@ -47,11 +47,12 @@ interface WechatConnectedInfoProps {
applicationId: string;
credentials: Record<string, string>;
};
+ disabled?: boolean;
onQrAuthenticated?: (credentials: { botId: string; botToken: string; userId: string }) => void;
}
const WechatConnectedInfo = memo<WechatConnectedInfoProps>(
- ({ currentConfig, onQrAuthenticated }) => {
+ ({ currentConfig, disabled, onQrAuthenticated }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
@@ -72,6 +73,7 @@ const WechatConnectedInfo = memo<WechatConnectedInfoProps>(
<QrCodeAuth
buttonLabel={t('channel.wechatRebind')}
buttonType="default"
+ disabled={disabled}
showTips={false}
onAuthenticated={onQrAuthenticated}
/>
diff --git a/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx b/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx
index dcd938eaeb0..4ec3bf4e988 100644
--- a/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx
+++ b/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx
@@ -7,7 +7,7 @@ import ConnectedInfo from './ConnectedInfo';
import QrCodeAuth from './QrCodeAuth';
const CredentialBody = memo<PlatformCredentialBodyProps>(
- ({ currentConfig, hasConfig, onAuthenticated }) => {
+ ({ currentConfig, disabled, hasConfig, onAuthenticated }) => {
const handleQrAuthenticated = useCallback(
(creds: { botId: string; botToken: string; userId: string }) => {
const botToken = creds.botToken?.trim();
@@ -28,14 +28,18 @@ const CredentialBody = memo<PlatformCredentialBodyProps>(
if (hasConfig && currentConfig) {
return (
- <ConnectedInfo currentConfig={currentConfig} onQrAuthenticated={handleQrAuthenticated} />
+ <ConnectedInfo
+ currentConfig={currentConfig}
+ disabled={disabled}
+ onQrAuthenticated={handleQrAuthenticated}
+ />
);
}
if (onAuthenticated) {
return (
<div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>
- <QrCodeAuth onAuthenticated={handleQrAuthenticated} />
+ <QrCodeAuth disabled={disabled} onAuthenticated={handleQrAuthenticated} />
</div>
);
}
diff --git a/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx b/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
index fa96ecf93e8..e2440d842b3 100644
--- a/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
+++ b/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
@@ -13,12 +13,13 @@ const QR_POLL_INTERVAL_MS = 2000;
interface QrCodeAuthProps {
buttonLabel?: string;
buttonType?: ButtonProps['type'];
+ disabled?: boolean;
onAuthenticated: (credentials: { botId: string; botToken: string; userId: string }) => void;
showTips?: boolean;
}
const QrCodeAuth = memo<QrCodeAuthProps>(
- ({ buttonLabel, buttonType = 'primary', onAuthenticated, showTips = true }) => {
+ ({ buttonLabel, buttonType = 'primary', disabled, onAuthenticated, showTips = true }) => {
const { t } = useTranslation('agent');
const [open, setOpen] = useState(false);
const [qrImgUrl, setQrImgUrl] = useState<string>();
@@ -93,9 +94,10 @@ const QrCodeAuth = memo<QrCodeAuthProps>(
}, [onAuthenticated, stopPolling, t]);
const handleOpen = useCallback(() => {
+ if (disabled) return;
setOpen(true);
startQrFlow();
- }, [startQrFlow]);
+ }, [disabled, startQrFlow]);
const handleClose = useCallback(() => {
stopPolling();
@@ -112,7 +114,12 @@ const QrCodeAuth = memo<QrCodeAuthProps>(
return (
<>
<div style={{ alignItems: 'center', display: 'flex', flexDirection: 'column', gap: 12 }}>
- <Button icon={<QrCode size={16} />} type={buttonType} onClick={handleOpen}>
+ <Button
+ disabled={disabled}
+ icon={<QrCode size={16} />}
+ type={buttonType}
+ onClick={handleOpen}
+ >
{buttonLabel || t('channel.wechatScanToConnect')}
</Button>
{showTips && (
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
index 33be2e6bb9f..6cfa1f80717 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
@@ -1,9 +1,10 @@
'use client';
import { memo, useLayoutEffect, useRef } from 'react';
-import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { useLocation, useParams, useSearchParams } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';
@@ -16,7 +17,7 @@ const getSearchSuffix = (searchParams: URLSearchParams) => {
// sync outside state to useChatStore
const ChatHydration = memo(() => {
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ aid?: string; topicId?: string }>();
const [searchParams] = useSearchParams();
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
index b758e225d13..f5d220f6ea3 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
@@ -6,11 +6,17 @@ import HeaderActions from './index';
vi.mock('@lobehub/ui', () => ({
ActionIcon: () => <button data-testid={'overflow-menu-button'} />,
- DropdownMenu: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ DropdownMenu: ({ children, header }: { children?: ReactNode; header?: ReactNode }) => (
+ <div>
+ {header}
+ {children}
+ </div>
+ ),
}));
vi.mock('./useMenu', () => ({
useMenu: () => ({
+ menuHeader: <div data-testid={'topic-info-header'} />,
menuItems: [],
}),
}));
@@ -21,4 +27,10 @@ describe('Conversation header actions', () => {
expect(screen.getByTestId('overflow-menu-button')).toBeInTheDocument();
});
+
+ it('passes the topic info header to the dropdown', () => {
+ render(<HeaderActions />);
+
+ expect(screen.getByTestId('topic-info-header')).toBeInTheDocument();
+ });
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
index 787a08c65a8..e0535f0c553 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
@@ -9,12 +9,12 @@ import HeaderSlot from '@/routes/(main)/agent/(chat)/_layout/HeaderSlot';
import { useMenu } from './useMenu';
const HeaderActions = memo(() => {
- const { menuItems } = useMenu();
+ const { menuHeader, menuItems } = useMenu();
return (
<>
<HeaderSlot.Outlet />
- <DropdownMenu items={menuItems}>
+ <DropdownMenu header={menuHeader} items={menuItems}>
<ActionIcon icon={MoreHorizontal} size={'small'} />
</DropdownMenu>
</>
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
index 8a02f209249..6e7b8cd30b5 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
@@ -1,7 +1,8 @@
/**
* @vitest-environment happy-dom
*/
-import { act, renderHook } from '@testing-library/react';
+import { act, render, renderHook, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { useMenu } from './useMenu';
@@ -16,6 +17,10 @@ const removeTopicMock = vi.hoisted(() => vi.fn());
const updateTopicTitleMock = vi.hoisted(() => vi.fn());
const useLocationMock = vi.hoisted(() => vi.fn());
+vi.mock('@/business/client/hooks/useAuthorInfo', () => ({
+ useAuthorInfo: () => ({ fullName: 'Miao Miao' }),
+}));
+
vi.mock('@/components/RenameModal', () => ({
openRenameModal: vi.fn(),
}));
@@ -25,7 +30,10 @@ vi.mock('@/const/version', () => ({
}));
vi.mock('@lobehub/ui', () => ({
+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Icon: () => null,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
vi.mock('antd', () => ({
@@ -63,6 +71,8 @@ vi.mock('@/store/chat', () => ({
favorite: false,
id: 'topic-1',
title: 'Topic 1',
+ updatedAt: '2026-05-27T00:15:00.000Z',
+ userId: 'user-1',
},
autoRenameTopicTitle: autoRenameTopicTitleMock,
favoriteTopic: favoriteTopicMock,
@@ -89,6 +99,7 @@ vi.mock('@/store/global/selectors', () => ({
const isActionItem = (
item: unknown,
): item is {
+ desc?: unknown;
key: string;
label?: unknown;
onClick?: () => void;
@@ -128,4 +139,22 @@ describe('Conversation header action menu', () => {
expect(popupItem).toBeUndefined();
});
+
+ it('renders topic info in the dropdown header above menu actions', () => {
+ useLocationMock.mockReturnValue({ pathname: '/agent/agent-1' });
+
+ const { result } = renderHook(() => useMenu());
+
+ const topicInfoItem = result.current.menuItems.find(
+ (item) => isActionItem(item) && item.key === 'topic-info',
+ );
+
+ expect(topicInfoItem).toBeUndefined();
+ expect(result.current.menuHeader).toBeDefined();
+
+ render(result.current.menuHeader);
+
+ expect(screen.getByText('topic:info.title')).toBeInTheDocument();
+ expect(screen.getByText(/Miao Miao.*topic:info.updatedAt/)).toBeInTheDocument();
+ });
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
index 3fed036f602..6c8c9f2a71b 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
@@ -1,6 +1,7 @@
'use client';
-import { type DropdownItem, Icon } from '@lobehub/ui';
+import type { DropdownItem } from '@lobehub/ui';
+import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import {
@@ -14,10 +15,12 @@ import {
Trash,
Wand2,
} from 'lucide-react';
+import type { ReactNode } from 'react';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useParams } from 'react-router-dom';
+import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import { openRenameModal } from '@/components/RenameModal';
import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';
import { isDesktop } from '@/const/version';
@@ -34,7 +37,34 @@ import { useDocumentStore } from '@/store/document';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-export const useMenu = (): { menuItems: DropdownItem[] } => {
+interface TopicInfoHeaderProps {
+ authorName: string;
+ title: string;
+ updatedAtLabel?: string;
+}
+
+const TopicInfoHeader = ({ authorName, title, updatedAtLabel }: TopicInfoHeaderProps) => (
+ <Block
+ horizontal
+ align={'center'}
+ gap={12}
+ paddingBlock={8}
+ paddingInline={12}
+ style={{ minWidth: 240 }}
+ variant={'borderless'}
+ >
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <Text ellipsis style={{ lineHeight: 1.4 }} weight={'bold'}>
+ {title}
+ </Text>
+ <Text ellipsis fontSize={12} style={{ lineHeight: 1.4 }} type={'secondary'}>
+ {updatedAtLabel ? `${authorName} ${updatedAtLabel}` : authorName}
+ </Text>
+ </Flexbox>
+ </Block>
+);
+
+export const useMenu = (): { menuHeader?: ReactNode; menuItems: DropdownItem[] } => {
const { t } = useTranslation(['chat', 'topic', 'common', 'file']);
const { message } = App.useApp();
const { pathname } = useLocation();
@@ -147,9 +177,36 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {
}
}, [docId, handleRestoreHistory, message, saveSourceLabels, t]);
+ const authorInfo = useAuthorInfo(activeTopic?.userId);
+
const topicId = activeTopic?.id;
const topicTitle = activeTopic?.title ?? '';
const isFavorite = !!activeTopic?.favorite;
+ const menuHeader = useMemo<ReactNode | undefined>(() => {
+ if (!authorInfo?.fullName || !topicId) return undefined;
+
+ const updatedAt = activeTopic?.updatedAt;
+ const formattedDate = updatedAt
+ ? new Date(updatedAt).toLocaleString(undefined, {
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ month: '2-digit',
+ year: 'numeric',
+ })
+ : '';
+ const updatedAtLabel = formattedDate
+ ? t('info.updatedAt', { ns: 'topic', time: formattedDate })
+ : undefined;
+
+ return (
+ <TopicInfoHeader
+ authorName={authorInfo.fullName}
+ title={t('info.title', { ns: 'topic' })}
+ updatedAtLabel={updatedAtLabel}
+ />
+ );
+ }, [activeTopic?.updatedAt, authorInfo?.fullName, topicId, t]);
const menuItems = useMemo<DropdownItem[]>(() => {
const items: DropdownItem[] = [];
@@ -296,5 +353,5 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {
message,
]);
- return { menuItems };
+ return { menuHeader, menuItems };
};
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx
new file mode 100644
index 00000000000..55f83cff11a
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx
@@ -0,0 +1,96 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import type { ComponentType, ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ShareButton from './index';
+
+const mocks = vi.hoisted(() => ({
+ activeTopicId: 'topic-1' as string | undefined,
+ enableBusinessFeatures: true,
+ permission: {
+ allowed: true,
+ reason: 'requires member',
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button data-testid="share-button" disabled={disabled} title={title} onClick={onClick}>
+ {title}
+ </button>
+ ),
+}));
+
+vi.mock('next/dynamic', () => ({
+ default: () =>
+ function DynamicComponent({ children }: { children?: ReactNode }) {
+ return <div data-testid="share-popover">{children}</div>;
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/components/withSuspense', () => ({
+ withSuspense: (Component: ComponentType) => Component,
+}));
+
+vi.mock('@/features/ShareModal', () => ({
+ useShareModal: () => ({
+ openShareModal: vi.fn(),
+ }),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: { activeTopicId?: string }) => unknown) =>
+ selector({ activeTopicId: mocks.activeTopicId }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (
+ selector: (state: { serverConfig: { enableBusinessFeatures: boolean } }) => unknown,
+ ) => selector({ serverConfig: { enableBusinessFeatures: mocks.enableBusinessFeatures } }),
+}));
+
+vi.mock('@/store/serverConfig/selectors', () => ({
+ serverConfigSelectors: {
+ enableBusinessFeatures: (s: { serverConfig: { enableBusinessFeatures: boolean } }) =>
+ s.serverConfig.enableBusinessFeatures,
+ },
+}));
+
+describe('Conversation ShareButton', () => {
+ beforeEach(() => {
+ mocks.activeTopicId = 'topic-1';
+ mocks.enableBusinessFeatures = true;
+ mocks.permission.allowed = true;
+ });
+
+ it('does not open share popover for workspace viewers', () => {
+ mocks.permission.allowed = false;
+
+ const { queryByTestId, getByTestId } = render(<ShareButton />);
+
+ expect(getByTestId('share-button')).toBeDisabled();
+ expect(getByTestId('share-button')).toHaveAttribute('title', 'requires member');
+ expect(queryByTestId('share-popover')).toBeNull();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx
index 2f594855b7e..79040010d78 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx
@@ -9,6 +9,7 @@ import { withSuspense } from '@/components/withSuspense';
import { DESKTOP_HEADER_ICON_SMALL_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useShareModal } from '@/features/ShareModal';
import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
@@ -24,22 +25,26 @@ const ShareButton = memo<ShareButtonProps>(({ mobile, setOpen, open }) => {
const { t } = useTranslation('common');
const activeTopicId = useChatStore((s) => s.activeTopicId);
const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
+ const { allowed: canShare, reason } = usePermission('edit_own_content');
// Hide share button when no topic exists (no messages sent yet)
if (!activeTopicId) return null;
const iconButton = (
<ActionIcon
+ disabled={!canShare}
icon={Share2}
size={mobile ? MOBILE_HEADER_ICON_SIZE : DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={t('share')}
+ title={canShare ? t('share') : reason}
tooltipProps={{
placement: 'bottom',
}}
- onClick={enableTopicLinkShare ? undefined : openShareModal}
+ onClick={enableTopicLinkShare || !canShare ? undefined : openShareModal}
/>
);
+ if (!canShare) return iconButton;
+
return (
<>
{enableTopicLinkShare ? (
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
index f0565bbce11..a5f6c3e473b 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
@@ -5,9 +5,10 @@ import { createStaticStyles } from 'antd-style';
import { FileText, MessageSquareText } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation, useNavigate, useParams } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -52,7 +53,7 @@ const styles = createStaticStyles(({ css }) => ({
const ViewSwitcher = memo(() => {
const { t } = useTranslation('chat');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
const params = useParams<{ aid?: string; topicId?: string }>();
const activeTopicId = useChatStore((s) => s.activeTopicId);
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
index e3f4fc053f5..73b23f61f1d 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -7,6 +7,7 @@ import { useConversationStore } from '@/features/Conversation';
import { overlayCaptureUploadPool } from '@/features/Electron/ScreenCapture/overlayCaptureUploadPool';
import { canConsumePendingOverlayDispatch } from '@/features/Electron/ScreenCapture/overlayDispatch';
import { useOverlayDispatchStore } from '@/features/Electron/ScreenCapture/overlayDispatchStore';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import type { UploadFileItem } from '@/types/files/upload';
@@ -27,6 +28,8 @@ const MessageFromUrl = () => {
const [searchParams, setSearchParams] = useSearchParams();
const location = useLocation();
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [pendingDispatch, clearPendingDispatch] = useOverlayDispatchStore((s) => [
s.pendingDispatch,
s.clearPendingDispatch,
@@ -45,6 +48,7 @@ const MessageFromUrl = () => {
useEffect(() => {
const message = searchParams.get('message');
if (!message) return;
+ if (!canCreate) return;
// Wait for agentId to be available before sending
if (!agentId) return;
@@ -81,6 +85,7 @@ const MessageFromUrl = () => {
setSearchParams,
sendMessage,
agentId,
+ canCreate,
context.topicId,
isAgentConfigLoading,
messagesInit,
@@ -89,6 +94,7 @@ const MessageFromUrl = () => {
useEffect(() => {
if (!pendingDispatch) return;
+ if (!canCreate) return;
if (
!canConsumePendingOverlayDispatch({
@@ -113,7 +119,7 @@ const MessageFromUrl = () => {
void (async () => {
try {
- if (modelId && provider) {
+ if (canEdit && modelId && provider) {
const agentState = useAgentStore.getState();
const currentModel = agentByIdSelectors.getAgentModelById(agentId!)(agentState);
const currentProvider = agentByIdSelectors.getAgentModelProviderById(agentId!)(
@@ -137,6 +143,8 @@ const MessageFromUrl = () => {
})();
}, [
agentId,
+ canCreate,
+ canEdit,
clearPendingDispatch,
context.topicId,
isAgentConfigLoading,
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx
index b5028b4240c..581c02132e2 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx
@@ -2,8 +2,8 @@ import { Avatar, Button, Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -32,7 +32,7 @@ const styles = createStaticStyles(({ css }) => ({
const AgentSummary = memo(() => {
const { t } = useTranslation(['chat', 'discover']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const meta = useAgentStore(agentSelectors.currentAgentMeta);
const { data: providers = [] } = useAgentStore((s) => s.useFetchBotProviders(activeAgentId));
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
index 9c81acd7c6f..9bb4ac63357 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
@@ -12,6 +12,7 @@ import { shallow } from 'zustand/shallow';
import Menu from '@/components/Menu';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
import { AgentSettings as Settings } from '@/features/AgentSetting';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -20,6 +21,7 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfi
const Content = memo(() => {
const { t } = useTranslation('setting');
const theme = useTheme();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [agentId, isInbox] = useAgentStore(
(s) => [s.activeAgentId, builtinAgentSelectors.isInboxAgent(s)],
shallow,
@@ -45,11 +47,13 @@ const Content = memo(() => {
}, [activeTab, tab]);
const updateAgentConfig = async (config: any) => {
+ if (!canEdit) return;
if (!agentId) return;
await useAgentStore.getState().optimisticUpdateAgentConfig(agentId, config);
};
const updateAgentMeta = async (meta: any) => {
+ if (!canEdit) return;
if (!agentId) return;
await useAgentStore.getState().optimisticUpdateAgentMeta(agentId, meta);
};
@@ -141,6 +145,7 @@ const Content = memo(() => {
{activeTab && (
<Settings
config={config}
+ disabled={!canEdit}
id={agentId}
loading={false}
meta={meta}
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx
new file mode 100644
index 00000000000..cad2b852821
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx
@@ -0,0 +1,94 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import EditorCanvas from './index';
+
+const editorProps = vi.hoisted(() => ({
+ last: undefined as any,
+}));
+
+const editor = {
+ getDocument: vi.fn(),
+ setDocument: vi.fn(),
+};
+
+const handleContentChange = vi.fn();
+const updateAgentConfig = vi.fn();
+
+vi.mock('@lobehub/editor/react', () => ({
+ Editor: Object.assign(
+ vi.fn((props: any) => {
+ editorProps.last = props;
+ return <div data-testid="profile-editor" />;
+ }),
+ { withProps: (_plugin: unknown, props: unknown) => ({ props }) },
+ ),
+}));
+
+vi.mock('@lobehub/editor', () => ({
+ ReactMentionPlugin: vi.fn(),
+ ReactTablePlugin: vi.fn(),
+ ReactToolbarPlugin: vi.fn(),
+}));
+
+vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({
+ createChatInputRichPlugins: () => [],
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: false, reason: 'requires member' }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: any) =>
+ selector({
+ config: {
+ editorData: undefined,
+ systemRole: 'readonly prompt',
+ },
+ streamingSystemRole: undefined,
+ streamingSystemRoleInProgress: false,
+ updateAgentConfig,
+ }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ currentAgentConfig: (s: any) => s.config,
+ },
+}));
+
+vi.mock('../ProfileEditor/MentionList', () => ({
+ useMentionOptions: () => undefined,
+}));
+
+vi.mock('../store', () => ({
+ useProfileStore: (selector: any) => selector({ editor, handleContentChange }),
+}));
+
+vi.mock('./TypoBar', () => ({
+ default: () => <div />,
+}));
+
+vi.mock('./useSlashItems', () => ({
+ useSlashItems: () => [],
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('Agent profile EditorCanvas', () => {
+ beforeEach(() => {
+ editorProps.last = undefined;
+ });
+
+ it('passes editable=false to the editor when workspace permission blocks edits', () => {
+ render(<EditorCanvas />);
+
+ expect(editorProps.last?.editable).toBe(false);
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
index 42f9f87ed5c..055d86295e0 100644
--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
@@ -7,6 +7,7 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
+import { usePermission } from '@/hooks/usePermission';
import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -18,6 +19,7 @@ import { useSlashItems } from './useSlashItems';
const EditorCanvas = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [editorInit, setEditorInit] = useState(false);
const [contentInit, setContentInit] = useState(false);
const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
@@ -40,10 +42,11 @@ const EditorCanvas = memo(() => {
// Wrap handleContentChange with updateConfig
const handleChange = useCallback(() => {
+ if (!canEdit) return;
// Don't trigger save during streaming
if (streamingInProgress) return;
handleContentChange(updateConfig);
- }, [handleContentChange, updateConfig, streamingInProgress]);
+ }, [canEdit, handleContentChange, updateConfig, streamingInProgress]);
// Handle streaming updates - update editor with streaming content
useEffect(() => {
@@ -67,6 +70,8 @@ const EditorCanvas = memo(() => {
// Trigger save when streaming ends
useEffect(() => {
if (wasStreamingRef.current && !streamingInProgress && editor && editorInit) {
+ if (!canEdit) return;
+
// Streaming just ended, wait for editor to update its internal state then save
// This ensures editorData (json) is properly updated from the markdown content
const timer = setTimeout(() => {
@@ -75,7 +80,7 @@ const EditorCanvas = memo(() => {
return () => clearTimeout(timer);
}
wasStreamingRef.current = !!streamingInProgress;
- }, [streamingInProgress, editor, editorInit, handleContentChange, updateConfig]);
+ }, [canEdit, streamingInProgress, editor, editorInit, handleContentChange, updateConfig]);
useEffect(() => {
if (!editorInit || !editor || contentInit) return;
@@ -96,12 +101,14 @@ const EditorCanvas = memo(() => {
return (
<div
+ style={canEdit ? undefined : { cursor: 'not-allowed', opacity: 0.65, pointerEvents: 'none' }}
onClick={(e) => {
e.stopPropagation();
}}
>
<Editor
content={initialLoad}
+ editable={canEdit}
editor={editor!}
lineEmptyPlaceholder={t('settingAgent.prompt.placeholder')}
mentionOption={mentionOptions}
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx b/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
index dec1d65d9d0..8b89b88f9b6 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
@@ -4,8 +4,8 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { marketApiService } from '@/services/marketApi';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -17,7 +17,7 @@ import { type AgentForkSourceResponse } from '@/types/discover';
*/
const AgentForkTag = memo(() => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [forkSource, setForkSource] = useState<AgentForkSourceResponse['source']>(null);
const [loading, setLoading] = useState(false);
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishButton.tsx b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishButton.tsx
index 9bd3879fc87..246165b08ca 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishButton.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishButton.tsx
@@ -6,6 +6,7 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
import { useAgentStore } from '@/store/agent';
@@ -23,6 +24,7 @@ interface MarketPublishButtonProps {
const PublishButton = memo<MarketPublishButtonProps>(({ action, onPublishSuccess }) => {
const { t } = useTranslation(['setting', 'marketAuth']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const { isAuthenticated, isLoading, signIn } = useMarketAuth();
const { checkOwnership, isCheckingOwnership, isPublishing, publish } = useMarketPublish({
@@ -157,10 +159,15 @@ const PublishButton = memo<MarketPublishButtonProps>(({ action, onPublishSuccess
}}
>
<Button
+ disabled={!canEdit}
icon={ShapesUploadIcon}
loading={loading}
title={buttonTitle}
- onClick={handleButtonClick}
+ onClick={() => {
+ if (!canEdit) return;
+
+ handleButtonClick();
+ }}
>
{t('publishToCommunity')}
</Button>
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishResultModal.tsx b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
index 56443bf4acc..81da24e2b10 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
@@ -4,7 +4,8 @@ import { FluentEmoji, Modal, Text } from '@lobehub/ui';
import { Result } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface PublishResultModalProps {
identifier?: string;
@@ -13,7 +14,7 @@ interface PublishResultModalProps {
}
const PublishResultModal = memo<PublishResultModalProps>(({ identifier, onCancel, open }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/useMarketPublish.ts b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/useMarketPublish.ts
index 0a5283ba1aa..8e21c877197 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/useMarketPublish.ts
+++ b/src/routes/(main)/agent/profile/features/Header/AgentPublishButton/useMarketPublish.ts
@@ -2,6 +2,7 @@ import isEqual from 'fast-deep-equal';
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { message } from '@/components/AntdStaticMethods';
import { useTokenCount } from '@/hooks/useTokenCount';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
@@ -56,6 +57,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
const model = useAgentStore(agentSelectors.currentAgentModel);
const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
const tokenUsage = useTokenCount(systemRole);
+ const hasActiveWorkspace = useHasActiveWorkspace();
const isSubmit = action === 'submit';
@@ -117,9 +119,13 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
isPublishingRef.current = true;
setIsPublishing(true);
message.loading({ content: loadingMessage, key: messageKey });
+ const actAs = hasActiveWorkspace
+ ? (await lambdaClient.workspace.ensureMarketOrganization.mutate()).marketAccountId
+ : undefined;
// Use tRPC publishOrCreate - backend handles ownership check automatically
const result = await lambdaClient.market.agent.publishOrCreate.mutate({
+ actAs,
avatar: meta?.avatar,
changelog,
config: {
@@ -189,6 +195,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
chatConfig?.historyCount,
chatConfig?.searchMode,
editorData,
+ hasActiveWorkspace,
isAuthenticated,
isSubmit,
language,
diff --git a/src/routes/(main)/agent/profile/features/Header/PublishConfirmModal.tsx b/src/routes/(main)/agent/profile/features/Header/PublishConfirmModal.tsx
new file mode 100644
index 00000000000..972c9557168
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/Header/PublishConfirmModal.tsx
@@ -0,0 +1,55 @@
+'use client';
+
+import { Button, Flexbox, Text } from '@lobehub/ui';
+import { createModal, useModalContext } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface PublishConfirmContentProps {
+ onConfirm: () => Promise<void>;
+}
+
+const PublishConfirmContent = memo<PublishConfirmContentProps>(({ onConfirm }) => {
+ const { t: tt } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
+ const [loading, setLoading] = useState(false);
+
+ const handleOk = async () => {
+ try {
+ setLoading(true);
+ await onConfirm();
+ } finally {
+ setLoading(false);
+ close();
+ }
+ };
+
+ return (
+ <Flexbox gap={20}>
+ <Text type="secondary">
+ {tt('marketPublish.validation.confirmPublishDesc', { ns: 'setting' })}
+ </Text>
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button onClick={close}>{tt('cancel', { ns: 'common' })}</Button>
+ <Button loading={loading} type="primary" onClick={handleOk}>
+ {tt('ok', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+PublishConfirmContent.displayName = 'PublishConfirmContent';
+
+export const openPublishConfirmModal = (onConfirm: () => Promise<void>) =>
+ createModal({
+ content: <PublishConfirmContent onConfirm={onConfirm} />,
+ styles: {
+ close: { flexShrink: 0 },
+ header: { gap: 8 },
+ title: { flex: 1, minWidth: 0 },
+ },
+ title: t('marketPublish.validation.confirmPublish', { ns: 'setting' }),
+ width: 420,
+ });
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 8896f69916e..86fb0c6f525 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -7,12 +7,16 @@ import type { TFunction } from 'i18next';
import { BotMessageSquareIcon, Download, MoreHorizontal, Settings2Icon, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';
+import { useBusinessAgentImportMenuItem } from '@/business/client/hooks/useBusinessAgentImportMenuItem';
import { message } from '@/components/AntdStaticMethods';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useCommunityPublishGuard } from '@/hooks/useCommunityPublishGuard';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
import { useAgentStore } from '@/store/agent';
@@ -30,6 +34,7 @@ import { type OriginalAgentInfo, useMarketPublish } from './AgentPublishButton/u
import AgentStatusTag from './AgentStatusTag';
import AgentVersionReviewTag, { useVersionReviewStatus } from './AgentVersionReviewTag';
import AutoSaveHint from './AutoSaveHint';
+import { openPublishConfirmModal } from './PublishConfirmModal';
type HeaderTranslation = TFunction<
readonly ['setting', 'marketAuth', 'chat', 'file', 'common'],
@@ -87,7 +92,7 @@ const buildAgentProfileMarkdown = (params: {
const Header = memo(() => {
const { t } = useTranslation(['setting', 'marketAuth', 'chat', 'file', 'common']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
@@ -102,8 +107,10 @@ const Header = memo(() => {
]);
const removeAgent = useHomeStore((s) => s.removeAgent);
const editor = useProfileStore((s) => s.editor);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
const { isUnderReview } = useVersionReviewStatus();
+ const ensureCommunityPublishAllowed = useCommunityPublishGuard();
const action = meta?.marketIdentifier ? 'upload' : 'submit';
@@ -133,6 +140,8 @@ const Header = memo(() => {
}, [checkOwnership, publish]);
const handlePublishClick = useCallback(async () => {
+ if (!canEdit) return;
+ if (!ensureCommunityPublishAllowed()) return;
if (isUnderReview) {
message.warning({
content: t('marketPublish.validation.underReview', {
@@ -156,36 +165,45 @@ const Header = memo(() => {
return;
}
- confirmModal({
- onOk: async () => {
- if (!isAuthenticated) {
- try {
- await signIn('publish');
- await doPublish();
- } catch (error) {
- console.error(`[MarketPublishButton][${action}] Authorization failed:`, error);
- const normalizedError = resolveMarketAuthError(error);
- message.error({
- content: t(`errors.${normalizedError.code}`, { ns: 'marketAuth' }),
- key: 'market-auth',
- });
- }
- return;
+ openPublishConfirmModal(async () => {
+ if (!isAuthenticated) {
+ try {
+ await signIn('publish');
+ await doPublish();
+ } catch (error) {
+ console.error(`[MarketPublishButton][${action}] Authorization failed:`, error);
+ const normalizedError = resolveMarketAuthError(error);
+ message.error({
+ content: t(`errors.${normalizedError.code}`, { ns: 'marketAuth' }),
+ key: 'market-auth',
+ });
}
- await doPublish();
- },
- title: t('marketPublish.validation.confirmPublish', { ns: 'setting' }),
+ return;
+ }
+ await doPublish();
});
- }, [action, doPublish, isAuthenticated, isUnderReview, meta?.title, signIn, systemRole, t]);
+ }, [
+ action,
+ canEdit,
+ doPublish,
+ ensureCommunityPublishAllowed,
+ isAuthenticated,
+ isUnderReview,
+ meta?.title,
+ signIn,
+ systemRole,
+ t,
+ ]);
const handleForkConfirm = useCallback(async () => {
+ if (!canEdit) return;
setShowForkModal(false);
setOriginalAgentInfo(null);
await publish();
- }, [publish]);
+ }, [canEdit, publish]);
const handleDelete = useCallback(() => {
- if (!activeAgentId) return;
+ if (!canEdit || !activeAgentId) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -195,7 +213,7 @@ const Header = memo(() => {
},
title: t('confirmRemoveSessionItemAlert', { ns: 'chat' }),
});
- }, [activeAgentId, navigate, removeAgent, t]);
+ }, [activeAgentId, canEdit, navigate, removeAgent, t]);
const handleExportMarkdown = useCallback(async () => {
try {
@@ -242,8 +260,13 @@ const Header = memo(() => {
}
}, [config.model, config.plugins, config.provider, editor, meta, systemRole, t]);
- const menuItems = useMemo(
- () => [
+ const importMenuItem = useBusinessAgentImportMenuItem(activeAgentId ?? undefined);
+ const transferMenuItems = useAgentTransferMenuItem(activeAgentId ?? undefined);
+
+ const menuItems = useMemo(() => {
+ const businessTransferMenuItems = transferMenuItems ?? [];
+
+ return [
{
icon: <Icon icon={Settings2Icon} />,
key: 'advanced-settings',
@@ -274,17 +297,30 @@ const Header = memo(() => {
key: 'export',
label: t('pageEditor.menu.export', { ns: 'file' }),
},
+ importMenuItem ? { type: 'divider' as const } : null,
+ importMenuItem,
+ businessTransferMenuItems.length > 0 ? { type: 'divider' as const } : null,
+ ...businessTransferMenuItems,
{ type: 'divider' as const },
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: handleDelete,
},
- ],
- [canPublishToCommunity, handlePublishClick, handleExportMarkdown, handleDelete, t],
- );
+ ].filter(Boolean);
+ }, [
+ canEdit,
+ canPublishToCommunity,
+ handlePublishClick,
+ handleExportMarkdown,
+ handleDelete,
+ t,
+ importMenuItem,
+ transferMenuItems,
+ ]);
return (
<>
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
new file mode 100644
index 00000000000..7b582c00aeb
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import AgentHeader from './AgentHeader';
+
+const emojiPickerProps = vi.hoisted(() => ({
+ last: undefined as any,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children }: any) => <div>{children}</div>,
+ Icon: () => <span />,
+ Input: () => <input readOnly />,
+ Skeleton: {
+ Button: () => <div />,
+ },
+ Tooltip: ({ children }: any) => <>{children}</>,
+}));
+
+vi.mock('ahooks', () => ({
+ useDebounceFn: (fn: (...args: unknown[]) => void) => ({ run: fn }),
+}));
+
+vi.mock('antd', () => ({
+ message: { error: vi.fn() },
+}));
+
+vi.mock('@/components/EmojiPicker', () => ({
+ default: vi.fn((props: any) => {
+ emojiPickerProps.last = props;
+ return <button type="button">avatar</button>;
+ }),
+}));
+
+vi.mock('@/features/AgentSetting/AgentMeta/BackgroundSwatches', () => ({
+ default: () => <div />,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: false, reason: 'requires member' }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: any) =>
+ selector({
+ meta: {
+ avatar: '🍷',
+ backgroundColor: undefined,
+ title: 'Readonly agent',
+ },
+ updateAgentMeta: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ currentAgentMeta: (s: any) => s.meta,
+ },
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: any) => selector({ uploadWithProgress: vi.fn() }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: any) => selector({ language: 'en-US' }),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ globalGeneralSelectors: {
+ currentLanguage: (s: any) => s.language,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('AgentHeader', () => {
+ beforeEach(() => {
+ emojiPickerProps.last = undefined;
+ });
+
+ it('keeps the emoji picker closed when edits are not allowed', () => {
+ render(<AgentHeader />);
+
+ expect(emojiPickerProps.last?.open).toBe(false);
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
index cad25abc0f3..bfd51e64965 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import EmojiPicker from '@/components/EmojiPicker';
import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useFileStore } from '@/store/file';
@@ -22,6 +23,7 @@ const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
const AgentHeader = memo(() => {
const { t } = useTranslation(['setting', 'common']);
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const { allowed: canEdit } = usePermission('edit_own_content');
// Get current meta from store
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
@@ -42,6 +44,8 @@ const AgentHeader = memo(() => {
// Debounced save for title
const { run: debouncedSaveTitle } = useDebounceFn(
(value: string) => {
+ if (!canEdit) return;
+
updateMeta({ title: value });
},
{ wait: EDITOR_DEBOUNCE_TIME },
@@ -49,12 +53,16 @@ const AgentHeader = memo(() => {
// Handle avatar change (immediate save)
const handleAvatarChange = (emoji: string) => {
+ if (!canEdit) return;
+
updateMeta({ avatar: emoji });
};
// Handle avatar upload
const handleAvatarUpload = useCallback(
async (file: File) => {
+ if (!canEdit) return;
+
if (file.size > MAX_AVATAR_SIZE) {
message.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
return;
@@ -70,16 +78,20 @@ const AgentHeader = memo(() => {
setUploading(false);
}
},
- [uploadWithProgress, updateMeta, t],
+ [canEdit, uploadWithProgress, updateMeta, t],
);
// Handle avatar delete
const handleAvatarDelete = useCallback(() => {
+ if (!canEdit) return;
+
updateMeta({ avatar: null });
- }, [updateMeta]);
+ }, [canEdit, updateMeta]);
// Handle background color change (immediate save)
const handleBackgroundColorChange = (color?: string) => {
+ if (!canEdit) return;
+
if (color !== undefined) {
updateMeta({ backgroundColor: color });
}
@@ -100,10 +112,11 @@ const AgentHeader = memo(() => {
{/* Avatar Section */}
<EmojiPicker
allowModelAvatar
- allowUpload
- allowDelete={!!meta.avatar}
+ allowDelete={canEdit && !!meta.avatar}
+ allowUpload={canEdit}
loading={uploading}
locale={locale}
+ open={canEdit ? undefined : false}
shape={'square'}
size={72}
value={meta.avatar}
@@ -130,6 +143,7 @@ const AgentHeader = memo(() => {
}
>
<BackgroundSwatches
+ disabled={!canEdit}
gap={8}
shape={'square'}
size={38}
@@ -152,6 +166,7 @@ const AgentHeader = memo(() => {
{/* Title Section */}
<Flexbox flex={1} style={{ minWidth: 0 }}>
<Input
+ disabled={!canEdit}
placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}
value={localTitle}
variant={'borderless'}
@@ -163,6 +178,8 @@ const AgentHeader = memo(() => {
}}
onChange={(e) => {
setLocalTitle(e.target.value);
+ if (!canEdit) return;
+
debouncedSaveTitle(e.target.value);
}}
/>
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx
index f4c3bc17275..758b76c8871 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx
@@ -8,8 +8,9 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { CheckCircle2, KeyRound, X } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';
// Fixed cred key for Claude Code OAuth token — never changes
@@ -121,11 +122,14 @@ interface TokenSectionProps {
const TokenSection = memo<TokenSectionProps>(({ existingCred, onSaved, onEnvChange }) => {
const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [editing, setEditing] = useState(!existingCred);
const [tokenInput, setTokenInput] = useState('');
const [saving, setSaving] = useState(false);
const handleSave = async () => {
+ if (!canEdit) return;
+
const token = tokenInput.trim();
if (!token) return;
setSaving(true);
@@ -153,7 +157,14 @@ const TokenSection = memo<TokenSectionProps>(({ existingCred, onSaved, onEnvChan
<span className={styles.sectionLabel}>{t('heterogeneousStatus.cloud.tokenLabel')}</span>
</Flexbox>
{existingCred && !editing && (
- <span className={styles.manageLink} onClick={() => setEditing(true)}>
+ <span
+ className={styles.manageLink}
+ onClick={() => {
+ if (!canEdit) return;
+
+ setEditing(true);
+ }}
+ >
{t('heterogeneousStatus.cloud.tokenChange')}
</span>
)}
@@ -173,13 +184,14 @@ const TokenSection = memo<TokenSectionProps>(({ existingCred, onSaved, onEnvChan
<Flexbox horizontal gap={8}>
<Input.Password
autoFocus={!!existingCred}
+ disabled={!canEdit}
placeholder={t('heterogeneousStatus.cloud.tokenPlaceholder')}
style={{ flex: 1 }}
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onPressEnter={handleSave}
/>
- <Button loading={saving} type="primary" onClick={handleSave}>
+ <Button disabled={!canEdit} loading={saving} type="primary" onClick={handleSave}>
{t('heterogeneousStatus.cloud.tokenSave')}
</Button>
{existingCred && (
@@ -210,9 +222,12 @@ interface RepoListSectionProps {
const RepoListSection = memo<RepoListSectionProps>(({ repos, onReposChange }) => {
const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [input, setInput] = useState('');
const addRepo = () => {
+ if (!canEdit) return;
+
const v = input.trim();
if (!v || repos.includes(v)) return;
onReposChange([...repos, v]);
@@ -221,6 +236,8 @@ const RepoListSection = memo<RepoListSectionProps>(({ repos, onReposChange }) =>
const removeRepo = (repo: string, e: React.MouseEvent) => {
e.stopPropagation();
+ if (!canEdit) return;
+
onReposChange(repos.filter((r) => r !== repo));
};
@@ -238,6 +255,7 @@ const RepoListSection = memo<RepoListSectionProps>(({ repos, onReposChange }) =>
</Typography.Text>
<button
className={`${styles.repoDeleteBtn} repo-delete-btn`}
+ disabled={!canEdit}
onClick={(e) => removeRepo(repo, e)}
>
<X size={12} />
@@ -249,13 +267,16 @@ const RepoListSection = memo<RepoListSectionProps>(({ repos, onReposChange }) =>
<Flexbox horizontal gap={8}>
<Input
+ disabled={!canEdit}
placeholder={t('heterogeneousStatus.cloud.repoPlaceholder')}
style={{ flex: 1 }}
value={input}
onChange={(e) => setInput(e.target.value)}
onPressEnter={addRepo}
/>
- <Button onClick={addRepo}>{t('heterogeneousStatus.cloud.repoAdd')}</Button>
+ <Button disabled={!canEdit} onClick={addRepo}>
+ {t('heterogeneousStatus.cloud.repoAdd')}
+ </Button>
</Flexbox>
<span className={styles.sectionDesc}>{t('heterogeneousStatus.cloud.repoDesc')}</span>
@@ -267,7 +288,8 @@ const RepoListSection = memo<RepoListSectionProps>(({ repos, onReposChange }) =>
const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(
({ provider, onEnvChange }) => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const currentEnv = provider.env ?? {};
const storedGithubCredKey = currentEnv.GITHUB_CRED_KEY ?? '';
@@ -292,6 +314,8 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(
);
const saveEnv = (patch: Record<string, string>) => {
+ if (!canEdit) return;
+
void onEnvChange({ ...currentEnv, ...patch });
};
@@ -335,6 +359,7 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(
<Select
allowClear
+ disabled={!canEdit}
placeholder={t('heterogeneousStatus.cloud.githubPlaceholder')}
style={{ width: '100%' }}
value={storedGithubCredKey || undefined}
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
index 3c967cf00ee..20da3bf5d58 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -12,9 +12,10 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { Loader2Icon, PencilLine, RefreshCw, XCircle } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { toolDetectorService } from '@/services/electron/toolDetector';
const COMMAND_LINE_HEIGHT = 28;
@@ -215,7 +216,8 @@ interface HeterogeneousAgentStatusCardProps {
const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
({ provider, onCommandChange }) => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const providerConfig = getHeterogeneousAgentClientConfig(provider.type);
const defaultCommand = providerConfig?.command || '';
const resolvedCommand = provider.command?.trim() || defaultCommand;
@@ -303,11 +305,12 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
}, [isEditingCommand]);
const startEditingCommand = useCallback(() => {
+ if (!canEdit) return;
if (savingCommand) return;
setCommandInput(resolvedCommand);
setIsEditingCommand(true);
- }, [resolvedCommand, savingCommand]);
+ }, [canEdit, resolvedCommand, savingCommand]);
const cancelEditingCommand = useCallback(() => {
setCommandInput(resolvedCommand);
@@ -315,6 +318,8 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
}, [resolvedCommand]);
const commitCommand = useCallback(async () => {
+ if (!canEdit) return;
+
const normalizedCommand = commandInput.trim() || defaultCommand;
setCommandInput(normalizedCommand);
@@ -330,7 +335,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
} finally {
setSavingCommand(false);
}
- }, [commandInput, defaultCommand, onCommandChange, resolvedCommand, savingCommand]);
+ }, [canEdit, commandInput, defaultCommand, onCommandChange, resolvedCommand, savingCommand]);
const renderStatusTag = () => {
if (detecting) {
@@ -409,7 +414,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
<div className={styles.commandInputWrap}>
<Input
className={styles.commandInput}
- disabled={savingCommand}
+ disabled={!canEdit || savingCommand}
placeholder={t('heterogeneousStatus.command.placeholder')}
ref={commandInputRef as never}
value={commandInput}
@@ -445,6 +450,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
<ActionIcon
aria-label={t('heterogeneousStatus.command.edit')}
className={`command-edit-button ${styles.commandEditButton}`}
+ disabled={!canEdit}
icon={PencilLine}
size="small"
onClick={startEditingCommand}
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
index 2f3f9be73e9..b41d6a6ebd6 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
@@ -13,6 +13,7 @@ import { memo, useCallback, useMemo } from 'react';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
@@ -112,6 +113,7 @@ const resolveApiDescription = (
};
const useMentionOptions = () => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const installedTools = useToolStore(toolSelectors.discoverableMetaList, isEqual);
const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
@@ -148,6 +150,8 @@ const useMentionOptions = () => {
label,
metadata: createMetadata(),
onSelect: (editor: IEditor) => {
+ if (!canEdit) return;
+
toggleAgentPlugin(tool.identifier, true);
editor.dispatchCommand(INSERT_MENTION_COMMAND, {
label,
@@ -156,7 +160,7 @@ const useMentionOptions = () => {
},
};
});
- }, [installedTools, toggleAgentPlugin]);
+ }, [canEdit, installedTools, toggleAgentPlugin]);
const loadItems = useCallback(
async (
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index 063cdcceea9..99f66837794 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -9,6 +9,7 @@ import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
import ModelSelect from '@/features/ModelSelect';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -22,12 +23,14 @@ import RemoteAgentConfigCard from './RemoteAgentConfigCard';
const ProfileEditor = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
const updateConfig = useAgentStore((s) => s.updateAgentConfig);
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const heterogeneousProvider = config.agencyConfig?.heterogeneousProvider;
const updateHeterogeneousCommand = async (command: string) => {
+ if (!canEdit) return;
if (!heterogeneousProvider) return;
await updateConfig({
agencyConfig: {
@@ -37,6 +40,7 @@ const ProfileEditor = memo(() => {
};
const updateHeterogeneousEnv = async (env: Record<string, string>) => {
+ if (!canEdit) return;
if (!heterogeneousProvider) return;
await updateConfig({
agencyConfig: {
@@ -113,12 +117,17 @@ const ProfileEditor = memo(() => {
>
<ModelSelect
initialWidth
+ disabled={!canEdit}
popupWidth={400}
value={{
model: config.model,
provider: config.provider,
}}
- onChange={updateConfig}
+ onChange={(value) => {
+ if (!canEdit) return;
+
+ updateConfig(value);
+ }}
/>
</Flexbox>
<AgentTool />
diff --git a/src/routes/(main)/agent/profile/index.tsx b/src/routes/(main)/agent/profile/index.tsx
index b32685eb7aa..ad1f0313a4f 100644
--- a/src/routes/(main)/agent/profile/index.tsx
+++ b/src/routes/(main)/agent/profile/index.tsx
@@ -7,6 +7,7 @@ import { memo, Suspense } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
import AgentBuilder from '@/features/AgentBuilder';
import WideScreenContainer from '@/features/WideScreenContainer';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { StyleSheet } from '@/utils/styles';
@@ -32,6 +33,7 @@ const styles = StyleSheet.create({
const ProfileArea = memo(() => {
const editor = useProfileStore((s) => s.editor);
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
+ const { allowed: canEdit } = usePermission('edit_own_content');
return (
<>
@@ -44,9 +46,10 @@ const ProfileArea = memo(() => {
<Flexbox
horizontal
height={'100%'}
- style={styles.contentWrapper}
+ style={{ ...styles.contentWrapper, cursor: canEdit ? 'text' : 'default' }}
width={'100%'}
onClick={(e) => {
+ if (!canEdit) return;
// Only focus editor for clicks within this DOM element,
// not from React portal (e.g. Modal) whose DOM is outside this tree
if (e.currentTarget.contains(e.target as Node)) {
diff --git a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
new file mode 100644
index 00000000000..5dca70bf2e2
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
@@ -0,0 +1,70 @@
+// @vitest-environment happy-dom
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it, vi } from 'vitest';
+
+import Header from './Header';
+
+const mocks = vi.hoisted(() => ({
+ useUserProfile: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ onClick }: { onClick?: () => void }) => (
+ <button data-testid="back-button" onClick={onClick} />
+ ),
+ Flexbox: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('@/features/NavHeader', () => ({
+ default: ({ left, right }: { left?: React.ReactNode; right?: React.ReactNode }) => (
+ <header>
+ <div>{left}</div>
+ <div>{right}</div>
+ </header>
+ ),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/routes/(main)/community/features/Search', () => ({
+ default: () => <div data-testid="community-search" />,
+}));
+
+vi.mock('@/routes/(main)/community/features/UserAvatar', () => ({
+ default: ({ avatarOverride }: { avatarOverride?: string | null }) => (
+ <div data-avatar={avatarOverride ?? ''} data-testid="community-user-avatar" />
+ ),
+}));
+
+vi.mock('@/store/discover', () => ({
+ useDiscoverStore: (
+ selector: (state: { useUserProfile: typeof mocks.useUserProfile }) => unknown,
+ ) => selector({ useUserProfile: mocks.useUserProfile }),
+}));
+
+describe('Community detail Header', () => {
+ it('shows the viewed organization avatar in the right corner', () => {
+ mocks.useUserProfile.mockReturnValue({
+ data: {
+ user: {
+ avatarUrl: 'sad-avatar',
+ },
+ },
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/011/community/org/sad']}>
+ <Header />
+ </MemoryRouter>,
+ );
+
+ expect(mocks.useUserProfile).toHaveBeenCalledWith({ username: 'sad' });
+ expect(screen.getByTestId('community-user-avatar')).toHaveAttribute(
+ 'data-avatar',
+ 'sad-avatar',
+ );
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/_layout/Header.tsx b/src/routes/(main)/community/(detail)/_layout/Header.tsx
index 14bcfcc9562..08766a53521 100644
--- a/src/routes/(main)/community/(detail)/_layout/Header.tsx
+++ b/src/routes/(main)/community/(detail)/_layout/Header.tsx
@@ -4,24 +4,35 @@ import { ActionIcon, Flexbox } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { ArrowLeft } from 'lucide-react';
import { memo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
import urlJoin from 'url-join';
import NavHeader from '@/features/NavHeader';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import StoreSearchBar from '@/routes/(main)/community/features/Search';
import UserAvatar from '@/routes/(main)/community/features/UserAvatar';
+import { useDiscoverStore } from '@/store/discover';
import { styles } from './Header/style';
const Header = memo(() => {
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const path = location.pathname.split('/').filter(Boolean);
+ const communityIndex = path.indexOf('community');
+ const detailType = communityIndex >= 0 ? path[communityIndex + 1] : undefined;
+ const detailSlug = communityIndex >= 0 ? path[communityIndex + 2] : undefined;
+ const profileUsername =
+ (detailType === 'user' || detailType === 'org') && detailSlug
+ ? decodeURIComponent(detailSlug)
+ : '';
- const handleGoBack = () => {
- // Extract the path segment (agent, model, provider, mcp, group_agent, user)
- const path = location.pathname.split('/').filter(Boolean);
- const detailType = path[1];
+ const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
+ const { data: detailProfile } = useUserProfile({ username: profileUsername });
+ const detailAvatar =
+ detailProfile?.user.avatarUrl || detailProfile?.user.userName || detailProfile?.user.namespace;
+ const handleGoBack = () => {
// group_agent goes back to agent list page
if (detailType === 'group_agent') {
navigate('/community/agent');
@@ -46,7 +57,7 @@ const Header = memo(() => {
return (
<NavHeader
className={styles.headerContainer}
- right={<UserAvatar />}
+ right={<UserAvatar avatarOverride={detailAvatar} />}
style={cssVariables}
left={
<Flexbox horizontal align={'center'} flex={1} gap={8}>
diff --git a/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx b/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
index 3558312a60a..6097c63543c 100644
--- a/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
@@ -4,10 +4,10 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import useSWR from 'swr';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { marketApiService } from '@/services/marketApi';
import { useDetailContext } from './DetailProvider';
@@ -18,7 +18,7 @@ import { useDetailContext } from './DetailProvider';
*/
const AgentForkTag = memo(() => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { identifier, forkedFromAgentId } = useDetailContext();
// Fetch fork source info
diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
index eb47ddf989b..c2f8d3689df 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
@@ -10,9 +10,9 @@ import { Avatar, Block, Flexbox, Icon, Image, Skeleton, Tag, Text } from '@lobeh
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useDiscoverStore } from '@/store/discover';
/**
@@ -270,7 +270,7 @@ const PluginItem = memo<PluginItemProps>(({ identifier }) => {
// For internal links (market plugins), use Link component
if (sourceConfig.href) {
- return <Link to={sourceConfig.href}>{content}</Link>;
+ return <WorkspaceLink to={sourceConfig.href}>{content}</WorkspaceLink>;
}
return content;
diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Overview/TagList.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Overview/TagList.tsx
index 5fbdb8023f0..34af75184ce 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Details/Overview/TagList.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Overview/TagList.tsx
@@ -4,8 +4,8 @@ import { Flexbox, Tag } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import qs from 'query-string';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { type AssistantMarketSource } from '@/types/discover';
@@ -30,7 +30,7 @@ const TagList = memo<{ tags: string[] }>(({ tags }) => {
showTags && (
<Flexbox horizontal gap={8} wrap={'wrap'}>
{tags.map((tag) => (
- <Link
+ <WorkspaceLink
key={tag}
to={qs.stringifyUrl(
{
@@ -44,7 +44,7 @@ const TagList = memo<{ tags: string[] }>(({ tags }) => {
)}
>
<Tag className={styles.tag}>{tag}</Tag>
- </Link>
+ </WorkspaceLink>
))}
</Flexbox>
)
diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx
index 5fbdb8023f0..34af75184ce 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx
@@ -4,8 +4,8 @@ import { Flexbox, Tag } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import qs from 'query-string';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { type AssistantMarketSource } from '@/types/discover';
@@ -30,7 +30,7 @@ const TagList = memo<{ tags: string[] }>(({ tags }) => {
showTags && (
<Flexbox horizontal gap={8} wrap={'wrap'}>
{tags.map((tag) => (
- <Link
+ <WorkspaceLink
key={tag}
to={qs.stringifyUrl(
{
@@ -44,7 +44,7 @@ const TagList = memo<{ tags: string[] }>(({ tags }) => {
)}
>
<Tag className={styles.tag}>{tag}</Tag>
- </Link>
+ </WorkspaceLink>
))}
</Flexbox>
)
diff --git a/src/routes/(main)/community/(detail)/agent/features/Header.tsx b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
index 60785a48539..60f45d075ca 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
@@ -25,16 +25,16 @@ import {
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import useSWR from 'swr';
-import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { socialService } from '@/services/social';
import { formatIntergerNumber } from '@/utils/format';
import { useCategory } from '../../../(list)/agent/features/Category/useCategory';
+import { resolveCommunityProfileLink } from '../../utils/profileLink';
import AgentForkTag from './AgentForkTag';
import { useDetailContext } from './DetailProvider';
@@ -59,6 +59,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
pluginCount,
knowledgeCount,
userName,
+ ownerType,
forkCount,
} = useDetailContext();
const { mobile = isMobile } = useResponsive();
@@ -109,7 +110,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
const cate = categories.find((c) => c.key === category);
const cateButton = (
- <Link
+ <WorkspaceLink
to={qs.stringifyUrl({
query: { category: cate?.key },
url: '/community/agent',
@@ -118,7 +119,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
<Button icon={cate?.icon} size={'middle'} variant={'outlined'}>
{cate?.label}
</Button>
- </Link>
+ </WorkspaceLink>
);
return (
@@ -172,9 +173,12 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
{author && userName ? (
- <Link style={{ color: 'inherit' }} to={urlJoin('/community/user', userName)}>
+ <WorkspaceLink
+ style={{ color: 'inherit' }}
+ to={resolveCommunityProfileLink(userName, ownerType)}
+ >
{author}
- </Link>
+ </WorkspaceLink>
) : (
author
)}
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
index 595b270397f..31f62715a68 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
@@ -7,9 +7,10 @@ import { createStaticStyles } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { SESSION_CHAT_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
import { useAgentStore } from '@/store/agent';
@@ -39,8 +40,9 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
const createAgent = useAgentStore((s) => s.createAgent);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('discover');
+ const { allowed: canCreate } = usePermission('create_content');
const meta = {
avatar,
@@ -67,7 +69,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const createAgentWithMarketIdentifier = async (shouldNavigate = true) => {
- if (!config) return;
+ if (!canCreate || !config) return;
// Note: agentService.createAgent automatically normalizes market config (handles model as object)
const agentData = {
@@ -97,6 +99,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const handleCreateAndConverse = async () => {
+ if (!canCreate) return;
setIsLoading(true);
try {
const result = await createAgentWithMarketIdentifier(true);
@@ -108,6 +111,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const handleCreate = async () => {
+ if (!canCreate) return;
setIsLoading(true);
try {
await createAgentWithMarketIdentifier(false);
@@ -118,7 +122,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const handleAddAgentAndConverse = async () => {
- if (!config) return;
+ if (!canCreate || !config) return;
const isDuplicate = await checkDuplicateAgent();
if (isDuplicate) {
@@ -129,7 +133,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const handleAddAgent = async () => {
- if (!config) return;
+ if (!canCreate || !config) return;
const isDuplicate = await checkDuplicateAgent();
if (isDuplicate) {
@@ -141,6 +145,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
const menuItems = [
{
+ disabled: !canCreate,
key: 'addAgent',
label: t('assistants.addAgent'),
onClick: handleAddAgent,
@@ -152,6 +157,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
<Button
block
className={styles.primaryButton}
+ disabled={!canCreate}
loading={isLoading}
size={'large'}
style={{ flex: 1, width: 'unset' }}
@@ -163,11 +169,11 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
<DropdownMenu
items={menuItems}
popupProps={{ style: { minWidth: 267 } }}
- triggerProps={{ disabled: isLoading }}
+ triggerProps={{ disabled: isLoading || !canCreate }}
>
<Button
className={styles.menuButton}
- disabled={isLoading}
+ disabled={isLoading || !canCreate}
icon={<Icon icon={ChevronDownIcon} />}
size={'large'}
type={'primary'}
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
index d7479c997a8..e48eaef803d 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
@@ -6,10 +6,13 @@ import { createStaticStyles } from 'antd-style';
import { customAlphabet } from 'nanoid/non-secure';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { SESSION_CHAT_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { lambdaClient } from '@/libs/trpc/client';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
import { marketApiService } from '@/services/marketApi';
@@ -40,9 +43,11 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
const createAgent = useAgentStore((s) => s.createAgent);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('discover');
const { isAuthenticated, signIn } = useMarketAuth();
+ const { allowed: canCreate } = usePermission('create_content');
+ const activeWorkspaceId = useActiveWorkspaceId();
const meta = {
avatar,
@@ -54,6 +59,7 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
};
const handleForkAndChat = async () => {
+ if (!canCreate) return;
// Check if user is authenticated
if (!isAuthenticated) {
try {
@@ -79,9 +85,27 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
// Generate a unique identifier for the forked agent
const newIdentifier = generateMarketIdentifier();
+ // When forking inside a workspace, attribute the fork to the workspace's
+ // Market organization mirror so `agents.ownerId` ends up on the org
+ // account rather than the actor. Provisioning is idempotent.
+ let actAs: number | undefined;
+ if (activeWorkspaceId) {
+ try {
+ const { marketAccountId } =
+ await lambdaClient.workspace.ensureMarketOrganization.mutate();
+ actAs = marketAccountId;
+ } catch (error) {
+ console.warn(
+ 'Failed to provision Market organization for workspace; falling back to personal fork:',
+ error,
+ );
+ }
+ }
+
// Step 2: Fork the agent via Market API (single-item batch)
const [forkOutcome] = await marketApiService.forkAgent([
{
+ actAs,
identifier: newIdentifier,
name: title,
sourceIdentifier: identifier!,
@@ -140,6 +164,7 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
<Button
block
className={styles.buttonGroup}
+ disabled={!canCreate}
loading={isLoading}
size={'large'}
type={'primary'}
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/index.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/index.tsx
index 675b6164db9..acce603247b 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/index.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/index.tsx
@@ -2,9 +2,9 @@ import { Flexbox } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { type AssistantMarketSource } from '@/types/discover';
@@ -45,9 +45,9 @@ const Related = memo(() => {
{ skipNull: true },
);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/agent/features/StatusPage/index.tsx b/src/routes/(main)/community/(detail)/agent/features/StatusPage/index.tsx
index b15a249c835..3873ef08728 100644
--- a/src/routes/(main)/community/(detail)/agent/features/StatusPage/index.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/StatusPage/index.tsx
@@ -5,14 +5,15 @@ import { Button, FluentEmoji, Text } from '@lobehub/ui';
import { Result } from 'antd';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface StatusPageProps {
status: 'unpublished' | 'archived' | 'deprecated';
}
const StatusPage = memo<StatusPageProps>(({ status }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('discover');
const handleBackToMarket = () => {
diff --git a/src/routes/(main)/community/(detail)/features/Back.tsx b/src/routes/(main)/community/(detail)/features/Back.tsx
index d6377047b84..a51a6edc1b2 100644
--- a/src/routes/(main)/community/(detail)/features/Back.tsx
+++ b/src/routes/(main)/community/(detail)/features/Back.tsx
@@ -6,7 +6,8 @@ import { ArrowLeft } from 'lucide-react';
import { type CSSProperties } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
const styles = createStaticStyles(({ css, cssVar }) => {
return {
@@ -24,12 +25,12 @@ const Back = memo<{ href: string; style?: CSSProperties }>(({ href, style }) =>
const { t } = useTranslation('discover');
return (
- <Link className={styles.back} style={{ marginBottom: 8, ...style }} to={href}>
+ <WorkspaceLink className={styles.back} style={{ marginBottom: 8, ...style }} to={href}>
<Flexbox horizontal align={'center'} gap={8}>
<Icon icon={ArrowLeft} />
{t(`back`)}
</Flexbox>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/community/(detail)/features/Block.tsx b/src/routes/(main)/community/(detail)/features/Block.tsx
index dc16fc087b7..edfabdde611 100644
--- a/src/routes/(main)/community/(detail)/features/Block.tsx
+++ b/src/routes/(main)/community/(detail)/features/Block.tsx
@@ -3,7 +3,8 @@ import { Button, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { ChevronRight } from 'lucide-react';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
const styles = createStaticStyles(({ css, cssVar }) => ({
more: css`
@@ -31,12 +32,12 @@ const Block = memo<BlockProps>(({ title, more, moreLink, children, ...rest }) =>
<Flexbox horizontal align={'center'} gap={16} justify={'space-between'} width={'100%'}>
<h2 className={styles.title}>{title}</h2>
{moreLink && (
- <Link target={moreLink.startsWith('http') ? '_blank' : undefined} to={moreLink}>
+ <WorkspaceLink target={moreLink.startsWith('http') ? '_blank' : undefined} to={moreLink}>
<Button className={styles.more} type={'text'}>
<span>{more}</span>
<Icon icon={ChevronRight} />
</Button>
- </Link>
+ </WorkspaceLink>
)}
</Flexbox>
<Flexbox {...rest}>{children}</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/features/Breadcrumb.tsx b/src/routes/(main)/community/(detail)/features/Breadcrumb.tsx
index 8896cc7e651..0a77992692a 100644
--- a/src/routes/(main)/community/(detail)/features/Breadcrumb.tsx
+++ b/src/routes/(main)/community/(detail)/features/Breadcrumb.tsx
@@ -6,8 +6,8 @@ import { Breadcrumb as AntdBreadcrumb } from 'antd';
import { cssVar } from 'antd-style';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { DiscoverTab } from '@/types/discover';
const Breadcrumb = memo<{ identifier: string; tab: DiscoverTab }>(({ tab, identifier }) => {
@@ -24,7 +24,7 @@ const Breadcrumb = memo<{ identifier: string; tab: DiscoverTab }>(({ tab, identi
if (tab === DiscoverTab.User) {
return [
{
- title: <Link to="/community">Community</Link>,
+ title: <WorkspaceLink to="/community">Community</WorkspaceLink>,
},
{
title: (
@@ -45,10 +45,10 @@ const Breadcrumb = memo<{ identifier: string; tab: DiscoverTab }>(({ tab, identi
return [
{
- title: <Link to="/community">Community</Link>,
+ title: <WorkspaceLink to="/community">Community</WorkspaceLink>,
},
{
- title: <Link to={`/community/${tab}`}>{tabLabel}</Link>,
+ title: <WorkspaceLink to={`/community/${tab}`}>{tabLabel}</WorkspaceLink>,
},
{
title: (
diff --git a/src/routes/(main)/community/(detail)/features/FollowButton.tsx b/src/routes/(main)/community/(detail)/features/FollowButton.tsx
new file mode 100644
index 00000000000..7b57d762ebc
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/features/FollowButton.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { socialService } from '@/services/social';
+import { useDiscoverStore } from '@/store/discover';
+
+interface FollowButtonProps {
+ userId: number;
+}
+
+const FollowButton = memo<FollowButtonProps>(({ userId }) => {
+ const { t } = useTranslation('discover');
+ const { isAuthenticated, signIn, session } = useMarketAuth();
+ const [loading, setLoading] = useState(false);
+
+ const useFollowStatus = useDiscoverStore((s) => s.useFollowStatus);
+ const follow = useDiscoverStore((s) => s.follow);
+ const unfollow = useDiscoverStore((s) => s.unfollow);
+
+ if (session?.accessToken) {
+ socialService.setAccessToken(session.accessToken);
+ }
+
+ const { data: followStatus, mutate } = useFollowStatus(userId);
+ const isFollowing = followStatus?.isFollowing ?? false;
+
+ const handleClick = async () => {
+ if (!isAuthenticated) {
+ await signIn();
+ return;
+ }
+
+ setLoading(true);
+ try {
+ if (isFollowing) {
+ await unfollow(userId);
+ } else {
+ await follow(userId);
+ }
+ await mutate();
+ } catch (error) {
+ console.error('Follow action failed:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Button
+ loading={loading}
+ shape={'round'}
+ size={'large'}
+ type={isFollowing ? 'default' : 'primary'}
+ style={{
+ fontWeight: 500,
+ minWidth: 120,
+ }}
+ onClick={handleClick}
+ >
+ {isFollowing ? t('user.unfollow') : t('user.follow')}
+ </Button>
+ );
+});
+
+export default FollowButton;
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Details/Related/index.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Details/Related/index.tsx
index 4e16a8e11b6..fe390def6bb 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Details/Related/index.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Details/Related/index.tsx
@@ -2,16 +2,16 @@ import { Avatar, Flexbox, Grid, Text } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { type DiscoverGroupAgentItem } from '@/types/discover';
import Title from '../../../../../features/Title';
import { useDetailContext } from '../../DetailProvider';
const GroupAgentCard = memo<DiscoverGroupAgentItem>((item) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleClick = () => {
if (!item.identifier) return;
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx b/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
index 18846a7df16..e0c97d72a99 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
@@ -4,10 +4,10 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import useSWR from 'swr';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { marketApiService } from '@/services/marketApi';
import { useDetailContext } from './DetailProvider';
@@ -18,7 +18,7 @@ import { useDetailContext } from './DetailProvider';
*/
const GroupAgentForkTag = memo(() => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { identifier, forkedFromGroupId } = useDetailContext();
// Fetch fork source info
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
index e041f6089f5..d48c7d8fd5d 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
@@ -17,14 +17,14 @@ import { BookmarkCheckIcon, BookmarkIcon, DotIcon, GitBranchIcon, UsersIcon } fr
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import useSWR from 'swr';
-import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { socialService } from '@/services/social';
+import { resolveCommunityProfileLink } from '../../utils/profileLink';
import { useDetailContext } from './DetailProvider';
import GroupAgentForkTag from './GroupAgentForkTag';
@@ -52,6 +52,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
identifier,
createdAt,
userName,
+ ownerType,
forkCount,
} = data;
@@ -99,7 +100,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
};
const cateButton = category ? (
- <Link
+ <WorkspaceLink
to={qs.stringifyUrl({
query: { category },
url: '/community/group_agent',
@@ -108,7 +109,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
<Button size={'middle'} variant={'outlined'}>
{category}
</Button>
- </Link>
+ </WorkspaceLink>
) : null;
return (
@@ -168,9 +169,12 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
const authorName = authorObj ? authorObj.name || authorObj.userName : author;
return authorName && userName ? (
- <Link style={{ color: 'inherit' }} to={urlJoin('/community/user', userName)}>
+ <WorkspaceLink
+ style={{ color: 'inherit' }}
+ to={resolveCommunityProfileLink(userName, ownerType)}
+ >
{authorName}
- </Link>
+ </WorkspaceLink>
) : (
authorName
);
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/AddGroupAgent.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/AddGroupAgent.tsx
index d0f586359b3..fee75f92b13 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/AddGroupAgent.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/AddGroupAgent.tsx
@@ -7,9 +7,10 @@ import { createStaticStyles } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { chatGroupService } from '@/services/chatGroup';
import { discoverService } from '@/services/discover';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -45,8 +46,9 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
const [isLoading, setIsLoading] = useState(false);
const { message } = App.useApp();
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const loadGroups = useAgentGroupStore((s) => s.loadGroups);
+ const { allowed: canCreate } = usePermission('create_content');
const meta = {
avatar,
@@ -81,6 +83,7 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
};
const createGroupFromMarket = async (shouldNavigate = true) => {
+ if (!canCreate) return;
if (!config) {
message.error(
t('groupAgents.noConfig', { defaultValue: 'Group configuration not available' }),
@@ -119,7 +122,6 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
};
// Filter out null/undefined values
supervisorConfig = Object.fromEntries(
-
Object.entries(rawConfig).filter(([_, v]) => v != null),
);
}
@@ -207,6 +209,7 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
};
const handleAddAndConverse = async () => {
+ if (!canCreate) return;
setIsLoading(true);
try {
const isDuplicate = await checkDuplicateGroup();
@@ -221,6 +224,7 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
};
const handleAdd = async () => {
+ if (!canCreate) return;
setIsLoading(true);
try {
const isDuplicate = await checkDuplicateGroup();
@@ -236,6 +240,7 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
const menuItems = [
{
+ disabled: !canCreate,
key: 'addGroup',
label: t('groupAgents.addGroup', { defaultValue: 'Add Group' }),
onClick: handleAdd,
@@ -247,6 +252,7 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
<Button
block
className={styles.primaryButton}
+ disabled={!canCreate}
loading={isLoading}
size={'large'}
style={{ flex: 1, width: 'unset' }}
@@ -258,11 +264,11 @@ const AddGroupAgent = memo<{ mobile?: boolean }>(() => {
<DropdownMenu
items={menuItems}
popupProps={{ style: { minWidth: 267 } }}
- triggerProps={{ disabled: isLoading }}
+ triggerProps={{ disabled: isLoading || !canCreate }}
>
<Button
className={styles.menuButton}
- disabled={isLoading}
+ disabled={isLoading || !canCreate}
icon={<Icon icon={ChevronDownIcon} />}
size={'large'}
type={'primary'}
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx
index 729f0b9ceba..f7e4408449b 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx
@@ -6,10 +6,13 @@ import { createStaticStyles } from 'antd-style';
import { customAlphabet } from 'nanoid/non-secure';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { lambdaClient } from '@/libs/trpc/client';
import { chatGroupService } from '@/services/chatGroup';
import { discoverService } from '@/services/discover';
import { marketApiService } from '@/services/marketApi';
@@ -46,9 +49,11 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {
const [isLoading, setIsLoading] = useState(false);
const { message } = App.useApp();
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const loadGroups = useAgentGroupStore((s) => s.loadGroups);
const { isAuthenticated, signIn } = useMarketAuth();
+ const { allowed: canCreate } = usePermission('create_content');
+ const activeWorkspaceId = useActiveWorkspaceId();
const meta = {
avatar,
@@ -59,6 +64,7 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {
};
const handleForkAndChat = async () => {
+ if (!canCreate) return;
// Check if user is authenticated
if (!isAuthenticated) {
try {
@@ -91,8 +97,23 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {
// Generate a unique identifier for the forked group
const newIdentifier = generateMarketIdentifier();
+ let actAs: number | undefined;
+ if (activeWorkspaceId) {
+ try {
+ const { marketAccountId } =
+ await lambdaClient.workspace.ensureMarketOrganization.mutate();
+ actAs = marketAccountId;
+ } catch (error) {
+ console.warn(
+ 'Failed to resolve Market organization for workspace; falling back to personal group fork:',
+ error,
+ );
+ }
+ }
+
// Step 2: Fork the group via Market API
const forkResult = await marketApiService.forkAgentGroup(identifier!, {
+ actAs,
identifier: newIdentifier,
name: title,
status: 'published',
@@ -210,6 +231,7 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {
<Button
block
className={styles.buttonGroup}
+ disabled={!canCreate}
loading={isLoading}
size={'large'}
type={'primary'}
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/StatusPage/index.tsx b/src/routes/(main)/community/(detail)/group_agent/features/StatusPage/index.tsx
index a77ed5de99f..dc8b1e4f9d0 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/StatusPage/index.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/StatusPage/index.tsx
@@ -5,14 +5,15 @@ import { Button, FluentEmoji, Text } from '@lobehub/ui';
import { Result } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface StatusPageProps {
status: 'unpublished' | 'archived' | 'deprecated';
}
const StatusPage = memo<StatusPageProps>(({ status }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('discover');
const handleBackToMarket = () => {
diff --git a/src/routes/(main)/community/(detail)/group_agent/index.tsx b/src/routes/(main)/community/(detail)/group_agent/index.tsx
index dfacb3f2bf8..31e163b4737 100644
--- a/src/routes/(main)/community/(detail)/group_agent/index.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/index.tsx
@@ -75,6 +75,9 @@ const GroupAgentDetailPage = memo<GroupAgentDetailPageProps>(({ mobile }) => {
likeCount: (data as any)?.group?.likeCount,
locale: (data as any)?.locale,
memberAgents: (data as any)?.memberAgents || [],
+ ownerType: ((data as any)?.author?.type === 'organization' ? 'organization' : 'user') as
+ | 'organization'
+ | 'user',
status: (data as any)?.group?.status,
summary: (data as any)?.summary,
tags: (data as any)?.currentVersion?.tags,
diff --git a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx
index b0a5e8733e5..9db6634c949 100644
--- a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx
+++ b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import MCPInstallProgress from '@/features/MCP/MCPInstallProgress';
import { useDetailContext } from '@/features/MCPPluginDetail/DetailProvider';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';
@@ -25,6 +26,8 @@ const ActionButton = memo(() => {
const detailContext = useDetailContext();
const { identifier, haveCloudEndpoint } = detailContext;
const [isLoading, setIsLoading] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
const [installed, installMCPPlugin, uninstallMCPPlugin] = useToolStore((s) => [
@@ -37,6 +40,7 @@ const ActionButton = memo(() => {
const isCloudMcp = haveCloudEndpoint;
const installPlugin = async () => {
+ if (!canCreate || !canEdit) return;
if (!identifier) return;
// If this is a cloud MCP and user is not authenticated, request authorization first
@@ -72,6 +76,7 @@ const ActionButton = memo(() => {
</Button>
<Button
+ disabled={!canEdit}
icon={<Icon icon={Trash2Icon} size={20} />}
loading={buttonLoading}
size={'large'}
@@ -80,6 +85,7 @@ const ActionButton = memo(() => {
icon: { height: 20 },
}}
onClick={async () => {
+ if (!canEdit) return;
setIsLoading(true);
await uninstallMCPPlugin(identifier!);
setIsLoading(false);
@@ -91,6 +97,7 @@ const ActionButton = memo(() => {
<Button
block
className={styles.button}
+ disabled={!canCreate || !canEdit}
loading={buttonLoading}
size={'large'}
type={'primary'}
diff --git a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/index.tsx b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/index.tsx
index e2e0446df28..57bf0dea57e 100644
--- a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/index.tsx
+++ b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/index.tsx
@@ -2,10 +2,10 @@ import { Flexbox } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
import { useDetailContext } from '@/features/MCPPluginDetail/DetailProvider';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import Title from '../../../../../features/Title';
import Item from './Item';
@@ -31,9 +31,9 @@ const Related = memo(() => {
{related?.map((item, index) => {
const link = urlJoin('/community/mcp', item.identifier);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/model/features/Details/Overview/ProviderList/index.tsx b/src/routes/(main)/community/(detail)/model/features/Details/Overview/ProviderList/index.tsx
index e35abb1407d..7772e919c9e 100644
--- a/src/routes/(main)/community/(detail)/model/features/Details/Overview/ProviderList/index.tsx
+++ b/src/routes/(main)/community/(detail)/model/features/Details/Overview/ProviderList/index.tsx
@@ -6,12 +6,12 @@ import { cssVar } from 'antd-style';
import { BadgeCheck, BookIcon, ChevronRightIcon, KeyIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
import InlineTable from '@/components/InlineTable';
import { ModelInfoTags } from '@/components/ModelSelect';
import { BASE_PROVIDER_DOC_URL } from '@/const/url';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { formatPriceByCurrency, formatTokenNumber } from '@/utils/format';
import { getTextInputUnitRate, getTextOutputUnitRate } from '@/utils/pricing';
@@ -34,12 +34,15 @@ const ProviderList = memo(() => {
key: 'provider',
render: (_, record) => {
return (
- <Link style={{ color: 'inherit' }} to={urlJoin('/community/provider', record.id)}>
+ <WorkspaceLink
+ style={{ color: 'inherit' }}
+ to={urlJoin('/community/provider', record.id)}
+ >
<Flexbox horizontal align="center" gap={8}>
<ProviderIcon provider={record.id} size={24} type={'avatar'} />
<div style={{ fontWeight: 500 }}>{record.name}</div>
</Flexbox>
- </Link>
+ </WorkspaceLink>
);
},
sorter: (a, b) => a.name.localeCompare(b.name),
@@ -170,7 +173,7 @@ const ProviderList = memo(() => {
<ActionIcon icon={BookIcon} size={'small'} variant={'filled'} />
</a>
</Tooltip>
- <Link
+ <WorkspaceLink
style={{ color: 'inherit' }}
to={urlJoin('/community/provider', record.id)}
>
@@ -180,7 +183,7 @@ const ProviderList = memo(() => {
size={'small'}
variant={'filled'}
/>
- </Link>
+ </WorkspaceLink>
</Flexbox>
);
},
diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx
index aec8eee16b7..023a4d7fee4 100644
--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx
+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx
@@ -7,9 +7,11 @@ import { createStaticStyles } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import { useDetailContext } from '../../DetailProvider';
const styles = createStaticStyles(({ css }) => ({
@@ -24,16 +26,16 @@ const ChatWithModel = memo(() => {
const { t } = useTranslation('discover');
const { providers = [] } = useDetailContext();
const includeLobeHub = providers.some((item) => item.id === 'lobehub');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const list = providers.filter((provider) => provider.id !== 'lobehub');
const items = list.map((item) => ({
icon: <ProviderIcon provider={item.id} size={20} type={'avatar'} />,
key: item.id,
label: (
- <Link to={urlJoin('/community/provider', item.id)}>
+ <WorkspaceLink to={urlJoin('/community/provider', item.id)}>
{[item.name, t('models.guide')].join(' ')}
- </Link>
+ </WorkspaceLink>
),
}));
@@ -61,11 +63,11 @@ const ChatWithModel = memo(() => {
if (items.length === 1)
return (
- <Link style={{ flex: 1 }} to={urlJoin('/community/provider', items[0].key)}>
+ <WorkspaceLink style={{ flex: 1 }} to={urlJoin('/community/provider', items[0].key)}>
<Button block className={styles.button} size={'large'} type={'primary'}>
{t('models.guide')}
</Button>
- </Link>
+ </WorkspaceLink>
);
return (
diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/index.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/index.tsx
index 53225e64a2e..aa1009a1a66 100644
--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/index.tsx
+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/index.tsx
@@ -2,9 +2,10 @@ import { Flexbox } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import Title from '../../../../../features/Title';
import { useDetailContext } from '../../DetailProvider';
import Item from './Item';
@@ -30,9 +31,9 @@ const Related = memo(() => {
{related?.map((item, index) => {
const link = urlJoin('/community/model', item.identifier);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/index.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/index.tsx
index 80538ffc998..901858fd2a0 100644
--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/index.tsx
+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/index.tsx
@@ -1,9 +1,10 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import Title from '../../../../../features/Title';
import { useDetailContext } from '../../DetailProvider';
import Item from './Item';
@@ -21,9 +22,9 @@ const Related = memo(() => {
{providers.slice(0, 6).map((item, index) => {
const link = urlJoin('/community/provider', item.id);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/organization/features/DetailProvider.tsx b/src/routes/(main)/community/(detail)/organization/features/DetailProvider.tsx
new file mode 100644
index 00000000000..e18120a3657
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/DetailProvider.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { createContext, memo, type ReactNode, use } from 'react';
+
+import type {
+ DiscoverAssistantItem,
+ DiscoverGroupAgentItem,
+ DiscoverPluginItem,
+ DiscoverSkillItem,
+ DiscoverUserInfo,
+} from '@/types/discover';
+
+export interface OrganizationDetailContextConfig {
+ agentCount: number;
+ agentGroups?: DiscoverGroupAgentItem[];
+ agents: DiscoverAssistantItem[];
+ groupCount: number;
+ mobile?: boolean;
+ plugins?: DiscoverPluginItem[];
+ skills?: DiscoverSkillItem[];
+ totalInstalls: number;
+ user: DiscoverUserInfo;
+}
+
+export const OrganizationDetailContext = createContext<OrganizationDetailContextConfig | null>(
+ null,
+);
+
+export const OrganizationDetailProvider = memo<{
+ children: ReactNode;
+ config: OrganizationDetailContextConfig;
+}>(({ children, config }) => {
+ return <OrganizationDetailContext value={config}>{children}</OrganizationDetailContext>;
+});
+
+export const useOrganizationDetailContext = () => {
+ const context = use(OrganizationDetailContext);
+ if (!context) {
+ throw new Error('useOrganizationDetailContext must be used within OrganizationDetailProvider');
+ }
+ return context;
+};
diff --git a/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx b/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx
new file mode 100644
index 00000000000..d9503e7812e
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useDiscoverStore } from '@/store/discover';
+
+import { useOrganizationDetailContext } from './DetailProvider';
+
+const FollowStats = memo(() => {
+ const { t } = useTranslation('discover');
+ const { user } = useOrganizationDetailContext();
+
+ // Fall back to the static profile counts (sourced from the authoritative
+ // `accounts.*_count` columns) whenever the live count is missing or 0, so a
+ // not-yet-populated live query never clobbers a real count.
+ const useFollowCounts = useDiscoverStore((s) => s.useFollowCounts);
+ const { data: followCounts } = useFollowCounts(user.id);
+
+ const followingCount = followCounts?.followingCount || user.followingCount || 0;
+ const followersCount = followCounts?.followersCount || user.followersCount || 0;
+
+ return (
+ <Flexbox horizontal align={'center'} gap={16}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text style={{ fontWeight: 600 }}>{followingCount}</Text>
+ <Text type={'secondary'}>{t('user.following')}</Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text style={{ fontWeight: 600 }}>{followersCount}</Text>
+ <Text type={'secondary'}>{t('user.followers')}</Text>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default FollowStats;
diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx
new file mode 100644
index 00000000000..478ce09f2f2
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { Center } from '@lobehub/ui';
+import { createStaticStyles, responsive } from 'antd-style';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ banner: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ width: 100%;
+ height: 160px;
+ padding: 16px;
+
+ ${responsive.sm} {
+ position: relative;
+
+ width: calc(100% + 32px);
+ height: 120px;
+ margin-block: -16px 0;
+ margin-inline: -16px;
+ }
+
+ @media (width <= 1720px) {
+ height: 144px;
+ padding: 0;
+ }
+ `,
+ bannerAvatar: css`
+ filter: blur(100px);
+ `,
+ bannerInner: css`
+ position: relative;
+
+ overflow: hidden;
+
+ width: 100%;
+ height: 100%;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillTertiary};
+
+ @media (width <= 1720px) {
+ border-radius: 0;
+ }
+ `,
+ placeholder: css`
+ position: relative;
+ width: 100%;
+ height: 64px;
+ min-height: 64px;
+
+ ${responsive.sm} {
+ display: none;
+ }
+ `,
+}));
+
+interface BannerProps {
+ avatar?: string | null;
+ bannerUrl?: string | null;
+}
+
+const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {
+ const backgroundImage = bannerUrl || avatar;
+ const shouldBlur = !bannerUrl && !!avatar;
+
+ return (
+ <>
+ <div className={styles.banner}>
+ <Center className={styles.bannerInner}>
+ {backgroundImage && (
+ <div
+ className={shouldBlur ? styles.bannerAvatar : undefined}
+ style={{
+ backgroundImage: `url(${backgroundImage})`,
+ backgroundPosition: 'center',
+ backgroundSize: 'cover',
+ height: '100%',
+ width: '100%',
+ }}
+ />
+ )}
+ </Center>
+ </div>
+ <div className={styles.placeholder} />
+ </>
+ );
+});
+
+export default Banner;
diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx
new file mode 100644
index 00000000000..ebbfaa0a22e
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx
@@ -0,0 +1,69 @@
+// @vitest-environment happy-dom
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type OrganizationDetailContextConfig,
+ OrganizationDetailProvider,
+} from '../DetailProvider';
+import OrganizationHeader from './index';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/routes/(main)/community/(detail)/features/FollowButton', () => ({
+ default: ({ userId }: { userId: number }) => <button>follow-{userId}</button>,
+}));
+
+vi.mock('../FollowStats', () => ({
+ default: () => <div>organization-follow-stats</div>,
+}));
+
+vi.mock('./Banner', () => ({
+ default: () => <div data-testid="organization-banner" />,
+}));
+
+const createConfig = (
+ overrides: Partial<OrganizationDetailContextConfig> = {},
+): OrganizationDetailContextConfig => ({
+ agentCount: 0,
+ agentGroups: [],
+ agents: [],
+ groupCount: 0,
+ plugins: [],
+ skills: [],
+ totalInstalls: 0,
+ user: {
+ avatarUrl: null,
+ bannerUrl: null,
+ createdAt: '',
+ description: 'An organization profile',
+ displayName: 'Acme Labs',
+ followersCount: 2,
+ followingCount: 0,
+ id: 42,
+ namespace: 'acme-labs',
+ socialLinks: { website: 'https://acme.example' },
+ type: 'organization',
+ userName: null,
+ },
+ ...overrides,
+});
+
+describe('OrganizationHeader', () => {
+ it('identifies the page as an organization account and keeps follow controls separate', () => {
+ render(
+ <OrganizationDetailProvider config={createConfig()}>
+ <OrganizationHeader />
+ </OrganizationDetailProvider>,
+ );
+
+ expect(screen.getByRole('heading', { name: 'Acme Labs' })).toBeInTheDocument();
+ expect(screen.getByText('user.accountType.organization')).toBeInTheDocument();
+ expect(screen.getByText('@acme-labs')).toBeInTheDocument();
+ expect(screen.getByText('organization-follow-stats')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'follow-42' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'user.editProfile' })).not.toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/index.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/index.tsx
new file mode 100644
index 00000000000..2e7eb57be08
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/Header/index.tsx
@@ -0,0 +1,98 @@
+'use client';
+
+import { SiGithub, SiX } from '@icons-pack/react-simple-icons';
+import { ActionIcon, Avatar, Flexbox, Tag, Text, Tooltip, TooltipGroup } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { Globe } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import FollowButton from '@/routes/(main)/community/(detail)/features/FollowButton';
+
+import { useOrganizationDetailContext } from '../DetailProvider';
+import FollowStats from '../FollowStats';
+import Banner from './Banner';
+
+const normalizeUrl = (input?: string | null) => {
+ if (!input) return undefined;
+ if (input.startsWith('/')) return `${window.location.origin}${input}`;
+ return input;
+};
+
+const OrganizationHeader = memo(() => {
+ const { t } = useTranslation('discover');
+ const { user } = useOrganizationDetailContext();
+
+ const displayName = user.displayName || user.userName || user.namespace;
+ const username = user.userName || user.namespace;
+ const avatarUrl = useMemo(() => normalizeUrl(user.avatarUrl), [user.avatarUrl]);
+ const bannerUrl = useMemo(() => normalizeUrl(user.bannerUrl), [user.bannerUrl]);
+
+ return (
+ <>
+ <Banner avatar={avatarUrl} bannerUrl={bannerUrl} />
+ <Flexbox gap={16}>
+ <Avatar
+ avatar={avatarUrl}
+ shape={'square'}
+ size={64}
+ style={{ boxShadow: `0 0 0 4px ${cssVar.colorBgContainer}`, flexShrink: 0 }}
+ />
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4} style={{ overflow: 'hidden' }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text ellipsis as={'h1'} fontSize={24} style={{ margin: 0 }} weight={'bold'}>
+ {displayName}
+ </Text>
+ <Tag style={{ flexShrink: 0, margin: 0 }}>{t('user.accountType.organization')}</Tag>
+ </Flexbox>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ @{username}
+ </Text>
+ </Flexbox>
+ <FollowButton userId={user.id} />
+ </Flexbox>
+
+ <FollowStats />
+
+ {user.description && <Text as={'p'}>{user.description}</Text>}
+
+ <TooltipGroup>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {user.socialLinks?.github && (
+ <Tooltip title={`@${user.socialLinks.github}`}>
+ <a
+ href={`https://github.com/${user.socialLinks.github}`}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ <ActionIcon icon={<SiGithub size={16} />} size={20} variant={'outlined'} />
+ </a>
+ </Tooltip>
+ )}
+ {user.socialLinks?.twitter && (
+ <Tooltip title={`@${user.socialLinks.twitter}`}>
+ <a
+ href={`https://twitter.com/${user.socialLinks.twitter}`}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ <ActionIcon icon={<SiX size={16} />} size={20} variant={'outlined'} />
+ </a>
+ </Tooltip>
+ )}
+ {user.socialLinks?.website && (
+ <Tooltip title={user.socialLinks.website}>
+ <a href={user.socialLinks.website} rel="noopener noreferrer" target="_blank">
+ <ActionIcon icon={Globe} size={20} variant={'outlined'} />
+ </a>
+ </Tooltip>
+ )}
+ </Flexbox>
+ </TooltipGroup>
+ </Flexbox>
+ </>
+ );
+});
+
+export default OrganizationHeader;
diff --git a/src/routes/(main)/community/(detail)/organization/features/OrganizationContent.tsx b/src/routes/(main)/community/(detail)/organization/features/OrganizationContent.tsx
new file mode 100644
index 00000000000..6d564152979
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/features/OrganizationContent.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+
+import {
+ type WorkspaceDetailContextConfig,
+ WorkspaceDetailProvider,
+} from '../../workspace/features/DetailProvider';
+import WorkspaceAgentList from '../../workspace/features/WorkspaceAgentList';
+import WorkspaceGroupList from '../../workspace/features/WorkspaceGroupList';
+import WorkspacePluginList from '../../workspace/features/WorkspacePluginList';
+import WorkspaceSkillList from '../../workspace/features/WorkspaceSkillList';
+import { useOrganizationDetailContext } from './DetailProvider';
+
+const OrganizationContent = memo(() => {
+ const {
+ agents,
+ agentCount,
+ agentGroups,
+ groupCount,
+ mobile,
+ plugins,
+ skills,
+ totalInstalls,
+ user,
+ } = useOrganizationDetailContext();
+
+ const workspaceConfig = useMemo<WorkspaceDetailContextConfig>(
+ () => ({
+ agentCount,
+ agentGroups,
+ agents,
+ canEdit: false,
+ groupCount,
+ mobile,
+ plugins,
+ skills,
+ totalInstalls,
+ user,
+ }),
+ [agentCount, agentGroups, agents, groupCount, mobile, plugins, skills, totalInstalls, user],
+ );
+
+ return (
+ <WorkspaceDetailProvider config={workspaceConfig}>
+ <Flexbox gap={32}>
+ <WorkspaceAgentList />
+ <WorkspaceGroupList />
+ <WorkspaceSkillList />
+ <WorkspacePluginList />
+ </Flexbox>
+ </WorkspaceDetailProvider>
+ );
+});
+
+export default OrganizationContent;
diff --git a/src/routes/(main)/community/(detail)/organization/index.tsx b/src/routes/(main)/community/(detail)/organization/index.tsx
new file mode 100644
index 00000000000..a7629861479
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/index.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { memo, useEffect, useMemo } from 'react';
+import { useLocation, useParams } from 'react-router-dom';
+
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useDiscoverStore } from '@/store/discover';
+
+import NotFound from '../components/NotFound';
+import { resolveWorkspaceCommunityProfileRedirect } from '../workspace/features/resolveWorkspaceProfileEdit';
+import { OrganizationDetailProvider } from './features/DetailProvider';
+import OrganizationHeader from './features/Header';
+import OrganizationContent from './features/OrganizationContent';
+import Loading from './loading';
+
+interface OrganizationDetailPageProps {
+ mobile?: boolean;
+}
+
+const OrganizationDetailPage = memo<OrganizationDetailPageProps>(({ mobile }) => {
+ const params = useParams<{ slug: string }>();
+ const location = useLocation();
+ const username = decodeURIComponent(params.slug ?? '');
+ const navigate = useWorkspaceAwareNavigate();
+ const { isWorkspaceScope } = useCommunityWorkspaceProfile();
+
+ const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
+ const { data, isLoading } = useUserProfile({ username });
+
+ useEffect(() => {
+ const redirectTo = resolveWorkspaceCommunityProfileRedirect({
+ isWorkspaceScope,
+ pathname: location.pathname,
+ search: location.search,
+ });
+ if (redirectTo) navigate(redirectTo, { replace: true });
+ }, [isWorkspaceScope, location.pathname, location.search, navigate]);
+
+ const contextConfig = useMemo(() => {
+ if (!data?.user || data.user.type !== 'organization') return null;
+ const { user, agents, agentGroups, skills, plugins } = data;
+ const totalInstalls = agents.reduce((sum, agent) => sum + (agent.installCount || 0), 0);
+
+ return {
+ agentCount: agents.length,
+ agentGroups: agentGroups || [],
+ agents,
+ groupCount: agentGroups?.length || 0,
+ mobile,
+ plugins: plugins || [],
+ skills: skills || [],
+ totalInstalls,
+ user,
+ };
+ }, [data, mobile]);
+
+ if (isLoading) return <Loading />;
+ if (!contextConfig) return <NotFound />;
+
+ return (
+ <OrganizationDetailProvider config={contextConfig}>
+ <OrganizationHeader />
+ <OrganizationContent />
+ </OrganizationDetailProvider>
+ );
+});
+
+export const MobileOrganizationDetailPage = memo(() => {
+ return <OrganizationDetailPage mobile={true} />;
+});
+
+export default OrganizationDetailPage;
diff --git a/src/routes/(main)/community/(detail)/organization/loading.tsx b/src/routes/(main)/community/(detail)/organization/loading.tsx
new file mode 100644
index 00000000000..5b2f4509ff9
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/organization/loading.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import ListLoading from '@/routes/(main)/community/components/ListLoading';
+
+import Banner from './features/Header/Banner';
+
+const Loading = memo(() => {
+ return (
+ <Flexbox gap={24} width={'100%'}>
+ <Banner />
+ <Flexbox gap={16}>
+ <Skeleton.Avatar
+ shape={'square'}
+ size={64}
+ style={{ boxShadow: `0 0 0 4px ${cssVar.colorBgContainer}`, flexShrink: 0 }}
+ />
+ <Skeleton paragraph={{ rows: 1 }} />
+ </Flexbox>
+
+ <ListLoading length={4} rows={4} />
+ </Flexbox>
+ );
+});
+
+export default Loading;
diff --git a/src/routes/(main)/community/(detail)/provider/features/Details/Overview/ModelList/index.tsx b/src/routes/(main)/community/(detail)/provider/features/Details/Overview/ModelList/index.tsx
index 643d10ceaca..0de43dabce1 100644
--- a/src/routes/(main)/community/(detail)/provider/features/Details/Overview/ModelList/index.tsx
+++ b/src/routes/(main)/community/(detail)/provider/features/Details/Overview/ModelList/index.tsx
@@ -6,11 +6,11 @@ import { cssVar } from 'antd-style';
import { ChevronRightIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
import InlineTable from '@/components/InlineTable';
import { ModelInfoTags } from '@/components/ModelSelect';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { formatPriceByCurrency, formatTokenNumber } from '@/utils/format';
import { getTextInputUnitRate, getTextOutputUnitRate } from '@/utils/pricing';
@@ -33,7 +33,10 @@ const ModelList = memo(() => {
key: 'model',
render: (_, record) => {
return (
- <Link style={{ color: 'inherit' }} to={urlJoin('/community/model', record.id)}>
+ <WorkspaceLink
+ style={{ color: 'inherit' }}
+ to={urlJoin('/community/model', record.id)}
+ >
<Flexbox horizontal align="center" gap={8}>
<ModelIcon model={record.id} size={24} type={'avatar'} />
<Flexbox style={{ overflow: 'hidden' }}>
@@ -43,7 +46,7 @@ const ModelList = memo(() => {
</div>
</Flexbox>
</Flexbox>
- </Link>
+ </WorkspaceLink>
);
},
sorter: (a, b) => a.displayName.localeCompare(b.displayName),
@@ -135,14 +138,17 @@ const ModelList = memo(() => {
render: (_, record) => {
return (
<Flexbox horizontal align="center" gap={4} justify={'flex-end'}>
- <Link style={{ color: 'inherit' }} to={urlJoin('/community/model', record.id)}>
+ <WorkspaceLink
+ style={{ color: 'inherit' }}
+ to={urlJoin('/community/model', record.id)}
+ >
<ActionIcon
color={cssVar.colorTextDescription}
icon={ChevronRightIcon}
size={'small'}
variant={'filled'}
/>
- </Link>
+ </WorkspaceLink>
</Flexbox>
);
},
diff --git a/src/routes/(main)/community/(detail)/provider/features/Sidebar/ActionButton/ProviderConfig.tsx b/src/routes/(main)/community/(detail)/provider/features/Sidebar/ActionButton/ProviderConfig.tsx
index cf5ca283de7..bf9f9a44980 100644
--- a/src/routes/(main)/community/(detail)/provider/features/Sidebar/ActionButton/ProviderConfig.tsx
+++ b/src/routes/(main)/community/(detail)/provider/features/Sidebar/ActionButton/ProviderConfig.tsx
@@ -7,7 +7,9 @@ import { createStaticStyles } from 'antd-style';
import { ChevronDownIcon, SquareArrowOutUpRight } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useDetailContext } from '../../DetailProvider';
@@ -22,7 +24,7 @@ const styles = createStaticStyles(({ css }) => ({
const ProviderConfig = memo(() => {
const { t } = useTranslation('discover');
const { url, modelsUrl, identifier } = useDetailContext();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const openSettings = async () => {
if (isDesktop) {
const { ensureElectronIpc } = await import('@/utils/electron/ipc');
@@ -41,18 +43,18 @@ const ProviderConfig = memo(() => {
icon,
key: 'officialSite',
label: (
- <Link target={'_blank'} to={url}>
+ <WorkspaceLink target={'_blank'} to={url}>
{t('providers.officialSite')}
- </Link>
+ </WorkspaceLink>
),
},
modelsUrl && {
icon,
key: 'modelSite',
label: (
- <Link target={'_blank'} to={modelsUrl}>
+ <WorkspaceLink target={'_blank'} to={modelsUrl}>
{t('providers.modelSite')}
- </Link>
+ </WorkspaceLink>
),
},
].filter(Boolean) as any;
diff --git a/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/index.tsx b/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/index.tsx
index 994090aefc1..348c18f3250 100644
--- a/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/index.tsx
+++ b/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/index.tsx
@@ -1,9 +1,10 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import Title from '../../../../../features/Title';
import { useDetailContext } from '../../DetailProvider';
import Item from './Item';
@@ -21,9 +22,9 @@ const Related = memo(() => {
{related?.map((item, index) => {
const link = urlJoin('/community/provider', item.identifier);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/index.tsx b/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/index.tsx
index ad209eb5a31..f129b608592 100644
--- a/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/index.tsx
+++ b/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/index.tsx
@@ -2,9 +2,10 @@ import { Flexbox } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import urlJoin from 'url-join';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import Title from '../../../../../features/Title';
import { useDetailContext } from '../../DetailProvider';
import Item from './Item';
@@ -30,9 +31,9 @@ const Related = memo(() => {
{models?.slice(0, 6)?.map((item, index) => {
const link = urlJoin('/community/model', item.id);
return (
- <Link key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink key={index} style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Item {...item} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/skill/features/Details/Versions/index.tsx b/src/routes/(main)/community/(detail)/skill/features/Details/Versions/index.tsx
index c1bef9ddc32..75f040e7a85 100644
--- a/src/routes/(main)/community/(detail)/skill/features/Details/Versions/index.tsx
+++ b/src/routes/(main)/community/(detail)/skill/features/Details/Versions/index.tsx
@@ -4,10 +4,11 @@ import { Block, Flexbox, Tag } from '@lobehub/ui';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useLocation } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
import InlineTable from '@/components/InlineTable';
import PublishedTime from '@/components/PublishedTime';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import Title from '../../../../../components/Title';
import { useDetailContext } from '../../DetailProvider';
@@ -29,7 +30,7 @@ const Versions = memo(() => {
{
dataIndex: 'version',
render: (_, record) => (
- <Link
+ <WorkspaceLink
style={{ color: 'inherit' }}
to={qs.stringifyUrl({
query: {
@@ -44,7 +45,7 @@ const Versions = memo(() => {
<Tag color={'info'}>{t('skills.details.versions.table.isLatest')}</Tag>
)}
</Flexbox>
- </Link>
+ </WorkspaceLink>
),
title: t('skills.details.versions.table.version'),
},
diff --git a/src/routes/(main)/community/(detail)/skill/features/Header.tsx b/src/routes/(main)/community/(detail)/skill/features/Header.tsx
index 8cfec01aeb1..ebcb76295ab 100644
--- a/src/routes/(main)/community/(detail)/skill/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/skill/features/Header.tsx
@@ -13,9 +13,9 @@ import {
} from 'lucide-react';
import qs from 'query-string';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
import PublishedTime from '@/components/PublishedTime';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useSkillCategoryItem } from '@/hooks/useSkillCategory';
import { useDetailContext } from './DetailProvider';
@@ -89,7 +89,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile }) => {
);
const cateButton = cate ? (
- <Link
+ <WorkspaceLink
to={qs.stringifyUrl({
query: { category: cate.key },
url: '/community/skill',
@@ -98,7 +98,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile }) => {
<Button icon={<Icon icon={cate.icon} />} size={'middle'} variant={'outlined'}>
{cate.label}
</Button>
- </Link>
+ </WorkspaceLink>
) : null;
return (
diff --git a/src/routes/(main)/community/(detail)/skill/features/Sidebar/Platform.tsx b/src/routes/(main)/community/(detail)/skill/features/Sidebar/Platform.tsx
index 497c4752c2f..e751202695e 100644
--- a/src/routes/(main)/community/(detail)/skill/features/Sidebar/Platform.tsx
+++ b/src/routes/(main)/community/(detail)/skill/features/Sidebar/Platform.tsx
@@ -19,8 +19,8 @@ import { createStaticStyles, cx } from 'antd-style';
import { BotIcon, UserRoundIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -116,7 +116,7 @@ const genLayout = (
const Platform = memo<PlatformProps>(
({ lite, identifier, mobile, expandCodeByDefault, downloadUrl }) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const sendMessage = useChatStore((s) => s.sendMessage);
const [active, setActive] = useState<PlatformType>(PlatformType.Claude);
diff --git a/src/routes/(main)/community/(detail)/user/features/FollowButton.tsx b/src/routes/(main)/community/(detail)/user/features/FollowButton.tsx
index 5b1f409d0ca..d58f7cd875e 100644
--- a/src/routes/(main)/community/(detail)/user/features/FollowButton.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/FollowButton.tsx
@@ -1,70 +1 @@
-'use client';
-
-import { Button } from '@lobehub/ui';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { socialService } from '@/services/social';
-import { useDiscoverStore } from '@/store/discover';
-
-interface FollowButtonProps {
- userId: number;
-}
-
-const FollowButton = memo<FollowButtonProps>(({ userId }) => {
- const { t } = useTranslation('discover');
- const { isAuthenticated, signIn, session } = useMarketAuth();
- const [loading, setLoading] = useState(false);
-
- const useFollowStatus = useDiscoverStore((s) => s.useFollowStatus);
- const follow = useDiscoverStore((s) => s.follow);
- const unfollow = useDiscoverStore((s) => s.unfollow);
-
- // Set access token for social service
- if (session?.accessToken) {
- socialService.setAccessToken(session.accessToken);
- }
-
- const { data: followStatus, mutate } = useFollowStatus(userId);
- const isFollowing = followStatus?.isFollowing ?? false;
-
- const handleClick = async () => {
- if (!isAuthenticated) {
- await signIn();
- return;
- }
-
- setLoading(true);
- try {
- if (isFollowing) {
- await unfollow(userId);
- } else {
- await follow(userId);
- }
- await mutate();
- } catch (error) {
- console.error('Follow action failed:', error);
- } finally {
- setLoading(false);
- }
- };
-
- return (
- <Button
- loading={loading}
- shape={'round'}
- size={'large'}
- type={isFollowing ? 'default' : 'primary'}
- style={{
- fontWeight: 500,
- minWidth: 120,
- }}
- onClick={handleClick}
- >
- {isFollowing ? t('user.unfollow') : t('user.follow')}
- </Button>
- );
-});
-
-export default FollowButton;
+export { default } from '../../features/FollowButton';
diff --git a/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx b/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
index 7620916fde0..fcdfadd58b5 100644
--- a/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
@@ -4,14 +4,24 @@ import { Flexbox, Text } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useDiscoverStore } from '@/store/discover';
+
import { useUserDetailContext } from './DetailProvider';
const FollowStats = memo(() => {
const { t } = useTranslation('discover');
const { user } = useUserDetailContext();
- const followingCount = user.followingCount ?? 0;
- const followersCount = user.followersCount ?? 0;
+ // Live follow counts: the `follow-counts-{userId}` cache is invalidated by
+ // follow()/unfollow(), so the numbers update immediately after toggling follow.
+ // Fall back to the static profile counts (which come straight from the
+ // authoritative `accounts.*_count` columns) whenever the live count is missing
+ // or 0 — so a not-yet-populated live query never clobbers a real count.
+ const useFollowCounts = useDiscoverStore((s) => s.useFollowCounts);
+ const { data: followCounts } = useFollowCounts(user.id);
+
+ const followingCount = followCounts?.followingCount || user.followingCount || 0;
+ const followersCount = followCounts?.followersCount || user.followersCount || 0;
return (
<Flexbox horizontal align={'center'} gap={16}>
diff --git a/src/routes/(main)/community/(detail)/user/features/Header/index.tsx b/src/routes/(main)/community/(detail)/user/features/Header/index.tsx
index 115a0aaccdc..3a05d90cccf 100644
--- a/src/routes/(main)/community/(detail)/user/features/Header/index.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/Header/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { SiGithub, SiX } from '@icons-pack/react-simple-icons';
-import { ActionIcon, Avatar, Button, Flexbox, Text, Tooltip, TooltipGroup } from '@lobehub/ui';
+import { ActionIcon, Avatar, Button, Flexbox, Tag, Text, Tooltip, TooltipGroup } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { Globe } from 'lucide-react';
import { memo, useMemo } from 'react';
@@ -18,6 +18,8 @@ const UserHeader = memo(() => {
const displayName = user.displayName || user.userName || user.namespace;
const username = user.userName || user.namespace;
+ const showEditButton = isOwner && !!onEditProfile;
+ const isOrg = user.type === 'organization';
// Normalize avatar URL - convert relative paths to absolute URLs
const avatarUrl = useMemo(() => {
@@ -55,19 +57,22 @@ const UserHeader = memo(() => {
overflow: 'hidden',
}}
>
- <Text ellipsis as={'h1'} fontSize={24} style={{ margin: 0 }} weight={'bold'}>
- {displayName}
- </Text>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text ellipsis as={'h1'} fontSize={24} style={{ margin: 0 }} weight={'bold'}>
+ {displayName}
+ </Text>
+ {isOrg && (
+ <Tag style={{ flexShrink: 0, margin: 0 }}>{t('user.accountType.organization')}</Tag>
+ )}
+ </Flexbox>
<Text ellipsis fontSize={12} type={'secondary'}>
@{username}
</Text>
</Flexbox>
- {isOwner ? (
- onEditProfile && (
- <Button shape={'round'} onClick={() => onEditProfile()}>
- {t('user.editProfile')}
- </Button>
- )
+ {showEditButton ? (
+ <Button shape={'round'} onClick={() => onEditProfile?.()}>
+ {t('user.editProfile')}
+ </Button>
) : (
<FollowButton userId={user.id} />
)}
diff --git a/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
index d442f96646b..11290c02c97 100644
--- a/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { lambdaClient } from '@/libs/trpc/client';
interface SubmitRepoModalProps {
+ beforeSubmit?: () => Promise<{ actAs?: number } | void>;
onClose: () => void;
onSuccess?: () => void;
open: boolean;
@@ -15,86 +16,94 @@ interface SubmitRepoModalProps {
const GITHUB_URL_REGEX = /^https?:\/\/github\.com\/[\w-]+\/[\w.-]+\/?$/;
-export const SubmitRepoModal = memo<SubmitRepoModalProps>(({ open, onClose, onSuccess }) => {
- const { t } = useTranslation('discover');
- const { message } = App.useApp();
- const [form] = Form.useForm();
-
- const [isSubmitting, setIsSubmitting] = useState(false);
-
- const handleSubmit = useCallback(async () => {
- try {
- const values = await form.validateFields();
- const gitUrl = values.gitUrl?.trim();
-
- if (!gitUrl) {
- return;
+export const SubmitRepoModal = memo<SubmitRepoModalProps>(
+ ({ open, onClose, onSuccess, beforeSubmit }) => {
+ const { t } = useTranslation('discover');
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleSubmit = useCallback(async () => {
+ try {
+ const values = await form.validateFields();
+ const gitUrl = values.gitUrl?.trim();
+
+ if (!gitUrl) {
+ return;
+ }
+
+ setIsSubmitting(true);
+
+ const submitContext = await beforeSubmit?.();
+
+ await lambdaClient.market.socialProfile.submitRepo.mutate({
+ actAs: submitContext?.actAs,
+ gitUrl,
+ type: 'skill',
+ });
+
+ message.success(t('user.submitRepoSuccess'));
+ onSuccess?.();
+ onClose();
+ form.resetFields();
+ } catch (error) {
+ console.error('[SubmitRepoModal] Failed to submit:', error);
+ message.error(error instanceof Error ? error.message : t('user.submitRepoError'));
+ } finally {
+ setIsSubmitting(false);
}
+ }, [beforeSubmit, form, message, t, onSuccess, onClose]);
- setIsSubmitting(true);
-
- await lambdaClient.market.socialProfile.submitRepo.mutate({ gitUrl, type: 'skill' });
-
- message.success(t('user.submitRepoSuccess'));
- onSuccess?.();
- onClose();
+ const handleCancel = useCallback(() => {
form.resetFields();
- } catch (error) {
- console.error('[SubmitRepoModal] Failed to submit:', error);
- message.error(error instanceof Error ? error.message : t('user.submitRepoError'));
- } finally {
- setIsSubmitting(false);
- }
- }, [form, message, t, onSuccess, onClose]);
-
- const handleCancel = useCallback(() => {
- form.resetFields();
- onClose();
- }, [form, onClose]);
-
- return (
- <Modal
- centered
- cancelText={t('user.cancel')}
- confirmLoading={isSubmitting}
- okText={t('user.submit')}
- open={open}
- title={false}
- width={480}
- onCancel={handleCancel}
- onOk={handleSubmit}
- >
- <Text strong fontSize={20} style={{ display: 'block', marginBottom: 8, marginTop: 16 }}>
- {t('user.submitRepoTitle')}
- </Text>
- <Text style={{ display: 'block', marginBottom: 16 }} type="secondary">
- {t('user.submitRepoDescription')}
- </Text>
-
- <Form form={form} layout="vertical">
- <Form.Item
- label={t('user.githubUrl')}
- name="gitUrl"
- rules={[
- { required: true, message: t('user.githubUrlRequired') },
- {
- pattern: GITHUB_URL_REGEX,
- message: t('user.githubUrlInvalid'),
- },
- ]}
- >
- <Input placeholder="https://github.com/username/repo" />
- </Form.Item>
- </Form>
-
- <Flexbox style={{ marginTop: 8 }}>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t('user.submitRepoHint')}
+ onClose();
+ }, [form, onClose]);
+
+ return (
+ <Modal
+ centered
+ cancelText={t('user.cancel')}
+ confirmLoading={isSubmitting}
+ okText={t('user.submit')}
+ open={open}
+ title={false}
+ width={480}
+ onCancel={handleCancel}
+ onOk={handleSubmit}
+ >
+ <Text strong fontSize={20} style={{ display: 'block', marginBottom: 8, marginTop: 16 }}>
+ {t('user.submitRepoTitle')}
</Text>
- </Flexbox>
- </Modal>
- );
-});
+ <Text style={{ display: 'block', marginBottom: 16 }} type="secondary">
+ {t('user.submitRepoDescription')}
+ </Text>
+
+ <Form form={form} layout="vertical">
+ <Form.Item
+ label={t('user.githubUrl')}
+ name="gitUrl"
+ rules={[
+ { required: true, message: t('user.githubUrlRequired') },
+ {
+ pattern: GITHUB_URL_REGEX,
+ message: t('user.githubUrlInvalid'),
+ },
+ ]}
+ >
+ <Input placeholder="https://github.com/username/repo" />
+ </Form.Item>
+ </Form>
+
+ <Flexbox style={{ marginTop: 8 }}>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('user.submitRepoHint')}
+ </Text>
+ </Flexbox>
+ </Modal>
+ );
+ },
+);
SubmitRepoModal.displayName = 'SubmitRepoModal';
diff --git a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
index 7b0c1a9dc9d..a9ee0812d61 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
@@ -29,10 +29,12 @@ import {
import qs from 'query-string';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import { usePermission } from '@/hooks/usePermission';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
import { useAgentStore } from '@/store/agent';
@@ -134,9 +136,11 @@ const UserAgentCard = memo<UserAgentCardProps>(
isValidated,
}) => {
const { t } = useTranslation(['discover', 'setting']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { message } = App.useApp();
const { isOwner, onStatusChange } = useUserDetailContext();
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [, setIsEditLoading] = useState(false);
const createAgent = useAgentStore((s) => s.createAgent);
@@ -151,12 +155,17 @@ const UserAgentCard = memo<UserAgentCardProps>(
);
const isPublished = status === 'published';
+ // Agents under review can't be self-managed — publishing is approval-gated and
+ // the market rejects manual publish with `forbidden`. Show a view-only card
+ // (no owner action menu) until the agent has been validated.
+ const isUnderReview = isValidated === false;
const handleViewDetail = useCallback(() => {
window.open(urlJoin('/community/agent', identifier), '_blank');
}, [identifier]);
const handleEdit = useCallback(async () => {
+ if (!canEdit || !canCreate) return;
setIsEditLoading(true);
try {
// First, try to find the local agent by market identifier
@@ -203,13 +212,14 @@ const UserAgentCard = memo<UserAgentCardProps>(
} finally {
setIsEditLoading(false);
}
- }, [identifier, navigate, createAgent, refreshAgentList, message, t]);
+ }, [canCreate, canEdit, identifier, navigate, createAgent, refreshAgentList, message, t]);
const handleStatusAction = useCallback(
(action: 'publish' | 'unpublish' | 'deprecate') => {
+ if (!canEdit) return;
onStatusChange?.(identifier, action);
},
- [identifier, onStatusChange],
+ [canEdit, identifier, onStatusChange],
);
const menuItems = isOwner
@@ -221,6 +231,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
onClick: handleViewDetail,
},
{
+ disabled: !canEdit || !canCreate,
icon: <Icon icon={Pencil} />,
key: 'edit',
label: t('setting:myAgents.actions.edit'),
@@ -230,6 +241,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
type: 'divider' as const,
},
{
+ disabled: !canEdit,
icon: <Icon icon={isPublished ? EyeOff : Eye} />,
key: 'togglePublish',
label: isPublished
@@ -239,6 +251,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
},
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={AlertTriangle} />,
key: 'deprecate',
label: t('setting:myAgents.actions.deprecate'),
@@ -261,7 +274,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
}}
onClick={() => navigate(link)}
>
- {isOwner && (
+ {isOwner && !isUnderReview && (
<div onClick={stopPropagation}>
<DropdownMenu items={menuItems as any}>
<div className={cx('more-button', styles.moreButton)}>
@@ -300,7 +313,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
}}
>
<Flexbox horizontal align={'center'} gap={8}>
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', flex: 1, overflow: 'hidden' }}
to={link}
onClick={(e) => e.stopPropagation()}
@@ -308,7 +321,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
<Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>
{title}
</Text>
- </Link>
+ </WorkspaceLink>
{isValidated === false ? (
<AntTag color="orange" style={{ flexShrink: 0, margin: 0 }}>
{t('assistant.underReview', { defaultValue: 'Under Review' })}
diff --git a/src/routes/(main)/community/(detail)/user/features/UserAgentList.tsx b/src/routes/(main)/community/(detail)/user/features/UserAgentList.tsx
index ede133b3a24..9430031d9f6 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserAgentList.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserAgentList.tsx
@@ -23,7 +23,9 @@ const UserAgentList = memo<UserAgentListProps>(({ rows = 4, pageSize = 8 }) => {
forkedAgents = [],
favoriteAgents = [],
isOwner,
+ user,
} = useUserDetailContext();
+ const isOrg = user.type === 'organization';
const [currentPage, setCurrentPage] = useState(1);
const [statusFilter, setStatusFilter] = useState<StatusFilterValue>('published');
const [searchQuery, setSearchQuery] = useState('');
@@ -71,8 +73,14 @@ const UserAgentList = memo<UserAgentListProps>(({ rows = 4, pageSize = 8 }) => {
if (agents.length === 0 && forkedAgents.length === 0)
return (
<AssistantEmpty
- description={isOwner ? t('user.noAgents.ownerDescription') : t('user.noAgents')}
title={t('user.noAgents.title')}
+ description={
+ isOwner
+ ? t('user.noAgents.ownerDescription')
+ : isOrg
+ ? t('user.org.noAgents')
+ : t('user.noAgents')
+ }
/>
);
diff --git a/src/routes/(main)/community/(detail)/user/features/UserFavoriteAgents.tsx b/src/routes/(main)/community/(detail)/user/features/UserFavoriteAgents.tsx
index c2c9563b90d..7894a4c5fa8 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserFavoriteAgents.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserFavoriteAgents.tsx
@@ -17,10 +17,11 @@ import { ClockIcon, DownloadIcon, Heart } from 'lucide-react';
import qs from 'query-string';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { type FavoriteAgentItem } from '@/services/social';
import { socialService } from '@/services/social';
@@ -102,7 +103,7 @@ const FavoriteAgentCard = memo<FavoriteAgentCardProps>(
showUnfavorite,
}) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = qs.stringifyUrl(
{
@@ -163,7 +164,7 @@ const FavoriteAgentCard = memo<FavoriteAgentCardProps>(
}}
>
<Flexbox horizontal align={'center'} gap={8}>
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', flex: 1, overflow: 'hidden' }}
to={link}
onClick={stopPropagation}
@@ -171,7 +172,7 @@ const FavoriteAgentCard = memo<FavoriteAgentCardProps>(
<Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>
{name}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/user/features/UserFavoritePlugins.tsx b/src/routes/(main)/community/(detail)/user/features/UserFavoritePlugins.tsx
index fa151cb7ae8..c35f2760383 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserFavoritePlugins.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserFavoritePlugins.tsx
@@ -17,10 +17,11 @@ import { ClockIcon, Heart } from 'lucide-react';
import qs from 'query-string';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { type FavoritePluginItem } from '@/services/social';
import { socialService } from '@/services/social';
@@ -91,7 +92,7 @@ const FavoritePluginCard = memo<FavoritePluginCardProps>(
showUnfavorite,
}) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = qs.stringifyUrl(
{
@@ -151,7 +152,7 @@ const FavoritePluginCard = memo<FavoritePluginCardProps>(
}}
>
<Flexbox horizontal align={'center'} gap={8}>
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', flex: 1, overflow: 'hidden' }}
to={link}
onClick={stopPropagation}
@@ -159,7 +160,7 @@ const FavoritePluginCard = memo<FavoritePluginCardProps>(
<Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>
{name}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
index 2c07c84ba61..5c39d5e4b75 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
@@ -28,10 +28,11 @@ import {
import qs from 'query-string';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { type DiscoverGroupAgentItem, type GroupAgentStatus } from '@/types/discover';
import { formatIntergerNumber } from '@/utils/format';
@@ -126,7 +127,7 @@ const UserGroupCard = memo<UserGroupCardProps>(
isValidated,
}) => {
const { t } = useTranslation(['discover', 'setting']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { isOwner, onStatusChange } = useUserDetailContext();
const link = qs.stringifyUrl(
@@ -138,6 +139,9 @@ const UserGroupCard = memo<UserGroupCardProps>(
);
const isPublished = status === 'published';
+ // Under-review groups can't be self-managed (publish is approval-gated and the
+ // market rejects it with `forbidden`), so owners get a view-only card.
+ const isUnderReview = isValidated === false;
const handleCardClick = useCallback(() => {
navigate(link);
@@ -197,7 +201,7 @@ const UserGroupCard = memo<UserGroupCardProps>(
}}
onClick={handleCardClick}
>
- {isOwner && (
+ {isOwner && !isUnderReview && (
<div onClick={stopPropagation}>
<DropdownMenu items={menuItems as any}>
<div className={cx('more-button', styles.moreButton)}>
@@ -230,7 +234,7 @@ const UserGroupCard = memo<UserGroupCardProps>(
}}
>
<Flexbox horizontal align={'center'} gap={8}>
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', flex: 1, overflow: 'hidden' }}
to={link}
onClick={stopPropagation}
@@ -238,7 +242,7 @@ const UserGroupCard = memo<UserGroupCardProps>(
<Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>
{title}
</Text>
- </Link>
+ </WorkspaceLink>
{isValidated === false ? (
<AntTag color="orange" style={{ flexShrink: 0, margin: 0 }}>
{t('groupAgents.underReview', { defaultValue: 'Under Review' })}
diff --git a/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx
index 897074795d6..13a31106814 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx
@@ -4,9 +4,10 @@ import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { type DiscoverPluginItem } from '@/types/discover';
const styles = createStaticStyles(({ css, cssVar }) => {
@@ -45,7 +46,7 @@ type UserPluginCardProps = DiscoverPluginItem;
const UserPluginCard = memo<UserPluginCardProps>(
({ title, avatar, author, description, identifier, category }) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/plugin', identifier);
const handleClick = useCallback(() => {
@@ -98,11 +99,11 @@ const UserPluginCard = memo<UserPluginCardProps>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{title}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<Flexbox horizontal align={'center'} className={styles.author} gap={8}>
{author && <div>{author}</div>}
diff --git a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
index b6c8a339d21..8e988c36d28 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
@@ -6,10 +6,11 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ClockIcon, FileTextIcon, StarIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { discoverService } from '@/services/discover';
import { type DiscoverSkillItem } from '@/types/discover';
@@ -62,7 +63,7 @@ const UserSkillCard = memo<UserSkillCardProps>(
resourcesCount = 0,
}) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/skill', identifier);
const handleClick = useCallback(() => {
@@ -123,11 +124,11 @@ const UserSkillCard = memo<UserSkillCardProps>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{name}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<Flexbox horizontal align={'center'} className={styles.author} gap={8}>
{Boolean(ratingAvg) && (
diff --git a/src/routes/(main)/community/(detail)/user/index.tsx b/src/routes/(main)/community/(detail)/user/index.tsx
index c0caa019b37..416700721bc 100644
--- a/src/routes/(main)/community/(detail)/user/index.tsx
+++ b/src/routes/(main)/community/(detail)/user/index.tsx
@@ -1,13 +1,16 @@
'use client';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useMarketAuth, useMarketUserProfile } from '@/layout/AuthProvider/MarketAuth';
import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
import { useDiscoverStore } from '@/store/discover';
import NotFound from '../components/NotFound';
+import { resolveWorkspaceCommunityProfileRedirect } from '../workspace/features/resolveWorkspaceProfileEdit';
import { UserDetailProvider } from './features/DetailProvider';
import UserHeader from './features/Header';
import UserContent from './features/UserContent';
@@ -20,8 +23,10 @@ interface UserDetailPageProps {
const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
const params = useParams<{ slug: string }>();
+ const location = useLocation();
const username = decodeURIComponent(params.slug ?? '');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { isWorkspaceScope } = useCommunityWorkspaceProfile();
const { checkAndShowClaimableResources, getCurrentUserInfo, isAuthenticated, openProfileSetup } =
useMarketAuth();
@@ -29,22 +34,32 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
const { data, isLoading, mutate } = useUserProfile({ username });
- // Get current user's profile to check ownership by userName
+ // When inside a workspace scope, /community/user/:slug and /community/org/:slug are not the
+ // right surface — redirect to the dedicated workspace community page.
+ useEffect(() => {
+ const redirectTo = resolveWorkspaceCommunityProfileRedirect({
+ isWorkspaceScope,
+ pathname: location.pathname,
+ search: location.search,
+ });
+ if (redirectTo) navigate(redirectTo, { replace: true });
+ }, [isWorkspaceScope, location.pathname, location.search, navigate]);
+
const currentUser = getCurrentUserInfo();
const { data: currentUserProfile } = useMarketUserProfile(currentUser?.sub);
- // Check if the current user is viewing their own profile
const isOwner =
- isAuthenticated && !!currentUser && data?.user?.namespace === currentUserProfile?.namespace;
+ !isWorkspaceScope &&
+ isAuthenticated &&
+ !!currentUser &&
+ data?.user?.namespace === currentUserProfile?.namespace;
// Track if we've already checked for claimable resources in this session
const hasCheckedClaimable = useRef(false);
- // Check for claimable resources when owner visits their profile
useEffect(() => {
if (isOwner && !hasCheckedClaimable.current) {
hasCheckedClaimable.current = true;
- // Pass mutate callback to refresh page data after claim
checkAndShowClaimableResources(() => {
mutate();
});
@@ -53,18 +68,14 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
const { handleStatusChange } = useUserDetail({ onMutate: mutate });
- // Handle profile edit with navigation on userName change
const handleEditProfile = useCallback(
(onSuccess?: (profile: MarketUserProfile) => void) => {
const currentUserName = data?.user?.userName || data?.user?.namespace;
openProfileSetup((profile) => {
- // Call the original onSuccess callback if provided
onSuccess?.(profile);
- // Refresh page data to show updated profile
mutate();
- // Navigate to new URL if userName changed
const newUserName = profile.userName || profile.namespace;
if (newUserName && newUserName !== currentUserName) {
navigate(`/community/user/${newUserName}`, { replace: true });
@@ -88,6 +99,7 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
plugins,
} = data;
const totalInstalls = agents.reduce((sum, agent) => sum + (agent.installCount || 0), 0);
+
return {
agentCount: agents.length,
agentGroups: agentGroups || [],
@@ -106,7 +118,7 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
totalInstalls,
user,
};
- }, [data, isOwner, mobile, handleEditProfile, handleStatusChange]);
+ }, [data, handleEditProfile, handleStatusChange, isOwner, mobile]);
if (isLoading) return <Loading />;
if (!contextConfig) return <NotFound />;
diff --git a/src/routes/(main)/community/(detail)/utils/profileLink.ts b/src/routes/(main)/community/(detail)/utils/profileLink.ts
new file mode 100644
index 00000000000..948aa169a0e
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/utils/profileLink.ts
@@ -0,0 +1,13 @@
+import urlJoin from 'url-join';
+
+/**
+ * Resolve the community profile link for a resource author.
+ *
+ * Organization-owned resources link to the organization public page
+ * (`/community/org/:slug`), while individual users link to the user
+ * page (`/community/user/:slug`).
+ */
+export const resolveCommunityProfileLink = (
+ userName: string,
+ ownerType?: 'user' | 'organization',
+): string => urlJoin(ownerType === 'organization' ? '/community/org' : '/community/user', userName);
diff --git a/src/routes/(main)/community/(detail)/workspace/features/DetailProvider.tsx b/src/routes/(main)/community/(detail)/workspace/features/DetailProvider.tsx
new file mode 100644
index 00000000000..57ee3d3a123
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/DetailProvider.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { createContext, memo, type ReactNode, use } from 'react';
+
+import {
+ type DiscoverAssistantItem,
+ type DiscoverGroupAgentItem,
+ type DiscoverPluginItem,
+ type DiscoverSkillItem,
+ type DiscoverUserInfo,
+} from '@/types/discover';
+
+export interface WorkspaceDetailContextConfig {
+ agentCount: number;
+ agentGroups?: DiscoverGroupAgentItem[];
+ agents: DiscoverAssistantItem[];
+ canEdit: boolean;
+ groupCount: number;
+ isLoading?: boolean;
+ mobile?: boolean;
+ onEditWorkspaceProfile?: () => void;
+ onRefreshProfile?: () => Promise<void>;
+ plugins?: DiscoverPluginItem[];
+ skills?: DiscoverSkillItem[];
+ totalInstalls: number;
+ user: DiscoverUserInfo;
+}
+
+export const WorkspaceDetailContext = createContext<WorkspaceDetailContextConfig | null>(null);
+
+export const WorkspaceDetailProvider = memo<{
+ children: ReactNode;
+ config: WorkspaceDetailContextConfig;
+}>(({ children, config }) => {
+ return <WorkspaceDetailContext value={config}>{children}</WorkspaceDetailContext>;
+});
+
+export const useWorkspaceDetailContext = () => {
+ const context = use(WorkspaceDetailContext);
+ if (!context) {
+ throw new Error('useWorkspaceDetailContext must be used within WorkspaceDetailProvider');
+ }
+ return context;
+};
diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx
new file mode 100644
index 00000000000..478ce09f2f2
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { Center } from '@lobehub/ui';
+import { createStaticStyles, responsive } from 'antd-style';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ banner: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ width: 100%;
+ height: 160px;
+ padding: 16px;
+
+ ${responsive.sm} {
+ position: relative;
+
+ width: calc(100% + 32px);
+ height: 120px;
+ margin-block: -16px 0;
+ margin-inline: -16px;
+ }
+
+ @media (width <= 1720px) {
+ height: 144px;
+ padding: 0;
+ }
+ `,
+ bannerAvatar: css`
+ filter: blur(100px);
+ `,
+ bannerInner: css`
+ position: relative;
+
+ overflow: hidden;
+
+ width: 100%;
+ height: 100%;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillTertiary};
+
+ @media (width <= 1720px) {
+ border-radius: 0;
+ }
+ `,
+ placeholder: css`
+ position: relative;
+ width: 100%;
+ height: 64px;
+ min-height: 64px;
+
+ ${responsive.sm} {
+ display: none;
+ }
+ `,
+}));
+
+interface BannerProps {
+ avatar?: string | null;
+ bannerUrl?: string | null;
+}
+
+const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {
+ const backgroundImage = bannerUrl || avatar;
+ const shouldBlur = !bannerUrl && !!avatar;
+
+ return (
+ <>
+ <div className={styles.banner}>
+ <Center className={styles.bannerInner}>
+ {backgroundImage && (
+ <div
+ className={shouldBlur ? styles.bannerAvatar : undefined}
+ style={{
+ backgroundImage: `url(${backgroundImage})`,
+ backgroundPosition: 'center',
+ backgroundSize: 'cover',
+ height: '100%',
+ width: '100%',
+ }}
+ />
+ )}
+ </Center>
+ </div>
+ <div className={styles.placeholder} />
+ </>
+ );
+});
+
+export default Banner;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx
new file mode 100644
index 00000000000..2b731f42a77
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx
@@ -0,0 +1,109 @@
+// @vitest-environment happy-dom
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { type WorkspaceDetailContextConfig, WorkspaceDetailProvider } from '../DetailProvider';
+import WorkspaceHeader from './index';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('./Banner', () => ({
+ default: () => <div data-testid="workspace-banner" />,
+}));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const createConfig = (
+ overrides: Partial<WorkspaceDetailContextConfig> = {},
+): WorkspaceDetailContextConfig => ({
+ agentCount: 0,
+ agents: [],
+ canEdit: false,
+ groupCount: 0,
+ totalInstalls: 0,
+ user: {
+ avatarUrl: null,
+ bannerUrl: null,
+ createdAt: '',
+ description: null,
+ displayName: 'dsdk',
+ id: 0,
+ namespace: '',
+ socialLinks: null,
+ type: 'organization',
+ userName: null,
+ },
+ ...overrides,
+});
+
+describe('WorkspaceHeader', () => {
+ it('does not render a workspace handle before the Market namespace exists', () => {
+ render(
+ <WorkspaceDetailProvider config={createConfig({ onEditWorkspaceProfile: vi.fn() })}>
+ <WorkspaceHeader />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(screen.getByRole('heading', { name: 'dsdk' })).toBeInTheDocument();
+ expect(screen.queryByText(/^@/)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'user.setupWorkspaceProfile' })).toBeInTheDocument();
+ });
+
+ it('does not render the setup button while the profile is loading', () => {
+ render(
+ <WorkspaceDetailProvider
+ config={createConfig({ isLoading: true, onEditWorkspaceProfile: vi.fn() })}
+ >
+ <WorkspaceHeader />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(
+ screen.queryByRole('button', { name: 'user.setupWorkspaceProfile' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders the organization handle when the Market namespace exists', () => {
+ render(
+ <WorkspaceDetailProvider
+ config={createConfig({
+ user: {
+ ...createConfig().user,
+ namespace: 'org-7k3p9xq2m4',
+ },
+ })}
+ >
+ <WorkspaceHeader />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(screen.getByText('@org-7k3p9xq2m4')).toBeInTheDocument();
+ });
+
+ it('opens the public organization profile in a new tab after setup', async () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+
+ render(
+ <WorkspaceDetailProvider
+ config={createConfig({
+ onEditWorkspaceProfile: vi.fn(),
+ user: {
+ ...createConfig().user,
+ namespace: 'acme-labs',
+ },
+ })}
+ >
+ <WorkspaceHeader />
+ </WorkspaceDetailProvider>,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'user.openWorkspacePublicProfile' }));
+
+ expect(open).toHaveBeenCalledWith('/community/org/acme-labs', '_blank', 'noopener,noreferrer');
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/index.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/index.tsx
new file mode 100644
index 00000000000..db0f6b9f69f
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/index.tsx
@@ -0,0 +1,109 @@
+'use client';
+
+import {
+ ActionIcon,
+ Avatar,
+ Button,
+ Flexbox,
+ Skeleton,
+ Text,
+ Tooltip,
+ TooltipGroup,
+} from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { ExternalLink, Globe, Settings } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceDetailContext } from '../DetailProvider';
+import Banner from './Banner';
+
+const normalizeUrl = (input?: string | null) => {
+ if (!input) return undefined;
+ if (input.startsWith('/')) return `${window.location.origin}${input}`;
+ return input;
+};
+
+const getWorkspacePublicProfileUrl = (username: string) => `/community/org/${username}`;
+
+const WorkspaceHeader = memo(() => {
+ const { t } = useTranslation('discover');
+ const { user, onEditWorkspaceProfile, isLoading } = useWorkspaceDetailContext();
+
+ const displayName = user.displayName || user.userName || user.namespace;
+ const username = user.userName || user.namespace;
+ const isSetup = !username;
+
+ const avatarUrl = useMemo(() => normalizeUrl(user.avatarUrl), [user.avatarUrl]);
+ const bannerUrl = useMemo(() => normalizeUrl(user.bannerUrl), [user.bannerUrl]);
+ const publicProfileUrl = username ? getWorkspacePublicProfileUrl(username) : undefined;
+
+ const handleOpenPublicProfile = useCallback(() => {
+ if (!publicProfileUrl) return;
+
+ window.open(publicProfileUrl, '_blank', 'noopener,noreferrer');
+ }, [publicProfileUrl]);
+
+ return (
+ <>
+ <Banner avatar={avatarUrl} bannerUrl={bannerUrl} />
+ <Flexbox gap={16}>
+ <Avatar
+ avatar={avatarUrl}
+ shape={'square'}
+ size={64}
+ style={{ boxShadow: `0 0 0 4px ${cssVar.colorBgContainer}`, flexShrink: 0 }}
+ />
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4} style={{ overflow: 'hidden' }}>
+ <Text ellipsis as={'h1'} fontSize={24} style={{ margin: 0 }} weight={'bold'}>
+ {displayName}
+ </Text>
+ {username && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ @{username}
+ </Text>
+ )}
+ </Flexbox>
+ {isLoading ? (
+ <Skeleton.Button active style={{ height: 32, width: 140 }} />
+ ) : (
+ <Flexbox horizontal gap={8}>
+ {publicProfileUrl && (
+ <Button icon={ExternalLink} shape={'round'} onClick={handleOpenPublicProfile}>
+ {t('user.openWorkspacePublicProfile')}
+ </Button>
+ )}
+ {onEditWorkspaceProfile && (
+ <Button
+ icon={Settings}
+ shape={'round'}
+ type={'primary'}
+ onClick={onEditWorkspaceProfile}
+ >
+ {t(isSetup ? 'user.setupWorkspaceProfile' : 'user.editWorkspaceProfile')}
+ </Button>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+
+ {user.description && <Text as={'p'}>{user.description}</Text>}
+
+ <TooltipGroup>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {user.socialLinks?.website && (
+ <Tooltip title={user.socialLinks?.website}>
+ <a href={user?.socialLinks?.website} rel="noopener noreferrer" target="_blank">
+ <ActionIcon icon={Globe} size={20} variant={'outlined'} />
+ </a>
+ </Tooltip>
+ )}
+ </Flexbox>
+ </TooltipGroup>
+ </Flexbox>
+ </>
+ );
+});
+
+export default WorkspaceHeader;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceAgentList.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceAgentList.tsx
new file mode 100644
index 00000000000..39ef7ae35c6
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceAgentList.tsx
@@ -0,0 +1,108 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Input, Pagination } from 'antd';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AssistantEmpty from '../../../features/AssistantEmpty';
+import UserAgentCard from '../../user/features/UserAgentCard';
+import { useWorkspaceDetailContext } from './DetailProvider';
+import {
+ filterWorkspaceMarketItems,
+ type WorkspaceMarketStatusFilterValue,
+} from './filterWorkspaceMarketItems';
+import WorkspaceStatusFilter from './WorkspaceStatusFilter';
+
+interface WorkspaceAgentListProps {
+ pageSize?: number;
+ rows?: number;
+}
+
+const WorkspaceAgentList = memo<WorkspaceAgentListProps>(({ rows = 4, pageSize = 8 }) => {
+ const { t } = useTranslation('discover');
+ const { agents, agentCount, canEdit } = useWorkspaceDetailContext();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [statusFilter, setStatusFilter] = useState<WorkspaceMarketStatusFilterValue>('published');
+
+ const filteredAgents = useMemo(() => {
+ return filterWorkspaceMarketItems({
+ getDescription: (agent) => agent.description,
+ getTitle: (agent) => agent.title,
+ items: agents,
+ searchQuery,
+ status: statusFilter,
+ });
+ }, [agents, searchQuery, statusFilter]);
+
+ const paginatedAgents = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return filteredAgents.slice(startIndex, startIndex + pageSize);
+ }, [filteredAgents, currentPage, pageSize]);
+
+ useEffect(() => {
+ setCurrentPage(1);
+ }, [searchQuery, statusFilter]);
+
+ // Visitors with nothing to see get the full-page empty state; editors always keep the
+ // title + search + status filter row (matching the User page's "published agents").
+ if (agents.length === 0 && !canEdit) {
+ return (
+ <AssistantEmpty description={t('user.workspace.noAgents')} title={t('user.noAgents.title')} />
+ );
+ }
+
+ const isEmpty = agents.length === 0;
+ const showPagination = filteredAgents.length > pageSize;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={16} weight={500}>
+ {t('user.publishedAgents')}
+ </Text>
+ {agentCount > 0 && <Tag>{filteredAgents.length}</Tag>}
+ </Flexbox>
+ {canEdit && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Input.Search
+ allowClear
+ placeholder={t('user.searchPlaceholder')}
+ style={{ width: 200 }}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ <WorkspaceStatusFilter value={statusFilter} onChange={setStatusFilter} />
+ </Flexbox>
+ )}
+ </Flexbox>
+ {isEmpty ? (
+ <AssistantEmpty
+ description={t('user.workspace.noAgents')}
+ title={t('user.noAgents.title')}
+ />
+ ) : (
+ <Grid rows={rows} width={'100%'}>
+ {paginatedAgents.map((item, index) => (
+ <UserAgentCard key={item.identifier || index} {...item} />
+ ))}
+ </Grid>
+ )}
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={filteredAgents.length}
+ onChange={(page) => setCurrentPage(page)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export default WorkspaceAgentList;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx
new file mode 100644
index 00000000000..986c0ba878d
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment happy-dom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type WorkspaceDetailContextConfig, WorkspaceDetailProvider } from './DetailProvider';
+import WorkspaceContent from './WorkspaceContent';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('../../user/features/useUserDetail', () => ({
+ useUserDetail: () => ({ handleStatusChange: vi.fn() }),
+}));
+
+vi.mock('./WorkspaceAgentList', () => ({
+ default: () => <div>Created Agents</div>,
+}));
+
+vi.mock('./WorkspaceGroupList', () => ({
+ default: () => <div>Agent Groups</div>,
+}));
+
+vi.mock('./WorkspacePluginList', () => ({
+ default: () => <div>MCP</div>,
+}));
+
+const createConfig = (
+ overrides: Partial<WorkspaceDetailContextConfig> = {},
+): WorkspaceDetailContextConfig => ({
+ agentCount: 0,
+ agents: [],
+ canEdit: true,
+ groupCount: 0,
+ onEditWorkspaceProfile: vi.fn(),
+ totalInstalls: 0,
+ user: {
+ avatarUrl: null,
+ bannerUrl: null,
+ createdAt: '',
+ description: null,
+ displayName: 'Acme',
+ id: 0,
+ namespace: '',
+ socialLinks: null,
+ type: 'organization',
+ userName: null,
+ },
+ ...overrides,
+});
+
+describe('WorkspaceContent', () => {
+ it('shows setup guidance instead of published resource sections before setup', () => {
+ render(
+ <WorkspaceDetailProvider config={createConfig()}>
+ <WorkspaceContent />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(screen.getByText('user.workspaceProfile.setup.empty.title')).toBeInTheDocument();
+ expect(screen.queryByText('Created Agents')).not.toBeInTheDocument();
+ expect(screen.queryByText('MCP')).not.toBeInTheDocument();
+ });
+
+ it('opens setup from the empty state action', () => {
+ const onEditWorkspaceProfile = vi.fn();
+
+ render(
+ <WorkspaceDetailProvider config={createConfig({ onEditWorkspaceProfile })}>
+ <WorkspaceContent />
+ </WorkspaceDetailProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'user.workspaceProfile.setup.save' }));
+
+ expect(onEditWorkspaceProfile).toHaveBeenCalledOnce();
+ });
+
+ it('shows a skeleton instead of the setup empty-state while the profile is loading', () => {
+ render(
+ <WorkspaceDetailProvider config={createConfig({ isLoading: true })}>
+ <WorkspaceContent />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(screen.queryByText('user.workspaceProfile.setup.empty.title')).not.toBeInTheDocument();
+ });
+
+ it('renders resource sections after setup', () => {
+ render(
+ <WorkspaceDetailProvider
+ config={createConfig({
+ user: {
+ ...createConfig().user,
+ namespace: 'acme-labs',
+ },
+ })}
+ >
+ <WorkspaceContent />
+ </WorkspaceDetailProvider>,
+ );
+
+ expect(screen.getByText('Created Agents')).toBeInTheDocument();
+ expect(screen.getByText('MCP')).toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.tsx
new file mode 100644
index 00000000000..dc41b7ea739
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import { Button, Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Building2 } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ListLoading from '@/routes/(main)/community/components/ListLoading';
+
+import {
+ type UserDetailContextConfig,
+ UserDetailProvider,
+} from '../../user/features/DetailProvider';
+import { useUserDetail } from '../../user/features/useUserDetail';
+import { useWorkspaceDetailContext } from './DetailProvider';
+import WorkspaceAgentList from './WorkspaceAgentList';
+import WorkspaceGroupList from './WorkspaceGroupList';
+import WorkspacePluginList from './WorkspacePluginList';
+// Skill upload for organizations is not yet available, so the section is hidden for now.
+// import WorkspaceSkillList from './WorkspaceSkillList';
+
+const WorkspaceContent = memo(() => {
+ const { t } = useTranslation('discover');
+ const workspace = useWorkspaceDetailContext();
+ const { canEdit, isLoading, onEditWorkspaceProfile, user } = workspace;
+
+ // The community list cards (UserAgentCard / UserGroupCard / …) are shared with the
+ // personal-user profile and read from UserDetailContext. Bridge the workspace context
+ // into that shape so the cards render here, with the workspace owner treated as owner.
+ const { handleStatusChange } = useUserDetail({ onMutate: workspace.onRefreshProfile });
+ const userDetailConfig = useMemo<UserDetailContextConfig>(
+ () => ({
+ agentCount: workspace.agentCount,
+ agentGroups: workspace.agentGroups,
+ agents: workspace.agents,
+ groupCount: workspace.groupCount,
+ isOwner: canEdit,
+ mobile: workspace.mobile,
+ onStatusChange: canEdit ? handleStatusChange : undefined,
+ plugins: workspace.plugins,
+ skills: workspace.skills,
+ totalInstalls: workspace.totalInstalls,
+ user: workspace.user,
+ }),
+ [workspace, canEdit, handleStatusChange],
+ );
+
+ // While the market profile is still resolving we don't yet know whether this
+ // workspace has a community profile, so render a skeleton instead of flashing
+ // the setup empty-state (which would pop in and then be replaced by content).
+ if (!user.namespace && isLoading) return <ListLoading length={4} rows={4} />;
+
+ if (!user.namespace) {
+ return (
+ <Center height="100%" style={{ minHeight: '42vh' }} width="100%">
+ <Flexbox align="center" gap={16} style={{ maxWidth: 420, textAlign: 'center' }}>
+ <Icon icon={Building2} size={40} />
+ <Flexbox gap={8}>
+ <Text as="h2" fontSize={24} style={{ margin: 0 }} weight="bold">
+ {t('user.workspaceProfile.setup.empty.title')}
+ </Text>
+ <Text type="secondary">{t('user.workspaceProfile.setup.empty.description')}</Text>
+ </Flexbox>
+ {canEdit && onEditWorkspaceProfile && (
+ <Button type="primary" onClick={onEditWorkspaceProfile}>
+ {t('user.workspaceProfile.setup.save')}
+ </Button>
+ )}
+ </Flexbox>
+ </Center>
+ );
+ }
+
+ return (
+ <UserDetailProvider config={userDetailConfig}>
+ <Flexbox gap={32}>
+ <WorkspaceAgentList />
+ <WorkspaceGroupList />
+ {/* <WorkspaceSkillList /> */}
+ <WorkspacePluginList />
+ </Flexbox>
+ </UserDetailProvider>
+ );
+});
+
+export default WorkspaceContent;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceGroupList.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceGroupList.tsx
new file mode 100644
index 00000000000..2ae701a47c1
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceGroupList.tsx
@@ -0,0 +1,105 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Input, Pagination } from 'antd';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AssistantEmpty from '../../../features/AssistantEmpty';
+import UserGroupCard from '../../user/features/UserGroupCard';
+import { useWorkspaceDetailContext } from './DetailProvider';
+import {
+ filterWorkspaceMarketItems,
+ type WorkspaceMarketStatusFilterValue,
+} from './filterWorkspaceMarketItems';
+import WorkspaceStatusFilter from './WorkspaceStatusFilter';
+
+interface WorkspaceGroupListProps {
+ pageSize?: number;
+ rows?: number;
+}
+
+const WorkspaceGroupList = memo<WorkspaceGroupListProps>(({ rows = 4, pageSize = 8 }) => {
+ const { t } = useTranslation('discover');
+ const { agentGroups = [], groupCount, canEdit } = useWorkspaceDetailContext();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [statusFilter, setStatusFilter] = useState<WorkspaceMarketStatusFilterValue>('published');
+
+ const filteredGroups = useMemo(() => {
+ return filterWorkspaceMarketItems({
+ getDescription: (group) => group.description,
+ getTitle: (group) => group.title,
+ items: agentGroups,
+ searchQuery,
+ status: statusFilter,
+ });
+ }, [agentGroups, searchQuery, statusFilter]);
+
+ const paginatedGroups = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return filteredGroups.slice(startIndex, startIndex + pageSize);
+ }, [filteredGroups, currentPage, pageSize]);
+
+ useEffect(() => {
+ setCurrentPage(1);
+ }, [searchQuery, statusFilter]);
+
+ // Visitors with no groups don't see this section at all (the agent list above already
+ // renders the page-level empty state); editors always keep the title + search + status
+ // filter row, matching the "published agents" section.
+ if (agentGroups.length === 0 && !canEdit) return null;
+
+ const isEmpty = agentGroups.length === 0;
+ const showPagination = filteredGroups.length > pageSize;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={16} weight={500}>
+ {t('user.publishedGroups', { defaultValue: '创作的群组' })}
+ </Text>
+ {groupCount > 0 && <Tag>{filteredGroups.length}</Tag>}
+ </Flexbox>
+ {canEdit && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Input.Search
+ allowClear
+ placeholder={t('user.searchPlaceholder')}
+ style={{ width: 200 }}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ <WorkspaceStatusFilter value={statusFilter} onChange={setStatusFilter} />
+ </Flexbox>
+ )}
+ </Flexbox>
+ {isEmpty ? (
+ <AssistantEmpty
+ description={t('user.workspace.noGroups')}
+ title={t('user.noGroups.title')}
+ />
+ ) : (
+ <Grid rows={rows} width={'100%'}>
+ {paginatedGroups.map((item, index) => (
+ <UserGroupCard key={item.identifier || index} {...item} />
+ ))}
+ </Grid>
+ )}
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={filteredGroups.length}
+ onChange={(page) => setCurrentPage(page)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export default WorkspaceGroupList;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspacePluginList.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspacePluginList.tsx
new file mode 100644
index 00000000000..1f8ec68c805
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspacePluginList.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Input, Pagination } from 'antd';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import UserPluginCard from '../../user/features/UserPluginCard';
+import { useWorkspaceDetailContext } from './DetailProvider';
+
+interface WorkspacePluginListProps {
+ pageSize?: number;
+ rows?: number;
+}
+
+const WorkspacePluginList = memo<WorkspacePluginListProps>(({ rows = 4, pageSize = 8 }) => {
+ const { t } = useTranslation('discover');
+ const { plugins = [], canEdit } = useWorkspaceDetailContext();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [searchQuery, setSearchQuery] = useState('');
+
+ const filteredPlugins = useMemo(() => {
+ let list = [...plugins];
+ if (searchQuery.trim()) {
+ const query = searchQuery.toLowerCase();
+ list = list.filter((plugin) => {
+ const title = plugin?.title?.toLowerCase() || '';
+ const description = plugin?.description?.toLowerCase() || '';
+ return title.includes(query) || description.includes(query);
+ });
+ }
+ return list;
+ }, [plugins, searchQuery]);
+
+ const paginatedPlugins = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return filteredPlugins.slice(startIndex, startIndex + pageSize);
+ }, [filteredPlugins, currentPage, pageSize]);
+
+ useEffect(() => {
+ setCurrentPage(1);
+ }, [searchQuery]);
+
+ if (plugins.length === 0) return null;
+
+ const showPagination = filteredPlugins.length > pageSize;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={16} weight={500}>
+ {t('user.plugins')}
+ </Text>
+ {plugins.length > 0 && <Tag>{filteredPlugins.length}</Tag>}
+ </Flexbox>
+ {canEdit && plugins.length > 0 && (
+ <Input.Search
+ allowClear
+ placeholder={t('user.searchPlaceholder')}
+ style={{ width: 200 }}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ )}
+ </Flexbox>
+ <Grid rows={rows} width={'100%'}>
+ {paginatedPlugins.map((item, index) => (
+ <UserPluginCard key={item.identifier || index} {...item} />
+ ))}
+ </Grid>
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={filteredPlugins.length}
+ onChange={(page) => setCurrentPage(page)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export default WorkspacePluginList;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx
new file mode 100644
index 00000000000..530b928e82f
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx
@@ -0,0 +1,493 @@
+'use client';
+
+import { OFFICIAL_URL } from '@lobechat/const';
+import type { CollapseProps } from '@lobehub/ui';
+import {
+ Button,
+ Center,
+ Collapse,
+ Flexbox,
+ Icon,
+ Input,
+ Text,
+ TextArea,
+ Tooltip,
+} from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import type { UploadProps } from 'antd';
+import { App, Form, Input as AntInput, Upload } from 'antd';
+import { cssVar } from 'antd-style';
+import { CircleHelp, Globe, ImagePlus, Loader2, Trash2 } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ checkCommunityWorkspaceNamespaceAvailable,
+ isCommunityWorkspaceNamespaceTakenError,
+ setupCommunityWorkspaceProfile,
+ updateCommunityWorkspaceProfile,
+} from '@/business/client/services/communityWorkspaceProfile';
+import EmojiPicker from '@/components/EmojiPicker';
+import { useFileStore } from '@/store/file';
+import type { DiscoverUserInfo } from '@/types/discover';
+
+interface FormValues {
+ description?: string;
+ displayName: string;
+ namespace?: string;
+ websiteUrl?: string;
+}
+
+interface ContentProps {
+ onSuccess?: () => void | Promise<void>;
+ user: DiscoverUserInfo;
+}
+
+const trimOptional = (value: string | undefined) => {
+ const trimmed = value?.trim();
+ return trimmed || undefined;
+};
+
+const MAX_FILE_SIZE = 2 * 1024 * 1024;
+const ORGANIZATION_URL_PREFIX = `${OFFICIAL_URL.replace(/^https?:\/\//, '')}/community/org/`;
+
+const normalizeNamespace = (value: string) =>
+ value
+ .trim()
+ .toLowerCase()
+ .replaceAll(/[^a-z0-9-]/g, '-')
+ .replaceAll(/-+/g, '-')
+ .replaceAll(/^-|-$/g, '')
+ .slice(0, 32);
+
+// Mirrors the namespace Form rules below — only run the live availability check
+// once the handle is well-formed, so we don't probe Market for invalid input.
+const NAMESPACE_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
+const isNamespaceFormatValid = (value: string) =>
+ value.length >= 3 && value.length <= 32 && NAMESPACE_PATTERN.test(value);
+
+type NamespaceAvailability = 'available' | 'checking' | 'idle' | 'taken';
+
+export const Content = memo<ContentProps>(({ user, onSuccess }) => {
+ const { t } = useTranslation('discover');
+ const { message } = App.useApp();
+ const { close } = useModalContext();
+ const [form] = Form.useForm<FormValues>();
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [avatarUrl, setAvatarUrl] = useState<string | null>(user.avatarUrl ?? null);
+ const [avatarUploading, setAvatarUploading] = useState(false);
+ const [bannerUrl, setBannerUrl] = useState<string | null>(user.bannerUrl ?? null);
+ const [bannerUploading, setBannerUploading] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const isSetup = !user.namespace;
+
+ // Live namespace-availability check (setup only — the handle is immutable once
+ // set). Mirrors the workspace create wizard's slug check: debounce, only probe
+ // a well-formed handle, and treat it purely as a UX hint — the setup mutation
+ // still rejects a taken handle on submit.
+ const namespaceValue = Form.useWatch('namespace', form);
+ const trimmedNamespace = (namespaceValue ?? '').trim();
+ const [namespaceAvailability, setNamespaceAvailability] = useState<NamespaceAvailability>('idle');
+
+ useEffect(() => {
+ if (!isSetup || !isNamespaceFormatValid(trimmedNamespace)) {
+ setNamespaceAvailability('idle');
+ return;
+ }
+ setNamespaceAvailability('checking');
+ let cancelled = false;
+ const timer = setTimeout(async () => {
+ try {
+ const available = await checkCommunityWorkspaceNamespaceAvailable(trimmedNamespace);
+ if (!cancelled) setNamespaceAvailability(available ? 'available' : 'taken');
+ } catch {
+ // Transient error — don't block; the setup mutation guards uniqueness.
+ if (!cancelled) setNamespaceAvailability('idle');
+ }
+ }, 400);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [isSetup, trimmedNamespace]);
+
+ const namespaceStatusNode = useMemo(() => {
+ if (!isSetup || namespaceAvailability === 'idle') return null;
+ const color = {
+ available: cssVar.colorSuccess,
+ checking: cssVar.colorTextSecondary,
+ taken: cssVar.colorError,
+ }[namespaceAvailability];
+ return (
+ <Flexbox horizontal align="center" gap={6} style={{ color, fontSize: 12 }}>
+ {namespaceAvailability === 'checking' && <Icon spin icon={Loader2} size={13} />}
+ {t(`user.workspaceProfile.fields.namespace.${namespaceAvailability}` as any)}
+ </Flexbox>
+ );
+ }, [isSetup, namespaceAvailability, t]);
+
+ const handleAvatarUpload = useCallback(
+ async (file: File) => {
+ if (file.size > MAX_FILE_SIZE) {
+ message.error(t('user.workspaceProfile.errors.fileTooLarge'));
+ return;
+ }
+
+ setAvatarUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) {
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ return;
+ }
+ setAvatarUrl(
+ result.url.startsWith('/') ? `${window.location.origin}${result.url}` : result.url,
+ );
+ } catch (error) {
+ console.error('[WorkspaceProfileModal] Avatar upload failed:', error);
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ } finally {
+ setAvatarUploading(false);
+ }
+ },
+ [message, t, uploadWithProgress],
+ );
+
+ const handleAvatarChange = useCallback((next: string) => {
+ if (next.startsWith('data:')) return;
+ try {
+ const { protocol } = new URL(next);
+ if (protocol === 'http:' || protocol === 'https:') {
+ setAvatarUrl(next);
+ }
+ } catch {
+ // Workspace Market profiles only accept URL avatars.
+ }
+ }, []);
+
+ const handleBannerUpload: UploadProps['customRequest'] = useCallback(
+ async (options: Parameters<NonNullable<UploadProps['customRequest']>>[0]) => {
+ const file = options.file as File;
+
+ if (file.size > MAX_FILE_SIZE) {
+ message.error(t('user.workspaceProfile.errors.fileTooLarge'));
+ options.onError?.(new Error('File too large'));
+ return;
+ }
+
+ setBannerUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) {
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ options.onError?.(new Error('Upload failed'));
+ return;
+ }
+ const url = result.url.startsWith('/')
+ ? `${window.location.origin}${result.url}`
+ : result.url;
+ setBannerUrl(url);
+ options.onSuccess?.(result);
+ } catch (error) {
+ console.error('[WorkspaceProfileModal] Banner upload failed:', error);
+ message.error(t('user.workspaceProfile.errors.uploadFailed'));
+ options.onError?.(error as Error);
+ } finally {
+ setBannerUploading(false);
+ }
+ },
+ [message, t, uploadWithProgress],
+ );
+
+ const handleSave = useCallback(async () => {
+ if (loading) return;
+
+ const values = await form.validateFields();
+
+ if (isSetup && namespaceAvailability === 'taken') {
+ message.error(t('user.workspaceProfile.fields.namespace.taken'));
+ return;
+ }
+
+ setLoading(true);
+ try {
+ const profile = {
+ avatarUrl,
+ bannerUrl,
+ description: trimOptional(values.description),
+ displayName: values.displayName.trim(),
+ websiteUrl: trimOptional(values.websiteUrl),
+ };
+
+ if (isSetup) {
+ await setupCommunityWorkspaceProfile({
+ ...profile,
+ namespace: values.namespace!.trim(),
+ });
+ } else {
+ await updateCommunityWorkspaceProfile(profile);
+ }
+
+ message.success(
+ t(isSetup ? 'user.workspaceProfile.setup.success' : 'user.workspaceProfile.success'),
+ );
+ await onSuccess?.();
+ close();
+ } catch (error) {
+ console.error('[WorkspaceProfileModal] Failed to update workspace profile:', error);
+ // Surface a namespace conflict (e.g. the handle was claimed between the
+ // live check and submit) as a taken-handle message instead of a generic one.
+ if (isSetup && isCommunityWorkspaceNamespaceTakenError(error)) {
+ setNamespaceAvailability('taken');
+ message.error(t('user.workspaceProfile.fields.namespace.taken'));
+ } else {
+ message.error(
+ t(isSetup ? 'user.workspaceProfile.setup.failed' : 'user.workspaceProfile.failed'),
+ );
+ }
+ } finally {
+ setLoading(false);
+ }
+ }, [
+ avatarUrl,
+ bannerUrl,
+ close,
+ form,
+ isSetup,
+ loading,
+ message,
+ namespaceAvailability,
+ onSuccess,
+ t,
+ ]);
+
+ const optionalItems = useMemo<CollapseProps['items']>(
+ () => [
+ {
+ children: (
+ <>
+ <Form.Item
+ label={t('user.workspaceProfile.fields.websiteUrl')}
+ name="websiteUrl"
+ rules={[{ message: t('user.workspaceProfile.errors.url'), type: 'url' }]}
+ >
+ <Input
+ placeholder={t('user.workspaceProfile.fields.websiteUrl.placeholder')}
+ prefix={
+ <Icon color={cssVar.colorTextSecondary} icon={Globe} style={{ marginRight: 8 }} />
+ }
+ />
+ </Form.Item>
+
+ <Form.Item
+ label={
+ <Flexbox horizontal align="center" gap={4}>
+ {t('user.workspaceProfile.fields.bannerUrl')}
+ <Tooltip title={t('user.workspaceProfile.fields.bannerUrl.tooltip')}>
+ <CircleHelp size={14} style={{ cursor: 'help', opacity: 0.5 }} />
+ </Tooltip>
+ </Flexbox>
+ }
+ >
+ <Flexbox gap={8} width="100%">
+ <Upload
+ accept="image/*"
+ customRequest={handleBannerUpload}
+ maxCount={1}
+ showUploadList={false}
+ style={{ display: 'block', width: '100%' }}
+ >
+ <div
+ style={{
+ backgroundColor: bannerUrl ? undefined : cssVar.colorFillTertiary,
+ backgroundImage: bannerUrl ? `url(${bannerUrl})` : undefined,
+ backgroundPosition: 'center',
+ backgroundSize: 'cover',
+ borderRadius: cssVar.borderRadiusLG,
+ cursor: 'pointer',
+ height: 160,
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ >
+ <Center
+ style={{
+ background: bannerUrl ? 'rgba(0,0,0,0.4)' : 'transparent',
+ height: '100%',
+ opacity: bannerUrl ? 0 : 1,
+ transition: 'opacity 0.2s',
+ width: '100%',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.opacity = '1';
+ }}
+ onMouseLeave={(e) => {
+ if (bannerUrl) e.currentTarget.style.opacity = '0';
+ }}
+ >
+ <Flexbox align="center" gap={8}>
+ <ImagePlus
+ size={24}
+ style={{ color: bannerUrl ? '#fff' : cssVar.colorTextSecondary }}
+ />
+ <Text
+ style={{
+ color: bannerUrl ? '#fff' : cssVar.colorTextSecondary,
+ fontSize: 12,
+ }}
+ >
+ {bannerUploading
+ ? t('user.workspaceProfile.fields.bannerUrl.uploading')
+ : t('user.workspaceProfile.fields.bannerUrl.clickToUpload')}
+ </Text>
+ </Flexbox>
+ </Center>
+ </div>
+ </Upload>
+ {bannerUrl && (
+ <Flexbox horizontal align="center" gap={8} justify="flex-end">
+ <Text
+ style={{
+ color: cssVar.colorError,
+ cursor: 'pointer',
+ fontSize: 12,
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ setBannerUrl(null);
+ }}
+ >
+ <Flexbox horizontal align="center" gap={4}>
+ <Trash2 size={12} />
+ {t('user.workspaceProfile.fields.bannerUrl.remove')}
+ </Flexbox>
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </Form.Item>
+ </>
+ ),
+ key: 'optional',
+ label: t('user.workspaceProfile.optional.toggle'),
+ },
+ ],
+ [bannerUploading, bannerUrl, handleBannerUpload, t],
+ );
+
+ return (
+ <Flexbox gap={20} padding={24}>
+ <Form
+ form={form}
+ layout="vertical"
+ initialValues={{
+ description: user.description ?? undefined,
+ displayName: user.displayName ?? user.userName ?? user.namespace,
+ namespace: user.namespace || normalizeNamespace(user.displayName ?? user.userName ?? ''),
+ websiteUrl: user.socialLinks?.website,
+ }}
+ >
+ <Flexbox horizontal gap={24}>
+ <Flexbox flex={1}>
+ <Form.Item
+ label={t('user.workspaceProfile.fields.displayName')}
+ name="displayName"
+ rules={[
+ { message: t('user.workspaceProfile.errors.displayName'), required: true },
+ { max: 50, message: t('user.workspaceProfile.fields.displayName.maxLength') },
+ ]}
+ >
+ <Input
+ showCount
+ maxLength={50}
+ placeholder={t('user.workspaceProfile.fields.displayName.placeholder')}
+ />
+ </Form.Item>
+ </Flexbox>
+
+ <Form.Item>
+ <EmojiPicker
+ allowDelete={!!avatarUrl}
+ loading={avatarUploading}
+ shape="square"
+ size={80}
+ value={avatarUrl || undefined}
+ allowUpload={{
+ enableEmoji: false,
+ }}
+ onChange={handleAvatarChange}
+ onDelete={() => setAvatarUrl(null)}
+ onUpload={handleAvatarUpload}
+ />
+ </Form.Item>
+ </Flexbox>
+
+ {isSetup && (
+ <Form.Item
+ extra={namespaceStatusNode}
+ label={t('user.workspaceProfile.fields.namespace')}
+ name="namespace"
+ rules={[
+ { message: t('user.workspaceProfile.errors.namespace.required'), required: true },
+ { max: 32, message: t('user.workspaceProfile.errors.namespace.length') },
+ { min: 3, message: t('user.workspaceProfile.errors.namespace.length') },
+ {
+ message: t('user.workspaceProfile.errors.namespace.pattern'),
+ pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,
+ },
+ ]}
+ >
+ <AntInput
+ showCount
+ addonBefore={ORGANIZATION_URL_PREFIX}
+ maxLength={32}
+ placeholder={t('user.workspaceProfile.fields.namespace.placeholder')}
+ />
+ </Form.Item>
+ )}
+
+ <Form.Item
+ label={t('user.workspaceProfile.fields.description')}
+ name="description"
+ rules={[{ max: 200, message: t('user.workspaceProfile.fields.description.maxLength') }]}
+ >
+ <TextArea
+ showCount
+ maxLength={200}
+ placeholder={t('user.workspaceProfile.fields.description.placeholder')}
+ rows={3}
+ />
+ </Form.Item>
+
+ <Collapse
+ defaultActiveKey={isSetup ? undefined : ['optional']}
+ expandIconPlacement="end"
+ items={optionalItems}
+ size="small"
+ variant="borderless"
+ styles={{
+ header: { cursor: 'pointer', width: '100%' },
+ title: { cursor: 'pointer', width: '100%' },
+ }}
+ />
+ </Form>
+
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={loading} onClick={close}>
+ {t('user.workspaceProfile.cancel')}
+ </Button>
+ <Button
+ disabled={isSetup && namespaceAvailability === 'taken'}
+ loading={loading}
+ type="primary"
+ onClick={handleSave}
+ >
+ {t(isSetup ? 'user.workspaceProfile.setup.save' : 'user.workspaceProfile.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+Content.displayName = 'WorkspaceProfileModalContent';
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/index.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/index.tsx
new file mode 100644
index 00000000000..188154aa87d
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/index.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import type { ModalInstance } from '@lobehub/ui/base-ui';
+import { createModal } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import type { DiscoverUserInfo } from '@/types/discover';
+
+import { Content } from './Content';
+
+interface OpenWorkspaceProfileModalOptions {
+ onSuccess?: () => void | Promise<void>;
+ user: DiscoverUserInfo;
+}
+
+export const openWorkspaceProfileModal = ({
+ user,
+ onSuccess,
+}: OpenWorkspaceProfileModalOptions): ModalInstance => {
+ const title = t(
+ user.namespace ? 'user.workspaceProfile.title' : 'user.workspaceProfile.setup.title',
+ {
+ ns: 'discover',
+ },
+ );
+
+ return createModal({
+ content: <Content user={user} onSuccess={onSuccess} />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: { padding: 0 },
+ },
+ title: user.namespace ? (
+ title
+ ) : (
+ <Flexbox gap={8}>
+ <span>{title}</span>
+ <Text style={{ fontSize: 14, fontWeight: 400, lineHeight: 1.5 }} type="secondary">
+ {t('user.workspaceProfile.setup.description', { ns: 'discover' })}
+ </Text>
+ </Flexbox>
+ ),
+ width: 'min(92vw, 560px)',
+ });
+};
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceSkillList.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceSkillList.tsx
new file mode 100644
index 00000000000..28ca60e9716
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceSkillList.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Input, Pagination } from 'antd';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+import SubmitRepoModal from '../../user/features/SubmitRepoModal';
+import UserSkillCard from '../../user/features/UserSkillCard';
+import { useWorkspaceDetailContext } from './DetailProvider';
+
+interface WorkspaceSkillListProps {
+ pageSize?: number;
+ rows?: number;
+}
+
+const WorkspaceSkillList = memo<WorkspaceSkillListProps>(({ rows = 4, pageSize = 8 }) => {
+ const { t } = useTranslation('discover');
+ const { skills = [], canEdit, onRefreshProfile } = useWorkspaceDetailContext();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [submitModalOpen, setSubmitModalOpen] = useState(false);
+
+ const prepareWorkspaceSubmit = useCallback(async () => {
+ const { marketAccountId } = await lambdaClient.workspace.ensureMarketOrganization.mutate();
+ return { actAs: marketAccountId };
+ }, []);
+
+ const filteredSkills = useMemo(() => {
+ let list = [...skills];
+ if (searchQuery.trim()) {
+ const query = searchQuery.toLowerCase();
+ list = list.filter((skill) => {
+ const name = skill?.name?.toLowerCase() || '';
+ const description = skill?.description?.toLowerCase() || '';
+ return name.includes(query) || description.includes(query);
+ });
+ }
+ return list;
+ }, [skills, searchQuery]);
+
+ const paginatedSkills = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return filteredSkills.slice(startIndex, startIndex + pageSize);
+ }, [filteredSkills, currentPage, pageSize]);
+
+ useEffect(() => {
+ setCurrentPage(1);
+ }, [searchQuery]);
+
+ if (skills.length === 0 && !canEdit) return null;
+
+ const showPagination = filteredSkills.length > pageSize;
+
+ return (
+ <>
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={16} weight={500}>
+ {t('user.skills')}
+ </Text>
+ {skills.length > 0 && <Tag>{filteredSkills.length}</Tag>}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {canEdit && skills.length > 0 && (
+ <Input.Search
+ allowClear
+ placeholder={t('user.searchPlaceholder')}
+ style={{ width: 200 }}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ )}
+ {/* Skill upload to community is temporarily disabled
+ {canEdit && (
+ <Button icon={<Plus size={14} />} onClick={() => setSubmitModalOpen(true)}>
+ {t('user.submitRepo')}
+ </Button>
+ )} */}
+ </Flexbox>
+ </Flexbox>
+ {skills.length > 0 ? (
+ <Grid rows={rows} width={'100%'}>
+ {paginatedSkills.map((item, index) => (
+ <UserSkillCard key={item.identifier || index} {...item} />
+ ))}
+ </Grid>
+ ) : (
+ <Flexbox align={'center'} justify={'center'} style={{ minHeight: 120, opacity: 0.5 }}>
+ <Text type={'secondary'}>{t('user.noSkills')}</Text>
+ </Flexbox>
+ )}
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={filteredSkills.length}
+ onChange={(page) => setCurrentPage(page)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ <SubmitRepoModal
+ beforeSubmit={prepareWorkspaceSubmit}
+ open={submitModalOpen}
+ onClose={() => setSubmitModalOpen(false)}
+ onSuccess={onRefreshProfile}
+ />
+ </>
+ );
+});
+
+export default WorkspaceSkillList;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceStatusFilter.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceStatusFilter.tsx
new file mode 100644
index 00000000000..5ab635c1a8a
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceStatusFilter.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { Select } from 'antd';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WorkspaceMarketStatusFilterValue } from './filterWorkspaceMarketItems';
+
+interface WorkspaceStatusFilterProps {
+ onChange: (value: WorkspaceMarketStatusFilterValue) => void;
+ value: WorkspaceMarketStatusFilterValue;
+}
+
+const WorkspaceStatusFilter = memo<WorkspaceStatusFilterProps>(({ value, onChange }) => {
+ const { t } = useTranslation('discover');
+
+ const options = [
+ { label: t('user.statusFilter.published'), value: 'published' as const },
+ { label: t('user.statusFilter.unpublished'), value: 'unpublished' as const },
+ { label: t('user.statusFilter.deprecated'), value: 'deprecated' as const },
+ { label: t('user.statusFilter.archived'), value: 'archived' as const },
+ ];
+
+ return <Select options={options} style={{ minWidth: 120 }} value={value} onChange={onChange} />;
+});
+
+export default WorkspaceStatusFilter;
diff --git a/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.test.ts b/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.test.ts
new file mode 100644
index 00000000000..1d818c04ba4
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ filterWorkspaceMarketItems,
+ type WorkspaceMarketStatusFilterValue,
+} from './filterWorkspaceMarketItems';
+
+interface TestItem {
+ description: string;
+ status: WorkspaceMarketStatusFilterValue;
+ title: string;
+}
+
+describe('filterWorkspaceMarketItems', () => {
+ const items: TestItem[] = [
+ {
+ description: 'Published sales helper',
+ status: 'published',
+ title: 'Sales Assistant',
+ },
+ {
+ description: 'Draft marketing helper',
+ status: 'unpublished',
+ title: 'Marketing Assistant',
+ },
+ {
+ description: 'Archived operations helper',
+ status: 'archived',
+ title: 'Ops Assistant',
+ },
+ ];
+
+ it('filters items by status', () => {
+ expect(
+ filterWorkspaceMarketItems({
+ getDescription: (item) => item.description,
+ getTitle: (item) => item.title,
+ items,
+ searchQuery: '',
+ status: 'unpublished',
+ }),
+ ).toEqual([items[1]]);
+ });
+
+ it('filters items by search query case-insensitively', () => {
+ expect(
+ filterWorkspaceMarketItems({
+ getDescription: (item) => item.description,
+ getTitle: (item) => item.title,
+ items,
+ searchQuery: 'SALES',
+ status: 'published',
+ }),
+ ).toEqual([items[0]]);
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.ts b/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.ts
new file mode 100644
index 00000000000..47161e6e70a
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/filterWorkspaceMarketItems.ts
@@ -0,0 +1,37 @@
+export type WorkspaceMarketStatusFilterValue =
+ | 'published'
+ | 'unpublished'
+ | 'deprecated'
+ | 'archived';
+
+interface WorkspaceMarketStatusItem {
+ status?: WorkspaceMarketStatusFilterValue;
+}
+
+interface FilterWorkspaceMarketItemsParams<T extends WorkspaceMarketStatusItem> {
+ getDescription: (item: T) => string | null | undefined;
+ getTitle: (item: T) => string | null | undefined;
+ items: T[];
+ searchQuery: string;
+ status: WorkspaceMarketStatusFilterValue;
+}
+
+export const filterWorkspaceMarketItems = <T extends WorkspaceMarketStatusItem>({
+ getDescription,
+ getTitle,
+ items,
+ searchQuery,
+ status,
+}: FilterWorkspaceMarketItemsParams<T>) => {
+ const query = searchQuery.trim().toLowerCase();
+
+ return items.filter((item) => {
+ if (item.status !== status) return false;
+ if (!query) return true;
+
+ const title = getTitle(item)?.toLowerCase() || '';
+ const description = getDescription(item)?.toLowerCase() || '';
+
+ return title.includes(query) || description.includes(query);
+ });
+};
diff --git a/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.test.ts b/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.test.ts
new file mode 100644
index 00000000000..a998e1aeb5b
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.test.ts
@@ -0,0 +1,162 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ resolveCommunityProfileUsername,
+ resolveWorkspaceCommunityProfile,
+ resolveWorkspaceCommunityProfileRedirect,
+ shouldShowWorkspaceProfileEdit,
+} from './resolveWorkspaceProfileEdit';
+
+describe('shouldShowWorkspaceProfileEdit', () => {
+ it('returns true for the active workspace organization when editing is allowed', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: true,
+ marketOrganizationProfile: { accountId: 42 },
+ user: { id: 42, type: 'organization' },
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false for personal user profiles', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: true,
+ marketOrganizationProfile: { accountId: 42 },
+ user: { id: 42, type: 'user' },
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false for a different organization profile', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: true,
+ marketOrganizationProfile: { accountId: 42 },
+ user: { id: 99, type: 'organization' },
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false when the caller cannot edit the workspace', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: false,
+ marketOrganizationProfile: { accountId: 42 },
+ user: { id: 42, type: 'organization' },
+ }),
+ ).toBe(false);
+ });
+
+ it('returns true for an owner before the Market organization is provisioned', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: true,
+ marketOrganizationProfile: null,
+ user: { id: 0, type: 'organization' },
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false for a non-owner before the Market organization is provisioned', () => {
+ expect(
+ shouldShowWorkspaceProfileEdit({
+ canEdit: false,
+ marketOrganizationProfile: null,
+ user: { id: 0, type: 'organization' },
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('resolveCommunityProfileUsername', () => {
+ it('uses the workspace organization username in workspace scope', () => {
+ expect(
+ resolveCommunityProfileUsername({
+ routeUsername: 'personal-user',
+ workspaceUsername: 'ws-team',
+ }),
+ ).toBe('ws-team');
+ });
+
+ it('uses the route username outside workspace scope', () => {
+ expect(
+ resolveCommunityProfileUsername({
+ routeUsername: 'personal-user',
+ }),
+ ).toBe('personal-user');
+ });
+});
+
+describe('resolveWorkspaceCommunityProfileRedirect', () => {
+ it('redirects workspace user URLs to the workspace Community page', () => {
+ expect(
+ resolveWorkspaceCommunityProfileRedirect({
+ isWorkspaceScope: true,
+ pathname: '/hug/community/user/rdmclin2',
+ }),
+ ).toBe('/community/workspace');
+ });
+
+ it('redirects workspace org URLs to the workspace Community page', () => {
+ expect(
+ resolveWorkspaceCommunityProfileRedirect({
+ isWorkspaceScope: true,
+ pathname: '/hug/community/org/other',
+ search: '?tab=skills',
+ }),
+ ).toBe('/community/workspace?tab=skills');
+ });
+
+ it('keeps the current URL outside workspace scope', () => {
+ expect(
+ resolveWorkspaceCommunityProfileRedirect({
+ isWorkspaceScope: false,
+ pathname: '/community/user/rdmclin2',
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('resolveWorkspaceCommunityProfile', () => {
+ const baseProfile = {
+ agentGroups: [],
+ agents: [],
+ favoriteAgentGroups: [],
+ favoriteAgents: [],
+ forkedAgentGroups: [],
+ forkedAgents: [],
+ plugins: [],
+ skills: [],
+ user: {
+ avatarUrl: null,
+ bannerUrl: null,
+ createdAt: '',
+ description: null,
+ displayName: 'Market workspace',
+ followersCount: 0,
+ followingCount: 0,
+ id: 42,
+ namespace: 'ws-xuxu',
+ socialLinks: null,
+ type: 'organization',
+ userName: null,
+ },
+ };
+
+ it('uses workspace avatar when the Market organization profile has no avatar', () => {
+ expect(
+ resolveWorkspaceCommunityProfile({
+ fallbackProfile: {
+ ...baseProfile,
+ user: {
+ ...baseProfile.user,
+ avatarUrl: '/avatars/workspace.png',
+ displayName: 'xuxu',
+ },
+ },
+ marketProfile: baseProfile,
+ })?.user.avatarUrl,
+ ).toBe('/avatars/workspace.png');
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.ts b/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.ts
new file mode 100644
index 00000000000..9e50d446723
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/features/resolveWorkspaceProfileEdit.ts
@@ -0,0 +1,85 @@
+import type { DiscoverUserProfile } from '@/types/discover';
+
+interface CommunityProfileOwner {
+ id: number;
+ type?: string | null;
+}
+
+interface MarketOrganizationProfileRef {
+ accountId: number;
+}
+
+interface ShouldShowWorkspaceProfileEditParams {
+ canEdit: boolean;
+ marketOrganizationProfile?: MarketOrganizationProfileRef | null;
+ user: CommunityProfileOwner;
+}
+
+interface ResolveCommunityProfileUsernameParams {
+ routeUsername: string;
+ workspaceUsername?: string | null;
+}
+
+interface ResolveWorkspaceCommunityProfileRedirectParams {
+ isWorkspaceScope: boolean;
+ pathname: string;
+ search?: string;
+}
+
+interface ResolveWorkspaceCommunityProfileParams {
+ fallbackProfile: DiscoverUserProfile | null;
+ marketProfile?: DiscoverUserProfile;
+}
+
+export const shouldShowWorkspaceProfileEdit = ({
+ canEdit,
+ marketOrganizationProfile,
+ user,
+}: ShouldShowWorkspaceProfileEditParams) => {
+ if (!canEdit || user.type !== 'organization') return false;
+ // The workspace's mirror Market organization is provisioned lazily (on the
+ // first write to Market). Before it exists, `marketOrganizationProfile` is
+ // null — an owner should still see the edit entry on their own workspace
+ // Community page; saving provisions the organization on demand. Once
+ // provisioned, the accountId must match the viewed profile so the edit entry
+ // never leaks onto a different organization's page.
+ if (!marketOrganizationProfile) return true;
+ return marketOrganizationProfile.accountId === user.id;
+};
+
+export const resolveCommunityProfileUsername = ({
+ routeUsername,
+ workspaceUsername,
+}: ResolveCommunityProfileUsernameParams) => workspaceUsername || routeUsername;
+
+export const resolveWorkspaceCommunityProfile = ({
+ fallbackProfile,
+ marketProfile,
+}: ResolveWorkspaceCommunityProfileParams): DiscoverUserProfile | null => {
+ if (!marketProfile) return fallbackProfile;
+ if (!fallbackProfile) return marketProfile;
+
+ return {
+ ...marketProfile,
+ user: {
+ ...marketProfile.user,
+ avatarUrl: marketProfile.user.avatarUrl || fallbackProfile.user.avatarUrl,
+ description: marketProfile.user.description ?? fallbackProfile.user.description,
+ displayName: marketProfile.user.displayName || fallbackProfile.user.displayName,
+ },
+ };
+};
+
+export const resolveWorkspaceCommunityProfileRedirect = ({
+ isWorkspaceScope,
+ pathname,
+ search = '',
+}: ResolveWorkspaceCommunityProfileRedirectParams) => {
+ if (!isWorkspaceScope) return null;
+
+ const targetPath = '/community/workspace';
+ if (pathname.endsWith(targetPath)) return null;
+ if (!pathname.includes('/community/user/') && !pathname.includes('/community/org/')) return null;
+
+ return `${targetPath}${search}`;
+};
diff --git a/src/routes/(main)/community/(detail)/workspace/index.tsx b/src/routes/(main)/community/(detail)/workspace/index.tsx
new file mode 100644
index 00000000000..95b39168bf6
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/index.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import { memo, useCallback, useMemo } from 'react';
+
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useDiscoverStore } from '@/store/discover';
+import type { DiscoverUserProfile } from '@/types/discover';
+
+import NotFound from '../components/NotFound';
+import { WorkspaceDetailProvider } from './features/DetailProvider';
+import WorkspaceHeader from './features/Header';
+import {
+ resolveWorkspaceCommunityProfile,
+ shouldShowWorkspaceProfileEdit,
+} from './features/resolveWorkspaceProfileEdit';
+import WorkspaceContent from './features/WorkspaceContent';
+import { openWorkspaceProfileModal } from './features/WorkspaceProfileModal';
+import Loading from './loading';
+
+interface WorkspaceDetailPageProps {
+ mobile?: boolean;
+}
+
+const WorkspaceDetailPage = memo<WorkspaceDetailPageProps>(({ mobile }) => {
+ const {
+ avatarUrl: workspaceAvatarUrl,
+ bannerUrl: workspaceBannerUrl,
+ canEdit,
+ description: workspaceDescription,
+ displayName: workspaceDisplayName,
+ isLoading: isWorkspaceProfileLoading,
+ profile: marketOrganizationProfile,
+ refresh: refreshWorkspaceProfile,
+ username: workspaceUsername,
+ } = useCommunityWorkspaceProfile();
+ const navigate = useWorkspaceAwareNavigate();
+
+ const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
+ const {
+ data,
+ isLoading: isUserProfileLoading,
+ mutate,
+ } = useUserProfile({
+ username: workspaceUsername ?? '',
+ });
+
+ // Fallback profile so the page header renders even before the market profile is materialized
+ const fallbackProfile = useMemo<DiscoverUserProfile | null>(() => {
+ const displayName = workspaceDisplayName ?? workspaceUsername;
+ if (!displayName) return null;
+
+ return {
+ agentGroups: [],
+ agents: [],
+ favoriteAgentGroups: [],
+ favoriteAgents: [],
+ forkedAgentGroups: [],
+ forkedAgents: [],
+ plugins: [],
+ skills: [],
+ user: {
+ avatarUrl: workspaceAvatarUrl ?? null,
+ bannerUrl: workspaceBannerUrl ?? null,
+ createdAt: '',
+ description: workspaceDescription ?? null,
+ displayName,
+ followersCount: 0,
+ followingCount: 0,
+ id: marketOrganizationProfile?.accountId ?? 0,
+ namespace: workspaceUsername ?? '',
+ socialLinks: null,
+ type: 'organization',
+ userName: null,
+ },
+ };
+ }, [
+ marketOrganizationProfile?.accountId,
+ workspaceAvatarUrl,
+ workspaceBannerUrl,
+ workspaceDescription,
+ workspaceDisplayName,
+ workspaceUsername,
+ ]);
+
+ const profileData = useMemo(
+ () =>
+ resolveWorkspaceCommunityProfile({
+ fallbackProfile,
+ marketProfile: data,
+ }),
+ [data, fallbackProfile],
+ );
+
+ const handleEditWorkspaceProfile = useCallback(() => {
+ if (marketOrganizationProfile) {
+ navigate('/community/workspace/settings');
+ return;
+ }
+
+ if (!profileData?.user) return;
+
+ openWorkspaceProfileModal({
+ onSuccess: async () => {
+ await Promise.all([mutate(), refreshWorkspaceProfile()]);
+ },
+ user: profileData.user,
+ });
+ }, [marketOrganizationProfile, mutate, navigate, profileData?.user, refreshWorkspaceProfile]);
+
+ const handleRefreshWorkspaceProfile = useCallback(async () => {
+ await Promise.all([mutate(), refreshWorkspaceProfile()]);
+ }, [mutate, refreshWorkspaceProfile]);
+
+ const contextConfig = useMemo(() => {
+ if (!profileData?.user) return null;
+ const { user, agents, agentGroups, skills, plugins } = profileData;
+ const totalInstalls = agents.reduce((sum, agent) => sum + (agent.installCount || 0), 0);
+ const canEditCurrent = shouldShowWorkspaceProfileEdit({
+ canEdit,
+ marketOrganizationProfile,
+ user,
+ });
+
+ return {
+ agentCount: agents.length,
+ agentGroups: agentGroups || [],
+ agents,
+ canEdit: canEditCurrent,
+ groupCount: agentGroups?.length || 0,
+ isLoading: isWorkspaceProfileLoading || isUserProfileLoading,
+ mobile,
+ onEditWorkspaceProfile: canEditCurrent ? handleEditWorkspaceProfile : undefined,
+ onRefreshProfile: handleRefreshWorkspaceProfile,
+ plugins: plugins || [],
+ skills: skills || [],
+ totalInstalls,
+ user,
+ };
+ }, [
+ canEdit,
+ handleEditWorkspaceProfile,
+ handleRefreshWorkspaceProfile,
+ isUserProfileLoading,
+ isWorkspaceProfileLoading,
+ marketOrganizationProfile,
+ mobile,
+ profileData,
+ ]);
+
+ if ((isWorkspaceProfileLoading || isUserProfileLoading) && !fallbackProfile) return <Loading />;
+ if (!contextConfig) return <NotFound />;
+
+ return (
+ <WorkspaceDetailProvider config={contextConfig}>
+ <WorkspaceHeader />
+ <WorkspaceContent />
+ </WorkspaceDetailProvider>
+ );
+});
+
+export const MobileWorkspaceDetailPage = memo(() => {
+ return <WorkspaceDetailPage mobile={true} />;
+});
+
+export default WorkspaceDetailPage;
diff --git a/src/routes/(main)/community/(detail)/workspace/loading.tsx b/src/routes/(main)/community/(detail)/workspace/loading.tsx
new file mode 100644
index 00000000000..5b2f4509ff9
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/loading.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import ListLoading from '@/routes/(main)/community/components/ListLoading';
+
+import Banner from './features/Header/Banner';
+
+const Loading = memo(() => {
+ return (
+ <Flexbox gap={24} width={'100%'}>
+ <Banner />
+ <Flexbox gap={16}>
+ <Skeleton.Avatar
+ shape={'square'}
+ size={64}
+ style={{ boxShadow: `0 0 0 4px ${cssVar.colorBgContainer}`, flexShrink: 0 }}
+ />
+ <Skeleton paragraph={{ rows: 1 }} />
+ </Flexbox>
+
+ <ListLoading length={4} rows={4} />
+ </Flexbox>
+ );
+});
+
+export default Loading;
diff --git a/src/routes/(main)/community/(detail)/workspace/settings/index.tsx b/src/routes/(main)/community/(detail)/workspace/settings/index.tsx
new file mode 100644
index 00000000000..0d67a03370e
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/workspace/settings/index.tsx
@@ -0,0 +1,3 @@
+import CommunityWorkspaceSettings from '@/features/CommunityWorkspaceSettings';
+
+export default CommunityWorkspaceSettings;
diff --git a/src/routes/(main)/community/(list)/agent/features/Category/index.tsx b/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
index 090485c3f2d..61040783a6f 100644
--- a/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
@@ -3,9 +3,10 @@
import { Icon, Tag } from '@lobehub/ui';
import qs from 'query-string';
import { memo, useMemo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
import { withSuspense } from '@/components/withSuspense';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
@@ -22,7 +23,7 @@ const Category = memo(() => {
source,
} = useQuery() as { category?: AssistantCategory; q?: string; source?: string };
const { data: items = [] } = useAssistantCategories({ q, source: source as any });
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
const genUrl = (key: AssistantCategory) =>
@@ -80,7 +81,7 @@ const Category = memo(() => {
),
...item,
icon: <Icon icon={item.icon} size={18} />,
- label: <Link to={genUrl(item.key)}>{item.label}</Link>,
+ label: <WorkspaceLink to={genUrl(item.key)}>{item.label}</WorkspaceLink>,
};
})}
onClick={(v) => handleClick(v.key as AssistantCategory)}
diff --git a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx b/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
index a75656c87a2..8636555ee2f 100644
--- a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
@@ -4,10 +4,11 @@ import { ClockIcon } from 'lucide-react';
import qs from 'query-string';
import React, { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { discoverService } from '@/services/discover';
import { type AssistantMarketSource, type DiscoverAssistantItem } from '@/types/discover';
@@ -71,7 +72,7 @@ const AssistantItem = memo<DiscoverAssistantItem>(
userName,
type,
}) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { source } = useQuery() as { source?: AssistantMarketSource };
const isGroupAgent = type === 'agent-group';
const basePath = isGroupAgent ? '/community/group_agent' : '/community/agent';
@@ -175,11 +176,11 @@ const AssistantItem = memo<DiscoverAssistantItem>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{title}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
{author && (
<div
diff --git a/src/routes/(main)/community/(list)/features/Pagination.tsx b/src/routes/(main)/community/(list)/features/Pagination.tsx
index 77ae87e8090..b8794e06f78 100644
--- a/src/routes/(main)/community/(list)/features/Pagination.tsx
+++ b/src/routes/(main)/community/(list)/features/Pagination.tsx
@@ -3,8 +3,9 @@
import { Pagination as Page } from 'antd';
import { createStaticStyles, useResponsive } from 'antd-style';
import { memo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { type DiscoverTab } from '@/types/discover';
@@ -38,7 +39,7 @@ interface PaginationProps {
const Pagination = memo<PaginationProps>(({ tab, currentPage, total, pageSize }) => {
const { page } = useQuery();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
const { mobile } = useResponsive();
diff --git a/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx b/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
index d8e2d3fb748..7f39d60b908 100644
--- a/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
@@ -3,9 +3,10 @@
import { Icon, Tag } from '@lobehub/ui';
import qs from 'query-string';
import { memo, useMemo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
import { withSuspense } from '@/components/withSuspense';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useCategory } from '@/hooks/useMCPCategory';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
@@ -21,7 +22,7 @@ const Category = memo(() => {
q?: string;
};
const { data: items = [] } = useMcpCategories({ q });
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
const genUrl = (key: McpCategory) =>
@@ -78,7 +79,7 @@ const Category = memo(() => {
),
...item,
icon: <Icon icon={item.icon} size={18} />,
- label: <Link to={genUrl(item.key)}>{item.label}</Link>,
+ label: <WorkspaceLink to={genUrl(item.key)}>{item.label}</WorkspaceLink>,
};
})}
onClick={(v) => handleClick(v.key as McpCategory)}
diff --git a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
index a88bb5c90a3..f3d4fe78b58 100644
--- a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
@@ -17,13 +17,14 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ClockIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import InstallationIcon from '@/components/MCPDepsIcon';
import OfficialIcon from '@/components/OfficialIcon';
import PublishedTime from '@/components/PublishedTime';
import Scores from '@/features/MCP/Scores';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { discoverService } from '@/services/discover';
import { type DiscoverMcpItem } from '@/types/discover';
@@ -86,7 +87,7 @@ const McpItem = memo<DiscoverMcpItem>(
github,
}) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/mcp', identifier);
const handleClick = useCallback(() => {
@@ -148,11 +149,11 @@ const McpItem = memo<DiscoverMcpItem>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{name}
</Text>
- </Link>
+ </WorkspaceLink>
{isOfficial && (
<Tooltip title={t('isOfficial')}>
<OfficialIcon />
diff --git a/src/routes/(main)/community/(list)/model/features/Category/index.tsx b/src/routes/(main)/community/(list)/model/features/Category/index.tsx
index f8a7f5adbb8..d33280e0cfc 100644
--- a/src/routes/(main)/community/(list)/model/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/model/features/Category/index.tsx
@@ -3,9 +3,10 @@
import { Icon, Tag } from '@lobehub/ui';
import qs from 'query-string';
import { memo, useMemo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
import { withSuspense } from '@/components/withSuspense';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
@@ -17,7 +18,7 @@ const Category = memo(() => {
const useModelCategories = useDiscoverStore((s) => s.useModelCategories);
const { category = 'all', q } = useQuery() as { category?: string; q?: string };
const { data: items = [] } = useModelCategories({ q });
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
const genUrl = (key: string) =>
@@ -70,7 +71,7 @@ const Category = memo(() => {
),
...item,
icon: <Icon icon={item.icon} size={18} />,
- label: <Link to={genUrl(item.key)}>{item.label}</Link>,
+ label: <WorkspaceLink to={genUrl(item.key)}>{item.label}</WorkspaceLink>,
};
})}
onClick={(v) => handleClick(v.key as string)}
diff --git a/src/routes/(main)/community/(list)/model/features/List/Item.tsx b/src/routes/(main)/community/(list)/model/features/List/Item.tsx
index 16f19dad93b..75bd2ca09c5 100644
--- a/src/routes/(main)/community/(list)/model/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/model/features/List/Item.tsx
@@ -7,11 +7,12 @@ import dayjs from 'dayjs';
import { ClockIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import { ModelInfoTags } from '@/components/ModelSelect';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { type DiscoverModelItem } from '@/types/discover';
import ModelTypeIcon from './ModelTypeIcon';
@@ -62,7 +63,7 @@ const ModelItem = memo<DiscoverModelItem>(
providers,
}) => {
const { t } = useTranslation(['models', 'discover']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/model', identifier);
return (
<Block
@@ -112,11 +113,11 @@ const ModelItem = memo<DiscoverModelItem>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{displayName}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<div className={styles.author}>{identifier}</div>
</Flexbox>
diff --git a/src/routes/(main)/community/(list)/provider/features/List/Item.tsx b/src/routes/(main)/community/(list)/provider/features/List/Item.tsx
index b0658b06d6b..f2ac5de4ada 100644
--- a/src/routes/(main)/community/(list)/provider/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/provider/features/List/Item.tsx
@@ -4,9 +4,10 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { GlobeIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { type DiscoverProviderItem } from '@/types/discover';
const styles = createStaticStyles(({ css, cssVar }) => {
@@ -45,7 +46,7 @@ const styles = createStaticStyles(({ css, cssVar }) => {
const ProviderItem = memo<DiscoverProviderItem>(
({ url, name, description, identifier, models }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/provider', identifier);
const { t } = useTranslation(['discover', 'providers']);
@@ -78,9 +79,9 @@ const ProviderItem = memo<DiscoverProviderItem>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<ProviderCombine provider={identifier} size={28} style={{ flex: 'none' }} />
- </Link>
+ </WorkspaceLink>
<div className={styles.author}>@{name}</div>
</Flexbox>
<Flexbox horizontal align={'center'}>
@@ -121,9 +122,9 @@ const ProviderItem = memo<DiscoverProviderItem>(
.slice(0, 6)
.filter(Boolean)
.map((tag: string) => (
- <Link key={tag} to={urlJoin('/model', tag)}>
+ <WorkspaceLink key={tag} to={urlJoin('/community/model', tag)}>
<ModelTag model={tag} style={{ margin: 0 }} />
- </Link>
+ </WorkspaceLink>
))}
</MaskShadow>
</Flexbox>
diff --git a/src/routes/(main)/community/(list)/skill/features/Category/index.tsx b/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
index eec417a2c68..578618503c1 100644
--- a/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
@@ -3,9 +3,10 @@
import { Icon, Tag } from '@lobehub/ui';
import qs from 'query-string';
import { memo, useMemo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
import { withSuspense } from '@/components/withSuspense';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { useSkillCategory } from '@/hooks/useSkillCategory';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
@@ -21,7 +22,7 @@ const Category = memo(() => {
q?: string;
};
const { data: items = [] } = useSkillCategories({ q });
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const cates = useSkillCategory();
const genUrl = (key: SkillCategory) =>
@@ -78,7 +79,7 @@ const Category = memo(() => {
),
...item,
icon: <Icon icon={item.icon} size={18} />,
- label: <Link to={genUrl(item.key)}>{item.label}</Link>,
+ label: <WorkspaceLink to={genUrl(item.key)}>{item.label}</WorkspaceLink>,
};
})}
onClick={(v) => handleClick(v.key as SkillCategory)}
diff --git a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx b/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
index a78452f89be..1d88195b2ca 100644
--- a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
@@ -7,10 +7,11 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ClockIcon, FileTextIcon, StarIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import urlJoin from 'url-join';
import PublishedTime from '@/components/PublishedTime';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { discoverService } from '@/services/discover';
import { type DiscoverSkillItem } from '@/types/discover';
@@ -65,7 +66,7 @@ const SkillItem = memo<DiscoverSkillItem>(
resourcesCount = 0,
}) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const link = urlJoin('/community/skill', identifier);
const handleClick = useCallback(() => {
@@ -127,11 +128,11 @@ const SkillItem = memo<DiscoverSkillItem>(
overflow: 'hidden',
}}
>
- <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
+ <WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>
<Text ellipsis as={'h2'} className={styles.title}>
{name}
</Text>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<Flexbox horizontal align={'center'} className={styles.author} gap={8}>
{Boolean(ratingAvg) && (
diff --git a/src/routes/(main)/community/_layout/Sidebar/Content.tsx b/src/routes/(main)/community/_layout/Sidebar/Content.tsx
new file mode 100644
index 00000000000..8ce569c8d46
--- /dev/null
+++ b/src/routes/(main)/community/_layout/Sidebar/Content.tsx
@@ -0,0 +1,13 @@
+import { memo } from 'react';
+
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Header from './Header';
+
+const Content = memo(() => {
+ return <SideBarLayout header={<Header />} />;
+});
+
+Content.displayName = 'DiscoverSidebarContent';
+
+export default Content;
diff --git a/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx
index b9453193ef1..64fed50eb36 100644
--- a/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx
@@ -5,10 +5,11 @@ import { McpIcon, ProviderIcon, SkillsIcon } from '@lobehub/ui/icons';
import { Bot, Brain, ShapesIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import { type NavItemProps } from '@/features/NavPanel/components/NavItem';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { usePathname } from '@/libs/router/navigation';
import { DiscoverTab } from '@/types/discover';
import { isModifierClick } from '@/utils/navigation';
@@ -23,54 +24,55 @@ interface Item {
const useActiveTabKey = () => {
const pathname = usePathname();
- if (pathname === '/community') return DiscoverTab.Home;
- return (pathname.split('/community/').find(Boolean)! as DiscoverTab) || DiscoverTab.Home;
+ if (pathname.endsWith('/community')) return DiscoverTab.Home;
+ return (pathname.split('/community/').at(1) as DiscoverTab) || DiscoverTab.Home;
};
const Nav = memo(() => {
const tab = useActiveTabKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('discover');
const items: Item[] = useMemo(
- () => [
- {
- icon: ShapesIcon,
- key: DiscoverTab.Home,
- title: t('tab.home'),
- url: '/community',
- },
- {
- icon: Bot,
- key: DiscoverTab.Assistants,
- title: t('tab.assistant'),
- url: '/community/agent',
- },
- {
- icon: SkillsIcon,
- key: DiscoverTab.Skills,
- title: t('tab.skill'),
- url: '/community/skill',
- },
- {
- icon: McpIcon,
- key: DiscoverTab.Mcp,
- title: `MCP`,
- url: '/community/mcp',
- },
- {
- icon: Brain,
- key: DiscoverTab.Models,
- title: t('tab.model'),
- url: '/community/model',
- },
- {
- icon: ProviderIcon,
- key: DiscoverTab.Providers,
- title: t('tab.provider'),
- url: '/community/provider',
- },
- ],
+ () =>
+ [
+ {
+ icon: ShapesIcon,
+ key: DiscoverTab.Home,
+ title: t('tab.home'),
+ url: '/community',
+ },
+ {
+ icon: Bot,
+ key: DiscoverTab.Assistants,
+ title: t('tab.assistant'),
+ url: '/community/agent',
+ },
+ {
+ icon: SkillsIcon,
+ key: DiscoverTab.Skills,
+ title: t('tab.skill'),
+ url: '/community/skill',
+ },
+ {
+ icon: McpIcon,
+ key: DiscoverTab.Mcp,
+ title: `MCP`,
+ url: '/community/mcp',
+ },
+ {
+ icon: Brain,
+ key: DiscoverTab.Models,
+ title: t('tab.model'),
+ url: '/community/model',
+ },
+ {
+ icon: ProviderIcon,
+ key: DiscoverTab.Providers,
+ title: t('tab.provider'),
+ url: '/community/provider',
+ },
+ ] as Item[],
[t],
);
@@ -89,7 +91,7 @@ const Nav = memo(() => {
if (!item.url) return content;
return (
- <Link
+ <WorkspaceLink
key={item.key}
to={item.url}
onClick={(e) => {
@@ -102,7 +104,7 @@ const Nav = memo(() => {
}}
>
<NavItem active={tab.startsWith(item.key)} icon={item.icon} title={item.title} />
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/community/_layout/Sidebar/index.tsx b/src/routes/(main)/community/_layout/Sidebar/index.tsx
index 467bf11a59f..caf9740236a 100644
--- a/src/routes/(main)/community/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/community/_layout/Sidebar/index.tsx
@@ -1,14 +1,13 @@
-import React, { memo } from 'react';
+import { memo } from 'react';
import { NavPanelPortal } from '@/features/NavPanel';
-import SideBarLayout from '@/features/NavPanel/SideBarLayout';
-import Header from './Header';
+import Content from './Content';
const Sidebar = memo(() => {
return (
<NavPanelPortal navKey="discover">
- <SideBarLayout header={<Header />} />
+ <Content />
</NavPanelPortal>
);
});
diff --git a/src/routes/(main)/community/components/Title.tsx b/src/routes/(main)/community/components/Title.tsx
index 058ed425373..a07fe33c64b 100644
--- a/src/routes/(main)/community/components/Title.tsx
+++ b/src/routes/(main)/community/components/Title.tsx
@@ -6,7 +6,8 @@ import { createStaticStyles, responsive, useResponsive } from 'antd-style';
import { ChevronRight } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { SCROLL_PARENT_ID } from '../features/const';
@@ -75,7 +76,7 @@ const Title = memo<TitleProps>(({ tag, children, moreLink, more }) => {
title
)}
{moreLink && (
- <Link
+ <WorkspaceLink
target={moreLink.startsWith('http') ? '_blank' : undefined}
to={moreLink}
onClick={handleMoreClick}
@@ -84,7 +85,7 @@ const Title = memo<TitleProps>(({ tag, children, moreLink, more }) => {
<span>{more}</span>
<Icon icon={ChevronRight} />
</Button>
- </Link>
+ </WorkspaceLink>
)}
</Flexbox>
);
diff --git a/src/routes/(main)/community/features/Title.tsx b/src/routes/(main)/community/features/Title.tsx
index b358cb6dd3f..4822874c306 100644
--- a/src/routes/(main)/community/features/Title.tsx
+++ b/src/routes/(main)/community/features/Title.tsx
@@ -6,7 +6,8 @@ import { createStaticStyles, cx } from 'antd-style';
import { ChevronRight } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo } from 'react';
-import { Link as RouterLink } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
const styles = createStaticStyles(({ css, cssVar }) => ({
more: css`
@@ -59,18 +60,17 @@ const Title = memo<TitleProps>(
);
} else if (isCommunityRoute) {
moreLinkElement = (
- <RouterLink className={styles.more} to={moreLink}>
+ <WorkspaceLink className={styles.more} to={moreLink}>
<span style={{ marginRight: 4 }}>{more}</span>
<Icon icon={ChevronRight} />
- </RouterLink>
+ </WorkspaceLink>
);
} else {
- // For non-external, non-community routes (like auth pages), use RouterLink
moreLinkElement = (
- <RouterLink className={styles.more} to={moreLink}>
+ <WorkspaceLink className={styles.more} to={moreLink}>
<span style={{ marginRight: 4 }}>{more}</span>
<Icon icon={ChevronRight} />
- </RouterLink>
+ </WorkspaceLink>
);
}
}
diff --git a/src/routes/(main)/community/features/UserAvatar/index.test.tsx b/src/routes/(main)/community/features/UserAvatar/index.test.tsx
new file mode 100644
index 00000000000..b685a3fd2ec
--- /dev/null
+++ b/src/routes/(main)/community/features/UserAvatar/index.test.tsx
@@ -0,0 +1,67 @@
+// @vitest-environment happy-dom
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import UserAvatar from './index';
+
+const mocks = vi.hoisted(() => ({
+ communityWorkspaceProfile: {
+ avatarUrl: null as string | null,
+ isWorkspaceScope: true,
+ username: 'workspace-market-namespace',
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Avatar: ({ avatar, onClick }: { avatar?: string | null; onClick?: () => void }) => (
+ <button data-avatar={avatar ?? ''} data-testid="community-user-avatar" onClick={onClick} />
+ ),
+ Button: ({ children }: { children?: string }) => <button>{children}</button>,
+ Skeleton: {
+ Avatar: () => <div data-testid="avatar-skeleton" />,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/business/client/hooks/useCommunityWorkspaceProfile', () => ({
+ useCommunityWorkspaceProfile: () => mocks.communityWorkspaceProfile,
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/layout/AuthProvider/MarketAuth', () => ({
+ useMarketAuth: () => ({
+ getCurrentUserInfo: () => ({ sub: 'current-user' }),
+ isAuthenticated: true,
+ isLoading: false,
+ signIn: vi.fn(),
+ }),
+ useMarketUserProfile: () => ({
+ data: { avatarUrl: 'user-avatar', namespace: 'personal-user', userName: 'personal-user' },
+ }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (state: { enableMarketTrustedClient: boolean }) => boolean) =>
+ selector({ enableMarketTrustedClient: true }),
+}));
+
+vi.mock('@/store/serverConfig/selectors', () => ({
+ serverConfigSelectors: {
+ enableMarketTrustedClient: (state: { enableMarketTrustedClient: boolean }) =>
+ state.enableMarketTrustedClient,
+ },
+}));
+
+describe('Community UserAvatar', () => {
+ it('uses the provided avatar override before workspace fallback', () => {
+ render(<UserAvatar avatarOverride={'🏢'} />);
+
+ expect(screen.getByTestId('community-user-avatar')).toHaveAttribute('data-avatar', '🏢');
+ });
+});
diff --git a/src/routes/(main)/community/features/UserAvatar/index.tsx b/src/routes/(main)/community/features/UserAvatar/index.tsx
index bfcff3ae7d3..25302892b08 100644
--- a/src/routes/(main)/community/features/UserAvatar/index.tsx
+++ b/src/routes/(main)/community/features/UserAvatar/index.tsx
@@ -4,12 +4,19 @@ import { Avatar, Button, Skeleton } from '@lobehub/ui';
import { UserCircleIcon } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useCommunityWorkspaceProfile } from '@/business/client/hooks/useCommunityWorkspaceProfile';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useMarketAuth, useMarketUserProfile } from '@/layout/AuthProvider/MarketAuth';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+import { resolveCommunityUserAvatarTarget } from './navigation';
+
+interface UserAvatarProps {
+ avatarOverride?: string | null;
+}
+
/**
* Check whether the user needs to complete their profile
* When using trustedClient auto-authorization, the user's meta-related fields will be empty
@@ -34,10 +41,15 @@ const checkNeedsProfileSetup = (
return !hasAvatarUrl;
};
-const UserAvatar = memo(() => {
+const UserAvatar = memo<UserAvatarProps>(({ avatarOverride }) => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [loading, setLoading] = useState(false);
+ const {
+ avatarUrl: workspaceAvatarUrl,
+ isWorkspaceScope,
+ username: workspaceUsername,
+ } = useCommunityWorkspaceProfile();
const { isAuthenticated, isLoading, getCurrentUserInfo, signIn } = useMarketAuth();
const enableMarketTrustedClient = useServerConfigStore(
@@ -68,10 +80,15 @@ const UserAvatar = memo(() => {
const handleAvatarClick = useCallback(() => {
const profileUserName = userProfile?.userName || userProfile?.namespace;
- if (profileUserName) {
- navigate(`/community/user/${profileUserName}`);
+ const target = resolveCommunityUserAvatarTarget({
+ isWorkspaceScope,
+ profileUsername: profileUserName,
+ });
+
+ if (target) {
+ navigate(target);
}
- }, [navigate, userProfile?.userName, userProfile?.namespace]);
+ }, [isWorkspaceScope, navigate, userProfile?.userName, userProfile?.namespace]);
if (isLoading) {
return <Skeleton.Avatar active shape={'square'} size={28} style={{ borderRadius: 6 }} />;
@@ -96,16 +113,13 @@ const UserAvatar = memo(() => {
}
// Get avatar from user profile (fetched via SWR with caching)
- const avatarUrl = userProfile?.avatarUrl;
-
- return (
- <Avatar
- avatar={avatarUrl || userProfile?.userName || username}
- shape={'square'}
- size={28}
- onClick={handleAvatarClick}
- />
- );
+ const avatarUrl =
+ avatarOverride ||
+ (isWorkspaceScope
+ ? workspaceAvatarUrl || workspaceUsername
+ : userProfile?.avatarUrl || userProfile?.userName || username);
+
+ return <Avatar avatar={avatarUrl} shape={'square'} size={28} onClick={handleAvatarClick} />;
});
export default UserAvatar;
diff --git a/src/routes/(main)/community/features/UserAvatar/navigation.test.ts b/src/routes/(main)/community/features/UserAvatar/navigation.test.ts
new file mode 100644
index 00000000000..ad4f36ad9f2
--- /dev/null
+++ b/src/routes/(main)/community/features/UserAvatar/navigation.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveCommunityUserAvatarTarget } from './navigation';
+
+describe('resolveCommunityUserAvatarTarget', () => {
+ it('routes workspace scope to the workspace community page even before an org namespace exists', () => {
+ expect(
+ resolveCommunityUserAvatarTarget({
+ isWorkspaceScope: true,
+ profileUsername: 'personal-user',
+ }),
+ ).toBe('/community/workspace');
+ });
+
+ it('routes personal scope to the user profile when available', () => {
+ expect(
+ resolveCommunityUserAvatarTarget({
+ isWorkspaceScope: false,
+ profileUsername: 'personal-user',
+ }),
+ ).toBe('/community/user/personal-user');
+ });
+});
diff --git a/src/routes/(main)/community/features/UserAvatar/navigation.ts b/src/routes/(main)/community/features/UserAvatar/navigation.ts
new file mode 100644
index 00000000000..2a3cb5b798d
--- /dev/null
+++ b/src/routes/(main)/community/features/UserAvatar/navigation.ts
@@ -0,0 +1,12 @@
+interface ResolveCommunityUserAvatarTargetParams {
+ isWorkspaceScope: boolean;
+ profileUsername?: string | null;
+}
+
+export const resolveCommunityUserAvatarTarget = ({
+ isWorkspaceScope,
+ profileUsername,
+}: ResolveCommunityUserAvatarTargetParams) => {
+ if (isWorkspaceScope) return '/community/workspace';
+ if (profileUsername) return `/community/user/${profileUsername}`;
+};
diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
index c95de4013dc..ea3ea205242 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
@@ -16,10 +16,11 @@ import {
} from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useEvalStore } from '@/store/eval';
import { isModifierClick } from '@/utils/navigation';
@@ -49,7 +50,7 @@ interface BenchmarkListProps {
const BenchmarkList = memo<BenchmarkListProps>(({ activeKey, itemKey }) => {
const { t } = useTranslation('eval');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const benchmarkList = useEvalStore((s) => s.benchmarkList);
const isInit = useEvalStore((s) => s.benchmarkListInit);
@@ -76,7 +77,7 @@ const BenchmarkList = memo<BenchmarkListProps>(({ activeKey, itemKey }) => {
<SkeletonList rows={3} />
) : benchmarkList.length > 0 ? (
benchmarkList.map((b: any) => (
- <Link
+ <WorkspaceLink
key={b.id}
to={`/eval/bench/${b.id}`}
onClick={(e) => {
@@ -91,7 +92,7 @@ const BenchmarkList = memo<BenchmarkListProps>(({ activeKey, itemKey }) => {
iconSize={16}
title={b.name}
/>
- </Link>
+ </WorkspaceLink>
))
) : (
<Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx
index 32edbfc4fb4..5af8300a7b2 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx
@@ -4,9 +4,10 @@ import { Accordion, Flexbox } from '@lobehub/ui';
import { LayoutDashboardIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { usePathname } from '@/libs/router/navigation';
import { useEvalStore } from '@/store/eval';
@@ -24,7 +25,7 @@ const useActiveKey = () => {
const Body = memo(() => {
const activeKey = useActiveKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('eval');
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
useFetchBenchmarks();
@@ -32,7 +33,7 @@ const Body = memo(() => {
return (
<Flexbox gap={8} paddingInline={4}>
<Flexbox gap={1}>
- <Link
+ <WorkspaceLink
to="/eval"
onClick={(e) => {
e.preventDefault();
@@ -44,7 +45,7 @@ const Body = memo(() => {
icon={LayoutDashboardIcon}
title={t('sidebar.dashboard')}
/>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<Accordion defaultExpandedKeys={['benchmarks']} gap={8}>
<BenchmarkList activeKey={activeKey} itemKey="benchmarks" />
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
index ecb1390f09d..8618c711654 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
@@ -4,10 +4,11 @@ import { AccordionItem, Flexbox, Text } from '@lobehub/ui';
import { Database } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useEvalStore } from '@/store/eval';
interface DatasetListProps {
@@ -18,7 +19,7 @@ interface DatasetListProps {
const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey }) => {
const { t } = useTranslation('eval');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const datasetList = useEvalStore((s) => s.datasetList);
const isLoading = useEvalStore((s) => s.isLoadingDatasets);
@@ -45,7 +46,7 @@ const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey })
<SkeletonList rows={3} />
) : datasetList.length > 0 ? (
datasetList.map((ds: any) => (
- <Link
+ <WorkspaceLink
key={ds.id}
to={`/eval/bench/${benchmarkId}/datasets/${ds.id}`}
onClick={(e) => {
@@ -59,7 +60,7 @@ const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey })
iconSize={16}
title={ds.name}
/>
- </Link>
+ </WorkspaceLink>
))
) : (
<Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx
index 52f2d9a88bf..a44830de60a 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx
@@ -4,10 +4,11 @@ import { AccordionItem, Flexbox, Text } from '@lobehub/ui';
import { CheckCircle2, CircleDot, CircleSlash, Loader2, Play, XCircle } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { runSelectors, useEvalStore } from '@/store/eval';
const getRunIcon = (status?: string) => {
@@ -41,7 +42,7 @@ interface RunListProps {
const RunList = memo<RunListProps>(({ activeKey, benchmarkId, itemKey }) => {
const { t } = useTranslation('eval');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const runList = useEvalStore(runSelectors.runList);
const isLoading = useEvalStore(runSelectors.isLoadingRuns);
@@ -76,7 +77,7 @@ const RunList = memo<RunListProps>(({ activeKey, benchmarkId, itemKey }) => {
<SkeletonList rows={3} />
) : sortedRuns.length > 0 ? (
sortedRuns.map((run) => (
- <Link
+ <WorkspaceLink
key={run.id}
to={`/eval/bench/${benchmarkId}/runs/${run.id}`}
onClick={(e) => {
@@ -91,7 +92,7 @@ const RunList = memo<RunListProps>(({ activeKey, benchmarkId, itemKey }) => {
loading={run.status === 'running'}
title={run.name || `Run ${run.id.slice(0, 8)}`}
/>
- </Link>
+ </WorkspaceLink>
))
) : (
<Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
index 2d9eb70ce48..c9b83bb9b6a 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
@@ -4,9 +4,11 @@ import { Accordion, Flexbox } from '@lobehub/ui';
import { LayoutDashboard } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { usePathname } from '@/libs/router/navigation';
import { useEvalStore } from '@/store/eval';
@@ -32,7 +34,7 @@ const useActiveKey = () => {
const Body = memo(() => {
const { t } = useTranslation('eval');
const { benchmarkId } = useParams<{ benchmarkId: string }>();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);
const useFetchRuns = useEvalStore((s) => s.useFetchRuns);
@@ -44,7 +46,7 @@ const Body = memo(() => {
return (
<Flexbox gap={8} paddingInline={4}>
<Flexbox paddingInline={4}>
- <Link
+ <WorkspaceLink
to={`/eval/bench/${benchmarkId}`}
onClick={(e) => {
e.preventDefault();
@@ -57,7 +59,7 @@ const Body = memo(() => {
iconSize={16}
title={t('sidebar.dashboard')}
/>
- </Link>
+ </WorkspaceLink>
</Flexbox>
<Accordion defaultExpandedKeys={['datasets', 'runs']} gap={8}>
<DatasetList activeKey={activeKey} benchmarkId={benchmarkId || ''} itemKey="datasets" />
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
index 09ea6dd5a18..d95191a31ed 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
@@ -26,8 +26,8 @@ import {
Zap,
} from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useEvalStore } from '@/store/eval';
const SYSTEM_ICONS = [
@@ -56,7 +56,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const BenchmarkHead = memo<{ id: string }>(({ id }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
useFetchBenchmarks();
const benchmark = useEvalStore((s) => s.benchmarkDetailMap[id]);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
index 472e187c357..495713fb7e1 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
@@ -6,8 +6,10 @@ import { App, Typography } from 'antd';
import { ArrowLeft, Database, Pencil, Plus, Trash2 } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { agentEvalService } from '@/services/agentEval';
import { runSelectors, useEvalStore } from '@/store/eval';
@@ -24,7 +26,7 @@ import RunCard from '../../features/RunsTab/RunCard';
const DatasetDetail = memo(() => {
const { t } = useTranslation('eval');
const { benchmarkId, datasetId } = useParams<{ benchmarkId: string; datasetId: string }>();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { message } = App.useApp();
const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
@@ -122,7 +124,7 @@ const DatasetDetail = memo(() => {
style={{ minWidth: 0, overflow: 'auto', paddingBlock: 24, paddingInline: 32 }}
>
{/* Back link */}
- <Link
+ <WorkspaceLink
to={`/eval/bench/${benchmarkId}`}
style={{
alignItems: 'center',
@@ -143,7 +145,7 @@ const DatasetDetail = memo(() => {
>
<ArrowLeft size={16} />
{t('dataset.detail.backToBenchmark')}
- </Link>
+ </WorkspaceLink>
{/* Header */}
<Flexbox horizontal align="start" justify="space-between">
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
index 881df16b809..0235501602d 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
@@ -20,8 +20,8 @@ import {
import { type LucideIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useEvalStore } from '@/store/eval';
import { createBenchmarkEditModal } from '../../../../features/BenchmarkEditModal';
@@ -98,7 +98,7 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
totalCases,
}) => {
const { t } = useTranslation('eval');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
const refreshBenchmarkDetail = useEvalStore((s) => s.refreshBenchmarkDetail);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
index 1fe8ac5b437..ed4a6bf95ec 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
@@ -5,9 +5,9 @@ import { createStaticStyles } from 'antd-style';
import { ArrowRight, ChevronRight, Database, Ellipsis, Pencil, Play, Trash2 } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { agentEvalService } from '@/services/agentEval';
import { DATASET_PRESETS } from '../../../../config/datasetPresets';
@@ -251,14 +251,14 @@ const DatasetCard = memo<DatasetCardProps>(
/>
)}
<Flexbox horizontal align="center" className={styles.footer} justify="center">
- <Link
+ <WorkspaceLink
className={styles.footerLink}
to={`/eval/bench/${benchmarkId}/datasets/${dataset.id}`}
>
<Button icon={ArrowRight} iconPosition="end" size="small" variant="text">
{t('dataset.detail.viewDetail')}
</Button>
- </Link>
+ </WorkspaceLink>
</Flexbox>
</div>
)}
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/RunSummaryCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/RunSummaryCard.tsx
index 8efb42f585d..4cfd38ff46b 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/RunSummaryCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/RunSummaryCard.tsx
@@ -4,8 +4,8 @@ import { Flexbox } from '@lobehub/ui';
import { Card, Progress, Typography } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import StatusBadge from '@/routes/(main)/eval/features/StatusBadge';
interface RunSummaryCardProps {
@@ -25,7 +25,7 @@ const RunSummaryCard = memo<RunSummaryCardProps>(({ id, name, status, metrics, b
const isActive = status === 'running' || status === 'pending';
return (
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', textDecoration: 'none' }}
to={`/eval/bench/${benchmarkId}/runs/${id}`}
>
@@ -58,7 +58,7 @@ const RunSummaryCard = memo<RunSummaryCardProps>(({ id, name, status, metrics, b
)}
</Flexbox>
</Card>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
index 2fdd3a5ec18..9459ec59969 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
@@ -8,8 +8,8 @@ import { createStaticStyles } from 'antd-style';
import { SquareArrowOutUpRight } from 'lucide-react';
import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { agentService } from '@/services/agent';
import { useEvalStore } from '@/store/eval';
@@ -72,7 +72,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
const { t } = useTranslation('eval');
const { t: tChat } = useTranslation('chat');
const { close } = useModalContext();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const createRun = useEvalStore((s) => s.createRun);
const startRun = useEvalStore((s) => s.startRun);
const datasetList = useEvalStore((s) => s.datasetList);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
index 7a18ef799a8..aab1c58c47c 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
@@ -9,8 +9,9 @@ import { createStaticStyles } from 'antd-style';
import { SquareArrowOutUpRight } from 'lucide-react';
import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { agentService } from '@/services/agent';
import { useEvalStore } from '@/store/eval';
@@ -56,7 +57,7 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
const { t: tChat } = useTranslation('chat');
const { close } = useModalContext();
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { benchmarkId } = useParams<{ benchmarkId: string }>();
const updateRun = useEvalStore((s) => s.updateRun);
const datasetList = useEvalStore((s) => s.datasetList);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
index 81d38574c66..5c49b68b40c 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
@@ -16,8 +16,8 @@ import {
} from 'lucide-react';
import { Fragment, memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useEvalStore } from '@/store/eval';
import StatusBadge from '../../../../features/StatusBadge';
@@ -240,7 +240,7 @@ const RunCard = memo<RunCardProps>(({ benchmarkId, run, onRefresh, onEdit }) =>
];
return (
- <Link className={styles.cardLink} to={`/eval/bench/${benchmarkId}/runs/${run.id}`}>
+ <WorkspaceLink className={styles.cardLink} to={`/eval/bench/${benchmarkId}/runs/${run.id}`}>
<Card className={styles.card}>
<Flexbox horizontal align="center" gap={16}>
{/* Left: Info */}
@@ -334,7 +334,7 @@ const RunCard = memo<RunCardProps>(({ benchmarkId, run, onRefresh, onEdit }) =>
<Icon className={styles.arrowIcon} icon={ArrowRight} size={16} />
</Flexbox>
</Card>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
index d41630dce83..874e9558fac 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
@@ -4,8 +4,9 @@ import type { EvalThreadResult } from '@lobechat/types';
import { Flexbox, Tabs } from '@lobehub/ui';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { runSelectors, useEvalStore } from '@/store/eval';
import CaseHeader from './features/CaseBanner';
@@ -21,7 +22,7 @@ const CaseDetail = memo(() => {
runId: string;
}>();
const { t } = useTranslation('eval');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const useFetchRunDetail = useEvalStore((s) => s.useFetchRunDetail);
const useFetchRunResults = useEvalStore((s) => s.useFetchRunResults);
const isActive = useEvalStore(runSelectors.isRunActive(runId!));
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx
index 3597c25a6b4..87fbf86acb5 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx
@@ -10,7 +10,8 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { Footprints, Play, RotateCcw } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { getResumeTarget } from '../resumeTarget';
@@ -235,12 +236,12 @@ const CaseResultsTable = memo<CaseResultsTableProps>(
dataIndex: ['testCase', 'content', 'input'],
key: 'input',
render: (text: string, record: any) => (
- <Link
+ <WorkspaceLink
className={styles.caseLink}
to={`/eval/bench/${benchmarkId}/runs/${runId}/cases/${record.testCaseId}`}
>
{text}
- </Link>
+ </WorkspaceLink>
),
title: t('table.columns.input'),
},
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
index 4adac288ca7..8dfad2e035d 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
@@ -18,8 +18,9 @@ import {
} from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { createRunEditModal } from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal';
import StatusBadge from '@/routes/(main)/eval/features/StatusBadge';
import { useEvalStore } from '@/store/eval';
@@ -117,7 +118,7 @@ interface RunHeaderProps {
const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
const { t } = useTranslation('eval');
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const abortRun = useEvalStore((s) => s.abortRun);
const deleteRun = useEvalStore((s) => s.deleteRun);
const startRun = useEvalStore((s) => s.startRun);
@@ -196,10 +197,10 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
return (
<Flexbox gap={16}>
{/* Back link */}
- <Link className={styles.backLink} to={`/eval/bench/${benchmarkId}`}>
+ <WorkspaceLink className={styles.backLink} to={`/eval/bench/${benchmarkId}`}>
<ArrowLeft size={16} />
{t('run.detail.backToBenchmark')}
- </Link>
+ </WorkspaceLink>
{/* Header Card */}
<Card styles={{ body: { padding: 20 } }}>
@@ -221,13 +222,13 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
{/* Meta info row */}
<Flexbox horizontal align="center" className={styles.metaRow} gap={8}>
{run.dataset && (
- <Link
+ <WorkspaceLink
className={styles.datasetLink}
target="_blank"
to={`/eval/bench/${benchmarkId}/datasets/${run.dataset.id}`}
>
{run.dataset.name}
- </Link>
+ </WorkspaceLink>
)}
{run.targetAgentId && (
<>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunInfo/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunInfo/index.tsx
index 7041fc5e3f9..8f18d290a95 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunInfo/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunInfo/index.tsx
@@ -5,7 +5,8 @@ import { Avatar, Button, Flexbox } from '@lobehub/ui';
import { Descriptions, Tag, Typography } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
interface RunInfoProps {
benchmarkId: string;
@@ -58,9 +59,12 @@ const RunInfo = memo<RunInfoProps>(({ benchmarkId, run }) => {
items={[
{
children: run.dataset ? (
- <Link target="_blank" to={`/eval/bench/${benchmarkId}/datasets/${run.dataset.id}`}>
+ <WorkspaceLink
+ target="_blank"
+ to={`/eval/bench/${benchmarkId}/datasets/${run.dataset.id}`}
+ >
<Tag style={{ cursor: 'pointer' }}>{run.dataset.name}</Tag>
- </Link>
+ </WorkspaceLink>
) : (
<Typography.Text type="secondary">-</Typography.Text>
),
diff --git a/src/routes/(main)/eval/features/BenchmarkCard/RunRow.tsx b/src/routes/(main)/eval/features/BenchmarkCard/RunRow.tsx
index 189a92c87f2..720d2b058be 100644
--- a/src/routes/(main)/eval/features/BenchmarkCard/RunRow.tsx
+++ b/src/routes/(main)/eval/features/BenchmarkCard/RunRow.tsx
@@ -4,7 +4,8 @@ import { Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { AlertTriangle, ArrowRight, CheckCircle2, XCircle } from 'lucide-react';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import StatusBadge from '../StatusBadge';
@@ -100,7 +101,7 @@ const RunRow = memo<RunRowProps>(
(status === 'completed' || status === 'running') && passCount + failCount + errorCount > 0;
return (
- <Link
+ <WorkspaceLink
style={{ color: 'inherit', textDecoration: 'none' }}
to={`/eval/bench/${benchmarkId}/runs/${id}`}
>
@@ -192,7 +193,7 @@ const RunRow = memo<RunRowProps>(
style={{ color: 'var(--ant-color-text-tertiary)', flexShrink: 0 }}
/>
</Flexbox>
- </Link>
+ </WorkspaceLink>
);
},
);
diff --git a/src/routes/(main)/eval/features/BenchmarkCard/index.tsx b/src/routes/(main)/eval/features/BenchmarkCard/index.tsx
index ea9c5a3f666..88eeaa793d6 100644
--- a/src/routes/(main)/eval/features/BenchmarkCard/index.tsx
+++ b/src/routes/(main)/eval/features/BenchmarkCard/index.tsx
@@ -23,7 +23,8 @@ import {
} from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import RunRow from './RunRow';
@@ -191,9 +192,9 @@ const BenchmarkCard = memo<BenchmarkCardProps>(
/>
</div>
<Flexbox gap={4}>
- <Link className={styles.name} to={`/eval/bench/${id}`}>
+ <WorkspaceLink className={styles.name} to={`/eval/bench/${id}`}>
{name}
- </Link>
+ </WorkspaceLink>
<Flexbox horizontal align="center" className={styles.meta} gap={4}>
<span>{t('benchmark.card.datasetCount', { count: datasetCount })}</span>
<span>·</span>
@@ -221,9 +222,9 @@ const BenchmarkCard = memo<BenchmarkCardProps>(
</Flexbox>
</Flexbox>
- <Link className={styles.detailLink} to={`/eval/bench/${id}`}>
+ <WorkspaceLink className={styles.detailLink} to={`/eval/bench/${id}`}>
<Icon icon={ArrowRight} size={16} />
- </Link>
+ </WorkspaceLink>
</Flexbox>
{/* Description */}
@@ -262,20 +263,20 @@ const BenchmarkCard = memo<BenchmarkCardProps>(
>
{t('benchmark.card.noDatasetHint')}
</p>
- <Link style={{ textDecoration: 'none' }} to={`/eval/bench/${id}`}>
+ <WorkspaceLink style={{ textDecoration: 'none' }} to={`/eval/bench/${id}`}>
<Button icon={Upload} size="small" variant="filled">
{t('benchmark.card.importDataset')}
</Button>
- </Link>
+ </WorkspaceLink>
</div>
) : (
<Flexbox gap={8}>
<Flexbox horizontal align="center" justify="space-between">
<span className={styles.recentLabel}>{t('benchmark.card.recentRuns')}</span>
{allRunCount > 3 && (
- <Link className={styles.viewAll} to={`/eval/bench/${id}`}>
+ <WorkspaceLink className={styles.viewAll} to={`/eval/bench/${id}`}>
{t('benchmark.card.viewAll', { count: allRunCount })}
- </Link>
+ </WorkspaceLink>
)}
</Flexbox>
@@ -350,11 +351,11 @@ const BenchmarkCard = memo<BenchmarkCardProps>(
>
{t('benchmark.card.emptyHint')}
</p>
- <Link style={{ textDecoration: 'none' }} to={`/eval/bench/${id}?tab=runs`}>
+ <WorkspaceLink style={{ textDecoration: 'none' }} to={`/eval/bench/${id}?tab=runs`}>
<Button icon={Play} size="small" variant="filled">
{t('benchmark.card.startFirst')}
</Button>
- </Link>
+ </WorkspaceLink>
</div>
)}
</Flexbox>
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
index 10aac8a58d8..b666368b1cd 100644
--- a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
@@ -5,8 +5,8 @@ import { useModalContext } from '@lobehub/ui/base-ui';
import { App, Form } from 'antd';
import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useEvalStore } from '@/store/eval';
const toIdentifier = (name: string) =>
@@ -25,7 +25,7 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
const { t } = useTranslation('eval');
const { close } = useModalContext();
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [form] = Form.useForm();
const [identifierTouched, setIdentifierTouched] = useState(false);
const createBenchmark = useEvalStore((s) => s.createBenchmark);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Content.tsx b/src/routes/(main)/group/_layout/Sidebar/Content.tsx
new file mode 100644
index 00000000000..185f6804a21
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Content.tsx
@@ -0,0 +1,14 @@
+import React, { memo } from 'react';
+
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Body from './Body';
+import Header from './Header';
+
+const GroupSidebarContent = memo(() => {
+ return <SideBarLayout body={<Body />} header={<Header />} />;
+});
+
+GroupSidebarContent.displayName = 'GroupSidebarContent';
+
+export default GroupSidebarContent;
diff --git a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
index 97182a04fb5..a74a9b75f8a 100644
--- a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
@@ -11,6 +11,7 @@ import { DEFAULT_AVATAR } from '@/const/meta';
import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';
import NavItem from '@/features/NavPanel/components/NavItem';
import UserAvatar from '@/features/User/UserAvatar';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -45,6 +46,7 @@ interface GroupMemberProps {
*/
const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange, groupId }) => {
const { t } = useTranslation('chat');
+ const { allowed: canEdit, reason } = usePermission('edit_own_content');
const router = useQueryRoute();
const location = useLocation();
const [nickname, username] = useUserStore((s) => [
@@ -68,6 +70,7 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
}, [groupId, location.pathname]);
const handleAddMembers = async (selectedAgents: string[]) => {
+ if (!canEdit) return;
if (!groupId) {
console.error('No active group to add members to');
return;
@@ -92,6 +95,7 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
};
const handleRemoveMember = async (memberId: string) => {
+ if (!canEdit) return;
if (!groupId) return;
await withRemovingFlag(memberId, () => removeAgentFromGroup(groupId, memberId));
@@ -128,10 +132,11 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
actions={
<ActionIcon
danger
+ disabled={!canEdit}
icon={UserMinus}
loading={removingMemberIds.includes(item.id)}
size={'small'}
- title={t('groupSidebar.members.removeMember')}
+ title={canEdit ? t('groupSidebar.members.removeMember') : reason}
onClick={(e) => {
e.stopPropagation();
handleRemoveMember(item.id);
diff --git a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
index 3c8196869db..d815bb69ff9 100644
--- a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
@@ -7,6 +7,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import GroupInfo from '@/features/GroupInfo';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { type LobeSession } from '@/types/session';
@@ -24,18 +25,22 @@ interface GroupRoleProps {
const GroupRole = memo<GroupRoleProps>(
({ currentSession, editorModalOpen, setEditorModalOpen, setEditing, editing }) => {
const { t } = useTranslation('chat');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
const updateGroupConfig = useAgentGroupStore((s) => s.updateGroupConfig);
const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig);
const handleSystemPromptChange = async (value: string) => {
+ if (!canEdit) return;
if (!activeGroupId) return;
await updateGroupConfig({ systemPrompt: value });
};
const handleOpenWithEdit = (e: MouseEvent) => {
e.stopPropagation();
+ if (!canEdit) return;
+
setEditing(true);
setEditorModalOpen(true);
};
@@ -72,8 +77,12 @@ const GroupRole = memo<GroupRoleProps>(
title: t('settingGroup.systemPrompt.title', { ns: 'setting' }),
}}
onChange={handleSystemPromptChange}
- onEditingChange={setEditing}
onOpenChange={setEditorModalOpen}
+ onEditingChange={(next) => {
+ if (!canEdit) return;
+
+ setEditing(next);
+ }}
/>
</Flexbox>
);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
index fe50b7b850f..68be0c8e540 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
@@ -1,14 +1,14 @@
import { Flexbox, Popover } from '@lobehub/ui';
import { type PropsWithChildren } from 'react';
import React, { memo, Suspense } from 'react';
-import { useNavigate } from 'react-router-dom';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import List from '@/routes/(main)/home/_layout/Body/Agent/List';
import { AgentModalProvider } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';
const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return (
<Popover
placement="bottomLeft"
diff --git a/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
index 30fb28b3dcf..5e68381478d 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
@@ -7,6 +7,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -18,6 +19,7 @@ interface MembersProps {
const Members = memo<MembersProps>(({ itemKey }) => {
const { t } = useTranslation('chat');
+ const { allowed: canEdit, reason } = usePermission('edit_own_content');
const [addModalOpen, setAddModalOpen] = useState(false);
const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
@@ -28,6 +30,8 @@ const Members = memo<MembersProps>(({ itemKey }) => {
const handleAddMember = (e: MouseEvent) => {
e.stopPropagation();
+ if (!canEdit) return;
+
setAddModalOpen(true);
};
@@ -40,9 +44,10 @@ const Members = memo<MembersProps>(({ itemKey }) => {
<>
{isRevalidating && <ActionIcon loading icon={Loader2Icon} size={'small'} />}
<ActionIcon
+ disabled={!canEdit}
icon={UserPlus}
size={'small'}
- title={t('groupSidebar.members.addMember')}
+ title={canEdit ? t('groupSidebar.members.addMember') : reason}
onClick={handleAddMember}
/>
</>
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..fba8f11fa16
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
@@ -0,0 +1,118 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicItemDropdownMenu } from './useDropdownMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: {
+ success: vi.fn(),
+ },
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('@/const/version', () => ({
+ isDesktop: false,
+}));
+
+vi.mock('@/features/Electron/titlebar/RecentlyViewed/plugins', () => ({
+ pluginRegistry: {
+ parseUrl: vi.fn(),
+ },
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://example.com',
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/agentGroup', () => ({
+ useAgentGroupStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ activeGroupId: 'group-1' }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ autoRenameTopicTitle: vi.fn(),
+ duplicateTopic: vi.fn(),
+ markTopicCompleted: vi.fn(),
+ removeTopic: vi.fn(),
+ unmarkTopicCompleted: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ addTab: vi.fn() }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ openGroupTopicInNewWindow: vi.fn() }),
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<ReturnType<typeof useTopicItemDropdownMenu>>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('group useTopicItemDropdownMenu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables topic management actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({
+ id: 'topic-1',
+ toggleEditing: vi.fn(),
+ }),
+ );
+ const items = result.current();
+
+ for (const key of ['markCompleted', 'autoRename', 'rename', 'duplicate', 'delete']) {
+ expect(getMenuItem(items, key)).toMatchObject({ disabled: true });
+ }
+
+ expect(getMenuItem(items, 'copySessionId')).not.toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'copyLink')).not.toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index 02e3b7dcfaf..108e546d709 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -17,10 +17,11 @@ import {
} from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { isDesktop } from '@/const/version';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
@@ -39,7 +40,9 @@ export const useTopicItemDropdownMenu = ({
}: TopicItemDropdownMenuProps): (() => MenuProps['items']) => {
const { t } = useTranslation(['topic', 'common']);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canCreateTopic } = usePermission('create_content');
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
const openGroupTopicInNewWindow = useGlobalStore((s) => s.openGroupTopicInNewWindow);
const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
@@ -67,6 +70,7 @@ export const useTopicItemDropdownMenu = ({
return [
{
+ disabled: !canEditTopic,
icon: <Icon icon={isCompleted ? Circle : CheckCircle2} />,
key: 'markCompleted',
label: isCompleted ? t('actions.unmarkCompleted') : t('actions.markCompleted'),
@@ -82,6 +86,7 @@ export const useTopicItemDropdownMenu = ({
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Wand2} />,
key: 'autoRename',
label: t('actions.autoRename'),
@@ -90,6 +95,7 @@ export const useTopicItemDropdownMenu = ({
},
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={PencilLine} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -147,6 +153,7 @@ export const useTopicItemDropdownMenu = ({
},
},
{
+ disabled: !canCreateTopic,
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('actions.duplicate'),
@@ -159,6 +166,7 @@ export const useTopicItemDropdownMenu = ({
},
{
danger: true,
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
@@ -179,6 +187,8 @@ export const useTopicItemDropdownMenu = ({
}, [
id,
isCompleted,
+ canCreateTopic,
+ canEditTopic,
activeGroupId,
appOrigin,
autoRenameTopicTitle,
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..d2f3bbd8d7e
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
@@ -0,0 +1,56 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useThreadItemDropdownMenu } from './useDropdownMenu';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({
+ allowed: false,
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ removeThread: vi.fn() }),
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<ReturnType<typeof useThreadItemDropdownMenu>>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('group useThreadItemDropdownMenu', () => {
+ it('disables thread management actions for workspace viewers', () => {
+ const { result } = renderHook(() =>
+ useThreadItemDropdownMenu({ id: 'thread-1', toggleEditing: vi.fn() }),
+ );
+ const items = result.current();
+
+ expect(getMenuItem(items, 'rename')).toMatchObject({ disabled: true });
+ expect(getMenuItem(items, 'delete')).toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
index 986799d602c..83fc3c0a4a2 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -5,6 +5,7 @@ import { PencilLine, Trash } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
interface ThreadItemDropdownMenuProps {
@@ -17,12 +18,14 @@ export const useThreadItemDropdownMenu = ({
toggleEditing,
}: ThreadItemDropdownMenuProps): (() => MenuProps['items']) => {
const { t } = useTranslation(['thread', 'common']);
+ const { allowed: canEditThread } = usePermission('edit_own_content');
const [removeThread] = useChatStore((s) => [s.removeThread]);
return useCallback(() => {
return [
{
+ disabled: !canEditThread,
icon: <Icon icon={PencilLine} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -35,6 +38,7 @@ export const useThreadItemDropdownMenu = ({
},
{
danger: true,
+ disabled: !canEditThread,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
@@ -52,5 +56,5 @@ export const useThreadItemDropdownMenu = ({
},
},
].filter(Boolean) as MenuProps['items'];
- }, [id, removeThread, toggleEditing, t]);
+ }, [id, canEditThread, removeThread, toggleEditing, t]);
};
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
new file mode 100644
index 00000000000..889b59146be
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
@@ -0,0 +1,88 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+const permissionMock = vi.hoisted(() => ({
+ create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ modal: {
+ confirm: vi.fn(),
+ error: vi.fn(),
+ },
+ }),
+ },
+ Upload: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (action: 'create_content' | 'edit_own_content') => ({
+ allowed: permissionMock[action],
+ reason: '',
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ importTopic: vi.fn(),
+ removeSessionTopics: vi.fn(),
+ removeUnstarredTopic: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ topicPageSize: 20,
+ updateSystemStatus: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ topicPageSize: (s: { topicPageSize: number }) => s.topicPageSize,
+ },
+}));
+
+const getMenuItem = (
+ items: NonNullable<ReturnType<typeof useTopicActionsDropdownMenu>>,
+ key: string,
+) => items.find((item) => item && 'key' in item && item.key === key);
+
+describe('group useTopicActionsDropdownMenu', () => {
+ beforeEach(() => {
+ permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
+ });
+
+ it('disables topic write management actions for workspace viewers', () => {
+ permissionMock.create_content = false;
+ permissionMock.edit_own_content = false;
+
+ const { result } = renderHook(() => useTopicActionsDropdownMenu());
+
+ expect(getMenuItem(result.current!, 'import')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current!, 'deleteUnstarred')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current!, 'deleteAll')).toMatchObject({ disabled: true });
+ });
+});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
index 073830b876a..fdf275cf6c6 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -7,6 +7,7 @@ import { Hash, Import, LucideCheck, Trash } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -30,6 +31,8 @@ export const useTopicActionsDropdownMenu = (
const { t } = useTranslation(['topic', 'common']);
const { modal } = App.useApp();
const { onUploadClose } = options;
+ const { allowed: canCreateTopic } = usePermission('create_content');
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
const [removeUnstarredTopic, removeAllTopic, importTopic] = useChatStore((s) => [
s.removeUnstarredTopic,
@@ -84,10 +87,16 @@ export const useTopicActionsDropdownMenu = (
type: 'divider' as const,
},
{
+ disabled: !canCreateTopic,
icon: <Icon icon={Import} />,
key: 'import',
label: (
- <Upload accept=".json" beforeUpload={handleImport} showUploadList={false}>
+ <Upload
+ accept=".json"
+ beforeUpload={handleImport}
+ disabled={!canCreateTopic}
+ showUploadList={false}
+ >
<div className={cx(hotArea)}>{t('actions.import')}</div>
</Upload>
),
@@ -97,6 +106,7 @@ export const useTopicActionsDropdownMenu = (
type: 'divider' as const,
},
{
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteUnstarred',
label: t('actions.removeUnstarred'),
@@ -112,6 +122,7 @@ export const useTopicActionsDropdownMenu = (
},
{
danger: true,
+ disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteAll',
label: t('actions.removeAll'),
@@ -130,6 +141,8 @@ export const useTopicActionsDropdownMenu = (
topicPageSize,
updateSystemStatus,
handleImport,
+ canCreateTopic,
+ canEditTopic,
onUploadClose,
removeUnstarredTopic,
removeAllTopic,
diff --git a/src/routes/(main)/group/_layout/Sidebar/index.tsx b/src/routes/(main)/group/_layout/Sidebar/index.tsx
index 72736d62ca7..8082a0c14ee 100644
--- a/src/routes/(main)/group/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/index.tsx
@@ -1,15 +1,13 @@
import React, { memo } from 'react';
import { NavPanelPortal } from '@/features/NavPanel';
-import SideBarLayout from '@/features/NavPanel/SideBarLayout';
-import Body from './Body';
-import Header from './Header';
+import GroupSidebarContent from './Content';
const Sidebar = memo(() => {
return (
<NavPanelPortal navKey="group">
- <SideBarLayout body={<Body />} header={<Header />} />
+ <GroupSidebarContent />
</NavPanelPortal>
);
});
diff --git a/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx
new file mode 100644
index 00000000000..da2373b6701
--- /dev/null
+++ b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ShareButton from './index';
+
+const mocks = vi.hoisted(() => ({
+ activeTopicId: 'topic-1' as string | undefined,
+ enableBusinessFeatures: true,
+ permission: {
+ allowed: true,
+ reason: 'requires member',
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button data-testid="share-button" disabled={disabled} title={title} onClick={onClick}>
+ {title}
+ </button>
+ ),
+}));
+
+vi.mock('@/libs/next/dynamic', () => ({
+ default: () =>
+ function DynamicComponent({ children }: { children?: ReactNode }) {
+ return <div data-testid="share-popover">{children}</div>;
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/features/ShareModal', () => ({
+ useShareModal: () => ({
+ openShareModal: vi.fn(),
+ }),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: { activeTopicId?: string }) => unknown) =>
+ selector({ activeTopicId: mocks.activeTopicId }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (
+ selector: (state: { serverConfig: { enableBusinessFeatures: boolean } }) => unknown,
+ ) => selector({ serverConfig: { enableBusinessFeatures: mocks.enableBusinessFeatures } }),
+}));
+
+vi.mock('@/store/serverConfig/selectors', () => ({
+ serverConfigSelectors: {
+ enableBusinessFeatures: (s: { serverConfig: { enableBusinessFeatures: boolean } }) =>
+ s.serverConfig.enableBusinessFeatures,
+ },
+}));
+
+describe('Group Conversation ShareButton', () => {
+ beforeEach(() => {
+ mocks.activeTopicId = 'topic-1';
+ mocks.enableBusinessFeatures = true;
+ mocks.permission.allowed = true;
+ });
+
+ it('does not open share popover for workspace viewers', () => {
+ mocks.permission.allowed = false;
+
+ const { queryByTestId, getByTestId } = render(<ShareButton />);
+
+ expect(getByTestId('share-button')).toBeDisabled();
+ expect(getByTestId('share-button')).toHaveAttribute('title', 'requires member');
+ expect(queryByTestId('share-popover')).toBeNull();
+ });
+});
diff --git a/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.tsx b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.tsx
index a1cf961db5c..3217a94c413 100644
--- a/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useShareModal } from '@/features/ShareModal';
import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
@@ -23,22 +24,26 @@ const ShareButton = memo<ShareButtonProps>(({ mobile, setOpen, open }) => {
const { t } = useTranslation('common');
const activeTopicId = useChatStore((s) => s.activeTopicId);
const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
+ const { allowed: canShare, reason } = usePermission('edit_own_content');
// Hide share button when no topic exists (no messages sent yet)
if (!activeTopicId) return null;
const iconButton = (
<ActionIcon
+ disabled={!canShare}
icon={Share2}
size={mobile ? MOBILE_HEADER_ICON_SIZE : DESKTOP_HEADER_ICON_SIZE}
- title={t('share')}
+ title={canShare ? t('share') : reason}
tooltipProps={{
placement: 'bottom',
}}
- onClick={enableTopicLinkShare ? undefined : openShareModal}
+ onClick={enableTopicLinkShare || !canShare ? undefined : openShareModal}
/>
);
+ if (!canShare) return iconButton;
+
return (
<>
{enableTopicLinkShare ? (
diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
index 5ee81ef32a5..ff7437ced8c 100644
--- a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
+++ b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -4,6 +4,7 @@ import { memo } from 'react';
import AgentBuilderWelcome from '@/features/AgentBuilder/AgentBuilderWelcome';
import { type ActionKeys } from '@/features/ChatInput';
import { ChatInput, ChatList } from '@/features/Conversation';
+import { usePermission } from '@/hooks/usePermission';
import TopicSelector from './TopicSelector';
@@ -18,11 +19,13 @@ const rightActions: ActionKeys[] = [];
* Displays the chat interface for configuring the agent via conversation
*/
const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId }) => {
+ const { allowed: canCreate } = usePermission('create_content');
+
return (
<Flexbox flex={1} height={'100%'}>
- <TopicSelector agentId={agentId} />
+ <TopicSelector agentId={agentId} disabled={!canCreate} />
<Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <ChatList welcome={<AgentBuilderWelcome mode="group" />} />
+ <ChatList welcome={<AgentBuilderWelcome disabled={!canCreate} mode="group" />} />
</Flexbox>
<ChatInput leftActions={actions} rightActions={rightActions} showControlBar={false} />
</Flexbox>
diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
index 02b256b7a4e..36ee3fb0ba9 100644
--- a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
+++ b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
@@ -12,9 +12,10 @@ import { topicSelectors } from '@/store/chat/slices/topic/selectors';
interface TopicSelectorProps {
agentId: string;
+ disabled?: boolean;
}
-const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
+const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {
const { t } = useTranslation('topic');
// Fetch topics for the group agent builder
@@ -48,6 +49,7 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
key: topic.id,
label: topic.title,
onCheckedChange: (checked) => {
+ if (disabled) return;
if (checked) {
handleSwitchTopic(topic.id);
}
@@ -65,18 +67,23 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
right={
<>
<ActionIcon
+ disabled={disabled}
icon={PlusIcon}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
title={t('actions.addNewTopic')}
- onClick={() => handleSwitchTopic(undefined)}
+ onClick={() => {
+ if (disabled) return;
+
+ handleSwitchTopic(undefined);
+ }}
/>
<DropdownMenu
items={items}
placement="bottomRight"
popupProps={{ style: { maxHeight: 600, minWidth: 200, overflowY: 'auto' } }}
- triggerProps={{ disabled: isEmpty }}
+ triggerProps={{ disabled: disabled || isEmpty }}
>
- <ActionIcon disabled={isEmpty} icon={Clock3Icon} />
+ <ActionIcon disabled={disabled || isEmpty} icon={Clock3Icon} />
</DropdownMenu>
</>
}
diff --git a/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
index 735f8c84024..e3cb5c1b9b5 100644
--- a/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import Menu from '@/components/Menu';
import { DEFAULT_AVATAR } from '@/const/meta';
import { AgentSettings as Settings } from '@/features/AgentSetting';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -17,11 +18,13 @@ import { ChatSettingsTabs } from '@/store/global/initialState';
const Content = memo(() => {
const { t } = useTranslation('setting');
const theme = useTheme();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
const [tab] = useState(ChatSettingsTabs.Opening);
const updateGroupConfig = async (config: any) => {
+ if (!canEdit) return;
if (!groupId) return;
// Only update openingMessage and openingQuestions
const groupConfig = {
@@ -32,6 +35,7 @@ const Content = memo(() => {
};
const updateGroupMeta = async (meta: any) => {
+ if (!canEdit) return;
if (!groupId) return;
await useAgentGroupStore.getState().updateGroup(groupId, meta);
};
@@ -125,6 +129,7 @@ const Content = memo(() => {
>
<Settings
config={agentConfig}
+ disabled={!canEdit}
id={groupId}
loading={false}
meta={agentMeta}
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx b/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
index 16252f05ab3..d2f3d965214 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
@@ -4,8 +4,8 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { marketApiService } from '@/services/marketApi';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -17,7 +17,7 @@ import { type AgentGroupForkSourceResponse } from '@/types/discover';
*/
const GroupForkTag = memo(() => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [forkSource, setForkSource] = useState<AgentGroupForkSourceResponse['source']>(null);
const [loading, setLoading] = useState(false);
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx b/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
index 85bfb23c1f6..a821267ebca 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import EmojiPicker from '@/components/EmojiPicker';
import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { usePermission } from '@/hooks/usePermission';
import GroupAvatar from '@/routes/(main)/group/features/GroupAvatar';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -22,6 +23,7 @@ const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
const GroupHeader = memo(() => {
const { t } = useTranslation('agentGroup');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
// Get group meta from agentGroup store
@@ -43,6 +45,8 @@ const GroupHeader = memo(() => {
// Debounced save for title
const { run: debouncedSaveTitle } = useDebounceFn(
(value: string) => {
+ if (!canEdit) return;
+
updateGroupMeta({ title: value });
},
{ wait: EDITOR_DEBOUNCE_TIME },
@@ -50,12 +54,16 @@ const GroupHeader = memo(() => {
// Handle avatar change (immediate save)
const handleAvatarChange = (emoji: string) => {
+ if (!canEdit) return;
+
updateGroupMeta({ avatar: emoji });
};
// Handle avatar upload
const handleAvatarUpload = useCallback(
async (file: File) => {
+ if (!canEdit) return;
+
if (file.size > MAX_AVATAR_SIZE) {
message.error(t('avatar.sizeExceeded'));
return;
@@ -71,16 +79,20 @@ const GroupHeader = memo(() => {
setUploading(false);
}
},
- [uploadWithProgress, updateGroupMeta, t],
+ [canEdit, uploadWithProgress, updateGroupMeta, t],
);
// Handle avatar delete
const handleAvatarDelete = useCallback(() => {
+ if (!canEdit) return;
+
updateGroupMeta({ avatar: undefined });
- }, [updateGroupMeta]);
+ }, [canEdit, updateGroupMeta]);
// Handle background color change
const handleBackgroundColorChange = (color?: string) => {
+ if (!canEdit) return;
+
if (color !== undefined) {
updateGroupMeta({ backgroundColor: color });
}
@@ -100,10 +112,11 @@ const GroupHeader = memo(() => {
>
{/* Avatar Section */}
<EmojiPicker
- allowUpload
- allowDelete={!!groupMeta.avatar}
+ allowDelete={canEdit && !!groupMeta.avatar}
+ allowUpload={canEdit}
loading={uploading}
locale={locale}
+ open={canEdit ? undefined : false}
shape={'square'}
size={72}
value={groupMeta.avatar}
@@ -141,6 +154,7 @@ const GroupHeader = memo(() => {
}
>
<BackgroundSwatches
+ disabled={!canEdit}
gap={8}
shape={'square'}
size={38}
@@ -163,6 +177,7 @@ const GroupHeader = memo(() => {
{/* Title Section */}
<Flexbox flex={1} style={{ minWidth: 0 }}>
<Input
+ disabled={!canEdit}
placeholder={t('name.placeholder')}
value={localTitle}
variant={'borderless'}
@@ -174,6 +189,8 @@ const GroupHeader = memo(() => {
}}
onChange={(e) => {
setLocalTitle(e.target.value);
+ if (!canEdit) return;
+
debouncedSaveTitle(e.target.value);
}}
/>
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
index 23e6233d984..f5618d66f75 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
@@ -1,14 +1,16 @@
'use client';
-import { Button, Flexbox } from '@lobehub/ui';
+import { ActionIcon, Button, DropdownMenu, Flexbox } from '@lobehub/ui';
import { Divider } from 'antd';
import { useTheme } from 'antd-style';
-import { PlayIcon, Settings2Icon } from 'lucide-react';
+import { MoreHorizontalIcon, PlayIcon, Settings2Icon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
+import { useAgentGroupTransferMenuItem } from '@/business/client/hooks/useAgentGroupTransferMenuItem';
import { EditorCanvas } from '@/features/EditorCanvas';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -24,12 +26,14 @@ import GroupVersionReviewTag from './GroupVersionReviewTag';
const GroupProfile = memo(() => {
const { t } = useTranslation(['setting', 'chat']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const theme = useTheme();
const [showAgentSetting, setShowAgentSetting] = useState(false);
const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
const updateGroup = useAgentGroupStore((s) => s.updateGroup);
const router = useQueryRoute();
+ const transferMenuItems = useAgentGroupTransferMenuItem(groupId ?? undefined);
const editor = useGroupProfileStore((s) => s.editor);
const handleContentChange = useGroupProfileStore((s) => s.handleContentChange);
@@ -39,18 +43,21 @@ const GroupProfile = memo(() => {
// Create save callback that captures latest groupId
const saveContent = useCallback(
async (payload: { content: string; editorData: Record<string, any> }) => {
+ if (!canEdit) return;
if (!groupId) return;
await updateGroup(groupId, {
content: payload.content,
editorData: payload.editorData,
});
},
- [updateGroup, groupId],
+ [canEdit, updateGroup, groupId],
);
const onContentChange = useCallback(() => {
+ if (!canEdit) return;
+
handleContentChange(saveContent);
- }, [handleContentChange, saveContent]);
+ }, [canEdit, handleContentChange, saveContent]);
// Stabilize editorData object reference to prevent unnecessary re-renders
const editorData = useMemo(
@@ -110,12 +117,26 @@ const GroupProfile = memo(() => {
{t('startConversation')}
</Button>
<GroupPublishButton />
+ {!!transferMenuItems?.length && (
+ <DropdownMenu items={transferMenuItems}>
+ <ActionIcon
+ icon={MoreHorizontalIcon}
+ size={'small'}
+ style={{ color: theme.colorTextSecondary }}
+ />
+ </DropdownMenu>
+ )}
<Button
+ disabled={!canEdit}
icon={Settings2Icon}
size={'small'}
style={{ color: theme.colorTextSecondary }}
type={'text'}
- onClick={() => setShowAgentSetting(true)}
+ onClick={() => {
+ if (!canEdit) return;
+
+ setShowAgentSetting(true);
+ }}
>
{t('advancedSettings')}
</Button>
@@ -124,6 +145,7 @@ const GroupProfile = memo(() => {
<Divider />
{/* Group Content Editor */}
<EditorCanvas
+ disabled={!canEdit}
editor={editor}
editorData={editorData}
entityId={groupId}
diff --git a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx
index d8f1e24bc7a..792159cbc6d 100644
--- a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx
+++ b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
import { HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { checkOwnership } from '@/hooks/useAgentOwnershipCheck';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -22,6 +23,7 @@ interface MarketPublishButtonProps {
const PublishButton = memo<MarketPublishButtonProps>(
({ action, marketIdentifier, onPublishSuccess }) => {
const { t } = useTranslation(['setting', 'marketAuth']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const mobile = useServerConfigStore((s) => s.isMobile);
@@ -129,11 +131,16 @@ const PublishButton = memo<MarketPublishButtonProps>(
return (
<ActionIcon
+ disabled={!canEdit}
icon={ShapesUploadIcon}
loading={loading}
size={HEADER_ICON_SIZE(mobile)}
title={buttonTitle}
- onClick={handleButtonClick}
+ onClick={() => {
+ if (!canEdit) return;
+
+ handleButtonClick();
+ }}
/>
);
},
diff --git a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
index 3684bbc5193..7ca68bf324b 100644
--- a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
+++ b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
@@ -4,7 +4,8 @@ import { FluentEmoji, Modal, Text } from '@lobehub/ui';
import { Result } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface PublishResultModalProps {
identifier?: string;
@@ -13,7 +14,7 @@ interface PublishResultModalProps {
}
const PublishResultModal = memo<PublishResultModalProps>(({ identifier, onCancel, open }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
diff --git a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts
index 815d41cfd36..0229220197e 100644
--- a/src/routes/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts
+++ b/src/routes/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts
@@ -2,9 +2,11 @@ import isEqual from 'fast-deep-equal';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { message } from '@/components/AntdStaticMethods';
import { useTokenCount } from '@/hooks/useTokenCount';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { lambdaClient } from '@/libs/trpc/client';
import { marketApiService } from '@/services/marketApi';
import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
@@ -37,6 +39,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
const model = useAgentStore(agentSelectors.currentAgentModel);
const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
const tokenUsage = useTokenCount(systemRole);
+ const hasActiveWorkspace = useHasActiveWorkspace();
const isSubmit = action === 'submit';
@@ -57,6 +60,9 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
setIsPublishing(true);
message.loading({ content: loadingMessage, key: messageKey });
marketApiService.setAccessToken(session.accessToken);
+ const actAs = hasActiveWorkspace
+ ? (await lambdaClient.workspace.ensureMarketOrganization.mutate()).marketAccountId
+ : undefined;
if (isSubmit) {
identifier = generateMarketIdentifier();
@@ -65,6 +71,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
await marketApiService.getAgentDetail(identifier);
} catch {
const createPayload: Record<string, unknown> = {
+ actAs,
identifier,
name: meta?.title || '',
};
@@ -79,6 +86,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
}
const versionPayload = {
+ actAs,
avatar: meta?.avatar,
changelog,
config: {
@@ -162,6 +170,7 @@ export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions)
chatConfig?.historyCount,
chatConfig?.searchMode,
editorData,
+ hasActiveWorkspace,
isAuthenticated,
isSubmit,
language,
diff --git a/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx b/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
index 5b7d8172dde..a4d1aa3edb4 100644
--- a/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
+++ b/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { Avatar, Flexbox } from '@lobehub/ui';
+import { Avatar, Flexbox, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { Plus } from 'lucide-react';
import { type ReactNode } from 'react';
@@ -31,6 +31,15 @@ const styles = createStaticStyles(({ css, cssVar: cv }) => ({
background: ${cv.colorFillTertiary};
}
`,
+ addButtonDisabled: css`
+ cursor: not-allowed;
+ color: ${cv.colorTextQuaternary};
+
+ &:hover {
+ color: ${cv.colorTextQuaternary};
+ background: transparent;
+ }
+ `,
container: css`
display: flex;
gap: 2px;
@@ -103,64 +112,76 @@ export interface ChromeTabItem {
interface ChromeTabsProps {
activeId: string;
+ addDisabled?: boolean;
+ addDisabledReason?: string;
items: ChromeTabItem[];
onAdd?: () => void;
onChange: (id: string) => void;
}
-const ChromeTabs = memo<ChromeTabsProps>(({ items, activeId, onChange, onAdd }) => {
- const { t } = useTranslation('chat');
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current || !activeId) return;
-
- const activeTab = containerRef.current.querySelector(`[data-tab-id="${activeId}"]`);
- if (!activeTab) return;
-
- const containerRect = containerRef.current.getBoundingClientRect();
- const tabRect = activeTab.getBoundingClientRect();
-
- const isVisible = tabRect.left >= containerRect.left && tabRect.right <= containerRect.right;
-
- if (!isVisible) {
- activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
- }
- }, [activeId]);
-
- return (
- <div className={styles.container} ref={containerRef}>
- {items.map((item) => {
- const isActive = item.id === activeId;
-
- return (
- <div
- className={cx(styles.tab, isActive && styles.tabActive)}
- data-tab-id={item.id}
- key={item.id}
- onClick={() => onChange(item.id)}
- >
- <Flexbox horizontal align="center" gap={6}>
- {item.icon ? (
- item.icon
- ) : item.avatar ? (
- <Avatar avatar={item.avatar} size={18} />
- ) : null}
- <span className={styles.tabTitle}>{item.title}</span>
- {item.isExternal && (
- <span className={styles.externalTag}>{t('group.profile.external')}</span>
- )}
- </Flexbox>
- </div>
- );
- })}
- {onAdd && (
- <div className={styles.addButton} onClick={onAdd}>
- <Plus size={16} />
- </div>
- )}
- </div>
- );
-});
+const ChromeTabs = memo<ChromeTabsProps>(
+ ({ items, activeId, onChange, onAdd, addDisabled, addDisabledReason }) => {
+ const { t } = useTranslation('chat');
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!containerRef.current || !activeId) return;
+
+ const activeTab = containerRef.current.querySelector(`[data-tab-id="${activeId}"]`);
+ if (!activeTab) return;
+
+ const containerRect = containerRef.current.getBoundingClientRect();
+ const tabRect = activeTab.getBoundingClientRect();
+
+ const isVisible = tabRect.left >= containerRect.left && tabRect.right <= containerRect.right;
+
+ if (!isVisible) {
+ activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
+ }
+ }, [activeId]);
+
+ return (
+ <div className={styles.container} ref={containerRef}>
+ {items.map((item) => {
+ const isActive = item.id === activeId;
+
+ return (
+ <div
+ className={cx(styles.tab, isActive && styles.tabActive)}
+ data-tab-id={item.id}
+ key={item.id}
+ onClick={() => onChange(item.id)}
+ >
+ <Flexbox horizontal align="center" gap={6}>
+ {item.icon ? (
+ item.icon
+ ) : item.avatar ? (
+ <Avatar avatar={item.avatar} size={18} />
+ ) : null}
+ <span className={styles.tabTitle}>{item.title}</span>
+ {item.isExternal && (
+ <span className={styles.externalTag}>{t('group.profile.external')}</span>
+ )}
+ </Flexbox>
+ </div>
+ );
+ })}
+ {onAdd && (
+ <Tooltip title={addDisabled ? addDisabledReason : undefined}>
+ <div
+ className={cx(styles.addButton, addDisabled && styles.addButtonDisabled)}
+ onClick={() => {
+ if (addDisabled) return;
+ onAdd();
+ }}
+ >
+ <Plus size={16} />
+ </div>
+ </Tooltip>
+ )}
+ </div>
+ );
+ },
+);
export default ChromeTabs;
diff --git a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/GroupPublishResultModal.tsx b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/GroupPublishResultModal.tsx
index e657aaab9ea..b08725218cf 100644
--- a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/GroupPublishResultModal.tsx
+++ b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/GroupPublishResultModal.tsx
@@ -4,7 +4,8 @@ import { FluentEmoji, Modal, Text } from '@lobehub/ui';
import { Result } from 'antd';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
interface GroupPublishResultModalProps {
identifier?: string;
@@ -14,7 +15,7 @@ interface GroupPublishResultModalProps {
const GroupPublishResultModal = memo<GroupPublishResultModalProps>(
({ identifier, onCancel, open }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
diff --git a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/PublishButton.tsx b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/PublishButton.tsx
index 6afa36063fd..87b151736f0 100644
--- a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/PublishButton.tsx
+++ b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/PublishButton.tsx
@@ -6,6 +6,8 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
+import { useCommunityPublishGuard } from '@/hooks/useCommunityPublishGuard';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -23,6 +25,9 @@ interface GroupPublishButtonProps {
const PublishButton = memo<GroupPublishButtonProps>(({ action, onPublishSuccess }) => {
const { t } = useTranslation(['setting', 'marketAuth']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ const ensureCommunityPublishAllowed = useCommunityPublishGuard();
const { isAuthenticated, isLoading, signIn } = useMarketAuth();
const { checkOwnership, isCheckingOwnership, isPublishing, publish } = useMarketGroupPublish({
@@ -76,6 +81,8 @@ const PublishButton = memo<GroupPublishButtonProps>(({ action, onPublishSuccess
}, [checkOwnership, publish]);
const handleButtonClick = useCallback(() => {
+ if (!ensureCommunityPublishAllowed()) return;
+
// Check if the latest version is under review
if (isUnderReview) {
message.warning({
@@ -100,7 +107,13 @@ const PublishButton = memo<GroupPublishButtonProps>(({ action, onPublishSuccess
// Open popconfirm for user confirmation
setConfirmOpened(true);
- }, [currentGroupMeta?.title, currentGroup?.content, isUnderReview, t]);
+ }, [
+ currentGroupMeta?.title,
+ currentGroup?.content,
+ ensureCommunityPublishAllowed,
+ isUnderReview,
+ t,
+ ]);
const handleConfirmPublish = useCallback(async () => {
setConfirmOpened(false);
@@ -157,10 +170,15 @@ const PublishButton = memo<GroupPublishButtonProps>(({ action, onPublishSuccess
}}
>
<Button
+ disabled={!canEdit}
icon={ShapesUploadIcon}
loading={loading}
title={buttonTitle}
- onClick={handleButtonClick}
+ onClick={() => {
+ if (!canEdit) return;
+
+ handleButtonClick();
+ }}
>
{t('publishToCommunity')}
</Button>
diff --git a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/useMarketGroupPublish.ts b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/useMarketGroupPublish.ts
index 496d27a3ee8..d74548d02af 100644
--- a/src/routes/(main)/group/profile/features/Header/GroupPublishButton/useMarketGroupPublish.ts
+++ b/src/routes/(main)/group/profile/features/Header/GroupPublishButton/useMarketGroupPublish.ts
@@ -2,6 +2,7 @@ import isEqual from 'fast-deep-equal';
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { message } from '@/components/AntdStaticMethods';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { lambdaClient } from '@/libs/trpc/client';
@@ -37,6 +38,7 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
const currentGroupAgents = useAgentGroupStore(agentGroupSelectors.currentGroupAgents);
const updateGroupMeta = useAgentGroupStore((s) => s.updateGroupMeta);
const language = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const hasActiveWorkspace = useHasActiveWorkspace();
const isSubmit = action === 'submit';
@@ -55,7 +57,24 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
try {
setIsCheckingOwnership(true);
- const result = await lambdaClient.market.agentGroup.checkOwnership.query({ identifier });
+ let actAs: number | undefined;
+ if (hasActiveWorkspace) {
+ try {
+ const { marketAccountId } =
+ await lambdaClient.workspace.ensureMarketOrganization.mutate();
+ actAs = marketAccountId;
+ } catch (error) {
+ console.warn(
+ 'Failed to resolve Market organization for workspace ownership check:',
+ error,
+ );
+ }
+ }
+
+ const result = await lambdaClient.market.agentGroup.checkOwnership.query({
+ actAs,
+ identifier,
+ });
// If group doesn't exist or user is owner, no confirmation needed
if (!result.exists || result.isOwner) {
@@ -74,7 +93,7 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
} finally {
setIsCheckingOwnership(false);
}
- }, [currentGroup]);
+ }, [currentGroup, hasActiveWorkspace]);
const publish = useCallback(async () => {
// Prevent duplicate publishing
@@ -103,6 +122,9 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
isPublishingRef.current = true;
setIsPublishing(true);
message.loading({ content: loadingMessage, key: messageKey });
+ const actAs = hasActiveWorkspace
+ ? (await lambdaClient.workspace.ensureMarketOrganization.mutate()).marketAccountId
+ : undefined;
// Prepare member agents data
const memberAgents = currentGroupAgents.map((agent, index) => ({
@@ -132,6 +154,7 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
// Use tRPC publishOrCreate
const result = await lambdaClient.market.agentGroup.publishOrCreate.mutate({
+ actAs,
// Only include avatar if it's not null/undefined
...(currentGroupMeta.avatar ? { avatar: currentGroupMeta.avatar } : {}),
// Only include backgroundColor if it's not null/undefined
@@ -199,6 +222,7 @@ export const useMarketGroupPublish = ({ action, onSuccess }: UseMarketGroupPubli
currentGroupAgents,
currentGroupConfig,
currentGroupMeta,
+ hasActiveWorkspace,
isAuthenticated,
isSubmit,
language,
diff --git a/src/routes/(main)/group/profile/features/Header/index.tsx b/src/routes/(main)/group/profile/features/Header/index.tsx
index ef5c9f5a5b1..58fbfa521c5 100644
--- a/src/routes/(main)/group/profile/features/Header/index.tsx
+++ b/src/routes/(main)/group/profile/features/Header/index.tsx
@@ -7,6 +7,7 @@ import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ToggleLeftPanelButton from '@/features/NavPanel/ToggleLeftPanelButton';
+import { usePermission } from '@/hooks/usePermission';
import { parseAsString, useQueryState } from '@/hooks/useQueryParam';
import AddGroupMemberModal from '@/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -43,6 +44,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const Header = memo(() => {
const { t } = useTranslation('chat');
+ const { allowed: canEdit, reason } = usePermission('edit_own_content');
const [showAddModal, setShowAddModal] = useState(false);
@@ -95,6 +97,8 @@ const Header = memo(() => {
<div className={styles.tabsWrapper}>
<ChromeTabs
activeId={selectedTabId}
+ addDisabled={!canEdit}
+ addDisabledReason={reason}
items={tabItems}
onAdd={() => setShowAddModal(true)}
onChange={setSelectedTabId}
diff --git a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
index 4cbb6d33d61..6fd8a600706 100644
--- a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
+++ b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import EmojiPicker from '@/components/EmojiPicker';
import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { usePermission } from '@/hooks/usePermission';
import SupervisorAvatar from '@/routes/(main)/group/features/GroupAvatar';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -22,15 +23,18 @@ import { useGroupProfileStore } from '@/store/groupProfile';
const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
interface AgentHeaderProps {
+ disabled?: boolean;
/**
* When true, shows fixed title (supervisor) and disables avatar editing
*/
readOnly?: boolean;
}
-const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
+const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }) => {
const { t } = useTranslation(['setting', 'common', 'chat']);
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const disabled = disabledProp || !canEdit;
// Get agentId from profile store
const agentId = useGroupProfileStore((s) => s.activeTabId);
@@ -54,6 +58,8 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
// Debounced save for title - save to agent store
const { run: debouncedSaveTitle } = useDebounceFn(
(value: string) => {
+ if (disabled) return;
+
optimisticUpdateAgentMeta(agentId, { title: value });
},
{ wait: EDITOR_DEBOUNCE_TIME },
@@ -61,12 +67,16 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
// Handle avatar change (immediate save) - save to agent store (supervisor agent)
const handleAvatarChange = (emoji: string) => {
+ if (disabled) return;
+
optimisticUpdateAgentMeta(agentId, { avatar: emoji });
};
// Handle avatar upload
const handleAvatarUpload = useCallback(
async (file: File) => {
+ if (disabled) return;
+
if (file.size > MAX_AVATAR_SIZE) {
message.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
return;
@@ -82,16 +92,20 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
setUploading(false);
}
},
- [uploadWithProgress, optimisticUpdateAgentMeta, agentId, t],
+ [disabled, uploadWithProgress, optimisticUpdateAgentMeta, agentId, t],
);
// Handle avatar delete
const handleAvatarDelete = useCallback(() => {
+ if (disabled) return;
+
optimisticUpdateAgentMeta(agentId, { avatar: null });
- }, [optimisticUpdateAgentMeta, agentId]);
+ }, [disabled, optimisticUpdateAgentMeta, agentId]);
// Handle background color change (immediate save) - save to agent store (supervisor agent)
const handleBackgroundColorChange = (color?: string) => {
+ if (disabled) return;
+
if (color !== undefined) {
optimisticUpdateAgentMeta(agentId, { backgroundColor: color });
}
@@ -139,10 +153,11 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
}}
>
<EmojiPicker
- allowUpload
- allowDelete={!!agentMeta.avatar}
+ allowDelete={!disabled && !!agentMeta.avatar}
+ allowUpload={!disabled}
loading={uploading}
locale={locale}
+ open={disabled ? false : undefined}
shape={'square'}
size={72}
value={agentMeta.avatar}
@@ -180,6 +195,7 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
}
>
<BackgroundSwatches
+ disabled={disabled}
gap={8}
shape={'square'}
size={38}
@@ -200,6 +216,7 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
onUpload={handleAvatarUpload}
/>
<Input
+ disabled={disabled}
placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}
value={localTitle}
variant={'borderless'}
@@ -211,6 +228,8 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
}}
onChange={(e) => {
setLocalTitle(e.target.value);
+ if (disabled) return;
+
debouncedSaveTitle(e.target.value);
}}
/>
diff --git a/src/routes/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx b/src/routes/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx
index 18fc0ec0d93..804de1fd0ef 100644
--- a/src/routes/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx
+++ b/src/routes/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx
@@ -13,6 +13,7 @@ import { memo, useCallback, useMemo } from 'react';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
@@ -112,6 +113,7 @@ const resolveApiDescription = (
};
const useMentionOptions = () => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
const installedTools = useToolStore(toolSelectors.metaList, isEqual);
const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
@@ -148,6 +150,8 @@ const useMentionOptions = () => {
label,
metadata: createMetadata(),
onSelect: (editor: IEditor) => {
+ if (!canEdit) return;
+
toggleAgentPlugin(tool.identifier, true);
editor.dispatchCommand(INSERT_MENTION_COMMAND, {
label,
@@ -156,7 +160,7 @@ const useMentionOptions = () => {
},
};
});
- }, [installedTools, toggleAgentPlugin]);
+ }, [canEdit, installedTools, toggleAgentPlugin]);
const loadItems = useCallback(
async (
diff --git a/src/routes/(main)/group/profile/features/MemberProfile/index.tsx b/src/routes/(main)/group/profile/features/MemberProfile/index.tsx
index 1c73680af87..cc6d632c781 100644
--- a/src/routes/(main)/group/profile/features/MemberProfile/index.tsx
+++ b/src/routes/(main)/group/profile/features/MemberProfile/index.tsx
@@ -10,6 +10,7 @@ import urlJoin from 'url-join';
import { EditorCanvas } from '@/features/EditorCanvas';
import ModelSelect from '@/features/ModelSelect';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -23,6 +24,7 @@ import AgentTool from './AgentTool';
const MemberProfile = memo(() => {
const { t } = useTranslation(['setting', 'chat']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
// Get agentId from profile store (activeTabId is the selected agent ID)
const agentId = useGroupProfileStore((s) => s.activeTabId);
@@ -61,25 +63,31 @@ const MemberProfile = memo(() => {
// Wrap updateAgentConfigById for saving editor content
const updateContent = useCallback(
async (payload: { content: string; editorData: Record<string, any> }) => {
+ if (!canEdit) return;
+
await updateAgentConfigById(agentId, {
editorData: payload.editorData,
systemRole: payload.content,
});
},
- [updateAgentConfigById, agentId],
+ [canEdit, updateAgentConfigById, agentId],
);
// Handle editor content change
const onContentChange = useCallback(() => {
+ if (!canEdit) return;
+
handleContentChange(updateContent);
- }, [handleContentChange, updateContent]);
+ }, [canEdit, handleContentChange, updateContent]);
// Wrap updateAgentConfigById for ModelSelect
const updateAgentConfig = useCallback(
async (config: { model?: string; provider?: string }) => {
+ if (!canEdit) return;
+
await updateAgentConfigById(agentId, config);
},
- [updateAgentConfigById, agentId],
+ [canEdit, updateAgentConfigById, agentId],
);
// Watch for agent builder content updates and apply them directly to the editor
@@ -118,7 +126,7 @@ const MemberProfile = memo(() => {
}}
>
{/* Header: Avatar + Name */}
- <AgentHeader readOnly={isSupervisor} />
+ <AgentHeader disabled={!canEdit} readOnly={isSupervisor} />
{/* Config Bar: Model Selector */}
<Flexbox
horizontal
@@ -129,6 +137,7 @@ const MemberProfile = memo(() => {
>
<ModelSelect
initialWidth
+ disabled={!canEdit}
value={{
model: config?.model,
provider: config?.provider,
@@ -145,6 +154,7 @@ const MemberProfile = memo(() => {
style={{ marginTop: 16 }}
>
<Button
+ disabled={!canEdit}
icon={PlayIcon}
type={'primary'}
onClick={() => {
@@ -159,6 +169,7 @@ const MemberProfile = memo(() => {
<Divider />
{/* Main Content: Prompt Editor */}
<EditorCanvas
+ disabled={!canEdit}
editor={editor}
editorData={editorData}
entityId={agentId}
diff --git a/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx b/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx
index 33bb3973c19..98a33b58c27 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx
@@ -1,12 +1,13 @@
'use client';
-import { ActionIcon, Block, Center, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
+import { ActionIcon, Block, Center, DropdownMenu, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ChevronDownIcon, PlusIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { usePermission } from '@/hooks/usePermission';
import { SessionDefaultGroup } from '@/types/session';
import { useCreateMenuItems } from '../../hooks';
@@ -43,6 +44,7 @@ interface CreateAgentButtonProps {
const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className }) => {
const { t } = useTranslation('chat');
+ const { allowed: canCreate, reason } = usePermission('create_content');
const {
createAgent,
createAgentMenuItem,
@@ -77,6 +79,7 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className })
]);
const handleClick = () => {
+ if (!canCreate) return;
if (openCreateModal) {
openCreateModal('agent', isCustomGroup ? { groupId } : undefined);
} else {
@@ -84,16 +87,16 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className })
}
};
- return (
+ const content = (
<Block
- clickable
horizontal
align={'center'}
className={cx(styles.container, className)}
+ clickable={canCreate}
gap={8}
height={36}
paddingInline={4}
- style={{ height: 36 }}
+ style={canCreate ? { height: 36 } : { cursor: 'not-allowed', height: 36, opacity: 0.5 }}
variant={'borderless'}
onClick={handleClick}
>
@@ -107,28 +110,35 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className })
<Text style={{ flex: 1 }} type={'secondary'}>
{t('newAgent')}
</Text>
- <Flexbox
- horizontal
- align={'center'}
- className={ACTION_CLASS_NAME}
- flex={'none'}
- justify={'flex-end'}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- >
- <DropdownMenu items={dropdownItems} nativeButton={false}>
- <ActionIcon
- color={cssVar.colorTextQuaternary}
- icon={ChevronDownIcon}
- size={'small'}
- style={{ flex: 'none' }}
- />
- </DropdownMenu>
- </Flexbox>
+ {canCreate && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={ACTION_CLASS_NAME}
+ flex={'none'}
+ justify={'flex-end'}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <DropdownMenu items={dropdownItems} nativeButton={false}>
+ <ActionIcon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronDownIcon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ />
+ </DropdownMenu>
+ </Flexbox>
+ )}
</Block>
);
+
+ // Wrap in Tooltip when the viewer/member lacks `create_content`. The
+ // dropdown is hidden in the disabled state (it'd let users bypass the
+ // gate); the main click target is intercepted in `handleClick`.
+ return canCreate ? content : <Tooltip title={reason}>{content}</Tooltip>;
});
export default CreateAgentButton;
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
index 108895f3427..085ebd73816 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
@@ -6,10 +6,10 @@ import { Loader2, PinIcon } from 'lucide-react';
import { type CSSProperties, type DragEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import AgentGroupAvatar from '@/features/AgentGroupAvatar';
import NavItem from '@/features/NavPanel/components/NavItem';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
@@ -103,7 +103,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
});
return (
- <Link aria-label={id} ref={setAnchor} to={groupUrl} onClick={onNavigate}>
+ <WorkspaceLink aria-label={id} ref={setAnchor} to={groupUrl} onClick={onNavigate}>
<NavItem
actions={<Actions dropdownMenu={dropdownMenu} />}
className={className}
@@ -119,7 +119,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
/>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
index 213921a357f..54b1d5d0033 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
@@ -7,6 +7,7 @@ import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { openEditingPopover } from '@/features/EditingPopover/store';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
@@ -31,6 +32,7 @@ export const useGroupDropdownMenu = ({
}: UseGroupDropdownMenuParams): (() => MenuProps['items']) => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
const [pinAgentGroup, duplicateAgentGroup, removeAgentGroup] = useHomeStore((s) => [
@@ -43,17 +45,25 @@ export const useGroupDropdownMenu = ({
() => () =>
[
{
+ disabled: !canEdit,
icon: <Icon icon={pinned ? PinOff : Pin} />,
key: 'pin',
label: t(pinned ? 'pinOff' : 'pin'),
- onClick: () => pinAgentGroup(id, !pinned),
+ onClick: () => {
+ if (!canEdit) return;
+
+ pinAgentGroup(id, !pinned);
+ },
},
{
+ disabled: !canEdit,
icon: <Icon icon={Pen} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
onClick: (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canEdit) return;
+
if (anchor) {
openEditingPopover({
anchor,
@@ -68,11 +78,14 @@ export const useGroupDropdownMenu = ({
},
},
{
+ disabled: !canEdit,
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('duplicate', { ns: 'common' }),
onClick: ({ domEvent }: any) => {
domEvent.stopPropagation();
+ if (!canEdit) return;
+
duplicateAgentGroup(id);
},
},
@@ -88,11 +101,14 @@ export const useGroupDropdownMenu = ({
{ type: 'divider' },
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: ({ domEvent }: any) => {
domEvent.stopPropagation();
+ if (!canEdit) return;
+
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('confirmRemoveChatGroupItemAlert'),
@@ -111,6 +127,7 @@ export const useGroupDropdownMenu = ({
anchor,
avatar,
backgroundColor,
+ canEdit,
memberAvatars,
t,
pinned,
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index 20379c3cda2..069d7f8090b 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -6,9 +6,9 @@ import { Loader2, PinIcon } from 'lucide-react';
import { type CSSProperties, type DragEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
@@ -202,7 +202,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
});
return (
- <Link
+ <WorkspaceLink
aria-label={displayTitle}
ref={setAnchor}
to={agentUrl}
@@ -224,7 +224,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
/>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index b526b25a8f1..a4ea1ccaaaf 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -19,6 +19,7 @@ import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { openEditingPopover } from '@/features/EditingPopover/store';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
@@ -54,18 +55,27 @@ export const useAgentDropdownMenu = ({
s.removeAgent,
]);
+ // Viewer has no write permissions on agents — disable every mutating menu
+ // item (pin/rename/duplicate/move/delete) while keeping the menu visible
+ // so they can still inspect what actions exist. `openInNewWindow` is a
+ // pure read so it stays enabled.
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const { allowed: canCreate } = usePermission('create_content');
+
const isDefault = group === SessionDefaultGroup.Default;
return useMemo(
() => () =>
[
{
+ disabled: !canEdit,
icon: <Icon icon={pinned ? PinOff : Pin} />,
key: 'pin',
label: t(pinned ? 'pinOff' : 'pin'),
onClick: () => pinAgent(id, !pinned),
},
{
+ disabled: !canEdit,
icon: <Icon icon={Pen} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -77,6 +87,7 @@ export const useAgentDropdownMenu = ({
},
},
{
+ disabled: !canCreate,
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('duplicate', { ns: 'common' }),
@@ -96,6 +107,7 @@ export const useAgentDropdownMenu = ({
},
{ type: 'divider' },
{
+ disabled: !canEdit,
children: [
...sessionCustomGroups.map(({ id: groupId, name }) => ({
icon: group === groupId ? <Icon icon={Check} /> : <div />,
@@ -127,6 +139,7 @@ export const useAgentDropdownMenu = ({
{ type: 'divider' },
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
@@ -148,6 +161,8 @@ export const useAgentDropdownMenu = ({
] as MenuProps['items'],
[
anchor,
+ canCreate,
+ canEdit,
pinned,
id,
avatar,
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
index 36838e85517..09598d5b39e 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
@@ -6,9 +6,9 @@ import { createStaticStyles } from 'antd-style';
import { Loader2 } from 'lucide-react';
import { type CSSProperties } from 'react';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
@@ -69,7 +69,7 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {
);
return (
- <Link aria-label={inboxAgentTitle} to={inboxUrl}>
+ <WorkspaceLink aria-label={inboxAgentTitle} to={inboxUrl}>
<NavItem
className={className}
style={style}
@@ -87,7 +87,7 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {
)
}
/>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
index caa8b7f56be..ea8d8e784fb 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
@@ -2,12 +2,12 @@
import { type ReactNode, useCallback } from 'react';
import { createContext, memo, use, useMemo, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
import { ChatGroupWizard } from '@/components/ChatGroupWizard';
import { MemberSelectionModal } from '@/components/MemberSelectionModal';
import CreatePlatformAgentModal from '@/features/CreatePlatformAgent';
import EditingPopover from '@/features/EditingPopover';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { CreateAgentModal } from '@/routes/(main)/home/_layout/hooks/useCreateModal';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
@@ -70,7 +70,7 @@ interface CreateModalRendererProps {
}
const CreateModalRenderer = memo<CreateModalRendererProps>(({ open, type, groupId, onClose }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const storeCreateAgent = useAgentStore((s) => s.createAgent);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
diff --git a/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx b/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
index b445524974b..78256dc979d 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
@@ -23,7 +23,11 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const GroupItem = memo<SessionGroupItemBase>(({ id, name }) => {
+interface GroupItemProps extends SessionGroupItemBase {
+ disabled?: boolean;
+}
+
+const GroupItem = memo<GroupItemProps>(({ id, name, disabled }) => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
@@ -32,15 +36,27 @@ const GroupItem = memo<SessionGroupItemBase>(({ id, name }) => {
return (
<>
- <SortableList.DragHandle />
+ {!disabled && <SortableList.DragHandle />}
{!editing ? (
<>
<span className={styles.title}>{name}</span>
- <ActionIcon icon={PencilLine} size={'small'} onClick={() => setEditing(true)} />
<ActionIcon
+ disabled={disabled}
+ icon={PencilLine}
+ size={'small'}
+ onClick={() => {
+ if (disabled) return;
+
+ setEditing(true);
+ }}
+ />
+ <ActionIcon
+ disabled={disabled}
icon={Trash}
size={'small'}
onClick={() => {
+ if (disabled) return;
+
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('sessionGroup.confirmRemoveGroupAlert'),
@@ -64,6 +80,8 @@ const GroupItem = memo<SessionGroupItemBase>(({ id, name }) => {
value={name}
onEditingChange={(e) => setEditing(e)}
onChangeEnd={async (input) => {
+ if (disabled) return;
+
if (name !== input) {
if (!input) return;
if (input.length === 0 || input.length > 20 || input.trim() === '')
diff --git a/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/index.tsx
index 2697dbadc5c..50a9cf64fc7 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/Modals/ConfigGroupModal/index.tsx
@@ -6,6 +6,7 @@ import { Plus } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
import type { SessionGroupItemBase } from '@/types/session';
@@ -27,6 +28,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const ConfigGroupModal = memo<ModalProps>(({ open, onCancel }) => {
const { t } = useTranslation('chat');
+ const { allowed: canEdit } = usePermission('edit_own_content');
// Map SidebarGroup to SessionGroupItem-like structure for the sortable list
const sessionGroupItems = useHomeStore(
(s) =>
@@ -61,18 +63,23 @@ const ConfigGroupModal = memo<ModalProps>(({ open, onCancel }) => {
id={item.id}
justify={'space-between'}
>
- <GroupItem {...item} />
+ <GroupItem {...item} disabled={!canEdit} />
</SortableList.Item>
)}
onChange={(items: SessionGroupItemBase[]) => {
+ if (!canEdit) return;
+
updateGroupSort(items);
}}
/>
<Button
block
+ disabled={!canEdit}
icon={Plus}
loading={loading}
onClick={async () => {
+ if (!canEdit) return;
+
setLoading(true);
await addGroup(t('sessionGroup.newGroup'));
setLoading(false);
diff --git a/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx b/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx
index e4cbccfd845..ab694d575b9 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx
@@ -5,6 +5,7 @@ import { type MouseEvent } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
@@ -15,6 +16,7 @@ interface CreateGroupModalProps extends ModalProps {
const CreateGroupModal = memo<CreateGroupModalProps>(
({ id, open, onCancel }: CreateGroupModalProps) => {
const { t } = useTranslation('chat');
+ const { allowed: canCreate } = usePermission('create_content');
const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);
const { message } = App.useApp();
@@ -27,7 +29,7 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
<Modal
allowFullscreen
destroyOnHidden
- okButtonProps={{ loading }}
+ okButtonProps={{ disabled: !canCreate, loading }}
open={open}
title={t('sessionGroup.createGroup')}
width={400}
@@ -36,6 +38,8 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
onCancel?.(e);
}}
onOk={async (e: MouseEvent<HTMLButtonElement>) => {
+ if (!canCreate) return;
+
if (input.length === 0 || input.length > 20 || input.trim() === '')
return message.warning(t('sessionGroup.tooLong'));
@@ -52,6 +56,7 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
<Flexbox paddingBlock={16}>
<Input
autoFocus
+ disabled={!canCreate}
placeholder={t('sessionGroup.inputPlaceholder')}
value={input}
onChange={(e) => setInput(e.target.value)}
diff --git a/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.test.ts b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.test.ts
new file mode 100644
index 00000000000..5dc1690d986
--- /dev/null
+++ b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { getAvailableSidebarItems } from './CustomizeSidebarModal';
+
+describe('CustomizeSidebarModal', () => {
+ it('keeps Memory available in personal mode', () => {
+ const items = getAvailableSidebarItems(false);
+
+ expect(items.some((item) => item.id === 'memory')).toBe(true);
+ });
+
+ it('removes Memory from workspace mode customization', () => {
+ const items = getAvailableSidebarItems(true);
+
+ expect(items.some((item) => item.id === 'memory')).toBe(false);
+ });
+});
diff --git a/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx
index c76e6a7d8bb..0e1cb15906b 100644
--- a/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx
+++ b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx
@@ -29,6 +29,7 @@ import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { getRouteById } from '@/config/routes';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -40,7 +41,7 @@ import { SIDEBAR_ACCORDION_KEYS, SIDEBAR_SPACER_ID } from '@/store/global/select
const ACCORDION_GROUP_ID = 'accordion-group';
-interface SidebarItemConfig {
+export interface SidebarItemConfig {
alwaysVisible?: boolean;
id: string;
labelKey: string;
@@ -58,11 +59,29 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'memory', labelKey: 'tab.memory', routeId: 'memory' },
];
+export const getAvailableSidebarItems = (isWorkspaceMode: boolean): SidebarItemConfig[] =>
+ ALL_SIDEBAR_ITEMS.filter((item) => !(isWorkspaceMode && item.id === 'memory'));
+
const ITEM_MAP = new Map(ALL_SIDEBAR_ITEMS.map((item) => [item.id, item]));
const isAccordionKey = (id: string) => SIDEBAR_ACCORDION_KEYS.has(id);
const isSpacer = (id: string) => id === SIDEBAR_SPACER_ID;
+const mergeAvailableSidebarItems = (
+ currentItems: string[],
+ nextAvailableItems: string[],
+ availableItemIds: Set<string>,
+): string[] => {
+ let nextAvailableIndex = 0;
+ const nextItems = currentItems.map((id) => {
+ if (!availableItemIds.has(id)) return id;
+
+ return nextAvailableItems[nextAvailableIndex++] ?? id;
+ });
+
+ return [...nextItems, ...nextAvailableItems.slice(nextAvailableIndex)];
+};
+
// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------
@@ -313,15 +332,24 @@ const CustomizeSidebarContent = memo(() => {
systemStatusSelectors.hiddenSidebarSections(s),
s.updateSystemStatus,
]);
+ const isWorkspaceMode = !!useActiveWorkspaceSlug();
+ const availableItemIds = useMemo(
+ () => new Set(getAvailableSidebarItems(isWorkspaceMode).map((item) => item.id)),
+ [isWorkspaceMode],
+ );
+ const filteredStoreItems = useMemo(
+ () => storeItems.filter((id) => availableItemIds.has(id)),
+ [storeItems, availableItemIds],
+ );
// Local state for drag operations — only persisted on dragEnd
- const [items, setItems] = useState<string[]>(storeItems);
+ const [items, setItems] = useState<string[]>(filteredStoreItems);
const [activeId, setActiveId] = useState<string | null>(null);
// Sync local state when store changes (e.g. reset)
useEffect(() => {
- setItems(storeItems);
- }, [storeItems]);
+ setItems(filteredStoreItems);
+ }, [filteredStoreItems]);
// Derive outer (with group placeholder) and inner (accordion items)
const { bindSpacerToAccordion, innerItems, outerItems } = useMemo(() => {
@@ -417,15 +445,24 @@ const CustomizeSidebarContent = memo(() => {
}
setItems(next);
- updateSystemStatus({ sidebarItems: next });
+ updateSystemStatus({
+ sidebarItems: mergeAvailableSidebarItems(storeItems, next, availableItemIds),
+ });
},
- [bindSpacerToAccordion, innerItems, outerItems, updateSystemStatus],
+ [
+ availableItemIds,
+ bindSpacerToAccordion,
+ innerItems,
+ outerItems,
+ storeItems,
+ updateSystemStatus,
+ ],
);
const handleDragCancel = useCallback(() => {
setActiveId(null);
- setItems(storeItems);
- }, [storeItems]);
+ setItems(filteredStoreItems);
+ }, [filteredStoreItems]);
const renderItem = (id: string) =>
isSpacer(id) ? (
diff --git a/src/routes/(main)/home/_layout/Body/InboxEntry.tsx b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
index 6fb9e85caf4..35218a55405 100644
--- a/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
+++ b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
@@ -5,9 +5,10 @@ import { Avatar, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { Loader2 } from 'lucide-react';
import { memo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -42,7 +43,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const InboxEntry = memo(() => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId!));
const isLoading = useChatStore(
@@ -56,7 +57,7 @@ const InboxEntry = memo(() => {
const avatarNode = <Avatar emojiScaleWithBackground avatar={avatar} shape={'square'} size={24} />;
return (
- <Link
+ <WorkspaceLink
aria-label={title}
to={url}
onClick={(e) => {
@@ -80,7 +81,7 @@ const InboxEntry = memo(() => {
)
}
/>
- </Link>
+ </WorkspaceLink>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Project/List/index.tsx b/src/routes/(main)/home/_layout/Body/Project/List/index.tsx
index 7e2d0748a1c..13cacc83f51 100644
--- a/src/routes/(main)/home/_layout/Body/Project/List/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Project/List/index.tsx
@@ -3,11 +3,12 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import { LIBRARY_URL } from '@/const/url';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useKnowledgeBaseStore } from '@/store/library';
import { useProjectMenuItems } from '../../../hooks';
@@ -15,7 +16,7 @@ import Item from './Item';
const ProjectList = memo(() => {
const { t } = useTranslation('home');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);
const { data, isLoading } = useFetchKnowledgeBaseList();
const { createProject } = useProjectMenuItems();
@@ -31,7 +32,7 @@ const ProjectList = memo(() => {
return (
<Flexbox gap={1}>
{data.map((item) => (
- <Link
+ <WorkspaceLink
aria-label={item.id}
key={item.id}
to={LIBRARY_URL(item.id)}
@@ -41,7 +42,7 @@ const ProjectList = memo(() => {
}}
>
<Item {...item} key={item.id} />
- </Link>
+ </WorkspaceLink>
))}
</Flexbox>
);
diff --git a/src/routes/(main)/home/_layout/Body/index.tsx b/src/routes/(main)/home/_layout/Body/index.tsx
index b04e1cf3b93..3bac756bd82 100644
--- a/src/routes/(main)/home/_layout/Body/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/index.tsx
@@ -6,9 +6,10 @@ import { EyeOffIcon, MoreHorizontalIcon, SlidersHorizontalIcon } from 'lucide-re
import type { Key, ReactElement } from 'react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import type { NavItem as NavItemType } from '@/hooks/useNavLayout';
import { useNavLayout } from '@/hooks/useNavLayout';
@@ -60,7 +61,7 @@ const mergeSidebarExpandedKeys = (
const Body = memo(() => {
const { t } = useTranslation('common');
const tab = useActiveTabKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { topNavItems, bottomMenuItems } = useNavLayout();
const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems);
const sidebarExpandedKeys = useGlobalStore(systemStatusSelectors.sidebarExpandedKeys);
@@ -117,7 +118,7 @@ const Body = memo(() => {
const navItem = navLinkItems.get(key);
if (!navItem || navItem.hidden) return null;
return (
- <Link
+ <WorkspaceLink
key={key}
to={navItem.url!}
onClick={(e) => {
@@ -137,7 +138,7 @@ const Body = memo(() => {
</DropdownMenu>
}
/>
- </Link>
+ </WorkspaceLink>
);
},
[navLinkItems, tab, getContextMenuItems, navigate],
diff --git a/src/routes/(main)/home/_layout/CreateGroupModal/index.tsx b/src/routes/(main)/home/_layout/CreateGroupModal/index.tsx
index b32df131934..f92507dd8fe 100644
--- a/src/routes/(main)/home/_layout/CreateGroupModal/index.tsx
+++ b/src/routes/(main)/home/_layout/CreateGroupModal/index.tsx
@@ -7,6 +7,7 @@ import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
+import { usePermission } from '@/hooks/usePermission';
import { agentService } from '@/services/agent';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
@@ -40,6 +41,7 @@ export interface CreateGroupModalProps {
const CreateGroupModal = memo<CreateGroupModalProps>(({ id, onCancel, open }) => {
const { t } = useTranslation(['chat', 'common']);
+ const { allowed: canCreate } = usePermission('create_content');
const { message } = App.useApp();
const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);
@@ -74,6 +76,8 @@ const CreateGroupModal = memo<CreateGroupModalProps>(({ id, onCancel, open }) =>
}, [open, id, setSelectedAgents]);
const handleConfirm = async () => {
+ if (!canCreate) return;
+
if (groupName.length === 0 || groupName.length > 20 || groupName.trim() === '') {
message.warning(t('sessionGroup.tooLong'));
return;
@@ -108,7 +112,8 @@ const CreateGroupModal = memo<CreateGroupModalProps>(({ id, onCancel, open }) =>
onCancel();
};
- const isConfirmDisabled = groupName.trim() === '' || selectedAgentIds.length === 0 || isCreating;
+ const isConfirmDisabled =
+ !canCreate || groupName.trim() === '' || selectedAgentIds.length === 0 || isCreating;
return (
<div onClick={stopPropagation}>
@@ -142,7 +147,11 @@ const CreateGroupModal = memo<CreateGroupModalProps>(({ id, onCancel, open }) =>
<SelectedAgentList
agents={allAgents}
groupName={groupName}
- onGroupNameChange={setGroupName}
+ onGroupNameChange={(name) => {
+ if (!canCreate) return;
+
+ setGroupName(name);
+ }}
/>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/home/_layout/Footer/index.test.tsx b/src/routes/(main)/home/_layout/Footer/index.test.tsx
index 0ec8105bf2e..946803f684c 100644
--- a/src/routes/(main)/home/_layout/Footer/index.test.tsx
+++ b/src/routes/(main)/home/_layout/Footer/index.test.tsx
@@ -152,7 +152,7 @@ const renderFooter = async ({
</div>
) : null,
}));
- vi.doMock('@/features/User/UserPanel/ThemeButton', () => ({
+ vi.doMock('@/features/User/AccountPanel/AccountTrigger', () => ({
default: () => null,
}));
function createNavLayoutState() {
@@ -214,7 +214,7 @@ afterEach(() => {
vi.doUnmock('@/components/ChangelogModal');
vi.doUnmock('@/components/FeedbackModal');
vi.doUnmock('@/components/HighlightNotification');
- vi.doUnmock('@/features/User/UserPanel/ThemeButton');
+ vi.doUnmock('@/features/User/AccountPanel/AccountTrigger');
vi.doUnmock('@/hooks/useNavLayout');
vi.doUnmock('@/store/global');
vi.doUnmock('@/store/serverConfig');
diff --git a/src/routes/(main)/home/_layout/Footer/index.tsx b/src/routes/(main)/home/_layout/Footer/index.tsx
index 6c935f45240..3723dea2192 100644
--- a/src/routes/(main)/home/_layout/Footer/index.tsx
+++ b/src/routes/(main)/home/_layout/Footer/index.tsx
@@ -14,13 +14,11 @@ import {
FlaskConical,
MessageCircle,
Rocket,
- Settings2,
- SettingsIcon,
} from 'lucide-react';
import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
import { openChangelogModal } from '@/components/ChangelogModal';
import { openFeedbackModal } from '@/components/FeedbackModal';
@@ -29,14 +27,15 @@ import { DOCUMENTS_REFER_URL, GITHUB } from '@/const/url';
import Billboard from '@/features/Billboard';
import { useBillboardMenuItems } from '@/features/Billboard/MenuItems';
import { useActiveNavKey } from '@/features/NavPanel';
-import ThemeButton from '@/features/User/UserPanel/ThemeButton';
+import AccountTrigger from '@/features/User/AccountPanel/AccountTrigger';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useNavLayout } from '@/hooks/useNavLayout';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors/systemStatus';
import { useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
-import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors/general';
+import InboxButton from '../Header/components/InboxButton';
import { resolveFooterPromotionState } from './promotionPipeline';
const AGENT_ONBOARDING_PROMO_SLUG = 'agent-onboarding-promo-v1';
@@ -72,13 +71,13 @@ const Footer = memo(() => {
const enableAgentOnboarding = useServerConfigStore((s) => s.featureFlags.enableAgentOnboarding);
const isMobile = useServerConfigStore((s) => !!s.isMobile);
const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);
- const [agentOnboardingFinished, agentOnboardingStarted, classicOnboardingFinished, isDevMode] =
- useUserStore((s) => [
+ const [agentOnboardingFinished, agentOnboardingStarted, classicOnboardingFinished] = useUserStore(
+ (s) => [
!!s.agentOnboarding?.finishedAt,
!!s.agentOnboarding?.activeTopicId,
!!s.onboarding?.finishedAt,
- userGeneralSettingsSelectors.config(s).isDevMode,
- ]);
+ ],
+ );
const [isAgentOnboardingCardOpen, setIsAgentOnboardingCardOpen] = useState(false);
const [isProductHuntCardOpen, setIsProductHuntCardOpen] = useState(false);
@@ -251,18 +250,9 @@ const Footer = memo(() => {
const helpMenuItems: MenuProps['items'] = useMemo(
() => [
- ...(footer.showSettingsEntry && !isDevMode
- ? [
- {
- icon: <Icon icon={Settings2} />,
- key: 'setting',
- label: <Link to="/settings">{t('userPanel.setting')}</Link>,
- },
- {
- type: 'divider' as const,
- },
- ]
- : []),
+ {
+ type: 'divider' as const,
+ },
{
icon: <Icon icon={Book} />,
key: 'docs',
@@ -314,7 +304,7 @@ const Footer = memo(() => {
{
icon: <Icon icon={FlaskConical} />,
key: 'eval',
- label: <Link to="/eval">Evaluation Lab</Link>,
+ label: <WorkspaceLink to="/eval">Evaluation Lab</WorkspaceLink>,
},
]
: []),
@@ -333,14 +323,12 @@ const Footer = memo(() => {
: []),
],
[
- footer.showSettingsEntry,
footer.layout,
footer.hideGitHub,
footer.showEvalEntry,
handleOpenChangelogModal,
handleOpenFeedbackModal,
handleOpenProductHuntCard,
- isDevMode,
shouldShowProductHuntMenuEntry,
t,
billboardMenuItems,
@@ -366,27 +354,15 @@ const Footer = memo(() => {
<ActionIcon icon={GithubIcon} size={16} title={'GitHub'} />
</a>
)}
- <Link to="/eval">
+ <WorkspaceLink to="/eval">
<ActionIcon icon={FlaskConical} size={16} title="Evaluation Lab" />
- </Link>
+ </WorkspaceLink>
</Flexbox>
- <ThemeButton placement={'topCenter'} size={16} />
+ <AccountTrigger />
</Flexbox>
) : (
- <Flexbox horizontal align={'center'} gap={2} padding={8}>
- <DropdownMenu items={helpMenuItems} placement="topLeft">
- <ActionIcon aria-label={t('userPanel.help')} icon={CircleHelp} size={16} />
- </DropdownMenu>
- {isDevMode && (
- <Link to="/settings">
- <ActionIcon
- aria-label={t('userPanel.setting')}
- icon={SettingsIcon}
- size={16}
- title={t('userPanel.setting')}
- />
- </Link>
- )}
+ <Flexbox horizontal align={'center'} padding={8}>
+ <AccountTrigger actions={<InboxButton />} extraItems={helpMenuItems} />
</Flexbox>
)}
{activePromotion && (
diff --git a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
index 66a1ba032ac..5c861a3b483 100644
--- a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
@@ -1,4 +1,4 @@
-import { ActionIcon, DropdownMenu, Flexbox } from '@lobehub/ui';
+import { ActionIcon, DropdownMenu, Flexbox, Tooltip } from '@lobehub/ui';
import { CreateBotIcon } from '@lobehub/ui/icons';
import { cssVar } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
@@ -6,11 +6,13 @@ import React, { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { usePermission } from '@/hooks/usePermission';
import { useCreateMenuItems } from '../../hooks';
const AddButton = memo(() => {
const { t: tChat } = useTranslation('chat');
+ const { allowed: canCreate, reason } = usePermission('create_content');
// Create menu items
const {
@@ -28,9 +30,10 @@ const AddButton = memo(() => {
(e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
+ if (!canCreate) return;
openCreateModal?.('agent');
},
- [openCreateModal],
+ [canCreate, openCreateModal],
);
const dropdownItems = useMemo(() => {
@@ -54,25 +57,36 @@ const AddButton = memo(() => {
createPlatformAgentMenuItem,
]);
+ // When viewer (no create_content): keep the icons visible per UX rule
+ // (disabled-not-hidden), but the click handler short-circuits and the
+ // dropdown is hidden (it would let users bypass the gate). Tooltip
+ // surfaces the missing-permission reason.
+ const mainIcon = (
+ <ActionIcon
+ disabled={!canCreate}
+ icon={CreateBotIcon}
+ loading={isMutatingAgent || isCreatingGroup}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={canCreate ? tChat('newAgent') : undefined}
+ onClick={handleMainIconClick}
+ />
+ );
+
return (
<Flexbox horizontal>
- <ActionIcon
- icon={CreateBotIcon}
- loading={isMutatingAgent || isCreatingGroup}
- size={DESKTOP_HEADER_ICON_SIZE}
- title={tChat('newAgent')}
- onClick={handleMainIconClick}
- />
- <DropdownMenu items={dropdownItems}>
- <ActionIcon
- color={cssVar.colorTextQuaternary}
- icon={ChevronDownIcon}
- size={{ blockSize: 32, size: 14 }}
- style={{
- width: 16,
- }}
- />
- </DropdownMenu>
+ {canCreate ? mainIcon : <Tooltip title={reason}>{mainIcon}</Tooltip>}
+ {canCreate && (
+ <DropdownMenu items={dropdownItems}>
+ <ActionIcon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronDownIcon}
+ size={{ blockSize: 32, size: 14 }}
+ style={{
+ width: 16,
+ }}
+ />
+ </DropdownMenu>
+ )}
</Flexbox>
);
});
diff --git a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
index 5e76f190337..50c7e4d12e8 100644
--- a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
@@ -5,7 +5,8 @@ import { createStaticStyles, cssVar } from 'antd-style';
import dayjs from 'dayjs';
import { ArchiveIcon, BellIcon, ImageIcon, VideoIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
const ACTION_CLASS_NAME = 'notification-item-actions';
@@ -55,7 +56,7 @@ interface NotificationItemProps {
const NotificationItem = memo<NotificationItemProps>(
({ id, type, title, content, createdAt, isRead, actionUrl, onMarkAsRead, onArchive }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const TypeIcon = TYPE_ICON_MAP[type] || BellIcon;
const handleClick = useCallback(() => {
diff --git a/src/routes/(main)/home/_layout/Header/components/Nav.tsx b/src/routes/(main)/home/_layout/Header/components/Nav.tsx
index b773c716a4d..2c021ebdc3a 100644
--- a/src/routes/(main)/home/_layout/Header/components/Nav.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/Nav.tsx
@@ -3,10 +3,11 @@
import { Flexbox, Tag } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
import { type NavItemProps } from '@/features/NavPanel/components/NavItem';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import { useNavLayout } from '@/hooks/useNavLayout';
import { isModifierClick } from '@/utils/navigation';
@@ -16,7 +17,7 @@ const HEADER_KEYS = new Set(['home', 'search']);
const Nav = memo(() => {
const tab = useActiveTabKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('common');
const { topNavItems: items } = useNavLayout();
@@ -47,7 +48,7 @@ const Nav = memo(() => {
if (!item.url) return <div key={item.key}>{navItem}</div>;
return (
- <Link
+ <WorkspaceLink
key={item.key}
to={item.url}
onClick={(e) => {
@@ -60,7 +61,7 @@ const Nav = memo(() => {
}}
>
{navItem}
- </Link>
+ </WorkspaceLink>
);
})}
</Flexbox>
diff --git a/src/routes/(main)/home/_layout/Header/components/User.tsx b/src/routes/(main)/home/_layout/Header/components/User.tsx
index 21c4ed4b043..a998493e47e 100644
--- a/src/routes/(main)/home/_layout/Header/components/User.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/User.tsx
@@ -5,6 +5,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo } from 'react';
+import { useActiveIdentity } from '@/business/client/hooks/useActiveIdentity';
import { ProductLogo } from '@/components/Branding';
import UserAvatar from '@/features/User/UserAvatar';
import UserPanel from '@/features/User/UserPanel';
@@ -31,6 +32,13 @@ const User = memo<{ lite?: boolean }>(({ lite }) => {
authSelectors.isLogin(s),
]);
+ // When in a team workspace, reflect the workspace context in the header
+ // (avatar + name) instead of the user's identity. Personal workspaces and
+ // OSS builds fall back to the user-level display.
+ const activeIdentity = useActiveIdentity();
+ const displayAvatar = activeIdentity?.avatar ?? undefined;
+ const displayName = activeIdentity?.name ?? (nickname || username);
+
return (
<UserPanel>
<Block
@@ -48,14 +56,19 @@ const User = memo<{ lite?: boolean }>(({ lite }) => {
paddingInlineStart: 2,
}}
>
- <UserAvatar shape={'square'} size={28} />
+ <UserAvatar
+ avatarOverride={displayAvatar}
+ nameOverride={activeIdentity?.name ?? undefined}
+ shape={'square'}
+ size={28}
+ />
{!lite && (
<Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>
- {!isSignedIn && (nickname || username) ? (
+ {!isSignedIn && !activeIdentity ? (
<ProductLogo color={cssVar.colorText} size={28} type={'text'} />
) : (
<Text ellipsis style={{ flex: 1 }} weight={500}>
- {nickname || username}
+ {displayName}
</Text>
)}
<Icon
diff --git a/src/routes/(main)/home/_layout/Header/index.tsx b/src/routes/(main)/home/_layout/Header/index.tsx
index a168d262444..964336fb49d 100644
--- a/src/routes/(main)/home/_layout/Header/index.tsx
+++ b/src/routes/(main)/home/_layout/Header/index.tsx
@@ -4,14 +4,13 @@ import { memo } from 'react';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
-import InboxButton from './components/InboxButton';
import Nav from './components/Nav';
import User from './components/User';
const Header = memo(() => {
return (
<>
- <SideBarHeaderLayout left={<User />} right={<InboxButton />} showBack={false} />
+ <SideBarHeaderLayout left={<User />} showBack={false} />
<Nav />
</>
);
diff --git a/src/routes/(main)/home/_layout/Sidebar.tsx b/src/routes/(main)/home/_layout/Sidebar.tsx
index 9a8eb201da9..6eeb6998898 100644
--- a/src/routes/(main)/home/_layout/Sidebar.tsx
+++ b/src/routes/(main)/home/_layout/Sidebar.tsx
@@ -1,10 +1,25 @@
import { memo } from 'react';
+import { useLocation } from 'react-router-dom';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { NavPanelPortal } from '@/features/NavPanel';
import SidebarContent from './SidebarContent';
const Sidebar = memo(() => {
+ const { pathname } = useLocation();
+ const activeSlug = useActiveWorkspaceSlug();
+
+ // DesktopHomeLayout stays mounted via React 19 <Activity> on non-home routes,
+ // so this Sidebar also stays mounted. Without this gate, its NavPanelPortal
+ // would keep racing the active route's portal (e.g. workspace settings) for
+ // the global snapshot and could overwrite it on re-render.
+ const isHomeRoute =
+ pathname === '/' ||
+ (!!activeSlug && (pathname === `/${activeSlug}` || pathname === `/${activeSlug}/`));
+
+ if (!isHomeRoute) return null;
+
return (
<NavPanelPortal navKey="home">
<SidebarContent />
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
index 6f67d76f7b1..39ee09819ee 100644
--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
@@ -7,12 +7,13 @@ import type { ItemType } from 'antd/es/menu/interface';
import { BotIcon, FileTextIcon, FolderCogIcon, FolderPlus, MonitorSmartphone } from 'lucide-react';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import useSWRMutation from 'swr/mutation';
import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCreateHeteroAgent } from '@/hooks/useCreateHeteroAgent';
+import { usePermission } from '@/hooks/usePermission';
import { useOptionalAgentModal } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';
import type { CreateAgentParams } from '@/services/agent';
import type { GroupMemberConfig } from '@/services/chatGroup';
@@ -38,8 +39,9 @@ export const useCreateMenuItems = () => {
const { t } = useTranslation('chat');
const { t: tFile } = useTranslation('file');
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const groupTemplates = useGroupTemplates();
+ const { allowed: canCreate } = usePermission('create_content');
const [storeCreateAgent] = useAgentStore((s) => [s.createAgent]);
const [addGroup, refreshAgentList, switchToGroup] = useHomeStore((s) => [
@@ -98,11 +100,13 @@ export const useCreateMenuItems = () => {
*/
const createAgent = useCallback(
async (options?: CreateAgentOptions & { prompt?: string }) => {
+ if (!canCreate) return;
+
const config = options?.prompt ? { systemRole: options.prompt } : undefined;
await mutateAgent({ config, groupId: options?.groupId });
options?.onSuccess?.();
},
- [mutateAgent],
+ [canCreate, mutateAgent],
);
/**
@@ -111,6 +115,8 @@ export const useCreateMenuItems = () => {
*/
const createGroupFromTemplate = useCallback(
async (templateId: string, selectedMemberTitles?: string[]) => {
+ if (!canCreate) return false;
+
setIsCreatingGroup(true);
try {
const template = groupTemplates.find((t) => t.id === templateId);
@@ -156,7 +162,7 @@ export const useCreateMenuItems = () => {
setIsCreatingGroup(false);
}
},
- [groupTemplates, refreshAgentList, loadGroups, switchToGroup, message, t],
+ [canCreate, groupTemplates, refreshAgentList, loadGroups, switchToGroup, message, t],
);
/**
@@ -164,6 +170,8 @@ export const useCreateMenuItems = () => {
*/
const createGroupWithMembers = useCallback(
async (selectedAgents: string[], groupTitle?: string) => {
+ if (!canCreate) return false;
+
setIsCreatingGroup(true);
try {
const title = groupTitle || t('defaultGroupChat');
@@ -185,7 +193,7 @@ export const useCreateMenuItems = () => {
setIsCreatingGroup(false);
}
},
- [createGroup, message, t],
+ [canCreate, createGroup, message, t],
);
/**
@@ -193,9 +201,11 @@ export const useCreateMenuItems = () => {
*/
const createEmptyGroup = useCallback(
async (options?: CreateAgentOptions & { title?: string }) => {
+ if (!canCreate) return;
+
await mutateGroup(options);
},
- [mutateGroup],
+ [canCreate, mutateGroup],
);
const agentModal = useOptionalAgentModal();
@@ -208,10 +218,13 @@ export const useCreateMenuItems = () => {
const createAgentMenuItem = useCallback(
(options?: CreateAgentOptions): ItemType => ({
icon: <Icon icon={BotIcon} />,
+ disabled: !canCreate,
key: 'newAgent',
label: t('newAgent'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
+
if (openCreateModal) {
openCreateModal('agent', options?.groupId ? { groupId: options.groupId } : undefined);
} else {
@@ -219,7 +232,7 @@ export const useCreateMenuItems = () => {
}
},
}),
- [t, createAgent, openCreateModal],
+ [canCreate, t, createAgent, openCreateModal],
);
/**
@@ -234,16 +247,19 @@ export const useCreateMenuItems = () => {
return {
icon: <AgentIcon size={'1em'} />,
+ disabled: !canCreate,
key: definition.menuKey,
label: t(definition.menuLabelKey),
onClick: async (info) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
+
await createHeterogeneousAgent(definition, options);
},
};
});
},
- [t, createHeterogeneousAgent],
+ [canCreate, t, createHeterogeneousAgent],
);
/**
@@ -275,10 +291,13 @@ export const useCreateMenuItems = () => {
const createGroupChatMenuItem = useCallback(
(options?: CreateAgentOptions): ItemType => ({
icon: <Icon icon={GroupBotSquareIcon} />,
+ disabled: !canCreate,
key: 'newGroupChat',
label: t('newGroupChat'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
+
if (openCreateModal) {
openCreateModal('group', options?.groupId ? { groupId: options.groupId } : undefined);
} else {
@@ -286,7 +305,7 @@ export const useCreateMenuItems = () => {
}
},
}),
- [t, createEmptyGroup, openCreateModal],
+ [canCreate, t, createEmptyGroup, openCreateModal],
);
/**
@@ -295,16 +314,19 @@ export const useCreateMenuItems = () => {
const createSessionGroupMenuItem = useCallback(
(): ItemType => ({
icon: <Icon icon={FolderPlus} />,
+ disabled: !canCreate,
key: 'addSessionGroup',
label: t('sessionGroup.createGroup'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
+
setIsCreatingSessionGroup(true);
await addGroup(t('sessionGroup.newGroup'));
setIsCreatingSessionGroup(false);
},
}),
- [t, addGroup],
+ [canCreate, t, addGroup],
);
/**
@@ -327,6 +349,8 @@ export const useCreateMenuItems = () => {
* Create page action
*/
const createPage = useCallback(async () => {
+ if (!canCreate) return;
+
const untitledTitle = tFile('pageList.untitled');
try {
const newPageId = await createNewPage(untitledTitle);
@@ -335,7 +359,7 @@ export const useCreateMenuItems = () => {
console.error('Failed to create page:', error);
message.error('Failed to create page');
}
- }, [createNewPage, tFile, navigate, message]);
+ }, [canCreate, createNewPage, tFile, navigate, message]);
/**
* Create page menu item
@@ -343,14 +367,17 @@ export const useCreateMenuItems = () => {
const createPageMenuItem = useCallback(
(): ItemType => ({
icon: <Icon icon={FileTextIcon} />,
+ disabled: !canCreate,
key: 'newPage',
label: t('newPage'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
+
await createPage();
},
}),
- [t, createPage],
+ [canCreate, t, createPage],
);
return {
diff --git a/src/routes/(main)/home/_layout/hooks/useProjectMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useProjectMenuItems.tsx
index 0b9e9702460..1d023e0a0bf 100644
--- a/src/routes/(main)/home/_layout/hooks/useProjectMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useProjectMenuItems.tsx
@@ -3,9 +3,9 @@ import { type ItemType } from 'antd/es/menu/interface';
import { BoxIcon } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { useCreateNewModal } from '@/features/LibraryModal';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
/**
* Hook for generating menu items/buttons for knowledge base actions
@@ -13,7 +13,7 @@ import { useCreateNewModal } from '@/features/LibraryModal';
*/
export const useProjectMenuItems = () => {
const { t } = useTranslation('knowledgeBase');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { open } = useCreateNewModal();
/**
diff --git a/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
index 05b506cb202..1a6e6ba2162 100644
--- a/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
@@ -2,7 +2,6 @@ import { Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { type ItemType } from 'antd/es/menu/interface';
-import { createStaticStyles } from 'antd-style';
import { FolderCogIcon, FolderPenIcon, Trash } from 'lucide-react';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,16 +9,11 @@ import { useTranslation } from 'react-i18next';
import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
import { openEditingPopover } from '@/features/EditingPopover/store';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useHomeStore } from '@/store/home';
-const styles = createStaticStyles(({ css }) => ({
- modalRoot: css`
- z-index: 2000;
- `,
-}));
-
/**
* Hook for generating menu items for session group containers
* Used in List/Group/Actions.tsx
@@ -28,6 +22,8 @@ export const useSessionGroupMenuItems = () => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
const groupTemplates = useGroupTemplates();
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [storeCreateAgent] = useAgentStore((s) => [s.createAgent]);
const [removeGroup, refreshAgentList] = useHomeStore((s) => [s.removeGroup, s.refreshAgentList]);
@@ -43,18 +39,21 @@ export const useSessionGroupMenuItems = () => {
(groupId: string, groupName: string, anchor: HTMLElement | null): ItemType => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
+ disabled: !canEdit,
icon: iconElement,
key: 'rename',
label: t('sessionGroup.rename'),
onClick: (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canEdit) return;
+
if (anchor) {
openEditingPopover({ anchor, id: groupId, title: groupName, type: 'group' });
}
},
};
},
- [t],
+ [canEdit, t],
);
/**
@@ -64,16 +63,19 @@ export const useSessionGroupMenuItems = () => {
(onOpenConfig: () => void): ItemType => {
const iconElement = <Icon icon={FolderCogIcon} />;
return {
+ disabled: !canEdit,
icon: iconElement,
key: 'config',
label: t('sessionGroup.config'),
onClick: (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canEdit) return;
+
onOpenConfig();
},
};
},
- [t],
+ [canEdit, t],
);
/**
@@ -84,11 +86,14 @@ export const useSessionGroupMenuItems = () => {
const trashIcon = <Icon icon={Trash} />;
return {
danger: true,
+ disabled: !canEdit,
icon: trashIcon,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canEdit) return;
+
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('sessionGroup.confirmRemoveGroupAlert'),
@@ -102,7 +107,7 @@ export const useSessionGroupMenuItems = () => {
},
};
},
- [t, removeGroup],
+ [canEdit, t, removeGroup],
);
/**
@@ -112,11 +117,13 @@ export const useSessionGroupMenuItems = () => {
(groupId: string, _isPinned?: boolean): ItemType => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
+ disabled: !canCreate,
icon: iconElement,
key: 'createAgent',
label: t('newAgent'),
onClick: async (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
const key = 'createNewAgent';
message.loading({ content: t('sessionGroup.creatingAgent'), duration: 0, key });
@@ -138,7 +145,7 @@ export const useSessionGroupMenuItems = () => {
},
};
},
- [t, message, storeCreateAgent, refreshAgentList],
+ [canCreate, t, message, storeCreateAgent, refreshAgentList],
);
/**
@@ -155,11 +162,13 @@ export const useSessionGroupMenuItems = () => {
): ItemType => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
+ disabled: !canCreate,
icon: iconElement,
key: 'createGroupChat',
label: t('newGroupChat'),
onClick: async (info: any) => {
info.domEvent?.stopPropagation();
+ if (!canCreate) return;
onOpenMemberSelection({
onCancel: () => {},
@@ -184,7 +193,7 @@ export const useSessionGroupMenuItems = () => {
},
};
},
- [t, message, createGroup],
+ [canCreate, t, message, createGroup],
);
/**
@@ -193,6 +202,8 @@ export const useSessionGroupMenuItems = () => {
*/
const createGroupFromTemplate = useCallback(
async (templateId: string, selectedMemberTitles?: string[]) => {
+ if (!canCreate) return false;
+
setIsCreatingGroup(true);
try {
const template = groupTemplates.find((t) => t.id === templateId);
@@ -252,7 +263,7 @@ export const useSessionGroupMenuItems = () => {
setIsCreatingGroup(false);
}
},
- [groupTemplates, storeCreateAgent, refreshAgentList, createGroup, message, t],
+ [canCreate, groupTemplates, storeCreateAgent, refreshAgentList, createGroup, message, t],
);
/**
@@ -261,6 +272,8 @@ export const useSessionGroupMenuItems = () => {
*/
const createGroupWithMembers = useCallback(
async (selectedAgents: string[], groupTitle?: string) => {
+ if (!canCreate) return false;
+
setIsCreatingGroup(true);
try {
const title = groupTitle || t('defaultGroupChat');
@@ -282,7 +295,7 @@ export const useSessionGroupMenuItems = () => {
setIsCreatingGroup(false);
}
},
- [createGroup, message, t],
+ [canCreate, createGroup, message, t],
);
return {
diff --git a/src/routes/(main)/home/_layout/index.tsx b/src/routes/(main)/home/_layout/index.tsx
index 66390eafe0f..9270afde07f 100644
--- a/src/routes/(main)/home/_layout/index.tsx
+++ b/src/routes/(main)/home/_layout/index.tsx
@@ -3,6 +3,7 @@ import { useTheme } from 'antd-style';
import { Activity, type FC, type ReactNode, useEffect, useMemo, useState } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { useIsDark } from '@/hooks/useIsDark';
import HomeAgentIdSync from './HomeAgentIdSync';
@@ -18,7 +19,10 @@ const Layout: FC<LayoutProps> = ({ children }) => {
const isDarkMode = useIsDark();
const theme = useTheme(); // Keep for colorBgContainerSecondary (not in cssVar)
const { pathname } = useLocation();
- const isHomeRoute = pathname === '/';
+ const activeSlug = useActiveWorkspaceSlug();
+ const isHomeRoute =
+ pathname === '/' ||
+ (!!activeSlug && (pathname === `/${activeSlug}` || pathname === `/${activeSlug}/`));
const [hasActivated, setHasActivated] = useState(isHomeRoute);
const content = children ?? <Outlet />;
@@ -39,7 +43,14 @@ const Layout: FC<LayoutProps> = ({ children }) => {
// Keep the Home layout alive and render it offscreen when inactive.
return (
<Activity mode={isHomeRoute ? 'visible' : 'hidden'} name="DesktopHomeLayout">
- <Flexbox className={styles.absoluteContainer} height={'100%'} width={'100%'}>
+ {/* `position: absolute; inset: 0` keeps overlaying the outlet when Activity is hidden,
+ because Activity preserves state but doesn't visually hide the DOM. Force-hide here. */}
+ <Flexbox
+ className={styles.absoluteContainer}
+ height={'100%'}
+ style={isHomeRoute ? undefined : { display: 'none' }}
+ width={'100%'}
+ >
<Sidebar />
<Flexbox
className={isDarkMode ? styles.contentDark : styles.contentLight}
diff --git a/src/routes/(main)/home/features/FeaturedPlugins/index.tsx b/src/routes/(main)/home/features/FeaturedPlugins/index.tsx
index fb631d1036c..9af8ac30688 100644
--- a/src/routes/(main)/home/features/FeaturedPlugins/index.tsx
+++ b/src/routes/(main)/home/features/FeaturedPlugins/index.tsx
@@ -4,9 +4,10 @@ import { MCP } from '@lobehub/icons';
import { ActionIcon, DropdownMenu, Grid } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { MoreHorizontal } from 'lucide-react';
-import { memo,Suspense } from 'react';
+import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import GroupBlock from '../components/GroupBlock';
import GroupSkeleton from '../components/GroupSkeleton';
@@ -15,7 +16,7 @@ import FeaturedPluginsList from './List';
const FeaturedPlugins = memo(() => {
const { t } = useTranslation('discover');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return (
<GroupBlock
diff --git a/src/routes/(main)/home/features/InputArea/BotIntegrationBanner.tsx b/src/routes/(main)/home/features/InputArea/BotIntegrationBanner.tsx
index 24c4329556d..cb8c016b7ae 100644
--- a/src/routes/(main)/home/features/InputArea/BotIntegrationBanner.tsx
+++ b/src/routes/(main)/home/features/InputArea/BotIntegrationBanner.tsx
@@ -6,8 +6,8 @@ import { RadioTowerIcon, X } from 'lucide-react';
import type { FC } from 'react';
import React, { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors/builtinAgentSelectors';
@@ -82,7 +82,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const BotIntegrationBanner = memo(() => {
const { t } = useTranslation('common');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
diff --git a/src/routes/(main)/home/features/InputArea/MessengerBanner.tsx b/src/routes/(main)/home/features/InputArea/MessengerBanner.tsx
index 635393d3d5d..7fede5dcc63 100644
--- a/src/routes/(main)/home/features/InputArea/MessengerBanner.tsx
+++ b/src/routes/(main)/home/features/InputArea/MessengerBanner.tsx
@@ -6,8 +6,8 @@ import { MessageCircleIcon, X } from 'lucide-react';
import type { FC } from 'react';
import React, { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
import { useGlobalStore } from '@/store/global';
@@ -73,7 +73,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const MessengerBanner = memo(() => {
const { t } = useTranslation('common');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
diff --git a/src/routes/(main)/home/features/InputArea/StarterList.tsx b/src/routes/(main)/home/features/InputArea/StarterList.tsx
index adbc1146e49..3fe12b3c87c 100644
--- a/src/routes/(main)/home/features/InputArea/StarterList.tsx
+++ b/src/routes/(main)/home/features/InputArea/StarterList.tsx
@@ -1,5 +1,5 @@
import { ModelIcon } from '@lobehub/icons';
-import { Button, Center, Skeleton, Tag } from '@lobehub/ui';
+import { Button, Center, Skeleton, Tag, Tooltip } from '@lobehub/ui';
import { App } from 'antd';
import { createStaticStyles, cx } from 'antd-style';
import { memo, useCallback, useState } from 'react';
@@ -11,6 +11,7 @@ import {
} from '@/business/client/hooks/useBusinessAgentMode';
import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';
import { useHomeNewModels } from '@/business/client/hooks/useHomeNewModels';
+import { usePermission } from '@/hooks/usePermission';
import { useStableNavigate } from '@/hooks/useStableNavigate';
import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
@@ -49,6 +50,7 @@ const StarterList = memo(() => {
const navigate = useStableNavigate();
const { message } = App.useApp();
const { agentId: activeAgentId } = useResolvedHomeAgentId();
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const [switchingKey, setSwitchingKey] = useState<string | null>(null);
const { isLoading, items } = useHomeNewModels(DEFAULT_HOME_NEW_MODELS);
@@ -56,6 +58,8 @@ const StarterList = memo(() => {
const handleClick = useCallback(
async (item: HomeNewModelItem) => {
+ if (!canCreateContent) return;
+
const key = getStarterItemKey(item);
if (item.type === 'video') {
@@ -111,6 +115,7 @@ const StarterList = memo(() => {
}
},
[
+ canCreateContent,
navigate,
activeAgentId,
applyBusinessModelModeConfig,
@@ -141,11 +146,10 @@ const StarterList = memo(() => {
: items.map((item) => {
const key = getStarterItemKey(item);
const isSwitching = switchingKey === key;
-
- return (
+ const button = (
<Button
className={cx(styles.button)}
- disabled={!!switchingKey && !isSwitching}
+ disabled={!canCreateContent || (!!switchingKey && !isSwitching)}
icon={<ModelIcon model={item.iconModel ?? item.model} size={18} />}
key={key}
loading={isSwitching}
@@ -156,6 +160,16 @@ const StarterList = memo(() => {
{item.title}
</Button>
);
+
+ if (!canCreateContent) {
+ return (
+ <Tooltip key={key} title={reason}>
+ <div>{button}</div>
+ </Tooltip>
+ );
+ }
+
+ return button;
})}
</Center>
);
diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
index 76a6dc8bb1f..2856c8c5ed4 100644
--- a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
+++ b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
@@ -4,11 +4,11 @@ import { Empty, Flexbox, SearchBar } from '@lobehub/ui';
import { SearchIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useClientDataSWR } from '@/libs/swr';
import { recentService } from '@/services/recent';
import { ALL_RECENTS_DRAWER_SWR_PREFIX } from '@/store/home/slices/recent/action';
@@ -74,13 +74,13 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {
/>
) : (
filteredRecents.map((item) => (
- <Link
+ <WorkspaceLink
key={`${item.type}-${item.id}`}
style={{ color: 'inherit', textDecoration: 'none' }}
to={getRecentRoute(item)}
>
<RecentListItem {...item} />
- </Link>
+ </WorkspaceLink>
))
)}
</Flexbox>
diff --git a/src/routes/(main)/home/features/Recents/List.tsx b/src/routes/(main)/home/features/Recents/List.tsx
index 51ce8248d54..50d31db3726 100644
--- a/src/routes/(main)/home/features/Recents/List.tsx
+++ b/src/routes/(main)/home/features/Recents/List.tsx
@@ -2,11 +2,11 @@ import { Flexbox } from '@lobehub/ui';
import { MoreHorizontalIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
@@ -44,13 +44,13 @@ const RecentsList = memo(() => {
return (
<Flexbox gap={1}>
{displayItems.map((item) => (
- <Link
+ <WorkspaceLink
key={`${item.type}-${item.id}`}
style={{ color: 'inherit', textDecoration: 'none' }}
to={getRecentRoute(item)}
>
<RecentListItem {...item} />
- </Link>
+ </WorkspaceLink>
))}
{hasMore && (
<NavItem icon={MoreHorizontalIcon} title={t('input.more')} onClick={openDrawer} />
diff --git a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
index 03fd99410ba..5a10a57e99b 100644
--- a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
@@ -5,6 +5,7 @@ import { PencilLineIcon, Trash } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { type RecentItem } from '@/server/routers/lambda/recent';
import { documentService } from '@/services/document';
import { taskService } from '@/services/task';
@@ -21,6 +22,11 @@ export const useRecentItemDropdownMenu = (
s.refreshRecents,
]);
+ // Viewer can read recents but cannot rename/delete them — keep the menu
+ // items visible-but-disabled so the affordance is clear (per disabled-not-
+ // hidden UX rule).
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
const handleRename = useCallback(
async (newTitle: string) => {
// Optimistic update
@@ -79,28 +85,24 @@ export const useRecentItemDropdownMenu = (
}, [item, t, refreshRecents]);
const dropdownMenu = useCallback((): MenuProps['items'] => {
- const canRename = true;
-
return [
- ...(canRename
- ? [
- {
- icon: <Icon icon={PencilLineIcon} />,
- key: 'rename',
- label: t('rename'),
- onClick: () => toggleEditing(true),
- },
- ]
- : []),
+ {
+ disabled: !canEdit,
+ icon: <Icon icon={PencilLineIcon} />,
+ key: 'rename',
+ label: t('rename'),
+ onClick: () => toggleEditing(true),
+ },
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete'),
onClick: handleDelete,
},
];
- }, [item.type, t, toggleEditing, handleDelete]);
+ }, [canEdit, t, toggleEditing, handleDelete]);
return { dropdownMenu, handleRename };
};
diff --git a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx
index 1100b520e69..2f6f716e0b0 100644
--- a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx
@@ -12,10 +12,11 @@ import {
} from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+import { Link } from 'react-router-dom';
import { type NavItemProps } from '@/features/NavPanel/components/NavItem';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePathname } from '@/libs/router/navigation';
import { useGlobalStore } from '@/store/global';
import { isModifierClick } from '@/utils/navigation';
@@ -45,7 +46,7 @@ const useActiveTabKey = () => {
const Nav = memo(() => {
const tab = useActiveTabKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('memory');
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
diff --git a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsx b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsx
index 67af1b9c878..15ec73d534d 100644
--- a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsx
@@ -3,10 +3,11 @@ import { cssVar } from 'antd-style';
import { Loader2Icon } from 'lucide-react';
import { type CSSProperties } from 'react';
import React, { memo, useCallback, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom';
import RepoIcon from '@/components/LibIcon';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useKnowledgeBaseStore } from '@/store/library';
@@ -26,7 +27,8 @@ interface KnowledgeBaseItemProps {
const KnowledgeBaseItem = memo<KnowledgeBaseItemProps>(
({ id, name, description, active, style, className }) => {
const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [editing, isLoading] = useKnowledgeBaseStore((s) => [
s.knowledgeBaseRenamingId === id,
@@ -53,11 +55,11 @@ const KnowledgeBaseItem = memo<KnowledgeBaseItemProps>(
const handleDoubleClick = useCallback(
(e: React.MouseEvent) => {
- if (e.altKey) {
+ if (e.altKey && canEdit) {
toggleEditing(true);
}
},
- [toggleEditing],
+ [canEdit, toggleEditing],
);
// Icon (show loader when updating)
diff --git a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsx b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsx
index c1fd0638b8e..db41a83c781 100644
--- a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsx
@@ -5,7 +5,9 @@ import { FileText, PencilLine, Trash } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { useKnowledgeBaseTransferMenuItem } from '@/business/client/hooks/useKnowledgeBaseTransferMenuItem';
import { useCreateNewModal } from '@/features/LibraryModal';
+import { usePermission } from '@/hooks/usePermission';
import { useKnowledgeBaseStore } from '@/store/library';
interface ActionProps {
@@ -24,8 +26,11 @@ export const useDropdownMenu = ({
const { t } = useTranslation(['file', 'common']);
const removeKnowledgeBase = useKnowledgeBaseStore((s) => s.removeKnowledgeBase);
const { open } = useCreateNewModal();
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const transferMenuItems = useKnowledgeBaseTransferMenuItem(id);
- const handleDelete = () => {
+ const handleDelete = useCallback(() => {
+ if (!canEdit) return;
if (!id) return;
confirmModal({
@@ -38,19 +43,21 @@ export const useDropdownMenu = ({
},
title: t('header.actions.deleteLibrary'),
});
- };
+ }, [canEdit, id, removeKnowledgeBase, t]);
- const handleEditDescription = () => {
+ const handleEditDescription = useCallback(() => {
+ if (!canEdit) return;
open({
id,
initialValues: { description: description || '', name },
});
- };
+ }, [canEdit, description, id, name, open]);
return useCallback(
() =>
[
{
+ disabled: !canEdit,
icon: <Icon icon={PencilLine} />,
key: 'rename',
label: t('rename', { ns: 'common' }),
@@ -60,6 +67,7 @@ export const useDropdownMenu = ({
},
},
{
+ disabled: !canEdit,
icon: <Icon icon={FileText} />,
key: 'editDescription',
label: t('edit', { ns: 'common' }),
@@ -68,25 +76,17 @@ export const useDropdownMenu = ({
handleEditDescription();
},
},
+ ...(canEdit ? (transferMenuItems ?? []) : []),
{ type: 'divider' },
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash} />,
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: handleDelete,
},
].filter(Boolean) as MenuProps['items'],
- [
- t,
- id,
- name,
- description,
- removeKnowledgeBase,
- toggleEditing,
- handleDelete,
- handleEditDescription,
- open,
- ],
+ [canEdit, t, toggleEditing, handleDelete, handleEditDescription, transferMenuItems],
);
};
diff --git a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
index 04508f5ebd0..d71f7992d74 100644
--- a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
@@ -3,11 +3,12 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { useCreateNewModal } from '@/features/LibraryModal';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useKnowledgeBaseStore } from '@/store/library';
import Item from './Item';
@@ -20,11 +21,13 @@ const LibraryList = memo(() => {
const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);
const { data, isLoading } = useFetchKnowledgeBaseList();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { open } = useCreateNewModal();
+ const { allowed: canCreate } = usePermission('create_content');
const handleCreate = () => {
+ if (!canCreate) return;
open({
onSuccess: (id) => {
navigate(`/resource/library/${id}`);
@@ -34,7 +37,8 @@ const LibraryList = memo(() => {
if (isLoading) return <SkeletonList paddingInline={4} rows={3} />;
- if (data?.length === 0) return <EmptyNavItem title={t('library.new')} onClick={handleCreate} />;
+ if (data?.length === 0)
+ return <EmptyNavItem disabled={!canCreate} title={t('library.new')} onClick={handleCreate} />;
return (
<Flexbox gap={1} paddingInline={4}>
diff --git a/src/routes/(main)/resource/(home)/_layout/Body/index.tsx b/src/routes/(main)/resource/(home)/_layout/Body/index.tsx
index c1017aa368f..eb4fd1769f1 100644
--- a/src/routes/(main)/resource/(home)/_layout/Body/index.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Body/index.tsx
@@ -1,20 +1,23 @@
-import { AccordionItem, ActionIcon, Text } from '@lobehub/ui';
+import { AccordionItem, ActionIcon, Text, Tooltip } from '@lobehub/ui';
import { PlusIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { useCreateNewModal } from '@/features/LibraryModal';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import LibraryList from './LibraryList';
const SidebarBody = memo<{ itemKey: string }>(({ itemKey }) => {
const { t } = useTranslation('file');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { open } = useCreateNewModal();
+ const { allowed: canCreate, reason } = usePermission('create_content');
const handleCreate = () => {
+ if (!canCreate) return;
open({
onSuccess: (id) => {
navigate(`/resource/library/${id}`);
@@ -22,19 +25,22 @@ const SidebarBody = memo<{ itemKey: string }>(({ itemKey }) => {
});
};
+ const createButton = (
+ <ActionIcon
+ disabled={!canCreate}
+ icon={PlusIcon}
+ size={'small'}
+ title={canCreate ? t('library.new') : undefined}
+ onClick={handleCreate}
+ />
+ );
+
return (
<AccordionItem
+ action={canCreate ? createButton : <Tooltip title={reason}>{createButton}</Tooltip>}
itemKey={itemKey}
paddingBlock={4}
paddingInline={'8px 4px'}
- action={
- <ActionIcon
- icon={PlusIcon}
- size={'small'}
- title={t('library.new')}
- onClick={handleCreate}
- />
- }
title={
<Text ellipsis fontSize={12} type={'secondary'} weight={500}>
{t('library.title')}
diff --git a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
index 7e8d663b13a..bfc13039d94 100644
--- a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
@@ -4,9 +4,10 @@ import { Flexbox } from '@lobehub/ui';
import { FileText, ImageIcon, LayoutPanelTopIcon, Mic2, SquarePlay } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useNavigate } from 'react-router-dom';
+import { Link } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { FilesTabs } from '@/types/files';
import { useResourceManagerStore } from '../../../features/store';
@@ -14,7 +15,7 @@ import { useResourceManagerStore } from '../../../features/store';
const CategoryMenu = memo(() => {
const { t } = useTranslation('file');
const [activeKey, setMode] = useResourceManagerStore((s) => [s.category, s.setMode]);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const items = useMemo(
() => [
diff --git a/src/routes/(main)/resource/features/DndContextWrapper.tsx b/src/routes/(main)/resource/features/DndContextWrapper.tsx
index aa9efe8f938..9d19f9bdb95 100644
--- a/src/routes/(main)/resource/features/DndContextWrapper.tsx
+++ b/src/routes/(main)/resource/features/DndContextWrapper.tsx
@@ -11,6 +11,7 @@ import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
+import { usePermission } from '@/hooks/usePermission';
import { useTreeStore } from '@/store/tree';
import { useResourceManagerStore } from './store';
@@ -74,6 +75,7 @@ export const useSetCurrentDrag = () => {
export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {
const { t } = useTranslation('components');
const { message } = App.useApp();
+ const { allowed: canEditResources } = usePermission('edit_own_content');
const [currentDrag, setCurrentDrag] = useState<DragState | null>(null);
const currentDragRef = useRef<DragState | null>(null);
currentDragRef.current = currentDrag;
@@ -109,6 +111,10 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {
const drag = currentDragRef.current;
if (!drag) return;
+ if (!canEditResources) {
+ setCurrentDrag(null);
+ return;
+ }
let dropTarget = event.target as HTMLElement;
let targetId: string | undefined;
@@ -190,7 +196,7 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {
document.removeEventListener('dragover', handleDragOver);
document.removeEventListener('dragend', handleDragEnd);
};
- }, [setCurrentDrag, setSelectedFileIds, message, t]);
+ }, [canEditResources, setCurrentDrag, setSelectedFileIds, message, t]);
const appElement = useAppElement();
diff --git a/src/routes/(main)/resource/features/modal/ModalPageClient.tsx b/src/routes/(main)/resource/features/modal/ModalPageClient.tsx
index 4831a4c4a33..038198bf2e2 100644
--- a/src/routes/(main)/resource/features/modal/ModalPageClient.tsx
+++ b/src/routes/(main)/resource/features/modal/ModalPageClient.tsx
@@ -1,7 +1,8 @@
'use client';
import { useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import FileDetail from './FileDetail';
import FilePreview from './FilePreview';
@@ -12,7 +13,7 @@ interface ModalPageClientProps {
}
const ModalPageClient = ({ id }: ModalPageClientProps) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleClose = useCallback(() => {
if (typeof window === 'undefined') return;
diff --git a/src/routes/(main)/resource/library/_layout/Header/LibraryHead.tsx b/src/routes/(main)/resource/library/_layout/Header/LibraryHead.tsx
index 4ef297cfb4c..168d53d43e8 100644
--- a/src/routes/(main)/resource/library/_layout/Header/LibraryHead.tsx
+++ b/src/routes/(main)/resource/library/_layout/Header/LibraryHead.tsx
@@ -14,9 +14,10 @@ import { createStaticStyles, cx } from 'antd-style';
import { ChevronsUpDownIcon } from 'lucide-react';
import { type DragEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import BusinessKnowledgeBaseImportAction from '@/business/client/BusinessKnowledgeBaseImportAction';
import RepoIcon from '@/components/LibIcon';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useDragActive } from '@/routes/(main)/resource/features/DndContextWrapper';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';
@@ -39,7 +40,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
* Quickly switch between libraries
*/
const Head = memo<{ id: string }>(({ id }) => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const name = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseNameById(id));
const [setMode, setLibraryId] = useResourceManagerStore((s) => [s.setMode, s.setLibraryId]);
const isDragActive = useDragActive();
@@ -145,6 +146,7 @@ const Head = memo<{ id: string }>(({ id }) => {
</Center>
</DropdownMenu>
)}
+ <BusinessKnowledgeBaseImportAction knowledgeBaseId={id} />
</Block>
);
});
diff --git a/src/routes/(main)/settings/_layout/Body/index.tsx b/src/routes/(main)/settings/_layout/Body/index.tsx
index 5f68f3ad3b2..efc05b7c644 100644
--- a/src/routes/(main)/settings/_layout/Body/index.tsx
+++ b/src/routes/(main)/settings/_layout/Body/index.tsx
@@ -2,9 +2,10 @@
import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';
import { memo, useMemo } from 'react';
-import { Link, useLocation, useNavigate } from 'react-router-dom';
+import { Link, useLocation } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { SettingsTabs } from '@/store/global/initialState';
import { isModifierClick } from '@/utils/navigation';
@@ -12,7 +13,7 @@ import { SettingsGroupKey, useCategory } from '../../hooks/useCategory';
const Body = memo(() => {
const categoryGroups = useCategory();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const location = useLocation();
// Extract current tab from pathname: /settings/profile -> profile
@@ -54,7 +55,7 @@ const Body = memo(() => {
>
<Flexbox gap={1} paddingBlock={1}>
{group.items.map((item) => {
- const url = getTabUrl(item.key);
+ const url = item.href ?? getTabUrl(item.key);
return (
<Link
key={item.key}
diff --git a/src/routes/(main)/settings/_layout/Header.tsx b/src/routes/(main)/settings/_layout/Header.tsx
index 3c33366e8dd..09a357f2ab3 100644
--- a/src/routes/(main)/settings/_layout/Header.tsx
+++ b/src/routes/(main)/settings/_layout/Header.tsx
@@ -8,6 +8,7 @@ import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
const Header = memo<PropsWithChildren>(() => {
const { t } = useTranslation('common');
+
return (
<SideBarHeaderLayout
breadcrumb={[
diff --git a/src/routes/(main)/settings/apikey/features/ApiKey.tsx b/src/routes/(main)/settings/apikey/features/ApiKey.tsx
index 1928953e350..ae63cac4824 100644
--- a/src/routes/(main)/settings/apikey/features/ApiKey.tsx
+++ b/src/routes/(main)/settings/apikey/features/ApiKey.tsx
@@ -11,6 +11,7 @@ import { type FC } from 'react';
import { useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaClient } from '@/libs/trpc/client';
import { type ApiKeyItem, type CreateApiKeyParams, type UpdateApiKeyParams } from '@/types/apiKey';
@@ -39,6 +40,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const ApiKey: FC = () => {
const { t } = useTranslation('auth');
+ const { allowed: canEdit, reason } = usePermission('create_content');
const actionRef = useRef<ActionType>(null);
@@ -65,6 +67,7 @@ const ApiKey: FC = () => {
});
const handleCreate = () => {
+ if (!canEdit) return;
createApiKeyModal({
onSubmit: async (values) => {
await createMutation.mutateAsync(values);
@@ -78,10 +81,12 @@ const ApiKey: FC = () => {
key: 'name',
render: (_, apiKey) => (
<EditableCell
+ disabled={!canEdit}
placeholder={t('apikey.display.enterPlaceholder')}
type="text"
value={apiKey.name}
onSubmit={(name) => {
+ if (!canEdit) return;
if (!name || name === apiKey.name) {
return;
}
@@ -106,7 +111,9 @@ const ApiKey: FC = () => {
render: (_, apiKey: ApiKeyItem) => (
<Switch
checked={!!apiKey.enabled}
+ disabled={!canEdit}
onChange={(checked) => {
+ if (!canEdit) return;
updateMutation.mutate({ id: apiKey.id!, params: { enabled: checked } });
}}
/>
@@ -119,10 +126,12 @@ const ApiKey: FC = () => {
key: 'expiresAt',
render: (_, apiKey) => (
<EditableCell
+ disabled={!canEdit}
placeholder={t('apikey.display.neverExpires')}
type="date"
value={apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires')}
onSubmit={(expiresAt) => {
+ if (!canEdit) return;
if (expiresAt === apiKey.expiresAt) {
return;
}
@@ -150,15 +159,20 @@ const ApiKey: FC = () => {
<Popconfirm
cancelText={t('apikey.list.actions.deleteConfirm.actions.cancel')}
description={t('apikey.list.actions.deleteConfirm.content')}
+ okButtonProps={{ disabled: !canEdit }}
okText={t('apikey.list.actions.deleteConfirm.actions.ok')}
title={t('apikey.list.actions.deleteConfirm.title')}
- onConfirm={() => deleteMutation.mutate(apiKey.id!)}
+ onConfirm={() => {
+ if (!canEdit) return;
+ deleteMutation.mutate(apiKey.id!);
+ }}
>
<Button
+ disabled={!canEdit}
icon={Trash}
size="small"
style={{ verticalAlign: 'middle' }}
- title={t('apikey.list.actions.delete')}
+ title={canEdit ? t('apikey.list.actions.delete') : reason}
type="text"
/>
</Popconfirm>
@@ -189,7 +203,13 @@ const ApiKey: FC = () => {
}}
toolbar={{
actions: [
- <Button key="create" type="primary" onClick={handleCreate}>
+ <Button
+ disabled={!canEdit}
+ key="create"
+ title={reason}
+ type="primary"
+ onClick={handleCreate}
+ >
{t('apikey.list.actions.create')}
</Button>,
],
diff --git a/src/routes/(main)/settings/creds/features/CreateCredModal/CredTypeSelector.tsx b/src/routes/(main)/settings/creds/features/CreateCredModal/CredTypeSelector.tsx
index ae52ca0d617..d8ccdca826f 100644
--- a/src/routes/(main)/settings/creds/features/CreateCredModal/CredTypeSelector.tsx
+++ b/src/routes/(main)/settings/creds/features/CreateCredModal/CredTypeSelector.tsx
@@ -18,6 +18,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}
`,
+ cardDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+ `,
description: css`
font-size: 12px;
color: ${cssVar.colorTextSecondary};
@@ -46,6 +50,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface CredTypeSelectorProps {
+ disabled?: boolean;
onSelect: (type: CredType) => void;
}
@@ -76,13 +81,21 @@ const typeConfigs: Array<{
},
];
-const CredTypeSelector: FC<CredTypeSelectorProps> = ({ onSelect }) => {
+const CredTypeSelector: FC<CredTypeSelectorProps> = ({ disabled, onSelect }) => {
const { t } = useTranslation('setting');
return (
<div className={styles.grid}>
{typeConfigs.map(({ type, icon, description }) => (
- <Card className={styles.card} key={type} size="small" onClick={() => onSelect(type)}>
+ <Card
+ className={`${styles.card} ${disabled ? styles.cardDisabled : ''}`}
+ key={type}
+ size="small"
+ onClick={() => {
+ if (disabled) return;
+ onSelect(type);
+ }}
+ >
<Flexbox align="center">
<div className={styles.icon}>{icon}</div>
<div className={styles.title}>{t(`creds.types.${type}`)}</div>
diff --git a/src/routes/(main)/settings/creds/features/CreateCredModal/FileCredForm.tsx b/src/routes/(main)/settings/creds/features/CreateCredModal/FileCredForm.tsx
index 39c1db0b9a3..33e3f8af0af 100644
--- a/src/routes/(main)/settings/creds/features/CreateCredModal/FileCredForm.tsx
+++ b/src/routes/(main)/settings/creds/features/CreateCredModal/FileCredForm.tsx
@@ -8,7 +8,7 @@ import { createStaticStyles } from 'antd-style';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient } from '@/libs/trpc/client';
+import { useCredsApi } from '../useCredsApi';
const styles = createStaticStyles(({ css }) => ({
footer: css`
@@ -20,6 +20,7 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface FileCredFormProps {
+ disabled?: boolean;
onBack: () => void;
onSuccess: () => void;
}
@@ -30,20 +31,23 @@ interface FormValues {
name: string;
}
-const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
+const FileCredForm: FC<FileCredFormProps> = ({ disabled, onBack, onSuccess }) => {
const { t } = useTranslation('setting');
const [form] = Form.useForm<FormValues>();
const [fileHashId, setFileHashId] = useState<string | null>(null);
const [fileName, setFileName] = useState<string>('');
const [isUploading, setIsUploading] = useState(false);
+ const credsApi = useCredsApi();
const createMutation = useMutation({
- mutationFn: (values: FormValues) => {
+ mutationFn: async (values: FormValues) => {
+ if (disabled) return;
+
if (!fileHashId || !fileName) {
throw new Error('File is required');
}
- return lambdaClient.market.creds.createFile.mutate({
+ await credsApi.client.createFile.mutate({
description: values.description,
fileHashId,
fileName,
@@ -57,6 +61,8 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
});
const handleUpload = async (file: File) => {
+ if (disabled) return false;
+
setIsUploading(true);
try {
@@ -69,8 +75,8 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
}
const base64 = btoa(binary);
- // Upload via TRPC
- const result = await lambdaClient.market.creds.uploadFile.mutate({
+ // Upload via TRPC (personal or workspace, based on active CredsApi context)
+ const result = await credsApi.client.uploadFile.mutate({
file: base64,
fileName: file.name,
fileType: file.type || 'application/octet-stream',
@@ -90,6 +96,8 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
};
const handleSubmit = (values: FormValues) => {
+ if (disabled) return;
+
if (!fileHashId) {
message.error(t('creds.form.fileRequired'));
return;
@@ -102,7 +110,7 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
<Form.Item required label={t('creds.form.file')}>
<Upload.Dragger
beforeUpload={handleUpload}
- disabled={isUploading}
+ disabled={isUploading || disabled}
maxCount={1}
showUploadList={fileName ? { showRemoveIcon: true } : false}
onRemove={() => {
@@ -133,7 +141,7 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
{ pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
]}
>
- <Input placeholder="e.g., gcp-service-account" />
+ <Input disabled={disabled} placeholder="e.g., gcp-service-account" />
</Form.Item>
<Form.Item
@@ -141,17 +149,21 @@ const FileCredForm: FC<FileCredFormProps> = ({ onBack, onSuccess }) => {
name="name"
rules={[{ required: true, message: t('creds.form.nameRequired') }]}
>
- <Input placeholder="e.g., GCP Service Account" />
+ <Input disabled={disabled} placeholder="e.g., GCP Service Account" />
</Form.Item>
<Form.Item label={t('creds.form.description')} name="description">
- <Input.TextArea placeholder={t('creds.form.descriptionPlaceholder')} rows={2} />
+ <Input.TextArea
+ disabled={disabled}
+ placeholder={t('creds.form.descriptionPlaceholder')}
+ rows={2}
+ />
</Form.Item>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
<Button
- disabled={!fileHashId}
+ disabled={!fileHashId || disabled}
htmlType="submit"
loading={createMutation.isPending}
type="primary"
diff --git a/src/routes/(main)/settings/creds/features/CreateCredModal/KVCredForm.tsx b/src/routes/(main)/settings/creds/features/CreateCredModal/KVCredForm.tsx
index a884cd55b30..df14d0467a8 100644
--- a/src/routes/(main)/settings/creds/features/CreateCredModal/KVCredForm.tsx
+++ b/src/routes/(main)/settings/creds/features/CreateCredModal/KVCredForm.tsx
@@ -8,7 +8,7 @@ import { Minus, Plus } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient } from '@/libs/trpc/client';
+import { useCredsApi } from '../useCredsApi';
const styles = createStaticStyles(({ css }) => ({
footer: css`
@@ -25,6 +25,7 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface KVCredFormProps {
+ disabled?: boolean;
onBack: () => void;
onSuccess: () => void;
type: 'kv-env' | 'kv-header';
@@ -37,12 +38,15 @@ interface FormValues {
name: string;
}
-const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
+const KVCredForm: FC<KVCredFormProps> = ({ type, disabled, onBack, onSuccess }) => {
const { t } = useTranslation('setting');
const [form] = Form.useForm<FormValues>();
+ const credsApi = useCredsApi();
const createMutation = useMutation({
- mutationFn: (values: FormValues) => {
+ mutationFn: async (values: FormValues) => {
+ if (disabled) return;
+
const kvPairs = values.kvPairs || [];
const valuesObj = kvPairs.reduce(
(acc, pair) => {
@@ -54,7 +58,7 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
{} as Record<string, string>,
);
- return lambdaClient.market.creds.createKV.mutate({
+ await credsApi.client.createKV.mutate({
description: values.description,
key: values.key,
name: values.name,
@@ -68,6 +72,8 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
});
const handleSubmit = (values: FormValues) => {
+ if (disabled) return;
+
createMutation.mutate(values);
};
@@ -86,7 +92,7 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
{ pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
]}
>
- <Input placeholder="e.g., openai" />
+ <Input disabled={disabled} placeholder="e.g., openai" />
</Form.Item>
<Form.Item
@@ -94,7 +100,7 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
name="name"
rules={[{ required: true, message: t('creds.form.nameRequired') }]}
>
- <Input placeholder="e.g., OpenAI API Key" />
+ <Input disabled={disabled} placeholder="e.g., OpenAI API Key" />
</Form.Item>
<Form.Item label={t('creds.form.values')}>
@@ -108,21 +114,39 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
name={[name, 'key']}
style={{ flex: 1, marginBottom: 0 }}
>
- <Input placeholder={type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'} />
+ <Input
+ disabled={disabled}
+ placeholder={type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
+ />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'value']}
style={{ flex: 2, marginBottom: 0 }}
>
- <Input.Password placeholder={t('creds.form.valuePlaceholder')} />
+ <Input.Password
+ disabled={disabled}
+ placeholder={t('creds.form.valuePlaceholder')}
+ />
</Form.Item>
{fields.length > 1 && (
- <Button icon={Minus} size="small" type="text" onClick={() => remove(name)} />
+ <Button
+ disabled={disabled}
+ icon={Minus}
+ size="small"
+ type="text"
+ onClick={() => remove(name)}
+ />
)}
</div>
))}
- <Button block icon={Plus} type="dashed" onClick={() => add({ key: '', value: '' })}>
+ <Button
+ block
+ disabled={disabled}
+ icon={Plus}
+ type="dashed"
+ onClick={() => add({ key: '', value: '' })}
+ >
{t('creds.form.addPair')}
</Button>
</Flexbox>
@@ -131,12 +155,21 @@ const KVCredForm: FC<KVCredFormProps> = ({ type, onBack, onSuccess }) => {
</Form.Item>
<Form.Item label={t('creds.form.description')} name="description">
- <Input.TextArea placeholder={t('creds.form.descriptionPlaceholder')} rows={2} />
+ <Input.TextArea
+ disabled={disabled}
+ placeholder={t('creds.form.descriptionPlaceholder')}
+ rows={2}
+ />
</Form.Item>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
- <Button htmlType="submit" loading={createMutation.isPending} type="primary">
+ <Button
+ disabled={disabled}
+ htmlType="submit"
+ loading={createMutation.isPending}
+ type="primary"
+ >
{t('creds.form.submit')}
</Button>
</div>
diff --git a/src/routes/(main)/settings/creds/features/CreateCredModal/OAuthCredForm.tsx b/src/routes/(main)/settings/creds/features/CreateCredModal/OAuthCredForm.tsx
index 64563b39bd9..21997b33ef7 100644
--- a/src/routes/(main)/settings/creds/features/CreateCredModal/OAuthCredForm.tsx
+++ b/src/routes/(main)/settings/creds/features/CreateCredModal/OAuthCredForm.tsx
@@ -7,7 +7,7 @@ import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';
+import { useCredsApi } from '../useCredsApi';
const styles = createStaticStyles(({ css, cssVar }) => ({
connectionOption: css`
@@ -30,6 +30,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface OAuthCredFormProps {
+ disabled?: boolean;
onBack: () => void;
onSuccess: () => void;
}
@@ -41,18 +42,20 @@ interface FormValues {
oauthConnectionId: number;
}
-const OAuthCredForm: FC<OAuthCredFormProps> = ({ onBack, onSuccess }) => {
+const OAuthCredForm: FC<OAuthCredFormProps> = ({ disabled, onBack, onSuccess }) => {
const { t } = useTranslation('setting');
const [form] = Form.useForm<FormValues>();
+ const credsApi = useCredsApi();
- const { data: connectionsData, isLoading } =
- lambdaQuery.market.creds.listOAuthConnections.useQuery();
+ const { data: connectionsData, isLoading } = credsApi.query.listOAuthConnections.useQuery();
const connections = connectionsData?.connections ?? [];
const createMutation = useMutation({
- mutationFn: (values: FormValues) => {
- return lambdaClient.market.creds.createOAuth.mutate({
+ mutationFn: async (values: FormValues) => {
+ if (disabled) return;
+
+ await credsApi.client.createOAuth.mutate({
description: values.description,
key: values.key,
name: values.name,
@@ -65,6 +68,8 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ onBack, onSuccess }) => {
});
const handleSubmit = (values: FormValues) => {
+ if (disabled) return;
+
createMutation.mutate(values);
};
@@ -94,7 +99,7 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ onBack, onSuccess }) => {
name="oauthConnectionId"
rules={[{ required: true, message: t('creds.form.connectionRequired') }]}
>
- <Select placeholder={t('creds.form.selectConnectionPlaceholder')}>
+ <Select disabled={disabled} placeholder={t('creds.form.selectConnectionPlaceholder')}>
{connections.map((conn: any) => {
const provider = conn.providerId || 'OAuth';
const displayName =
@@ -122,7 +127,7 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ onBack, onSuccess }) => {
{ pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
]}
>
- <Input placeholder="e.g., github-oauth" />
+ <Input disabled={disabled} placeholder="e.g., github-oauth" />
</Form.Item>
<Form.Item
@@ -130,16 +135,25 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ onBack, onSuccess }) => {
name="name"
rules={[{ required: true, message: t('creds.form.nameRequired') }]}
>
- <Input placeholder="e.g., GitHub Connection" />
+ <Input disabled={disabled} placeholder="e.g., GitHub Connection" />
</Form.Item>
<Form.Item label={t('creds.form.description')} name="description">
- <Input.TextArea placeholder={t('creds.form.descriptionPlaceholder')} rows={2} />
+ <Input.TextArea
+ disabled={disabled}
+ placeholder={t('creds.form.descriptionPlaceholder')}
+ rows={2}
+ />
</Form.Item>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
- <Button htmlType="submit" loading={createMutation.isPending} type="primary">
+ <Button
+ disabled={disabled}
+ htmlType="submit"
+ loading={createMutation.isPending}
+ type="primary"
+ >
{t('creds.form.submit')}
</Button>
</div>
diff --git a/src/routes/(main)/settings/creds/features/CredItem.tsx b/src/routes/(main)/settings/creds/features/CredItem.tsx
index 34ee97856e5..b95e805d1bf 100644
--- a/src/routes/(main)/settings/creds/features/CredItem.tsx
+++ b/src/routes/(main)/settings/creds/features/CredItem.tsx
@@ -17,6 +17,8 @@ import {
import { type FC, memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
+
import { styles } from './style';
interface CredItemProps {
@@ -42,8 +44,11 @@ const typeColors: Record<string, string> = {
const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) => {
const { t } = useTranslation('setting');
+ const { allowed: canManageCredentials } = usePermission('manage_provider_key');
const handleDelete = () => {
+ if (!canManageCredentials) return;
+
confirmModal({
content: t('creds.actions.deleteConfirm.content'),
okButtonProps: { danger: true },
@@ -53,7 +58,7 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) =>
});
};
- const canView = cred.type === 'kv-env' || cred.type === 'kv-header';
+ const canView = canManageCredentials && (cred.type === 'kv-env' || cred.type === 'kv-header');
const menuItems = [
...(canView
@@ -70,10 +75,12 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) =>
icon: <Icon icon={Pencil} />,
key: 'edit',
label: t('creds.actions.edit'),
+ disabled: !canManageCredentials,
onClick: () => onEdit(cred),
},
{
danger: true,
+ disabled: !canManageCredentials,
icon: <Icon icon={Trash2} />,
key: 'delete',
label: t('creds.actions.delete'),
@@ -118,7 +125,7 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) =>
</Flexbox>
<Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>
<DropdownMenu items={menuItems} placement="bottomRight">
- <Button icon={MoreHorizontalIcon} />
+ <Button disabled={!canManageCredentials} icon={MoreHorizontalIcon} />
</DropdownMenu>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/settings/creds/features/CredsList.tsx b/src/routes/(main)/settings/creds/features/CredsList.tsx
index fd146ce7323..2113a4457bd 100644
--- a/src/routes/(main)/settings/creds/features/CredsList.tsx
+++ b/src/routes/(main)/settings/creds/features/CredsList.tsx
@@ -9,11 +9,12 @@ import { LogIn } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';
import CredItem from './CredItem';
import { createEditCredModal } from './EditCredModal';
+import { useCredsApi } from './useCredsApi';
import { createViewCredModal } from './ViewCredModal';
const styles = createStaticStyles(({ css }) => ({
@@ -40,13 +41,18 @@ const styles = createStaticStyles(({ css }) => ({
const CredsList: FC = () => {
const { t } = useTranslation('setting');
const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
+ const { allowed: canManageCredentials } = usePermission('manage_provider_key');
+ const credsApi = useCredsApi();
- const { data, isLoading, refetch } = lambdaQuery.market.creds.list.useQuery(undefined, {
+ const { data, isLoading, refetch } = credsApi.query.list.useQuery(undefined, {
enabled: isAuthenticated,
});
const deleteMutation = useMutation({
- mutationFn: (id: number) => lambdaClient.market.creds.delete.mutate({ id }),
+ mutationFn: async (id: number) => {
+ if (!canManageCredentials) return;
+ await credsApi.client.delete.mutate({ id });
+ },
onSuccess: () => {
refetch();
},
@@ -99,8 +105,11 @@ const CredsList: FC = () => {
cred={cred}
key={cred.id}
onDelete={(id) => deleteMutation.mutate(id)}
- onEdit={handleEdit}
onView={handleView}
+ onEdit={(cred) => {
+ if (!canManageCredentials) return;
+ handleEdit(cred);
+ }}
/>
))}
</Flexbox>
diff --git a/src/routes/(main)/settings/creds/features/EditCredModal/EditKVForm.tsx b/src/routes/(main)/settings/creds/features/EditCredModal/EditKVForm.tsx
index 59c96b528b5..a24b1c58f72 100644
--- a/src/routes/(main)/settings/creds/features/EditCredModal/EditKVForm.tsx
+++ b/src/routes/(main)/settings/creds/features/EditCredModal/EditKVForm.tsx
@@ -9,7 +9,9 @@ import { Minus, Plus } from 'lucide-react';
import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient } from '@/libs/trpc/client';
+import { usePermission } from '@/hooks/usePermission';
+
+import { useCredsApi } from '../useCredsApi';
const styles = createStaticStyles(({ css }) => ({
footer: css`
@@ -39,14 +41,21 @@ interface FormValues {
const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
const { t } = useTranslation('setting');
+ const { allowed: canManageCredentials } = usePermission('manage_provider_key');
const [form] = Form.useForm<FormValues>();
const [isLoading, setIsLoading] = useState(true);
+ const credsApi = useCredsApi();
// Fetch decrypted values on mount
useEffect(() => {
const fetchDecryptedValues = async () => {
+ if (!canManageCredentials) {
+ setIsLoading(false);
+ return;
+ }
+
try {
- const result = await lambdaClient.market.creds.get.query({
+ const result = await credsApi.client.get.query({
decrypt: true,
id: cred.id,
});
@@ -76,10 +85,12 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
};
fetchDecryptedValues();
- }, [cred.id, cred.name, cred.description, form]);
+ }, [canManageCredentials, cred.id, cred.name, cred.description, credsApi, form]);
const updateMutation = useMutation({
- mutationFn: (values: FormValues) => {
+ mutationFn: async (values: FormValues) => {
+ if (!canManageCredentials) return;
+
const kvPairs = values.kvPairs || [];
const valuesObj = kvPairs.reduce(
(acc, pair) => {
@@ -91,7 +102,7 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
{} as Record<string, string>,
);
- return lambdaClient.market.creds.update.mutate({
+ await credsApi.client.update.mutate({
description: values.description,
id: cred.id,
name: values.name,
@@ -104,6 +115,8 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
});
const handleSubmit = (values: FormValues) => {
+ if (!canManageCredentials) return;
+
updateMutation.mutate(values);
};
@@ -122,7 +135,7 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
name="name"
rules={[{ required: true, message: t('creds.form.nameRequired') }]}
>
- <Input />
+ <Input disabled={!canManageCredentials} />
</Form.Item>
<Form.Item label={t('creds.form.values')}>
@@ -136,21 +149,39 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
name={[name, 'key']}
style={{ flex: 1, marginBottom: 0 }}
>
- <Input placeholder={cred.type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'} />
+ <Input
+ disabled={!canManageCredentials}
+ placeholder={cred.type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
+ />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'value']}
style={{ flex: 2, marginBottom: 0 }}
>
- <Input.Password placeholder={t('creds.form.valuePlaceholder')} />
+ <Input.Password
+ disabled={!canManageCredentials}
+ placeholder={t('creds.form.valuePlaceholder')}
+ />
</Form.Item>
{fields.length > 1 && (
- <Button icon={Minus} size="small" type="text" onClick={() => remove(name)} />
+ <Button
+ disabled={!canManageCredentials}
+ icon={Minus}
+ size="small"
+ type="text"
+ onClick={() => remove(name)}
+ />
)}
</div>
))}
- <Button block icon={Plus} type="dashed" onClick={() => add({ key: '', value: '' })}>
+ <Button
+ block
+ disabled={!canManageCredentials}
+ icon={Plus}
+ type="dashed"
+ onClick={() => add({ key: '', value: '' })}
+ >
{t('creds.form.addPair')}
</Button>
</Flexbox>
@@ -159,12 +190,21 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, onCancel, onSuccess }) => {
</Form.Item>
<Form.Item label={t('creds.form.description')} name="description">
- <Input.TextArea placeholder={t('creds.form.descriptionPlaceholder')} rows={2} />
+ <Input.TextArea
+ disabled={!canManageCredentials}
+ placeholder={t('creds.form.descriptionPlaceholder')}
+ rows={2}
+ />
</Form.Item>
<div className={styles.footer}>
<Button onClick={onCancel}>{t('creds.form.cancel')}</Button>
- <Button htmlType="submit" loading={updateMutation.isPending} type="primary">
+ <Button
+ disabled={!canManageCredentials}
+ htmlType="submit"
+ loading={updateMutation.isPending}
+ type="primary"
+ >
{t('creds.form.save')}
</Button>
</div>
diff --git a/src/routes/(main)/settings/creds/features/EditCredModal/EditMetaForm.tsx b/src/routes/(main)/settings/creds/features/EditCredModal/EditMetaForm.tsx
index 54cd711200b..a57d8c45b40 100644
--- a/src/routes/(main)/settings/creds/features/EditCredModal/EditMetaForm.tsx
+++ b/src/routes/(main)/settings/creds/features/EditCredModal/EditMetaForm.tsx
@@ -8,7 +8,9 @@ import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient } from '@/libs/trpc/client';
+import { usePermission } from '@/hooks/usePermission';
+
+import { useCredsApi } from '../useCredsApi';
const styles = createStaticStyles(({ css }) => ({
footer: css`
@@ -32,11 +34,15 @@ interface FormValues {
const EditMetaForm: FC<EditMetaFormProps> = ({ cred, onCancel, onSuccess }) => {
const { t } = useTranslation('setting');
+ const { allowed: canManageCredentials } = usePermission('manage_provider_key');
const [form] = Form.useForm<FormValues>();
+ const credsApi = useCredsApi();
const updateMutation = useMutation({
- mutationFn: (values: FormValues) => {
- return lambdaClient.market.creds.update.mutate({
+ mutationFn: async (values: FormValues) => {
+ if (!canManageCredentials) return;
+
+ await credsApi.client.update.mutate({
description: values.description,
id: cred.id,
name: values.name,
@@ -48,6 +54,8 @@ const EditMetaForm: FC<EditMetaFormProps> = ({ cred, onCancel, onSuccess }) => {
});
const handleSubmit = (values: FormValues) => {
+ if (!canManageCredentials) return;
+
updateMutation.mutate(values);
};
@@ -66,16 +74,25 @@ const EditMetaForm: FC<EditMetaFormProps> = ({ cred, onCancel, onSuccess }) => {
name="name"
rules={[{ required: true, message: t('creds.form.nameRequired') }]}
>
- <Input />
+ <Input disabled={!canManageCredentials} />
</Form.Item>
<Form.Item label={t('creds.form.description')} name="description">
- <Input.TextArea placeholder={t('creds.form.descriptionPlaceholder')} rows={2} />
+ <Input.TextArea
+ disabled={!canManageCredentials}
+ placeholder={t('creds.form.descriptionPlaceholder')}
+ rows={2}
+ />
</Form.Item>
<div className={styles.footer}>
<Button onClick={onCancel}>{t('creds.form.cancel')}</Button>
- <Button htmlType="submit" loading={updateMutation.isPending} type="primary">
+ <Button
+ disabled={!canManageCredentials}
+ htmlType="submit"
+ loading={updateMutation.isPending}
+ type="primary"
+ >
{t('creds.form.save')}
</Button>
</div>
diff --git a/src/routes/(main)/settings/creds/features/ViewCredModal/Content.tsx b/src/routes/(main)/settings/creds/features/ViewCredModal/Content.tsx
index 79479d6ce9a..468b6ba95a6 100644
--- a/src/routes/(main)/settings/creds/features/ViewCredModal/Content.tsx
+++ b/src/routes/(main)/settings/creds/features/ViewCredModal/Content.tsx
@@ -9,7 +9,7 @@ import { Eye, EyeOff } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaClient } from '@/libs/trpc/client';
+import { useCredsApi } from '../useCredsApi';
const { Text } = Typography;
@@ -129,10 +129,11 @@ export interface ViewCredModalContentProps {
const ViewCredModalContent: FC<ViewCredModalContentProps> = ({ cred }) => {
const { t } = useTranslation('setting');
+ const credsApi = useCredsApi();
const { data, isLoading, error } = useQuery({
queryFn: () =>
- lambdaClient.market.creds.get.query({
+ credsApi.client.get.query({
decrypt: true,
id: cred.id,
}),
diff --git a/src/routes/(main)/settings/creds/features/useCredsApi.ts b/src/routes/(main)/settings/creds/features/useCredsApi.ts
new file mode 100644
index 00000000000..eb85fb90196
--- /dev/null
+++ b/src/routes/(main)/settings/creds/features/useCredsApi.ts
@@ -0,0 +1,33 @@
+'use client';
+
+import { createContext, useContext } from 'react';
+
+import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';
+
+/**
+ * Personal vs workspace creds API binding.
+ *
+ * The personal page (`/settings/creds`) and the workspace page
+ * (`/[workspaceSlug]/settings/creds`) share UI components but talk to
+ * different tRPC routers — `market.creds` (Market user account) versus
+ * `workspaceCreds` (Market organization mirroring the cloud workspace).
+ *
+ * The workspace shell wraps the page in {@link CredsApiProvider} with the
+ * workspace bindings. Forms/modals read whichever client/query namespace is
+ * active via {@link useCredsApi} and otherwise behave identically.
+ */
+export interface CredsApi {
+ client: typeof lambdaClient.market.creds;
+ query: typeof lambdaQuery.market.creds;
+}
+
+const defaultCredsApi: CredsApi = {
+ client: lambdaClient.market.creds,
+ query: lambdaQuery.market.creds,
+};
+
+const CredsApiContext = createContext<CredsApi | null>(null);
+
+export const CredsApiProvider = CredsApiContext.Provider;
+
+export const useCredsApi = (): CredsApi => useContext(CredsApiContext) ?? defaultCredsApi;
diff --git a/src/routes/(main)/settings/creds/index.tsx b/src/routes/(main)/settings/creds/index.tsx
index 17df92ecbc2..ee27a9cb14b 100644
--- a/src/routes/(main)/settings/creds/index.tsx
+++ b/src/routes/(main)/settings/creds/index.tsx
@@ -1,10 +1,11 @@
'use client';
-import { Button, Icon } from '@lobehub/ui';
+import { Button, Icon, Tooltip } from '@lobehub/ui';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';
import { createCreateCredModal } from './features/CreateCredModal';
@@ -12,9 +13,11 @@ import CredsList from './features/CredsList';
const Page = () => {
const { t } = useTranslation('setting');
+ const { allowed: canManageCredentials, reason } = usePermission('manage_provider_key');
const [refreshKey, setRefreshKey] = useState(0);
const handleCreate = () => {
+ if (!canManageCredentials) return;
createCreateCredModal({
onSuccess: () => setRefreshKey((k) => k + 1),
});
@@ -25,9 +28,16 @@ const Page = () => {
<SettingHeader
title={t('tab.creds')}
extra={
- <Button icon={<Icon icon={Plus} />} size={'large'} onClick={handleCreate}>
- {t('creds.create')}
- </Button>
+ <Tooltip title={reason}>
+ <Button
+ disabled={!canManageCredentials}
+ icon={<Icon icon={Plus} />}
+ size={'large'}
+ onClick={handleCreate}
+ >
+ {t('creds.create')}
+ </Button>
+ </Tooltip>
}
/>
<CredsList key={refreshKey} />
diff --git a/src/routes/(main)/settings/features/SettingsContent.tsx b/src/routes/(main)/settings/features/SettingsContent.tsx
index 6cad3bfdbe7..bac7116c4ab 100644
--- a/src/routes/(main)/settings/features/SettingsContent.tsx
+++ b/src/routes/(main)/settings/features/SettingsContent.tsx
@@ -1,10 +1,10 @@
'use client';
import { Fragment, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
import NavHeader from '@/features/NavHeader';
import SettingContainer from '@/features/Setting/SettingContainer';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { SettingsTabs } from '@/store/global/initialState';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -25,11 +25,14 @@ interface SettingsContentProps {
const SettingsContent = ({ mobile, activeTab }: SettingsContentProps) => {
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
useEffect(() => {
if (activeTab && REDIRECT_MAP[activeTab]) {
- navigate(`/settings/${REDIRECT_MAP[activeTab]}`, { replace: true });
+ // Personal-only redirect: legacy URL aliases (common, agent, tts, image,
+ // chat-appearance) map to personal-settings tabs. `escape: true` keeps the
+ // user in personal context even when a workspace happens to be active.
+ navigate(`/settings/${REDIRECT_MAP[activeTab]}`, { escape: true, replace: true });
}
}, [activeTab, navigate]);
diff --git a/src/routes/(main)/settings/hooks/useCategory.tsx b/src/routes/(main)/settings/hooks/useCategory.tsx
index 403e98116b0..d739d4936a2 100644
--- a/src/routes/(main)/settings/hooks/useCategory.tsx
+++ b/src/routes/(main)/settings/hooks/useCategory.tsx
@@ -46,6 +46,8 @@ export enum SettingsGroupKey {
}
export interface CategoryItem {
+ /** Override the navigation URL. When omitted, Body derives the URL from `key`. */
+ href?: string;
icon: any;
key: SettingsTabs;
label: string;
@@ -121,7 +123,9 @@ export const useCategory = () => {
title: t('group.common'),
});
- // Subscription group
+ // Personal subscription / billing items. Always shown when business
+ // features are enabled — workspace settings live under a separate
+ // `/:workspaceSlug/settings/*` surface and never share this sidebar.
if (enableBusinessFeatures) {
const subscriptionItems: CategoryItem[] = [
{ icon: Map, key: SettingsTabs.Plans, label: tSubscription('tab.plans') },
diff --git a/src/routes/(main)/settings/image/features/Image.tsx b/src/routes/(main)/settings/image/features/Image.tsx
index 43cc5099094..9abc3aae3e2 100644
--- a/src/routes/(main)/settings/image/features/Image.tsx
+++ b/src/routes/(main)/settings/image/features/Image.tsx
@@ -2,7 +2,7 @@
import { type UserImageConfig } from '@lobechat/types';
import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon, Skeleton } from '@lobehub/ui';
+import { Form, Icon, Skeleton, Tooltip } from '@lobehub/ui';
import { Loader2Icon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,11 +10,13 @@ import { useTranslation } from 'react-i18next';
import { FormSliderWithInput } from '@/components/FormInput';
import { FORM_STYLE } from '@/const/layoutTokens';
import { MAX_DEFAULT_IMAGE_NUM, MIN_DEFAULT_IMAGE_NUM } from '@/const/settings';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/slices/settings/selectors';
const ImageSettings = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
const [form] = Form.useForm<UserImageConfig>();
const [isUpdating, setIsUpdating] = useState(false);
@@ -30,12 +32,14 @@ const ImageSettings = memo(() => {
children: [
{
children: (
- <FormSliderWithInput
- disabled={isUpdating}
- max={MAX_DEFAULT_IMAGE_NUM}
- min={MIN_DEFAULT_IMAGE_NUM}
- step={1}
- />
+ <Tooltip title={reason}>
+ <FormSliderWithInput
+ disabled={isUpdating || !canManageServiceModel}
+ max={MAX_DEFAULT_IMAGE_NUM}
+ min={MIN_DEFAULT_IMAGE_NUM}
+ step={1}
+ />
+ </Tooltip>
),
desc: t('settingImage.defaultCount.desc'),
label: t('settingImage.defaultCount.label'),
@@ -58,6 +62,8 @@ const ImageSettings = memo(() => {
itemsType={'group'}
variant={'filled'}
onValuesChange={async (values) => {
+ if (!canManageServiceModel) return;
+
setIsUpdating(true);
try {
await setSettings({ image: values });
diff --git a/src/routes/(main)/settings/index.tsx b/src/routes/(main)/settings/index.tsx
index 77e07f79019..bc7fea26294 100644
--- a/src/routes/(main)/settings/index.tsx
+++ b/src/routes/(main)/settings/index.tsx
@@ -1,17 +1,36 @@
'use client';
import { memo } from 'react';
-import { useParams } from 'react-router-dom';
+import { useMatches, useParams } from 'react-router-dom';
import { SettingsTabs } from '@/store/global/initialState';
import { type LayoutProps } from './_layout/type';
import SettingsContent from './features/SettingsContent';
+interface SettingsRouteHandle {
+ settingsTab?: SettingsTabs;
+}
+
+const isSettingsRouteHandle = (handle: unknown): handle is SettingsRouteHandle => {
+ return typeof handle === 'object' && handle !== null && 'settingsTab' in handle;
+};
+
+const getSettingsTabFromMatches = (matches: ReturnType<typeof useMatches>) => {
+ for (const match of [...matches].reverse()) {
+ const { handle } = match;
+ if (isSettingsRouteHandle(handle) && handle.settingsTab) return handle.settingsTab;
+ }
+};
+
const Layout = memo<LayoutProps>(() => {
const params = useParams<{ tab?: string }>();
+ const matches = useMatches();
- const activeTab = (params.tab as SettingsTabs) || SettingsTabs.Profile;
+ const activeTab =
+ (params.tab as SettingsTabs | undefined) ||
+ getSettingsTabFromMatches(matches) ||
+ SettingsTabs.Profile;
return <SettingsContent activeTab={activeTab} mobile={false} />;
});
diff --git a/src/routes/(main)/settings/memory/features/Memory.tsx b/src/routes/(main)/settings/memory/features/Memory.tsx
index a7a7b1a936a..54b489a21d9 100644
--- a/src/routes/(main)/settings/memory/features/Memory.tsx
+++ b/src/routes/(main)/settings/memory/features/Memory.tsx
@@ -2,7 +2,7 @@
import { type UserMemoryEffort } from '@lobechat/types';
import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon, Skeleton } from '@lobehub/ui';
+import { Form, Icon, Skeleton, Tooltip } from '@lobehub/ui';
import { Switch } from 'antd';
import isEqual from 'fast-deep-equal';
import { Loader2Icon } from 'lucide-react';
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
import LevelSlider from '@/features/ModelSwitchPanel/components/ControlsForm/LevelSlider';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -18,6 +19,7 @@ const MEMORY_EFFORT_LEVELS: readonly UserMemoryEffort[] = ['low', 'medium', 'hig
const MemorySetting = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canManageMemory, reason } = usePermission('manage_settings');
const [form] = Form.useForm();
const { memory } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
@@ -28,7 +30,11 @@ const MemorySetting = memo(() => {
const memorySettings: FormGroupItemType = {
children: [
{
- children: <Switch />,
+ children: (
+ <Tooltip title={reason}>
+ <Switch disabled={!canManageMemory} />
+ </Tooltip>
+ ),
desc: t('memory.enabled.desc'),
label: t('memory.enabled.title'),
layout: 'horizontal',
@@ -38,22 +44,27 @@ const MemorySetting = memo(() => {
},
{
children: (
- <LevelSlider<UserMemoryEffort>
- defaultValue="medium"
- levels={MEMORY_EFFORT_LEVELS}
- style={{ minWidth: 160 }}
- value={memory?.effort ?? 'medium'}
- marks={{
- 0: t('memory.effort.level.low'),
- 1: t('memory.effort.level.medium'),
- 2: t('memory.effort.level.high'),
- }}
- onChange={async (value) => {
- setLoading(true);
- await setSettings({ memory: { effort: value } });
- setLoading(false);
- }}
- />
+ <Tooltip title={reason}>
+ <LevelSlider<UserMemoryEffort>
+ defaultValue="medium"
+ disabled={!canManageMemory}
+ levels={MEMORY_EFFORT_LEVELS}
+ style={{ minWidth: 160 }}
+ value={memory?.effort ?? 'medium'}
+ marks={{
+ 0: t('memory.effort.level.low'),
+ 1: t('memory.effort.level.medium'),
+ 2: t('memory.effort.level.high'),
+ }}
+ onChange={async (value) => {
+ if (!canManageMemory) return;
+
+ setLoading(true);
+ await setSettings({ memory: { effort: value } });
+ setLoading(false);
+ }}
+ />
+ </Tooltip>
),
desc: t('memory.effort.desc'),
label: t('memory.effort.title'),
@@ -74,6 +85,8 @@ const MemorySetting = memo(() => {
itemsType={'group'}
variant={'filled'}
onValuesChange={async (values) => {
+ if (!canManageMemory) return;
+
setLoading(true);
await setSettings({ memory: values });
setLoading(false);
diff --git a/src/routes/(main)/settings/provider/(list)/ProviderGrid/EnableSwitch.tsx b/src/routes/(main)/settings/provider/(list)/ProviderGrid/EnableSwitch.tsx
index 5a96677283d..50f101341f4 100644
--- a/src/routes/(main)/settings/provider/(list)/ProviderGrid/EnableSwitch.tsx
+++ b/src/routes/(main)/settings/provider/(list)/ProviderGrid/EnableSwitch.tsx
@@ -1,6 +1,7 @@
import { type FC } from 'react';
import InstantSwitch from '@/components/InstantSwitch';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
interface SwitchProps {
@@ -10,6 +11,7 @@ interface SwitchProps {
}
const Switch = ({ id, Component, enabled }: SwitchProps) => {
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const [toggleProviderEnabled] = useAiInfraStore((s) => [s.toggleProviderEnabled]);
// slot for cloud
@@ -17,9 +19,11 @@ const Switch = ({ id, Component, enabled }: SwitchProps) => {
return (
<InstantSwitch
+ disabled={!canManageProvider}
enabled={enabled}
size={'small'}
onChange={async (checked) => {
+ if (!canManageProvider) return;
await toggleProviderEnabled(id, checked);
}}
/>
diff --git a/src/routes/(main)/settings/provider/ProviderMenu/AddNew.tsx b/src/routes/(main)/settings/provider/ProviderMenu/AddNew.tsx
index fe84b0237d9..389d661cc19 100644
--- a/src/routes/(main)/settings/provider/ProviderMenu/AddNew.tsx
+++ b/src/routes/(main)/settings/provider/ProviderMenu/AddNew.tsx
@@ -1,24 +1,32 @@
'use client';
-import { ActionIcon } from '@lobehub/ui';
+import { ActionIcon, Tooltip } from '@lobehub/ui';
import { PlusIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { usePermission } from '@/hooks/usePermission';
import { createCreateNewProviderModal } from '../features/CreateNewProvider';
const AddNewProvider = () => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
- return (
+ const button = (
<ActionIcon
+ disabled={!canManageProvider}
icon={PlusIcon}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={t('menu.addCustomProvider')}
- onClick={() => createCreateNewProviderModal()}
+ title={canManageProvider ? t('menu.addCustomProvider') : undefined}
+ onClick={() => {
+ if (!canManageProvider) return;
+ createCreateNewProviderModal();
+ }}
/>
);
+
+ return canManageProvider ? button : <Tooltip title={reason}>{button}</Tooltip>;
};
export default AddNewProvider;
diff --git a/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/GroupItem.tsx b/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/GroupItem.tsx
index 021cd3bcf67..8d303bf560a 100644
--- a/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/GroupItem.tsx
+++ b/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/GroupItem.tsx
@@ -4,7 +4,11 @@ import { memo } from 'react';
import { type AiProviderListItem } from '@/types/aiProvider';
-const GroupItem = memo<AiProviderListItem>(({ id, name, source, logo }) => {
+interface GroupItemProps extends AiProviderListItem {
+ disabled?: boolean;
+}
+
+const GroupItem = memo<GroupItemProps>(({ id, name, source, logo, disabled }) => {
return (
<>
<Flexbox horizontal gap={8}>
@@ -21,7 +25,7 @@ const GroupItem = memo<AiProviderListItem>(({ id, name, source, logo }) => {
)}
{name}
</Flexbox>
- <SortableList.DragHandle />
+ {!disabled && <SortableList.DragHandle />}
</>
);
});
diff --git a/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/index.tsx b/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/index.tsx
index 8abfb2014c6..c4b139ac289 100644
--- a/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/index.tsx
+++ b/src/routes/(main)/settings/provider/ProviderMenu/SortProviderModal/index.tsx
@@ -4,6 +4,7 @@ import { createStaticStyles } from 'antd-style';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import { type AiProviderListItem } from '@/types/aiProvider';
@@ -29,6 +30,7 @@ interface ConfigGroupModalProps {
}
const ConfigGroupModal = memo<ConfigGroupModalProps>(({ open, onCancel, defaultItems }) => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const updateAiProviderSort = useAiInfraStore((s) => s.updateAiProviderSort);
const [loading, setLoading] = useState(false);
const { message } = App.useApp();
@@ -55,19 +57,24 @@ const ConfigGroupModal = memo<ConfigGroupModalProps>(({ open, onCancel, defaultI
id={item.id}
justify={'space-between'}
>
- <GroupItem {...item} />
+ <GroupItem {...item} disabled={!canManageProvider} />
</SortableList.Item>
)}
onChange={async (items: AiProviderListItem[]) => {
+ if (!canManageProvider) return;
+
setItems(items);
}}
/>
<Button
block
+ disabled={!canManageProvider}
loading={loading}
style={{ bottom: 0, position: 'sticky' }}
type={'primary'}
onClick={async () => {
+ if (!canManageProvider) return;
+
const sortMap = items.map((item, index) => ({
id: item.id,
sort: index,
diff --git a/src/routes/(main)/settings/provider/features/CreateNewProvider/Content.tsx b/src/routes/(main)/settings/provider/features/CreateNewProvider/Content.tsx
index 98d226c0089..33ddefbe1b9 100644
--- a/src/routes/(main)/settings/provider/features/CreateNewProvider/Content.tsx
+++ b/src/routes/(main)/settings/provider/features/CreateNewProvider/Content.tsx
@@ -6,8 +6,8 @@ import { Select, useModalContext } from '@lobehub/ui/base-ui';
import { App, Form } from 'antd';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAiInfraStore } from '@/store/aiInfra/store';
import { type CreateAiProviderParams } from '@/types/aiProvider';
@@ -27,7 +27,7 @@ const CreateNewProviderContent = memo(() => {
const [loading, setLoading] = useState(false);
const createNewAiProvider = useAiInfraStore((s) => s.createNewAiProvider);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { close } = useModalContext();
const onFinish = async (values: CreateAiProviderParams) => {
diff --git a/src/routes/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx b/src/routes/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
index a579a545c77..f49371567dd 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
@@ -13,6 +13,7 @@ import { type ChatModelCard } from '@/types/llm';
import ExtendParamsSelect from './ExtendParamsSelect';
interface ModelConfigFormProps {
+ disabled?: boolean;
idEditable?: boolean;
initialValues?: ChatModelCard;
onFormInstanceReady: (instance: FormInstance) => void;
@@ -21,7 +22,7 @@ interface ModelConfigFormProps {
}
const ModelConfigForm = memo<ModelConfigFormProps>(
- ({ showDeployName, idEditable = true, onFormInstanceReady, initialValues }) => {
+ ({ showDeployName, idEditable = true, onFormInstanceReady, initialValues, disabled }) => {
const { t } = useTranslation('modelProvider');
const [formInstance] = Form.useForm();
@@ -67,6 +68,7 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
>
<Form
colon={false}
+ disabled={disabled}
form={formInstance}
initialValues={initialValues}
labelCol={{ span: 4 }}
@@ -80,7 +82,7 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
rules={[{ required: true }]}
>
<Input
- disabled={!idEditable}
+ disabled={disabled || !idEditable}
placeholder={t('providerModels.item.modelConfig.id.placeholder')}
/>
</Form.Item>
diff --git a/src/routes/(main)/settings/provider/features/ModelList/EmptyModels.tsx b/src/routes/(main)/settings/provider/features/ModelList/EmptyModels.tsx
index 2ae324efc5f..972b51d07d2 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/EmptyModels.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/EmptyModels.tsx
@@ -1,9 +1,10 @@
-import { Button, Center, Flexbox, Icon } from '@lobehub/ui';
+import { Button, Center, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { BrainIcon, LucideRefreshCcwDot, PlusIcon } from 'lucide-react';
import { memo, use, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import { createCreateNewModelModal } from './CreateNewModelModal';
@@ -47,6 +48,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const EmptyState = memo<{ provider: string }>(({ provider }) => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
const [fetchRemoteModelList] = useAiInfraStore((s) => [s.fetchRemoteModelList]);
@@ -64,32 +66,40 @@ const EmptyState = memo<{ provider: string }>(({ provider }) => {
</Flexbox>
<Flexbox horizontal gap={8}>
- <Button
- icon={PlusIcon}
- onClick={() => {
- createCreateNewModelModal({ showDeployName });
- }}
- >
- {t('providerModels.list.addNew')}
- </Button>
- <Button
- icon={<Icon icon={LucideRefreshCcwDot} />}
- loading={fetchRemoteModelsLoading}
- type={'primary'}
- onClick={async () => {
- setFetchRemoteModelsLoading(true);
- try {
- await fetchRemoteModelList(provider);
- } catch (e) {
- console.error(e);
- }
- setFetchRemoteModelsLoading(false);
- }}
- >
- {fetchRemoteModelsLoading
- ? t('providerModels.list.fetcher.fetching')
- : t('providerModels.list.fetcher.fetch')}
- </Button>
+ <Tooltip title={canManageProvider ? '' : reason}>
+ <Button
+ disabled={!canManageProvider}
+ icon={PlusIcon}
+ onClick={() => {
+ if (!canManageProvider) return;
+ createCreateNewModelModal({ showDeployName });
+ }}
+ >
+ {t('providerModels.list.addNew')}
+ </Button>
+ </Tooltip>
+ <Tooltip title={canManageProvider ? '' : reason}>
+ <Button
+ disabled={!canManageProvider}
+ icon={<Icon icon={LucideRefreshCcwDot} />}
+ loading={fetchRemoteModelsLoading}
+ type={'primary'}
+ onClick={async () => {
+ if (!canManageProvider) return;
+ setFetchRemoteModelsLoading(true);
+ try {
+ await fetchRemoteModelList(provider);
+ } catch (e) {
+ console.error(e);
+ }
+ setFetchRemoteModelsLoading(false);
+ }}
+ >
+ {fetchRemoteModelsLoading
+ ? t('providerModels.list.fetcher.fetching')
+ : t('providerModels.list.fetcher.fetch')}
+ </Button>
+ </Tooltip>
</Flexbox>
</Center>
);
diff --git a/src/routes/(main)/settings/provider/features/ModelList/EnabledModelList/index.tsx b/src/routes/(main)/settings/provider/features/ModelList/EnabledModelList/index.tsx
index 2924d8013ee..a9ceb7d86cd 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/EnabledModelList/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/EnabledModelList/index.tsx
@@ -4,6 +4,7 @@ import { ArrowDownUpIcon, ToggleLeft } from 'lucide-react';
import { use, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiModelSelectors } from '@/store/aiInfra/selectors';
@@ -18,6 +19,7 @@ interface EnabledModelListProps {
const EnabledModelList = ({ activeTab }: EnabledModelListProps) => {
const { t } = useTranslation('modelProvider');
const { modelEditable } = use(ProviderSettingsContext);
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
const enabledModels = useAiInfraStore(aiModelSelectors.enabledAiProviderModelList, isEqual);
const batchToggleAiModels = useAiInfraStore((s) => s.batchToggleAiModels);
@@ -51,11 +53,15 @@ const EnabledModelList = ({ activeTab }: EnabledModelListProps) => {
<Flexbox horizontal>
{togglableModels.length > 0 && (
<ActionIcon
+ disabled={!canManageProvider}
icon={ToggleLeft}
loading={batchLoading}
size={'small'}
- title={t('providerModels.list.enabledActions.disableAll')}
+ title={
+ canManageProvider ? t('providerModels.list.enabledActions.disableAll') : reason
+ }
onClick={async () => {
+ if (!canManageProvider) return;
setBatchLoading(true);
await batchToggleAiModels(
togglableModels.map((i) => i.id),
@@ -67,10 +73,12 @@ const EnabledModelList = ({ activeTab }: EnabledModelListProps) => {
)}
<ActionIcon
+ disabled={!canManageProvider}
icon={ArrowDownUpIcon}
size={'small'}
- title={t('providerModels.list.enabledActions.sort')}
+ title={canManageProvider ? t('providerModels.list.enabledActions.sort') : reason}
onClick={() => {
+ if (!canManageProvider) return;
setOpen(true);
}}
/>
diff --git a/src/routes/(main)/settings/provider/features/ModelList/ModelItem.tsx b/src/routes/(main)/settings/provider/features/ModelList/ModelItem.tsx
index 4f473ed7d7d..b276ba94a90 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/ModelItem.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/ModelItem.tsx
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import { ModelInfoTags } from '@/components/ModelSelect';
import NewModelBadge from '@/components/ModelSelect/NewModelBadge';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { formatPriceByCurrency } from '@/utils/format';
import {
@@ -81,6 +82,7 @@ const ModelItem = memo<ModelItemProps>(
}) => {
const { t } = useTranslation(['modelProvider', 'components', 'models', 'common']);
const { modelEditable, showDeployName } = use(ProviderSettingsContext);
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
const [activeAiProvider, isModelLoading, toggleModelEnabled, removeAiModel] = useAiInfraStore(
(s) => [
@@ -175,9 +177,11 @@ const ModelItem = memo<ModelItemProps>(
const EnableSwitch = canToggle ? (
<Switch
checked={checked}
+ disabled={!canManageProvider}
loading={isModelLoading}
size={'small'}
onChange={async (e) => {
+ if (!canManageProvider) return;
setChecked(e);
await toggleModelEnabled({ enabled: e, id, source, type });
}}
@@ -189,20 +193,24 @@ const ModelItem = memo<ModelItemProps>(
((style?: React.CSSProperties) => (
<Flexbox horizontal className={styles.config} style={style}>
<ActionIcon
+ disabled={!canManageProvider}
icon={LucidePencil}
size={'small'}
- title={t('providerModels.item.config')}
+ title={canManageProvider ? t('providerModels.item.config') : reason}
onClick={(e) => {
e.stopPropagation();
+ if (!canManageProvider) return;
createModelConfigModal({ id, showDeployName });
}}
/>
{source !== AiModelSourceEnum.Builtin && (
<ActionIcon
+ disabled={!canManageProvider}
icon={TrashIcon}
size={'small'}
- title={t('providerModels.item.delete.title')}
+ title={canManageProvider ? t('providerModels.item.delete.title') : reason}
onClick={() => {
+ if (!canManageProvider) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('providerModels.item.delete.confirm', {
diff --git a/src/routes/(main)/settings/provider/features/ModelList/ModelTitle/index.tsx b/src/routes/(main)/settings/provider/features/ModelList/ModelTitle/index.tsx
index cf070464d8e..4d460b756c3 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/ModelTitle/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/ModelTitle/index.tsx
@@ -1,4 +1,4 @@
-import { ActionIcon, Button, DropdownMenu, Flexbox, Skeleton, Text } from '@lobehub/ui';
+import { ActionIcon, Button, DropdownMenu, Flexbox, Skeleton, Text, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App, Space } from 'antd';
import { cssVar } from 'antd-style';
@@ -7,6 +7,7 @@ import { memo, use, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiModelSelectors } from '@/store/aiInfra/selectors';
@@ -24,6 +25,7 @@ const ModelTitle = memo<ModelFetcherProps>(
({ provider, showAddNewModel = true, showModelFetcher = true }) => {
const { t } = useTranslation('modelProvider');
const { message } = App.useApp();
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
const [
searchKeyword,
totalModels,
@@ -83,11 +85,13 @@ const ModelTitle = memo<ModelFetcherProps>(
{t('providerModels.list.total', { count: totalModels })}
{hasRemoteModels && (
<ActionIcon
+ disabled={!canManageProvider}
icon={CircleX}
loading={clearRemoteModelsLoading}
size={'small'}
- title={t('providerModels.list.fetcher.clear')}
+ title={canManageProvider ? t('providerModels.list.fetcher.clear') : undefined}
onClick={async () => {
+ if (!canManageProvider) return;
setClearRemoteModelsLoading(true);
await clearObtainedModels(provider);
setClearRemoteModelsLoading(false);
@@ -112,40 +116,50 @@ const ModelTitle = memo<ModelFetcherProps>(
)}
<Space.Compact>
{showModelFetcher && (
- <Button
- icon={LucideRefreshCcwDot}
- loading={fetchRemoteModelsLoading}
- size={'small'}
- onClick={async () => {
- setFetchRemoteModelsLoading(true);
- try {
- await fetchRemoteModelList(provider);
- } catch (e) {
- console.error(e);
- }
- setFetchRemoteModelsLoading(false);
- }}
- >
- {fetchRemoteModelsLoading
- ? t('providerModels.list.fetcher.fetching')
- : t('providerModels.list.fetcher.fetch')}
- </Button>
+ <Tooltip title={canManageProvider ? '' : reason}>
+ <Button
+ disabled={!canManageProvider}
+ icon={LucideRefreshCcwDot}
+ loading={fetchRemoteModelsLoading}
+ size={'small'}
+ onClick={async () => {
+ if (!canManageProvider) return;
+ setFetchRemoteModelsLoading(true);
+ try {
+ await fetchRemoteModelList(provider);
+ } catch (e) {
+ console.error(e);
+ }
+ setFetchRemoteModelsLoading(false);
+ }}
+ >
+ {fetchRemoteModelsLoading
+ ? t('providerModels.list.fetcher.fetching')
+ : t('providerModels.list.fetcher.fetch')}
+ </Button>
+ </Tooltip>
)}
{showAddNewModel && (
- <Button
- icon={PlusIcon}
- size={'small'}
- onClick={() => {
- createCreateNewModelModal({ showDeployName });
- }}
- />
+ <Tooltip title={canManageProvider ? '' : reason}>
+ <Button
+ disabled={!canManageProvider}
+ icon={PlusIcon}
+ size={'small'}
+ onClick={() => {
+ if (!canManageProvider) return;
+ createCreateNewModelModal({ showDeployName });
+ }}
+ />
+ </Tooltip>
)}
<DropdownMenu
items={[
{
+ disabled: !canManageProvider,
key: 'reset',
label: t('providerModels.list.resetAll.title'),
onClick: async () => {
+ if (!canManageProvider) return;
confirmModal({
content: t('providerModels.list.resetAll.conform'),
onOk: async () => {
diff --git a/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/ListItem.tsx b/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/ListItem.tsx
index 6b14ac5949f..993fb344b38 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/ListItem.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/ListItem.tsx
@@ -3,14 +3,18 @@ import { Flexbox, SortableList } from '@lobehub/ui';
import { type AiProviderModelListItem } from 'model-bank';
import { memo } from 'react';
-const ListItem = memo<AiProviderModelListItem>(({ id, displayName }) => {
+interface ListItemProps extends AiProviderModelListItem {
+ disabled?: boolean;
+}
+
+const ListItem = memo<ListItemProps>(({ id, displayName, disabled }) => {
return (
<>
<Flexbox horizontal gap={8}>
<ModelIcon model={id} size={24} type={'avatar'} />
{displayName || id}
</Flexbox>
- <SortableList.DragHandle />
+ {!disabled && <SortableList.DragHandle />}
</>
);
});
diff --git a/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/index.tsx b/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/index.tsx
index 5d5dfe51bf2..0f7181dae4b 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/SortModelModal/index.tsx
@@ -5,6 +5,7 @@ import { type AiProviderModelListItem } from 'model-bank';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useAiInfraStore } from '@/store/aiInfra';
import ListItem from './ListItem';
@@ -29,6 +30,7 @@ interface SortModelModalProps {
}
const SortModelModal = memo<SortModelModalProps>(({ open, onCancel, defaultItems }) => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const [providerId, updateAiModelsSort] = useAiInfraStore((s) => [
s.activeAiProvider,
s.updateAiModelsSort,
@@ -58,19 +60,23 @@ const SortModelModal = memo<SortModelModalProps>(({ open, onCancel, defaultItems
id={item.id}
justify={'space-between'}
>
- <ListItem {...item} />
+ <ListItem {...item} disabled={!canManageProvider} />
</SortableList.Item>
)}
onChange={async (items: AiProviderModelListItem[]) => {
+ if (!canManageProvider) return;
+
setItems(items);
}}
/>
<Button
block
+ disabled={!canManageProvider}
loading={loading}
style={{ bottom: 0, position: 'sticky' }}
type={'primary'}
onClick={async () => {
+ if (!canManageProvider) return;
if (!providerId) return;
const sortMap = items.map((item, index) => ({
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx
index 122abfc74c7..06657e15aee 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx
@@ -12,6 +12,7 @@ import { type ReactNode } from 'react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useProviderName } from '@/hooks/useProviderName';
import { chatService } from '@/services/chat';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -66,6 +67,7 @@ interface ConnectionCheckerProps {
const Checker = memo<ConnectionCheckerProps>(
({ model, provider, checkErrorRender: CheckErrorRender, onBeforeCheck, onAfterCheck }) => {
const { t } = useTranslation('setting');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const [isProviderConfigUpdating, updateAiProviderConfig] = useAiInfraStore((s) => [
aiProviderSelectors.isProviderConfigUpdating(provider)(s),
@@ -174,6 +176,7 @@ const Checker = memo<ConnectionCheckerProps>(
<Flexbox horizontal gap={8}>
<Select
virtual
+ disabled={!canManageProvider}
listItemHeight={36}
options={sortedModels.map((id) => ({ label: id, value: id }))}
popupClassName={cx(styles.popup)}
@@ -192,6 +195,8 @@ const Checker = memo<ConnectionCheckerProps>(
overflow: 'hidden',
}}
onSelect={async (value) => {
+ if (!canManageProvider) return;
+
// Update local state
setCheckModel(value);
setPass(false);
@@ -203,7 +208,7 @@ const Checker = memo<ConnectionCheckerProps>(
}}
/>
<Button
- disabled={isProviderConfigUpdating}
+ disabled={!canManageProvider || isProviderConfigUpdating}
loading={loading}
icon={
pass ? (
@@ -223,6 +228,8 @@ const Checker = memo<ConnectionCheckerProps>(
: undefined
}
onClick={async () => {
+ if (!canManageProvider) return;
+
await onBeforeCheck();
try {
await checkConnection();
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/EnableSwitch.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/EnableSwitch.tsx
index 21441606aaf..95ba812b8fc 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/EnableSwitch.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/EnableSwitch.tsx
@@ -1,8 +1,9 @@
-import { Skeleton } from '@lobehub/ui';
+import { Skeleton, Tooltip } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import InstantSwitch from '@/components/InstantSwitch';
+import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
const styles = createStaticStyles(({ css }) => ({
@@ -25,20 +26,25 @@ const Switch = ({ id, Component }: SwitchProps) => {
aiProviderSelectors.isProviderEnabled(id)(s),
aiProviderSelectors.isAiProviderConfigLoading(id)(s),
]);
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
if (isLoading) return <Skeleton.Button active className={styles.switchLoading} />;
// slot for cloud
if (Component) return <Component id={id} />;
- return (
+ const switchNode = (
<InstantSwitch
+ disabled={!canManageProvider}
enabled={enabled}
onChange={async (enabled) => {
+ if (!canManageProvider) return;
await toggleProviderEnabled(id as any, enabled);
}}
/>
);
+
+ return canManageProvider ? switchNode : <Tooltip title={reason}>{switchNode}</Tooltip>;
};
export default Switch;
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
index 2059d0dc059..562015e67cc 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
@@ -11,6 +11,7 @@ import { type ReactNode } from 'react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaQuery } from '@/libs/trpc/client';
import { useOAuthDeviceFlow } from './useOAuthDeviceFlow';
@@ -131,6 +132,7 @@ export interface OAuthDeviceFlowAuthProps {
const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
({ providerId, name, onAuthChange, title, extra }) => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const [isAuthenticating, setIsAuthenticating] = useState(false);
const hasAutoClosedRef = useRef(false);
@@ -165,6 +167,8 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
});
const handleDisconnect = useCallback(() => {
+ if (!canManageProvider) return;
+
confirmModal({
content: t('providerModels.config.oauth.disconnectConfirm'),
okButtonProps: { danger: true },
@@ -174,13 +178,15 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
},
title: t('providerModels.config.oauth.disconnect'),
});
- }, [providerId, revokeAuth, t]);
+ }, [canManageProvider, providerId, revokeAuth, t]);
const handleStartAuth = useCallback(async () => {
+ if (!canManageProvider) return;
+
hasAutoClosedRef.current = false;
setIsAuthenticating(true);
await startAuth();
- }, [startAuth]);
+ }, [canManageProvider, startAuth]);
const handleCancelAuth = useCallback(() => {
setIsAuthenticating(false);
@@ -225,6 +231,7 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
</div>
</Flexbox>
<Button
+ disabled={!canManageProvider}
icon={<Icon icon={LogOutIcon} />}
loading={revokeAuth.isPending}
onClick={handleDisconnect}
@@ -260,7 +267,12 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
<Text className={styles.errorText}>{t(errorKey as any)}</Text>
</Flexbox>
<Flexbox gap={12} style={{ width: '100%' }} width={280}>
- <Button block type="primary" onClick={handleStartAuth}>
+ <Button
+ block
+ disabled={!canManageProvider}
+ type="primary"
+ onClick={handleStartAuth}
+ >
{t('providerModels.config.oauth.retry')}
</Button>
<Button block type="text" onClick={handleCancelAuth}>
@@ -324,7 +336,12 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
<Icon color={cssVar.colorError} icon={UnplugIcon} size={18} />
<Text className={styles.errorText}>{t(errorKey as any)}</Text>
</Flexbox>
- <Button size="large" type="primary" onClick={handleStartAuth}>
+ <Button
+ disabled={!canManageProvider}
+ size="large"
+ type="primary"
+ onClick={handleStartAuth}
+ >
{t('providerModels.config.oauth.connect', { name })}
</Button>
<div className={styles.serviceNote}>
@@ -337,7 +354,12 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
// Default state - show connect button
return (
<div className={styles.content}>
- <Button size="large" type="primary" onClick={handleStartAuth}>
+ <Button
+ disabled={!canManageProvider}
+ size="large"
+ type="primary"
+ onClick={handleStartAuth}
+ >
{t('providerModels.config.oauth.connect', { name })}
</Button>
<div className={styles.serviceNote}>
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
index d01c2f14d02..55ec8376ab9 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
@@ -6,8 +6,8 @@ import { App } from 'antd';
import { BrainIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAiInfraStore } from '@/store/aiInfra/store';
import { type AiProviderDetailItem, type UpdateAiProviderParams } from '@/types/aiProvider';
@@ -30,7 +30,7 @@ const CreateNewProvider = memo<CreateNewProviderProps>(({ onClose, open, initial
]);
const { message } = App.useApp();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const onFinish = async (values: UpdateAiProviderParams) => {
setLoading(true);
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/index.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/index.tsx
index 33bb5342c1c..f07be0caf9d 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/UpdateProviderInfo/index.tsx
@@ -6,6 +6,7 @@ import { SettingsIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import SettingModal from './SettingModal';
@@ -15,17 +16,20 @@ const UpdateProviderInfo = memo(() => {
const [open, setOpen] = useState(false);
const providerConfig = useAiInfraStore(aiProviderSelectors.activeProviderConfig, isEqual);
+ const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
return (
<>
- <Tooltip title={t('updateAiProvider.tooltip')}>
+ <Tooltip title={canManageProvider ? t('updateAiProvider.tooltip') : reason}>
<Button
+ disabled={!canManageProvider}
icon={SettingsIcon}
size={'small'}
type={'text'}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
+ if (!canManageProvider) return;
setOpen(true);
}}
/>
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
index 0e47689b3ed..a7f012a051f 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
@@ -26,6 +26,7 @@ import { z } from 'zod';
import { FormInput, FormPassword } from '@/components/FormInput';
import { SkeletonInput, SkeletonSwitch } from '@/components/Skeleton';
+import { usePermission } from '@/hooks/usePermission';
import { lambdaQuery } from '@/libs/trpc/client';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -146,6 +147,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
} = settings || {};
const { t } = useTranslation('modelProvider');
const [form] = Form.useForm();
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const isOAuthProvider = authType === 'oauthDeviceFlow';
@@ -504,10 +506,12 @@ const ProviderConfig = memo<ProviderConfigProps>(
{shouldShowForm && (
<Form
className={cx(styles.form, className)}
+ disabled={!canManageProvider}
form={form}
items={[model]}
variant={'borderless'}
onValuesChange={(_, values) => {
+ if (!canManageProvider) return;
debouncedHandleValueChange(id, values);
}}
{...FORM_STYLE}
diff --git a/src/routes/(main)/settings/provider/index.tsx b/src/routes/(main)/settings/provider/index.tsx
index f14a23f1cc9..acc14f5205a 100644
--- a/src/routes/(main)/settings/provider/index.tsx
+++ b/src/routes/(main)/settings/provider/index.tsx
@@ -2,9 +2,10 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
-import { Outlet, useNavigate, useParams } from 'react-router-dom';
+import { Outlet, useParams } from 'react-router-dom';
import { isCustomBranding } from '@/const/version';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import DesktopLayoutContainer from './_layout/Desktop/Container';
import Footer from './(list)/Footer';
@@ -13,7 +14,7 @@ import ProviderMenu from './ProviderMenu';
// Layout component that wraps provider pages with navigation
export const ProviderLayout = memo(() => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleProviderSelect = (providerKey: string) => {
navigate(`/settings/provider/${providerKey}`);
@@ -41,7 +42,7 @@ ProviderLayout.displayName = 'ProviderLayout';
// Detail page component that receives providerId from route params
export const ProviderDetailPage = memo(() => {
const params = useParams<{ providerId: string }>();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleProviderSelect = (providerKey: string) => {
navigate(`/settings/provider/${providerKey}`);
diff --git a/src/routes/(main)/settings/skill/features/Actions.tsx b/src/routes/(main)/settings/skill/features/Actions.tsx
index d38f97c8daf..b8d4f1f19c8 100644
--- a/src/routes/(main)/settings/skill/features/Actions.tsx
+++ b/src/routes/(main)/settings/skill/features/Actions.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import McpSettingsModal from '@/features/MCP/MCPSettings/McpSettingsModal';
import PluginDetailModal from '@/features/PluginDetailModal';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -35,6 +36,8 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
const { t } = useTranslation('plugin');
const [settingsOpen, setSettingsOpen] = useState(false);
const plugin = useToolStore(pluginSelectors.getToolManifestById(identifier));
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [togglePlugin, isPluginEnabledInAgent] = useAgentStore((s) => [
s.togglePlugin,
agentSelectors.currentAgentPlugins(s).includes(identifier),
@@ -49,7 +52,9 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
const configureButton = (
<Button
+ disabled={!canEdit}
onClick={() => {
+ if (!canEdit) return;
if (isCustomPlugin) {
setModal(true);
} else if (isCommunityMCP) {
@@ -81,10 +86,12 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall'),
onClick: () => {
+ if (!canEdit) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -105,9 +112,11 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
</Space.Compact>
) : (
<Button
+ disabled={!canCreate || !canEdit}
loading={installing}
size={mobile ? 'small' : undefined}
onClick={async () => {
+ if (!canCreate || !canEdit) return;
if (isMCP) {
await installMCPPlugin(identifier);
await togglePlugin(identifier);
diff --git a/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx b/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx
index 8136bd8d843..659bf90f8a3 100644
--- a/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx
+++ b/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx
@@ -10,6 +10,7 @@ import { lazy, memo, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { createBuiltinAgentSkillDetailModal } from '@/features/SkillStore/SkillDetail';
+import { usePermission } from '@/hooks/usePermission';
import { agentSkillService } from '@/services/skill';
import { useToolStore } from '@/store/tool';
import { builtinToolSelectors } from '@/store/tool/selectors';
@@ -36,6 +37,8 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
const [loading, setLoading] = useState(false);
const [detailOpen, setDetailOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const isBuiltin = isBuiltinSkill(skill);
@@ -68,6 +71,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
};
const handleUninstall = () => {
+ if (!canEdit) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -105,6 +109,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: tp('store.actions.uninstall'),
@@ -112,12 +117,19 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
},
]}
>
- <Button icon={MoreHorizontalIcon} />
+ <Button disabled={!canEdit} icon={MoreHorizontalIcon} />
</DropdownMenu>
);
}
return (
- <Button icon={Plus} onClick={() => installBuiltinTool(skill.identifier)}>
+ <Button
+ disabled={!canCreate}
+ icon={Plus}
+ onClick={() => {
+ if (!canCreate) return;
+ installBuiltinTool(skill.identifier);
+ }}
+ >
{tp('store.actions.install')}
</Button>
);
@@ -125,7 +137,9 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
return (
<Space.Compact>
- <Button onClick={() => setEditOpen(true)}>{tp('store.actions.configure')}</Button>
+ <Button disabled={!canEdit} onClick={() => setEditOpen(true)}>
+ {tp('store.actions.configure')}
+ </Button>
<DropdownMenu
placement="bottomRight"
items={[
@@ -142,6 +156,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
: []),
{
danger: true,
+ disabled: !canEdit,
icon: <Trash2 size={16} />,
key: 'uninstall',
label: tp('store.actions.uninstall'),
@@ -149,7 +164,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
},
]}
>
- <Button icon={MoreHorizontalIcon} loading={loading} />
+ <Button disabled={!canEdit} icon={MoreHorizontalIcon} loading={loading} />
</DropdownMenu>
</Space.Compact>
);
diff --git a/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx b/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx
index a0bf42c65c6..b3841280f85 100644
--- a/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx
+++ b/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx
@@ -7,6 +7,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { createBuiltinSkillDetailModal } from '@/features/SkillStore/SkillDetail';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import { builtinToolSelectors } from '@/store/tool/selectors';
@@ -23,6 +24,8 @@ interface BuiltinSkillItemProps {
const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
({ identifier, title, avatar, isSelected, onSelect }) => {
const { t } = useTranslation(['setting', 'plugin', 'common']);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [installBuiltinTool, uninstallBuiltinTool, isInstalled] = useToolStore((s) => [
s.installBuiltinTool,
@@ -31,10 +34,13 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
]);
const handleInstall = async () => {
+ if (!canCreate) return;
await installBuiltinTool(identifier);
};
const handleUninstall = () => {
+ if (!canEdit) return;
+
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('store.actions.confirmUninstall', { ns: 'plugin' }),
@@ -70,6 +76,7 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Trash2} />,
key: 'uninstall',
label: t('store.actions.uninstall', { ns: 'plugin' }),
@@ -77,13 +84,13 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
},
]}
>
- <Button icon={MoreHorizontalIcon} />
+ <Button disabled={!canEdit} icon={MoreHorizontalIcon} />
</DropdownMenu>
);
}
return (
- <Button icon={Plus} onClick={handleInstall}>
+ <Button disabled={!canCreate} icon={Plus} onClick={handleInstall}>
{t('store.actions.install', { ns: 'plugin' })}
</Button>
);
diff --git a/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx b/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx
index dd4e4620a6e..49bac9d5435 100644
--- a/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx
+++ b/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx
@@ -1,7 +1,7 @@
'use client';
import { type KlavisServerType } from '@lobechat/const';
-import { Avatar, Button as LobeButton, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
+import { Avatar, Button as LobeButton, DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { Button } from 'antd';
import { cssVar } from 'antd-style';
@@ -10,6 +10,7 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { createKlavisSkillDetailModal } from '@/features/SkillStore/SkillDetail';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import { type KlavisServer } from '@/store/tool/slices/klavisStore';
import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';
@@ -31,6 +32,8 @@ interface KlavisSkillItemProps {
const KlavisSkillItem = memo<KlavisSkillItemProps>(
({ serverType, server, isSelected, onSelect }) => {
const { t } = useTranslation('setting');
+ const { allowed: canCreate, reason: createReason } = usePermission('create_content');
+ const { allowed: canEdit, reason: editReason } = usePermission('edit_own_content');
const [isConnecting, setIsConnecting] = useState(false);
const [isWaitingAuth, setIsWaitingAuth] = useState(false);
@@ -139,6 +142,7 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(
);
const handleConnect = async () => {
+ if (!canCreate || !canEdit) return;
if (!userId) return;
if (server) return;
@@ -165,6 +169,7 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(
};
const handleDisconnect = () => {
+ if (!canEdit) return;
if (!server) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
@@ -226,22 +231,27 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(
if (!server) {
return (
- <Button
- icon={<Icon icon={SquareArrowOutUpRight} />}
- type="default"
- onClick={handleConnect}
- >
- {t('tools.klavis.connect', { defaultValue: 'Connect' })}
- </Button>
+ <Tooltip title={!canCreate ? createReason : editReason}>
+ <Button
+ disabled={!canCreate || !canEdit}
+ icon={<Icon icon={SquareArrowOutUpRight} />}
+ type="default"
+ onClick={handleConnect}
+ >
+ {t('tools.klavis.connect', { defaultValue: 'Connect' })}
+ </Button>
+ </Tooltip>
);
}
if (server.status === KlavisServerStatus.PENDING_AUTH) {
return (
<Button
+ disabled={!canCreate || !canEdit}
icon={<Icon icon={SquareArrowOutUpRight} />}
type="default"
onClick={() => {
+ if (!canCreate || !canEdit) return;
if (server.oauthUrl) {
openOAuthWindow(server.oauthUrl, server.identifier);
}
@@ -259,6 +269,7 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(
items={[
{
danger: true,
+ disabled: !canEdit,
icon: <Icon icon={Unplug} />,
key: 'disconnect',
label: t('tools.klavis.disconnect', { defaultValue: 'Disconnect' }),
@@ -266,7 +277,9 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(
},
]}
>
- <LobeButton icon={MoreHorizontalIcon} />
+ <Tooltip title={editReason}>
+ <LobeButton disabled={!canEdit} icon={MoreHorizontalIcon} />
+ </Tooltip>
</DropdownMenu>
);
}
diff --git a/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx b/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx
index e9541145cf7..a88e1fb0126 100644
--- a/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx
+++ b/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx
@@ -1,7 +1,7 @@
'use client';
import { type LobehubSkillProviderType } from '@lobechat/const';
-import { Avatar, Button as LobeButton, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
+import { Avatar, Button as LobeButton, DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { Button } from 'antd';
import { cssVar } from 'antd-style';
@@ -10,6 +10,7 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { createLobehubSkillDetailModal } from '@/features/SkillStore/SkillDetail';
+import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
import { type LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
@@ -29,6 +30,8 @@ interface LobehubSkillItemProps {
const LobehubSkillItem = memo<LobehubSkillItemProps>(
({ provider, server, isSelected, onSelect }) => {
const { t } = useTranslation('setting');
+ const { allowed: canCreate, reason: createReason } = usePermission('create_content');
+ const { allowed: canEdit, reason: editReason } = usePermission('edit_own_content');
const [isConnecting, setIsConnecting] = useState(false);
const [isWaitingAuth, setIsWaitingAuth] = useState(false);
@@ -152,6 +155,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
}, [provider.id, cleanup, checkStatus]);
const handleConnect = async () => {
+ if (!canCreate || !canEdit) return;
if (server?.isConnected) return;
setIsConnecting(true);
@@ -170,6 +174,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
};
const handleDisconnect = () => {
+ if (!canEdit) return;
if (!server) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
@@ -232,13 +237,16 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
if (!server || server.status !== LobehubSkillStatus.CONNECTED) {
return (
- <Button
- icon={<Icon icon={SquareArrowOutUpRight} />}
- type="default"
- onClick={handleConnect}
- >
- {t('tools.lobehubSkill.connect')}
- </Button>
+ <Tooltip title={!canCreate ? createReason : editReason}>
+ <Button
+ disabled={!canCreate || !canEdit}
+ icon={<Icon icon={SquareArrowOutUpRight} />}
+ type="default"
+ onClick={handleConnect}
+ >
+ {t('tools.lobehubSkill.connect')}
+ </Button>
+ </Tooltip>
);
}
@@ -247,6 +255,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
placement="bottomRight"
items={[
{
+ disabled: !canEdit,
icon: <Icon icon={Unplug} />,
key: 'disconnect',
label: t('tools.lobehubSkill.disconnect', { defaultValue: 'Disconnect' }),
@@ -254,7 +263,9 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
},
]}
>
- <LobeButton icon={MoreHorizontalIcon} />
+ <Tooltip title={editReason}>
+ <LobeButton disabled={!canEdit} icon={MoreHorizontalIcon} />
+ </Tooltip>
</DropdownMenu>
);
};
diff --git a/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx b/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx
new file mode 100644
index 00000000000..6ced4478419
--- /dev/null
+++ b/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx
@@ -0,0 +1,79 @@
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { Clock3Icon, ClockArrowUp, UsersIcon } from 'lucide-react';
+import { memo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { useActiveWorkspace } from '@/business/client/hooks/useActiveWorkspace';
+import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';
+import { formatIntergerNumber } from '@/utils/format';
+
+import TimeLabel from '../components/TimeLabel';
+
+const formatEnglishNumber = (number: number) => {
+ if (number === 1) return '1st';
+ if (number === 2) return '2nd';
+ if (number === 3) return '3rd';
+ return `${formatIntergerNumber(number)}th`;
+};
+
+const WorkspaceWelcome = memo<{ mobile?: boolean }>(({ mobile }) => {
+ const { t, i18n } = useTranslation('auth');
+ const { t: tSetting } = useTranslation('setting');
+ const workspace = useActiveWorkspace();
+ const members = useWorkspaceMembers();
+
+ if (!workspace) {
+ return <Skeleton.Button active style={{ height: 24, minWidth: 200, width: 200 }} />;
+ }
+
+ const days = Math.max(1, dayjs().diff(dayjs(workspace.createdAt), 'day'));
+ const memberCount = members.length;
+
+ return (
+ <Flexbox padding={mobile ? 16 : 0}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ wrap={'wrap'}
+ style={{
+ fontSize: 16,
+ fontWeight: 500,
+ }}
+ >
+ <Trans
+ i18nKey="stats.workspace.welcome"
+ ns={'auth'}
+ components={{
+ span: <span style={{ fontWeight: 'bold' }} />,
+ }}
+ values={{
+ days:
+ i18n.language === 'en-US' ? formatEnglishNumber(days) : formatIntergerNumber(days),
+ name: workspace.name,
+ }}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={16} wrap={'wrap'}>
+ <TimeLabel
+ date={String(memberCount)}
+ icon={UsersIcon}
+ title={tSetting('workspaceSetting.tab.members')}
+ />
+ <TimeLabel
+ date={dayjs(workspace.createdAt).format('YYYY-MM-DD')}
+ icon={Clock3Icon}
+ title={t('stats.createdAt')}
+ />
+ <TimeLabel
+ date={dayjs(workspace.updatedAt).format('YYYY-MM-DD')}
+ icon={ClockArrowUp}
+ title={t('stats.updatedAt')}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default WorkspaceWelcome;
diff --git a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
index 67f04892ac0..e6891bc90f5 100644
--- a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
@@ -4,10 +4,10 @@ import { MaximizeIcon } from 'lucide-react';
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { DEFAULT_AVATAR } from '@/const/meta';
import { SESSION_CHAT_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Link from '@/libs/router/Link';
import { useClientDataSWR } from '@/libs/swr';
import { agentService } from '@/services/agent';
@@ -20,7 +20,7 @@ import StatsFormGroup from '../components/StatsFormGroup';
export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const [open, setOpen] = useState(false);
const { t } = useTranslation(['auth', 'chat']);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { data, isLoading } = useClientDataSWR('rank-agents', async () =>
agentService.rankAgents(),
diff --git a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
index c23edd84191..2a08960ceea 100644
--- a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
@@ -5,9 +5,9 @@ import { MaximizeIcon, MessageSquareIcon } from 'lucide-react';
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Link from '@/libs/router/Link';
import { useClientDataSWR } from '@/libs/swr';
import { topicService } from '@/services/topic';
@@ -20,7 +20,7 @@ import StatsFormGroup from '../components/StatsFormGroup';
export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const [open, setOpen] = useState(false);
const { t } = useTranslation('auth');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { data, isLoading } = useClientDataSWR('rank-topics', async () =>
topicService.rankTopics(),
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/ModelTable.tsx b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/ModelTable.tsx
index 8ad6d76e974..41c34b8ffbc 100644
--- a/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/ModelTable.tsx
+++ b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/ModelTable.tsx
@@ -1,12 +1,12 @@
import { CategoryBar, useThemeColorRange } from '@lobehub/charts';
import { ModelIcon, ProviderIcon } from '@lobehub/icons';
-import { Collapse, Flexbox, Skeleton, Tag } from '@lobehub/ui';
+import { Avatar, Collapse, Flexbox, Skeleton, Tag } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import InlineTable from '@/components/InlineTable';
-import { type UsageLog } from '@/types/usage/usageRecord';
+import { type UsageLog, type UsageRecordItem } from '@/types/usage/usageRecord';
import { formatPrice } from '@/utils/format';
import { type UsageChartProps } from '../../../../types';
@@ -18,6 +18,19 @@ interface WeightGroup {
weight: number;
}
+// Outer grouping key (top-level rows). For User mode, group by userId.
+const outerKey = (log: UsageRecordItem, groupBy: GroupBy): string => {
+ if (groupBy === GroupBy.Model) return log.model;
+ if (groupBy === GroupBy.Provider) return log.provider;
+ return log.userId;
+};
+
+// Inner grouping key (sub-rows). For Model→Provider, Provider→Model, User→Model.
+const innerKey = (log: UsageRecordItem, groupBy: GroupBy): string => {
+ if (groupBy === GroupBy.Model) return log.provider;
+ return log.model;
+};
+
const formatData = (
data: UsageLog[],
groupBy: GroupBy,
@@ -30,7 +43,7 @@ const formatData = (
const requestLogs = data.flatMap((log) => log.records);
const groupedLogs = requestLogs.reduce((acc, log) => {
- const key = groupBy === GroupBy.Model ? log.model : log.provider;
+ const key = outerKey(log, groupBy);
if (!acc.has(key)) {
acc.set(key, []);
}
@@ -43,7 +56,7 @@ const formatData = (
// The logs here span multiple days and need to be summed
// If the current groupBy is Model, logs should be grouped by Provider
const spend = logs.reduce((acc, log) => {
- const key = groupBy === GroupBy.Model ? log.provider : log.model;
+ const key = innerKey(log, groupBy);
acc.set(key, (acc.get(key) || 0) + log.spend);
return acc;
}, new Map<string, number>());
@@ -69,7 +82,7 @@ const formatData = (
.sort((a, b) => b.totalSpend - a.totalSpend);
};
-const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
+const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy, resolveUser }) => {
const { t } = useTranslation('auth');
const themeColorRange = useThemeColorRange();
@@ -78,6 +91,53 @@ const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
[data, groupBy],
);
+ // Sub-row column shows the "other" dimension. For Model→Provider,
+ // Provider→Model, and User→Model.
+ const innerColumnKey =
+ (groupBy ?? GroupBy.Model) === GroupBy.Model
+ ? 'usage.activeModels.table.provider'
+ : 'usage.activeModels.table.model';
+
+ const renderInnerIcon = (id: string, color: string) => {
+ const baseStyle = {
+ boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}, 0 0 0 4px ${color}`,
+ boxSizing: 'content-box' as const,
+ };
+ return (groupBy ?? GroupBy.Model) === GroupBy.Provider ? (
+ <ProviderIcon provider={id} style={baseStyle} />
+ ) : (
+ <ModelIcon model={id} style={baseStyle} />
+ );
+ };
+
+ const renderOuterLabel = (key: string) => {
+ if (groupBy === GroupBy.User) {
+ const display = resolveUser?.(key);
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Avatar
+ avatar={display?.avatar || display?.name || key}
+ background={cssVar.colorFillSecondary}
+ shape={'circle'}
+ size={24}
+ title={display?.name || key}
+ />
+ {display?.name || key}
+ </Flexbox>
+ );
+ }
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {groupBy === GroupBy.Provider ? (
+ <ProviderIcon provider={key} size={24} />
+ ) : (
+ <ModelIcon model={key} size={24} />
+ )}
+ {key}
+ </Flexbox>
+ );
+ };
+
return isLoading ? (
<Skeleton active paragraph={{ rows: 8 }} title={false} />
) : (
@@ -108,31 +168,12 @@ const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
render: (value, record, index) => {
return (
<Flexbox horizontal align={'center'} gap={12} key={value}>
- {groupBy === GroupBy.Provider ? (
- <ProviderIcon
- provider={record.id}
- style={{
- boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}, 0 0 0 4px ${themeColorRange[index]}`,
- boxSizing: 'content-box',
- }}
- />
- ) : (
- <ModelIcon
- model={record.id}
- style={{
- boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}, 0 0 0 4px ${themeColorRange[index]}`,
- boxSizing: 'content-box',
- }}
- />
- )}
+ {renderInnerIcon(record.id, themeColorRange[index])}
{value}
</Flexbox>
);
},
- title:
- groupBy === GroupBy.Model
- ? t('usage.activeModels.table.provider')
- : t('usage.activeModels.table.model'),
+ title: t(innerColumnKey),
width: 200,
},
{
@@ -149,16 +190,7 @@ const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
),
extra: <Tag>{item?.childrens?.length ?? 0}</Tag>,
key,
- label: (
- <Flexbox horizontal align={'center'} gap={8}>
- {groupBy === GroupBy.Model ? (
- <ModelIcon model={key} size={24} />
- ) : (
- <ProviderIcon provider={key} size={24} />
- )}
- {key}
- </Flexbox>
- ),
+ label: renderOuterLabel(key),
};
})}
padding={{
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx
new file mode 100644
index 00000000000..8ff39e6d950
--- /dev/null
+++ b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx
@@ -0,0 +1,85 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { UsageLog } from '@/types/usage/usageRecord';
+
+import { GroupBy } from '../../../../types';
+import ActiveModels from './index';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/icons', () => ({
+ ModelIcon: ({ model }: { model: string }) => <span>{model}</span>,
+ ProviderIcon: ({ provider }: { provider: string }) => <span>{provider}</span>,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: () => <button type="button" />,
+ Avatar: ({ avatar, title }: { avatar?: string | null; title?: string }) => (
+ <span aria-label={title} data-testid="active-user-avatar">
+ {avatar}
+ </span>
+ ),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Modal: () => null,
+}));
+
+vi.mock('@/components/StatisticCard', () => ({
+ default: ({ statistic }: { statistic: { description?: ReactNode; value?: ReactNode } }) => (
+ <div>
+ <span>{statistic.value}</span>
+ {statistic.description}
+ </div>
+ ),
+}));
+
+vi.mock('@/components/StatisticCard/TitleWithPercentage', () => ({
+ default: ({ title }: { title: string }) => <span>{title}</span>,
+}));
+
+const usageLog: UsageLog[] = [
+ {
+ date: 1,
+ day: '2026-05-27',
+ records: [
+ {
+ createdAt: new Date('2026-05-27T00:00:00.000Z'),
+ id: 'record-1',
+ model: 'gpt-5-mini',
+ provider: 'openai',
+ spend: 1,
+ totalInputTokens: 10,
+ totalOutputTokens: 20,
+ totalTokens: 30,
+ type: 'chat',
+ updatedAt: new Date('2026-05-27T00:00:00.000Z'),
+ userId: 'user-1',
+ },
+ ],
+ totalRequests: 1,
+ totalSpend: 1,
+ totalTokens: 30,
+ },
+];
+
+describe('ActiveModels', () => {
+ it('uses the resolved user name as the avatar fallback when the user has no avatar URL', () => {
+ render(
+ <ActiveModels
+ data={usageLog}
+ groupBy={GroupBy.User}
+ resolveUser={() => ({ avatar: null, name: 'Ada Lovelace' })}
+ />,
+ );
+
+ expect(screen.getByTestId('active-user-avatar')).toHaveTextContent('Ada Lovelace');
+ });
+});
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.tsx b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.tsx
index 7e7c37e6c98..868935a7874 100644
--- a/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.tsx
+++ b/src/routes/(main)/settings/stats/features/usage/UsageCards/ActiveModels/index.tsx
@@ -1,5 +1,5 @@
import { ModelIcon, ProviderIcon } from '@lobehub/icons';
-import { ActionIcon, Flexbox, Modal } from '@lobehub/ui';
+import { ActionIcon, Avatar, Flexbox, Modal } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { MaximizeIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
@@ -27,6 +27,9 @@ const computeList = (data: UsageLog[], groupBy: GroupBy): string[] => {
if (groupBy === GroupBy.Provider && item.provider?.length !== 0) {
acc.add(item.provider);
}
+ if (groupBy === GroupBy.User && item.userId) {
+ acc.add(item.userId);
+ }
}
}
return acc;
@@ -34,7 +37,26 @@ const computeList = (data: UsageLog[], groupBy: GroupBy): string[] => {
);
};
-const ActiveModels = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
+const titleI18n = (
+ groupBy: GroupBy,
+): 'usage.activeModels.models' | 'usage.activeModels.providers' | 'usage.activeModels.users' => {
+ if (groupBy === GroupBy.Model) return 'usage.activeModels.models';
+ if (groupBy === GroupBy.Provider) return 'usage.activeModels.providers';
+ return 'usage.activeModels.users';
+};
+
+const tableTitleI18n = (
+ groupBy: GroupBy,
+):
+ | 'usage.activeModels.modelTable'
+ | 'usage.activeModels.providerTable'
+ | 'usage.activeModels.userTable' => {
+ if (groupBy === GroupBy.Model) return 'usage.activeModels.modelTable';
+ if (groupBy === GroupBy.Provider) return 'usage.activeModels.providerTable';
+ return 'usage.activeModels.userTable';
+};
+
+const ActiveModels = memo<UsageChartProps>(({ data, isLoading, groupBy, resolveUser }) => {
const { t } = useTranslation('auth');
const [open, setOpen] = useState(false);
@@ -44,20 +66,45 @@ const ActiveModels = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
[data, groupBy],
);
+ const renderIcon = (item: string, i: number) => {
+ const baseStyle = {
+ border: `2px solid ${cssVar.colorBgContainer}`,
+ boxSizing: 'content-box' as const,
+ marginRight: -8,
+ zIndex: i + 1,
+ };
+ if (groupBy === GroupBy.User) {
+ const display = resolveUser?.(item);
+ return (
+ <Avatar
+ avatar={display?.avatar || display?.name || item}
+ background={cssVar.colorFillSecondary}
+ key={item}
+ shape={'circle'}
+ size={18}
+ style={baseStyle}
+ title={display?.name || item}
+ />
+ );
+ }
+ return groupBy === GroupBy.Provider ? (
+ <ProviderIcon key={item} provider={item} size={18} style={baseStyle} />
+ ) : (
+ <ModelIcon key={item} model={item} size={18} style={baseStyle} />
+ );
+ };
+
return (
<>
<StatisticCard
key={groupBy}
loading={isLoading}
+ title={<TitleWithPercentage title={t(titleI18n(groupBy ?? GroupBy.Model))} />}
extra={
<ActionIcon
icon={MaximizeIcon}
size={'small'}
- title={
- groupBy === GroupBy.Model
- ? t('usage.activeModels.modelTable')
- : t('usage.activeModels.providerTable')
- }
+ title={t(tableTitleI18n(groupBy ?? GroupBy.Model))}
onClick={() => setOpen(true)}
/>
}
@@ -66,58 +113,21 @@ const ActiveModels = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
<Flexbox horizontal wrap={'wrap'}>
{iconList.map((item, i) => {
if (!item) return null;
- return groupBy === GroupBy.Model ? (
- <ModelIcon
- key={item}
- model={item}
- size={18}
- style={{
- border: `2px solid ${cssVar.colorBgContainer}`,
- boxSizing: 'content-box',
- marginRight: -8,
- zIndex: i + 1,
- }}
- />
- ) : (
- <ProviderIcon
- key={item}
- provider={item}
- size={18}
- style={{
- border: `2px solid ${cssVar.colorBgContainer}`,
- boxSizing: 'content-box',
- marginRight: -8,
- zIndex: i + 1,
- }}
- />
- );
+ return renderIcon(item, i);
})}
</Flexbox>
),
precision: 0,
value: formatNumber(iconList?.length ?? 0),
}}
- title={
- <TitleWithPercentage
- title={
- groupBy === GroupBy.Model
- ? t('usage.activeModels.models')
- : t('usage.activeModels.providers')
- }
- />
- }
/>
<Modal
footer={null}
open={open}
- title={
- groupBy === GroupBy.Model
- ? t('usage.activeModels.modelTable')
- : t('usage.activeModels.providerTable')
- }
+ title={t(tableTitleI18n(groupBy ?? GroupBy.Model))}
onCancel={() => setOpen(false)}
>
- <ModelTable data={data} groupBy={groupBy} isLoading={isLoading} />
+ <ModelTable data={data} groupBy={groupBy} isLoading={isLoading} resolveUser={resolveUser} />
</Modal>
</>
);
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageCards/index.tsx b/src/routes/(main)/settings/stats/features/usage/UsageCards/index.tsx
index 3c9fe16863f..2d46252a1b7 100644
--- a/src/routes/(main)/settings/stats/features/usage/UsageCards/index.tsx
+++ b/src/routes/(main)/settings/stats/features/usage/UsageCards/index.tsx
@@ -6,12 +6,12 @@ import ActiveModels from './ActiveModels';
import MonthSpend from './MonthSpend';
import TodaySpend from './TodaySpend';
-const UsageCards = memo<UsageChartProps>(({ isLoading, data, groupBy }) => {
+const UsageCards = memo<UsageChartProps>(({ isLoading, data, groupBy, resolveUser }) => {
return (
<Flexbox horizontal gap={16}>
<TodaySpend data={data} isLoading={isLoading} />
<MonthSpend data={data} isLoading={isLoading} />
- <ActiveModels data={data} groupBy={groupBy} isLoading={isLoading} />
+ <ActiveModels data={data} groupBy={groupBy} isLoading={isLoading} resolveUser={resolveUser} />
</Flexbox>
);
});
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageTrends.tsx b/src/routes/(main)/settings/stats/features/usage/UsageTrends.tsx
index 4610f2f654e..e3741fa6b6f 100644
--- a/src/routes/(main)/settings/stats/features/usage/UsageTrends.tsx
+++ b/src/routes/(main)/settings/stats/features/usage/UsageTrends.tsx
@@ -3,28 +3,41 @@ import { Segmented, Skeleton } from '@lobehub/ui';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { type UsageLog } from '@/types/usage/usageRecord';
+import { type UsageLog, type UsageRecordItem } from '@/types/usage/usageRecord';
import { formatNumber } from '@/utils/format';
-import { type UsageChartProps } from '../../types';
+import { type UsageChartProps, type UserDisplayResolver } from '../../types';
import { GroupBy } from '../../types';
import StatsFormGroup from '../components/StatsFormGroup';
import { UsageBarChart } from '../components/UsageBarChart';
+const recordKey = (item: UsageRecordItem, groupBy: GroupBy): string => {
+ if (groupBy === GroupBy.Model) return item.model;
+ if (groupBy === GroupBy.Provider) return item.provider;
+ return item.userId;
+};
+
+const categoryLabel = (
+ key: string,
+ groupBy: GroupBy,
+ resolveUser?: UserDisplayResolver,
+): string => {
+ if (groupBy === GroupBy.User && resolveUser) return resolveUser(key).name;
+ return key;
+};
+
const groupByType = (
data: UsageLog[],
type: 'spend' | 'token',
groupBy: GroupBy,
+ resolveUser?: UserDisplayResolver,
): { categories: string[]; data: BarChartProps['data'] } => {
if (!data || data?.length === 0) return { categories: [], data: [] };
const cate: Map<string, number> = data.reduce((acc, log) => {
if (log.records) {
for (const item of log.records) {
- if (groupBy === GroupBy.Model && item.model) {
- acc.set(item.model, 0);
- } else if (groupBy === GroupBy.Provider && item.provider) {
- acc.set(item.provider, 0);
- }
+ const key = recordKey(item, groupBy);
+ if (key) acc.set(categoryLabel(key, groupBy, resolveUser), 0);
}
}
return acc;
@@ -38,7 +51,7 @@ const groupByType = (
const todayCate = new Map<string, number>(cate);
for (const item of log.records) {
const value = type === 'spend' ? item.spend || 0 : item.totalTokens || 0;
- const key = groupBy === GroupBy.Model ? item.model : item.provider;
+ const key = categoryLabel(recordKey(item, groupBy), groupBy, resolveUser);
let displayValue = (todayCate.get(key) || 0) + value;
if (type === 'spend') {
const formattedNum = formatNumber((todayCate.get(key) || 0) + value, 2);
@@ -64,7 +77,7 @@ enum ShowType {
Token = 'token',
}
-const UsageTrends = memo<UsageChartProps>(({ isLoading, data, groupBy }) => {
+const UsageTrends = memo<UsageChartProps>(({ isLoading, data, groupBy, resolveUser }) => {
const { t } = useTranslation('auth');
const [type, setType] = useState<ShowType>(ShowType.Spend);
@@ -73,11 +86,13 @@ const UsageTrends = memo<UsageChartProps>(({ isLoading, data, groupBy }) => {
data || [],
'spend',
groupBy || GroupBy.Model,
+ resolveUser,
);
const { categories: tokenCate, data: tokenData } = groupByType(
data || [],
'token',
groupBy || GroupBy.Model,
+ resolveUser,
);
const charts =
diff --git a/src/routes/(main)/settings/stats/index.tsx b/src/routes/(main)/settings/stats/index.tsx
index 76391ffec6a..de814078508 100644
--- a/src/routes/(main)/settings/stats/index.tsx
+++ b/src/routes/(main)/settings/stats/index.tsx
@@ -5,8 +5,8 @@ import { ProviderIcon } from '@lobehub/ui/icons';
import { type DatePickerProps } from 'antd';
import { DatePicker, Divider } from 'antd';
import dayjs from 'dayjs';
-import { Brain } from 'lucide-react';
-import { memo, useEffect, useState } from 'react';
+import { Brain, UserIcon } from 'lucide-react';
+import { memo, type ReactNode, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useClientDataSWR } from '@/libs/swr';
@@ -24,103 +24,149 @@ import {
import { AssistantsRank, ModelsRank, TopicsRank } from './features/rankings';
import { UsageCards, UsageTable, UsageTrends } from './features/usage';
import { AiHeatmaps } from './features/visualization';
-import { GroupBy } from './types';
+import { GroupBy, type UserDisplayResolver } from './types';
-const StatsSetting = memo<{ mobile?: boolean }>(({ mobile }) => {
- const { t, i18n } = useTranslation('auth');
- dayjs.locale(i18n.language);
+interface StatsSettingProps {
+ /**
+ * Enable the "By User" group-by dimension in the Usage section. Only
+ * meaningful when multiple users contribute to the data (i.e. workspace
+ * mode). Combine with `resolveUser` to render names instead of opaque IDs.
+ */
+ enableUserDimension?: boolean;
+ /**
+ * Replace the personal Welcome banner (uses user nickname / registration
+ * date) with a custom node. Pass `false` to drop the banner entirely.
+ * When set (non-undefined), the personal ShareButton is also hidden because
+ * the share link embeds user-identity context.
+ */
+ headerNode?: ReactNode | false;
+ mobile?: boolean;
+ /** Resolve userId → display info. Required when `enableUserDimension` is true. */
+ resolveUser?: UserDisplayResolver;
+}
- const [groupBy, setGroupBy] = useState<GroupBy>(GroupBy.Model);
- const [dateRange, setDateRange] = useState<dayjs.Dayjs>(dayjs(new Date()));
- const [dateStrings, setDateStrings] = useState<string>();
+const StatsSetting = memo<StatsSettingProps>(
+ ({ mobile, headerNode, enableUserDimension, resolveUser }) => {
+ const { t, i18n } = useTranslation('auth');
+ dayjs.locale(i18n.language);
- const { data, isLoading, mutate } = useClientDataSWR('usage-stat', async () =>
- usageService.findAndGroupByDay(dateStrings),
- );
+ const [groupBy, setGroupBy] = useState<GroupBy>(GroupBy.Model);
+ const [dateRange, setDateRange] = useState<dayjs.Dayjs>(dayjs(new Date()));
+ const [dateStrings, setDateStrings] = useState<string>();
- useEffect(() => {
- if (dateStrings) {
- mutate();
- }
- }, [dateStrings]);
+ const { data, isLoading, mutate } = useClientDataSWR('usage-stat', async () =>
+ usageService.findAndGroupByDay(dateStrings),
+ );
- const handleDateChange: DatePickerProps['onChange'] = (dates, dateStrings) => {
- // Handle both single date and array
- const actualDate = Array.isArray(dates) ? dates[0] : dates;
- if (actualDate) {
- setDateRange(actualDate);
- }
- if (typeof dateStrings === 'string') {
- setDateStrings(dateStrings);
- }
- };
+ useEffect(() => {
+ if (dateStrings) {
+ mutate();
+ }
+ }, [dateStrings]);
- return (
- <>
- <SettingHeader title={t('tab.stats')} />
- {/* ========== Header Section ========== */}
- <FormGroup
- collapsible={false}
- extra={<ShareButton />}
- gap={16}
- title={<Welcome mobile={mobile} />}
- variant={'filled'}
- >
- <Grid gap={8} maxItemWidth={150} rows={4}>
- <TotalAssistants mobile={mobile} />
- <TotalTopics mobile={mobile} />
- <TotalMessages mobile={mobile} />
- <TotalTokens />
- </Grid>
- <Divider dashed />
- <AiHeatmaps mobile={mobile} />
- <Divider dashed />
- <Grid gap={16} rows={3} style={{ paddingBottom: 12 }}>
- <ModelsRank />
- <AssistantsRank mobile={mobile} />
- <TopicsRank mobile={mobile} />
- </Grid>
- </FormGroup>
- <FormGroup
- collapsible={false}
- gap={16}
- title={t('tab.usage')}
- variant={'filled'}
- extra={
- <>
- <DatePicker picker="month" value={dateRange} onChange={handleDateChange} />
- <Segmented
- style={{ marginLeft: 8 }}
- value={groupBy}
- variant={'outlined'}
- options={[
- {
- icon: <Icon icon={Brain} />,
- label: t('usage.welcome.model'),
- value: GroupBy.Model,
- },
- {
- icon: <Icon icon={ProviderIcon} />,
- label: t('usage.welcome.provider'),
- value: GroupBy.Provider,
- },
- ]}
- onChange={(v) => setGroupBy(v as GroupBy)}
- />
- </>
- }
- styles={{
- title: { lineHeight: '35px' },
- }}
- >
- <UsageCards data={data} groupBy={groupBy} isLoading={isLoading} />
- <Divider />
- <UsageTrends data={data} groupBy={groupBy} isLoading={isLoading} />
- <div style={{ height: 24 }} />
- <UsageTable dateStrings={dateStrings} />
- </FormGroup>
- </>
- );
-});
+ const handleDateChange: DatePickerProps['onChange'] = (dates, dateStrings) => {
+ // Handle both single date and array
+ const actualDate = Array.isArray(dates) ? dates[0] : dates;
+ if (actualDate) {
+ setDateRange(actualDate);
+ }
+ if (typeof dateStrings === 'string') {
+ setDateStrings(dateStrings);
+ }
+ };
+
+ return (
+ <>
+ <SettingHeader title={t('tab.stats')} />
+ {/* ========== Header Section ========== */}
+ <FormGroup
+ collapsible={false}
+ extra={headerNode === undefined ? <ShareButton /> : undefined}
+ gap={16}
+ variant={'filled'}
+ title={
+ headerNode === undefined ? (
+ <Welcome mobile={mobile} />
+ ) : headerNode === false ? undefined : (
+ headerNode
+ )
+ }
+ >
+ <Grid gap={8} maxItemWidth={150} rows={4}>
+ <TotalAssistants mobile={mobile} />
+ <TotalTopics mobile={mobile} />
+ <TotalMessages mobile={mobile} />
+ <TotalTokens />
+ </Grid>
+ <Divider dashed />
+ <AiHeatmaps mobile={mobile} />
+ <Divider dashed />
+ <Grid gap={16} rows={3} style={{ paddingBottom: 12 }}>
+ <ModelsRank />
+ <AssistantsRank mobile={mobile} />
+ <TopicsRank mobile={mobile} />
+ </Grid>
+ </FormGroup>
+ <FormGroup
+ collapsible={false}
+ gap={16}
+ title={t('tab.usage')}
+ variant={'filled'}
+ extra={
+ <>
+ <DatePicker picker="month" value={dateRange} onChange={handleDateChange} />
+ <Segmented
+ style={{ marginLeft: 8 }}
+ value={groupBy}
+ variant={'outlined'}
+ options={[
+ {
+ icon: <Icon icon={Brain} />,
+ label: t('usage.welcome.model'),
+ value: GroupBy.Model,
+ },
+ {
+ icon: <Icon icon={ProviderIcon} />,
+ label: t('usage.welcome.provider'),
+ value: GroupBy.Provider,
+ },
+ ...(enableUserDimension
+ ? [
+ {
+ icon: <Icon icon={UserIcon} />,
+ label: t('usage.welcome.user'),
+ value: GroupBy.User,
+ },
+ ]
+ : []),
+ ]}
+ onChange={(v) => setGroupBy(v as GroupBy)}
+ />
+ </>
+ }
+ styles={{
+ title: { lineHeight: '35px' },
+ }}
+ >
+ <UsageCards
+ data={data}
+ groupBy={groupBy}
+ isLoading={isLoading}
+ resolveUser={resolveUser}
+ />
+ <Divider />
+ <UsageTrends
+ data={data}
+ groupBy={groupBy}
+ isLoading={isLoading}
+ resolveUser={resolveUser}
+ />
+ <div style={{ height: 24 }} />
+ <UsageTable dateStrings={dateStrings} />
+ </FormGroup>
+ </>
+ );
+ },
+);
export default StatsSetting;
diff --git a/src/routes/(main)/settings/stats/types.ts b/src/routes/(main)/settings/stats/types.ts
index c2b1d5503d3..3309d6e112d 100644
--- a/src/routes/(main)/settings/stats/types.ts
+++ b/src/routes/(main)/settings/stats/types.ts
@@ -1,5 +1,12 @@
import { type UsageLog } from '@/types/usage/usageRecord';
+export interface UserDisplay {
+ avatar?: string | null;
+ name: string;
+}
+
+export type UserDisplayResolver = (userId: string) => UserDisplay;
+
export interface UsageChartProps {
data?: UsageLog[];
dateStrings?: string;
@@ -7,11 +14,14 @@ export interface UsageChartProps {
inShare?: boolean;
isLoading?: boolean;
mobile?: boolean;
+ /** Resolve a userId to a display name + avatar. Used by `GroupBy.User`. */
+ resolveUser?: UserDisplayResolver;
}
export enum GroupBy {
Model = 'model',
Provider = 'provider',
+ User = 'user',
}
export enum HeatmapType {
diff --git a/src/routes/(main)/settings/storage/features/Advanced.tsx b/src/routes/(main)/settings/storage/features/Advanced.tsx
index 859dde6af09..d899cbd154a 100644
--- a/src/routes/(main)/settings/storage/features/Advanced.tsx
+++ b/src/routes/(main)/settings/storage/features/Advanced.tsx
@@ -10,6 +10,7 @@ import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import AccountDeletion from '@/business/client/features/AccountDeletion';
+import { useTransferAgentsFormItem } from '@/business/client/hooks/useTransferAgentsFormItem';
import { FORM_STYLE } from '@/const/layoutTokens';
import DataImporter from '@/features/DataImporter';
import { configService } from '@/services/config';
@@ -28,6 +29,7 @@ const AdvancedActions = () => {
const { hideDocs } = useServerConfigStore(featureFlagsSelectors);
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
const checked = useUserStore(userGeneralSettingsSelectors.telemetry);
+ const transferAgentsFormItems = useTransferAgentsFormItem();
const [clearSessions, clearSessionGroups] = useSessionStore((s) => [
s.clearSessions,
s.clearSessionGroups,
@@ -165,13 +167,24 @@ const AdvancedActions = () => {
title: t('analytics.title'),
};
+ const dataMigration: FormGroupItemType | undefined = transferAgentsFormItems
+ ? {
+ children: transferAgentsFormItems,
+ title: t('storage.migration.title'),
+ }
+ : undefined;
+
return (
<>
<Form
collapsible={false}
- items={hideDocs ? [analytics, system] : [system]}
itemsType={'group'}
variant={'filled'}
+ items={[
+ ...(hideDocs ? [analytics] : []),
+ ...(dataMigration ? [dataMigration] : []),
+ system,
+ ]}
{...FORM_STYLE}
/>
{enableBusinessFeatures && <AccountDeletion />}
diff --git a/src/routes/(main)/settings/tts/features/OpenAI.tsx b/src/routes/(main)/settings/tts/features/OpenAI.tsx
index 5428b77ab27..db3c5d82b26 100644
--- a/src/routes/(main)/settings/tts/features/OpenAI.tsx
+++ b/src/routes/(main)/settings/tts/features/OpenAI.tsx
@@ -1,7 +1,7 @@
'use client';
import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon, Skeleton } from '@lobehub/ui';
+import { Form, Icon, Skeleton, Tooltip } from '@lobehub/ui';
import { Select } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { Loader2Icon } from 'lucide-react';
@@ -9,6 +9,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -16,6 +17,7 @@ import { opeanaiSTTOptions, opeanaiTTSOptions } from './const';
const OpenAI = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
const [form] = Form.useForm();
const { tts } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
@@ -27,14 +29,26 @@ const OpenAI = memo(() => {
children: [
{
children: (
- <Select options={opeanaiTTSOptions} style={{ width: 448 }} />
+ <Tooltip title={reason}>
+ <Select
+ disabled={!canManageServiceModel}
+ options={opeanaiTTSOptions}
+ style={{ width: 448 }}
+ />
+ </Tooltip>
),
label: t('settingTTS.openai.ttsModel'),
name: ['openAI', 'ttsModel'],
},
{
children: (
- <Select options={opeanaiSTTOptions} style={{ width: 448 }} />
+ <Tooltip title={reason}>
+ <Select
+ disabled={!canManageServiceModel}
+ options={opeanaiSTTOptions}
+ style={{ width: 448 }}
+ />
+ </Tooltip>
),
label: t('settingTTS.openai.sttModel'),
name: ['openAI', 'sttModel'],
@@ -53,6 +67,8 @@ const OpenAI = memo(() => {
itemsType={'group'}
variant={'filled'}
onValuesChange={async (values) => {
+ if (!canManageServiceModel) return;
+
setLoading(true);
await setSettings({
tts: values,
diff --git a/src/routes/(main)/settings/tts/features/STT.tsx b/src/routes/(main)/settings/tts/features/STT.tsx
index 7c4656c6f02..b3306de9eba 100644
--- a/src/routes/(main)/settings/tts/features/STT.tsx
+++ b/src/routes/(main)/settings/tts/features/STT.tsx
@@ -1,7 +1,7 @@
'use client';
import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon, Skeleton } from '@lobehub/ui';
+import { Form, Icon, Skeleton, Tooltip } from '@lobehub/ui';
import { Select } from '@lobehub/ui/base-ui';
import { Switch } from 'antd';
import isEqual from 'fast-deep-equal';
@@ -10,6 +10,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
+import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -17,6 +18,7 @@ import { sttOptions } from './const';
const STT = memo(() => {
const { t } = useTranslation('setting');
+ const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
const [form] = Form.useForm();
const { tts } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
@@ -27,13 +29,21 @@ const STT = memo(() => {
const stt: FormGroupItemType = {
children: [
{
- children: <Select options={sttOptions} style={{ width: 448 }} />,
+ children: (
+ <Tooltip title={reason}>
+ <Select disabled={!canManageServiceModel} options={sttOptions} style={{ width: 448 }} />
+ </Tooltip>
+ ),
desc: t('settingTTS.sttService.desc'),
label: t('settingTTS.sttService.title'),
name: 'sttServer',
},
{
- children: <Switch />,
+ children: (
+ <Tooltip title={reason}>
+ <Switch disabled={!canManageServiceModel} />
+ </Tooltip>
+ ),
desc: t('settingTTS.sttAutoStop.desc'),
label: t('settingTTS.sttAutoStop.title'),
layout: 'horizontal',
@@ -54,6 +64,8 @@ const STT = memo(() => {
itemsType={'group'}
variant={'filled'}
onValuesChange={async (values) => {
+ if (!canManageServiceModel) return;
+
setLoading(true);
await setSettings({
tts: values,
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
index 6a2973fb2e1..eda8f7b476b 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
@@ -2,7 +2,6 @@ import { ActionIcon, DropdownMenu, Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { type ItemType } from 'antd/es/menu/interface';
-import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import {
Check,
@@ -19,6 +18,7 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/index';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { useSessionStore } from '@/store/session';
@@ -26,12 +26,6 @@ import { sessionHelpers } from '@/store/session/helpers';
import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
import { SessionDefaultGroup } from '@/types/index';
-const styles = createStaticStyles(({ css }) => ({
- modalRoot: css`
- z-index: 2000;
- `,
-}));
-
interface ActionProps {
group: string | undefined;
id: string;
@@ -42,6 +36,8 @@ interface ActionProps {
const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType, setOpen }) => {
const { t } = useTranslation('chat');
+ const { allowed: canCreate, reason: createReason } = usePermission('create_content');
+ const { allowed: canEdit, reason: editReason } = usePermission('edit_own_content');
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
@@ -73,10 +69,13 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
(
[
{
+ 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 {
@@ -85,11 +84,14 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
},
},
{
+ disabled: !canCreate,
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('duplicate', { ns: 'common' }),
+ title: createReason,
onClick: ({ domEvent }) => {
domEvent.stopPropagation();
+ if (!canCreate) return;
duplicateSession(id);
},
@@ -113,18 +115,24 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
{
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);
},
},
@@ -132,29 +140,37 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
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 () => {
@@ -175,7 +191,29 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
},
] as ItemType[]
).filter(Boolean),
- [id, pin, openAgentInNewWindow],
+ [
+ canCreate,
+ canEdit,
+ createReason,
+ duplicateSession,
+ editReason,
+ group,
+ id,
+ isDefault,
+ openAgentInNewWindow,
+ openCreateGroupModal,
+ parentType,
+ pin,
+ pinAgentGroup,
+ pinSession,
+ removeAgentGroup,
+ removeSession,
+ sessionCustomGroups,
+ sessionType,
+ t,
+ updateSessionGroup,
+ message,
+ ],
);
return (
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
index 0dace555a05..e6a0f00abaa 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx
@@ -23,7 +23,11 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const GroupItem = memo<SessionGroupItem>(({ id, name }) => {
+interface GroupItemProps extends SessionGroupItem {
+ disabled?: boolean;
+}
+
+const GroupItem = memo<GroupItemProps>(({ id, name, disabled = false }) => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
@@ -35,15 +39,25 @@ const GroupItem = memo<SessionGroupItem>(({ id, name }) => {
return (
<>
- <SortableList.DragHandle />
+ {!disabled && <SortableList.DragHandle />}
{!editing ? (
<>
<span className={styles.title}>{name}</span>
- <ActionIcon icon={PencilLine} size={'small'} onClick={() => setEditing(true)} />
<ActionIcon
+ disabled={disabled}
+ icon={PencilLine}
+ size={'small'}
+ onClick={() => {
+ if (disabled) return;
+ setEditing(true);
+ }}
+ />
+ <ActionIcon
+ disabled={disabled}
icon={Trash}
size={'small'}
onClick={() => {
+ if (disabled) return;
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
content: t('sessionGroup.confirmRemoveGroupAlert'),
@@ -67,6 +81,7 @@ const GroupItem = memo<SessionGroupItem>(({ id, name }) => {
value={name}
onEditingChange={(e) => setEditing(e)}
onChangeEnd={async (input) => {
+ if (disabled) return;
if (name !== input) {
if (!input) return;
if (input.length === 0 || input.length > 20 || input.trim() === '')
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/index.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/index.tsx
index 3d02a653bad..edde7c53253 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/index.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/ConfigGroupModal/index.tsx
@@ -6,6 +6,7 @@ import { Plus } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useSessionStore } from '@/store/session';
import { sessionGroupSelectors } from '@/store/session/selectors';
import { type SessionGroupItem } from '@/types/session';
@@ -27,6 +28,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const ConfigGroupModal = memo<ModalProps>(({ open, onCancel }) => {
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,
@@ -55,18 +58,22 @@ const ConfigGroupModal = memo<ModalProps>(({ open, onCancel }) => {
id={item.id}
justify={'space-between'}
>
- <GroupItem {...item} />
+ <GroupItem {...item} disabled={!canEdit} />
</SortableList.Item>
)}
onChange={(items: SessionGroupItem[]) => {
+ if (!canEdit) return;
updateSessionGroupSort(items);
}}
/>
<Button
block
+ disabled={!canCreate}
icon={Plus}
loading={loading}
+ title={createReason}
onClick={async () => {
+ if (!canCreate) return;
setLoading(true);
await addSessionGroup(t('sessionGroup.newGroup'));
setLoading(false);
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx
index 52b5bed9a43..0906cfe60f5 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx
@@ -5,6 +5,7 @@ import { type MouseEvent } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
@@ -15,6 +16,7 @@ interface CreateGroupModalProps extends ModalProps {
const CreateGroupModal = memo<CreateGroupModalProps>(
({ id, open, onCancel }: CreateGroupModalProps) => {
const { t } = useTranslation('chat');
+ const { allowed: canCreate } = usePermission('create_content');
const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);
const { message } = App.useApp();
@@ -30,7 +32,7 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
<Modal
allowFullscreen
destroyOnHidden
- okButtonProps={{ loading }}
+ okButtonProps={{ disabled: !canCreate, loading }}
open={open}
title={t('sessionGroup.createGroup')}
width={400}
@@ -39,6 +41,7 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
onCancel?.(e);
}}
onOk={async (e: MouseEvent<HTMLButtonElement>) => {
+ if (!canCreate) return;
if (input.length === 0 || input.length > 20 || input.trim() === '')
return message.warning(t('sessionGroup.tooLong'));
@@ -55,6 +58,7 @@ const CreateGroupModal = memo<CreateGroupModalProps>(
<Flexbox paddingBlock={16}>
<Input
autoFocus
+ disabled={!canCreate}
placeholder={t('sessionGroup.inputPlaceholder')}
value={input}
onChange={(e) => setInput(e.target.value)}
diff --git a/src/routes/(mobile)/_layout/NavBar.tsx b/src/routes/(mobile)/_layout/NavBar.tsx
index 0a95192b65c..67e5dfd1372 100644
--- a/src/routes/(mobile)/_layout/NavBar.tsx
+++ b/src/routes/(mobile)/_layout/NavBar.tsx
@@ -7,9 +7,9 @@ import { createStaticStyles } from 'antd-style';
import { Compass, MessageSquare, User } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { MOBILE_TABBAR_HEIGHT } from '@/const/layoutTokens';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import { SidebarTabKey } from '@/store/global/initialState';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -31,7 +31,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const NavBar = memo(() => {
const { t } = useTranslation('common');
const activeKey = useActiveTabKey();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { showMarket } = useServerConfigStore(featureFlagsSelectors);
@@ -64,7 +64,7 @@ const NavBar = memo(() => {
),
key: SidebarTabKey.Me,
onClick: () => {
- navigate('/me');
+ navigate('/me', { escape: true });
},
title: t('tab.me'),
},
diff --git a/src/routes/(mobile)/_layout/index.tsx b/src/routes/(mobile)/_layout/index.tsx
index e3ce6bbcabd..4b810fbe374 100644
--- a/src/routes/(mobile)/_layout/index.tsx
+++ b/src/routes/(mobile)/_layout/index.tsx
@@ -4,6 +4,7 @@ import { type FC } from 'react';
import { Suspense } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
+import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';
import Loading from '@/components/Loading/BrandTextLoading';
import { RouteMetaBridge } from '@/features/RouteMeta';
import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';
@@ -30,7 +31,7 @@ const MobileMainLayout: FC = () => {
const pathname = location.pathname;
const showNav = MOBILE_NAV_ROUTES.has(pathname);
return (
- <>
+ <WorkspaceContextSlot>
<RouteMetaBridge />
<Suspense fallback={null}>{showCloudPromotion && <CloudBanner mobile />}</Suspense>
<MarketAuthProvider isDesktop={false}>
@@ -39,7 +40,7 @@ const MobileMainLayout: FC = () => {
{showNav && <NavBar />}
</Suspense>
</MarketAuthProvider>
- </>
+ </WorkspaceContextSlot>
);
};
diff --git a/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/SystemRole.tsx b/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/SystemRole.tsx
index 50b89786fa0..b00e2cdb28a 100644
--- a/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/SystemRole.tsx
+++ b/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/SystemRole.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import AgentInfo from '@/features/AgentInfo';
import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -35,6 +36,7 @@ interface SystemRoleProps {
const SystemRole = memo(({ editing, setEditing, open, setOpen, isLoading }: SystemRoleProps) => {
const openChatSettings = useOpenChatSettings(ChatSettingsTabs.Prompt);
const { t } = useTranslation('common');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [systemRole, updateAgentConfig, meta] = useAgentStore((s) => [
agentSelectors.currentAgentSystemRole(s),
@@ -43,7 +45,7 @@ const SystemRole = memo(({ editing, setEditing, open, setOpen, isLoading }: Syst
]);
const handleOpenWithEdit = (e: MouseEvent) => {
- if (isLoading) return;
+ if (!canEdit || isLoading) return;
e.stopPropagation();
setEditing(true);
setOpen(true);
@@ -51,7 +53,7 @@ const SystemRole = memo(({ editing, setEditing, open, setOpen, isLoading }: Syst
const handleOpen = (e: MouseEvent) => {
if (isLoading) return;
- if (e.altKey) handleOpenWithEdit(e);
+ if (canEdit && e.altKey) handleOpenWithEdit(e);
setOpen(true);
};
@@ -88,14 +90,18 @@ const SystemRole = memo(({ editing, setEditing, open, setOpen, isLoading }: Syst
text={{
cancel: t('cancel'),
confirm: t('ok'),
- edit: t('edit'),
+ edit: canEdit ? t('edit') : '',
title: t('settingAgent.prompt.title', { ns: 'setting' }),
}}
- onEditingChange={setEditing}
onOpenChange={setOpen}
onChange={(e) => {
+ if (!canEdit) return;
updateAgentConfig({ systemRole: e });
}}
+ onEditingChange={(value) => {
+ if (!canEdit && value) return;
+ setEditing(value);
+ }}
/>
</Flexbox>
);
diff --git a/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/index.tsx b/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/index.tsx
index 05830c8244a..451c08ecdb5 100644
--- a/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/index.tsx
+++ b/src/routes/(mobile)/chat/features/Topic/features/AgentConfig/index.tsx
@@ -7,6 +7,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useMergeState from 'use-merge-value';
+import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
@@ -40,11 +41,12 @@ const AgentConfig = memo(() => {
});
const { t } = useTranslation('common');
+ const { allowed: canEdit } = usePermission('edit_own_content');
const isLoading = !init || isAgentConfigLoading;
const handleOpenWithEdit = (e: MouseEvent) => {
- if (isLoading) return;
+ if (!canEdit || isLoading) return;
e.stopPropagation();
setEditing(true);
@@ -58,7 +60,13 @@ const AgentConfig = memo(() => {
sessionId={sessionId}
title={<Header />}
actions={
- <ActionIcon icon={Edit} size={'small'} title={t('edit')} onClick={handleOpenWithEdit} />
+ <ActionIcon
+ disabled={!canEdit}
+ icon={Edit}
+ size={'small'}
+ title={t('edit')}
+ onClick={handleOpenWithEdit}
+ />
}
>
<SystemRole
diff --git a/src/routes/(mobile)/chat/settings/_layout/Header.tsx b/src/routes/(mobile)/chat/settings/_layout/Header.tsx
index a407680d699..fd7dfe8bb5c 100644
--- a/src/routes/(mobile)/chat/settings/_layout/Header.tsx
+++ b/src/routes/(mobile)/chat/settings/_layout/Header.tsx
@@ -3,13 +3,13 @@
import { ChatHeader } from '@lobehub/ui/mobile';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { mobileHeaderSticky } from '@/styles/mobileHeader';
const Header = memo(() => {
const { t } = useTranslation('setting');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return (
<ChatHeader
diff --git a/src/routes/(mobile)/chat/settings/index.tsx b/src/routes/(mobile)/chat/settings/index.tsx
index 1491a105573..06dd0d0c9ae 100644
--- a/src/routes/(mobile)/chat/settings/index.tsx
+++ b/src/routes/(mobile)/chat/settings/index.tsx
@@ -8,6 +8,7 @@ import MobileContentLayout from '@/components/server/MobileNavLayout';
import { useCategory } from '@/features/AgentSetting/AgentCategory/useCategory';
import AgentSettings from '@/features/AgentSetting/AgentSettings';
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';
@@ -18,6 +19,7 @@ export default memo(() => {
const [tab, setTab] = useState(ChatSettingsTabs.Prompt);
const cateItems = useCategory();
const id = useSessionStore((s) => s.activeId);
+ const { allowed: canEdit } = usePermission('edit_own_content');
const [updateAgentConfig, updateAgentMeta, config, meta] = useAgentStore((s) => [
s.updateAgentConfig,
@@ -41,6 +43,7 @@ export default memo(() => {
/>
<AgentSettings
config={config}
+ disabled={!canEdit}
id={id}
loading={isLoading}
meta={meta}
diff --git a/src/routes/(mobile)/community/(detail)/_layout/Header.tsx b/src/routes/(mobile)/community/(detail)/_layout/Header.tsx
index 110b3477191..be90b080851 100644
--- a/src/routes/(mobile)/community/(detail)/_layout/Header.tsx
+++ b/src/routes/(mobile)/community/(detail)/_layout/Header.tsx
@@ -2,13 +2,14 @@
import { ChatHeader } from '@lobehub/ui/mobile';
import { memo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { mobileHeaderSticky } from '@/styles/mobileHeader';
const Header = memo(() => {
const location = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
// Extract the path segment (assistant, model, provider, mcp)
const path = location.pathname.split('/').find(Boolean);
diff --git a/src/routes/(mobile)/community/(list)/_layout/Nav.tsx b/src/routes/(mobile)/community/(list)/_layout/Nav.tsx
index e4553945a05..69c6d2b14b6 100644
--- a/src/routes/(mobile)/community/(list)/_layout/Nav.tsx
+++ b/src/routes/(mobile)/community/(list)/_layout/Nav.tsx
@@ -5,9 +5,9 @@ import { Drawer } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import { MenuIcon } from 'lucide-react';
import { memo, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
import Menu from '@/components/Menu';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { DiscoverTab } from '@/types/discover';
import { useNav } from '../../../../(main)/community/features/useNav';
@@ -43,7 +43,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
const Nav = memo(() => {
const [open, setOpen] = useState(false);
const { items, activeKey, activeItem } = useNav();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
return (
<>
diff --git a/src/routes/(mobile)/me/(home)/features/UserBanner.tsx b/src/routes/(mobile)/me/(home)/features/UserBanner.tsx
index a2a6a233032..e820aa87017 100644
--- a/src/routes/(mobile)/me/(home)/features/UserBanner.tsx
+++ b/src/routes/(mobile)/me/(home)/features/UserBanner.tsx
@@ -2,11 +2,11 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
-import { Link } from 'react-router-dom';
import DataStatistics from '@/features/User/DataStatistics';
import UserInfo from '@/features/User/UserInfo';
import UserLoginOrSignup from '@/features/User/UserLoginOrSignup/Community';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
@@ -18,12 +18,12 @@ const UserBanner = memo(() => {
<Flexbox gap={12} paddingBlock={8}>
{isLoginWithAuth ? (
<>
- <Link style={{ color: 'inherit' }} to="/settings/profile">
+ <WorkspaceLink style={{ color: 'inherit' }} to="/settings/profile">
<UserInfo />
- </Link>
- <Link style={{ color: 'inherit' }} to="/settings/stats">
+ </WorkspaceLink>
+ <WorkspaceLink style={{ color: 'inherit' }} to="/settings/stats">
<DataStatistics paddingInline={12} />
- </Link>
+ </WorkspaceLink>
</>
) : (
<UserLoginOrSignup
diff --git a/src/routes/(mobile)/me/profile/features/Category.tsx b/src/routes/(mobile)/me/profile/features/Category.tsx
index e709674143d..05816b91912 100644
--- a/src/routes/(mobile)/me/profile/features/Category.tsx
+++ b/src/routes/(mobile)/me/profile/features/Category.tsx
@@ -3,17 +3,17 @@
import { ChartColumnBigIcon, LogOut, UserCircle } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { type CellProps } from '@/components/Cell';
import Cell from '@/components/Cell';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { ProfileTabs } from '@/store/global/initialState';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
const Category = memo(() => {
const [isLogin, signOut] = useUserStore((s) => [authSelectors.isLogin(s), s.logout]);
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation('auth');
const items: CellProps[] = [
{
diff --git a/src/routes/(mobile)/me/settings/features/useCategory.tsx b/src/routes/(mobile)/me/settings/features/useCategory.tsx
index 5241bb84c2e..63f361f5d41 100644
--- a/src/routes/(mobile)/me/settings/features/useCategory.tsx
+++ b/src/routes/(mobile)/me/settings/features/useCategory.tsx
@@ -18,9 +18,9 @@ import {
} from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
import { type CellProps } from '@/components/Cell';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { SettingsTabs } from '@/store/global/initialState';
import {
featureFlagsSelectors,
@@ -48,7 +48,7 @@ export interface CategoryGroup {
}
export const useCategory = (): CategoryGroup[] => {
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { t } = useTranslation(['setting', 'auth', 'subscription']);
const { hideDocs, showApiKeyManage, showProvider } = useServerConfigStore(featureFlagsSelectors);
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
diff --git a/src/routes/(mobile)/settings/_layout/Header.tsx b/src/routes/(mobile)/settings/_layout/Header.tsx
index 317f9f5f0b1..e7168132ddc 100644
--- a/src/routes/(mobile)/settings/_layout/Header.tsx
+++ b/src/routes/(mobile)/settings/_layout/Header.tsx
@@ -4,8 +4,9 @@ import { Flexbox } from '@lobehub/ui';
import { ChatHeader } from '@lobehub/ui/mobile';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';
import { SettingsTabs } from '@/store/global/initialState';
import { useSessionStore } from '@/store/session';
@@ -30,7 +31,7 @@ const TAB_TITLE_KEY: Partial<Record<SettingsTabs, string>> = {
const Header = memo(() => {
const { t } = useTranslation(['setting', 'auth', 'subscription']);
const showMobileWorkspace = useShowMobileWorkspace();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ providerId?: string; tab?: string }>();
const isSessionActive = useSessionStore((s) => !!s.activeId);
@@ -40,9 +41,9 @@ const Header = memo(() => {
if (isSessionActive && showMobileWorkspace) {
navigate('/agent');
} else if (isProvider) {
- navigate('/settings/provider/all');
+ navigate('/settings/provider/all', { escape: true });
} else {
- navigate('/me/settings');
+ navigate('/me/settings', { escape: true });
}
};
diff --git a/src/routes/(mobile)/settings/provider/_layout/index.tsx b/src/routes/(mobile)/settings/provider/_layout/index.tsx
index 599f707d972..e93a3fada97 100644
--- a/src/routes/(mobile)/settings/provider/_layout/index.tsx
+++ b/src/routes/(mobile)/settings/provider/_layout/index.tsx
@@ -1,12 +1,14 @@
'use client';
-import { Outlet, useNavigate, useParams } from 'react-router-dom';
+import { Outlet, useParams } from 'react-router-dom';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import ProviderMenu from '../../../../(main)/settings/provider/ProviderMenu';
const Layout = () => {
const params = useParams<{ providerId: string }>();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const handleProviderSelect = (providerKey: string) => {
navigate(`/settings/provider/${providerKey}`);
diff --git a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx
index 3d8bd841637..1b6ed383f5e 100644
--- a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx
+++ b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx
@@ -6,10 +6,11 @@ import { createStaticStyles, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { MoreHorizontalIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useParams } from 'react-router-dom';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
import { type SidebarAgentItem } from '@/database/repositories/home';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
@@ -157,7 +158,7 @@ const QuickChatAgentSwitcher = memo(() => {
// so we trigger the agent list fetch ourselves.
useFetchAgentList();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const { aid } = useParams<{ aid: string }>();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const items = useSwitchItems();
diff --git a/src/routes/onboarding/_layout/index.tsx b/src/routes/onboarding/_layout/index.tsx
index 16b0f245e35..4a6bbb1476d 100644
--- a/src/routes/onboarding/_layout/index.tsx
+++ b/src/routes/onboarding/_layout/index.tsx
@@ -8,11 +8,12 @@ import { Divider } from 'antd';
import { cx, useTheme } from 'antd-style';
import { type FC, type MouseEvent, type PropsWithChildren, useCallback, useEffect } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { useLocation, useNavigate } from 'react-router-dom';
+import { useLocation } from 'react-router-dom';
import { ProductLogo } from '@/components/Branding';
import LangButton from '@/features/User/UserPanel/LangButton';
import ThemeButton from '@/features/User/UserPanel/ThemeButton';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useIsDark } from '@/hooks/useIsDark';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -27,7 +28,7 @@ const OnBoardingContainer: FC<PropsWithChildren> = ({ children }) => {
const theme = useTheme();
const { t } = useTranslation('onboarding');
const { pathname, search } = useLocation();
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
// Signup flows land here with a threaded `callbackUrl`; stash it so finish
// points can restore the original target after onboarding completes.
diff --git a/src/routes/onboarding/features/ModeSelectionStep.tsx b/src/routes/onboarding/features/ModeSelectionStep.tsx
index e8fb4d207bd..80bcaec8e5e 100644
--- a/src/routes/onboarding/features/ModeSelectionStep.tsx
+++ b/src/routes/onboarding/features/ModeSelectionStep.tsx
@@ -5,8 +5,8 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';
import { Undo2Icon } from 'lucide-react';
import React, { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useIsDark } from '@/hooks/useIsDark';
import LobeMessage from '@/routes/onboarding/components/LobeMessage';
import { useUserStore } from '@/store/user';
@@ -78,7 +78,7 @@ interface ModeSelectionStepProps {
const ModeSelectionStep = memo<ModeSelectionStepProps>(({ onBack, onNext }) => {
const { t } = useTranslation('onboarding');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const isDarkMode = useIsDark();
const imageStyles = useMemo<React.CSSProperties>(
diff --git a/src/routes/share/t/[id]/features/ActionBar.tsx b/src/routes/share/t/[id]/features/ActionBar.tsx
index d484ab1a6c0..60526d7c181 100644
--- a/src/routes/share/t/[id]/features/ActionBar.tsx
+++ b/src/routes/share/t/[id]/features/ActionBar.tsx
@@ -2,10 +2,10 @@ import { Avatar, Block, Button, Center, Flexbox, Text } from '@lobehub/ui';
import { HandIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
import GroupAvatar from '@/features/GroupAvatar';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { type SharedTopicData } from '@/types/topic';
interface ActionBarProps {
@@ -88,17 +88,17 @@ const ActionBar = memo<ActionBarProps>(({ data }) => {
{renderAgentOrGroupTitle()}
</Flexbox>
<Flexbox horizontal align="center" gap={8}>
- <Link to={`/community/agent`}>
+ <WorkspaceLink to={`/community/agent`}>
<Button shape={'round'} variant={'filled'}>
{t('sharePage.actions.findMord')}
</Button>
- </Link>
+ </WorkspaceLink>
{showActions && (
- <Link to={`/community/agent/${agentMarketIdentifier}`}>
+ <WorkspaceLink to={`/community/agent/${agentMarketIdentifier}`}>
<Button icon={HandIcon} shape={'round'} type={'primary'}>
{t('sharePage.actions.tryItYourself')}
</Button>
- </Link>
+ </WorkspaceLink>
)}
</Flexbox>
</Block>
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 7873e11ec1b..f1874fc7b15 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -261,6 +261,13 @@ class AgentService {
rankAgents = async (limit?: number): Promise<AgentRankItem[]> => {
return lambdaClient.agent.rankAgents.query(limit);
};
+
+ transferAgent = async (
+ agentId: string,
+ targetWorkspaceId: string | null,
+ ): Promise<{ agentId: string; slug: string | null }> => {
+ return lambdaClient.agent.transferAgent.mutate({ agentId, targetWorkspaceId });
+ };
}
export const agentService = new AgentService();
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index a90583e75a8..b49fb1968e3 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -460,6 +460,8 @@ class ChatService {
},
provider,
});
+ const { getBusinessTrpcHeaders } = await import('@/business/client/trpc-headers');
+ Object.assign(headers as Record<string, string>, await getBusinessTrpcHeaders());
const { DEFAULT_MODEL_PROVIDER_LIST } = await import('model-bank/modelProviders');
const providerConfig = DEFAULT_MODEL_PROVIDER_LIST.find((item) => item.id === provider);
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index 27e900c39e1..168da2660bb 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -151,6 +151,13 @@ class ChatGroupService {
): Promise<{ groupId: string; supervisorAgentId: string } | null> => {
return lambdaClient.group.duplicateGroup.mutate({ groupId, newTitle });
};
+
+ transferGroup = (
+ groupId: string,
+ targetWorkspaceId: string | null,
+ ): Promise<{ groupId: string } | null> => {
+ return lambdaClient.group.transferGroup.mutate({ groupId, targetWorkspaceId });
+ };
}
export const chatGroupService = new ChatGroupService();
diff --git a/src/services/document/index.ts b/src/services/document/index.ts
index ab2e7eef1a6..c08619f3dd6 100644
--- a/src/services/document/index.ts
+++ b/src/services/document/index.ts
@@ -230,6 +230,17 @@ export class DocumentService {
savedAt: result.savedAt instanceof Date ? result.savedAt.toISOString() : result.savedAt,
};
}
+
+ async transferDocument(documentId: string, targetWorkspaceId: string | null): Promise<void> {
+ await lambdaClient.document.transferDocument.mutate({ documentId, targetWorkspaceId });
+ }
+
+ async copyDocumentToWorkspace(
+ documentId: string,
+ targetWorkspaceId: string | null,
+ ): Promise<{ rootId: string }> {
+ return lambdaClient.document.copyDocumentToWorkspace.mutate({ documentId, targetWorkspaceId });
+ }
}
export const documentService = new DocumentService() as DocumentService &
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index bf52589e365..81a9526b4b3 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -140,6 +140,22 @@ export class FileService {
getRecentPages = async (limit?: number) => {
return lambdaClient.file.recentPages.query({ limit });
};
+
+ transferEntity = async (
+ id: string,
+ entityType: 'document' | 'file' | 'folder',
+ targetWorkspaceId: string | null,
+ ) => {
+ return lambdaClient.file.transferEntity.mutate({ entityType, id, targetWorkspaceId });
+ };
+
+ copyEntityToWorkspace = async (
+ id: string,
+ entityType: 'document' | 'file' | 'folder',
+ targetWorkspaceId: string | null,
+ ) => {
+ return lambdaClient.file.copyEntityToWorkspace.mutate({ entityType, id, targetWorkspaceId });
+ };
}
export const fileService = new FileService();
diff --git a/src/services/knowledgeBase.ts b/src/services/knowledgeBase.ts
index df92fed3625..a7ed8c10182 100644
--- a/src/services/knowledgeBase.ts
+++ b/src/services/knowledgeBase.ts
@@ -22,6 +22,17 @@ class KnowledgeBaseService {
return lambdaClient.knowledgeBase.removeKnowledgeBase.mutate({ id });
};
+ transferKnowledgeBase = async (id: string, targetWorkspaceId: string | null) => {
+ return lambdaClient.knowledgeBase.transferKnowledgeBase.mutate({ id, targetWorkspaceId });
+ };
+
+ copyKnowledgeBaseToWorkspace = async (id: string, targetWorkspaceId: string | null) => {
+ return lambdaClient.knowledgeBase.copyKnowledgeBaseToWorkspace.mutate({
+ id,
+ targetWorkspaceId,
+ });
+ };
+
addFilesToKnowledgeBase = async (knowledgeBaseId: string, ids: string[]) => {
return lambdaClient.knowledgeBase.addFilesToKnowledgeBase.mutate({ ids, knowledgeBaseId });
};
diff --git a/src/services/marketApi.ts b/src/services/marketApi.ts
index 3141bbbbd7f..fc1cb805085 100644
--- a/src/services/marketApi.ts
+++ b/src/services/marketApi.ts
@@ -34,6 +34,7 @@ export class MarketApiService {
// Create new agent
async createAgent(agentData: {
+ actAs?: number;
homepage?: string;
identifier: string;
isFeatured?: boolean;
@@ -66,6 +67,7 @@ export class MarketApiService {
// Create agent version
async createAgentVersion(versionData: {
+ actAs?: number;
a2aProtocolVersion?: string;
avatar?: string;
category?: string;
diff --git a/src/services/messenger.test.ts b/src/services/messenger.test.ts
index c4b18018ff6..33c7235324b 100644
--- a/src/services/messenger.test.ts
+++ b/src/services/messenger.test.ts
@@ -11,6 +11,7 @@ vi.mock('@/libs/trpc/client', () => ({
confirmLink: { mutate: vi.fn() },
getMyLink: { query: vi.fn() },
listAgentsForBinding: { query: vi.fn() },
+ listBindingScopes: { query: vi.fn() },
listMyInstallations: { query: vi.fn() },
listMyLinks: { query: vi.fn() },
peekLinkToken: { query: vi.fn() },
@@ -41,10 +42,22 @@ describe('messengerService', () => {
expect(messenger.peekLinkToken.query).toHaveBeenCalledWith({ randomId: 'rand-1' });
});
- it('listAgentsForBinding delegates to query', async () => {
+ it('listAgentsForBinding defaults to the personal scope (workspaceId=null)', async () => {
messenger.listAgentsForBinding.query.mockResolvedValueOnce([]);
await messengerService.listAgentsForBinding();
- expect(messenger.listAgentsForBinding.query).toHaveBeenCalledTimes(1);
+ expect(messenger.listAgentsForBinding.query).toHaveBeenCalledWith({ workspaceId: null });
+ });
+
+ it('listAgentsForBinding forwards the workspace scope', async () => {
+ messenger.listAgentsForBinding.query.mockResolvedValueOnce([]);
+ await messengerService.listAgentsForBinding('ws_1');
+ expect(messenger.listAgentsForBinding.query).toHaveBeenCalledWith({ workspaceId: 'ws_1' });
+ });
+
+ it('listBindingScopes delegates to query', async () => {
+ messenger.listBindingScopes.query.mockResolvedValueOnce([]);
+ await messengerService.listBindingScopes();
+ expect(messenger.listBindingScopes.query).toHaveBeenCalledTimes(1);
});
it('confirmLink forwards mutate params verbatim', async () => {
diff --git a/src/services/messenger.ts b/src/services/messenger.ts
index 991ab33ba4d..ce202d270a3 100644
--- a/src/services/messenger.ts
+++ b/src/services/messenger.ts
@@ -11,8 +11,12 @@ class MessengerService {
return lambdaClient.messenger.peekLinkToken.query({ randomId });
};
- listAgentsForBinding = async () => {
- return lambdaClient.messenger.listAgentsForBinding.query();
+ listAgentsForBinding = async (workspaceId?: string | null) => {
+ return lambdaClient.messenger.listAgentsForBinding.query({ workspaceId: workspaceId ?? null });
+ };
+
+ listBindingScopes = async () => {
+ return lambdaClient.messenger.listBindingScopes.query();
};
confirmLink = async (params: { initialAgentId: string; randomId: string }) => {
diff --git a/src/services/task.ts b/src/services/task.ts
index 9dedced79e8..c822db13a67 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -160,6 +160,14 @@ class TaskService {
lambdaClient.brief.resolve.mutate({ id, ...opts });
markBriefRead = async (id: string) => lambdaClient.brief.markRead.mutate({ id });
+
+ // ── Transfer / Copy ──
+
+ transferTask = async (taskId: string, targetWorkspaceId: string | null) =>
+ lambdaClient.task.transferTask.mutate({ targetWorkspaceId, taskId });
+
+ copyTaskToWorkspace = async (taskId: string, targetWorkspaceId: string | null) =>
+ lambdaClient.task.copyTaskToWorkspace.mutate({ targetWorkspaceId, taskId });
}
export const taskService = new TaskService();
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 56e8cb834bb..e27677debe2 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -25,6 +25,23 @@ import DesktopImageLayout from '@/routes/(main)/(create)/image/_layout';
import VideoPage from '@/routes/(main)/(create)/video';
import DesktopVideoLayout from '@/routes/(main)/(create)/video/_layout';
import TaskWorkspaceLayout from '@/routes/(main)/(task-workspace)/_layout';
+import WorkspaceSlugLayout from '@/routes/(main)/[workspaceSlug]/_layout';
+import WorkspaceSlugSettingsIndexPage from '@/routes/(main)/[workspaceSlug]/settings';
+import WorkspaceSlugSettingsContentLayout from '@/routes/(main)/[workspaceSlug]/settings/_content-layout';
+import WorkspaceSlugSettingsLayout from '@/routes/(main)/[workspaceSlug]/settings/_layout';
+import WorkspaceSlugSettingsApiKeyPage from '@/routes/(main)/[workspaceSlug]/settings/apikey';
+import WorkspaceSlugSettingsBillingPage from '@/routes/(main)/[workspaceSlug]/settings/billing';
+import WorkspaceSlugSettingsCreditsPage from '@/routes/(main)/[workspaceSlug]/settings/credits';
+import WorkspaceSlugSettingsCredsPage from '@/routes/(main)/[workspaceSlug]/settings/creds';
+import WorkspaceSlugSettingsGeneralPage from '@/routes/(main)/[workspaceSlug]/settings/general';
+import WorkspaceSlugSettingsMembersPage from '@/routes/(main)/[workspaceSlug]/settings/members';
+import WorkspaceSlugSettingsPlansPage from '@/routes/(main)/[workspaceSlug]/settings/plans';
+import WorkspaceSlugSettingsProviderPage from '@/routes/(main)/[workspaceSlug]/settings/provider';
+import WorkspaceSlugSettingsServiceModelPage from '@/routes/(main)/[workspaceSlug]/settings/service-model';
+import WorkspaceSlugSettingsSkillPage from '@/routes/(main)/[workspaceSlug]/settings/skill';
+import WorkspaceSlugSettingsStatsPage from '@/routes/(main)/[workspaceSlug]/settings/stats';
+import WorkspaceSlugSettingsStoragePage from '@/routes/(main)/[workspaceSlug]/settings/storage';
+import WorkspaceSlugSettingsUsagePage from '@/routes/(main)/[workspaceSlug]/settings/usage';
// Pages — sync import
import AgentPage from '@/routes/(main)/agent';
import DesktopChatLayout from '@/routes/(main)/agent/_layout';
@@ -40,9 +57,12 @@ import CommunityDetailAgentPage from '@/routes/(main)/community/(detail)/agent';
import CommunityDetailGroupAgentPage from '@/routes/(main)/community/(detail)/group_agent';
import CommunityDetailMcpPage from '@/routes/(main)/community/(detail)/mcp';
import CommunityDetailModelPage from '@/routes/(main)/community/(detail)/model';
+import CommunityDetailOrganizationPage from '@/routes/(main)/community/(detail)/organization';
import CommunityDetailProviderPage from '@/routes/(main)/community/(detail)/provider';
import CommunityDetailSkillPage from '@/routes/(main)/community/(detail)/skill';
import CommunityDetailUserPage from '@/routes/(main)/community/(detail)/user';
+import CommunityDetailWorkspacePage from '@/routes/(main)/community/(detail)/workspace';
+import CommunityDetailWorkspaceSettingsPage from '@/routes/(main)/community/(detail)/workspace/settings';
import CommunityListLayout from '@/routes/(main)/community/(list)/_layout';
import CommunityListHomePage from '@/routes/(main)/community/(list)/(home)';
import CommunityListAgentPage from '@/routes/(main)/community/(list)/agent';
@@ -95,474 +115,557 @@ import SharePagePage from '@/routes/share/page/[id]';
import ShareTopicPage from '@/routes/share/t/[id]';
import ShareTopicLayout from '@/routes/share/t/[id]/_layout';
import { routeMeta } from '@/spa/router/routeMeta';
+import { SettingsTabs } from '@/store/global/initialState';
import { ErrorBoundary, redirectElement } from '@/utils/router';
-// Desktop router configuration — all sync imports for Electron local build
-export const desktopRoutes: RouteObject[] = [
+/**
+ * Children shared between `/` and `/:workspaceSlug` for the Electron build.
+ * Mirror of the async `sharedMainAreaChildren` — paths must match (the router
+ * sync test enforces this).
+ */
+export const sharedMainAreaChildren: RouteObject[] = [
+ // Chat routes (agent)
{
children: [
- // Chat routes (agent)
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
{
children: [
- {
- element: redirectElement('/'),
- index: true,
- },
{
children: [
{
- children: [
- {
- element: <AgentPage />,
- handle: { meta: agentRouteMeta },
- index: true,
- },
- {
- element: <AgentPage />,
- handle: { meta: agentRouteMeta },
- path: ':topicId',
- },
- ],
- element: <DesktopAgentChatLayout />,
- },
- {
- element: <AgentProfilePage />,
- path: 'profile',
- },
- {
- element: <AgentChannelPage />,
- path: 'channel',
- },
- {
- element: <AgentTopicsPage />,
- path: 'topics',
+ element: <AgentPage />,
+ handle: { meta: agentRouteMeta },
+ index: true,
},
{
- element: <AgentTaskDetailRoute />,
- handle: { meta: taskRouteMeta },
- path: 'task/:taskId',
+ element: <AgentPage />,
+ handle: { meta: agentRouteMeta },
+ path: ':topicId',
},
],
- element: <DesktopChatLayout />,
- errorElement: <ErrorBoundary />,
- path: ':aid',
+ element: <DesktopAgentChatLayout />,
+ },
+ {
+ element: <AgentProfilePage />,
+ path: 'profile',
+ },
+ {
+ element: <AgentChannelPage />,
+ path: 'channel',
+ },
+ {
+ element: <AgentTopicsPage />,
+ path: 'topics',
+ },
+ {
+ element: <AgentTaskDetailRoute />,
+ handle: { meta: taskRouteMeta },
+ path: 'task/:taskId',
},
],
- path: 'agent',
+ element: <DesktopChatLayout />,
+ errorElement: <ErrorBoundary />,
+ path: ':aid',
},
+ ],
+ path: 'agent',
+ },
- // Group chat routes
+ // Group chat routes
+ {
+ children: [
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
{
children: [
{
- element: redirectElement('/'),
+ element: <GroupPage />,
+ handle: { meta: groupRouteMeta },
index: true,
},
{
- children: [
- {
- element: <GroupPage />,
- handle: { meta: groupRouteMeta },
- index: true,
- },
- {
- element: <GroupProfilePage />,
- path: 'profile',
- },
- ],
- element: <DesktopGroupLayout />,
- errorElement: <ErrorBoundary />,
- path: ':gid',
+ element: <GroupProfilePage />,
+ path: 'profile',
},
],
- path: 'group',
+ element: <DesktopGroupLayout />,
+ errorElement: <ErrorBoundary />,
+ path: ':gid',
},
+ ],
+ path: 'group',
+ },
- // Discover routes with nested structure
+ // Discover routes with nested structure
+ {
+ children: [
+ {
+ element: <CommunityDetailWorkspaceSettingsPage />,
+ path: 'workspace/settings',
+ },
+ // List routes (with ListLayout)
{
children: [
- // List routes (with ListLayout)
{
children: [
{
- children: [
- {
- element: <CommunityListAgentPage />,
- handle: {
- meta: routeMeta({
- icon: ShapesIcon,
- titleKey: 'navigation.discoverAssistants',
- }),
- },
- index: true,
- },
- ],
- element: <CommunityListAgentLayout />,
- path: 'agent',
- },
- {
- children: [
- {
- element: <CommunityListModelPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
- },
- index: true,
- },
- ],
- element: <CommunityListModelLayout />,
- path: 'model',
- },
- {
- element: <CommunityListProviderPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
- },
- path: 'provider',
- },
- {
- children: [
- {
- element: <CommunityListSkillPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
- element: <CommunityListSkillLayout />,
- path: 'skill',
- },
- {
- children: [
- {
- element: <CommunityListMcpPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
- },
- index: true,
- },
- ],
- element: <CommunityListMcpLayout />,
- path: 'mcp',
- },
- {
- element: <CommunityListHomePage />,
+ element: <CommunityListAgentPage />,
handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ meta: routeMeta({
+ icon: ShapesIcon,
+ titleKey: 'navigation.discoverAssistants',
+ }),
},
index: true,
},
],
- element: <CommunityListLayout />,
+ element: <CommunityListAgentLayout />,
+ path: 'agent',
},
- // Detail routes (with DetailLayout)
{
children: [
{
- element: <CommunityDetailAgentPage />,
- path: 'agent/:slug',
- },
- {
- element: <CommunityDetailGroupAgentPage />,
- path: 'group_agent/:slug',
- },
- {
- element: <CommunityDetailModelPage />,
- path: 'model/:slug',
- },
- {
- element: <CommunityDetailProviderPage />,
- path: 'provider/:slug',
- },
- {
- element: <CommunityDetailSkillPage />,
- path: 'skill/:slug',
- },
- {
- element: <CommunityDetailMcpPage />,
- path: 'mcp/:slug',
- },
- {
- element: <CommunityDetailUserPage />,
- path: 'user/:slug',
+ element: <CommunityListModelPage />,
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
+ },
+ index: true,
},
],
- element: <CommunityDetailLayout />,
+ element: <CommunityListModelLayout />,
+ path: 'model',
+ },
+ {
+ element: <CommunityListProviderPage />,
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
+ },
+ path: 'provider',
},
- ],
- element: <CommunityLayout />,
- errorElement: <ErrorBoundary />,
- path: 'community',
- },
-
- // Resource routes
- {
- children: [
- // Home routes (resource list)
{
children: [
{
- element: <ResourceHomePage />,
+ element: <CommunityListSkillPage />,
handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
},
index: true,
},
],
- element: <ResourceHomeLayout />,
+ element: <CommunityListSkillLayout />,
+ path: 'skill',
},
- // Library routes (knowledge base detail)
{
children: [
{
- element: <ResourceLibraryPage />,
+ element: <CommunityListMcpPage />,
handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
},
index: true,
},
- {
- element: <ResourceLibrarySlugPage />,
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- path: ':slug',
- },
],
- element: <ResourceLibraryLayout />,
- path: 'library/:id',
+ element: <CommunityListMcpLayout />,
+ path: 'mcp',
+ },
+ {
+ element: <CommunityDetailWorkspacePage />,
+ path: 'workspace',
+ },
+ {
+ element: <CommunityListHomePage />,
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ },
+ index: true,
},
],
- element: <ResourceLayout />,
- errorElement: <ErrorBoundary />,
- path: 'resource',
+ element: <CommunityListLayout />,
},
-
- // Settings routes
+ // Detail routes (with DetailLayout)
{
children: [
{
- element: redirectElement('/settings/profile'),
- index: true,
+ element: <CommunityDetailAgentPage />,
+ path: 'agent/:slug',
},
- // Provider routes with nested structure
{
- children: [
- {
- element: redirectElement('/settings/provider/all'),
- index: true,
- },
- {
- element: <ProviderDetailPage />,
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: ':providerId',
- },
- ],
- element: <ProviderLayout />,
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: 'provider',
+ element: <CommunityDetailGroupAgentPage />,
+ path: 'group_agent/:slug',
},
- // Other settings tabs
{
- element: <SettingsTabPage />,
- handle: { meta: settingsRouteMeta },
- path: ':tab',
+ element: <CommunityDetailModelPage />,
+ path: 'model/:slug',
},
- // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse
- // the same tab page; nested feature components read `:sub` via useParams.
{
- element: <SettingsTabPage />,
- handle: { meta: settingsRouteMeta },
- path: ':tab/:sub',
+ element: <CommunityDetailProviderPage />,
+ path: 'provider/:slug',
+ },
+ {
+ element: <CommunityDetailSkillPage />,
+ path: 'skill/:slug',
+ },
+ {
+ element: <CommunityDetailMcpPage />,
+ path: 'mcp/:slug',
+ },
+ {
+ element: <CommunityDetailUserPage />,
+ path: 'user/:slug',
+ },
+ {
+ element: <CommunityDetailOrganizationPage />,
+ path: 'org/:slug',
},
],
- element: <SettingsLayout />,
- errorElement: <ErrorBoundary />,
- path: 'settings',
+ element: <CommunityDetailLayout />,
},
+ ],
+ element: <CommunityLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'community',
+ },
- // Memory routes
+ // Resource routes
+ {
+ children: [
+ // Home routes (resource list)
{
children: [
{
- element: <MemoryHomePage />,
+ element: <ResourceHomePage />,
handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
},
index: true,
},
+ ],
+ element: <ResourceHomeLayout />,
+ },
+ // Library routes (knowledge base detail)
+ {
+ children: [
{
- element: <MemoryIdentitiesPage />,
+ element: <ResourceLibraryPage />,
handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
},
- path: 'identities',
+ index: true,
},
{
- element: <MemoryContextsPage />,
+ element: <ResourceLibrarySlugPage />,
handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
},
- path: 'contexts',
+ path: ':slug',
+ },
+ ],
+ element: <ResourceLibraryLayout />,
+ path: 'library/:id',
+ },
+ ],
+ element: <ResourceLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'resource',
+ },
+
+ // Memory routes
+ {
+ children: [
+ {
+ element: <MemoryHomePage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ index: true,
+ },
+ {
+ element: <MemoryIdentitiesPage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
+ },
+ path: 'identities',
+ },
+ {
+ element: <MemoryContextsPage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
+ },
+ path: 'contexts',
+ },
+ {
+ element: <MemoryPreferencesPage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
+ },
+ path: 'preferences',
+ },
+ {
+ element: <MemoryExperiencesPage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
+ },
+ path: 'experiences',
+ },
+ {
+ element: <MemoryActivitiesPage />,
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ path: 'activities',
+ },
+ ],
+ element: <DesktopMemoryLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'memory',
+ },
+
+ // Video routes
+ {
+ children: [
+ {
+ element: <VideoPage />,
+ index: true,
+ },
+ ],
+ element: <DesktopVideoLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'video',
+ },
+
+ // Image routes
+ {
+ children: [
+ {
+ element: <ImagePage />,
+ handle: {
+ meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
+ },
+ index: true,
+ },
+ ],
+ element: <DesktopImageLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'image',
+ },
+
+ ...BusinessDesktopRoutesWithMainLayout,
+
+ // Eval routes
+ {
+ children: [
+ // Home (overview)
+ {
+ children: [
+ {
+ element: <EvalOverviewPage />,
+ index: true,
},
+ ],
+ element: <EvalHomeLayout />,
+ },
+ // Bench routes (with dedicated sidebar)
+ {
+ children: [
{
- element: <MemoryPreferencesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
- },
- path: 'preferences',
+ element: <EvalBenchmarkDetailPage />,
+ index: true,
},
{
- element: <MemoryExperiencesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
- },
- path: 'experiences',
+ children: [
+ {
+ element: <EvalRunDetailPage />,
+ index: true,
+ },
+ {
+ element: <EvalCaseDetailPage />,
+ path: 'cases/:caseId',
+ },
+ ],
+ path: 'runs/:runId',
},
{
- element: <MemoryActivitiesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- path: 'activities',
+ element: <EvalDatasetDetailPage />,
+ path: 'datasets/:datasetId',
},
],
- element: <DesktopMemoryLayout />,
- errorElement: <ErrorBoundary />,
- path: 'memory',
+ element: <EvalBenchLayout />,
+ path: 'bench/:benchmarkId',
},
+ ],
+ element: <EvalLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'eval',
+ },
- // Video routes
+ // Task workspace routes (cross-agent)
+ {
+ children: [
{
children: [
{
- element: <VideoPage />,
+ element: <AllTasksPage />,
+ handle: { meta: tasksRouteMeta },
index: true,
},
],
- element: <DesktopVideoLayout />,
- errorElement: <ErrorBoundary />,
- path: 'video',
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'tasks',
},
-
- // Image routes
{
children: [
{
- element: <ImagePage />,
- handle: {
- meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
- },
- index: true,
+ element: <TaskDetailRoute />,
+ handle: { meta: taskRouteMeta },
+ path: ':taskId',
},
],
- element: <DesktopImageLayout />,
- errorElement: <ErrorBoundary />,
- path: 'image',
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'task',
},
+ ],
+ element: <TaskWorkspaceLayout />,
+ },
+
+ // Pages routes
+ {
+ children: [
+ {
+ element: <PageIndexPage />,
+ handle: {
+ meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
+ },
+ index: true,
+ },
+ {
+ element: <PageDetailPage />,
+ handle: { meta: pageRouteMeta },
+ path: ':id',
+ },
+ ],
+ element: <DesktopPageLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'page',
+ },
+];
- ...BusinessDesktopRoutesWithMainLayout,
+// Desktop router configuration — all sync imports for Electron local build
+export const desktopRoutes: RouteObject[] = [
+ {
+ children: [
+ ...sharedMainAreaChildren,
- // Eval routes
+ // Settings routes (personal-only — never mirrored under /:workspaceSlug)
{
children: [
- // Home (overview)
{
- children: [
- {
- element: <EvalOverviewPage />,
- index: true,
- },
- ],
- element: <EvalHomeLayout />,
+ element: redirectElement('/settings/profile'),
+ index: true,
},
- // Bench routes (with dedicated sidebar)
+ // Provider routes with nested structure
{
children: [
{
- element: <EvalBenchmarkDetailPage />,
+ element: redirectElement('/settings/provider/all'),
index: true,
},
{
- children: [
- {
- element: <EvalRunDetailPage />,
- index: true,
- },
- {
- element: <EvalCaseDetailPage />,
- path: 'cases/:caseId',
- },
- ],
- path: 'runs/:runId',
- },
- {
- element: <EvalDatasetDetailPage />,
- path: 'datasets/:datasetId',
+ element: <ProviderDetailPage />,
+ handle: {
+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
+ },
+ path: ':providerId',
},
],
- element: <EvalBenchLayout />,
- path: 'bench/:benchmarkId',
+ element: <ProviderLayout />,
+ handle: {
+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
+ },
+ path: 'provider',
+ },
+ {
+ element: <SettingsTabPage />,
+ handle: { settingsTab: SettingsTabs.Memory },
+ path: 'memory',
+ },
+ // Other settings tabs
+ {
+ element: <SettingsTabPage />,
+ handle: { meta: settingsRouteMeta },
+ path: ':tab',
+ },
+ // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse
+ // the same tab page; nested feature components read `:sub` via useParams.
+ {
+ element: <SettingsTabPage />,
+ handle: { meta: settingsRouteMeta },
+ path: ':tab/:sub',
},
],
- element: <EvalLayout />,
+ element: <SettingsLayout />,
errorElement: <ErrorBoundary />,
- path: 'eval',
+ path: 'settings',
},
- // Task workspace routes (cross-agent)
+ // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
{
children: [
+ // Workspace home — handled by the persistent `DesktopHomeLayout`
+ // (mirrors `/` index). Adding an element renders Home twice.
+ { index: true },
+ ...sharedMainAreaChildren,
+ // Workspace settings — `/:slug/settings/*`. Dedicated layout with
+ // its own sidebar (workspace avatar + 6 tabs + back-to-chat), fully
+ // decoupled from personal `/settings/*`.
{
children: [
+ { element: <WorkspaceSlugSettingsIndexPage />, index: true },
+ // Full-bleed tabs render directly inside the workspace settings
+ // shell (sidebar + outlet) — they own their internal layout.
+ { element: <WorkspaceSlugSettingsProviderPage />, path: 'provider' },
+ { element: <WorkspaceSlugSettingsSkillPage />, path: 'skill' },
+ // Padded tabs share a centered, max-width container layout.
{
- element: <AllTasksPage />,
- handle: { meta: tasksRouteMeta },
- index: true,
+ children: [
+ { element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },
+ { element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },
+ { element: <WorkspaceSlugSettingsStatsPage />, path: 'stats' },
+ { element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },
+ { element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },
+ { element: <WorkspaceSlugSettingsCreditsPage />, path: 'credits' },
+ { element: <WorkspaceSlugSettingsUsagePage />, path: 'usage' },
+ { element: <WorkspaceSlugSettingsServiceModelPage />, path: 'service-model' },
+ { element: <WorkspaceSlugSettingsCredsPage />, path: 'creds' },
+ { element: <WorkspaceSlugSettingsApiKeyPage />, path: 'apikey' },
+ { element: <WorkspaceSlugSettingsStoragePage />, path: 'storage' },
+ ],
+ element: <WorkspaceSlugSettingsContentLayout />,
},
],
- errorElement: <ErrorBoundary resetPath="/" />,
- path: 'tasks',
+ element: <WorkspaceSlugSettingsLayout />,
+ errorElement: <ErrorBoundary />,
+ path: 'settings',
},
+ // Legacy `/:slug/billing/*` URLs — redirect to `/:slug/settings/*`.
{
children: [
- {
- element: <TaskDetailRoute />,
- handle: { meta: taskRouteMeta },
- path: ':taskId',
- },
+ { element: redirectElement('../settings/plans'), path: 'plans' },
+ { element: redirectElement('../settings/usage'), path: 'usage' },
+ { element: redirectElement('../settings/credits'), path: 'credits' },
+ { element: redirectElement('../settings/billing'), path: 'billing' },
],
- errorElement: <ErrorBoundary resetPath="/tasks" />,
- path: 'task',
- },
- ],
- element: <TaskWorkspaceLayout />,
- },
-
- // Pages routes
- {
- children: [
- {
- element: <PageIndexPage />,
- handle: {
- meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
- },
- index: true,
- },
- {
- element: <PageDetailPage />,
- handle: { meta: pageRouteMeta },
- path: ':id',
+ path: 'billing',
},
],
- element: <DesktopPageLayout />,
+ element: <WorkspaceSlugLayout />,
errorElement: <ErrorBoundary />,
- path: 'page',
+ path: ':workspaceSlug',
},
// Default route - home page (handled by persistent layout)
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index 564b4d0e086..47ec4c4da7b 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -21,358 +21,629 @@ import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
import { routeMeta } from '@/spa/router/routeMeta';
+import { SettingsTabs } from '@/store/global/initialState';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
const agentChatElement = dynamicElement(() => import('@/routes/(main)/agent'), 'Desktop > Chat');
-// Desktop router configuration (declarative mode)
-export const desktopRoutes: RouteObject[] = [
+/**
+ * Children shared between the root tree (`/`) and the workspace tree
+ * (`/:workspaceSlug`). Personal-only segments (settings, index, catch-all,
+ * the workspace-slug block itself) are NOT included.
+ *
+ * Index redirects inside this list use **relative paths** so they resolve
+ * correctly under both `/` (→ `/`) and `/:workspaceSlug` (→ `/:workspaceSlug`).
+ */
+export const sharedMainAreaChildren: RouteObject[] = [
+ // Chat routes (agent)
{
children: [
- // Chat routes (agent)
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
{
children: [
- {
- element: redirectElement('/'),
- index: true,
- },
{
children: [
{
- children: [
- {
- element: agentChatElement,
- handle: { meta: agentRouteMeta },
- index: true,
- },
- {
- element: agentChatElement,
- handle: { meta: agentRouteMeta },
- path: ':topicId',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/agent/(chat)/_layout'),
- 'Desktop > Chat > ChatLayout',
- ),
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/profile'),
- 'Desktop > Chat > Profile',
- ),
- path: 'profile',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/channel'),
- 'Desktop > Chat > Channel',
- ),
- path: 'channel',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/topics'),
- 'Desktop > Chat > Topics',
- ),
- path: 'topics',
+ element: agentChatElement,
+ handle: { meta: agentRouteMeta },
+ index: true,
},
{
- element: dynamicElement(
- () => import('@/routes/(main)/agent/task/[taskId]'),
- 'Desktop > Chat > Task Detail',
- ),
- handle: { meta: taskRouteMeta },
- path: 'task/:taskId',
+ element: agentChatElement,
+ handle: { meta: agentRouteMeta },
+ path: ':topicId',
},
],
element: dynamicLayout(
- () => import('@/routes/(main)/agent/_layout'),
- 'Desktop > Chat > Layout',
+ () => import('@/routes/(main)/agent/(chat)/_layout'),
+ 'Desktop > Chat > ChatLayout',
),
- errorElement: <ErrorBoundary />,
- path: ':aid',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/profile'),
+ 'Desktop > Chat > Profile',
+ ),
+ path: 'profile',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/channel'),
+ 'Desktop > Chat > Channel',
+ ),
+ path: 'channel',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/topics'),
+ 'Desktop > Chat > Topics',
+ ),
+ path: 'topics',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/task/[taskId]'),
+ 'Desktop > Chat > Task Detail',
+ ),
+ handle: { meta: taskRouteMeta },
+ path: 'task/:taskId',
},
],
- path: 'agent',
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/_layout'),
+ 'Desktop > Chat > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':aid',
},
+ ],
+ path: 'agent',
+ },
- // Group chat routes
+ // Group chat routes
+ {
+ children: [
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
{
children: [
{
- element: redirectElement('/'),
+ element: dynamicElement(() => import('@/routes/(main)/group'), 'Desktop > Agent Group'),
+ handle: { meta: groupRouteMeta },
index: true,
},
{
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/group'),
- 'Desktop > Agent Group',
- ),
- handle: { meta: groupRouteMeta },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/group/profile'),
- 'Desktop > Agent Group > Profile',
- ),
- path: 'profile',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/group/_layout'),
- 'Desktop > Group > Layout',
+ element: dynamicElement(
+ () => import('@/routes/(main)/group/profile'),
+ 'Desktop > Agent Group > Profile',
),
- errorElement: <ErrorBoundary />,
- path: ':gid',
+ path: 'profile',
},
],
- path: 'group',
+ element: dynamicLayout(
+ () => import('@/routes/(main)/group/_layout'),
+ 'Desktop > Group > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':gid',
},
+ ],
+ path: 'group',
+ },
- // Discover routes with nested structure
+ // Discover routes with nested structure
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/workspace/settings'),
+ 'Desktop > Discover > Workspace > Settings',
+ ),
+ path: 'workspace/settings',
+ },
+ // List routes (with ListLayout)
{
children: [
- // List routes (with ListLayout)
{
children: [
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/agent'),
- 'Desktop > Discover > List > Agent',
- ),
- handle: {
- meta: routeMeta({
- icon: ShapesIcon,
- titleKey: 'navigation.discoverAssistants',
- }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/agent/_layout'),
- 'Desktop > Discover > List > Agent > Layout',
- ),
- path: 'agent',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/model'),
- 'Desktop > Discover > List > Model',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/model/_layout'),
- 'Desktop > Discover > List > Model > Layout',
- ),
- path: 'model',
- },
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/provider'),
- 'Desktop > Discover > List > Provider',
+ () => import('@/routes/(main)/community/(list)/agent'),
+ 'Desktop > Discover > List > Agent',
),
handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
+ meta: routeMeta({
+ icon: ShapesIcon,
+ titleKey: 'navigation.discoverAssistants',
+ }),
},
- path: 'provider',
+ index: true,
},
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/agent/_layout'),
+ 'Desktop > Discover > List > Agent > Layout',
+ ),
+ path: 'agent',
+ },
+ {
+ children: [
{
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/skill'),
- 'Desktop > Discover > List > Skill',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/skill/_layout'),
- 'Desktop > Discover > List > Skill > Layout',
+ () => import('@/routes/(main)/community/(list)/model'),
+ 'Desktop > Discover > List > Model',
),
- path: 'skill',
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
+ },
+ index: true,
},
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/model/_layout'),
+ 'Desktop > Discover > List > Model > Layout',
+ ),
+ path: 'model',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/provider'),
+ 'Desktop > Discover > List > Provider',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
+ },
+ path: 'provider',
+ },
+ {
+ children: [
{
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/mcp'),
- 'Desktop > Discover > List > MCP',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
- },
- index: true,
- },
- ],
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/mcp/_layout'),
- 'Desktop > Discover > List > MCP > Layout',
+ () => import('@/routes/(main)/community/(list)/skill'),
+ 'Desktop > Discover > List > Skill',
),
- path: 'mcp',
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ },
+ index: true,
},
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/skill/_layout'),
+ 'Desktop > Discover > List > Skill > Layout',
+ ),
+ path: 'skill',
+ },
+ {
+ children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/(home)'),
- 'Desktop > Discover > List > Home',
+ () => import('@/routes/(main)/community/(list)/mcp'),
+ 'Desktop > Discover > List > MCP',
),
handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
},
index: true,
},
],
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/_layout'),
- 'Desktop > Discover > List > Layout',
+ () => import('@/routes/(main)/community/(list)/mcp/_layout'),
+ 'Desktop > Discover > List > MCP > Layout',
+ ),
+ path: 'mcp',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/workspace'),
+ 'Desktop > Discover > List > Workspace',
+ ),
+ path: 'workspace',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/(home)'),
+ 'Desktop > Discover > List > Home',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/_layout'),
+ 'Desktop > Discover > List > Layout',
+ ),
+ },
+ // Detail routes (with DetailLayout)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/agent'),
+ 'Desktop > Discover > Detail > Agent',
+ ),
+ path: 'agent/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/group_agent'),
+ 'Desktop > Discover > Detail > Group Agent',
+ ),
+ path: 'group_agent/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/model'),
+ 'Desktop > Discover > Detail > Model',
+ ),
+ path: 'model/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/provider'),
+ 'Desktop > Discover > Detail > Provider',
+ ),
+ path: 'provider/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/skill'),
+ 'Desktop > Discover > Detail > Skill',
+ ),
+ path: 'skill/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/mcp'),
+ 'Desktop > Discover > Detail > MCP',
+ ),
+ path: 'mcp/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/user'),
+ 'Desktop > Discover > Detail > User',
+ ),
+ path: 'user/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/organization'),
+ 'Desktop > Discover > Detail > Organization',
+ ),
+ path: 'org/:slug',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/_layout'),
+ 'Desktop > Discover > Detail > Layout',
+ ),
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/_layout'),
+ 'Desktop > Discover > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'community',
+ },
+
+ // Resource routes
+ {
+ children: [
+ // Home routes (resource list)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/(home)'),
+ 'Desktop > Resource > Home',
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/(home)/_layout'),
+ 'Desktop > Resource > Home > Layout',
+ ),
+ },
+ // Library routes (knowledge base detail)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library'),
+ 'Desktop > Resource > Library',
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
+ },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library/[slug]'),
+ 'Desktop > Resource > Library > Slug',
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
+ },
+ path: ':slug',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library/_layout'),
+ 'Desktop > Resource > Library > Layout',
+ ),
+ path: 'library/:id',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/_layout'),
+ 'Desktop > Resource > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'resource',
+ },
+
+ // Memory routes
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/(home)'),
+ 'Desktop > Memory > Home',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/identities'),
+ 'Desktop > Memory > Identities',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
+ },
+ path: 'identities',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/contexts'),
+ 'Desktop > Memory > Contexts',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
+ },
+ path: 'contexts',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/preferences'),
+ 'Desktop > Memory > Preferences',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
+ },
+ path: 'preferences',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/experiences'),
+ 'Desktop > Memory > Experiences',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
+ },
+ path: 'experiences',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/activities'),
+ 'Desktop > Memory > Activities',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ path: 'activities',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/memory/_layout'),
+ 'Desktop > Memory > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'memory',
+ },
+
+ // Video routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Desktop > Video'),
+ index: true,
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(create)/video/_layout'),
+ 'Desktop > Video > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'video',
+ },
+
+ // Image routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Desktop > Image'),
+ handle: {
+ meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(create)/image/_layout'),
+ 'Desktop > Image > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'image',
+ },
+
+ ...BusinessDesktopRoutesWithMainLayout,
+
+ // Eval routes
+ {
+ children: [
+ // Home (overview)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval'),
+ 'Desktop > Eval > Overview',
+ ),
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/(home)/_layout'),
+ 'Desktop > Eval > Home > Layout',
+ ),
+ },
+ // Bench routes (with dedicated sidebar)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
+ 'Desktop > Eval > Benchmark Detail',
),
+ index: true,
},
- // Detail routes (with DetailLayout)
{
children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/agent'),
- 'Desktop > Discover > Detail > Agent',
- ),
- path: 'agent/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/group_agent'),
- 'Desktop > Discover > Detail > Group Agent',
- ),
- path: 'group_agent/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/model'),
- 'Desktop > Discover > Detail > Model',
- ),
- path: 'model/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/provider'),
- 'Desktop > Discover > Detail > Provider',
- ),
- path: 'provider/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/skill'),
- 'Desktop > Discover > Detail > Skill',
- ),
- path: 'skill/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/mcp'),
- 'Desktop > Discover > Detail > MCP',
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
+ 'Desktop > Eval > Run Detail',
),
- path: 'mcp/:slug',
+ index: true,
},
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/user'),
- 'Desktop > Discover > Detail > User',
+ () =>
+ import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
+ 'Desktop > Eval > Case Detail',
),
- path: 'user/:slug',
+ path: 'cases/:caseId',
},
],
+ path: 'runs/:runId',
+ },
+ {
element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/_layout'),
- 'Desktop > Discover > Detail > Layout',
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
+ 'Desktop > Eval > Dataset Detail',
),
+ path: 'datasets/:datasetId',
},
],
element: dynamicElement(
- () => import('@/routes/(main)/community/_layout'),
- 'Desktop > Discover > Layout',
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
+ 'Desktop > Eval > Bench > Layout',
),
- errorElement: <ErrorBoundary />,
- path: 'community',
+ path: 'bench/:benchmarkId',
},
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/_layout'),
+ 'Desktop > Eval > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'eval',
+ },
- // Resource routes
+ // Task workspace routes (cross-agent)
+ {
+ children: [
{
children: [
- // Home routes (resource list)
{
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/(home)'),
- 'Desktop > Resource > Home',
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/resource/(home)/_layout'),
- 'Desktop > Resource > Home > Layout',
- ),
+ element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks'),
+ handle: { meta: tasksRouteMeta },
+ index: true,
},
- // Library routes (knowledge base detail)
+ ],
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'tasks',
+ },
+ {
+ children: [
{
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/library'),
- 'Desktop > Resource > Library',
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/library/[slug]'),
- 'Desktop > Resource > Library > Slug',
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- path: ':slug',
- },
- ],
element: dynamicElement(
- () => import('@/routes/(main)/resource/library/_layout'),
- 'Desktop > Resource > Library > Layout',
+ () => import('@/routes/(main)/task/[taskId]'),
+ 'Desktop > Task Detail',
),
- path: 'library/:id',
+ handle: { meta: taskRouteMeta },
+ path: ':taskId',
},
],
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'task',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(task-workspace)/_layout'),
+ 'Desktop > Task Workspace > Layout',
+ ),
+ },
+
+ // Pages routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page'),
+ handle: {
+ meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
+ },
+ index: true,
+ },
+ {
element: dynamicElement(
- () => import('@/routes/(main)/resource/_layout'),
- 'Desktop > Resource > Layout',
+ () => import('@/routes/(main)/page/[id]'),
+ 'Desktop > Page > Detail',
),
- errorElement: <ErrorBoundary />,
- path: 'resource',
+ handle: { meta: pageRouteMeta },
+ path: ':id',
},
+ ],
+ element: dynamicLayout(() => import('@/routes/(main)/page/_layout'), 'Desktop > Page > Layout'),
+ errorElement: <ErrorBoundary />,
+ path: 'page',
+ },
+];
+
+// Desktop router configuration (declarative mode)
+export const desktopRoutes: RouteObject[] = [
+ {
+ children: [
+ ...sharedMainAreaChildren,
- // Settings routes
+ // Settings routes (personal-only — never mirrored under /:workspaceSlug)
{
children: [
{
@@ -407,6 +678,14 @@ export const desktopRoutes: RouteObject[] = [
},
path: 'provider',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings'),
+ 'Desktop > Settings > Memory',
+ ),
+ handle: { settingsTab: SettingsTabs.Memory },
+ path: 'memory',
+ },
// Other settings tabs
{
element: dynamicElement(
@@ -435,253 +714,154 @@ export const desktopRoutes: RouteObject[] = [
path: 'settings',
},
- // Memory routes
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/(home)'),
- 'Desktop > Memory > Home',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/identities'),
- 'Desktop > Memory > Identities',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
- },
- path: 'identities',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/contexts'),
- 'Desktop > Memory > Contexts',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
- },
- path: 'contexts',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/preferences'),
- 'Desktop > Memory > Preferences',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
- },
- path: 'preferences',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/experiences'),
- 'Desktop > Memory > Experiences',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
- },
- path: 'experiences',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/activities'),
- 'Desktop > Memory > Activities',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- path: 'activities',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/memory/_layout'),
- 'Desktop > Memory > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: 'memory',
- },
-
- // Video routes
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/(create)/video'),
- 'Desktop > Video',
- ),
- index: true,
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(create)/video/_layout'),
- 'Desktop > Video > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: 'video',
- },
-
- // Image routes
+ // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
{
children: [
+ // Workspace home — handled by the persistent `DesktopHomeLayout` at
+ // the outer main layout (mirrors how `/` index is empty here). Adding
+ // an element would render Home twice on top of `DesktopHomeLayout`.
{
- element: dynamicElement(
- () => import('@/routes/(main)/(create)/image'),
- 'Desktop > Image',
- ),
- handle: {
- meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
- },
index: true,
},
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(create)/image/_layout'),
- 'Desktop > Image > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: 'image',
- },
-
- ...BusinessDesktopRoutesWithMainLayout,
-
- // Eval routes
- {
- children: [
- // Home (overview)
+ ...sharedMainAreaChildren,
+ // Workspace settings — `/:slug/settings/*`. Dedicated layout with its
+ // own sidebar (workspace avatar + 6 tabs + back-to-chat), fully
+ // decoupled from personal `/settings/*`.
{
children: [
+ {
+ element: redirectElement('general'),
+ index: true,
+ },
+ // Full-bleed tabs render directly inside the workspace settings
+ // shell (sidebar + outlet) — they own their internal layout.
{
element: dynamicElement(
- () => import('@/routes/(main)/eval'),
- 'Desktop > Eval > Overview',
+ () => import('@/routes/(main)/[workspaceSlug]/settings/provider'),
+ 'Desktop > Workspace > Settings > Provider',
),
- index: true,
+ path: 'provider',
},
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/(home)/_layout'),
- 'Desktop > Eval > Home > Layout',
- ),
- },
- // Bench routes (with dedicated sidebar)
- {
- children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
- 'Desktop > Eval > Benchmark Detail',
+ () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),
+ 'Desktop > Workspace > Settings > Skill',
),
- index: true,
+ path: 'skill',
},
+ // Padded tabs share a centered, max-width container layout.
{
children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
- 'Desktop > Eval > Run Detail',
+ () => import('@/routes/(main)/[workspaceSlug]/settings/general'),
+ 'Desktop > Workspace > Settings > General',
+ ),
+ path: 'general',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/members'),
+ 'Desktop > Workspace > Settings > Members',
+ ),
+ path: 'members',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/stats'),
+ 'Desktop > Workspace > Settings > Stats',
+ ),
+ path: 'stats',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),
+ 'Desktop > Workspace > Settings > Plans',
+ ),
+ path: 'plans',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),
+ 'Desktop > Workspace > Settings > Billing',
+ ),
+ path: 'billing',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),
+ 'Desktop > Workspace > Settings > Credits',
+ ),
+ path: 'credits',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),
+ 'Desktop > Workspace > Settings > Usage',
+ ),
+ path: 'usage',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/service-model'),
+ 'Desktop > Workspace > Settings > Service Model',
+ ),
+ path: 'service-model',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/creds'),
+ 'Desktop > Workspace > Settings > Creds',
+ ),
+ path: 'creds',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/apikey'),
+ 'Desktop > Workspace > Settings > API Key',
),
- index: true,
+ path: 'apikey',
},
{
element: dynamicElement(
- () =>
- import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
- 'Desktop > Eval > Case Detail',
+ () => import('@/routes/(main)/[workspaceSlug]/settings/storage'),
+ 'Desktop > Workspace > Settings > Storage',
),
- path: 'cases/:caseId',
+ path: 'storage',
},
],
- path: 'runs/:runId',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
- 'Desktop > Eval > Dataset Detail',
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),
+ 'Desktop > Workspace > Settings > Content Layout',
),
- path: 'datasets/:datasetId',
},
],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
- 'Desktop > Eval > Bench > Layout',
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),
+ 'Desktop > Workspace > Settings > Layout',
),
- path: 'bench/:benchmarkId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/_layout'),
- 'Desktop > Eval > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: 'eval',
- },
-
- // Task workspace routes (cross-agent)
- {
- children: [
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks'),
- handle: { meta: tasksRouteMeta },
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath="/" />,
- path: 'tasks',
+ errorElement: <ErrorBoundary />,
+ path: 'settings',
},
+ // Legacy `/:slug/billing/*` URLs — redirect to the corresponding
+ // `/:slug/settings/*` page. Kept for deep-links and bookmarks.
{
children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/task/[taskId]'),
- 'Desktop > Task Detail',
- ),
- handle: { meta: taskRouteMeta },
- path: ':taskId',
- },
+ { element: redirectElement('../settings/plans'), path: 'plans' },
+ { element: redirectElement('../settings/usage'), path: 'usage' },
+ { element: redirectElement('../settings/credits'), path: 'credits' },
+ { element: redirectElement('../settings/billing'), path: 'billing' },
],
- errorElement: <ErrorBoundary resetPath="/tasks" />,
- path: 'task',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(task-workspace)/_layout'),
- 'Desktop > Task Workspace > Layout',
- ),
- },
-
- // Pages routes
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page'),
- handle: {
- meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/page/[id]'),
- 'Desktop > Page > Detail',
- ),
- handle: { meta: pageRouteMeta },
- path: ':id',
+ path: 'billing',
},
],
element: dynamicLayout(
- () => import('@/routes/(main)/page/_layout'),
- 'Desktop > Page > Layout',
+ () => import('@/routes/(main)/[workspaceSlug]/_layout'),
+ 'Desktop > Workspace > Layout',
),
errorElement: <ErrorBoundary />,
- path: 'page',
+ path: ':workspaceSlug',
},
// Default route - home page (handled by persistent layout)
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 8e3fbe034ca..c592244d117 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -1,8 +1,11 @@
import { readFile } from 'node:fs/promises';
import path from 'node:path';
+import { matchRoutes } from 'react-router-dom';
import { describe, expect, it } from 'vitest';
+import { desktopRoutes } from './desktopRouter.config';
+
/**
* Known path pairs that intentionally differ between web and desktop (Electron).
* Map: desktop path → web path
@@ -56,6 +59,16 @@ async function readDesktopRouterSources() {
}
describe('desktopRouter config sync', () => {
+ it('personal memory settings route is not shadowed by workspace memory route', () => {
+ const matches = matchRoutes(desktopRoutes, '/settings/memory');
+ const paths = matches?.map((match) => match.route.path);
+
+ expect(paths).toContain('settings');
+ expect(paths).not.toContain(':workspaceSlug');
+ expect(paths?.at(-1)).toBe('memory');
+ expect(matches?.at(-1)?.route.handle).toMatchObject({ settingsTab: 'memory' });
+ });
+
it('desktop (sync) route paths must match web (async) route paths', async () => {
const [asyncSource, syncSource] = await readDesktopRouterSources();
@@ -88,6 +101,37 @@ describe('desktopRouter config sync', () => {
);
});
+ it('workspace settings tree is registered with all tabs in both configs', async () => {
+ const [asyncSource, syncSource] = await readDesktopRouterSources();
+
+ const requiredImportTargets = [
+ '@/routes/(main)/[workspaceSlug]/settings/_layout',
+ '@/routes/(main)/[workspaceSlug]/settings/general',
+ '@/routes/(main)/[workspaceSlug]/settings/members',
+ '@/routes/(main)/[workspaceSlug]/settings/plans',
+ '@/routes/(main)/[workspaceSlug]/settings/billing',
+ '@/routes/(main)/[workspaceSlug]/settings/credits',
+ '@/routes/(main)/[workspaceSlug]/settings/usage',
+ '@/routes/(main)/[workspaceSlug]/settings/skill',
+ ];
+
+ for (const target of requiredImportTargets) {
+ expect(asyncSource, `async config missing ${target}`).toContain(`import('${target}')`);
+ expect(syncSource, `sync config missing ${target}`).toContain(`from '${target}'`);
+ }
+
+ // Old billing route directory is gone in both configs
+ expect(asyncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/_layout');
+ expect(asyncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/plans');
+ expect(syncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/_layout');
+ expect(syncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/plans');
+
+ // Legacy /:slug/billing/* redirects still exist (string match — the
+ // `path: 'billing'` block under `:workspaceSlug` is preserved as redirects)
+ expect(asyncSource).toContain("redirectElement('../settings/plans')");
+ expect(syncSource).toContain("redirectElement('../settings/plans')");
+ });
+
it('task list and detail desktop routes share one workspace layout', async () => {
const [asyncSource, syncSource] = await readDesktopRouterSources();
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 075f564e75e..7b928949f76 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -13,178 +13,259 @@ import {
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
-// Mobile router configuration (declarative mode)
-export const mobileRoutes: RouteObject[] = [
+/**
+ * Children shared between `/` and `/:workspaceSlug` for mobile. Mobile only
+ * mirrors the subset of routes it actually supports — settings / me / default
+ * home stay personal-only.
+ */
+export const sharedMainAreaChildren: RouteObject[] = [
+ // Chat routes
{
children: [
- // Chat routes
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
{
children: [
{
- element: redirectElement('/'),
+ element: dynamicElement(() => import('@/routes/(mobile)/chat'), 'Mobile > Chat'),
+ handle: { meta: agentRouteMeta },
index: true,
},
{
- children: [
- {
- element: dynamicElement(() => import('@/routes/(mobile)/chat'), 'Mobile > Chat'),
- handle: { meta: agentRouteMeta },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(mobile)/chat'),
- 'Mobile > Chat > Topic',
- ),
- handle: { meta: agentRouteMeta },
- path: ':topicId',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(mobile)/chat/settings'),
- 'Mobile > Chat > Settings',
- ),
- handle: { meta: mobileAgentSettingsRouteMeta },
- path: 'settings',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(mobile)/chat/_layout'),
- 'Mobile > Chat > Layout',
+ element: dynamicElement(
+ () => import('@/routes/(mobile)/chat'),
+ 'Mobile > Chat > Topic',
),
- errorElement: <ErrorBoundary />,
- path: ':aid',
+ handle: { meta: agentRouteMeta },
+ path: ':topicId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(mobile)/chat/settings'),
+ 'Mobile > Chat > Settings',
+ ),
+ handle: { meta: mobileAgentSettingsRouteMeta },
+ path: 'settings',
},
],
- path: 'agent',
+ element: dynamicLayout(
+ () => import('@/routes/(mobile)/chat/_layout'),
+ 'Mobile > Chat > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':aid',
},
+ ],
+ path: 'agent',
+ },
- // Discover routes with nested structure
+ // Discover routes with nested structure
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/workspace/settings'),
+ 'Mobile > Discover > Workspace > Settings',
+ ),
+ path: 'workspace/settings',
+ },
+ // List routes (with ListLayout)
{
children: [
- // List routes (with ListLayout)
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/(home)'),
+ 'Mobile > Discover > List > Home',
+ ),
+ index: true,
+ },
{
children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/(home)'),
- 'Mobile > Discover > List > Home',
+ () => import('@/routes/(main)/community/(list)/agent'),
+ 'Mobile > Discover > List > Agent',
),
- index: true,
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/agent'),
- 'Mobile > Discover > List > Agent',
- ),
- path: 'agent',
- },
- ],
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/model'),
- 'Mobile > Discover > List > Model',
- ),
- path: 'model',
- },
- ],
+ path: 'agent',
},
+ ],
+ },
+ {
+ children: [
{
element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/provider'),
- 'Mobile > Discover > List > Provider',
+ () => import('@/routes/(main)/community/(list)/model'),
+ 'Mobile > Discover > List > Model',
),
- path: 'provider',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/mcp'),
- 'Mobile > Discover > List > MCP',
- ),
- path: 'mcp',
- },
- ],
+ path: 'model',
},
],
+ },
+ {
element: dynamicElement(
- () => import('@/routes/(mobile)/community/(list)/_layout'),
- 'Mobile > Discover > List > Layout',
+ () => import('@/routes/(main)/community/(list)/provider'),
+ 'Mobile > Discover > List > Provider',
),
+ path: 'provider',
},
- // Detail routes (with DetailLayout)
{
children: [
{
element: dynamicElement(
- () =>
- import('@/routes/(main)/community/(detail)/agent').then(
- (m) => m.MobileDiscoverAssistantDetailPage,
- ),
- 'Mobile > Discover > Detail > Agent',
+ () => import('@/routes/(main)/community/(list)/mcp'),
+ 'Mobile > Discover > List > MCP',
),
- path: 'agent/:slug',
+ path: 'mcp',
},
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/community/(detail)/model').then(
- (m) => m.MobileModelPage,
- ),
- 'Mobile > Discover > Detail > Model',
+ ],
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/community/(detail)/workspace').then(
+ (m) => m.MobileWorkspaceDetailPage,
),
- path: 'model/:slug',
- },
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/community/(detail)/provider').then(
- (m) => m.MobileProviderPage,
- ),
- 'Mobile > Discover > Detail > Provider',
+ 'Mobile > Discover > List > Workspace',
+ ),
+ path: 'workspace',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(mobile)/community/(list)/_layout'),
+ 'Mobile > Discover > List > Layout',
+ ),
+ },
+ // Detail routes (with DetailLayout)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/community/(detail)/agent').then(
+ (m) => m.MobileDiscoverAssistantDetailPage,
),
- path: 'provider/:slug',
- },
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/community/(detail)/mcp').then((m) => m.MobileMcpPage),
- 'Mobile > Discover > Detail > MCP',
+ 'Mobile > Discover > Detail > Agent',
+ ),
+ path: 'agent/:slug',
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/community/(detail)/model').then((m) => m.MobileModelPage),
+ 'Mobile > Discover > Detail > Model',
+ ),
+ path: 'model/:slug',
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/community/(detail)/provider').then(
+ (m) => m.MobileProviderPage,
),
- path: 'mcp/:slug',
- },
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/community/(detail)/user').then(
- (m) => m.MobileUserDetailPage,
- ),
- 'Mobile > Discover > Detail > User',
+ 'Mobile > Discover > Detail > Provider',
+ ),
+ path: 'provider/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/mcp').then((m) => m.MobileMcpPage),
+ 'Mobile > Discover > Detail > MCP',
+ ),
+ path: 'mcp/:slug',
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/community/(detail)/user').then(
+ (m) => m.MobileUserDetailPage,
),
- path: 'user/:slug',
- },
- ],
+ 'Mobile > Discover > Detail > User',
+ ),
+ path: 'user/:slug',
+ },
+ {
element: dynamicElement(
- () => import('@/routes/(mobile)/community/(detail)/_layout'),
- 'Mobile > Discover > Detail > Layout',
+ () =>
+ import('@/routes/(main)/community/(detail)/organization').then(
+ (m) => m.MobileOrganizationDetailPage,
+ ),
+ 'Mobile > Discover > Detail > Organization',
),
+ path: 'org/:slug',
},
],
element: dynamicElement(
- () => import('@/routes/(mobile)/community/_layout'),
- 'Mobile > Discover > Layout',
+ () => import('@/routes/(mobile)/community/(detail)/_layout'),
+ 'Mobile > Discover > Detail > Layout',
),
- errorElement: <ErrorBoundary />,
- path: 'community',
},
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(mobile)/community/_layout'),
+ 'Mobile > Discover > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'community',
+ },
+
+ // Task workspace routes (cross-agent)
+ {
+ children: [
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Mobile > Tasks'),
+ index: true,
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'tasks',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/task/[taskId]'),
+ 'Mobile > Task Detail',
+ ),
+ path: ':taskId',
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'task',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/task/[taskId]'),
+ 'Mobile > Agent Task Detail',
+ ),
+ path: ':aid/task/:taskId',
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'agent',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(task-workspace)/_layout'),
+ 'Mobile > Task Workspace > Layout',
+ ),
+ },
+
+ ...BusinessMobileRoutesWithMainLayout,
+];
+
+// Mobile router configuration (declarative mode)
+export const mobileRoutes: RouteObject[] = [
+ {
+ children: [
+ ...sharedMainAreaChildren,
- // Settings routes
+ // Settings routes (personal-only — never mirrored under /:workspaceSlug)
{
children: [
{
@@ -233,55 +314,7 @@ export const mobileRoutes: RouteObject[] = [
path: 'settings',
},
- // Task workspace routes (cross-agent)
- {
- children: [
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Mobile > Tasks'),
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath="/" />,
- path: 'tasks',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/task/[taskId]'),
- 'Mobile > Task Detail',
- ),
- path: ':taskId',
- },
- ],
- errorElement: <ErrorBoundary resetPath="/tasks" />,
- path: 'task',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/task/[taskId]'),
- 'Mobile > Agent Task Detail',
- ),
- path: ':aid/task/:taskId',
- },
- ],
- errorElement: <ErrorBoundary resetPath="/tasks" />,
- path: 'agent',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(task-workspace)/_layout'),
- 'Mobile > Task Workspace > Layout',
- ),
- },
-
- ...BusinessMobileRoutesWithMainLayout,
-
- // Me routes (mobile personal center)
+ // Me routes (mobile personal center — never mirrored under /:workspaceSlug)
{
children: [
{
@@ -348,6 +381,91 @@ export const mobileRoutes: RouteObject[] = [
),
},
+ // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
+ {
+ children: [
+ // Workspace home — handled by the persistent home layout (mirrors
+ // how `/` index is empty); rendering here would duplicate Home.
+ {
+ index: true,
+ },
+ ...sharedMainAreaChildren,
+ // Workspace settings — `/:slug/settings/*`. Mobile reuses the mobile
+ // settings chrome (header + content wrapper) for now; a dedicated
+ // mobile workspace sidebar is follow-up work.
+ {
+ children: [
+ { element: redirectElement('general'), index: true },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/general'),
+ 'Mobile > Workspace > Settings > General',
+ ),
+ path: 'general',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/members'),
+ 'Mobile > Workspace > Settings > Members',
+ ),
+ path: 'members',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),
+ 'Mobile > Workspace > Settings > Plans',
+ ),
+ path: 'plans',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),
+ 'Mobile > Workspace > Settings > Billing',
+ ),
+ path: 'billing',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),
+ 'Mobile > Workspace > Settings > Credits',
+ ),
+ path: 'credits',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),
+ 'Mobile > Workspace > Settings > Usage',
+ ),
+ path: 'usage',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(mobile)/settings/_layout'),
+ 'Mobile > Workspace > Settings > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'settings',
+ },
+ // Legacy `/:slug/billing/*` URLs — redirect to `/:slug/settings/*`.
+ {
+ children: [
+ { element: redirectElement('../settings/plans'), path: 'plans' },
+ { element: redirectElement('../settings/usage'), path: 'usage' },
+ { element: redirectElement('../settings/credits'), path: 'credits' },
+ { element: redirectElement('../settings/billing'), path: 'billing' },
+ ],
+ path: 'billing',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/_layout'),
+ 'Mobile > Workspace > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':workspaceSlug',
+ },
+
// Catch-all route
{
element: redirectElement('/'),
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index a697e66cb32..033c5afeeea 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -159,6 +159,13 @@ export class AgentSliceActionImpl {
this.#set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, 'toggleAgentPinned');
};
+ transferAgent = async (
+ agentId: string,
+ targetWorkspaceId: string | null,
+ ): Promise<{ agentId: string; slug: string | null }> => {
+ return agentService.transferAgent(agentId, targetWorkspaceId);
+ };
+
toggleAgentPlugin = async (pluginId: string, state?: boolean): Promise<void> => {
const { activeAgentId, agentMap, updateAgentConfig } = this.#get();
if (!activeAgentId) return;
diff --git a/src/store/discover/slices/social/action.test.ts b/src/store/discover/slices/social/action.test.ts
new file mode 100644
index 00000000000..66fd6d46474
--- /dev/null
+++ b/src/store/discover/slices/social/action.test.ts
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate } from '@/libs/swr';
+import type { FollowCounts } from '@/services/social';
+import { socialService } from '@/services/social';
+
+import { SocialActionImpl } from './action';
+
+vi.mock('swr', () => ({
+ default: vi.fn(),
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+}));
+
+const mutateMock = vi.mocked(mutate);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('SocialActionImpl', () => {
+ describe('follow', () => {
+ it('optimistically increments target follower count after following', async () => {
+ vi.spyOn(socialService, 'follow').mockResolvedValue();
+ const action = new SocialActionImpl(vi.fn(), vi.fn());
+
+ await action.follow(42);
+
+ expect(socialService.follow).toHaveBeenCalledWith(42);
+ expect(mutateMock).toHaveBeenCalledWith(
+ 'follow-status-42',
+ { isFollowing: true, isMutual: false },
+ { revalidate: false },
+ );
+
+ const countsCall = mutateMock.mock.calls.find(([key]) => key === 'follow-counts-42');
+ const updateCounts = countsCall?.[1] as
+ | ((current?: FollowCounts) => FollowCounts)
+ | undefined;
+
+ expect(updateCounts?.({ followersCount: 2, followingCount: 7 })).toEqual({
+ followersCount: 3,
+ followingCount: 7,
+ });
+ expect(updateCounts?.()).toEqual({ followersCount: 1, followingCount: 0 });
+ });
+ });
+
+ describe('unfollow', () => {
+ it('optimistically decrements target follower count after unfollowing', async () => {
+ vi.spyOn(socialService, 'unfollow').mockResolvedValue();
+ const action = new SocialActionImpl(vi.fn(), vi.fn());
+
+ await action.unfollow(42);
+
+ expect(socialService.unfollow).toHaveBeenCalledWith(42);
+ expect(mutateMock).toHaveBeenCalledWith(
+ 'follow-status-42',
+ { isFollowing: false, isMutual: false },
+ { revalidate: false },
+ );
+
+ const countsCall = mutateMock.mock.calls.find(([key]) => key === 'follow-counts-42');
+ const updateCounts = countsCall?.[1] as
+ | ((current?: FollowCounts) => FollowCounts)
+ | undefined;
+
+ expect(updateCounts?.({ followersCount: 2, followingCount: 7 })).toEqual({
+ followersCount: 1,
+ followingCount: 7,
+ });
+ expect(updateCounts?.({ followersCount: 0, followingCount: 7 })).toEqual({
+ followersCount: 0,
+ followingCount: 7,
+ });
+ });
+ });
+});
diff --git a/src/store/discover/slices/social/action.ts b/src/store/discover/slices/social/action.ts
index 77e33a737b6..d154660d8a4 100644
--- a/src/store/discover/slices/social/action.ts
+++ b/src/store/discover/slices/social/action.ts
@@ -1,6 +1,7 @@
import { type SWRResponse } from 'swr';
-import useSWR, { mutate } from 'swr';
+import useSWR from 'swr';
+import { mutate } from '@/libs/swr';
import {
type FavoriteAgentItem,
type FavoritePluginItem,
@@ -18,6 +19,44 @@ type Setter = StoreSetter<DiscoverStore>;
export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new SocialActionImpl(set, get, _api);
+const followStatusKey = (userId: number) => `follow-status-${userId}`;
+const followCountsKey = (userId: number) => `follow-counts-${userId}`;
+
+const optimisticFollowCounts =
+ (isFollowing: boolean) =>
+ (current?: FollowCounts): FollowCounts => {
+ const followersCount = current?.followersCount ?? 0;
+
+ return {
+ followersCount: isFollowing ? followersCount + 1 : Math.max(0, followersCount - 1),
+ followingCount: current?.followingCount ?? 0,
+ };
+ };
+
+const updateFollowCaches = async (followingId: number, isFollowing: boolean) => {
+ await Promise.all([
+ mutate(
+ followStatusKey(followingId),
+ {
+ isFollowing,
+ isMutual: false,
+ } satisfies FollowStatus,
+ { revalidate: false },
+ ),
+ mutate(followCountsKey(followingId), optimisticFollowCounts(isFollowing), {
+ revalidate: false,
+ }),
+ mutate(
+ (key) =>
+ typeof key === 'string' && (key.startsWith('followers-') || key.startsWith('following-')),
+ undefined,
+ {
+ revalidate: true,
+ },
+ ),
+ ]);
+};
+
export class SocialActionImpl {
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
@@ -35,10 +74,7 @@ export class SocialActionImpl {
follow = async (followingId: number): Promise<void> => {
await socialService.follow(followingId);
- // Invalidate follow-related caches
- await mutate((key) => typeof key === 'string' && key.startsWith('follow-'), undefined, {
- revalidate: true,
- });
+ await updateFollowCaches(followingId, true);
};
removeFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
@@ -63,10 +99,7 @@ export class SocialActionImpl {
unfollow = async (followingId: number): Promise<void> => {
await socialService.unfollow(followingId);
- // Invalidate follow-related caches
- await mutate((key) => typeof key === 'string' && key.startsWith('follow-'), undefined, {
- revalidate: true,
- });
+ await updateFollowCaches(followingId, false);
};
useFavoriteAgents = (
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index 504ea222028..0d03fa7bfa7 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -2,6 +2,8 @@ import { toast } from '@lobehub/ui/base-ui';
import { act, renderHook } from '@testing-library/react';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { notification } from '@/components/AntdStaticMethods';
+
import { useFileStore as useStore } from '../../store';
vi.mock('zustand/traditional');
@@ -19,6 +21,20 @@ vi.mock('@/components/AntdStaticMethods', () => ({
},
}));
+vi.mock('i18next', () => ({
+ t: (key: string, options?: { reason?: string }) => {
+ if (key === 'upload.permissionDenied') {
+ return 'You do not have permission to upload files in this workspace.';
+ }
+
+ if (key === 'upload.uploadFailed') return 'File upload failed.';
+
+ if (key === 'upload.unknownError') return `Error reason: ${options?.reason}`;
+
+ return key;
+ },
+}));
+
beforeAll(() => {
Object.defineProperty(File.prototype, 'arrayBuffer', {
writable: true,
@@ -77,4 +93,23 @@ describe('useFileStore:chat', () => {
expect(result.current.chatUploadFileList).toEqual([]);
expect(toast.error).toHaveBeenCalledWith(expect.any(String));
});
+
+ it('shows a permission denied description when upload is rejected by RBAC', async () => {
+ const { result } = renderHook(() => useStore());
+ const file = new File(['test'], 'test.txt', { type: 'text/plain' });
+
+ vi.spyOn(result.current, 'uploadWithProgress').mockRejectedValue({
+ data: { code: 'FORBIDDEN' },
+ message: 'Missing any of: file:upload:all, file:upload:owner',
+ });
+
+ await act(async () => {
+ await result.current.uploadChatFiles([file]);
+ });
+
+ expect(notification.error).toHaveBeenCalledWith({
+ description: 'You do not have permission to upload files in this workspace.',
+ message: 'File upload failed.',
+ });
+ });
});
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index fd699373bb5..022b18709bb 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -27,6 +27,37 @@ type Setter = StoreSetter<FileStore>;
export const createFileSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
new FileActionImpl(set, get, _api);
+const getTrpcErrorCode = (error: unknown): string | undefined => {
+ if (typeof error !== 'object' || error === null || !('data' in error)) return;
+
+ const data = (error as { data?: { code?: unknown } }).data;
+ return typeof data?.code === 'string' ? data.code : undefined;
+};
+
+const getErrorMessage = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+
+ if (typeof error === 'object' && error !== null && 'message' in error) {
+ const message = (error as { message?: unknown }).message;
+ if (typeof message === 'string') return message;
+ }
+
+ return String(error);
+};
+
+const getUploadErrorDescription = (error: unknown): string => {
+ if (error === UPLOAD_NETWORK_ERROR) return t('upload.networkError', { ns: 'error' });
+
+ if (getTrpcErrorCode(error) === 'FORBIDDEN') {
+ return t('upload.permissionDenied', { ns: 'error' });
+ }
+
+ return typeof error === 'string'
+ ? error
+ : t('upload.unknownError', { ns: 'error', reason: getErrorMessage(error) });
+};
+
export class FileActionImpl {
readonly #get: () => FileStore;
readonly #set: Setter;
@@ -165,16 +196,9 @@ export class FileActionImpl {
});
} catch (error) {
// skip `UNAUTHORIZED` error
- if ((error as any)?.message !== 'UNAUTHORIZED')
+ if (getErrorMessage(error) !== 'UNAUTHORIZED')
notification.error({
- description:
- // it may be a network error or the cors error
- error === UPLOAD_NETWORK_ERROR
- ? t('upload.networkError', { ns: 'error' })
- : // or the error from the server
- typeof error === 'string'
- ? error
- : t('upload.unknownError', { ns: 'error', reason: (error as Error).message }),
+ description: getUploadErrorDescription(error),
message: t('upload.uploadFailed', { ns: 'error' }),
});
diff --git a/src/store/file/slices/resource/hooks.test.ts b/src/store/file/slices/resource/hooks.test.ts
new file mode 100644
index 00000000000..9127310db0d
--- /dev/null
+++ b/src/store/file/slices/resource/hooks.test.ts
@@ -0,0 +1,82 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ getActiveWorkspaceId,
+ useActiveWorkspaceId,
+} from '@/business/client/hooks/useActiveWorkspaceId';
+import { mutate } from '@/libs/swr';
+import type { FilesTabs } from '@/types/files';
+
+import { revalidateResources, useFetchResources } from './hooks';
+
+const mocks = vi.hoisted(() => ({
+ mutate: vi.fn(),
+ queryParams: {
+ category: 'audios' as FilesTabs,
+ parentId: null,
+ showFilesInKnowledgeBase: false,
+ },
+ useClientDataSWR: vi.fn(() => ({ data: undefined })),
+ activeWorkspaceId: null as string | null,
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: mocks.mutate,
+ useClientDataSWR: mocks.useClientDataSWR,
+}));
+
+vi.mock('../../store', () => ({
+ useFileStore: {
+ getState: () => ({
+ queryParams: mocks.queryParams,
+ }),
+ },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
+ useActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
+}));
+
+describe('revalidateResources', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.activeWorkspaceId = null;
+ });
+
+ it('matches workspace-scoped resource SWR keys', async () => {
+ mocks.activeWorkspaceId = 'workspace-1';
+
+ await revalidateResources();
+
+ const [matcher] = vi.mocked(mutate).mock.calls[0] as [(key: unknown) => boolean];
+
+ expect(matcher).toEqual(expect.any(Function));
+ expect(matcher(['SWR_RESOURCES', mocks.queryParams, 'workspace-1'])).toBe(true);
+ expect(matcher(['SWR_RESOURCES', mocks.queryParams, 'workspace-2'])).toBe(false);
+ expect(matcher(['SWR_RESOURCES', mocks.queryParams])).toBe(false);
+ expect(matcher(['OTHER_KEY', mocks.queryParams, 'workspace-1'])).toBe(false);
+ expect(getActiveWorkspaceId).toHaveBeenCalled();
+ });
+});
+
+describe('useFetchResources', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.activeWorkspaceId = null;
+ });
+
+ it('scopes the resource SWR key by active workspace', () => {
+ mocks.activeWorkspaceId = 'workspace-1';
+
+ renderHook(() => useFetchResources(mocks.queryParams));
+
+ expect(mocks.useClientDataSWR).toHaveBeenCalledWith(
+ ['SWR_RESOURCES', mocks.queryParams, 'workspace-1'],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ expect(useActiveWorkspaceId).toHaveBeenCalled();
+ });
+});
diff --git a/src/store/file/slices/resource/hooks.ts b/src/store/file/slices/resource/hooks.ts
index 18cc80474cc..5f1a915d5b1 100644
--- a/src/store/file/slices/resource/hooks.ts
+++ b/src/store/file/slices/resource/hooks.ts
@@ -2,14 +2,29 @@ import { isEqual } from 'es-toolkit';
import { useEffect } from 'react';
import { shallow } from 'zustand/shallow';
+import {
+ getActiveWorkspaceId,
+ useActiveWorkspaceId,
+} from '@/business/client/hooks/useActiveWorkspaceId';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { resourceService } from '@/services/resource';
-import { type ResourceQueryParams } from '@/types/resource';
+import type { ResourceQueryParams } from '@/types/resource';
import { useFileStore } from '../../store';
import { mergeServerResourcesWithOptimistic } from './utils';
const SWR_KEY_RESOURCES = 'SWR_RESOURCES';
+type ResourceSWRKey = [typeof SWR_KEY_RESOURCES, ResourceQueryParams, string | null];
+
+const isResourceSWRKey = (
+ key: unknown,
+ queryParams: ResourceQueryParams,
+ workspaceId: string | null,
+) => {
+ if (!Array.isArray(key)) return false;
+
+ return key[0] === SWR_KEY_RESOURCES && isEqual(key[1], queryParams) && key[2] === workspaceId;
+};
/**
* Revalidate resources with current or specific query params
@@ -17,8 +32,15 @@ const SWR_KEY_RESOURCES = 'SWR_RESOURCES';
*/
export const revalidateResources = async (params?: ResourceQueryParams) => {
const queryParams = params || useFileStore.getState().queryParams;
+ const workspaceId = getActiveWorkspaceId();
if (queryParams) {
- await mutate([SWR_KEY_RESOURCES, queryParams]);
+ await mutate(
+ (key) => isResourceSWRKey(key, queryParams, workspaceId),
+ async (currentData) => currentData,
+ {
+ revalidate: true,
+ },
+ );
}
};
@@ -26,9 +48,11 @@ export const revalidateResources = async (params?: ResourceQueryParams) => {
* Custom SWR hook for fetching resources with caching and revalidation
*/
export const useFetchResources = (params: ResourceQueryParams | null, enable: any = true) => {
+ const workspaceId = useActiveWorkspaceId();
+
const swr = useClientDataSWR(
- enable && params ? [SWR_KEY_RESOURCES, params] : null,
- async ([, queryParams]: [string, ResourceQueryParams]) => {
+ enable && params ? ([SWR_KEY_RESOURCES, params, workspaceId] satisfies ResourceSWRKey) : null,
+ async ([, queryParams]: ResourceSWRKey) => {
const response = await resourceService.queryResources({
...queryParams,
limit: queryParams.limit || 50,
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 68ecaaf0fb0..dca614404f7 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -42,7 +42,7 @@ const taskKanbanHiddenColumns = (s: GlobalState): string[] =>
const taskKanbanHiddenPanelCollapsed = (s: GlobalState): boolean =>
s.status.taskKanbanHiddenPanelCollapsed ?? false;
-export const DEFAULT_HIDDEN_SECTIONS: string[] = ['memory'];
+export const DEFAULT_HIDDEN_SECTIONS: string[] = [];
const hiddenSidebarSections = (s: GlobalState): string[] =>
s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS;
diff --git a/src/store/home/slices/group/action.ts b/src/store/home/slices/group/action.ts
index 82f14dc7d14..9e7eb28c2a3 100644
--- a/src/store/home/slices/group/action.ts
+++ b/src/store/home/slices/group/action.ts
@@ -1,6 +1,6 @@
+import { stableWorkspaceAwareNavigate } from '@/features/Workspace/stableWorkspaceAwareNavigate';
import { type HomeStore } from '@/store/home/store';
import { type StoreSetter } from '@/store/types';
-import { getStableNavigate } from '@/utils/stableNavigate';
type Setter = StoreSetter<HomeStore>;
export const createGroupSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
@@ -14,7 +14,7 @@ export class GroupActionImpl {
}
switchToGroup = (groupId: string): void => {
- getStableNavigate()?.(`/group/${groupId}`);
+ stableWorkspaceAwareNavigate(`/group/${groupId}`);
};
}
diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.ts
index 66648a90900..4c0da7e7471 100644
--- a/src/store/home/slices/homeInput/action.ts
+++ b/src/store/home/slices/homeInput/action.ts
@@ -1,6 +1,7 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+import { stableWorkspaceAwareNavigate } from '@/features/Workspace/stableWorkspaceAwareNavigate';
import { chatGroupService } from '@/services/chatGroup';
import { documentService } from '@/services/document';
import { getAgentStoreState } from '@/store/agent';
@@ -12,7 +13,6 @@ import { useGroupProfileStore } from '@/store/groupProfile';
import { type HomeStore } from '@/store/home/store';
import { type StoreSetter } from '@/store/types';
import { markdownToTxt } from '@/utils/markdownToTxt';
-import { getStableNavigate } from '@/utils/stableNavigate';
import { setNamespace } from '@/utils/storeDebug';
import { type StarterMode } from './initialState';
@@ -95,7 +95,7 @@ export class HomeInputActionImpl {
}
// 3. Navigate to Agent profile page
- getStableNavigate()?.(`/agent/${result.agentId}/profile`);
+ stableWorkspaceAwareNavigate(`/agent/${result.agentId}/profile`);
// 4. Refresh agent list
this.#get().refreshAgentList();
@@ -170,7 +170,7 @@ export class HomeInputActionImpl {
}
// 5. Navigate to Group profile page
- getStableNavigate()?.(`/group/${group.id}/profile`);
+ stableWorkspaceAwareNavigate(`/group/${group.id}/profile`);
// 6. Update groupAgentBuilder's model config and send initial message.
// Hydrate first so we don't race with the group profile page's own init.
@@ -231,7 +231,7 @@ export class HomeInputActionImpl {
});
// 3. Navigate to Page
- getStableNavigate()?.(`/page/${newDoc.id}`);
+ stableWorkspaceAwareNavigate(`/page/${newDoc.id}`);
// 4. Update pageAgent's model config and send initial message. Hydrate
// first to avoid the same race the agent/group flows hit.
diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.ts
index 081c1007fcb..f71fd47a70d 100644
--- a/src/store/library/slices/crud/action.test.ts
+++ b/src/store/library/slices/crud/action.test.ts
@@ -1,14 +1,33 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { mutate } from '@/libs/swr';
import { knowledgeBaseService } from '@/services/knowledgeBase';
-import { type CreateKnowledgeBaseParams, type KnowledgeBaseItem } from '@/types/knowledgeBase';
+import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';
import { withSWR } from '~test-utils';
import { useKnowledgeBaseStore } from '../../store';
vi.mock('zustand/traditional');
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: null as string | null,
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
+ useActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
+}));
+
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const modules = await importOriginal();
+ return {
+ ...(modules as any),
+ mutate: vi.fn(),
+ };
+});
+
vi.mock('swr', async (importOriginal) => {
const modules = await importOriginal();
return {
@@ -19,6 +38,7 @@ vi.mock('swr', async (importOriginal) => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.activeWorkspaceId = null;
useKnowledgeBaseStore.setState(
{
@@ -127,12 +147,25 @@ describe('KnowledgeBaseCrudAction', () => {
it('should execute refresh without errors', async () => {
const { result } = renderHook(() => useKnowledgeBaseStore());
- // The action uses mutate internally - we just verify it doesn't throw
await expect(
act(async () => {
await result.current.refreshKnowledgeBaseList();
}),
).resolves.not.toThrow();
+
+ expect(mutate).toHaveBeenCalledWith('FETCH_KNOWLEDGE_BASE');
+ });
+
+ it('should refresh the active workspace-scoped cache key', async () => {
+ mocks.activeWorkspaceId = 'workspace-1';
+ const { result } = renderHook(() => useKnowledgeBaseStore());
+
+ await act(async () => {
+ await result.current.refreshKnowledgeBaseList();
+ });
+
+ expect(mutate).toHaveBeenCalledWith(['FETCH_KNOWLEDGE_BASE', 'workspace-1']);
+ expect(getActiveWorkspaceId).toHaveBeenCalled();
});
});
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index 104619fb29c..151c6cb4dce 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -1,10 +1,11 @@
-import { type SWRResponse } from 'swr';
+import type { SWRResponse } from 'swr';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { knowledgeBaseService } from '@/services/knowledgeBase';
-import { type KnowledgeBaseStore } from '@/store/library/store';
-import { type StoreSetter } from '@/store/types';
-import { type CreateKnowledgeBaseParams, type KnowledgeBaseItem } from '@/types/knowledgeBase';
+import type { KnowledgeBaseStore } from '@/store/library/store';
+import type { StoreSetter } from '@/store/types';
+import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';
const FETCH_KNOWLEDGE_BASE_LIST_KEY = 'FETCH_KNOWLEDGE_BASE';
const FETCH_KNOWLEDGE_BASE_ITEM_KEY = 'FETCH_KNOWLEDGE_BASE_ITEM';
@@ -44,7 +45,10 @@ export class KnowledgeBaseCrudActionImpl {
};
refreshKnowledgeBaseList = async (): Promise<void> => {
- await mutate(FETCH_KNOWLEDGE_BASE_LIST_KEY);
+ const workspaceId = getActiveWorkspaceId();
+ await mutate(
+ workspaceId ? [FETCH_KNOWLEDGE_BASE_LIST_KEY, workspaceId] : FETCH_KNOWLEDGE_BASE_LIST_KEY,
+ );
};
removeKnowledgeBase = async (id: string): Promise<void> => {
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index 32480d87ece..79e77060c4d 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -29,6 +29,7 @@ const documentItemToLobeDocument = (document: DocumentItem): LobeDocument => ({
totalCharCount: document.content?.length || 0,
totalLineCount: 0,
updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),
+ userId: document.userId,
});
const n = setNamespace('page/list');