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: migrate Next.js navigation APIs to React Router for SPA (#11394)

Innei2253d46ee0db
diff --git a/apps/desktop/src/main/__mocks__/node-mac-permissions.ts b/apps/desktop/src/main/__mocks__/node-mac-permissions.ts
index d2e2b3a5a52..d1f926e878a 100644
--- a/apps/desktop/src/main/__mocks__/node-mac-permissions.ts
+++ b/apps/desktop/src/main/__mocks__/node-mac-permissions.ts
@@ -2,7 +2,6 @@
* Mock for node-mac-permissions native module
* Used in tests since the native module only works on macOS
*/
-
import { vi } from 'vitest';
export const askForAccessibilityAccess = vi.fn(() => undefined);
diff --git a/apps/desktop/src/main/__mocks__/setup.ts b/apps/desktop/src/main/__mocks__/setup.ts
index 9909a87222b..48b9b48e1a8 100644
--- a/apps/desktop/src/main/__mocks__/setup.ts
+++ b/apps/desktop/src/main/__mocks__/setup.ts
@@ -1,7 +1,6 @@
/**
* Vitest setup file for mocking native modules
*/
-
import { vi } from 'vitest';
// Mock node-mac-permissions before any imports
diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
index 613247c4d65..5c3bb8e207c 100644
--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
@@ -4,10 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
import type { IpcContext } from '@/utils/ipc';
import { IpcHandler } from '@/utils/ipc/base';
-import {
- __resetMacPermissionsModuleCache,
- __setMacPermissionsModule,
-} from '@/utils/permissions';
+import { __resetMacPermissionsModuleCache, __setMacPermissionsModule } from '@/utils/permissions';
import SystemController from '../SystemCtr';
diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json
index 55612a3039c..194f5b3c05e 100644
--- a/apps/desktop/tsconfig.json
+++ b/apps/desktop/tsconfig.json
@@ -15,15 +15,9 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"paths": {
- "@/*": [
- "./src/main/*"
- ],
- "~common/*": [
- "./src/common/*"
- ],
- "*": [
- "./*"
- ]
+ "@/*": ["./src/main/*"],
+ "~common/*": ["./src/common/*"],
+ "*": ["./*"]
}
},
"include": [
@@ -33,4 +27,4 @@
"electron-builder.js",
"native-deps.config.js"
]
-}
\ No newline at end of file
+}
diff --git a/e2e/scripts/setup.ts b/e2e/scripts/setup.ts
index 0083c833d37..56b819abfaf 100644
--- a/e2e/scripts/setup.ts
+++ b/e2e/scripts/setup.ts
@@ -16,9 +16,7 @@
* --port <port> Server port (default: 3006)
* --help Show help message
*/
-
-import { type ChildProcess, spawn, spawnSync } from 'node:child_process';
-import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
+import { spawn, spawnSync } from 'node:child_process';
import { resolve } from 'node:path';
// ============================================================================
@@ -33,21 +31,27 @@ const CONFIG = {
defaultPort: 3006,
dockerImage: 'paradedb/paradedb:latest',
projectRoot: resolve(__dirname, '../..'),
- serverTimeout: 120_000, // 2 minutes
-
- // Secrets (for e2e testing only)
- secrets: {
- betterAuthSecret: 'e2e-test-secret-key-for-better-auth-32chars!',
- keyVaultsSecret: 'LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=',
- },
+
- // S3 Mock (required even if not testing file uploads)
- s3Mock: {
+// S3 Mock (required even if not testing file uploads)
+s3Mock: {
accessKeyId: 'e2e-mock-access-key',
bucket: 'e2e-mock-bucket',
endpoint: 'https://e2e-mock-s3.localhost',
secretAccessKey: 'e2e-mock-secret-key',
+ },
+
+
+
+// 2 minutes
+// Secrets (for e2e testing only)
+secrets: {
+ betterAuthSecret: 'e2e-test-secret-key-for-better-auth-32chars!',
+ keyVaultsSecret: 'LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=',
},
+
+
+ serverTimeout: 120_000,
};
// ============================================================================
@@ -55,11 +59,11 @@ const CONFIG = {
// ============================================================================
const colors = {
- cyan: (s: string) => `\x1b[36m${s}\x1b[0m`,
- dim: (s: string) => `\x1b[2m${s}\x1b[0m`,
- green: (s: string) => `\x1b[32m${s}\x1b[0m`,
- red: (s: string) => `\x1b[31m${s}\x1b[0m`,
- yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
+ cyan: (s: string) => `\u001B[36m${s}\u001B[0m`,
+ dim: (s: string) => `\u001B[2m${s}\u001B[0m`,
+ green: (s: string) => `\u001B[32m${s}\u001B[0m`,
+ red: (s: string) => `\u001B[31m${s}\u001B[0m`,
+ yellow: (s: string) => `\u001B[33m${s}\u001B[0m`,
};
function log(emoji: string, message: string) {
@@ -73,12 +77,12 @@ function logStep(step: number, total: number, message: string) {
function exec(
command: string,
args: string[] = [],
- options: { cwd?: string; silent?: boolean } = {}
+ options: { cwd?: string; silent?: boolean } = {},
) {
const { cwd = CONFIG.projectRoot, silent = false } = options;
const result = spawnSync(command, args, {
cwd,
- encoding: 'utf-8',
+ encoding: 'utf8',
shell: true,
stdio: silent ? 'pipe' : 'inherit',
});
@@ -88,7 +92,7 @@ function exec(
function execAsync(
command: string,
args: string[] = [],
- env: Record<string, string> = {}
+ env: Record<string, string> = {},
): Promise<void> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
@@ -111,14 +115,16 @@ function execAsync(
}
async function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
}
async function waitForCondition(
check: () => Promise<boolean>,
timeout: number,
interval: number = 1000,
- onWait?: () => void
+ onWait?: () => void,
): Promise<boolean> {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
@@ -204,7 +210,7 @@ async function startPostgres(): Promise<void> {
},
30_000,
2000,
- () => process.stdout.write('.')
+ () => process.stdout.write('.'),
);
console.log();
@@ -327,7 +333,7 @@ async function startServer(port: number): Promise<void> {
() => isServerRunning(port),
CONFIG.serverTimeout,
2000,
- () => process.stdout.write('.')
+ () => process.stdout.write('.'),
);
console.log();
@@ -412,27 +418,34 @@ function parseArgs(): Options {
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--help':
- case '-h':
+ case '-h': {
options.help = true;
break;
- case '--clean':
+ }
+ case '--clean': {
options.clean = true;
break;
- case '--skip-db':
+ }
+ case '--skip-db': {
options.skipDb = true;
break;
- case '--skip-migrate':
+ }
+ case '--skip-migrate': {
options.skipMigrate = true;
break;
- case '--build':
+ }
+ case '--build': {
options.build = true;
break;
- case '--start':
+ }
+ case '--start': {
options.start = true;
break;
- case '--port':
+ }
+ case '--port': {
options.port = parseInt(args[++i], 10) || CONFIG.defaultPort;
break;
+ }
}
}
@@ -526,4 +539,4 @@ ${colors.green('✅ E2E environment setup completed!')}
}
}
-main();
+await main();
diff --git a/packages/database/src/models/__tests__/knowledgeBase.test.ts b/packages/database/src/models/__tests__/knowledgeBase.test.ts
index 9cda90e3c55..dcce46ba388 100644
--- a/packages/database/src/models/__tests__/knowledgeBase.test.ts
+++ b/packages/database/src/models/__tests__/knowledgeBase.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { sleep } from '@/utils/sleep';
+import { getTestDB } from '../../core/getTestDB';
import {
NewKnowledgeBase,
documents,
@@ -15,7 +16,6 @@ import {
} from '../../schemas';
import { LobeChatDatabase } from '../../type';
import { KnowledgeBaseModel } from '../knowledgeBase';
-import { getTestDB } from '../../core/getTestDB';
const serverDB: LobeChatDatabase = await getTestDB();
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index be65c05ebaa..29f8cd10693 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -556,10 +556,7 @@ export class KnowledgeRepo {
// When in a knowledge base, return standalone documents (folders and notes without fileId)
// that have the knowledgeBaseId column set. Documents with fileId are already
// returned by the file query via their linked file records.
- kbWhereConditions.push(
- sql`d.file_id IS NULL`,
- sql`d.knowledge_base_id = ${knowledgeBaseId}`,
- );
+ kbWhereConditions.push(sql`d.file_id IS NULL`, sql`d.knowledge_base_id = ${knowledgeBaseId}`);
return sql`
SELECT
diff --git a/packages/types/src/discover/assistants.ts b/packages/types/src/discover/assistants.ts
index f380229bd78..a73822e5ac7 100644
--- a/packages/types/src/discover/assistants.ts
+++ b/packages/types/src/discover/assistants.ts
@@ -18,7 +18,7 @@ export enum AssistantCategory {
Marketing = 'marketing',
Office = 'office',
Programming = 'programming',
- Translation = 'translation'
+ Translation = 'translation',
}
export enum AssistantSorts {
@@ -29,7 +29,7 @@ export enum AssistantSorts {
PluginCount = 'pluginCount',
Recommended = 'recommended',
Title = 'title',
- TokenUsage = 'tokenUsage'
+ TokenUsage = 'tokenUsage',
}
export enum AssistantNavKey {
diff --git a/scripts/migrate-spa-navigation.ts b/scripts/migrate-spa-navigation.ts
new file mode 100644
index 00000000000..aac6d8d9832
--- /dev/null
+++ b/scripts/migrate-spa-navigation.ts
@@ -0,0 +1,129 @@
+#!/usr/bin/env bun
+/**
+ * Script to migrate SPA internal components from @/libs/next/navigation
+ * to React Router version hooks.
+ *
+ * For files in (main) directory:
+ * - usePathname -> @/app/[variants]/(main)/hooks/usePathname
+ * - useSearchParams -> @/app/[variants]/(main)/hooks/useSearchParams
+ * - useRouter -> @/app/[variants]/(main)/hooks/useRouter
+ *
+ * @see RFC 147: LOBE-2850 - Phase 3
+ */
+
+import { readFile, writeFile } from 'node:fs/promises';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+// Files that should be migrated to React Router version
+const SPA_FILES = [
+ // (main) directory files using @/libs/next/navigation
+ 'src/app/[variants]/(main)/community/_layout/Sidebar/Header/Nav.tsx',
+ 'src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx',
+ 'src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts',
+ 'src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts',
+ 'src/app/[variants]/(main)/chat/_layout/Sidebar/Header/AddTopicButon.tsx',
+ 'src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Nav.tsx',
+ 'src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts',
+ 'src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts',
+ 'src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx',
+];
+
+interface MigrationResult {
+ changes: string[];
+ filePath: string;
+}
+
+async function migrateFile(relativePath: string): Promise<MigrationResult | null> {
+ const fullPath = join(__dirname, '..', relativePath);
+ const content = await readFile(fullPath, 'utf8');
+ let newContent = content;
+ const changes: string[] = [];
+
+ // Check what hooks are being imported from @/libs/next/navigation
+ const importMatch = content.match(
+ /import\s*\{([^}]+)\}\s*from\s*['"]@\/libs\/next\/navigation['"]/
+ );
+
+ if (!importMatch) {
+ console.log(`⏭️ ${relativePath} - No @/libs/next/navigation import found`);
+ return null;
+ }
+
+ const importedHooks = importMatch[1]
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+
+ console.log(`📝 ${relativePath}`);
+ console.log(` Imported hooks: ${importedHooks.join(', ')}`);
+
+ // Build new imports
+ const newImports: string[] = [];
+
+ for (const hook of importedHooks) {
+ if (hook === 'usePathname') {
+ newImports.push(`import { usePathname } from '@/app/[variants]/(main)/hooks/usePathname';`);
+ changes.push('usePathname -> React Router version');
+ } else if (hook === 'useSearchParams') {
+ newImports.push(
+ `import { useSearchParams } from '@/app/[variants]/(main)/hooks/useSearchParams';`
+ );
+ changes.push('useSearchParams -> React Router version');
+ } else if (hook === 'useRouter') {
+ newImports.push(`import { useRouter } from '@/app/[variants]/(main)/hooks/useRouter';`);
+ changes.push('useRouter -> React Router version');
+ } else {
+ // Keep other imports (like notFound, redirect) from next/navigation
+ console.log(` ⚠️ Unknown hook "${hook}" - keeping original import`);
+ }
+ }
+
+ if (newImports.length === 0) {
+ console.log(` ⏭️ No hooks to migrate`);
+ return null;
+ }
+
+ // Replace the old import with new imports
+ newContent = newContent.replace(
+ /import\s*\{[^}]+\}\s*from\s*['"]@\/libs\/next\/navigation['"];?\n?/,
+ newImports.join('\n') + '\n'
+ );
+
+ if (newContent !== content) {
+ await writeFile(fullPath, newContent, 'utf8');
+ for (const change of changes) {
+ console.log(` ✅ ${change}`);
+ }
+ return { changes, filePath: relativePath };
+ }
+
+ return null;
+}
+
+async function main() {
+ console.log('🚀 Starting SPA navigation migration...\n');
+
+ const results: MigrationResult[] = [];
+
+ for (const file of SPA_FILES) {
+ try {
+ const result = await migrateFile(file);
+ if (result) {
+ results.push(result);
+ }
+ } catch (error) {
+ console.error(`❌ Error processing ${file}:`, error);
+ }
+ }
+
+ console.log('\n' + '='.repeat(60));
+ console.log(`📊 Migration Summary:`);
+ console.log(` - Files processed: ${SPA_FILES.length}`);
+ console.log(` - Files modified: ${results.length}`);
+ console.log('\n✨ SPA navigation migration complete!');
+}
+
+await main();
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
index f5a605ccbe5..a4e7ecd3476 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
@@ -4,143 +4,145 @@ import {
tracer as upstashWorkflowTracer,
} from '@lobechat/observability-otel/modules/upstash-workflow';
import { LayersEnum, MemorySourceType } from '@lobechat/types';
-import { serve } from '@upstash/workflow/nextjs';
+import { Client } from '@upstash/qstash';
import { WorkflowAbort } from '@upstash/workflow';
+import { serve } from '@upstash/workflow/nextjs';
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import {
MemoryExtractionExecutor,
type MemoryExtractionPayloadInput,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { Client } from '@upstash/qstash'
-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
const CEP_LAYERS: LayersEnum[] = [LayersEnum.Context, LayersEnum.Experience, LayersEnum.Preference];
const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];
-export const { POST } = serve<MemoryExtractionPayloadInput>((context) =>
- upstashWorkflowTracer.startActiveSpan(
- 'workflow:memory-user-memory:process-topics',
- async (span) => {
- const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
-
- span.setAttributes({
- ...buildUpstashWorkflowAttributes(context),
- 'workflow.memory_user_memory.force_all': payload.forceAll,
- 'workflow.memory_user_memory.force_topics': payload.forceTopics,
- 'workflow.memory_user_memory.layers': payload.layers.join(','),
- 'workflow.memory_user_memory.source': payload.sources.join(','),
- 'workflow.memory_user_memory.topic_count': payload.topicIds.length,
- 'workflow.memory_user_memory.user_count': payload.userIds.length,
- 'workflow.name': 'memory-user-memory:process-topics',
- });
-
- try {
- console.log('[chat-topic][batch] Starting batch topic processing workflow', {
- topicIds: payload.topicIds,
- userIds: payload.userIds,
+export const { POST } = serve<MemoryExtractionPayloadInput>(
+ (context) =>
+ upstashWorkflowTracer.startActiveSpan(
+ 'workflow:memory-user-memory:process-topics',
+ async (span) => {
+ const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
+
+ span.setAttributes({
+ ...buildUpstashWorkflowAttributes(context),
+ 'workflow.memory_user_memory.force_all': payload.forceAll,
+ 'workflow.memory_user_memory.force_topics': payload.forceTopics,
+ 'workflow.memory_user_memory.layers': payload.layers.join(','),
+ 'workflow.memory_user_memory.source': payload.sources.join(','),
+ 'workflow.memory_user_memory.topic_count': payload.topicIds.length,
+ 'workflow.memory_user_memory.user_count': payload.userIds.length,
+ 'workflow.name': 'memory-user-memory:process-topics',
});
- if (!payload.userIds.length) {
- span.setStatus({ code: SpanStatusCode.OK });
-
- return {
- message: 'No user id provided for topic batch.',
- processedTopics: 0,
- processedUsers: 0,
- };
- }
- if (!payload.topicIds.length) {
- span.setStatus({ code: SpanStatusCode.OK });
-
- return {
- message: 'No topic ids provided for extraction.',
- processedTopics: 0,
- processedUsers: 0,
- };
- }
- if (!payload.sources.includes(MemorySourceType.ChatTopic)) {
- span.setStatus({ code: SpanStatusCode.OK });
-
- return {
- message: 'Source not supported in topic batch.',
- processedTopics: 0,
- processedUsers: 0,
- };
- }
-
- const userId = payload.userIds[0];
- const executor = await MemoryExtractionExecutor.create();
+ try {
+ console.log('[chat-topic][batch] Starting batch topic processing workflow', {
+ topicIds: payload.topicIds,
+ userIds: payload.userIds,
+ });
+
+ if (!payload.userIds.length) {
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ message: 'No user id provided for topic batch.',
+ processedTopics: 0,
+ processedUsers: 0,
+ };
+ }
+ if (!payload.topicIds.length) {
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ message: 'No topic ids provided for extraction.',
+ processedTopics: 0,
+ processedUsers: 0,
+ };
+ }
+ if (!payload.sources.includes(MemorySourceType.ChatTopic)) {
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ message: 'Source not supported in topic batch.',
+ processedTopics: 0,
+ processedUsers: 0,
+ };
+ }
+
+ const userId = payload.userIds[0];
+ const executor = await MemoryExtractionExecutor.create();
+
+ // CEP: run in parallel across the batch
+ await Promise.all(
+ payload.topicIds.map((topicId, index) =>
+ context.run(
+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:cep:${index}`,
+ () =>
+ executor.extractTopic({
+ forceAll: payload.forceAll,
+ forceTopics: payload.forceTopics,
+ from: payload.from,
+ layers: CEP_LAYERS,
+ source: MemorySourceType.ChatTopic,
+ to: payload.to,
+ topicId,
+ userId,
+ }),
+ ),
+ ),
+ );
- // CEP: run in parallel across the batch
- await Promise.all(
- payload.topicIds.map((topicId, index) =>
- context.run(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:cep:${index}`,
+ // Identity: run sequentially for the batch
+ for (const [index, topicId] of payload.topicIds.entries()) {
+ await context.run(
+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity:${index}`,
() =>
executor.extractTopic({
forceAll: payload.forceAll,
forceTopics: payload.forceTopics,
from: payload.from,
- layers: CEP_LAYERS,
+ layers: IDENTITY_LAYERS,
source: MemorySourceType.ChatTopic,
to: payload.to,
topicId,
userId,
}),
- ),
- ),
- );
-
- // Identity: run sequentially for the batch
- for (const [index, topicId] of payload.topicIds.entries()) {
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity:${index}`,
- () =>
- executor.extractTopic({
- forceAll: payload.forceAll,
- forceTopics: payload.forceTopics,
- from: payload.from,
- layers: IDENTITY_LAYERS,
- source: MemorySourceType.ChatTopic,
- to: payload.to,
- topicId,
- userId,
- }),
- );
- }
+ );
+ }
- console.log('[chat-topic][batch] Batch topic processing workflow completed', {
- processedTopics: payload.topicIds.length,
- });
+ console.log('[chat-topic][batch] Batch topic processing workflow completed', {
+ processedTopics: payload.topicIds.length,
+ });
- span.setStatus({ code: SpanStatusCode.OK });
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ processedTopics: payload.topicIds.length,
+ processedUsers: payload.userIds.length,
+ };
+ } catch (error) {
+ // NOTICE: Let WorkflowAbort bubble up (used internally by Upstash); record others
+ if (error instanceof WorkflowAbort) {
+ console.warn('workflow aborted:', error.message);
+ throw error;
+ }
+
+ span.recordException(error as Error);
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'process-topics workflow failed',
+ });
- return {
- processedTopics: payload.topicIds.length,
- processedUsers: payload.userIds.length,
- };
- } catch (error) {
- // NOTICE: Let WorkflowAbort bubble up (used internally by Upstash); record others
- if (error instanceof WorkflowAbort) {
- console.warn('workflow aborted:', error.message);
throw error;
+ } finally {
+ span.end();
}
-
- span.recordException(error as Error);
- span.setStatus({
- code: SpanStatusCode.ERROR,
- message: error instanceof Error ? error.message : 'process-topics workflow failed',
- });
-
- throw error;
- } finally {
- span.end();
- }
- },
- ), {
+ },
+ ),
+ {
// NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
// intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
// for passing additional headers, we have to provide a custom QStash client with the required headers here.
@@ -151,6 +153,7 @@ export const { POST } = serve<MemoryExtractionPayloadInput>((context) =>
headers: {
...upstashWorkflowExtraHeaders,
},
- token: process.env.QSTASH_TOKEN!
- })
-});
+ token: process.env.QSTASH_TOKEN!,
+ }),
+ },
+);
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
index 5d4e5712014..334eb14feee 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
@@ -1,5 +1,9 @@
+import { MemorySourceType } from '@lobechat/types';
+import { Client } from '@upstash/qstash';
import { serve } from '@upstash/workflow/nextjs';
+
import type { ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import {
MemoryExtractionExecutor,
type MemoryExtractionPayloadInput,
@@ -8,135 +12,143 @@ import {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';
-import { MemorySourceType } from '@lobechat/types';
-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
-import { Client } from '@upstash/qstash'
const TOPIC_PAGE_SIZE = 50;
const TOPIC_BATCH_SIZE = 4;
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
-export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {
- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
- if (!params.userIds.length) {
- return { message: 'No user ids provided for topic processing.' };
- }
- if (!params.sources.includes(MemorySourceType.ChatTopic)) {
- return { message: 'No supported sources requested, skip topic processing.' };
- }
-
- const executor = await MemoryExtractionExecutor.create();
-
- const scheduleNextPage = async (userId: string, cursorCreatedAt: Date, cursorId: string) => {
- await MemoryExtractionWorkflowService.triggerProcessUserTopics({
- ...buildWorkflowPayloadInput({
- ...params,
- topicCursor: {
- createdAt: cursorCreatedAt.toISOString(),
- id: cursorId,
- userId,
- },
- topicIds: [],
- userId,
- userIds: [userId],
- }),
- }, { extraHeaders: upstashWorkflowExtraHeaders });
- };
-
- for (const userId of params.userIds) {
- const topicCursor =
- params.topicCursor && params.topicCursor.userId === userId
- ? {
- createdAt: new Date(params.topicCursor.createdAt),
- id: params.topicCursor.id,
- }
- : undefined;
+export const { POST } = serve<MemoryExtractionPayloadInput>(
+ async (context) => {
+ const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
+ if (!params.userIds.length) {
+ return { message: 'No user ids provided for topic processing.' };
+ }
+ if (!params.sources.includes(MemorySourceType.ChatTopic)) {
+ return { message: 'No supported sources requested, skip topic processing.' };
+ }
- const topicsFromPayload =
- params.topicIds && params.topicIds.length > 0
- ? await context.run(
- `memory:user-memory:extract:users:${userId}:filter-topic-ids`,
- async () => {
- const filtered = await executor.filterTopicIdsForUser(userId, params.topicIds);
- return filtered.length > 0 ? filtered : undefined;
- },
- )
- : undefined;
+ const executor = await MemoryExtractionExecutor.create();
- const topicBatch = await context.run<{
- cursor?: ListTopicsForMemoryExtractorCursor;
- ids: string[];
- }>(`memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`, () =>
- topicsFromPayload && topicsFromPayload.length > 0
- ? Promise.resolve({ ids: topicsFromPayload })
- : executor.getTopicsForUser(
- {
- cursor: topicCursor,
- forceAll: params.forceAll,
- forceTopics: params.forceTopics,
- from: params.from,
- to: params.to,
+ const scheduleNextPage = async (userId: string, cursorCreatedAt: Date, cursorId: string) => {
+ await MemoryExtractionWorkflowService.triggerProcessUserTopics(
+ {
+ ...buildWorkflowPayloadInput({
+ ...params,
+ topicCursor: {
+ createdAt: cursorCreatedAt.toISOString(),
+ id: cursorId,
userId,
},
- TOPIC_PAGE_SIZE,
- ),
- );
+ topicIds: [],
+ userId,
+ userIds: [userId],
+ }),
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ );
+ };
- const ids = topicBatch.ids;
- if (!ids.length) {
- continue;
- }
+ for (const userId of params.userIds) {
+ const topicCursor =
+ params.topicCursor && params.topicCursor.userId === userId
+ ? {
+ createdAt: new Date(params.topicCursor.createdAt),
+ id: params.topicCursor.id,
+ }
+ : undefined;
- const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;
+ const topicsFromPayload =
+ params.topicIds && params.topicIds.length > 0
+ ? await context.run(
+ `memory:user-memory:extract:users:${userId}:filter-topic-ids`,
+ async () => {
+ const filtered = await executor.filterTopicIdsForUser(userId, params.topicIds);
+ return filtered.length > 0 ? filtered : undefined;
+ },
+ )
+ : undefined;
- await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {
- // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path
- // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow
- // URLs would inherit that base and lose the desired /process-topics/workflows prefix.
- await context.run(
- `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,
+ const topicBatch = await context.run<{
+ cursor?: ListTopicsForMemoryExtractorCursor;
+ ids: string[];
+ }>(
+ `memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`,
() =>
- MemoryExtractionWorkflowService.triggerProcessTopics({
- ...buildWorkflowPayloadInput(params),
- topicCursor: undefined,
- topicIds,
- userId,
- userIds: [userId],
- }, { extraHeaders: upstashWorkflowExtraHeaders }),
+ topicsFromPayload && topicsFromPayload.length > 0
+ ? Promise.resolve({ ids: topicsFromPayload })
+ : executor.getTopicsForUser(
+ {
+ cursor: topicCursor,
+ forceAll: params.forceAll,
+ forceTopics: params.forceTopics,
+ from: params.from,
+ to: params.to,
+ userId,
+ },
+ TOPIC_PAGE_SIZE,
+ ),
);
- });
- if (!topicsFromPayload && cursor) {
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`,
- () => {
- // NOTICE: Upstash Workflow only supports serializable data into plain JSON,
- // this causes the Date object to be converted into string when passed as parameter from
- // context to child workflow. So we need to convert it back to Date object here.
- const createdAt = new Date(cursor.createdAt);
- if (Number.isNaN(createdAt.getTime())) {
- throw new Error('Invalid cursor date when scheduling next topic page');
- }
+ const ids = topicBatch.ids;
+ if (!ids.length) {
+ continue;
+ }
- scheduleNextPage(userId, createdAt, cursor.id);
- },
- );
+ const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;
+
+ await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {
+ // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path
+ // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow
+ // URLs would inherit that base and lose the desired /process-topics/workflows prefix.
+ await context.run(
+ `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,
+ () =>
+ MemoryExtractionWorkflowService.triggerProcessTopics(
+ {
+ ...buildWorkflowPayloadInput(params),
+ topicCursor: undefined,
+ topicIds,
+ userId,
+ userIds: [userId],
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ );
+ });
+
+ if (!topicsFromPayload && cursor) {
+ await context.run(
+ `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`,
+ () => {
+ // NOTICE: Upstash Workflow only supports serializable data into plain JSON,
+ // this causes the Date object to be converted into string when passed as parameter from
+ // context to child workflow. So we need to convert it back to Date object here.
+ const createdAt = new Date(cursor.createdAt);
+ if (Number.isNaN(createdAt.getTime())) {
+ throw new Error('Invalid cursor date when scheduling next topic page');
+ }
+
+ scheduleNextPage(userId, createdAt, cursor.id);
+ },
+ );
+ }
}
- }
- return { processedUsers: params.userIds.length };
-}, {
- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
- // for passing additional headers, we have to provide a custom QStash client with the required headers here.
- //
- // Refer to the doc for more details:
- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering
- qstashClient: new Client({
- headers: {
- ...upstashWorkflowExtraHeaders,
- },
- token: process.env.QSTASH_TOKEN!
- })
-});
+ return { processedUsers: params.userIds.length };
+ },
+ {
+ // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
+ // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
+ // for passing additional headers, we have to provide a custom QStash client with the required headers here.
+ //
+ // Refer to the doc for more details:
+ // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering
+ qstashClient: new Client({
+ headers: {
+ ...upstashWorkflowExtraHeaders,
+ },
+ token: process.env.QSTASH_TOKEN!,
+ }),
+ },
+);
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
index f423c08753c..0e70a906feb 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
@@ -1,7 +1,8 @@
+import { Client } from '@upstash/qstash';
import { serve } from '@upstash/workflow/nextjs';
import { chunk } from 'es-toolkit/compat';
-import { Client } from '@upstash/qstash'
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import {
MemoryExtractionExecutor,
type MemoryExtractionPayloadInput,
@@ -9,82 +10,90 @@ import {
buildWorkflowPayloadInput,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
const USER_PAGE_SIZE = 50;
const USER_BATCH_SIZE = 10;
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
-export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {
- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
- if (params.sources.length === 0) {
- return { message: 'No sources provided, skip memory extraction.' };
- }
+export const { POST } = serve<MemoryExtractionPayloadInput>(
+ async (context) => {
+ const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
+ if (params.sources.length === 0) {
+ return { message: 'No sources provided, skip memory extraction.' };
+ }
- const executor = await MemoryExtractionExecutor.create();
+ const executor = await MemoryExtractionExecutor.create();
- // NOTICE: Upstash Workflow only supports serializable data into plain JSON,
- // this causes the Date object to be converted into string when passed as parameter from
- // context to child workflow. So we need to convert it back to Date object here.
- const userCursor = params.userCursor
- ? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }
- : undefined;
+ // NOTICE: Upstash Workflow only supports serializable data into plain JSON,
+ // this causes the Date object to be converted into string when passed as parameter from
+ // context to child workflow. So we need to convert it back to Date object here.
+ const userCursor = params.userCursor
+ ? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }
+ : undefined;
- const userBatch = await context.run('memory:user-memory:extract:get-users', () =>
- params.userIds.length > 0
- ? { ids: params.userIds }
- : executor.getUsers(USER_PAGE_SIZE, userCursor),
- );
+ const userBatch = await context.run('memory:user-memory:extract:get-users', () =>
+ params.userIds.length > 0
+ ? { ids: params.userIds }
+ : executor.getUsers(USER_PAGE_SIZE, userCursor),
+ );
- const ids = userBatch.ids;
- if (ids.length === 0) {
- return { message: 'No users to process for memory extraction.' };
- }
+ const ids = userBatch.ids;
+ if (ids.length === 0) {
+ return { message: 'No users to process for memory extraction.' };
+ }
- const cursor = 'cursor' in userBatch ? userBatch.cursor : undefined;
+ const cursor = 'cursor' in userBatch ? userBatch.cursor : undefined;
- const batches = chunk(ids, USER_BATCH_SIZE);
- await Promise.all(
- batches.map((userIds) =>
- context.run(`memory:user-memory:extract:users:process-topic-batches`, () =>
- MemoryExtractionWorkflowService.triggerProcessUserTopics({
- ...buildWorkflowPayloadInput(params),
- topicCursor: undefined,
- userId: userIds[0],
- userIds,
- }, { extraHeaders: upstashWorkflowExtraHeaders},),
+ const batches = chunk(ids, USER_BATCH_SIZE);
+ await Promise.all(
+ batches.map((userIds) =>
+ context.run(`memory:user-memory:extract:users:process-topic-batches`, () =>
+ MemoryExtractionWorkflowService.triggerProcessUserTopics(
+ {
+ ...buildWorkflowPayloadInput(params),
+ topicCursor: undefined,
+ userId: userIds[0],
+ userIds,
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ ),
),
- ),
- );
-
- if (params.userIds.length === 0 && cursor) {
- await context.run('memory:user-memory:extract:users:schedule-next-user-batch', () =>
- MemoryExtractionWorkflowService.triggerProcessUsers({
- ...buildWorkflowPayloadInput({
- ...params,
- userCursor: { createdAt: cursor.createdAt.toISOString(), id: cursor.id },
- }),
- }, { extraHeaders: upstashWorkflowExtraHeaders }),
);
- }
- return {
- batches: batches.length,
- nextCursor: cursor ? cursor.id : null,
- processedUsers: ids.length,
- };
-}, {
- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
- // for passing additional headers, we have to provide a custom QStash client with the required headers here.
- //
- // Refer to the doc for more details:
- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering
- qstashClient: new Client({
- headers: {
- ...upstashWorkflowExtraHeaders,
- },
- token: process.env.QSTASH_TOKEN!
- })
-});
+ if (params.userIds.length === 0 && cursor) {
+ await context.run('memory:user-memory:extract:users:schedule-next-user-batch', () =>
+ MemoryExtractionWorkflowService.triggerProcessUsers(
+ {
+ ...buildWorkflowPayloadInput({
+ ...params,
+ userCursor: { createdAt: cursor.createdAt.toISOString(), id: cursor.id },
+ }),
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ );
+ }
+
+ return {
+ batches: batches.length,
+ nextCursor: cursor ? cursor.id : null,
+ processedUsers: ids.length,
+ };
+ },
+ {
+ // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
+ // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
+ // for passing additional headers, we have to provide a custom QStash client with the required headers here.
+ //
+ // Refer to the doc for more details:
+ // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering
+ qstashClient: new Client({
+ headers: {
+ ...upstashWorkflowExtraHeaders,
+ },
+ token: process.env.QSTASH_TOKEN!,
+ }),
+ },
+);
diff --git a/src/app/[variants]/(auth)/auth-error/page.tsx b/src/app/[variants]/(auth)/auth-error/page.tsx
index 4d6567ad671..cabb4cbf135 100644
--- a/src/app/[variants]/(auth)/auth-error/page.tsx
+++ b/src/app/[variants]/(auth)/auth-error/page.tsx
@@ -2,7 +2,7 @@
import { SiDiscord } from '@icons-pack/react-simple-icons';
import { Alert, Button, Flexbox, Icon } from '@lobehub/ui';
-import Link from 'next/link';
+import Link from '@/libs/next/Link';
import { parseAsString, useQueryState } from 'nuqs';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/login/[[...login]]/page.tsx b/src/app/[variants]/(auth)/login/[[...login]]/page.tsx
index f203cd36847..e133ac4592c 100644
--- a/src/app/[variants]/(auth)/login/[[...login]]/page.tsx
+++ b/src/app/[variants]/(auth)/login/[[...login]]/page.tsx
@@ -1,6 +1,6 @@
import { SignIn } from '@clerk/nextjs';
import { BRANDING_NAME } from '@lobechat/business-const';
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { enableClerk } from '@/envs/auth';
import { metadataModule } from '@/server/metadata';
diff --git a/src/app/[variants]/(auth)/next-auth/error/AuthErrorPage.tsx b/src/app/[variants]/(auth)/next-auth/error/AuthErrorPage.tsx
index f068b8faf66..569778448d2 100644
--- a/src/app/[variants]/(auth)/next-auth/error/AuthErrorPage.tsx
+++ b/src/app/[variants]/(auth)/next-auth/error/AuthErrorPage.tsx
@@ -1,7 +1,7 @@
'use client';
import { signIn } from 'next-auth/react';
-import { useSearchParams } from 'next/navigation';
+import { useSearchParams } from '@/libs/next/navigation';
import { memo } from 'react';
import ErrorCapture from '@/components/Error';
diff --git a/src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx b/src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx
index 836bc38b50b..f38d27a4e22 100644
--- a/src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx
+++ b/src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx
@@ -8,7 +8,7 @@ import { Col, Flex, Row } from 'antd';
import { createStaticStyles } from 'antd-style';
import { AuthError } from 'next-auth';
import { signIn } from 'next-auth/react';
-import { useRouter, useSearchParams } from 'next/navigation';
+import { useRouter, useSearchParams } from '@/libs/next/navigation';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/oauth/callback/error/page.tsx b/src/app/[variants]/(auth)/oauth/callback/error/page.tsx
index 5d1533e811d..b4cb9be80a1 100644
--- a/src/app/[variants]/(auth)/oauth/callback/error/page.tsx
+++ b/src/app/[variants]/(auth)/oauth/callback/error/page.tsx
@@ -2,7 +2,7 @@
import { Button, Flexbox, FluentEmoji, Highlighter, Text } from '@lobehub/ui';
import { Result } from 'antd';
-import Link from 'next/link';
+import Link from '@/libs/next/Link';
import { parseAsString, useQueryState } from 'nuqs';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/oauth/callback/success/page.tsx b/src/app/[variants]/(auth)/oauth/callback/success/page.tsx
index a3ee7b1fee0..9f449e1e1d4 100644
--- a/src/app/[variants]/(auth)/oauth/callback/success/page.tsx
+++ b/src/app/[variants]/(auth)/oauth/callback/success/page.tsx
@@ -2,7 +2,7 @@
import { FluentEmoji, Text } from '@lobehub/ui';
import { Result } from 'antd';
-import { useSearchParams } from 'next/navigation';
+import { useSearchParams } from '@/libs/next/navigation';
import React, { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/oauth/consent/[uid]/page.tsx b/src/app/[variants]/(auth)/oauth/consent/[uid]/page.tsx
index ef68a4f858c..6237340e0b0 100644
--- a/src/app/[variants]/(auth)/oauth/consent/[uid]/page.tsx
+++ b/src/app/[variants]/(auth)/oauth/consent/[uid]/page.tsx
@@ -1,4 +1,4 @@
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { authEnv } from '@/envs/auth';
import { defaultClients } from '@/libs/oidc-provider/config';
diff --git a/src/app/[variants]/(auth)/reset-password/layout.tsx b/src/app/[variants]/(auth)/reset-password/layout.tsx
index c4375cac0ce..5f388fe6ab1 100644
--- a/src/app/[variants]/(auth)/reset-password/layout.tsx
+++ b/src/app/[variants]/(auth)/reset-password/layout.tsx
@@ -1,4 +1,4 @@
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { type PropsWithChildren } from 'react';
import { enableBetterAuth } from '@/envs/auth';
diff --git a/src/app/[variants]/(auth)/reset-password/page.tsx b/src/app/[variants]/(auth)/reset-password/page.tsx
index 41c733c7bac..a9d0cd7c2a2 100644
--- a/src/app/[variants]/(auth)/reset-password/page.tsx
+++ b/src/app/[variants]/(auth)/reset-password/page.tsx
@@ -2,8 +2,8 @@
import { Button } from '@lobehub/ui';
import { ChevronLeftIcon } from 'lucide-react';
-import Link from 'next/link';
-import { useRouter, useSearchParams } from 'next/navigation';
+import Link from '@/libs/next/Link';
+import { useRouter, useSearchParams } from '@/libs/next/navigation';
import { useTranslation } from 'react-i18next';
import AuthCard from '../../../../features/AuthCard';
diff --git a/src/app/[variants]/(auth)/signin/layout.tsx b/src/app/[variants]/(auth)/signin/layout.tsx
index c4375cac0ce..5f388fe6ab1 100644
--- a/src/app/[variants]/(auth)/signin/layout.tsx
+++ b/src/app/[variants]/(auth)/signin/layout.tsx
@@ -1,4 +1,4 @@
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { type PropsWithChildren } from 'react';
import { enableBetterAuth } from '@/envs/auth';
diff --git a/src/app/[variants]/(auth)/signin/useSignIn.ts b/src/app/[variants]/(auth)/signin/useSignIn.ts
index 23e926391e5..e149114bcfc 100644
--- a/src/app/[variants]/(auth)/signin/useSignIn.ts
+++ b/src/app/[variants]/(auth)/signin/useSignIn.ts
@@ -1,6 +1,6 @@
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { Form } from 'antd';
-import { useRouter, useSearchParams } from 'next/navigation';
+import { useRouter, useSearchParams } from '@/libs/next/navigation';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/signup/[[...signup]]/BetterAuthSignUpForm.tsx b/src/app/[variants]/(auth)/signup/[[...signup]]/BetterAuthSignUpForm.tsx
index f8d5214d7d2..524c638d3c7 100644
--- a/src/app/[variants]/(auth)/signup/[[...signup]]/BetterAuthSignUpForm.tsx
+++ b/src/app/[variants]/(auth)/signup/[[...signup]]/BetterAuthSignUpForm.tsx
@@ -3,8 +3,8 @@
import { Button, Icon, Text } from '@lobehub/ui';
import { Form, Input } from 'antd';
import { Lock, Mail } from 'lucide-react';
-import Link from 'next/link';
-import { useSearchParams } from 'next/navigation';
+import Link from '@/libs/next/Link';
+import { useSearchParams } from '@/libs/next/navigation';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/signup/[[...signup]]/page.tsx b/src/app/[variants]/(auth)/signup/[[...signup]]/page.tsx
index 934bbd5cce5..5dbc3bad387 100644
--- a/src/app/[variants]/(auth)/signup/[[...signup]]/page.tsx
+++ b/src/app/[variants]/(auth)/signup/[[...signup]]/page.tsx
@@ -1,5 +1,5 @@
import { SignUp } from '@clerk/nextjs';
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { enableBetterAuth, enableClerk } from '@/envs/auth';
import { metadataModule } from '@/server/metadata';
diff --git a/src/app/[variants]/(auth)/signup/[[...signup]]/useSignUp.tsx b/src/app/[variants]/(auth)/signup/[[...signup]]/useSignUp.tsx
index 853b1252d77..e67747bddd9 100644
--- a/src/app/[variants]/(auth)/signup/[[...signup]]/useSignUp.tsx
+++ b/src/app/[variants]/(auth)/signup/[[...signup]]/useSignUp.tsx
@@ -1,6 +1,6 @@
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { form } from 'motion/react-m';
-import { useRouter, useSearchParams } from 'next/navigation';
+import { useRouter, useSearchParams } from '@/libs/next/navigation';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(auth)/verify-email/layout.tsx b/src/app/[variants]/(auth)/verify-email/layout.tsx
index c4375cac0ce..5f388fe6ab1 100644
--- a/src/app/[variants]/(auth)/verify-email/layout.tsx
+++ b/src/app/[variants]/(auth)/verify-email/layout.tsx
@@ -1,4 +1,4 @@
-import { notFound } from 'next/navigation';
+import { notFound } from '@/libs/next/navigation';
import { type PropsWithChildren } from 'react';
import { enableBetterAuth } from '@/envs/auth';
diff --git a/src/app/[variants]/(auth)/verify-email/page.tsx b/src/app/[variants]/(auth)/verify-email/page.tsx
index fe94ca6661e..3770a11e14f 100644
--- a/src/app/[variants]/(auth)/verify-email/page.tsx
+++ b/src/app/[variants]/(auth)/verify-email/page.tsx
@@ -2,8 +2,8 @@
import { Button } from '@lobehub/ui';
import { ChevronLeftIcon } from 'lucide-react';
-import Link from 'next/link';
-import { useSearchParams } from 'next/navigation';
+import Link from '@/libs/next/Link';
+import { useSearchParams } from '@/libs/next/navigation';
import { useTranslation } from 'react-i18next';
import AuthCard from '../../../../features/AuthCard';
diff --git a/src/app/[variants]/(main)/_layout/index.tsx b/src/app/[variants]/(main)/_layout/index.tsx
index 99eee685455..8026a13dccb 100644
--- a/src/app/[variants]/(main)/_layout/index.tsx
+++ b/src/app/[variants]/(main)/_layout/index.tsx
@@ -3,7 +3,6 @@
import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { Flexbox } from '@lobehub/ui';
import { cx } from 'antd-style';
-import dynamic from 'next/dynamic';
import { type FC, Suspense, lazy } from 'react';
import { HotkeysProvider } from 'react-hotkeys-hook';
import { Outlet } from 'react-router-dom';
@@ -20,6 +19,7 @@ import { useFeedbackModal } from '@/hooks/useFeedbackModal';
import { usePlatform } from '@/hooks/usePlatform';
import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';
import CmdkLazy from '@/layout/GlobalProvider/CmdkLazy';
+import dynamic from '@/libs/next/dynamic';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { HotkeyScopeEnum } from '@/types/hotkey';
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx
index e5d50254b66..24cc28d93aa 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx
@@ -6,8 +6,8 @@ import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
-import { useRouter } from '@/app/[variants]/(main)/hooks/useRouter';
import type { AgentCronJob } from '@/database/schemas/agentCronJob';
+import { useRouter } from '@/libs/router/navigation';
import Actions from './Actions';
import CronTopicItem from './CronTopicItem';
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/AddTopicButon.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/AddTopicButon.tsx
index 29aaffcacdf..a01638395d6 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/AddTopicButon.tsx
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/AddTopicButon.tsx
@@ -2,7 +2,6 @@
import { ActionIcon } from '@lobehub/ui';
import { MessageSquarePlusIcon } from 'lucide-react';
-import { usePathname } from 'next/navigation';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
@@ -10,6 +9,7 @@ import urlJoin from 'url-join';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { usePathname } from '@/libs/router/navigation';
import { useActionSWR } from '@/libs/swr';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index 1f035e2648c..bff1a3b95ff 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -3,7 +3,6 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
import { MessageSquarePlusIcon, SearchIcon } from 'lucide-react';
-import { usePathname } from 'next/navigation';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
@@ -11,6 +10,7 @@ import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { usePathname } from '@/libs/router/navigation';
import { useActionSWR } from '@/libs/swr';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
index 07797a5f393..f028347132b 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
@@ -1,12 +1,12 @@
'use client';
import { Flexbox, SearchBar } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import dynamic from '@/libs/next/dynamic';
const Content = dynamic(() => import('./Content'), {
loading: () => (
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
index b78c1cb1a34..ba38916982d 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
@@ -1,9 +1,9 @@
-import { usePathname } from 'next/navigation';
import { useCallback } from 'react';
import { useParams } from 'react-router-dom';
import urlJoin from 'url-join';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { usePathname } from '@/libs/router/navigation';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
index a462d63a8a1..ca93720a3f2 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
@@ -1,8 +1,8 @@
-import { usePathname } from 'next/navigation';
import { useCallback } from 'react';
import urlJoin from 'url-join';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { usePathname } from '@/libs/router/navigation';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
diff --git a/src/app/[variants]/(main)/agent/features/TelemetryNotification.tsx b/src/app/[variants]/(main)/agent/features/TelemetryNotification.tsx
index 3b6d724f023..3a0dc361eea 100644
--- a/src/app/[variants]/(main)/agent/features/TelemetryNotification.tsx
+++ b/src/app/[variants]/(main)/agent/features/TelemetryNotification.tsx
@@ -4,7 +4,6 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { Avatar, Button, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { LucideArrowUpRightFromSquare, TelescopeIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -56,10 +55,10 @@ const TelemetryNotification = memo<{ mobile?: boolean }>(({ mobile }) => {
<div className={styles.desc}>
{t('telemetry.desc', { appName: BRANDING_NAME })}
<span>
- <Link href={PRIVACY_URL} target={'_blank'}>
+ <a href={PRIVACY_URL} rel="noreferrer" target="_blank">
{t('telemetry.learnMore')}
<Icon icon={LucideArrowUpRightFromSquare} style={{ marginInlineStart: 4 }} />
- </Link>
+ </a>
</span>
</div>
</Flexbox>
diff --git a/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Nav.tsx b/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Nav.tsx
index c2bb05e6232..fc6dfd3027d 100644
--- a/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Nav.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Nav.tsx
@@ -4,7 +4,6 @@ import { SOCIAL_URL } from '@lobechat/business-const';
import { Flexbox, Icon, Tabs, Tag } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { BookOpenIcon, HistoryIcon, LayersIcon, ListIcon, SquareUserIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -104,21 +103,22 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = AssistantNavKey.
<Flexbox align={'center'} className={styles.nav} horizontal justify={'space-between'}>
{nav}
<Flexbox gap={12} horizontal>
- <Link className={styles.link} href={SOCIAL_URL.discord} target={'_blank'}>
+ <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">
{t('mcp.details.nav.needHelp')}
- </Link>
+ </a>
{identifier && marketplaceLink && (
- <Link className={styles.link} href={marketplaceLink} target={'_blank'}>
+ <a className={styles.link} href={marketplaceLink} rel="noreferrer" target="_blank">
{t('mcp.details.nav.viewSourceCode')}
- </Link>
+ </a>
)}
- <Link
+ <a
className={styles.link}
- href={'https://github.com/lobehub/lobe-chat-agents/issues/new/choose'}
- target={'_blank'}
+ href="https://github.com/lobehub/lobe-chat-agents/issues/new/choose"
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.reportIssue')}
- </Link>
+ </a>
</Flexbox>
</Flexbox>
);
diff --git a/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Versions/index.tsx b/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Versions/index.tsx
index 76447d47541..7122cecad5c 100644
--- a/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Versions/index.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/assistant/features/Details/Versions/index.tsx
@@ -5,9 +5,9 @@ import qs from 'query-string';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import Link from '@/app/[variants]/(main)/components/Link';
-import { usePathname } from '@/app/[variants]/(main)/hooks/usePathname';
-import { useQuery } from '@/app/[variants]/(main)/hooks/useQuery';
+import Link from '@/libs/router/Link';
+import { usePathname } from '@/libs/router/navigation';
+import { useQuery } from '@/libs/router/navigation';
import InlineTable from '@/components/InlineTable';
import PublishedTime from '@/components/PublishedTime';
import { type AssistantMarketSource, AssistantNavKey } from '@/types/discover';
diff --git a/src/app/[variants]/(main)/community/(detail)/features/MakedownRender.tsx b/src/app/[variants]/(main)/community/(detail)/features/MakedownRender.tsx
index 3d83c6f4e38..c336030a94e 100644
--- a/src/app/[variants]/(main)/community/(detail)/features/MakedownRender.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/features/MakedownRender.tsx
@@ -2,7 +2,6 @@
import { Center, Empty, Markdown } from '@lobehub/ui';
import { FileText } from 'lucide-react';
-import Link from 'next/link';
import { type ReactNode, memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,7 +27,7 @@ const MarkdownRender = memo<{ children?: string }>(({ children }) => {
components={{
a: ({ href, ...rest }: { children?: ReactNode; href?: string }) => {
if (href && href.startsWith('http'))
- return <Link {...rest} href={href} target={'_blank'} />;
+ return <a {...rest} href={href} rel="noreferrer" target="_blank" />;
return rest?.children;
},
h1: H1,
diff --git a/src/app/[variants]/(main)/community/(detail)/features/ShareButton.tsx b/src/app/[variants]/(main)/community/(detail)/features/ShareButton.tsx
index ce7e9fa3645..311347349be 100644
--- a/src/app/[variants]/(main)/community/(detail)/features/ShareButton.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/features/ShareButton.tsx
@@ -15,7 +15,6 @@ import {
import { createStaticStyles, cssVar } from 'antd-style';
import { startCase } from 'es-toolkit/compat';
import { LinkIcon, Share2Icon } from 'lucide-react';
-import Link from 'next/link';
import { type ReactNode, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -121,14 +120,14 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {
{[x, reddit, telegram, whatsapp, mastodon, weibo].map(
(item) =>
item.icon && (
- <Link href={item.link} key={item.title} target={'_blank'}>
+ <a href={item.link} key={item.title} rel="noreferrer" target="_blank">
<ActionIcon
className={styles.icon}
icon={item.icon}
size={{ blockSize: 36, borderRadius: 18, size: 16 }}
title={item.title}
/>
- </Link>
+ </a>
),
)}
</Flexbox>
diff --git a/src/app/[variants]/(main)/community/(detail)/features/Toc/Heading.tsx b/src/app/[variants]/(main)/community/(detail)/features/Toc/Heading.tsx
index fa00f92a131..b241c505945 100644
--- a/src/app/[variants]/(main)/community/(detail)/features/Toc/Heading.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/features/Toc/Heading.tsx
@@ -4,7 +4,6 @@ import { Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { kebabCase } from 'es-toolkit/compat';
import { Heading2, Heading3, Heading4, Heading5 } from 'lucide-react';
-import Link from 'next/link';
import {
Children,
type ComponentProps,
@@ -92,14 +91,14 @@ const createHeading = (Tag: `h${1 | 2 | 3 | 4 | 5 | 6}`) => {
id={id}
>
{children}
- <Link
+ <a
aria-label="Permalink for this section"
className={styles.anchor}
href={`#${id}`}
style={{ scrollMarginTop: 96 }}
>
<Icon icon={HeadingIcon[Tag]} />
- </Link>
+ </a>
</Tag>
);
};
diff --git a/src/app/[variants]/(main)/community/(detail)/mcp/features/Details/Versions/index.tsx b/src/app/[variants]/(main)/community/(detail)/mcp/features/Details/Versions/index.tsx
index fdf0b468466..e011e18c445 100644
--- a/src/app/[variants]/(main)/community/(detail)/mcp/features/Details/Versions/index.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/mcp/features/Details/Versions/index.tsx
@@ -5,8 +5,8 @@ import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import Link from '@/app/[variants]/(main)/components/Link';
-import { usePathname } from '@/app/[variants]/(main)/hooks/usePathname';
+import Link from '@/libs/router/Link';
+import { usePathname } from '@/libs/router/navigation';
import InlineTable from '@/components/InlineTable';
import PublishedTime from '../../../../../../../../../components/PublishedTime';
diff --git a/src/app/[variants]/(main)/community/(detail)/model/features/Details/Nav.tsx b/src/app/[variants]/(main)/community/(detail)/model/features/Details/Nav.tsx
index 885122a0440..e13d509874b 100644
--- a/src/app/[variants]/(main)/community/(detail)/model/features/Details/Nav.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/model/features/Details/Nav.tsx
@@ -4,7 +4,6 @@ import { SOCIAL_URL } from '@lobechat/business-const';
import { Flexbox, Icon, Tabs } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { BookOpenIcon, ListIcon, Settings2Icon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -65,23 +64,25 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ModelNavKey.Over
<Flexbox align={'center'} className={styles.nav} horizontal justify={'space-between'}>
{nav}
<Flexbox gap={12} horizontal>
- <Link className={styles.link} href={SOCIAL_URL.discord} target={'_blank'}>
+ <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">
{t('mcp.details.nav.needHelp')}
- </Link>
- <Link
+ </a>
+ <a
className={styles.link}
- href={'https://github.com/lobehub/lobe-chat/tree/main/src/config/aiModels'}
- target={'_blank'}
+ href="https://github.com/lobehub/lobe-chat/tree/main/src/config/aiModels"
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.viewSourceCode')}
- </Link>
- <Link
+ </a>
+ <a
className={styles.link}
- href={'https://github.com/lobehub/lobe-chat/issues/new/choose'}
- target={'_blank'}
+ href="https://github.com/lobehub/lobe-chat/issues/new/choose"
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.reportIssue')}
- </Link>
+ </a>
</Flexbox>
</Flexbox>
);
diff --git a/src/app/[variants]/(main)/community/(detail)/model/features/Details/Parameter/ParameterItem.tsx b/src/app/[variants]/(main)/community/(detail)/model/features/Details/Parameter/ParameterItem.tsx
index cdca0340e93..15bbafdefe5 100644
--- a/src/app/[variants]/(main)/community/(detail)/model/features/Details/Parameter/ParameterItem.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/model/features/Details/Parameter/ParameterItem.tsx
@@ -1,7 +1,6 @@
import { Flexbox } from '@lobehub/ui';
import { Divider } from 'antd';
import { cssVar } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,9 +28,9 @@ const ParameterItem = memo<ParameterItemProps>(
<Flexbox align={'flex-start'} gap={16}>
<p style={{ color: cssVar.colorTextSecondary, margin: 0 }}>
{desc}{' '}
- <Link href={docUrl} target={'_blank'}>
+ <a href={docUrl} rel="noreferrer" target="_blank">
{t('models.parameterList.docs')}
- </Link>
+ </a>
</p>
<Divider dashed style={{ margin: 0 }} />
<Flexbox align={'center'} gap={16} horizontal style={{ paddingBottom: 8 }} wrap={'wrap'}>
diff --git a/src/app/[variants]/(main)/community/(detail)/provider/features/Details/Nav.tsx b/src/app/[variants]/(main)/community/(detail)/provider/features/Details/Nav.tsx
index 32f1c97dadb..94edaf13fac 100644
--- a/src/app/[variants]/(main)/community/(detail)/provider/features/Details/Nav.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/provider/features/Details/Nav.tsx
@@ -4,7 +4,6 @@ import { BRANDING_PROVIDER, SOCIAL_URL } from '@lobechat/business-const';
import { Flexbox, Icon, Tabs } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { BookOpenIcon, BrainCircuitIcon, ListIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -78,28 +77,30 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ProviderNavKey.O
<Flexbox align={'center'} className={styles.nav} horizontal justify={'space-between'}>
{nav}
<Flexbox gap={12} horizontal>
- <Link className={styles.link} href={SOCIAL_URL.discord} target={'_blank'}>
+ <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">
{t('mcp.details.nav.needHelp')}
- </Link>
+ </a>
{identifier && (
- <Link
+ <a
className={styles.link}
href={urlJoin(
'https://github.com/lobehub/lobe-chat/tree/main/src/config/modelProviders',
`${identifier}.ts`,
)}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.viewSourceCode')}
- </Link>
+ </a>
)}
- <Link
+ <a
className={styles.link}
- href={'https://github.com/lobehub/lobe-chat/issues/new/choose'}
- target={'_blank'}
+ href="https://github.com/lobehub/lobe-chat/issues/new/choose"
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.reportIssue')}
- </Link>
+ </a>
</Flexbox>
</Flexbox>
);
diff --git a/src/app/[variants]/(main)/community/(detail)/provider/features/Header.tsx b/src/app/[variants]/(main)/community/(detail)/provider/features/Header.tsx
index 780ad389064..8f70605c6d6 100644
--- a/src/app/[variants]/(main)/community/(detail)/provider/features/Header.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/provider/features/Header.tsx
@@ -4,7 +4,6 @@ import { Github, ProviderCombine } from '@lobehub/icons';
import { ActionIcon, Flexbox } from '@lobehub/ui';
import { cssVar, useResponsive } from 'antd-style';
import { GlobeIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -32,9 +31,9 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
<ProviderCombine provider={identifier} size={mobile ? 32 : 48} />
<Flexbox align={'center'} gap={4} horizontal>
{Boolean(url || modelsUrl) ? (
- <Link href={url || (modelsUrl as string)} target={'_blank'}>
+ <a href={url || (modelsUrl as string)} rel="noreferrer" target="_blank">
@{name}
- </Link>
+ </a>
) : (
<span>@{name}</span>
)}
@@ -42,25 +41,27 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
</Flexbox>
<Flexbox align={'center'} horizontal>
{Boolean(url || modelsUrl) && (
- <Link
+ <a
href={(url || modelsUrl) as string}
onClick={(e) => e.stopPropagation()}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
<ActionIcon color={cssVar.colorTextDescription} icon={GlobeIcon} />
- </Link>
+ </a>
)}
- <Link
+ <a
href={urlJoin(
'https://github.com/lobehub/lobe-chat-agents/tree/main/locales',
identifier as string,
)}
onClick={(e) => e.stopPropagation()}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
<ActionIcon fill={cssVar.colorTextDescription} icon={Github} />
- </Link>
+ </a>
</Flexbox>
</Flexbox>
diff --git a/src/app/[variants]/(main)/community/(list)/(home)/index.tsx b/src/app/[variants]/(main)/community/(list)/(home)/index.tsx
index d7bab5a53ac..0c2a7e696be 100644
--- a/src/app/[variants]/(main)/community/(list)/(home)/index.tsx
+++ b/src/app/[variants]/(main)/community/(list)/(home)/index.tsx
@@ -4,7 +4,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useDiscoverStore } from '@/store/discover';
-import { McpSorts, AssistantSorts } from '@/types/discover';
+import { AssistantSorts, McpSorts } from '@/types/discover';
import Title from '../../components/Title';
import AssistantList from '../assistant/features/List';
diff --git a/src/app/[variants]/(main)/community/(list)/assistant/features/Category/useCategory.tsx b/src/app/[variants]/(main)/community/(list)/assistant/features/Category/useCategory.tsx
index ef8d2e585ff..896576ec46d 100644
--- a/src/app/[variants]/(main)/community/(list)/assistant/features/Category/useCategory.tsx
+++ b/src/app/[variants]/(main)/community/(list)/assistant/features/Category/useCategory.tsx
@@ -2,6 +2,7 @@ import {
BadgeDollarSignIcon,
BriefcaseIcon,
Coffee,
+ CompassIcon,
DramaIcon,
GamepadIcon,
GraduationCapIcon,
@@ -14,7 +15,6 @@ import {
PencilIcon,
PrinterIcon,
TerminalSquareIcon,
- CompassIcon,
} from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/community/(list)/features/SortButton/index.tsx b/src/app/[variants]/(main)/community/(list)/features/SortButton/index.tsx
index 97ab6119e15..aab56b8ef1b 100644
--- a/src/app/[variants]/(main)/community/(list)/features/SortButton/index.tsx
+++ b/src/app/[variants]/(main)/community/(list)/features/SortButton/index.tsx
@@ -1,12 +1,11 @@
-import { Dropdown, type DropdownMenuItemType, Icon , Button } from '@lobehub/ui';
+import { Button, Dropdown, type DropdownMenuItemType, Icon } from '@lobehub/ui';
import { ArrowDownWideNarrow, ChevronDown } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { usePathname } from '@/app/[variants]/(main)/hooks/usePathname';
-import { useQuery } from '@/app/[variants]/(main)/hooks/useQuery';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { usePathname , useQuery } from '@/libs/router/navigation';
import {
AssistantSorts,
DiscoverTab,
diff --git a/src/app/[variants]/(main)/community/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/community/_layout/Sidebar/Header/Nav.tsx
index eafbce0f2f1..e5ce9099b9e 100644
--- a/src/app/[variants]/(main)/community/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/community/_layout/Sidebar/Header/Nav.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { McpIcon, ProviderIcon } from '@lobehub/ui/icons';
import { Bot, Brain, ShapesIcon } from 'lucide-react';
-import { usePathname } from 'next/navigation';
+import { usePathname } from '@/libs/router/navigation';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
diff --git a/src/app/[variants]/(main)/community/features/CreateButton/Inner.tsx b/src/app/[variants]/(main)/community/features/CreateButton/Inner.tsx
index f8410a2b246..29725d54f37 100644
--- a/src/app/[variants]/(main)/community/features/CreateButton/Inner.tsx
+++ b/src/app/[variants]/(main)/community/features/CreateButton/Inner.tsx
@@ -1,7 +1,7 @@
import { Button, Icon, Tag, Typography } from '@lobehub/ui';
import { Divider } from 'antd';
import { Github, Settings, Share2 } from 'lucide-react';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/community/features/CreateButton/index.tsx b/src/app/[variants]/(main)/community/features/CreateButton/index.tsx
index b7ba26deeb4..73b8822c2f1 100644
--- a/src/app/[variants]/(main)/community/features/CreateButton/index.tsx
+++ b/src/app/[variants]/(main)/community/features/CreateButton/index.tsx
@@ -1,7 +1,7 @@
import { ActionIcon, Button, Modal , Skeleton } from '@lobehub/ui';
import { useResponsive } from 'antd-style';
import { Brush } from 'lucide-react';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/community/features/Search.tsx b/src/app/[variants]/(main)/community/features/Search.tsx
index bd161089b12..6c9459d96b9 100644
--- a/src/app/[variants]/(main)/community/features/Search.tsx
+++ b/src/app/[variants]/(main)/community/features/Search.tsx
@@ -6,8 +6,8 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
-import { usePathname } from '@/app/[variants]/(main)/hooks/usePathname';
-import { useQuery } from '@/app/[variants]/(main)/hooks/useQuery';
+import { usePathname } from '@/libs/router/navigation';
+import { useQuery } from '@/libs/router/navigation';
import { withSuspense } from '@/components/withSuspense';
import { useQueryRoute } from '@/hooks/useQueryRoute';
diff --git a/src/app/[variants]/(main)/community/features/Title.tsx b/src/app/[variants]/(main)/community/features/Title.tsx
index eedbdce342b..b189291bc39 100644
--- a/src/app/[variants]/(main)/community/features/Title.tsx
+++ b/src/app/[variants]/(main)/community/features/Title.tsx
@@ -3,7 +3,6 @@
import { Flexbox, type FlexboxProps, Icon } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { ChevronRight } from 'lucide-react';
-import NextLink from 'next/link';
import { type ReactNode, memo } from 'react';
import { Link as RouterLink } from 'react-router-dom';
@@ -51,10 +50,10 @@ const Title = memo<TitleProps>(
if (moreLink) {
if (isExternalLink) {
moreLinkElement = (
- <NextLink className={styles.more} href={moreLink} target="_blank">
+ <a className={styles.more} href={moreLink} rel="noreferrer" target="_blank">
<span style={{ marginRight: 4 }}>{more}</span>
<Icon icon={ChevronRight} />
- </NextLink>
+ </a>
);
} else if (isCommunityRoute) {
moreLinkElement = (
@@ -64,11 +63,12 @@ const Title = memo<TitleProps>(
</RouterLink>
);
} else {
+ // For non-external, non-community routes (like auth pages), use RouterLink
moreLinkElement = (
- <NextLink className={styles.more} href={moreLink}>
+ <RouterLink className={styles.more} to={moreLink}>
<span style={{ marginRight: 4 }}>{more}</span>
<Icon icon={ChevronRight} />
- </NextLink>
+ </RouterLink>
);
}
}
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
index c888cf0d4d1..99cac313480 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
@@ -3,7 +3,6 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
import { MessageSquarePlusIcon, SearchIcon } from 'lucide-react';
-import { usePathname } from 'next/navigation';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
@@ -11,6 +10,7 @@ import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { usePathname } from '@/libs/router/navigation';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
index 07797a5f393..7d1fd9d774a 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox, SearchBar } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
index b78c1cb1a34..d4e882de541 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
@@ -1,4 +1,4 @@
-import { usePathname } from 'next/navigation';
+import { usePathname } from '@/libs/router/navigation';
import { useCallback } from 'react';
import { useParams } from 'react-router-dom';
import urlJoin from 'url-join';
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx
index 1933bb89881..3508c6cdf83 100644
--- a/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx
@@ -2,12 +2,12 @@
import { ActionIcon } from '@lobehub/ui';
import { Share2 } from 'lucide-react';
-import dynamic from 'next/dynamic';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useWorkspaceModal } from '@/hooks/useWorkspaceModal';
+import dynamic from '@/libs/next/dynamic';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
diff --git a/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx b/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx
index 3b6d724f023..3a0dc361eea 100644
--- a/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx
+++ b/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx
@@ -4,7 +4,6 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { Avatar, Button, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { LucideArrowUpRightFromSquare, TelescopeIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -56,10 +55,10 @@ const TelemetryNotification = memo<{ mobile?: boolean }>(({ mobile }) => {
<div className={styles.desc}>
{t('telemetry.desc', { appName: BRANDING_NAME })}
<span>
- <Link href={PRIVACY_URL} target={'_blank'}>
+ <a href={PRIVACY_URL} rel="noreferrer" target="_blank">
{t('telemetry.learnMore')}
<Icon icon={LucideArrowUpRightFromSquare} style={{ marginInlineStart: 4 }} />
- </Link>
+ </a>
</span>
</div>
</Flexbox>
diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/AllAgentsDrawer/index.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/AllAgentsDrawer/index.tsx
index 3e8f9ab17b9..e62978035b9 100644
--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/AllAgentsDrawer/index.tsx
+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/AllAgentsDrawer/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox, SearchBar } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/hooks/useActiveTabKey.ts b/src/app/[variants]/(main)/hooks/useActiveTabKey.ts
index db14654d019..04dbba1cf1b 100644
--- a/src/app/[variants]/(main)/hooks/useActiveTabKey.ts
+++ b/src/app/[variants]/(main)/hooks/useActiveTabKey.ts
@@ -1,21 +1,18 @@
-import { useLocation, useSearchParams } from 'react-router-dom';
-
import { ProfileTabs, SettingsTabs, type SidebarTabKey } from '@/store/global/initialState';
+import { usePathname, useSearchParams } from '@/libs/router/navigation';
/**
* Returns the active tab key (chat/discover/settings/...)
- * React Router version for (main) directory
+ * Uses React Router via @/libs/router
*/
export const useActiveTabKey = () => {
- const location = useLocation();
- const pathname = location.pathname;
-
+ const pathname = usePathname();
return pathname.split('/').find(Boolean) as SidebarTabKey;
};
/**
* Returns the active setting page key (?active=common/sync/agent/...)
- * React Router version for (main) directory
+ * Uses React Router via @/libs/router
*/
export const useActiveSettingsKey = () => {
const [searchParams] = useSearchParams();
@@ -26,12 +23,10 @@ export const useActiveSettingsKey = () => {
/**
* Returns the active profile page key (profile/security/stats/...)
- * React Router version for (main) directory
+ * Uses React Router via @/libs/router
*/
export const useActiveProfileKey = () => {
- const location = useLocation();
- const pathname = location.pathname;
-
+ const pathname = usePathname();
const tabs = pathname.split('/').findLast(Boolean);
if (tabs === 'profile') return ProfileTabs.Profile;
diff --git a/src/app/[variants]/(main)/hooks/usePathname.ts b/src/app/[variants]/(main)/hooks/usePathname.ts
deleted file mode 100644
index c3590091f52..00000000000
--- a/src/app/[variants]/(main)/hooks/usePathname.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { useLocation } from 'react-router-dom';
-
-/**
- * Hook to get current pathname
- * React Router version for (main) directory
- */
-export const usePathname = () => {
- const location = useLocation();
- return location.pathname;
-};
diff --git a/src/app/[variants]/(main)/hooks/useQuery.ts b/src/app/[variants]/(main)/hooks/useQuery.ts
deleted file mode 100644
index 8d2cca367e6..00000000000
--- a/src/app/[variants]/(main)/hooks/useQuery.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import qs from 'query-string';
-import { useMemo } from 'react';
-import { useSearchParams } from 'react-router-dom';
-
-/**
- * Hook to get query parameters
- * React Router version for (main) directory
- */
-export const useQuery = () => {
- const [searchParams] = useSearchParams();
- return useMemo(() => qs.parse(searchParams.toString()), [searchParams]);
-};
diff --git a/src/app/[variants]/(main)/hooks/useRouter.ts b/src/app/[variants]/(main)/hooks/useRouter.ts
deleted file mode 100644
index bc69eef5774..00000000000
--- a/src/app/[variants]/(main)/hooks/useRouter.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { useNavigate } from 'react-router-dom';
-
-/**
- * Hook to get router navigation functions
- * React Router version for (main) directory
- *
- * Provides a Next.js-like API using React Router
- */
-export const useRouter = () => {
- const navigate = useNavigate();
-
- return {
- back: () => navigate(-1),
- forward: () => navigate(1),
- // Note: prefetch is not supported in React Router
- prefetch: () => {},
-
- push: (href: string) => navigate(href),
-
- replace: (href: string) => navigate(href, { replace: true }),
- };
-};
diff --git a/src/app/[variants]/(main)/hooks/useSearchParams.ts b/src/app/[variants]/(main)/hooks/useSearchParams.ts
deleted file mode 100644
index 9386e096b7e..00000000000
--- a/src/app/[variants]/(main)/hooks/useSearchParams.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { useSearchParams as useReactRouterSearchParams } from 'react-router-dom';
-
-/**
- * Hook to get search params
- * React Router version for (main) directory
- *
- * Returns [searchParams, setSearchParams] tuple similar to React Router
- */
-export const useSearchParams = () => {
- return useReactRouterSearchParams();
-};
diff --git a/src/app/[variants]/(main)/image/NotSupportClient.tsx b/src/app/[variants]/(main)/image/NotSupportClient.tsx
index 006ee63b7fc..05ee31d41bb 100644
--- a/src/app/[variants]/(main)/image/NotSupportClient.tsx
+++ b/src/app/[variants]/(main)/image/NotSupportClient.tsx
@@ -4,7 +4,6 @@ import { UTM_SOURCE } from '@lobechat/business-const';
import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { Database, FileImage, Network, Sparkles } from 'lucide-react';
-import Link from 'next/link';
import { Trans, useTranslation } from 'react-i18next';
import FeatureList from '@/components/FeatureList';
@@ -131,11 +130,13 @@ const NotSupportClient = () => {
<Trans
components={[
<span key="0" />,
- <Link href={DATABASE_SELF_HOSTING_URL} key="1" />,
+ <a href={DATABASE_SELF_HOSTING_URL} key="1" rel="noreferrer" target="_blank" />,
<span key="2" />,
- <Link
+ <a
href={`${OFFICIAL_URL}?utm_source=${UTM_SOURCE}&utm_medium=client_not_support_image`}
key="3"
+ rel="noreferrer"
+ target="_blank"
/>,
]}
i18nKey={'notSupportGuide.desc'}
diff --git a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
index 8417c073052..4c00101353c 100644
--- a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
+++ b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
@@ -4,7 +4,7 @@ import { Center } from '@lobehub/ui';
import { App } from 'antd';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { Image as ImageIcon, X } from 'lucide-react';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import React, { type FC, memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/ImageManageModal.tsx b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/ImageManageModal.tsx
index 1fdf15ef8af..4917748b5c4 100644
--- a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/ImageManageModal.tsx
+++ b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/ImageManageModal.tsx
@@ -3,7 +3,7 @@
import { Button, Modal } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { Upload, X } from 'lucide-react';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import React, { type FC, memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/index.tsx b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/index.tsx
index 6dbb047f8df..3bf8e5c1f34 100644
--- a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/index.tsx
+++ b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/MultiImagesUpload/index.tsx
@@ -4,7 +4,7 @@
import { Center } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { Image as ImageIcon, X } from 'lucide-react';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import React, { type FC, memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx
index 74a2a577697..394ea093a53 100644
--- a/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx
+++ b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx
@@ -1,7 +1,7 @@
import { ActionIcon, Block } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { MaximizeIcon, MinimizeIcon } from 'lucide-react';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useEffect, useState } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
diff --git a/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx
index 95b38c706a2..e1fc204f922 100644
--- a/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx
@@ -9,7 +9,7 @@ import {
SearchIcon,
SignatureIcon,
} from 'lucide-react';
-import { usePathname } from 'next/navigation';
+import { usePathname } from '@/libs/router/navigation';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
diff --git a/src/app/[variants]/(main)/memory/features/SourceLink.tsx b/src/app/[variants]/(main)/memory/features/SourceLink.tsx
index 2c68e8105cb..04b09e4fba9 100644
--- a/src/app/[variants]/(main)/memory/features/SourceLink.tsx
+++ b/src/app/[variants]/(main)/memory/features/SourceLink.tsx
@@ -1,7 +1,7 @@
import { Button, Icon, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { Link2 } from 'lucide-react';
-import Link from 'next/link';
+import Link from '@/libs/router/Link';
import { memo } from 'react';
import { useNavigate } from 'react-router-dom';
diff --git a/src/app/[variants]/(main)/page/_layout/Body/AllPagesDrawer/index.tsx b/src/app/[variants]/(main)/page/_layout/Body/AllPagesDrawer/index.tsx
index 28f2cfb5071..d8806edc6c1 100644
--- a/src/app/[variants]/(main)/page/_layout/Body/AllPagesDrawer/index.tsx
+++ b/src/app/[variants]/(main)/page/_layout/Body/AllPagesDrawer/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox, SearchBar } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/settings/about/features/ItemCard.tsx b/src/app/[variants]/(main)/settings/about/features/ItemCard.tsx
index 4661ac16354..c9382422312 100644
--- a/src/app/[variants]/(main)/settings/about/features/ItemCard.tsx
+++ b/src/app/[variants]/(main)/settings/about/features/ItemCard.tsx
@@ -1,7 +1,6 @@
import { Block, Icon } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { type LucideIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
export interface ItemCardProps {
@@ -13,12 +12,12 @@ export interface ItemCardProps {
const ItemCard = memo<ItemCardProps>(({ label, icon, href }) => {
return (
- <Link href={href} style={{ color: 'inherit' }} target={'_blank'}>
+ <a href={href} rel="noreferrer" style={{ color: 'inherit' }} target="_blank">
<Block clickable gap={12} horizontal paddingBlock={12} paddingInline={18}>
{icon && <Icon fill={cssVar.colorText} icon={icon} size={18} />}
{label}
</Block>
- </Link>
+ </a>
);
});
diff --git a/src/app/[variants]/(main)/settings/about/features/ItemLink.tsx b/src/app/[variants]/(main)/settings/about/features/ItemLink.tsx
index 0b07543d526..fd1a8ee97b4 100644
--- a/src/app/[variants]/(main)/settings/about/features/ItemLink.tsx
+++ b/src/app/[variants]/(main)/settings/about/features/ItemLink.tsx
@@ -1,7 +1,6 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { type LucideIcon, SquareArrowOutUpRight } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
export interface ItemLinkProps {
@@ -13,12 +12,12 @@ export interface ItemLinkProps {
const ItemLink = memo<ItemLinkProps>(({ label, href }) => {
return (
- <Link href={href} style={{ color: 'inherit' }} target={'_blank'}>
+ <a href={href} rel="noreferrer" style={{ color: 'inherit' }} target="_blank">
<Flexbox align={'center'} gap={8} horizontal>
{label}
<Icon color={cssVar.colorTextDescription} icon={SquareArrowOutUpRight} size={14} />
</Flexbox>
- </Link>
+ </a>
);
});
diff --git a/src/app/[variants]/(main)/settings/about/features/Version.tsx b/src/app/[variants]/(main)/settings/about/features/Version.tsx
index 4d9a890bade..8ecc2bb722e 100644
--- a/src/app/[variants]/(main)/settings/about/features/Version.tsx
+++ b/src/app/[variants]/(main)/settings/about/features/Version.tsx
@@ -1,7 +1,6 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Block, Button, Flexbox, Tag } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -31,7 +30,7 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
width={'100%'}
>
<Flexbox align={'center'} flex={'none'} gap={16} horizontal>
- <Link href={OFFICIAL_SITE} target={'_blank'}>
+ <a href={OFFICIAL_SITE} rel="noreferrer" target="_blank">
<Block
align={'center'}
className={styles.logo}
@@ -42,7 +41,7 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
>
<ProductLogo size={52} />
</Block>
- </Link>
+ </a>
<Flexbox align={'flex-start'} gap={6}>
<div style={{ fontSize: 18, fontWeight: 'bolder' }}>{BRANDING_NAME}</div>
<Flexbox gap={6} horizontal={!mobile}>
@@ -56,15 +55,15 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
</Flexbox>
</Flexbox>
<Flexbox flex={mobile ? 1 : undefined} gap={8} horizontal>
- <Link href={CHANGELOG_URL} style={{ flex: 1 }} target={'_blank'}>
+ <a href={CHANGELOG_URL} rel="noreferrer" style={{ flex: 1 }} target="_blank">
<Button block={mobile}>{t('changelog')}</Button>
- </Link>
+ </a>
{hasNewVersion && (
- <Link href={MANUAL_UPGRADE_URL} style={{ flex: 1 }} target={'_blank'}>
+ <a href={MANUAL_UPGRADE_URL} rel="noreferrer" style={{ flex: 1 }} target="_blank">
<Button block={mobile} type={'primary'}>
{t('upgradeVersion.action')}
</Button>
- </Link>
+ </a>
)}
</Flexbox>
</Flexbox>
diff --git a/src/app/[variants]/(main)/settings/features/SettingsContent.tsx b/src/app/[variants]/(main)/settings/features/SettingsContent.tsx
index 0b9e1cd7fc4..687f764d05b 100644
--- a/src/app/[variants]/(main)/settings/features/SettingsContent.tsx
+++ b/src/app/[variants]/(main)/settings/features/SettingsContent.tsx
@@ -1,7 +1,7 @@
'use client';
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { Fragment } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
diff --git a/src/app/[variants]/(main)/settings/features/UpgradeAlert.tsx b/src/app/[variants]/(main)/settings/features/UpgradeAlert.tsx
index 62e5702f583..7ba34ef14cf 100644
--- a/src/app/[variants]/(main)/settings/features/UpgradeAlert.tsx
+++ b/src/app/[variants]/(main)/settings/features/UpgradeAlert.tsx
@@ -1,7 +1,6 @@
'use client';
import { Alert, Button, Flexbox } from '@lobehub/ui';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,16 +19,17 @@ const UpgradeAlert = memo(() => {
title={
<Flexbox gap={8}>
<p>{t('upgradeVersion.newVersion', { version: `v${latestVersion}` })}</p>
- <Link
+ <a
aria-label={t('upgradeVersion.action')}
href={MANUAL_UPGRADE_URL}
+ rel="noreferrer"
style={{ marginBottom: 6 }}
- target={'_blank'}
+ target="_blank"
>
<Button block size={'small'} type={'primary'}>
{t('upgradeVersion.action')}
</Button>
- </Link>
+ </a>
</Flexbox>
}
type={'info'}
diff --git a/src/app/[variants]/(main)/settings/provider/(list)/Footer.tsx b/src/app/[variants]/(main)/settings/provider/(list)/Footer.tsx
index 580e30853d7..9b5e65c76eb 100644
--- a/src/app/[variants]/(main)/settings/provider/(list)/Footer.tsx
+++ b/src/app/[variants]/(main)/settings/provider/(list)/Footer.tsx
@@ -2,7 +2,6 @@
import { Center } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -24,10 +23,11 @@ const Footer = memo(() => {
<Trans
components={[
<span key="0" />,
- <Link
+ <a
aria-label={t('llm.waitingForMoreLinkAriaLabel')}
href={MORE_MODEL_PROVIDER_REQUEST_URL}
key="1"
+ rel="noreferrer"
target="_blank"
/>,
]}
diff --git a/src/app/[variants]/(main)/settings/provider/detail/index.tsx b/src/app/[variants]/(main)/settings/provider/detail/index.tsx
index fc884e9c492..6f34ec9692b 100644
--- a/src/app/[variants]/(main)/settings/provider/detail/index.tsx
+++ b/src/app/[variants]/(main)/settings/provider/detail/index.tsx
@@ -1,4 +1,4 @@
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import Loading from '@/components/Loading/BrandTextLoading';
diff --git a/src/app/[variants]/(main)/settings/provider/detail/ollama/CheckError.tsx b/src/app/[variants]/(main)/settings/provider/detail/ollama/CheckError.tsx
index 7a4f02b8a65..43ea81742de 100644
--- a/src/app/[variants]/(main)/settings/provider/detail/ollama/CheckError.tsx
+++ b/src/app/[variants]/(main)/settings/provider/detail/ollama/CheckError.tsx
@@ -1,6 +1,6 @@
import { type ChatMessageError } from '@lobechat/types';
import { Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type ReactNode } from 'react';
import Container from './Container';
diff --git a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx
index 371f0a3b133..5b8eab82081 100644
--- a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx
+++ b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx
@@ -16,7 +16,6 @@ import { useDebounceFn } from 'ahooks';
import { Form as AntdForm, Switch } from 'antd';
import { createStaticStyles, cssVar, cx, responsive } from 'antd-style';
import { Loader2Icon, LockIcon } from 'lucide-react';
-import Link from 'next/link';
import { type ReactNode, memo, useCallback, useLayoutEffect, useRef } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -261,7 +260,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
<span key="0" />,
<span key="1" />,
<span key="2" />,
- <Link href={apiKeyUrl} key="3" target={'_blank'} />,
+ <a href={apiKeyUrl} key="3" rel="noreferrer" target="_blank" />,
]}
i18nKey="providerModels.config.apiKey.descWithUrl"
ns={'modelProvider'}
@@ -282,7 +281,13 @@ const ProviderConfig = memo<ProviderConfigProps>(
<Trans
components={[
<span key="0" />,
- <Link href={AES_GCM_URL} key="1" style={{ marginInline: 4 }} target={'_blank'} />,
+ <a
+ href={AES_GCM_URL}
+ key="1"
+ rel="noreferrer"
+ style={{ marginInline: 4 }}
+ target="_blank"
+ />,
]}
i18nKey="providerModels.config.aesGcm"
ns={'modelProvider'}
@@ -437,15 +442,16 @@ const ProviderConfig = memo<ProviderConfigProps>(
<>
{title ?? <ProviderCombine provider={id} size={24} />}
<Tooltip title={t('providerModels.config.helpDoc')}>
- <Link
+ <a
href={urlJoin(BASE_PROVIDER_DOC_URL, id)}
onClick={(e) => e.stopPropagation()}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
<Center className={styles.help} height={20} width={20}>
?
</Center>
- </Link>
+ </a>
</Tooltip>
</>
)}
diff --git a/src/app/[variants]/(main)/settings/security/index.tsx b/src/app/[variants]/(main)/settings/security/index.tsx
index 7d797d5cb22..ab5d5719e3d 100644
--- a/src/app/[variants]/(main)/settings/security/index.tsx
+++ b/src/app/[variants]/(main)/settings/security/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { useTranslation } from 'react-i18next';
import { Navigate } from 'react-router-dom';
diff --git a/src/app/[variants]/(main)/settings/stats/features/overview/ShareButton/ShareModal.tsx b/src/app/[variants]/(main)/settings/stats/features/overview/ShareButton/ShareModal.tsx
index b4a5cbf35b1..0b653e30ae8 100644
--- a/src/app/[variants]/(main)/settings/stats/features/overview/ShareButton/ShareModal.tsx
+++ b/src/app/[variants]/(main)/settings/stats/features/overview/ShareButton/ShareModal.tsx
@@ -3,7 +3,7 @@
import { type FormItemProps, FormModal, type FormModalProps, Segmented } from '@lobehub/ui';
import { Skeleton } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/settings/stats/features/rankings/AssistantsRank.tsx b/src/app/[variants]/(main)/settings/stats/features/rankings/AssistantsRank.tsx
index fd72818ac34..847d0644eda 100644
--- a/src/app/[variants]/(main)/settings/stats/features/rankings/AssistantsRank.tsx
+++ b/src/app/[variants]/(main)/settings/stats/features/rankings/AssistantsRank.tsx
@@ -1,7 +1,7 @@
import { BarList } from '@lobehub/charts';
import { ActionIcon, Avatar, Modal } from '@lobehub/ui';
import { MaximizeIcon } from 'lucide-react';
-import Link from 'next/link';
+import Link from '@/libs/router/Link';
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(main)/settings/stats/features/rankings/TopicsRank.tsx b/src/app/[variants]/(main)/settings/stats/features/rankings/TopicsRank.tsx
index e9600376f7d..9f5dfe46aef 100644
--- a/src/app/[variants]/(main)/settings/stats/features/rankings/TopicsRank.tsx
+++ b/src/app/[variants]/(main)/settings/stats/features/rankings/TopicsRank.tsx
@@ -2,7 +2,7 @@ import { BarList } from '@lobehub/charts';
import { ActionIcon, Icon, Modal } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { MaximizeIcon, MessageSquareIcon } from 'lucide-react';
-import Link from 'next/link';
+import Link from '@/libs/router/Link';
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(mobile)/_layout/index.tsx b/src/app/[variants]/(mobile)/_layout/index.tsx
index 808e9df9b6a..b08cd19926e 100644
--- a/src/app/[variants]/(mobile)/_layout/index.tsx
+++ b/src/app/[variants]/(mobile)/_layout/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type FC, Suspense } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
diff --git a/src/app/[variants]/(mobile)/chat/settings/features/AgentInfoDescription/index.tsx b/src/app/[variants]/(mobile)/chat/settings/features/AgentInfoDescription/index.tsx
index e1bc6ba6571..deec79416e7 100644
--- a/src/app/[variants]/(mobile)/chat/settings/features/AgentInfoDescription/index.tsx
+++ b/src/app/[variants]/(mobile)/chat/settings/features/AgentInfoDescription/index.tsx
@@ -3,7 +3,7 @@
import { ProDescriptions } from '@ant-design/pro-components';
import { type AgentItemDetail } from '@lobehub/market-sdk';
import { Flexbox, Tag } from '@lobehub/ui';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/app/[variants]/(mobile)/chat/settings/features/SettingButton.tsx b/src/app/[variants]/(mobile)/chat/settings/features/SettingButton.tsx
index 90457cd8763..e6061beaf60 100644
--- a/src/app/[variants]/(mobile)/chat/settings/features/SettingButton.tsx
+++ b/src/app/[variants]/(mobile)/chat/settings/features/SettingButton.tsx
@@ -2,12 +2,12 @@
import { ActionIcon } from '@lobehub/ui';
import { AlignJustify } from 'lucide-react';
-import dynamic from 'next/dynamic';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import dynamic from '@/libs/next/dynamic';
import { useSessionStore } from '@/store/session';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
diff --git a/src/app/[variants]/(mobile)/router/index.tsx b/src/app/[variants]/(mobile)/router/index.tsx
index a716ae17e22..0f6898898f0 100644
--- a/src/app/[variants]/(mobile)/router/index.tsx
+++ b/src/app/[variants]/(mobile)/router/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import Loading from '@/components/Loading/BrandTextLoading';
diff --git a/src/app/[variants]/page.tsx b/src/app/[variants]/page.tsx
index 03d109bc6d0..3f79bbe3a57 100644
--- a/src/app/[variants]/page.tsx
+++ b/src/app/[variants]/page.tsx
@@ -1,4 +1,4 @@
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import Loading from '@/components/Loading/BrandTextLoading';
import { type DynamicLayoutProps } from '@/types/next';
diff --git a/src/app/[variants]/router/index.tsx b/src/app/[variants]/router/index.tsx
index 769c15d6c3e..0c317f981b9 100644
--- a/src/app/[variants]/router/index.tsx
+++ b/src/app/[variants]/router/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import Loading from '@/components/Loading/BrandTextLoading';
diff --git a/src/components/404/index.tsx b/src/components/404/index.tsx
index 8edb1aeaf2f..0e948528821 100644
--- a/src/components/404/index.tsx
+++ b/src/components/404/index.tsx
@@ -1,7 +1,6 @@
'use client';
import { Button, Flexbox, FluentEmoji } from '@lobehub/ui';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -32,9 +31,10 @@ const NotFound = memo(() => {
<div>{t('notFound.desc')}</div>
<div style={{ marginTop: '0.5em' }}>{t('notFound.check')}</div>
</div>
- <Link href="/">
- <Button type={'primary'}>{t('notFound.backHome')}</Button>
- </Link>
+
+ <Button onClick={() => (window.location.href = '/')} type={'primary'}>
+ {t('notFound.backHome')}
+ </Button>
</Flexbox>
);
});
diff --git a/src/components/Analytics/index.tsx b/src/components/Analytics/index.tsx
index 9aee24d4802..a547ac88f4e 100644
--- a/src/components/Analytics/index.tsx
+++ b/src/components/Analytics/index.tsx
@@ -1,4 +1,4 @@
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { isDesktop } from '@/const/version';
import { analyticsEnv } from '@/envs/analytics';
diff --git a/src/components/BrandWatermark/index.tsx b/src/components/BrandWatermark/index.tsx
index e979c4231a9..e8336b57fa8 100644
--- a/src/components/BrandWatermark/index.tsx
+++ b/src/components/BrandWatermark/index.tsx
@@ -4,7 +4,6 @@ import { ORG_NAME, UTM_SOURCE } from '@lobechat/business-const';
import { Flexbox, type FlexboxProps } from '@lobehub/ui';
import { LobeHub } from '@lobehub/ui/brand';
import { createStaticStyles, cssVar } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { isCustomORG } from '@/const/version';
@@ -35,13 +34,14 @@ const BrandWatermark = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest })
{isCustomORG ? (
<span>{ORG_NAME}</span>
) : (
- <Link
+ <a
className={styles.logoLink}
href={`https://lobehub.com?utm_source=${UTM_SOURCE}&utm_content=brand_watermark`}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
<LobeHub size={20} type={'text'} />
- </Link>
+ </a>
)}
</Flexbox>
);
diff --git a/src/components/Branding/ProductLogo/Custom.tsx b/src/components/Branding/ProductLogo/Custom.tsx
index 174552516b2..7a9e4270f3c 100644
--- a/src/components/Branding/ProductLogo/Custom.tsx
+++ b/src/components/Branding/ProductLogo/Custom.tsx
@@ -3,7 +3,7 @@ import type { IconType } from '@lobehub/icons';
import { Flexbox, type FlexboxProps } from '@lobehub/ui';
import type { LobeChatProps } from '@lobehub/ui/brand';
import { createStaticStyles, cssVar } from 'antd-style';
-import Image, { type ImageProps } from 'next/image';
+import Image, { type ImageProps } from '@/libs/next/Image';
import { type ReactNode, forwardRef, memo } from 'react';
const styles = createStaticStyles(({ css }) => {
diff --git a/src/components/Error/index.tsx b/src/components/Error/index.tsx
index 3f3bb38fba2..ae5eb001c1b 100644
--- a/src/components/Error/index.tsx
+++ b/src/components/Error/index.tsx
@@ -1,7 +1,6 @@
'use client';
import { Button, Flexbox, FluentEmoji } from '@lobehub/ui';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -39,9 +38,9 @@ const ErrorCapture = memo<ErrorCaptureProps>(({ reset }) => {
<p style={{ marginBottom: '2em' }}>{t('error.desc')}</p>
<Flexbox gap={12} horizontal style={{ marginBottom: '1em' }}>
<Button onClick={() => reset()}>{t('error.retry')}</Button>
- <Link href="/">
- <Button type={'primary'}>{t('error.backHome')}</Button>
- </Link>
+ <Button onClick={() => (window.location.href = '/')} type={'primary'}>
+ {t('error.backHome')}
+ </Button>
</Flexbox>
</Flexbox>
);
diff --git a/src/components/GoBack/index.tsx b/src/components/GoBack/index.tsx
index d213d885546..b7d5d7ee060 100644
--- a/src/components/GoBack/index.tsx
+++ b/src/components/GoBack/index.tsx
@@ -1,9 +1,9 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { ArrowLeft } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
const styles = createStaticStyles(({ css }) => {
return {
@@ -31,7 +31,7 @@ const GoBack = memo<GoBackProps>(({ href }) => {
const { t } = useTranslation('components');
return (
- <Link href={href}>
+ <Link to={href}>
<Flexbox align={'center'} className={styles.container} gap={4} horizontal>
<Icon icon={ArrowLeft} />
<div>{t('GoBack.back')}</div>
diff --git a/src/components/LabsModal/LabCard.tsx b/src/components/LabsModal/LabCard.tsx
index 1c74da3df5a..a760492309d 100644
--- a/src/components/LabsModal/LabCard.tsx
+++ b/src/components/LabsModal/LabCard.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { Switch } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import { type PropsWithChildren, memo } from 'react';
import { SkeletonSwitch } from '@/components/Skeleton';
diff --git a/src/components/Link.tsx b/src/components/Link.tsx
index e373be28c2f..c055c942be7 100644
--- a/src/components/Link.tsx
+++ b/src/components/Link.tsx
@@ -1,12 +1,32 @@
-import NextLink, { type LinkProps as NextLinkProps } from 'next/link';
-import React, { memo } from 'react';
+import React, { type AnchorHTMLAttributes, memo } from 'react';
+import { Link as RouterLink } from 'react-router-dom';
-interface LinkProps extends NextLinkProps {
+interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
children?: React.ReactNode | undefined;
+ href?: string;
}
-const Link = memo<LinkProps>((props) => {
- return <NextLink {...props} prefetch={false} />;
+/**
+ * Smart Link component for global use.
+ * - External links (http://, https://) → native <a> tag
+ * - Internal routes → React Router Link
+ */
+const Link = memo<LinkProps>(({ href, children, ...props }) => {
+ // External links use native <a> tag
+ if (href?.startsWith('http://') || href?.startsWith('https://')) {
+ return (
+ <a href={href} rel="noreferrer" {...props}>
+ {children}
+ </a>
+ );
+ }
+
+ // Internal routes use React Router Link
+ return (
+ <RouterLink to={href || '/'} {...props}>
+ {children}
+ </RouterLink>
+ );
});
export default Link;
diff --git a/src/components/OllamaSetupGuide/index.tsx b/src/components/OllamaSetupGuide/index.tsx
index 55316fc66e9..06a49e1caf2 100644
--- a/src/components/OllamaSetupGuide/index.tsx
+++ b/src/components/OllamaSetupGuide/index.tsx
@@ -2,7 +2,6 @@ import { ProviderCombine } from '@lobehub/icons';
import { Flexbox, Highlighter, Snippet, Tabs } from '@lobehub/ui';
import { Steps } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
-import Link from 'next/link';
import { readableColor } from 'polished';
import React, { memo, useMemo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -48,7 +47,7 @@ const SetupGuide = memo(() => {
<Trans
components={[
<span key="0" />,
- <Link href={'https://ollama.com/download'} key="1" />,
+ <a href={'https://ollama.com/download'} key="1" rel="noreferrer" target="_blank" />,
]}
i18nKey={'OllamaSetupGuide.install.description'}
ns={'components'}
@@ -94,7 +93,7 @@ const SetupGuide = memo(() => {
<Trans
components={[
<span key="0" />,
- <Link href={'https://ollama.com/download'} key="1" />,
+ <a href={'https://ollama.com/download'} key="1" rel="noreferrer" target="_blank" />,
]}
i18nKey={'OllamaSetupGuide.install.description'}
ns={'components'}
@@ -139,9 +138,11 @@ const SetupGuide = memo(() => {
<Trans
components={[
<span key="0" />,
- <Link
+ <a
href={'https://github.com/ollama/ollama/blob/main/docs/linux.md'}
key="1"
+ rel="noreferrer"
+ target="_blank"
/>,
]}
i18nKey={'OllamaSetupGuide.install.linux.manual'}
diff --git a/src/components/WebFavicon/index.tsx b/src/components/WebFavicon/index.tsx
index e49a0be8767..ff30d4822a9 100644
--- a/src/components/WebFavicon/index.tsx
+++ b/src/components/WebFavicon/index.tsx
@@ -1,4 +1,4 @@
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
interface WebFaviconProps {
alt?: string;
diff --git a/src/components/client/ClientResponsiveContent/index.tsx b/src/components/client/ClientResponsiveContent/index.tsx
index f61ac480987..d89c40f18a6 100644
--- a/src/components/client/ClientResponsiveContent/index.tsx
+++ b/src/components/client/ClientResponsiveContent/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { type Loader } from 'next/dist/shared/lib/dynamic';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type FC, memo } from 'react';
import MobileSwitchLoading from '@/features/MobileSwitchLoading';
diff --git a/src/components/client/ClientResponsiveLayout.tsx b/src/components/client/ClientResponsiveLayout.tsx
index b92ba877cfa..e590fb1acc3 100644
--- a/src/components/client/ClientResponsiveLayout.tsx
+++ b/src/components/client/ClientResponsiveLayout.tsx
@@ -1,7 +1,7 @@
'use client';
import { type Loader } from 'next/dist/shared/lib/dynamic';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type FC, type PropsWithChildren, memo } from 'react';
import MobileSwitchLoading from '@/features/MobileSwitchLoading';
diff --git a/src/components/mdx/Image.tsx b/src/components/mdx/Image.tsx
index 03a7cf24521..9c803731377 100644
--- a/src/components/mdx/Image.tsx
+++ b/src/components/mdx/Image.tsx
@@ -1,7 +1,7 @@
'use server';
import { Image } from '@lobehub/ui/mdx';
-import Img from 'next/image';
+import Img from '@/libs/next/Image';
import { getPlaiceholder } from 'plaiceholder';
import { type FC } from 'react';
diff --git a/src/components/mdx/Link.tsx b/src/components/mdx/Link.tsx
index 47b5be2d02b..25c939f01d5 100644
--- a/src/components/mdx/Link.tsx
+++ b/src/components/mdx/Link.tsx
@@ -1,20 +1,37 @@
'use client';
-import Link, { type LinkProps } from 'next/link';
-import { type FC } from 'react';
+import { type AnchorHTMLAttributes, type FC } from 'react';
+import { Link } from 'react-router-dom';
const EXTERNAL_HREF_REGEX = /https?:\/\//;
-const A: FC<LinkProps> = ({ href = '', ...props }) => {
+interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
+ href?: string;
+}
+
+const A: FC<LinkProps> = ({ href = '', children, ...props }) => {
const isOutbound = EXTERNAL_HREF_REGEX.test(href as string);
const isOfficial = String(href).includes('lobechat') || String(href).includes('lobehub');
+
+ // External links use native <a> tag
+ if (isOutbound) {
+ return (
+ <a
+ href={href}
+ rel={isOfficial ? 'noreferrer' : 'nofollow noreferrer'}
+ target="_blank"
+ {...props}
+ >
+ {children}
+ </a>
+ );
+ }
+
+ // Internal links use React Router
return (
- <Link
- href={href}
- rel={isOutbound && !isOfficial ? 'nofollow' : undefined}
- target={isOutbound ? '_blank' : undefined}
- {...props}
- />
+ <Link to={href} {...props}>
+ {children}
+ </Link>
);
};
diff --git a/src/features/AlertBanner/CloudBanner.tsx b/src/features/AlertBanner/CloudBanner.tsx
index 0242c2383b8..64c3f4915bd 100644
--- a/src/features/AlertBanner/CloudBanner.tsx
+++ b/src/features/AlertBanner/CloudBanner.tsx
@@ -5,7 +5,6 @@ import { Button, Center, Flexbox, Icon, lobeStaticStylish } from '@lobehub/ui';
import { useSize } from 'ahooks';
import { createStaticStyles, cx } from 'antd-style';
import { ArrowRightIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo, useEffect, useRef, useState } from 'react';
import Marquee from 'react-fast-marquee';
import { useTranslation } from 'react-i18next';
@@ -83,11 +82,11 @@ const CloudBanner = memo<{ mobile?: boolean }>(({ mobile }) => {
<div className={styles.background} />
<Center className={styles.wrapper} gap={16} horizontal width={'100%'}>
{isTruncated ? <Marquee pauseOnHover>{content}</Marquee> : content}
- <Link href={`${OFFICIAL_URL}?utm_source=${UTM_SOURCE}&utm_medium=banner`} target={'_blank'}>
+ <a href={`${OFFICIAL_URL}?utm_source=${UTM_SOURCE}&utm_medium=banner`} rel="noreferrer" target="_blank">
<Button size={'small'} type="primary">
{t('alert.cloud.action')} <Icon icon={ArrowRightIcon} />
</Button>
- </Link>
+ </a>
</Center>
</Center>
);
diff --git a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
index 79a8f50eb85..2d4fd7e655e 100644
--- a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
@@ -2,7 +2,6 @@ import { Form } from '@lobehub/ui';
import type { FormItemProps } from '@lobehub/ui';
import { Form as AntdForm, Grid, Switch } from 'antd';
import isEqual from 'fast-deep-equal';
-import Link from 'next/link';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -62,12 +61,13 @@ const ControlsForm = memo(() => {
<span style={isNarrow ? descNarrow : descWide}>
<Trans i18nKey={'extendParams.disableContextCaching.desc'} ns={'chat'}>
单条对话生成成本最高可降低 90%,响应速度提升 4 倍(
- <Link
+ <a
href={'https://www.anthropic.com/news/prompt-caching?utm_source=lobechat'}
- rel={'nofollow'}
+ rel="noreferrer nofollow"
+ target="_blank"
>
了解更多
- </Link>
+ </a>
)。开启后将自动禁用历史记录限制
</Trans>
</span>
@@ -83,14 +83,15 @@ const ControlsForm = memo(() => {
<span style={isNarrow ? descNarrow : descWide}>
<Trans i18nKey={'extendParams.enableReasoning.desc'} ns={'chat'}>
基于 Claude Thinking 机制限制(
- <Link
+ <a
href={
'https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking?utm_source=lobechat#why-thinking-blocks-must-be-preserved'
}
- rel={'nofollow'}
+ rel="noreferrer nofollow"
+ target="_blank"
>
了解更多
- </Link>
+ </a>
),开启后将自动禁用历史消息数限制
</Trans>
</span>
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index 0aadb6ce2ed..cd452b18209 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -306,9 +306,7 @@ const Controls = memo<ControlsProps>(({ setUpdating }) => {
...(enableMaxTokens
? [
{
- children: (
- <SliderWithInput max={32_000} min={0} step={100} unlimitedInput />
- ),
+ children: <SliderWithInput max={32_000} min={0} step={100} unlimitedInput />,
label: (
<Flexbox align={'center'} className={styles.label} gap={8} horizontal>
{t('settingModel.maxTokens.title')}
diff --git a/src/features/ChatInput/ActionBar/Token/index.tsx b/src/features/ChatInput/ActionBar/Token/index.tsx
index 1ce16aaf23c..5a1c2a3ecfe 100644
--- a/src/features/ChatInput/ActionBar/Token/index.tsx
+++ b/src/features/ChatInput/ActionBar/Token/index.tsx
@@ -1,4 +1,4 @@
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type PropsWithChildren, memo } from 'react';
import { useModelHasContextWindowToken } from '@/hooks/useModelHasContextWindowToken';
diff --git a/src/features/ChatInput/Mobile/index.tsx b/src/features/ChatInput/Mobile/index.tsx
index 99e15c41357..46846bdf751 100644
--- a/src/features/ChatInput/Mobile/index.tsx
+++ b/src/features/ChatInput/Mobile/index.tsx
@@ -3,7 +3,7 @@
import { ChatInput, ChatInputActionBar } from '@lobehub/editor/react';
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo } from 'react';
import { useChatInputStore } from '@/features/ChatInput/store';
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
index c10e3d2caa0..c30bc731a68 100644
--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
@@ -1,6 +1,6 @@
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type ReactNode, Suspense, memo, useCallback } from 'react';
import { useConversationStore } from '@/features/Conversation/store';
diff --git a/src/features/Conversation/Error/OllamaBizError/index.tsx b/src/features/Conversation/Error/OllamaBizError/index.tsx
index 708670b7a55..d1983b3661f 100644
--- a/src/features/Conversation/Error/OllamaBizError/index.tsx
+++ b/src/features/Conversation/Error/OllamaBizError/index.tsx
@@ -1,6 +1,6 @@
import { type ChatMessageError } from '@lobechat/types';
import { type AlertProps, Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo } from 'react';
import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
diff --git a/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx b/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx
index 3c638a6dc14..9164d9809e4 100644
--- a/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx
+++ b/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx
@@ -1,6 +1,5 @@
import { Ollama } from '@lobehub/icons';
import { Button } from '@lobehub/ui';
-import Link from 'next/link';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -29,7 +28,7 @@ const OllamaDesktopSetupGuide = memo<{ id?: string }>(({ id }) => {
avatar={<Ollama.Avatar shape={'square'} size={40} />}
desc={
<Trans
- components={[<span key="0" />, <Link href={'https://ollama.com/download'} key="1" />]}
+ components={[<span key="0" />, <a href={'https://ollama.com/download'} key="1" rel="noreferrer" target="_blank" />]}
i18nKey={'OllamaSetupGuide.install.description'}
ns={'components'}
/>
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index 3d5c9598cc9..07792d21619 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -3,7 +3,7 @@ import { AgentRuntimeErrorType, type ILobeAgentRuntimeErrorType } from '@lobecha
import { ChatErrorType, type ChatMessageError, type ErrorType } from '@lobechat/types';
import { type IPluginErrorType } from '@lobehub/chat-plugin-sdk';
import { type AlertProps, Block, Highlighter, Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/Settings.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/Settings.tsx
index e0634199a6d..5da7a72d56f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/Settings.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Actions/Settings.tsx
@@ -1,6 +1,6 @@
import { ActionIcon, createRawModal } from '@lobehub/ui';
import { LucideSettings } from 'lucide-react';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index fc20e697dba..f744e693da0 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -2,9 +2,9 @@ import { LOADING_FLAT } from '@lobechat/const';
import { type ChatToolResult, type ToolIntervention } from '@lobechat/types';
import { AccordionItem, Flexbox, Skeleton } from '@lobehub/ui';
import { Divider } from 'antd';
-import dynamic from 'next/dynamic';
import { memo, useEffect, useState } from 'react';
+import dynamic from '@/libs/next/dynamic';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { useToolStore } from '@/store/tool';
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 4f7bd3b44f8..ee8efb08bf8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -2,7 +2,7 @@
import type { AssistantContentBlock } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { type MouseEventHandler, Suspense, memo, useCallback, useMemo } from 'react';
import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
diff --git a/src/features/Conversation/Messages/Tool/Tool/index.tsx b/src/features/Conversation/Messages/Tool/Tool/index.tsx
index 5adf8d9c163..0c1c6595d7c 100644
--- a/src/features/Conversation/Messages/Tool/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Tool/Tool/index.tsx
@@ -1,8 +1,8 @@
import { Accordion, AccordionItem, Flexbox, Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
import { type CSSProperties, memo, useState } from 'react';
import Actions from '@/features/Conversation/Messages/AssistantGroup/Tool/Actions';
+import dynamic from '@/libs/next/dynamic';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';
import Inspectors from '../../AssistantGroup/Tool/Inspector';
diff --git a/src/features/Conversation/Messages/components/SearchGrounding.tsx b/src/features/Conversation/Messages/components/SearchGrounding.tsx
index cb420f736cd..dcdb773b44f 100644
--- a/src/features/Conversation/Messages/components/SearchGrounding.tsx
+++ b/src/features/Conversation/Messages/components/SearchGrounding.tsx
@@ -2,7 +2,7 @@ import { Flexbox, Icon, SearchResultCards, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ChevronDown, ChevronRight, Globe } from 'lucide-react';
import { AnimatePresence, m as motion } from 'motion/react';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/DataImporter/Error.tsx b/src/features/DataImporter/Error.tsx
index f98318e969c..ad6c68579d4 100644
--- a/src/features/DataImporter/Error.tsx
+++ b/src/features/DataImporter/Error.tsx
@@ -1,7 +1,6 @@
import { Alert, Button, Flexbox, Highlighter, Icon } from '@lobehub/ui';
import { Result } from 'antd';
import { ShieldAlert } from 'lucide-react';
-import Link from 'next/link';
import React, { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import Balancer from 'react-wrap-balancer';
@@ -41,17 +40,18 @@ const Error = memo<ErrorProps>(({ error, onClick }) => {
<Balancer>
<Trans i18nKey="importModal.error.desc" ns={'common'}>
非常抱歉,数据库升级过程发生异常。请重试升级,或
- <Link
+ <a
aria-label={'issue'}
href={GITHUB_ISSUES}
onClick={(e) => {
e.preventDefault();
githubService.submitImportError(error!);
}}
+ rel="noreferrer"
target="_blank"
>
提交问题
- </Link>
+ </a>
我们将会第一时间帮你排查问题。
</Trans>
</Balancer>
diff --git a/src/features/DevPanel/CacheViewer/cacheProvider.tsx b/src/features/DevPanel/CacheViewer/cacheProvider.tsx
index f077fb25a14..0b33f362963 100644
--- a/src/features/DevPanel/CacheViewer/cacheProvider.tsx
+++ b/src/features/DevPanel/CacheViewer/cacheProvider.tsx
@@ -1,6 +1,5 @@
'use client';
-import { usePathname } from 'next/navigation';
import {
type PropsWithChildren,
createContext,
@@ -10,6 +9,8 @@ import {
useTransition,
} from 'react';
+import { usePathname } from '@/libs/router/navigation';
+
import { getCacheFiles } from './getCacheEntries';
import type { NextCacheFileData } from './schema';
diff --git a/src/features/DevPanel/MetadataViewer/Og.tsx b/src/features/DevPanel/MetadataViewer/Og.tsx
index ec731979a37..13e36d8280b 100644
--- a/src/features/DevPanel/MetadataViewer/Og.tsx
+++ b/src/features/DevPanel/MetadataViewer/Og.tsx
@@ -1,5 +1,5 @@
import { Flexbox, Form, Input, TextArea } from '@lobehub/ui';
-import Image from 'next/image';
+import Image from '@/libs/next/Image';
import { memo } from 'react';
import { useHead } from './useHead';
diff --git a/src/features/DevPanel/features/FloatPanel.tsx b/src/features/DevPanel/features/FloatPanel.tsx
index 7472a65be6e..69e1d4f3f15 100644
--- a/src/features/DevPanel/features/FloatPanel.tsx
+++ b/src/features/DevPanel/features/FloatPanel.tsx
@@ -5,11 +5,11 @@ import { ActionIcon, Flexbox, FluentEmoji, Icon, SideNav } from '@lobehub/ui';
import { FloatButton } from 'antd';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { BugIcon, BugOff, XIcon } from 'lucide-react';
-import { usePathname } from 'next/navigation';
import { type ReactNode, memo, useEffect, useState } from 'react';
import { Rnd } from 'react-rnd';
import { isDesktop } from '@/const/version';
+import { usePathname } from '@/libs/next/navigation';
// 定义样式
const styles = createStaticStyles(({ css }) => {
diff --git a/src/features/DevPanel/features/Table/TooltipContent.tsx b/src/features/DevPanel/features/Table/TooltipContent.tsx
index 585964ba54d..5ddba351ae2 100644
--- a/src/features/DevPanel/features/Table/TooltipContent.tsx
+++ b/src/features/DevPanel/features/Table/TooltipContent.tsx
@@ -1,6 +1,5 @@
import { Flexbox, Highlighter } from '@lobehub/ui';
-import Image from 'next/image';
-import Link from 'next/link';
+import Image from '@/libs/next/Image';
import { type ReactNode, memo } from 'react';
const TooltipContent = memo<{ children: ReactNode }>(({ children }) => {
@@ -19,9 +18,9 @@ const TooltipContent = memo<{ children: ReactNode }>(({ children }) => {
if (children.startsWith('http'))
return (
- <Link href={children} target={'_blank'}>
+ <a href={children} rel="noreferrer" target="_blank">
{children}
- </Link>
+ </a>
);
const code = children.trim().trimEnd();
diff --git a/src/features/DevPanel/index.tsx b/src/features/DevPanel/index.tsx
index cd4b5a2361e..3a043faa2f6 100644
--- a/src/features/DevPanel/index.tsx
+++ b/src/features/DevPanel/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { BookText, Cog, FlagIcon, GlobeLockIcon } from 'lucide-react';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import CacheViewer from './CacheViewer';
import FeatureFlagViewer from './FeatureFlagViewer';
diff --git a/src/features/EditorCanvas/InlineToolbar.tsx b/src/features/EditorCanvas/InlineToolbar.tsx
index 2a366a571bd..ebcb909bb32 100644
--- a/src/features/EditorCanvas/InlineToolbar.tsx
+++ b/src/features/EditorCanvas/InlineToolbar.tsx
@@ -1,11 +1,6 @@
'use client';
-import {
- HotkeyEnum,
- INSERT_HEADING_COMMAND,
- getHotkeyById,
- type IEditor,
-} from '@lobehub/editor';
+import { HotkeyEnum, type IEditor, INSERT_HEADING_COMMAND, getHotkeyById } from '@lobehub/editor';
import {
ChatInputActions,
type ChatInputActionsProps,
diff --git a/src/features/FileViewer/NotSupport/index.tsx b/src/features/FileViewer/NotSupport/index.tsx
index 6887216d161..1a660f5a6e4 100644
--- a/src/features/FileViewer/NotSupport/index.tsx
+++ b/src/features/FileViewer/NotSupport/index.tsx
@@ -1,6 +1,5 @@
import { Button, Center, Flexbox, FluentEmoji } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import Link from 'next/link';
import { type CSSProperties, type ComponentType, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -37,9 +36,9 @@ const NotSupport: ComponentType<NotSupportProps> = ({ fileName, url, style }) =>
<Flexbox style={{ textAlign: 'center' }}>
<Trans i18nKey="preview.unsupportedFileAndContact" ns={'file'}>
此文件格式暂不支持在线预览,如有预览诉求,欢迎
- <Link aria-label={'todo'} href={MORE_FILE_PREVIEW_REQUEST_URL} target="_blank">
+ <a aria-label={'todo'} href={MORE_FILE_PREVIEW_REQUEST_URL} rel="noreferrer" target="_blank">
反馈给我们
- </Link>
+ </a>
</Trans>
</Flexbox>
{url && (
diff --git a/src/features/Follow/index.tsx b/src/features/Follow/index.tsx
index cc46be7d558..167810c4897 100644
--- a/src/features/Follow/index.tsx
+++ b/src/features/Follow/index.tsx
@@ -4,7 +4,6 @@ import { SiDiscord, SiGithub, SiMedium, SiX } from '@icons-pack/react-simple-ico
import { SOCIAL_URL } from '@lobechat/business-const';
import { ActionIcon, Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,30 +29,30 @@ const Follow = memo(() => {
const { t } = useTranslation('common');
return (
<Flexbox gap={8} horizontal>
- <Link href={GITHUB} rel="noreferrer" target={'_blank'}>
+ <a href={GITHUB} rel="noreferrer" target="_blank">
<ActionIcon
className={styles.icon}
icon={SiGithub as any}
title={t('follow', { name: 'GitHub' })}
/>
- </Link>
- <Link href={SOCIAL_URL.x} rel="noreferrer" target={'_blank'}>
+ </a>
+ <a href={SOCIAL_URL.x} rel="noreferrer" target="_blank">
<ActionIcon className={styles.icon} icon={SiX as any} title={t('follow', { name: 'X' })} />
- </Link>
- <Link href={SOCIAL_URL.discord} rel="noreferrer" target={'_blank'}>
+ </a>
+ <a href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">
<ActionIcon
className={styles.icon}
icon={SiDiscord as any}
title={t('follow', { name: 'Discord' })}
/>
- </Link>
- <Link href={SOCIAL_URL.medium} rel="noreferrer" target={'_blank'}>
+ </a>
+ <a href={SOCIAL_URL.medium} rel="noreferrer" target="_blank">
<ActionIcon
className={styles.icon}
icon={SiMedium as any}
title={t('follow', { name: 'Medium' })}
/>
- </Link>
+ </a>
</Flexbox>
);
});
diff --git a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx b/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx
index c7bde3bd612..ef245b755e0 100644
--- a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx
+++ b/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx
@@ -1,8 +1,8 @@
import { Block, Button, Flexbox, Form, MaterialFileTypeIcon, Select } from '@lobehub/ui';
import { App } from 'antd';
-import Link from 'next/link';
import { memo, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
import RepoIcon from '@/components/LibIcon';
import { useKnowledgeBaseStore } from '@/store/library';
@@ -34,7 +34,7 @@ const SelectForm = memo<CreateFormProps>(({ onClose, knowledgeBaseId, fileIds })
<Trans
components={[
<span key="0" />,
- <Link href={`/knowledge/library/${values.id}`} key="1" />,
+ <Link key="1" to={`/knowledge/library/${values.id}`} />,
]}
i18nKey={'addToKnowledgeBase.addSuccess'}
ns={'knowledgeBase'}
diff --git a/src/features/MCP/Scores.tsx b/src/features/MCP/Scores.tsx
index 1ba3bcd8e8f..cddd40fb386 100644
--- a/src/features/MCP/Scores.tsx
+++ b/src/features/MCP/Scores.tsx
@@ -3,7 +3,7 @@
import { Center, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { CircleDashedIcon, HammerIcon, LayersIcon, MessageSquareQuoteIcon } from 'lucide-react';
-import Link from 'next/link';
+import { Link } from '@/libs/router';
import qs from 'query-string';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/MCPPluginDetail/Nav.tsx b/src/features/MCPPluginDetail/Nav.tsx
index 5f2ebf44087..253de8cfbe8 100644
--- a/src/features/MCPPluginDetail/Nav.tsx
+++ b/src/features/MCPPluginDetail/Nav.tsx
@@ -12,7 +12,6 @@ import {
PackageCheckIcon,
SettingsIcon,
} from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -178,21 +177,22 @@ const Nav = memo<NavProps>(
{nav}
{!inModal && (
<Flexbox gap={12} horizontal>
- <Link className={styles.link} href={SOCIAL_URL.discord} target={'_blank'}>
+ <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">
{t('mcp.details.nav.needHelp')}
- </Link>
+ </a>
{github?.url && (
<>
- <Link className={styles.link} href={github.url} target={'_blank'}>
+ <a className={styles.link} href={github.url} rel="noreferrer" target="_blank">
{t('mcp.details.nav.viewSourceCode')}
- </Link>
- <Link
+ </a>
+ <a
className={styles.link}
href={urlJoin(github.url, 'issues')}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
{t('mcp.details.nav.reportIssue')}
- </Link>
+ </a>
</>
)}
</Flexbox>
diff --git a/src/features/MCPPluginDetail/Overview/TagList.tsx b/src/features/MCPPluginDetail/Overview/TagList.tsx
index 619f676ff85..a859d0d7b7d 100644
--- a/src/features/MCPPluginDetail/Overview/TagList.tsx
+++ b/src/features/MCPPluginDetail/Overview/TagList.tsx
@@ -2,7 +2,7 @@
import { Flexbox, Tag } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import Link from 'next/link';
+import { Link } from '@/libs/router';
import qs from 'query-string';
import { memo } from 'react';
diff --git a/src/features/MobileTabBar/index.tsx b/src/features/MobileTabBar/index.tsx
index bd12ddc9101..5a9041395d3 100644
--- a/src/features/MobileTabBar/index.tsx
+++ b/src/features/MobileTabBar/index.tsx
@@ -2,10 +2,11 @@ import { Icon } from '@lobehub/ui';
import { TabBar, type TabBarProps } from '@lobehub/ui/mobile';
import { createStaticStyles, cssVar } from 'antd-style';
import { Bot, MessageSquare, User } from 'lucide-react';
-import { useRouter } from 'next/navigation';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useRouter } from '@/libs/router/navigation';
+
import { SidebarTabKey } from '@/store/global/initialState';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
diff --git a/src/features/OllamaSetupGuide/Desktop.tsx b/src/features/OllamaSetupGuide/Desktop.tsx
index a743837d366..4aa6de3d212 100644
--- a/src/features/OllamaSetupGuide/Desktop.tsx
+++ b/src/features/OllamaSetupGuide/Desktop.tsx
@@ -1,7 +1,6 @@
import { Ollama } from '@lobehub/icons';
import { Center } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import Link from 'next/link';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -17,7 +16,7 @@ const OllamaDesktopSetupGuide = memo(() => {
description={
<span>
<Trans
- components={[<span key="0" />, <Link href={'https://ollama.com/download'} key="1" />]}
+ components={[<span key="0" />, <a href={'https://ollama.com/download'} key="1" rel="noreferrer" target="_blank" />]}
i18nKey={'OllamaSetupGuide.install.description'}
ns={'components'}
/>
diff --git a/src/features/PWAInstall/Install.tsx b/src/features/PWAInstall/Install.tsx
index 3837617e3da..9db7c6f10d5 100644
--- a/src/features/PWAInstall/Install.tsx
+++ b/src/features/PWAInstall/Install.tsx
@@ -1,7 +1,7 @@
'use client';
import { BRANDING_NAME } from '@lobechat/business-const';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useEffect, useLayoutEffect } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/PWAInstall/index.tsx b/src/features/PWAInstall/index.tsx
index 4b905c61270..326f38a7be9 100644
--- a/src/features/PWAInstall/index.tsx
+++ b/src/features/PWAInstall/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { pwaInstallHandler } from 'pwa-install-handler';
import { memo, useEffect, useState } from 'react';
diff --git a/src/features/PluginStore/McpList/index.tsx b/src/features/PluginStore/McpList/index.tsx
index 7efdc618604..08b97f4d9d8 100644
--- a/src/features/PluginStore/McpList/index.tsx
+++ b/src/features/PluginStore/McpList/index.tsx
@@ -1,6 +1,6 @@
import { DraggablePanel, Flexbox } from '@lobehub/ui';
import { cssVar, useTheme } from 'antd-style';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo, useRef } from 'react';
import { useServerConfigStore } from '@/store/serverConfig';
diff --git a/src/features/PluginStore/PluginList/Detail/Header.tsx b/src/features/PluginStore/PluginList/Detail/Header.tsx
index 554d7d172e0..8b0de30249d 100644
--- a/src/features/PluginStore/PluginList/Detail/Header.tsx
+++ b/src/features/PluginStore/PluginList/Detail/Header.tsx
@@ -4,7 +4,6 @@ import { Github } from '@lobehub/icons';
import { ActionIcon, Avatar, Collapse, Flexbox, Icon, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar, useResponsive } from 'antd-style';
import { DotIcon } from 'lucide-react';
-import Link from 'next/link';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
@@ -77,16 +76,17 @@ const Header = memo<{ inModal?: boolean; mobile?: boolean }>(({ mobile: isMobile
</Flexbox>
{identifier && (
<Flexbox align={'center'} gap={6} horizontal>
- <Link
+ <a
href={urlJoin(
'https://github.com/lobehub/lobe-chat-agents/tree/main/locales',
identifier,
)}
onClick={(e) => e.stopPropagation()}
- target={'_blank'}
+ rel="noreferrer"
+ target="_blank"
>
<ActionIcon fill={cssVar.colorTextDescription} icon={Github} />
- </Link>
+ </a>
</Flexbox>
)}
</Flexbox>
@@ -94,9 +94,9 @@ const Header = memo<{ inModal?: boolean; mobile?: boolean }>(({ mobile: isMobile
<Flexbox>
<Flexbox align={'center'} gap={4} horizontal>
{author && (
- <Link href={urlJoin('https://github.com', author)} target={'_blank'}>
+ <a href={urlJoin('https://github.com', author)} rel="noreferrer" target="_blank">
{author}
- </Link>
+ </a>
)}
<Icon icon={DotIcon} />
<PublishedTime
diff --git a/src/features/PluginsUI/Render/DefaultType/index.tsx b/src/features/PluginsUI/Render/DefaultType/index.tsx
index 3ec9ac52c21..000810fecd8 100644
--- a/src/features/PluginsUI/Render/DefaultType/index.tsx
+++ b/src/features/PluginsUI/Render/DefaultType/index.tsx
@@ -1,5 +1,5 @@
import { Skeleton } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { Suspense, memo } from 'react';
import { useToolStore } from '@/store/tool';
diff --git a/src/features/Portal/Artifacts/Body/Renderer/index.tsx b/src/features/Portal/Artifacts/Body/Renderer/index.tsx
index ed292c08f66..6b830e27fe9 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/index.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/index.tsx
@@ -1,5 +1,5 @@
import { Markdown, Mermaid } from '@lobehub/ui';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo } from 'react';
import HTMLRenderer from './HTML';
diff --git a/src/features/ResourceManager/components/ChunkDrawer/index.tsx b/src/features/ResourceManager/components/ChunkDrawer/index.tsx
index ab2be7d0a08..4707d6744a9 100644
--- a/src/features/ResourceManager/components/ChunkDrawer/index.tsx
+++ b/src/features/ResourceManager/components/ChunkDrawer/index.tsx
@@ -1,7 +1,7 @@
import { Flexbox } from '@lobehub/ui';
import { Drawer } from 'antd';
import { cssVar } from 'antd-style';
-import dynamic from 'next/dynamic';
+import dynamic from '@/libs/next/dynamic';
import { memo } from 'react';
import { fileManagerSelectors, useFileStore } from '@/store/file';
diff --git a/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx b/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx
index 4da041bda54..204f5fdbe19 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx
@@ -34,33 +34,33 @@ const ListViewSkeleton = ({
opacity: getOpacity(index),
}}
>
- <Center height={40} style={{ paddingInline: 4 }}>
- <Checkbox disabled />
- </Center>
- <Flexbox
- align={'center'}
- horizontal
- style={{
- flexShrink: 0,
- maxWidth: columnWidths.name,
- minWidth: columnWidths.name,
- paddingInline: 8,
- width: columnWidths.name,
- }}
- >
- <Skeleton.Avatar active shape={'square'} size={24} style={{ marginInline: 8 }} />
- <Skeleton.Button active style={{ height: 16, width: '60%' }} />
- </Flexbox>
- <Flexbox style={{ flexShrink: 0, paddingInline: '0 24px' }} width={columnWidths.date}>
- <Skeleton.Button active style={{ height: 16, width: '80%' }} />
- </Flexbox>
- <Flexbox style={{ flexShrink: 0, paddingInline: '0 24px' }} width={columnWidths.size}>
- <Skeleton.Button active style={{ height: 16, width: '60%' }} />
+ <Center height={40} style={{ paddingInline: 4 }}>
+ <Checkbox disabled />
+ </Center>
+ <Flexbox
+ align={'center'}
+ horizontal
+ style={{
+ flexShrink: 0,
+ maxWidth: columnWidths.name,
+ minWidth: columnWidths.name,
+ paddingInline: 8,
+ width: columnWidths.name,
+ }}
+ >
+ <Skeleton.Avatar active shape={'square'} size={24} style={{ marginInline: 8 }} />
+ <Skeleton.Button active style={{ height: 16, width: '60%' }} />
+ </Flexbox>
+ <Flexbox style={{ flexShrink: 0, paddingInline: '0 24px' }} width={columnWidths.date}>
+ <Skeleton.Button active style={{ height: 16, width: '80%' }} />
+ </Flexbox>
+ <Flexbox style={{ flexShrink: 0, paddingInline: '0 24px' }} width={columnWidths.size}>
+ <Skeleton.Button active style={{ height: 16, width: '60%' }} />
+ </Flexbox>
</Flexbox>
- </Flexbox>
- ))}
- </Flexbox>
-);
+ ))}
+ </Flexbox>
+ );
};
export default ListViewSkeleton;
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
index dcad1dd855a..beadc9c2178 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
@@ -29,168 +29,166 @@ interface BatchActionsDropdownProps {
selectCount: number;
}
-const BatchActionsDropdown = memo<BatchActionsDropdownProps>(
- ({ selectCount, onActionClick }) => {
- const { t } = useTranslation(['components', 'common', 'file', 'knowledgeBase']);
- const { modal, message } = App.useApp();
-
- const [libraryId, selectedFileIds] = useResourceManagerStore((s) => [
- s.libraryId,
- s.selectedFileIds,
- ]);
- const [useFetchKnowledgeBaseList, addFilesToKnowledgeBase] = useKnowledgeBaseStore((s) => [
- s.useFetchKnowledgeBaseList,
- s.addFilesToKnowledgeBase,
- ]);
- const { data: knowledgeBases } = useFetchKnowledgeBaseList();
-
- const menuItems = useMemo<DropdownItem[]>(() => {
- const items: DropdownItem[] = [];
-
- // Show delete library option only when in a knowledge base and no files selected
- if (libraryId && selectCount === 0) {
- items.push({
- danger: true,
- icon: <Icon icon={Trash2Icon} />,
- key: 'deleteLibrary',
- label: t('header.actions.deleteLibrary', { ns: 'file' }),
- onClick: async () => {
- modal.confirm({
- okButtonProps: {
- danger: true,
- },
- onOk: async () => {
- await onActionClick('deleteLibrary');
- },
- title: t('library.list.confirmRemoveLibrary', { ns: 'file' }),
- });
- },
- });
- return items;
- }
-
- // Filter out current knowledge base and create submenu items
- const availableKnowledgeBases = (knowledgeBases || []).filter((kb) => kb.id !== libraryId);
-
- const addToKnowledgeBaseSubmenu: DropdownItem[] = availableKnowledgeBases.map((kb) => ({
- disabled: selectCount === 0,
- icon: <RepoIcon />,
- key: `add-to-kb-${kb.id}`,
- label: <span style={{ marginLeft: 8 }}>{kb.name}</span>,
+const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onActionClick }) => {
+ const { t } = useTranslation(['components', 'common', 'file', 'knowledgeBase']);
+ const { modal, message } = App.useApp();
+
+ const [libraryId, selectedFileIds] = useResourceManagerStore((s) => [
+ s.libraryId,
+ s.selectedFileIds,
+ ]);
+ const [useFetchKnowledgeBaseList, addFilesToKnowledgeBase] = useKnowledgeBaseStore((s) => [
+ s.useFetchKnowledgeBaseList,
+ s.addFilesToKnowledgeBase,
+ ]);
+ const { data: knowledgeBases } = useFetchKnowledgeBaseList();
+
+ const menuItems = useMemo<DropdownItem[]>(() => {
+ const items: DropdownItem[] = [];
+
+ // Show delete library option only when in a knowledge base and no files selected
+ if (libraryId && selectCount === 0) {
+ items.push({
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'deleteLibrary',
+ label: t('header.actions.deleteLibrary', { ns: 'file' }),
onClick: async () => {
- try {
- await addFilesToKnowledgeBase(kb.id, selectedFileIds);
- message.success(
- t('addToKnowledgeBase.addSuccess', {
- count: selectCount,
- ns: 'knowledgeBase',
- }),
- );
- } catch (e) {
- console.error(e);
- message.error(t('addToKnowledgeBase.error', { ns: 'knowledgeBase' }));
- }
+ modal.confirm({
+ okButtonProps: {
+ danger: true,
+ },
+ onOk: async () => {
+ await onActionClick('deleteLibrary');
+ },
+ title: t('library.list.confirmRemoveLibrary', { ns: 'file' }),
+ });
},
- }));
-
- if (libraryId) {
- items.push({
- disabled: selectCount === 0,
- icon: <Icon icon={BookMinusIcon} />,
- key: 'removeFromKnowledgeBase',
- label: t('FileManager.actions.removeFromKnowledgeBase'),
- onClick: () => {
- modal.confirm({
- okButtonProps: {
- danger: true,
- },
- onOk: async () => {
- await onActionClick('removeFromKnowledgeBase');
- message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
- },
- title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
- count: selectCount,
- }),
- });
- },
- });
+ });
+ return items;
+ }
+
+ // Filter out current knowledge base and create submenu items
+ const availableKnowledgeBases = (knowledgeBases || []).filter((kb) => kb.id !== libraryId);
+
+ const addToKnowledgeBaseSubmenu: DropdownItem[] = availableKnowledgeBases.map((kb) => ({
+ disabled: selectCount === 0,
+ icon: <RepoIcon />,
+ key: `add-to-kb-${kb.id}`,
+ label: <span style={{ marginLeft: 8 }}>{kb.name}</span>,
+ onClick: async () => {
+ try {
+ await addFilesToKnowledgeBase(kb.id, selectedFileIds);
+ message.success(
+ t('addToKnowledgeBase.addSuccess', {
+ count: selectCount,
+ ns: 'knowledgeBase',
+ }),
+ );
+ } catch (e) {
+ console.error(e);
+ message.error(t('addToKnowledgeBase.error', { ns: 'knowledgeBase' }));
+ }
+ },
+ }));
- if (availableKnowledgeBases.length > 0) {
- items.push({
- children: addToKnowledgeBaseSubmenu as any,
- disabled: selectCount === 0,
- icon: <Icon icon={BookPlusIcon} />,
- key: 'addToOtherKnowledgeBase',
- label: t('FileManager.actions.addToOtherKnowledgeBase'),
+ if (libraryId) {
+ items.push({
+ disabled: selectCount === 0,
+ icon: <Icon icon={BookMinusIcon} />,
+ key: 'removeFromKnowledgeBase',
+ label: t('FileManager.actions.removeFromKnowledgeBase'),
+ onClick: () => {
+ modal.confirm({
+ okButtonProps: {
+ danger: true,
+ },
+ onOk: async () => {
+ await onActionClick('removeFromKnowledgeBase');
+ message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
+ },
+ title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
+ count: selectCount,
+ }),
});
- }
- } else if (availableKnowledgeBases.length > 0) {
+ },
+ });
+
+ if (availableKnowledgeBases.length > 0) {
items.push({
children: addToKnowledgeBaseSubmenu as any,
disabled: selectCount === 0,
icon: <Icon icon={BookPlusIcon} />,
- key: 'addToKnowledgeBase',
- label: t('FileManager.actions.addToKnowledgeBase'),
+ key: 'addToOtherKnowledgeBase',
+ label: t('FileManager.actions.addToOtherKnowledgeBase'),
});
}
-
- items.push(
- {
- disabled: selectCount === 0,
- icon: <Icon icon={FileBoxIcon} />,
- key: 'batchChunking',
- label: t('FileManager.actions.batchChunking'),
- onClick: async () => {
- await onActionClick('batchChunking');
- },
- },
- {
- type: 'divider',
+ } else if (availableKnowledgeBases.length > 0) {
+ items.push({
+ children: addToKnowledgeBaseSubmenu as any,
+ disabled: selectCount === 0,
+ icon: <Icon icon={BookPlusIcon} />,
+ key: 'addToKnowledgeBase',
+ label: t('FileManager.actions.addToKnowledgeBase'),
+ });
+ }
+
+ items.push(
+ {
+ disabled: selectCount === 0,
+ icon: <Icon icon={FileBoxIcon} />,
+ key: 'batchChunking',
+ label: t('FileManager.actions.batchChunking'),
+ onClick: async () => {
+ await onActionClick('batchChunking');
},
- {
- danger: true,
- disabled: selectCount === 0,
- icon: <Icon icon={Trash2Icon} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: async () => {
- modal.confirm({
- okButtonProps: {
- danger: true,
- },
- onOk: async () => {
- await onActionClick('delete');
- message.success(t('FileManager.actions.deleteSuccess'));
- },
- title: t('FileManager.actions.confirmDeleteMultiFiles', { count: selectCount }),
- });
- },
+ },
+ {
+ type: 'divider',
+ },
+ {
+ danger: true,
+ disabled: selectCount === 0,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: async () => {
+ modal.confirm({
+ okButtonProps: {
+ danger: true,
+ },
+ onOk: async () => {
+ await onActionClick('delete');
+ message.success(t('FileManager.actions.deleteSuccess'));
+ },
+ title: t('FileManager.actions.confirmDeleteMultiFiles', { count: selectCount }),
+ });
},
- );
-
- return items;
- }, [
- libraryId,
- selectCount,
- selectedFileIds,
- onActionClick,
- addFilesToKnowledgeBase,
- t,
- modal,
- message,
- knowledgeBases,
- ]);
-
- return (
- <DropdownMenu items={menuItems} placement="bottomLeft">
- <ActionIconWithChevron
- icon={CircleEllipsisIcon}
- title={t('FileManager.actions.batchActions', 'Batch actions')}
- />
- </DropdownMenu>
+ },
);
- },
-);
+
+ return items;
+ }, [
+ libraryId,
+ selectCount,
+ selectedFileIds,
+ onActionClick,
+ addFilesToKnowledgeBase,
+ t,
+ modal,
+ message,
+ knowledgeBases,
+ ]);
+
+ return (
+ <DropdownMenu items={menuItems} placement="bottomLeft">
+ <ActionIconWithChevron
+ icon={CircleEllipsisIcon}
+ title={t('FileManager.actions.batchActions', 'Batch actions')}
+ />
+ </DropdownMenu>
+ );
+});
BatchActionsDropdown.displayName = 'BatchActionsDropdown';
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index 81c2b807727..09ea41e2691 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -3,12 +3,12 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Flexbox } from '@lobehub/ui';
import { createStyles, cssVar } from 'antd-style';
-import dynamic from 'next/dynamic';
import { memo, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';
import { PageEditor } from '@/features/PageEditor';
+import dynamic from '@/libs/next/dynamic';
import { documentService } from '@/services/document';
import { useFileStore } from '@/store/file';
import { documentSelectors } from '@/store/file/slices/document/selectors';
diff --git a/src/features/Setting/Footer.tsx b/src/features/Setting/Footer.tsx
index f646e482813..646278e769a 100644
--- a/src/features/Setting/Footer.tsx
+++ b/src/features/Setting/Footer.tsx
@@ -4,7 +4,6 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { Center, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { MessageSquareHeart } from 'lucide-react';
-import Link from 'next/link';
import { type PropsWithChildren, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -43,7 +42,7 @@ const Footer = memo<PropsWithChildren>(() => {
>
<div style={{ textAlign: 'center' }}>
<Icon icon={MessageSquareHeart} /> {`${t('footer.title')} `}
- <Link
+ <a
aria-label={'star'}
href={GITHUB}
onClick={(e) => {
@@ -52,9 +51,9 @@ const Footer = memo<PropsWithChildren>(() => {
}}
>
{t('footer.action.star')}
- </Link>
+ </a>
{` ${t('footer.and')} `}
- <Link
+ <a
aria-label={'feedback'}
href={GITHUB_ISSUES}
onClick={(e) => {
@@ -63,7 +62,7 @@ const Footer = memo<PropsWithChildren>(() => {
}}
>
{t('footer.action.feedback')}
- </Link>
+ </a>
{' !'}
</div>
</Center>
diff --git a/src/features/User/UserPanel/PanelContent.tsx b/src/features/User/UserPanel/PanelContent.tsx
index 1f2d5af2753..107264615e2 100644
--- a/src/features/User/UserPanel/PanelContent.tsx
+++ b/src/features/User/UserPanel/PanelContent.tsx
@@ -1,6 +1,6 @@
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { Flexbox } from '@lobehub/ui';
-import { useRouter } from 'next/navigation';
+import { useRouter } from '@/libs/next/navigation';
import { memo } from 'react';
import { Link, useNavigate } from 'react-router-dom';
diff --git a/src/hooks/useActiveTabKey.ts b/src/hooks/useActiveTabKey.ts
index adce20ceda6..5c092eb8b8b 100644
--- a/src/hooks/useActiveTabKey.ts
+++ b/src/hooks/useActiveTabKey.ts
@@ -1,9 +1,11 @@
-import { usePathname, useSearchParams } from 'next/navigation';
+import { usePathname } from '@/libs/router/navigation';
+import { useSearchParams } from '@/libs/router/navigation';
import { ProfileTabs, SettingsTabs, SidebarTabKey } from '@/store/global/initialState';
/**
* Returns the active tab key (chat/market/settings/...)
+ * React Router version for SPA
*/
export const useActiveTabKey = () => {
const pathname = usePathname();
@@ -12,16 +14,18 @@ export const useActiveTabKey = () => {
/**
* Returns the active setting page key (?active=common/sync/agent/...)
+ * React Router version for SPA
*/
export const useActiveSettingsKey = () => {
- const search = useSearchParams();
- const tabs = search.get('active');
+ const [searchParams] = useSearchParams();
+ const tabs = searchParams.get('active');
if (!tabs) return SettingsTabs.Common;
return tabs as SettingsTabs;
};
/**
* Returns the active profile page key (profile/security/stats/...)
+ * React Router version for SPA
*/
export const useActiveProfileKey = () => {
const pathname = usePathname();
diff --git a/src/hooks/useIsSingleMode.test.ts b/src/hooks/useIsSingleMode.test.ts
index ad3b0de2cef..16e38003378 100644
--- a/src/hooks/useIsSingleMode.test.ts
+++ b/src/hooks/useIsSingleMode.test.ts
@@ -1,23 +1,18 @@
import { renderHook } from '@testing-library/react';
-import { ReadonlyURLSearchParams } from 'next/navigation';
import { describe, expect, it, vi } from 'vitest';
import { useIsSingleMode } from './useIsSingleMode';
-// Mock next/navigation
+// Mock react-router-dom useSearchParams (via the wrapper hook)
const mockUseSearchParams = vi.hoisted(() => vi.fn());
-vi.mock('next/navigation', () => ({
+vi.mock('@/libs/router/navigation', () => ({
useSearchParams: mockUseSearchParams,
}));
describe('useIsSingleMode', () => {
-
it('should return false initially (during SSR)', () => {
- const mockSearchParams = {
- get: vi.fn(() => 'single'),
- } as unknown as ReadonlyURLSearchParams;
-
- mockUseSearchParams.mockReturnValue(mockSearchParams);
+ const mockSearchParams = new URLSearchParams('mode=single');
+ mockUseSearchParams.mockReturnValue([mockSearchParams, vi.fn()]);
const { result } = renderHook(() => useIsSingleMode());
@@ -26,11 +21,8 @@ describe('useIsSingleMode', () => {
});
it('should return true when mode=single', () => {
- const mockSearchParams = {
- get: vi.fn((key: string) => (key === 'mode' ? 'single' : null)),
- } as unknown as ReadonlyURLSearchParams;
-
- mockUseSearchParams.mockReturnValue(mockSearchParams);
+ const mockSearchParams = new URLSearchParams('mode=single');
+ mockUseSearchParams.mockReturnValue([mockSearchParams, vi.fn()]);
const { result } = renderHook(() => useIsSingleMode());
@@ -39,11 +31,8 @@ describe('useIsSingleMode', () => {
});
it('should return false when mode is not single', () => {
- const mockSearchParams = {
- get: vi.fn((key: string) => (key === 'mode' ? 'normal' : null)),
- } as unknown as ReadonlyURLSearchParams;
-
- mockUseSearchParams.mockReturnValue(mockSearchParams);
+ const mockSearchParams = new URLSearchParams('mode=normal');
+ mockUseSearchParams.mockReturnValue([mockSearchParams, vi.fn()]);
const { result } = renderHook(() => useIsSingleMode());
@@ -52,11 +41,8 @@ describe('useIsSingleMode', () => {
});
it('should return false when no mode parameter exists', () => {
- const mockSearchParams = {
- get: vi.fn(() => null),
- } as unknown as ReadonlyURLSearchParams;
-
- mockUseSearchParams.mockReturnValue(mockSearchParams);
+ const mockSearchParams = new URLSearchParams();
+ mockUseSearchParams.mockReturnValue([mockSearchParams, vi.fn()]);
const { result } = renderHook(() => useIsSingleMode());
diff --git a/src/hooks/useIsSingleMode.ts b/src/hooks/useIsSingleMode.ts
index 156fefe7f72..973b30f0fdb 100644
--- a/src/hooks/useIsSingleMode.ts
+++ b/src/hooks/useIsSingleMode.ts
@@ -1,11 +1,13 @@
'use client';
-import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
+import { useSearchParams } from '@/libs/router/navigation';
+
/**
* Hook to check if the current page is in single mode
* Single mode is used for standalone windows in desktop app
+ * React Router version for SPA
* @returns boolean indicating if the current page is in single mode
*/
export const useIsSingleMode = (): boolean => {
@@ -16,7 +18,7 @@ export const useIsSingleMode = (): boolean => {
setMounted(true);
}, []);
- const searchParams = useSearchParams();
+ const [searchParams] = useSearchParams();
useEffect(() => {
if (mounted) {
diff --git a/src/hooks/useIsSubSlug.ts b/src/hooks/useIsSubSlug.ts
index 232a1150a85..385a0a4b012 100644
--- a/src/hooks/useIsSubSlug.ts
+++ b/src/hooks/useIsSubSlug.ts
@@ -1,7 +1,8 @@
-import { usePathname } from 'next/navigation';
+import { usePathname } from '@/libs/router/navigation';
/**
* Returns true if the current path has a sub slug (`/chat/mobile` or `/chat/settings`)
+ * React Router version for SPA
*/
export const useIsSubSlug = () => {
const pathname = usePathname();
diff --git a/src/hooks/useQuery.ts b/src/hooks/useQuery.ts
index 47e13e314df..f6f85971152 100644
--- a/src/hooks/useQuery.ts
+++ b/src/hooks/useQuery.ts
@@ -1,13 +1,13 @@
-import { useSearchParams } from 'next/navigation';
import qs from 'query-string';
import { useMemo } from 'react';
+import { useSearchParams } from '@/libs/router/navigation';
+
/**
* Hook to get query parameters
- * This is the Next.js version
- * For React Router version, use useQuery from @/app/[variants]/(main)/hooks/useQuery
+ * React Router version for SPA
*/
export const useQuery = () => {
- const rawQuery = useSearchParams();
- return useMemo(() => qs.parse(rawQuery.toString()), [rawQuery]);
+ const [searchParams] = useSearchParams();
+ return useMemo(() => qs.parse(searchParams.toString()), [searchParams]);
};
diff --git a/src/layout/GlobalProvider/AppTheme.tsx b/src/layout/GlobalProvider/AppTheme.tsx
index e0e64624b6d..e2c2f7c3525 100644
--- a/src/layout/GlobalProvider/AppTheme.tsx
+++ b/src/layout/GlobalProvider/AppTheme.tsx
@@ -13,15 +13,15 @@ import { createStaticStyles, cx, useTheme } from 'antd-style';
import 'antd/dist/reset.css';
import { AppConfigContext } from 'antd/es/app/context';
import * as motion from 'motion/react-m';
-import Image from 'next/image';
-import Link from 'next/link';
import { type ReactNode, memo, useEffect, useMemo, useState } from 'react';
import AntdStaticMethods from '@/components/AntdStaticMethods';
+import Link from '@/components/Link';
import { LOBE_THEME_NEUTRAL_COLOR, LOBE_THEME_PRIMARY_COLOR } from '@/const/theme';
import { isDesktop } from '@/const/version';
import { useIsDark } from '@/hooks/useIsDark';
import { getUILocaleAndResources } from '@/libs/getUILocaleAndResources';
+import Image from '@/libs/next/Image';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
diff --git a/src/layout/GlobalProvider/StyleRegistry.tsx b/src/layout/GlobalProvider/StyleRegistry.tsx
index f388a279783..f51b14aeefa 100644
--- a/src/layout/GlobalProvider/StyleRegistry.tsx
+++ b/src/layout/GlobalProvider/StyleRegistry.tsx
@@ -1,7 +1,7 @@
'use client';
import { StyleProvider } from 'antd-style';
-import { useServerInsertedHTML } from 'next/navigation';
+import { useServerInsertedHTML } from '@/libs/next/navigation';
import { type PropsWithChildren } from 'react';
import { isDesktop } from '@/const/version';
diff --git a/src/layout/GlobalProvider/useUserStateRedirect.ts b/src/layout/GlobalProvider/useUserStateRedirect.ts
index 8f888de7f7c..8c9f8f7bf7d 100644
--- a/src/layout/GlobalProvider/useUserStateRedirect.ts
+++ b/src/layout/GlobalProvider/useUserStateRedirect.ts
@@ -1,7 +1,6 @@
'use client';
import { OFFICIAL_URL } from '@lobechat/const';
-import { usePathname } from 'next/navigation';
import { useCallback } from 'react';
import { getDesktopOnboardingCompleted } from '@/app/[variants]/(desktop)/desktop-onboarding/storage';
@@ -11,20 +10,12 @@ import { useUserStore } from '@/store/user';
import { onboardingSelectors } from '@/store/user/selectors';
import type { UserInitializationState } from '@/types/user';
-const redirectIfNotOn = (currentPath: string | null | undefined, path: string) => {
- if (!currentPath?.startsWith(path)) {
+const redirectIfNotOn = (currentPath: string, path: string) => {
+ if (!currentPath.startsWith(path)) {
window.location.href = path;
}
};
-const useCurrentPathname = () => {
- const pathname = usePathname();
- return useCallback(() => {
- if (typeof window === 'undefined') return pathname;
- return window.location.pathname || pathname;
- }, [pathname]);
-};
-
export const useDesktopUserStateRedirect = () => {
const dataSyncConfig = useElectronStore((s) => s.dataSyncConfig);
const logout = useUserStore((s) => s.logout);
@@ -69,25 +60,22 @@ export const useDesktopUserStateRedirect = () => {
);
};
-export const useWebUserStateRedirect = (getCurrentPathname: () => string | null | undefined) =>
- useCallback(
- (state: UserInitializationState) => {
- if (state.isInWaitList === true) {
- redirectIfNotOn(getCurrentPathname(), '/waitlist');
- return;
- }
+export const useWebUserStateRedirect = () =>
+ useCallback((state: UserInitializationState) => {
+ const pathname = window.location.pathname;
+ if (state.isInWaitList === true) {
+ redirectIfNotOn(pathname, '/waitlist');
+ return;
+ }
- if (!onboardingSelectors.needsOnboarding(state)) return;
+ if (!onboardingSelectors.needsOnboarding(state)) return;
- redirectIfNotOn(getCurrentPathname(), '/onboarding');
- },
- [getCurrentPathname],
- );
+ redirectIfNotOn(pathname, '/onboarding');
+ }, []);
export const useUserStateRedirect = () => {
- const getCurrentPathname = useCurrentPathname();
const desktopRedirect = useDesktopUserStateRedirect();
- const webRedirect = useWebUserStateRedirect(getCurrentPathname);
+ const webRedirect = useWebUserStateRedirect();
return useCallback(
(state: UserInitializationState) => {
diff --git a/src/libs/next/Image.tsx b/src/libs/next/Image.tsx
new file mode 100644
index 00000000000..f7d4537c16f
--- /dev/null
+++ b/src/libs/next/Image.tsx
@@ -0,0 +1,13 @@
+/**
+ * Image component wrapper for Next.js Image.
+ * This module provides a unified interface that can be easily replaced
+ * with a generic <img> or custom image component in the future.
+ *
+ * @see Phase 3.4: LOBE-2991
+ */
+
+// Re-export the Image component
+
+// Re-export types
+export type { ImageProps, StaticImageData } from 'next/image';
+export { default } from 'next/image';
diff --git a/src/libs/next/Link.tsx b/src/libs/next/Link.tsx
new file mode 100644
index 00000000000..1ea98f27326
--- /dev/null
+++ b/src/libs/next/Link.tsx
@@ -0,0 +1,13 @@
+/**
+ * Link component wrapper for Next.js Link.
+ * This module provides a unified interface that can be easily replaced
+ * with react-router-dom Link in the future.
+ *
+ * @see Phase 3.2: LOBE-2989
+ */
+
+// Re-export the Link component
+
+// Re-export the type for props
+export type { LinkProps } from 'next/link';
+export { default } from 'next/link';
diff --git a/src/libs/next/dynamic.tsx b/src/libs/next/dynamic.tsx
new file mode 100644
index 00000000000..0986587239c
--- /dev/null
+++ b/src/libs/next/dynamic.tsx
@@ -0,0 +1,13 @@
+/**
+ * Dynamic import wrapper for Next.js dynamic.
+ * This module provides a unified interface that can be easily replaced
+ * with React.lazy + Suspense in the future.
+ *
+ * @see Phase 3.3: LOBE-2990
+ */
+
+// Re-export the dynamic function
+
+// Re-export types
+export type { DynamicOptions, Loader, LoaderComponent } from 'next/dynamic';
+export { default } from 'next/dynamic';
diff --git a/src/libs/next/index.ts b/src/libs/next/index.ts
new file mode 100644
index 00000000000..c87b7d5b8f9
--- /dev/null
+++ b/src/libs/next/index.ts
@@ -0,0 +1,22 @@
+/**
+ * Next.js wrapper module
+ *
+ * This module provides unified interfaces for Next.js-specific APIs,
+ * making it easier to migrate from Next.js to other frameworks (e.g., Vite + React Router).
+ *
+ * Usage:
+ * - import { useRouter, usePathname } from '@/libs/next/navigation';
+ * - import Link from '@/libs/next/Link';
+ * - import dynamic from '@/libs/next/dynamic';
+ * - import Image from '@/libs/next/Image';
+ *
+ * @see RFC 147: LOBE-2850 - Phase 3
+ */
+
+// Navigation exports
+export * from './navigation';
+
+// Component exports (re-export as named for convenience)
+export { default as dynamic } from './dynamic';
+export { default as Image } from './Image';
+export { default as Link } from './Link';
diff --git a/src/libs/next/navigation.ts b/src/libs/next/navigation.ts
new file mode 100644
index 00000000000..59f3deb547e
--- /dev/null
+++ b/src/libs/next/navigation.ts
@@ -0,0 +1,22 @@
+/**
+ * Navigation utilities wrapper for Next.js navigation APIs.
+ * This module provides a unified interface that can be easily replaced
+ * with react-router-dom in the future.
+ *
+ * @see Phase 3.1: LOBE-2988
+ */
+
+// Re-export all navigation hooks and utilities from Next.js
+export {
+ notFound,
+ ReadonlyURLSearchParams,
+ redirect,
+ useParams,
+ usePathname,
+ useRouter,
+ useSearchParams,
+ useServerInsertedHTML,
+} from 'next/navigation';
+
+// Re-export types
+export type { RedirectType } from 'next/navigation';
diff --git a/src/libs/router/Link.tsx b/src/libs/router/Link.tsx
new file mode 100644
index 00000000000..7c8c3ad5a6c
--- /dev/null
+++ b/src/libs/router/Link.tsx
@@ -0,0 +1,30 @@
+/**
+ * React Router Link component wrapper.
+ * Provides a Next.js-like API (href prop) while using React Router internally.
+ *
+ * @see RFC 147: LOBE-2850 - Phase 3
+ */
+
+import React, { memo } from 'react';
+import { Link as ReactRouterLink, type LinkProps as ReactRouterLinkProps } from 'react-router-dom';
+
+interface LinkProps extends Omit<ReactRouterLinkProps, 'to'> {
+ children?: React.ReactNode;
+ href?: string;
+ to?: string;
+}
+
+/**
+ * Link component for React Router.
+ * Provides a Next.js-like API (href prop) while using React Router internally.
+ */
+const Link = memo<LinkProps>(({ href, to, ...props }) => {
+ const linkTo = href || to || '/';
+ return <ReactRouterLink {...props} to={linkTo} />;
+});
+
+Link.displayName = 'Link';
+
+export default Link;
+
+export type { LinkProps };
diff --git a/src/libs/router/index.ts b/src/libs/router/index.ts
new file mode 100644
index 00000000000..d2eb5d48b82
--- /dev/null
+++ b/src/libs/router/index.ts
@@ -0,0 +1,18 @@
+/**
+ * React Router wrapper module for SPA routing.
+ *
+ * This module provides unified interfaces for React Router APIs,
+ * with a Next.js-like API surface for easier migration.
+ *
+ * Usage:
+ * - import { useRouter, usePathname, useSearchParams } from '@/libs/router';
+ * - import Link from '@/libs/router/Link';
+ *
+ * @see RFC 147: LOBE-2850 - Phase 3
+ */
+
+// Navigation exports
+export * from './navigation';
+
+// Component exports
+export { default as Link } from './Link';
diff --git a/src/libs/router/navigation.ts b/src/libs/router/navigation.ts
new file mode 100644
index 00000000000..5f9496532d9
--- /dev/null
+++ b/src/libs/router/navigation.ts
@@ -0,0 +1,72 @@
+/**
+ * React Router navigation hooks wrapper.
+ * This module provides unified navigation hooks for SPA routing.
+ *
+ * Usage:
+ * - import { useRouter, usePathname, useSearchParams, useQuery } from '@/libs/router/navigation';
+ *
+ * @see RFC 147: LOBE-2850 - Phase 3
+ */
+
+import qs from 'query-string';
+import { useMemo } from 'react';
+import {
+ useLocation,
+ useNavigate,
+ useParams as useReactRouterParams,
+ useSearchParams as useReactRouterSearchParams,
+} from 'react-router-dom';
+
+/**
+ * Hook to get router navigation functions.
+ * Provides a Next.js-like API using React Router.
+ */
+export const useRouter = () => {
+ const navigate = useNavigate();
+
+ return useMemo(
+ () => ({
+ back: () => navigate(-1),
+ forward: () => navigate(1),
+ // Note: prefetch is not supported in React Router
+ prefetch: () => {},
+ push: (href: string) => navigate(href),
+ replace: (href: string) => navigate(href, { replace: true }),
+ }),
+ [navigate]
+ );
+};
+
+/**
+ * Hook to get current pathname.
+ */
+export const usePathname = () => {
+ const location = useLocation();
+ return location.pathname;
+};
+
+/**
+ * Hook to get search params.
+ * Returns [searchParams, setSearchParams] tuple similar to React Router.
+ */
+export const useSearchParams = () => {
+ return useReactRouterSearchParams();
+};
+
+/**
+ * Hook to get route params.
+ */
+export const useParams = <T extends Record<string, string | undefined> = Record<string, string | undefined>>() => {
+ return useReactRouterParams<T>();
+};
+
+/**
+ * Hook to get query parameters as a parsed object.
+ */
+export const useQuery = () => {
+ const [searchParams] = useReactRouterSearchParams();
+ return useMemo(() => qs.parse(searchParams.toString()), [searchParams]);
+};
+
+// Re-export types
+export type { Location, NavigateFunction, Params } from 'react-router-dom';
diff --git a/src/server/modules/AgentRuntime/AgentStateManager.ts b/src/server/modules/AgentRuntime/AgentStateManager.ts
index 869c47249f1..919f9f7e672 100644
--- a/src/server/modules/AgentRuntime/AgentStateManager.ts
+++ b/src/server/modules/AgentRuntime/AgentStateManager.ts
@@ -1,4 +1,8 @@
-import { type AgentEvent, type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';
+import {
+ type AgentEvent,
+ type AgentRuntimeContext,
+ type AgentState,
+} from '@lobechat/agent-runtime';
import debug from 'debug';
import type { Redis } from 'ioredis';
diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.ts
index 8dbbaedbee3..42f54a4f73a 100644
--- a/src/store/chat/slices/portal/selectors.test.ts
+++ b/src/store/chat/slices/portal/selectors.test.ts
@@ -111,9 +111,7 @@ describe('chatDockSelectors', () => {
it('should return the messageId when ToolUI view is on stack', () => {
const state = createState({
- portalStack: [
- { type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' },
- ],
+ portalStack: [{ type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' }],
});
expect(chatPortalSelectors.toolMessageId(state)).toBe('test-id');
});
@@ -122,9 +120,7 @@ describe('chatDockSelectors', () => {
describe('isMessageToolUIOpen', () => {
it('should return false when id does not match or showDock is false', () => {
const state = createState({
- portalStack: [
- { type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' },
- ],
+ portalStack: [{ type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' }],
showPortal: false,
});
expect(chatPortalSelectors.isPluginUIOpen('test-id')(state)).toBe(false);
@@ -133,9 +129,7 @@ describe('chatDockSelectors', () => {
it('should return true when id matches and showDock is true', () => {
const state = createState({
- portalStack: [
- { type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' },
- ],
+ portalStack: [{ type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' }],
showPortal: true,
});
expect(chatPortalSelectors.isPluginUIOpen('test-id')(state)).toBe(true);
@@ -149,9 +143,7 @@ describe('chatDockSelectors', () => {
it('should return true when ToolUI view is on stack', () => {
const state = createState({
- portalStack: [
- { type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' },
- ],
+ portalStack: [{ type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' }],
});
expect(chatPortalSelectors.showPluginUI(state)).toBe(true);
});
@@ -164,9 +156,7 @@ describe('chatDockSelectors', () => {
it('should return the identifier when ToolUI view is on stack', () => {
const state = createState({
- portalStack: [
- { type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' },
- ],
+ portalStack: [{ type: PortalViewType.ToolUI, messageId: 'test-id', identifier: 'test' }],
});
expect(chatPortalSelectors.toolUIIdentifier(state)).toBe('test');
});
diff --git a/src/store/page/index.ts b/src/store/page/index.ts
index 356c4062b8c..9e62bbbe3a4 100644
--- a/src/store/page/index.ts
+++ b/src/store/page/index.ts
@@ -1,2 +1,2 @@
export * from './selectors';
-export { getPageStoreState, type PageStore,usePageStore } from './store';
+export { getPageStoreState, type PageStore, usePageStore } from './store';
diff --git a/src/store/page/slices/crud/index.ts b/src/store/page/slices/crud/index.ts
index 0ae253b699b..2ae5307a29d 100644
--- a/src/store/page/slices/crud/index.ts
+++ b/src/store/page/slices/crud/index.ts
@@ -1,2 +1,2 @@
export { createCrudSlice, type CrudAction } from './action';
-export { type CrudState,initialCrudState } from './initialState';
+export { type CrudState, initialCrudState } from './initialState';