diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs index f33af13..ce99464 100644 --- a/ecosystem.config.cjs +++ b/ecosystem.config.cjs @@ -10,5 +10,22 @@ module.exports = { autorestart: true, max_memory_restart: "512M", log_date_format: "YYYY-MM-DD HH:mm:ss", + watch: ["src", "scripts", "package.json", "next.config.ts", ".env"], + watch_delay: 1000, + watch_options: { + followSymlinks: false, + usePolling: true, + interval: 1000, + }, + ignore_watch: [ + "node_modules", + ".next", + ".git", + "logs", + "dist", + "build", + "coverage", + "public", + ], }], }; diff --git a/public/icon-192.png b/public/icon-192.png new file mode 100644 index 0000000..a0ebeb2 Binary files /dev/null and b/public/icon-192.png differ diff --git a/public/icon-512.png b/public/icon-512.png new file mode 100644 index 0000000..4f29252 Binary files /dev/null and b/public/icon-512.png differ diff --git a/public/manifest.json b/public/manifest.json new file mode 100644 index 0000000..e005065 --- /dev/null +++ b/public/manifest.json @@ -0,0 +1,21 @@ +{ + "name": "LLM Proxy", + "short_name": "LLM Proxy", + "description": "Multi-provider LLM chat interface", + "start_url": "/chat", + "display": "standalone", + "background_color": "#0a0b0f", + "theme_color": "#0a0b0f", + "icons": [ + { + "src": "/icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ] +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..40ca0c0 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,35 @@ +const CACHE_NAME = "llm-proxy-v1"; +const STATIC_ASSETS = ["/chat"]; + +self.addEventListener("install", (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS)) + ); + self.skipWaiting(); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches.keys().then((keys) => + Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))) + ) + ); + self.clients.claim(); +}); + +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url); + + // Network-first for API routes + if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/v1/")) { + event.respondWith( + fetch(event.request).catch(() => caches.match(event.request)) + ); + return; + } + + // Cache-first for static assets + event.respondWith( + caches.match(event.request).then((cached) => cached || fetch(event.request)) + ); +}); diff --git a/src/app/api/chat/conversations/[conversationId]/route.ts b/src/app/api/chat/conversations/[conversationId]/route.ts index fc4db78..1aeca11 100644 --- a/src/app/api/chat/conversations/[conversationId]/route.ts +++ b/src/app/api/chat/conversations/[conversationId]/route.ts @@ -25,6 +25,7 @@ export async function PATCH( const data: Record = {}; if (typeof body.title === "string") data.title = body.title.trim(); if (typeof body.model === "string") data.model = body.model.trim(); + if (typeof body.callDuration === "number") data.callDuration = body.callDuration; const updated = await db.chatConversation.update({ where: { id: conversationId }, data }); return NextResponse.json({ data: updated }); diff --git a/src/app/api/chat/conversations/route.ts b/src/app/api/chat/conversations/route.ts index ab6b4fe..5cab4c8 100644 --- a/src/app/api/chat/conversations/route.ts +++ b/src/app/api/chat/conversations/route.ts @@ -2,12 +2,18 @@ import { NextResponse } from "next/server"; import { getSession } from "@/lib/auth-helpers"; import { db } from "@/lib/db"; -export async function GET() { +export async function GET(req: Request) { const session = await getSession(); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + const { searchParams } = new URL(req.url); + const type = searchParams.get("type"); + + const where: Record = { userId: session.user.id }; + if (type) where.type = type; + const conversations = await db.chatConversation.findMany({ - where: { userId: session.user.id }, + where, orderBy: { updatedAt: "desc" }, take: 100, }); @@ -28,12 +34,16 @@ export async function POST(req: Request) { const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "New chat"; const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : ""; + const type = body.type === "call" ? "call" : "chat"; + const callDuration = typeof body.callDuration === "number" ? body.callDuration : undefined; const conversation = await db.chatConversation.create({ data: { userId: session.user.id, title, model, + type, + ...(callDuration != null ? { callDuration } : {}), }, }); diff --git a/src/app/api/chat/friends/[friendId]/memory/route.ts b/src/app/api/chat/friends/[friendId]/memory/route.ts new file mode 100644 index 0000000..2eb1dfb --- /dev/null +++ b/src/app/api/chat/friends/[friendId]/memory/route.ts @@ -0,0 +1,58 @@ +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/auth-helpers"; +import { db } from "@/lib/db"; + +// GET — returns the conversation messages (memory) for a friend +export async function GET( + _req: Request, + { params }: { params: Promise<{ friendId: string }> }, +) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const { friendId } = await params; + const friend = await db.friend.findUnique({ where: { id: friendId } }); + if (!friend || (friend as Record).userId !== session.user.id) { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + + const f = friend as Record; + if (!f.conversationId) { + return NextResponse.json({ data: { messages: [], messageCount: 0 } }); + } + + const messages = await db.chatMessage.findMany({ + where: { conversationId: f.conversationId as string }, + orderBy: { createdAt: "asc" }, + }); + + return NextResponse.json({ + data: { + conversationId: f.conversationId, + messages, + messageCount: (messages as unknown[]).length, + }, + }); +} + +// DELETE — clears all messages (resets memory) but keeps the conversation +export async function DELETE( + _req: Request, + { params }: { params: Promise<{ friendId: string }> }, +) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const { friendId } = await params; + const friend = await db.friend.findUnique({ where: { id: friendId } }); + if (!friend || (friend as Record).userId !== session.user.id) { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + + const f = friend as Record; + if (f.conversationId) { + await db.chatMessage.deleteMany({ where: { conversationId: f.conversationId as string } }); + } + + return NextResponse.json({ ok: true }); +} diff --git a/src/app/api/chat/friends/[friendId]/route.ts b/src/app/api/chat/friends/[friendId]/route.ts new file mode 100644 index 0000000..1fea62d --- /dev/null +++ b/src/app/api/chat/friends/[friendId]/route.ts @@ -0,0 +1,84 @@ +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/auth-helpers"; +import { db } from "@/lib/db"; + +export async function GET( + _req: Request, + { params }: { params: Promise<{ friendId: string }> }, +) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const { friendId } = await params; + const friend = await db.friend.findUnique({ where: { id: friendId } }); + if (!friend || (friend as Record).userId !== session.user.id) { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + + return NextResponse.json({ data: friend }); +} + +export async function PATCH( + req: Request, + { params }: { params: Promise<{ friendId: string }> }, +) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const { friendId } = await params; + const friend = await db.friend.findUnique({ where: { id: friendId } }); + if (!friend || (friend as Record).userId !== session.user.id) { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + + let body: Record; + try { + body = (await req.json()) as Record; + } catch { + return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); + } + + const data: Record = {}; + if (typeof body.name === "string") data.name = body.name.trim(); + if (typeof body.modelId === "string") data.modelId = body.modelId.trim(); + if (typeof body.systemPrompt === "string") data.systemPrompt = body.systemPrompt; + if (typeof body.characterStyle === "string") data.characterStyle = body.characterStyle; + if (typeof body.avatarColor === "string") data.avatarColor = body.avatarColor; + if (body.voiceSettings && typeof body.voiceSettings === "object") data.voiceSettings = body.voiceSettings; + + // Create conversation for friend if it doesn't have one yet + const f = friend as Record; + if (body.ensureConversation && !f.conversationId) { + const conv = await db.chatConversation.create({ + data: { userId: session.user.id, model: (f.modelId as string) || "", title: `Chat with ${f.name as string}`, type: "chat" }, + }); + data.conversationId = (conv as Record).id; + } + + const updated = await db.friend.update({ where: { id: friendId }, data }); + return NextResponse.json({ data: updated }); +} + +export async function DELETE( + _req: Request, + { params }: { params: Promise<{ friendId: string }> }, +) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const { friendId } = await params; + const friend = await db.friend.findUnique({ where: { id: friendId } }); + if (!friend || (friend as Record).userId !== session.user.id) { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + + // Delete associated conversation and messages + const f = friend as Record; + if (f.conversationId) { + await db.chatMessage.deleteMany({ where: { conversationId: f.conversationId as string } }); + await db.chatConversation.delete({ where: { id: f.conversationId as string } }).catch(() => {}); + } + + await db.friend.delete({ where: { id: friendId } }); + return NextResponse.json({ ok: true }); +} diff --git a/src/app/api/chat/friends/route.ts b/src/app/api/chat/friends/route.ts new file mode 100644 index 0000000..ea47c64 --- /dev/null +++ b/src/app/api/chat/friends/route.ts @@ -0,0 +1,58 @@ +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/auth-helpers"; +import { db } from "@/lib/db"; + +export async function GET() { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const friends = await db.friend.findMany({ + where: { userId: session.user.id }, + orderBy: { createdAt: "desc" }, + }); + + return NextResponse.json({ data: friends }); +} + +export async function POST(req: Request) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + let body: Record; + try { + body = (await req.json()) as Record; + } catch { + return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); + } + + const name = typeof body.name === "string" ? body.name.trim() : ""; + const modelId = typeof body.modelId === "string" ? body.modelId.trim() : ""; + if (!name || !modelId) { + return NextResponse.json({ error: "name and modelId are required" }, { status: 400 }); + } + + // Create a persistent conversation for this friend + const conversation = await db.chatConversation.create({ + data: { + userId: session.user.id, + title: `Chat with ${name}`, + model: modelId, + type: "chat", + }, + }); + + const friend = await db.friend.create({ + data: { + userId: session.user.id, + name, + modelId, + systemPrompt: typeof body.systemPrompt === "string" ? body.systemPrompt : undefined, + characterStyle: typeof body.characterStyle === "string" ? body.characterStyle : undefined, + avatarColor: typeof body.avatarColor === "string" ? body.avatarColor : undefined, + voiceSettings: body.voiceSettings && typeof body.voiceSettings === "object" ? body.voiceSettings : undefined, + conversationId: conversation.id, + }, + }); + + return NextResponse.json({ data: friend }, { status: 201 }); +} diff --git a/src/app/api/chat/generate/route.ts b/src/app/api/chat/generate/route.ts new file mode 100644 index 0000000..33460c7 --- /dev/null +++ b/src/app/api/chat/generate/route.ts @@ -0,0 +1,68 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { getSession } from "@/lib/auth-helpers"; +import { db } from "@/lib/db"; +import { resolveModelRouteCandidates } from "@/server/services/model-router"; +import { checkRateLimit } from "@/server/services/rate-limiter"; +import { ApiError, rateLimitExceeded, modelNotFound, internalError } from "@/lib/api-error"; +import type { UnifiedChatRequest } from "@/types/unified-request"; + +const schema = z.object({ + model: z.string().min(1), + messages: z.array(z.object({ role: z.enum(["user", "assistant", "system"]), content: z.string() })).min(1), + max_tokens: z.number().int().min(1).max(4000).optional(), +}); + +/** Lightweight non-streaming chat completion for internal UI use (e.g. voice previews). */ +export async function POST(req: Request) { + const session = await getSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + let body: unknown; + try { body = await req.json(); } catch { return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); } + + const parsed = schema.safeParse(body); + if (!parsed.success) return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 }); + + const apiKeys = await db.userApiKey.findMany({ + where: { userId: session.user.id }, + orderBy: { createdAt: "asc" }, + select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true }, + }); + type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null }; + const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null; + if (!apiKey) return NextResponse.json({ error: "No active API key" }, { status: 400 }); + + const sub = await db.subscription.findUnique({ where: { userId: session.user.id }, include: { plan: true } }) as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null; + if (!sub?.plan) return NextResponse.json({ error: "No subscription" }, { status: 403 }); + + const limits = { + dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null, + dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null, + dailyCostCents: apiKey.softCostLimitCents ?? null, + }; + const rl = await checkRateLimit(apiKey.id, limits); + if (!rl.allowed) return rateLimitExceeded(rl.reason!, rl.retryAfter!); + + const routes = await resolveModelRouteCandidates(parsed.data.model); + if (routes.length === 0) return modelNotFound(parsed.data.model).toResponse(); + + const unifiedReq: UnifiedChatRequest = { + model: parsed.data.model, + messages: parsed.data.messages, + stream: false, + max_tokens: parsed.data.max_tokens ?? 150, + }; + + for (const route of routes) { + try { + const result = await route.adapter.chatCompletion(unifiedReq, route.ctx); + return NextResponse.json(result); + } catch (error) { + if (error instanceof ApiError && (error.statusCode === 429 || error.statusCode >= 500)) continue; + if (error instanceof ApiError) return error.toResponse(); + } + } + + return internalError().toResponse(); +} diff --git a/src/app/chat/page.tsx b/src/app/chat/page.tsx index a24ec9e..647e2e5 100644 --- a/src/app/chat/page.tsx +++ b/src/app/chat/page.tsx @@ -1,1897 +1,32 @@ "use client"; -import { FormEvent, useCallback, useEffect, useRef, useState } from "react"; -import Link from "next/link"; -import { toast } from "sonner"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import { - ArrowUp, - Check, - ChevronDown, - Download, - EyeOff, - Image as ImageIcon, - LayoutDashboard, - Mic, - Palette, - Pause, - Play, - MessageSquare, - Plus, - Settings, - Sparkles, - Square, - Star, - Trash2, - X, -} from "lucide-react"; -import { cn } from "@/lib/utils"; - -// ── Types ──────────────────────────────────────────────── - -type ModelType = "chat" | "image" | "audio"; - -interface ModelOption { - id: string; - providerId: string; - modelType: ModelType; -} - -interface ImagePart { - type: "image_url"; - image_url: { url: string; detail?: string }; -} - -interface ChatMessage { - id?: string; - role: "user" | "assistant"; - content: string; - images?: ImagePart[]; - generatedImages?: Array<{ b64_json?: string; url?: string; revised_prompt?: string }>; - audioB64?: string; - audioContentType?: string; - model?: string; - providerId?: string; - tokensIn?: number; - tokensOut?: number; - createdAt?: string; -} - -interface Conversation { - id: string; - title: string; - model: string; - updatedAt: string; -} - -// ── SSE parser helper ──────────────────────────────────── - -function parseSSELines(buffer: string): { events: Array<{ event?: string; data: string }>; remaining: string } { - const events: Array<{ event?: string; data: string }> = []; - const lines = buffer.split("\n"); - let currentEvent: string | undefined; - let currentData: string[] = []; - let lastProcessed = 0; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - - if (line.startsWith("event: ")) { - currentEvent = line.slice(7).trim(); - } else if (line.startsWith("data: ")) { - currentData.push(line.slice(6)); - } else if (line === "" && currentData.length > 0) { - events.push({ event: currentEvent, data: currentData.join("\n") }); - currentEvent = undefined; - currentData = []; - lastProcessed = i + 1; - } else if (line === "") { - lastProcessed = i + 1; - } - } - - // Return unprocessed trailing text as remaining - const remaining = lines.slice(lastProcessed).join("\n"); - return { events, remaining }; -} - -// ── Model menu item ────────────────────────────────────── - -function ModelMenuItem({ - m, - model, - isDefault, - isFavourite, - onSelect, - onToggleFav, - onSetDefault, -}: { - m: ModelOption; - model: string; - isDefault: boolean; - isFavourite: boolean; - onSelect: () => void; - onToggleFav: () => void; - onSetDefault: () => void; -}) { - return ( -
- - {m.providerId} - - -
- ); -} - -// ── Custom audio player with waveform ──────────────────── - -function AudioPlayer({ src }: { src: string }) { - const audioRef = useRef(null); - const canvasRef = useRef(null); - const animFrameRef = useRef(0); - const [playing, setPlaying] = useState(false); - const [progress, setProgress] = useState(0); - const [duration, setDuration] = useState(0); - const [bars, setBars] = useState([]); - const barsCount = 48; - - // Generate deterministic waveform bars from audio data - useEffect(() => { - // Generate pseudo-random bars from src hash - const seed = src.length; - const generated: number[] = []; - for (let i = 0; i < barsCount; i++) { - const sin1 = Math.sin(i * 0.4 + seed * 0.01) * 0.3; - const sin2 = Math.sin(i * 0.15 + seed * 0.007) * 0.25; - const sin3 = Math.sin(i * 0.8 + seed * 0.003) * 0.15; - const base = 0.15 + Math.abs(sin1 + sin2 + sin3); - // Envelope: taper at edges - const envelope = Math.sin((i / (barsCount - 1)) * Math.PI); - generated.push(Math.max(0.08, Math.min(1, base * (0.4 + envelope * 0.6)))); - } - setBars(generated); - }, [src]); - - // Decode actual audio waveform for more accurate visualization - useEffect(() => { - async function decode() { - try { - const response = await fetch(src); - const arrayBuffer = await response.arrayBuffer(); - const audioCtx = new AudioContext(); - const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer); - const channelData = audioBuffer.getChannelData(0); - const samplesPerBar = Math.floor(channelData.length / barsCount); - const decoded: number[] = []; - for (let i = 0; i < barsCount; i++) { - let sum = 0; - const start = i * samplesPerBar; - for (let j = start; j < start + samplesPerBar && j < channelData.length; j++) { - sum += Math.abs(channelData[j]); - } - decoded.push(sum / samplesPerBar); - } - // Normalize - const max = Math.max(...decoded, 0.001); - setBars(decoded.map((v) => Math.max(0.08, v / max))); - audioCtx.close(); - } catch { - // Keep the generated bars as fallback - } - } - decode(); - }, [src]); - - useEffect(() => { - const audio = audioRef.current; - if (!audio) return; - - const onTime = () => { - if (audio.duration) { - setProgress(audio.currentTime / audio.duration); - } - }; - const onMeta = () => setDuration(audio.duration || 0); - const onEnd = () => { setPlaying(false); setProgress(0); }; - - audio.addEventListener("timeupdate", onTime); - audio.addEventListener("loadedmetadata", onMeta); - audio.addEventListener("ended", onEnd); - return () => { - audio.removeEventListener("timeupdate", onTime); - audio.removeEventListener("loadedmetadata", onMeta); - audio.removeEventListener("ended", onEnd); - }; - }, []); - - // Draw waveform - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas || !bars.length) return; - const ctx = canvas.getContext("2d"); - if (!ctx) return; - - function draw() { - const dpr = window.devicePixelRatio || 1; - const rect = canvas!.getBoundingClientRect(); - canvas!.width = rect.width * dpr; - canvas!.height = rect.height * dpr; - ctx!.scale(dpr, dpr); - - const w = rect.width; - const h = rect.height; - ctx!.clearRect(0, 0, w, h); - - const barWidth = Math.max(2, (w / bars.length) * 0.6); - const gap = (w - barWidth * bars.length) / (bars.length - 1 || 1); - const progressIndex = progress * bars.length; - - for (let i = 0; i < bars.length; i++) { - const x = i * (barWidth + gap); - const barH = Math.max(3, bars[i] * (h - 4)); - const y = (h - barH) / 2; - const radius = Math.min(barWidth / 2, 2); - - if (i < progressIndex) { - // Played — emerald gradient - const grad = ctx!.createLinearGradient(x, y, x, y + barH); - grad.addColorStop(0, "rgba(52, 211, 153, 0.95)"); - grad.addColorStop(1, "rgba(16, 185, 129, 0.7)"); - ctx!.fillStyle = grad; - } else { - // Unplayed — dim - ctx!.fillStyle = "rgba(255, 255, 255, 0.12)"; - } - - // Rounded rect - ctx!.beginPath(); - ctx!.moveTo(x + radius, y); - ctx!.lineTo(x + barWidth - radius, y); - ctx!.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius); - ctx!.lineTo(x + barWidth, y + barH - radius); - ctx!.quadraticCurveTo(x + barWidth, y + barH, x + barWidth - radius, y + barH); - ctx!.lineTo(x + radius, y + barH); - ctx!.quadraticCurveTo(x, y + barH, x, y + barH - radius); - ctx!.lineTo(x, y + radius); - ctx!.quadraticCurveTo(x, y, x + radius, y); - ctx!.closePath(); - ctx!.fill(); - } - - animFrameRef.current = requestAnimationFrame(draw); - } - - draw(); - return () => cancelAnimationFrame(animFrameRef.current); - }, [bars, progress]); - - function togglePlay() { - const audio = audioRef.current; - if (!audio) return; - if (playing) { - audio.pause(); - setPlaying(false); - } else { - audio.play(); - setPlaying(true); - } - } - - function seekFromClick(e: React.MouseEvent) { - const audio = audioRef.current; - const canvas = canvasRef.current; - if (!audio || !canvas || !audio.duration) return; - const rect = canvas.getBoundingClientRect(); - const pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); - audio.currentTime = pct * audio.duration; - setProgress(pct); - } - - function formatTime(s: number) { - if (!s || !isFinite(s)) return "0:00"; - const m = Math.floor(s / 60); - const sec = Math.floor(s % 60); - return `${m}:${sec.toString().padStart(2, "0")}`; - } - - return ( -
-
- ); -} - -// ── Markdown renderer ──────────────────────────────────── - -function MarkdownContent({ content }: { content: string }) { - return ( -
-

{children}

, - h1: ({ children }) =>

{children}

, - h2: ({ children }) =>

{children}

, - h3: ({ children }) =>

{children}

, - ul: ({ children }) =>
    {children}
, - ol: ({ children }) =>
    {children}
, - li: ({ children }) =>
  • {children}
  • , - blockquote: ({ children }) => ( -
    - {children} -
    - ), - code: ({ className, children, ...props }) => { - const isBlock = className?.includes("language-"); - if (isBlock) { - const lang = className?.replace("language-", "") ?? ""; - return ( -
    - {lang && ( -
    - {lang} - -
    - )} -
    -                    {children}
    -                  
    -
    - ); - } - return ( - - {children} - - ); - }, - pre: ({ children }) => <>{children}, - img: ({ src, alt }) => ( - {alt - ), - a: ({ href, children }) => ( - - {children} - - ), - table: ({ children }) => ( -
    - {children}
    -
    - ), - thead: ({ children }) => {children}, - th: ({ children }) => {children}, - td: ({ children }) => {children}, - hr: () =>
    , - strong: ({ children }) => {children}, - }} - > - {content} -
    -
    - ); -} - -// ── Component ──────────────────────────────────────────── +import { useEffect } from "react"; +import { useChatEngine } from "@/components/chat/useChatEngine"; +import { useUIMode } from "@/components/chat/useUIMode"; +import { CustomCSSInjector } from "@/components/chat/CustomCSSInjector"; +import { ClassicChatUI } from "@/components/chat/ClassicChatUI"; +import { MessengerUI } from "@/components/chat/alt/MessengerUI"; +import { VirtualPhoneUI } from "@/components/chat/alt/VirtualPhoneUI"; +import { applyOSAttribute } from "@/lib/detect-os"; export default function ChatPage() { - // Models - const [models, setModels] = useState([]); - const [model, setModel] = useState(""); - const [modelMenuOpen, setModelMenuOpen] = useState(false); - const [modelSearch, setModelSearch] = useState(""); + const engine = useChatEngine(); + const { mode, setMode, toggleAltMode } = useUIMode(); - // Preferences - const [favourites, setFavourites] = useState([]); - const [defaultModel, setDefaultModel] = useState(""); - - // Conversations - const [conversations, setConversations] = useState([]); - const [activeConversationId, setActiveConversationId] = useState(null); - const [messages, setMessages] = useState([]); - - // Input - const [input, setInput] = useState(""); - const [submitting, setSubmitting] = useState(false); - const [streamingText, setStreamingText] = useState(""); - const [streamingProviderId, setStreamingProviderId] = useState(); - const abortRef = useRef(null); - const fileInputRef = useRef(null); - const [pendingImages, setPendingImages] = useState([]); - - // Incognito - const [incognito, setIncognito] = useState(false); - const [incognitoHistory, setIncognitoHistory] = useState([]); - - // UI - const [sidebarOpen, setSidebarOpen] = useState(true); - const [settingsOpen, setSettingsOpen] = useState(false); - const scrollRef = useRef(null); - const textareaRef = useRef(null); - - // Advanced settings — chat - const [systemPrompt, setSystemPrompt] = useState(""); - const [temperature, setTemperature] = useState(null); - const [maxTokens, setMaxTokens] = useState(null); - const [topP, setTopP] = useState(null); - const [frequencyPenalty, setFrequencyPenalty] = useState(null); - const [presencePenalty, setPresencePenalty] = useState(null); - - // Advanced settings — audio (OpenAI) - const [audioVoice, setAudioVoice] = useState("alloy"); - const [audioSpeed, setAudioSpeed] = useState(1); - - // Advanced settings — audio (ElevenLabs) - const [elevenVoiceId, setElevenVoiceId] = useState(""); - const [elevenStability, setElevenStability] = useState(0.5); - const [elevenSimilarityBoost, setElevenSimilarityBoost] = useState(0.75); - const [elevenStyle, setElevenStyle] = useState(0); - const [elevenSpeed, setElevenSpeed] = useState(1); - const [elevenVoices, setElevenVoices] = useState>([]); - - // Advanced settings — image - const [imageSize, setImageSize] = useState("1024x1024"); - const [imageQuality, setImageQuality] = useState("auto"); - const [imageStyle, setImageStyle] = useState("vivid"); - const [imageN, setImageN] = useState(1); - - const currentMessages = incognito ? incognitoHistory : messages; - - // ── Load models + preferences ────────────────────────── useEffect(() => { - Promise.all([ - fetch("/api/dashboard/playground").then((r) => (r.ok ? r.json() : null)), - fetch("/api/chat/preferences").then((r) => (r.ok ? r.json() : null)), - ]).then(([modelsData, prefsData]) => { - const modelList: ModelOption[] = modelsData?.data ?? []; - setModels(modelList); - - const prefs = prefsData?.data as { defaultModel?: string; favouriteModels?: string[]; chatSettings?: Record } | undefined; - const favs = prefs?.favouriteModels ?? []; - const defModel = prefs?.defaultModel ?? ""; - setFavourites(favs); - setDefaultModel(defModel); - - // Restore chat settings - const cs = prefs?.chatSettings; - if (cs) { - if (typeof cs.systemPrompt === "string") setSystemPrompt(cs.systemPrompt); - if (typeof cs.temperature === "number") setTemperature(cs.temperature); - if (typeof cs.maxTokens === "number") setMaxTokens(cs.maxTokens); - if (typeof cs.topP === "number") setTopP(cs.topP); - if (typeof cs.frequencyPenalty === "number") setFrequencyPenalty(cs.frequencyPenalty); - if (typeof cs.presencePenalty === "number") setPresencePenalty(cs.presencePenalty); - if (typeof cs.audioVoice === "string") setAudioVoice(cs.audioVoice); - if (typeof cs.audioSpeed === "number") setAudioSpeed(cs.audioSpeed); - if (typeof cs.voiceId === "string") setElevenVoiceId(cs.voiceId); - if (typeof cs.stability === "number") setElevenStability(cs.stability); - if (typeof cs.similarityBoost === "number") setElevenSimilarityBoost(cs.similarityBoost); - if (typeof cs.audioStyle === "number") setElevenStyle(cs.audioStyle); - if (typeof cs.imageSize === "string") setImageSize(cs.imageSize); - if (typeof cs.imageQuality === "string") setImageQuality(cs.imageQuality); - if (typeof cs.imageStyle === "string") setImageStyle(cs.imageStyle); - if (typeof cs.imageN === "number") setImageN(cs.imageN); - } - - // Set initial model: default > first favourite > first model - if (!model) { - const initial = - (defModel && modelList.some((m) => m.id === defModel) ? defModel : "") || - favs.find((f) => modelList.some((m) => m.id === f)) || - modelList[0]?.id || - ""; - setModel(initial); - } - }).catch(() => {}); - }, []); // eslint-disable-line react-hooks/exhaustive-deps - - // ── Save preferences helper ──────────────────────────── - const savePreferences = useCallback( - async (newFavs: string[], newDefault: string) => { - setFavourites(newFavs); - setDefaultModel(newDefault); - await fetch("/api/chat/preferences", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ favouriteModels: newFavs, defaultModel: newDefault }), - }).catch(() => {}); - }, - [], - ); - - const saveChatSettings = useCallback(() => { - const chatSettings: Record = {}; - if (systemPrompt) chatSettings.systemPrompt = systemPrompt; - if (temperature !== null) chatSettings.temperature = temperature; - if (maxTokens !== null) chatSettings.maxTokens = maxTokens; - if (topP !== null) chatSettings.topP = topP; - if (frequencyPenalty !== null) chatSettings.frequencyPenalty = frequencyPenalty; - if (presencePenalty !== null) chatSettings.presencePenalty = presencePenalty; - chatSettings.audioVoice = audioVoice; - chatSettings.audioSpeed = audioSpeed; - if (elevenVoiceId) chatSettings.voiceId = elevenVoiceId; - chatSettings.stability = elevenStability; - chatSettings.similarityBoost = elevenSimilarityBoost; - chatSettings.audioStyle = elevenStyle; - chatSettings.imageSize = imageSize; - chatSettings.imageQuality = imageQuality; - chatSettings.imageStyle = imageStyle; - chatSettings.imageN = imageN; - fetch("/api/chat/preferences", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ chatSettings }), - }).catch(() => {}); - }, [systemPrompt, temperature, maxTokens, topP, frequencyPenalty, presencePenalty, audioVoice, audioSpeed, elevenVoiceId, elevenStability, elevenSimilarityBoost, elevenStyle, imageSize, imageQuality, imageStyle, imageN]); - - // Load ElevenLabs voices when an ElevenLabs model is selected - useEffect(() => { - const m = models.find((mod) => mod.id === model); - if (m?.providerId === "elevenlabs" && elevenVoices.length === 0) { - fetch("/api/chat/elevenlabs-voices") - .then((r) => (r.ok ? r.json() : null)) - .then((data) => { - if (data?.voices?.length) { - setElevenVoices(data.voices); - if (!elevenVoiceId && data.voices[0]) setElevenVoiceId(data.voices[0].voice_id); - } - }) - .catch(() => {}); - } - }, [model, models, elevenVoices.length, elevenVoiceId]); - - function toggleFavourite(modelId: string) { - const next = favourites.includes(modelId) - ? favourites.filter((f) => f !== modelId) - : [...favourites, modelId]; - // If unfavouriting the default model, clear default - const nextDefault = !next.includes(defaultModel) && defaultModel === modelId ? "" : defaultModel; - savePreferences(next, nextDefault); - } - - function setAsDefault(modelId: string) { - const nextDefault = defaultModel === modelId ? "" : modelId; - // Auto-favourite when setting as default - const nextFavs = nextDefault && !favourites.includes(modelId) ? [...favourites, modelId] : favourites; - savePreferences(nextFavs, nextDefault); - } - - // Sorted models: default first, then favourites, then rest - const sortedModels = [...models].sort((a, b) => { - const aDefault = a.id === defaultModel ? 0 : 1; - const bDefault = b.id === defaultModel ? 0 : 1; - if (aDefault !== bDefault) return aDefault - bDefault; - const aFav = favourites.includes(a.id) ? 0 : 1; - const bFav = favourites.includes(b.id) ? 0 : 1; - if (aFav !== bFav) return aFav - bFav; - return a.id.localeCompare(b.id); - }); - - const filteredModels = modelSearch - ? sortedModels.filter((m) => m.id.toLowerCase().includes(modelSearch.toLowerCase())) - : sortedModels; - - // ── Load conversations ───────────────────────────────── - const loadConversations = useCallback(async () => { - const res = await fetch("/api/chat/conversations"); - if (!res.ok) return; - const data = await res.json(); - setConversations(data.data ?? []); + applyOSAttribute(); }, []); - useEffect(() => { - loadConversations(); - }, [loadConversations]); - - // ── Load messages for active conversation ────────────── - useEffect(() => { - if (!activeConversationId || incognito) return; - fetch(`/api/chat/conversations/${activeConversationId}/messages`) - .then((r) => (r.ok ? r.json() : null)) - .then((data) => { - if (data?.data) setMessages(data.data); - }) - .catch(() => {}); - }, [activeConversationId, incognito]); - - // ── Auto scroll ──────────────────────────────────────── - useEffect(() => { - requestAnimationFrame(() => { - scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" }); - }); - }, [currentMessages, submitting, streamingText]); - - // ── Auto resize textarea ────────────────────────────── - useEffect(() => { - const el = textareaRef.current; - if (!el) return; - el.style.height = "auto"; - el.style.height = Math.min(el.scrollHeight, 200) + "px"; - }, [input]); - - // ── Image helpers ──────────────────────────────────────── - function fileToBase64(file: File): Promise { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result as string); - reader.onerror = reject; - reader.readAsDataURL(file); - }); - } - - async function addImageFiles(files: FileList | File[]) { - const allowed = ["image/png", "image/jpeg", "image/gif", "image/webp"]; - const maxSize = 20 * 1024 * 1024; // 20 MB - const newParts: ImagePart[] = []; - for (const file of Array.from(files)) { - if (!allowed.includes(file.type)) { - toast.error(`Unsupported file type: ${file.type}`); - continue; - } - if (file.size > maxSize) { - toast.error(`File too large: ${file.name} (max 20 MB)`); - continue; - } - const dataUrl = await fileToBase64(file); - newParts.push({ type: "image_url", image_url: { url: dataUrl } }); - } - if (newParts.length) { - setPendingImages((prev) => [...prev, ...newParts].slice(0, 10)); - } - } - - function removePendingImage(index: number) { - setPendingImages((prev) => prev.filter((_, i) => i !== index)); - } - - // ── New chat ─────────────────────────────────────────── - function newChat() { - if (incognito) { - setIncognitoHistory([]); - return; - } - setActiveConversationId(null); - setMessages([]); - } - - // ── Select conversation ──────────────────────────────── - function selectConversation(conv: Conversation) { - if (incognito) setIncognito(false); - setActiveConversationId(conv.id); - if (conv.model) setModel(conv.model); - } - - // ── Delete conversation ──────────────────────────────── - async function deleteConversation(id: string) { - await fetch(`/api/chat/conversations/${id}`, { method: "DELETE" }); - if (activeConversationId === id) { - setActiveConversationId(null); - setMessages([]); - } - loadConversations(); - } - - // ── Toggle incognito ─────────────────────────────────── - function toggleIncognito() { - if (!incognito) { - setIncognito(true); - setIncognitoHistory([]); - } else { - setIncognito(false); - } - } - - // ── Stop generation ──────────────────────────────────── - function stopGeneration() { - abortRef.current?.abort(); - } - - // ── Read SSE stream ──────────────────────────────────── - async function readStream(response: Response, onToken: (token: string) => void): Promise<{ - fullText: string; - providerId?: string; - tokensIn?: number; - tokensOut?: number; - }> { - const reader = response.body!.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - let fullText = ""; - let providerId: string | undefined; - let tokensIn: number | undefined; - let tokensOut: number | undefined; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - - buffer += decoder.decode(value, { stream: true }); - const { events, remaining } = parseSSELines(buffer); - buffer = remaining; - - for (const evt of events) { - if (evt.event === "meta") { - try { - const meta = JSON.parse(evt.data); - if (meta.providerId) providerId = meta.providerId; - } catch { /* skip */ } - continue; - } - - if (evt.event === "done") { - try { - const meta = JSON.parse(evt.data); - if (meta.tokensIn != null) tokensIn = meta.tokensIn; - if (meta.tokensOut != null) tokensOut = meta.tokensOut; - } catch { /* skip */ } - continue; - } - - if (evt.data === "[DONE]") continue; - - try { - const json = JSON.parse(evt.data); - const delta = json.choices?.[0]?.delta; - if (delta?.content) { - fullText += delta.content; - onToken(delta.content); - } - } catch { - // skip non-JSON lines - } - } - } - - return { fullText, providerId, tokensIn, tokensOut }; - } - - // ── Image/Audio generation helpers ─────────────────────── - async function handleImageGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages | typeof setIncognitoHistory, convId: string | null) { - try { - const res = await fetch("/api/chat/generate-image", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model, prompt: userContent, size: imageSize, quality: imageQuality, style: imageStyle, n: imageN }), - signal: abort.signal, - }); - if (!res.ok) { - const err = await res.json().catch(() => null); - toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Image generation failed"); - msgSetter((prev) => prev.slice(0, -1)); - setInput(userContent); - return; - } - const data = await res.json(); - const assistantMsg: ChatMessage = { - role: "assistant", - content: data.images?.[0]?.revised_prompt || "Generated image", - generatedImages: data.images, - providerId: data.providerId, - model, - }; - msgSetter((prev) => [...prev, assistantMsg]); - - // Save to DB if not incognito - if (convId) { - await fetch(`/api/chat/conversations/${convId}/save`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - messages: [ - { role: "user", content: userContent }, - { role: "assistant", content: assistantMsg.content, model, providerId: data.providerId, generatedImages: data.images }, - ], - }), - }).catch(() => {}); - loadConversations(); - } - } catch (err) { - if ((err as Error).name !== "AbortError") { - toast.error("Image generation failed"); - msgSetter((prev) => prev.slice(0, -1)); - setInput(userContent); - } - } - } - - async function handleAudioGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages | typeof setIncognitoHistory, convId: string | null) { - try { - const res = await fetch("/api/chat/generate-audio", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - model, - input: userContent, - voice: audioVoice, - speed: audioSpeed, - ...(currentModel?.providerId === "elevenlabs" ? { - voice_id: elevenVoiceId || undefined, - stability: elevenStability, - similarity_boost: elevenSimilarityBoost, - style: elevenStyle, - speed: elevenSpeed, - } : {}), - }), - signal: abort.signal, - }); - if (!res.ok) { - const err = await res.json().catch(() => null); - toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Audio generation failed"); - msgSetter((prev) => prev.slice(0, -1)); - setInput(userContent); - return; - } - const data = await res.json(); - const assistantMsg: ChatMessage = { - role: "assistant", - content: "Generated audio", - audioB64: data.audio?.b64, - audioContentType: data.audio?.contentType ?? "audio/mpeg", - providerId: data.providerId, - model, - }; - msgSetter((prev) => [...prev, assistantMsg]); - - // Save to DB if not incognito - if (convId) { - await fetch(`/api/chat/conversations/${convId}/save`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - messages: [ - { role: "user", content: userContent }, - { role: "assistant", content: "Generated audio", model, providerId: data.providerId, audioB64: data.audio?.b64, audioContentType: data.audio?.contentType ?? "audio/mpeg" }, - ], - }), - }).catch(() => {}); - loadConversations(); - } - } catch (err) { - if ((err as Error).name !== "AbortError") { - toast.error("Audio generation failed"); - msgSetter((prev) => prev.slice(0, -1)); - setInput(userContent); - } - } - } - - // ── Send message ─────────────────────────────────────── - async function handleSubmit(e?: FormEvent) { - e?.preventDefault(); - if ((!input.trim() && !pendingImages.length) || !model || submitting) return; - - const userContent = input.trim() || (pendingImages.length ? "What's in this image?" : ""); - const userImages = pendingImages.length ? [...pendingImages] : undefined; - setInput(""); - setPendingImages([]); - setStreamingText(""); - setStreamingProviderId(undefined); - - const abort = new AbortController(); - abortRef.current = abort; - - // For image/audio models, use dedicated endpoints - if (currentModelType === "image" || currentModelType === "audio") { - const msgSetter = incognito ? setIncognitoHistory : setMessages; - const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages }; - msgSetter((prev) => [...prev, userMsg]); - setSubmitting(true); - - // Create conversation if not incognito and no active conversation - let convId: string | null = incognito ? null : activeConversationId; - if (!incognito && !convId) { - try { - const convRes = await fetch("/api/chat/conversations", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model }), - }); - if (convRes.ok) { - const convData = await convRes.json(); - convId = convData.data.id; - setActiveConversationId(convId); - } - } catch { /* continue without saving */ } - } - - if (currentModelType === "image") { - await handleImageGeneration(userContent, abort, msgSetter, convId); - } else { - await handleAudioGeneration(userContent, abort, msgSetter, convId); - } - - setStreamingText(""); - setSubmitting(false); - return; - } - - if (incognito) { - const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages }; - setIncognitoHistory((prev) => [...prev, userMsg]); - setSubmitting(true); - - try { - const res = await fetch("/api/chat/incognito", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - model, - message: userContent, - ...(userImages ? { images: userImages } : {}), - history: incognitoHistory.map((m) => ({ - role: m.role, - content: m.content, - ...(m.images ? { images: m.images } : {}), - })), - ...(systemPrompt ? { systemPrompt } : {}), - ...(temperature !== null ? { temperature } : {}), - ...(maxTokens !== null ? { maxTokens } : {}), - ...(topP !== null ? { topP } : {}), - ...(frequencyPenalty !== null ? { frequencyPenalty } : {}), - ...(presencePenalty !== null ? { presencePenalty } : {}), - }), - signal: abort.signal, - }); - - if (!res.ok || !res.body) { - const err = await res.json().catch(() => null); - toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Request failed"); - setIncognitoHistory((prev) => prev.slice(0, -1)); - setInput(userContent); - setSubmitting(false); - return; - } - - let accumulated = ""; - const result = await readStream(res, (token) => { - accumulated += token; - setStreamingText(accumulated); - }); - - setStreamingProviderId(result.providerId); - setIncognitoHistory((prev) => [ - ...prev, - { - role: "assistant", - content: result.fullText, - providerId: result.providerId, - model, - }, - ]); - } catch (err) { - if ((err as Error).name !== "AbortError") { - toast.error("Stream failed"); - setIncognitoHistory((prev) => prev.slice(0, -1)); - setInput(userContent); - } - } - - setStreamingText(""); - setSubmitting(false); - return; - } - - // Normal mode: create conversation if needed - let convId = activeConversationId; - if (!convId) { - const res = await fetch("/api/chat/conversations", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model }), - }); - if (!res.ok) { - toast.error("Failed to create conversation"); - return; - } - const data = await res.json(); - convId = data.data.id; - setActiveConversationId(convId); - } - - const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages }; - setMessages((prev) => [...prev, userMsg]); - setSubmitting(true); - - try { - const res = await fetch(`/api/chat/conversations/${convId}/messages`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - content: userContent, - model, - ...(userImages ? { images: userImages } : {}), - ...(systemPrompt ? { systemPrompt } : {}), - ...(temperature !== null ? { temperature } : {}), - ...(maxTokens !== null ? { maxTokens } : {}), - ...(topP !== null ? { topP } : {}), - ...(frequencyPenalty !== null ? { frequencyPenalty } : {}), - ...(presencePenalty !== null ? { presencePenalty } : {}), - }), - signal: abort.signal, - }); - - if (!res.ok || !res.body) { - const err = await res.json().catch(() => null); - toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Request failed"); - setMessages((prev) => prev.slice(0, -1)); - setInput(userContent); - setSubmitting(false); - return; - } - - let accumulated = ""; - const result = await readStream(res, (token) => { - accumulated += token; - setStreamingText(accumulated); - }); - - setStreamingProviderId(result.providerId); - - // Replace optimistic user message + add the full assistant message - setMessages((prev) => { - const updated = [...prev]; - // The last message is the optimistic user message; keep it - updated.push({ - role: "assistant", - content: result.fullText, - providerId: result.providerId, - model, - tokensIn: result.tokensIn, - tokensOut: result.tokensOut, - }); - return updated; - }); - - loadConversations(); - } catch (err) { - if ((err as Error).name !== "AbortError") { - toast.error("Stream failed"); - setMessages((prev) => prev.slice(0, -1)); - setInput(userContent); - } - } - - setStreamingText(""); - setSubmitting(false); - } - - // ── Group conversations by date ──────────────────────── - function groupConversations() { - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); - const yesterday = new Date(today.getTime() - 86400000); - const sevenDaysAgo = new Date(today.getTime() - 7 * 86400000); - const thirtyDaysAgo = new Date(today.getTime() - 30 * 86400000); - - const groups: { label: string; items: Conversation[] }[] = [ - { label: "Today", items: [] }, - { label: "Yesterday", items: [] }, - { label: "Previous 7 days", items: [] }, - { label: "Previous 30 days", items: [] }, - { label: "Older", items: [] }, - ]; - - for (const conv of conversations) { - const d = new Date(conv.updatedAt); - if (d >= today) groups[0].items.push(conv); - else if (d >= yesterday) groups[1].items.push(conv); - else if (d >= sevenDaysAgo) groups[2].items.push(conv); - else if (d >= thirtyDaysAgo) groups[3].items.push(conv); - else groups[4].items.push(conv); - } - - return groups.filter((g) => g.items.length > 0); - } - - const currentModel = models.find((m) => m.id === model); - const providerForModel = currentModel?.providerId; - const currentModelType: ModelType = currentModel?.modelType ?? "chat"; - return ( -
    - {/* ── Sidebar overlay for mobile ──────────────────── */} - {sidebarOpen && ( -
    setSidebarOpen(false)} /> + <> + + {mode === "messenger" ? ( + setMode("classic")} /> + ) : mode === "phone" ? ( + setMode("classic")} /> + ) : ( + )} - - {/* ── Sidebar ─────────────────────────────────────── */} - - - {/* ── Main area ───────────────────────────────────── */} -
    - {/* Top bar */} -
    -
    - - - {/* Model selector */} -
    - - {modelMenuOpen && ( - <> -
    { setModelMenuOpen(false); setModelSearch(""); }} /> -
    - {/* Search input */} -
    - setModelSearch(e.target.value)} - autoFocus - className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm text-foreground outline-none placeholder:text-muted-foreground/50 focus:border-blue-500/50" - /> -
    -
    - {/* Favourites section */} - {filteredModels.some((m) => favourites.includes(m.id)) && ( - <> -

    - Favourites -

    - {filteredModels - .filter((m) => favourites.includes(m.id)) - .map((m) => ( - { setModel(m.id); setModelMenuOpen(false); setModelSearch(""); }} - onToggleFav={() => toggleFavourite(m.id)} - onSetDefault={() => setAsDefault(m.id)} - /> - ))} -
    -

    - All Models -

    - - )} - {filteredModels - .filter((m) => !favourites.includes(m.id)) - .map((m) => ( - { setModel(m.id); setModelMenuOpen(false); setModelSearch(""); }} - onToggleFav={() => toggleFavourite(m.id)} - onSetDefault={() => setAsDefault(m.id)} - /> - ))} -
    -
    - - )} -
    - - {providerForModel && ( - via {providerForModel} - )} -
    - -
    - {incognito && ( -
    - - Incognito -
    - )} - -
    -
    - - {/* Advanced settings panel */} - {settingsOpen && ( -
    -
    - {currentModelType === "chat" && ( - <> -
    - -