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 client service (#9991)

Arvin Xu9137dba6a041
diff --git a/packages/const/src/version.ts b/packages/const/src/version.ts
index 30b5f7f1f9f..27130cf4e4e 100644
--- a/packages/const/src/version.ts
+++ b/packages/const/src/version.ts
@@ -4,12 +4,12 @@ import { BRANDING_NAME, ORG_NAME } from './branding';
export const CURRENT_VERSION = pkg.version;
-export const isServerMode = process.env.NEXT_PUBLIC_SERVICE_MODE === 'server';
-export const isUsePgliteDB = process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite';
+export const isServerMode = true;
+export const isUsePgliteDB = false;
export const isDesktop = process.env.NEXT_PUBLIC_IS_DESKTOP_APP === '1';
-export const isDeprecatedEdition = !isServerMode && !isUsePgliteDB;
+export const isDeprecatedEdition = false;
// @ts-ignore
export const isCustomBranding = BRANDING_NAME !== 'LobeHub';
diff --git a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
index 2ccf64c082b..554bd0289f3 100644
--- a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
+++ b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
@@ -12,12 +12,13 @@ import {
topics,
users,
} from '@/database/schemas';
-import { CURRENT_CONFIG_VERSION } from '@/migrations';
import { ImporterEntryData } from '@/types/importer';
import { DeprecatedDataImporterRepos as DataImporterRepos } from '../index';
import mockImportData from './fixtures/messages.json';
+const CURRENT_CONFIG_VERSION = 7;
+
const serverDB = await getTestDBInstance();
const userId = 'test-user-id';
diff --git a/packages/database/src/repositories/dataImporter/deprecated/index.ts b/packages/database/src/repositories/dataImporter/deprecated/index.ts
index 50a7c9a183f..7a6a5b96b2b 100644
--- a/packages/database/src/repositories/dataImporter/deprecated/index.ts
+++ b/packages/database/src/repositories/dataImporter/deprecated/index.ts
@@ -1,6 +1,5 @@
import { and, eq, inArray, sql } from 'drizzle-orm';
-import { ImportResult } from '@/services/import/_deprecated';
import { ImporterEntryData } from '@/types/importer';
import { sanitizeUTF8 } from '@/utils/sanitizeUTF8';
@@ -16,6 +15,13 @@ import {
} from '../../../schemas';
import { LobeChatDatabase } from '../../../type';
+interface ImportResult {
+ added: number;
+ errors: number;
+ skips: number;
+ updated?: number;
+}
+
export class DeprecatedDataImporterRepos {
private userId: string;
private db: LobeChatDatabase;
diff --git a/src/app/(backend)/trpc/edge/[trpc]/route.ts b/src/app/(backend)/trpc/edge/[trpc]/route.ts
deleted file mode 100644
index 09b45345f25..00000000000
--- a/src/app/(backend)/trpc/edge/[trpc]/route.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
-import type { NextRequest } from 'next/server';
-
-import { pino } from '@/libs/logger';
-import { createEdgeContext } from '@/libs/trpc/edge/context';
-import { edgeRouter } from '@/server/routers/edge';
-
-const handler = (req: NextRequest) =>
- fetchRequestHandler({
- /**
- * @link https://trpc.io/docs/v11/context
- */
- createContext: () => createEdgeContext(req),
-
- endpoint: '/trpc/edge',
-
- onError: ({ error, path }) => {
- pino.info(`Error in tRPC handler (edge) on path: ${path}`);
- console.error(error);
- },
-
- req,
- router: edgeRouter,
- });
-
-export { handler as GET, handler as POST };
diff --git a/src/app/[variants]/(main)/(mobile)/me/(home)/__tests__/useCategory.test.tsx b/src/app/[variants]/(main)/(mobile)/me/(home)/__tests__/useCategory.test.tsx
index 2bea3e18d8d..3e9d9424ee1 100644
--- a/src/app/[variants]/(main)/(mobile)/me/(home)/__tests__/useCategory.test.tsx
+++ b/src/app/[variants]/(main)/(mobile)/me/(home)/__tests__/useCategory.test.tsx
@@ -40,6 +40,15 @@ vi.mock('@/const/auth', () => ({
},
}));
+// Mock version constants
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/const/version')>();
+ return {
+ ...actual,
+ isServerMode: false,
+ };
+});
+
afterEach(() => {
enableAuth = true;
enableClerk = true;
diff --git a/src/app/[variants]/(main)/(mobile)/me/(home)/layout.tsx b/src/app/[variants]/(main)/(mobile)/me/(home)/layout.tsx
index 88ba04e3ff1..0077aaecfa3 100644
--- a/src/app/[variants]/(main)/(mobile)/me/(home)/layout.tsx
+++ b/src/app/[variants]/(main)/(mobile)/me/(home)/layout.tsx
@@ -2,7 +2,6 @@ import { PropsWithChildren, Suspense } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
import MobileContentLayout from '@/components/server/MobileNavLayout';
-import InitClientDB from '@/features/InitClientDB';
import Header from './features/Header';
@@ -10,7 +9,6 @@ const Layout = ({ children }: PropsWithChildren) => {
return (
<MobileContentLayout header={<Header />} withNav>
<Suspense fallback={<Loading />}>{children}</Suspense>
- <InitClientDB />
</MobileContentLayout>
);
};
diff --git a/src/app/[variants]/(main)/(mobile)/me/data/features/Category.tsx b/src/app/[variants]/(main)/(mobile)/me/data/features/Category.tsx
deleted file mode 100644
index 5d5f4596d92..00000000000
--- a/src/app/[variants]/(main)/(mobile)/me/data/features/Category.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import Cell, { CellProps } from '@/components/Cell';
-import DataImporter from '@/features/DataImporter';
-import { configService } from '@/services/export/_deprecated';
-
-const Category = memo(() => {
- const { t } = useTranslation('common');
- const items: CellProps[] = [
- {
- key: 'allAgent',
- label: t('exportType.allAgent'),
- onClick: configService.exportAgents,
- },
- {
- key: 'allAgentWithMessage',
- label: t('exportType.allAgentWithMessage'),
- onClick: configService.exportSessions,
- },
- {
- key: 'globalSetting',
- label: t('exportType.globalSetting'),
- onClick: configService.exportSettings,
- },
- {
- type: 'divider',
- },
- {
- key: 'all',
- label: t('exportType.all'),
- onClick: configService.exportAll,
- },
- {
- type: 'divider',
- },
- {
- key: 'import',
- label: <DataImporter>{t('importData')}</DataImporter>,
- },
- ];
-
- return items?.map(({ key, ...item }, index) => <Cell key={key || index} {...item} />);
-});
-
-export default Category;
diff --git a/src/app/[variants]/(main)/(mobile)/me/data/features/Header.tsx b/src/app/[variants]/(main)/(mobile)/me/data/features/Header.tsx
deleted file mode 100644
index dcd0e34cd6b..00000000000
--- a/src/app/[variants]/(main)/(mobile)/me/data/features/Header.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-'use client';
-
-import { ChatHeader } from '@lobehub/ui/mobile';
-import { useRouter } from 'next/navigation';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { mobileHeaderSticky } from '@/styles/mobileHeader';
-
-const Header = memo(() => {
- const { t } = useTranslation('common');
-
- const router = useRouter();
- return (
- <ChatHeader
- center={
- <ChatHeader.Title
- title={
- <Flexbox align={'center'} gap={4} horizontal>
- {t('userPanel.data')}
- </Flexbox>
- }
- />
- }
- onBackClick={() => router.push('/me')}
- showBackButton
- style={mobileHeaderSticky}
- />
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/(mobile)/me/data/layout.tsx b/src/app/[variants]/(main)/(mobile)/me/data/layout.tsx
deleted file mode 100644
index 6e2a2f2c498..00000000000
--- a/src/app/[variants]/(main)/(mobile)/me/data/layout.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { PropsWithChildren } from 'react';
-
-import MobileContentLayout from '@/components/server/MobileNavLayout';
-
-import Header from './features/Header';
-
-const Layout = ({ children }: PropsWithChildren) => {
- return <MobileContentLayout header={<Header />}>{children}</MobileContentLayout>;
-};
-
-Layout.displayName = 'MeDataLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/(mobile)/me/data/loading.tsx b/src/app/[variants]/(main)/(mobile)/me/data/loading.tsx
deleted file mode 100644
index d73434fcb68..00000000000
--- a/src/app/[variants]/(main)/(mobile)/me/data/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import SkeletonLoading from '@/components/Loading/SkeletonLoading';
-
-export default () => {
- return <SkeletonLoading paragraph={{ rows: 8 }} />;
-};
diff --git a/src/app/[variants]/(main)/(mobile)/me/data/page.tsx b/src/app/[variants]/(main)/(mobile)/me/data/page.tsx
deleted file mode 100644
index e990c3b119e..00000000000
--- a/src/app/[variants]/(main)/(mobile)/me/data/page.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { redirect } from 'next/navigation';
-
-import { metadataModule } from '@/server/metadata';
-import { translation } from '@/server/translation';
-import { DynamicLayoutProps } from '@/types/next';
-import { RouteVariants } from '@/utils/server/routeVariants';
-
-import Category from './features/Category';
-
-export const generateMetadata = async (props: DynamicLayoutProps) => {
- const locale = await RouteVariants.getLocale(props);
- const { t } = await translation('common', locale);
- return metadataModule.generate({
- title: t('userPanel.data'),
- url: '/me/data',
- });
-};
-
-const Page = async (props: DynamicLayoutProps) => {
- const mobile = await RouteVariants.getIsMobile(props);
-
- if (!mobile) return redirect('/chat');
-
- return <Category />;
-};
-
-Page.displayName = 'MeData';
-
-export default Page;
diff --git a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
index 37b1d8f0b86..1baaa4825bf 100644
--- a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
+++ b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/Actions.tsx
@@ -1,3 +1,5 @@
+import { isDesktop } from '@lobechat/const';
+import { SessionDefaultGroup } from '@lobechat/types';
import { ActionIcon, Dropdown, Icon } from '@lobehub/ui';
import { App } from 'antd';
import { createStyles } from 'antd-style';
@@ -6,7 +8,6 @@ import isEqual from 'fast-deep-equal';
import {
Check,
ExternalLink,
- HardDriveDownload,
ListTree,
LucideCopy,
LucidePlus,
@@ -18,14 +19,11 @@ import {
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { isDesktop, isServerMode } from '@/const/version';
-import { configService } from '@/services/config';
-import { useGlobalStore } from '@/store/global';
import { useChatGroupStore } from '@/store/chatGroup';
+import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { sessionHelpers } from '@/store/session/helpers';
import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
-import { SessionDefaultGroup } from '@/types/session';
const useStyles = createStyles(({ css }) => ({
modalRoot: css`
@@ -148,29 +146,6 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
{
type: 'divider',
},
- isServerMode
- ? undefined
- : {
- children: [
- {
- key: 'agent',
- label: t('exportType.agent', { ns: 'common' }),
- onClick: () => {
- configService.exportSingleAgent(id);
- },
- },
- {
- key: 'agentWithMessage',
- label: t('exportType.agentWithMessage', { ns: 'common' }),
- onClick: () => {
- configService.exportSingleSession(id);
- },
- },
- ],
- icon: <Icon icon={HardDriveDownload} />,
- key: 'export',
- label: t('export', { ns: 'common' }),
- },
{
danger: true,
icon: <Icon icon={Trash} />,
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx
index 810aad90453..ba76fc26c7a 100644
--- a/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx
@@ -2,7 +2,6 @@ import { Suspense } from 'react';
import { Flexbox } from 'react-layout-kit';
import { isDesktop } from '@/const/version';
-import InitClientDB from '@/features/InitClientDB';
import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';
import { LayoutProps } from '../type';
@@ -22,7 +21,6 @@ const Layout = ({ children, session }: LayoutProps) => {
<SessionPanel>{session}</SessionPanel>
<Workspace>{children}</Workspace>
</Flexbox>
- {!isDesktop && <InitClientDB bottom={60} />}
{/* ↓ cloud slot ↓ */}
{/* ↑ cloud slot ↑ */}
diff --git a/src/app/[variants]/(main)/chat/_layout/Mobile.tsx b/src/app/[variants]/(main)/chat/_layout/Mobile.tsx
index e35d7719141..f0a2b9db18c 100644
--- a/src/app/[variants]/(main)/chat/_layout/Mobile.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Mobile.tsx
@@ -1,11 +1,10 @@
'use client';
import { createStyles } from 'antd-style';
-import { Suspense, memo } from 'react';
+import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { withSuspense } from '@/components/withSuspense';
-import InitClientDB from '@/features/InitClientDB';
import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';
import { LayoutProps } from './type';
@@ -40,9 +39,6 @@ const Layout = memo<LayoutProps>(({ children, session }) => {
>
{children}
</Flexbox>
- <Suspense>
- <InitClientDB bottom={100} />
- </Suspense>
</>
);
});
diff --git a/src/app/[variants]/(main)/chat/features/Migration/DBReader.ts b/src/app/[variants]/(main)/chat/features/Migration/DBReader.ts
deleted file mode 100644
index 3a5667bc409..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/DBReader.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-import {
- ImportMessage,
- ImportSession,
- ImportSessionGroup,
- ImportTopic,
- ImporterEntryData,
-} from '@/types/importer';
-
-interface V2DB_File {
- /**
- * create Time
- */
- createdAt: number;
- /**
- * file data array buffer
- */
- data: ArrayBuffer;
- /**
- * file type
- * @example 'image/png'
- */
- fileType: string;
- id: string;
- metadata: any;
- /**
- * file name
- * @example 'test.png'
- */
- name: string;
- /**
- * the mode database save the file
- * local mean save the raw file into data
- * url mean upload the file to a cdn and then save the url
- */
- saveMode: 'local' | 'url';
- /**
- * file size
- */
- size: number;
- /**
- * file url if saveMode is url
- */
- url: string;
-}
-
-interface V2DB_MESSAGE {
- content: string;
- createdAt: number;
- error?: any;
- favorite: 0 | 1;
- files?: string[];
- fromModel?: string;
- fromProvider?: string;
- id: string;
- observationId?: string;
- // foreign keys
- parentId?: string;
- plugin?: any;
- pluginError?: any;
- pluginState?: any;
-
- quotaId?: string;
- role: string;
- sessionId?: string;
- tool_call_id?: string;
- tools?: object[];
- topicId?: string;
-
- traceId?: string;
- translate?: object | false;
- tts?: any;
- updatedAt: number;
-}
-
-interface DB_Plugin {
- createdAt: number;
- id: string;
- identifier: string;
- manifest?: object;
- settings?: object;
- type: 'plugin' | 'customPlugin';
- updatedAt: number;
-}
-
-interface DB_Session {
- config: object;
- createdAt: number;
- group?: string;
- // 原 Agent 类型
- id: string;
- meta: object;
- pinned?: number;
- type?: 'agent' | 'group';
- updatedAt: number;
-}
-
-interface DB_SessionGroup {
- createdAt: number;
- id: string;
- name: string;
- sort?: number;
- updatedAt: number;
-}
-
-interface DB_Topic {
- createdAt: number;
- favorite?: number;
- id: string;
- sessionId?: string;
- title: string;
- updatedAt: number;
-}
-
-interface DB_User {
- avatar?: string;
- createdAt: number;
- id: string;
- settings: object;
- updatedAt: number;
- uuid: string;
-}
-
-interface MigrationData {
- files: V2DB_File[];
- messages: V2DB_MESSAGE[];
- plugins: DB_Plugin[];
- sessionGroups: DB_SessionGroup[];
- sessions: DB_Session[];
- topics: DB_Topic[];
- users: DB_User[];
-}
-
-const LOBE_CHAT_LOCAL_DB_NAME = 'LOBE_CHAT_DB';
-
-const V2DB_LASET_SCHEMA_VERSION = 7;
-export class V2DBReader {
- private dbName: string = LOBE_CHAT_LOCAL_DB_NAME;
- private storeNames: string[];
-
- constructor(storeNames: string[]) {
- this.storeNames = storeNames;
- }
-
- /**
- * 读取所有数据
- */
- async readAllData(): Promise<MigrationData> {
- try {
- // 打开数据库连接
- const db = await this.openDB();
-
- // 并行读取所有表的数据
- const results = await Promise.all(
- this.storeNames.map((storeName) => this.readStore(db, storeName)),
- );
-
- // 构建返回结果
- const migrationData = this.storeNames.reduce((acc, storeName, index) => {
- // @ts-expect-error
- acc[storeName] = results[index];
- return acc;
- }, {} as MigrationData);
-
- // 关闭数据库连接
- db.close();
-
- return migrationData;
- } catch (error) {
- console.error('读取数据库失败:', error);
- throw error;
- }
- }
-
- async convertToImportData(data: MigrationData): Promise<ImporterEntryData> {
- // 转换 messages
- const messages = data.messages.map(
- (msg): ImportMessage => ({
- // 使用原有的 id
- content: msg.content,
- createdAt: msg.createdAt,
- // 处理 error
- error: msg.error || msg.pluginError,
-
- // 处理额外信息
- extra: {
- fromModel: msg.fromModel,
- fromProvider: msg.fromProvider,
- translate: msg.translate as any,
- tts: msg.tts,
- },
-
- files: msg.files,
- id: msg.id,
-
- // 复制原有字段
- observationId: msg.observationId,
- parentId: msg.parentId,
- plugin: msg.plugin,
- pluginState: msg.pluginState,
- quotaId: msg.quotaId,
- role: msg.role as any,
- sessionId: msg.sessionId,
- tool_call_id: msg.tool_call_id,
- tools: msg.tools as any,
-
- topicId: msg.topicId,
-
- traceId: msg.traceId,
-
- updatedAt: msg.updatedAt,
- }),
- );
-
- // 转换 sessionGroups
- const sessionGroups = data.sessionGroups.map(
- (group): ImportSessionGroup => ({
- createdAt: group.createdAt,
- id: group.id,
- // 使用原有的 id
- name: group.name,
- sort: group.sort || null,
- updatedAt: group.updatedAt,
- }),
- );
-
- // 转换 sessions
- const sessions = data.sessions.map(
- (session): ImportSession => ({
- // 使用原有的 id
- config: session.config as any,
- createdAt: new Date(session.createdAt).toString(),
- group: session.group,
- id: session.id,
- meta: session.meta as any,
- pinned: session.pinned ? true : undefined,
- type: session.type || 'agent',
- updatedAt: new Date(session.updatedAt).toString(),
- }),
- );
-
- const topics = data.topics.map(
- (topic): ImportTopic => ({
- ...topic,
- favorite: topic.favorite ? true : undefined,
- }),
- );
-
- return {
- messages,
- sessionGroups,
- sessions,
- topics,
- version: V2DB_LASET_SCHEMA_VERSION,
- };
- }
-
- /**
- * 打开数据库
- */
- private openDB(): Promise<IDBDatabase> {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(this.dbName);
-
- // eslint-disable-next-line unicorn/prefer-add-event-listener
- request.onerror = () => {
- reject(request.error);
- };
- request.onsuccess = () => resolve(request.result);
- });
- }
-
- /**
- * 读取单个存储对象的所有数据
- */
- private readStore(db: IDBDatabase, storeName: string): Promise<any[]> {
- return new Promise((resolve, reject) => {
- try {
- const transaction = db.transaction(storeName, 'readonly');
- const store = transaction.objectStore(storeName);
- const request = store.getAll();
-
- // eslint-disable-next-line unicorn/prefer-add-event-listener
- request.onerror = () => reject(request.error);
- request.onsuccess = () => resolve(request.result);
- } catch (error) {
- reject(error);
- }
- });
- }
-}
diff --git a/src/app/[variants]/(main)/chat/features/Migration/ExportConfigButton.tsx b/src/app/[variants]/(main)/chat/features/Migration/ExportConfigButton.tsx
deleted file mode 100644
index d64b63e42de..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/ExportConfigButton.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Button } from '@lobehub/ui';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { BRANDING_NAME } from '@/const/branding';
-
-const ExportConfigButton = memo<{ primary?: boolean; state: any }>(({ state, primary }) => {
- const { t } = useTranslation('migration');
-
- const exportData = () => {
- const config = { exportType: 'sessions', state, version: 1 };
-
- const url = URL.createObjectURL(
- new Blob([JSON.stringify(config)], { type: 'application/json' }),
- );
-
- const a = document.createElement('a');
- a.href = url;
- a.download = `${BRANDING_NAME}-backup-v1.json`;
-
- document.body.append(a);
- a.click();
-
- URL.revokeObjectURL(url);
- a.remove();
- };
-
- return (
- <Button onClick={exportData} size={'large'} type={primary ? 'primary' : undefined}>
- {t('dbV1.action.downloadBackup')}
- </Button>
- );
-});
-
-export default ExportConfigButton;
diff --git a/src/app/[variants]/(main)/chat/features/Migration/Failed.tsx b/src/app/[variants]/(main)/chat/features/Migration/Failed.tsx
deleted file mode 100644
index 8471bc6844c..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/Failed.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { Alert, Button, Highlighter, Icon } from '@lobehub/ui';
-import { Popconfirm, Result } from 'antd';
-import { useTheme } from 'antd-style';
-import { createStore, del, get, set } from 'idb-keyval';
-import { ShieldAlert } from 'lucide-react';
-import Link from 'next/link';
-import { lighten } from 'polished';
-import { memo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import Balancer from 'react-wrap-balancer';
-
-import { GITHUB_ISSUES } from '@/const/url';
-import { githubService } from '@/services/github';
-
-import ExportConfigButton from './ExportConfigButton';
-import UpgradeButton from './UpgradeButton';
-import { MigrationError, UpgradeStatus, V1DB_NAME, V1DB_TABLE_NAME } from './const';
-
-const clearLocal = async () => {
- const store = createStore(V1DB_NAME, V1DB_TABLE_NAME);
- // delete the state key and back it up to state_backup for reproduce
- const state = await get('state', store);
- await del('state');
- await set('state_backup', state, store);
- location.reload();
-};
-
-interface FailedProps {
- error?: MigrationError;
- setError: (error: MigrationError) => void;
- setUpgradeStatus: (status: UpgradeStatus) => void;
- state: any;
- upgradeStatus: UpgradeStatus;
-}
-const Failed = memo<FailedProps>(({ error, state, setUpgradeStatus, setError, upgradeStatus }) => {
- const { t } = useTranslation('migration');
- const theme = useTheme();
-
- return (
- <Result
- extra={
- <Flexbox gap={24}>
- {!!error && (
- <Alert
- extra={
- <Highlighter actionIconSize={'small'} language={'json'}>
- {JSON.stringify(error)}
- </Highlighter>
- }
- message={error.message}
- style={{ flex: 1 }}
- type={'error'}
- />
- )}
- <Flexbox
- gap={16}
- horizontal
- justify={'center'}
- style={{
- alignSelf: 'center',
- flexWrap: 'wrap',
- }}
- >
- <ExportConfigButton primary state={state} />
- <Popconfirm
- arrow={false}
- okButtonProps={{
- danger: true,
- type: 'primary',
- }}
- onConfirm={clearLocal}
- styles={{
- body: { background: lighten(0.03, theme.colorBgElevated) },
- root: { width: 340 },
- }}
- title={t('dbV1.clear.confirm')}
- >
- <Button size={'large'}>{t('dbV1.action.clearDB')}</Button>
- </Popconfirm>
- <UpgradeButton
- primary={false}
- setError={setError}
- setUpgradeStatus={setUpgradeStatus}
- state={state}
- upgradeStatus={upgradeStatus}
- >
- {t('dbV1.action.reUpgrade')}
- </UpgradeButton>
- </Flexbox>
- </Flexbox>
- }
- icon={<Icon icon={ShieldAlert} />}
- status={'error'}
- style={{ paddingBlock: 24, width: 450 }}
- subTitle={
- <Balancer>
- <Trans i18nKey="dbV1.upgrade.error.subTitle" ns={'migration'}>
- 非常抱歉,数据库升级过程发生异常。请重试升级,或
- <Link
- aria-label={'issue'}
- href={GITHUB_ISSUES}
- onClick={(e) => {
- e.preventDefault();
- githubService.submitDBV1UpgradeError(1, error!);
- }}
- target="_blank"
- >
- 提交问题
- </Link>
- 我们将会第一时间帮你排查问题。
- </Trans>
- </Balancer>
- }
- title={t('dbV1.upgrade.error.title')}
- />
- );
-});
-
-export default Failed;
diff --git a/src/app/[variants]/(main)/chat/features/Migration/Modal.tsx b/src/app/[variants]/(main)/chat/features/Migration/Modal.tsx
deleted file mode 100644
index 7b4fd0ba5f6..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/Modal.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { Button, Icon } from '@lobehub/ui';
-import { Result } from 'antd';
-import { CheckCircle, CpuIcon } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center } from 'react-layout-kit';
-
-import DataStyleModal from '@/components/DataStyleModal';
-import { BRANDING_NAME } from '@/const/branding';
-
-import Failed from './Failed';
-import MigrationStart from './Start';
-import { MigrationError, UpgradeStatus } from './const';
-
-interface MigrationModalProps {
- open: boolean;
- setOpen: (open: boolean) => void;
- state: any;
-}
-
-const MigrationModal = memo<MigrationModalProps>(({ setOpen, open, state: dbState }) => {
- const { t } = useTranslation('migration');
- const [upgradeStatus, setUpgradeStatus] = useState<UpgradeStatus>(UpgradeStatus.START);
-
- const [error, setError] = useState<MigrationError>();
-
- const close = () => {
- setOpen(false);
- };
-
- const renderContent = () => {
- switch (upgradeStatus) {
- case UpgradeStatus.START:
- case UpgradeStatus.UPGRADING: {
- return (
- <MigrationStart
- setError={setError}
- setUpgradeStatus={setUpgradeStatus}
- state={dbState}
- upgradeStatus={upgradeStatus}
- />
- );
- }
- case UpgradeStatus.UPGRADED: {
- return (
- <Result
- extra={
- <Button onClick={close} size={'large'} type={'primary'}>
- {t('dbV1.action.start')}
- </Button>
- }
- icon={<Icon icon={CheckCircle} />}
- status={'success'}
- style={{ paddingBlock: 24 }}
- subTitle={t('dbV1.upgrade.success.subTitle', { appName: BRANDING_NAME })}
- title={t('dbV1.upgrade.success.title')}
- />
- );
- }
- case UpgradeStatus.UPGRADE_FAILED: {
- return (
- <Failed
- error={error}
- setError={setError}
- setUpgradeStatus={setUpgradeStatus}
- state={dbState}
- upgradeStatus={upgradeStatus}
- />
- );
- }
- }
- };
-
- return (
- <DataStyleModal icon={CpuIcon} open={open} title={t('dbV1.title', { appName: BRANDING_NAME })}>
- <Center gap={48}>{renderContent()}</Center>
- </DataStyleModal>
- );
-});
-
-export default MigrationModal;
diff --git a/src/app/[variants]/(main)/chat/features/Migration/Start.tsx b/src/app/[variants]/(main)/chat/features/Migration/Start.tsx
deleted file mode 100644
index bacbe9c7036..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/Start.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { Icon } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { Database, SearchCheck, Zap } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center, Flexbox } from 'react-layout-kit';
-import Balancer from 'react-wrap-balancer';
-
-import { BRANDING_NAME } from '@/const/branding';
-
-import ExportConfigButton from './ExportConfigButton';
-import UpgradeButton, { UpgradeButtonProps } from './UpgradeButton';
-
-const useStyles = createStyles(({ css, token, isDarkMode, responsive }) => ({
- desc: css`
- width: 280px;
- color: ${token.colorTextSecondary};
-
- ${responsive.mobile} {
- line-height: ${token.lineHeight};
- }
- `,
- hint: css`
- font-size: ${token.fontSizeSM}px;
- color: ${token.colorTextTertiary};
- text-align: center;
- `,
- icon: css`
- color: ${isDarkMode ? token.blue : token.geekblue};
- `,
- iconCtn: css`
- width: 72px;
- height: 72px;
- border-radius: 50%;
- background: ${isDarkMode ? token.blue1 : token.geekblue1};
- `,
- intro: css`
- ${responsive.mobile} {
- width: 350px;
- margin-block-start: 24px;
- line-height: ${token.lineHeight};
- }
- `,
-
- title: css`
- font-size: ${token.fontSizeLG}px;
- font-weight: bold;
- `,
-}));
-
-const MigrationStart = memo<UpgradeButtonProps>((props) => {
- const { t } = useTranslation('migration');
- const { styles } = useStyles();
-
- const features = [
- {
- avatar: Database,
- desc: t('dbV1.features.capability.desc'),
- title: t('dbV1.features.capability.title'),
- },
- {
- avatar: Zap,
- desc: t('dbV1.features.performance.desc'),
- title: t('dbV1.features.performance.title'),
- },
- {
- avatar: SearchCheck,
- desc: t('dbV1.features.use.desc'),
- title: t('dbV1.features.use.title'),
- },
- ];
-
- return (
- <>
- <Flexbox>
- <Flexbox className={styles.intro} style={{ textAlign: 'center' }} width={460}>
- {t('dbV1.description', { appName: BRANDING_NAME })}
- </Flexbox>
- </Flexbox>
- <Flexbox gap={32}>
- {features.map((item) => {
- return (
- <Flexbox align={'flex-start'} gap={24} horizontal key={item.title}>
- <Center className={styles.iconCtn}>
- <Icon className={styles.icon} icon={item.avatar} size={36} />
- </Center>
- <Flexbox gap={8}>
- <p className={styles.title}>{item.title}</p>
- <p className={styles.desc}>{item.desc}</p>
- </Flexbox>
- </Flexbox>
- );
- })}
- </Flexbox>
- <Flexbox align={'center'} gap={16} style={{ paddingBottom: 16 }}>
- <Flexbox gap={16} horizontal justify={'center'} style={{ flexWrap: 'wrap' }}>
- <ExportConfigButton state={props.state} />
- <UpgradeButton {...props} />
- </Flexbox>
- <Flexbox align={'center'} className={styles.hint}>
- <Balancer>{t('dbV1.upgradeTip', { appName: BRANDING_NAME })}</Balancer>
- </Flexbox>
- </Flexbox>
- </>
- );
-});
-
-export default MigrationStart;
diff --git a/src/app/[variants]/(main)/chat/features/Migration/UpgradeButton.tsx b/src/app/[variants]/(main)/chat/features/Migration/UpgradeButton.tsx
deleted file mode 100644
index 89ca06b344a..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/UpgradeButton.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Button } from '@lobehub/ui';
-import { ReactNode, memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { ClientService } from '@/services/import/_deprecated';
-import { useChatStore } from '@/store/chat';
-import { useSessionStore } from '@/store/session';
-
-import { MigrationError, UpgradeStatus } from './const';
-
-export interface UpgradeButtonProps {
- children?: ReactNode;
- primary?: boolean;
- setError: (error: MigrationError) => void;
- setUpgradeStatus: (status: UpgradeStatus) => void;
- state: any;
- upgradeStatus: UpgradeStatus;
-}
-
-const UpgradeButton = memo<UpgradeButtonProps>(
- ({ setUpgradeStatus, upgradeStatus, state, setError, primary = true, children }) => {
- const { t } = useTranslation('migration');
-
- const refreshSession = useSessionStore((s) => s.refreshSessions);
- const [refreshMessages, refreshTopic] = useChatStore((s) => [
- s.refreshMessages,
- s.refreshTopic,
- ]);
-
- const upgrade = async () => {
- try {
- setUpgradeStatus(UpgradeStatus.UPGRADING);
-
- const configService = new ClientService();
- await configService.importConfigState({
- exportType: 'sessions',
- state: state,
- version: 7,
- });
-
- await refreshSession();
- await refreshMessages();
- await refreshTopic();
-
- localStorage.setItem('V2DB_IS_MIGRATED', '1');
-
- setUpgradeStatus(UpgradeStatus.UPGRADED);
-
- return { success: true };
- } catch (error) {
- setUpgradeStatus(UpgradeStatus.UPGRADE_FAILED);
- const err = error as { message: string; stack: string };
-
- setError({ message: err.message, stack: err.stack });
- }
- };
-
- return (
- <Button
- color={primary ? undefined : 'default'}
- loading={upgradeStatus === UpgradeStatus.UPGRADING}
- onClick={upgrade}
- size={'large'}
- >
- {children ?? t('dbV1.action.upgrade')}
- </Button>
- );
- },
-);
-
-export default UpgradeButton;
diff --git a/src/app/[variants]/(main)/chat/features/Migration/const.ts b/src/app/[variants]/(main)/chat/features/Migration/const.ts
deleted file mode 100644
index 2006283d440..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/const.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export const MIGRATE_KEY = 'migrated';
-export enum UpgradeStatus {
- START,
- UPGRADING,
- UPGRADED,
- UPGRADE_FAILED,
-}
-
-export const V1DB_NAME = 'LobeHub';
-export const V1DB_TABLE_NAME = 'LOBE_CHAT';
-
-export interface MigrationError {
- message: string;
- stack: string;
-}
diff --git a/src/app/[variants]/(main)/chat/features/Migration/index.tsx b/src/app/[variants]/(main)/chat/features/Migration/index.tsx
deleted file mode 100644
index 4313ce4c2df..00000000000
--- a/src/app/[variants]/(main)/chat/features/Migration/index.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-'use client';
-
-import { Spin } from 'antd';
-import dynamic from 'next/dynamic';
-import { memo, useEffect, useState } from 'react';
-
-import { isServerMode } from '@/const/version';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-import { V2DBReader } from './DBReader';
-
-const Modal = dynamic(() => import('./Modal'), { loading: () => <Spin fullscreen />, ssr: false });
-
-const Migration = memo(() => {
- const [dbState, setDbState] = useState(null);
- const [open, setOpen] = useState(false);
-
- const isPgliteInited = useGlobalStore(systemStatusSelectors.isPgliteInited);
-
- const checkMigration = async () => {
- const isMigrated = localStorage.getItem('V2DB_IS_MIGRATED');
- // if db have migrated already, don't show modal
- if (isMigrated || isServerMode) return;
-
- const dbReader = new V2DBReader([
- 'messages',
- 'files',
- 'plugins',
- 'sessionGroups',
- 'sessions',
- 'topics',
- 'users',
- ]);
- const data = await dbReader.readAllData();
- console.log('migration data:', data);
- const state = await dbReader.convertToImportData(data);
- console.log('import state', state);
- setDbState(state as any);
- setOpen(true);
- };
-
- useEffect(() => {
- if (isPgliteInited) checkMigration();
- }, [isPgliteInited]);
-
- return open && <Modal open={open} setOpen={setOpen} state={dbState} />;
-});
-
-export default Migration;
diff --git a/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx b/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx
index e5e370b4942..5cc40e9be39 100644
--- a/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx
+++ b/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx
@@ -1,69 +1,9 @@
-import { ActionIcon, Button, Dropdown, type MenuProps } from '@lobehub/ui';
-import { HardDriveDownload } from 'lucide-react';
-import { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { isServerMode } from '@/const/version';
-import { configService } from '@/services/config';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
+import { memo } from 'react';
import SubmitAgentButton from './SubmitAgentButton';
export const HeaderContent = memo<{ mobile?: boolean; modal?: boolean }>(({ modal }) => {
- const { t } = useTranslation('setting');
- const id = useSessionStore((s) => s.activeId);
-
- const mobile = useServerConfigStore((s) => s.isMobile);
-
- const items = useMemo<MenuProps['items']>(
- () =>
- isServerMode
- ? []
- : [
- {
- key: 'agent',
- label: <div>{t('exportType.agent', { ns: 'common' })}</div>,
- onClick: () => {
- if (!id) return;
-
- configService.exportSingleAgent(id);
- },
- },
- {
- key: 'agentWithMessage',
- label: <div>{t('exportType.agentWithMessage', { ns: 'common' })}</div>,
- onClick: () => {
- if (!id) return;
-
- configService.exportSingleSession(id);
- },
- },
- ],
- [],
- );
-
- return (
- <>
- <SubmitAgentButton modal={modal} />
- {!isServerMode && (
- <Dropdown arrow={false} menu={{ items }} trigger={['click']}>
- {modal ? (
- <Button block icon={HardDriveDownload} variant={'filled'}>
- {t('export', { ns: 'common' })}
- </Button>
- ) : (
- <ActionIcon
- icon={HardDriveDownload}
- size={HEADER_ICON_SIZE(mobile)}
- title={t('export', { ns: 'common' })}
- />
- )}
- </Dropdown>
- )}
- </>
- );
+ return <SubmitAgentButton modal={modal} />;
});
export default HeaderContent;
diff --git a/src/app/[variants]/(main)/image/page.tsx b/src/app/[variants]/(main)/image/page.tsx
index c85f722bd34..56439467e53 100644
--- a/src/app/[variants]/(main)/image/page.tsx
+++ b/src/app/[variants]/(main)/image/page.tsx
@@ -2,7 +2,6 @@ import { Suspense } from 'react';
import StructuredData from '@/components/StructuredData';
import { BRANDING_NAME } from '@/const/branding';
-import InitClientDB from '@/features/InitClientDB';
import { ldModule } from '@/server/ld';
import { metadataModule } from '@/server/metadata';
import { translation } from '@/server/translation';
@@ -34,7 +33,6 @@ const AiImage = async (props: DynamicLayoutProps) => {
return (
<>
<StructuredData ld={ld} />
- <InitClientDB bottom={100} />
<Suspense fallback={<SkeletonList />}>
<ImageWorkspace />
</Suspense>
diff --git a/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx
index 145c7aceec6..b9c73ce957d 100644
--- a/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx
+++ b/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx
@@ -5,7 +5,6 @@ import { memo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import InitClientDB from '@/features/InitClientDB';
import Footer from '@/features/Setting/Footer';
import SettingContainer from '@/features/Setting/SettingContainer';
import { useActiveProfileKey } from '@/hooks/useActiveTabKey';
@@ -21,30 +20,30 @@ const Layout = memo<LayoutProps>(({ children, category }) => {
const activeKey = useActiveProfileKey();
return (
- <>
- <Flexbox
- height={'100%'}
- horizontal={md}
- ref={ref}
- style={{ position: 'relative' }}
- width={'100%'}
+ <Flexbox
+ height={'100%'}
+ horizontal={md}
+ ref={ref}
+ style={{ position: 'relative' }}
+ width={'100%'}
+ >
+ {md ? (
+ <SideBar>{category}</SideBar>
+ ) : (
+ <Header getContainer={() => ref.current} title={<>{t(`tab.${activeKey}`)}</>}>
+ {category}
+ </Header>
+ )}
+ <SettingContainer
+ addonAfter={<Footer />}
+ style={{
+ paddingBlock: 24,
+ paddingInline: 32,
+ }}
>
- {md ? (
- <SideBar>{category}</SideBar>
- ) : (
- <Header getContainer={() => ref.current} title={<>{t(`tab.${activeKey}`)}</>}>
- {category}
- </Header>
- )}
- <SettingContainer
- addonAfter={<Footer />}
- style={{
- paddingBlock: 24,
- paddingInline: 32,
- }}>{children}</SettingContainer>
- </Flexbox>
- <InitClientDB />
- </>
+ {children}
+ </SettingContainer>
+ </Flexbox>
);
});
diff --git a/src/app/[variants]/(main)/profile/_layout/Mobile/index.tsx b/src/app/[variants]/(main)/profile/_layout/Mobile/index.tsx
index c972d95a39f..80c194d2e44 100644
--- a/src/app/[variants]/(main)/profile/_layout/Mobile/index.tsx
+++ b/src/app/[variants]/(main)/profile/_layout/Mobile/index.tsx
@@ -1,5 +1,4 @@
import MobileContentLayout from '@/components/server/MobileNavLayout';
-import InitClientDB from '@/features/InitClientDB';
import Footer from '@/features/Setting/Footer';
import { LayoutProps } from '../type';
@@ -7,14 +6,11 @@ import Header from './Header';
const Layout = ({ children }: LayoutProps) => {
return (
- <>
- <MobileContentLayout header={<Header />}>
- {children}
- <div style={{ flex: 1 }} />
- <Footer />
- </MobileContentLayout>
- <InitClientDB />
- </>
+ <MobileContentLayout header={<Header />}>
+ {children}
+ <div style={{ flex: 1 }} />
+ <Footer />
+ </MobileContentLayout>
);
};
diff --git a/src/app/[variants]/(main)/settings/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/settings/_layout/Desktop/index.tsx
index 4af7a095559..1732a8d767e 100644
--- a/src/app/[variants]/(main)/settings/_layout/Desktop/index.tsx
+++ b/src/app/[variants]/(main)/settings/_layout/Desktop/index.tsx
@@ -5,7 +5,6 @@ import { parseAsStringEnum, useQueryState } from 'nuqs';
import { memo, useRef } from 'react';
import { Flexbox } from 'react-layout-kit';
-import InitClientDB from '@/features/InitClientDB';
import SettingContainer from '@/features/Setting/SettingContainer';
import { SettingsTabs } from '@/store/global/initialState';
@@ -43,7 +42,6 @@ const Layout = memo<LayoutProps>((props) => {
<SettingContainer maxWidth={'none'}>
<SettingsContent activeTab={activeTab} mobile={false} showLLM={showLLM} />
</SettingContainer>
- <InitClientDB />
</Flexbox>
);
});
diff --git a/src/app/[variants]/(main)/settings/_layout/Mobile/index.tsx b/src/app/[variants]/(main)/settings/_layout/Mobile/index.tsx
index 558ec38966a..d353143f96d 100644
--- a/src/app/[variants]/(main)/settings/_layout/Mobile/index.tsx
+++ b/src/app/[variants]/(main)/settings/_layout/Mobile/index.tsx
@@ -3,7 +3,6 @@
import { useQueryState } from 'nuqs';
import MobileContentLayout from '@/components/server/MobileNavLayout';
-import InitClientDB from '@/features/InitClientDB';
import Footer from '@/features/Setting/Footer';
import { SettingsTabs } from '@/store/global/initialState';
@@ -19,7 +18,6 @@ const Layout = () => {
<MobileContentLayout header={<Header />}>
<SettingsContent activeTab={activeTab} mobile={true} />
<Footer />
- <InitClientDB />
</MobileContentLayout>
);
};
diff --git a/src/app/[variants]/loading/Client/Content.tsx b/src/app/[variants]/loading/Client/Content.tsx
deleted file mode 100644
index 262ab7790cc..00000000000
--- a/src/app/[variants]/loading/Client/Content.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import dynamic from 'next/dynamic';
-import React, { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import FullscreenLoading from '@/components/Loading/FullscreenLoading';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { DatabaseLoadingState } from '@/types/clientDB';
-
-import { CLIENT_LOADING_STAGES } from '../stage';
-
-const InitError = dynamic(() => import('./Error'), { ssr: false });
-
-interface InitProps {
- setActiveStage: (value: string) => void;
-}
-
-const Init = memo<InitProps>(({ setActiveStage }) => {
- const useInitClientDB = useGlobalStore((s) => s.useInitClientDB);
-
- useInitClientDB({ onStateChange: setActiveStage });
-
- return null;
-});
-
-interface ContentProps {
- loadingStage: string;
- setActiveStage: (value: string) => void;
-}
-
-const Content = memo<ContentProps>(({ loadingStage, setActiveStage }) => {
- const { t } = useTranslation('common');
- const isPgliteNotInited = useGlobalStore(systemStatusSelectors.isPgliteNotInited);
- const isError = useGlobalStore((s) => s.initClientDBStage === DatabaseLoadingState.Error);
-
- return (
- <>
- {isPgliteNotInited && <Init setActiveStage={setActiveStage} />}
- <FullscreenLoading
- activeStage={CLIENT_LOADING_STAGES.indexOf(loadingStage)}
- contentRender={isError && <InitError />}
- stages={CLIENT_LOADING_STAGES.map((key) => t(`appLoading.${key}` as any))}
- />
- </>
- );
-});
-
-export default Content;
diff --git a/src/app/[variants]/loading/Client/Error.tsx b/src/app/[variants]/loading/Client/Error.tsx
deleted file mode 100644
index 29ce8ff1e7b..00000000000
--- a/src/app/[variants]/loading/Client/Error.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { Button } from '@lobehub/ui';
-import React from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center } from 'react-layout-kit';
-
-import ErrorResult from '@/features/InitClientDB/ErrorResult';
-
-const InitError = () => {
- const { t } = useTranslation('common');
-
- return (
- <ErrorResult>
- {({ setOpen }) => (
- <Center gap={8}>
- {t('appLoading.failed')}
- <div>
- <Button onClick={() => setOpen(true)} type={'primary'}>
- {t('appLoading.showDetail')}
- </Button>
- </div>
- </Center>
- )}
- </ErrorResult>
- );
-};
-
-export default InitError;
diff --git a/src/app/[variants]/loading/Client/Redirect.tsx b/src/app/[variants]/loading/Client/Redirect.tsx
deleted file mode 100644
index 69fcf09e9cc..00000000000
--- a/src/app/[variants]/loading/Client/Redirect.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-'use client';
-
-import { useRouter } from 'next/navigation';
-import { memo, useEffect } from 'react';
-
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useUserStore } from '@/store/user';
-
-import { AppLoadingStage } from '../stage';
-
-interface RedirectProps {
- setActiveStage: (value: AppLoadingStage) => void;
-}
-
-const Redirect = memo<RedirectProps>(({ setActiveStage }) => {
- const router = useRouter();
- const isUserStateInit = useUserStore((s) => s.isUserStateInit);
-
- const isPgliteNotEnabled = useGlobalStore(systemStatusSelectors.isPgliteNotEnabled);
-
- const navToChat = () => {
- setActiveStage(AppLoadingStage.GoToChat);
- router.replace('/chat');
- };
-
- useEffect(() => {
- // if pglite is not enabled, redirect to chat
- if (isPgliteNotEnabled) {
- navToChat();
- return;
- }
-
- // if user state not init, wait for loading
- if (!isUserStateInit) {
- setActiveStage(AppLoadingStage.InitUser);
- return;
- }
-
- // finally check the conversation status
- navToChat();
- }, [isUserStateInit, isPgliteNotEnabled]);
-
- return null;
-});
-
-export default Redirect;
diff --git a/src/app/[variants]/loading/Client/index.tsx b/src/app/[variants]/loading/Client/index.tsx
deleted file mode 100644
index 544ac88bae9..00000000000
--- a/src/app/[variants]/loading/Client/index.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-'use client';
-
-import { useState } from 'react';
-
-import { AppLoadingStage } from '../stage';
-import Content from './Content';
-import Redirect from './Redirect';
-
-const ClientMode = () => {
- const [activeStage, setActiveStage] = useState<string>(AppLoadingStage.Initializing);
-
- return (
- <>
- <Content loadingStage={activeStage} setActiveStage={setActiveStage} />
- <Redirect setActiveStage={setActiveStage} />
- </>
- );
-};
-
-ClientMode.displayName = 'ClientMode';
-
-export default ClientMode;
diff --git a/src/app/[variants]/loading/index.tsx b/src/app/[variants]/loading/index.tsx
index d66fd36b791..da5bd6f4728 100644
--- a/src/app/[variants]/loading/index.tsx
+++ b/src/app/[variants]/loading/index.tsx
@@ -1,10 +1 @@
-import { isServerMode } from '@/const/version';
-
-import Client from './Client';
-import Server from './Server';
-
-const ScreenLoading = () => (isServerMode ? <Server /> : <Client />);
-
-ScreenLoading.displayName = 'ScreenLoading';
-
-export default ScreenLoading;
+export { default } from './Server';
diff --git a/src/database/_deprecated/core/__tests__/db-upgrade.test.ts b/src/database/_deprecated/core/__tests__/db-upgrade.test.ts
deleted file mode 100644
index 5bd67efc510..00000000000
--- a/src/database/_deprecated/core/__tests__/db-upgrade.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import Dexie from 'dexie';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { BrowserDB } from '../db';
-import { dbSchemaV3 } from '../schemas';
-import { LOBE_CHAT_LOCAL_DB_NAME } from '../types/db';
-
-beforeEach(async () => {
- // 确保在测试开始前删除数据库
- await Dexie.delete(LOBE_CHAT_LOCAL_DB_NAME);
-});
-
-afterEach(async () => {
- // 确保在测试结束后删除数据库
- await Dexie.delete(LOBE_CHAT_LOCAL_DB_NAME);
-});
-
-describe('LocalDB migration', () => {
- it('should upgrade from version 3 to version 4 correctly', async () => {
- // 使用版本3的schema创建数据库实例并填充测试数据
- const dbV3 = new Dexie(LOBE_CHAT_LOCAL_DB_NAME);
- dbV3.version(3).stores(dbSchemaV3);
- await dbV3.open();
- await dbV3.table('sessions').bulkAdd([
- { id: 's1', group: 'pinned' },
- { id: 's2', group: 'default' },
- ]);
- dbV3.close();
-
- // 创建新的数据库实例,包含版本4的迁移逻辑
- const dbV4 = new BrowserDB();
- await dbV4.open();
-
- // 验证迁移后的数据
- const updatedSession1 = await dbV4.sessions.get('s1');
- const updatedSession2 = await dbV4.sessions.get('s2');
- expect(updatedSession1).toEqual({ id: 's1', pinned: 1, group: 'default' });
- expect(updatedSession2).toEqual({ id: 's2', pinned: 0, group: 'default' });
-
- dbV4.close();
- });
-});
diff --git a/src/database/_deprecated/core/__tests__/db.test.ts b/src/database/_deprecated/core/__tests__/db.test.ts
deleted file mode 100644
index fee6490631e..00000000000
--- a/src/database/_deprecated/core/__tests__/db.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { DB_File } from '../../schemas/files';
-import { BrowserDB } from '../db';
-import { DBModel } from '../types/db';
-
-describe('LocalDB', () => {
- let db: BrowserDB;
-
- beforeEach(() => {
- db = new BrowserDB();
- });
-
- afterEach(async () => {
- await db.delete();
- db.close();
- });
-
- it('should be instantiated with the correct schema', () => {
- const filesTable = db.files;
-
- expect(filesTable).toBeDefined();
- });
-
- it('should allow adding a file', async () => {
- const file: DBModel<DB_File> = {
- id: 'file1',
- name: 'testfile.txt',
- data: new ArrayBuffer(3),
- saveMode: 'local',
- fileType: 'plain/text',
- size: 3,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- };
-
- await db.files.add(file);
-
- expect(await db.files.get(file.id)).toEqual(file);
- });
-
- it('should allow updating a file', async () => {
- const file: DBModel<DB_File> = {
- id: 'file1',
- name: 'testfile.txt',
- data: new ArrayBuffer(3),
- saveMode: 'local',
- fileType: 'plain/text',
- size: 3,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- };
- await db.files.add(file);
-
- // Act
- await db.files.update(file.id, { name: 'update.txt' });
-
- // Assert
- expect(await db.files.get(file.id)).toHaveProperty('name', 'update.txt');
- });
-
- it('should allow deleting a file', async () => {
- const file: DBModel<DB_File> = {
- id: 'file1',
- name: 'testfile.txt',
- data: new ArrayBuffer(3),
- saveMode: 'local',
- fileType: 'plain/text',
- size: 3,
- updatedAt: Date.now(),
- createdAt: Date.now(),
- };
- await db.files.add(file);
-
- await db.files.delete(file.id);
-
- expect(await db.files.get(file.id)).toBeUndefined();
- });
-});
diff --git a/src/database/_deprecated/core/__tests__/model.test.ts b/src/database/_deprecated/core/__tests__/model.test.ts
deleted file mode 100644
index 75be5d261da..00000000000
--- a/src/database/_deprecated/core/__tests__/model.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { z } from 'zod';
-
-import { BaseModel } from '../model';
-
-// Define a mock schema for testing
-const mockSchema = z.object({
- name: z.string(),
- content: z.string(),
-});
-
-// Define a mock table name
-const mockTableName = 'files';
-
-describe('BaseModel', () => {
- let baseModel: BaseModel<typeof mockTableName>;
-
- beforeEach(() => {
- baseModel = new BaseModel(mockTableName, mockSchema);
- // Mock the console.error to test error logging
- vi.spyOn(console, 'error').mockImplementation(() => {});
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- // console.error = originalConsoleError;
- });
-
- it('should have a table property', () => {
- expect(baseModel.table).toBeDefined();
- });
-
- describe('add method', () => {
- it('should add a valid record to the database', async () => {
- const validData = {
- name: 'testfile.txt',
- content: 'Hello, World!',
- };
-
- const result = await baseModel['_addWithSync'](validData);
-
- expect(result).toHaveProperty('id');
- expect(console.error).not.toHaveBeenCalled();
- });
-
- it('should throw an error and log to console when adding an invalid record', async () => {
- const invalidData = {
- name: 123, // Invalid type, should be a string
- content: 'Hello, World!',
- };
-
- await expect(baseModel['_addWithSync'](invalidData)).rejects.toThrow(TypeError);
- });
- });
-});
diff --git a/src/database/_deprecated/core/db.ts b/src/database/_deprecated/core/db.ts
deleted file mode 100644
index bc40e10c5e1..00000000000
--- a/src/database/_deprecated/core/db.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import Dexie, { Transaction } from 'dexie';
-
-import { MigrationLLMSettings } from '@/migrations/FromV3ToV4';
-import { MigrationAgentChatConfig } from '@/migrations/FromV5ToV6';
-import { MigrationKeyValueSettings } from '@/migrations/FromV6ToV7';
-import { uuid } from '@/utils/uuid';
-
-import { DB_File } from '../schemas/files';
-import { DB_Message } from '../schemas/message';
-import { DB_Plugin } from '../schemas/plugin';
-import { DB_Session } from '../schemas/session';
-import { DB_SessionGroup } from '../schemas/sessionGroup';
-import { DB_Topic } from '../schemas/topic';
-import { DB_User } from '../schemas/user';
-import { migrateSettingsToUser } from './migrations/migrateSettingsToUser';
-import {
- dbSchemaV1,
- dbSchemaV2,
- dbSchemaV3,
- dbSchemaV4,
- dbSchemaV5,
- dbSchemaV6,
- dbSchemaV7,
- dbSchemaV9,
-} from './schemas';
-import { DBModel, LOBE_CHAT_LOCAL_DB_NAME } from './types/db';
-
-export interface LobeDBSchemaMap {
- files: DB_File;
- messages: DB_Message;
- plugins: DB_Plugin;
- sessionGroups: DB_SessionGroup;
- sessions: DB_Session;
- topics: DB_Topic;
- users: DB_User;
-}
-
-// Define a local DB
-export class BrowserDB extends Dexie {
- public files: BrowserDBTable<'files'>;
- public sessions: BrowserDBTable<'sessions'>;
- public messages: BrowserDBTable<'messages'>;
- public topics: BrowserDBTable<'topics'>;
- public plugins: BrowserDBTable<'plugins'>;
- public sessionGroups: BrowserDBTable<'sessionGroups'>;
- public users: BrowserDBTable<'users'>;
-
- constructor() {
- super(LOBE_CHAT_LOCAL_DB_NAME);
- this.version(1).stores(dbSchemaV1);
- this.version(2).stores(dbSchemaV2);
- this.version(3).stores(dbSchemaV3);
- this.version(4)
- .stores(dbSchemaV4)
- .upgrade((trans) => this.upgradeToV4(trans));
-
- this.version(5)
- .stores(dbSchemaV5)
- .upgrade((trans) => this.upgradeToV5(trans));
-
- this.version(6)
- .stores(dbSchemaV6)
- .upgrade((trans) => this.upgradeToV6(trans));
-
- this.version(7)
- .stores(dbSchemaV7)
- .upgrade((trans) => this.upgradeToV7(trans));
-
- this.version(8)
- .stores(dbSchemaV7)
- .upgrade((trans) => this.upgradeToV8(trans));
-
- this.version(9)
- .stores(dbSchemaV9)
- .upgrade((trans) => this.upgradeToV9(trans));
-
- this.version(10)
- .stores(dbSchemaV9)
- .upgrade((trans) => this.upgradeToV10(trans));
-
- this.version(11)
- .stores(dbSchemaV9)
- .upgrade((trans) => this.upgradeToV11(trans));
-
- this.files = this.table('files');
- this.sessions = this.table('sessions');
- this.messages = this.table('messages');
- this.topics = this.table('topics');
- this.plugins = this.table('plugins');
- this.sessionGroups = this.table('sessionGroups');
- this.users = this.table('users');
- }
-
- /**
- * 2024.01.22
- *
- * DB V3 to V4
- * from `group = pinned` to `pinned:true`
- */
- upgradeToV4 = async (trans: Transaction) => {
- const sessions = trans.table('sessions');
- await sessions.toCollection().modify((session) => {
- // translate boolean to number
- session.pinned = session.group === 'pinned' ? 1 : 0;
- session.group = 'default';
- });
- };
-
- /**
- * 2024.01.29
- * settings from localStorage to indexedDB
- */
- upgradeToV5 = async (trans: Transaction) => {
- const users = trans.table('users');
-
- // if no user, create one
- if ((await users.count()) === 0) {
- const data = localStorage.getItem('LOBE_SETTINGS');
-
- if (data) {
- let json;
-
- try {
- json = JSON.parse(data);
- } catch {
- /* empty */
- }
-
- if (!json?.state?.settings) return;
-
- const settings = json.state.settings;
-
- const user = migrateSettingsToUser(settings);
- await users.add(user);
- }
- }
- };
-
- /**
- * 2024.02.27
- * add uuid to user
- */
- upgradeToV6 = async (trans: Transaction) => {
- const users = trans.table('users');
-
- await users.toCollection().modify((user: DB_User) => {
- if (!user.uuid) user.uuid = uuid();
- });
- };
-
- /**
- * 2024.03.14
- * add `id` in plugins
- */
- upgradeToV7 = async (trans: Transaction) => {
- const plugins = trans.table('plugins');
-
- await plugins.toCollection().modify((plugin: DB_Plugin) => {
- plugin.id = plugin.identifier;
- });
- };
-
- upgradeToV8 = async (trans: Transaction) => {
- const users = trans.table('users');
- await users.toCollection().modify((user: DB_User) => {
- if (user.settings) {
- user.settings = MigrationLLMSettings.migrateSettings(user.settings as any);
- }
- });
- };
-
- /**
- * 2024.05.11
- *
- * message role=function to role=tool
- */
- upgradeToV9 = async (trans: Transaction) => {
- const messages = trans.table('messages');
- await messages.toCollection().modify(async (message: DBModel<DB_Message>) => {
- if ((message.role as string) === 'function') {
- const origin = Object.assign({}, message);
-
- const toolCallId = `tool_call_${message.id}`;
- const assistantMessageId = `tool_calls_${message.id}`;
-
- message.role = 'tool';
- message.tool_call_id = toolCallId;
- message.parentId = assistantMessageId;
-
- await messages.add({
- ...origin,
- content: '',
- createdAt: message.createdAt - 10,
- error: undefined,
- id: assistantMessageId,
- role: 'assistant',
- tools: [{ ...message.plugin!, id: toolCallId }],
- updatedAt: message.updatedAt - 10,
- } as DBModel<DB_Message>);
- }
- });
- };
-
- /**
- * 2024.05.25
- * migrate some agent config to chatConfig
- */
- upgradeToV10 = async (trans: Transaction) => {
- const sessions = trans.table('sessions');
- await sessions.toCollection().modify(async (session: DBModel<DB_Session>) => {
- if (session.config)
- session.config = MigrationAgentChatConfig.migrateChatConfig(session.config as any);
- });
- };
-
- /**
- * 2024.05.27
- * migrate apiKey in languageModel to keyVaults
- */
- upgradeToV11 = async (trans: Transaction) => {
- const users = trans.table('users');
-
- await users.toCollection().modify((user: DB_User) => {
- if (user.settings) {
- user.settings = MigrationKeyValueSettings.migrateSettings(user.settings as any);
- }
- });
- };
-}
-
-export const browserDB = new BrowserDB();
-
-// ================================================ //
-// ================================================ //
-// ================================================ //
-// ================================================ //
-// ================================================ //
-
-// types helper
-export type BrowserDBSchema = {
- [t in keyof LobeDBSchemaMap]: {
- model: LobeDBSchemaMap[t];
- table: Dexie.Table<DBModel<LobeDBSchemaMap[t]>, string>;
- };
-};
-type BrowserDBTable<T extends keyof LobeDBSchemaMap> = BrowserDBSchema[T]['table'];
diff --git a/src/database/_deprecated/core/index.ts b/src/database/_deprecated/core/index.ts
deleted file mode 100644
index 144f37ce02c..00000000000
--- a/src/database/_deprecated/core/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { browserDB } from './db';
-export * from './model';
diff --git a/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/input.json b/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/input.json
deleted file mode 100644
index 14087f9f573..00000000000
--- a/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/input.json
+++ /dev/null
@@ -1,55 +0,0 @@
-{
- "avatar": "",
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-3.5-turbo-1106",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.7,
- "top_p": 0.7
- },
- "plugins": ["website-crawler"],
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- },
- "enableHistoryCount": true
- },
- "meta": {}
- },
- "fontSize": 14,
- "language": "auto",
- "languageModel": {
- "openAI": {
- "OPENAI_API_KEY": "dfdf",
- "models": [
- "gpt-3.5-turbo",
- "gpt-3.5-turbo-1106",
- "gpt-3.5-turbo-16k",
- "gpt-4",
- "gpt-4-32k",
- "gpt-4-0125-preview",
- "gpt-4-vision-preview"
- ],
- "customModelName": "+glm-4,+glm-4v",
- "endpoint": "sdaddsd"
- },
- "zhipu": { "ZHIPU_API_KEY": "", "enabled": false }
- },
- "password": "",
- "themeMode": "auto",
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- }
-}
diff --git a/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/output.json b/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/output.json
deleted file mode 100644
index 518c15c0468..00000000000
--- a/src/database/_deprecated/core/migrations/migrateSettingsToUser/fixtures/output.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "avatar": "",
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-3.5-turbo-1106",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.7,
- "top_p": 0.7
- },
- "plugins": ["website-crawler"],
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": {
- "openai": "alloy"
- }
- },
- "enableHistoryCount": true
- },
- "meta": {}
- },
- "fontSize": 14,
- "language": "auto",
- "languageModel": {
- "openai": {
- "OPENAI_API_KEY": "dfdf",
- "models": [
- "gpt-3.5-turbo",
- "gpt-3.5-turbo-1106",
- "gpt-3.5-turbo-16k",
- "gpt-4",
- "gpt-4-32k",
- "gpt-4-0125-preview",
- "gpt-4-vision-preview"
- ],
- "customModelName": "+glm-4,+glm-4v",
- "endpoint": "sdaddsd"
- }
- },
- "password": "",
- "themeMode": "auto",
- "tts": {
- "openAI": {
- "sttModel": "whisper-1",
- "ttsModel": "tts-1"
- },
- "sttAutoStop": true,
- "sttServer": "openai"
- }
- }
-}
diff --git a/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.test.ts b/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.test.ts
deleted file mode 100644
index b6969c4abfc..00000000000
--- a/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.test.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { describe, expect } from 'vitest';
-
-import input from './fixtures/input.json';
-import outputData from './fixtures/output.json';
-import { migrateSettingsToUser } from './index';
-import { V4Settings } from './type';
-
-describe('migrateSettingsFromLocalStorage', () => {
- it('from localStorage to indexedDB', () => {
- const output = migrateSettingsToUser(input as V4Settings);
-
- expect(output).toEqual(outputData);
- });
-});
diff --git a/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.ts b/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.ts
deleted file mode 100644
index 747e4e50cd3..00000000000
--- a/src/database/_deprecated/core/migrations/migrateSettingsToUser/index.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { V4Settings, V5Settings } from './type';
-
-export const migrateSettingsToUser = (
- settings: V4Settings,
-): { avatar: string; settings: V5Settings } => {
- const dbSettings: V5Settings = {
- defaultAgent: settings.defaultAgent,
- fontSize: settings.fontSize,
- language: settings.language,
- languageModel: {
- openai: settings.languageModel.openAI,
- },
- password: settings.password,
- themeMode: settings.themeMode,
- tts: settings.tts,
- };
-
- return {
- avatar: settings.avatar,
- settings: dbSettings,
- };
-};
diff --git a/src/database/_deprecated/core/migrations/migrateSettingsToUser/type.ts b/src/database/_deprecated/core/migrations/migrateSettingsToUser/type.ts
deleted file mode 100644
index 93d2285be96..00000000000
--- a/src/database/_deprecated/core/migrations/migrateSettingsToUser/type.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { FewShots, LobeAgentTTSConfig, MetaData, STTServer } from '@lobechat/types';
-import type { ThemeMode } from 'antd-style';
-import { LLMParams } from 'model-bank';
-
-interface V4LobeAgentConfig {
- autoCreateTopicThreshold: number;
- compressThreshold?: number;
- displayMode?: 'chat' | 'docs';
- enableAutoCreateTopic: boolean;
- /**
- * 历史消息长度压缩阈值
- */
- enableCompressThreshold?: boolean;
- /**
- * 开启历史记录条数
- */
- enableHistoryCount?: boolean;
- enableMaxTokens?: boolean;
-
- fewShots?: FewShots;
- /**
- * 历史消息条数
- */
- historyCount?: number;
- inputTemplate?: string;
- /**
- * 角色所使用的语言模型
- * @default gpt-3.5-turbo
- */
- model: string;
- /**
- * 语言模型参数
- */
- params: LLMParams;
- /**
- * 启用的插件
- */
- plugins?: string[];
- /**
- * 模型供应商
- */
- provider?: string;
- /**
- * 系统角色
- */
- systemRole: string;
- /**
- * 语音服务
- */
- tts: LobeAgentTTSConfig;
-}
-
-interface V4DefaultAgent {
- config: V4LobeAgentConfig;
- meta: MetaData;
-}
-
-interface OpenAIConfig {
- OPENAI_API_KEY: string;
- azureApiVersion?: string;
- customModelName?: string;
- endpoint?: string;
- models?: string[];
- useAzure?: boolean;
-}
-
-interface V4LLMConfig {
- openAI: OpenAIConfig;
-}
-
-interface TTSConfig {
- openAI: {
- sttModel: 'whisper-1';
- ttsModel: 'tts-1' | 'tts-1-hd';
- };
- sttAutoStop: boolean;
- sttServer: STTServer;
-}
-
-export interface V4Settings {
- avatar: string;
- defaultAgent: V4DefaultAgent;
- fontSize: number;
- language: string;
- languageModel: V4LLMConfig;
- neutralColor?: string;
- password: string;
- primaryColor?: string;
- themeMode: ThemeMode;
- tts: TTSConfig;
-}
-
-export interface V5Settings {
- defaultAgent: V4DefaultAgent;
- fontSize: number;
- language: string;
- languageModel: {
- openai: OpenAIConfig;
- };
- neutralColor?: string;
- password: string;
- primaryColor?: string;
- themeMode: ThemeMode;
- tts: TTSConfig;
-}
diff --git a/src/database/_deprecated/core/model.ts b/src/database/_deprecated/core/model.ts
deleted file mode 100644
index 5ec6c55ae65..00000000000
--- a/src/database/_deprecated/core/model.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import Dexie, { BulkError } from 'dexie';
-import { ZodObject } from 'zod';
-
-import { nanoid } from '@/utils/uuid';
-
-import { BrowserDB, BrowserDBSchema, browserDB } from './db';
-import { DBBaseFieldsSchema } from './types/db';
-
-export class BaseModel<N extends keyof BrowserDBSchema = any, T = BrowserDBSchema[N]['table']> {
- protected readonly db: BrowserDB;
- private readonly schema: ZodObject<any>;
- private readonly _tableName: keyof BrowserDBSchema;
-
- constructor(table: N, schema: ZodObject<any>, db = browserDB) {
- this.db = db;
- this.schema = schema;
- this._tableName = table;
- }
-
- get table() {
- return this.db[this._tableName] as Dexie.Table;
- }
-
- // **************** Create *************** //
-
- /**
- * create a new record
- */
- protected async _addWithSync<T = BrowserDBSchema[N]['model']>(
- data: T,
- id: string | number = nanoid(),
- primaryKey: string = 'id',
- ) {
- const result = this.schema.safeParse(data);
-
- if (!result.success) {
- const errorMsg = `[${this.db.name}][${this._tableName}] Failed to create new record. Error: ${result.error}`;
-
- const newError = new TypeError(errorMsg);
- // make this error show on console to help debug
- console.error(newError);
- throw newError;
- }
-
- const tableName = this._tableName;
-
- const record: any = {
- ...result.data,
- createdAt: Date.now(),
- [primaryKey]: id,
- updatedAt: Date.now(),
- };
-
- const newId = await this.db[tableName].add(record);
-
- // sync data to yjs data map
- this.updateYMapItem(newId);
-
- return { id: newId };
- }
-
- /**
- * Batch create new records
- * @param dataArray An array of data to be added
- * @param options
- * @param options.generateId
- * @param options.createWithNewId
- */
- protected async _batchAdd<T = BrowserDBSchema[N]['model']>(
- dataArray: T[],
- options: {
- /**
- * always create with a new id
- */
- createWithNewId?: boolean;
- idGenerator?: () => string;
- } = {},
- ): Promise<{
- added: number;
- errors?: Error[];
- ids: string[];
- skips: string[];
- success: boolean;
- }> {
- const { idGenerator = nanoid, createWithNewId = false } = options;
- const validatedData: any[] = [];
- const errors = [];
- const skips: string[] = [];
-
- for (const data of dataArray) {
- const schemaWithId = this.schema.merge(DBBaseFieldsSchema.partial());
-
- const result = schemaWithId.safeParse(data);
-
- if (result.success) {
- const item = result.data;
- const autoId = idGenerator();
-
- const id = createWithNewId ? autoId : (item.id ?? autoId);
-
- // skip if the id already exists
- if (await this.table.get(id)) {
- skips.push(id as string);
- continue;
- }
-
- const getTime = (time?: string | number) => {
- if (!time) return Date.now();
- if (typeof time === 'number') return time;
-
- return new Date(time).valueOf();
- };
-
- validatedData.push({
- ...item,
- createdAt: getTime(item.createdAt as string),
- id,
- updatedAt: getTime(item.updatedAt as string),
- });
- } else {
- errors.push(result.error);
-
- const errorMsg = `[${this.db.name}][${
- this._tableName
- }] Failed to create the record. Data: ${JSON.stringify(data)}. Errors: ${result.error}`;
- console.error(new TypeError(errorMsg));
- }
- }
- if (validatedData.length === 0) {
- // No valid data to add
- return { added: 0, errors, ids: [], skips, success: false };
- }
-
- // Using bulkAdd to insert validated data
- try {
- await this.table.bulkAdd(validatedData);
-
- return {
- added: validatedData.length,
- ids: validatedData.map((item) => item.id),
- skips,
- success: true,
- };
- } catch (error) {
- const bulkError = error as BulkError;
- // Handle bulkAdd errors here
- console.error(`[${this.db.name}][${this._tableName}] Bulk add error:`, bulkError);
- // Return the number of successfully added records and errors
- return {
- added: validatedData.length - skips.length - bulkError.failures.length,
- errors: bulkError.failures,
- ids: validatedData.map((item) => item.id),
- skips,
- success: false,
- };
- }
- }
-
- // **************** Delete *************** //
-
- protected async _deleteWithSync(id: string) {
- return await this.table.delete(id);
- }
-
- protected async _bulkDeleteWithSync(keys: string[]) {
- await this.table.bulkDelete(keys);
- // sync delete data to yjs data map
- }
-
- protected async _clearWithSync() {
- return await this.table.clear();
- }
-
- // **************** Update *************** //
-
- protected async _updateWithSync(id: string, data: Partial<T>) {
- // we need to check whether the data is valid
- // pick data related schema from the full schema
- const keys = Object.keys(data);
- const partialSchema = this.schema.pick(Object.fromEntries(keys.map((key) => [key, true])));
-
- const result = partialSchema.safeParse(data);
- if (!result.success) {
- const errorMsg = `[${this.db.name}][${this._tableName}] Failed to update the record:${id}. Error: ${result.error}`;
-
- const newError = new TypeError(errorMsg);
- // make this error show on console to help debug
- console.error(newError);
- throw newError;
- }
-
- const success = await this.table.update(id, { ...data, updatedAt: Date.now() });
-
- // sync data to yjs data map
- this.updateYMapItem(id);
-
- return { success };
- }
-
- protected async _putWithSync(data: any, id: string) {
- const result = await this.table.put(data, id);
-
- // sync data to yjs data map
- this.updateYMapItem(id);
-
- return result;
- }
-
- protected async _bulkPutWithSync(items: T[]) {
- await this.table.bulkPut(items);
- }
-
- // **************** Helper *************** //
-
- private updateYMapItem = async (id: string) => {
- await this.table.get(id);
- };
-}
diff --git a/src/database/_deprecated/core/schemas.ts b/src/database/_deprecated/core/schemas.ts
deleted file mode 100644
index 650a207c223..00000000000
--- a/src/database/_deprecated/core/schemas.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// ************************************** //
-// ******* Version 1 - 2023-11-14 ******* //
-// ************************************** //
-// - Initial database schema with `files` table
-
-export const dbSchemaV1 = {
- files: '&id, name, fileType, saveMode',
-};
-
-// ************************************** //
-// ******* Version 2 - 2023-11-27 ******* //
-// ************************************** //
-// - Added `sessions` 、`messages` 、`topics` tables
-// - Added `createdAt` and `updatedAt` fields to all
-export const dbSchemaV2 = {
- files: '&id, name, fileType, saveMode, createdAt, updatedAt, messageId, sessionId',
-
- messages:
- '&id, role, content, fromModel, favorite, plugin.identifier, plugin.apiName, translate.content, createdAt, updatedAt, sessionId, topicId, quotaId, parentId, [sessionId+topicId]',
- sessions: '&id, type, group, meta.title, meta.description, meta.tags, createdAt, updatedAt',
- topics: '&id, title, favorite, createdAt, updatedAt, sessionId',
-};
-
-// ************************************** //
-// ******* Version 3 - 2023-12-06 ******* //
-// ************************************** //
-// - Added `plugins` table
-
-export const dbSchemaV3 = {
- ...dbSchemaV2,
- plugins:
- '&identifier, type, manifest.type, manifest.meta.title, manifest.meta.description, manifest.meta.author, createdAt, updatedAt',
-};
-
-// ************************************** //
-// ******* Version 4 - 2024-01-21 ******* //
-// ************************************** //
-// - Added `sessionGroups` table
-// - Add `pinned` to sessions table
-
-export const dbSchemaV4 = {
- ...dbSchemaV3,
- sessionGroups: '&id, name, sort, createdAt, updatedAt',
- sessions:
- '&id, type, group, pinned, meta.title, meta.description, meta.tags, createdAt, updatedAt',
-};
-
-// ************************************** //
-// ******* Version 5 - 2024-01-29 ******* //
-// ************************************** //
-// - Added `users` table
-
-export const dbSchemaV5 = {
- ...dbSchemaV4,
- users: '++id',
-};
-
-// ************************************** //
-// ******* Version 6 - 2024-02-27 ******* //
-// ************************************** //
-// - Added uuid to `users` table
-// - Added traceId to `messages` table
-export const dbSchemaV6 = {
- ...dbSchemaV5,
- messages:
- '&id, role, content, fromModel, favorite, plugin.identifier, plugin.apiName, translate.content, createdAt, updatedAt, sessionId, topicId, quotaId, parentId, [sessionId+topicId], traceId',
- users: '++id, uuid',
-};
-
-// ************************************** //
-// ******* Version 7 - 2024-03-14 ******* //
-// ************************************** //
-// - Added id to `plugins` table
-export const dbSchemaV7 = {
- ...dbSchemaV6,
- plugins:
- '&identifier, id, type, manifest.type, manifest.meta.title, manifest.meta.description, manifest.meta.author, createdAt, updatedAt',
-};
-
-// ************************************** //
-// ******* Version 9 - 2024-05-11 ******* //
-// ************************************** //
-// - Added tool_call_id to `messages` table
-export const dbSchemaV9 = {
- ...dbSchemaV7,
- messages:
- '&id, role, content, fromModel, favorite, tool_call_id, plugin.identifier, plugin.apiName, translate.content, createdAt, updatedAt, sessionId, topicId, quotaId, parentId, [sessionId+topicId], traceId',
-};
diff --git a/src/database/_deprecated/core/types/db.ts b/src/database/_deprecated/core/types/db.ts
deleted file mode 100644
index 8f4d31d8cfc..00000000000
--- a/src/database/_deprecated/core/types/db.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { z } from 'zod';
-
-export type DBModel<T> = T & {
- createdAt: number;
- id: string;
- updatedAt: number;
-};
-
-export const DBBaseFieldsSchema = z.object({
- createdAt: z.number().or(z.string()),
- id: z.string(),
- updatedAt: z.number().or(z.string()),
-});
-
-export const LOBE_CHAT_LOCAL_DB_NAME = 'LOBE_CHAT_DB';
diff --git a/src/database/_deprecated/models/__DEBUG.ts b/src/database/_deprecated/models/__DEBUG.ts
deleted file mode 100644
index 19951870dfa..00000000000
--- a/src/database/_deprecated/models/__DEBUG.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-// This file is for debugging purposes only.
-// DON'T USE IT IN PRODUCTION.
-import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { DB_Message } from '@/database/_deprecated/schemas/message';
-import { DB_Topic } from '@/database/_deprecated/schemas/topic';
-
-import { BaseModel } from '../core';
-import { DB_Session, DB_SessionSchema } from '../schemas/session';
-
-class _DEBUG_MODEL extends BaseModel<'sessions'> {
- constructor() {
- super('sessions', DB_SessionSchema);
- }
- private getRandomInt(min: number, max: number) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
-
- private randomString(length: number) {
- const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
- let result = '';
- for (let i = 0; i < length; i++) {
- result += characters.charAt(Math.floor(Math.random() * characters.length));
- }
- return result;
- }
-
- private randomDate(start: Date, end: Date) {
- return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).getTime();
- }
-
- private randomPick<T>(array: T[]): T {
- const randomIndex = this.getRandomInt(0, array.length - 1);
- return array[randomIndex];
- }
-
- createRandomData = async ({
- sessionCount = 10,
- topicCount = 2000,
- messageCount = 10_000,
- startIndex = 1,
- }) => {
- const numberOfSessions = sessionCount;
- const numberOfTopics = topicCount;
- const numberOfMessages = messageCount;
-
- // Prepare data for batch inserts
- const sessionsData: DBModel<DB_Session>[] = [];
- const topicsData: DBModel<DB_Topic>[] = [];
- const messagesData: DBModel<DB_Message>[] = [];
-
- // Prepare sessions
- for (let i = startIndex; i < numberOfSessions + startIndex; i++) {
- sessionsData.push({
- config: DEFAULT_AGENT_CONFIG,
- createdAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- group: 'default',
- id: `sess_${i}`,
- meta: {
- description: `Session Description ${i}`,
- title: `Session Title ${i}`,
- },
- type: 'agent',
- updatedAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- });
- }
-
- // Prepare topics
- for (let i = startIndex; i < numberOfTopics + startIndex; i++) {
- topicsData.push({
- createdAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- favorite: this.getRandomInt(0, 1),
- id: `topic_${i}`,
- sessionId: `sess_${this.getRandomInt(startIndex, numberOfSessions)}`,
- title: `Topic Title ${i}`,
- updatedAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- });
- }
-
- // Prepare messages
- for (let i = startIndex; i < numberOfMessages + startIndex; i++) {
- messagesData.push({
- content: this.randomString(300),
- createdAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- favorite: this.getRandomInt(0, 1),
- fromModel: 'model',
- id: `msg_${i}`,
- parentId: `msg_${this.getRandomInt(startIndex, numberOfMessages)}`,
- quotaId: `msg_${this.getRandomInt(startIndex, numberOfMessages)}`,
- role: this.randomPick(['user', 'assistant']),
- sessionId: `sess_${this.getRandomInt(startIndex, numberOfSessions)}`,
- topicId: `topic_${this.getRandomInt(startIndex, numberOfTopics)}`,
- updatedAt: this.randomDate(new Date(2020, 0, 1), new Date()),
- });
- }
-
- // Start a transaction for batch inserts
- await this.db.transaction(
- 'rw',
- this.db.sessions,
- this.db.topics,
- this.db.messages,
- async () => {
- // Batch insert sessions, topics, and messages
- console.log('开始插入 sessions');
- console.time('插入sessions');
- await this.db.sessions.bulkAdd(sessionsData);
- console.timeEnd('插入sessions');
-
- console.log('开始插入 topics');
- console.time('插入topics');
- await this.db.topics.bulkAdd(topicsData);
- console.timeEnd('插入topics');
-
- console.log('开始插入 messages');
- console.time('插入messages');
- await this.db.messages.bulkAdd(messagesData);
- console.timeEnd('插入messages');
- },
- );
- };
-}
-
-export const DEBUG_MODEL = new _DEBUG_MODEL();
diff --git a/src/database/_deprecated/models/__tests__/file.test.ts b/src/database/_deprecated/models/__tests__/file.test.ts
deleted file mode 100644
index c433ff44ac2..00000000000
--- a/src/database/_deprecated/models/__tests__/file.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { BrowserDB } from '../../core/db';
-import { DB_File } from '../../schemas/files';
-import { FileModel } from '../file';
-
-// Assuming LocalDB is already mocked or using an in-memory database
-// and LocalFileSchema has been imported correctly.
-
-describe('_FileModel', () => {
- let fileData: DB_File;
-
- beforeEach(() => {
- // Set up file data with the correct structure according to LocalFileSchema
- fileData = {
- data: new ArrayBuffer(10),
- fileType: 'image/png',
- name: 'test.png',
- saveMode: 'local',
- size: 10,
- // url is optional, only needed if saveMode is 'url'
- };
- });
-
- afterEach(async () => {
- // Clean up the database after each test
- const db = new BrowserDB();
- await db.files.clear();
- db.close();
- });
-
- it('should create a file record', async () => {
- // First, create a file to test the create method
- const fileData: DB_File = {
- data: new ArrayBuffer(10),
- fileType: 'image/png',
- name: 'test.png',
- saveMode: 'local',
- size: 10,
- };
-
- const result = await FileModel.create(fileData);
-
- expect(result).toHaveProperty('id');
- expect(result.id).toMatch(/^file-/);
-
- // Verify that the file has been added to the database
- const fileInDb = await FileModel.findById(result.id);
-
- expect(fileInDb).toEqual(expect.objectContaining(fileData));
- });
-
- it('should find a file by id', async () => {
- // First, create a file to test the findById method
- const createdFile = await FileModel.create(fileData);
- const foundFile = await FileModel.findById(createdFile.id);
-
- expect(foundFile).toEqual(expect.objectContaining(fileData));
- });
-
- it('should delete a file by id', async () => {
- // First, create a file to test the delete method
- const createdFile = await FileModel.create(fileData);
- await FileModel.delete(createdFile.id);
-
- // Verify that the file has been removed from the database
- const fileInDb = await FileModel.findById(createdFile.id);
- expect(fileInDb).toBeUndefined();
- });
-
- it('should clear all files', async () => {
- // First, create a file to test the delete method
- const createdFile = await FileModel.create(fileData);
- const createdFile2 = await FileModel.create(fileData);
- await FileModel.clear();
-
- // Verify that the file has been removed from the database
- const fileInDb = await FileModel.findById(createdFile.id);
- expect(fileInDb).toBeUndefined();
- const fileInDb2 = await FileModel.findById(createdFile2.id);
- expect(fileInDb2).toBeUndefined();
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/message.test.ts b/src/database/_deprecated/models/__tests__/message.test.ts
deleted file mode 100644
index 60c232de29e..00000000000
--- a/src/database/_deprecated/models/__tests__/message.test.ts
+++ /dev/null
@@ -1,426 +0,0 @@
-import { UIChatMessage } from '@lobechat/types';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { CreateMessageParams, MessageModel } from '../message';
-
-describe('MessageModel', () => {
- let messageData: CreateMessageParams;
-
- beforeEach(() => {
- // 设置正确结构的消息数据
- messageData = {
- content: 'Test message content',
- role: 'user',
- sessionId: 'session1',
- topicId: 'topic1',
- };
- });
-
- afterEach(async () => {
- // 每次测试后清理数据库
- await MessageModel.clearTable();
- });
-
- describe('create', () => {
- it('should create a message record', async () => {
- const result = await MessageModel.create(messageData);
-
- expect(result).toHaveProperty('id');
- // 验证消息是否已添加到数据库
- const messageInDb = await MessageModel.findById(result.id);
-
- expect(messageInDb).toEqual(
- expect.objectContaining({
- content: messageData.content,
- role: messageData.role,
- sessionId: messageData.sessionId,
- topicId: messageData.topicId,
- }),
- );
- });
-
- it('should create with tts', async () => {
- const result = await MessageModel.create({
- content: 'abc',
- role: 'assistant',
- extra: { translate: { content: 'avc', from: 'a', to: 'f' } },
- sessionId: 'a',
- });
-
- // 验证消息是否已添加到数据库
- const messageInDb = await MessageModel.findById(result.id);
-
- expect(messageInDb).toEqual(
- expect.objectContaining({
- content: 'abc',
- role: 'assistant',
- translate: { content: 'avc', from: 'a', to: 'f' },
- sessionId: 'a',
- }),
- );
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create message records', async () => {
- const messagesToCreate = [messageData, messageData] as UIChatMessage[];
- const results = await MessageModel.batchCreate(messagesToCreate);
-
- expect(results.success).toBeTruthy();
- expect(results.errors).toBeUndefined();
-
- // 验证消息是否已添加到数据库
- for (const message of results.ids!) {
- const messageInDb = await MessageModel.findById(message);
- expect(messageInDb).toEqual(
- expect.objectContaining({
- content: messageData.content,
- role: messageData.role,
- sessionId: messageData.sessionId,
- topicId: messageData.topicId,
- }),
- );
- }
- });
- });
-
- describe('query', () => {
- it('should query messages with pagination', async () => {
- // 创建多条消息以测试查询方法
- await MessageModel.batchCreate([messageData, messageData] as UIChatMessage[]);
-
- const queriedMessages = await MessageModel.query({
- pageSize: 1,
- current: 0,
- sessionId: messageData.sessionId,
- topicId: messageData.topicId,
- });
-
- expect(queriedMessages).toHaveLength(1);
- });
-
- it('should query correctly without topic id', async () => {
- // 创建多条消息以测试查询方法
- await MessageModel.batchCreate([messageData, messageData] as UIChatMessage[]);
-
- const queriedMessages = await MessageModel.query({ sessionId: messageData.sessionId });
-
- expect(queriedMessages).toHaveLength(0);
- });
-
- it('should query correctly with exactly topic id', async () => {
- // 创建多条消息以测试查询方法
- await MessageModel.batchCreate([
- messageData,
- { ...messageData, topicId: undefined },
- ] as UIChatMessage[]);
-
- const queriedMessages = await MessageModel.query({ sessionId: messageData.sessionId });
-
- expect(queriedMessages).toHaveLength(1);
- });
-
- it('should should have correct order', async () => {
- const data: UIChatMessage[] = [
- {
- role: 'user',
- content: '1',
- createdAt: 1697120044345,
- id: 'NQ7RscYx',
- updatedAt: 1697120181827,
- extra: {},
- meta: {},
- sessionId: '1',
- },
- {
- role: 'assistant',
- content: '2',
- parentId: 'NQ7RscYx',
- createdAt: 1697120130973,
- id: '9tDAumEx',
- updatedAt: 1697120181827,
- meta: {},
- extra: {
- fromModel: 'gpt-3.5-turbo-16k',
- },
- sessionId: '1',
- },
- {
- role: 'assistant',
- content: '3',
- parentId: 'tOMH7c5R',
- meta: {},
- createdAt: 1697120163272,
- id: '5Ie5hClg',
- updatedAt: 1697120181827,
- extra: {
- fromModel: 'gpt-3.5-turbo-16k',
- },
- sessionId: '1',
- },
- {
- role: 'user',
- content: '4',
- meta: {},
- createdAt: 1697120163272,
- id: 'tOMH7c5R',
- updatedAt: 1697120181827,
- extra: {},
- sessionId: '1',
- },
- ];
-
- await MessageModel.batchCreate(data);
-
- const queriedMessages = await MessageModel.query({ sessionId: '1' });
-
- expect(queriedMessages).toEqual([
- {
- role: 'user',
- content: '1',
- createdAt: 1697120044345,
- id: 'NQ7RscYx',
- updatedAt: 1697120181827,
- sessionId: '1',
- extra: {},
- meta: {},
- },
- {
- role: 'assistant',
- content: '2',
- parentId: 'NQ7RscYx',
- createdAt: 1697120130973,
- id: '9tDAumEx',
- sessionId: '1',
- updatedAt: 1697120181827,
- meta: {},
- extra: {
- fromModel: 'gpt-3.5-turbo-16k',
- },
- },
- {
- role: 'user',
- content: '4',
- sessionId: '1',
- createdAt: 1697120163272,
- id: 'tOMH7c5R',
- updatedAt: 1697120181827,
- meta: {},
- extra: {},
- },
- {
- role: 'assistant',
- content: '3',
- parentId: 'tOMH7c5R',
- meta: {},
- createdAt: 1697120163272,
- sessionId: '1',
- id: '5Ie5hClg',
- updatedAt: 1697120181827,
- extra: {
- fromModel: 'gpt-3.5-turbo-16k',
- },
- },
- ]);
- });
- });
-
- describe('findById', () => {
- it('should find a message by id', async () => {
- const createdMessage = await MessageModel.create(messageData);
- const messageInDb = await MessageModel.findById(createdMessage.id);
-
- expect(messageInDb).toEqual(
- expect.objectContaining({
- id: createdMessage.id,
- content: messageData.content,
- }),
- );
- });
- });
-
- describe('delete', () => {
- it('should delete a message', async () => {
- const createdMessage = await MessageModel.create(messageData);
- await MessageModel.delete(createdMessage.id);
-
- const messageInDb = await MessageModel.findById(createdMessage.id);
- expect(messageInDb).toBeUndefined();
- });
- });
-
- describe('bulkDelete', () => {
- it('should delete many messages', async () => {
- const createdMessage = await MessageModel.create(messageData);
- const createdMessage2 = await MessageModel.create(messageData);
- await MessageModel.bulkDelete([createdMessage.id, createdMessage2.id]);
-
- const messageInDb1 = await MessageModel.findById(createdMessage.id);
- const messageInDb2 = await MessageModel.findById(createdMessage2.id);
- expect(messageInDb1).toBeUndefined();
- expect(messageInDb2).toBeUndefined();
- });
- });
-
- describe('update', () => {
- it('should update a message', async () => {
- const createdMessage = await MessageModel.create(messageData);
- const updateData = { content: 'Updated content' };
-
- await MessageModel.update(createdMessage.id, updateData);
- const updatedMessage = await MessageModel.findById(createdMessage.id);
-
- expect(updatedMessage).toHaveProperty('content', 'Updated content');
- });
-
- it('should update a role and plugins', async () => {
- const createdMessage = await MessageModel.create(messageData);
- const updateData = {
- role: 'tool' as const,
- plugin: { apiName: 'a', identifier: 'b', arguments: 'abc' },
- };
-
- await MessageModel.update(createdMessage.id, updateData);
- const updatedMessage = await MessageModel.findById(createdMessage.id);
-
- expect(updatedMessage).toHaveProperty('role', 'tool');
- });
- });
-
- describe('batchUpdate', () => {
- it('should batch update messages', async () => {
- const createdMessage1 = await MessageModel.create(messageData);
- const createdMessage2 = await MessageModel.create(messageData);
- const updateData = { content: 'Batch updated content' };
-
- const numUpdated = await MessageModel.batchUpdate(
- [createdMessage1.id, createdMessage2.id],
- updateData,
- );
-
- expect(numUpdated).toBe(2);
-
- const updatedMessage1 = await MessageModel.findById(createdMessage1.id);
- const updatedMessage2 = await MessageModel.findById(createdMessage2.id);
-
- expect(updatedMessage1).toHaveProperty('content', 'Batch updated content');
- expect(updatedMessage2).toHaveProperty('content', 'Batch updated content');
- });
- });
-
- describe('batchDelete', () => {
- it('should batch delete messages by session id', async () => {
- // 创建多条消息以测试批量删除方法
- const createdMessage1 = await MessageModel.create(messageData);
- const createdMessage2 = await MessageModel.create(messageData);
-
- await MessageModel.batchDelete(messageData.sessionId, undefined);
-
- // 验证所有具有给定会话 ID 的消息是否已删除
- const messagesInDb = await MessageModel.query({ sessionId: messageData.sessionId });
- expect(messagesInDb).toHaveLength(0);
- });
-
- it('should batch delete messages by session id and topic id', async () => {
- // 创建多条消息以测试批量删除方法
- const createdMessage1 = await MessageModel.create(messageData);
- const createdMessage2 = await MessageModel.create(messageData);
-
- await MessageModel.batchDelete(messageData.sessionId, messageData.topicId);
-
- // 验证所有具有给定会话 ID 和话题 ID 的消息是否已删除
- const messagesInDb = await MessageModel.query({
- sessionId: messageData.sessionId,
- topicId: messageData.topicId,
- });
- expect(messagesInDb).toHaveLength(0);
- });
- });
-
- describe('duplicateMessages', () => {
- it('should duplicate messages and update parentId for copied messages', async () => {
- // 创建原始消息和父消息
- const parentMessageData: CreateMessageParams = {
- content: 'Parent message content',
- role: 'user',
- sessionId: 'session1',
- topicId: undefined,
- };
- const parentMessage = await MessageModel.create(parentMessageData);
-
- const childMessageData: CreateMessageParams = {
- content: 'Child message content',
- role: 'user',
- sessionId: 'session1',
- parentId: parentMessage.id,
- };
-
- await MessageModel.create(childMessageData);
-
- // 获取数据库中的消息以进行复制
- const originalMessages = await MessageModel.queryAll();
-
- // 执行复制操作
- const duplicatedMessages = await MessageModel.duplicateMessages(originalMessages);
-
- // 验证复制的消息数量是否正确
- expect(duplicatedMessages.length).toBe(originalMessages.length);
-
- // 验证每个复制的消息是否具有新的唯一ID,并且parentId被正确更新
- for (const original of originalMessages) {
- const copied = duplicatedMessages.find((m) => m.content === original.content);
- expect(copied).toBeDefined();
- expect(copied).not.toBeNull();
- expect(copied!.id).not.toBe(original.id);
- if (original.parentId) {
- const originalParent = originalMessages.find((m) => m.id === original.parentId);
- expect(originalParent).toBeDefined();
- const copiedParent = duplicatedMessages.find(
- (m) => m.content === originalParent!.content,
- );
-
- expect(copied!.parentId).toBe(copiedParent!.id);
- }
- }
- });
- });
-
- describe('clearTable', () => {
- it('should clear the table', async () => {
- await MessageModel.create(messageData);
- await MessageModel.clearTable();
- const messages = await MessageModel.queryAll();
- expect(messages).toHaveLength(0);
- });
- });
-
- describe('updatePluginState', () => {
- it('should update plugin state', async () => {
- const createdMessage = await MessageModel.create(messageData);
- await MessageModel.updatePluginState(createdMessage.id, { testKey: 'testValue' });
- const updatedMessage = await MessageModel.findById(createdMessage.id);
- expect(updatedMessage.pluginState).toHaveProperty('testKey', 'testValue');
- });
- });
-
- describe('updatePlugin', () => {
- it('should update plugin', async () => {
- const value = {
- identifier: 'testValue',
- arguments: 'abc',
- apiName: 'abc',
- };
- const createdMessage = await MessageModel.create(messageData);
- await MessageModel.updatePlugin(createdMessage.id, value);
- const updatedMessage = await MessageModel.findById(createdMessage.id);
- expect(updatedMessage.plugin).toEqual(value);
- });
- });
-
- describe('isEmpty', () => {
- it('should return true if table is empty', async () => {
- const number = await MessageModel.count();
- expect(number === 0).toBeTruthy();
- });
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/plugin.test.ts b/src/database/_deprecated/models/__tests__/plugin.test.ts
deleted file mode 100644
index ada338b5f97..00000000000
--- a/src/database/_deprecated/models/__tests__/plugin.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { DB_Plugin } from '../../schemas/plugin';
-import { PluginModel } from '../plugin';
-
-describe('PluginModel', () => {
- let pluginData: DB_Plugin;
-
- beforeEach(() => {
- // 设置正确结构的插件数据
- pluginData = {
- identifier: 'test-plugin',
- id: 'test-plugin',
- manifest: {},
- type: 'plugin',
- };
- });
-
- afterEach(async () => {
- // 每次测试后清理数据库
- await PluginModel.clear();
- });
-
- describe('getList', () => {
- it('should fetch and return the plugin list', async () => {
- await PluginModel.create(pluginData);
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(1);
- expect(plugins[0]).toEqual(pluginData);
- });
- });
-
- describe('create', () => {
- it('should create a plugin record', async () => {
- await PluginModel.create(pluginData);
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(1);
- expect(plugins[0]).toEqual(pluginData);
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create plugin records', async () => {
- await PluginModel.batchCreate([pluginData, { ...pluginData, identifier: 'abc' }]);
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(2);
- });
- });
-
- describe('delete', () => {
- it('should delete a plugin', async () => {
- await PluginModel.create(pluginData);
- await PluginModel.delete(pluginData.identifier);
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(0);
- });
- });
-
- describe('update', () => {
- it('should update a plugin', async () => {
- await PluginModel.create(pluginData);
- const updatedPluginData: DB_Plugin = {
- ...pluginData,
- type: 'customPlugin',
- };
- await PluginModel.update(pluginData.identifier, updatedPluginData);
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(1);
- expect(plugins[0]).toEqual({ ...updatedPluginData, updatedAt: expect.any(Number) });
- });
- });
-
- describe('clear', () => {
- it('should clear the table', async () => {
- await PluginModel.create(pluginData);
- await PluginModel.clear();
- const plugins = await PluginModel.getList();
- expect(plugins).toHaveLength(0);
- });
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/session.test.ts b/src/database/_deprecated/models/__tests__/session.test.ts
deleted file mode 100644
index e34de554930..00000000000
--- a/src/database/_deprecated/models/__tests__/session.test.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
-import { CreateMessageParams, MessageModel } from '@/database/_deprecated/models/message';
-import { SessionGroupModel } from '@/database/_deprecated/models/sessionGroup';
-import { TopicModel } from '@/database/_deprecated/models/topic';
-import { LobeAgentConfig } from '@/types/agent';
-import {
- LobeAgentSession,
- LobeSessionType,
- SessionDefaultGroup,
- SessionGroupId,
-} from '@/types/session';
-
-import { SessionModel } from '../session';
-
-describe('SessionModel', () => {
- let sessionData: Partial<LobeAgentSession>;
-
- beforeEach(() => {
- // Set up session data with the correct structure
- sessionData = {
- type: LobeSessionType.Agent,
- group: 'testGroup',
- meta: {},
- config: DEFAULT_AGENT_CONFIG,
- };
- });
-
- afterEach(async () => {
- // Clean up the database after each test
- await SessionModel.clearTable();
- });
- describe('create', () => {
- it('should create a session record', async () => {
- const result = await SessionModel.create('agent', sessionData);
-
- expect(result).toHaveProperty('id');
- // Verify that the session has been added to the database
- // Assuming findById is a method that retrieves a session by ID
- const sessionInDb = await SessionModel.findById(result.id);
-
- expect(sessionInDb).toEqual(expect.objectContaining(sessionData));
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create session records', async () => {
- const sessionsToCreate = [sessionData, sessionData];
- const results = await SessionModel.batchCreate(sessionsToCreate as LobeAgentSession[]);
-
- expect(results.ids).toHaveLength(sessionsToCreate.length);
- // Verify that the sessions have been added to the database
- for (const result of results.ids!) {
- const sessionInDb = await SessionModel.findById(result);
- expect(sessionInDb).toEqual(expect.objectContaining(sessionData));
- }
- });
-
- it('should set group to default if it does not exist in SessionGroup', async () => {
- const sessionDataWithInvalidGroup = {
- ...sessionData,
- group: 'nonExistentGroup',
- } as LobeAgentSession;
-
- const results = await SessionModel.batchCreate([sessionDataWithInvalidGroup]);
-
- // Verify that the group has been set to default
- for (const result of results.ids!) {
- const sessionInDb = await SessionModel.findById(result);
- expect(sessionInDb.group).toEqual(SessionDefaultGroup.Default);
- }
- });
- });
-
- describe('query', () => {
- it('should query sessions with pagination', async () => {
- // Create multiple sessions to test the query method
- await SessionModel.batchCreate([sessionData, sessionData] as LobeAgentSession[]);
-
- const queriedSessions = await SessionModel.query({ pageSize: 1, current: 0 });
-
- expect(queriedSessions).toHaveLength(1);
- });
- });
-
- describe('querySessionsByGroupId', () => {
- it('should query sessions by group', async () => {
- // Create multiple sessions to test the queryByGroup method
- const group: SessionGroupId = 'testGroup';
- await SessionGroupModel.create('测试分组', 0, group);
-
- await SessionModel.batchCreate([sessionData, sessionData] as LobeAgentSession[]);
-
- const sessionsByGroup = await SessionModel.querySessionsByGroupId(group);
-
- // Assuming all created sessions belong to the same group
- expect(sessionsByGroup).toHaveLength(2);
- expect(sessionsByGroup.every((i) => i.group === group)).toBeTruthy();
- });
- });
-
- describe('update', () => {
- it('should update a session', async () => {
- const createdSession = await SessionModel.create('agent', sessionData);
- const updateData = { group: 'newGroup' };
-
- await SessionModel.update(createdSession.id, updateData);
- const updatedSession = await SessionModel.findById(createdSession.id);
-
- expect(updatedSession).toHaveProperty('group', 'newGroup');
- });
-
- it('should update pinned status of a session', async () => {
- const createdSession = await SessionModel.create('agent', sessionData);
- await SessionModel.update(createdSession.id, { pinned: 1 });
- const updatedSession = await SessionModel.findById(createdSession.id);
- expect(updatedSession).toHaveProperty('pinned', 1);
- });
- });
-
- describe('updateConfig', () => {
- it('should update config of a session', async () => {
- const { id } = await SessionModel.create('agent', sessionData);
- const dbSession = await SessionModel.findById(id);
-
- const newConfig = { ...dbSession.config, systemRole: 'newValue' } as LobeAgentConfig;
- await SessionModel.updateConfig(id, newConfig);
- const updatedSession = await SessionModel.findById(id);
- expect(updatedSession.config).toEqual(newConfig);
- });
- });
-
- describe('clearTable', () => {
- it('should clear all sessions', async () => {
- await SessionModel.batchCreate([sessionData, sessionData] as LobeAgentSession[]);
- await SessionModel.clearTable();
- const sessionsInDb = await SessionModel.query();
- expect(sessionsInDb).toHaveLength(0);
- });
- });
-
- describe('isEmpty', () => {
- it('should check if table is empty', async () => {
- await SessionModel.clearTable();
- const isEmpty = await SessionModel.isEmpty();
- expect(isEmpty).toBeTruthy();
- await SessionModel.create('agent', sessionData);
- const isNotEmpty = await SessionModel.isEmpty();
- expect(isNotEmpty).toBeFalsy();
- });
- });
-
- describe('queryByKeyword', () => {
- it('should query sessions by keyword', async () => {
- const keyword = 'testKeyword';
- const sessionWithKeyword = { ...sessionData, meta: { title: keyword } };
- await SessionModel.create('agent', sessionWithKeyword);
- const sessionsByKeyword = await SessionModel.queryByKeyword(keyword);
- expect(sessionsByKeyword).toHaveLength(1);
- expect(sessionsByKeyword[0].meta.title).toContain(keyword);
- });
- });
-
- describe('getPinnedSessions', () => {
- it('should get pinned sessions', async () => {
- const pinnedSession = { ...sessionData, pinned: true };
- const unpinnedSession = { ...sessionData, pinned: false };
- await SessionModel.batchCreate([pinnedSession, unpinnedSession] as LobeAgentSession[]);
- const pinnedSessions = await SessionModel.getPinnedSessions();
- expect(pinnedSessions).toHaveLength(1);
- expect(pinnedSessions[0].pinned).toBeTruthy();
- });
- });
-
- describe('queryWithGroups', () => {
- it('should query sessions with groups', async () => {
- await SessionModel.create('agent', sessionData);
-
- const sessionsWithGroups = await SessionModel.queryWithGroups();
- expect(sessionsWithGroups.sessions).toHaveLength(1);
- expect(sessionsWithGroups.sessions[0]).toEqual(expect.objectContaining(sessionData));
- });
- });
-
- describe('queryByGroupIds', () => {
- it('should query sessions by group ids', async () => {
- const createdSession = await SessionModel.create('agent', sessionData);
- const session = await SessionModel.findById(createdSession.id);
- const sessionsByGroupIds = await SessionModel.queryByGroupIds([session.group]);
- expect(sessionsByGroupIds[session.group]).toHaveLength(1);
- expect(sessionsByGroupIds[session.group][0]).toEqual(expect.objectContaining(sessionData));
- });
- });
-
- describe('delete', () => {
- it('should delete a session', async () => {
- const createdSession = await SessionModel.create('agent', sessionData);
- await SessionModel.delete(createdSession.id);
- const sessionInDb = await SessionModel.findById(createdSession.id);
- expect(sessionInDb).toBeUndefined();
- });
-
- // 删除一个 session 时,也需要同步删除具有 sessionId 的 topic 和 message
- it('should delete a session and its associated data', async () => {
- // create session , topic and message test data
- const { id: sessionId } = await SessionModel.create('agent', sessionData);
-
- const topicData = {
- title: 'Test Topic',
- sessionId: sessionId,
- favorite: false,
- };
- const createdTopic = await TopicModel.create(topicData);
-
- const messageData: CreateMessageParams = {
- content: 'Test Message',
- sessionId: sessionId,
- topicId: createdTopic.id,
- role: 'user',
- };
- await MessageModel.create(messageData);
-
- await SessionModel.delete(sessionId);
-
- // Verify the session and its related data (topics, messages) are deleted
- const sessionInDb = await SessionModel.findById(sessionId);
- expect(sessionInDb).toBeUndefined();
-
- // You need to verify that topics and messages related to the session are also deleted
- const topicsInDb = await TopicModel.findBySessionId(sessionId);
- expect(topicsInDb).toHaveLength(0);
-
- // Verify all associated messages are deleted
- const messagesInDb = await MessageModel.query({ sessionId });
- expect(messagesInDb).toHaveLength(0);
- });
- });
-
- describe('duplicate', () => {
- it('should duplicate a session', async () => {
- const createdSession = await SessionModel.create('agent', sessionData);
- const duplicatedSession = await SessionModel.duplicate(createdSession.id);
- const sessionsInDb = await SessionModel.query();
- expect(sessionsInDb).toHaveLength(2);
-
- if (!duplicatedSession) return;
- const session = await SessionModel.findById(duplicatedSession.id);
-
- expect(session).toEqual(expect.objectContaining(sessionData));
- });
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/sessionGroup.test.ts b/src/database/_deprecated/models/__tests__/sessionGroup.test.ts
deleted file mode 100644
index 21b5066edfc..00000000000
--- a/src/database/_deprecated/models/__tests__/sessionGroup.test.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { SessionGroups } from '@/types/session';
-
-import { DB_SessionGroup } from '../../schemas/sessionGroup';
-import { SessionGroupModel } from '../sessionGroup';
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-
-describe('SessionGroupModel', () => {
- let sessionGroupData: DB_SessionGroup;
-
- beforeEach(() => {
- // 设置正确结构的会话组数据
- sessionGroupData = {
- name: 'test-group',
- sort: 1,
- };
- });
-
- afterEach(async () => {
- // 每次测试后清理数据库
- await SessionGroupModel.clear();
- });
-
- describe('create', () => {
- it('should create a session group record', async () => {
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
- const item = await SessionGroupModel.findById(createdGroup.id);
- expect(item.name).toEqual(sessionGroupData.name);
- expect(item.sort).toEqual(sessionGroupData.sort);
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create session group records', async () => {
- const groups = [
- sessionGroupData,
- { ...sessionGroupData, name: 'another-group' },
- ] as SessionGroups;
- await SessionGroupModel.batchCreate(groups);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toHaveLength(2);
- });
- });
-
- describe('update', () => {
- it('should update a session group', async () => {
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
- const updatedGroupData: DB_SessionGroup = { ...sessionGroupData, name: 'updated-group' };
- await SessionGroupModel.update(createdGroup.id, updatedGroupData);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].name).toEqual(updatedGroupData.name);
- });
- });
-
- describe('delete', () => {
- it('should delete a session group', async () => {
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
- await SessionGroupModel.delete(createdGroup.id);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toHaveLength(0);
- });
- it('should delete a session group and update associated sessions', async () => {
- // Create a new session group
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
-
- // Delete the created session group
- await SessionGroupModel.delete(createdGroup.id);
-
- // Fetch all session groups to confirm deletion
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toHaveLength(0);
-
- // Fetch all sessions to confirm update
- const fetchedSessions = await SessionModel.query();
- fetchedSessions.forEach((session) => {
- expect(session.group).not.toEqual(createdGroup.id);
- });
- });
- it('should update associated sessions to default group when a session group is deleted', async () => {
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
- const sessionId = await SessionModel.create('agent', {}, createdGroup.id);
- await SessionGroupModel.delete(createdGroup.id);
- const updatedSession = await SessionModel.findById(sessionId.id);
- expect(updatedSession.group).toEqual('default');
- });
- });
-
- describe('query', () => {
- it('should fetch and return the session group list', async () => {
- await SessionGroupModel.create(sessionGroupData.name, sessionGroupData.sort);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toHaveLength(1);
- expect(fetchedGroups[0].name).toEqual(sessionGroupData.name);
- });
-
- it('should return an empty array when there are no session groups', async () => {
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toEqual([]);
- });
-
- it('should return session groups sorted by sort field when it exists', async () => {
- const group1 = await SessionGroupModel.create('group1', 2);
- const group2 = await SessionGroupModel.create('group2', 1);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(group2.id);
- expect(fetchedGroups[1].id).toEqual(group1.id);
- });
-
- it('should return session groups sorted by createdAt when sort field does not exist', async () => {
- const group1 = await SessionGroupModel.create('group1');
- await new Promise((resolve) => setTimeout(() => resolve(undefined), 300));
- const group2 = await SessionGroupModel.create('group2');
-
- const fetchedGroups = await SessionGroupModel.query();
-
- expect(fetchedGroups[0].id).toEqual(group2.id);
- expect(fetchedGroups[1].id).toEqual(group1.id);
- });
-
- it('should return session groups sorted by sort field first and then by createdAt', async () => {
- const group0 = await SessionGroupModel.create('group0');
- await sleep(10);
- const group1 = await SessionGroupModel.create('group1', 1);
- await sleep(10);
- const group2 = await SessionGroupModel.create('group2');
- await sleep(10);
- const group3 = await SessionGroupModel.create('group3', 2);
- await sleep(10);
-
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(group1.id);
- expect(fetchedGroups[1].id).toEqual(group3.id);
- expect(fetchedGroups[2].id).toEqual(group2.id);
- expect(fetchedGroups[3].id).toEqual(group0.id);
- });
-
- it('should return session groups sorted by sort ', async () => {
- const group1 = await SessionGroupModel.create('group1', 1);
- const group2 = await SessionGroupModel.create('group2');
- const group3 = await SessionGroupModel.create('group3', 2);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(group1.id);
- expect(fetchedGroups[1].id).toEqual(group3.id);
- expect(fetchedGroups[2].id).toEqual(group2.id);
- });
-
- it('should return session groups sorted by createdAt when sort fields are equal', async () => {
- const group1 = await SessionGroupModel.create('group1', 1);
- await new Promise((resolve) => setTimeout(() => resolve(undefined), 300));
- const group2 = await SessionGroupModel.create('group2', 1);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(group2.id);
- expect(fetchedGroups[1].id).toEqual(group1.id);
- });
-
- it('should sort session groups correctly when only b has a sort value', async () => {
- const groupA = await SessionGroupModel.create('groupA'); // sort undefined
- const groupB = await SessionGroupModel.create('groupB', 1); // sort defined
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(groupB.id);
- expect(fetchedGroups[1].id).toEqual(groupA.id);
- });
- });
-
- describe('updateOrder', () => {
- it('should update the order of session groups', async () => {
- const group1 = await SessionGroupModel.create(sessionGroupData.name, sessionGroupData.sort);
- const group2 = await SessionGroupModel.create('another-group', 2);
- await SessionGroupModel.updateOrder([
- { id: group1.id, sort: 2 },
- { id: group2.id, sort: 1 },
- ]);
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups[0].id).toEqual(group2.id);
- expect(fetchedGroups[1].id).toEqual(group1.id);
- });
- });
-
- describe('findById', () => {
- it('should find a session group by id', async () => {
- const createdGroup = await SessionGroupModel.create(
- sessionGroupData.name,
- sessionGroupData.sort,
- );
- const fetchedGroup = await SessionGroupModel.findById(createdGroup.id);
- expect(fetchedGroup).toMatchObject({ ...createdGroup, ...sessionGroupData });
- });
- });
-
- describe('clear', () => {
- it('should clear all session groups', async () => {
- await SessionGroupModel.create(sessionGroupData.name, sessionGroupData.sort);
- const first = await SessionGroupModel.query();
- expect(first).toHaveLength(1);
-
- await SessionGroupModel.clear();
-
- const fetchedGroups = await SessionGroupModel.query();
- expect(fetchedGroups).toHaveLength(0);
- });
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/topic.test.ts b/src/database/_deprecated/models/__tests__/topic.test.ts
deleted file mode 100644
index c1a5eed63c6..00000000000
--- a/src/database/_deprecated/models/__tests__/topic.test.ts
+++ /dev/null
@@ -1,523 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { CreateMessageParams, MessageModel } from '@/database/_deprecated/models/message';
-import { DB_Message } from '@/database/_deprecated/schemas/message';
-import { DB_Topic } from '@/database/_deprecated/schemas/topic';
-import { nanoid } from '@/utils/uuid';
-import * as uuidUtils from '@/utils/uuid';
-
-import { CreateTopicParams, QueryTopicParams, TopicModel } from '../topic';
-
-describe('TopicModel', () => {
- let topicData: CreateTopicParams;
- const currentSessionId = 'session1';
- beforeEach(() => {
- // Set up topic data with the correct structure
- topicData = {
- sessionId: currentSessionId,
- title: 'Test Topic',
- favorite: false,
- };
- });
-
- afterEach(async () => {
- // Clean up the database after each test
- await TopicModel.clearTable();
- });
-
- describe('create', () => {
- it('should create a topic record', async () => {
- const result = await TopicModel.create(topicData);
-
- expect(result).toHaveProperty('id');
- // Verify that the topic has been added to the database
- const topicInDb = await TopicModel.findById(result.id);
-
- expect(topicInDb).toEqual(
- expect.objectContaining({
- title: topicData.title,
- favorite: topicData.favorite ? 1 : 0,
- sessionId: topicData.sessionId,
- }),
- );
- });
-
- it('should create a topic with favorite set to true', async () => {
- const favoriteTopicData: CreateTopicParams = {
- ...topicData,
- favorite: true,
- };
- const result = await TopicModel.create(favoriteTopicData);
-
- expect(result).toHaveProperty('id');
- const topicInDb = await TopicModel.findById(result.id);
- expect(topicInDb).toEqual(
- expect.objectContaining({
- title: favoriteTopicData.title,
- favorite: 1,
- sessionId: favoriteTopicData.sessionId,
- }),
- );
- });
-
- it('should update messages with the new topic id when messages are provided', async () => {
- const messagesToUpdate = [nanoid(), nanoid()];
- // 假设这些消息存在于数据库中
- for (const messageId of messagesToUpdate) {
- await MessageModel.table.add({ id: messageId, text: 'Sample message', topicId: null });
- }
-
- const topicDataWithMessages = {
- ...topicData,
- messages: messagesToUpdate,
- };
-
- const topic = await TopicModel.create(topicDataWithMessages);
- expect(topic).toHaveProperty('id');
-
- // 验证数据库中的消息是否已更新
- const updatedMessages: DB_Message[] = await MessageModel.table
- .where('id')
- .anyOf(messagesToUpdate)
- .toArray();
-
- expect(updatedMessages).toHaveLength(messagesToUpdate.length);
- for (const message of updatedMessages) {
- expect(message.topicId).toEqual(topic.id);
- }
- });
-
- it('should create a topic with a unique id when no id is provided', async () => {
- const spy = vi.spyOn(uuidUtils, 'nanoid'); // 使用 Vitest 的 spy 功能来监视 nanoid 调用
- const result = await TopicModel.create(topicData);
-
- expect(spy).toHaveBeenCalled(); // 验证 nanoid 被调用来生成 id
- expect(result).toHaveProperty('id');
- expect(typeof result.id).toBe('string');
- spy.mockRestore(); // 测试结束后恢复原始行为
- });
- });
- describe('batch create', () => {
- it('should batch create topic records', async () => {
- const topicsToCreate = [topicData, topicData];
- const results = await TopicModel.batchCreate(topicsToCreate);
-
- expect(results.ids).toHaveLength(topicsToCreate.length);
- // Verify that the topics have been added to the database
- for (const result of results.ids!) {
- const topicInDb = await TopicModel.findById(result);
- expect(topicInDb).toEqual(
- expect.objectContaining({
- title: topicData.title,
- favorite: topicData.favorite ? 1 : 0,
- sessionId: topicData.sessionId,
- }),
- );
- }
- });
-
- it('should batch create topics with mixed favorite values', async () => {
- const mixedTopicsData: CreateTopicParams[] = [
- { ...topicData, favorite: true },
- { ...topicData, favorite: false },
- ];
-
- const results = await TopicModel.batchCreate(mixedTopicsData);
-
- expect(results.ids).toHaveLength(mixedTopicsData.length);
- for (const id of results.ids!) {
- const topicInDb = await TopicModel.findById(id);
- expect(topicInDb).toBeDefined();
- expect(topicInDb.favorite).toBeGreaterThanOrEqual(0);
- expect(topicInDb.favorite).toBeLessThanOrEqual(1);
- }
- });
- });
-
- it('should query topics with pagination', async () => {
- // Create multiple topics to test the query method
- await TopicModel.batchCreate([topicData, topicData]);
-
- const queryParams: QueryTopicParams = { pageSize: 1, current: 0, containerId: 'session1' };
- const queriedTopics = await TopicModel.query(queryParams);
-
- expect(queriedTopics).toHaveLength(1);
- });
-
- it('should find topics by session id', async () => {
- // Create multiple topics to test the findBySessionId method
- await TopicModel.batchCreate([topicData, topicData]);
-
- const topicsBySessionId = await TopicModel.findBySessionId(topicData.sessionId);
-
- expect(topicsBySessionId).toHaveLength(2);
- expect(topicsBySessionId.every((i) => i.sessionId === topicData.sessionId)).toBeTruthy();
- });
-
- it('should delete a topic and its associated messages', async () => {
- const createdTopic = await TopicModel.create(topicData);
-
- await TopicModel.delete(createdTopic.id);
-
- // Verify the topic and its related messages are deleted
- const topicInDb = await TopicModel.findById(createdTopic.id);
- expect(topicInDb).toBeUndefined();
-
- // You need to verify that messages related to the topic are also deleted
- // This would require additional setup to create messages associated with the topic
- // and then assertions to check that they're deleted after the topic itself is deleted
- });
-
- it('should batch delete topics by session id', async () => {
- // Create multiple topics to test the batchDeleteBySessionId method
- await TopicModel.batchCreate([topicData, topicData]);
-
- await TopicModel.batchDeleteBySessionId(topicData.sessionId);
-
- // Verify that all topics with the given session id are deleted
- const topicsInDb = await TopicModel.findBySessionId(topicData.sessionId);
- expect(topicsInDb).toHaveLength(0);
- });
-
- it('should update a topic', async () => {
- const createdTopic = await TopicModel.create(topicData);
- const updateData = { title: 'New Title' };
-
- await TopicModel.update(createdTopic.id, updateData);
- const updatedTopic = await TopicModel.findById(createdTopic.id);
-
- expect(updatedTopic).toHaveProperty('title', 'New Title');
- });
-
- describe('toggleFavorite', () => {
- it('should toggle favorite status of a topic', async () => {
- const createdTopic = await TopicModel.create(topicData);
-
- const newState = await TopicModel.toggleFavorite(createdTopic.id);
-
- expect(newState).toBe(true);
- const topicInDb = await TopicModel.findById(createdTopic.id);
- expect(topicInDb).toHaveProperty('favorite', 1);
- });
-
- it('should handle toggleFavorite when topic does not exist', async () => {
- const nonExistentTopicId = 'non-existent-id';
- await expect(TopicModel.toggleFavorite(nonExistentTopicId)).rejects.toThrow(
- `Topic with id ${nonExistentTopicId} not found`,
- );
- });
-
- it('should set favorite to specific state using toggleFavorite', async () => {
- const createdTopic = await TopicModel.create(topicData);
-
- // Set favorite to true regardless of current state
- await TopicModel.toggleFavorite(createdTopic.id, true);
- let topicInDb = await TopicModel.findById(createdTopic.id);
- expect(topicInDb.favorite).toBe(1);
-
- // Set favorite to false regardless of current state
- await TopicModel.toggleFavorite(createdTopic.id, false);
- topicInDb = await TopicModel.findById(createdTopic.id);
- expect(topicInDb.favorite).toBe(0);
- });
- });
-
- it('should delete a topic and its associated messages', async () => {
- // 创建话题和相关联的消息
- const createdTopic = await TopicModel.create(topicData);
- const messageData: CreateMessageParams = {
- content: 'Test Message',
- topicId: createdTopic.id,
- sessionId: topicData.sessionId,
- role: 'user',
- };
- await MessageModel.create(messageData);
-
- // 删除话题
- await TopicModel.delete(createdTopic.id);
-
- // 验证话题是否被删除
- const topicInDb = await TopicModel.findById(createdTopic.id);
- expect(topicInDb).toBeUndefined();
-
- // 验证与话题关联的消息是否也被删除
- const messagesInDb = await MessageModel.query({
- sessionId: topicData.sessionId,
- topicId: createdTopic.id,
- });
- expect(messagesInDb).toHaveLength(0);
- });
-
- it('should batch delete topics and their associated messages', async () => {
- // 创建多个话题和相关联的消息
- const createdTopic1 = await TopicModel.create(topicData);
- const createdTopic2 = await TopicModel.create(topicData);
-
- const messageData1: CreateMessageParams = {
- content: 'Test Message 1',
- topicId: createdTopic1.id,
- sessionId: topicData.sessionId,
- role: 'user',
- };
- const messageData2: CreateMessageParams = {
- content: 'Test Message 2',
- topicId: createdTopic2.id,
- sessionId: topicData.sessionId,
- role: 'user',
- };
- await MessageModel.create(messageData1);
- await MessageModel.create(messageData2);
-
- // 执行批量删除
- await TopicModel.batchDelete([createdTopic1.id, createdTopic2.id]);
-
- // 验证话题是否被删除
- const topicInDb1 = await TopicModel.findById(createdTopic1.id);
- const topicInDb2 = await TopicModel.findById(createdTopic2.id);
- expect(topicInDb1).toBeUndefined();
- expect(topicInDb2).toBeUndefined();
-
- // 验证与话题关联的消息是否也被删除
- const messagesInDb1 = await MessageModel.query({
- sessionId: topicData.sessionId,
- topicId: createdTopic1.id,
- });
- const messagesInDb2 = await MessageModel.query({
- sessionId: topicData.sessionId,
- topicId: createdTopic2.id,
- });
- expect(messagesInDb1).toHaveLength(0);
- expect(messagesInDb2).toHaveLength(0);
- });
-
- describe('duplicateTopic', () => {
- let originalTopic: DBModel<DB_Topic>;
- let originalMessages: any[];
-
- beforeEach(async () => {
- // 创建一个原始主题
- const { id } = await TopicModel.create({
- title: 'Original Topic',
- sessionId: 'session1',
- favorite: false,
- });
- originalTopic = await TopicModel.findById(id);
-
- // 创建一些关联到原始主题的消息
- originalMessages = await Promise.all(
- ['Message 1', 'Message 2'].map((text) =>
- MessageModel.create({
- content: text,
- topicId: originalTopic.id,
- sessionId: originalTopic.sessionId!,
- role: 'user',
- }),
- ),
- );
- });
-
- afterEach(async () => {
- // 清理数据库中的所有主题和消息
- await TopicModel.clearTable();
- await MessageModel.clearTable();
- });
-
- it('should duplicate a topic with all associated messages', async () => {
- // 执行复制操作
- await TopicModel.duplicateTopic(originalTopic.id);
-
- // 验证复制后的主题是否存在
- const duplicatedTopic = await TopicModel.findBySessionId(originalTopic.sessionId!);
- expect(duplicatedTopic).toHaveLength(2);
-
- // 验证复制后的消息是否存在
- const duplicatedMessages = await MessageModel.query({
- sessionId: originalTopic.sessionId!,
- topicId: duplicatedTopic[1].id, // 假设复制的主题是第二个
- });
- expect(duplicatedMessages).toHaveLength(originalMessages.length);
- });
-
- it('should throw an error if the topic does not exist', async () => {
- // 尝试复制一个不存在的主题
- const nonExistentTopicId = nanoid();
- await expect(TopicModel.duplicateTopic(nonExistentTopicId)).rejects.toThrow(
- `Topic with id ${nonExistentTopicId} not found`,
- );
- });
-
- it('should preserve the properties of the duplicated topic', async () => {
- // 执行复制操作
- await TopicModel.duplicateTopic(originalTopic.id);
-
- // 获取复制的主题
- const topics = await TopicModel.findBySessionId(originalTopic.sessionId!);
- const duplicatedTopic = topics.find((topic) => topic.id !== originalTopic.id);
-
- // 验证复制的主题是否保留了原始主题的属性
- expect(duplicatedTopic).toBeDefined();
- expect(duplicatedTopic).toMatchObject({
- title: originalTopic.title,
- favorite: originalTopic.favorite,
- sessionId: originalTopic.sessionId,
- });
- // 确保生成了新的 ID
- expect(duplicatedTopic.id).not.toBe(originalTopic.id);
- });
-
- it('should properly handle the messages hierarchy when duplicating', async () => {
- // 创建一个子消息关联到其中一个原始消息
- const { id } = await MessageModel.create({
- content: 'Child Message',
- topicId: originalTopic.id,
- parentId: originalMessages[0].id,
- sessionId: originalTopic.sessionId!,
- role: 'user',
- });
- const childMessage = await MessageModel.findById(id);
-
- // 执行复制操作
- await TopicModel.duplicateTopic(originalTopic.id);
-
- // 获取复制的消息
- const duplicatedMessages = await MessageModel.queryBySessionId(originalTopic.sessionId!);
-
- // 验证复制的子消息是否存在并且 parentId 已更新
- const duplicatedChildMessage = duplicatedMessages.find(
- (message) => message.content === childMessage.content && message.id !== childMessage.id,
- );
-
- expect(duplicatedChildMessage).toBeDefined();
- expect(duplicatedChildMessage.parentId).not.toBe(childMessage.parentId);
- expect(duplicatedChildMessage.parentId).toBeDefined();
- });
-
- it('should fail if the database transaction fails', async () => {
- // 强制数据库事务失败,例如通过在复制过程中抛出异常
- const dbTransactionFailedError = new Error('DB transaction failed');
- const spyOn = vi.spyOn(TopicModel['db'], 'transaction').mockImplementation((async () => {
- throw dbTransactionFailedError;
- }) as any);
-
- // 尝试复制主题并捕捉期望的错误
- await expect(TopicModel.duplicateTopic(originalTopic.id)).rejects.toThrow(
- dbTransactionFailedError,
- );
- spyOn.mockRestore();
- });
-
- it('should not create partial duplicates if the process fails at some point', async () => {
- // 假设复制消息的过程中发生了错误
- vi.spyOn(MessageModel, 'duplicateMessages').mockImplementation(async () => {
- throw new Error('Failed to duplicate messages');
- });
-
- // 尝试复制主题,期望会抛出错误
- await expect(TopicModel.duplicateTopic(originalTopic.id)).rejects.toThrow();
-
- // 确保没有创建任何副本
- const topics = await TopicModel.findBySessionId(originalTopic.sessionId!);
- expect(topics).toHaveLength(1); // 只有原始主题
-
- const messages = await MessageModel.queryBySessionId(originalTopic.sessionId!);
- expect(messages).toHaveLength(originalMessages.length); // 只有原始消息
- });
- });
-
- describe('clearTable', () => {
- it('should clear the table', async () => {
- // Create a topic to ensure the table is not empty
- await TopicModel.create(topicData);
-
- // Clear the table
- await TopicModel.clearTable();
-
- // Verify the table is empty
- const topics = await TopicModel.queryAll();
- expect(topics).toHaveLength(0);
- });
- });
-
- describe('update', () => {
- it('should update a topic', async () => {
- // Create a topic
- const createdTopic = await TopicModel.create(topicData);
-
- // Update the topic
- const newTitle = 'Updated Title';
- await TopicModel.update(createdTopic.id, { title: newTitle });
-
- // Verify the topic is updated
- const updatedTopic = await TopicModel.findById(createdTopic.id);
- expect(updatedTopic.title).toBe(newTitle);
- });
- });
-
- describe('batchDelete', () => {
- it('should batch delete topics', async () => {
- // Create multiple topics
- const topic1 = await TopicModel.create(topicData);
- const topic2 = await TopicModel.create(topicData);
-
- await TopicModel.create(topicData);
-
- const ids = [topic1.id, topic2.id];
- // Batch delete the topics
- await TopicModel.batchDelete(ids);
-
- expect(await TopicModel.table.count()).toEqual(1);
- });
- });
-
- describe('queryAll', () => {
- it('should query all topics', async () => {
- // Create multiple topics
- await TopicModel.batchCreate([topicData, topicData]);
-
- // Query all topics
- const topics = await TopicModel.queryAll();
-
- // Verify all topics are queried
- expect(topics).toHaveLength(2);
- });
- });
-
- describe('queryByKeyword', () => {
- it('should query global topics by keyword', async () => {
- // Create a topic with a unique title
- const uniqueTitle = 'Unique Title';
- await TopicModel.create({ ...topicData, title: uniqueTitle });
-
- // Query topics by the unique title
- const topics = await TopicModel.queryByKeyword(uniqueTitle);
-
- // Verify the correct topic is queried
- expect(topics).toHaveLength(1);
- expect(topics[0].title).toBe(uniqueTitle);
- });
- it('should query topics in current session by keyword', async () => {
- // Create a topic with a unique title
- const uniqueTitle = 'Unique Title';
- await TopicModel.create({ ...topicData, title: uniqueTitle });
-
- // Query topics by the unique title
- const topics = await TopicModel.queryByKeyword(uniqueTitle, currentSessionId);
-
- // Verify the correct topic is queried
- expect(topics).toHaveLength(1);
- expect(topics[0].title).toBe(uniqueTitle);
- });
- it('should not query any topic in other session by keyword', async () => {
- // Create a topic with a unique title
- const uniqueTitle = 'Unique Title';
- await TopicModel.create({ ...topicData, title: uniqueTitle });
-
- // Query topics by the unique title
- const topics = await TopicModel.queryByKeyword(uniqueTitle, 'session-id-2');
-
- // Verify the correct topic is queried
- expect(topics).toHaveLength(0);
- });
- });
-});
diff --git a/src/database/_deprecated/models/__tests__/user.test.ts b/src/database/_deprecated/models/__tests__/user.test.ts
deleted file mode 100644
index d69f24e620f..00000000000
--- a/src/database/_deprecated/models/__tests__/user.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { UserModel } from '../user';
-
-describe('UserModel', () => {
- let userData: any;
-
- beforeEach(() => {
- // Set up user data with the correct structure
- userData = {
- uuid: 'user1',
- settings: {},
- avatar: 'avatar.png',
- };
- });
-
- afterEach(async () => {
- // Clean up the database after each test
- await UserModel.clear();
- });
-
- it('should create a user record', async () => {
- const result = await UserModel.create(userData);
-
- expect(result).toEqual(1);
- // Verify that the user has been added to the database
- const userInDb = await UserModel.getUser();
-
- expect(userInDb).toEqual(
- expect.objectContaining({
- uuid: userData.uuid,
- settings: userData.settings,
- avatar: userData.avatar,
- }),
- );
- });
-
- it('should update a user record', async () => {
- const result = await UserModel.create(userData);
-
- const newAvatar = 'new_avatar.png';
- await UserModel.updateAvatar(newAvatar);
-
- const userInDb = await UserModel.getUser();
-
- expect(userInDb).toHaveProperty('avatar', newAvatar);
- });
-
- it('should update user settings', async () => {
- await UserModel.create(userData);
-
- await UserModel.updateSettings({ general: { themeMode: 'dark' } });
-
- const userInDb = await UserModel.getUser();
-
- expect(userInDb).toHaveProperty('settings', {
- general: { themeMode: 'dark' },
- });
- });
-
- it('should reset user settings', async () => {
- await UserModel.create(userData);
-
- await UserModel.updateSettings({ general: { themeMode: 'dark' } });
-
- await UserModel.resetSettings();
-
- const userInDb = await UserModel.getUser();
-
- expect(userInDb.settings).toBeUndefined();
- });
-
- it('should clear the user table', async () => {
- await UserModel.create(userData);
-
- await UserModel.clear();
-
- const userInDb = await UserModel.table.count();
-
- expect(userInDb).toEqual(0);
- });
-});
diff --git a/src/database/_deprecated/models/file.ts b/src/database/_deprecated/models/file.ts
deleted file mode 100644
index 1edb2ddcbdb..00000000000
--- a/src/database/_deprecated/models/file.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { DB_File, DB_FileSchema } from '@/database/_deprecated/schemas/files';
-import { clientS3Storage } from '@/services/file/ClientS3';
-import { nanoid } from '@/utils/uuid';
-
-import { BaseModel } from '../core';
-
-class _FileModel extends BaseModel<'files'> {
- constructor() {
- super('files', DB_FileSchema);
- }
-
- async create(file: DB_File) {
- const id = nanoid();
-
- return this._addWithSync(file, `file-${id}`);
- }
-
- async findById(id: string): Promise<DBModel<DB_File> | undefined> {
- const item = await this.table.get(id);
- if (!item) return;
-
- // arrayBuffer to url
- let base64;
- if (!item.data) {
- const hash = (item.url as string).replace('client-s3://', '');
- base64 = await this.getBase64ByFileHash(hash);
- } else {
- base64 = Buffer.from(item.data).toString('base64');
- }
-
- return { ...item, base64, url: `data:${item.fileType};base64,${base64}` };
- }
-
- async delete(id: string) {
- return this.table.delete(id);
- }
-
- async clear() {
- return this.table.clear();
- }
-
- private async getBase64ByFileHash(hash: string) {
- const fileItem = await clientS3Storage.getObject(hash);
- if (!fileItem) throw new Error('file not found');
-
- return Buffer.from(await fileItem.arrayBuffer()).toString('base64');
- }
-}
-
-export const FileModel = new _FileModel();
diff --git a/src/database/_deprecated/models/message.ts b/src/database/_deprecated/models/message.ts
deleted file mode 100644
index b0f59596f79..00000000000
--- a/src/database/_deprecated/models/message.ts
+++ /dev/null
@@ -1,277 +0,0 @@
-import { UIChatMessage } from '@lobechat/types';
-import type { PartialDeep } from 'type-fest';
-
-import { BaseModel } from '@/database/_deprecated/core';
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { DB_Message, DB_MessageSchema } from '@/database/_deprecated/schemas/message';
-import { nanoid } from '@/utils/uuid';
-
-/**
- * use `@/types/message` instead
- * @deprecated
- */
-export interface CreateMessageParams
- extends Partial<Omit<UIChatMessage, 'content' | 'role'>>,
- Pick<UIChatMessage, 'content' | 'role'> {
- files?: string[];
- fromModel?: string;
- fromProvider?: string;
- sessionId: string;
- traceId?: string;
-}
-
-export interface QueryMessageParams {
- current?: number;
- pageSize?: number;
- sessionId: string;
- topicId?: string;
-}
-
-class _MessageModel extends BaseModel {
- constructor() {
- super('messages', DB_MessageSchema);
- }
-
- // **************** Query *************** //
-
- async query({
- sessionId,
- topicId,
- pageSize = 9999,
- current = 0,
- }: QueryMessageParams): Promise<UIChatMessage[]> {
- const offset = current * pageSize;
-
- const query = !!topicId
- ? // TODO: The query {"sessionId":"xxx","topicId":"xxx"} on messages would benefit of a compound index [sessionId+topicId]
- this.table.where({ sessionId, topicId }) // Use a compound index
- : this.table
- .where('sessionId')
- .equals(sessionId)
- .and((message) => !message.topicId);
-
- const dbMessages: DBModel<DB_Message>[] = await query
- .sortBy('createdAt')
- // handle page size
- .then((sortedArray) => sortedArray.slice(offset, offset + pageSize));
-
- const messages = dbMessages.map((msg) => this.mapToChatMessage(msg));
-
- const finalList: UIChatMessage[] = [];
-
- const addItem = (item: UIChatMessage) => {
- const isExist = finalList.some((i) => item.id === i.id);
- if (!isExist) {
- finalList.push(item);
- }
- };
- const messageMap = new Map<string, UIChatMessage>();
- for (const item of messages) messageMap.set(item.id, item);
-
- for (const item of messages) {
- if (!item.parentId || !messageMap.has(item.parentId)) {
- // 如果消息没有父消息或者父消息不在列表中,直接添加
- addItem(item);
- } else {
- // 如果消息有父消息,确保先添加父消息
- addItem(messageMap.get(item.parentId)!);
- addItem(item);
- }
- }
- return finalList;
- }
-
- async findById(id: string): Promise<DBModel<DB_Message>> {
- return this.table.get(id);
- }
-
- async queryAll() {
- const data: DBModel<DB_Message>[] = await this.table.orderBy('updatedAt').toArray();
-
- return data.map((element) => this.mapToChatMessage(element));
- }
-
- async queryBySessionId(sessionId: string) {
- return this.table.where('sessionId').equals(sessionId).toArray();
- }
-
- queryByTopicId = async (topicId: string) => {
- const dbMessages = await this.table.where('topicId').equals(topicId).toArray();
-
- return dbMessages.map((message) => this.mapToChatMessage(message));
- };
-
- async count() {
- return this.table.count();
- }
-
- // **************** Create *************** //
-
- async create(data: CreateMessageParams) {
- const id = nanoid();
-
- const messageData: DB_Message = this.mapChatMessageToDBMessage(data as UIChatMessage);
-
- return this._addWithSync(messageData, id);
- }
-
- async batchCreate(messages: UIChatMessage[]) {
- const data: DB_Message[] = messages.map((m) => this.mapChatMessageToDBMessage(m));
-
- return this._batchAdd(data);
- }
-
- async duplicateMessages(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
- const duplicatedMessages = await this.createDuplicateMessages(messages);
- // 批量添加复制后的消息到数据库
- await this.batchCreate(duplicatedMessages);
- return duplicatedMessages;
- }
-
- // **************** Delete *************** //
-
- async delete(id: string) {
- return super._deleteWithSync(id);
- }
-
- async bulkDelete(ids: string[]) {
- return super._bulkDeleteWithSync(ids);
- }
-
- async clearTable() {
- return this._clearWithSync();
- }
-
- /**
- * Deletes multiple messages based on the assistantId and optionally the topicId.
- * If topicId is not provided, it deletes messages where topicId is undefined or null.
- * If topicId is provided, it deletes messages with that specific topicId.
- *
- * @param {string} sessionId - The identifier of the assistant associated with the messages.
- * @param {string | undefined} topicId - The identifier of the topic associated with the messages (optional).
- * @returns {Promise<void>}
- */
- async batchDelete(sessionId: string, topicId: string | undefined): Promise<void> {
- // If topicId is specified, use both assistantId and topicId as the filter criteria in the query.
- // Otherwise, filter by assistantId and require that topicId is undefined.
- const query = !!topicId
- ? this.table.where({ sessionId, topicId }) // Use a compound index
- : this.table
- .where('sessionId')
- .equals(sessionId)
- .and((message) => !message.topicId);
-
- // Retrieve a collection of message IDs that satisfy the criteria
- const messageIds = await query.primaryKeys();
-
- // Use the bulkDelete method to delete all selected messages in bulk
- return this._bulkDeleteWithSync(messageIds);
- }
-
- async batchDeleteBySessionId(sessionId: string): Promise<void> {
- // If topicId is specified, use both assistantId and topicId as the filter criteria in the query.
- // Otherwise, filter by assistantId and require that topicId is undefined.
- const messageIds = await this.table.where('sessionId').equals(sessionId).primaryKeys();
-
- // Use the bulkDelete method to delete all selected messages in bulk
- return this._bulkDeleteWithSync(messageIds);
- }
-
- /**
- * Delete all messages associated with the topicId
- * @param topicId
- */
- async batchDeleteByTopicId(topicId: string): Promise<void> {
- const messageIds = await this.table.where('topicId').equals(topicId).primaryKeys();
-
- return this._bulkDeleteWithSync(messageIds);
- }
-
- // **************** Update *************** //
-
- async update(id: string, data: PartialDeep<DB_Message>) {
- return super._updateWithSync(id, data);
- }
-
- async updatePluginState(id: string, value: any) {
- const item = await this.findById(id);
-
- return this.update(id, { pluginState: { ...item.pluginState, ...value } });
- }
-
- async updatePlugin(id: string, value: any) {
- const item = await this.findById(id);
-
- return this.update(id, { plugin: { ...item.plugin, ...value } });
- }
-
- /**
- * Batch updates multiple fields of the specified messages.
- *
- * @param {string[]} messageIds - The identifiers of the messages to be updated.
- * @param {Partial<DB_Message>} updateFields - An object containing the fields to update and their new values.
- * @returns {Promise<number>} - The number of updated messages.
- */
- async batchUpdate(messageIds: string[], updateFields: Partial<DB_Message>): Promise<number> {
- // Retrieve the messages by their IDs
- const messagesToUpdate = await this.table.where('id').anyOf(messageIds).toArray();
-
- // Update the specified fields of each message
- const updatedMessages = messagesToUpdate.map((message) => ({
- ...message,
- ...updateFields,
- }));
-
- // Use the bulkPut method to update the messages in bulk
- await this._bulkPutWithSync(updatedMessages);
-
- return updatedMessages.length;
- }
-
- // **************** Helper *************** //
-
- private async createDuplicateMessages(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
- // 创建一个映射来存储原始消息ID和复制消息ID之间的关系
- const idMapping = new Map<string, string>();
-
- // 首先复制所有消息,并为每个复制的消息生成新的ID
- const duplicatedMessages = messages.map((originalMessage) => {
- const newId = nanoid();
- idMapping.set(originalMessage.id, newId);
-
- return { ...originalMessage, id: newId };
- });
-
- // 更新 parentId 为复制后的新ID
- for (const duplicatedMessage of duplicatedMessages) {
- if (duplicatedMessage.parentId && idMapping.has(duplicatedMessage.parentId)) {
- duplicatedMessage.parentId = idMapping.get(duplicatedMessage.parentId);
- }
- }
-
- return duplicatedMessages;
- }
-
- private mapChatMessageToDBMessage(message: UIChatMessage): DB_Message {
- const { extra, ...messageData } = message;
-
- return { ...messageData, ...extra } as DB_Message;
- }
-
- private mapToChatMessage = ({
- fromModel,
- fromProvider,
- translate,
- tts,
- ...item
- }: DBModel<DB_Message>) => {
- return {
- ...item,
- extra: { fromModel, fromProvider, translate, tts },
- meta: {},
- topicId: item.topicId ?? undefined,
- } as UIChatMessage;
- };
-}
-
-export const MessageModel = new _MessageModel();
diff --git a/src/database/_deprecated/models/plugin.ts b/src/database/_deprecated/models/plugin.ts
deleted file mode 100644
index 425b1b60bf0..00000000000
--- a/src/database/_deprecated/models/plugin.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { LobeTool } from '@lobechat/types';
-import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
-
-import { BaseModel } from '@/database/_deprecated/core';
-import { merge } from '@/utils/merge';
-
-import { DB_Plugin, DB_PluginSchema } from '../schemas/plugin';
-
-export interface InstallPluginParams {
- identifier: string;
- manifest?: LobeChatPluginManifest;
- type: 'plugin' | 'customPlugin';
-}
-
-class _PluginModel extends BaseModel {
- constructor() {
- super('plugins', DB_PluginSchema);
- }
- // **************** Query *************** //
-
- getList = async (): Promise<DB_Plugin[]> => {
- return this.table.toArray();
- };
- // **************** Create *************** //
-
- create = async (plugin: InstallPluginParams) => {
- const old = await this.table.get(plugin.identifier);
- const dbPlugin = this.mapToDBPlugin(plugin);
-
- return this._putWithSync(merge(old, dbPlugin), plugin.identifier);
- };
-
- batchCreate = async (plugins: LobeTool[]) => {
- const dbPlugins = plugins.map((item) => this.mapToDBPlugin(item));
-
- return this._batchAdd(dbPlugins);
- };
- // **************** Delete *************** //
-
- delete(id: string) {
- return this._deleteWithSync(id);
- }
- clear() {
- return this._clearWithSync();
- }
-
- // **************** Update *************** //
-
- update: (id: string, value: Partial<DB_Plugin>) => Promise<number> = async (id, value) => {
- const { success } = await this._updateWithSync(id, value);
-
- return success;
- };
-
- // **************** Helper *************** //
-
- mapToDBPlugin(plugin: LobeTool) {
- return { ...plugin, id: plugin.identifier } as DB_Plugin;
- }
-}
-
-export const PluginModel = new _PluginModel();
diff --git a/src/database/_deprecated/models/session.ts b/src/database/_deprecated/models/session.ts
deleted file mode 100644
index 659b50d6841..00000000000
--- a/src/database/_deprecated/models/session.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-import type { PartialDeep } from 'type-fest';
-
-import { DEFAULT_AGENT_LOBE_SESSION } from '@/const/session';
-import { BaseModel } from '@/database/_deprecated/core';
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { DB_Session, DB_SessionSchema } from '@/database/_deprecated/schemas/session';
-import { LobeAgentConfig } from '@/types/agent';
-import {
- ChatSessionList,
- LobeAgentSession,
- LobeSessions,
- SessionDefaultGroup,
- SessionGroupId,
-} from '@/types/session';
-import { merge } from '@/utils/merge';
-import { uuid } from '@/utils/uuid';
-
-import { MessageModel } from './message';
-import { SessionGroupModel } from './sessionGroup';
-import { TopicModel } from './topic';
-
-class _SessionModel extends BaseModel {
- constructor() {
- super('sessions', DB_SessionSchema);
- }
-
- // **************** Query *************** //
-
- async query({
- pageSize = 9999,
- current = 0,
- }: { current?: number; pageSize?: number } = {}): Promise<LobeSessions> {
- const offset = current * pageSize;
-
- const items: DBModel<DB_Session>[] = await this.table
- .orderBy('updatedAt')
- .reverse()
- .offset(offset)
- .limit(pageSize)
- .toArray();
-
- return this.mapToAgentSessions(items);
- }
-
- async queryWithGroups(): Promise<ChatSessionList> {
- const sessionGroups = await SessionGroupModel.query();
-
- const sessions = await this.query();
-
- return { sessionGroups, sessions };
- }
-
- /**
- * get sessions by group
- * @param group
- */
- async querySessionsByGroupId(group: SessionGroupId): Promise<LobeSessions> {
- const items: DBModel<DB_Session>[] = await this.table
- .where('group')
- .equals(group)
- .and((session) => !session.pinned)
- .reverse()
- .sortBy('updatedAt');
-
- return this.mapToAgentSessions(items);
- }
-
- async queryByGroupIds(groups: string[]) {
- const pools = groups.map(async (id) => {
- return [id, await this.querySessionsByGroupId(id)] as const;
- });
- const groupItems = await Promise.all(pools);
-
- return Object.fromEntries(groupItems);
- }
-
- /**
- * Query sessions by keyword in title, description, content, or translated content
- * @param keyword The keyword to search for
- */
- async queryByKeyword(keyword: string): Promise<LobeSessions> {
- if (!keyword) return [];
-
- const startTime = Date.now();
- const keywordLowerCase = keyword.toLowerCase();
-
- // First, filter sessions by title and description
- const matchingSessionsPromise = this.table
- .filter((session) => {
- return (
- session.meta.title?.toLowerCase().includes(keywordLowerCase) ||
- session.meta.description?.toLowerCase().includes(keywordLowerCase)
- );
- })
- .toArray();
-
- // Next, find message IDs that contain the keyword in content or translated content
- const matchingMessagesPromise = this.db.messages
- .filter((message) => {
- // check content
- if (message.content.toLowerCase().includes(keywordLowerCase)) return true;
-
- // check translate content
- if (message.translate && message.translate.content) {
- return message.translate.content.toLowerCase().includes(keywordLowerCase);
- }
-
- return false;
- })
- .toArray();
-
- // match topics
- const matchingTopicsPromise = this.db.topics
- .filter((topic) => {
- return topic.title?.toLowerCase().includes(keywordLowerCase);
- })
- .toArray();
-
- // Resolve both promises
- const [matchingSessions, matchingMessages, matchingTopics] = await Promise.all([
- matchingSessionsPromise,
- matchingMessagesPromise,
- matchingTopicsPromise,
- ]);
-
- const sessionIdsFromMessages = matchingMessages.map((message) => message.sessionId);
- const sessionIdsFromTopics = matchingTopics.map((topic) => topic.sessionId);
-
- // Combine session IDs from both sources
- const combinedSessionIds = new Set([
- ...sessionIdsFromMessages,
- ...sessionIdsFromTopics,
- ...matchingSessions.map((session) => session.id),
- ]);
-
- // Retrieve unique sessions by IDs
- const items: DBModel<DB_Session>[] = await this.table
- .where('id')
- .anyOf([...combinedSessionIds])
- .toArray();
-
- console.log(`检索到 ${items.length} 项,耗时 ${Date.now() - startTime}ms`);
- return this.mapToAgentSessions(items);
- }
-
- async getPinnedSessions(): Promise<LobeSessions> {
- const items: DBModel<DB_Session>[] = await this.table
- .where('pinned')
- .equals(1)
- .reverse()
- .sortBy('updatedAt');
-
- return this.mapToAgentSessions(items);
- }
-
- async findById(id: string): Promise<DBModel<DB_Session>> {
- return this.table.get(id);
- }
-
- async isEmpty() {
- return (await this.table.count()) === 0;
- }
-
- async count() {
- return this.table.count();
- }
-
- // **************** Create *************** //
-
- async create(type: 'agent' | 'group', defaultValue: Partial<LobeAgentSession>, id = uuid()) {
- const data = merge(DEFAULT_AGENT_LOBE_SESSION, { type, ...defaultValue });
- const dataDB = this.mapToDB_Session(data);
- return this._addWithSync(dataDB, id);
- }
-
- async batchCreate(sessions: LobeAgentSession[]) {
- const DB_Sessions = await Promise.all(
- sessions.map(async (s) => {
- if (s.group && s.group !== SessionDefaultGroup.Default) {
- // Check if the group exists in the SessionGroup table
- const groupExists = await SessionGroupModel.findById(s.group);
- // If the group does not exist, set it to default
- if (!groupExists) {
- s.group = SessionDefaultGroup.Default;
- }
- }
- return this.mapToDB_Session(s);
- }),
- );
-
- return this._batchAdd<DB_Session>(DB_Sessions, { idGenerator: uuid });
- }
-
- async duplicate(id: string, newTitle?: string) {
- const session = await this.findById(id);
- if (!session) return;
-
- const newSession = merge(session, { meta: { title: newTitle } });
-
- return this._addWithSync(newSession, uuid());
- }
-
- // **************** Delete *************** //
-
- /**
- * Delete a session , also delete all messages and topic associated with it.
- */
- async delete(id: string) {
- return this.db.transaction('rw', [this.table, this.db.topics, this.db.messages], async () => {
- // Delete all topics associated with the session
- await TopicModel.batchDeleteBySessionId(id);
-
- // Delete all messages associated with the session
- await MessageModel.batchDeleteBySessionId(id);
-
- // Finally, delete the session itself
- await this._deleteWithSync(id);
- });
- }
-
- async batchDelete(ids: string[]) {
- return this._bulkDeleteWithSync(ids);
- }
-
- async clearTable() {
- return this._clearWithSync();
- }
-
- // **************** Update *************** //
-
- async update(id: string, data: Partial<DB_Session>) {
- return super._updateWithSync(id, data);
- }
-
- async updateConfig(id: string, data: PartialDeep<LobeAgentConfig>) {
- const session = await this.findById(id);
- if (!session) return;
-
- const config = merge(session.config, data);
-
- return this.update(id, { config });
- }
-
- // **************** Helper *************** //
-
- private mapToDB_Session(session: LobeAgentSession): DBModel<DB_Session> {
- return {
- ...session,
- createdAt: session.createdAt?.valueOf(),
- group: session.group || SessionDefaultGroup.Default,
- pinned: session.pinned ? 1 : 0,
- updatedAt: session.updatedAt?.valueOf(),
- };
- }
-
- private DB_SessionToAgentSession(session: DBModel<DB_Session>) {
- return {
- ...session,
- createdAt: new Date(session.createdAt),
- model: session.config.model,
- pinned: !!session.pinned,
- updatedAt: new Date(session.updatedAt),
- } as LobeAgentSession;
- }
-
- private mapToAgentSessions(session: DBModel<DB_Session>[]) {
- return session.map((item) => this.DB_SessionToAgentSession(item));
- }
-}
-
-export const SessionModel = new _SessionModel();
diff --git a/src/database/_deprecated/models/sessionGroup.ts b/src/database/_deprecated/models/sessionGroup.ts
deleted file mode 100644
index 4ae44887861..00000000000
--- a/src/database/_deprecated/models/sessionGroup.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { BaseModel } from '@/database/_deprecated/core';
-import {
- DB_SessionGroup,
- DB_SessionGroupSchema,
-} from '@/database/_deprecated/schemas/sessionGroup';
-import { SessionGroups } from '@/types/session';
-import { nanoid } from '@/utils/uuid';
-
-class _SessionGroupModel extends BaseModel {
- constructor() {
- super('sessionGroups', DB_SessionGroupSchema);
- }
-
- // **************** Query *************** //
-
- async query(): Promise<SessionGroups> {
- const allGroups = await this.table.toArray();
-
- // 自定义排序,先按 sort 存在与否分组,然后分别排序
- return allGroups.sort((a, b) => {
- // 如果两个项都有 sort,则按 sort 排序
- if (a.sort !== undefined && b.sort !== undefined) {
- // 如果sort 一样,按时间倒序排序
- if (a.sort === b.sort) return b.createdAt - a.createdAt;
-
- return a.sort - b.sort;
- }
- // 如果 a 有 sort 而 b 没有,则 a 排在前面
- if (a.sort !== undefined) {
- return -1;
- }
- // 如果 b 有 sort 而 a 没有,则 b 排在前面
- if (b.sort !== undefined) {
- return 1;
- }
- // 如果两个项都没有 sort,则按 createdAt 倒序排序
- return b.createdAt - a.createdAt;
- });
- }
-
- async findById(id: string): Promise<DB_SessionGroup> {
- return this.table.get(id);
- }
-
- // **************** Create *************** //
-
- async create(name: string, sort?: number, id = nanoid()) {
- return this._addWithSync({ name, sort }, id);
- }
-
- async batchCreate(groups: SessionGroups) {
- return this._batchAdd(groups, { idGenerator: nanoid });
- }
-
- // **************** Delete *************** //
- async delete(id: string, removeGroupItem: boolean = false) {
- const { SessionModel } = await import('./session');
- this.db.sessions.toCollection().modify(async (session) => {
- // update all session associated with the sessionGroup to default
- if (session.group === id) {
- await SessionModel.update(session.id, { group: 'default' });
- }
- });
-
- if (!removeGroupItem) {
- return this._deleteWithSync(id);
- } else {
- const sessionIds = await this.db.sessions.where('group').equals(id).primaryKeys();
-
- return await SessionModel.batchDelete(sessionIds);
- }
- }
-
- async clear() {
- await this._clearWithSync();
- }
-
- // **************** Update *************** //
-
- async update(id: string, data: Partial<DB_SessionGroup>) {
- return super._updateWithSync(id, data);
- }
-
- async updateOrder(sortMap: { id: string; sort: number }[]) {
- return this.db.transaction('rw', this.table, async () => {
- for (const { id, sort } of sortMap) {
- await this.update(id, { sort });
- }
- });
- }
-}
-
-export const SessionGroupModel = new _SessionGroupModel();
diff --git a/src/database/_deprecated/models/topic.ts b/src/database/_deprecated/models/topic.ts
deleted file mode 100644
index 30b8e6c5e5e..00000000000
--- a/src/database/_deprecated/models/topic.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { BaseModel } from '@/database/_deprecated/core';
-import { DBModel } from '@/database/_deprecated/core/types/db';
-import { MessageModel } from '@/database/_deprecated/models/message';
-import { DB_Topic, DB_TopicSchema } from '@/database/_deprecated/schemas/topic';
-import { ChatTopic } from '@/types/topic';
-import { nanoid } from '@/utils/uuid';
-
-export interface CreateTopicParams {
- favorite?: boolean;
- messages?: string[];
- sessionId: string;
- title: string;
-}
-
-export interface QueryTopicParams {
- containerId?: string | null; // sessionId or groupId
- current?: number;
- pageSize?: number;
-}
-
-class _TopicModel extends BaseModel {
- constructor() {
- super('topics', DB_TopicSchema);
- }
-
- // **************** Query *************** //
-
- async query({
- pageSize = 9999,
- current = 0,
- containerId,
- }: QueryTopicParams): Promise<ChatTopic[]> {
- const offset = current * pageSize;
-
- // get all topics
- const allTopics = containerId
- ? await this.table.where('sessionId').equals(containerId).toArray()
- : await this.table.toArray();
-
- // 将所有主题按星标消息优先,时间倒序进行排序
- const sortedTopics = allTopics.sort((a, b) => {
- if (a.favorite && !b.favorite) return -1; // a是星标,b不是,a排前面
- if (!a.favorite && b.favorite) return 1; // b是星标,a不是,b排前面
-
- // 如果星标状态相同,则按时间倒序排序
- return b.createdAt - a.createdAt;
- });
-
- // handle pageSize
- const pagedTopics = sortedTopics.slice(offset, offset + pageSize);
-
- return pagedTopics.map((i) => this.mapToChatTopic(i));
- }
-
- queryAll() {
- return this.table.orderBy('updatedAt').toArray();
- }
-
- /**
- * Query topics by keyword in title, message content, or translated content
- * @param keyword The keyword to search for
- * @param sessionId The currently activated session id.
- */
- async queryByKeyword(keyword: string, sessionId?: string): Promise<ChatTopic[]> {
- if (!keyword) return [];
-
- console.time('queryTopicsByKeyword');
- const keywordLowerCase = keyword.toLowerCase();
-
- // Find topics with matching title
- const queryTable = sessionId ? this.table.where('sessionId').equals(sessionId) : this.table;
- const matchingTopicsPromise = queryTable
- .filter((topic) => topic.title.toLowerCase().includes(keywordLowerCase))
- .toArray();
-
- // Find messages with matching content or translate.content
- const queryMessages = sessionId
- ? this.db.messages.where('sessionId').equals(sessionId)
- : this.db.messages;
- const matchingMessagesPromise = queryMessages
- .filter((message) => {
- // check content
- if (message.content.toLowerCase().includes(keywordLowerCase)) return true;
-
- // check translate content
- if (message.translate && message.translate.content) {
- return message.translate.content.toLowerCase().includes(keywordLowerCase);
- }
-
- return false;
- })
- .toArray();
-
- // Resolve both promises
- const [matchingTopics, matchingMessages] = await Promise.all([
- matchingTopicsPromise,
- matchingMessagesPromise,
- ]);
-
- // Extract topic IDs from messages
- const topicIdsFromMessages = matchingMessages.map((message) => message.topicId);
-
- // Combine topic IDs from both sources
- const combinedTopicIds = new Set([
- ...topicIdsFromMessages,
- ...matchingTopics.map((topic) => topic.id),
- ]);
-
- // Retrieve unique topics by IDs
- const uniqueTopics = await this.table
- .where('id')
- .anyOf([...combinedTopicIds])
- .toArray();
-
- console.timeEnd('queryTopicsByKeyword');
- return uniqueTopics.map((i) => ({ ...i, favorite: !!i.favorite }));
- }
-
- async findBySessionId(sessionId: string) {
- return this.table.where({ sessionId }).toArray();
- }
-
- async findById(id: string): Promise<DBModel<DB_Topic>> {
- return this.table.get(id);
- }
-
- async count() {
- return this.table.count();
- }
-
- // **************** Create *************** //
-
- async create({ title, favorite, sessionId, messages }: CreateTopicParams, id = nanoid()) {
- const topic = await this._addWithSync(
- { favorite: favorite ? 1 : 0, sessionId, title: title },
- id,
- );
-
- // add topicId to these messages
- if (messages) {
- await MessageModel.batchUpdate(messages, { topicId: topic.id });
- }
-
- return topic;
- }
-
- async batchCreate(topics: CreateTopicParams[]) {
- return this._batchAdd(topics.map((t) => ({ ...t, favorite: t.favorite ? 1 : 0 })));
- }
-
- async duplicateTopic(topicId: string, newTitle?: string) {
- return this.db.transaction('rw', [this.db.topics, this.db.messages], async () => {
- // Step 1: get DB_Topic
- const topic = await this.findById(topicId);
-
- if (!topic) {
- throw new Error(`Topic with id ${topicId} not found`);
- }
-
- // Step 3: 查询与 `topic` 关联的 `messages`
- const originalMessages = await MessageModel.queryByTopicId(topicId);
-
- const duplicateMessages = await MessageModel.duplicateMessages(originalMessages);
-
- const { id } = await this.create({
- ...this.mapToChatTopic(topic),
- messages: duplicateMessages.map((m) => m.id),
- sessionId: topic.sessionId!,
- title: newTitle || topic.title,
- });
-
- return id;
- });
- }
-
- // **************** Delete *************** //
-
- /**
- * Deletes a topic and all messages associated with it.
- */
- async delete(id: string) {
- return this.db.transaction('rw', [this.table, this.db.messages], async () => {
- // Delete all messages associated with the topic
- await MessageModel.batchDeleteByTopicId(id);
-
- await this._deleteWithSync(id);
- });
- }
-
- /**
- * Deletes multiple topic based on the sessionId.
- *
- * @param {string} sessionId - The identifier of the assistant associated with the messages.
- * @returns {Promise<void>}
- */
- async batchDeleteBySessionId(sessionId: string): Promise<void> {
- // use sessionId as the filter criteria in the query.
- const query = this.table.where('sessionId').equals(sessionId);
-
- // Retrieve a collection of message IDs that satisfy the criteria
- const topicIds = await query.primaryKeys();
-
- // Use the bulkDelete method to delete all selected messages in bulk
- return this._bulkDeleteWithSync(topicIds);
- }
- /**
- * Deletes multiple topics and all messages associated with them in a transaction.
- */
- async batchDelete(topicIds: string[]) {
- return this.db.transaction('rw', [this.table, this.db.messages], async () => {
- // Iterate over each topicId and delete related messages, then delete the topic itself
- for (const topicId of topicIds) {
- // Delete all messages associated with the topic
- await this.delete(topicId);
- }
- });
- }
-
- async clearTable() {
- return this._clearWithSync();
- }
-
- // **************** Update *************** //
- async update(id: string, data: Partial<DB_Topic>) {
- return super._updateWithSync(id, data);
- }
-
- async toggleFavorite(id: string, newState?: boolean) {
- const topic = await this.findById(id);
- if (!topic) {
- throw new Error(`Topic with id ${id} not found`);
- }
-
- // Toggle the 'favorite' status
- const nextState = typeof newState !== 'undefined' ? newState : !topic.favorite;
-
- await this.update(id, { favorite: nextState ? 1 : 0 });
-
- return nextState;
- }
-
- // **************** Helper *************** //
-
- private mapToChatTopic = (dbTopic: DBModel<DB_Topic>): ChatTopic => ({
- ...dbTopic,
- favorite: !!dbTopic.favorite,
- });
-}
-
-export const TopicModel = new _TopicModel();
diff --git a/src/database/_deprecated/models/user.ts b/src/database/_deprecated/models/user.ts
deleted file mode 100644
index fb4e5a0b538..00000000000
--- a/src/database/_deprecated/models/user.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import type { PartialDeep } from 'type-fest';
-
-import { BaseModel } from '@/database/_deprecated/core';
-import { LobeAgentConfig } from '@/types/agent';
-import { uuid } from '@/utils/uuid';
-
-import { DB_Settings, DB_User, DB_UserSchema } from '../schemas/user';
-
-class _UserModel extends BaseModel {
- constructor() {
- super('users', DB_UserSchema);
- }
- // **************** Query *************** //
-
- getUser = async (): Promise<DB_User & { id: number }> => {
- const noUser = !(await this.table.count());
-
- if (noUser) await this.table.put({ uuid: uuid() });
-
- const list = (await this.table.toArray()) as (DB_User & { id: number })[];
-
- return list[0];
- };
-
- getAgentConfig = async () => {
- const user = await this.getUser();
-
- return user.settings?.defaultAgent?.config as LobeAgentConfig;
- };
- // **************** Create *************** //
-
- create = async (user: DB_User) => {
- return this.table.put(user);
- };
-
- // **************** Delete *************** //
-
- clear() {
- return this.table.clear();
- }
-
- // **************** Update *************** //
-
- async updateSettings(settings: PartialDeep<DB_Settings>) {
- const user = await this.getUser();
-
- return this.update(user.id, { settings: settings as any });
- }
-
- async resetSettings() {
- const user = await this.getUser();
-
- return this.update(user.id, { avatar: undefined, settings: undefined });
- }
-
- async updateAvatar(avatar: string) {
- const user = await this.getUser();
-
- return this.update(user.id, { avatar });
- }
-
- // **************** Helper *************** //
-
- private update = async (id: number, value: PartialDeep<DB_User>) => {
- return this.table.update(id, value);
- };
-}
-
-export const UserModel = new _UserModel();
diff --git a/src/database/_deprecated/schemas/files.ts b/src/database/_deprecated/schemas/files.ts
deleted file mode 100644
index 487e479ac12..00000000000
--- a/src/database/_deprecated/schemas/files.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { z } from 'zod';
-
-export const DB_FileSchema = z.object({
- /**
- * create Time
- */
- createdAt: z.number().optional(),
- /**
- * file data array buffer
- */
- data: z.instanceof(ArrayBuffer).optional(),
- /**
- * file type
- * @example 'image/png'
- */
- fileType: z.string(),
- metadata: z.any().optional(),
- /**
- * file name
- * @example 'test.png'
- */
- name: z.string(),
- /**
- * the mode database save the file
- * local mean save the raw file into data
- * url mean upload the file to a cdn and then save the url
- */
- saveMode: z.enum(['local', 'url']),
- /**
- * file size
- */
- size: z.number(),
- /**
- * file url if saveMode is url
- */
- url: z.string().optional(),
-});
-
-export type DB_File = z.infer<typeof DB_FileSchema>;
diff --git a/src/database/_deprecated/schemas/message.ts b/src/database/_deprecated/schemas/message.ts
deleted file mode 100644
index 22cdf531896..00000000000
--- a/src/database/_deprecated/schemas/message.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix */
-import { z } from 'zod';
-
-const TranslateSchema = z.object({
- from: z.string().optional(),
- to: z.string(),
- content: z.string().optional(),
-});
-
-const PluginSchema = z.object({
- identifier: z.string(),
- arguments: z.string(),
- apiName: z.string(),
- type: z.enum(['default', 'markdown', 'standalone', 'builtin', 'mcp']).default('default'),
-});
-
-const ToolCallSchema = PluginSchema.extend({
- id: z.string(),
-});
-
-export const DB_MessageSchema = z.object({
- role: z.enum(['user', 'system', 'assistant', 'tool']),
- content: z.string(),
- files: z.array(z.string()).optional(),
- favorite: z.number().int().min(0).max(1).optional(),
- error: z.any().optional(),
-
- tools: z.array(ToolCallSchema).optional(),
- tool_call_id: z.string().optional(),
-
- plugin: PluginSchema.optional(),
- pluginState: z.any().optional(),
- pluginError: z.any().optional(),
-
- fromModel: z.string().optional(),
- fromProvider: z.string().optional(),
- translate: TranslateSchema.optional().or(z.literal(false)).or(z.null()),
- tts: z.any().optional(),
-
- traceId: z.string().optional(),
- observationId: z.string().optional(),
-
- // foreign keys
- parentId: z.string().optional(),
- quotaId: z.string().optional(),
- sessionId: z.string(),
- topicId: z.string().nullable().optional(),
-});
-
-export type DB_Message = z.infer<typeof DB_MessageSchema>;
diff --git a/src/database/_deprecated/schemas/plugin.ts b/src/database/_deprecated/schemas/plugin.ts
deleted file mode 100644
index 0f3dae905b5..00000000000
--- a/src/database/_deprecated/schemas/plugin.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix */
-import { z } from 'zod';
-
-export const DB_PluginSchema = z.object({
- identifier: z.string(),
- id: z.string(),
- type: z.enum(['plugin', 'customPlugin']),
- manifest: z.any().optional(),
- settings: z.any().optional(),
-});
-
-export type DB_Plugin = z.infer<typeof DB_PluginSchema>;
diff --git a/src/database/_deprecated/schemas/session.ts b/src/database/_deprecated/schemas/session.ts
deleted file mode 100644
index c389bdebd00..00000000000
--- a/src/database/_deprecated/schemas/session.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { z } from 'zod';
-
-import { DEFAULT_MODEL } from '@/const/settings';
-import { AgentChatConfigSchema } from '@/types/agent';
-import { LobeMetaDataSchema } from '@/types/meta';
-
-const fewShotsSchema = z.array(
- z.object({
- content: z.string(),
- role: z.string(),
- }),
-);
-
-const ttsSchema = z.object({
- showAllLocaleVoice: z.boolean().optional(),
- sttLocale: z.string().default('auto'),
- ttsService: z.string().default('openai'),
- voice: z
- .object({
- edge: z.string().optional(),
- microsoft: z.string().optional(),
- openai: z.string().default(''),
- })
- .optional(),
-});
-
-export const AgentSchema = z.object({
- chatConfig: AgentChatConfigSchema,
- fewShots: fewShotsSchema.optional(),
- model: z.string().default(DEFAULT_MODEL),
- openingMessage: z.string().optional(),
- openingQuestions: z.array(z.string()).default([]).optional(),
- params: z.object({
- frequency_penalty: z.number().default(0).optional(),
- max_tokens: z.number().optional(),
- presence_penalty: z.number().default(0).optional(),
- temperature: z.number().default(1).optional(),
- top_p: z.number().default(1).optional(),
- }),
- plugins: z.array(z.string()).optional(),
- provider: z.string().default('openai').optional(),
- systemRole: z.string().default(''),
- tts: ttsSchema.optional(),
-});
-
-export const DB_SessionSchema = z.object({
- config: AgentSchema,
- group: z.string().default('default'),
- meta: LobeMetaDataSchema,
- pinned: z.number().int().min(0).max(1).optional(),
- type: z.enum(['agent', 'group']).default('agent'),
-});
-
-export type DB_Session = z.infer<typeof DB_SessionSchema>;
diff --git a/src/database/_deprecated/schemas/sessionGroup.ts b/src/database/_deprecated/schemas/sessionGroup.ts
deleted file mode 100644
index 4bef20d0158..00000000000
--- a/src/database/_deprecated/schemas/sessionGroup.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { z } from 'zod';
-
-export const DB_SessionGroupSchema = z.object({
- name: z.string(),
- sort: z.number().optional(),
-});
-
-export type DB_SessionGroup = z.infer<typeof DB_SessionGroupSchema>;
diff --git a/src/database/_deprecated/schemas/topic.ts b/src/database/_deprecated/schemas/topic.ts
deleted file mode 100644
index c9601d2eabb..00000000000
--- a/src/database/_deprecated/schemas/topic.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix */
-import { z } from 'zod';
-
-export const DB_TopicSchema = z.object({
- title: z.string(),
- favorite: z.number().int().default(0),
-
- // foreign keys
- sessionId: z.string().optional(),
-});
-
-export type DB_Topic = z.infer<typeof DB_TopicSchema>;
diff --git a/src/database/_deprecated/schemas/user.ts b/src/database/_deprecated/schemas/user.ts
deleted file mode 100644
index e78458879d9..00000000000
--- a/src/database/_deprecated/schemas/user.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { z } from 'zod';
-
-import { AgentSchema } from '@/database/_deprecated/schemas/session';
-import { LobeMetaDataSchema } from '@/types/meta';
-
-const generalSechma = z.object({
- fontSize: z.number().default(14),
- language: z.string(),
- neutralColor: z.string().optional(),
- password: z.string(),
- themeMode: z.string(),
-});
-
-const settingsSchema = z.object({
- defaultAgent: z.object({
- config: AgentSchema,
- meta: LobeMetaDataSchema,
- }),
- general: generalSechma.partial().optional(),
- keyVaults: z.any().optional(),
- languageModel: z.any().optional(),
- tts: z.object({
- openAI: z.object({
- sttModel: z.string(),
- ttsModel: z.string(),
- }),
- sttAutoStop: z.boolean(),
- sttServer: z.string(),
- }),
-});
-
-export const DB_UserSchema = z.object({
- avatar: z.string().optional(),
- settings: settingsSchema.partial(),
- uuid: z.string(),
-});
-
-export type DB_User = z.infer<typeof DB_UserSchema>;
-
-export type DB_Settings = z.infer<typeof settingsSchema>;
diff --git a/src/envs/app.ts b/src/envs/app.ts
index 129a399e1d8..6b94ccb98a4 100644
--- a/src/envs/app.ts
+++ b/src/envs/app.ts
@@ -2,8 +2,6 @@
import { createEnv } from '@t3-oss/env-nextjs';
import { z } from 'zod';
-import { isServerMode } from '@/const/version';
-
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
@@ -16,12 +14,11 @@ const isInVercel = process.env.VERCEL === '1';
const vercelUrl = `https://${process.env.VERCEL_URL}`;
-const APP_URL = process.env.APP_URL ? process.env.APP_URL : isInVercel ? vercelUrl : undefined;
-
-// only throw error in server mode and server side
-if (typeof window === 'undefined' && isServerMode && !APP_URL) {
- throw new Error('`APP_URL` is required in server mode');
-}
+const APP_URL = process.env.APP_URL
+ ? process.env.APP_URL
+ : isInVercel
+ ? vercelUrl
+ : 'http://localhost:3010';
const ASSISTANT_INDEX_URL = 'https://registry.npmmirror.com/@lobehub/agents-index/v1/files/public';
diff --git a/src/features/DataImporter/_deprecated.ts b/src/features/DataImporter/_deprecated.ts
deleted file mode 100644
index 40bf1926fb5..00000000000
--- a/src/features/DataImporter/_deprecated.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { t } from 'i18next';
-
-import { notification } from '@/components/AntdStaticMethods';
-import { Migration } from '@/migrations';
-import { ConfigFile } from '@/types/exportConfig';
-
-/**
- * V2 删除该方法
- * 不再需要 Migration.migrate
- * @deprecated
- */
-export const importConfigFile = async (
- file: File,
- onConfigImport: (config: ConfigFile) => Promise<void>,
-) => {
- const text = await file.text();
-
- try {
- const config = JSON.parse(text);
-
- // it means the config file is exported from a newer version
- if ('schemaHash' in config) {
- notification.error({
- description: t('import.incompatible.description', { ns: 'error' }),
- message: t('import.incompatible.title', { ns: 'error' }),
- });
- return;
- }
-
- const { state, version } = Migration.migrate(config);
-
- await onConfigImport({ ...config, state, version });
- } catch (error) {
- console.error(error);
- notification.error({
- description: t('import.importConfigFile.description', {
- ns: 'error',
- reason: (error as any).message,
- }),
- message: t('import.importConfigFile.title', { ns: 'error' }),
- });
- }
-};
diff --git a/src/features/DataImporter/index.tsx b/src/features/DataImporter/index.tsx
index 1f207b206da..f4f2a3a3b0a 100644
--- a/src/features/DataImporter/index.tsx
+++ b/src/features/DataImporter/index.tsx
@@ -9,21 +9,32 @@ import { Center } from 'react-layout-kit';
import DataStyleModal from '@/components/DataStyleModal';
import { importService } from '@/services/import';
-import { ImportResult, ImportResults } from '@/services/import/_deprecated';
import { useChatStore } from '@/store/chat';
import { useSessionStore } from '@/store/session';
import { ImportPgDataStructure } from '@/types/export';
-import { ConfigFile } from '@/types/exportConfig';
-import { ErrorShape, FileUploadState, ImportStage, OnImportCallbacks } from '@/types/importer';
+import { ErrorShape, FileUploadState, ImportStage } from '@/types/importer';
import ImportError from './Error';
import { FileUploading } from './FileUploading';
import ImportPreviewModal from './ImportDetail';
import DataLoading from './Loading';
import SuccessResult from './SuccessResult';
-import { importConfigFile } from './_deprecated';
import { parseConfigFile } from './config';
+export interface ImportResult {
+ added: number;
+ errors: number;
+ skips: number;
+ updated?: number;
+}
+export interface ImportResults {
+ messages?: ImportResult;
+ sessionGroups?: ImportResult;
+ sessions?: ImportResult;
+ topics?: ImportResult;
+ type?: string;
+}
+
const useStyles = createStyles(({ css }) => ({
children: css`
&::before {
@@ -157,62 +168,6 @@ const DataImporter = memo<DataImporterProps>(({ children, onFinishImport }) => {
const config = await parseConfigFile(file);
if (!config) return false;
- if (!('schemaHash' in config)) {
- // TODO: remove in V2
- await importConfigFile(file, async (config) => {
- setImportState(ImportStage.Preparing);
- console.log(config);
-
- const importConfigState = async (
- config: ConfigFile,
- callbacks?: OnImportCallbacks,
- ): Promise<void> => {
- if (config.exportType === 'settings') {
- await importService.importSettings(config.state.settings);
- callbacks?.onStageChange?.(ImportStage.Success);
- return;
- }
-
- if (config.exportType === 'all') {
- await importService.importSettings(config.state.settings);
- }
-
- await importService.importData(
- {
- messages: (config.state as any).messages || [],
- sessionGroups: (config.state as any).sessionGroups || [],
- sessions: (config.state as any).sessions || [],
- topics: (config.state as any).topics || [],
- version: config.version,
- },
- callbacks,
- );
- };
-
- await importConfigState(config, {
- onError: (error) => {
- setImportError(error);
- },
- onFileUploading: (state) => {
- setUploadingState(state);
- },
- onStageChange: (stage) => {
- setImportState(stage);
- },
- onSuccess: (data, duration) => {
- if (data) setImportResults(data);
- setDuration(duration);
- },
- });
-
- await refreshSessions();
- await refreshMessages();
- await refreshTopics();
- });
-
- return false;
- }
-
setImportPgData(config);
setShowImportModal(true);
diff --git a/src/features/DevPanel/PostgresViewer/usePgTable.ts b/src/features/DevPanel/PostgresViewer/usePgTable.ts
index 5bb9472111f..ea69f0756c1 100644
--- a/src/features/DevPanel/PostgresViewer/usePgTable.ts
+++ b/src/features/DevPanel/PostgresViewer/usePgTable.ts
@@ -25,7 +25,8 @@ export const useTableColumns = (tableName?: string) => {
export const usePgTable = (tableName?: string) => {
const isDBInited = useGlobalStore(systemStatusSelectors.isDBInited);
- return useSWR(isDBInited && tableName ? FETCH_TABLE_DATA_KEY(tableName) : null, ([, table]) =>
- tableViewerService.getTableData(table),
+ return useSWR(
+ isDBInited && tableName ? FETCH_TABLE_DATA_KEY(tableName) : null,
+ ([, table]) => tableViewerService.getTableData(table) as any,
);
};
diff --git a/src/features/InitClientDB/EnableModal.tsx b/src/features/InitClientDB/EnableModal.tsx
deleted file mode 100644
index 55a9dbebf1e..00000000000
--- a/src/features/InitClientDB/EnableModal.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { Button, Icon } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { CpuIcon, LibraryBig, ShieldCheck } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import DataStyleModal from '@/components/DataStyleModal';
-import { useGlobalStore } from '@/store/global';
-import { useServerConfigStore } from '@/store/serverConfig';
-
-import PGliteIcon from './PGliteIcon';
-
-const useStyles = createStyles(({ css, token, isDarkMode, responsive }) => ({
- desc: css`
- width: 280px;
- color: ${token.colorTextSecondary};
-
- ${responsive.mobile} {
- line-height: ${token.lineHeight};
- }
- `,
- hint: css`
- font-size: ${token.fontSizeSM}px;
- color: ${token.colorTextTertiary};
- text-align: center;
- `,
- icon: css`
- color: ${isDarkMode ? token.blue : token.geekblue};
- `,
- iconCtn: css`
- width: 72px;
- height: 72px;
- border-radius: 50%;
- background: ${isDarkMode ? token.blue1 : token.geekblue1};
- `,
- intro: css`
- ${responsive.mobile} {
- width: 350px;
- margin-block-start: 24px;
- line-height: ${token.lineHeight};
- }
- `,
-
- title: css`
- margin-block-end: 0;
- font-size: ${token.fontSizeLG}px;
- font-weight: bold;
- `,
-}));
-
-interface EnableClientDBModalProps {
- open: boolean;
-}
-
-const EnableClientDBModal = memo<EnableClientDBModalProps>(({ open }) => {
- const { t } = useTranslation('common');
- const { styles } = useStyles();
- const isMobile = useServerConfigStore((s) => s.isMobile);
-
- const markPgliteEnabled = useGlobalStore((s) => s.markPgliteEnabled);
- const features = [
- {
- avatar: PGliteIcon,
- desc: t('clientDB.modal.features.pglite.desc'),
- title: t('clientDB.modal.features.pglite.title'),
- },
- {
- avatar: ShieldCheck,
- desc: t('clientDB.modal.features.localFirst.desc'),
- title: t('clientDB.modal.features.localFirst.title'),
- },
- {
- avatar: LibraryBig,
- desc: t('clientDB.modal.features.knowledgeBase.desc'),
- title: t('clientDB.modal.features.knowledgeBase.title'),
- },
- ];
-
- return (
- <DataStyleModal
- height={isMobile ? '80vh' : undefined}
- icon={CpuIcon}
- open={open}
- title={t('clientDB.modal.title')}
- >
- <Center gap={48}>
- <Flexbox>
- <Flexbox className={styles.intro} style={{ textAlign: 'center' }} width={460}>
- {t('clientDB.modal.desc')}
- </Flexbox>
- </Flexbox>
- <Flexbox gap={32}>
- {features.map((item) => (
- <Flexbox align={'flex-start'} gap={24} horizontal key={item.title}>
- <Center className={styles.iconCtn}>
- <Icon className={styles.icon} icon={item.avatar} size={36} />
- </Center>
- <Flexbox gap={8}>
- <p className={styles.title}>{item.title}</p>
- <p className={styles.desc}>{item.desc}</p>
- </Flexbox>
- </Flexbox>
- ))}
- </Flexbox>
- <Flexbox align={'center'} gap={16} style={{ paddingBottom: 16 }}>
- <Flexbox gap={16} horizontal justify={'center'} style={{ flexWrap: 'wrap' }}>
- <Button onClick={markPgliteEnabled} size={'large'} type={'primary'}>
- {t('clientDB.modal.enable')}
- </Button>
- </Flexbox>
- </Flexbox>
- </Center>
- </DataStyleModal>
- );
-});
-
-export default EnableClientDBModal;
diff --git a/src/features/InitClientDB/ErrorResult.tsx b/src/features/InitClientDB/ErrorResult.tsx
deleted file mode 100644
index 0fb7d996d54..00000000000
--- a/src/features/InitClientDB/ErrorResult.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import { Alert, Button, Highlighter, Icon, Modal } from '@lobehub/ui';
-import { Spin } from 'antd';
-import { createStyles } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { PenToolIcon, TriangleAlert } from 'lucide-react';
-import dynamic from 'next/dynamic';
-import { ReactNode, memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import { githubService } from '@/services/github';
-import { useGlobalStore } from '@/store/global';
-
-const DatabaseRepair = dynamic(() => import('./features/DatabaseRepair'), {
- loading: () => <Spin fullscreen />,
- ssr: false,
-});
-
-const useStyles = createStyles(({ css, token }) => ({
- bg: css`
- cursor: pointer;
-
- padding-block: 8px;
- padding-inline: 24px;
- border-radius: 40px;
-
- background: ${token.red6};
-
- transition: transform 0.2s;
-
- :hover {
- transform: scale(1.05);
- }
-
- :active {
- transform: scale(1);
- }
- `,
- text: css`
- font-size: 15px;
- color: ${token.colorText};
- `,
-}));
-
-interface MigrationError {
- message: string;
- stack: string;
-}
-
-interface FailedModalProps {
- children?: (props: { setOpen: (open: boolean) => void }) => ReactNode;
- error?: MigrationError;
-}
-
-const ErrorResult = memo<FailedModalProps>(({ children }) => {
- const { t } = useTranslation('common');
- const { styles } = useStyles();
- const initializeClientDB = useGlobalStore((s) => s.initializeClientDB);
- const error = useGlobalStore((s) => s.initClientDBError, isEqual);
- const [open, setOpen] = useState(false);
- const [showRepair, setShowRepair] = useState(true);
-
- return (
- <>
- {children ? (
- children({ setOpen })
- ) : (
- <Flexbox
- align={'center'}
- className={styles.bg}
- gap={12}
- horizontal
- onClick={() => {
- setOpen(true);
- }}
- >
- <Center height={40} width={24}>
- <Icon icon={TriangleAlert} size={20} />
- </Center>
- <span className={styles.text}>{t('clientDB.initing.error')}</span>
- </Flexbox>
- )}
- <Modal
- footer={null}
- onCancel={() => {
- setOpen(false);
- }}
- open={open}
- title={t('clientDB.error.title')}
- >
- {showRepair ? (
- <DatabaseRepair setShowRepair={setShowRepair} />
- ) : (
- <Center gap={24}>
- <div>{t('clientDB.error.desc')}</div>
- <Flexbox width={'100%'}>
- <Alert
- description={`[${error?.name}] ${error?.message}`}
- extra={
- <Flexbox gap={8} style={{ marginTop: 8, overflow: 'scroll' }} width={'100%'}>
- <Highlighter actionIconSize={'small'} language={'json'}>
- {JSON.stringify(error, null, 2)}
- </Highlighter>
- </Flexbox>
- }
- message={t('clientDB.error.detailTitle')}
- type={'error'}
- />
- </Flexbox>
-
- <Flexbox horizontal justify={'space-between'}>
- <Button
- onClick={(e) => {
- e.preventDefault();
- githubService.submitPgliteInitError(error);
- }}
- target={'_blank'}
- type={'text'}
- >
- {t('clientDB.error.report')}
- </Button>
- <Flexbox gap={8} horizontal>
- <Button
- icon={<Icon icon={PenToolIcon} />}
- onClick={() => {
- setShowRepair(true);
- }}
- >
- {t('clientDB.error.selfSolve')}
- </Button>
- <Button onClick={() => initializeClientDB()} type={'primary'}>
- {t('clientDB.error.retry')}
- </Button>
- </Flexbox>
- </Flexbox>
- </Center>
- )}
- </Modal>
- </>
- );
-});
-
-export default ErrorResult;
diff --git a/src/features/InitClientDB/InitIndicator.tsx b/src/features/InitClientDB/InitIndicator.tsx
deleted file mode 100644
index 40dca670663..00000000000
--- a/src/features/InitClientDB/InitIndicator.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-'use client';
-
-import { Progress } from 'antd';
-import { createStyles } from 'antd-style';
-import { AnimatePresence, motion } from 'framer-motion';
-import { rgba } from 'polished';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import { useGlobalStore } from '@/store/global';
-import { ClientDatabaseInitStages, DatabaseLoadingState } from '@/types/clientDB';
-
-import ErrorResult from './ErrorResult';
-
-const useStyles = createStyles(({ css, token, prefixCls }) => ({
- bg: css`
- padding-block: 8px;
- padding-inline: 8px 32px;
- border-radius: 40px;
- background: ${token.colorText};
- `,
- container: css`
- position: fixed;
- z-index: 1000;
- `,
- progress: css`
- .${prefixCls}-progress-text {
- font-size: 12px;
- color: ${token.colorBgContainer} !important;
- }
- `,
- progressReady: css`
- .${prefixCls}-progress-text {
- color: ${token.colorSuccessBorder} !important;
- }
- `,
-
- text: css`
- font-size: 15px;
- color: ${token.colorBgContainer};
- `,
-}));
-
-interface InitClientDBProps {
- bottom?: number;
- show: boolean;
-}
-
-const InitClientDB = memo<InitClientDBProps>(({ bottom = 80, show }) => {
- const { styles, theme, cx } = useStyles();
- const currentStage = useGlobalStore((s) => s.initClientDBStage || DatabaseLoadingState.Idle);
- const { t } = useTranslation('common');
- const useInitClientDB = useGlobalStore((s) => s.useInitClientDB);
-
- useInitClientDB();
-
- const getStateMessage = (state: DatabaseLoadingState) => {
- switch (state) {
- case DatabaseLoadingState.Finished:
- case DatabaseLoadingState.Ready: {
- return t('clientDB.initing.ready');
- }
-
- case DatabaseLoadingState.Idle: {
- return t('clientDB.initing.idle');
- }
- case DatabaseLoadingState.Initializing: {
- return t('clientDB.initing.initializing');
- }
- case DatabaseLoadingState.LoadingDependencies: {
- return t('clientDB.initing.loadingDependencies');
- }
-
- case DatabaseLoadingState.LoadingWasm: {
- return t('clientDB.initing.loadingWasmModule');
- }
-
- case DatabaseLoadingState.Migrating: {
- return t('clientDB.initing.migrating');
- }
- }
- };
-
- const currentStageIndex = ClientDatabaseInitStages.indexOf(currentStage);
- const isReady = currentStage === DatabaseLoadingState.Finished;
- const isError = currentStage === DatabaseLoadingState.Error;
- return (
- <AnimatePresence>
- {show && (
- <Center className={styles.container} style={{ bottom }} width={'100%'}>
- <motion.div
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: 30 }}
- initial={{ opacity: 0, y: 30 }}
- transition={{ duration: 0.3 }}
- >
- {isError ? (
- <ErrorResult />
- ) : (
- <Flexbox align={'center'} className={styles.bg} gap={12} horizontal>
- <Progress
- className={cx(styles.progress, isReady && styles.progressReady)}
- format={isReady ? undefined : (percent) => percent}
- percent={parseInt(
- ((currentStageIndex / (ClientDatabaseInitStages.length - 1)) * 100).toFixed(0),
- )}
- size={40}
- strokeColor={isReady ? theme.colorSuccessActive : theme.colorBgContainer}
- strokeLinecap={'round'}
- strokeWidth={10}
- trailColor={rgba(theme.colorBgContainer, 0.1)}
- type={'circle'}
- />
- <span className={styles.text}>{getStateMessage(currentStage)}</span>
- </Flexbox>
- )}
- </motion.div>
- </Center>
- )}
- </AnimatePresence>
- );
-});
-export default InitClientDB;
diff --git a/src/features/InitClientDB/PGliteIcon.tsx b/src/features/InitClientDB/PGliteIcon.tsx
deleted file mode 100644
index 789797a70f7..00000000000
--- a/src/features/InitClientDB/PGliteIcon.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-'use client';
-
-import type { IconType } from '@lobehub/icons';
-import { forwardRef } from 'react';
-
-const PGliteIcon: IconType = forwardRef(({ size = '1em', style }, ref) => {
- return (
- <svg
- fill="currentColor"
- fillRule="evenodd"
- height={size}
- ref={ref}
- style={{ flex: 'none', lineHeight: 1, ...style }}
- viewBox="0 0 1024 1024"
- width={size}
- xmlns="http://www.w3.org/2000/svg"
- >
- <title>PGlite</title>
- <path
- clipRule="evenodd"
- d="M941.581 335.737v460.806c0 15.926-12.913 28.836-28.832 28.818l-115.283-.137c-15.243-.018-27.706-11.88-28.703-26.877.011-.569.018-1.138.018-1.711l-.004-172.904c0-47.745-38.736-86.451-86.454-86.451-46.245 0-84.052-36.359-86.342-82.068V191.496l201.708.149c79.484.058 143.892 64.553 143.892 144.092zm-576-144.281v201.818c0 47.746 38.682 86.456 86.4 86.456h86.4v-5.796c0 66.816 54.13 120.98 120.902 120.98 28.617 0 51.815 23.213 51.815 51.848v149.644c0 .688.011 1.372.025 2.057-.943 15.065-13.453 26.992-28.746 26.992l-144.982-.007.986-201.586c.079-15.915-12.755-28.88-28.66-28.959-15.904-.079-28.861 12.763-28.94 28.678l-.986 201.741v.118l-172.174-.01V623.722c0-15.915-12.895-28.819-28.8-28.819-15.906 0-28.8 12.904-28.8 28.819v201.704l-143.642-.007c-15.905-.004-28.798-12.904-28.798-28.819V335.547c0-79.58 64.471-144.093 144.001-144.092l143.999.001zm446.544 173.693c0-23.874-19.343-43.228-43.2-43.228-23.861 0-43.2 19.354-43.2 43.228 0 23.875 19.339 43.226 43.2 43.226 23.857 0 43.2-19.351 43.2-43.226z"
- fillRule="evenodd"
- />
- </svg>
- );
-});
-
-export default PGliteIcon;
diff --git a/src/features/InitClientDB/features/DatabaseRepair/Backup.tsx b/src/features/InitClientDB/features/DatabaseRepair/Backup.tsx
deleted file mode 100644
index 856ecec7514..00000000000
--- a/src/features/InitClientDB/features/DatabaseRepair/Backup.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { Alert, Button, Text } from '@lobehub/ui';
-import { App, Card } from 'antd';
-import { createStyles } from 'antd-style';
-import { AlertCircle } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { resetClientDatabase } from '@/database/client/db';
-
-const useStyles = createStyles(({ css, token }) => ({
- card: css`
- border-radius: ${token.borderRadiusLG}px;
- `,
-}));
-
-const Backup = () => {
- const { t } = useTranslation('common');
- const { styles } = useStyles();
-
- const { modal } = App.useApp();
- return (
- <Flexbox gap={24}>
- <Card
- className={styles.card}
- extra={<Text type="secondary">{t('clientDB.solve.backup.desc')}</Text>}
- title={t('clientDB.solve.backup.title')}
- >
- <Text as={'p'}>{t('clientDB.solve.backup.exportDesc')}</Text>
- <Button block type={'primary'}>
- {t('clientDB.solve.backup.export')}
- </Button>
- </Card>
-
- <Card
- className={styles.card}
- extra={<Text type="secondary">{t('clientDB.solve.backup.reset.desc')}</Text>}
- title={t('clientDB.solve.backup.reset.title')}
- >
- <Flexbox gap={24}>
- <Alert
- description={t('clientDB.solve.backup.reset.alertDesc')}
- icon={<AlertCircle size={16} />}
- message={t('clientDB.solve.backup.reset.alert')}
- showIcon
- type="error"
- variant={'borderless'}
- />
-
- <Button
- block
- danger
- onClick={() => {
- modal.confirm({
- content: t('clientDB.solve.backup.reset.confirm.desc'),
- okButtonProps: {
- danger: true,
- },
- onOk: async () => {
- await resetClientDatabase();
-
- location.reload();
- },
- title: t('clientDB.solve.backup.reset.confirm.title'),
- });
- }}
- >
- {t('clientDB.solve.backup.reset.button')}
- </Button>
- </Flexbox>
- </Card>
- </Flexbox>
- );
-};
-
-export default Backup;
diff --git a/src/features/InitClientDB/features/DatabaseRepair/Diagnosis.tsx b/src/features/InitClientDB/features/DatabaseRepair/Diagnosis.tsx
deleted file mode 100644
index e43e362dbed..00000000000
--- a/src/features/InitClientDB/features/DatabaseRepair/Diagnosis.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import { Highlighter, Tag } from '@lobehub/ui';
-import { Card, List, Popover } from 'antd';
-import { createStyles } from 'antd-style';
-import dayjs from 'dayjs';
-import isEqual from 'fast-deep-equal';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useGlobalStore } from '@/store/global';
-import { clientDBSelectors } from '@/store/global/selectors';
-
-const useStyles = createStyles(({ css, token }) => ({
- card: css`
- margin-block-end: ${token.marginMD}px;
- border-radius: ${token.borderRadiusLG}px;
- `,
- hash: css`
- font-family: ${token.fontFamilyCode};
- `,
- sql: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 3;
-
- font-size: 12px;
- `,
- time: css`
- font-size: 12px;
- color: ${token.colorTextTertiary};
- `,
-}));
-
-const Diagnosis = () => {
- const { t } = useTranslation('common');
- const { styles, cx } = useStyles();
-
- const migrations = useGlobalStore(clientDBSelectors.displayMigrationStatus, isEqual);
-
- return (
- <Card
- className={styles.card}
- styles={{ body: { padding: 0 } }}
- title={t('clientDB.solve.diagnosis.title')}
- >
- <List
- dataSource={migrations}
- renderItem={(migration) => (
- <List.Item
- key={migration.id}
- style={{ display: 'flex', gap: 12, justifyContent: 'space-between' }}
- >
- <Flexbox gap={4} horizontal>
- <Flexbox style={{ minWidth: 20 }} width={20}>
- {migration.index}
- </Flexbox>
- <Popover
- content={
- <Flexbox gap={8}>
- <div className={styles.hash}>Hash: {migration.id}</div>
- <Highlighter
- language={'sql'}
- style={{ maxHeight: '30vh', maxWidth: '70vw', overflow: 'scroll' }}
- >
- {migration.sql.join('\n')}
- </Highlighter>
- </Flexbox>
- }
- title={t('clientDB.solve.diagnosis.sql')}
- >
- <Flexbox gap={8}>
- <Flexbox
- className={cx(styles.sql, migration.status === 'success' && styles.time)}
- >
- {migration.desc}
- </Flexbox>
- <Flexbox>
- <Flexbox className={styles.time}>
- {t('clientDB.solve.diagnosis.createdAt')}
- {dayjs(migration.createdAt).format('YYYY-MM-DD hh:mm:ss')} ·{' '}
- {t('clientDB.solve.diagnosis.migratedAt')}{' '}
- {dayjs(migration.migratedAt).format('YYYY-MM-DD hh:mm:ss')}
- </Flexbox>
- </Flexbox>
- </Flexbox>
- </Popover>
- </Flexbox>
- <Tag bordered={false} color={migration.status}>
- {migration.status}
- </Tag>
- </List.Item>
- )}
- size="small"
- />
- </Card>
- );
-};
-export default Diagnosis;
diff --git a/src/features/InitClientDB/features/DatabaseRepair/Repair.tsx b/src/features/InitClientDB/features/DatabaseRepair/Repair.tsx
deleted file mode 100644
index 41e012ecb16..00000000000
--- a/src/features/InitClientDB/features/DatabaseRepair/Repair.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-'use client';
-
-import { Alert, Button, CodeEditor, Icon, Text } from '@lobehub/ui';
-import { Card, List } from 'antd';
-import { createStyles } from 'antd-style';
-import dayjs from 'dayjs';
-import isEqual from 'fast-deep-equal';
-import { AlertCircle, CheckCircle, Play } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { clientDB, updateMigrationRecord } from '@/database/client/db';
-import { useGlobalStore } from '@/store/global';
-import { clientDBSelectors } from '@/store/global/selectors';
-
-// 使用 antd-style 创建样式
-const useStyles = createStyles(({ css, token }) => ({
- actionBar: css`
- display: flex;
- justify-content: flex-end;
- margin-block-start: ${token.marginSM}px;
- `,
- card: css`
- margin-block-end: ${token.marginMD}px;
- border-radius: ${token.borderRadiusLG}px;
- `,
- codeBlock: css`
- overflow-x: auto;
-
- margin-block: ${token.marginSM}px;
- margin-inline: 0;
- padding: ${token.paddingSM}px;
- border-radius: ${token.borderRadiusSM}px;
-
- font-family: ${token.fontFamilyCode};
- font-size: 12px;
-
- background: ${token.colorBgTextHover};
- `,
- container: css`
- overflow-y: auto;
- padding: 0;
- `,
- header: css`
- display: flex;
- align-items: center;
- margin-block-end: ${token.marginMD}px;
- `,
- migrationItem: css`
- display: flex;
- align-items: center;
- justify-content: space-between;
-
- padding-block: ${token.paddingSM}px;
- padding-inline: 0;
- border-block-end: none;
- `,
- spotlight: css`
- margin-block-end: ${token.marginLG}px;
- `,
-
- templateCard: css`
- margin-block-end: ${token.marginSM}px;
- `,
-}));
-
-interface QueryResult {
- message: string;
- success: boolean;
-}
-const Repair = memo(() => {
- const { t } = useTranslation('common');
-
- const { styles } = useStyles();
- const [sqlQuery, setSqlQuery] = useState('');
- const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
- const [showSQLHash, setShowSQLHash] = useState('');
-
- const errorMigrations = useGlobalStore(clientDBSelectors.errorMigrations, isEqual);
-
- const handleExecuteSQL = async () => {
- try {
- // 移除 BEGIN 和 COMMIT
- let processedSQL = sqlQuery.replaceAll(/BEGIN;|COMMIT;/g, '');
-
- // 分割 SQL 语句(使用 statement-breakpoint 作为分隔符)
- const migrationQueries = processedSQL.split('--> statement-breakpoint');
-
- // 手动管理事务
- await clientDB.execute('BEGIN;');
-
- try {
- for (const query of migrationQueries) {
- if (query.trim()) {
- await clientDB.execute(query);
- }
- }
- await clientDB.execute('COMMIT;');
-
- setQueryResult({
- message: `SQL executed successfully.`,
- success: true,
- });
- } catch (error) {
- await clientDB.execute('ROLLBACK;');
-
- throw error;
- }
- } catch (error) {
- setQueryResult({ message: (error as Error).message, success: false });
- }
- };
-
- return (
- <div>
- <Card
- className={styles.card}
- extra={<Text type="secondary">{t('clientDB.solve.repair.desc')}</Text>}
- title={t('clientDB.solve.repair.title')}
- variant={'borderless'}
- >
- <List
- dataSource={errorMigrations}
- renderItem={(migration) => (
- <>
- <List.Item
- actions={[
- <Button
- icon={<Icon icon={Play} />}
- key="retry"
- onClick={() => {
- setShowSQLHash(!!showSQLHash ? '' : migration.hash);
- setSqlQuery(migration.sql.join('--> statement-breakpoint\n'));
- }}
- >
- {t('clientDB.solve.repair.runSQL')}
- </Button>,
- ]}
- className={styles.migrationItem}
- key={migration.hash}
- >
- <List.Item.Meta
- description={
- <Flexbox>
- {t('clientDB.solve.diagnosis.createdAt')}
- {dayjs(migration.folderMillis).format('YYYY-MM-DD hh:mm:ss')} ·
- </Flexbox>
- }
- title={migration.sql[0]}
- />
- </List.Item>
- {showSQLHash === migration.hash && (
- <Card
- className={styles.card}
- extra={<Text type="secondary">{t('clientDB.solve.repair.sql.desc')}</Text>}
- title={t('clientDB.solve.repair.sql.title')}
- >
- <Flexbox gap={16}>
- <CodeEditor
- language={'sql'}
- onValueChange={(e) => setSqlQuery(e)}
- placeholder={t('clientDB.solve.repair.sql.placeholder')}
- style={{ fontFamily: 'monospace', height: 300 }}
- value={sqlQuery}
- />
- <Flexbox horizontal style={{ justifyContent: 'space-between' }}>
- <Button onClick={() => setSqlQuery('')}>
- {t('clientDB.solve.repair.sql.clear')}
- </Button>
- <Button disabled={!sqlQuery.trim()} onClick={handleExecuteSQL} type="primary">
- {t('clientDB.solve.repair.sql.run')}
- </Button>
- </Flexbox>
-
- {queryResult && (
- <Alert
- action={
- queryResult.success && (
- <Button
- key="complete"
- onClick={() => updateMigrationRecord(migration.hash)}
- size={'small'}
- type="primary"
- >
- {t('clientDB.solve.repair.sql.markFinished')}
- </Button>
- )
- }
- description={
- <pre style={{ marginTop: '8px', whiteSpace: 'pre-wrap' }}>
- {queryResult.message}
- </pre>
- }
- icon={
- queryResult.success ? (
- <AlertCircle size={16} />
- ) : (
- <CheckCircle size={16} />
- )
- }
- message={t('clientDB.solve.repair.sql.result')}
- showIcon
- type={queryResult.success ? 'success' : 'error'}
- />
- )}
- </Flexbox>
- </Card>
- )}
- </>
- )}
- />
- </Card>
- </div>
- );
-});
-
-export default Repair;
diff --git a/src/features/InitClientDB/features/DatabaseRepair/index.tsx b/src/features/InitClientDB/features/DatabaseRepair/index.tsx
deleted file mode 100644
index 545d207db2f..00000000000
--- a/src/features/InitClientDB/features/DatabaseRepair/index.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-'use client';
-
-import { Button, Segmented } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { AlertCircle, ArrowLeft, PenToolIcon as Tool } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import Backup from './Backup';
-import Diagnosis from './Diagnosis';
-import Repair from './Repair';
-
-const useStyles = createStyles(({ css, token }) => ({
- backButton: css`
- margin-inline-end: ${token.marginSM}px;
- padding-block: 4px;
- padding-inline: 8px;
- `,
-}));
-
-enum DatabaseRepairTab {
- Backup = 'backup',
- Diagnosis = 'diagnosis',
- Repair = 'repair',
-}
-
-interface DatabaseRepairProps {
- setShowRepair: (value: boolean) => void;
-}
-
-const DatabaseRepair = memo<DatabaseRepairProps>(({ setShowRepair }) => {
- const { t } = useTranslation('common');
- const { styles } = useStyles();
- const [activeTab, setActiveTab] = useState<DatabaseRepairTab>(DatabaseRepairTab.Diagnosis);
-
- return (
- <Flexbox gap={12}>
- <Flexbox horizontal justify={'space-between'}>
- <Button
- className={styles.backButton}
- icon={<ArrowLeft size={16} />}
- onClick={() => setShowRepair(false)}
- type="text"
- >
- {t('back')}
- </Button>
- <Segmented
- onChange={(v) => setActiveTab(v as DatabaseRepairTab)}
- options={[
- {
- label: (
- <Flexbox align={'center'} horizontal>
- <AlertCircle size={16} style={{ marginRight: 8 }} />
- {t('clientDB.solve.tabs.diagnosis')}
- </Flexbox>
- ),
- value: 'diagnosis',
- },
- {
- label: (
- <Flexbox align={'center'} horizontal>
- <Tool size={16} style={{ marginRight: 8 }} />
- {t('clientDB.solve.tabs.repair')}
- </Flexbox>
- ),
- value: 'repair',
- },
- // {
- // label: (
- // <Flexbox align={'center'} horizontal>
- // <Shield size={16} style={{ marginRight: 8 }} />
- // {t('clientDB.solve.tabs.backup')}
- // </Flexbox>
- // ),
- // value: 'backup',
- // },
- ]}
- value={activeTab}
- />
- <Flexbox width={36} />
- </Flexbox>
-
- {activeTab === DatabaseRepairTab.Diagnosis && <Diagnosis />}
- {activeTab === DatabaseRepairTab.Repair && <Repair />}
- {activeTab === DatabaseRepairTab.Backup && <Backup />}
- </Flexbox>
- );
-});
-
-export default DatabaseRepair;
diff --git a/src/features/InitClientDB/index.tsx b/src/features/InitClientDB/index.tsx
deleted file mode 100644
index 19064e475cf..00000000000
--- a/src/features/InitClientDB/index.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-'use client';
-
-import { Spin } from 'antd';
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-const Modal = dynamic(() => import('./EnableModal'), {
- loading: () => <Spin fullscreen />,
- ssr: false,
-});
-
-const InitIndicator = dynamic(() => import('./InitIndicator'), {
- ssr: false,
-});
-
-interface InitClientDBProps {
- bottom?: number;
-}
-
-const InitClientDB = memo<InitClientDBProps>(({ bottom }) => {
- const isPgliteNotEnabled = useGlobalStore(systemStatusSelectors.isPgliteNotEnabled);
- const isPgliteNotInited = useGlobalStore(systemStatusSelectors.isPgliteNotInited);
-
- return (
- <>
- {/* 当用户没有设置启用 pglite 时,强弹窗引导用户来开启弹窗 */}
- {isPgliteNotEnabled && <Modal open={isPgliteNotEnabled} />}
- {/* 当用户已经启用 pglite 但没有初始化时,展示初始化指示器 */}
- {isPgliteNotInited && <InitIndicator bottom={bottom} show={isPgliteNotInited} />}
- </>
- );
-});
-
-export default InitClientDB;
diff --git a/src/hooks/useInterceptingRoutes.test.ts b/src/hooks/useInterceptingRoutes.test.ts
index 3c6e2a547df..33462918fb7 100644
--- a/src/hooks/useInterceptingRoutes.test.ts
+++ b/src/hooks/useInterceptingRoutes.test.ts
@@ -10,21 +10,27 @@ import { useSessionStore } from '@/store/session';
import { useOpenChatSettings } from './useInterceptingRoutes';
// Mocks
+const mockPush = vi.fn((href) => href);
vi.mock('next/navigation', () => ({
useRouter: vi.fn(() => ({
- push: vi.fn((href) => href),
+ push: mockPush,
replace: vi.fn((href) => href),
})),
}));
vi.mock('nextjs-toploader/app', () => ({
useRouter: vi.fn(() => ({
- push: vi.fn((href) => href),
+ push: mockPush,
replace: vi.fn((href) => href),
})),
}));
vi.mock('@/hooks/useQuery', () => ({
useQuery: vi.fn(() => ({})),
}));
+vi.mock('@/hooks/useQueryRoute', () => ({
+ useQueryRoute: vi.fn(() => ({
+ push: mockPush,
+ })),
+}));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
@@ -36,20 +42,32 @@ vi.mock('@/store/global', () => ({
setState: vi.fn(),
},
}));
+let isDeprecatedEdition = false;
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/const/version')>();
+ return {
+ ...actual,
+ get isDeprecatedEdition() {
+ return isDeprecatedEdition;
+ },
+ };
+});
describe('useOpenChatSettings', () => {
it('should handle inbox session id correctly', () => {
+ isDeprecatedEdition = true;
vi.mocked(useSessionStore).mockReturnValue(INBOX_SESSION_ID);
const { result } = renderHook(() => useOpenChatSettings());
expect(result.current()).toBe('/settings?active=agent'); // Assuming openSettings returns a function
+ isDeprecatedEdition = false;
});
it('should handle mobile route for chat settings', () => {
vi.mocked(useSessionStore).mockReturnValue('123');
vi.mocked(useIsMobile).mockReturnValue(true);
const { result } = renderHook(() => useOpenChatSettings(ChatSettingsTabs.Meta));
- expect(result.current()).toBe('/chat/settings?session=123');
+ expect(result.current()).toBe('/chat/settings');
});
it('should handle desktop route for chat settings with session and tab', () => {
diff --git a/src/libs/trpc/client/edge.ts b/src/libs/trpc/client/edge.ts
deleted file mode 100644
index d5ba2050c1e..00000000000
--- a/src/libs/trpc/client/edge.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { createTRPCClient, httpBatchLink } from '@trpc/client';
-import superjson from 'superjson';
-
-import { isDesktop } from '@/const/version';
-import type { EdgeRouter } from '@/server/routers/edge';
-import { fetchWithDesktopRemoteRPC } from '@/utils/electron/desktopRemoteRPCFetch';
-
-export const edgeClient = createTRPCClient<EdgeRouter>({
- links: [
- httpBatchLink({
- fetch: isDesktop
- ? // eslint-disable-next-line no-undef
- (input, init) => fetchWithDesktopRemoteRPC(input as string, init as RequestInit)
- : undefined,
- headers: async () => {
- // dynamic import to avoid circular dependency
- const { createHeaderWithAuth } = await import('@/services/_auth');
-
- return createHeaderWithAuth();
- },
- maxURLLength: 2083,
- transformer: superjson,
- url: '/trpc/edge',
- }),
- ],
-});
diff --git a/src/libs/trpc/client/index.ts b/src/libs/trpc/client/index.ts
index 7beca2d0739..6ca55647f74 100644
--- a/src/libs/trpc/client/index.ts
+++ b/src/libs/trpc/client/index.ts
@@ -1,5 +1,4 @@
export { asyncClient } from './async';
export * from './desktop';
-export { edgeClient } from './edge';
export * from './lambda';
export * from './tools';
diff --git a/src/libs/trpc/client/lambda.ts b/src/libs/trpc/client/lambda.ts
index 18c80aceea4..f63d0877773 100644
--- a/src/libs/trpc/client/lambda.ts
+++ b/src/libs/trpc/client/lambda.ts
@@ -22,10 +22,12 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
complete: () => observer.complete(),
error: async (err) => {
// Check if this is an abort error and should be ignored
- const isAbortError = err.message.includes('aborted') || err.name === 'AbortError' ||
- err.cause?.name === 'AbortError' ||
- err.message.includes('signal is aborted without reason');
-
+ const isAbortError =
+ err.message.includes('aborted') ||
+ err.name === 'AbortError' ||
+ err.cause?.name === 'AbortError' ||
+ err.message.includes('signal is aborted without reason');
+
const showError = (op.context?.showNotification as boolean) ?? true;
const status = err.data?.httpStatus as number;
@@ -50,7 +52,8 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
}
default: {
- fetchErrorNotification.error({ errorMessage: err.message, status });
+ if (fetchErrorNotification)
+ fetchErrorNotification.error({ errorMessage: err.message, status });
}
}
}
diff --git a/src/libs/trpc/edge/context.ts b/src/libs/trpc/edge/context.ts
deleted file mode 100644
index af7570d39b7..00000000000
--- a/src/libs/trpc/edge/context.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { ClientSecretPayload } from '@lobechat/types';
-import { User } from 'next-auth';
-import { NextRequest } from 'next/server';
-
-import { LOBE_CHAT_AUTH_HEADER, enableClerk, enableNextAuth } from '@/const/auth';
-import { ClerkAuth, IClerkAuth } from '@/libs/clerk-auth';
-
-export interface AuthContext {
- authorizationHeader?: string | null;
- clerkAuth?: IClerkAuth;
- jwtPayload?: ClientSecretPayload | null;
- nextAuth?: User;
- userId?: string | null;
-}
-
-/**
- * Inner function for `createContext` where we create the context.
- * This is useful for testing when we don't want to mock Next.js' request/response
- */
-export const createContextInner = async (params?: {
- authorizationHeader?: string | null;
- clerkAuth?: IClerkAuth;
- nextAuth?: User;
- userId?: string | null;
-}): Promise<AuthContext> => ({
- authorizationHeader: params?.authorizationHeader,
- clerkAuth: params?.clerkAuth,
- nextAuth: params?.nextAuth,
- userId: params?.userId,
-});
-
-export type EdgeContext = Awaited<ReturnType<typeof createContextInner>>;
-
-/**
- * Creates context for an incoming request
- * @link https://trpc.io/docs/v11/context
- */
-export const createEdgeContext = async (request: NextRequest): Promise<EdgeContext> => {
- // for API-response caching see https://trpc.io/docs/v11/caching
-
- const authorization = request.headers.get(LOBE_CHAT_AUTH_HEADER);
-
- let userId;
- let auth;
-
- if (enableClerk) {
- const clerkAuth = new ClerkAuth();
- const result = clerkAuth.getAuthFromRequest(request);
- auth = result.clerkAuth;
- userId = result.userId;
-
- return createContextInner({ authorizationHeader: authorization, clerkAuth: auth, userId });
- }
-
- if (enableNextAuth) {
- try {
- const { default: NextAuth } = await import('@/libs/next-auth');
-
- const session = await NextAuth.auth();
- if (session && session?.user?.id) {
- auth = session.user;
- userId = session.user.id;
- }
- return createContextInner({ authorizationHeader: authorization, nextAuth: auth, userId });
- } catch (e) {
- console.error('next auth err', e);
- }
- }
-
- return createContextInner({ authorizationHeader: authorization, userId });
-};
diff --git a/src/libs/trpc/edge/index.ts b/src/libs/trpc/edge/index.ts
deleted file mode 100644
index 9a66d69d42f..00000000000
--- a/src/libs/trpc/edge/index.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * This is your entry point to setup the root configuration for tRPC on the server.
- * - `initTRPC` should only be used once per app.
- * - We export only the functionality that we use so we can enforce which base procedures should be used
- *
- * Learn how to create protected base procedures and other things below:
- * @link https://trpc.io/docs/v11/router
- * @link https://trpc.io/docs/v11/procedures
- */
-import { DESKTOP_USER_ID } from '@/const/desktop';
-import { isDesktop } from '@/const/version';
-
-import { edgeTrpc } from './init';
-import { jwtPayloadChecker } from './middleware/jwtPayload';
-
-/**
- * Create a router
- * @link https://trpc.io/docs/v11/router
- */
-export const router = edgeTrpc.router;
-
-/**
- * Create an unprotected procedure
- * @link https://trpc.io/docs/v11/procedures
- **/
-export const publicProcedure = edgeTrpc.procedure.use(({ next, ctx }) => {
- return next({
- ctx: { userId: isDesktop ? DESKTOP_USER_ID : ctx.userId },
- });
-});
-
-// procedure that asserts that the user add the password
-export const passwordProcedure = edgeTrpc.procedure.use(jwtPayloadChecker);
-
-/**
- * Merge multiple routers together
- * @link https://trpc.io/docs/v11/merging-routers
- */
-export const mergeRouters = edgeTrpc.mergeRouters;
-
-/**
- * Create a server-side caller
- * @link https://trpc.io/docs/v11/server/server-side-calls
- */
-export const createCallerFactory = edgeTrpc.createCallerFactory;
diff --git a/src/libs/trpc/edge/init.ts b/src/libs/trpc/edge/init.ts
deleted file mode 100644
index dcf4da527ec..00000000000
--- a/src/libs/trpc/edge/init.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * This is your entry point to setup the root configuration for tRPC on the server.
- * - `initTRPC` should only be used once per app.
- * - We export only the functionality that we use so we can enforce which base procedures should be used
- *
- * Learn how to create protected base procedures and other things below:
- * @link https://trpc.io/docs/v11/router
- * @link https://trpc.io/docs/v11/procedures
- */
-import { initTRPC } from '@trpc/server';
-import superjson from 'superjson';
-
-import type { EdgeContext } from './context';
-
-export const edgeTrpc = initTRPC.context<EdgeContext>().create({
- /**
- * @link https://trpc.io/docs/v11/error-formatting
- */
- errorFormatter({ shape }) {
- return shape;
- },
- /**
- * @link https://trpc.io/docs/v11/data-transformers
- */
- transformer: superjson,
-});
diff --git a/src/libs/trpc/edge/middleware/jwtPayload.test.ts b/src/libs/trpc/edge/middleware/jwtPayload.test.ts
deleted file mode 100644
index 41a83100bb3..00000000000
--- a/src/libs/trpc/edge/middleware/jwtPayload.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-// @vitest-environment node
-import * as utils from '@lobechat/utils/server';
-import { TRPCError } from '@trpc/server';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { createCallerFactory } from '@/libs/trpc/edge';
-import { AuthContext, createContextInner } from '@/libs/trpc/edge/context';
-import { edgeTrpc as trpc } from '@/libs/trpc/edge/init';
-
-import { jwtPayloadChecker } from './jwtPayload';
-
-const appRouter = trpc.router({
- protectedQuery: trpc.procedure.use(jwtPayloadChecker).query(async ({ ctx }) => {
- return ctx.jwtPayload;
- }),
-});
-
-const createCaller = createCallerFactory(appRouter);
-let ctx: AuthContext;
-let router: ReturnType<typeof createCaller>;
-
-vi.mock('@/libs/next-auth/edge', () => {
- return {
- auth: vi.fn().mockResolvedValue(undefined),
- };
-});
-
-beforeEach(() => {
- vi.resetAllMocks();
-});
-
-describe('passwordChecker middleware', () => {
- it('should throw UNAUTHORIZED error if authorizationHeader is not present in context', async () => {
- ctx = await createContextInner();
- router = createCaller(ctx);
-
- await expect(router.protectedQuery()).rejects.toThrow(new TRPCError({ code: 'UNAUTHORIZED' }));
- });
-
- it('should call next with jwtPayload in context if access code is correct', async () => {
- const jwtPayload = { accessCode: '123' };
-
- vi.spyOn(utils, 'getXorPayload').mockResolvedValue(jwtPayload);
-
- ctx = await createContextInner({ authorizationHeader: 'Bearer token' });
- router = createCaller(ctx);
-
- const data = await router.protectedQuery();
-
- expect(data).toEqual(jwtPayload);
- });
-
- it('should call next with jwtPayload in context if no access codes are set', async () => {
- const jwtPayload = {};
- vi.spyOn(utils, 'getXorPayload').mockResolvedValue(jwtPayload);
-
- ctx = await createContextInner({ authorizationHeader: 'Bearer token' });
- router = createCaller(ctx);
-
- const data = await router.protectedQuery();
-
- expect(data).toEqual(jwtPayload);
- });
- it('should call next with jwtPayload in context if access codes is undefined', async () => {
- const jwtPayload = {};
- vi.spyOn(utils, 'getXorPayload').mockResolvedValue(jwtPayload);
-
- ctx = await createContextInner({ authorizationHeader: 'Bearer token' });
- router = createCaller(ctx);
-
- const data = await router.protectedQuery();
-
- expect(data).toEqual(jwtPayload);
- });
-});
diff --git a/src/libs/trpc/edge/middleware/jwtPayload.ts b/src/libs/trpc/edge/middleware/jwtPayload.ts
deleted file mode 100644
index 82b3c4b27fb..00000000000
--- a/src/libs/trpc/edge/middleware/jwtPayload.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { getXorPayload } from '@lobechat/utils/server';
-import { TRPCError } from '@trpc/server';
-
-import { edgeTrpc } from '../init';
-
-export const jwtPayloadChecker = edgeTrpc.middleware(async (opts) => {
- const { ctx } = opts;
-
- if (!ctx.authorizationHeader) throw new TRPCError({ code: 'UNAUTHORIZED' });
-
- const jwtPayload = getXorPayload(ctx.authorizationHeader);
-
- return opts.next({ ctx: { jwtPayload } });
-});
diff --git a/src/migrations/FromV0ToV1.ts b/src/migrations/FromV0ToV1.ts
deleted file mode 100644
index c6ba73d7044..00000000000
--- a/src/migrations/FromV0ToV1.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { Migration, MigrationData } from './VersionController';
-
-export class MigrationV0ToV1 implements Migration {
- // from this version to start migration
- version = 0;
-
- migrate(data: MigrationData): MigrationData {
- return data;
- }
-}
diff --git a/src/migrations/FromV1ToV2/fixtures/input-v1-session.json b/src/migrations/FromV1ToV2/fixtures/input-v1-session.json
deleted file mode 100644
index 4ad9c963d6b..00000000000
--- a/src/migrations/FromV1ToV2/fixtures/input-v1-session.json
+++ /dev/null
@@ -1,191 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": {
- "06cc3e20-e870-4099-a619-c07a849d742d": {
- "chats": {
- "n2Tsl3Dm": {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "createAt": 1698463981313,
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "updateAt": 1698464004494,
- "topicId": "CZg3IEdy",
- "extra": { "fromModel": "gpt-3.5-turbo" }
- },
- "xPft8Msa": {
- "content": "如何指定 自定义函数的引入位置?",
- "createAt": 1698464173224,
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "updateAt": 1698464173226,
- "topicId": "CZg3IEdy"
- },
- "jZc2KKRs": {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "createAt": 1698464173228,
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "updateAt": 1698464181896,
- "topicId": "CZg3IEdy",
- "extra": { "fromModel": "gpt-3.5-turbo" }
- },
- "LjG9XSuq": {
- "content": "如何启动一个 postgres Docker 镜像?",
- "createAt": 1698754460196,
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "updateAt": 1698754463118,
- "topicId": "MNWhBEh5"
- },
- "CL7E1Mc5": {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "createAt": 1698754479751,
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "updateAt": 1698754507690,
- "topicId": "MNWhBEh5",
- "extra": { "fromModel": "gpt-3.5-turbo" }
- },
- "UIvHZr7m": {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "createAt": 1698754591763,
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "updateAt": 1698754591764,
- "topicId": "MNWhBEh5"
- },
- "XLJOK44r": {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "createAt": 1698754591765,
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "updateAt": 1698754609275,
- "topicId": "MNWhBEh5",
- "extra": { "fromModel": "gpt-3.5-turbo" }
- },
- "W3J6jQjm": {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "createAt": 1698754700529,
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "updateAt": 1698754700530,
- "topicId": "MNWhBEh5"
- },
- "L7mq0ehV": {
- "content": "如何启动 pgadmin",
- "createAt": 1698755749886,
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "updateAt": 1698755749888,
- "topicId": "MNWhBEh5"
- },
- "d5XTX9EQ": {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "createAt": 1698755749889,
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "updateAt": 1698755786183,
- "topicId": "MNWhBEh5",
- "extra": { "fromModel": "gpt-3.5-turbo" }
- },
- "KPPDiRyW": {
- "content": "abcabc",
- "createAt": 1690650544852,
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "function",
- "updateAt": 1690650572399,
- "extra": {
- "fromModel": "gpt-3.5-turbo-16k"
- },
- "function_call": {
- "name": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}"
- },
- "name": "websiteCrawler"
- },
- "9cRjevRQ": {
- "content": "bbbbb",
- "createAt": 1700065743405,
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "function",
- "updateAt": 1700065751861,
- "extra": {
- "fromModel": "gpt-3.5-turbo-16k"
- },
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- },
- "name": "website-crawler"
- }
- },
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updateAt": 1698463356269,
- "pinned": true,
- "topics": {
- "CZg3IEdy": {
- "createAt": 1698463911747,
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "updateAt": 1698463915716
- },
- "MNWhBEh5": {
- "createAt": 1698754463117,
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "updateAt": 1698754464867
- }
- }
- }
- }
- },
- "version": 1
-}
diff --git a/src/migrations/FromV1ToV2/fixtures/output-v2.json b/src/migrations/FromV1ToV2/fixtures/output-v2.json
deleted file mode 100644
index 0e724e8b63e..00000000000
--- a/src/migrations/FromV1ToV2/fixtures/output-v2.json
+++ /dev/null
@@ -1,202 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "pinned"
- }
- ],
- "topics": [
- {
- "createdAt": 1698463911747,
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "createdAt": 1698754463117,
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "createdAt": 1698463981313,
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "updatedAt": 1698464004494,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "createdAt": 1698464173224,
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "updatedAt": 1698464173226,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy"
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "createdAt": 1698464173228,
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "updatedAt": 1698464181896,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "createdAt": 1698754460196,
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754463118,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "createdAt": 1698754479751,
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "updatedAt": 1698754507690,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "createdAt": 1698754591763,
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754591764,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "createdAt": 1698754591765,
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "updatedAt": 1698754609275,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "createdAt": 1698754700529,
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754700530,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "如何启动 pgadmin",
- "createdAt": 1698755749886,
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "updatedAt": 1698755749888,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "createdAt": 1698755749889,
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "updatedAt": 1698755786183,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "abcabc",
- "createdAt": 1690650544852,
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "function",
- "updatedAt": 1690650572399,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
-
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- },
- {
- "content": "bbbbb",
- "createdAt": 1700065743405,
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "function",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- }
- }
- ]
- },
- "version": 2
-}
diff --git a/src/migrations/FromV1ToV2/index.ts b/src/migrations/FromV1ToV2/index.ts
deleted file mode 100644
index 4247fc34ab9..00000000000
--- a/src/migrations/FromV1ToV2/index.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { INBOX_SESSION_ID } from '@/const/session';
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-
-import { V1Chat, V1ConfigState, V1Session, V1Topic } from './types/v1';
-import { V2ConfigState, V2Message, V2Session, V2Topic } from './types/v2';
-
-export class MigrationV1ToV2 implements Migration {
- // from this version to start migration
- version = 1;
-
- migrateSession = (
- session: V1Session,
- finalMessages: V2Message[],
- finalTopics: V2Topic[],
- ): V2Session => {
- const { chats, topics, createAt, updateAt, pinned, ...i } = session;
-
- if (chats) {
- for (const chat of Object.values(chats)) {
- finalMessages.push(this.migrationMessage(chat, i.id));
- }
- }
-
- if (topics) {
- for (const chat of Object.values(topics)) {
- finalTopics.push(this.migrationTopic(i.id, chat));
- }
- }
-
- return { ...i, createdAt: createAt, group: pinned ? 'pinned' : 'default', updatedAt: updateAt };
- };
-
- migrate(data: MigrationData<V1ConfigState>): MigrationData<V2ConfigState> {
- const { sessions: v1Session = {}, inbox } = data.state;
- const v2Messages: V2Message[] = [];
- const v2Topics: V2Topic[] = [];
-
- const sessions: V2Session[] = Object.values(v1Session).map((s) =>
- this.migrateSession(s, v2Messages, v2Topics),
- );
-
- if (inbox) {
- this.migrateSession({ ...inbox, id: INBOX_SESSION_ID }, v2Messages, v2Topics);
- }
-
- return {
- ...data,
- state: {
- ...data.state,
- messages: v2Messages,
- sessions,
- topics: v2Topics,
- },
- };
- }
-
- migrationMessage = (
- { createAt, extra, updateAt, name, function_call, ...chat }: V1Chat,
- sessionId: string,
- ): V2Message => ({
- ...chat,
- createdAt: createAt,
- plugin: function_call
- ? {
- apiName: function_call.name,
- arguments: function_call.arguments,
- identifier: name!,
- type: 'default',
- }
- : chat.plugin,
- sessionId,
- updatedAt: updateAt,
- ...extra,
- });
-
- migrationTopic = (sessionId: string, { createAt, updateAt, ...topic }: V1Topic): V2Topic => ({
- ...topic,
- createdAt: createAt,
- sessionId,
- updatedAt: updateAt,
- });
-}
diff --git a/src/migrations/FromV1ToV2/migrations.test.ts b/src/migrations/FromV1ToV2/migrations.test.ts
deleted file mode 100644
index cf1463dd5f2..00000000000
--- a/src/migrations/FromV1ToV2/migrations.test.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import { V1Config, V1ConfigState, V1Session } from '@/migrations/FromV1ToV2/types/v1';
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import inputV1Data from './fixtures/input-v1-session.json';
-import outputV2Data from './fixtures/output-v2.json';
-import { MigrationV1ToV2 } from './index';
-
-describe('MigrationV1ToV2', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV1ToV2];
- versionController = new VersionController(migrations, 2);
- });
-
- it('should migrate data correctly through multiple versions', () => {
- const data: MigrationData = inputV1Data;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputV2Data.version);
- expect(migratedData.state.sessions).toEqual(outputV2Data.state.sessions);
- expect(migratedData.state.topics).toEqual(outputV2Data.state.topics);
- expect(migratedData.state.messages).toEqual(outputV2Data.state.messages);
- });
-
- it('should work correctly with session with no topic', () => {
- const data: MigrationData<V1ConfigState> = {
- state: {
- sessions: {
- 'f8a620ef-c44f-403e-892c-e97fb745255e': {
- chats: {},
- config: {
- model: 'gpt-3.5-turbo',
- params: {
- temperature: 0.6,
- },
- systemRole:
- '你是一名前端专家。现在我们正在实现一个 zustand store。该store包含 agents、chats、sessionTree 三个关键的数据。它们的类型定义如下:\n\n```ts\n\n\nexport interface ChatSessionState {\n sessionTree: SessionTree[];\n chats: ChatContextMap;\n agents: ChatAgentMap;\n}\n\ninterface SessionTree {\n agentId: string;\n chats: string[];\n}\n\nexport type ChatContextMap = Record<string, ChatContext>;\nexport type ChatAgentMap = Record<string, ChatAgent>;\n\n```',
- displayMode: 'chat',
- plugins: [],
- } as unknown as V1Config,
- createAt: 1690016491289,
- id: 'f8a620ef-c44f-403e-892c-e97fb745255e',
- meta: {
- title: '前端 zustand store 专家',
- description: '你需要实现一个 zustand store 的功能',
- avatar: '输出: 🧪',
- },
- type: 'agent',
- updateAt: 1690016491289,
- },
- },
- },
- version: 1,
- };
-
- const migratedData = versionController.migrate(data);
- expect(migratedData.version).toEqual(2);
- expect(migratedData.state.sessions).toEqual([
- {
- group: 'default',
- config: {
- model: 'gpt-3.5-turbo',
- params: {
- temperature: 0.6,
- },
- systemRole:
- '你是一名前端专家。现在我们正在实现一个 zustand store。该store包含 agents、chats、sessionTree 三个关键的数据。它们的类型定义如下:\n\n```ts\n\n\nexport interface ChatSessionState {\n sessionTree: SessionTree[];\n chats: ChatContextMap;\n agents: ChatAgentMap;\n}\n\ninterface SessionTree {\n agentId: string;\n chats: string[];\n}\n\nexport type ChatContextMap = Record<string, ChatContext>;\nexport type ChatAgentMap = Record<string, ChatAgent>;\n\n```',
- displayMode: 'chat',
- plugins: [],
- },
- createdAt: 1690016491289,
- id: 'f8a620ef-c44f-403e-892c-e97fb745255e',
- meta: {
- title: '前端 zustand store 专家',
- description: '你需要实现一个 zustand store 的功能',
- avatar: '输出: 🧪',
- },
- type: 'agent',
- updatedAt: 1690016491289,
- },
- ]);
- });
-
- it('should add inbox messages', () => {
- const data: MigrationData<V1ConfigState> = {
- state: {
- inbox: {
- type: 'agent',
- updateAt: 12,
- createAt: 12,
- id: 'inbox',
- meta: {},
- config: {} as V1Config,
- chats: {
- HD4krtKa: {
- content: '1',
- createAt: 1692891912689,
- id: 'HD4krtKa',
- meta: {},
- role: 'user',
- updateAt: 1693114820406,
- topicId: 'jvfmUEwF',
- },
- K4AVcvGB: {
- content: '2',
- createAt: 1692891912699,
- id: 'K4AVcvGB',
- meta: {},
- parentId: 'HD4krtKa',
- role: 'assistant',
- updateAt: 1693114820418,
- extra: { fromModel: 'gpt-3.5-turbo' },
- topicId: 'jvfmUEwF',
- },
- QaAUgIGC: {
- content: '3',
- createAt: 1693043755942,
- id: 'QaAUgIGC',
- meta: {},
- role: 'user',
- updateAt: 1693114820428,
- topicId: 'jvfmUEwF',
- },
- jF4p75eF: {
- content: '4',
- createAt: 1693043755952,
- id: 'jF4p75eF',
- meta: {},
- parentId: 'QaAUgIGC',
- role: 'assistant',
- updateAt: 1693114820439,
- extra: { fromModel: 'gpt-3.5-turbo' },
- topicId: 'jvfmUEwF',
- },
- },
- topics: {
- jvfmUEwF: {
- createAt: 1693114820394,
- id: 'jvfmUEwF',
- title: 'JSX错误:children属性类型错误',
- updateAt: 1693114821388,
- },
- IVfDVB5g: {
- createAt: 1693228301335,
- id: 'IVfDVB5g',
- title: '上游服务端错误状态码\n下游服务器错误状态码',
- updateAt: 1693228303288,
- },
- },
- },
- },
- version: 1,
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(2);
- expect(migratedData.state.messages).toEqual([
- {
- content: '1',
- createdAt: 1692891912689,
- id: 'HD4krtKa',
- sessionId: 'inbox',
- meta: {},
- role: 'user',
- updatedAt: 1693114820406,
- topicId: 'jvfmUEwF',
- },
- {
- content: '2',
- createdAt: 1692891912699,
- id: 'K4AVcvGB',
- meta: {},
- sessionId: 'inbox',
- parentId: 'HD4krtKa',
- role: 'assistant',
- updatedAt: 1693114820418,
- fromModel: 'gpt-3.5-turbo',
- topicId: 'jvfmUEwF',
- },
- {
- content: '3',
- createdAt: 1693043755942,
- id: 'QaAUgIGC',
- sessionId: 'inbox',
- meta: {},
- role: 'user',
- updatedAt: 1693114820428,
- topicId: 'jvfmUEwF',
- },
- {
- content: '4',
- createdAt: 1693043755952,
- sessionId: 'inbox',
- id: 'jF4p75eF',
- meta: {},
- parentId: 'QaAUgIGC',
- role: 'assistant',
- updatedAt: 1693114820439,
- fromModel: 'gpt-3.5-turbo',
- topicId: 'jvfmUEwF',
- },
- ]);
- expect(migratedData.state.topics).toEqual([
- {
- createdAt: 1693114820394,
- id: 'jvfmUEwF',
- title: 'JSX错误:children属性类型错误',
- sessionId: 'inbox',
- updatedAt: 1693114821388,
- },
- {
- createdAt: 1693228301335,
- id: 'IVfDVB5g',
- title: '上游服务端错误状态码\n下游服务器错误状态码',
- sessionId: 'inbox',
- updatedAt: 1693228303288,
- },
- ]);
- });
-});
diff --git a/src/migrations/FromV1ToV2/types/v1.ts b/src/migrations/FromV1ToV2/types/v1.ts
deleted file mode 100644
index fbeb77abc62..00000000000
--- a/src/migrations/FromV1ToV2/types/v1.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-export interface V1MetaData {
- avatar?: string;
- backgroundColor?: string;
- description?: string;
- tags?: string[];
- title?: string;
-}
-
-export interface V1Chat {
- content: string;
- createAt: number;
- extra?: {
- fromModel: string;
- };
- function_call?: {
- arguments: string;
- name: string;
- };
- id: string;
- meta: V1MetaData;
- // function call name
- name?: string;
- parentId?: string;
- plugin?: {
- apiName: string;
- arguments: string;
- identifier: string;
- type: 'default';
- };
- role: string;
- topicId: string;
- updateAt: number;
-}
-
-export interface V1Session {
- chats: Record<string, V1Chat>;
- config: V1Config;
- createAt: number;
- id: string;
- meta: V1MetaData;
- pinned?: boolean;
- topics?: Record<string, V1Topic>;
- type: 'agent';
- updateAt: number;
-}
-
-export interface V1Config {
- displayMode: string;
- enableCompressThreshold: boolean;
- enableMaxTokens: boolean;
- historyCount: number;
- inputTemplate: string;
- model: string;
- params: Partial<Params>;
- plugins: string[];
- systemRole: string;
-}
-
-export interface Params {
- frequency_penalty: number;
- max_tokens: number;
- presence_penalty: number;
- temperature: number;
- top_p: number;
-}
-
-export interface V1Topic {
- createAt: number;
- favorite?: boolean;
- id: string;
- title: string;
- updateAt: number;
-}
-
-export interface V1ConfigState {
- inbox?: V1Session;
- sessions?: Record<string, V1Session>;
-}
diff --git a/src/migrations/FromV1ToV2/types/v2.ts b/src/migrations/FromV1ToV2/types/v2.ts
deleted file mode 100644
index 57fdf2899e6..00000000000
--- a/src/migrations/FromV1ToV2/types/v2.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { V1Config } from './v1';
-
-export interface V2ConfigState {
- messages: V2Message[];
- sessions: V2Session[];
- topics: V2Topic[];
-}
-
-export interface V2Session {
- config: V1Config;
- createdAt: number;
- group: 'default' | 'pinned';
- id: string;
- meta: Meta;
- type: string;
- updatedAt: number;
-}
-
-export interface Meta {
- avatar?: string;
- backgroundColor?: string;
- description?: string;
- tags?: string[];
- title?: string;
-}
-
-export interface V2Topic {
- createdAt: number;
- id: string;
- sessionId: string;
- title: string;
- updatedAt: number;
-}
-
-export interface V2Message {
- content: string;
- createdAt: number;
- fromModel?: string;
- id: string;
- meta: Meta;
- parentId?: string;
- plugin?: {
- apiName: string;
- arguments: string;
- identifier: string;
- type: 'default';
- };
- role: string;
- sessionId: string;
- topicId: string;
- updatedAt: number;
-}
diff --git a/src/migrations/FromV2ToV3/fixtures/input-v2-session.json b/src/migrations/FromV2ToV3/fixtures/input-v2-session.json
deleted file mode 100644
index bf00c049a9e..00000000000
--- a/src/migrations/FromV2ToV3/fixtures/input-v2-session.json
+++ /dev/null
@@ -1,72 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "pinned"
- },
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4098-a619-c07a849d74dd",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default"
- }
- ],
- "topics": [],
- "messages": []
- },
- "version": 2
-}
diff --git a/src/migrations/FromV2ToV3/fixtures/output-v3-from-v1.json b/src/migrations/FromV2ToV3/fixtures/output-v3-from-v1.json
deleted file mode 100644
index b6b39f4417e..00000000000
--- a/src/migrations/FromV2ToV3/fixtures/output-v3-from-v1.json
+++ /dev/null
@@ -1,203 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default",
- "pinned": true
- }
- ],
- "topics": [
- {
- "createdAt": 1698463911747,
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "createdAt": 1698754463117,
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "createdAt": 1698463981313,
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "updatedAt": 1698464004494,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "createdAt": 1698464173224,
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "updatedAt": 1698464173226,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy"
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "createdAt": 1698464173228,
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "updatedAt": 1698464181896,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "createdAt": 1698754460196,
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754463118,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "createdAt": 1698754479751,
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "updatedAt": 1698754507690,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "createdAt": 1698754591763,
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754591764,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "createdAt": 1698754591765,
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "updatedAt": 1698754609275,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "createdAt": 1698754700529,
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754700530,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "如何启动 pgadmin",
- "createdAt": 1698755749886,
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "updatedAt": 1698755749888,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "createdAt": 1698755749889,
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "updatedAt": 1698755786183,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "abcabc",
- "createdAt": 1690650544852,
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "function",
- "updatedAt": 1690650572399,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
-
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- },
- {
- "content": "bbbbb",
- "createdAt": 1700065743405,
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "function",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- }
- }
- ]
- },
- "version": 3
-}
diff --git a/src/migrations/FromV2ToV3/fixtures/output-v3.json b/src/migrations/FromV2ToV3/fixtures/output-v3.json
deleted file mode 100644
index f551f7ce8b6..00000000000
--- a/src/migrations/FromV2ToV3/fixtures/output-v3.json
+++ /dev/null
@@ -1,74 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default",
- "pinned": true
- },
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4098-a619-c07a849d74dd",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default",
- "pinned": false
- }
- ],
- "topics": [],
- "messages": []
- },
- "version": 3
-}
diff --git a/src/migrations/FromV2ToV3/index.ts b/src/migrations/FromV2ToV3/index.ts
deleted file mode 100644
index 691e121ec21..00000000000
--- a/src/migrations/FromV2ToV3/index.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-
-import { V2ConfigState, V2Session } from '../FromV1ToV2/types/v2';
-import { V3ConfigState, V3Session } from './types/v3';
-
-export class MigrationV2ToV3 implements Migration {
- // from this version to start migration
- version = 2;
-
- migrate(data: MigrationData<V2ConfigState>): MigrationData<V3ConfigState> {
- const { sessions } = data.state;
-
- return {
- ...data,
- state: {
- ...data.state,
- sessionGroups: [],
- sessions: sessions.map((s) => this.migrateSession(s)),
- },
- };
- }
-
- migrateSession = (session: V2Session): V3Session => {
- return {
- ...session,
- group: 'default',
- pinned: session.group === 'pinned',
- };
- };
-}
diff --git a/src/migrations/FromV2ToV3/migrations.test.ts b/src/migrations/FromV2ToV3/migrations.test.ts
deleted file mode 100644
index fd9315a52d7..00000000000
--- a/src/migrations/FromV2ToV3/migrations.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import { MigrationV1ToV2 } from '../FromV1ToV2';
-import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
-import inputV2Data from './fixtures/input-v2-session.json';
-import outputV3DataFromV1 from './fixtures/output-v3-from-v1.json';
-import outputV3Data from './fixtures/output-v3.json';
-import { MigrationV2ToV3 } from './index';
-
-describe('MigrationV2ToV3', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV2ToV3];
- versionController = new VersionController(migrations, 3);
- });
-
- it('should migrate data correctly through multiple versions', () => {
- const data: MigrationData = inputV2Data;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputV3Data.version);
- expect(migratedData.state.sessions).toEqual(outputV3Data.state.sessions);
- expect(migratedData.state.topics).toEqual(outputV3Data.state.topics);
- expect(migratedData.state.messages).toEqual(outputV3Data.state.messages);
- });
-
- it('should work correct from v1 to v3', () => {
- const data: MigrationData = inputV1Data;
-
- versionController = new VersionController([MigrationV2ToV3, MigrationV1ToV2], 3);
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputV3DataFromV1.version);
- expect(migratedData.state.sessions).toEqual(outputV3DataFromV1.state.sessions);
- expect(migratedData.state.topics).toEqual(outputV3DataFromV1.state.topics);
- expect(migratedData.state.messages).toEqual(outputV3DataFromV1.state.messages);
- });
-});
diff --git a/src/migrations/FromV2ToV3/types/v3.ts b/src/migrations/FromV2ToV3/types/v3.ts
deleted file mode 100644
index 9f322a2639d..00000000000
--- a/src/migrations/FromV2ToV3/types/v3.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { V1Config } from '@/migrations/FromV1ToV2/types/v1';
-
-import { Meta, V2ConfigState } from '../../FromV1ToV2/types/v2';
-
-export interface V3ConfigState extends V2ConfigState {
- sessionGroups: V3SessionGroup[];
- sessions: V3Session[];
-}
-
-export interface V3Session {
- config: V1Config;
- createdAt: number;
- group: 'default';
- id: string;
- meta: Meta;
- pinned?: boolean;
- type: string;
- updatedAt: number;
-}
-
-export interface V3SessionGroup {
- createdAt: number;
- id: string;
- name: string;
- sort: number;
- updatedAt: number;
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/azure-input-v3.json b/src/migrations/FromV3ToV4/fixtures/azure-input-v3.json
deleted file mode 100644
index 05c99a8d25a..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/azure-input-v3.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "deployments": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openAI": {
- "OPENAI_API_KEY": "asbdasd",
- "enabled": true,
- "models": [],
- "endpoint": "https://api.chatanywhere.com.cn",
- "customModelName": "deerercsds",
- "useAzure": true,
- "azureApiVersion": "2024-02-15-preview"
- },
- "openrouter": { "apiKey": "", "enabled": false },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "OPENAI_API_KEY": "",
- "models": ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"],
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 3
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/azure-output-v4.json b/src/migrations/FromV3ToV4/fixtures/azure-output-v4.json
deleted file mode 100644
index b59c83252f1..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/azure-output-v4.json
+++ /dev/null
@@ -1,75 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": {
- "apiKey": "asbdasd",
- "apiVersion": "2024-02-15-preview",
- "enabled": true,
- "endpoint": "https://api.chatanywhere.com.cn"
- },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openrouter": { "apiKey": "", "enabled": false },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "apiKey": "",
- "endpoint": "",
- "enabled": true
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 4
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/ollama-input-v3.json b/src/migrations/FromV3ToV4/fixtures/ollama-input-v3.json
deleted file mode 100644
index fd2908ba611..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/ollama-input-v3.json
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "deployments": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": {
- "enabled": false,
- "endpoint": "",
- "customModelName": "-all,+llava"
- },
- "openAI": {
- "OPENAI_API_KEY": "",
- "enabled": true,
- "models": [],
- "endpoint": "",
- "customModelName": "",
- "useAzure": false
- },
- "openrouter": {
- "apiKey": "",
- "enabled": true
- },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "OPENAI_API_KEY": "",
- "models": ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"],
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 3
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/ollama-output-v4.json b/src/migrations/FromV3ToV4/fixtures/ollama-output-v4.json
deleted file mode 100644
index 05b742d78f7..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/ollama-output-v4.json
+++ /dev/null
@@ -1,86 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": {
- "enabled": false,
- "endpoint": "",
- "customModelCards": [
- {
- "description": "LLaVA 是结合视觉编码器和 Vicuna 的多模态模型,用于强大的视觉和语言理解。",
- "displayName": "LLaVA 7B",
- "enabled": true,
- "id": "llava",
- "contextWindowTokens": 4096,
- "vision": true
- }
- ]
- },
- "openrouter": {
- "apiKey": "",
- "enabled": true
- },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "apiKey": "",
- "enabled": true,
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 4
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/openai-input-v3.json b/src/migrations/FromV3ToV4/fixtures/openai-input-v3.json
deleted file mode 100644
index 07321a9c2e9..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/openai-input-v3.json
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "deployments": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openAI": {
- "OPENAI_API_KEY": "asbdasd",
- "enabled": true,
- "models": [],
- "endpoint": "https://api.chatanywhere.com.cn",
- "customModelName": "deerercsds"
- },
- "openrouter": { "apiKey": "", "enabled": false },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "OPENAI_API_KEY": "",
- "models": ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"],
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 3
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/openai-output-v4.json b/src/migrations/FromV3ToV4/fixtures/openai-output-v4.json
deleted file mode 100644
index fda5bffe5bc..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/openai-output-v4.json
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openrouter": { "apiKey": "", "enabled": false },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "enabled": true,
- "apiKey": "asbdasd",
- "endpoint": "https://api.chatanywhere.com.cn",
- "customModelCards": [
- {
- "displayName": "deerercsds",
- "enabled": true,
- "id": "deerercsds"
- }
- ]
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 4
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/openrouter-input-v3.json b/src/migrations/FromV3ToV4/fixtures/openrouter-input-v3.json
deleted file mode 100644
index 972c2903193..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/openrouter-input-v3.json
+++ /dev/null
@@ -1,82 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "deployments": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openAI": {
- "OPENAI_API_KEY": "",
- "enabled": true,
- "models": [],
- "endpoint": "",
- "customModelName": "",
- "useAzure": false
- },
- "openrouter": {
- "apiKey": "",
- "enabled": true,
- "customModelName": "-all,+01-ai/yi-34b-chat,+huggingfaceh4/zephyr-7b-beta"
- },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "OPENAI_API_KEY": "",
- "models": ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"],
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 3
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/openrouter-output-v4.json b/src/migrations/FromV3ToV4/fixtures/openrouter-output-v4.json
deleted file mode 100644
index 3c3a6289503..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/openrouter-output-v4.json
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "apiKey": "", "enabled": false },
- "azure": { "apiKey": "", "enabled": false, "endpoint": "" },
- "bedrock": {
- "accessKeyId": "",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": ""
- },
- "google": { "apiKey": "", "enabled": false },
- "groq": { "apiKey": "", "enabled": false },
- "mistral": { "apiKey": "", "enabled": false },
- "moonshot": { "apiKey": "", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "" },
- "openrouter": {
- "apiKey": "",
- "enabled": true,
- "customModelCards": [
- {
- "displayName": "01-ai/yi-34b-chat",
- "enabled": true,
- "id": "01-ai/yi-34b-chat"
- },
- {
- "displayName": "huggingfaceh4/zephyr-7b-beta",
- "enabled": true,
- "id": "huggingfaceh4/zephyr-7b-beta"
- }
- ]
- },
- "perplexity": { "apiKey": "", "enabled": false },
- "togetherai": { "apiKey": "", "enabled": false },
- "zeroone": { "apiKey": "", "enabled": false },
- "zhipu": { "apiKey": "", "enabled": false },
- "openai": {
- "apiKey": "",
- "enabled": true,
- "endpoint": ""
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 4
-}
diff --git a/src/migrations/FromV3ToV4/fixtures/output-v4-from-v1.json b/src/migrations/FromV3ToV4/fixtures/output-v4-from-v1.json
deleted file mode 100644
index 490e8fcf88a..00000000000
--- a/src/migrations/FromV3ToV4/fixtures/output-v4-from-v1.json
+++ /dev/null
@@ -1,203 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default",
- "pinned": true
- }
- ],
- "topics": [
- {
- "createdAt": 1698463911747,
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "createdAt": 1698754463117,
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "createdAt": 1698463981313,
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "updatedAt": 1698464004494,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "createdAt": 1698464173224,
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "updatedAt": 1698464173226,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy"
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "createdAt": 1698464173228,
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "updatedAt": 1698464181896,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "createdAt": 1698754460196,
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754463118,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "createdAt": 1698754479751,
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "updatedAt": 1698754507690,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "createdAt": 1698754591763,
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754591764,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "createdAt": 1698754591765,
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "updatedAt": 1698754609275,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "createdAt": 1698754700529,
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754700530,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "如何启动 pgadmin",
- "createdAt": 1698755749886,
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "updatedAt": 1698755749888,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "createdAt": 1698755749889,
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "updatedAt": 1698755786183,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "abcabc",
- "createdAt": 1690650544852,
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "function",
- "updatedAt": 1690650572399,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
-
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- },
- {
- "content": "bbbbb",
- "createdAt": 1700065743405,
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "function",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- }
- }
- ]
- },
- "version": 4
-}
diff --git a/src/migrations/FromV3ToV4/index.ts b/src/migrations/FromV3ToV4/index.ts
deleted file mode 100644
index 72691cd6837..00000000000
--- a/src/migrations/FromV3ToV4/index.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-import { transformToChatModelCards } from '@/utils/_deprecated/parseModels';
-
-import { V3ConfigState, V3LegacyConfig, V3OpenAIConfig, V3Settings } from './types/v3';
-import { V4AzureOpenAIConfig, V4ConfigState, V4ProviderConfig, V4Settings } from './types/v4';
-
-export class MigrationV3ToV4 implements Migration {
- // from this version to start migration
- version = 3;
-
- migrate(data: MigrationData<V3ConfigState>): MigrationData<V4ConfigState> {
- const { settings } = data.state;
-
- return {
- ...data,
- state: {
- ...data.state,
- settings: !settings ? undefined : MigrationV3ToV4.migrateSettings(settings),
- },
- };
- }
-
- static migrateSettings = (settings: V3Settings): V4Settings => {
- const { languageModel } = settings;
-
- if (!languageModel) return { ...settings, languageModel: undefined };
-
- const { openAI, togetherai, openrouter, ollama, ...res } = languageModel;
- const { openai, azure } = this.migrateOpenAI(openAI);
-
- return {
- ...settings,
- languageModel: {
- ...res,
- azure,
- ollama: ollama && this.migrateProvider(ollama),
- openai,
- openrouter: openrouter && this.migrateProvider(openrouter),
- togetherai: togetherai && this.migrateProvider(togetherai),
- },
- };
- };
-
- static migrateOpenAI = (
- openai?: V3OpenAIConfig,
- ): { azure: V4AzureOpenAIConfig; openai: V4ProviderConfig } => {
- if (!openai)
- return {
- azure: { apiKey: '', enabled: false },
- openai: { apiKey: '', enabled: true },
- };
-
- if (openai.useAzure) {
- return {
- azure: {
- apiKey: openai.OPENAI_API_KEY,
- apiVersion: openai.azureApiVersion,
- enabled: true,
- endpoint: openai.endpoint,
- },
- openai: { apiKey: '', enabled: true, endpoint: '' },
- };
- }
-
- const customModelCards = transformToChatModelCards({
- defaultChatModels: [],
- modelString: openai.customModelName,
- });
-
- return {
- azure: {
- apiKey: '',
- enabled: false,
- endpoint: '',
- },
- openai: {
- apiKey: openai.OPENAI_API_KEY,
- customModelCards:
- customModelCards && customModelCards.length > 0 ? customModelCards : undefined,
- enabled: true,
- endpoint: openai.endpoint,
- },
- };
- };
-
- static migrateProvider = (provider: V3LegacyConfig): V4ProviderConfig => {
- const customModelCards = transformToChatModelCards({
- defaultChatModels: [],
- modelString: provider.customModelName,
- });
-
- return {
- apiKey: provider.apiKey,
- customModelCards:
- customModelCards && customModelCards.length > 0 ? customModelCards : undefined,
- enabled: provider.enabled,
- endpoint: provider.endpoint,
- };
- };
-}
-
-export const MigrationLLMSettings = MigrationV3ToV4;
diff --git a/src/migrations/FromV3ToV4/migrations.test.ts b/src/migrations/FromV3ToV4/migrations.test.ts
deleted file mode 100644
index 339689299e3..00000000000
--- a/src/migrations/FromV3ToV4/migrations.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { describe } from 'vitest';
-
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import { MigrationV1ToV2 } from '../FromV1ToV2';
-import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
-import { MigrationV2ToV3 } from '../FromV2ToV3';
-import azureInputV3 from './fixtures/azure-input-v3.json';
-import azureOutputV4 from './fixtures/azure-output-v4.json';
-import ollamaInputV3 from './fixtures/ollama-input-v3.json';
-import ollamaOutputV4 from './fixtures/ollama-output-v4.json';
-import openaiInputV3 from './fixtures/openai-input-v3.json';
-import openaiOutputV4 from './fixtures/openai-output-v4.json';
-import openrouterInputV3 from './fixtures/openrouter-input-v3.json';
-import openrouterOutputV4 from './fixtures/openrouter-output-v4.json';
-import outputV4Data from './fixtures/output-v4-from-v1.json';
-import { MigrationV3ToV4 } from './index';
-
-describe('MigrationV3ToV4', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV3ToV4];
- versionController = new VersionController(migrations, 4);
- });
-
- describe('should migrate data correctly from previous versions', () => {
- it('openai', () => {
- const data: MigrationData = openaiInputV3;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(openaiOutputV4.version);
- expect(migratedData.state.settings.languageModel).toEqual(
- openaiOutputV4.state.settings.languageModel,
- );
- });
-
- it('azure', () => {
- const data: MigrationData = azureInputV3;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(azureOutputV4.version);
- expect(migratedData.state.settings.languageModel).toEqual(
- azureOutputV4.state.settings.languageModel,
- );
- });
-
- it('openrouter', () => {
- const data: MigrationData = openrouterInputV3;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(openrouterOutputV4.version);
- expect(migratedData.state.settings.languageModel).toEqual(
- openrouterOutputV4.state.settings.languageModel,
- );
- });
-
- it('ollama', () => {
- const data: MigrationData = ollamaInputV3;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(ollamaOutputV4.version);
- expect(migratedData.state.settings.languageModel).toEqual(
- ollamaOutputV4.state.settings.languageModel,
- );
- });
- });
-
- it('should work correct from v1 to v4', () => {
- const data: MigrationData = inputV1Data;
-
- versionController = new VersionController(
- [MigrationV3ToV4, MigrationV2ToV3, MigrationV1ToV2],
- 4,
- );
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputV4Data.version);
- // expect(migratedData.state.sessions).toEqual(outputV3DataFromV1.state.sessions);
- // expect(migratedData.state.topics).toEqual(outputV3DataFromV1.state.topics);
- // expect(migratedData.state.messages).toEqual(outputV3DataFromV1.state.messages);
- });
-
- describe('Edge Case', () => {
- it('should handle undefined settings or languageModel', () => {
- const data: MigrationData = {
- version: 3,
- state: {
- // settings undefined
- },
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(4);
- expect(migratedData.state.settings).toBeUndefined();
- });
-
- it('should handle undefined languageModel', () => {
- const data: MigrationData = {
- version: 3,
- state: {
- settings: {
- // languageModel undefined
- },
- },
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(4);
- expect(migratedData.state.settings.languageModel).toBeUndefined();
- });
-
- it('should handle missing provider configurations', () => {
- const data: MigrationData = {
- version: 3,
- state: {
- settings: {
- languageModel: {
- // missing togetherai、openrouter 、 ollama
- openAI: {
- // openAI
- },
- },
- },
- },
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(4);
- expect(migratedData.state.settings.languageModel.togetherai).toBeUndefined();
- expect(migratedData.state.settings.languageModel.openrouter).toBeUndefined();
- expect(migratedData.state.settings.languageModel.ollama).toBeUndefined();
- });
-
- it('should success for invalid data format', () => {
- const data: MigrationData = {
- version: 3,
- state: {
- settings: {
- languageModel: {
- openAI: 'invalid-config', // 错误的配置格式
- },
- },
- },
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(4);
- expect(migratedData.state.settings.languageModel.openai).toEqual({ enabled: true });
- expect(migratedData.state.settings.languageModel.togetherai).toBeUndefined();
- expect(migratedData.state.settings.languageModel.openrouter).toBeUndefined();
- expect(migratedData.state.settings.languageModel.ollama).toBeUndefined();
- });
-
- it('should handle empty strings and empty objects', () => {
- const data: MigrationData = {
- version: 3,
- state: {
- settings: {
- languageModel: {
- openAI: undefined,
- togetherai: {
- apiKey: '',
- endpoint: '',
- customModelName: '',
- },
- },
- },
- },
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(4);
- expect(migratedData.state.settings.languageModel.openai).toEqual({
- apiKey: '',
- enabled: true,
- });
-
- expect(migratedData.state.settings.languageModel.togetherai.apiKey).toEqual('');
- expect(migratedData.state.settings.languageModel.togetherai.endpoint).toEqual('');
- expect(migratedData.state.settings.languageModel.togetherai.customModelCards).toBeUndefined();
- });
- });
-});
diff --git a/src/migrations/FromV3ToV4/types/v3.ts b/src/migrations/FromV3ToV4/types/v3.ts
deleted file mode 100644
index 8eecdf196e0..00000000000
--- a/src/migrations/FromV3ToV4/types/v3.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-interface V3GeneralConfig {
- apiKey?: string;
- enabled: boolean;
- endpoint?: string;
-}
-
-export interface V3OpenAIConfig {
- OPENAI_API_KEY: string;
- azureApiVersion?: string;
- customModelName?: string;
- enabled: boolean;
- endpoint?: string;
- useAzure?: boolean;
-}
-
-export interface V3LegacyConfig {
- apiKey?: string;
- customModelName?: string;
- enabled?: boolean;
- enabledModels: string[];
- endpoint?: string;
-}
-
-export interface V3LLMConfig {
- bedrock: any;
- google: V3GeneralConfig;
- ollama: V3LegacyConfig;
- openAI: V3OpenAIConfig;
- openrouter: V3LegacyConfig;
- togetherai: V3LegacyConfig;
-}
-
-/**
- * 配置设置
- */
-export interface V3Settings {
- defaultAgent: any;
- fontSize: number;
- language: string;
- languageModel?: Partial<V3LLMConfig>;
- neutralColor?: string;
- password: string;
- primaryColor?: string;
- sync: any;
- themeMode: string;
- tool: any;
- tts: any;
-}
-
-export interface V3ConfigState {
- settings?: V3Settings;
-}
diff --git a/src/migrations/FromV3ToV4/types/v4.ts b/src/migrations/FromV3ToV4/types/v4.ts
deleted file mode 100644
index 78585cd41c0..00000000000
--- a/src/migrations/FromV3ToV4/types/v4.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { ChatModelCard } from '@/types/llm';
-
-import { V3LLMConfig, V3Settings } from './v3';
-
-export interface V4ProviderConfig {
- apiKey?: string;
- customModelCards?: ChatModelCard[];
- enabled?: boolean;
- /**
- * enabled models id
- */
- enabledModels?: string[] | null;
- endpoint?: string;
-}
-export interface V4AzureOpenAIConfig extends V4ProviderConfig {
- apiVersion?: string;
-}
-
-export interface V4lLLMConfig
- extends Omit<Partial<V3LLMConfig>, 'ollama' | 'openAI' | 'openrouter' | 'togetherai'> {
- azure?: V4AzureOpenAIConfig;
- ollama?: V4ProviderConfig;
- openai: V4ProviderConfig;
- openrouter?: V4ProviderConfig;
- togetherai?: V4ProviderConfig;
-}
-
-/**
- * 配置设置
- */
-export interface V4Settings extends Omit<V3Settings, 'languageModel'> {
- languageModel?: V4lLLMConfig;
-}
-
-export interface V4ConfigState {
- settings?: V4Settings;
-}
diff --git a/src/migrations/FromV4ToV5/fixtures/from-v1-to-v5-output.json b/src/migrations/FromV4ToV5/fixtures/from-v1-to-v5-output.json
deleted file mode 100644
index dc0fd7d910e..00000000000
--- a/src/migrations/FromV4ToV5/fixtures/from-v1-to-v5-output.json
+++ /dev/null
@@ -1,245 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "createdAt": 1698463356269,
- "group": "default",
- "updatedAt": 1698463356269,
- "pinned": true
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "topicId": "CZg3IEdy",
- "createdAt": 1698463981313,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464004494,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "topicId": "CZg3IEdy",
- "createdAt": 1698464173224,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464173226
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "topicId": "CZg3IEdy",
- "createdAt": 1698464173228,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464181896,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754460196,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754463118
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754479751,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754507690,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754591763,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754591764
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754591765,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754609275,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754700529,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754700530
- },
- {
- "content": "如何启动 pgadmin",
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698755749886,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698755749888
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698755749889,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698755786183,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "",
- "id": "tool_calls_KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "assistant",
- "createdAt": 1690650544842,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1690650572389,
- "fromModel": "gpt-3.5-turbo-16k",
- "tools": [
- {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "id": "tool_call_KPPDiRyW",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- ]
- },
- {
- "content": "abcabc",
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "tool_calls_KPPDiRyW",
- "role": "tool",
- "createdAt": 1690650544852,
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- },
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1690650572399,
- "fromModel": "gpt-3.5-turbo-16k",
- "tool_call_id": "tool_call_KPPDiRyW"
- },
- {
- "content": "",
- "id": "tool_calls_9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "assistant",
- "createdAt": 1700065743395,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751851,
- "fromModel": "gpt-3.5-turbo-16k",
- "tools": [
- {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "id": "tool_call_9cRjevRQ",
- "identifier": "website-crawler",
- "type": "default"
- }
- ]
- },
- {
- "content": "bbbbb",
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "tool_calls_9cRjevRQ",
- "role": "tool",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- },
- "createdAt": 1700065743405,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "tool_call_id": "tool_call_9cRjevRQ"
- }
- ],
- "topics": [
- {
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "createdAt": 1698463911747,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "createdAt": 1698754463117,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "sessionGroups": []
- },
- "version": 5
-}
diff --git a/src/migrations/FromV4ToV5/fixtures/function-input-v4.json b/src/migrations/FromV4ToV5/fixtures/function-input-v4.json
deleted file mode 100644
index f83e41855a2..00000000000
--- a/src/migrations/FromV4ToV5/fixtures/function-input-v4.json
+++ /dev/null
@@ -1,96 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "messages": [
- {
- "role": "function",
- "content": "[{\"city\":\"杭州市\",\"adcode\":\"330100\",\"province\":\"浙江\",\"reporttime\":\"2024-05-11 10:32:32\",\"casts\":[{\"date\":\"2024-05-11\",\"week\":\"6\",\"dayweather\":\"中雨\",\"nightweather\":\"中雨\",\"daytemp\":\"25\",\"nighttemp\":\"18\",\"daywind\":\"南\",\"nightwind\":\"南\",\"daypower\":\"4\",\"nightpower\":\"4\",\"daytemp_float\":\"25.0\",\"nighttemp_float\":\"18.0\"},{\"date\":\"2024-05-12\",\"week\":\"7\",\"dayweather\":\"多云\",\"nightweather\":\"晴\",\"daytemp\":\"25\",\"nighttemp\":\"16\",\"daywind\":\"北\",\"nightwind\":\"北\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"25.0\",\"nighttemp_float\":\"16.0\"},{\"date\":\"2024-05-13\",\"week\":\"1\",\"dayweather\":\"晴\",\"nightweather\":\"晴\",\"daytemp\":\"28\",\"nighttemp\":\"16\",\"daywind\":\"东北\",\"nightwind\":\"东北\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"28.0\",\"nighttemp_float\":\"16.0\"},{\"date\":\"2024-05-14\",\"week\":\"2\",\"dayweather\":\"多云\",\"nightweather\":\"阴\",\"daytemp\":\"28\",\"nighttemp\":\"15\",\"daywind\":\"东\",\"nightwind\":\"东\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"28.0\",\"nighttemp_float\":\"15.0\"}]}]",
- "fromModel": "gpt-3.5-turbo",
- "fromProvider": "openai",
- "parentId": "WwRdrdCz",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715395810026,
- "id": "UQ5VAGkk",
- "updatedAt": 1715395822026,
- "traceId": "4a8381a2-5582-46ce-87d8-c0f010de5c68",
- "observationId": "904f7ab0-4066-4f9b-84fa-b1677974f976",
- "plugin": {
- "apiName": "fetchCurrentWeather",
- "arguments": "{\n \"city\": \"杭州\"\n}",
- "identifier": "realtime-weather",
- "type": "default"
- }
- },
- {
- "role": "user",
- "content": "杭州天气如何?\n\n",
- "files": [],
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715394828164,
- "id": "WwRdrdCz",
- "updatedAt": 1715394828164
- },
- {
- "role": "assistant",
- "content": "杭州的天气情况如下:\n\n- 今天(5月11日)白天和晚上都有中雨,白天温度为25摄氏度,晚上温度为18摄氏度,南风,风力为4级。\n- 明天(5月12日)白天多云,晚上晴,白天温度为25摄氏度,晚上温度为16摄氏度,北风,风力为1-3级。\n- 后天(5月13日)白天和晚上都是晴天,白天温度为28摄氏度,晚上温度为16摄氏度,东北风,风力为1-3级。\n- 大后天(5月14日)白天多云,晚上阴天,白天温度为28摄氏度,晚上温度为15摄氏度,东风,风力为1-3级。\n\n请注意根据实际情况做好防雨和保暖措施。",
- "fromModel": "gpt-3.5-turbo",
- "fromProvider": "openai",
- "parentId": "UQ5VAGkk",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715395822125,
- "id": "hbqsYoMn",
- "updatedAt": 1715395830606,
- "traceId": "4a8381a2-5582-46ce-87d8-c0f010de5c68",
- "observationId": "cad6a5bd-6a7a-4ff9-b37a-3deaa23b094a"
- }
- ],
- "sessions": [
- {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "group": "default",
- "meta": {},
- "pinned": false,
- "type": "agent",
- "createdAt": 1715394818440,
- "id": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "updatedAt": 1715394822366,
- "model": "gpt-3.5-turbo"
- }
- ],
- "topics": [
- {
- "title": "杭州天气查询",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "createdAt": 1715394835099,
- "id": "yjkdZafZ",
- "updatedAt": 1715394838061,
- "favorite": false
- }
- ]
- },
- "version": 4
-}
diff --git a/src/migrations/FromV4ToV5/fixtures/function-output-v5.json b/src/migrations/FromV4ToV5/fixtures/function-output-v5.json
deleted file mode 100644
index 439747b37f6..00000000000
--- a/src/migrations/FromV4ToV5/fixtures/function-output-v5.json
+++ /dev/null
@@ -1,120 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "messages": [
- {
- "role": "assistant",
- "content": "",
- "fromModel": "gpt-3.5-turbo",
- "fromProvider": "openai",
- "parentId": "WwRdrdCz",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715395810016,
- "id": "tool_calls_UQ5VAGkk",
- "updatedAt": 1715395822016,
- "traceId": "4a8381a2-5582-46ce-87d8-c0f010de5c68",
- "observationId": "904f7ab0-4066-4f9b-84fa-b1677974f976",
- "tools": [
- {
- "id": "tool_call_UQ5VAGkk",
- "apiName": "fetchCurrentWeather",
- "arguments": "{\n \"city\": \"杭州\"\n}",
- "identifier": "realtime-weather",
- "type": "default"
- }
- ]
- },
- {
- "role": "tool",
- "content": "[{\"city\":\"杭州市\",\"adcode\":\"330100\",\"province\":\"浙江\",\"reporttime\":\"2024-05-11 10:32:32\",\"casts\":[{\"date\":\"2024-05-11\",\"week\":\"6\",\"dayweather\":\"中雨\",\"nightweather\":\"中雨\",\"daytemp\":\"25\",\"nighttemp\":\"18\",\"daywind\":\"南\",\"nightwind\":\"南\",\"daypower\":\"4\",\"nightpower\":\"4\",\"daytemp_float\":\"25.0\",\"nighttemp_float\":\"18.0\"},{\"date\":\"2024-05-12\",\"week\":\"7\",\"dayweather\":\"多云\",\"nightweather\":\"晴\",\"daytemp\":\"25\",\"nighttemp\":\"16\",\"daywind\":\"北\",\"nightwind\":\"北\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"25.0\",\"nighttemp_float\":\"16.0\"},{\"date\":\"2024-05-13\",\"week\":\"1\",\"dayweather\":\"晴\",\"nightweather\":\"晴\",\"daytemp\":\"28\",\"nighttemp\":\"16\",\"daywind\":\"东北\",\"nightwind\":\"东北\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"28.0\",\"nighttemp_float\":\"16.0\"},{\"date\":\"2024-05-14\",\"week\":\"2\",\"dayweather\":\"多云\",\"nightweather\":\"阴\",\"daytemp\":\"28\",\"nighttemp\":\"15\",\"daywind\":\"东\",\"nightwind\":\"东\",\"daypower\":\"1-3\",\"nightpower\":\"1-3\",\"daytemp_float\":\"28.0\",\"nighttemp_float\":\"15.0\"}]}]",
- "fromModel": "gpt-3.5-turbo",
- "fromProvider": "openai",
- "parentId": "tool_calls_UQ5VAGkk",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715395810026,
- "id": "UQ5VAGkk",
- "updatedAt": 1715395822026,
- "traceId": "4a8381a2-5582-46ce-87d8-c0f010de5c68",
- "observationId": "904f7ab0-4066-4f9b-84fa-b1677974f976",
- "tool_call_id": "tool_call_UQ5VAGkk",
- "plugin": {
- "apiName": "fetchCurrentWeather",
- "arguments": "{\n \"city\": \"杭州\"\n}",
- "identifier": "realtime-weather",
- "type": "default"
- }
- },
- {
- "role": "user",
- "content": "杭州天气如何?\n\n",
- "files": [],
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715394828164,
- "id": "WwRdrdCz",
- "updatedAt": 1715394828164
- },
- {
- "role": "assistant",
- "content": "杭州的天气情况如下:\n\n- 今天(5月11日)白天和晚上都有中雨,白天温度为25摄氏度,晚上温度为18摄氏度,南风,风力为4级。\n- 明天(5月12日)白天多云,晚上晴,白天温度为25摄氏度,晚上温度为16摄氏度,北风,风力为1-3级。\n- 后天(5月13日)白天和晚上都是晴天,白天温度为28摄氏度,晚上温度为16摄氏度,东北风,风力为1-3级。\n- 大后天(5月14日)白天多云,晚上阴天,白天温度为28摄氏度,晚上温度为15摄氏度,东风,风力为1-3级。\n\n请注意根据实际情况做好防雨和保暖措施。",
- "fromModel": "gpt-3.5-turbo",
- "fromProvider": "openai",
- "parentId": "UQ5VAGkk",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "topicId": "yjkdZafZ",
- "createdAt": 1715395822125,
- "id": "hbqsYoMn",
- "updatedAt": 1715395830606,
- "traceId": "4a8381a2-5582-46ce-87d8-c0f010de5c68",
- "observationId": "cad6a5bd-6a7a-4ff9-b37a-3deaa23b094a"
- }
- ],
- "sessions": [
- {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "group": "default",
- "meta": {},
- "pinned": false,
- "type": "agent",
- "createdAt": 1715394818440,
- "id": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "updatedAt": 1715394822366,
- "model": "gpt-3.5-turbo"
- }
- ],
- "topics": [
- {
- "title": "杭州天气查询",
- "sessionId": "8eb073bb-e133-4dbd-81a2-5305a8447b5f",
- "createdAt": 1715394835099,
- "id": "yjkdZafZ",
- "updatedAt": 1715394838061,
- "favorite": false
- }
- ]
- },
- "version": 5
-}
diff --git a/src/migrations/FromV4ToV5/index.ts b/src/migrations/FromV4ToV5/index.ts
deleted file mode 100644
index 366188536a2..00000000000
--- a/src/migrations/FromV4ToV5/index.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-
-import { V4ConfigState, V4Message } from './types/v4';
-import { V5ConfigState, V5Message } from './types/v5';
-
-export class MigrationV4ToV5 implements Migration {
- // from this version to start migration
- version = 4;
-
- migrate(data: MigrationData<V4ConfigState>): MigrationData<V5ConfigState> {
- const { messages } = data.state;
-
- return {
- ...data,
- state: {
- ...data.state,
- messages: MigrationV4ToV5.migrateMessage(messages),
- },
- };
- }
-
- static migrateMessage(messages: V4Message[]): V5Message[] {
- let v5Messages: V5Message[] = [];
-
- messages.forEach((item) => {
- if (item.role === 'function') {
- const toolCallId = `tool_call_${item.id}`;
- const assistantMessageId = `tool_calls_${item.id}`;
- const assistantMessage: V5Message = {
- ...item,
- content: '',
- // make sure the createdAt is before than tool message
- createdAt: item.createdAt - 10,
- id: assistantMessageId,
- plugin: undefined,
- role: 'assistant',
- tools: [{ ...item.plugin!, id: toolCallId }],
- updatedAt: item.updatedAt - 10,
- };
-
- const toolMessage: V5Message = {
- ...item,
- parentId: assistantMessageId,
- role: 'tool',
- tool_call_id: toolCallId,
- };
- v5Messages.push(assistantMessage, toolMessage);
- }
-
- // if not function message, just push it
- else {
- v5Messages.push(item as V5Message);
- }
- });
-
- return v5Messages;
- }
-}
diff --git a/src/migrations/FromV4ToV5/migrations.test.ts b/src/migrations/FromV4ToV5/migrations.test.ts
deleted file mode 100644
index 9ce33d5fc50..00000000000
--- a/src/migrations/FromV4ToV5/migrations.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { describe } from 'vitest';
-
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import { MigrationV1ToV2 } from '../FromV1ToV2';
-import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
-import { MigrationV2ToV3 } from '../FromV2ToV3';
-import { MigrationV3ToV4 } from '../FromV3ToV4';
-import outputDataFromV1ToV5 from './fixtures/from-v1-to-v5-output.json';
-import functionInputV4 from './fixtures/function-input-v4.json';
-import functionOutputV5 from './fixtures/function-output-v5.json';
-import { MigrationV4ToV5 } from './index';
-
-describe('MigrationV4ToV5', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV4ToV5];
- versionController = new VersionController(migrations, 5);
- });
-
- describe('should migrate data correctly from previous versions', () => {
- it('role=function', () => {
- const data: MigrationData = functionInputV4;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(functionOutputV5.version);
- expect(migratedData.state.messages).toEqual(functionOutputV5.state.messages);
- });
- });
-
- it('should work correct from v1 to v5', () => {
- const data: MigrationData = inputV1Data;
-
- versionController = new VersionController(
- [MigrationV4ToV5, MigrationV3ToV4, MigrationV2ToV3, MigrationV1ToV2],
- 5,
- );
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputDataFromV1ToV5.version);
- expect(migratedData.state.messages).toEqual(outputDataFromV1ToV5.state.messages);
- expect(migratedData.state.sessions).toEqual(outputDataFromV1ToV5.state.sessions);
- expect(migratedData.state.topics).toEqual(outputDataFromV1ToV5.state.topics);
- });
-});
diff --git a/src/migrations/FromV4ToV5/types/v4.ts b/src/migrations/FromV4ToV5/types/v4.ts
deleted file mode 100644
index 70560f9cde3..00000000000
--- a/src/migrations/FromV4ToV5/types/v4.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { LobeToolRenderType } from '@lobechat/types';
-
-export interface V4ChatPluginPayload {
- apiName: string;
- arguments: string;
- identifier: string;
- type: LobeToolRenderType;
-}
-
-export interface V4Message {
- content: string;
- createdAt: number;
- id: string;
- plugin?: V4ChatPluginPayload;
- role: 'user' | 'system' | 'assistant' | 'function';
- updatedAt: number;
-}
-
-export interface V4ConfigState {
- messages: V4Message[];
-}
diff --git a/src/migrations/FromV4ToV5/types/v5.ts b/src/migrations/FromV4ToV5/types/v5.ts
deleted file mode 100644
index 2c30e3ea199..00000000000
--- a/src/migrations/FromV4ToV5/types/v5.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { LobeToolRenderType } from '@lobechat/types';
-
-import { V4ChatPluginPayload } from './v4';
-
-interface ChatToolPayload {
- apiName: string;
- arguments: string;
- id: string;
- identifier: string;
- type: LobeToolRenderType;
-}
-
-export interface V5Message {
- content: string;
- createdAt: number;
- id: string;
- parentId?: string;
- plugin?: V4ChatPluginPayload;
- role: 'user' | 'system' | 'assistant' | 'tool';
- tool_call_id?: string;
- tools?: ChatToolPayload[];
- updatedAt: number;
-}
-
-export interface V5ConfigState {
- messages: V5Message[];
-}
diff --git a/src/migrations/FromV5ToV6/fixtures/from-v1-to-v6-output.json b/src/migrations/FromV5ToV6/fixtures/from-v1-to-v6-output.json
deleted file mode 100644
index e735a2657dc..00000000000
--- a/src/migrations/FromV5ToV6/fixtures/from-v1-to-v6-output.json
+++ /dev/null
@@ -1,247 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "chatConfig": {
- "displayMode": "chat",
- "historyCount": 1,
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa"
- },
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "createdAt": 1698463356269,
- "group": "default",
- "updatedAt": 1698463356269,
- "pinned": true
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "topicId": "CZg3IEdy",
- "createdAt": 1698463981313,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464004494,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "topicId": "CZg3IEdy",
- "createdAt": 1698464173224,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464173226
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "topicId": "CZg3IEdy",
- "createdAt": 1698464173228,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698464181896,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754460196,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754463118
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754479751,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754507690,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754591763,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754591764
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754591765,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754609275,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698754700529,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754700530
- },
- {
- "content": "如何启动 pgadmin",
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "topicId": "MNWhBEh5",
- "createdAt": 1698755749886,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698755749888
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "topicId": "MNWhBEh5",
- "createdAt": 1698755749889,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698755786183,
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "",
- "id": "tool_calls_KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "assistant",
- "createdAt": 1690650544842,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1690650572389,
- "fromModel": "gpt-3.5-turbo-16k",
- "tools": [
- {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "id": "tool_call_KPPDiRyW",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- ]
- },
- {
- "content": "abcabc",
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "tool_calls_KPPDiRyW",
- "role": "tool",
- "createdAt": 1690650544852,
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- },
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1690650572399,
- "fromModel": "gpt-3.5-turbo-16k",
- "tool_call_id": "tool_call_KPPDiRyW"
- },
- {
- "content": "",
- "id": "tool_calls_9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "assistant",
- "createdAt": 1700065743395,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751851,
- "fromModel": "gpt-3.5-turbo-16k",
- "tools": [
- {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "id": "tool_call_9cRjevRQ",
- "identifier": "website-crawler",
- "type": "default"
- }
- ]
- },
- {
- "content": "bbbbb",
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "tool_calls_9cRjevRQ",
- "role": "tool",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- },
- "createdAt": 1700065743405,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "tool_call_id": "tool_call_9cRjevRQ"
- }
- ],
- "topics": [
- {
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "createdAt": 1698463911747,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "createdAt": 1698754463117,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "sessionGroups": []
- },
- "version": 6
-}
diff --git a/src/migrations/FromV5ToV6/fixtures/session-input-v5.json b/src/migrations/FromV5ToV6/fixtures/session-input-v5.json
deleted file mode 100644
index 4ec1fc6b799..00000000000
--- a/src/migrations/FromV5ToV6/fixtures/session-input-v5.json
+++ /dev/null
@@ -1,81 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": [],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": {
- "openai": "alloy"
- }
- }
- },
- "group": "default",
- "meta": {},
- "pinned": false,
- "type": "agent",
- "createdAt": 1715710690494,
- "id": "6626ebf6-fb45-4d5b-a6e8-f77b0d9b77fa",
- "updatedAt": 1715710690494,
- "model": "gpt-3.5-turbo"
- },
- {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "claude-3-sonnet-20240229",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": [],
- "systemRole": "As the Assistant and Judge for TOEFL Writing, your primary role is to deal with tasks related to TOEFL Writing.\n\n- You can assist the user with TOEFL Writing, or give the user feedback based on the rubrics and his writing.\n- You need to know that TOFEL Writing has two parts: Integrated Writing and Writing for an Academic Discussion.\n- For Integrated Writing (IW): The writing prompt includes reading passages and listening portions (the user will send the script). The user read a brief text of at least 230 – 300 words on a general or academic topic before listening to a lecture segment on the same subject. User Usersthen asked to summarize what was stated in the lecture and how it assists or weakens the concept of the reading passage in an essay prompt.\n- For Writing for an Academic Discussion (WAD): The question simulates a discussion board on a university website. Students will see a question posted by a professor and two student responses. The student’s job is to read everything and then write their response.\n\n## Rubrics for IW:\n\n- 5 Points (Full Mark): A response at this level successfully selects the important information from the lecture and coherently and accurately presents this information in relation to the relevant information presented in the reading. The response is well organized, and occasional language errors that are present do not result in inaccurate or imprecise presentation of content or connections.\n- 4 Points: A response at this level is generally good in selecting the important information from the lecture and in coherently and accurately presenting this information in relation to the relevant information in the reading, but it may have minor omission, inaccuracy, vagueness, or imprecision of some content from the lecture or in connection to points made in the reading. A response is also scored at this level if it has more frequent or noticeable minor language errors, as long as such usage and grammatical structures do not result in anything more than an occasional lapse of clarity or in the connection of ideas.\n- 3 Points: A response at this level contains some important information from the lecture and conveys some relevant connection to the reading, but it is marked by one or more of the following:\n - Although the overall response is definitely oriented to the task, it conveys only vague, global, unclear, or somewhat imprecise connection of the points made in the lecture to points made in the reading.\n - The response may omit one major key point made in the lecture.\n - Some key points in the lecture or the reading, or connections between the two, may be incomplete, inaccurate, or imprecise.\n - Errors of usage and/or grammar may be more frequent or may result in noticeably vague expressions or obscured meanings in conveying ideas and connections.\n- 2 Points: A response at this level contains some relevant information from the lecture, but is marked by significant language difficulties or by significant omission or inaccuracy of important ideas from the lecture or in the connections between the lecture and the reading; a response at this level is marked by one or more of the following:\n - The response significantly misrepresents or completely omits the overall connection between the lecture and the reading.\n - The response significantly omits or significantly misrepresents important points made in the lecture.\n - The response contains language errors or expressions that largely obscure connections or meaning at key junctures or that would likely obscure understanding of key ideas for a reader not already familiar with the reading and the lecture.\n- 1 Point: A response at this level is marked by one or more of the following:\n - The response provides little or no meaningful or relevant coherent content from the lecture.\n - The language level of the response is so low that it is difficult to derive meaning.\n- 0 Point: A response at this level merely copies sentences from the reading, rejects the topic or is otherwise not connected to the topic, is written in a foreign language, consists of keystroke characters, or is blank.\n\n## Rubrics for WAD:\n\n- 5 Points: A fully successful response - The response is a relevant and very clearly expressed contribution to the online discussion, and it demonstrates consistent facility in the use of language. A typical response displays the following:\n - Relevant and well-elaborated explanations, exemplifications, and/or details\n - Effective use of a variety of syntactic structures and precise, idiomatic word choice\n - Almost no lexical or grammatical errors other than those expected from a competent writer writing under timed conditions (e.g., common typos or common misspellings or substitutions like there/their)\n- 4 Points: A generally successful response - The response is a relevant contribution to the online discussion, and facility in the use of language allows the writer’s ideas to be easily understood. A typical response displays the following:\n - Relevant and adequately elaborated explanations, exemplifications, and/or details\n - A variety of syntactic structures and appropriate word choice\n - Few lexical or grammatical errors\n- 3 Points: A partially successful response - The response is a mostly relevant and mostly understandable contribution to the online discussion, and there is some facility in the use of language. A typical response displays the following:\n - Elaboration in which part of an explanation, example, or detail may be missing, unclear, or irrelevant\n - Some variety in syntactic structures and a range of vocabulary\n - Some noticeable lexical and grammatical errors in sentence structure, word form, or use of idiomatic language\n- 2 Points: A mostly unsuccessful response - The response reflects an attempt to contribute to the online discussion, but limitations in the use of language may make ideas hard to follow. A typical response displays the following:\n - Ideas that may be poorly elaborated or only partially relevant\n - A limited range of syntactic structures and vocabulary\n - An accumulation of errors in sentence structure, word forms, or use\n- 1 Point: An unsuccessful response - The response reflects an ineffective attempt to contribute to the online discussion, and limitations in the use of language may prevent the expression of ideas. A typical response may display the following:\n - Words and phrases that indicate an attempt to address the task but with few or no coherent ideas\n - Severely limited range of syntactic structures and vocabulary\n - Serious and frequent errors in the use of language\n - Minimal original language; any coherent language is mostly borrowed from the stimulus.\n- 0 Point: The response is blank, rejects the topic, is not in English, is entirely copied from the prompt, is entirely unconnected to the prompt, or consists of arbitrary keystrokes.\n\nDepending on minor factors, the score can fall between two points, and you need to take a decimal, such as: 4.25 or 4.5, depending on the other details.\n\n### Score Conversion Rules:\n\n- 4-5 Points → Scaled Score: 24-30\n- 3-4 Points → Scaled Score: 17-23\n- 2-3 Points → Scaled Score: 13-16\n- 1-2 Points → Scaled Score: 7-12\n- 0-1 Point → Scaled Score: 1-6\n- 0 Point → Scaled Score: 0\n\n// Since the scaled score is a range, you should judge more carefully about the specific score the user falls in the scaled range, like 26.\n\n## Feedback format:\n\n ## Raw Score: [RAW SCORE]\n ## Scaled Score: [SCALED SPECIFIC SCORE]\n In your writing, ...[Specific problems in user's writing(Use bullet list)]\n",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": {
- "openai": "alloy"
- }
- },
- "provider": "anthropic"
- },
- "group": "default",
- "meta": {
- "avatar": "📝",
- "description": "Your TOEFL Writing assistant and evaluator, specializing in feedback and guidance.",
- "tags": ["writing", "study"],
- "title": "TOEFL Writing Tutor"
- },
- "type": "agent",
- "createdAt": 1706114617725,
- "id": "711618cf-a5a8-40c8-821f-aff8f82db584",
- "updatedAt": 1709655104241,
- "pinned": true,
- "model": "claude-3-sonnet-20240229"
- }
- ]
- },
- "version": 5
-}
diff --git a/src/migrations/FromV5ToV6/fixtures/session-output-v6.json b/src/migrations/FromV5ToV6/fixtures/session-output-v6.json
deleted file mode 100644
index 850b4aaedb4..00000000000
--- a/src/migrations/FromV5ToV6/fixtures/session-output-v6.json
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "chatConfig": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1
- },
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": [],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": {
- "openai": "alloy"
- }
- }
- },
- "group": "default",
- "pinned": false,
- "type": "agent",
- "createdAt": 1715710690494,
- "meta": {},
- "id": "6626ebf6-fb45-4d5b-a6e8-f77b0d9b77fa",
- "updatedAt": 1715710690494,
- "model": "gpt-3.5-turbo"
- },
- {
- "config": {
- "chatConfig": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1
- },
- "model": "claude-3-sonnet-20240229",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": [],
- "systemRole": "As the Assistant and Judge for TOEFL Writing, your primary role is to deal with tasks related to TOEFL Writing.\n\n- You can assist the user with TOEFL Writing, or give the user feedback based on the rubrics and his writing.\n- You need to know that TOFEL Writing has two parts: Integrated Writing and Writing for an Academic Discussion.\n- For Integrated Writing (IW): The writing prompt includes reading passages and listening portions (the user will send the script). The user read a brief text of at least 230 – 300 words on a general or academic topic before listening to a lecture segment on the same subject. User Usersthen asked to summarize what was stated in the lecture and how it assists or weakens the concept of the reading passage in an essay prompt.\n- For Writing for an Academic Discussion (WAD): The question simulates a discussion board on a university website. Students will see a question posted by a professor and two student responses. The student’s job is to read everything and then write their response.\n\n## Rubrics for IW:\n\n- 5 Points (Full Mark): A response at this level successfully selects the important information from the lecture and coherently and accurately presents this information in relation to the relevant information presented in the reading. The response is well organized, and occasional language errors that are present do not result in inaccurate or imprecise presentation of content or connections.\n- 4 Points: A response at this level is generally good in selecting the important information from the lecture and in coherently and accurately presenting this information in relation to the relevant information in the reading, but it may have minor omission, inaccuracy, vagueness, or imprecision of some content from the lecture or in connection to points made in the reading. A response is also scored at this level if it has more frequent or noticeable minor language errors, as long as such usage and grammatical structures do not result in anything more than an occasional lapse of clarity or in the connection of ideas.\n- 3 Points: A response at this level contains some important information from the lecture and conveys some relevant connection to the reading, but it is marked by one or more of the following:\n - Although the overall response is definitely oriented to the task, it conveys only vague, global, unclear, or somewhat imprecise connection of the points made in the lecture to points made in the reading.\n - The response may omit one major key point made in the lecture.\n - Some key points in the lecture or the reading, or connections between the two, may be incomplete, inaccurate, or imprecise.\n - Errors of usage and/or grammar may be more frequent or may result in noticeably vague expressions or obscured meanings in conveying ideas and connections.\n- 2 Points: A response at this level contains some relevant information from the lecture, but is marked by significant language difficulties or by significant omission or inaccuracy of important ideas from the lecture or in the connections between the lecture and the reading; a response at this level is marked by one or more of the following:\n - The response significantly misrepresents or completely omits the overall connection between the lecture and the reading.\n - The response significantly omits or significantly misrepresents important points made in the lecture.\n - The response contains language errors or expressions that largely obscure connections or meaning at key junctures or that would likely obscure understanding of key ideas for a reader not already familiar with the reading and the lecture.\n- 1 Point: A response at this level is marked by one or more of the following:\n - The response provides little or no meaningful or relevant coherent content from the lecture.\n - The language level of the response is so low that it is difficult to derive meaning.\n- 0 Point: A response at this level merely copies sentences from the reading, rejects the topic or is otherwise not connected to the topic, is written in a foreign language, consists of keystroke characters, or is blank.\n\n## Rubrics for WAD:\n\n- 5 Points: A fully successful response - The response is a relevant and very clearly expressed contribution to the online discussion, and it demonstrates consistent facility in the use of language. A typical response displays the following:\n - Relevant and well-elaborated explanations, exemplifications, and/or details\n - Effective use of a variety of syntactic structures and precise, idiomatic word choice\n - Almost no lexical or grammatical errors other than those expected from a competent writer writing under timed conditions (e.g., common typos or common misspellings or substitutions like there/their)\n- 4 Points: A generally successful response - The response is a relevant contribution to the online discussion, and facility in the use of language allows the writer’s ideas to be easily understood. A typical response displays the following:\n - Relevant and adequately elaborated explanations, exemplifications, and/or details\n - A variety of syntactic structures and appropriate word choice\n - Few lexical or grammatical errors\n- 3 Points: A partially successful response - The response is a mostly relevant and mostly understandable contribution to the online discussion, and there is some facility in the use of language. A typical response displays the following:\n - Elaboration in which part of an explanation, example, or detail may be missing, unclear, or irrelevant\n - Some variety in syntactic structures and a range of vocabulary\n - Some noticeable lexical and grammatical errors in sentence structure, word form, or use of idiomatic language\n- 2 Points: A mostly unsuccessful response - The response reflects an attempt to contribute to the online discussion, but limitations in the use of language may make ideas hard to follow. A typical response displays the following:\n - Ideas that may be poorly elaborated or only partially relevant\n - A limited range of syntactic structures and vocabulary\n - An accumulation of errors in sentence structure, word forms, or use\n- 1 Point: An unsuccessful response - The response reflects an ineffective attempt to contribute to the online discussion, and limitations in the use of language may prevent the expression of ideas. A typical response may display the following:\n - Words and phrases that indicate an attempt to address the task but with few or no coherent ideas\n - Severely limited range of syntactic structures and vocabulary\n - Serious and frequent errors in the use of language\n - Minimal original language; any coherent language is mostly borrowed from the stimulus.\n- 0 Point: The response is blank, rejects the topic, is not in English, is entirely copied from the prompt, is entirely unconnected to the prompt, or consists of arbitrary keystrokes.\n\nDepending on minor factors, the score can fall between two points, and you need to take a decimal, such as: 4.25 or 4.5, depending on the other details.\n\n### Score Conversion Rules:\n\n- 4-5 Points → Scaled Score: 24-30\n- 3-4 Points → Scaled Score: 17-23\n- 2-3 Points → Scaled Score: 13-16\n- 1-2 Points → Scaled Score: 7-12\n- 0-1 Point → Scaled Score: 1-6\n- 0 Point → Scaled Score: 0\n\n// Since the scaled score is a range, you should judge more carefully about the specific score the user falls in the scaled range, like 26.\n\n## Feedback format:\n\n ## Raw Score: [RAW SCORE]\n ## Scaled Score: [SCALED SPECIFIC SCORE]\n In your writing, ...[Specific problems in user's writing(Use bullet list)]\n",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": {
- "openai": "alloy"
- }
- },
- "provider": "anthropic"
- },
- "group": "default",
- "meta": {
- "avatar": "📝",
- "description": "Your TOEFL Writing assistant and evaluator, specializing in feedback and guidance.",
- "tags": ["writing", "study"],
- "title": "TOEFL Writing Tutor"
- },
- "type": "agent",
- "createdAt": 1706114617725,
- "id": "711618cf-a5a8-40c8-821f-aff8f82db584",
- "updatedAt": 1709655104241,
- "pinned": true,
- "model": "claude-3-sonnet-20240229"
- }
- ]
- },
- "version": 6
-}
diff --git a/src/migrations/FromV5ToV6/index.ts b/src/migrations/FromV5ToV6/index.ts
deleted file mode 100644
index 3110ae8545b..00000000000
--- a/src/migrations/FromV5ToV6/index.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-
-import { V5ConfigState, V5Session } from './types/v5';
-import { V6ConfigState, V6Session } from './types/v6';
-
-export class MigrationV5ToV6 implements Migration {
- // from this version to start migration
- version = 5;
-
- migrate(data: MigrationData<V5ConfigState>): MigrationData<V6ConfigState> {
- const { sessions } = data.state;
-
- return {
- ...data,
- state: {
- ...data.state,
- sessions: MigrationV5ToV6.migrateSession(sessions),
- },
- };
- }
- static migrateChatConfig(config: V5Session['config']): V6Session['config'] {
- const {
- autoCreateTopicThreshold,
- enableAutoCreateTopic,
- compressThreshold,
- enableCompressThreshold,
- enableHistoryCount,
- enableMaxTokens,
- historyCount,
- inputTemplate,
- displayMode,
- ...agentConfig
- } = config;
-
- return {
- ...agentConfig,
- chatConfig: {
- autoCreateTopicThreshold,
- compressThreshold,
- displayMode,
- enableAutoCreateTopic,
- enableCompressThreshold,
- enableHistoryCount,
- enableMaxTokens,
- historyCount,
- inputTemplate,
- },
- };
- }
-
- static migrateSession(sessions: V5Session[]): V6Session[] {
- return sessions.map(({ config, updateAt, updatedAt, createdAt, createAt, ...res }) => ({
- ...res,
- config: MigrationV5ToV6.migrateChatConfig(config),
- createdAt: createdAt || createAt!,
- updatedAt: updatedAt || updateAt!,
- }));
- }
-}
-
-export const MigrationAgentChatConfig = MigrationV5ToV6;
diff --git a/src/migrations/FromV5ToV6/migrations.test.ts b/src/migrations/FromV5ToV6/migrations.test.ts
deleted file mode 100644
index 8429624e9b2..00000000000
--- a/src/migrations/FromV5ToV6/migrations.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe } from 'vitest';
-
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import { MigrationV1ToV2 } from '../FromV1ToV2';
-import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
-import { MigrationV2ToV3 } from '../FromV2ToV3';
-import { MigrationV3ToV4 } from '../FromV3ToV4';
-import { MigrationV4ToV5 } from '../FromV4ToV5';
-import outputDataFromV1ToV6 from './fixtures/from-v1-to-v6-output.json';
-import sessionInputV5 from './fixtures/session-input-v5.json';
-import sessionOutputV6 from './fixtures/session-output-v6.json';
-import { MigrationV5ToV6 } from './index';
-
-describe('MigrationV5ToV6', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV5ToV6];
- versionController = new VersionController(migrations, 6);
- });
-
- describe('should migrate data correctly from previous versions', () => {
- it('session config', () => {
- const data: MigrationData = sessionInputV5;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(sessionOutputV6.version);
- expect(migratedData.state.sessions).toEqual(sessionOutputV6.state.sessions);
- });
- });
-
- it('should work correct from v1 to v6', () => {
- const data: MigrationData = inputV1Data;
-
- versionController = new VersionController(
- [MigrationV5ToV6, MigrationV4ToV5, MigrationV3ToV4, MigrationV2ToV3, MigrationV1ToV2],
- 6,
- );
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputDataFromV1ToV6.version);
- expect(migratedData.state.messages).toEqual(outputDataFromV1ToV6.state.messages);
- expect(migratedData.state.sessions).toEqual(outputDataFromV1ToV6.state.sessions);
- expect(migratedData.state.topics).toEqual(outputDataFromV1ToV6.state.topics);
- });
-});
diff --git a/src/migrations/FromV5ToV6/types/v5.ts b/src/migrations/FromV5ToV6/types/v5.ts
deleted file mode 100644
index 1aa8c5bf6e7..00000000000
--- a/src/migrations/FromV5ToV6/types/v5.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { FewShots, LobeAgentTTSConfig } from '@lobechat/types';
-import { LLMParams } from 'model-bank';
-
-/**
- * Lobe Agent
- */
-export interface V5Session {
- config: V5AgentConfig;
- createAt?: number;
- createdAt: number;
- group?: string;
- id: string;
- meta: {
- avatar?: string;
- backgroundColor?: string;
- description?: string;
- tags?: string[];
- title?: string;
- };
- model: string;
- pinned?: boolean;
- type: 'agent';
- updateAt?: number;
- updatedAt: number;
-}
-
-export interface V5AgentConfig {
- autoCreateTopicThreshold: number;
- compressThreshold?: number;
- displayMode?: 'chat' | 'docs';
- enableAutoCreateTopic: boolean;
- enableCompressThreshold?: boolean;
- enableHistoryCount?: boolean;
- enableMaxTokens?: boolean;
- fewShots?: FewShots;
- historyCount?: number;
- inputTemplate?: string;
- model: string;
- params: LLMParams;
- plugins?: string[];
- provider?: string;
- systemRole: string;
- tts: LobeAgentTTSConfig;
-}
-
-export interface V5ConfigState {
- sessions: V5Session[];
-}
diff --git a/src/migrations/FromV5ToV6/types/v6.ts b/src/migrations/FromV5ToV6/types/v6.ts
deleted file mode 100644
index aaeb32edfb0..00000000000
--- a/src/migrations/FromV5ToV6/types/v6.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { FewShots } from '@lobechat/types';
-import { LLMParams } from 'model-bank';
-
-export type TTSServer = 'openai' | 'edge' | 'microsoft';
-
-export interface TTSConfig {
- showAllLocaleVoice?: boolean;
- sttLocale: 'auto' | string;
- ttsService: TTSServer;
- voice: {
- edge?: string;
- microsoft?: string;
- openai: string;
- };
-}
-
-export interface ChatConfig {
- autoCreateTopicThreshold: number;
- compressThreshold?: number;
- displayMode?: 'chat' | 'docs';
- enableAutoCreateTopic?: boolean;
- enableCompressThreshold?: boolean;
- enableHistoryCount?: boolean;
- enableMaxTokens?: boolean;
- historyCount?: number;
- inputTemplate?: string;
-}
-
-export interface V6AgentConfig {
- chatConfig: ChatConfig;
- fewShots?: FewShots;
- model: string;
- openingMessage?: string;
- openingQuestions?: string[];
- params: LLMParams;
- plugins?: string[];
- provider?: string;
- systemRole: string;
- tts: TTSConfig;
-}
-
-export interface V6Session {
- config: V6AgentConfig;
- createdAt: number;
-
- group?: string;
- id: string;
- meta: {
- avatar?: string;
- backgroundColor?: string;
- description?: string;
- tags?: string[];
- title?: string;
- };
- model: string;
- pinned?: boolean;
- type: 'agent';
- updatedAt: number;
-}
-
-export interface V6ConfigState {
- sessions: V6Session[];
-}
diff --git a/src/migrations/FromV6ToV7/fixtures/output-v7-from-v1.json b/src/migrations/FromV6ToV7/fixtures/output-v7-from-v1.json
deleted file mode 100644
index 7005fe12153..00000000000
--- a/src/migrations/FromV6ToV7/fixtures/output-v7-from-v1.json
+++ /dev/null
@@ -1,203 +0,0 @@
-{
- "exportType": "sessions",
- "state": {
- "sessions": [
- {
- "config": {
- "displayMode": "chat",
- "historyCount": 1,
- "model": "gpt-3.5-turbo",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1,
- "max_tokens": 2200
- },
- "plugins": [],
- "systemRole": "你是一名 Postgresql 的数据库专家。用户是一名数据库小白,你需要使用简单直白的方式告诉用户如何使用 ostgresql 和它相应的 orm 工具 primsa",
- "enableCompressThreshold": false,
- "enableMaxTokens": false,
- "inputTemplate": ""
- },
- "createdAt": 1698463356269,
- "id": "06cc3e20-e870-4099-a619-c07a849d742d",
- "meta": {
- "avatar": "🐘",
- "backgroundColor": "rgba(0,0,0,0)",
- "title": "Postgresql 指南",
- "description": "PostgreSQL 数据库和 Prisma ORM 工具的简单使用指南",
- "tags": ["数据库", "PostgreSQL", "教程", "ORM", "Prisma"]
- },
- "type": "agent",
- "updatedAt": 1698463356269,
- "group": "default",
- "pinned": true
- }
- ],
- "topics": [
- {
- "createdAt": 1698463911747,
- "id": "CZg3IEdy",
- "title": "Prisma中的cuid函数作用是什么",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698463915716
- },
- {
- "createdAt": 1698754463117,
- "id": "MNWhBEh5",
- "title": "启动 PostgreSQL Docker 镜像方法",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1698754464867
- }
- ],
- "messages": [
- {
- "content": "是的,你可以使用 Prisma 来自定义生成 `id` 的逻辑,例如使用 `nanoid` 库来生成唯一标识符。\n\n首先,你需要在项目中安装 `nanoid` 库:\n\n```\nnpm install nanoid\n```\n\n然后,你可以在 Prisma 的模型定义中使用 `@default` 指令,并提供一个自定义的默认值函数来生成 `id`。\n\n```prisma\nmodel Message {\n id String @id @default(dbgenerated(\"nanoid(10)\"))\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n在上述模型定义中,我们使用 `dbgenerated` 指令来定义一个自定义的默认值函数。函数 `nanoid(10)` 会生成一个长度为 10 的唯一标识符。\n\n请注意,使用自定义的 `id` 生成逻辑可能会对数据库性能产生一些影响,因为每次创建新记录时都需要执行自定义函数。因此,请确保你的自定义逻辑是高效的,并在实际使用中进行测试和评估性能。",
- "createdAt": 1698463981313,
- "id": "n2Tsl3Dm",
- "meta": {},
- "parentId": "JSZaJOGj",
- "role": "assistant",
- "updatedAt": 1698464004494,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定 自定义函数的引入位置?",
- "createdAt": 1698464173224,
- "id": "xPft8Msa",
- "meta": {},
- "role": "user",
- "updatedAt": 1698464173226,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy"
- },
- {
- "content": "在 Prisma 中,你可以通过在 `schema.prisma` 文件的顶部使用 `generator` 块来指定自定义函数的引入位置。\n\n例如,假设你想使用 `nanoid` 库来生成自定义的 `id`,你可以按照以下方式配置:\n\n```prisma\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./node_modules/@prisma/client\"\n}\n\ngenerator dbgenerated {\n provider = \"prisma-dbgenerator\"\n output = \"./node_modules/@prisma/client\"\n binaryTargets = [\"native\"]\n previewFeatures = [\"nativeTypes\"]\n config = {\n \"generator\": {\n \"dbgenerated\": {\n \"output\": \"./src/db/generated\",\n \"provider\": \"./src/db/generated/provider.js\"\n }\n }\n }\n}\n```\n\n在上述配置中,我们定义了两个生成器。`client` 生成器用于生成 Prisma 客户端代码,而 `dbgenerated` 生成器用于生成数据库相关的代码。\n\n注意到 `dbgenerated` 生成器的 `config` 部分中有一个 `provider` 字段,它指定了自定义函数的引入位置。在这个示例中,我们将自定义函数放在 `./src/db/generated/provider.js` 文件中。\n\n你可以根据你的项目结构和需要来调整路径和文件名,确保指定的 `provider` 路径正确引入了自定义函数。",
- "createdAt": 1698464173228,
- "id": "jZc2KKRs",
- "meta": {},
- "parentId": "xPft8Msa",
- "role": "assistant",
- "updatedAt": 1698464181896,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "CZg3IEdy",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何启动一个 postgres Docker 镜像?",
- "createdAt": 1698754460196,
- "id": "LjG9XSuq",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754463118,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动一个 PostgreSQL Docker 镜像,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,可以在终端中运行 `docker --version` 来检查。\n\n2. 在终端中运行以下命令以下载并启动一个 PostgreSQL 镜像:\n\n ```shell\n docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres\n ```\n\n 这将从 Docker Hub 下载 PostgreSQL 镜像",
- "createdAt": 1698754479751,
- "id": "CL7E1Mc5",
- "meta": {},
- "parentId": "LjG9XSuq",
- "role": "assistant",
- "updatedAt": 1698754507690,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "如何指定本地存储的目录到 /www/database/postgres",
- "createdAt": 1698754591763,
- "id": "UIvHZr7m",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754591764,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要将本地存储的目录映射到容器内的 `/var/lib/postgresql/data` 目录,你可以使用 Docker 的 `-v` 参数。\n\n以下是示例命令:\n\n```shell\ndocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres\n```\n\n在这个命令中,我们使用了 `-v` 参数来指定本地目录 `/www/database/postgres` 映射到容器内的 `/var/lib/postgresql/data` 目录。这样,所有的 PostgreSQL 数据将会保存在本地指定的目录中。",
- "createdAt": 1698754591765,
- "id": "XLJOK44r",
- "meta": {},
- "parentId": "UIvHZr7m",
- "role": "assistant",
- "updatedAt": 1698754609275,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "docker run --name postgres -e POSTGRES_PASSWORD=DSLapHYdzNrai5j6 -p 33300:5432 -v /www/database/postgres:/var/lib/postgresql/data -d postgres",
- "createdAt": 1698754700529,
- "id": "W3J6jQjm",
- "meta": {},
- "role": "user",
- "updatedAt": 1698754700530,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "如何启动 pgadmin",
- "createdAt": 1698755749886,
- "id": "L7mq0ehV",
- "meta": {},
- "role": "user",
- "updatedAt": 1698755749888,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5"
- },
- {
- "content": "要启动 pgAdmin,你可以按照以下步骤操作:\n\n1. 首先,确保你已经安装了 Docker,并且已经成功启动了 PostgreSQL Docker 容器。\n\n2. 在终端中运行以下命令以启动 pgAdmin Docker 容器:\n\n ```shell\n docker run --name my-pgadmin -p 5050:80 -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=mypassword -d dpage/pgadmin4\n ```\n\n 在这个命令中,我们使用了 `-p` 参数来将容器的端口 80 映射到本地的端口 5050。你可以根据需要修改这个端口映射。\n\n 我们还使用了 `-e` 参数来设置 pgAdmin 的默认登录邮箱和密码。你可以根据需要修改这些值。\n\n3. 在浏览器中访问 `http://localhost:5050`,你将看到 pgAdmin 的登录界面。\n\n4. 使用在上一步中设置的邮箱和密码进行登录。\n\n5. 在 pgAdmin 中,你可以添加一个新的服务器连接,以连接到运行在 Docker 容器中的 PostgreSQL 数据库。要添加一个新的服务器连接,你需要提供以下信息:\n\n - 主机名/地址:使用 Docker 容器的 IP 地址或者 `localhost`。\n - 端口:使用 Docker 容器中 PostgreSQL 的映射端口,例如 33300。\n - 用户名和密码:使用在启动 PostgreSQL 容器时设置的用户名和密码。\n\n 完成上述信息的填写后,点击保存并连接到 PostgreSQL 服务器。\n\n现在,你已经成功启动了 pgAdmin 并连接到了你的 PostgreSQL 数据库。你可以使用 pgAdmin 来管理和操作你的数据库。",
- "createdAt": 1698755749889,
- "id": "d5XTX9EQ",
- "meta": {},
- "parentId": "L7mq0ehV",
- "role": "assistant",
- "updatedAt": 1698755786183,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "topicId": "MNWhBEh5",
- "fromModel": "gpt-3.5-turbo"
- },
- {
- "content": "abcabc",
- "createdAt": 1690650544852,
- "id": "KPPDiRyW",
- "meta": {},
- "parentId": "42k72jMi",
- "role": "function",
- "updatedAt": 1690650572399,
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
-
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "websiteCrawler",
- "arguments": "{\n \"url\": \"https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651264337&idx=1&sn=d7d9126578c74c912e1f0d42cb5629da&chksm=bd48ccd58a3f45c3f2cbc7d7b732c820b9e7cd6b547c06acc8170b233710b5fb5ed62f5fd94d&mpshare=1&scene=1&srcid=07294Mpw7C6JCLgtagL1cBDR&sharer_sharetime=1690622712877&sharer_shareid=0358058a42fc25387d28337fc3d22c3c#rd\"\n}",
- "identifier": "websiteCrawler",
- "type": "default"
- }
- },
- {
- "content": "bbbbb",
- "createdAt": 1700065743405,
- "id": "9cRjevRQ",
- "meta": {},
- "parentId": "3nDXtEKv",
- "role": "function",
- "sessionId": "06cc3e20-e870-4099-a619-c07a849d742d",
- "updatedAt": 1700065751861,
- "fromModel": "gpt-3.5-turbo-16k",
- "plugin": {
- "apiName": "getWebsiteContent",
- "arguments": "{\n \"url\": \"https://nodejs.org/api/packages.html#dual-package-hazard\"\n}",
- "identifier": "website-crawler",
- "type": "default"
- }
- }
- ]
- },
- "version": 7
-}
diff --git a/src/migrations/FromV6ToV7/fixtures/provider-input-v6.json b/src/migrations/FromV6ToV7/fixtures/provider-input-v6.json
deleted file mode 100644
index ba80a508282..00000000000
--- a/src/migrations/FromV6ToV7/fixtures/provider-input-v6.json
+++ /dev/null
@@ -1,103 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "password": "213455",
- "languageModel": {
- "anthropic": { "apiKey": "anthropic", "enabled": false, "endpoint": "anthropic-baseURL" },
- "azure": {
- "apiKey": "asbdasd",
- "apiVersion": "2024-02-15-preview",
- "enabled": true,
- "endpoint": "https://api.chatanywhere.com.cn"
- },
- "bedrock": {
- "accessKeyId": "accessKeyId",
- "enabled": false,
- "region": "us-east-1",
- "secretAccessKey": "secretAccessKey"
- },
- "google": { "apiKey": "google", "enabled": false, "endpoint": "google-baseURL" },
- "deepseek": { "apiKey": "deepseek", "enabled": true },
- "groq": { "apiKey": "groq", "enabled": false, "endpoint": "groq-baseURL" },
- "mistral": { "apiKey": "mistral", "enabled": false },
- "moonshot": { "apiKey": "moonshot", "enabled": false },
- "ollama": { "enabled": false, "endpoint": "http://1237.0.0.1:3245" },
- "openrouter": {
- "apiKey": "openrouter-key",
- "enabled": true,
- "customModelCards": [
- {
- "displayName": "01-ai/yi-34b-chat",
- "enabled": true,
- "id": "01-ai/yi-34b-chat"
- },
- {
- "displayName": "huggingfaceh4/zephyr-7b-beta",
- "enabled": true,
- "id": "huggingfaceh4/zephyr-7b-beta"
- }
- ]
- },
- "perplexity": {
- "apiKey": "perplexity",
- "enabled": false,
- "endpoint": "perplexity-baseURL"
- },
- "togetherai": { "apiKey": "togetherai", "enabled": false },
- "zeroone": { "apiKey": "zeroone", "enabled": false },
- "zhipu": { "apiKey": "zhipu", "enabled": false },
- "openai": {
- "apiKey": "openai",
- "endpoint": "endpoint",
- "enabled": true,
- "customModelCards": [
- {
- "displayName": "deerercsds",
- "enabled": true,
- "id": "deerercsds"
- }
- ]
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- },
- "version": 6
-}
diff --git a/src/migrations/FromV6ToV7/fixtures/provider-output-v7.json b/src/migrations/FromV6ToV7/fixtures/provider-output-v7.json
deleted file mode 100644
index 9bf9a8df7e3..00000000000
--- a/src/migrations/FromV6ToV7/fixtures/provider-output-v7.json
+++ /dev/null
@@ -1,118 +0,0 @@
-{
- "exportType": "settings",
- "state": {
- "settings": {
- "defaultAgent": {
- "config": {
- "autoCreateTopicThreshold": 2,
- "displayMode": "chat",
- "enableAutoCreateTopic": true,
- "historyCount": 1,
- "model": "gpt-4-vision-preview",
- "params": {
- "frequency_penalty": 0,
- "presence_penalty": 0,
- "temperature": 0.6,
- "top_p": 1
- },
- "plugins": ["realtime-weather", "steam"],
- "provider": "openai",
- "systemRole": "",
- "tts": {
- "showAllLocaleVoice": false,
- "sttLocale": "auto",
- "ttsService": "openai",
- "voice": { "openai": "alloy" }
- }
- },
- "meta": {}
- },
- "languageModel": {
- "anthropic": { "enabled": false },
- "azure": { "enabled": true },
- "bedrock": { "enabled": false },
- "google": { "enabled": false },
- "deepseek": { "enabled": true },
- "groq": { "enabled": false },
- "mistral": { "enabled": false },
- "moonshot": { "enabled": false },
- "ollama": { "enabled": false },
- "openrouter": {
- "enabled": true,
- "customModelCards": [
- {
- "displayName": "01-ai/yi-34b-chat",
- "enabled": true,
- "id": "01-ai/yi-34b-chat"
- },
- {
- "displayName": "huggingfaceh4/zephyr-7b-beta",
- "enabled": true,
- "id": "huggingfaceh4/zephyr-7b-beta"
- }
- ]
- },
- "perplexity": { "enabled": false },
- "togetherai": { "enabled": false },
- "zeroone": { "enabled": false },
- "zhipu": { "enabled": false },
- "openai": {
- "enabled": true,
- "customModelCards": [
- {
- "displayName": "deerercsds",
- "enabled": true,
- "id": "deerercsds"
- }
- ]
- }
- },
- "keyVaults": {
- "password": "213455",
- "anthropic": { "apiKey": "anthropic", "baseURL": "anthropic-baseURL" },
- "azure": {
- "apiKey": "asbdasd",
- "apiVersion": "2024-02-15-preview",
- "endpoint": "https://api.chatanywhere.com.cn"
- },
- "bedrock": {
- "accessKeyId": "accessKeyId",
- "region": "us-east-1",
- "secretAccessKey": "secretAccessKey"
- },
- "google": { "apiKey": "google", "baseURL": "google-baseURL" },
- "groq": { "apiKey": "groq", "baseURL": "groq-baseURL" },
- "mistral": { "apiKey": "mistral" },
- "moonshot": { "apiKey": "moonshot" },
- "ollama": { "baseURL": "http://1237.0.0.1:3245" },
- "openrouter": {
- "apiKey": "openrouter-key"
- },
- "perplexity": { "apiKey": "perplexity", "baseURL": "perplexity-baseURL" },
- "togetherai": { "apiKey": "togetherai" },
- "deepseek": { "apiKey": "deepseek" },
- "zeroone": { "apiKey": "zeroone" },
- "zhipu": { "apiKey": "zhipu" },
- "openai": {
- "apiKey": "openai",
- "baseURL": "endpoint"
- }
- },
- "sync": { "webrtc": { "enabled": false } },
- "tool": { "dalle": { "autoGenerate": false } },
- "tts": {
- "openAI": { "sttModel": "whisper-1", "ttsModel": "tts-1" },
- "sttAutoStop": true,
- "sttServer": "openai"
- },
- "general": {
- "fontSize": 14,
- "language": "auto",
- "themeMode": "auto",
- "primaryColor": "",
- "neutralColor": ""
- }
- }
- },
- "version": 7
-}
diff --git a/src/migrations/FromV6ToV7/index.ts b/src/migrations/FromV6ToV7/index.ts
deleted file mode 100644
index 410f6ceffa1..00000000000
--- a/src/migrations/FromV6ToV7/index.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import type { Migration, MigrationData } from '@/migrations/VersionController';
-
-import { V6ConfigState, V6Settings } from './types/v6';
-import { V7ConfigState, V7KeyVaults, V7Settings } from './types/v7';
-
-const SENSITIVE_KEYS = [
- 'apiKey',
- 'endpoint',
- 'accessKeyId',
- 'secretAccessKey',
- 'apiVersion',
- 'region',
-];
-
-type SensitiveKeys = (typeof SENSITIVE_KEYS)[number];
-
-function extractSensitiveInfo<T extends Record<string, any>>(
- obj: T,
- sensitiveKeys: SensitiveKeys[],
- provider: string,
-): [T, Record<SensitiveKeys, string>] {
- const keyVaults: Record<SensitiveKeys, string> = {} as any;
-
- sensitiveKeys.forEach((key) => {
- if (obj[key]) {
- if (key === 'endpoint' && provider !== 'azure') {
- keyVaults['baseURL'] = obj[key];
- } else {
- keyVaults[key] = obj[key];
- }
-
- delete obj[key];
- }
- });
-
- return [obj, keyVaults];
-}
-
-export class MigrationV6ToV7 implements Migration {
- // from this version to start migration
- version = 6;
-
- migrate(data: MigrationData<V6ConfigState>): MigrationData<V7ConfigState> {
- const { settings } = data.state;
-
- return {
- ...data,
- state: {
- ...data.state,
- settings: !settings ? undefined : MigrationV6ToV7.migrateSettings(settings),
- },
- };
- }
-
- static migrateSettings = (settings: V6Settings): V7Settings => {
- const {
- languageModel = {},
- password,
- neutralColor,
- themeMode,
- fontSize,
- primaryColor,
- language,
- ...res
- } = settings;
-
- const keyVaults = {
- password,
- } as V7KeyVaults;
-
- Object.entries(languageModel).forEach(([provider, config]) => {
- if (!config) return;
-
- const [strippedConfig, providerVaults] = extractSensitiveInfo(
- config,
- SENSITIVE_KEYS,
- provider,
- );
-
- // @ts-ignore
- languageModel[provider] = strippedConfig as any;
- // @ts-ignore
- keyVaults[provider] = providerVaults;
- });
-
- return {
- ...res,
- general: {
- fontSize,
- language,
- neutralColor,
- primaryColor,
- themeMode,
- },
- keyVaults,
- languageModel,
- };
- };
-}
-
-export const MigrationKeyValueSettings = MigrationV6ToV7;
diff --git a/src/migrations/FromV6ToV7/migrations.test.ts b/src/migrations/FromV6ToV7/migrations.test.ts
deleted file mode 100644
index f6c40898e4d..00000000000
--- a/src/migrations/FromV6ToV7/migrations.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe } from 'vitest';
-
-import { MigrationV1ToV2 } from '@/migrations/FromV1ToV2';
-import { MigrationV2ToV3 } from '@/migrations/FromV2ToV3';
-import { MigrationV3ToV4 } from '@/migrations/FromV3ToV4';
-import { MigrationV4ToV5 } from '@/migrations/FromV4ToV5';
-import { MigrationV5ToV6 } from '@/migrations/FromV5ToV6';
-import { MigrationData, VersionController } from '@/migrations/VersionController';
-
-import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
-import outputV7Data from './fixtures/output-v7-from-v1.json';
-import providerInputV6 from './fixtures/provider-input-v6.json';
-import providerOutputV7 from './fixtures/provider-output-v7.json';
-import { MigrationV6ToV7 } from './index';
-
-describe('MigrationV6ToV7', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [MigrationV6ToV7];
- versionController = new VersionController(migrations, 7);
- });
-
- describe('should migrate data correctly from previous versions', () => {
- it('provider', () => {
- const data: MigrationData = providerInputV6;
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(providerOutputV7.version);
- expect(migratedData.state.settings.languageModel).toEqual(
- providerOutputV7.state.settings.languageModel,
- );
- expect(migratedData.state.settings.keyVaults).toEqual(
- providerOutputV7.state.settings.keyVaults,
- );
- expect(migratedData.state.settings.general).toEqual(providerOutputV7.state.settings.general);
- });
- });
-
- it('should work correct from v1 to v7', () => {
- const data: MigrationData = inputV1Data;
-
- versionController = new VersionController(
- [
- MigrationV6ToV7,
- MigrationV5ToV6,
- MigrationV4ToV5,
- MigrationV3ToV4,
- MigrationV2ToV3,
- MigrationV1ToV2,
- ],
- 7,
- );
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData.version).toEqual(outputV7Data.version);
- // expect(migratedData.state.sessions).toEqual(outputV3DataFromV1.state.sessions);
- // expect(migratedData.state.topics).toEqual(outputV3DataFromV1.state.topics);
- // expect(migratedData.state.messages).toEqual(outputV3DataFromV1.state.messages);
- });
-});
diff --git a/src/migrations/FromV6ToV7/types/v6.ts b/src/migrations/FromV6ToV7/types/v6.ts
deleted file mode 100644
index 4c8cd4d622e..00000000000
--- a/src/migrations/FromV6ToV7/types/v6.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-interface V6OpenAICompatibleConfig {
- apiKey?: string;
- autoFetchModelLists?: boolean;
- customModelCards?: any[];
- enabled: boolean;
- enabledModels?: string[] | null;
- endpoint?: string;
- fetchOnClient?: boolean;
- latestFetchTime?: number;
- remoteModelCards?: any[];
-}
-
-interface AzureOpenAIConfig extends Omit<V6OpenAICompatibleConfig, 'endpoint'> {
- apiVersion?: string;
- endpoint?: string;
-}
-
-interface AWSBedrockConfig extends Omit<V6OpenAICompatibleConfig, 'apiKey' | 'endpoint'> {
- accessKeyId?: string;
- region?: string;
- secretAccessKey?: string;
-}
-
-interface V6ModelProviderConfig {
- anthropic: V6OpenAICompatibleConfig;
- azure: AzureOpenAIConfig;
- bedrock: AWSBedrockConfig;
- deepseek: V6OpenAICompatibleConfig;
- google: V6OpenAICompatibleConfig;
- groq: V6OpenAICompatibleConfig;
- minimax: V6OpenAICompatibleConfig;
- mistral: V6OpenAICompatibleConfig;
- moonshot: V6OpenAICompatibleConfig;
- ollama: V6OpenAICompatibleConfig;
- openai: V6OpenAICompatibleConfig;
- openrouter: V6OpenAICompatibleConfig;
- perplexity: V6OpenAICompatibleConfig;
- togetherai: V6OpenAICompatibleConfig;
- zeroone: V6OpenAICompatibleConfig;
- zhipu: V6OpenAICompatibleConfig;
-}
-
-export type V6ProviderKey = keyof V6ModelProviderConfig;
-
-export interface V6Settings {
- defaultAgent: any;
- fontSize: number;
- language: string;
- languageModel?: V6ModelProviderConfig;
- neutralColor?: string;
- password: string;
- primaryColor?: string;
- sync: any;
- themeMode: string;
- tool: any;
- tts: any;
-}
-
-export interface V6ConfigState {
- settings?: V6Settings;
-}
diff --git a/src/migrations/FromV6ToV7/types/v7.ts b/src/migrations/FromV6ToV7/types/v7.ts
deleted file mode 100644
index c3fc6989901..00000000000
--- a/src/migrations/FromV6ToV7/types/v7.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-interface OpenAICompatibleKeyVault {
- apiKey?: string;
- baseURL?: string;
-}
-interface AzureOpenAIKeyVault {
- apiKey?: string;
- apiVersion?: string;
- endpoint?: string;
-}
-
-export interface AWSBedrockKeyVault {
- accessKeyId?: string;
- region?: string;
- secretAccessKey?: string;
-}
-
-export interface V7KeyVaults {
- anthropic: OpenAICompatibleKeyVault;
- azure: AzureOpenAIKeyVault;
- bedrock: AWSBedrockKeyVault;
- deepseek: OpenAICompatibleKeyVault;
- google: OpenAICompatibleKeyVault;
- groq: OpenAICompatibleKeyVault;
- minimax: OpenAICompatibleKeyVault;
- mistral: OpenAICompatibleKeyVault;
- moonshot: OpenAICompatibleKeyVault;
- ollama: OpenAICompatibleKeyVault;
- openai: OpenAICompatibleKeyVault;
- openrouter: OpenAICompatibleKeyVault;
- password: string;
- perplexity: OpenAICompatibleKeyVault;
- togetherai: OpenAICompatibleKeyVault;
- zeroone: OpenAICompatibleKeyVault;
- zhipu: OpenAICompatibleKeyVault;
-}
-
-interface V7ProviderConfig {
- autoFetchModelLists?: boolean;
- customModelCards?: any[];
- enabled: boolean;
- enabledModels?: string[] | null;
- fetchOnClient?: boolean;
- latestFetchTime?: number;
- remoteModelCards?: any[];
-}
-
-export type V7ModelProviderConfig = Record<string, V7ProviderConfig>;
-
-export interface V7GeneralSettings {
- fontSize: number;
- language: string;
- neutralColor?: string;
- primaryColor?: string;
- themeMode: string;
-}
-
-export interface V7Settings {
- defaultAgent: any;
- general: V7GeneralSettings;
- keyVaults: V7KeyVaults;
- languageModel?: V7ModelProviderConfig;
- sync: any;
- tool: any;
- tts: any;
-}
-
-export interface V7ConfigState {
- settings?: V7Settings;
-}
diff --git a/src/migrations/VersionController.test.ts b/src/migrations/VersionController.test.ts
deleted file mode 100644
index 0c1d1a21610..00000000000
--- a/src/migrations/VersionController.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { Migration, MigrationData, VersionController } from './VersionController';
-
-class TestMigration0 implements Migration {
- version = 0;
-
- migrate(data: MigrationData): MigrationData {
- return data;
- }
-}
-class TestMigration1 implements Migration {
- version = 1;
-
- migrate(data: MigrationData): MigrationData {
- return {
- state: {
- ...data.state,
- value1: data.state.value * 2,
- },
- version: this.version,
- };
- }
-}
-
-class TestMigration2 implements Migration {
- version = 2;
-
- migrate(data: MigrationData): MigrationData {
- return {
- state: {
- ...data.state,
- value2: data.state.value1 * 2,
- },
- version: this.version,
- };
- }
-}
-
-describe('VersionController', () => {
- let migrations;
- let versionController: VersionController<any>;
-
- beforeEach(() => {
- migrations = [TestMigration0, TestMigration1, TestMigration2];
- versionController = new VersionController(migrations);
- });
-
- it('should instantiate with sorted migrations', () => {
- expect(versionController['migrations'][0].version).toBe(0);
- expect(versionController['migrations'][1].version).toBe(1);
- expect(versionController['migrations'][2].version).toBe(2);
- });
-
- it('should throw error if data version is undefined', () => {
- const data = {
- state: { value: 10 },
- };
-
- expect(() => versionController.migrate(data as any)).toThrow();
- });
-
- it('should migrate data correctly through multiple versions', () => {
- const data: MigrationData = {
- state: { value: 10 },
- version: 0,
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData).toEqual({
- state: { value: 10, value1: 20, value2: 40 },
- version: 3,
- });
- });
-
- it('should migrate data correctly if starting from a specific version', () => {
- const data: MigrationData = {
- state: { value: 10, value1: 20 },
- version: 1,
- };
-
- const migratedData = versionController.migrate(data);
-
- expect(migratedData).toEqual({
- state: { value: 10, value1: 20, value2: 40 },
- version: 3,
- });
- });
-});
diff --git a/src/migrations/VersionController.ts b/src/migrations/VersionController.ts
deleted file mode 100644
index a371d14def2..00000000000
--- a/src/migrations/VersionController.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { t } from 'i18next';
-
-/**
- * 迁移接口
- * @template T - 状态类型
- */
-export interface Migration<T = any> {
- /**
- * 迁移数据
- * @param data - 迁移数据
- * @returns 迁移后的数据
- */
- migrate(data: MigrationData<T>): MigrationData;
- /**
- * 迁移版本号
- */
- version: number;
-}
-
-/**
- * 迁移数据接口
- * @template T - 状态类型
- */
-export interface MigrationData<T = any> {
- /**
- * 状态数据
- */
- state: T;
- /**
- * 迁移版本号
- */
- version: number;
-}
-export class VersionController<T> {
- private migrations: Migration[];
- targetVersion: number;
-
- constructor(migrations: any[], targetVersion: number = migrations.length) {
- this.migrations = migrations
- .map((cls) => {
- return new cls() as Migration;
- })
- .sort((a, b) => a.version - b.version);
-
- this.targetVersion = targetVersion;
- }
-
- migrate(data: MigrationData<T>): MigrationData<T> {
- let nextData = data;
- const targetVersion = this.targetVersion || this.migrations.length;
- if (data.version === undefined)
- throw new Error(t('migrateError.missVersion', { ns: 'migration' }));
- const currentVersion = data.version;
-
- for (let i = currentVersion || 0; i < targetVersion; i++) {
- const migration = this.migrations.find((m) => m.version === i);
- if (!migration) throw new Error(t('migrateError.noMigration', { ns: 'migration' }));
-
- nextData = migration.migrate(nextData);
-
- nextData.version += 1;
- console.debug('迁移器:', migration, '数据:', nextData, '迁移后版本:', nextData.version);
- }
-
- return nextData;
- }
-}
diff --git a/src/migrations/index.ts b/src/migrations/index.ts
deleted file mode 100644
index 5b6ddcf8a32..00000000000
--- a/src/migrations/index.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { MigrationV2ToV3 } from '@/migrations/FromV2ToV3';
-import { VersionController } from '@/migrations/VersionController';
-import { ConfigStateAll } from '@/types/exportConfig';
-
-import { MigrationV0ToV1 } from './FromV0ToV1';
-import { MigrationV1ToV2 } from './FromV1ToV2';
-import { MigrationV3ToV4 } from './FromV3ToV4';
-import { MigrationV4ToV5 } from './FromV4ToV5';
-import { MigrationV5ToV6 } from './FromV5ToV6';
-import { MigrationV6ToV7 } from './FromV6ToV7';
-
-// Current latest version
-export const CURRENT_CONFIG_VERSION = 7;
-
-// Version migrations module
-const ConfigMigrations = [
- /**
- * 2024.05.27
- *
- * apiKey in languageModel change to keyVaults
- */
- MigrationV6ToV7,
- /**
- * 2024.05.24
- *
- * some config in agentConfig change to chatConfig
- */ MigrationV5ToV6,
- /**
- * 2024.05.11
- *
- * role=function to role=tool
- */
- MigrationV4ToV5,
- /**
- * 2024.04.09
- * settings migrate the `languageModel`
- * - from `openAI` to `openai`, `azure`
- * - from customModelName to `enabledModels` and `customModelCards`
- */
- MigrationV3ToV4,
- /**
- * 2024.01.22
- * from `group = pinned` to `pinned:true`
- */
- MigrationV2ToV3,
- /**
- * 2023.11.27
- * 从单 key 数据库转换为基于 dexie 的关系型结构
- */
- MigrationV1ToV2,
- /**
- * 2023.07.11
- * just the first version, Nothing to do
- */
- MigrationV0ToV1,
-];
-
-export const Migration = new VersionController<ConfigStateAll>(
- ConfigMigrations,
- CURRENT_CONFIG_VERSION,
-);
diff --git a/src/server/routers/desktop/mcp.ts b/src/server/routers/desktop/mcp.ts
index c544f4a0d32..c229a86410c 100644
--- a/src/server/routers/desktop/mcp.ts
+++ b/src/server/routers/desktop/mcp.ts
@@ -2,8 +2,6 @@ import { GetStreamableMcpServerManifestInputSchema } from '@lobechat/types';
import debug from 'debug';
import { z } from 'zod';
-import { isServerMode } from '@/const/version';
-import { passwordProcedure } from '@/libs/trpc/edge';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { mcpService } from '@/server/services/mcp';
@@ -24,7 +22,7 @@ const stdioParamsSchema = z.object({
type: z.literal('stdio').default('stdio'),
});
-const mcpProcedure = isServerMode ? authedProcedure : passwordProcedure;
+const mcpProcedure = authedProcedure;
export const mcpRouter = router({
getStdioMcpServerManifest: mcpProcedure.input(stdioParamsSchema).query(async ({ input }) => {
diff --git a/src/server/routers/edge/appStatus.ts b/src/server/routers/edge/appStatus.ts
deleted file mode 100644
index aae9e5c6b1a..00000000000
--- a/src/server/routers/edge/appStatus.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { router } from '@/libs/trpc/edge';
-
-export const appStatusRouter = router({});
diff --git a/src/server/routers/edge/index.ts b/src/server/routers/edge/index.ts
deleted file mode 100644
index e4ee38318a5..00000000000
--- a/src/server/routers/edge/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * @deprecated
- * TODO: it will be remove in V2.0
- */
-import { publicProcedure, router } from '@/libs/trpc/edge';
-
-import { uploadRouter } from './upload';
-
-export const edgeRouter = router({
- healthcheck: publicProcedure.query(() => "i'm live!"),
- upload: uploadRouter,
-});
-
-export type EdgeRouter = typeof edgeRouter;
diff --git a/src/server/routers/edge/upload.ts b/src/server/routers/edge/upload.ts
deleted file mode 100644
index ea8ff41c7b4..00000000000
--- a/src/server/routers/edge/upload.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from 'zod';
-
-import { passwordProcedure, router } from '@/libs/trpc/edge';
-import { S3 } from '@/server/modules/S3';
-
-export const uploadRouter = router({
- createS3PreSignedUrl: passwordProcedure
- .input(z.object({ pathname: z.string() }))
- .mutation(async ({ input }) => {
- const s3 = new S3();
-
- return await s3.createPreSignedUrl(input.pathname);
- }),
-});
-
-export type FileRouter = typeof uploadRouter;
diff --git a/src/server/routers/lambda/config/index.test.ts b/src/server/routers/lambda/config/index.test.ts
index 58eb9c029bd..084a305d197 100644
--- a/src/server/routers/lambda/config/index.test.ts
+++ b/src/server/routers/lambda/config/index.test.ts
@@ -4,8 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* This file contains the root router of your tRPC-backend
*/
-import { createCallerFactory } from '@/libs/trpc/edge';
-import { AuthContext, createContextInner } from '@/libs/trpc/edge/context';
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { AuthContext, createContextInner } from '@/libs/trpc/lambda/context';
import { configRouter } from './index';
diff --git a/src/server/routers/tools/mcp.ts b/src/server/routers/tools/mcp.ts
index 9a73545f86b..05f10d01492 100644
--- a/src/server/routers/tools/mcp.ts
+++ b/src/server/routers/tools/mcp.ts
@@ -1,3 +1,4 @@
+import { isDesktop } from '@lobechat/const';
import {
GetStreamableMcpServerManifestInputSchema,
StreamableHTTPAuthSchema,
@@ -5,8 +6,6 @@ import {
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
-import { isDesktop, isServerMode } from '@/const/version';
-import { passwordProcedure } from '@/libs/trpc/edge';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { mcpService } from '@/server/services/mcp';
@@ -38,7 +37,7 @@ const checkStdioEnvironment = (params: z.infer<typeof mcpClientParamsSchema>) =>
}
};
-const mcpProcedure = isServerMode ? authedProcedure : passwordProcedure;
+const mcpProcedure = authedProcedure;
export const mcpRouter = router({
getStreamableMcpServerManifest: mcpProcedure
diff --git a/src/server/routers/tools/search.test.ts b/src/server/routers/tools/search.test.ts
index 5611b8e610d..42bef5b943c 100644
--- a/src/server/routers/tools/search.test.ts
+++ b/src/server/routers/tools/search.test.ts
@@ -23,13 +23,7 @@ vi.mock('@/server/services/search/impls/searxng/client');
describe('searchRouter', () => {
const mockContext = {
- req: {
- headers: {
- authorization: 'Bearer mock-token',
- },
- },
- authorizationHeader: 'Bearer mock-token',
- jwtPayload: { userId: '1' },
+ userId: 'test-user-id',
};
beforeEach(() => {
diff --git a/src/server/routers/tools/search.ts b/src/server/routers/tools/search.ts
index 67c5cc5b0c4..67c0f723151 100644
--- a/src/server/routers/tools/search.ts
+++ b/src/server/routers/tools/search.ts
@@ -1,12 +1,9 @@
-import { isServerMode } from '@lobechat/const';
import { z } from 'zod';
-import { passwordProcedure } from '@/libs/trpc/edge';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { searchService } from '@/server/services/search';
-// TODO: password procedure 未来的处理方式可能要思考下
-const searchProcedure = isServerMode ? authedProcedure : passwordProcedure;
+const searchProcedure = authedProcedure;
export const searchRouter = router({
crawlPages: searchProcedure
diff --git a/src/services/__tests__/tool.test.ts b/src/services/__tests__/tool.test.ts
index 4abf6bfa4c0..749887a247c 100644
--- a/src/services/__tests__/tool.test.ts
+++ b/src/services/__tests__/tool.test.ts
@@ -1,8 +1,5 @@
import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
-import { edgeClient } from '@/libs/trpc/client';
-import { globalHelpers } from '@/store/global/helpers';
-
import { toolService } from '../tool';
import openAPIV3 from './openai/OpenAPI_V3.json';
import OpenAIPlugin from './openai/plugin.json';
diff --git a/src/services/aiModel/client.ts b/src/services/aiModel/client.ts
deleted file mode 100644
index 0be09d1005e..00000000000
--- a/src/services/aiModel/client.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { AiModelModel } from '@/database/models/aiModel';
-import { AiInfraRepos } from '@/database/repositories/aiInfra';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { IAiModelService } from './type';
-
-export class ClientService extends BaseClientService implements IAiModelService {
- private get aiModel(): AiModelModel {
- return new AiModelModel(clientDB as any, this.userId);
- }
- private get aiInfraRepos(): AiInfraRepos {
- let config = {};
-
- if (typeof window !== 'undefined') {
- config = window.global_serverConfigStore.getState().serverConfig.aiProvider || {};
- }
-
- return new AiInfraRepos(clientDB as any, this.userId, config);
- }
-
- createAiModel: IAiModelService['createAiModel'] = async (params) => {
- const data = await this.aiModel.create(params);
-
- return data?.id;
- };
-
- getAiProviderModelList: IAiModelService['getAiProviderModelList'] = async (id) => {
- return this.aiInfraRepos.getAiProviderModelList(id);
- };
-
- getAiModelById: IAiModelService['getAiModelById'] = async (id) => {
- return this.aiModel.findById(id);
- };
-
- toggleModelEnabled: IAiModelService['toggleModelEnabled'] = async (params) => {
- return this.aiModel.toggleModelEnabled(params);
- };
-
- updateAiModel: IAiModelService['updateAiModel'] = async (id, providerId, value) => {
- return this.aiModel.update(id, providerId, value);
- };
-
- batchUpdateAiModels: IAiModelService['batchUpdateAiModels'] = async (id, models) => {
- return this.aiModel.batchUpdateAiModels(id, models);
- };
-
- batchToggleAiModels: IAiModelService['batchToggleAiModels'] = async (id, models, enabled) => {
- return this.aiModel.batchToggleAiModels(id, models, enabled);
- };
-
- clearRemoteModels: IAiModelService['clearRemoteModels'] = async (providerId) => {
- return this.aiModel.clearRemoteModels(providerId);
- };
-
- clearModelsByProvider: IAiModelService['clearModelsByProvider'] = async (providerId) => {
- return this.aiModel.clearModelsByProvider(providerId);
- };
-
- updateAiModelOrder: IAiModelService['updateAiModelOrder'] = async (providerId, items) => {
- return this.aiModel.updateModelsOrder(providerId, items);
- };
-
- deleteAiModel: IAiModelService['deleteAiModel'] = async (params: {
- id: string;
- providerId: string;
- }) => {
- return this.aiModel.delete(params.id, params.providerId);
- };
-}
diff --git a/src/services/aiModel/index.test.ts b/src/services/aiModel/index.test.ts
index 73e9fa33634..fd2d7c5cb82 100644
--- a/src/services/aiModel/index.test.ts
+++ b/src/services/aiModel/index.test.ts
@@ -1,10 +1,7 @@
import { testService } from '~test-utils';
-import { ClientService } from './client';
import { ServerService } from './server';
describe('aiModelService', () => {
testService(ServerService);
-
- testService(ClientService);
});
diff --git a/src/services/aiModel/index.ts b/src/services/aiModel/index.ts
index 0812e4767ea..7abe2821438 100644
--- a/src/services/aiModel/index.ts
+++ b/src/services/aiModel/index.ts
@@ -1,9 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService } from './client';
import { ServerService } from './server';
-export const aiModelService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : new ClientService();
+export const aiModelService = new ServerService();
diff --git a/src/services/aiProvider/client.ts b/src/services/aiProvider/client.ts
deleted file mode 100644
index df7aff6af23..00000000000
--- a/src/services/aiProvider/client.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { AiProviderModel } from '@/database/models/aiProvider';
-import { AiInfraRepos } from '@/database/repositories/aiInfra';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { IAiProviderService } from './type';
-
-export class ClientService extends BaseClientService implements IAiProviderService {
- private get aiProviderModel(): AiProviderModel {
- return new AiProviderModel(clientDB as any, this.userId);
- }
- private get aiInfraRepos(): AiInfraRepos {
- let config = {};
- if (typeof window !== 'undefined') {
- config = window.global_serverConfigStore.getState().serverConfig.aiProvider || {};
- }
-
- return new AiInfraRepos(clientDB as any, this.userId, config);
- }
-
- createAiProvider: IAiProviderService['createAiProvider'] = async (params) => {
- const data = await this.aiProviderModel.create(params);
-
- return data?.id;
- };
-
- getAiProviderById: IAiProviderService['getAiProviderById'] = async (id) => {
- return this.aiInfraRepos.getAiProviderDetail(id);
- };
-
- getAiProviderList: IAiProviderService['getAiProviderList'] = async () => {
- return await this.aiInfraRepos.getAiProviderList();
- };
-
- getAiProviderRuntimeState: IAiProviderService['getAiProviderRuntimeState'] = async () => {
- return await this.aiInfraRepos.getAiProviderRuntimeState();
- };
-
- toggleProviderEnabled: IAiProviderService['toggleProviderEnabled'] = async (id, enabled) => {
- return this.aiProviderModel.toggleProviderEnabled(id, enabled);
- };
-
- updateAiProvider: IAiProviderService['updateAiProvider'] = async (id, value) => {
- return this.aiProviderModel.update(id, value);
- };
-
- updateAiProviderConfig: IAiProviderService['updateAiProviderConfig'] = async (id, value) => {
- return this.aiProviderModel.updateConfig(id, value);
- };
-
- updateAiProviderOrder: IAiProviderService['updateAiProviderOrder'] = async (items) => {
- return this.aiProviderModel.updateOrder(items);
- };
-
- deleteAiProvider: IAiProviderService['deleteAiProvider'] = async (id) => {
- return this.aiProviderModel.delete(id);
- };
-}
diff --git a/src/services/aiProvider/index.test.ts b/src/services/aiProvider/index.test.ts
index 2fb26461bd4..d2fe4589d78 100644
--- a/src/services/aiProvider/index.test.ts
+++ b/src/services/aiProvider/index.test.ts
@@ -1,10 +1,7 @@
import { testService } from '~test-utils';
-import { ClientService } from './client';
import { ServerService } from './server';
describe('aiProviderService', () => {
testService(ServerService);
-
- testService(ClientService);
});
diff --git a/src/services/aiProvider/index.ts b/src/services/aiProvider/index.ts
index b98a14574ee..814978a5171 100644
--- a/src/services/aiProvider/index.ts
+++ b/src/services/aiProvider/index.ts
@@ -1,9 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService } from './client';
import { ServerService } from './server';
-export const aiProviderService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : new ClientService();
+export const aiProviderService = new ServerService();
diff --git a/src/services/baseClientService/index.ts b/src/services/baseClientService/index.ts
deleted file mode 100644
index 15c2350b234..00000000000
--- a/src/services/baseClientService/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-const FALLBACK_CLIENT_DB_USER_ID = 'DEFAULT_LOBE_CHAT_USER';
-
-export class BaseClientService {
- protected readonly userId: string;
-
- constructor(userId?: string) {
- this.userId = userId || FALLBACK_CLIENT_DB_USER_ID;
- }
-}
diff --git a/src/services/chatGroup/client.ts b/src/services/chatGroup/client.ts
deleted file mode 100644
index c314193bc37..00000000000
--- a/src/services/chatGroup/client.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import {
- ChatGroupAgentItem,
- ChatGroupItem,
- NewChatGroup,
- NewChatGroupAgent,
-} from '@/database/schemas/chatGroup';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { IChatGroupService } from './type';
-
-export class ClientService extends BaseClientService implements IChatGroupService {
- private get chatGroupModel(): ChatGroupModel {
- return new ChatGroupModel(clientDB as any, this.userId);
- }
-
- async createGroup(params: Omit<NewChatGroup, 'userId'>): Promise<ChatGroupItem> {
- return this.chatGroupModel.create(params);
- }
-
- async updateGroup(id: string, value: Partial<ChatGroupItem>): Promise<ChatGroupItem> {
- return this.chatGroupModel.update(id, value);
- }
-
- async deleteGroup(id: string): Promise<any> {
- return this.chatGroupModel.delete(id);
- }
-
- async deleteAllGroups(): Promise<any> {
- return this.chatGroupModel.deleteAll();
- }
-
- async getGroup(id: string): Promise<ChatGroupItem | undefined> {
- return this.chatGroupModel.findById(id);
- }
-
- async getGroups(): Promise<ChatGroupItem[]> {
- return this.chatGroupModel.queryWithMemberDetails();
- }
-
- async addAgentsToGroup(groupId: string, agentIds: string[]): Promise<ChatGroupAgentItem[]> {
- return this.chatGroupModel.addAgentsToGroup(groupId, agentIds);
- }
-
- async removeAgentsFromGroup(groupId: string, agentIds: string[]): Promise<any> {
- for (const agentId of agentIds) {
- await this.chatGroupModel.removeAgentFromGroup(groupId, agentId);
- }
- }
-
- async updateAgentInGroup(
- groupId: string,
- agentId: string,
- updates: Partial<Pick<NewChatGroupAgent, 'order' | 'role'>>,
- ): Promise<ChatGroupAgentItem> {
- return this.chatGroupModel.updateAgentInGroup(groupId, agentId, updates);
- }
-
- async getGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
- return this.chatGroupModel.getGroupAgents(groupId);
- }
-}
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index 6d992dce9b4..27dae282f93 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -1,12 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new ServerService();
-
-export const chatGroupService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const chatGroupService = new ServerService();
diff --git a/src/services/config.ts b/src/services/config.ts
index 1f18789bfcd..390e1c1b364 100644
--- a/src/services/config.ts
+++ b/src/services/config.ts
@@ -1,23 +1,13 @@
-import { BRANDING_NAME, isDeprecatedEdition, isServerMode } from '@lobechat/const';
+import { BRANDING_NAME, isServerMode } from '@lobechat/const';
import { downloadFile, exportJSONFile } from '@lobechat/utils/client';
import dayjs from 'dayjs';
-import { CURRENT_CONFIG_VERSION } from '@/migrations';
import { ImportPgDataStructure } from '@/types/export';
import { exportService } from './export';
-import { configService as deprecatedExportService } from './export/_deprecated';
class ConfigService {
exportAll = async () => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const config = await deprecatedExportService.exportAll();
- const filename = `${BRANDING_NAME}-config-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(config, filename);
- return;
- }
-
const { data, url } = await exportService.exportData();
const filename = `${dayjs().format('YYYY-MM-DD-hh-mm')}_${BRANDING_NAME}-data.json`;
@@ -34,60 +24,6 @@ class ConfigService {
exportJSONFile(result, filename);
};
- exportAgents = async () => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const config = await deprecatedExportService.exportAgents();
- const filename = `${BRANDING_NAME}-agents-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(config, filename);
- return;
- }
- };
-
- exportSingleAgent = async (agentId: string) => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const result = await deprecatedExportService.exportSingleAgent(agentId);
- if (!result) return;
-
- const filename = `${BRANDING_NAME}-${result.title}-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(result.config, filename);
- return;
- }
- };
-
- exportSessions = async () => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const config = await deprecatedExportService.exportSessions();
- const filename = `${BRANDING_NAME}-sessions-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(config, filename);
- return;
- }
- };
-
- exportSettings = async () => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const config = await deprecatedExportService.exportSessions();
- const filename = `${BRANDING_NAME}-settings-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(config, filename);
- return;
- }
- };
-
- exportSingleSession = async (sessionId: string) => {
- // TODO: remove this in V2
- if (isDeprecatedEdition) {
- const data = await deprecatedExportService.exportSingleSession(sessionId);
- if (!data) return;
-
- const filename = `${BRANDING_NAME}-${data.title}-v${CURRENT_CONFIG_VERSION}.json`;
- exportJSONFile(data.config, filename);
- return;
- }
- };
-
private createDataStructure = async (
data: any,
mode: 'pglite' | 'postgres',
diff --git a/src/services/export/_deprecated.ts b/src/services/export/_deprecated.ts
deleted file mode 100644
index 24718bac58a..00000000000
--- a/src/services/export/_deprecated.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { Migration } from '@/migrations';
-import { messageService } from '@/services/message';
-import { sessionService } from '@/services/session';
-import { topicService } from '@/services/topic';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import {
- ConfigFileAgents,
- ConfigFileAll,
- ConfigFileSessions,
- ConfigFileSettings,
- ConfigFileSingleSession,
- ConfigModelMap,
- ExportType,
-} from '@/types/exportConfig';
-
-type CreateConfigFileState<T extends ExportType> = ConfigModelMap[T]['state'];
-
-type CreateConfigFile<T extends ExportType> = ConfigModelMap[T]['file'];
-
-const createConfigFile = <T extends ExportType>(
- type: T,
- state: CreateConfigFileState<T>,
-): CreateConfigFile<T> => {
- switch (type) {
- case 'agents': {
- return {
- exportType: 'agents',
- state,
- version: Migration.targetVersion,
- } as ConfigFileAgents;
- }
-
- case 'sessions': {
- return {
- exportType: 'sessions',
- state,
- version: Migration.targetVersion,
- } as ConfigFileSessions;
- }
-
- case 'settings': {
- return {
- exportType: 'settings',
- state,
- version: Migration.targetVersion,
- } as ConfigFileSettings;
- }
-
- case 'singleSession': {
- return {
- exportType: 'sessions',
- state,
- version: Migration.targetVersion,
- } as ConfigFileSingleSession;
- }
-
- case 'all': {
- return {
- exportType: 'all',
- state,
- version: Migration.targetVersion,
- } as ConfigFileAll;
- }
- }
-
- throw new Error('缺少正确的导出类型,请检查实现...');
-};
-
-/**
- * @deprecated
- */
-export class ConfigService {
- /**
- * export all agents
- */
- exportAgents = async () => {
- const agents = await sessionService.getSessionsByType('agent');
- const sessionGroups = await sessionService.getSessionGroups();
-
- return createConfigFile('agents', { sessionGroups, sessions: agents });
- };
-
- /**
- * export all sessions
- */
- exportSessions = async () => {
- const sessions = await sessionService.getSessionsByType();
- const sessionGroups = await sessionService.getSessionGroups();
- const messages = await messageService.getAllMessages();
- const topics = await topicService.getAllTopics();
-
- return createConfigFile('sessions', { messages, sessionGroups, sessions, topics });
- };
-
- /**
- * export a session
- */
- exportSingleSession = async (id: string) => {
- const session = this.getSession(id);
- if (!session) return;
-
- const messages = await messageService.getAllMessagesInSession(id);
- const topics = await topicService.getTopics({ containerId: id });
-
- const config = createConfigFile('singleSession', { messages, sessions: [session], topics });
- return { config, title: `${session.meta?.title}-session` };
- };
-
- exportSingleAgent = async (id: string) => {
- const agent = this.getAgent(id);
- if (!agent) return;
-
- const config = createConfigFile('agents', { sessionGroups: [], sessions: [agent] });
-
- return { config, title: `${agent.meta?.title}-session` };
- };
-
- /**
- * export settings
- */
- exportSettings = async () => {
- const settings = this.getSettings();
-
- return createConfigFile('settings', { settings });
- };
-
- /**
- * export all data
- */
- exportAll = async () => {
- const sessions = await sessionService.getSessionsByType();
- const sessionGroups = await sessionService.getSessionGroups();
- const messages = await messageService.getAllMessages();
- const topics = await topicService.getAllTopics();
- const settings = this.getSettings();
-
- return createConfigFile('all', { messages, sessionGroups, sessions, settings, topics });
- };
-
- private getSettings = () => settingsSelectors.exportSettings(useUserStore.getState());
-
- private getSession = (id: string) =>
- sessionSelectors.getSessionById(id)(useSessionStore.getState());
-
- private getAgent = (id: string) =>
- sessionSelectors.getSessionById(id)(useSessionStore.getState());
-}
-
-/**
- * @deprecated
- */
-export const configService = new ConfigService();
diff --git a/src/services/export/client.ts b/src/services/export/client.ts
deleted file mode 100644
index 773b2534423..00000000000
--- a/src/services/export/client.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { DataExporterRepos } from '@/database/repositories/dataExporter';
-import { BaseClientService } from '@/services/baseClientService';
-
-export class ClientService extends BaseClientService {
- private get dataExporterRepos(): DataExporterRepos {
- return new DataExporterRepos(clientDB as any, this.userId);
- }
-
- exportData = async () => {
- const data = await this.dataExporterRepos.export();
-
- return { data, url: undefined };
- };
-}
diff --git a/src/services/export/index.ts b/src/services/export/index.ts
index 63be3be5d2d..d282504bebb 100644
--- a/src/services/export/index.ts
+++ b/src/services/export/index.ts
@@ -1,6 +1,3 @@
-import { isServerMode } from '@/const/version';
-
-import { ClientService } from './client';
import { ServerService } from './server';
-export const exportService = isServerMode ? new ServerService() : new ClientService();
+export const exportService = new ServerService();
diff --git a/src/services/file/_deprecated.test.ts b/src/services/file/_deprecated.test.ts
deleted file mode 100644
index ca0e6ac426d..00000000000
--- a/src/services/file/_deprecated.test.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { Mock, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { FileModel } from '@/database/_deprecated/models/file';
-import { DB_File } from '@/database/_deprecated/schemas/files';
-import { fileEnv } from '@/envs/file';
-import { clientS3Storage } from '@/services/file/ClientS3';
-import { serverConfigSelectors } from '@/store/serverConfig/selectors';
-import { createServerConfigStore } from '@/store/serverConfig/store';
-
-import { ClientService } from './_deprecated';
-
-const fileService = new ClientService();
-
-beforeAll(() => {
- createServerConfigStore();
-});
-// Mocks for the FileModel
-vi.mock('@/database/_deprecated/models/file', () => ({
- FileModel: {
- create: vi.fn(),
- delete: vi.fn(),
- findById: vi.fn(),
- clear: vi.fn(),
- },
-}));
-
-let s3Domain: string;
-
-vi.mock('@/config/file', () => ({
- fileEnv: {
- get NEXT_PUBLIC_S3_DOMAIN() {
- return s3Domain;
- },
- },
-}));
-
-// Mocks for the URL and Blob objects
-global.URL.createObjectURL = vi.fn();
-global.Blob = vi.fn();
-
-beforeEach(() => {
- // Reset all mocks before each test
- vi.resetAllMocks();
- s3Domain = '';
-});
-
-describe('FileService', () => {
- it('createFile should save the file to the database', async () => {
- const localFile = {
- name: 'test',
- fileType: 'image/png',
- url: 'client-s3://123',
- size: 1,
- hash: '123',
- };
-
- await clientS3Storage.putObject(
- '123',
- new File([new ArrayBuffer(1)], 'test.png', { type: 'image/png' }),
- );
-
- (FileModel.create as Mock).mockResolvedValue(localFile);
-
- const result = await fileService.createFile(localFile);
-
- expect(result).toEqual({ url: 'data:image/png;base64,AA==' });
- });
-
- it('removeFile should delete the file from the database', async () => {
- const fileId = '1';
- (FileModel.delete as Mock).mockResolvedValue(true);
-
- const result = await fileService.removeFile(fileId);
-
- expect(FileModel.delete).toHaveBeenCalledWith(fileId);
- expect(result).toBe(true);
- });
-
- describe('getFile', () => {
- it('should retrieve and convert local file info to FilePreview', async () => {
- const fileId = '1';
- const fileData = {
- name: 'test',
- data: new ArrayBuffer(1),
- fileType: 'image/png',
- saveMode: 'local',
- size: 1,
- createdAt: 1,
- updatedAt: 2,
- } as DB_File;
-
- (FileModel.findById as Mock).mockResolvedValue(fileData);
- (global.URL.createObjectURL as Mock).mockReturnValue('blob:test');
- (global.Blob as Mock).mockImplementation(() => ['test']);
-
- const result = await fileService.getFile(fileId);
-
- expect(FileModel.findById).toHaveBeenCalledWith(fileId);
- expect(result).toEqual({
- createdAt: new Date(1),
- id: '1',
- size: 1,
- type: 'image/png',
- name: 'test',
- url: 'blob:test',
- updatedAt: new Date(2),
- });
- });
-
- it('should throw an error when the file is not found', async () => {
- const fileId = 'non-existent';
- (FileModel.findById as Mock).mockResolvedValue(null);
-
- const getFilePromise = fileService.getFile(fileId);
-
- await expect(getFilePromise).rejects.toThrow('file not found');
- });
- });
-});
diff --git a/src/services/file/_deprecated.ts b/src/services/file/_deprecated.ts
deleted file mode 100644
index c4430ff7b58..00000000000
--- a/src/services/file/_deprecated.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { FileModel } from '@/database/_deprecated/models/file';
-import { clientS3Storage } from '@/services/file/ClientS3';
-import { FileItem, UploadFileParams } from '@/types/files';
-
-import { IFileService } from './type';
-
-export class ClientService implements IFileService {
- async createFile(file: UploadFileParams) {
- // save to local storage
- // we may want to save to a remote server later
- const res = await FileModel.create({
- createdAt: Date.now(),
- data: undefined,
- fileHash: file.hash,
- fileType: file.fileType,
- metadata: file.metadata,
- name: file.name,
- saveMode: 'url',
- size: file.size,
- url: file.url,
- } as any);
-
- // get file to base64 url
- const base64 = await this.getBase64ByFileHash(file.hash!);
-
- return {
- id: res.id,
- url: `data:${file.fileType};base64,${base64}`,
- };
- }
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- async checkFileHash(_hash: string) {
- return { isExist: false, metadata: {}, url: '' };
- }
-
- async getFile(id: string): Promise<FileItem> {
- const item = await FileModel.findById(id);
- if (!item) {
- throw new Error('file not found');
- }
-
- // arrayBuffer to blob or base64 to blob
- const blob = !!item.data
- ? new Blob([item.data!], { type: item.fileType })
- : // @ts-ignore
- new Blob([Buffer.from(item.base64!, 'base64')], { type: item.fileType });
-
- const url = URL.createObjectURL(blob);
-
- return {
- createdAt: new Date(item.createdAt),
- id,
- name: item.name,
- size: item.size,
- type: item.fileType,
- updatedAt: new Date(item.updatedAt),
- url,
- };
- }
-
- async removeFile(id: string) {
- return FileModel.delete(id);
- }
-
- async removeFiles(ids: string[]) {
- await Promise.all(ids.map((id) => FileModel.delete(id)));
- }
-
- async removeAllFiles() {
- return FileModel.clear();
- }
-
- private async getBase64ByFileHash(hash: string) {
- const fileItem = await clientS3Storage.getObject(hash);
- if (!fileItem) throw new Error('file not found');
-
- return Buffer.from(await fileItem.arrayBuffer()).toString('base64');
- }
-}
diff --git a/src/services/file/client.test.ts b/src/services/file/client.test.ts
deleted file mode 100644
index 94b46921d7b..00000000000
--- a/src/services/file/client.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import { files, globalFiles, users } from '@/database/schemas';
-import { clientS3Storage } from '@/services/file/ClientS3';
-import { UploadFileParams } from '@/types/files';
-
-import { ClientService } from './client';
-
-const userId = 'file-user';
-
-const fileService = new ClientService(userId);
-
-const mockFile = {
- name: 'mock.png',
- fileType: 'image/png',
- size: 1,
- url: '',
-};
-
-beforeEach(async () => {
- await initializeDB();
-
- await clientDB.delete(users);
- await clientDB.delete(globalFiles);
- // 创建测试数据
- await clientDB.transaction(async (tx) => {
- await tx.insert(users).values({ id: userId });
- });
-});
-
-describe('FileService', () => {
- describe('createFile', () => {
- it('createFile should save the file to the database', async () => {
- const localFile: UploadFileParams = {
- name: 'test',
- fileType: 'image/png',
- url: '',
- size: 1,
- hash: '123',
- };
-
- await clientS3Storage.putObject(
- '123',
- new File([new ArrayBuffer(1)], 'test.png', { type: 'image/png' }),
- );
-
- const result = await fileService.createFile(localFile);
-
- expect(result).toMatchObject({ url: 'data:image/png;base64,AA==' });
- });
-
- it('should throw error when file is not found in storage during base64 conversion', async () => {
- const localFile: UploadFileParams = {
- name: 'test',
- fileType: 'image/png',
- url: '',
- size: 1,
- hash: 'non-existing-hash',
- };
-
- // 不调用 clientS3Storage.putObject,模拟文件不存在的情况
-
- const promise = fileService.createFile(localFile);
-
- await expect(promise).rejects.toThrow('file not found');
- });
- });
-
- it('removeFile should delete the file from the database', async () => {
- const fileId = '1';
- await clientDB.insert(files).values({ id: fileId, userId, ...mockFile });
-
- await fileService.removeFile(fileId);
-
- const result = await clientDB.query.files.findFirst({
- where: eq(files.id, fileId),
- });
-
- expect(result).toBeUndefined();
- });
-
- describe('getFile', () => {
- it('should retrieve and convert local file info to FilePreview', async () => {
- const fileId = 'rwlijweled';
- const file = {
- fileType: 'image/png',
- size: 1,
- name: 'test.png',
- url: 'idb://12312/abc.png',
- hashId: '123tttt',
- };
-
- await clientDB.insert(globalFiles).values({ ...file, creator: userId });
-
- await clientDB.insert(files).values({
- id: fileId,
- userId,
- ...file,
- createdAt: new Date(1),
- updatedAt: new Date(2),
- fileHash: file.hashId,
- });
-
- await clientS3Storage.putObject(
- file.hashId,
- new File([new ArrayBuffer(1)], file.name, { type: file.fileType }),
- );
-
- const result = await fileService.getFile(fileId);
-
- expect(result).toMatchObject({
- createdAt: new Date(1),
- id: 'rwlijweled',
- size: 1,
- type: 'image/png',
- name: 'test.png',
- updatedAt: new Date(2),
- });
- });
-
- it('should throw an error when the file is not found', async () => {
- const fileId = 'non-existent';
-
- const getFilePromise = fileService.getFile(fileId);
-
- await expect(getFilePromise).rejects.toThrow('file not found');
- });
- });
-
- describe('removeFiles', () => {
- it('should delete multiple files from the database', async () => {
- const fileIds = ['1', '2', '3'];
-
- // 插入测试文件数据
- await Promise.all(
- fileIds.map((id) => clientDB.insert(files).values({ id, userId, ...mockFile })),
- );
-
- await fileService.removeFiles(fileIds);
-
- // 验证所有文件都被删除
- const remainingFiles = await clientDB.query.files.findMany({
- where: (fields, { inArray }) => inArray(fields.id, fileIds),
- });
-
- expect(remainingFiles).toHaveLength(0);
- });
- });
-
- describe('removeAllFiles', () => {
- it('should clear all files for the user', async () => {
- // 插入测试文件数据
- await Promise.all([
- clientDB.insert(files).values({ id: '1', userId, ...mockFile }),
- clientDB.insert(files).values({ id: '2', userId, ...mockFile }),
- ]);
-
- await fileService.removeAllFiles();
-
- // 验证用户的所有文件都被删除
- const remainingFiles = await clientDB.query.files.findMany({
- where: eq(files.userId, userId),
- });
-
- expect(remainingFiles).toHaveLength(0);
- });
- });
-
- describe('checkFileHash', () => {
- it('should return true if file hash exists', async () => {
- const hash = 'existing-hash';
- await clientDB.insert(globalFiles).values({
- ...mockFile,
- hashId: hash,
- creator: userId,
- });
- await clientDB.insert(files).values({
- id: '1',
- userId,
- ...mockFile,
- fileHash: hash,
- });
-
- const exists = await fileService.checkFileHash(hash);
-
- expect(exists).toMatchObject({ isExist: true });
- });
-
- it('should return false if file hash does not exist', async () => {
- const hash = 'non-existing-hash';
-
- const exists = await fileService.checkFileHash(hash);
-
- expect(exists).toEqual({ isExist: false });
- });
- });
-});
diff --git a/src/services/file/client.ts b/src/services/file/client.ts
deleted file mode 100644
index b1e84472f22..00000000000
--- a/src/services/file/client.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { FileModel } from '@/database/models/file';
-import { BaseClientService } from '@/services/baseClientService';
-import { clientS3Storage } from '@/services/file/ClientS3';
-
-import { IFileService } from './type';
-
-export class ClientService extends BaseClientService implements IFileService {
- private get fileModel(): FileModel {
- return new FileModel(clientDB as any, this.userId);
- }
-
- createFile: IFileService['createFile'] = async (file) => {
- const { isExist } = await this.fileModel.checkHash(file.hash!);
-
- // save to local storage
- // we may want to save to a remote server later
- const res = await this.fileModel.create(
- {
- fileHash: file.hash,
- fileType: file.fileType,
- knowledgeBaseId: file.knowledgeBaseId,
- metadata: file.metadata,
- name: file.name,
- size: file.size,
- url: file.url!,
- },
- !isExist,
- );
-
- // get file to base64 url
- const base64 = await this.getBase64ByFileHash(file.hash!);
-
- return {
- id: res.id,
- url: `data:${file.fileType};base64,${base64}`,
- };
- };
-
- getFile: IFileService['getFile'] = async (id) => {
- const item = await this.fileModel.findById(id);
- if (!item) {
- throw new Error('file not found');
- }
-
- // arrayBuffer to url
- const fileItem = await clientS3Storage.getObject(item.fileHash!);
- if (!fileItem) throw new Error('file not found');
-
- const url = URL.createObjectURL(fileItem);
-
- return {
- createdAt: new Date(item.createdAt),
- id,
- name: item.name,
- size: item.size,
- type: item.fileType,
- updatedAt: new Date(item.updatedAt),
- url,
- };
- };
-
- removeFile: IFileService['removeFile'] = async (id) => {
- await this.fileModel.delete(id, false);
- };
-
- removeFiles: IFileService['removeFiles'] = async (ids) => {
- await this.fileModel.deleteMany(ids, false);
- };
-
- removeAllFiles: IFileService['removeAllFiles'] = async () => {
- return this.fileModel.clear();
- };
-
- checkFileHash: IFileService['checkFileHash'] = async (hash) => {
- return this.fileModel.checkHash(hash);
- };
-
- private getBase64ByFileHash = async (hash: string) => {
- const fileItem = await clientS3Storage.getObject(hash);
- if (!fileItem) throw new Error('file not found');
-
- return Buffer.from(await fileItem.arrayBuffer()).toString('base64');
- };
-}
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index 9f7c7f2bca9..9b93a0cd9df 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -1,13 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const fileService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const fileService = new ServerService();
diff --git a/src/services/import/_deprecated.ts b/src/services/import/_deprecated.ts
deleted file mode 100644
index 01651c63fcd..00000000000
--- a/src/services/import/_deprecated.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { MessageModel } from '@/database/_deprecated/models/message';
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { SessionGroupModel } from '@/database/_deprecated/models/sessionGroup';
-import { TopicModel } from '@/database/_deprecated/models/topic';
-import { useUserStore } from '@/store/user';
-import { ConfigFile } from '@/types/exportConfig';
-import { ImportStage, ImporterEntryData, OnImportCallbacks } from '@/types/importer';
-import { UserSettings } from '@/types/user/settings';
-
-export interface ImportResult {
- added: number;
- errors: number;
- skips: number;
- updated?: number;
-}
-export interface ImportResults {
- messages?: ImportResult;
- sessionGroups?: ImportResult;
- sessions?: ImportResult;
- topics?: ImportResult;
- type?: string;
-}
-
-export class ClientService {
- importSettings = async (settings: UserSettings) => {
- await useUserStore.getState().importAppSettings(settings);
- };
-
- importData = async (
- config: ImporterEntryData,
- callbacks?: OnImportCallbacks,
- ): Promise<ImportResults> => {
- callbacks?.onStageChange?.(ImportStage.Importing);
- const time = Date.now();
-
- const { messages = [], sessionGroups = [], sessions = [], topics = [] } = config;
-
- let messageResult: ImportResult | undefined;
- let sessionResult: ImportResult | undefined;
- let sessionGroupResult: ImportResult | undefined;
- let topicResult: ImportResult | undefined;
-
- if (messages.length > 0) {
- const res = await MessageModel.batchCreate(messages as any);
- messageResult = this.mapImportResult(res);
- }
-
- if (sessionGroups.length > 0) {
- const res = await SessionGroupModel.batchCreate(sessionGroups as any);
- sessionGroupResult = this.mapImportResult(res);
- }
-
- if (topics.length > 0) {
- const res = await TopicModel.batchCreate(topics as any);
- topicResult = this.mapImportResult(res);
- }
-
- if (sessions.length > 0) {
- const data = await SessionModel.batchCreate(sessions as any);
- sessionResult = this.mapImportResult(data);
- }
-
- const result = {
- messages: messageResult,
- sessionGroups: sessionGroupResult,
- sessions: sessionResult,
- topics: topicResult,
- };
-
- const duration = Date.now() - time;
- callbacks?.onStageChange?.(ImportStage.Success);
- callbacks?.onSuccess?.(result, duration);
-
- return result;
- };
-
- private mapImportResult = (input: {
- added: number;
- errors?: Error[];
- skips: string[];
- }): ImportResult => {
- return {
- added: input.added,
- errors: input.errors?.length || 0,
- skips: input.skips.length,
- };
- };
-
- importConfigState = async (config: ConfigFile, callbacks?: OnImportCallbacks): Promise<void> => {
- if (config.exportType === 'settings') {
- await this.importSettings(config.state.settings);
- callbacks?.onStageChange?.(ImportStage.Success);
- return;
- }
-
- if (config.exportType === 'all') {
- await this.importSettings(config.state.settings);
- }
-
- await this.importData(
- {
- messages: (config.state as any).messages || [],
- sessionGroups: (config.state as any).sessionGroups || [],
- sessions: (config.state as any).sessions || [],
- topics: (config.state as any).topics || [],
- version: config.version,
- },
- callbacks,
- );
- };
-
- importPgData = async () => {
- throw new Error('Not implemented');
- };
-}
diff --git a/src/services/import/client.test.ts b/src/services/import/client.test.ts
deleted file mode 100644
index ada86c39502..00000000000
--- a/src/services/import/client.test.ts
+++ /dev/null
@@ -1,1015 +0,0 @@
-import { eq, inArray } from 'drizzle-orm';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import mockImportData from '@/database/repositories/dataImporter/deprecated/__tests__/fixtures/messages.json';
-import {
- agents,
- agentsToSessions,
- messages,
- sessionGroups,
- sessions,
- topics,
- users,
-} from '@/database/schemas';
-import { CURRENT_CONFIG_VERSION } from '@/migrations';
-import { ImportResults, ImporterEntryData } from '@/types/importer';
-
-import { ClientService } from './client';
-
-const userId = 'test-user-id';
-const service = new ClientService(userId);
-
-beforeEach(async () => {
- await initializeDB();
-
- await clientDB.delete(users);
-
- // 创建测试数据
- await clientDB.transaction(async (tx) => {
- await tx.insert(users).values({ id: userId });
- });
-});
-
-describe('ImporterService', () => {
- describe('import sessionGroups', () => {
- it('should import session groups and return correct result', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessionGroups: [
- { id: 'group1', name: 'Group 1', createdAt: 1715186011586, updatedAt: 1715186015053 },
- { id: 'group2', name: 'Group 2', createdAt: 1715186011586, updatedAt: 1715186015053 },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.sessionGroups!.added).toBe(2);
- expect(result!.sessionGroups!.skips).toBe(0);
- expect(result!.sessionGroups!.errors).toBe(0);
-
- const groups = await clientDB.query.sessionGroups.findMany({
- where: eq(sessionGroups.userId, userId),
- });
- expect(groups).toHaveLength(2);
- });
-
- it('should skip existing session groups and return correct result', async () => {
- await clientDB
- .insert(sessionGroups)
- .values({ clientId: 'group1', name: 'Existing Group', userId })
- .execute();
-
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessionGroups: [
- { id: 'group1', name: 'Group 1', createdAt: 1715186011586, updatedAt: 1715186015053 },
- { id: 'group2', name: 'Group 2', createdAt: 1715186011586, updatedAt: 1715186015053 },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.sessionGroups!.added).toBe(1);
- expect(result!.sessionGroups!.skips).toBe(1);
- expect(result!.sessionGroups!.errors).toBe(0);
- });
- });
-
- describe('import sessions', () => {
- it('should import sessions and return correct result', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.sessions!.added).toBe(2);
- expect(result!.sessions!.skips).toBe(0);
- expect(result!.sessions!.errors).toBe(0);
-
- const importedSessions = await clientDB.query.sessions.findMany({
- where: eq(sessions.userId, userId),
- });
- expect(importedSessions).toHaveLength(2);
-
- const agentCount = await clientDB.query.agents.findMany({
- where: eq(agents.userId, userId),
- });
-
- expect(agentCount.length).toBe(2);
-
- const agentSessionCount = await clientDB.query.agentsToSessions.findMany();
- expect(agentSessionCount.length).toBe(2);
- });
-
- it('should skip existing sessions and return correct result', async () => {
- await clientDB.insert(sessions).values({ clientId: 'session1', userId }).execute();
-
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.sessions!.added).toBe(1);
- expect(result!.sessions!.skips).toBe(1);
- expect(result!.sessions!.errors).toBe(0);
- });
-
- it('should associate imported sessions with session groups', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessionGroups: [
- { id: 'group1', name: 'Group 1', createdAt: 1715186011586, updatedAt: 1715186015053 },
- { id: 'group2', name: 'Group 2', createdAt: 1715186011586, updatedAt: 1715186015053 },
- ],
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- group: 'group1',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- group: 'group2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
- {
- id: 'session3',
- group: 'group4',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 3',
- },
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.sessionGroups!.added).toBe(2);
- expect(result!.sessionGroups!.skips).toBe(0);
-
- expect(result!.sessions!.added).toBe(3);
- expect(result!.sessions!.skips).toBe(0);
-
- // session 1 should be associated with group 1
- const session1 = await clientDB.query.sessions.findFirst({
- where: eq(sessions.clientId, 'session1'),
- with: { group: true },
- });
- expect(session1?.group).toBeDefined();
-
- // session 3 should not have group
- const session3 = await clientDB.query.sessions.findFirst({
- where: eq(sessions.clientId, 'session3'),
- with: { group: true },
- });
- expect(session3?.group).toBeNull();
- });
-
- it('should create agents and associate them with imported sessions', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'def',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 2',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
- ],
- };
-
- await service.importData(data);
-
- // 验证是否为每个 session 创建了对应的 agent
- const agentCount = await clientDB.query.agents.findMany({
- where: eq(agents.userId, userId),
- });
- expect(agentCount).toHaveLength(2);
-
- // 验证 agent 的属性是否正确设置
- const agent1 = await clientDB.query.agents.findFirst({
- where: eq(agents.systemRole, 'Test Agent 1'),
- });
- expect(agent1?.model).toBe('abc');
-
- const agent2 = await clientDB.query.agents.findFirst({
- where: eq(agents.systemRole, 'Test Agent 2'),
- });
- expect(agent2?.model).toBe('def');
-
- // 验证 agentsToSessions 关联是否正确建立
- const session1 = await clientDB.query.sessions.findFirst({
- where: eq(sessions.clientId, 'session1'),
- });
- const session1Agent = await clientDB.query.agentsToSessions.findFirst({
- where: eq(agentsToSessions.sessionId, session1?.id!),
- with: { agent: true },
- });
-
- expect((session1Agent?.agent as any).systemRole).toBe('Test Agent 1');
-
- const session2 = await clientDB.query.sessions.findFirst({
- where: eq(sessions.clientId, 'session2'),
- });
- const session2Agent = await clientDB.query.agentsToSessions.findFirst({
- where: eq(agentsToSessions.sessionId, session2?.id!),
- with: { agent: true },
- });
-
- expect((session2Agent?.agent as any).systemRole).toBe('Test Agent 2');
- });
-
- it('should not create duplicate agents for existing sessions', async () => {
- // 先导入一些 sessions
- await service.importData({
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
- version: CURRENT_CONFIG_VERSION,
- });
-
- // 再次导入相同的 sessions
- await service.importData({
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
- version: CURRENT_CONFIG_VERSION,
- });
-
- // 验证只创建了一个 agent
- const agentCount = await clientDB.query.agents.findMany({
- where: eq(agents.userId, userId),
- });
- expect(agentCount).toHaveLength(1);
- });
- });
-
- describe('import topics', () => {
- it('should import topics and return correct result', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- topics: [
- {
- id: 'topic1',
- title: 'Topic 1',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- },
- {
- id: 'topic2',
- title: 'Topic 2',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session2',
- },
- ],
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.topics!.added).toBe(2);
- expect(result!.topics!.skips).toBe(0);
- expect(result!.topics!.errors).toBe(0);
-
- const importedTopics = await clientDB.query.topics.findMany({
- where: eq(topics.userId, userId),
- });
- expect(importedTopics).toHaveLength(2);
- });
-
- it('should skip existing topics and return correct result', async () => {
- await clientDB
- .insert(topics)
- .values({ clientId: 'topic1', title: 'Existing Topic', userId })
- .execute();
-
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- topics: [
- { id: 'topic1', title: 'Topic 1', createdAt: 1715186011586, updatedAt: 1715186015053 },
- { id: 'topic2', title: 'Topic 2', createdAt: 1715186011586, updatedAt: 1715186015053 },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.topics!.added).toBe(1);
- expect(result!.topics!.skips).toBe(1);
- expect(result!.topics!.errors).toBe(0);
- });
-
- it('should associate imported topics with sessions', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
- topics: [
- {
- id: 'topic1',
- title: 'Topic 1',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- },
- { id: 'topic2', title: 'Topic 2', createdAt: 1715186011586, updatedAt: 1715186015053 },
- ],
- };
-
- await service.importData(data);
-
- // topic1 should be associated with session1
- const [topic1] = await clientDB
- .select({ sessionClientId: sessions.clientId })
- .from(topics)
- .where(eq(topics.clientId, 'topic1'))
- .leftJoin(sessions, eq(topics.sessionId, sessions.id));
-
- expect(topic1?.sessionClientId).toBe('session1');
-
- // topic2 should not have session
- const topic2 = await clientDB.query.topics.findFirst({
- where: eq(topics.clientId, 'topic2'),
- with: { session: true },
- });
- expect(topic2?.session).toBeNull();
- });
- });
-
- describe('import messages', () => {
- it('should import messages and return correct result', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- messages: [
- {
- id: 'msg1',
- content: 'Message 1',
- role: 'user',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- topicId: 'topic1',
- },
- {
- id: 'msg2',
- content: 'Message 2',
- role: 'assistant',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- topicId: 'topic1',
- parentId: 'msg1',
- },
- ],
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
- topics: [
- {
- id: 'topic1',
- title: 'Topic 1',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.messages!.added).toBe(2);
- expect(result!.messages!.skips).toBe(0);
- expect(result!.messages!.errors).toBe(0);
-
- const importedMessages = await clientDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
- expect(importedMessages).toHaveLength(2);
- });
-
- it('should skip existing messages and return correct result', async () => {
- await clientDB
- .insert(messages)
- .values({
- clientId: 'msg1',
- content: 'Existing Message',
- role: 'user',
- userId,
- })
- .execute();
-
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- messages: [
- {
- id: 'msg1',
- content: 'Message 1',
- role: 'user',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- },
- {
- id: 'msg2',
- content: 'Message 2',
- role: 'assistant',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- },
- ],
- };
-
- let result: ImportResults;
- await service.importData(data, {
- onSuccess: (res) => {
- result = res;
- },
- });
-
- expect(result!.messages!.added).toBe(1);
- expect(result!.messages!.skips).toBe(1);
- expect(result!.messages!.errors).toBe(0);
- });
-
- it('should associate imported messages with sessions and topics', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
- topics: [
- {
- id: 'topic1',
- title: 'Topic 1',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- },
- ],
- messages: [
- {
- id: 'msg1',
- content: 'Message 1',
- role: 'user',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- topicId: 'topic1',
- },
- {
- id: 'msg2',
- content: 'Message 2',
- role: 'assistant',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- sessionId: 'session1',
- topicId: 'topic1',
- parentId: 'msg1',
- },
- {
- id: 'msg3',
- content: 'Message 3',
- role: 'user',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- },
- ],
- };
-
- await service.importData(data);
-
- // msg1 and msg2 should be associated with session1 and topic1
- const [msg1, msg2] = await clientDB.query.messages.findMany({
- where: inArray(messages.clientId, ['msg1', 'msg2']),
- with: {
- session: true,
- topic: true,
- },
- });
-
- expect(msg1.session?.clientId).toBe('session1');
- expect(msg1.topic?.clientId).toBe('topic1');
- expect(msg2.session?.clientId).toBe('session1');
- expect(msg2.topic?.clientId).toBe('topic1');
-
- // msg3 should not have session and topic
- const msg3 = await clientDB.query.messages.findFirst({
- where: eq(messages.clientId, 'msg3'),
- with: {
- session: true,
- topic: true,
- },
- });
- expect(msg3?.session).toBeNull();
- expect(msg3?.topic).toBeNull();
- });
-
- it('should set parentId for messages', async () => {
- const data: ImporterEntryData = {
- version: CURRENT_CONFIG_VERSION,
- messages: [
- {
- id: 'msg1',
- content: 'Message 1',
- role: 'user',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- },
- {
- id: 'msg2',
- content: 'Message 2',
- role: 'assistant',
- createdAt: 1715186011586,
- updatedAt: 1715186015053,
- parentId: 'msg1',
- },
- ],
- };
-
- await service.importData(data);
-
- const msg2 = await clientDB.query.messages.findFirst({
- where: eq(messages.clientId, 'msg2'),
- with: { parent: true },
- });
-
- expect(msg2?.parent?.clientId).toBe('msg1');
- });
-
- it('should import parentId Success', () => {});
- });
-
- describe('real world examples', () => {
- it('should import successfully', async () => {
- let result: ImportResults;
-
- await service.importData(
- {
- messages: [
- {
- role: 'user',
- content: 'hello',
- files: [],
- sessionId: 'inbox',
- topicId: '2wcF8yaS',
- createdAt: 1714236590340,
- id: 'DCG1G1EH',
- updatedAt: 1714236590340,
- extra: {},
- },
- {
- role: 'assistant',
- content: '...',
- parentId: 'DCG1G1EH',
- sessionId: 'inbox',
- topicId: '2wcF8yaS',
- createdAt: 1714236590441,
- id: 'gY41w5vQ',
- updatedAt: 1714236590518,
- error: {
- body: {
- error: {
- message: "model 'mixtral' not found, try pulling it first",
- name: 'ResponseError',
- status_code: 404,
- },
- provider: 'ollama',
- },
- message:
- 'Error requesting Ollama service, please troubleshoot or retry based on the following information',
- type: 'OllamaBizError',
- },
- extra: { fromModel: 'mixtral', fromProvider: 'ollama' },
- },
- {
- role: 'user',
- content: 'hello',
- files: [],
- sessionId: 'a5fefc88-f6c1-44fb-9e98-3d366b1ed589',
- topicId: 'v38snJ0A',
- createdAt: 1717080410895,
- id: 'qOIxEGEB',
- updatedAt: 1717080410895,
- extra: {},
- },
- {
- role: 'assistant',
- content: '...',
- parentId: 'qOIxEGEB',
- sessionId: 'a5fefc88-f6c1-44fb-9e98-3d366b1ed589',
- topicId: 'v38snJ0A',
- createdAt: 1717080410970,
- id: 'w28FcqY5',
- updatedAt: 1717080411485,
- error: {
- body: { error: { errorType: 'NoOpenAIAPIKey' }, provider: 'openai' },
- message: 'OpenAI API Key is empty, please add a custom OpenAI API Key',
- type: 'NoOpenAIAPIKey',
- },
- extra: { fromModel: 'gpt-3.5-turbo', fromProvider: 'openai' },
- },
- ],
- sessionGroups: [
- {
- name: 'Writter',
- sort: 0,
- createdAt: 1706114744425,
- id: 'XlUbvOvL',
- updatedAt: 1706114747468,
- },
- ],
- sessions: [
- {
- config: {
- model: 'gpt-3.5-turbo',
- params: {
- frequency_penalty: 0,
- presence_penalty: 0,
- temperature: 0.6,
- top_p: 1,
- },
- plugins: [],
- systemRole:
- "You are a LobeChat technical operator 🍐🐊. You now need to write a developer's guide for LobeChat as a guide for them to develop LobeChat. This guide will include several sections, and you need to output the corresponding document content based on the user's input.\n\nHere is the technical introduction of LobeChat\n\n LobeChat is an AI conversation application built with the Next.js framework. It uses a series of technology stacks to implement various functions and features.\n\n\n ## Basic Technology Stack\n\n The core technology stack of LobeChat is as follows:\n\n - **Framework**: We chose [Next.js](https://nextjs.org/), a powerful React framework that provides key features such as server-side rendering, routing framework, and Router Handler for our project.\n - **Component Library**: We use [Ant Design (antd)](https://ant.design/) as the basic component library, and introduce [lobe-ui](https://github.com/lobehub/lobe-ui) as our business component library.\n - **State Management**: We use [zustand](https://github.com/pmndrs/zustand), a lightweight and easy-to-use state management library.\n - **Network Request**: We adopt [swr](https://swr.vercel.app/), a React Hooks library for data fetching.\n - **Routing**: We directly use the routing solution provided by [Next.js](https://nextjs.org/) itself.\n - **Internationalization**: We use [i18next](https://www.i18next.com/) to implement multi-language support for the application.\n - **Styling**: We use [antd-style](https://github.com/ant-design/antd-style), a CSS-in-JS library that is compatible with Ant Design.\n - **Unit Testing**: We use [vitest](https://github.com/vitejs/vitest) for unit testing.\n\n ## Folder Directory Structure\n\n The folder directory structure of LobeChat is as follows:\n\n \\`\\`\\`bash\n src\n ├── app # Main logic and state management related code of the application\n ├── components # Reusable UI components\n ├── config # Application configuration files, including client environment variables and server environment variables\n ├── const # Used to define constants, such as action types, route names, etc.\n ├── features # Function modules related to business functions, such as Agent settings, plugin development pop-ups, etc.\n ├── hooks # Custom utility Hooks reused throughout the application\n ├── layout # Layout components of the application, such as navigation bar, sidebar, etc.\n ├── locales # Language files for internationalization\n ├── services # Encapsulated backend service interfaces, such as HTTP requests\n ├── store # Zustand store for state management\n ├── types # TypeScript type definition files\n └── utils # Common utility functions\n \\`\\`\\`\n",
- tts: {
- showAllLocaleVoice: false,
- sttLocale: 'auto',
- ttsService: 'openai',
- voice: { openai: 'alloy' },
- },
- chatConfig: {
- autoCreateTopicThreshold: 2,
- displayMode: 'chat',
- enableAutoCreateTopic: true,
- historyCount: 1,
- },
- openingQuestions: ['Question 1', 'Question 2'],
- openingMessage: 'Hello, I am [LobeChat](https://github.com/lobehub/lobe-chat).',
- },
- group: 'XlUbvOvL',
- meta: {
- avatar: '📝',
- description:
- 'LobeChat is an AI conversation application built with the Next.js framework. I will help you write the development documentation for LobeChat.',
- tags: [
- 'Development Documentation',
- 'Technical Introduction',
- 'next-js',
- 'react',
- 'lobe-chat',
- ],
- title: 'LobeChat Technical Documentation Expert',
- },
- type: 'agent',
- createdAt: '2024-01-24T16:43:12.164Z',
- id: 'a5fefc88-f6c1-44fb-9e98-3d366b1ed589',
- updatedAt: '2024-01-24T16:46:15.226Z',
- pinned: false,
- },
- ],
- topics: [
- {
- title: 'Default Topic',
- sessionId: 'inbox',
- createdAt: 1714236590531,
- id: '2wcF8yaS',
- updatedAt: 1714236590531,
- },
- {
- title: 'Default Topic',
- sessionId: 'a5fefc88-f6c1-44fb-9e98-3d366b1ed589',
- createdAt: 1717080410825,
- id: 'v38snJ0A',
- updatedAt: 1717080410825,
- },
- ],
- version: mockImportData.version,
- },
- { onSuccess: (res) => (result = res) },
- );
-
- expect(result!).toEqual({
- sessionGroups: { added: 1, errors: 0, skips: 0 },
- sessions: { added: 1, errors: 0, skips: 0 },
- topics: { added: 2, errors: 0, skips: 0 },
- messages: { added: 4, errors: 0, skips: 0 },
- });
- });
-
- it('should import real world data', async () => {
- let result: ImportResults;
-
- await service.importData(
- { ...(mockImportData.state as any), version: mockImportData.version },
- {
- onSuccess: (res) => {
- result = res;
- },
- },
- );
-
- expect(result!).toEqual({
- sessionGroups: { added: 2, errors: 0, skips: 0 },
- sessions: { added: 15, errors: 0, skips: 0 },
- topics: { added: 4, errors: 0, skips: 0 },
- messages: { added: 32, errors: 0, skips: 0 },
- });
- });
- });
-});
diff --git a/src/services/import/client.ts b/src/services/import/client.ts
deleted file mode 100644
index 9900632676a..00000000000
--- a/src/services/import/client.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { DataImporterRepos } from '@/database/repositories/dataImporter';
-import { BaseClientService } from '@/services/baseClientService';
-import { useUserStore } from '@/store/user';
-import { ImportStage } from '@/types/importer';
-
-import { IImportService } from './type';
-
-export class ClientService extends BaseClientService implements IImportService {
- private get dataImporter(): DataImporterRepos {
- return new DataImporterRepos(clientDB as any, this.userId);
- }
-
- importSettings: IImportService['importSettings'] = async (settings) => {
- await useUserStore.getState().importAppSettings(settings);
- };
-
- importData: IImportService['importData'] = async (data, callbacks) => {
- callbacks?.onStageChange?.(ImportStage.Importing);
- const time = Date.now();
- try {
- const result = await this.dataImporter.importData(data);
- const duration = Date.now() - time;
-
- callbacks?.onStageChange?.(ImportStage.Success);
- callbacks?.onSuccess?.(result.results, duration);
- } catch (e) {
- console.error(e);
- callbacks?.onStageChange?.(ImportStage.Error);
- const error = e as Error;
-
- callbacks?.onError?.({ code: 'ImportError', httpStatus: 0, message: error.message });
- }
- };
-
- importPgData: IImportService['importPgData'] = async (
- data,
- { callbacks, overwriteExisting } = {},
- ) => {
- callbacks?.onStageChange?.(ImportStage.Importing);
- const time = Date.now();
- try {
- const result = await this.dataImporter.importPgData(
- data,
- overwriteExisting ? 'override' : 'skip',
- );
-
- const duration = Date.now() - time;
-
- callbacks?.onStageChange?.(ImportStage.Success);
- if (result.success) {
- callbacks?.onSuccess?.(result.results, duration);
- } else {
- callbacks?.onError?.({ code: 'ImportError', httpStatus: 0, message: result.error.message });
- }
- } catch (e) {
- console.error(e);
- callbacks?.onStageChange?.(ImportStage.Error);
- const error = e as Error;
-
- callbacks?.onError?.({ code: 'ImportError', httpStatus: 0, message: error.message });
- }
- };
-}
diff --git a/src/services/import/index.ts b/src/services/import/index.ts
index e1d22eae389..4bfa61588e3 100644
--- a/src/services/import/index.ts
+++ b/src/services/import/index.ts
@@ -1,9 +1,3 @@
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const importService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' ? new ServerService() : clientService;
+export const importService = new ServerService();
diff --git a/src/services/message/_deprecated.test.ts b/src/services/message/_deprecated.test.ts
deleted file mode 100644
index acb7c2fa48c..00000000000
--- a/src/services/message/_deprecated.test.ts
+++ /dev/null
@@ -1,398 +0,0 @@
-import {
- ChatMessageError,
- ChatPluginPayload,
- ChatTTS,
- ChatTranslate,
- UIChatMessage,
-} from '@lobechat/types';
-import dayjs from 'dayjs';
-import { Mock, describe, expect, it, vi } from 'vitest';
-
-import { CreateMessageParams, MessageModel } from '@/database/_deprecated/models/message';
-
-import { ClientService } from './_deprecated';
-
-const messageService = new ClientService();
-
-// Mock the MessageModel
-vi.mock('@/database/_deprecated/models/message', () => {
- return {
- MessageModel: {
- create: vi.fn(),
- batchCreate: vi.fn(),
- count: vi.fn(),
- query: vi.fn(),
- delete: vi.fn(),
- bulkDelete: vi.fn(),
- queryBySessionId: vi.fn(),
- update: vi.fn(),
- updatePlugin: vi.fn(),
- batchDelete: vi.fn(),
- clearTable: vi.fn(),
- batchUpdate: vi.fn(),
- queryAll: vi.fn(),
- updatePluginState: vi.fn(),
- },
- };
-});
-
-describe('MessageClientService', () => {
- // Mock data
- const mockMessageId = 'mock-message-id';
- const mockMessage = {
- id: mockMessageId,
- content: 'Mock message content',
- sessionId: 'mock-session-id',
- createdAt: 100,
- updatedAt: 100,
- role: 'user',
- // ... other properties
- } as UIChatMessage;
- const mockMessages = [mockMessage];
-
- beforeEach(() => {
- // Reset all mocks before running each test case
- vi.resetAllMocks();
- });
-
- describe('create', () => {
- it('should create a message and return its id', async () => {
- // Setup
- const createParams = {
- content: 'New message content',
- sessionId: '1',
- // ... other properties
- } as CreateMessageParams;
- (MessageModel.create as Mock).mockResolvedValue({ id: mockMessageId });
-
- // Execute
- const messageId = await messageService.createMessage(createParams);
-
- // Assert
- expect(MessageModel.create).toHaveBeenCalledWith(createParams);
- expect(messageId).toBe(mockMessageId);
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create messages', async () => {
- // Setup
- (MessageModel.batchCreate as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const result = await messageService.batchCreateMessages(mockMessages);
-
- // Assert
- expect(MessageModel.batchCreate).toHaveBeenCalledWith(mockMessages);
- expect(result).toBe(mockMessages);
- });
- });
-
- describe('removeMessage', () => {
- it('should remove a message by id', async () => {
- // Setup
- (MessageModel.delete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await messageService.removeMessage(mockMessageId);
-
- // Assert
- expect(MessageModel.delete).toHaveBeenCalledWith(mockMessageId);
- expect(result).toBe(true);
- });
- });
- describe('removeMessages', () => {
- it('should remove a message by id', async () => {
- // Setup
- (MessageModel.bulkDelete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await messageService.removeMessages([mockMessageId]);
-
- // Assert
- expect(MessageModel.bulkDelete).toHaveBeenCalledWith([mockMessageId]);
- expect(result).toBe(true);
- });
- });
-
- describe('getMessages', () => {
- it('should retrieve messages by sessionId and topicId', async () => {
- // Setup
- const sessionId = 'session-id';
- const topicId = 'topic-id';
- (MessageModel.query as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const messages = await messageService.getMessages(sessionId, topicId);
-
- // Assert
- expect(MessageModel.query).toHaveBeenCalledWith({ sessionId, topicId });
- expect(messages).toEqual(mockMessages.map((i) => ({ ...i, imageList: [] })));
- });
- });
-
- describe('getAllMessagesInSession', () => {
- it('should retrieve all messages in a session', async () => {
- // Setup
- const sessionId = 'session-id';
- (MessageModel.queryBySessionId as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const messages = await messageService.getAllMessagesInSession(sessionId);
-
- // Assert
- expect(MessageModel.queryBySessionId).toHaveBeenCalledWith(sessionId);
- expect(messages).toBe(mockMessages);
- });
- });
-
- describe('removeMessagesByAssistant', () => {
- it('should batch remove messages by assistantId and topicId', async () => {
- // Setup
- const assistantId = 'assistant-id';
- const topicId = 'topic-id';
- (MessageModel.batchDelete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await messageService.removeMessagesByAssistant(assistantId, topicId);
-
- // Assert
- expect(MessageModel.batchDelete).toHaveBeenCalledWith(assistantId, topicId);
- expect(result).toBe(true);
- });
- });
-
- describe('clearAllMessage', () => {
- it('should clear all messages from the table', async () => {
- // Setup
- (MessageModel.clearTable as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await messageService.removeAllMessages();
-
- // Assert
- expect(MessageModel.clearTable).toHaveBeenCalled();
- expect(result).toBe(true);
- });
- });
-
- describe('bindMessagesToTopic', () => {
- it('should batch update messages to bind them to a topic', async () => {
- // Setup
- const topicId = 'topic-id';
- const messageIds = [mockMessageId];
- (MessageModel.batchUpdate as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const result = await messageService.bindMessagesToTopic(topicId, messageIds);
-
- // Assert
- expect(MessageModel.batchUpdate).toHaveBeenCalledWith(messageIds, { topicId });
- expect(result).toBe(mockMessages);
- });
- });
-
- describe('getAllMessages', () => {
- it('should retrieve all messages', async () => {
- // Setup
- (MessageModel.queryAll as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const messages = await messageService.getAllMessages();
-
- // Assert
- expect(MessageModel.queryAll).toHaveBeenCalled();
- expect(messages).toBe(mockMessages);
- });
- });
-
- describe('updateMessageError', () => {
- it('should update the error field of a message', async () => {
- // Setup
- const newError = {
- type: 'InvalidProviderAPIKey',
- message: 'Error occurred',
- } as ChatMessageError;
- (MessageModel.update as Mock).mockResolvedValue({ ...mockMessage, error: newError });
-
- // Execute
- const result = await messageService.updateMessageError(mockMessageId, newError);
-
- // Assert
- expect(MessageModel.update).toHaveBeenCalledWith(mockMessageId, { error: newError });
- expect(result).toEqual({ ...mockMessage, error: newError });
- });
- });
-
- // describe('updateMessagePlugin', () => {
- // it('should update the plugin payload of a message', async () => {
- // // Setup
- // const newPlugin = {
- // type: 'default',
- // apiName: 'abc',
- // arguments: '',
- // identifier: 'plugin1',
- // } as ChatPluginPayload;
- //
- // (MessageModel.update as Mock).mockResolvedValue({ ...mockMessage, plugin: newPlugin });
- //
- // // Execute
- // const result = await messageService.updateMessagePlugin(mockMessageId, newPlugin);
- //
- // // Assert
- // expect(MessageModel.update).toHaveBeenCalledWith(mockMessageId, { plugin: newPlugin });
- // expect(result).toEqual({ ...mockMessage, plugin: newPlugin });
- // });
- // });
-
- describe('updateMessagePluginState', () => {
- it('should update the plugin state of a message', async () => {
- // Setup
- const key = 'stateKey';
- const value = 'stateValue';
- const newPluginState = { [key]: value };
- (MessageModel.updatePluginState as Mock).mockResolvedValue({
- ...mockMessage,
- pluginState: newPluginState,
- });
-
- // Execute
- const result = await messageService.updateMessagePluginState(mockMessageId, { key: value });
-
- // Assert
- expect(MessageModel.updatePluginState).toHaveBeenCalledWith(mockMessageId, { key: value });
- expect(result).toEqual({ ...mockMessage, pluginState: newPluginState });
- });
- });
-
- describe('updateMessagePluginArguments', () => {
- it('should update the plugin arguments object of a message', async () => {
- // Setup
- const key = 'stateKey';
- const value = 'stateValue';
- (MessageModel.updatePlugin as Mock).mockResolvedValue({});
-
- // Execute
- await messageService.updateMessagePluginArguments(mockMessageId, { key: value });
-
- // Assert
- expect(MessageModel.updatePlugin).toHaveBeenCalledWith(mockMessageId, {
- arguments: '{"key":"stateValue"}',
- });
- });
- it('should update the plugin arguments string of a message', async () => {
- // Setup
- const key = 'stateKey';
- const value = 'stateValue';
- (MessageModel.updatePlugin as Mock).mockResolvedValue({});
-
- // Execute
- await messageService.updateMessagePluginArguments(
- mockMessageId,
- JSON.stringify({ key: value }),
- );
-
- // Assert
- expect(MessageModel.updatePlugin).toHaveBeenCalledWith(mockMessageId, {
- arguments: '{"key":"stateValue"}',
- });
- });
- });
-
- describe('countMessages', () => {
- it('should count the total number of messages', async () => {
- // Setup
- const mockCount = 10;
- (MessageModel.count as Mock).mockResolvedValue(mockCount);
-
- // Execute
- const count = await messageService.countMessages();
-
- // Assert
- expect(MessageModel.count).toHaveBeenCalled();
- expect(count).toBe(mockCount);
- });
- });
-
- describe('countTodayMessages', () => {
- it('should count the number of messages created today', async () => {
- // Setup
- const today = dayjs().format('YYYY-MM-DD');
- const mockMessages = [
- { ...mockMessage, createdAt: today },
- { ...mockMessage, createdAt: today },
- { ...mockMessage, createdAt: '2023-01-01' },
- ];
- (MessageModel.queryAll as Mock).mockResolvedValue(mockMessages);
-
- // Execute
- const count = await messageService.countTodayMessages();
-
- // Assert
- expect(MessageModel.queryAll).toHaveBeenCalled();
- expect(count).toBe(2);
- });
- });
-
- describe('updateMessageTTS', () => {
- it('should update the TTS field of a message', async () => {
- // Setup
- const newTTS: ChatTTS = {
- contentMd5: 'abc',
- file: 'file-abc',
- };
-
- (MessageModel.update as Mock).mockResolvedValue({ ...mockMessage, tts: newTTS });
-
- // Execute
- const result = await messageService.updateMessageTTS(mockMessageId, newTTS);
-
- // Assert
- expect(MessageModel.update).toHaveBeenCalledWith(mockMessageId, { tts: newTTS });
- expect(result).toEqual({ ...mockMessage, tts: newTTS });
- });
- });
-
- describe('updateMessageTranslate', () => {
- it('should update the translate field of a message', async () => {
- // Setup
- const newTranslate: ChatTranslate = {
- content: 'Translated text',
- to: 'es',
- };
-
- (MessageModel.update as Mock).mockResolvedValue({ ...mockMessage, translate: newTranslate });
-
- // Execute
- const result = await messageService.updateMessageTranslate(mockMessageId, newTranslate);
-
- // Assert
- expect(MessageModel.update).toHaveBeenCalledWith(mockMessageId, { translate: newTranslate });
- expect(result).toEqual({ ...mockMessage, translate: newTranslate });
- });
- });
-
- describe('hasMessages', () => {
- it('should return true if there are messages', async () => {
- // Setup
- (MessageModel.count as Mock).mockResolvedValue(1);
-
- // Execute
- const result = await messageService.hasMessages();
-
- // Assert
- expect(result).toBe(true);
- });
-
- it('should return false if there are no messages', async () => {
- // Setup
- (MessageModel.count as Mock).mockResolvedValue(0);
-
- // Execute
- const result = await messageService.hasMessages();
-
- // Assert
- expect(result).toBe(false);
- });
- });
-});
diff --git a/src/services/message/_deprecated.ts b/src/services/message/_deprecated.ts
deleted file mode 100644
index db95aef1876..00000000000
--- a/src/services/message/_deprecated.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import {
- ChatFileItem,
- ChatMessageError,
- ChatTTS,
- ChatTranslate,
- CreateMessageParams,
- CreateNewMessageParams,
- ModelRankItem,
- UIChatMessage,
-} from '@lobechat/types';
-import dayjs from 'dayjs';
-
-import { FileModel } from '@/database/_deprecated/models/file';
-import { MessageModel } from '@/database/_deprecated/models/message';
-import { DB_Message } from '@/database/_deprecated/schemas/message';
-
-import { IMessageService } from './type';
-
-export class ClientService implements IMessageService {
- async createMessage(data: CreateMessageParams) {
- const { id } = await MessageModel.create(data);
-
- return id;
- }
-
- async createNewMessage(data: CreateNewMessageParams) {
- const { id } = await MessageModel.create(data as any);
- const messages = await this.getMessages(data.sessionId, data.topicId);
-
- return { id, messages };
- }
-
- // @ts-ignore
- async batchCreateMessages(messages: UIChatMessage[]) {
- return MessageModel.batchCreate(messages);
- }
-
- async getMessages(sessionId: string, topicId?: string): Promise<UIChatMessage[]> {
- const messages = await MessageModel.query({ sessionId, topicId });
-
- const fileList = (await Promise.all(
- messages
- .flatMap((item) => item.files)
- .filter(Boolean)
- .map(async (id) => FileModel.findById(id!)),
- )) as ChatFileItem[];
-
- return messages.map((item) => ({
- ...item,
- imageList: fileList
- .filter((file) => item.files?.includes(file.id) && file.fileType.startsWith('image'))
- .map((file) => ({
- alt: file.name,
- id: file.id,
- url: file.url,
- })),
- }));
- }
-
- async getGroupMessages(groupId: string, topicId?: string): Promise<UIChatMessage[]> {
- // For the deprecated service, group messages are the same as regular messages
- // since the old schema doesn't differentiate between session and group messages
- return this.getMessages(groupId, topicId);
- }
-
- async getAllMessages() {
- return MessageModel.queryAll();
- }
-
- async countMessages() {
- return MessageModel.count();
- }
-
- // @ts-ignore
- async rankModels(): Promise<ModelRankItem[]> {
- throw new Error('Method not implemented.');
- }
-
- // @ts-ignore
- async countWords(): Promise<number> {
- throw new Error('Method not implemented.');
- }
-
- // @ts-ignore
- async getHeatmaps() {
- throw new Error('Method not implemented.');
- }
-
- async countTodayMessages() {
- const topics = await MessageModel.queryAll();
- return topics.filter(
- (item) => dayjs(item.createdAt).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD'),
- ).length;
- }
-
- async getAllMessagesInSession(sessionId: string) {
- return MessageModel.queryBySessionId(sessionId);
- }
-
- async updateMessageError(id: string, error: ChatMessageError) {
- return MessageModel.update(id, { error });
- }
-
- // @ts-ignore
- async updateMessage(id: string, message: Partial<DB_Message>): Promise<any> {
- return MessageModel.update(id, message);
- }
-
- async updateMessageTTS(id: string, tts: Partial<ChatTTS> | false) {
- return MessageModel.update(id, { tts });
- }
-
- async updateMessageTranslate(id: string, translate: Partial<ChatTranslate> | false) {
- return MessageModel.update(id, { translate });
- }
-
- async updateMessagePluginState(id: string, value: Record<string, any>) {
- return MessageModel.updatePluginState(id, value);
- }
-
- async updateMessagePluginArguments(id: string, value: string | Record<string, any>) {
- const args = typeof value === 'string' ? value : JSON.stringify(value);
-
- return MessageModel.updatePlugin(id, { arguments: args });
- }
-
- async bindMessagesToTopic(topicId: string, messageIds: string[]) {
- return MessageModel.batchUpdate(messageIds, { topicId });
- }
-
- async removeMessage(id: string) {
- return MessageModel.delete(id);
- }
-
- async removeMessages(ids: string[]) {
- return MessageModel.bulkDelete(ids);
- }
-
- async removeMessagesByAssistant(assistantId: string, topicId?: string) {
- return MessageModel.batchDelete(assistantId, topicId);
- }
-
- async removeMessagesByGroup(groupId: string, topicId?: string) {
- return MessageModel.batchDelete(groupId, topicId);
- }
-
- async removeAllMessages() {
- return MessageModel.clearTable();
- }
-
- async hasMessages() {
- const number = await this.countMessages();
- return number > 0;
- }
-
- async messageCountToCheckTrace() {
- const number = await this.countMessages();
- return number >= 4;
- }
-
- async updateMessagePluginError() {
- throw new Error('Method not implemented.');
- }
-
- async updateMessageRAG(): Promise<void> {
- throw new Error('Method not implemented.');
- }
-}
diff --git a/src/services/message/client.test.ts b/src/services/message/client.test.ts
deleted file mode 100644
index 6826aab0ad3..00000000000
--- a/src/services/message/client.test.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-import {
- ChatMessageError,
- ChatTTS,
- ChatTranslate,
- CreateMessageParams,
- DBMessageItem,
- UIChatMessage,
-} from '@lobechat/types';
-import { and, eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import {
- files,
- messagePlugins,
- messageTTS,
- messageTranslates,
- messages,
- sessions,
- topics,
- users,
-} from '@/database/schemas';
-
-import { ClientService } from './client';
-
-const userId = 'message-db';
-const sessionId = '1';
-const topicId = 'topic-id';
-
-// Mock data
-const mockMessageId = 'mock-message-id';
-const mockMessage = {
- id: mockMessageId,
- content: 'Mock message content',
- sessionId,
- role: 'user',
-} as UIChatMessage;
-
-const mockMessages = [mockMessage];
-
-beforeEach(async () => {
- await initializeDB();
-
- // 在每个测试用例之前,清空表
- await clientDB.transaction(async (trx) => {
- await trx.delete(users);
- await trx.insert(users).values([{ id: userId }, { id: '456' }]);
-
- await trx.insert(sessions).values([{ id: sessionId, userId }]);
- await trx.insert(topics).values([{ id: topicId, sessionId, userId }]);
- await trx.insert(files).values({
- id: 'f1',
- userId: userId,
- url: 'abc',
- name: 'file-1',
- fileType: 'image/png',
- size: 1000,
- });
- });
-});
-
-afterEach(async () => {
- // 在每个测试用例之后,清空表
- await clientDB.delete(users);
-});
-
-const messageService = new ClientService(userId);
-
-describe('MessageClientService', () => {
- describe('create', () => {
- it('should create a message and return its id', async () => {
- // Setup
- const createParams: CreateMessageParams = {
- content: 'New message content',
- sessionId,
- role: 'user',
- };
-
- // Execute
- const messageId = await messageService.createMessage(createParams);
-
- // Assert
- expect(messageId).toMatch(/^msg_/);
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create messages', async () => {
- // Execute
- await messageService.batchCreateMessages([
- {
- content: 'Mock message content',
- sessionId,
- role: 'user',
- },
- {
- content: 'Mock message content',
- sessionId,
- role: 'user',
- },
- ] as DBMessageItem[]);
- const count = await clientDB.$count(messages);
-
- // Assert
- expect(count).toBe(2);
- });
- });
-
- describe('removeMessage', () => {
- it('should remove a message by id', async () => {
- // Execute
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- await messageService.removeMessage(mockMessageId);
-
- // Assert
- const count = await clientDB.$count(messages);
-
- expect(count).toBe(0);
- });
- });
- describe('removeMessages', () => {
- it('should remove a message by id', async () => {
- // Setup
- await clientDB.insert(messages).values([
- { id: mockMessageId, role: 'user', userId },
- { role: 'assistant', userId },
- ]);
-
- // Execute
- await messageService.removeMessages([mockMessageId]);
-
- // Assert
- const count = await clientDB.$count(messages);
-
- expect(count).toBe(1);
- });
- });
-
- describe('getMessages', () => {
- it('should retrieve messages by sessionId and topicId', async () => {
- // Setup
- await clientDB
- .insert(messages)
- .values({ id: mockMessageId, sessionId, topicId, role: 'user', userId });
-
- // Execute
- const data = await messageService.getMessages(sessionId, topicId);
-
- // Assert
- expect(data[0]).toMatchObject({ id: mockMessageId, role: 'user' });
- });
- });
-
- describe('getAllMessagesInSession', () => {
- it('should retrieve all messages in a session', async () => {
- // Setup
- const sessionId = 'session-id';
- await clientDB.insert(sessions).values([
- { id: 'bbb', userId },
- { id: sessionId, userId },
- ]);
- await clientDB.insert(messages).values([
- { sessionId, topicId, role: 'user', userId },
- { sessionId, topicId, role: 'assistant', userId },
- { sessionId: 'bbb', topicId, role: 'assistant', userId },
- ]);
-
- // Execute
- const data = await messageService.getAllMessagesInSession(sessionId);
-
- // Assert
- expect(data.length).toBe(2);
- });
- });
-
- describe('removeMessagesByAssistant', () => {
- it('should batch remove messages by assistantId and topicId', async () => {
- // Setup
- const assistantId = 'assistant-id';
- const sessionId = 'session-id';
- await clientDB.insert(sessions).values([
- { id: 'bbb', userId },
- { id: sessionId, userId },
- ]);
- await clientDB.insert(messages).values([
- { sessionId, topicId, role: 'user', userId },
- { sessionId, topicId, role: 'assistant', userId },
- { sessionId: 'bbb', topicId, role: 'assistant', userId },
- ]);
-
- // Execute
- await messageService.removeMessagesByAssistant(sessionId, topicId);
-
- // Assert
- const result = await clientDB.query.messages.findMany({
- where: and(eq(messages.sessionId, sessionId), eq(messages.topicId, topicId)),
- });
-
- expect(result.length).toBe(0);
- });
- });
-
- describe('clearAllMessage', () => {
- it('should clear all messages from the table', async () => {
- // Setup
- await clientDB.insert(users).values({ id: 'another' });
- await clientDB.insert(messages).values([
- { id: mockMessageId, role: 'user', userId },
- { role: 'user', userId: 'another' },
- ]);
-
- // Execute
- await messageService.removeAllMessages();
-
- // Assert
- const result = await clientDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
- expect(result.length).toBe(0);
- });
- });
-
- describe('getAllMessages', () => {
- it('should retrieve all messages', async () => {
- await clientDB.insert(messages).values([
- { sessionId, topicId, content: '1', role: 'user', userId },
- { sessionId, topicId, content: '2', role: 'assistant', userId },
- ]);
-
- // Execute
- const data = await messageService.getAllMessages();
-
- // Assert
- expect(data).toMatchObject([
- { sessionId, topicId, content: '1', role: 'user', userId },
- { sessionId, topicId, content: '2', role: 'assistant', userId },
- ]);
- });
- });
-
- describe('updateMessageError', () => {
- it('should update the error field of a message', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- const newError = {
- type: 'InvalidProviderAPIKey',
- message: 'Error occurred',
- } as ChatMessageError;
-
- // Execute
- await messageService.updateMessageError(mockMessageId, newError);
-
- // Assert
- const result = await clientDB.query.messages.findFirst({
- where: eq(messages.id, mockMessageId),
- });
-
- expect(result!.error).toEqual(newError);
- });
- });
-
- // describe('updateMessagePlugin', () => {
- // it('should update the plugin payload of a message', async () => {
- // // Setup
- // const newPlugin = {
- // type: 'default',
- // apiName: 'abc',
- // arguments: '',
- // identifier: 'plugin1',
- // } as ChatPluginPayload;
- //
- // (MessageModel.update as Mock).mockResolvedValue({ ...mockMessage, plugin: newPlugin });
- //
- // // Execute
- // const result = await messageService.updateMessagePlugin(mockMessageId, newPlugin);
- //
- // // Assert
- // expect(MessageModel.update).toHaveBeenCalledWith(mockMessageId, { plugin: newPlugin });
- // expect(result).toEqual({ ...mockMessage, plugin: newPlugin });
- // });
- // });
-
- describe('updateMessagePluginState', () => {
- it('should update the plugin state of a message', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- await clientDB.insert(messagePlugins).values({ id: mockMessageId, userId });
- const key = 'stateKey';
- const value = 'stateValue';
- const newPluginState = { [key]: value };
-
- // Execute
- await messageService.updateMessagePluginState(mockMessageId, { stateKey: value });
-
- // Assert
- const result = await clientDB.query.messagePlugins.findFirst({
- where: eq(messagePlugins.id, mockMessageId),
- });
- expect(result!.state).toEqual(newPluginState);
- });
- });
-
- describe('updateMessagePluginArguments', () => {
- it('should update the plugin arguments object of a message', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- await clientDB.insert(messagePlugins).values({ id: mockMessageId, userId });
- const value = 'stateValue';
-
- // Execute
- await messageService.updateMessagePluginArguments(mockMessageId, { key: value });
-
- // Assert
- const result = await clientDB.query.messagePlugins.findFirst({
- where: eq(messageTTS.id, mockMessageId),
- });
- expect(result).toMatchObject({ arguments: '{"key":"stateValue"}' });
- });
- it('should update the plugin arguments string of a message', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- await clientDB.insert(messagePlugins).values({ id: mockMessageId, userId });
- const value = 'stateValue';
- // Execute
- await messageService.updateMessagePluginArguments(
- mockMessageId,
- JSON.stringify({ abc: value }),
- );
-
- // Assert
- const result = await clientDB.query.messagePlugins.findFirst({
- where: eq(messageTTS.id, mockMessageId),
- });
- expect(result).toMatchObject({ arguments: '{"abc":"stateValue"}' });
- });
- });
-
- describe('countMessages', () => {
- it('should count the total number of messages', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
-
- // Execute
- const count = await messageService.countMessages();
-
- // Assert
- expect(count).toBe(1);
- });
- });
-
- describe('updateMessageTTS', () => {
- it('should update the TTS field of a message', async () => {
- // Setup
- await clientDB
- .insert(files)
- .values({ id: 'file-abc', fileType: 'text', name: 'abc', url: 'abc', size: 100, userId });
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- const newTTS: ChatTTS = { contentMd5: 'abc', file: 'file-abc' };
-
- // Execute
- await messageService.updateMessageTTS(mockMessageId, newTTS);
-
- // Assert
- const result = await clientDB.query.messageTTS.findFirst({
- where: eq(messageTTS.id, mockMessageId),
- });
-
- expect(result).toMatchObject({ contentMd5: 'abc', fileId: 'file-abc', id: mockMessageId });
- });
- });
-
- describe('updateMessageTranslate', () => {
- it('should update the translate field of a message', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
- const newTranslate: ChatTranslate = { content: 'Translated text', to: 'es' };
-
- // Execute
- await messageService.updateMessageTranslate(mockMessageId, newTranslate);
-
- // Assert
- const result = await clientDB.query.messageTranslates.findFirst({
- where: eq(messageTranslates.id, mockMessageId),
- });
-
- expect(result).toMatchObject(newTranslate);
- });
- });
-
- describe('hasMessages', () => {
- it('should return true if there are messages', async () => {
- // Setup
- await clientDB.insert(messages).values({ id: mockMessageId, role: 'user', userId });
-
- // Execute
- const result = await messageService.hasMessages();
-
- // Assert
- expect(result).toBe(true);
- });
-
- it('should return false if there are no messages', async () => {
- // Execute
- const result = await messageService.hasMessages();
-
- // Assert
- expect(result).toBe(false);
- });
- });
-});
diff --git a/src/services/message/client.ts b/src/services/message/client.ts
deleted file mode 100644
index 9861530e84d..00000000000
--- a/src/services/message/client.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { UIChatMessage } from '@lobechat/types';
-
-import { INBOX_SESSION_ID } from '@/const/session';
-import { clientDB } from '@/database/client/db';
-import { MessageModel } from '@/database/models/message';
-import { BaseClientService } from '@/services/baseClientService';
-import { clientS3Storage } from '@/services/file/ClientS3';
-
-import { IMessageService } from './type';
-
-export class ClientService extends BaseClientService implements IMessageService {
- private get messageModel(): MessageModel {
- return new MessageModel(clientDB as any, this.userId);
- }
-
- createMessage: IMessageService['createMessage'] = async ({ sessionId, ...params }) => {
- const { id } = await this.messageModel.create({
- ...params,
- sessionId: sessionId ? (this.toDbSessionId(sessionId) as string) : '',
- });
-
- return id;
- };
-
- createNewMessage: IMessageService['createNewMessage'] = async ({ sessionId, ...params }) => {
- return await this.messageModel.createNewMessage(
- {
- ...params,
- sessionId: sessionId ? (this.toDbSessionId(sessionId) as string) : '',
- },
- {
- postProcessUrl: this.postProcessUrl,
- },
- );
- };
-
- batchCreateMessages: IMessageService['batchCreateMessages'] = async (messages) => {
- return this.messageModel.batchCreate(messages);
- };
-
- getMessages: IMessageService['getMessages'] = async (sessionId, topicId) => {
- const data = await this.messageModel.query(
- {
- sessionId: this.toDbSessionId(sessionId),
- topicId,
- },
- {
- groupAssistantMessages: false,
- postProcessUrl: this.postProcessUrl,
- },
- );
-
- return data as unknown as UIChatMessage[];
- };
-
- getGroupMessages: IMessageService['getGroupMessages'] = async (groupId, topicId) => {
- // Use full query to hydrate fileList/imageList like single chat
- const data = await this.messageModel.query(
- {
- sessionId: groupId,
- topicId,
- },
- {
- groupAssistantMessages: false,
- postProcessUrl: this.postProcessUrl,
- },
- );
-
- return data as unknown as UIChatMessage[];
- };
-
- getAllMessages: IMessageService['getAllMessages'] = async () => {
- const data = await this.messageModel.queryAll();
-
- return data as unknown as UIChatMessage[];
- };
-
- countMessages: IMessageService['countMessages'] = async (params) => {
- return this.messageModel.count(params);
- };
-
- countWords: IMessageService['countWords'] = async (params) => {
- return this.messageModel.countWords(params);
- };
-
- rankModels: IMessageService['rankModels'] = async () => {
- return this.messageModel.rankModels();
- };
-
- getHeatmaps: IMessageService['getHeatmaps'] = async () => {
- return this.messageModel.getHeatmaps();
- };
-
- getAllMessagesInSession: IMessageService['getAllMessagesInSession'] = async (sessionId) => {
- const data = this.messageModel.queryBySessionId(this.toDbSessionId(sessionId));
-
- return data as unknown as UIChatMessage[];
- };
-
- updateMessageError: IMessageService['updateMessageError'] = async (id, error) => {
- return this.messageModel.update(id, { error });
- };
-
- updateMessage: IMessageService['updateMessage'] = async (id, message, options) => {
- return this.messageModel.update(id, message, {
- postProcessUrl: this.postProcessUrl,
- sessionId: options?.sessionId,
- topicId: options?.topicId,
- });
- };
-
- updateMessageTTS: IMessageService['updateMessageTTS'] = async (id, tts) => {
- return this.messageModel.updateTTS(id, tts as any);
- };
-
- updateMessageTranslate: IMessageService['updateMessageTranslate'] = async (id, translate) => {
- return this.messageModel.updateTranslate(id, translate as any);
- };
-
- updateMessagePluginState: IMessageService['updateMessagePluginState'] = async (id, value) => {
- return this.messageModel.updatePluginState(id, value);
- };
-
- updateMessagePluginError: IMessageService['updateMessagePluginError'] = async (id, value) => {
- return this.messageModel.updateMessagePlugin(id, { error: value });
- };
-
- updateMessageRAG: IMessageService['updateMessageRAG'] = async (id, value) => {
- console.log(id, value);
- throw new Error('not implemented');
- };
-
- updateMessagePluginArguments: IMessageService['updateMessagePluginArguments'] = async (
- id,
- value,
- ) => {
- const args = typeof value === 'string' ? value : JSON.stringify(value);
-
- return this.messageModel.updateMessagePlugin(id, { arguments: args });
- };
-
- removeMessage: IMessageService['removeMessage'] = async (id) => {
- return this.messageModel.deleteMessage(id);
- };
-
- removeMessages: IMessageService['removeMessages'] = async (ids) => {
- return this.messageModel.deleteMessages(ids);
- };
-
- removeMessagesByAssistant: IMessageService['removeMessagesByAssistant'] = async (
- sessionId,
- topicId,
- ) => {
- return this.messageModel.deleteMessagesBySession(this.toDbSessionId(sessionId), topicId);
- };
-
- removeMessagesByGroup: IMessageService['removeMessagesByGroup'] = async (groupId, topicId) => {
- return this.messageModel.deleteMessagesBySession(groupId, topicId);
- };
-
- removeAllMessages: IMessageService['removeAllMessages'] = async () => {
- return this.messageModel.deleteAllMessages();
- };
-
- hasMessages: IMessageService['hasMessages'] = async () => {
- const number = await this.countMessages();
- return number > 0;
- };
-
- messageCountToCheckTrace: IMessageService['messageCountToCheckTrace'] = async () => {
- const number = await this.countMessages();
- return number >= 4;
- };
-
- private toDbSessionId = (sessionId: string | undefined) => {
- return sessionId === INBOX_SESSION_ID ? undefined : sessionId;
- };
-
- private postProcessUrl = async (url: string | null, file: any) => {
- const hash = (url as string).replace('client-s3://', '');
- const base64 = await this.getBase64ByFileHash(hash);
-
- return `data:${file.fileType};base64,${base64}`;
- };
-
- private getBase64ByFileHash = async (hash: string) => {
- const fileItem = await clientS3Storage.getObject(hash);
- if (!fileItem) throw new Error('file not found');
-
- return Buffer.from(await fileItem.arrayBuffer()).toString('base64');
- };
-}
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 5edefccdc27..515878ba591 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -1,13 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const messageService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const messageService = new ServerService();
diff --git a/src/services/plugin/_deprecated.test.ts b/src/services/plugin/_deprecated.test.ts
deleted file mode 100644
index fb047ff8888..00000000000
--- a/src/services/plugin/_deprecated.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-import { LobeTool } from '@lobechat/types';
-import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { PluginModel } from '@/database/_deprecated/models/plugin';
-import { DB_Plugin } from '@/database/_deprecated/schemas/plugin';
-import { LobeToolCustomPlugin } from '@/types/tool/plugin';
-
-import { ClientService } from './_deprecated';
-import { InstallPluginParams } from './type';
-
-const pluginService = new ClientService();
-
-// Mocking modules and functions
-
-vi.mock('@/database/_deprecated/models/plugin', () => ({
- PluginModel: {
- getList: vi.fn(),
- create: vi.fn(),
- delete: vi.fn(),
- update: vi.fn(),
- clear: vi.fn(),
- },
-}));
-
-beforeEach(() => {
- vi.resetAllMocks();
-});
-
-describe('PluginService', () => {
- describe('installPlugin', () => {
- it('should install a plugin', async () => {
- // Arrange
- const fakePlugin = {
- identifier: 'test-plugin',
- manifest: { name: 'TestPlugin', version: '1.0.0' } as unknown as LobeChatPluginManifest,
- type: 'plugin',
- } as InstallPluginParams;
- vi.mocked(PluginModel.create).mockResolvedValue(fakePlugin);
-
- // Act
- const installedPlugin = await pluginService.installPlugin(fakePlugin);
-
- // Assert
- expect(PluginModel.create).toHaveBeenCalledWith(fakePlugin);
- expect(installedPlugin).toEqual(fakePlugin);
- });
- });
-
- describe('getInstalledPlugins', () => {
- it('should return a list of installed plugins', async () => {
- // Arrange
- const fakePlugins = [{ identifier: 'test-plugin', type: 'plugin' }] as LobeTool[];
- vi.mocked(PluginModel.getList).mockResolvedValue(fakePlugins as DB_Plugin[]);
-
- // Act
- const installedPlugins = await pluginService.getInstalledPlugins();
-
- // Assert
- expect(PluginModel.getList).toHaveBeenCalled();
- expect(installedPlugins).toEqual(fakePlugins);
- });
- });
-
- describe('uninstallPlugin', () => {
- it('should uninstall a plugin', async () => {
- // Arrange
- const identifier = 'test-plugin';
- vi.mocked(PluginModel.delete).mockResolvedValue();
-
- // Act
- const result = await pluginService.uninstallPlugin(identifier);
-
- // Assert
- expect(PluginModel.delete).toHaveBeenCalledWith(identifier);
- expect(result).toBe(undefined);
- });
- });
-
- describe('createCustomPlugin', () => {
- it('should create a custom plugin', async () => {
- // Arrange
- const customPlugin = {
- identifier: 'custom-plugin',
- manifest: {},
- type: 'customPlugin',
- } as LobeToolCustomPlugin;
- vi.mocked(PluginModel.create).mockResolvedValue(customPlugin);
-
- // Act
- const result = await pluginService.createCustomPlugin(customPlugin);
-
- // Assert
- expect(PluginModel.create).toHaveBeenCalledWith({
- ...customPlugin,
- type: 'customPlugin',
- });
- expect(result).toEqual(customPlugin);
- });
- });
-
- describe('updatePlugin', () => {
- it('should update a plugin', async () => {
- // Arrange
- const id = 'plugin-id';
- const value = { settings: { ab: '1' } } as unknown as LobeToolCustomPlugin;
- vi.mocked(PluginModel.update).mockResolvedValue(1);
-
- // Act
- const result = await pluginService.updatePlugin(id, value);
-
- // Assert
- expect(PluginModel.update).toHaveBeenCalledWith(id, value);
- expect(result).toEqual(undefined);
- });
- });
-
- describe('updatePluginManifest', () => {
- it('should update a plugin manifest', async () => {
- // Arrange
- const id = 'plugin-id';
- const manifest = { name: 'NewPluginManifest' } as unknown as LobeChatPluginManifest;
- vi.mocked(PluginModel.update).mockResolvedValue(1);
-
- // Act
- const result = await pluginService.updatePluginManifest(id, manifest);
-
- // Assert
- expect(PluginModel.update).toHaveBeenCalledWith(id, { manifest });
- expect(result).toEqual(undefined);
- });
- });
-
- describe('removeAllPlugins', () => {
- it('should remove all plugins', async () => {
- // Arrange
- vi.mocked(PluginModel.clear).mockResolvedValue(undefined);
-
- // Act
- const result = await pluginService.removeAllPlugins();
-
- // Assert
- expect(PluginModel.clear).toHaveBeenCalled();
- expect(result).toBe(undefined);
- });
- });
-
- describe('updatePluginSettings', () => {
- it('should update plugin settings', async () => {
- // Arrange
- const id = 'plugin-id';
- const settings = { color: 'blue' };
-
- // Act
- const result = await pluginService.updatePluginSettings(id, settings);
-
- // Assert
- expect(PluginModel.update).toHaveBeenCalledWith(id, { settings });
- expect(result).toEqual(undefined);
- });
- });
-});
diff --git a/src/services/plugin/_deprecated.ts b/src/services/plugin/_deprecated.ts
deleted file mode 100644
index a11fe251896..00000000000
--- a/src/services/plugin/_deprecated.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { LobeTool } from '@lobechat/types';
-import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
-
-import { PluginModel } from '@/database/_deprecated/models/plugin';
-import { LobeToolCustomPlugin } from '@/types/tool/plugin';
-
-import { IPluginService, InstallPluginParams } from './type';
-
-export class ClientService implements IPluginService {
- installPlugin = async (plugin: InstallPluginParams) => {
- return PluginModel.create(plugin);
- };
-
- getInstalledPlugins = () => {
- return PluginModel.getList() as Promise<LobeTool[]>;
- };
-
- uninstallPlugin(identifier: string) {
- return PluginModel.delete(identifier);
- }
-
- async createCustomPlugin(customPlugin: LobeToolCustomPlugin) {
- return PluginModel.create({ ...customPlugin, type: 'customPlugin' });
- }
-
- async updatePlugin(id: string, value: Partial<LobeToolCustomPlugin>) {
- await PluginModel.update(id, value);
- return;
- }
- async updatePluginManifest(id: string, manifest: LobeChatPluginManifest) {
- await PluginModel.update(id, { manifest });
- }
-
- async removeAllPlugins() {
- return PluginModel.clear();
- }
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- async updatePluginSettings(id: string, settings: any, _?: AbortSignal) {
- await PluginModel.update(id, { settings });
- }
-}
diff --git a/src/services/plugin/client.test.ts b/src/services/plugin/client.test.ts
deleted file mode 100644
index 5109e846e54..00000000000
--- a/src/services/plugin/client.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import { LobeTool } from '@lobechat/types';
-import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
-import { eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import { userInstalledPlugins, users } from '@/database/schemas';
-import { LobeToolCustomPlugin } from '@/types/tool/plugin';
-
-import { ClientService } from './client';
-import { InstallPluginParams } from './type';
-
-// Mocking modules and functions
-
-const userId = 'message-db';
-const pluginService = new ClientService(userId);
-
-// Mock data
-beforeEach(async () => {
- await initializeDB();
-
- // 在每个测试用例之前,重置表数据
- await clientDB.transaction(async (trx) => {
- await trx.delete(users);
- await trx.insert(users).values([{ id: userId }, { id: '456' }]);
- });
-});
-
-describe('PluginService', () => {
- describe('installPlugin', () => {
- it('should install a plugin', async () => {
- // Arrange
- const fakePlugin = {
- identifier: 'test-plugin-d',
- manifest: { name: 'TestPlugin', version: '1.0.0' } as unknown as LobeChatPluginManifest,
- type: 'plugin',
- } as InstallPluginParams;
-
- // Act
- await pluginService.installPlugin(fakePlugin);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, fakePlugin.identifier),
- });
- expect(result).toMatchObject(fakePlugin);
- });
- });
-
- describe('getInstalledPlugins', () => {
- it('should return a list of installed plugins', async () => {
- // Arrange
- const fakePlugins = [{ identifier: 'test-plugin', type: 'plugin' }] as LobeTool[];
- await clientDB
- .insert(userInstalledPlugins)
- .values([{ identifier: 'test-plugin', type: 'plugin', userId }]);
- // Act
- const data = await pluginService.getInstalledPlugins();
-
- // Assert
- expect(data).toMatchObject(fakePlugins);
- });
- });
-
- describe('uninstallPlugin', () => {
- it('should uninstall a plugin', async () => {
- // Arrange
- const identifier = 'test-plugin';
- await clientDB.insert(userInstalledPlugins).values([{ identifier, type: 'plugin', userId }]);
-
- // Act
- await pluginService.uninstallPlugin(identifier);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, identifier),
- });
- expect(result).toBe(undefined);
- });
- });
-
- describe('createCustomPlugin', () => {
- it('should create a custom plugin', async () => {
- // Arrange
- const customPlugin = {
- identifier: 'custom-plugin-x',
- manifest: {},
- type: 'customPlugin',
- } as LobeToolCustomPlugin;
-
- // Act
- await pluginService.createCustomPlugin(customPlugin);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, customPlugin.identifier),
- });
- expect(result).toMatchObject(customPlugin);
- });
- });
-
- describe('updatePlugin', () => {
- it('should update a plugin', async () => {
- // Arrange
- const identifier = 'plugin-id';
- const value = { customParams: { ab: '1' } } as unknown as LobeToolCustomPlugin;
- await clientDB.insert(userInstalledPlugins).values([{ identifier, type: 'plugin', userId }]);
-
- // Act
- await pluginService.updatePlugin(identifier, value);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, identifier),
- });
- expect(result).toMatchObject(value);
- });
- });
-
- describe('updatePluginManifest', () => {
- it('should update a plugin manifest', async () => {
- // Arrange
- const identifier = 'plugin-id';
- const manifest = { name: 'NewPluginManifest' } as unknown as LobeChatPluginManifest;
- await clientDB.insert(userInstalledPlugins).values([{ identifier, type: 'plugin', userId }]);
-
- // Act
- await pluginService.updatePluginManifest(identifier, manifest);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, identifier),
- });
- expect(result).toMatchObject({ manifest });
- });
- });
-
- describe('removeAllPlugins', () => {
- it('should remove all plugins', async () => {
- // Arrange
- await clientDB.insert(userInstalledPlugins).values([
- { identifier: '123', type: 'plugin', userId },
- { identifier: '234', type: 'plugin', userId },
- ]);
-
- // Act
- await pluginService.removeAllPlugins();
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findMany({
- where: eq(userInstalledPlugins.userId, userId),
- });
- expect(result.length).toEqual(0);
- });
- });
-
- describe('updatePluginSettings', () => {
- it('should update plugin settings', async () => {
- // Arrange
- const id = 'plugin-id';
- const settings = { color: 'blue' };
- await clientDB
- .insert(userInstalledPlugins)
- .values([{ identifier: id, type: 'plugin', userId }]);
-
- // Act
- await pluginService.updatePluginSettings(id, settings);
-
- // Assert
- const result = await clientDB.query.userInstalledPlugins.findFirst({
- where: eq(userInstalledPlugins.identifier, id),
- });
-
- expect(result).toMatchObject({ settings });
- });
- });
-});
diff --git a/src/services/plugin/client.ts b/src/services/plugin/client.ts
deleted file mode 100644
index 6d515e7ae73..00000000000
--- a/src/services/plugin/client.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { LobeTool } from '@lobechat/types';
-
-import { clientDB } from '@/database/client/db';
-import { PluginModel } from '@/database/models/plugin';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { IPluginService } from './type';
-
-export class ClientService extends BaseClientService implements IPluginService {
- private get pluginModel(): PluginModel {
- return new PluginModel(clientDB as any, this.userId);
- }
-
- installPlugin: IPluginService['installPlugin'] = async (plugin) => {
- await this.pluginModel.create(plugin);
- };
-
- getInstalledPlugins: IPluginService['getInstalledPlugins'] = () => {
- return this.pluginModel.query() as Promise<LobeTool[]>;
- };
-
- uninstallPlugin: IPluginService['uninstallPlugin'] = async (identifier) => {
- await this.pluginModel.delete(identifier);
- };
-
- createCustomPlugin: IPluginService['createCustomPlugin'] = async (customPlugin) => {
- await this.pluginModel.create({ ...customPlugin, type: 'customPlugin' });
- };
-
- updatePlugin: IPluginService['updatePlugin'] = async (id, value) => {
- await this.pluginModel.update(id, value);
- };
-
- updatePluginManifest: IPluginService['updatePluginManifest'] = async (id, manifest) => {
- await this.pluginModel.update(id, { manifest });
- };
-
- removeAllPlugins: IPluginService['removeAllPlugins'] = async () => {
- await this.pluginModel.deleteAll();
- };
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- updatePluginSettings: IPluginService['updatePluginSettings'] = async (id, settings, _?) => {
- await this.pluginModel.update(id, { settings });
- };
-}
diff --git a/src/services/plugin/index.ts b/src/services/plugin/index.ts
index 26caa1e18de..008295a7829 100644
--- a/src/services/plugin/index.ts
+++ b/src/services/plugin/index.ts
@@ -1,13 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const pluginService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const pluginService = new ServerService();
diff --git a/src/services/session/_deprecated.test.ts b/src/services/session/_deprecated.test.ts
deleted file mode 100644
index 810eeba333e..00000000000
--- a/src/services/session/_deprecated.test.ts
+++ /dev/null
@@ -1,440 +0,0 @@
-import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { SessionGroupModel } from '@/database/_deprecated/models/sessionGroup';
-import { LobeAgentConfig } from '@/types/agent';
-import { LobeAgentSession, LobeSessionType, SessionGroups } from '@/types/session';
-
-import { ClientService } from './_deprecated';
-
-const sessionService = new ClientService();
-
-// Mock the SessionModel
-vi.mock('@/database/_deprecated/models/session', () => {
- return {
- SessionModel: {
- create: vi.fn(),
- query: vi.fn(),
- delete: vi.fn(),
- clearTable: vi.fn(),
- update: vi.fn(),
- count: vi.fn(),
- batchCreate: vi.fn(),
- findById: vi.fn(),
- isEmpty: vi.fn(),
- queryByKeyword: vi.fn(),
- updateConfig: vi.fn(),
- queryByGroupIds: vi.fn(),
- updatePinned: vi.fn(),
- duplicate: vi.fn(),
- queryWithGroups: vi.fn(),
- },
- };
-});
-
-// Mock the SessionGroupModel
-vi.mock('@/database/_deprecated/models/sessionGroup', () => {
- return {
- SessionGroupModel: {
- create: vi.fn(),
- query: vi.fn(),
- delete: vi.fn(),
- clear: vi.fn(),
- update: vi.fn(),
- batchCreate: vi.fn(),
- isEmpty: vi.fn(),
- updateOrder: vi.fn(),
- queryByKeyword: vi.fn(),
- updateConfig: vi.fn(),
- queryByGroupIds: vi.fn(),
- },
- };
-});
-
-describe('SessionService', () => {
- const mockSessionId = 'mock-session-id';
- const mockSession = {
- id: mockSessionId,
- type: 'agent',
- meta: { title: 'Mock Session' },
- } as LobeAgentSession;
- const mockSessions = [mockSession];
-
- beforeEach(() => {
- // Reset all mocks before running each test case
- vi.resetAllMocks();
- });
-
- describe('createSession', () => {
- it('should create a new session and return its id', async () => {
- // Setup
- const sessionType = LobeSessionType.Agent;
- const defaultValue = { meta: { title: 'New Session' } } as Partial<LobeAgentSession>;
- (SessionModel.create as Mock).mockResolvedValue(mockSession);
-
- // Execute
- const sessionId = await sessionService.createSession(sessionType, defaultValue);
-
- // Assert
- expect(SessionModel.create).toHaveBeenCalledWith(sessionType, defaultValue);
- expect(sessionId).toBe(mockSessionId);
- });
-
- it('should throw an error if session creation fails', async () => {
- // Setup
- const sessionType = LobeSessionType.Agent;
- const defaultValue = { meta: { title: 'New Session' } } as Partial<LobeAgentSession>;
- (SessionModel.create as Mock).mockResolvedValue(null);
-
- // Execute & Assert
- await expect(sessionService.createSession(sessionType, defaultValue)).rejects.toThrow(
- 'session create Error',
- );
- });
- });
-
- describe('batchCreateSessions', () => {
- it('should batch create sessions', async () => {
- // Setup
- (SessionModel.batchCreate as Mock).mockResolvedValue(mockSessions);
-
- // Execute
- const result = await sessionService.batchCreateSessions(mockSessions);
-
- // Assert
- expect(SessionModel.batchCreate).toHaveBeenCalledWith(mockSessions);
- expect(result).toBe(mockSessions);
- });
- });
-
- describe('getSessionsByType', () => {
- it('should retrieve sessions with their group ids', async () => {
- // Setup
- (SessionModel.query as Mock).mockResolvedValue(mockSessions);
-
- // Execute
- const sessions = await sessionService.getSessionsByType();
-
- // Assert
- expect(SessionModel.query).toHaveBeenCalled();
- expect(sessions).toBe(mockSessions);
- });
-
- it('should retrieve all agent sessions', async () => {
- // Setup
- // Assuming that SessionModel.query has been modified to accept filters
- const agentSessions = mockSessions.filter((session) => session.type === 'agent');
- (SessionModel.query as Mock).mockResolvedValue(agentSessions);
-
- // Execute
- const result = await sessionService.getSessionsByType('agent');
-
- // Assert
- // Assuming that SessionModel.query would be called with a filter for agents
- expect(SessionModel.query).toHaveBeenCalled(); // Add filter argument if applicable
- expect(result).toBe(agentSessions);
- });
- });
-
- describe('removeSession', () => {
- it('should remove a session by its id', async () => {
- // Setup
- (SessionModel.delete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await sessionService.removeSession(mockSessionId);
-
- // Assert
- expect(SessionModel.delete).toHaveBeenCalledWith(mockSessionId);
- expect(result).toBe(true);
- });
- });
-
- describe('removeAllSessions', () => {
- it('should clear all sessions from the table', async () => {
- // Setup
- (SessionModel.clearTable as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await sessionService.removeAllSessions();
-
- // Assert
- expect(SessionModel.clearTable).toHaveBeenCalled();
- expect(result).toBe(true);
- });
- });
-
- describe('updateSession', () => {
- it('should update the group of a session', async () => {
- // Setup
- const groupId = 'new-group';
- (SessionModel.update as Mock).mockResolvedValue({ ...mockSession, group: groupId });
-
- // Execute
- const result = await sessionService.updateSession(mockSessionId, { group: groupId });
-
- // Assert
- expect(SessionModel.update).toHaveBeenCalledWith(mockSessionId, { group: groupId });
- expect(result).toEqual({ ...mockSession, group: groupId });
- });
-
- it('should update the meta of a session', async () => {
- // Setup
- const newMeta = { description: 'Updated description' };
- (SessionModel.update as Mock).mockResolvedValue({ ...mockSession, meta: newMeta });
-
- // Execute
- const result = await sessionService.updateSession(mockSessionId, { meta: newMeta });
-
- // Assert
- expect(SessionModel.update).toHaveBeenCalledWith(mockSessionId, { meta: newMeta });
- expect(result).toEqual({ ...mockSession, meta: newMeta });
- });
-
- it('should update the pinned status of a session', async () => {
- // Setup
- const pinned = true;
-
- // Execute
- await sessionService.updateSession(mockSessionId, { pinned });
-
- // Assert
- expect(SessionModel.update).toHaveBeenCalledWith(mockSessionId, { pinned: 1 });
- });
- });
-
- describe('updateSessionConfig', () => {
- it('should update the config of a session', async () => {
- // Setup
- const newConfig = { model: 'abc' } as LobeAgentConfig;
- (SessionModel.updateConfig as Mock).mockResolvedValue({ ...mockSession, config: newConfig });
-
- // Execute
- const result = await sessionService.updateSessionConfig(mockSessionId, newConfig);
-
- // Assert
- expect(SessionModel.updateConfig).toHaveBeenCalledWith(mockSessionId, newConfig);
- expect(result).toEqual({ ...mockSession, config: newConfig });
- });
- });
-
- describe('countSessions', () => {
- it('should return false if no sessions exist', async () => {
- // Setup
- (SessionModel.count as Mock).mockResolvedValue(0);
-
- // Execute
- const result = await sessionService.countSessions();
-
- // Assert
- expect(SessionModel.count).toHaveBeenCalled();
- expect(result).toBe(0);
- });
-
- it('should return true if sessions exist', async () => {
- // Setup
- (SessionModel.count as Mock).mockResolvedValue(1);
-
- // Execute
- const result = await sessionService.countSessions();
-
- // Assert
- expect(SessionModel.count).toHaveBeenCalled();
- expect(result).toBe(1);
- });
- });
-
- describe('hasSessions', () => {
- it('should return false if no sessions exist', async () => {
- // Setup
- (SessionModel.count as Mock).mockResolvedValue(0);
-
- // Execute
- const result = await sessionService.hasSessions();
-
- // Assert
- expect(SessionModel.count).toHaveBeenCalled();
- expect(result).toBe(false);
- });
-
- it('should return true if sessions exist', async () => {
- // Setup
- (SessionModel.count as Mock).mockResolvedValue(1);
-
- // Execute
- const result = await sessionService.hasSessions();
-
- // Assert
- expect(SessionModel.count).toHaveBeenCalled();
- expect(result).toBe(true);
- });
- });
-
- describe('searchSessions', () => {
- it('should return sessions that match the keyword', async () => {
- // Setup
- const keyword = 'search';
- (SessionModel.queryByKeyword as Mock).mockResolvedValue(mockSessions);
-
- // Execute
- const result = await sessionService.searchSessions(keyword);
-
- // Assert
- expect(SessionModel.queryByKeyword).toHaveBeenCalledWith(keyword);
- expect(result).toBe(mockSessions);
- });
- });
-
- describe('cloneSession', () => {
- it('should duplicate a session and return its id', async () => {
- // Setup
- const newTitle = 'Duplicated Session';
- (SessionModel.duplicate as Mock).mockResolvedValue({
- ...mockSession,
- id: 'duplicated-session-id',
- });
-
- // Execute
- const duplicatedSessionId = await sessionService.cloneSession(mockSessionId, newTitle);
-
- // Assert
- expect(SessionModel.duplicate).toHaveBeenCalledWith(mockSessionId, newTitle);
- expect(duplicatedSessionId).toBe('duplicated-session-id');
- });
- });
-
- describe('getGroupedSessions', () => {
- it('should retrieve sessions with their group', async () => {
- // Setup
- (SessionModel.queryWithGroups as Mock).mockResolvedValue(mockSessions);
-
- // Execute
- const sessionsWithGroup = await sessionService.getGroupedSessions();
-
- // Assert
- expect(SessionModel.queryWithGroups).toHaveBeenCalled();
- expect(sessionsWithGroup).toBe(mockSessions);
- });
- });
-
- // SessionGroup related tests
- describe('createSessionGroup', () => {
- it('should create a new session group and return its id', async () => {
- // Setup
- const groupName = 'New Group';
- const sort = 1;
- (SessionGroupModel.create as Mock).mockResolvedValue({
- id: 'new-group-id',
- name: groupName,
- sort,
- });
-
- // Execute
- const groupId = await sessionService.createSessionGroup(groupName, sort);
-
- // Assert
- expect(SessionGroupModel.create).toHaveBeenCalledWith(groupName, sort);
- expect(groupId).toBe('new-group-id');
- });
- });
-
- describe('batchCreateSessionGroups', () => {
- it('should batch create session groups', async () => {
- // Setup
- const groups = [
- { id: 'group-1', name: 'Group 1', sort: 1 },
- { id: 'group-2', name: 'Group 2', sort: 2 },
- ] as SessionGroups;
-
- (SessionGroupModel.batchCreate as Mock).mockResolvedValue(groups);
-
- // Execute
- const result = await sessionService.batchCreateSessionGroups(groups);
-
- // Assert
- expect(SessionGroupModel.batchCreate).toHaveBeenCalledWith(groups);
- expect(result).toBe(groups);
- });
- });
-
- describe('removeSessionGroup', () => {
- it('should remove a session group by its id', async () => {
- // Setup
- const removeChildren = true;
- (SessionGroupModel.delete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await sessionService.removeSessionGroup('group-id', removeChildren);
-
- // Assert
- expect(SessionGroupModel.delete).toHaveBeenCalledWith('group-id', removeChildren);
- expect(result).toBe(true);
- });
- });
-
- describe('clearSessionGroups', () => {
- it('should clear all session groups', async () => {
- // Setup
- (SessionGroupModel.clear as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await sessionService.removeSessionGroups();
-
- // Assert
- expect(SessionGroupModel.clear).toHaveBeenCalled();
- expect(result).toBe(true);
- });
- });
-
- describe('getSessionGroups', () => {
- it('should retrieve all session groups', async () => {
- // Setup
- const groups = [
- { id: 'group-1', name: 'Group 1', sort: 1 },
- { id: 'group-2', name: 'Group 2', sort: 2 },
- ];
- (SessionGroupModel.query as Mock).mockResolvedValue(groups);
-
- // Execute
- const result = await sessionService.getSessionGroups();
-
- // Assert
- expect(SessionGroupModel.query).toHaveBeenCalled();
- expect(result).toBe(groups);
- });
- });
-
- describe('updateSessionGroup', () => {
- it('should update a session group', async () => {
- // Setup
- const groupId = 'group-1';
- const data = { name: 'Updated Group', sort: 2 };
- (SessionGroupModel.update as Mock).mockResolvedValue({ id: groupId, ...data });
-
- // Execute
- const result = await sessionService.updateSessionGroup(groupId, data);
-
- // Assert
- expect(SessionGroupModel.update).toHaveBeenCalledWith(groupId, data);
- expect(result).toEqual({ id: groupId, ...data });
- });
- });
-
- describe('updateSessionGroupOrder', () => {
- it('should update the order of session groups', async () => {
- // Setup
- const sortMap = [
- { id: 'group-1', sort: 2 },
- { id: 'group-2', sort: 1 },
- ];
- (SessionGroupModel.updateOrder as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await sessionService.updateSessionGroupOrder(sortMap);
-
- // Assert
- expect(SessionGroupModel.updateOrder).toHaveBeenCalledWith(sortMap);
- expect(result).toBe(true);
- });
- });
-});
diff --git a/src/services/session/_deprecated.ts b/src/services/session/_deprecated.ts
deleted file mode 100644
index 4bc0c3cc972..00000000000
--- a/src/services/session/_deprecated.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import type { PartialDeep } from 'type-fest';
-
-import { INBOX_SESSION_ID } from '@/const/session';
-import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { SessionGroupModel } from '@/database/_deprecated/models/sessionGroup';
-import { UserModel } from '@/database/_deprecated/models/user';
-import { useUserStore } from '@/store/user';
-import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';
-import { MetaData } from '@/types/meta';
-import {
- ChatSessionList,
- LobeAgentSession,
- LobeSessionType,
- LobeSessions,
- SessionGroupItem,
- SessionGroups,
-} from '@/types/session';
-import { merge } from '@/utils/merge';
-
-import { ISessionService } from './type';
-
-export class ClientService implements ISessionService {
- async createSession(
- type: LobeSessionType,
- defaultValue: Partial<LobeAgentSession>,
- ): Promise<string> {
- const item = await SessionModel.create(type, defaultValue);
- if (!item) {
- throw new Error('session create Error');
- }
- return item.id;
- }
-
- async batchCreateSessions(importSessions: LobeSessions) {
- // @ts-ignore
- return SessionModel.batchCreate(importSessions);
- }
-
- async cloneSession(id: string, newTitle: string): Promise<string | undefined> {
- const res = await SessionModel.duplicate(id, newTitle);
-
- if (res) return res?.id;
- }
-
- async getGroupedSessions(): Promise<ChatSessionList> {
- return SessionModel.queryWithGroups();
- }
-
- async getSessionConfig(id: string): Promise<LobeAgentConfig> {
- if (!id || id === INBOX_SESSION_ID) {
- return (await UserModel.getAgentConfig()) || DEFAULT_AGENT_CONFIG;
- }
-
- const res = await SessionModel.findById(id);
-
- if (!res) throw new Error('Session not found');
-
- return res.config as LobeAgentConfig;
- }
-
- async getSessionsByType(type: 'agent' | 'group' | 'all' = 'all'): Promise<LobeSessions> {
- switch (type) {
- // TODO: add a filter to get only agents or agents
- case 'group': {
- return SessionModel.query();
- }
- case 'agent': {
- return SessionModel.query();
- }
-
- case 'all': {
- return SessionModel.query();
- }
- }
- }
-
- async getAllAgents(): Promise<LobeSessions> {
- // TODO: add a filter to get only agents
- return SessionModel.query();
- }
-
- async countSessions() {
- return SessionModel.count();
- }
-
- // @ts-ignore
- async rankSessions() {
- throw new Error('Method not implemented.');
- }
-
- async hasSessions() {
- return (await this.countSessions()) !== 0;
- }
-
- async searchSessions(keyword: string) {
- return SessionModel.queryByKeyword(keyword);
- }
-
- async updateSession(
- id: string,
- data: Partial<Pick<LobeAgentSession, 'group' | 'meta' | 'pinned'>>,
- ) {
- const pinned = typeof data.pinned === 'boolean' ? (data.pinned ? 1 : 0) : undefined;
- const prev = await SessionModel.findById(id);
-
- return SessionModel.update(id, merge(prev, { ...data, pinned }));
- }
-
- async updateSessionConfig(
- activeId: string,
- config: PartialDeep<LobeAgentConfig>,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _?: AbortSignal,
- ) {
- // TODO: 需要删除这部分处理逻辑
- // 后续直接给用户创建一个 inbox 的 session
- if (activeId === INBOX_SESSION_ID) {
- return useUserStore.getState().updateDefaultAgent({ config });
- }
-
- return SessionModel.updateConfig(activeId, config);
- }
-
- async updateSessionMeta(
- activeId: string,
- meta: Partial<MetaData>,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _?: AbortSignal,
- ) {
- // inbox 不允许修改 meta
- if (activeId === INBOX_SESSION_ID) return;
-
- return SessionModel.update(activeId, { meta });
- }
-
- async updateSessionChatConfig(
- activeId: string,
- config: PartialDeep<LobeAgentChatConfig>,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _?: AbortSignal,
- ) {
- return this.updateSessionConfig(activeId, { chatConfig: config });
- }
-
- async removeSession(id: string) {
- return SessionModel.delete(id);
- }
-
- async removeAllSessions() {
- return SessionModel.clearTable();
- }
-
- // ************************************** //
- // *********** SessionGroup *********** //
- // ************************************** //
-
- async createSessionGroup(name: string, sort?: number) {
- const item = await SessionGroupModel.create(name, sort);
- if (!item) {
- throw new Error('session group create Error');
- }
-
- return item.id;
- }
-
- async batchCreateSessionGroups(groups: SessionGroups) {
- return SessionGroupModel.batchCreate(groups);
- }
-
- async removeSessionGroup(id: string, removeChildren?: boolean) {
- return SessionGroupModel.delete(id, removeChildren);
- }
-
- async updateSessionGroup(id: string, data: Partial<SessionGroupItem>) {
- return SessionGroupModel.update(id, data as any);
- }
-
- async updateSessionGroupOrder(sortMap: { id: string; sort: number }[]) {
- return SessionGroupModel.updateOrder(sortMap);
- }
-
- async getSessionGroups(): Promise<SessionGroupItem[]> {
- return SessionGroupModel.query();
- }
-
- async removeSessionGroups() {
- return SessionGroupModel.clear();
- }
-}
diff --git a/src/services/session/client.test.ts b/src/services/session/client.test.ts
deleted file mode 100644
index a750a5e0b8a..00000000000
--- a/src/services/session/client.test.ts
+++ /dev/null
@@ -1,413 +0,0 @@
-import { eq, not } from 'drizzle-orm';
-import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { INBOX_SESSION_ID } from '@/const/session';
-import { clientDB, initializeDB } from '@/database/client/db';
-import {
- NewSession,
- SessionItem,
- agents,
- agentsToSessions,
- sessionGroups,
- sessions,
- users,
-} from '@/database/schemas';
-import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';
-import { LobeAgentSession, LobeSessionType, SessionGroups } from '@/types/session';
-
-import { ClientService } from './client';
-
-const userId = 'message-db';
-const sessionService = new ClientService(userId);
-
-const mockSessionId = 'mock-session-id';
-const mockAgentId = 'agent-id';
-
-// Mock data
-beforeEach(async () => {
- await initializeDB();
-
- // 在每个测试用例之前,清空表
- await clientDB.transaction(async (trx) => {
- await trx.insert(users).values([{ id: userId }, { id: '456' }]);
- await trx.insert(sessions).values([{ id: mockSessionId, userId }]);
- await trx.insert(agents).values([{ id: mockAgentId, userId }]);
- await trx
- .insert(agentsToSessions)
- .values([{ agentId: mockAgentId, sessionId: mockSessionId, userId }]);
- await trx.insert(sessionGroups).values([
- { id: 'group-1', name: 'group-A', sort: 2, userId },
- { id: 'group-2', name: 'group-B', sort: 1, userId },
- { id: 'group-4', name: 'group-C', sort: 1, userId: '456' },
- ]);
- });
-});
-
-afterEach(async () => {
- // 在每个测试用例之后,清空表
- await clientDB.delete(users);
-});
-
-describe('SessionService', () => {
- const mockSession = {
- id: mockSessionId,
- type: 'agent',
- meta: { title: 'Mock Session' },
- } as LobeAgentSession;
-
- describe('createSession', () => {
- it('should create a new session and return its id', async () => {
- // Setup
- const sessionType = LobeSessionType.Agent;
- const defaultValue = { meta: { title: 'New Session' } } as Partial<LobeAgentSession>;
-
- // Execute
- const sessionId = await sessionService.createSession(sessionType, defaultValue);
-
- // Assert
- expect(sessionId).toMatch(/^ssn_/);
- });
- });
-
- describe('removeSession', () => {
- it('should remove a session by its id', async () => {
- // Execute
- await sessionService.removeSession(mockSessionId);
-
- // Assert
-
- const result = await clientDB.query.sessions.findFirst({
- where: eq(sessions.id, mockSessionId),
- });
- // Assert
- expect(result).toBeUndefined();
- });
- });
-
- describe('removeAllSessions', () => {
- it('should clear all sessions from the table', async () => {
- // Setup
- await clientDB
- .insert(sessions)
- .values([{ userId: userId }, { userId: userId }, { userId: userId }]);
-
- // Execute
- await sessionService.removeAllSessions();
-
- // Assert
- const result = await clientDB.query.sessions.findMany({
- where: eq(sessionGroups.userId, userId),
- });
-
- expect(result.length).toBe(0);
- });
- });
-
- describe('updateSession', () => {
- it('should update the group of a session', async () => {
- // Setup
- const groupId = 'group-1';
-
- // Execute
- await sessionService.updateSession(mockSessionId, { group: groupId });
-
- // Assert
- const result = await clientDB.query.sessions.findFirst({
- where: eq(sessions.id, mockSessionId),
- });
- expect(result).toMatchObject({ groupId });
- });
-
- it('should update the pinned status of a session', async () => {
- // Setup
- const pinned = true;
-
- // Execute
- await sessionService.updateSession(mockSessionId, { pinned });
-
- // Assert
- const result = await clientDB.query.sessions.findFirst({
- where: eq(sessions.id, mockSessionId),
- });
-
- expect(result!.pinned).toBeTruthy();
- });
- });
-
- describe('updateSessionConfig', () => {
- it('should update the config of a session', async () => {
- // Setup
- const newConfig = { model: 'abc' } as LobeAgentConfig;
-
- // Execute
- await sessionService.updateSessionConfig(mockSessionId, newConfig);
-
- // Assert
- const result = await sessionService.getSessionConfig(mockSessionId);
- expect(result).toMatchObject(newConfig);
- });
- });
-
- describe('countSessions', () => {
- it('should return false if no sessions exist', async () => {
- await clientDB.delete(sessions);
-
- // Execute
- const result = await sessionService.countSessions();
-
- // Assert
- expect(result).toBe(0);
- });
-
- it('should return true if sessions exist', async () => {
- // Setup
- await clientDB.delete(sessions);
- await clientDB.insert(sessions).values([{ userId }]);
-
- // Execute
- const result = await sessionService.countSessions();
-
- // Assert
- expect(result).toBe(1);
- });
- });
-
- describe('searchSessions', () => {
- it('should return sessions that match the keyword', async () => {
- // Setup
- await clientDB.insert(agents).values({ userId, id: 'agent-1', title: 'Session Name' });
- await clientDB
- .insert(agentsToSessions)
- .values({ agentId: 'agent-1', sessionId: mockSessionId, userId });
-
- // Execute
- const keyword = 'Name';
- const result = await sessionService.searchSessions(keyword);
-
- // Assert
- // TODO: 后续需要把这个搜索的标题和描述都加上,现在这个 client 搜索会有问题
- expect(result).toMatchObject([{ id: mockSessionId }]);
- });
- });
-
- describe('cloneSession', () => {
- it('should duplicate a session and return its id', async () => {
- // Setup
- const newTitle = 'Duplicated Session';
- const session: NewSession = {
- id: 'duplicated-session-id',
- title: '123',
- userId,
- };
- await clientDB.insert(sessions).values([session]);
- await clientDB.insert(agents).values({ userId, id: 'agent-1' });
- await clientDB
- .insert(agentsToSessions)
- .values({ agentId: 'agent-1', sessionId: 'duplicated-session-id', userId });
-
- // Execute
- const duplicatedSessionId = await sessionService.cloneSession(mockSessionId, newTitle);
-
- // Assert
-
- const result = await clientDB.query.sessions.findFirst({
- where: eq(sessions.id, duplicatedSessionId!),
- });
- expect(result).toMatchObject({ title: 'Duplicated Session' });
- });
- });
-
- describe('getGroupedSessions', () => {
- it('should retrieve sessions with their group', async () => {
- // Execute
- const sessionsWithGroup = await sessionService.getGroupedSessions();
-
- expect(sessionsWithGroup).toMatchObject({
- sessionGroups: [
- { id: 'group-2', name: 'group-B', sort: 1 },
- { id: 'group-1', name: 'group-A', sort: 2 },
- ],
- sessions: [{ id: 'mock-session-id', type: 'agent' }],
- });
- });
- });
-
- describe('getSessionsByType', () => {
- it('should get sessions by type "all"', async () => {
- const sessions = await sessionService.getSessionsByType('all');
- expect(sessions).toBeDefined();
- });
-
- it('should get sessions by type "agent"', async () => {
- const sessions = await sessionService.getSessionsByType('agent');
- expect(sessions).toBeDefined();
- });
-
- it('should get sessions by type "group"', async () => {
- const sessions = await sessionService.getSessionsByType('group');
- expect(sessions).toBeDefined();
- });
- });
-
- describe('getSessionConfig', () => {
- it.skip('should get default config for INBOX_SESSION_ID', async () => {
- const config = await sessionService.getSessionConfig(INBOX_SESSION_ID);
- expect(config).toBeDefined();
- });
-
- it('should throw error for non-existent session', async () => {
- await expect(sessionService.getSessionConfig('non-existent')).rejects.toThrow(
- 'Session not found',
- );
- });
- });
-
- describe('updateSessionMeta', () => {
- it('should not update meta for INBOX_SESSION_ID', async () => {
- const result = await sessionService.updateSessionMeta(INBOX_SESSION_ID, {
- title: 'New Title',
- });
- expect(result).toBeUndefined();
- });
-
- it('should update meta for normal session', async () => {
- const meta = { title: 'Updated Title' };
- await sessionService.updateSessionMeta(mockSessionId, meta);
-
- const session = await clientDB.query.sessions.findFirst({
- where: eq(sessions.id, mockSessionId),
- });
- expect(session).toBeDefined();
- });
- });
-
- describe('updateSessionChatConfig', () => {
- it('should update chat config', async () => {
- const chatConfig = { temperature: 0.8 } as Partial<LobeAgentChatConfig>;
- const result = await sessionService.updateSessionChatConfig(mockSessionId, chatConfig);
- expect(result).toBeDefined();
- });
- });
-
- describe('model getters', () => {
- it('should return session model instance', () => {
- // @ts-ignore - accessing private getter
- const model = sessionService.sessionModel;
- expect(model).toBeDefined();
- });
-
- it('should return session group model instance', () => {
- // @ts-ignore - accessing private getter
- const model = sessionService.sessionGroupModel;
- expect(model).toBeDefined();
- });
- });
-
- // SessionGroup related tests
- describe('createSessionGroup', () => {
- it('should create a new session group and return its id', async () => {
- // Setup
- const groupName = 'New Group';
- const sort = 1;
-
- // Execute
- const groupId = await sessionService.createSessionGroup(groupName, sort);
-
- // Assert
- expect(groupId).toMatch(/^sg_/);
-
- const result = await clientDB.query.sessionGroups.findFirst({
- where: eq(sessionGroups.id, groupId),
- });
-
- expect(result).toMatchObject({ id: groupId, name: groupName, sort });
- });
- });
-
- describe('removeSessionGroup', () => {
- it('should remove a session group by its id', async () => {
- const groupId = 'group-1';
- // Execute
- await sessionService.removeSessionGroup(groupId);
-
- const result = await clientDB.query.sessionGroups.findFirst({
- where: eq(sessionGroups.id, groupId),
- });
- // Assert
- expect(result).toBeUndefined();
- });
- });
-
- describe('clearSessionGroups', () => {
- it('should clear all session groups', async () => {
- // Execute
- await sessionService.removeSessionGroups();
-
- // Assert
- const result = await clientDB.query.sessionGroups.findMany({
- where: eq(sessionGroups.userId, userId),
- });
-
- expect(result.length).toBe(0);
-
- const result2 = await clientDB.query.sessionGroups.findMany({
- where: not(eq(sessionGroups.userId, userId)),
- });
-
- expect(result2.length).toBeGreaterThan(0);
- });
- });
-
- describe('getSessionGroups', () => {
- it('should retrieve all session groups', async () => {
- // Execute
- const result = await sessionService.getSessionGroups();
-
- // Assert
- const groups = [
- { id: 'group-2', name: 'group-B', sort: 1 },
- { id: 'group-1', name: 'group-A', sort: 2 },
- ];
- expect(result).toMatchObject(groups);
- });
- });
-
- describe('updateSessionGroup', () => {
- it('should update a session group', async () => {
- // Setup
- const groupId = 'group-1';
- const data = { name: 'Updated Group', sort: 2 };
-
- // Execute
- await sessionService.updateSessionGroup(groupId, data);
-
- // Assert
- const result = await clientDB.query.sessionGroups.findFirst({
- where: eq(sessionGroups.id, groupId),
- });
- expect(result).toMatchObject({ id: groupId, ...data });
- });
- });
-
- describe('updateSessionGroupOrder', () => {
- it('should update the order of session groups', async () => {
- // Setup
- const sortMap = [
- { id: 'group-1', sort: 2 },
- { id: 'group-2', sort: 1 },
- ];
-
- // Execute
- await sessionService.updateSessionGroupOrder(sortMap);
-
- // Assert
- const data = await clientDB.query.sessionGroups.findMany({
- where: eq(sessionGroups.userId, userId),
- });
- expect(data).toMatchObject([
- { id: 'group-1', sort: 2 },
- { id: 'group-2', sort: 1 },
- ]);
- });
- });
-});
diff --git a/src/services/session/client.ts b/src/services/session/client.ts
deleted file mode 100644
index 6e9989ba33f..00000000000
--- a/src/services/session/client.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-import { AgentItem, LobeAgentConfig } from '@lobechat/types';
-
-import { INBOX_SESSION_ID } from '@/const/session';
-import { clientDB } from '@/database/client/db';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import { SessionModel } from '@/database/models/session';
-import { SessionGroupModel } from '@/database/models/sessionGroup';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { ISessionService } from './type';
-
-export class ClientService extends BaseClientService implements ISessionService {
- private get sessionModel(): SessionModel {
- return new SessionModel(clientDB as any, this.userId);
- }
-
- private get sessionGroupModel(): SessionGroupModel {
- return new SessionGroupModel(clientDB as any, this.userId);
- }
-
- private get chatGroupModel(): ChatGroupModel {
- return new ChatGroupModel(clientDB as any, this.userId);
- }
-
- hasSessions: ISessionService['hasSessions'] = async () => {
- const result = await this.countSessions();
- return result === 0;
- };
-
- createSession: ISessionService['createSession'] = async (type, data) => {
- const { config, group, meta, ...session } = data;
-
- const item = await this.sessionModel.create({
- config: { ...config, ...meta } as any,
- session: { ...session, groupId: group },
- type,
- });
- if (!item) {
- throw new Error('session create Error');
- }
- return item.id;
- };
-
- batchCreateSessions: ISessionService['batchCreateSessions'] = async (importSessions) => {
- // @ts-ignore
- return this.sessionModel.batchCreate(importSessions);
- };
-
- cloneSession: ISessionService['cloneSession'] = async (id, newTitle) => {
- const res = await this.sessionModel.duplicate(id, newTitle);
-
- if (res) return res?.id;
- };
-
- getGroupedSessions: ISessionService['getGroupedSessions'] = async () => {
- const { sessions, sessionGroups } = await this.sessionModel.queryWithGroups();
- const chatGroups = await this.chatGroupModel.queryWithMemberDetails();
-
- const groupSessions = chatGroups.map((group) => {
- const { title, description, avatar, backgroundColor, groupId, ...rest } = group;
- return {
- ...rest,
- group: groupId, // Map groupId to group for consistent API
- meta: { avatar, backgroundColor, description, title },
- type: 'group' as const,
- };
- });
-
- const allSessions = [...sessions, ...groupSessions].sort(
- (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
- );
-
- return { sessionGroups, sessions: allSessions };
- };
-
- getSessionConfig: ISessionService['getSessionConfig'] = async (id) => {
- if (id === INBOX_SESSION_ID) {
- const item = await this.sessionModel.findByIdOrSlug(INBOX_SESSION_ID);
-
- // if there is no session for user, create one
- if (!item) {
- const defaultAgentConfig =
- window.global_serverConfigStore.getState().serverConfig.defaultAgent?.config || {};
-
- await this.sessionModel.createInbox(defaultAgentConfig);
- }
- }
-
- const res = await this.sessionModel.findByIdOrSlug(id);
-
- if (!res) throw new Error('Session not found');
-
- return res.agent as LobeAgentConfig;
- };
-
- /**
- * 这个方法要对应移除的
- */
- // @ts-ignore
- getSessionsByType: ISessionService['getSessionsByType'] = async (type = 'all') => {
- switch (type) {
- // TODO: add a filter to get only agents or agents
- case 'group':
- case 'agent':
- case 'all': {
- return this.sessionModel.query();
- }
- }
- };
-
- countSessions: ISessionService['countSessions'] = async (params) => {
- return this.sessionModel.count(params);
- };
-
- rankSessions: ISessionService['rankSessions'] = async (limit) => {
- return this.sessionModel.rank(limit);
- };
-
- searchSessions: ISessionService['searchSessions'] = async (keyword) => {
- return this.sessionModel.queryByKeyword(keyword);
- };
-
- updateSession: ISessionService['updateSession'] = async (id, value) => {
- return this.sessionModel.update(id, {
- ...value,
- groupId: value.group === 'default' ? null : value.group,
- });
- };
-
- updateSessionConfig: ISessionService['updateSessionConfig'] = async (activeId, config) => {
- return this.sessionModel.updateConfig(activeId, config as AgentItem);
- };
-
- updateSessionMeta: ISessionService['updateSessionMeta'] = async (activeId, meta) => {
- // inbox 不允许修改 meta
- if (activeId === INBOX_SESSION_ID) return;
-
- return this.sessionModel.update(activeId, meta);
- };
-
- updateSessionChatConfig: ISessionService['updateSessionChatConfig'] = async (
- activeId,
- config,
- ) => {
- return this.updateSessionConfig(activeId, { chatConfig: config });
- };
-
- removeSession: ISessionService['removeSession'] = async (id) => {
- return this.sessionModel.delete(id);
- };
-
- removeAllSessions: ISessionService['removeAllSessions'] = async () => {
- return this.sessionModel.deleteAll();
- };
-
- // ************************************** //
- // *********** SessionGroup *********** //
- // ************************************** //
-
- createSessionGroup: ISessionService['createSessionGroup'] = async (name, sort) => {
- const item = await this.sessionGroupModel.create({ name, sort });
- if (!item) {
- throw new Error('session group create Error');
- }
-
- return item.id;
- };
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- batchCreateSessionGroups: ISessionService['batchCreateSessionGroups'] = async (_groups) => {
- return { added: 0, ids: [], skips: [], success: true };
- };
-
- removeSessionGroup: ISessionService['removeSessionGroup'] = async (id) => {
- return this.sessionGroupModel.delete(id);
- };
-
- updateSessionGroup: ISessionService['updateSessionGroup'] = async (id, data) => {
- return this.sessionGroupModel.update(id, data);
- };
-
- updateSessionGroupOrder: ISessionService['updateSessionGroupOrder'] = async (sortMap) => {
- return this.sessionGroupModel.updateOrder(sortMap);
- };
-
- getSessionGroups: ISessionService['getSessionGroups'] = async () => {
- return this.sessionGroupModel.query();
- };
-
- removeSessionGroups: ISessionService['removeSessionGroups'] = async () => {
- return this.sessionGroupModel.deleteAll();
- };
-}
diff --git a/src/services/session/index.ts b/src/services/session/index.ts
index 7235c857936..151af7a4a96 100644
--- a/src/services/session/index.ts
+++ b/src/services/session/index.ts
@@ -1,13 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const sessionService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const sessionService = new ServerService();
diff --git a/src/services/tableViewer/client.ts b/src/services/tableViewer/client.ts
index 740d3289003..2c6a1ab82cc 100644
--- a/src/services/tableViewer/client.ts
+++ b/src/services/tableViewer/client.ts
@@ -1,16 +1,13 @@
-import { clientDB } from '@/database/client/db';
-import { TableViewerRepo } from '@/database/repositories/tableViewer';
-import { BaseClientService } from '@/services/baseClientService';
-
-export class ClientService extends BaseClientService {
- private get tableViewerRepo(): TableViewerRepo {
- return new TableViewerRepo(clientDB as any, this.userId);
- }
-
- getAllTables = async () => this.tableViewerRepo.getAllTables();
-
- getTableDetails = async (tableName: string) => this.tableViewerRepo.getTableDetails(tableName);
-
- getTableData = async (tableName: string) =>
- this.tableViewerRepo.getTableData(tableName, { page: 1, pageSize: 300 });
+export class ClientService {
+ getAllTables = async () => [];
+
+ getTableDetails = async (tableName: string) => {
+ console.log('getTableDetails:', tableName);
+ return [];
+ };
+
+ getTableData = async (tableName: string) => {
+ console.log('getTableData:', tableName);
+ return [];
+ };
}
diff --git a/src/services/thread/client.ts b/src/services/thread/client.ts
deleted file mode 100644
index 864fa252c88..00000000000
--- a/src/services/thread/client.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { INBOX_SESSION_ID } from '@/const/session';
-import { clientDB } from '@/database/client/db';
-import { MessageModel } from '@/database/models/message';
-import { ThreadModel } from '@/database/models/thread';
-import { BaseClientService } from '@/services/baseClientService';
-
-import { IThreadService } from './type';
-
-export class ClientService extends BaseClientService implements IThreadService {
- private get threadModel(): ThreadModel {
- return new ThreadModel(clientDB as any, this.userId);
- }
-
- private get messageModel(): MessageModel {
- return new MessageModel(clientDB as any, this.userId);
- }
-
- getThreads: IThreadService['getThreads'] = async (topicId) => {
- return this.threadModel.queryByTopicId(topicId);
- };
-
- createThreadWithMessage: IThreadService['createThreadWithMessage'] = async (input) => {
- const thread = await this.threadModel.create({
- parentThreadId: input.parentThreadId,
- sourceMessageId: input.sourceMessageId,
- title: input.message.content.slice(0, 20),
- topicId: input.topicId,
- type: input.type,
- });
-
- const message = await this.messageModel.create({
- ...input.message,
- sessionId: this.toDbSessionId(input.message.sessionId) as string,
- threadId: thread?.id,
- });
-
- return { messageId: message?.id, threadId: thread?.id };
- };
-
- updateThread: IThreadService['updateThread'] = async (id, data) => {
- return this.threadModel.update(id, data);
- };
-
- removeThread: IThreadService['removeThread'] = async (id) => {
- return this.threadModel.delete(id);
- };
-
- private toDbSessionId = (sessionId: string | undefined) => {
- return sessionId === INBOX_SESSION_ID ? null : sessionId;
- };
-}
diff --git a/src/services/thread/index.ts b/src/services/thread/index.ts
index a1699924f0b..7580f46fa66 100644
--- a/src/services/thread/index.ts
+++ b/src/services/thread/index.ts
@@ -1,9 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService } from './client';
import { ServerService } from './server';
-export const threadService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : new ClientService();
+export const threadService = new ServerService();
diff --git a/src/services/topic/_deprecated.test.ts b/src/services/topic/_deprecated.test.ts
deleted file mode 100644
index eda273b3606..00000000000
--- a/src/services/topic/_deprecated.test.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import { Mock, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { CreateTopicParams, TopicModel } from '@/database/_deprecated/models/topic';
-import { ChatTopic } from '@/types/topic';
-
-import { ClientService } from './_deprecated';
-
-const topicService = new ClientService();
-// Mock the TopicModel
-vi.mock('@/database/_deprecated/models/topic', () => {
- return {
- TopicModel: {
- create: vi.fn(),
- query: vi.fn(),
- delete: vi.fn(),
- count: vi.fn(),
- batchDeleteBySessionId: vi.fn(),
- batchDelete: vi.fn(),
- clearTable: vi.fn(),
- toggleFavorite: vi.fn(),
- batchCreate: vi.fn(),
- update: vi.fn(),
- queryAll: vi.fn(),
- queryByKeyword: vi.fn(),
- },
- };
-});
-
-describe('TopicService', () => {
- // Mock data
- const mockTopicId = 'mock-topic-id';
- const mockTopic: ChatTopic = {
- createdAt: 100,
- updatedAt: 100,
- id: mockTopicId,
- title: 'Mock Topic',
- };
- const mockTopics = [mockTopic];
-
- beforeEach(() => {
- // Reset all mocks before running each test case
- vi.resetAllMocks();
- });
-
- describe('createTopic', () => {
- it('should create a topic and return its id', async () => {
- // Setup
- const createParams: CreateTopicParams = {
- title: 'New Topic',
- sessionId: '1',
- };
- (TopicModel.create as Mock).mockResolvedValue(mockTopic);
-
- // Execute
- const topicId = await topicService.createTopic(createParams);
-
- // Assert
- expect(TopicModel.create).toHaveBeenCalledWith(createParams);
- expect(topicId).toBe(mockTopicId);
- });
- it('should throw an error if topic creation fails', async () => {
- // Setup
- const createParams: CreateTopicParams = {
- title: 'New Topic',
- sessionId: '1',
- };
-
- (TopicModel.create as Mock).mockResolvedValue(null);
-
- // Execute & Assert
- await expect(topicService.createTopic(createParams)).rejects.toThrow('topic create Error');
- });
- });
-
- describe('getTopics', () => {
- // Example for getTopics
- it('should query topics with given parameters', async () => {
- // Setup
- const queryParams = { containerId: 'session-id' };
- (TopicModel.query as Mock).mockResolvedValue(mockTopics);
-
- // Execute
- const topics = await topicService.getTopics(queryParams);
-
- // Assert
- expect(TopicModel.query).toHaveBeenCalledWith(queryParams);
- expect(topics).toBe(mockTopics);
- });
- });
-
- describe('updateTopic', () => {
- // Example for updateFavorite
- it('should toggle favorite status of a topic', async () => {
- // Setup
- const newState = true;
-
- // Execute
- await topicService.updateTopic(mockTopicId, { favorite: newState });
-
- // Assert
- expect(TopicModel.update).toHaveBeenCalledWith(mockTopicId, { favorite: 1 });
- });
-
- it('should update the title of a topic', async () => {
- // Setup
- const newTitle = 'Updated Topic Title';
- (TopicModel.update as Mock).mockResolvedValue({ ...mockTopic, title: newTitle });
-
- // Execute
- const result = await topicService.updateTopic(mockTopicId, { title: newTitle });
-
- // Assert
- expect(TopicModel.update).toHaveBeenCalledWith(mockTopicId, { title: newTitle });
- expect(result).toEqual({ ...mockTopic, title: newTitle });
- });
- });
-
- describe('removeTopic', () => {
- it('should remove a topic by id', async () => {
- // Setup
- (TopicModel.delete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await topicService.removeTopic(mockTopicId);
-
- // Assert
- expect(TopicModel.delete).toHaveBeenCalledWith(mockTopicId);
- expect(result).toBe(true);
- });
- });
-
- describe('removeTopics', () => {
- it('should remove all topics with a given session id', async () => {
- // Setup
- const sessionId = 'session-id';
- (TopicModel.batchDeleteBySessionId as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await topicService.removeTopics(sessionId);
-
- // Assert
- expect(TopicModel.batchDeleteBySessionId).toHaveBeenCalledWith(sessionId);
- expect(result).toBe(true);
- });
- });
-
- describe('batchRemoveTopics', () => {
- it('should batch remove topics', async () => {
- // Setup
- const topicIds = [mockTopicId, 'another-topic-id'];
- (TopicModel.batchDelete as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await topicService.batchRemoveTopics(topicIds);
-
- // Assert
- expect(TopicModel.batchDelete).toHaveBeenCalledWith(topicIds);
- expect(result).toBe(true);
- });
- });
-
- describe('removeAllTopic', () => {
- it('should clear all topics from the table', async () => {
- // Setup
- (TopicModel.clearTable as Mock).mockResolvedValue(true);
-
- // Execute
- const result = await topicService.removeAllTopic();
-
- // Assert
- expect(TopicModel.clearTable).toHaveBeenCalled();
- expect(result).toBe(true);
- });
- });
-
- describe('batchCreateTopics', () => {
- it('should batch create topics', async () => {
- // Setup
- (TopicModel.batchCreate as Mock).mockResolvedValue(mockTopics);
-
- // Execute
- const result = await topicService.batchCreateTopics(mockTopics);
-
- // Assert
- expect(TopicModel.batchCreate).toHaveBeenCalledWith(mockTopics);
- expect(result).toBe(mockTopics);
- });
- });
-
- describe('getAllTopics', () => {
- it('should retrieve all topics', async () => {
- // Setup
- (TopicModel.queryAll as Mock).mockResolvedValue(mockTopics);
-
- // Execute
- const result = await topicService.getAllTopics();
-
- // Assert
- expect(TopicModel.queryAll).toHaveBeenCalled();
- expect(result).toBe(mockTopics);
- });
- });
-
- describe('searchTopics', () => {
- it('should return all topics that match the keyword', async () => {
- // Setup
- const keyword = 'search';
- (TopicModel.queryByKeyword as Mock).mockResolvedValue(mockTopics);
-
- // Execute
- const result = await topicService.searchTopics(keyword, undefined);
-
- // Assert
- expect(TopicModel.queryByKeyword).toHaveBeenCalledWith(keyword, undefined);
- expect(result).toBe(mockTopics);
- });
- });
-
- describe('countTopics', () => {
- it('should return false if no topics exist', async () => {
- // Setup
- (TopicModel.count as Mock).mockResolvedValue(0);
-
- // Execute
- const result = await topicService.countTopics();
-
- // Assert
- expect(TopicModel.count).toHaveBeenCalled();
- expect(result).toBe(0);
- });
-
- it('should return true if topics exist', async () => {
- // Setup
- (TopicModel.count as Mock).mockResolvedValue(1);
-
- // Execute
- const result = await topicService.countTopics();
-
- // Assert
- expect(TopicModel.count).toHaveBeenCalled();
- expect(result).toBe(1);
- });
- });
-});
diff --git a/src/services/topic/_deprecated.ts b/src/services/topic/_deprecated.ts
deleted file mode 100644
index bec802f2fb5..00000000000
--- a/src/services/topic/_deprecated.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { TopicModel } from '@/database/_deprecated/models/topic';
-import { ChatTopic } from '@/types/topic';
-
-import { CreateTopicParams, ITopicService, QueryTopicParams } from './type';
-
-export class ClientService implements ITopicService {
- async createTopic(params: CreateTopicParams): Promise<string> {
- const item = await TopicModel.create(params as any);
-
- if (!item) {
- throw new Error('topic create Error');
- }
-
- return item.id;
- }
-
- async batchCreateTopics(importTopics: ChatTopic[]) {
- return TopicModel.batchCreate(importTopics as any);
- }
-
- async cloneTopic(id: string, newTitle?: string) {
- return TopicModel.duplicateTopic(id, newTitle);
- }
-
- async getTopics(params: QueryTopicParams): Promise<ChatTopic[]> {
- return TopicModel.query(params);
- }
-
- async searchTopics(keyword: string, sessionId?: string) {
- return TopicModel.queryByKeyword(keyword, sessionId);
- }
-
- async getAllTopics() {
- return TopicModel.queryAll();
- }
-
- async countTopics() {
- return TopicModel.count();
- }
-
- // @ts-ignore
- async rankTopics() {
- throw new Error('Method not implemented.');
- }
-
- async updateTopicFavorite(id: string, favorite?: boolean) {
- return this.updateTopic(id, { favorite });
- }
-
- async updateTopicTitle(id: string, text: string) {
- return this.updateTopic(id, { title: text });
- }
-
- async updateTopic(id: string, data: Partial<ChatTopic>) {
- const favorite = typeof data.favorite !== 'undefined' ? (data.favorite ? 1 : 0) : undefined;
-
- return TopicModel.update(id, { ...data, favorite });
- }
-
- async removeTopic(id: string) {
- return TopicModel.delete(id);
- }
-
- async removeTopics(sessionId: string) {
- return TopicModel.batchDeleteBySessionId(sessionId);
- }
-
- async batchRemoveTopics(topics: string[]) {
- return TopicModel.batchDelete(topics);
- }
-
- async removeAllTopic() {
- return TopicModel.clearTable();
- }
-}
diff --git a/src/services/topic/client.ts b/src/services/topic/client.ts
deleted file mode 100644
index e9060b0c655..00000000000
--- a/src/services/topic/client.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { INBOX_SESSION_ID } from '@/const/session';
-import { clientDB } from '@/database/client/db';
-import { TopicModel } from '@/database/models/topic';
-import { BaseClientService } from '@/services/baseClientService';
-import { ChatTopic } from '@/types/topic';
-
-import { ITopicService } from './type';
-
-export class ClientService extends BaseClientService implements ITopicService {
- private get topicModel(): TopicModel {
- return new TopicModel(clientDB as any, this.userId);
- }
-
- createTopic: ITopicService['createTopic'] = async (params) => {
- const item = await this.topicModel.create({
- ...params,
- sessionId: this.toDbSessionId(params.sessionId),
- } as any);
-
- if (!item) {
- throw new Error('topic create Error');
- }
-
- return item.id;
- };
-
- batchCreateTopics: ITopicService['batchCreateTopics'] = async (importTopics) => {
- const data = await this.topicModel.batchCreate(importTopics as any);
-
- return { added: data.length, ids: [], skips: [], success: true };
- };
-
- cloneTopic: ITopicService['cloneTopic'] = async (id, newTitle) => {
- const data = await this.topicModel.duplicate(id, newTitle);
- return data.topic.id;
- };
-
- getTopics: ITopicService['getTopics'] = async (params) => {
- const data = await this.topicModel.query({
- ...params,
- containerId: this.toDbSessionId(params.containerId),
- });
- return data as unknown as Promise<ChatTopic[]>;
- };
-
- searchTopics: ITopicService['searchTopics'] = async (keyword, sessionId) => {
- const data = await this.topicModel.queryByKeyword(keyword, this.toDbSessionId(sessionId));
-
- return data as unknown as Promise<ChatTopic[]>;
- };
-
- getAllTopics: ITopicService['getAllTopics'] = async () => {
- const data = await this.topicModel.queryAll();
-
- return data as unknown as Promise<ChatTopic[]>;
- };
-
- countTopics: ITopicService['countTopics'] = async (params) => {
- return this.topicModel.count(params);
- };
-
- rankTopics: ITopicService['rankTopics'] = async (limit) => {
- return this.topicModel.rank(limit);
- };
-
- updateTopic: ITopicService['updateTopic'] = async (id, data) => {
- return this.topicModel.update(id, data as any);
- };
-
- removeTopic: ITopicService['removeTopic'] = async (id) => {
- return this.topicModel.delete(id);
- };
-
- removeTopics: ITopicService['removeTopics'] = async (sessionId) => {
- return this.topicModel.batchDeleteBySessionId(this.toDbSessionId(sessionId));
- };
-
- batchRemoveTopics: ITopicService['batchRemoveTopics'] = async (topics) => {
- return this.topicModel.batchDelete(topics);
- };
-
- removeAllTopic: ITopicService['removeAllTopic'] = async () => {
- return this.topicModel.deleteAll();
- };
-
- private toDbSessionId(sessionId?: string | null) {
- return sessionId === INBOX_SESSION_ID ? null : sessionId;
- }
-}
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 0b9187f907e..e4333df14ee 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -1,13 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const topicService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
+export const topicService = new ServerService();
diff --git a/src/services/topic/pglite.test.ts b/src/services/topic/pglite.test.ts
deleted file mode 100644
index de028b46ac1..00000000000
--- a/src/services/topic/pglite.test.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import { sessions, topics, users } from '@/database/schemas';
-import { ChatTopic } from '@/types/topic';
-
-import { ClientService } from './client';
-
-// Mock data
-const userId = 'topic-user-test';
-const sessionId = 'topic-session';
-const mockTopicId = 'mock-topic-id';
-
-const mockTopic = {
- id: mockTopicId,
- title: 'Mock Topic',
-};
-
-const topicService = new ClientService(userId);
-
-beforeEach(async () => {
- await initializeDB();
-
- await clientDB.delete(users);
-
- // 创建测试数据
- await clientDB.transaction(async (tx) => {
- await tx.insert(users).values({ id: userId }).onConflictDoNothing();
- await tx.insert(sessions).values({ id: sessionId, userId });
- await tx.insert(topics).values({ ...mockTopic, sessionId, userId });
- });
-});
-
-describe('TopicService', () => {
- describe('createTopic', () => {
- it('should create a topic and return its id', async () => {
- // Setup
- const createParams = {
- title: 'New Topic',
- sessionId: sessionId,
- };
-
- // Execute
- const topicId = await topicService.createTopic(createParams);
-
- // Assert
- expect(topicId).toBeDefined();
- });
-
- it('should throw an error if topic creation fails', async () => {
- // Setup
- const createParams = {
- title: 'New Topic',
- sessionId: 123 as any, // sessionId should be string
- };
-
- // Execute & Assert
- await expect(topicService.createTopic(createParams)).rejects.toThrowError();
- });
- });
-
- describe('getTopics', () => {
- // Example for getTopics
- it('should query topics with given parameters', async () => {
- // Setup
- const queryParams = { containerId: sessionId };
-
- // Execute
- const data = await topicService.getTopics(queryParams);
-
- // Assert
- expect(data[0]).toMatchObject(mockTopic);
- });
- });
-
- describe('updateTopic', () => {
- // Example for updateFavorite
- it('should toggle favorite status of a topic', async () => {
- // Execute
- const result = await topicService.updateTopic(mockTopicId, { favorite: true });
-
- // Assert
- expect(result[0].favorite).toBeTruthy();
- });
-
- it('should update the title of a topic', async () => {
- // Setup
- const newTitle = 'Updated Topic Title';
-
- // Execute
- const result = await topicService.updateTopic(mockTopicId, { title: newTitle });
-
- // Assert
- expect(result[0].title).toEqual(newTitle);
- });
- });
-
- describe('removeTopic', () => {
- it('should remove a topic by id', async () => {
- // Execute
- await topicService.removeTopic(mockTopicId);
- const result = await clientDB.query.topics.findFirst({ where: eq(topics.id, mockTopicId) });
-
- // Assert
- expect(result).toBeUndefined();
- });
- });
-
- describe('removeTopics', () => {
- it('should remove all topics with a given session id', async () => {
- // Setup
- const sessionId = 'session-id';
-
- // Execute
- await topicService.removeTopics(sessionId);
- const result = await clientDB.query.topics.findMany({
- where: eq(topics.sessionId, sessionId),
- });
-
- expect(result.length).toEqual(0);
- });
- });
-
- describe('batchRemoveTopics', () => {
- it('should batch remove topics', async () => {
- await clientDB.insert(topics).values([{ id: 'topic-id-1', title: 'topic-title', userId }]);
- // Setup
- const topicIds = [mockTopicId, 'another-topic-id'];
-
- // Execute
- await topicService.batchRemoveTopics(topicIds);
-
- const count = await clientDB.$count(topics);
-
- // Assert
- expect(count).toBe(1);
- });
- });
-
- describe('removeAllTopic', () => {
- it('should clear all topics from the table', async () => {
- // Execute
- await topicService.removeAllTopic();
-
- const count = await clientDB.$count(topics);
- // Assert
- expect(count).toBe(0);
- });
- });
-
- describe('batchCreateTopics', () => {
- it('should batch create topics', async () => {
- // Execute
- const result = await topicService.batchCreateTopics([
- { id: 'topic-id-1', title: 'topic-title' },
- { id: 'topic-id-2', title: 'topic-title' },
- ] as ChatTopic[]);
-
- // Assert
- expect(result.success).toBeTruthy();
- expect(result.added).toBe(2);
- });
- });
-
- describe('getAllTopics', () => {
- it('should retrieve all topics', async () => {
- await clientDB.insert(topics).values([
- { id: 'topic-id-1', title: 'topic-title', userId },
- { id: 'topic-id-2', title: 'topic-title', userId },
- ]);
- // Execute
- const result = await topicService.getAllTopics();
-
- // Assert
- expect(result.length).toEqual(3);
- });
- });
-
- describe('searchTopics', () => {
- it('should return all topics that match the keyword', async () => {
- // Setup
- const keyword = 'Topic';
-
- // Execute
- const result = await topicService.searchTopics(keyword, sessionId);
-
- // Assert
- expect(result.length).toEqual(1);
- });
- it('should return empty topic if not match the keyword', async () => {
- // Setup
- const keyword = 'search';
-
- // Execute
- const result = await topicService.searchTopics(keyword, sessionId);
-
- // Assert
- expect(result.length).toEqual(0);
- });
- });
-
- describe('countTopics', () => {
- it('should return topic counts', async () => {
- // Execute
- const result = await topicService.countTopics();
-
- // Assert
- expect(result).toBe(1);
- });
- });
-});
diff --git a/src/services/user/_deprecated.test.ts b/src/services/user/_deprecated.test.ts
deleted file mode 100644
index 437d7d24e54..00000000000
--- a/src/services/user/_deprecated.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import type { PartialDeep } from 'type-fest';
-import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { UserModel } from '@/database/_deprecated/models/user';
-import { UserPreference } from '@/types/user';
-import { UserSettings } from '@/types/user/settings';
-
-import { ClientService } from './_deprecated';
-
-vi.mock('@/database/_deprecated/models/user', () => ({
- UserModel: {
- getUser: vi.fn(),
- updateSettings: vi.fn(),
- resetSettings: vi.fn(),
- updateAvatar: vi.fn(),
- },
-}));
-
-const mockUser = {
- avatar: 'avatar.png',
- settings: { themeMode: 'light' } as unknown as UserSettings,
- uuid: 'user-id',
-};
-
-const mockPreference = {
- useCmdEnterToSend: true,
-} as UserPreference;
-
-describe('ClientService', () => {
- let clientService: ClientService;
-
- beforeEach(() => {
- vi.clearAllMocks();
- clientService = new ClientService();
- });
-
- it('should get user state correctly', async () => {
- (UserModel.getUser as Mock).mockResolvedValue(mockUser);
- const spyOn = vi
- .spyOn(clientService['preferenceStorage'], 'getFromLocalStorage')
- .mockResolvedValue(mockPreference);
-
- const userState = await clientService.getUserState();
-
- expect(userState).toEqual({
- avatar: mockUser.avatar,
- isOnboard: true,
- canEnablePWAGuide: false,
- hasConversation: false,
- canEnableTrace: false,
- preference: mockPreference,
- settings: mockUser.settings,
- userId: mockUser.uuid,
- });
- expect(UserModel.getUser).toHaveBeenCalledTimes(1);
- expect(spyOn).toHaveBeenCalledTimes(1);
- });
-
- it('should update user settings correctly', async () => {
- const settingsPatch: PartialDeep<UserSettings> = { general: { fontSize: 12 } };
- (UserModel.updateSettings as Mock).mockResolvedValue(undefined);
-
- await clientService.updateUserSettings(settingsPatch);
-
- expect(UserModel.updateSettings).toHaveBeenCalledWith(settingsPatch);
- expect(UserModel.updateSettings).toHaveBeenCalledTimes(1);
- });
-
- it('should reset user settings correctly', async () => {
- (UserModel.resetSettings as Mock).mockResolvedValue(undefined);
-
- await clientService.resetUserSettings();
-
- expect(UserModel.resetSettings).toHaveBeenCalledTimes(1);
- });
-
- it('should update user avatar correctly', async () => {
- const newAvatar = 'new-avatar.png';
- (UserModel.updateAvatar as Mock).mockResolvedValue(undefined);
-
- await clientService.updateAvatar(newAvatar);
-
- expect(UserModel.updateAvatar).toHaveBeenCalledWith(newAvatar);
- expect(UserModel.updateAvatar).toHaveBeenCalledTimes(1);
- });
-
- it('should update user preference correctly', async () => {
- const newPreference = {
- useCmdEnterToSend: false,
- } as UserPreference;
-
- const spyOn = vi
- .spyOn(clientService['preferenceStorage'], 'saveToLocalStorage')
- .mockResolvedValue(undefined);
-
- await clientService.updatePreference(newPreference);
-
- expect(spyOn).toHaveBeenCalledWith(newPreference);
- expect(spyOn).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/src/services/user/_deprecated.ts b/src/services/user/_deprecated.ts
deleted file mode 100644
index 7cd90312bc9..00000000000
--- a/src/services/user/_deprecated.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { PartialDeep } from 'type-fest';
-
-import { MessageModel } from '@/database/_deprecated/models/message';
-import { SessionModel } from '@/database/_deprecated/models/session';
-import { UserModel } from '@/database/_deprecated/models/user';
-import { UserGuide, UserInitializationState, UserPreference } from '@/types/user';
-import { UserSettings } from '@/types/user/settings';
-import { AsyncLocalStorage } from '@/utils/localStorage';
-
-import { IUserService } from './type';
-
-export class ClientService implements IUserService {
- private preferenceStorage: AsyncLocalStorage<UserPreference>;
-
- constructor() {
- this.preferenceStorage = new AsyncLocalStorage('LOBE_PREFERENCE');
- }
-
- getUserRegistrationDuration = async () => {
- throw new Error('Method not implemented.');
- };
-
- async getUserState(): Promise<UserInitializationState> {
- const user = await UserModel.getUser();
- const messageCount = await MessageModel.count();
- const sessionCount = await SessionModel.count();
-
- return {
- avatar: user.avatar,
- canEnablePWAGuide: messageCount >= 4,
- canEnableTrace: messageCount >= 4,
- hasConversation: messageCount > 0 || sessionCount > 0,
- isOnboard: true,
- preference: await this.preferenceStorage.getFromLocalStorage(),
- settings: user.settings as UserSettings,
- userId: user.uuid,
- };
- }
-
- getUserSSOProviders = async () => {
- // Account not exist on next-auth in client mode, no need to implement this method
- return [];
- };
-
- unlinkSSOProvider = async () => {
- // Account not exist on next-auth in client mode, no need to implement this method
- };
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- updateUserSettings = async (patch: PartialDeep<UserSettings>, _?: any) => {
- return UserModel.updateSettings(patch);
- };
-
- resetUserSettings = async () => {
- return UserModel.resetSettings();
- };
-
- async updateAvatar(avatar: string) {
- await UserModel.updateAvatar(avatar);
- }
-
- async updatePreference(preference: Partial<UserPreference>) {
- await this.preferenceStorage.saveToLocalStorage(preference);
- }
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars,unused-imports/no-unused-vars
- async updateGuide(guide: Partial<UserGuide>) {
- throw new Error('Method not implemented.');
- }
-}
diff --git a/src/services/user/client.test.ts b/src/services/user/client.test.ts
deleted file mode 100644
index 83c708a02ad..00000000000
--- a/src/services/user/client.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { eq } from 'drizzle-orm';
-import type { PartialDeep } from 'type-fest';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
-import { userSettings, users } from '@/database/schemas';
-import { UserPreference } from '@/types/user';
-import { UserSettings } from '@/types/user/settings';
-
-import { ClientService } from './client';
-
-const mockUser = {
- avatar: 'avatar.png',
- settings: { themeMode: 'light' } as unknown as UserSettings,
- uuid: 'user-id',
-};
-
-const mockPreference = {
- useCmdEnterToSend: true,
-} as UserPreference;
-const clientService = new ClientService(mockUser.uuid);
-
-beforeEach(async () => {
- vi.clearAllMocks();
-
- await initializeDB();
- await clientDB.delete(users);
-
- await clientDB
- .insert(users)
- .values({ id: mockUser.uuid, avatar: 'avatar.png' })
- .onConflictDoNothing();
- await clientDB
- .insert(userSettings)
- .values({ id: mockUser.uuid, general: { themeMode: 'light' } });
-});
-
-describe('ClientService', () => {
- it('should get user state correctly', async () => {
- const spyOn = vi
- .spyOn(clientService['preferenceStorage'], 'getFromLocalStorage')
- .mockResolvedValue(mockPreference);
-
- const userState = await clientService.getUserState();
-
- expect(userState).toMatchObject({
- avatar: mockUser.avatar,
- isOnboard: true,
- canEnablePWAGuide: false,
- hasConversation: false,
- canEnableTrace: false,
- preference: mockPreference,
- settings: { general: { themeMode: 'light' } },
- userId: mockUser.uuid,
- });
- expect(spyOn).toHaveBeenCalledTimes(1);
- });
-
- it('should update user settings correctly', async () => {
- const settingsPatch: PartialDeep<UserSettings> = { general: { fontSize: 12 } };
-
- await clientService.updateUserSettings(settingsPatch);
-
- const result = await clientDB.query.userSettings.findFirst({
- where: eq(userSettings.id, mockUser.uuid),
- });
-
- expect(result).toMatchObject(settingsPatch);
- });
-
- it('should reset user settings correctly', async () => {
- await clientService.resetUserSettings();
-
- const result = await clientDB.query.userSettings.findFirst({
- where: eq(userSettings.id, mockUser.uuid),
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should update user avatar correctly', async () => {
- const newAvatar = 'new-avatar.png';
-
- await clientService.updateAvatar(newAvatar);
- });
-
- it('should update user preference correctly', async () => {
- const newPreference = {
- useCmdEnterToSend: false,
- } as UserPreference;
-
- const spyOn = vi
- .spyOn(clientService['preferenceStorage'], 'saveToLocalStorage')
- .mockResolvedValue(undefined);
-
- await clientService.updatePreference(newPreference);
-
- expect(spyOn).toHaveBeenCalledWith(newPreference);
- expect(spyOn).toHaveBeenCalledTimes(1);
- });
-
- it('should return empty array for getUserSSOProviders', async () => {
- const providers = await clientService.getUserSSOProviders();
- expect(providers).toEqual([]);
- });
-
- it('should do nothing when unlinkSSOProvider is called', async () => {
- const result = await clientService.unlinkSSOProvider('google', '123');
- expect(result).toBeUndefined();
- });
-});
diff --git a/src/services/user/client.ts b/src/services/user/client.ts
deleted file mode 100644
index b2275f4eb40..00000000000
--- a/src/services/user/client.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { clientDB } from '@/database/client/db';
-import { MessageModel } from '@/database/models/message';
-import { SessionModel } from '@/database/models/session';
-import { UserModel } from '@/database/models/user';
-import { users } from '@/database/schemas';
-import { BaseClientService } from '@/services/baseClientService';
-import { UserPreference } from '@/types/user';
-import { AsyncLocalStorage } from '@/utils/localStorage';
-
-import { IUserService } from './type';
-
-export class ClientService extends BaseClientService implements IUserService {
- private preferenceStorage: AsyncLocalStorage<UserPreference>;
-
- private get userModel(): UserModel {
- return new UserModel(clientDB as any, this.userId);
- }
- private get messageModel(): MessageModel {
- return new MessageModel(clientDB as any, this.userId);
- }
- private get sessionModel(): SessionModel {
- return new SessionModel(clientDB as any, this.userId);
- }
-
- constructor(userId?: string) {
- super(userId);
- this.preferenceStorage = new AsyncLocalStorage('LOBE_PREFERENCE');
- }
-
- getUserRegistrationDuration: IUserService['getUserRegistrationDuration'] = async () => {
- return this.userModel.getUserRegistrationDuration();
- };
-
- getUserState: IUserService['getUserState'] = async () => {
- // if user not exist in the db, create one to make sure the user exist
- await this.makeSureUserExist();
-
- const state = await this.userModel.getUserState((encryptKeyVaultsStr) =>
- encryptKeyVaultsStr ? JSON.parse(encryptKeyVaultsStr) : {},
- );
-
- const messageCount = await this.messageModel.count();
- const sessionCount = await this.sessionModel.count();
-
- return {
- ...state,
- avatar: state.avatar ?? '',
- canEnablePWAGuide: messageCount >= 4,
- canEnableTrace: messageCount >= 4,
- firstName: state.firstName,
- fullName: state.fullName,
- hasConversation: messageCount > 0 || sessionCount > 0,
- isOnboard: true,
- lastName: state.lastName,
- preference: await this.preferenceStorage.getFromLocalStorage(),
- username: state.username,
- };
- };
-
- getUserSSOProviders: IUserService['getUserSSOProviders'] = async () => {
- // Account not exist on next-auth in client mode, no need to implement this method
- return [];
- };
-
- unlinkSSOProvider: IUserService['unlinkSSOProvider'] = async () => {
- // Account not exist on next-auth in client mode, no need to implement this method
- };
-
- updateUserSettings: IUserService['updateUserSettings'] = async (value) => {
- const { keyVaults, ...res } = value;
-
- return this.userModel.updateSetting({ ...res, keyVaults: JSON.stringify(keyVaults) });
- };
-
- resetUserSettings: IUserService['resetUserSettings'] = async () => {
- return this.userModel.deleteSetting();
- };
-
- updateAvatar = async (avatar: string) => {
- await this.userModel.updateUser({ avatar });
- };
-
- updatePreference: IUserService['updatePreference'] = async (preference) => {
- await this.preferenceStorage.saveToLocalStorage(preference);
- };
-
- updateGuide: IUserService['updateGuide'] = async () => {
- throw new Error('Method not implemented.');
- };
-
- makeSureUserExist = async () => {
- const existUsers = await clientDB.query.users.findMany();
-
- let user: { id: string };
- if (existUsers.length === 0) {
- const result = await clientDB.insert(users).values({ id: this.userId }).returning();
- user = result[0];
- } else {
- user = existUsers[0];
- }
-
- return user;
- };
-}
diff --git a/src/services/user/index.ts b/src/services/user/index.ts
index cdefe422632..944484e0a7e 100644
--- a/src/services/user/index.ts
+++ b/src/services/user/index.ts
@@ -1,15 +1,3 @@
-import { isDesktop } from '@/const/version';
-
-import { ClientService as DeprecatedService } from './_deprecated';
-import { ClientService } from './client';
import { ServerService } from './server';
-const clientService =
- process.env.NEXT_PUBLIC_CLIENT_DB === 'pglite' ? new ClientService() : new DeprecatedService();
-
-export const userService =
- process.env.NEXT_PUBLIC_SERVICE_MODE === 'server' || isDesktop
- ? new ServerService()
- : clientService;
-
-export const userClientService = clientService;
+export const userService = new ServerService();
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
index 29fcf02a54d..386e36acff7 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
@@ -87,57 +87,6 @@ describe('chatMessage actions', () => {
});
describe('message creation', () => {
- it('should create user message and trigger AI processing', async () => {
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- expect(messageService.createMessage).toHaveBeenCalledWith({
- content: TEST_CONTENT.USER_MESSAGE,
- files: undefined,
- role: 'user',
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- });
- expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();
- });
-
- it('should send message with files attached', async () => {
- const { result } = renderHook(() => useChatStore());
- const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE, files });
- });
-
- expect(messageService.createMessage).toHaveBeenCalledWith({
- content: TEST_CONTENT.USER_MESSAGE,
- files: [TEST_IDS.FILE_ID],
- role: 'user',
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- });
- });
-
- it('should send files without message content', async () => {
- const { result } = renderHook(() => useChatStore());
- const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files });
- });
-
- expect(messageService.createMessage).toHaveBeenCalledWith({
- content: TEST_CONTENT.EMPTY,
- files: [TEST_IDS.FILE_ID],
- role: 'user',
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- });
- });
-
it('should not process AI when onlyAddUserMessage is true', async () => {
const { result } = renderHook(() => useChatStore());
@@ -169,196 +118,6 @@ describe('chatMessage actions', () => {
expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();
});
});
-
- describe('auto-create topic', () => {
- const TOPIC_THRESHOLD = 5;
-
- it('should create topic when threshold is reached and feature is enabled', async () => {
- const { result } = renderHook(() => useChatStore());
-
- const createTopicMock = vi.fn(() => Promise.resolve(TEST_IDS.NEW_TOPIC_ID));
- const switchTopicMock = vi.fn();
-
- act(() => {
- setupMockSelectors({
- agentConfig: {
- enableAutoCreateTopic: true,
- autoCreateTopicThreshold: TOPIC_THRESHOLD,
- },
- });
-
- useChatStore.setState({
- activeTopicId: undefined,
- messagesMap: {
- [messageMapKey(TEST_IDS.SESSION_ID)]: createMockMessages(TOPIC_THRESHOLD),
- },
- createTopic: createTopicMock,
- switchTopic: switchTopicMock,
- });
- });
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- expect(createTopicMock).toHaveBeenCalled();
- expect(switchTopicMock).toHaveBeenCalledWith(TEST_IDS.NEW_TOPIC_ID, true);
- });
- });
-
- describe('RAG integration', () => {
- it('should include RAG query when RAG is enabled', async () => {
- const { result } = renderHook(() => useChatStore());
- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.RAG_QUERY });
- });
-
- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(
- expect.any(Array),
- expect.any(String),
- expect.objectContaining({
- ragQuery: TEST_CONTENT.RAG_QUERY,
- }),
- );
- });
-
- it('should not use RAG when feature is disabled', async () => {
- const { result } = renderHook(() => useChatStore());
- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);
- const retrieveChunksSpy = vi.spyOn(result.current, 'internal_retrieveChunks');
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- expect(retrieveChunksSpy).not.toHaveBeenCalled();
- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(
- expect.any(Array),
- expect.any(String),
- expect.not.objectContaining({
- ragQuery: expect.anything(),
- }),
- );
- });
- });
-
- describe('special flags', () => {
- it('should pass isWelcomeQuestion flag to processing', async () => {
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.sendMessage({
- message: TEST_CONTENT.USER_MESSAGE,
- isWelcomeQuestion: true,
- });
- });
-
- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- { isWelcomeQuestion: true },
- );
- });
-
- it('should return early when onlyAddUserMessage is true', async () => {
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.sendMessage({
- message: TEST_CONTENT.USER_MESSAGE,
- onlyAddUserMessage: true,
- });
- });
-
- expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();
- });
- });
-
- describe('topic creation flow', () => {
- it('should handle tempMessage during topic creation', async () => {
- setupMockSelectors({
- chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },
- });
-
- act(() => {
- useChatStore.setState({ activeTopicId: undefined });
- setupStoreWithMessages(createMockMessages(5));
- });
-
- const { result } = renderHook(() => useChatStore());
- const createTopicMock = vi
- .spyOn(result.current, 'createTopic')
- .mockResolvedValue(TEST_IDS.NEW_TOPIC_ID);
- const toggleMessageLoadingSpy = vi.spyOn(result.current, 'internal_toggleMessageLoading');
- const createTmpMessageSpy = vi
- .spyOn(result.current, 'internal_createTmpMessage')
- .mockReturnValue('temp-id');
- vi.spyOn(result.current, 'internal_fetchMessages').mockResolvedValue();
- vi.spyOn(result.current, 'switchTopic').mockResolvedValue();
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- expect(createTmpMessageSpy).toHaveBeenCalled();
- expect(toggleMessageLoadingSpy).toHaveBeenCalledWith(true, 'temp-id');
- expect(createTopicMock).toHaveBeenCalled();
- });
-
- it('should call summaryTopicTitle after processing when new topic created', async () => {
- setupMockSelectors({
- chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },
- });
-
- act(() => {
- useChatStore.setState({ activeTopicId: undefined });
- setupStoreWithMessages(createMockMessages(5));
- });
-
- const { result } = renderHook(() => useChatStore());
- vi.spyOn(result.current, 'createTopic').mockResolvedValue(TEST_IDS.NEW_TOPIC_ID);
- vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-id');
- vi.spyOn(result.current, 'internal_fetchMessages').mockResolvedValue();
- vi.spyOn(result.current, 'switchTopic').mockResolvedValue();
-
- const summaryTopicTitleSpy = vi
- .spyOn(result.current, 'summaryTopicTitle')
- .mockResolvedValue();
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- expect(summaryTopicTitleSpy).toHaveBeenCalledWith(TEST_IDS.NEW_TOPIC_ID, expect.any(Array));
- });
-
- it('should handle topic creation failure gracefully', async () => {
- setupMockSelectors({
- chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },
- });
-
- act(() => {
- useChatStore.setState({ activeTopicId: undefined });
- setupStoreWithMessages(createMockMessages(5));
- });
-
- const { result } = renderHook(() => useChatStore());
- vi.spyOn(result.current, 'createTopic').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-id');
- const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleMessageLoading');
- const updateTopicLoadingSpy = vi.spyOn(result.current, 'internal_updateTopicLoading');
-
- await act(async () => {
- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
- });
-
- // Should still call the AI processing even if topic creation fails
- expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();
- expect(updateTopicLoadingSpy).not.toHaveBeenCalled();
- });
- });
});
describe('regenerateMessage', () => {
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
index 4d6931c4912..59e7560172d 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
@@ -19,8 +19,33 @@ import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from '.
// Keep zustand mock as it's needed globally
vi.mock('zustand/traditional');
+// Mock AntdStaticMethods
+vi.mock('@/components/AntdStaticMethods', () => ({
+ notification: {
+ error: vi.fn(),
+ success: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ },
+ message: {
+ error: vi.fn(),
+ success: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ },
+}));
+
+// Mock sessionService to prevent TRPC requests
+vi.mock('@/services/session', () => ({
+ sessionService: {
+ updateSession: vi.fn(),
+ updateSessionConfig: vi.fn(),
+ updateSessionChatConfig: vi.fn(),
+ },
+}));
+
// Mock server mode for V2 tests
-vi.mock('@/const/version', async (importOriginal) => {
+vi.mock('@lobechat/const', async (importOriginal) => {
const module = await importOriginal();
return {
...(module as any),
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
index d3d69be84e7..3268edb779f 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
@@ -60,7 +60,9 @@ export const spyOnMessageService = () => {
const createMessageSpy = vi
.spyOn(messageService, 'createMessage')
.mockResolvedValue(TEST_IDS.NEW_MESSAGE_ID);
- const updateMessageSpy = vi.spyOn(messageService, 'updateMessage').mockResolvedValue(undefined);
+ const updateMessageSpy = vi
+ .spyOn(messageService, 'updateMessage')
+ .mockResolvedValue({ messages: [], success: true });
const removeMessageSpy = vi.spyOn(messageService, 'removeMessage').mockResolvedValue(undefined);
const updateMessageErrorSpy = vi
.spyOn(messageService, 'updateMessageError')
diff --git a/src/store/chat/slices/aiChat/actions/generateAIChat.ts b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
index 6265ab49153..4b5c8a62b9d 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIChat.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
@@ -17,15 +17,12 @@ import { StateCreator } from 'zustand/vanilla';
import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
-import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
import { getAgentStoreState } from '@/store/agent/store';
import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra';
import { getAiInfraStoreState } from '@/store/aiInfra/store';
import { ChatStore } from '@/store/chat/store';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getFileStoreState } from '@/store/file/store';
-import { useSessionStore } from '@/store/session';
import { WebBrowsingManifest } from '@/tools/web-browsing';
import { Action, setNamespace } from '@/utils/storeDebug';
@@ -158,13 +155,7 @@ export const generateAIChat: StateCreator<
},
sendMessage: async ({ message, files, onlyAddUserMessage, isWelcomeQuestion }) => {
- const {
- internal_coreProcessMessage,
- activeTopicId,
- activeId,
- activeThreadId,
- sendMessageInServer,
- } = get();
+ const { activeId, sendMessageInServer } = get();
if (!activeId) return;
const fileIdList = files?.map((f) => f.id);
@@ -177,134 +168,6 @@ export const generateAIChat: StateCreator<
// router to server mode send message
if (isServerMode)
return sendMessageInServer({ message, files, onlyAddUserMessage, isWelcomeQuestion });
-
- set({ isCreatingMessage: true }, false, n('creatingMessage/start'));
-
- const newMessage: CreateMessageParams = {
- content: message,
- // if message has attached with files, then add files to message and the agent
- files: fileIdList,
- role: 'user',
- sessionId: activeId,
- // if there is activeTopicId,then add topicId to message
- topicId: activeTopicId,
- threadId: activeThreadId,
- };
-
- const agentConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());
-
- let tempMessageId: string | undefined = undefined;
- let newTopicId: string | undefined = undefined;
-
- // it should be the default topic, then
- // if autoCreateTopic is enabled, check to whether we need to create a topic
- if (!onlyAddUserMessage && !activeTopicId && agentConfig.enableAutoCreateTopic) {
- // check activeTopic and then auto create topic
- const chats = chatSelectors.activeBaseChats(get());
-
- // we will add two messages (user and assistant), so the finial length should +2
- const featureLength = chats.length + 2;
-
- // if there is no activeTopicId and the feature length is greater than the threshold
- // then create a new topic and active it
- if (!activeTopicId && featureLength >= agentConfig.autoCreateTopicThreshold) {
- // we need to create a temp message for optimistic update
- tempMessageId = get().internal_createTmpMessage(newMessage);
- get().internal_toggleMessageLoading(true, tempMessageId);
-
- const topicId = await get().createTopic();
-
- if (topicId) {
- newTopicId = topicId;
- newMessage.topicId = topicId;
-
- // we need to copy the messages to the new topic or the message will disappear
- const mapKey = chatSelectors.currentChatKey(get());
- const newMaps = {
- ...get().messagesMap,
- [messageMapKey(activeId, topicId)]: get().messagesMap[mapKey],
- };
- set({ messagesMap: newMaps }, false, n('moveMessagesToNewTopic'));
-
- // make the topic loading
- get().internal_updateTopicLoading(topicId, true);
- }
- }
- }
- // update assistant update to make it rerank
- useSessionStore.getState().triggerSessionUpdate(get().activeId);
-
- const id = await get().internal_createMessage(newMessage, {
- tempMessageId,
- skipRefresh: !onlyAddUserMessage && newMessage.fileList?.length === 0,
- });
-
- if (!id) {
- set({ isCreatingMessage: false }, false, n('creatingMessage/start'));
- if (!!newTopicId) get().internal_updateTopicLoading(newTopicId, false);
- return;
- }
-
- if (tempMessageId) get().internal_toggleMessageLoading(false, tempMessageId);
-
- // switch to the new topic if create the new topic
- if (!!newTopicId) {
- await get().switchTopic(newTopicId, true);
- await get().internal_fetchMessages();
-
- // delete previous messages
- // remove the temp message map
- const newMaps = { ...get().messagesMap, [messageMapKey(activeId, null)]: [] };
- set({ messagesMap: newMaps }, false, 'internal_copyMessages');
- }
-
- // if only add user message, then stop
- if (onlyAddUserMessage) {
- set({ isCreatingMessage: false }, false, 'creatingMessage/start');
- return;
- }
-
- // Get the current messages to generate AI response
- const messages = chatSelectors.activeBaseChats(get());
- const userFiles = chatSelectors.currentUserFiles(get()).map((f) => f.id);
-
- await internal_coreProcessMessage(messages, id, {
- isWelcomeQuestion,
- ragQuery: get().internal_shouldUseRAG() ? message : undefined,
- threadId: activeThreadId,
- });
-
- set({ isCreatingMessage: false }, false, n('creatingMessage/stop'));
-
- const summaryTitle = async () => {
- // if autoCreateTopic is false, then stop
- if (!agentConfig.enableAutoCreateTopic) return;
-
- // check activeTopic and then auto update topic title
- if (newTopicId) {
- const chats = chatSelectors.getBaseChatsByKey(messageMapKey(activeId, newTopicId))(get());
- await get().summaryTopicTitle(newTopicId, chats);
- return;
- }
-
- if (!activeTopicId) return;
- const topic = topicSelectors.getTopicById(activeTopicId)(get());
-
- if (topic && !topic.title) {
- const chats = chatSelectors.getBaseChatsByKey(messageMapKey(activeId, topic.id))(get());
- await get().summaryTopicTitle(topic.id, chats);
- }
- };
-
- // if there is relative files, then add files to agent
- // only available in server mode
- const addFilesToAgent = async () => {
- if (userFiles.length === 0 || !isServerMode) return;
-
- await useAgentStore.getState().addFilesToAgent(userFiles, false);
- };
-
- await Promise.all([summaryTitle(), addFilesToAgent()]);
},
stopGenerateMessage: () => {
const { chatLoadingIdsAbortController, internal_toggleChatLoading } = get();
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index eea408fac9a..f1b4ec1cab5 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -4,7 +4,6 @@ import { withSWR } from '~test-utils';
import { DEFAULT_PREFERENCE } from '@/const/user';
import { userService } from '@/services/user';
-import { ClientService } from '@/services/user/_deprecated';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import { GlobalServerConfig } from '@/types/serverConfig';
@@ -31,9 +30,7 @@ describe('createCommonSlice', () => {
const avatar = 'data:image/png;base64,';
const spyOn = vi.spyOn(result.current, 'refreshUserState');
- const updateAvatarSpy = vi
- .spyOn(ClientService.prototype, 'updateAvatar')
- .mockResolvedValue(undefined);
+ const updateAvatarSpy = vi.spyOn(userService, 'updateAvatar').mockResolvedValue(undefined);
await act(async () => {
await result.current.updateAvatar(avatar);