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.

♻️ refactor: remove webrtc sync feature flag (#9002)

Arvin Xu0924d98f5e71
diff --git a/docs/self-hosting/advanced/webrtc.mdx b/docs/self-hosting/advanced/webrtc.mdx
deleted file mode 100644
index 2eb6a7b8eca..00000000000
--- a/docs/self-hosting/advanced/webrtc.mdx
+++ /dev/null
@@ -1,86 +0,0 @@
----
-title: LobeChat WebRTC Sync - Real-Time Data Sharing
-description: >-
- Explore LobeChat's WebRTC sync for real-time data sharing and privacy without servers.
-
-tags:
- - WebRTC
- - LobeChat
- - Data Synchronization
- - Real-Time Communication
- - Peer-to-Peer
----
-
-# LobeChat WebRTC Sync
-
-## Introduction to WebRTC
-
-WebRTC (Web Real-Time Communication) is a technology that enables peer-to-peer communication between browsers. In LobeChat, we experimentally implemented real-time data synchronization between devices based on WebRTC and YJS, without relying on traditional server databases. This solution offers high privacy, zero conflicts, and provides a real-time session synchronization experience.
-
-## Configuring WebRTC for Synchronization
-
-To use the WebRTC synchronization feature in LobeChat, you need to complete the following steps:
-
-<Steps>
- ### Deploy Signaling Server
-
- Deploy a WebRTC signaling server with one click using the Zeabur platform:
-
- [![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/MY0JZG?referralCode=arvinxx)
-
- Alternatively, you can view the [source code](https://github.com/lobehub/y-webrtc-signaling) and deploy it on your own.
-
- After deployment, you will receive a URL, for example: `https://my-signaling-server.zeabur.app`.
-
- ### Enable WebRTC Sync in the Deployment Instance
-
- The WebRTC sync feature in LobeChat is hidden by default and needs to be enabled by adding the environment variable `FEATURE_FLAGS=+webrtc_sync`.
-
- ### Configure WebRTC Sync Settings in LobeChat
-
- 1. Open LobeChat settings -> Data Sync
- 2. Enter the signaling server address in the WebRTC sync section;
- 3. Set the sync channel name and password
-
- <Image alt={'LobeChat Data Sync Settings Page'} height={356} inStep src={'https://github.com/lobehub/lobe-chat/assets/28616219/bf86bf1e-87fb-4015-8587-15ff28bb9c24'} />
-
- ### Repeat the Above Configuration on Devices that Need to Sync
-
- Ensure all devices use the same signaling server, channel name, and password. Once configured, the devices should automatically start syncing data.
-</Steps>
-
-## Limitations and Known Issues
-
-Although WebRTC has the advantages of no database and flexibility, after extensive community testing, the following limitations and known issues have been identified:
-
-### Requirement for Devices to be Online Simultaneously
-
-WebRTC requires devices to be online simultaneously to synchronize, meaning changes cannot be made on one device while offline and then synced later on another device.
-
-This limitation is due to the communication nature of WebRTC. In a pure frontend, serverless scenario, data synchronization between two devices can only be achieved through peer-to-peer communication. When one device is online and the other is offline, it is impossible to determine where the data should come from. Only when both devices are online can data communication occur. This mode is more like an online chat room where everyone needs to be online to see each other's data and achieve synchronization.
-
-Therefore, in certain situations, WebRTC's pure peer-to-peer approach may not fully meet users' needs (e.g., one device is a work computer, and the other is a home computer), and there are also some issues with data synchronization.
-
-### Network Issues Leading to Sync Failures
-
-Due to the implementation mechanism of WebRTC, its peer-to-peer communication has strict network requirements. Many of our users have reported:
-
-- Syncing between PCs is possible, but syncing between a mobile device with a SIM card and a PC is not, although syncing is possible when using the same WIFI as the PC;
-- Syncing fails when switching networks.
-
-### Stability and Performance Issues
-
-- Some users have reported ICE connection failures on the Firefox browser: [WebRTC Data Sync Feedback](https://github.com/lobehub/lobe-chat/issues/1683#issuecomment-2094745907)
-- For extremely long text or large amounts of conversation records, the synchronization process may slow down or become unstable: [When the model outputs a very long conversation, the end of the conversation will contain synchronization-related content tags, leading to sync failures](https://github.com/lobehub/lobe-chat/issues/1962)
-
-## Our Recommendations
-
-Considering the above reasons, we recommend users treat the WebRTC sync feature as experimental and regularly back up important data.
-
-We have already released a more stable and user-friendly server database synchronization solution ([deployment guide](/docs/self-hosting/advanced/server-database)). We recommend users prioritize using the server database synchronization solution.
-
-<Callout type={'warning'}>
- Please note that we have officially announced the archiving of this sync feature in [PR
- 3182](https://github.com/lobehub/lobe-chat/pull/3182), and the above issues will no longer be
- considered for fixes.
-</Callout>
diff --git a/docs/self-hosting/advanced/webrtc.zh-CN.mdx b/docs/self-hosting/advanced/webrtc.zh-CN.mdx
deleted file mode 100644
index 3ddc3c4b8c8..00000000000
--- a/docs/self-hosting/advanced/webrtc.zh-CN.mdx
+++ /dev/null
@@ -1,80 +0,0 @@
----
-title: LobeChat WebRTC 同步配置指南
-description: 在 LobeChat 中实现基于 WebRTC 和 YJS 的设备间实时数据同步。了解如何配置 WebRTC 并开启同步功能,以及使用局限性和已知问题。
-tags:
- - YJS
- - 信令服务器
----
-
-# LobeChat WebRTC 同步
-
-## WebRTC 简介
-
-WebRTC (Web Real-Time Communication) 是一项实现浏览器之间点对点通信的技术。在 LobeChat 中,我们实验性地基于 WebRTC 和 YJS 实现了设备间的实时数据同步,无需依赖传统的服务器数据库。这种方案具有高度隐私性、零冲突性,并能提供实时会话同步体验。
-
-## 配置 WebRTC 并实现同步
-
-要使用 LobeChat 的 WebRTC 同步功能,需要完成以下步骤:
-
-<Steps>
- ### 部署信令服务器
-
- 使用 Zeabur 平台一键部署 WebRTC 信令服务器:
-
- [![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/MY0JZG?referralCode=arvinxx)
-
- 或者查看 [源码](https://github.com/lobehub/y-webrtc-signaling) 自行部署。
-
- 部署完成后,可以得到一个 URL,例如:`https://my-signaling-server.zeabur.app`。
-
- ### 在部署实例中开启 WebRTC 同步
-
- LobeChat 默认隐藏了 WebRTC 同步功能,需要通过添加环境变量 `FEATURE_FLAGS=+webrtc_sync` 来开启 WebRTC 同步特性。
-
- ### 配置 LobeChat 的 WebRTC 同步设置
-
- 1. 打开 LobeChat 设置 -> 数据同步
- 2. 在 WebRTC 同步中填写信令服务器地址;
- 3. 设置同步频道名称和密码
-
- <Image alt={'LobeChat 数据同步设置页'} height={356} inStep src={'https://github.com/lobehub/lobe-chat/assets/28616219/bf86bf1e-87fb-4015-8587-15ff28bb9c24'} />
-
- ### 在需要同步的设备上重复以上配置
-
- 确保所有设备使用相同的信令服务器、频道名称和密码,完成配置后,设备间应该可以开始自动同步数据。
-</Steps>
-
-## 使用局限性和已知问题
-
-虽然 WebRTC 具有无数据库、比较灵活的特性,但目前该功能经过大范围社区测试,存在以下局限性和已知问题:
-
-### 设备同时在线要求
-
-WebRTC 要求设备同时在线才能进行同步,这意味着无法在一台设备离线时在另一台设备上进行更改并稍后同步。
-
-这是 WebRTC 本身的通信特性有关系,由于在纯前端、无服务端的情况下,两个设备的数据同步只能通过点对点通信的形式达成。当一个设备在线,一个设备离线的情况下,我们无从感知数据到底应该从哪来,只有当两台设备都在线的时候,双发数据才能通信。其实这种模式更像是一个在线聊天室,大家都在线时才能看到对方的数据,然后达成同步。
-
-因此 WebRTC 这种纯点对点的方式在某些情况下并无法完全满足用户的诉求(例如一个是公司电脑,一个是家里电脑),同时也存在一些数据同步层面的问题。
-
-### 网络问题可能导致同步失败
-
-由于 WebRTC 的实现机制,其点对点通信对于网络要求非常苛刻,我们的很多用户反馈:
-
-- 在 PC 上可以互相同步、 手机 sim 卡无法和 PC 同步、但是换成和 PC 一样的 WIFI 可以和 PC 同步;
-- 任何切换网络都无法同步;
-
-### 稳定性与性能问题
-
-- 部分用户报告在 Firefox 浏览器上遇到 ICE 连接失败的问题:[WebRTC Data Sync Feedback](https://github.com/lobehub/lobe-chat/issues/1683#issuecomment-2094745907)
-- 对于超长文本或大量对话记录,同步过程可能变慢或不稳定:[当模型输出超长对话时,对话末尾会出现同步相关的内容标签,导致同步失败](https://github.com/lobehub/lobe-chat/issues/1962)
-
-## 我们的建议
-
-鉴于以上原因,我们建议用户将 WebRTC 同步功能视为实验性功能,并定期备份重要数据。
-
-目前我们已经发布了更稳定、更用户友好的服务端数据库同步方案([部署指南](/zh/docs/self-hosting/advanced/server-database)),我们建议用户优先考虑使用服务端数据库同步方案。
-
-<Callout type={'warning'}>
- 请注意,我们已经在 [PR 3182](https://github.com/lobehub/lobe-chat/pull/3182)
- 中正式宣布归档该同步特性,上述问题将不再考虑进行修复。
-</Callout>
diff --git a/package.json b/package.json
index d0db28d454b..06b370a43bd 100644
--- a/package.json
+++ b/package.json
@@ -275,10 +275,7 @@
"use-merge-value": "^1.2.0",
"uuid": "^11.1.0",
"ws": "^8.18.3",
- "y-protocols": "^1.0.6",
- "y-webrtc": "^10.3.0",
"yaml": "^2.8.1",
- "yjs": "^13.6.27",
"zod": "^3.25.76",
"zustand": "5.0.4",
"zustand-utils": "^2.1.0"
diff --git a/src/app/[variants]/(main)/(mobile)/me/settings/features/useCategory.tsx b/src/app/[variants]/(main)/(mobile)/me/settings/features/useCategory.tsx
index 8f7aa5d7386..f2b3bbdee5b 100644
--- a/src/app/[variants]/(main)/(mobile)/me/settings/features/useCategory.tsx
+++ b/src/app/[variants]/(main)/(mobile)/me/settings/features/useCategory.tsx
@@ -1,8 +1,6 @@
-import { Tag } from '@lobehub/ui';
-import { Bot, Brain, Cloudy, Info, Mic2, Settings2, Sparkles } from 'lucide-react';
+import { Bot, Brain, Info, Mic2, Settings2, Sparkles } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
import urlJoin from 'url-join';
import { CellProps } from '@/components/Cell';
@@ -13,7 +11,7 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfi
export const useCategory = () => {
const router = useRouter();
const { t } = useTranslation('setting');
- const { enableWebrtc, showLLM } = useServerConfigStore(featureFlagsSelectors);
+ const { showLLM } = useServerConfigStore(featureFlagsSelectors);
const items: CellProps[] = [
{
@@ -26,18 +24,6 @@ export const useCategory = () => {
key: SettingsTabs.SystemAgent,
label: t('tab.system-agent'),
},
- enableWebrtc && {
- icon: Cloudy,
- key: SettingsTabs.Sync,
- label: (
- <Flexbox align={'center'} gap={8} horizontal>
- {t('tab.sync')}
- <Tag bordered={false} color={'warning'}>
- {t('tab.experiment')}
- </Tag>
- </Flexbox>
- ),
- },
showLLM &&
(isDeprecatedEdition
? {
diff --git a/src/app/[variants]/(main)/chat/@session/_layout/Desktop/SessionHeader.tsx b/src/app/[variants]/(main)/chat/@session/_layout/Desktop/SessionHeader.tsx
index 87b30cd0b85..5a3c015afb4 100644
--- a/src/app/[variants]/(main)/chat/@session/_layout/Desktop/SessionHeader.tsx
+++ b/src/app/[variants]/(main)/chat/@session/_layout/Desktop/SessionHeader.tsx
@@ -9,7 +9,6 @@ import { Flexbox } from 'react-layout-kit';
import { ProductLogo } from '@/components/Branding';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import SyncStatusTag from '@/features/SyncStatusInspector';
import { useActionSWR } from '@/libs/swr';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useSessionStore } from '@/store/session';
@@ -33,7 +32,7 @@ const Header = memo(() => {
const { styles } = useStyles();
const { t } = useTranslation('chat');
const [createSession] = useSessionStore((s) => [s.createSession]);
- const { enableWebrtc, showCreateSession } = useServerConfigStore(featureFlagsSelectors);
+ const { showCreateSession } = useServerConfigStore(featureFlagsSelectors);
const { mutate, isValidating } = useActionSWR('session.createSession', () => createSession());
@@ -50,7 +49,6 @@ const Header = memo(() => {
}}
>
<ProductLogo className={styles.logo} size={36} type={'text'} />
- {enableWebrtc && <SyncStatusTag />}
</Flexbox>
<Flexbox align={'center'} gap={4} horizontal>
<TogglePanelButton />
diff --git a/src/app/[variants]/(main)/chat/@session/_layout/Mobile/SessionHeader.tsx b/src/app/[variants]/(main)/chat/@session/_layout/Mobile/SessionHeader.tsx
index 4d896594e04..a8a5519c37a 100644
--- a/src/app/[variants]/(main)/chat/@session/_layout/Mobile/SessionHeader.tsx
+++ b/src/app/[variants]/(main)/chat/@session/_layout/Mobile/SessionHeader.tsx
@@ -9,7 +9,6 @@ import { Flexbox } from 'react-layout-kit';
import { ProductLogo } from '@/components/Branding';
import { MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import SyncStatusInspector from '@/features/SyncStatusInspector';
import UserAvatar from '@/features/User/UserAvatar';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useSessionStore } from '@/store/session';
@@ -18,7 +17,7 @@ import { mobileHeaderSticky } from '@/styles/mobileHeader';
const Header = memo(() => {
const [createSession] = useSessionStore((s) => [s.createSession]);
const router = useRouter();
- const { enableWebrtc, showCreateSession } = useServerConfigStore(featureFlagsSelectors);
+ const { showCreateSession } = useServerConfigStore(featureFlagsSelectors);
return (
<ChatHeader
@@ -26,7 +25,6 @@ const Header = memo(() => {
<Flexbox align={'center'} gap={8} horizontal style={{ marginLeft: 8 }}>
<UserAvatar onClick={() => router.push('/me')} size={32} />
<ProductLogo type={'text'} />
- {enableWebrtc && <SyncStatusInspector placement={'bottom'} />}
</Flexbox>
}
right={
diff --git a/src/app/[variants]/(main)/settings/hooks/useCategory.tsx b/src/app/[variants]/(main)/settings/hooks/useCategory.tsx
index 0db070c3e31..1a1dbbdd0b4 100644
--- a/src/app/[variants]/(main)/settings/hooks/useCategory.tsx
+++ b/src/app/[variants]/(main)/settings/hooks/useCategory.tsx
@@ -1,8 +1,7 @@
-import { Icon, Tag } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
import {
Bot,
Brain,
- Cloudy,
Database,
EthernetPort,
Info,
@@ -14,7 +13,6 @@ import {
import Link from 'next/link';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
import type { MenuProps } from '@/components/Menu';
import { isDeprecatedEdition, isDesktop } from '@/const/version';
@@ -24,8 +22,7 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfi
export const useCategory = () => {
const { t } = useTranslation('setting');
const mobile = useServerConfigStore((s) => s.isMobile);
- const { enableWebrtc, showLLM, enableSTT, hideDocs } =
- useServerConfigStore(featureFlagsSelectors);
+ const { showLLM, enableSTT, hideDocs } = useServerConfigStore(featureFlagsSelectors);
const cateItems: MenuProps['items'] = useMemo(
() =>
@@ -48,21 +45,6 @@ export const useCategory = () => {
</Link>
),
},
- // TODO: remove in V2
- enableWebrtc && {
- icon: <Icon icon={Cloudy} />,
- key: SettingsTabs.Sync,
- label: (
- <Link href={'/settings/sync'} onClick={(e) => e.preventDefault()}>
- <Flexbox align={'center'} gap={8} horizontal>
- {t('tab.sync')}
- <Tag bordered={false} color={'warning'}>
- {t('tab.experiment')}
- </Tag>
- </Flexbox>
- </Link>
- ),
- },
!mobile && {
icon: <Icon icon={KeyboardIcon} />,
key: SettingsTabs.Hotkey,
@@ -146,7 +128,7 @@ export const useCategory = () => {
),
},
].filter(Boolean) as MenuProps['items'],
- [t, enableWebrtc, showLLM],
+ [t, showLLM],
);
return cateItems;
diff --git a/src/app/[variants]/(main)/settings/sync/features/Alert.tsx b/src/app/[variants]/(main)/settings/sync/features/Alert.tsx
deleted file mode 100644
index ac874376a74..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/Alert.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-'use client';
-
-import { Alert } from '@lobehub/ui';
-import Link from 'next/link';
-import { memo } from 'react';
-import { Trans } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { MAX_WIDTH } from '@/const/layoutTokens';
-import { WEBRTC_SYNC_DOCUMENTS } from '@/const/url';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-
-interface ExperimentAlertProps {
- mobile?: boolean;
-}
-const ExperimentAlert = memo<ExperimentAlertProps>(({ mobile }) => {
- const [hideSyncAlert, updatePreference] = useUserStore((s) => [
- preferenceSelectors.hideSyncAlert(s),
- s.updatePreference,
- ]);
-
- return (
- !hideSyncAlert && (
- <Flexbox style={{ maxWidth: MAX_WIDTH }} width={'100%'}>
- <Alert
- banner={mobile}
- closable
- message={
- <Trans i18nKey="sync.warning.tip" ns={'setting'}>
- 经过较长一段时间测试,WebRTC 同步可能无法稳定满足通用的数据同步诉求。请自行
- <Link
- aria-label={'Webrtc Sync deployment'}
- href={WEBRTC_SYNC_DOCUMENTS}
- style={{ color: 'inherit', textDecoration: 'underline' }}
- target="_blank"
- >
- 部署信令服务器
- </Link>
- 后使用。
- </Trans>
- }
- onClose={() => {
- updatePreference({ hideSyncAlert: true });
- }}
- type={'warning'}
- />
- </Flexbox>
- )
- );
-});
-
-export default ExperimentAlert;
diff --git a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/Card.tsx b/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/Card.tsx
deleted file mode 100644
index c474934152e..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/Card.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { createStyles } from 'antd-style';
-import { ReactNode, memo } from 'react';
-import { Center, Flexbox } from 'react-layout-kit';
-
-const useStyles = createStyles(({ css, token, responsive }) => ({
- container: css`
- border-radius: ${token.borderRadius}px;
- background: ${token.colorFillTertiary};
-
- .${responsive.mobile} {
- width: 100%;
- }
- `,
- icon: css`
- width: 24px;
- height: 24px;
- `,
- title: css`
- font-size: 16px;
- `,
-}));
-
-const Card = memo<{ icon: ReactNode; title: string }>(({ title, icon }) => {
- const { styles } = useStyles();
-
- return (
- <Flexbox
- align={'center'}
- className={styles.container}
- flex={1}
- gap={12}
- horizontal
- paddingBlock={12}
- paddingInline={20}
- >
- <Center className={styles.icon}>{icon}</Center>
- <div className={styles.title}>{title}</div>
- </Flexbox>
- );
-});
-
-export default Card;
diff --git a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/DeviceName.tsx b/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/DeviceName.tsx
deleted file mode 100644
index 95824f7e20f..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/DeviceName.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-'use client';
-
-import { EditableText, Text } from '@lobehub/ui';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useUserStore } from '@/store/user';
-import { syncSettingsSelectors } from '@/store/user/selectors';
-
-const DeviceName = memo(() => {
- const { t } = useTranslation('setting');
-
- const [deviceName, setSettings] = useUserStore((s) => [
- syncSettingsSelectors.deviceName(s),
- s.setSettings,
- ]);
-
- const [editing, setEditing] = useState(false);
-
- const updateDeviceName = (deviceName: string) => {
- setSettings({ sync: { deviceName } });
- setEditing(false);
- };
-
- return (
- <Flexbox
- align={'center'}
- flex={1}
- height={40}
- horizontal
- style={{ fontSize: 20, fontWeight: 'bold', lineHeight: 1, minWidth: 240, paddingLeft: 8 }}
- >
- {!deviceName && !editing && (
- <Flexbox
- onClick={() => {
- setEditing(true);
- }}
- style={{ cursor: 'pointer' }}
- >
- <Text type={'secondary'}>{t('sync.device.deviceName.hint')}</Text>
- </Flexbox>
- )}
- <EditableText
- editing={editing}
- inputProps={{
- placeholder: t('sync.device.deviceName.placeholder'),
- }}
- onBlur={(e) => updateDeviceName(e.target.value)}
- onChange={(e) => {
- updateDeviceName(e);
- }}
- onEditingChange={setEditing}
- size={'large'}
- value={deviceName}
- variant={'filled'}
- />
- </Flexbox>
- );
-});
-
-export default DeviceName;
diff --git a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/SystemIcon.tsx b/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/SystemIcon.tsx
deleted file mode 100644
index dc9b1ce77ee..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/SystemIcon.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import {
- SiAndroid,
- SiApple,
- SiBlackberry,
- SiGooglechrome,
- SiLinux,
- SiWindows11,
-} from '@icons-pack/react-simple-icons';
-import { memo } from 'react';
-
-const SystemIcon = memo<{ title?: string }>(({ title }) => {
- if (!title) return;
-
- if (['Mac OS', 'iOS', 'iPadOS'].includes(title)) return <SiApple size={24} />;
-
- // Remove Microsoft brands in @icons-pack/react-simple-icons v10
- // https://github.com/simple-icons/simple-icons/pull/10019
- if (['Windows'].includes(title)) return <SiWindows11 size={24} />;
-
- if (title === 'Android') return <SiAndroid size={24} />;
-
- if (['BlackBerry'].includes(title)) return <SiBlackberry size={24} />;
-
- if (title === 'Linux') return <SiLinux size={24} />;
-
- if (title === 'Chrome OS') return <SiGooglechrome size={24} />;
-
- return null;
-});
-
-export default SystemIcon;
diff --git a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/index.tsx b/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/index.tsx
deleted file mode 100644
index 8415c703a5d..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/DeviceInfo/index.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-'use client';
-
-import { Text } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { rgba } from 'polished';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { BrowserIcon } from '@/components/BrowserIcon';
-import { MAX_WIDTH } from '@/const/layoutTokens';
-
-import Card from './Card';
-import DeviceName from './DeviceName';
-import SystemIcon from './SystemIcon';
-
-const useStyles = createStyles(({ css, cx, responsive, isDarkMode, token, stylish }) => ({
- container: css`
- position: relative;
- width: 100%;
- border-radius: ${token.borderRadiusLG}px;
- `,
- content: css`
- z-index: 2;
- padding: 8px;
- border-radius: ${token.borderRadiusLG - 1}px;
- background: ${rgba(token.colorBgContainer, isDarkMode ? 0.7 : 1)};
- `,
- glow: cx(
- stylish.gradientAnimation,
- css`
- pointer-events: none;
- opacity: 0.5;
- background-image: linear-gradient(
- -45deg,
- ${isDarkMode ? token.geekblue4 : token.geekblue},
- ${isDarkMode ? token.cyan4 : token.cyan}
- );
- animation-duration: 10s;
- `,
- ),
- wrapper: css`
- ${responsive.mobile} {
- padding-block: 8px;
- padding-inline: 4px;
- }
- `,
-}));
-
-interface DeviceCardProps {
- browser?: string;
- os?: string;
-}
-
-const DeviceCard = memo<DeviceCardProps>(({ browser, os }) => {
- const { styles } = useStyles();
- const { t } = useTranslation('setting');
-
- return (
- <Flexbox
- className={styles.wrapper}
- style={{ maxWidth: MAX_WIDTH, position: 'relative' }}
- width={'100%'}
- >
- <Flexbox className={styles.container} padding={4}>
- <Flexbox horizontal paddingBlock={8} paddingInline={12}>
- <div>
- <Text strong style={{ fontSize: 18 }}>
- {t('sync.device.title')}
- </Text>
- </div>
- </Flexbox>
- <Flexbox
- align={'center'}
- className={styles.content}
- flex={1}
- gap={16}
- horizontal
- justify={'space-between'}
- padding={12}
- wrap={'wrap'}
- >
- <DeviceName />
- <Flexbox flex={1} gap={12} horizontal>
- <Card icon={<SystemIcon title={os} />} title={os || t('sync.device.unknownOS')} />
- <Card
- icon={browser && <BrowserIcon browser={browser} size={24} />}
- title={browser || t('sync.device.unknownBrowser')}
- />
- </Flexbox>
- </Flexbox>
- <Flexbox
- className={styles.glow}
- height={'100%'}
- style={{ left: 0, position: 'absolute', top: 0 }}
- width={'100%'}
- />
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default DeviceCard;
diff --git a/src/app/[variants]/(main)/settings/sync/features/WebRTC/ChannelNameInput.tsx b/src/app/[variants]/(main)/settings/sync/features/WebRTC/ChannelNameInput.tsx
deleted file mode 100644
index 140ec9ab625..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/WebRTC/ChannelNameInput.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { ActionIcon, Input, InputProps } from '@lobehub/ui';
-import { FormInstance } from 'antd/es/form/hooks/useForm';
-import { LucideDices } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { generateRandomRoomName } from './generateRandomRoomName';
-
-interface ChannelNameInputProps extends Omit<InputProps, 'form'> {
- form: FormInstance;
-}
-
-const ChannelNameInput = memo<ChannelNameInputProps>(({ form, ...rest }) => {
- const { t } = useTranslation('setting');
- const [loading, setLoading] = useState(false);
-
- return (
- <Input
- placeholder={t('sync.webrtc.channelName.placeholder')}
- suffix={
- <ActionIcon
- active
- icon={LucideDices}
- loading={loading}
- onClick={async () => {
- setLoading(true);
- const name = await generateRandomRoomName();
- setLoading(false);
- form.setFieldValue(['sync', 'webrtc', 'channelName'], name);
- form.setFieldValue(['sync', 'webrtc', 'enabled'], false);
- form.submit();
- }}
- size={'small'}
- style={{
- marginRight: -4,
- }}
- title={t('sync.webrtc.channelName.shuffle')}
- />
- }
- {...rest}
- />
- );
-});
-
-export default ChannelNameInput;
diff --git a/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.css b/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.css
deleted file mode 100644
index ca811edebff..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.css
+++ /dev/null
@@ -1,238 +0,0 @@
-/* stylelint-disable */
-.wrapper {
- --hue: 223;
- --off-hue: 3;
- --on-hue1: 123;
- --on-hue2: 168;
- --fg: hsl(var(--hue), 10%, 90%);
- --primary: hsl(var(--hue), 90%, 50%);
- --trans-dur: 0.6s;
- --trans-timing: cubic-bezier(0.65, 0, 0.35, 1);
-
- font-size: 14px;
-}
-
-.switch,
-.switch__input {
- -webkit-tap-highlight-color: #0000;
-}
-
-.switch {
- position: relative;
-
- display: block;
-
- width: 5em;
- height: 3em;
- margin: auto;
-}
-
-.switch__base-outer,
-.switch__base-inner {
- position: absolute;
- display: block;
-}
-
-.switch__base-outer {
- top: 0.125em;
- left: 0.125em;
-
- width: 4.75em;
- height: 2.75em;
-
- border-radius: 1.25em;
- box-shadow:
- -0.125em -0.125em 0.25em hsl(var(--hue), 10%, 30%),
- 0.125em 0.125em 0.125em hsl(var(--hue), 10%, 30%) inset,
- 0.125em 0.125em 0.25em hsl(0deg, 0%, 0%),
- -0.125em -0.125em 0.125em hsl(var(--hue), 10%, 5%) inset;
-}
-
-.switch__base-inner {
- top: 0.375em;
- left: 0.375em;
-
- width: 4.25em;
- height: 2.25em;
-
- border-radius: 1.125em;
- box-shadow:
- -0.25em -0.25em 0.25em hsl(var(--hue), 10%, 30%) inset,
- 0.0625em 0.0625em 0.125em hsla(var(--hue), 10%, 30%),
- 0.125em 0.25em 0.25em hsl(var(--hue), 10%, 5%) inset,
- -0.0625em -0.0625em 0.125em hsla(var(--hue), 10%, 5%);
-}
-
-.switch__base-neon {
- position: absolute;
- top: 0;
- left: 0;
-
- overflow: visible;
- display: block;
-
- width: 100%;
- height: auto;
-}
-
-.switch__base-neon path {
- stroke-dasharray: 0 104.26 0;
- transition: stroke-dasharray var(--trans-dur) var(--trans-timing);
-}
-
-.switch__input {
- position: relative;
-
- width: 100%;
- height: 100%;
- appearance: none;
- outline: transparent;
-}
-
-.switch__input::before {
- content: '';
-
- position: absolute;
- inset: -0.125em;
-
- display: block;
-
- border-radius: 0.125em;
- box-shadow: 0 0 0 0.125em hsla(var(--hue), 90%, 50%, 0%);
-
- transition: box-shadow 0.15s linear;
-}
-
-.switch__input:focus-visible::before {
- box-shadow: 0 0 0 0.125em var(--primary);
-}
-
-.switch__knob,
-.switch__knob-container {
- position: absolute;
- display: block;
- border-radius: 1em;
-}
-
-.switch__knob {
- width: 2em;
- height: 2em;
-
- background-color: hsl(var(--hue), 10%, 15%);
- background-image:
- radial-gradient(
- 88% 88% at 50% 50%,
- hsl(var(--hue), 10%, 20%) 47%,
- hsla(var(--hue), 10%, 20%, 0%) 50%
- ),
- radial-gradient(
- 88% 88% at 47% 47%,
- hsl(var(--hue), 10%, 85%) 45%,
- hsla(var(--hue), 10%, 85%, 0%) 50%
- ),
- radial-gradient(
- 65% 70% at 40% 60%,
- hsl(var(--hue), 10%, 20%) 46%,
- hsla(var(--hue), 10%, 20%, 0%) 50%
- );
- box-shadow:
- -0.0625em -0.0625em 0.0625em hsl(var(--hue), 10%, 15%) inset,
- -0.125em -0.125em 0.0625em hsl(var(--hue), 10%, 5%) inset,
- 0.75em 0.25em 0.125em hsla(0deg, 0%, 0%, 80%);
-
- transition: transform var(--trans-dur) var(--trans-timing);
-}
-
-.switch__knob-container {
- top: 0.5em;
- left: 0.5em;
-
- overflow: hidden;
-
- width: 4em;
- height: 2em;
-}
-
-.switch__knob-neon {
- display: block;
- width: 2em;
- height: auto;
-}
-
-.switch__knob-neon circle {
- opacity: 0;
- stroke-dasharray: 0 90.32 0 54.19;
- transition:
- opacity var(--trans-dur) steps(1, end),
- stroke-dasharray var(--trans-dur) var(--trans-timing);
-}
-
-.switch__knob-shadow {
- position: absolute;
- top: 0.5em;
- left: 0.5em;
-
- display: block;
-
- width: 2em;
- height: 2em;
-
- border-radius: 50%;
- box-shadow: 0.125em 0.125em 0.125em hsla(0deg, 0%, 0%, 90%);
-
- transition: transform var(--trans-dur) var(--trans-timing);
-}
-
-.switch__led {
- position: absolute;
- top: 0;
- left: 0;
-
- display: block;
-
- width: 0.25em;
- height: 0.25em;
-
- background-color: hsl(var(--off-hue), 90%, 70%);
- border-radius: 50%;
- box-shadow:
- 0 -0.0625em 0.0625em hsl(var(--off-hue), 90%, 40%) inset,
- 0 0 0.125em hsla(var(--off-hue), 90%, 70%, 30%),
- 0 0 0.125em hsla(var(--off-hue), 90%, 70%, 30%),
- 0.125em 0.125em 0.125em hsla(0deg, 0%, 0%, 50%);
-
- transition:
- background-color var(--trans-dur) var(--trans-timing),
- box-shadow var(--trans-dur) var(--trans-timing);
-}
-
-.switch__text {
- position: absolute;
- overflow: hidden;
- width: 1px;
- height: 1px;
-}
-
-.switch__input:checked ~ .switch__led {
- background-color: hsl(var(--on-hue1), 90%, 70%);
- box-shadow:
- 0 -0.0625em 0.0625em hsl(var(--on-hue1), 90%, 40%) inset,
- 0 -0.125em 0.125em hsla(var(--on-hue1), 90%, 70%, 30%),
- 0 0.125em 0.125em hsla(var(--on-hue1), 90%, 70%, 30%),
- 0.125em 0.125em 0.125em hsla(0deg, 0%, 0%, 50%);
-}
-
-.switch__input:checked ~ .switch__base-neon path {
- stroke-dasharray: 52.13 0 52.13;
-}
-
-.switch__input:checked ~ .switch__knob-shadow,
-.switch__input:checked ~ .switch__knob-container .switch__knob {
- transform: translateX(100%);
-}
-
-.switch__input:checked ~ .switch__knob-container .switch__knob-neon circle {
- opacity: 1;
- stroke-dasharray: 45.16 0 45.16 54.19;
- transition-timing-function: steps(1, start), var(--trans-timing);
-}
diff --git a/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.tsx b/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.tsx
deleted file mode 100644
index ad8b0c88a00..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/WebRTC/SyncSwitch/index.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { memo } from 'react';
-
-import './index.css';
-
-interface SyncSwitchProps {
- onChange?: (checked: boolean) => void;
- value?: boolean;
-}
-const SyncSwitch = memo<SyncSwitchProps>(({ value, onChange }) => {
- return (
- <div className={'wrapper'}>
- <label className="switch">
- <input
- checked={value}
- className="switch__input"
- onChange={(e) => {
- onChange?.(e.target.checked);
- }}
- role="switch"
- type="checkbox"
- />
- <span className="switch__base-outer" />
- <span className="switch__base-inner" />
- <svg className="switch__base-neon" height="24px" viewBox="0 0 40 24" width="40px">
- <defs>
- <filter id="switch-glow">
- <feGaussianBlur result="coloredBlur" stdDeviation="1" />
- <feMerge>
- <feMergeNode in="coloredBlur" />
- <feMergeNode in="SourceGraphic" />
- </feMerge>
- </filter>
- <linearGradient id="switch-gradient1" x1="0" x2="1" y1="0" y2="0">
- <stop offset="0%" stopColor="hsl(var(--on-hue1),90%,70%)" />
- <stop offset="100%" stopColor="hsl(var(--on-hue2),90%,70%)" />
- </linearGradient>
- <linearGradient id="switch-gradient2" x1="0.7" x2="0.3" y1="0" y2="1">
- <stop offset="25%" stopColor="hsla(var(--on-hue1),90%,70%,0)" />
- <stop offset="50%" stopColor="hsla(var(--on-hue1),90%,70%,0.3)" />
- <stop offset="100%" stopColor="hsla(var(--on-hue2),90%,70%,0.3)" />
- </linearGradient>
- </defs>
- <path
- d="m.5,12C.5,5.649,5.649.5,12,.5h16c6.351,0,11.5,5.149,11.5,11.5s-5.149,11.5-11.5,11.5H12C5.649,23.5.5,18.351.5,12Z"
- fill="none"
- filter="url(#switch-glow)"
- stroke="url(#switch-gradient1)"
- strokeDasharray="0 104.26 0"
- strokeDashoffset="0.01"
- strokeLinecap="round"
- strokeWidth="1"
- />
- </svg>
- <span className="switch__knob-shadow" />
- <span className="switch__knob-container">
- <span className="switch__knob">
- <svg className="switch__knob-neon" height="48px" viewBox="0 0 48 48" width="48px">
- <circle
- cx="24"
- cy="24"
- fill="none"
- r="23"
- stroke="url(#switch-gradient2)"
- strokeDasharray="0 90.32 0 54.19"
- strokeLinecap="round"
- strokeWidth="1"
- transform="rotate(-112.5,24,24)"
- />
- </svg>
- </span>
- </span>
- <span className="switch__led" />
- <span className="switch__text">Power</span>
- </label>
- </div>
- );
-});
-
-export default SyncSwitch;
diff --git a/src/app/[variants]/(main)/settings/sync/features/WebRTC/generateRandomRoomName.ts b/src/app/[variants]/(main)/settings/sync/features/WebRTC/generateRandomRoomName.ts
deleted file mode 100644
index 04317fd0ae2..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/WebRTC/generateRandomRoomName.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export const generateRandomRoomName = async () => {
- const { generate } = await import('random-words');
- return (generate(3) as string[]).join('-');
-};
diff --git a/src/app/[variants]/(main)/settings/sync/features/WebRTC/index.tsx b/src/app/[variants]/(main)/settings/sync/features/WebRTC/index.tsx
deleted file mode 100644
index d2e125d8144..00000000000
--- a/src/app/[variants]/(main)/settings/sync/features/WebRTC/index.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-'use client';
-
-import { SiWebrtc } from '@icons-pack/react-simple-icons';
-import { Form, type FormGroupItemType, Input, InputPassword, Text, Tooltip } from '@lobehub/ui';
-import { Form as AntForm, Switch } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useSyncSettings } from '@/app/[variants]/(main)/settings/hooks/useSyncSettings';
-import { FORM_STYLE } from '@/const/layoutTokens';
-import SyncStatusInspector from '@/features/SyncStatusInspector';
-import { useUserStore } from '@/store/user';
-
-import ChannelNameInput from './ChannelNameInput';
-
-const WebRTC = memo(() => {
- const { t } = useTranslation('setting');
- const [form] = Form.useForm();
-
- const [setSettings] = useUserStore((s) => [s.setSettings]);
-
- useSyncSettings(form);
-
- const channelName = AntForm.useWatch(['sync', 'webrtc', 'channelName'], form);
- const signaling = AntForm.useWatch(['sync', 'webrtc', 'signaling'], form);
-
- const config: FormGroupItemType = {
- children: [
- {
- children: <Input placeholder={t('sync.webrtc.signaling.placeholder')} />,
- desc: t('sync.webrtc.signaling.desc'),
- label: t('sync.webrtc.signaling.title'),
- name: ['sync', 'webrtc', 'signaling'],
- },
- {
- children: <ChannelNameInput form={form} />,
- desc: t('sync.webrtc.channelName.desc'),
- label: t('sync.webrtc.channelName.title'),
- name: ['sync', 'webrtc', 'channelName'],
- },
- {
- children: (
- <InputPassword
- autoComplete={'nw-password'}
- placeholder={t('sync.webrtc.channelPassword.placeholder')}
- />
- ),
- desc: t('sync.webrtc.channelPassword.desc'),
- label: t('sync.webrtc.channelPassword.title'),
- name: ['sync', 'webrtc', 'channelPassword'],
- },
- {
- children:
- !channelName || !signaling ? (
- <Tooltip title={t('sync.webrtc.enabled.invalid')}>
- <Switch disabled />
- </Tooltip>
- ) : (
- <Switch />
- ),
-
- label: t('sync.webrtc.enabled.title'),
- minWidth: undefined,
- name: ['sync', 'webrtc', 'enabled'],
- },
- ],
- extra: (
- <div
- onClick={(e) => {
- e.stopPropagation();
- }}
- >
- <SyncStatusInspector hiddenActions hiddenEnableGuide />
- </div>
- ),
- title: (
- <Flexbox align={'center'} gap={12} horizontal wrap={'wrap'}>
- <Flexbox align={'center'} gap={8} horizontal>
- <SiWebrtc style={{ flex: 'none' }} />
- {t('sync.webrtc.title')}
- </Flexbox>
- <Text style={{ fontWeight: 'normal' }} type={'secondary'}>
- {t('sync.webrtc.desc')}
- </Text>
- </Flexbox>
- ),
- };
-
- return (
- <Form
- form={form}
- items={[config]}
- itemsType={'group'}
- onFinish={setSettings}
- onValuesChange={setSettings}
- variant={'borderless'}
- {...FORM_STYLE}
- />
- );
-});
-
-export default WebRTC;
diff --git a/src/app/[variants]/(main)/settings/sync/index.tsx b/src/app/[variants]/(main)/settings/sync/index.tsx
deleted file mode 100644
index 3f01a1da663..00000000000
--- a/src/app/[variants]/(main)/settings/sync/index.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import Alert from './features/Alert';
-import DeviceInfo from './features/DeviceInfo';
-import WebRTC from './features/WebRTC';
-
-const Page = ({ browser, os, mobile }: { browser?: string; mobile?: boolean; os?: string }) => {
- return (
- <>
- <DeviceInfo browser={browser} os={os} />
- <WebRTC />
- <Alert mobile={mobile} />
- </>
- );
-};
-
-Page.displayName = 'SyncSetting';
-
-export default Page;
diff --git a/src/app/[variants]/(main)/settings/sync/page.tsx b/src/app/[variants]/(main)/settings/sync/page.tsx
deleted file mode 100644
index 705a0622418..00000000000
--- a/src/app/[variants]/(main)/settings/sync/page.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { gerServerDeviceInfo } from '@lobechat/utils/server';
-import { notFound } from 'next/navigation';
-
-import { serverFeatureFlags } from '@/config/featureFlags';
-import { metadataModule } from '@/server/metadata';
-import { translation } from '@/server/translation';
-import { DynamicLayoutProps } from '@/types/next';
-import { RouteVariants } from '@/utils/server/routeVariants';
-
-import Page from './index';
-
-export const generateMetadata = async (props: DynamicLayoutProps) => {
- const locale = await RouteVariants.getLocale(props);
- const { t } = await translation('setting', locale);
- return metadataModule.generate({
- description: t('header.desc'),
- title: t('tab.sync'),
- url: '/settings/sync',
- });
-};
-export default async (props: DynamicLayoutProps) => {
- const enableWebrtc = serverFeatureFlags().enableWebrtc;
- if (!enableWebrtc) return notFound();
-
- const isMobile = await RouteVariants.getIsMobile(props);
- const { os, browser } = await gerServerDeviceInfo();
-
- return <Page browser={browser} mobile={isMobile} os={os} />;
-};
diff --git a/src/config/featureFlags/schema.test.ts b/src/config/featureFlags/schema.test.ts
index f0615d97f46..ffe537b7944 100644
--- a/src/config/featureFlags/schema.test.ts
+++ b/src/config/featureFlags/schema.test.ts
@@ -20,7 +20,7 @@ describe('FeatureFlagsSchema', () => {
it('should reject invalid feature flags', () => {
const result = FeatureFlagsSchema.safeParse({
- webrtc_sync: 'yes', // Invalid type, should be boolean
+ edit_agent: 'yes', // Invalid type, should be boolean
});
expect(result.success).toBe(false);
@@ -43,7 +43,6 @@ describe('mapFeatureFlagsEnvToState', () => {
};
const expectedState = {
- enableWebrtc: true,
isAgentEditable: false,
showCreateSession: true,
showLLM: false,
diff --git a/src/config/featureFlags/schema.ts b/src/config/featureFlags/schema.ts
index 7186202b8a0..24efb32e75a 100644
--- a/src/config/featureFlags/schema.ts
+++ b/src/config/featureFlags/schema.ts
@@ -2,10 +2,6 @@
import { z } from 'zod';
export const FeatureFlagsSchema = z.object({
- /**
- * Enable WebRTC sync
- */
- webrtc_sync: z.boolean().optional(),
check_updates: z.boolean().optional(),
pin_list: z.boolean().optional(),
@@ -51,7 +47,6 @@ export const FeatureFlagsSchema = z.object({
export type IFeatureFlags = z.infer<typeof FeatureFlagsSchema>;
export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
- webrtc_sync: false,
pin_list: false,
language_model_settings: true,
@@ -93,7 +88,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
export const mapFeatureFlagsEnvToState = (config: IFeatureFlags) => {
return {
- enableWebrtc: config.webrtc_sync,
isAgentEditable: config.edit_agent,
showCreateSession: config.create_session,
diff --git a/src/config/featureFlags/utils/parser.test.ts b/src/config/featureFlags/utils/parser.test.ts
index 742c58b40a4..c1af1d965d1 100644
--- a/src/config/featureFlags/utils/parser.test.ts
+++ b/src/config/featureFlags/utils/parser.test.ts
@@ -8,7 +8,7 @@ describe('parseFeatureFlag', () => {
});
it('should enable a feature when prefixed with +', () => {
- expect(parseFeatureFlag('+webrtc_sync')).toEqual({ webrtc_sync: true });
+ expect(parseFeatureFlag('+api_key_manage')).toEqual({ api_key_manage: true });
});
it('should disable a feature when prefixed with -', () => {
@@ -16,10 +16,10 @@ describe('parseFeatureFlag', () => {
});
it('should handle multiple flags separated by commas', () => {
- const input = '+webrtc_sync,-openai_api_key,+another_feature';
+ const input = '+api_key_manage,-openai_api_key,+another_feature';
expect(parseFeatureFlag(input)).toEqual({
- webrtc_sync: true,
+ api_key_manage: true,
openai_api_key: false,
});
});
@@ -53,19 +53,19 @@ describe('parseFeatureFlag', () => {
});
it('should handle flags separated by Chinese commas', () => {
- const input = '+webrtc_sync,-openai_api_key';
+ const input = '+api_key_manage,-openai_api_key';
expect(parseFeatureFlag(input)).toEqual({
- webrtc_sync: true,
+ api_key_manage: true,
openai_api_key: false,
});
});
it('should ignore whitespace around flags', () => {
- const input = ' +webrtc_sync , -openai_api_key ';
+ const input = ' +api_key_manage , -openai_api_key ';
expect(parseFeatureFlag(input)).toEqual({
- webrtc_sync: true,
+ api_key_manage: true,
openai_api_key: false,
});
});
diff --git a/src/database/_deprecated/core/index.ts b/src/database/_deprecated/core/index.ts
index d2fb8c94df5..144f37ce02c 100644
--- a/src/database/_deprecated/core/index.ts
+++ b/src/database/_deprecated/core/index.ts
@@ -1,3 +1,2 @@
export { browserDB } from './db';
export * from './model';
-export { dataSync } from './sync';
diff --git a/src/database/_deprecated/core/model.ts b/src/database/_deprecated/core/model.ts
index fe5587617a8..5ec6c55ae65 100644
--- a/src/database/_deprecated/core/model.ts
+++ b/src/database/_deprecated/core/model.ts
@@ -4,7 +4,6 @@ import { ZodObject } from 'zod';
import { nanoid } from '@/utils/uuid';
import { BrowserDB, BrowserDBSchema, browserDB } from './db';
-import { dataSync } from './sync';
import { DBBaseFieldsSchema } from './types/db';
export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchema[N]['table']> {
@@ -22,10 +21,6 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
return this.db[this._tableName] as Dexie.Table;
}
- get yMap() {
- return dataSync.getYMap(this._tableName);
- }
-
// **************** Create *************** //
/**
@@ -79,7 +74,6 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
*/
createWithNewId?: boolean;
idGenerator?: () => string;
- withSync?: boolean;
} = {},
): Promise<{
added: number;
@@ -88,7 +82,7 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
skips: string[];
success: boolean;
}> {
- const { idGenerator = nanoid, createWithNewId = false, withSync = true } = options;
+ const { idGenerator = nanoid, createWithNewId = false } = options;
const validatedData: any[] = [];
const errors = [];
const skips: string[] = [];
@@ -141,15 +135,6 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
try {
await this.table.bulkAdd(validatedData);
- if (withSync) {
- dataSync.transact(() => {
- const pools = validatedData.map(async (item) => {
- await this.updateYMapItem(item.id);
- });
- Promise.all(pools);
- });
- }
-
return {
added: validatedData.length,
ids: validatedData.map((item) => item.id),
@@ -174,28 +159,16 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
// **************** Delete *************** //
protected async _deleteWithSync(id: string) {
- const result = await this.table.delete(id);
- // sync delete data to yjs data map
- this.yMap?.delete(id);
- return result;
+ return await this.table.delete(id);
}
protected async _bulkDeleteWithSync(keys: string[]) {
await this.table.bulkDelete(keys);
// sync delete data to yjs data map
-
- dataSync.transact(() => {
- keys.forEach((id) => {
- this.yMap?.delete(id);
- });
- });
}
protected async _clearWithSync() {
- const result = await this.table.clear();
- // sync clear data to yjs data map
- this.yMap?.clear();
- return result;
+ return await this.table.clear();
}
// **************** Update *************** //
@@ -235,18 +208,11 @@ export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchem
protected async _bulkPutWithSync(items: T[]) {
await this.table.bulkPut(items);
-
- await dataSync.transact(() => {
- items.forEach((items) => {
- this.updateYMapItem((items as any).id);
- });
- });
}
// **************** Helper *************** //
private updateYMapItem = async (id: string) => {
- const newData = await this.table.get(id);
- this.yMap?.set(id, newData);
+ await this.table.get(id);
};
}
diff --git a/src/database/_deprecated/core/sync.ts b/src/database/_deprecated/core/sync.ts
deleted file mode 100644
index 36911699f84..00000000000
--- a/src/database/_deprecated/core/sync.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import Debug from 'debug';
-import { throttle, uniqBy } from 'lodash-es';
-import type { WebrtcProvider } from 'y-webrtc';
-import type { Doc, Transaction } from 'yjs';
-
-import {
- OnAwarenessChange,
- OnSyncEvent,
- OnSyncStatusChange,
- PeerSyncStatus,
- StartDataSyncParams,
-} from '@/types/sync';
-
-import { LobeDBSchemaMap, browserDB } from './db';
-
-const LOG_NAME_SPACE = 'DataSync';
-
-class DataSync {
- private _ydoc: Doc | null = null;
- private provider: WebrtcProvider | null = null;
-
- private syncParams!: StartDataSyncParams;
- private onAwarenessChange!: OnAwarenessChange;
-
- private waitForConnecting: any;
-
- logger = Debug(LOG_NAME_SPACE);
-
- transact(fn: (transaction: Transaction) => unknown) {
- this._ydoc?.transact(fn);
- }
-
- getYMap = (tableKey: keyof LobeDBSchemaMap) => {
- return this._ydoc?.getMap(tableKey);
- };
-
- startDataSync = async (params: StartDataSyncParams) => {
- this.syncParams = params;
- this.onAwarenessChange = params.onAwarenessChange;
-
- // 开发时由于存在 fast refresh 全局实例会缓存在运行时中
- // 因此需要在每次重新连接时清理上一次的实例
- if (window.__ONLY_USE_FOR_CLEANUP_IN_DEV) {
- await this.cleanConnection(window.__ONLY_USE_FOR_CLEANUP_IN_DEV);
- }
-
- await this.connect(params);
- };
-
- connect = async (params: StartDataSyncParams) => {
- const { channel, onSyncEvent, onSyncStatusChange, user, onAwarenessChange, signaling } = params;
- // ====== 1. init yjs doc ====== //
-
- await this.initYDoc();
-
- this.logger('[YJS] start to listen sync event...');
- this.initYjsObserve(onSyncEvent, onSyncStatusChange);
-
- // ====== 2. init webrtc provider ====== //
- this.logger(`[WebRTC] init provider... room: ${channel.name}`);
- const { WebrtcProvider } = await import('y-webrtc');
-
- // clients connected to the same room-name share document updates
- this.provider = new WebrtcProvider(channel.name, this._ydoc!, {
- password: channel.password,
- signaling: [signaling],
- });
-
- // when fast refresh in dev, the provider will be cached in window
- // so we need to clean it in destory
- if (process.env.NODE_ENV === 'development') {
- window.__ONLY_USE_FOR_CLEANUP_IN_DEV = this.provider;
- }
-
- this.logger(`[WebRTC] provider init success`);
-
- // ====== 3. check signaling server connection ====== //
-
- // 当本地设备正确连接到 WebRTC Provider 后,触发 status 事件
- // 当开始连接,则开始监听事件
- this.provider.on('status', async ({ connected }) => {
- this.logger('[WebRTC] peer status:', connected);
- if (connected) {
- // this.initObserve(onSyncEvent, onSyncStatusChange);
- onSyncStatusChange?.(PeerSyncStatus.Connecting);
- }
- });
-
- // check the connection with signaling server
- let connectionCheckCount = 0;
-
- this.waitForConnecting = setInterval(() => {
- const signalingConnection: IWebsocketClient = this.provider!.signalingConns[0];
-
- if (signalingConnection.connected) {
- onSyncStatusChange?.(PeerSyncStatus.Ready);
- clearInterval(this.waitForConnecting);
- return;
- }
-
- connectionCheckCount += 1;
-
- // check for 5 times, or make it failed
- if (connectionCheckCount > 5) {
- onSyncStatusChange?.(PeerSyncStatus.Unconnected);
- clearInterval(this.waitForConnecting);
- }
- }, 2000);
-
- // ====== 4. handle data sync ====== //
-
- // 当各方的数据均完成同步后,YJS 对象之间的数据已经一致时,触发 synced 事件
- this.provider.on('synced', async ({ synced }) => {
- this.logger('[WebRTC] peer sync status:', synced);
- if (synced) {
- this.logger('[WebRTC] start to init yjs data...');
- onSyncStatusChange?.(PeerSyncStatus.Syncing);
- await this.initSync();
- onSyncStatusChange?.(PeerSyncStatus.Synced);
- this.logger('[WebRTC] yjs data init success');
- } else {
- this.logger('[WebRTC] data not sync, try to reconnect in 1s...');
- // await this.reconnect(params);
- setTimeout(() => {
- onSyncStatusChange?.(PeerSyncStatus.Syncing);
- this.reconnect(params);
- }, 1000);
- }
- });
-
- // ====== 5. handle awareness ====== //
-
- this.initAwareness({ onAwarenessChange, user });
-
- return this.provider;
- };
-
- reconnect = async (params: StartDataSyncParams) => {
- await this.cleanConnection(this.provider);
-
- await this.connect(params);
- };
-
- async disconnect() {
- await this.cleanConnection(this.provider);
- }
-
- private initYDoc = async () => {
- if (typeof window === 'undefined') return;
-
- this.logger('[YJS] init YDoc...');
- const { Doc } = await import('yjs');
- this._ydoc = new Doc();
- };
-
- private async cleanConnection(provider: WebrtcProvider | null) {
- if (provider) {
- this.logger(`[WebRTC] clean Connection...`);
- this.logger(`[WebRTC] clean awareness...`);
- provider.awareness.destroy();
-
- this.logger(`[WebRTC] clean room...`);
- provider.room?.disconnect();
- provider.room?.destroy();
-
- this.logger(`[WebRTC] clean provider...`);
- provider.disconnect();
- provider.destroy();
-
- this.logger(`[WebRTC] clean yjs doc...`);
- this._ydoc?.destroy();
-
- this.logger(`[WebRTC] -------------------`);
- }
- }
-
- private initSync = async () => {
- await Promise.all(
- ['sessions', 'sessionGroups', 'topics', 'messages', 'plugins'].map(async (tableKey) =>
- this.loadDataFromDBtoYjs(tableKey as keyof LobeDBSchemaMap),
- ),
- );
- };
-
- private initYjsObserve = (onEvent: OnSyncEvent, onSyncStatusChange: OnSyncStatusChange) => {
- ['sessions', 'sessionGroups', 'topics', 'messages', 'plugins'].forEach((tableKey) => {
- // listen yjs change
- this.observeYMapChange(tableKey as keyof LobeDBSchemaMap, onEvent, onSyncStatusChange);
- });
- };
-
- private observeYMapChange = (
- tableKey: keyof LobeDBSchemaMap,
- onEvent: OnSyncEvent,
- onSyncStatusChange: OnSyncStatusChange,
- ) => {
- const table = browserDB[tableKey];
- const yItemMap = this.getYMap(tableKey);
- const updateSyncEvent = throttle(onEvent, 1000);
-
- // 定义一个变量来保存定时器的ID
- // eslint-disable-next-line no-undef
- let debounceTimer: NodeJS.Timeout;
-
- yItemMap?.observe(async (event) => {
- // abort local change
- if (event.transaction.local) return;
-
- // 每次有变更时,都先清除之前的定时器(如果有的话),然后设置新的定时器
- clearTimeout(debounceTimer);
-
- onSyncStatusChange(PeerSyncStatus.Syncing);
-
- this.logger(`[YJS] observe ${tableKey} changes:`, event.keysChanged.size);
- const pools = Array.from(event.keys).map(async ([id, payload]) => {
- const item: any = yItemMap.get(id);
-
- switch (payload.action) {
- case 'add':
- case 'update': {
- await table.put(item, id);
-
- break;
- }
-
- case 'delete': {
- await table.delete(id);
- break;
- }
- }
- });
-
- await Promise.all(pools);
-
- updateSyncEvent(tableKey);
-
- // 设置定时器,2000ms 后更新状态为'synced'
- debounceTimer = setTimeout(() => {
- onSyncStatusChange(PeerSyncStatus.Synced);
- }, 2000);
- });
- };
-
- private loadDataFromDBtoYjs = async (tableKey: keyof LobeDBSchemaMap) => {
- const table = browserDB[tableKey];
- const items = await table.toArray();
- const yItemMap = this.getYMap(tableKey);
-
- // 定义每批次最多包含的数据条数
- const batchSize = 50;
-
- // 计算总批次数
- const totalBatches = Math.ceil(items.length / batchSize);
-
- for (let i = 0; i < totalBatches; i++) {
- // 计算当前批次的起始和结束索引
- const start = i * batchSize;
- const end = start + batchSize;
-
- // 获取当前批次的数据
- const batchItems = items.slice(start, end);
-
- // 将当前批次的数据推送到 Yjs 中
- this._ydoc?.transact(() => {
- batchItems.forEach((item) => {
- yItemMap!.set(item.id, item);
- });
- });
- }
-
- this.logger('[DB]:', tableKey, yItemMap?.size);
- };
-
- private initAwareness = ({ user }: Pick<StartDataSyncParams, 'user' | 'onAwarenessChange'>) => {
- if (!this.provider) return;
-
- const awareness = this.provider.awareness;
-
- awareness.setLocalState({ clientID: awareness.clientID, user });
- this.onAwarenessChange?.([{ ...user, clientID: awareness.clientID, current: true }]);
-
- awareness.on('change', () => this.syncAwarenessToUI());
- };
-
- private syncAwarenessToUI = async () => {
- const awareness = this.provider?.awareness;
-
- if (!awareness) return;
-
- const state = Array.from(awareness.getStates().values()).map((s) => ({
- ...s.user,
- clientID: s.clientID,
- current: s.clientID === awareness.clientID,
- }));
-
- this.onAwarenessChange?.(uniqBy(state, 'id'));
- };
-}
-
-export const dataSync = new DataSync();
-
-interface IWebsocketClient {
- binaryType: 'arraybuffer' | 'blob' | null;
- connect(): void;
- connected: boolean;
- connecting: boolean;
- destroy(): void;
- disconnect(): void;
- lastMessageReceived: number;
- send(message: any): void;
- shouldConnect: boolean;
- unsuccessfulReconnects: number;
- url: string;
- ws: WebSocket;
-}
-
-declare global {
- interface Window {
- __ONLY_USE_FOR_CLEANUP_IN_DEV?: WebrtcProvider | null;
- }
-}
diff --git a/src/database/_deprecated/models/message.ts b/src/database/_deprecated/models/message.ts
index ae728696b6c..3a5046c83fe 100644
--- a/src/database/_deprecated/models/message.ts
+++ b/src/database/_deprecated/models/message.ts
@@ -118,7 +118,7 @@ class _MessageModel extends BaseModel {
async batchCreate(messages: ChatMessage[]) {
const data: DB_Message[] = messages.map((m) => this.mapChatMessageToDBMessage(m));
- return this._batchAdd(data, { withSync: true });
+ return this._batchAdd(data);
}
async duplicateMessages(messages: ChatMessage[]): Promise<ChatMessage[]> {
diff --git a/src/features/SyncStatusInspector/DisableSync.tsx b/src/features/SyncStatusInspector/DisableSync.tsx
deleted file mode 100644
index 1b586101196..00000000000
--- a/src/features/SyncStatusInspector/DisableSync.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { Button, Icon, Tag } from '@lobehub/ui';
-import { Badge, Popover } from 'antd';
-import { TooltipPlacement } from 'antd/es/tooltip';
-import { LucideCloudCog, LucideCloudy } from 'lucide-react';
-import Link from 'next/link';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useUserStore } from '@/store/user';
-import { syncSettingsSelectors } from '@/store/user/selectors';
-
-interface DisableSyncProps {
- noPopover?: boolean;
- placement?: TooltipPlacement;
-}
-
-const DisableSync = memo<DisableSyncProps>(({ noPopover, placement = 'bottomLeft' }) => {
- const { t } = useTranslation('common');
- const [haveConfig, setSettings] = useUserStore((s) => [
- !!syncSettingsSelectors.webrtcConfig(s).channelName,
- s.setSettings,
- ]);
-
- const enableSync = () => {
- setSettings({ sync: { webrtc: { enabled: true } } });
- };
-
- const tag = (
- <div>
- <Tag>
- <Badge status="default" />
- {t('sync.status.disabled')}
- </Tag>
- </div>
- );
-
- return noPopover ? (
- tag
- ) : (
- <Popover
- arrow={false}
- content={
- <Flexbox gap={12} width={320}>
- {t('sync.disabled.desc')}
- {haveConfig ? (
- <Flexbox gap={8} horizontal>
- <Link href={'/settings/sync'}>
- <Button block icon={<Icon icon={LucideCloudCog} />}>
- {t('sync.disabled.actions.settings')}
- </Button>
- </Link>
- <Button block onClick={enableSync} type={'primary'}>
- {t('sync.disabled.actions.enable')}
- </Button>
- </Flexbox>
- ) : (
- <Link href={'/settings/sync'}>
- <Button block icon={<Icon icon={LucideCloudCog} />} type={'primary'}>
- {t('sync.disabled.actions.settings')}
- </Button>
- </Link>
- )}
- </Flexbox>
- }
- placement={placement}
- title={
- <Flexbox gap={8} horizontal>
- <Icon icon={LucideCloudy} />
- {t('sync.disabled.title')}
- </Flexbox>
- }
- >
- {tag}
- </Popover>
- );
-});
-
-export default DisableSync;
diff --git a/src/features/SyncStatusInspector/EnableSync.tsx b/src/features/SyncStatusInspector/EnableSync.tsx
deleted file mode 100644
index 9b3a509f03b..00000000000
--- a/src/features/SyncStatusInspector/EnableSync.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { ActionIcon, Avatar, Icon, Tag, Text } from '@lobehub/ui';
-import { Divider, Popover, Switch } from 'antd';
-import { createStyles } from 'antd-style';
-import { TooltipPlacement } from 'antd/es/tooltip';
-import isEqual from 'fast-deep-equal';
-import { LucideCloudy, LucideLaptop, LucideSmartphone, SettingsIcon } from 'lucide-react';
-import Link from 'next/link';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useUserStore } from '@/store/user';
-import { syncSettingsSelectors } from '@/store/user/selectors';
-import { pathString } from '@/utils/url';
-
-import EnableTag from './EnableTag';
-
-const useStyles = createStyles(({ css, token, prefixCls }) => ({
- text: css`
- max-width: 100%;
- color: ${token.colorTextTertiary};
- .${prefixCls}-typography-copy {
- color: ${token.colorTextTertiary};
- }
- `,
- title: css`
- color: ${token.colorTextTertiary};
- `,
-}));
-
-interface EnableSyncProps {
- hiddenActions?: boolean;
- placement?: TooltipPlacement;
-}
-
-const EnableSync = memo<EnableSyncProps>(({ hiddenActions, placement = 'bottomLeft' }) => {
- const { t } = useTranslation('common');
-
- const { styles, theme } = useStyles();
- const [syncStatus, isSyncing, channelName, enableWebRTC, setSettings] = useUserStore((s) => [
- s.syncStatus,
- s.syncStatus === 'syncing',
- syncSettingsSelectors.webrtcChannelName(s),
- syncSettingsSelectors.enableWebRTC(s),
- s.setSettings,
- ]);
-
- const users = useUserStore((s) => s.syncAwareness, isEqual);
-
- const switchSync = (enabled: boolean) => {
- setSettings({ sync: { webrtc: { enabled } } });
- };
-
- return (
- <Popover
- arrow={false}
- content={
- <Flexbox gap={16}>
- <Flexbox align={'center'} gap={24} horizontal>
- <Flexbox
- align={'center'}
- className={styles.title}
- gap={4}
- horizontal
- style={{ paddingInlineEnd: 12 }}
- >
- {t('sync.channel')}
- <Text className={styles.text}>{channelName}</Text>
- </Flexbox>
- </Flexbox>
- <Divider dashed style={{ margin: 0 }} />
- <Flexbox gap={12}>
- {users.map((user) => (
- <Flexbox gap={12} horizontal key={user.clientID}>
- <Avatar
- avatar={
- <Icon
- color={theme.purple}
- icon={user.isMobile ? LucideSmartphone : LucideLaptop}
- size={24}
- />
- }
- background={theme.purple1}
- shape={'square'}
- />
-
- <Flexbox>
- <Flexbox gap={8} horizontal>
- {user.name || user.id}
- {user.current && (
- <Flexbox horizontal>
- <Tag bordered={false} color={'blue'}>
- {t('sync.awareness.current')}
- </Tag>
- </Flexbox>
- )}
- </Flexbox>
- <Text type={'secondary'}>
- {user.os} · {user.browser}
- </Text>
- </Flexbox>
- </Flexbox>
- ))}
- </Flexbox>
- </Flexbox>
- }
- placement={placement}
- title={
- <Flexbox distribution={'space-between'} horizontal>
- <Flexbox align={'center'} gap={8} horizontal>
- <Icon icon={LucideCloudy} />
- {t('sync.title')}
- {!hiddenActions && (
- <Switch checked={enableWebRTC} onChange={switchSync} size={'small'} />
- )}
- </Flexbox>
- {!hiddenActions && (
- <Link href={pathString('/settings/sync')}>
- <ActionIcon icon={SettingsIcon} title={t('sync.actions.settings')} />
- </Link>
- )}
- </Flexbox>
- }
- >
- <div>
- <EnableTag isSyncing={isSyncing} status={syncStatus} />
- </div>
- </Popover>
- );
-});
-
-export default EnableSync;
diff --git a/src/features/SyncStatusInspector/EnableTag.tsx b/src/features/SyncStatusInspector/EnableTag.tsx
deleted file mode 100644
index 460a618dcf2..00000000000
--- a/src/features/SyncStatusInspector/EnableTag.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { Icon, Tag, Tooltip } from '@lobehub/ui';
-import { Badge } from 'antd';
-import { LucideCloudy, LucideRefreshCw, LucideRouter, LucideWifiOff } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { PeerSyncStatus } from '@/types/sync';
-
-const EnableTag = memo<{ isSyncing: boolean; status: PeerSyncStatus }>(({ status, isSyncing }) => {
- const { t } = useTranslation('common');
-
- switch (status) {
- case PeerSyncStatus.Connecting: {
- return (
- <Tag
- bordered={false}
- color={'blue'}
- icon={<Badge color={'blue'} status="processing" />}
- style={{ display: 'flex', gap: 4 }}
- >
- {t('sync.status.connecting')}
- </Tag>
- );
- }
-
- case PeerSyncStatus.Synced: {
- return (
- <Tag bordered={false} color={'green'} icon={<Icon icon={LucideCloudy} />}>
- {t('sync.status.synced')}
- </Tag>
- );
- }
-
- case PeerSyncStatus.Ready: {
- return (
- <Tag bordered={false} color={'blue'} icon={<Icon icon={LucideRouter} />}>
- {t('sync.status.ready')}
- </Tag>
- );
- }
-
- case PeerSyncStatus.Syncing: {
- return (
- <Tag
- bordered={false}
- color={'blue'}
- icon={<Icon icon={LucideRefreshCw} spin={isSyncing} />}
- >
- {t('sync.status.syncing')}
- </Tag>
- );
- }
-
- case PeerSyncStatus.Unconnected: {
- return (
- <Tooltip title={t('sync.unconnected.tip')}>
- <Tag bordered={false} color={'red'} icon={<Icon icon={LucideWifiOff} />}>
- {t('sync.status.unconnected')}
- </Tag>
- </Tooltip>
- );
- }
- }
-});
-
-export default EnableTag;
diff --git a/src/features/SyncStatusInspector/index.tsx b/src/features/SyncStatusInspector/index.tsx
deleted file mode 100644
index 5dcddfc7dc6..00000000000
--- a/src/features/SyncStatusInspector/index.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { TooltipPlacement } from 'antd/es/tooltip';
-import { memo } from 'react';
-
-import { useUserStore } from '@/store/user';
-
-import DisableSync from './DisableSync';
-import EnableSync from './EnableSync';
-
-interface SyncStatusTagProps {
- hiddenActions?: boolean;
- hiddenEnableGuide?: boolean;
- placement?: TooltipPlacement;
-}
-
-const SyncStatusTag = memo<SyncStatusTagProps>(
- ({ hiddenActions, placement, hiddenEnableGuide }) => {
- const [enableSync] = useUserStore((s) => [s.syncEnabled]);
-
- return enableSync ? (
- <EnableSync hiddenActions={hiddenActions} placement={placement} />
- ) : (
- <DisableSync noPopover={hiddenEnableGuide} placement={placement} />
- );
- },
-);
-
-export default SyncStatusTag;
diff --git a/src/hooks/useSyncData.ts b/src/hooks/useSyncData.ts
deleted file mode 100644
index e03d7f55be8..00000000000
--- a/src/hooks/useSyncData.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useCallback } from 'react';
-
-import { useChatStore } from '@/store/chat';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { useUserStore } from '@/store/user';
-import { syncSettingsSelectors, userProfileSelectors } from '@/store/user/selectors';
-
-export const useSyncEvent = () => {
- const [refreshMessages, refreshTopic] = useChatStore((s) => [s.refreshMessages, s.refreshTopic]);
- const [refreshSessions] = useSessionStore((s) => [s.refreshSessions]);
-
- return useCallback((tableKey: string) => {
- // console.log('triggerSync Event:', tableKey);
-
- switch (tableKey) {
- case 'messages': {
- refreshMessages();
- break;
- }
-
- case 'topics': {
- refreshTopic();
- break;
- }
-
- case 'sessions': {
- refreshSessions();
- break;
- }
-
- default: {
- break;
- }
- }
- }, []);
-};
-
-export const useEnabledDataSync = () => {
- const [userId, userEnableSync, useEnabledSync] = useUserStore((s) => [
- userProfileSelectors.userId(s),
- syncSettingsSelectors.enableWebRTC(s),
- s.useEnabledSync,
- ]);
-
- const { enableWebrtc } = useServerConfigStore(featureFlagsSelectors);
- const syncEvent = useSyncEvent();
-
- useEnabledSync(enableWebrtc, { onEvent: syncEvent, userEnableSync, userId });
-};
diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsx
index 5adeb3f5afa..432422ae5ad 100644
--- a/src/layout/GlobalProvider/StoreInitialization.tsx
+++ b/src/layout/GlobalProvider/StoreInitialization.tsx
@@ -7,7 +7,6 @@ import { createStoreUpdater } from 'zustand-utils';
import { enableNextAuth } from '@/const/auth';
import { useIsMobile } from '@/hooks/useIsMobile';
-import { useEnabledDataSync } from '@/hooks/useSyncData';
import { useAgentStore } from '@/store/agent';
import { useAiInfraStore } from '@/store/aiInfra';
import { useGlobalStore } from '@/store/global';
@@ -70,8 +69,6 @@ const StoreInitialization = memo(() => {
},
});
- useEnabledDataSync();
-
const useStoreUpdater = createStoreUpdater(useGlobalStore);
const mobile = useIsMobile();
diff --git a/src/services/__tests__/sync.test.ts b/src/services/__tests__/sync.test.ts
deleted file mode 100644
index 7ebe9a5bd13..00000000000
--- a/src/services/__tests__/sync.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { dataSync } from '@/database/_deprecated/core';
-import { StartDataSyncParams } from '@/types/sync';
-
-import { syncService } from '../sync';
-
-vi.mock('@/database/_deprecated/core', () => ({
- dataSync: {
- startDataSync: vi.fn(),
- disconnect: vi.fn(),
- },
-}));
-
-describe('SyncService', () => {
- afterEach(() => {
- vi.resetAllMocks();
- });
-
- describe('enabledSync', () => {
- it('should return false when running on server side', async () => {
- const params = { user: { id: '123' }, authToken: 'abc' } as unknown as StartDataSyncParams;
-
- const origin = global.window;
-
- // @ts-ignore
- global.window = undefined;
-
- const result = await syncService.enabledSync(params);
-
- expect(result).toBe(false);
- expect(dataSync.startDataSync).not.toHaveBeenCalled();
-
- // reset
- global.window = origin;
- });
-
- it('should start data sync and return true when running on client side', async () => {
- const params = { user: { id: '123' }, authToken: 'abc' } as unknown as StartDataSyncParams;
-
- const result = await syncService.enabledSync(params);
-
- expect(result).toBe(true);
- expect(dataSync.startDataSync).toHaveBeenCalledWith(params);
- });
- });
-
- describe('disableSync', () => {
- it('should disconnect data sync and return false', async () => {
- const result = await syncService.disableSync();
-
- expect(result).toBe(false);
- expect(dataSync.disconnect).toHaveBeenCalled();
- });
- });
-});
diff --git a/src/services/sync.ts b/src/services/sync.ts
deleted file mode 100644
index 03e8b8bbc9a..00000000000
--- a/src/services/sync.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { dataSync } from '@/database/_deprecated/core';
-import { StartDataSyncParams } from '@/types/sync';
-
-class SyncService {
- enabledSync = async (params: StartDataSyncParams) => {
- if (typeof window === 'undefined') return false;
-
- await dataSync.startDataSync(params);
- return true;
- };
-
- disableSync = async () => {
- await dataSync.disconnect();
-
- return false;
- };
-}
-
-export const syncService = new SyncService();
diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.ts
index e0273a48c08..138495ce512 100644
--- a/src/store/serverConfig/selectors.test.ts
+++ b/src/store/serverConfig/selectors.test.ts
@@ -17,7 +17,6 @@ describe('featureFlagsSelectors', () => {
const result = featureFlagsSelectors(store.getState());
expect(result).toEqual({
- enableWebrtc: false,
isAgentEditable: false,
showApiKeyManage: false,
enablePlugins: true,
diff --git a/src/store/user/initialState.ts b/src/store/user/initialState.ts
index 5dd17f901d8..a69d34681e5 100644
--- a/src/store/user/initialState.ts
+++ b/src/store/user/initialState.ts
@@ -3,17 +3,14 @@ import { CommonState, initialCommonState } from './slices/common/initialState';
import { ModelListState, initialModelListState } from './slices/modelList/initialState';
import { UserPreferenceState, initialPreferenceState } from './slices/preference/initialState';
import { UserSettingsState, initialSettingsState } from './slices/settings/initialState';
-import { UserSyncState, initialSyncState } from './slices/sync/initialState';
-export type UserState = UserSyncState &
- UserSettingsState &
+export type UserState = UserSettingsState &
UserPreferenceState &
UserAuthState &
ModelListState &
CommonState;
export const initialState: UserState = {
- ...initialSyncState,
...initialSettingsState,
...initialPreferenceState,
...initialAuthState,
diff --git a/src/store/user/selectors.ts b/src/store/user/selectors.ts
index bd48dd5df8f..bdbb038d39a 100644
--- a/src/store/user/selectors.ts
+++ b/src/store/user/selectors.ts
@@ -10,4 +10,3 @@ export {
systemAgentSelectors,
userGeneralSettingsSelectors,
} from './slices/settings/selectors';
-export { syncSettingsSelectors } from './slices/sync/selectors';
diff --git a/src/store/user/slices/sync/action.test.ts b/src/store/user/slices/sync/action.test.ts
deleted file mode 100644
index fd44759a270..00000000000
--- a/src/store/user/slices/sync/action.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { withSWR } from '~test-utils';
-
-import { syncService } from '@/services/sync';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-import { syncSettingsSelectors } from '@/store/user/selectors';
-
-vi.mock('zustand/traditional');
-
-vi.mock('swr', async (importOriginal) => {
- const modules = await importOriginal();
- return {
- ...(modules as any),
- mutate: vi.fn(),
- };
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('createSyncSlice', () => {
- describe('refreshConnection', () => {
- it('should not call triggerEnableSync when userId is empty', async () => {
- const { result } = renderHook(() => useUserStore());
- const onEvent = vi.fn();
-
- vi.spyOn(userProfileSelectors, 'userId').mockReturnValueOnce(undefined as any);
- const triggerEnableSyncSpy = vi.spyOn(result.current, 'triggerEnableSync');
-
- await act(async () => {
- await result.current.refreshConnection(onEvent);
- });
-
- expect(triggerEnableSyncSpy).not.toHaveBeenCalled();
- });
-
- it('should call triggerEnableSync when userId exists', async () => {
- const { result } = renderHook(() => useUserStore());
- const onEvent = vi.fn();
- const userId = 'user-id';
-
- vi.spyOn(userProfileSelectors, 'userId').mockReturnValueOnce(userId);
- const triggerEnableSyncSpy = vi.spyOn(result.current, 'triggerEnableSync');
-
- await act(async () => {
- await result.current.refreshConnection(onEvent);
- });
-
- expect(triggerEnableSyncSpy).toHaveBeenCalledWith(userId, onEvent);
- });
- });
-
- describe('triggerEnableSync', () => {
- it('should return false when sync.channelName is empty', async () => {
- const { result } = renderHook(() => useUserStore());
- const userId = 'user-id';
- const onEvent = vi.fn();
-
- vi.spyOn(syncSettingsSelectors, 'webrtcConfig').mockReturnValueOnce({
- channelName: '',
- enabled: true,
- });
-
- const data = await act(async () => {
- return result.current.triggerEnableSync(userId, onEvent);
- });
-
- expect(data).toBe(false);
- });
-
- it('should call globalService.enabledSync when sync.channelName exists', async () => {
- const userId = 'user-id';
- const onEvent = vi.fn();
- const channelName = 'channel-name';
- const channelPassword = 'channel-password';
- const deviceName = 'device-name';
- const signaling = 'signaling';
-
- vi.spyOn(syncSettingsSelectors, 'webrtcConfig').mockReturnValueOnce({
- channelName,
- channelPassword,
- signaling,
- enabled: true,
- });
- vi.spyOn(syncSettingsSelectors, 'deviceName').mockReturnValueOnce(deviceName);
- const enabledSyncSpy = vi.spyOn(syncService, 'enabledSync').mockResolvedValueOnce(true);
- const { result } = renderHook(() => useUserStore());
-
- const data = await act(async () => {
- return result.current.triggerEnableSync(userId, onEvent);
- });
-
- expect(enabledSyncSpy).toHaveBeenCalledWith({
- channel: { name: channelName, password: channelPassword },
- onAwarenessChange: expect.any(Function),
- onSyncEvent: onEvent,
- onSyncStatusChange: expect.any(Function),
- signaling,
- user: expect.objectContaining({ id: userId, name: deviceName }),
- });
- expect(data).toBe(true);
- });
- });
-
- describe('useEnabledSync', () => {
- it('should return false when userId is empty', async () => {
- const { result } = renderHook(
- () =>
- useUserStore().useEnabledSync(true, {
- userEnableSync: true,
- userId: undefined,
- onEvent: vi.fn(),
- }),
- {
- wrapper: withSWR,
- },
- );
-
- await waitFor(() => expect(result.current.data).toBe(false));
- });
-
- it('should call syncService.disableSync when userEnableSync is false', async () => {
- const disableSyncSpy = vi.spyOn(syncService, 'disableSync').mockResolvedValueOnce(false);
-
- const { result } = renderHook(
- () =>
- useUserStore().useEnabledSync(true, {
- userEnableSync: false,
- userId: 'user-id',
- onEvent: vi.fn(),
- }),
-
- { wrapper: withSWR },
- );
-
- await waitFor(() => expect(result.current.data).toBeUndefined());
- expect(disableSyncSpy).toHaveBeenCalled();
- });
-
- it('should call triggerEnableSync when userEnableSync and userId exist', async () => {
- const userId = 'user-id';
- const onEvent = vi.fn();
- const triggerEnableSyncSpy = vi.fn().mockResolvedValueOnce(true);
-
- const { result } = renderHook(() => useUserStore());
-
- // replace triggerEnableSync as a mock
- result.current.triggerEnableSync = triggerEnableSyncSpy;
-
- const { result: swrResult } = renderHook(
- () => result.current.useEnabledSync(true, { userEnableSync: true, userId, onEvent }),
- {
- wrapper: withSWR,
- },
- );
-
- await waitFor(() => expect(swrResult.current.data).toBe(true));
- expect(triggerEnableSyncSpy).toHaveBeenCalledWith(userId, onEvent);
- });
- });
-});
diff --git a/src/store/user/slices/sync/action.ts b/src/store/user/slices/sync/action.ts
deleted file mode 100644
index 4860f5ec5d3..00000000000
--- a/src/store/user/slices/sync/action.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import useSWR, { SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
-
-import type { UserStore } from '@/store/user';
-import { OnSyncEvent, PeerSyncStatus } from '@/types/sync';
-import { browserInfo } from '@/utils/platform';
-import { setNamespace } from '@/utils/storeDebug';
-
-import { userProfileSelectors } from '../auth/selectors';
-import { syncSettingsSelectors } from './selectors';
-
-const n = setNamespace('sync');
-
-/**
- * 设置操作
- */
-export interface SyncAction {
- refreshConnection: (onEvent: OnSyncEvent) => Promise<void>;
- triggerEnableSync: (userId: string, onEvent: OnSyncEvent) => Promise<boolean>;
- useEnabledSync: (
- systemEnable: boolean | undefined,
- params: {
- onEvent: OnSyncEvent;
- userEnableSync: boolean;
- userId: string | undefined;
- },
- ) => SWRResponse;
-}
-
-export const createSyncSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- SyncAction
-> = (set, get) => ({
- refreshConnection: async (onEvent) => {
- const userId = userProfileSelectors.userId(get());
-
- if (!userId) return;
-
- await get().triggerEnableSync(userId, onEvent);
- },
-
- triggerEnableSync: async (userId: string, onEvent: OnSyncEvent) => {
- // double-check the sync ability
- // if there is no channelName, don't start sync
- const sync = syncSettingsSelectors.webrtcConfig(get());
- if (!sync.channelName || !sync.signaling) return false;
-
- const name = syncSettingsSelectors.deviceName(get());
-
- const defaultUserName = `My ${browserInfo.browser} (${browserInfo.os})`;
-
- set({ syncStatus: PeerSyncStatus.Connecting });
- const { syncService } = await import('@/services/sync');
-
- return syncService.enabledSync({
- channel: {
- name: sync.channelName,
- password: sync.channelPassword,
- },
- onAwarenessChange(state) {
- set({ syncAwareness: state });
- },
- onSyncEvent: onEvent,
- onSyncStatusChange: (status) => {
- set({ syncStatus: status });
- },
- signaling: sync.signaling,
- user: {
- id: userId,
- // if user don't set the name, use default name
- name: name || defaultUserName,
- ...browserInfo,
- },
- });
- },
-
- useEnabledSync: (systemEnable, { userEnableSync, userId, onEvent }) =>
- useSWR<boolean>(
- systemEnable ? ['enableSync', userEnableSync, userId] : null,
- async () => {
- // if user don't enable sync or no userId ,don't start sync
- if (!userId) return false;
-
- // if user don't enable sync, stop sync
- if (!userEnableSync) {
- const { syncService } = await import('@/services/sync');
- return syncService.disableSync();
- }
-
- return get().triggerEnableSync(userId, onEvent);
- },
- {
- onSuccess: (syncEnabled) => {
- set({ syncEnabled }, false, n('useEnabledSync'));
- },
- revalidateOnFocus: false,
- },
- ),
-});
diff --git a/src/store/user/slices/sync/initialState.ts b/src/store/user/slices/sync/initialState.ts
deleted file mode 100644
index 9345992102a..00000000000
--- a/src/store/user/slices/sync/initialState.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { PeerSyncStatus, SyncAwarenessState } from '@/types/sync';
-
-export interface UserSyncState {
- syncAwareness: SyncAwarenessState[];
- syncEnabled: boolean;
- syncStatus: PeerSyncStatus;
-}
-
-export const initialSyncState: UserSyncState = {
- syncAwareness: [],
- syncEnabled: false,
- syncStatus: PeerSyncStatus.Disabled,
-};
diff --git a/src/store/user/slices/sync/selectors.ts b/src/store/user/slices/sync/selectors.ts
deleted file mode 100644
index 5fb2f88fce5..00000000000
--- a/src/store/user/slices/sync/selectors.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { DEFAULT_SYNC_CONFIG } from '@/const/settings/sync';
-import { UserSyncSettings } from '@/types/user/settings';
-
-import type { UserStore } from '../../store';
-import { currentSettings } from '../settings/selectors/settings';
-
-const syncConfig = (s: UserStore): UserSyncSettings =>
- currentSettings(s).sync || DEFAULT_SYNC_CONFIG;
-
-const webrtcConfig = (s: UserStore) => syncConfig(s).webrtc;
-const webrtcChannelName = (s: UserStore) => webrtcConfig(s).channelName;
-const enableWebRTC = (s: UserStore) => webrtcConfig(s).enabled;
-const deviceName = (s: UserStore) => syncConfig(s).deviceName;
-
-export const syncSettingsSelectors = {
- deviceName,
- enableWebRTC,
- webrtcChannelName,
- webrtcConfig,
-};
diff --git a/src/store/user/store.ts b/src/store/user/store.ts
index 96ec240e34e..5bc8c712778 100644
--- a/src/store/user/store.ts
+++ b/src/store/user/store.ts
@@ -10,12 +10,10 @@ import { type CommonAction, createCommonSlice } from './slices/common/action';
import { type ModelListAction, createModelListSlice } from './slices/modelList/action';
import { type PreferenceAction, createPreferenceSlice } from './slices/preference/action';
import { type UserSettingsAction, createSettingsSlice } from './slices/settings/action';
-import { type SyncAction, createSyncSlice } from './slices/sync/action';
// =============== 聚合 createStoreFn ============ //
-export type UserStore = SyncAction &
- UserState &
+export type UserStore = UserState &
UserSettingsAction &
PreferenceAction &
ModelListAction &
@@ -24,7 +22,6 @@ export type UserStore = SyncAction &
const createStore: StateCreator<UserStore, [['zustand/devtools', never]]> = (...parameters) => ({
...initialState,
- ...createSyncSlice(...parameters),
...createSettingsSlice(...parameters),
...createPreferenceSlice(...parameters),
...createAuthSlice(...parameters),