🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf(share): open the share popover without creating a share record first (#21651)
AmAzing-c25dd90bd277
diff --git a/src/features/SharePopover/index.tsx b/src/features/SharePopover/index.tsxindex d161d3120df..5fb26a360d4 100644--- a/src/features/SharePopover/index.tsx+++ b/src/features/SharePopover/index.tsx@@ -28,24 +28,20 @@ import {WrenchIcon,} from 'lucide-react';import { type ReactNode } from 'react';-import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import { ArticleSkeleton } from '@/components/Skeleton';import { useAppOrigin } from '@/hooks/useAppOrigin';import { useIsMobile } from '@/hooks/useIsMobile';import { usePermission } from '@/hooks/usePermission';import { useTopicSharePermission } from '@/hooks/useTopicSharePermission';-import { shareKeys } from '@/libs/swr/keys';-import { topicService } from '@/services/topic';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { styles } from './style';--type Visibility = 'private' | 'link';+import { type ShareVisibility as Visibility, useTopicShare } from './useTopicShare';const PRIVACY_WARNING_ITEMS = [{ icon: WrenchIcon, labelKey: 'shareModal.popover.privacyWarning.items.toolCalls' },@@ -82,47 +78,16 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenMods.updateSystemStatus,]);- // Scoped to the topic that failed: the popover is reused across topics, so a- // sticky boolean would keep showing the error on the next one.- const [failedTopicId, setFailedTopicId] = useState<string>();const {- data: shareInfo,error: loadError,isLoading,- mutate,- } = useSWR(- activeTopicId && canShare ? shareKeys.topicInfo(activeTopicId) : null,- () => topicService.getShareInfo(activeTopicId!),- { revalidateOnFocus: false },- );-- // Auto-create share record if not exists. Surface failures (e.g. a 403 from- // the share permission gate) instead of leaving the popover on the skeleton.- // Skipped entirely when the caller cannot publish: the placeholder is of no- // use to them, and under a restricted agent the server would refuse it.- useEffect(() => {- if (isLoading || loadError || shareInfo || !activeTopicId || !canShare || !canPublishLink)- return;- // One attempt per topic — a rerender must not retry a create we know failed.- if (failedTopicId === activeTopicId) return;-- topicService- .enableSharing(activeTopicId, 'private')- .then(() => mutate())- .catch(() => setFailedTopicId(activeTopicId));- }, [- isLoading,- loadError,+ retry,+ setVisibility,shareInfo,- activeTopicId,- canShare,- canPublishLink,- failedTopicId,- mutate,- ]);+ visibility: currentVisibility,+ } = useTopicShare(activeTopicId, canShare);const shareUrl = shareInfo?.id ? `${appOrigin}/share/t/${shareInfo.id}` : '';- const currentVisibility = (shareInfo?.visibility as Visibility) || 'private';const updateVisibility = useCallback(async (visibility: Visibility) => {@@ -130,11 +95,10 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenModsetUpdating(true);try {- await topicService.updateShareVisibility(activeTopicId, visibility);- await mutate();+ const shareId = await setVisibility(visibility);// Auto-copy the share link the moment link sharing is enabled- if (visibility === 'link' && shareUrl) {- await copyToClipboard(shareUrl);+ if (visibility === 'link' && shareId) {+ await copyToClipboard(`${appOrigin}/share/t/${shareId}`);toast.success(t('shareModal.copyLinkSuccess'));} else {toast.success(t('shareModal.link.visibilityUpdated'));@@ -145,7 +109,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenModsetUpdating(false);}},- [activeTopicId, mutate, t, shareUrl],+ [activeTopicId, appOrigin, setVisibility, t],);const handleVisibilityChange = useCallback(@@ -219,12 +183,9 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenModonOpenModal?.();}, [close, onOpenModal]);- // Clearing the per-topic failure re-arms the create effect; `mutate` reruns- // the read so a transient load error clears with it.const handleRetry = useCallback(() => {- setFailedTopicId(undefined);- void mutate();- }, [mutate]);+ void retry();+ }, [retry]);if (!canShare) {return (@@ -235,7 +196,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenMod);}- if (loadError || failedTopicId === activeTopicId) {+ if (loadError) {return (<Flexbox className={styles.container} gap={8}><Text strong>{t('share', { ns: 'common' })}</Text>@@ -249,9 +210,8 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenMod);}- // Loading state. Without a share record a restricted caller still gets the- // real body (visibility defaults to private) instead of an eternal skeleton.- if (isLoading || (!shareInfo && canPublishLink)) {+ // Without a share record the body still renders: visibility defaults to private.+ if (isLoading) {return (<Flexbox className={styles.container} gap={16}><Text strong>{t('share', { ns: 'common' })}</Text>diff --git a/src/features/SharePopover/useTopicShare.test.ts b/src/features/SharePopover/useTopicShare.test.tsnew file mode 100644index 00000000000..ab2e6f9db13--- /dev/null+++ b/src/features/SharePopover/useTopicShare.test.ts@@ -0,0 +1,97 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { topicService } from '@/services/topic';++import { useTopicShare } from './useTopicShare';++vi.mock('@/services/topic', () => ({+ topicService: {+ enableSharing: vi.fn(),+ getShareInfo: vi.fn(),+ updateShareVisibility: vi.fn(),+ },+}));++const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++const renderShare = async () => {+ const hook = renderHook(() => useTopicShare('topic-1', true), { wrapper });+ await waitFor(() => expect(hook.result.current.isLoading).toBe(false));+ return hook;+};++describe('useTopicShare', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('treats a topic without a share record as private and does not create one on load', async () => {+ vi.mocked(topicService.getShareInfo).mockResolvedValue(null as any);++ const { result } = await renderShare();++ expect(result.current.visibility).toBe('private');+ expect(topicService.enableSharing).not.toHaveBeenCalled();+ });++ it('creates the share record with the requested visibility on the first change', async () => {+ vi.mocked(topicService.getShareInfo).mockResolvedValue(null as any);+ vi.mocked(topicService.enableSharing).mockResolvedValue({+ id: 'share-1',+ visibility: 'link',+ } as any);++ const { result } = await renderShare();+ let shareId: string | undefined;+ await act(async () => {+ shareId = await result.current.setVisibility('link');+ });++ expect(shareId).toBe('share-1');+ expect(topicService.enableSharing).toHaveBeenCalledWith('topic-1', 'link');+ expect(topicService.updateShareVisibility).not.toHaveBeenCalled();+ });++ it('applies the visibility when create returns a record that already existed', async () => {+ vi.mocked(topicService.getShareInfo).mockResolvedValue(null as any);+ vi.mocked(topicService.enableSharing).mockResolvedValue({+ id: 'share-1',+ visibility: 'private',+ } as any);+ vi.mocked(topicService.updateShareVisibility).mockResolvedValue({+ id: 'share-1',+ visibility: 'link',+ } as any);++ const { result } = await renderShare();+ await act(async () => {+ await result.current.setVisibility('link');+ });++ expect(topicService.updateShareVisibility).toHaveBeenCalledWith('topic-1', 'link');+ });++ it('updates an existing share record instead of creating one', async () => {+ vi.mocked(topicService.getShareInfo).mockResolvedValue({+ id: 'share-1',+ visibility: 'private',+ } as any);+ vi.mocked(topicService.updateShareVisibility).mockResolvedValue({+ id: 'share-1',+ visibility: 'link',+ } as any);++ const { result } = await renderShare();+ await waitFor(() => expect(result.current.shareInfo).toBeTruthy());+ await act(async () => {+ await result.current.setVisibility('link');+ });++ expect(topicService.updateShareVisibility).toHaveBeenCalledWith('topic-1', 'link');+ expect(topicService.enableSharing).not.toHaveBeenCalled();+ });+});diff --git a/src/features/SharePopover/useTopicShare.ts b/src/features/SharePopover/useTopicShare.tsnew file mode 100644index 00000000000..ed07a46ea99--- /dev/null+++ b/src/features/SharePopover/useTopicShare.ts@@ -0,0 +1,48 @@+import { useCallback } from 'react';+import useSWR from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { topicService } from '@/services/topic';++export type ShareVisibility = 'private' | 'link';++/**+ * Share record of a topic. A topic without a record is private: the record is+ * created on the first visibility change rather than when the share UI opens,+ * so opening it never waits on a write.+ */+export const useTopicShare = (topicId: string | undefined, enabled: boolean) => {+ const { data, error, isLoading, mutate } = useSWR(+ topicId && enabled ? shareKeys.topicInfo(topicId) : null,+ () => topicService.getShareInfo(topicId!),+ { revalidateOnFocus: false },+ );++ /** Resolves to the share id after the change. */+ const setVisibility = useCallback(+ async (visibility: ShareVisibility) => {+ if (!topicId) return;++ let record = data+ ? await topicService.updateShareVisibility(topicId, visibility)+ : await topicService.enableSharing(topicId, visibility);+ // A stale cache can miss a record created elsewhere; create then keeps+ // the existing visibility, so apply the requested one on top.+ if (record && record.visibility !== visibility)+ record = await topicService.updateShareVisibility(topicId, visibility);++ await mutate();+ return record?.id ?? data?.id;+ },+ [data, mutate, topicId],+ );++ return {+ error,+ isLoading,+ retry: mutate,+ setVisibility,+ shareInfo: data,+ visibility: (data?.visibility as ShareVisibility) || 'private',+ };+};