diff --git a/src/app/(main)/layout.tsx b/src/app/(main)/layout.tsx
index fe77aaf..d9504ce 100644
--- a/src/app/(main)/layout.tsx
+++ b/src/app/(main)/layout.tsx
@@ -1,27 +1,26 @@
-import { redirect } from "next/navigation";
-import { auth } from "@/lib/auth";
-import { MainNav } from "@/components/main-nav";
-import { DecorativeBackground } from "@/components/decorative-background";
-import { AIAssistant } from "@/components/ai-assistant";
-import { AIStatusProvider } from "@/components/ai-status-context";
-import { SessionGuard } from "@/components/session-guard";
+import { redirect } from 'next/navigation';
+import { auth } from '@/lib/auth';
+import { MainNav } from '@/components/main-nav';
+import { DecorativeBackground } from '@/components/decorative-background';
+import { AIAssistantLoader } from '@/components/ai-assistant-loader';
+import { AIStatusProvider } from '@/components/ai-status-context';
+import { SessionGuard } from '@/components/session-guard';
export default async function MainLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
- if (!session?.user) redirect("/login");
+ if (!session?.user) redirect('/login');
return (
);
}
-
diff --git a/src/app/api/ai/status/route.ts b/src/app/api/ai/status/route.ts
index 2f950d6..b237654 100644
--- a/src/app/api/ai/status/route.ts
+++ b/src/app/api/ai/status/route.ts
@@ -1,6 +1,6 @@
-import { NextResponse } from "next/server";
-import { auth } from "@/lib/auth";
-import { getAIStatus } from "@/lib/ai";
+import { NextResponse } from 'next/server';
+import { auth } from '@/lib/auth';
+import { getAIStatus } from '@/lib/ai/config';
export async function GET() {
const session = await auth();
diff --git a/src/app/api/ai/task-queue/route.ts b/src/app/api/ai/task-queue/route.ts
index 6cc2633..6a22e73 100644
--- a/src/app/api/ai/task-queue/route.ts
+++ b/src/app/api/ai/task-queue/route.ts
@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { getWrongNoteImageQueueStats } from '@/lib/ai/wrong-note-image-queue';
-import { imageUrlFor } from '@/lib/ai/wrong-note-image';
+import { imageUrlFor } from '@/lib/ai/image-url';
import { prisma } from '@/lib/prisma';
import { clampInt } from '@/lib/validate';
diff --git a/src/app/api/wrong-notes/route.ts b/src/app/api/wrong-notes/route.ts
index 444a57d..6a1ebb8 100644
--- a/src/app/api/wrong-notes/route.ts
+++ b/src/app/api/wrong-notes/route.ts
@@ -4,7 +4,7 @@ import { prisma } from '@/lib/prisma';
import { clampInt } from '@/lib/validate';
import { getDescendantTopicIds } from '@/lib/knowledge-stats';
import { PAGE_SIZE_DEFAULT, PAGE_SIZE_MAX } from '@/lib/constants';
-import { imageUrlFor } from '@/lib/ai/wrong-note-image';
+import { imageUrlFor } from '@/lib/ai/image-url';
function getStatusFilter(status: string | null) {
if (status === 'mastered') return { markedMastered: true };
diff --git a/src/components/ai-assistant-loader.tsx b/src/components/ai-assistant-loader.tsx
new file mode 100644
index 0000000..9ba6b4d
--- /dev/null
+++ b/src/components/ai-assistant-loader.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { useState } from 'react';
+import dynamic from 'next/dynamic';
+import { Bot } from 'lucide-react';
+
+const AIAssistant = dynamic(
+ () => import('@/components/ai-assistant').then((mod) => mod.AIAssistant),
+ { loading: () => null, ssr: false }
+);
+
+export function AIAssistantLoader() {
+ const [loaded, setLoaded] = useState(false);
+
+ if (loaded) return ;
+
+ return (
+
+
+
+ );
+}
diff --git a/src/components/ai-assistant.tsx b/src/components/ai-assistant.tsx
index e9d8cee..c4dd0f4 100644
--- a/src/components/ai-assistant.tsx
+++ b/src/components/ai-assistant.tsx
@@ -58,11 +58,12 @@ function normalizeSession(value: unknown): ChatSession | null {
};
}
-export function AIAssistant() {
- const [open, setOpen] = useState(false);
+export function AIAssistant({ defaultOpen = false }: { defaultOpen?: boolean }) {
+ const [open, setOpen] = useState(defaultOpen);
const [maximized, setMaximized] = useState(false);
const status = useAIStatus();
const [sessions, setSessions] = useState([]);
+ const [sessionsLoaded, setSessionsLoaded] = useState(false);
const [activeSessionId, setActiveSessionId] = useState(null);
const [messages, setMessages] = useState(initialMessages);
const [input, setInput] = useState('');
@@ -98,6 +99,7 @@ export function AIAssistant() {
});
useEffect(() => {
+ if (!open || sessionsLoaded) return;
let active = true;
async function loadSessions() {
const response = await fetch('/api/ai/chat/sessions').catch(() => null);
@@ -110,6 +112,7 @@ export function AIAssistant() {
: [];
if (!active) return;
setSessions(nextSessions);
+ setSessionsLoaded(true);
const latest = nextSessions[0];
if (latest) {
setActiveSessionId(latest.id);
@@ -120,7 +123,7 @@ export function AIAssistant() {
return () => {
active = false;
};
- }, []);
+ }, [open, sessionsLoaded]);
async function saveSession(
nextMessages: Message[],
diff --git a/src/lib/ai/config.ts b/src/lib/ai/config.ts
new file mode 100644
index 0000000..f47fe5e
--- /dev/null
+++ b/src/lib/ai/config.ts
@@ -0,0 +1,156 @@
+import type { AIConfig, AIProviderKey } from '@/lib/ai/types';
+import { encryptSecret, isEncryptionEnabled, resolveSecret } from '@/lib/crypto/secrets';
+import { prisma } from '@/lib/prisma';
+import { getSanitizedEndpoint, resolveDefaultModel } from '@/lib/ai/utils';
+
+const DEFAULT_BASE_URLS: Record = {
+ claude: 'https://api.anthropic.com',
+ openai: 'https://api.openai.com/v1',
+ gemini: 'https://generativelanguage.googleapis.com',
+ custom: undefined,
+};
+
+const PROVIDER_NAMES: Record = {
+ claude: 'Claude',
+ openai: 'OpenAI',
+ gemini: 'Gemini',
+ custom: 'Custom',
+};
+
+function envConfigFor(provider: AIProviderKey): AIConfig | null {
+ if (provider === 'claude') {
+ const apiKey = process.env.ANTHROPIC_API_KEY;
+ if (!apiKey) return null;
+ return {
+ provider,
+ apiKey,
+ model: process.env.ANTHROPIC_MODEL || resolveDefaultModel('claude'),
+ baseUrl: process.env.ANTHROPIC_BASE_URL,
+ };
+ }
+ if (provider === 'openai') {
+ const apiKey = process.env.OPENAI_API_KEY;
+ if (!apiKey) return null;
+ return {
+ provider,
+ apiKey,
+ model: process.env.OPENAI_MODEL || resolveDefaultModel('openai'),
+ baseUrl: process.env.OPENAI_BASE_URL,
+ };
+ }
+ if (provider === 'gemini') {
+ const apiKey = process.env.GEMINI_API_KEY;
+ if (!apiKey) return null;
+ return {
+ provider,
+ apiKey,
+ model: process.env.GEMINI_MODEL || resolveDefaultModel('gemini'),
+ baseUrl: process.env.GEMINI_BASE_URL,
+ };
+ }
+ if (provider === 'custom') {
+ const baseUrl = process.env.CUSTOM_BASE_URL;
+ if (!baseUrl) return null;
+ return {
+ provider,
+ apiKey: process.env.CUSTOM_API_KEY,
+ model: process.env.CUSTOM_MODEL || resolveDefaultModel('custom'),
+ baseUrl,
+ };
+ }
+ return null;
+}
+
+function resolveEnvConfig(): AIConfig | null {
+ const preferred = process.env.AI_PROVIDER?.toLowerCase() as AIProviderKey | undefined;
+ if (preferred) {
+ const config = envConfigFor(preferred);
+ if (config) return config;
+ }
+ for (const provider of ['claude', 'openai', 'gemini', 'custom'] as AIProviderKey[]) {
+ const config = envConfigFor(provider);
+ if (config) return config;
+ }
+ return null;
+}
+
+function normalizeProvider(raw: string | null | undefined): AIProviderKey | null {
+ if (!raw) return null;
+ const value = raw.toLowerCase();
+ if (value === 'claude' || value === 'openai' || value === 'gemini' || value === 'custom') {
+ return value;
+ }
+ return null;
+}
+
+function lazyMigrateApiKey(userId: string, plaintext: string): void {
+ void (async () => {
+ try {
+ const encrypted = encryptSecret(plaintext);
+ await prisma.userAISettings.update({
+ where: { userId },
+ data: { apiKeyEncrypted: encrypted, apiKey: null },
+ });
+ } catch {
+ // Migration retries on next request.
+ }
+ })();
+}
+
+export async function resolveAIConfig(userId?: string | null): Promise {
+ if (userId) {
+ const settings = await prisma.userAISettings.findUnique({ where: { userId } });
+ const provider = normalizeProvider(settings?.provider ?? null);
+ if (provider) {
+ const apiKey = resolveSecret(settings?.apiKeyEncrypted, settings?.apiKey);
+ const hasRequired = provider === 'custom' ? Boolean(settings?.baseUrl) : Boolean(apiKey);
+ if (hasRequired) {
+ if (settings && !settings.apiKeyEncrypted && settings.apiKey && isEncryptionEnabled()) {
+ lazyMigrateApiKey(userId, settings.apiKey);
+ }
+ return {
+ provider,
+ apiKey: apiKey ?? undefined,
+ model: settings?.model || resolveDefaultModel(provider),
+ baseUrl: settings?.baseUrl ?? undefined,
+ visionSupport: settings?.visionSupport ?? null,
+ };
+ }
+ }
+ }
+ return resolveEnvConfig();
+}
+
+export async function isAIConfigured(userId?: string | null) {
+ const config = await resolveAIConfig(userId);
+ return config !== null;
+}
+
+export async function getAIStatus(userId?: string | null) {
+ try {
+ const config = await resolveAIConfig(userId);
+ if (!config) {
+ return { configured: false, provider: null, model: null, endpoint: null, source: null };
+ }
+ const fallbackEndpoint = DEFAULT_BASE_URLS[config.provider] ?? config.baseUrl ?? '';
+ const source = await getConfigSource(userId);
+ return {
+ configured: true,
+ provider: PROVIDER_NAMES[config.provider],
+ model: config.model || resolveDefaultModel(config.provider),
+ endpoint: getSanitizedEndpoint(config.baseUrl, fallbackEndpoint),
+ source,
+ };
+ } catch {
+ return { configured: false, provider: null, model: null, endpoint: null, source: null };
+ }
+}
+
+async function getConfigSource(userId?: string | null) {
+ if (!userId) return 'env' as const;
+ const settings = await prisma.userAISettings.findUnique({ where: { userId } });
+ if (!settings?.provider) return 'env' as const;
+ const hasApiKey = Boolean(resolveSecret(settings.apiKeyEncrypted, settings.apiKey));
+ const hasRequired = settings.provider === 'custom' ? Boolean(settings.baseUrl) : hasApiKey;
+ return hasRequired ? ('user' as const) : ('env' as const);
+}
diff --git a/src/lib/ai/image-url.ts b/src/lib/ai/image-url.ts
new file mode 100644
index 0000000..c367785
--- /dev/null
+++ b/src/lib/ai/image-url.ts
@@ -0,0 +1,3 @@
+export function imageUrlFor(generation: { id: string; updatedAt: Date }) {
+ return `/api/ai/wrong-note-image/${generation.id}/file?v=${generation.updatedAt.getTime()}`;
+}
diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.ts
index c4ce0ba..9c5e5a2 100644
--- a/src/lib/ai/index.ts
+++ b/src/lib/ai/index.ts
@@ -1,115 +1,11 @@
-import type { AIConfig, AIProvider, AIProviderKey } from '@/lib/ai/types';
+import type { AIConfig, AIProvider } from '@/lib/ai/types';
+import { resolveAIConfig } from '@/lib/ai/config';
import { createClaudeProvider } from '@/lib/ai/providers/claude';
-import { createOpenAIProvider } from '@/lib/ai/providers/openai';
-import { createGeminiProvider } from '@/lib/ai/providers/gemini';
import { createCustomProvider } from '@/lib/ai/providers/custom';
-import { resolveDefaultModel } from '@/lib/ai/utils';
-import { prisma } from '@/lib/prisma';
-import { encryptSecret, isEncryptionEnabled, resolveSecret } from '@/lib/crypto/secrets';
-
-function envConfigFor(provider: AIProviderKey): AIConfig | null {
- if (provider === 'claude') {
- const apiKey = process.env.ANTHROPIC_API_KEY;
- if (!apiKey) return null;
- return {
- provider,
- apiKey,
- model: process.env.ANTHROPIC_MODEL || resolveDefaultModel('claude'),
- baseUrl: process.env.ANTHROPIC_BASE_URL,
- };
- }
- if (provider === 'openai') {
- const apiKey = process.env.OPENAI_API_KEY;
- if (!apiKey) return null;
- return {
- provider,
- apiKey,
- model: process.env.OPENAI_MODEL || resolveDefaultModel('openai'),
- baseUrl: process.env.OPENAI_BASE_URL,
- };
- }
- if (provider === 'gemini') {
- const apiKey = process.env.GEMINI_API_KEY;
- if (!apiKey) return null;
- return {
- provider,
- apiKey,
- model: process.env.GEMINI_MODEL || resolveDefaultModel('gemini'),
- baseUrl: process.env.GEMINI_BASE_URL,
- };
- }
- if (provider === 'custom') {
- const baseUrl = process.env.CUSTOM_BASE_URL;
- if (!baseUrl) return null;
- return {
- provider,
- apiKey: process.env.CUSTOM_API_KEY,
- model: process.env.CUSTOM_MODEL || resolveDefaultModel('custom'),
- baseUrl,
- };
- }
- return null;
-}
-
-function resolveEnvConfig(): AIConfig | null {
- const preferred = process.env.AI_PROVIDER?.toLowerCase() as AIProviderKey | undefined;
- if (preferred) {
- const config = envConfigFor(preferred);
- if (config) return config;
- }
- for (const provider of ['claude', 'openai', 'gemini', 'custom'] as AIProviderKey[]) {
- const config = envConfigFor(provider);
- if (config) return config;
- }
- return null;
-}
-
-function normalizeProvider(raw: string | null | undefined): AIProviderKey | null {
- if (!raw) return null;
- const value = raw.toLowerCase();
- if (value === 'claude' || value === 'openai' || value === 'gemini' || value === 'custom')
- return value;
- return null;
-}
-
-function lazyMigrateApiKey(userId: string, plaintext: string): void {
- void (async () => {
- try {
- const encrypted = encryptSecret(plaintext);
- await prisma.userAISettings.update({
- where: { userId },
- data: { apiKeyEncrypted: encrypted, apiKey: null },
- });
- } catch {
- // Silently swallow — migration retries on next request
- }
- })();
-}
+import { createGeminiProvider } from '@/lib/ai/providers/gemini';
+import { createOpenAIProvider } from '@/lib/ai/providers/openai';
-export async function resolveAIConfig(userId?: string | null): Promise {
- if (userId) {
- const settings = await prisma.userAISettings.findUnique({ where: { userId } });
- const provider = normalizeProvider(settings?.provider ?? null);
- if (provider) {
- const apiKey = resolveSecret(settings?.apiKeyEncrypted, settings?.apiKey);
- const hasRequired = provider === 'custom' ? Boolean(settings?.baseUrl) : Boolean(apiKey);
- if (hasRequired) {
- // Lazy-migrate legacy plaintext key to encrypted storage
- if (settings && !settings.apiKeyEncrypted && settings.apiKey && isEncryptionEnabled()) {
- lazyMigrateApiKey(userId, settings.apiKey);
- }
- return {
- provider,
- apiKey: apiKey ?? undefined,
- model: settings?.model || resolveDefaultModel(provider),
- baseUrl: settings?.baseUrl ?? undefined,
- visionSupport: settings?.visionSupport ?? null,
- };
- }
- }
- }
- return resolveEnvConfig();
-}
+export { getAIStatus, isAIConfigured, resolveAIConfig } from '@/lib/ai/config';
export function buildAIProvider(config: AIConfig): AIProvider {
if (config.provider === 'claude') return createClaudeProvider(config);
@@ -121,41 +17,8 @@ export function buildAIProvider(config: AIConfig): AIProvider {
export async function getAIProvider(userId?: string | null): Promise {
const config = await resolveAIConfig(userId);
- if (!config) throw new Error('未配置 AI 供应商,请在个人中心填入 API Key 或设置环境变量');
- return buildAIProvider(config);
-}
-
-export async function isAIConfigured(userId?: string | null) {
- const config = await resolveAIConfig(userId);
- return config !== null;
-}
-
-export async function getAIStatus(userId?: string | null) {
- try {
- const config = await resolveAIConfig(userId);
- if (!config) {
- return { configured: false, provider: null, model: null, endpoint: null, source: null };
- }
- const provider = buildAIProvider(config);
- const info = provider.getInfo();
- const source = await getConfigSource(userId);
- return {
- configured: true,
- provider: info.name,
- model: info.model,
- endpoint: info.endpoint,
- source,
- };
- } catch {
- return { configured: false, provider: null, model: null, endpoint: null, source: null };
+ if (!config) {
+ throw new Error('未配置 AI 供应商,请在个人中心填入 API Key 或设置环境变量');
}
-}
-
-async function getConfigSource(userId?: string | null) {
- if (!userId) return 'env' as const;
- const settings = await prisma.userAISettings.findUnique({ where: { userId } });
- if (!settings?.provider) return 'env' as const;
- const hasApiKey = Boolean(resolveSecret(settings.apiKeyEncrypted, settings.apiKey));
- const hasRequired = settings.provider === 'custom' ? Boolean(settings.baseUrl) : hasApiKey;
- return hasRequired ? ('user' as const) : ('env' as const);
+ return buildAIProvider(config);
}
diff --git a/src/lib/ai/wrong-note-image-queue.ts b/src/lib/ai/wrong-note-image-queue.ts
index 91a05ae..4bfc2a1 100644
--- a/src/lib/ai/wrong-note-image-queue.ts
+++ b/src/lib/ai/wrong-note-image-queue.ts
@@ -1,5 +1,3 @@
-import { runWrongNoteImageGeneration } from '@/lib/ai/wrong-note-image';
-
type QueueState = {
queue: string[];
queuedIds: Set;
@@ -39,7 +37,8 @@ function schedule() {
state.queuedIds.delete(generationId);
state.activeIds.add(generationId);
state.active += 1;
- void runWrongNoteImageGeneration(generationId)
+ void import('@/lib/ai/wrong-note-image')
+ .then(({ runWrongNoteImageGeneration }) => runWrongNoteImageGeneration(generationId))
.catch(() => undefined)
.finally(() => {
state.active -= 1;
diff --git a/src/lib/ai/wrong-note-image.ts b/src/lib/ai/wrong-note-image.ts
index 9236cfd..765c9ca 100644
--- a/src/lib/ai/wrong-note-image.ts
+++ b/src/lib/ai/wrong-note-image.ts
@@ -24,6 +24,7 @@ import {
} from '@/lib/ai/wrong-note-image-style-anchors';
import { extractImageUrls, normalizeErrorMessage } from '@/lib/ai/utils';
import { prisma } from '@/lib/prisma';
+import { imageUrlFor } from '@/lib/ai/image-url';
export const WRONG_NOTE_IMAGE_TEMPLATE_VERSION = '2026-05-02-v6-vision-support';
@@ -67,9 +68,7 @@ type GenerationForSerialization = {
errorMessage: string | null;
};
-export function imageUrlFor(generation: { id: string; updatedAt: Date }) {
- return `/api/ai/wrong-note-image/${generation.id}/file?v=${generation.updatedAt.getTime()}`;
-}
+export { imageUrlFor };
export function serializeImageGeneration(
generation: GenerationForSerialization
@@ -307,10 +306,9 @@ export async function runWrongNoteImageGeneration(generationId: string) {
);
const runtime = await getRuntime(generation.userId);
- const allContent = [
- note.question.content,
- ...note.question.options.map((o) => o.content),
- ].join('\n');
+ const allContent = [note.question.content, ...note.question.options.map((o) => o.content)].join(
+ '\n'
+ );
const imageUrls = extractImageUrls(allContent);
if (imageUrls.length > 0 && !runtime.promptProvider.supportsVision()) {
diff --git a/src/middleware.ts b/src/middleware.ts
index 093fc8a..d615982 100644
--- a/src/middleware.ts
+++ b/src/middleware.ts
@@ -10,6 +10,7 @@ const protectedRoutes = [
'/plan',
'/knowledge',
'/analysis',
+ '/tasks',
];
const authRoutes = ['/login', '/register', '/reset-password'];
@@ -43,6 +44,7 @@ export const config = {
'/plan/:path*',
'/knowledge/:path*',
'/analysis/:path*',
+ '/tasks/:path*',
'/login',
'/register',
'/reset-password/:path*',
diff --git a/src/prisma/migrations/20260503010000_add_performance_indexes/migration.sql b/src/prisma/migrations/20260503010000_add_performance_indexes/migration.sql
new file mode 100644
index 0000000..a9cf842
--- /dev/null
+++ b/src/prisma/migrations/20260503010000_add_performance_indexes/migration.sql
@@ -0,0 +1,10 @@
+CREATE INDEX "WrongNote_userId_markedMastered_updatedAt_idx" ON "WrongNote"("userId", "markedMastered", "updatedAt");
+CREATE INDEX "WrongNote_userId_updatedAt_idx" ON "WrongNote"("userId", "updatedAt");
+
+CREATE INDEX "AIImageGeneration_userId_updatedAt_idx" ON "AIImageGeneration"("userId", "updatedAt");
+CREATE INDEX "AIImageGeneration_userId_status_updatedAt_idx" ON "AIImageGeneration"("userId", "status", "updatedAt");
+CREATE INDEX "AIImageGeneration_userId_wrongNoteId_updatedAt_idx" ON "AIImageGeneration"("userId", "wrongNoteId", "updatedAt");
+
+CREATE INDEX "AIExplanationGeneration_userId_wrongNoteId_updatedAt_idx" ON "AIExplanationGeneration"("userId", "wrongNoteId", "updatedAt");
+
+CREATE INDEX "StudyPlan_userId_createdAt_idx" ON "StudyPlan"("userId", "createdAt");
diff --git a/src/prisma/schema.prisma b/src/prisma/schema.prisma
index c202488..875687c 100644
--- a/src/prisma/schema.prisma
+++ b/src/prisma/schema.prisma
@@ -274,6 +274,8 @@ model WrongNote {
@@unique([userId, questionId])
@@index([userId, markedMastered])
+ @@index([userId, markedMastered, updatedAt])
+ @@index([userId, updatedAt])
@@index([questionId])
@@index([createdAt])
}
@@ -307,6 +309,9 @@ model AIImageGeneration {
wrongNote WrongNote? @relation(fields: [wrongNoteId], references: [id], onDelete: SetNull)
@@index([userId, createdAt])
+ @@index([userId, updatedAt])
+ @@index([userId, status, updatedAt])
+ @@index([userId, wrongNoteId, updatedAt])
@@index([questionId])
@@index([wrongNoteId, status, createdAt])
@@index([fingerprint])
@@ -331,6 +336,7 @@ model AIExplanationGeneration {
wrongNote WrongNote? @relation(fields: [wrongNoteId], references: [id], onDelete: SetNull)
@@index([userId, createdAt])
+ @@index([userId, wrongNoteId, updatedAt])
@@index([questionId])
@@index([wrongNoteId, status, createdAt])
}
@@ -459,6 +465,7 @@ model StudyPlan {
days StudyPlanDay[]
@@index([userId, status])
+ @@index([userId, createdAt])
@@index([targetExamDate])
}