Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions src/app/(main)/layout.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="ose-page px-4 pb-12 pt-4 md:px-6">
<DecorativeBackground />
<div className="relative z-10">
<SessionGuard />
<MainNav userName={session.user.name || "学习伙伴"} userEmail={session.user.email} />
<MainNav userName={session.user.name || '学习伙伴'} userEmail={session.user.email} />
<AIStatusProvider>
{children}
<AIAssistant />
<AIAssistantLoader />
</AIStatusProvider>
</div>
</div>
);
}

6 changes: 3 additions & 3 deletions src/app/api/ai/status/route.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/ai/task-queue/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
2 changes: 1 addition & 1 deletion src/app/api/wrong-notes/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
28 changes: 28 additions & 0 deletions src/components/ai-assistant-loader.tsx
Original file line number Diff line number Diff line change
@@ -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 <AIAssistant defaultOpen />;

return (
<div className="fixed bottom-4 right-4 z-50 md:bottom-5 md:right-5">
<button
onClick={() => setLoaded(true)}
className="flex h-14 w-14 items-center justify-center rounded-full bg-primary text-white shadow-lift transition hover:scale-105 hover:bg-primary-dark"
aria-label="打开 OSE 智能助手"
>
<Bot className="h-7 w-7" />
</button>
</div>
);
}
9 changes: 6 additions & 3 deletions src/components/ai-assistant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ChatSession[]>([]);
const [sessionsLoaded, setSessionsLoaded] = useState(false);
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [messages, setMessages] = useState<Message[]>(initialMessages);
const [input, setInput] = useState('');
Expand Down Expand Up @@ -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);
Expand All @@ -110,6 +112,7 @@ export function AIAssistant() {
: [];
if (!active) return;
setSessions(nextSessions);
setSessionsLoaded(true);
const latest = nextSessions[0];
if (latest) {
setActiveSessionId(latest.id);
Expand All @@ -120,7 +123,7 @@ export function AIAssistant() {
return () => {
active = false;
};
}, []);
}, [open, sessionsLoaded]);

async function saveSession(
nextMessages: Message[],
Expand Down
156 changes: 156 additions & 0 deletions src/lib/ai/config.ts
Original file line number Diff line number Diff line change
@@ -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<AIProviderKey, string | undefined> = {
claude: 'https://api.anthropic.com',
openai: 'https://api.openai.com/v1',
gemini: 'https://generativelanguage.googleapis.com',
custom: undefined,
};

const PROVIDER_NAMES: Record<AIProviderKey, string> = {
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<AIConfig | null> {
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);
}
3 changes: 3 additions & 0 deletions src/lib/ai/image-url.ts
Original file line number Diff line number Diff line change
@@ -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()}`;
}
Loading
Loading