Alternative UI + Voice Calls

This commit is contained in:
Zebratic committed 2026-03-03 04:14:57 +01:00
1 parent 3b17ae8b9b
commit 3757a2cead
56 files changed
+5610 -1887

No files matched your search

+17
View File
@@ -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",
],
}],
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 995 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

+21
View File
@@ -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"
}
]
}
+35
View File
@@ -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))
);
});
@@ -25,6 +25,7 @@ export async function PATCH(
const data: Record<string, unknown> = {};
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 });
+12 -2
View File
@@ -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<string, unknown> = { 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 } : {}),
},
});
@@ -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<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const f = friend as Record<string, unknown>;
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<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const f = friend as Record<string, unknown>;
if (f.conversationId) {
await db.chatMessage.deleteMany({ where: { conversationId: f.conversationId as string } });
}
return NextResponse.json({ ok: true });
}
@@ -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<string, unknown>).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<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
let body: Record<string, unknown>;
try {
body = (await req.json()) as Record<string, unknown>;
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const data: Record<string, unknown> = {};
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<string, unknown>;
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<string, unknown>).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<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
// Delete associated conversation and messages
const f = friend as Record<string, unknown>;
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 });
}
+58
View File
@@ -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<string, unknown>;
try {
body = (await req.json()) as Record<string, unknown>;
} 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 });
}
+68
View File
@@ -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();
}
+20 -1885
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -43,3 +43,34 @@
color: var(--color-foreground);
}
}
/* OS-specific font stacks for messenger/phone UIs */
[data-os="mac"] .messenger-ui,
[data-os="mac"] .phone-ui,
[data-os="ios"] .messenger-ui,
[data-os="ios"] .phone-ui {
font-family: -apple-system, "SF Pro Text", "SF Pro Display", system-ui, sans-serif;
}
[data-os="windows"] .messenger-ui,
[data-os="windows"] .phone-ui {
font-family: "Segoe UI", system-ui, sans-serif;
}
[data-os="linux"] .messenger-ui,
[data-os="linux"] .phone-ui {
font-family: system-ui, "Ubuntu", "Cantarell", "Noto Sans", sans-serif;
}
[data-os="android"] .messenger-ui,
[data-os="android"] .phone-ui {
font-family: "Roboto", system-ui, sans-serif;
}
/* Safe area insets for PWA */
@supports (padding: env(safe-area-inset-top)) {
.phone-ui {
padding-top: env(safe-area-inset-top);
padding-bottom: env(safe-area-inset-bottom);
}
}
+10
View File
@@ -1,20 +1,30 @@
import type { Metadata } from "next";
import { SessionProvider } from "@/components/layout/session-provider";
import { ServiceWorkerRegistrar } from "@/components/layout/ServiceWorkerRegistrar";
import { Toaster } from "sonner";
import "./globals.css";
export const metadata: Metadata = {
title: "LLM Proxy",
description: "Multi-provider OpenAI-compatible API gateway",
manifest: "/manifest.json",
other: {
"apple-mobile-web-app-capable": "yes",
"apple-mobile-web-app-status-bar-style": "black-translucent",
},
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning className="dark">
<head>
<meta name="theme-color" content="#0a0b0f" />
</head>
<body className="bg-background text-foreground antialiased font-[Inter,ui-sans-serif,system-ui,-apple-system,Segoe_UI,Roboto,Helvetica,Arial,sans-serif]">
<SessionProvider>
{children}
<Toaster richColors position="top-right" />
<ServiceWorkerRegistrar />
</SessionProvider>
</body>
</html>
+191
View File
@@ -0,0 +1,191 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Download, Pause, Play } from "lucide-react";
import { cn } from "@/lib/utils";
export function AudioPlayer({ src }: { src: string }) {
const audioRef = useRef<HTMLAudioElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const animFrameRef = useRef<number>(0);
const [playing, setPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const [duration, setDuration] = useState(0);
const [bars, setBars] = useState<number[]>([]);
const barsCount = 48;
useEffect(() => {
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);
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]);
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);
}
const max = Math.max(...decoded, 0.001);
setBars(decoded.map((v) => Math.max(0.08, v / max)));
audioCtx.close();
} catch {
// Keep generated bars
}
}
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);
};
}, []);
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) {
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 {
ctx!.fillStyle = "rgba(255, 255, 255, 0.12)";
}
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<HTMLCanvasElement>) {
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 (
<div className="max-w-md overflow-hidden rounded-2xl border border-white/[0.06] bg-gradient-to-br from-emerald-500/[0.08] to-teal-500/[0.04]">
<audio ref={audioRef} src={src} preload="metadata" />
<div className="flex items-center gap-3 px-4 py-4">
<button
onClick={togglePlay}
className={cn(
"flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-all",
playing
? "bg-emerald-500 text-white shadow-lg shadow-emerald-500/25"
: "bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25",
)}
>
{playing ? <Pause className="h-4 w-4" /> : <Play className="ml-0.5 h-4 w-4" />}
</button>
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
<canvas
ref={canvasRef}
onClick={seekFromClick}
className="h-10 w-full cursor-pointer"
style={{ imageRendering: "auto" }}
/>
<div className="flex items-center justify-between px-0.5 text-[10px] text-muted-foreground/60">
<span>{formatTime((duration || 0) * progress)}</span>
<span>{formatTime(duration)}</span>
</div>
</div>
<button
onClick={() => {
const a = document.createElement("a");
a.href = src;
a.download = "speech.mp3";
a.click();
}}
title="Download MP3"
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground/40 transition-colors hover:bg-white/[0.06] hover:text-foreground"
>
<Download className="h-3.5 w-3.5" />
</button>
</div>
</div>
);
}
+535
View File
@@ -0,0 +1,535 @@
"use client";
import { useCallback, useRef } from "react";
import Link from "next/link";
import {
ArrowUp, Check, ChevronDown, EyeOff, Image as ImageIcon,
LayoutDashboard, Mic, Palette, MessageSquare, Phone, Plus, Settings,
Smartphone, Sparkles, Square, Star, Trash2, X,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { ModelMenuItem } from "./ModelMenuItem";
import { MarkdownContent } from "./MarkdownContent";
import { MessageBubble } from "./MessageBubble";
import { MicrophoneButton } from "./MicrophoneButton";
import { FileAttachButton, PendingFileChips } from "./FileAttachButton";
import { ResizableTextarea, type ResizableTextareaHandle } from "./ResizableTextarea";
import { useSpeechRecognition } from "./useSpeechRecognition";
import type { ChatEngine } from "./useChatEngine";
import { useVoiceCall } from "./call/useVoiceCall";
import { VoiceCallUI } from "./call/VoiceCallUI";
export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; onToggleMode: () => void }) {
const e = engine;
const resizableRef = useRef<ResizableTextareaHandle>(null);
const voiceCall = useVoiceCall(engine.callSettings);
const handleSpeechResult = useCallback((text: string, cursorPos: number) => {
e.setInput(prev => prev.slice(0, cursorPos) + text + prev.slice(cursorPos));
}, [e]);
const speech = useSpeechRecognition(handleSpeechResult);
return (
<div className="classic-ui flex h-[100dvh] bg-background text-foreground">
{/* Sidebar overlay for mobile */}
{e.sidebarOpen && (
<div className="fixed inset-0 z-40 bg-black/60 md:hidden" onClick={() => e.setSidebarOpen(false)} />
)}
{/* Sidebar */}
<aside
className={cn(
"fixed inset-y-0 left-0 z-50 flex w-72 flex-col border-r border-white/[0.06] bg-[hsl(220,16%,5%)] transition-transform duration-200 md:static md:z-auto",
e.sidebarOpen ? "translate-x-0" : "-translate-x-full md:w-0 md:translate-x-0 md:overflow-hidden md:border-r-0",
)}
>
<div className="flex h-14 items-center justify-between border-b border-white/[0.06] px-4">
<Link href="/dashboard" className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors">
<LayoutDashboard className="h-4 w-4" />
Dashboard
</Link>
<button
onClick={e.newChat}
className="flex items-center gap-1.5 rounded-lg bg-blue-500/10 px-3 py-1.5 text-sm text-blue-400 transition-colors hover:bg-blue-500/20"
>
<Plus className="h-3.5 w-3.5" />
New
</button>
</div>
<div className="flex-1 overflow-y-auto px-2 py-3">
{!e.incognito && e.groupConversations().map((group) => (
<div key={group.label} className="mb-4">
<p className="mb-1 px-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/60">
{group.label}
</p>
{group.items.map((conv) => (
<div
key={conv.id}
className={cn(
"group flex items-center gap-2 rounded-lg px-2 py-2 text-sm transition-colors cursor-pointer",
e.activeConversationId === conv.id
? "bg-white/[0.06] text-foreground"
: "text-muted-foreground hover:bg-white/[0.04] hover:text-foreground",
)}
onClick={() => e.selectConversation(conv)}
>
<MessageSquare className="h-3.5 w-3.5 shrink-0" />
<span className="flex-1 truncate">{conv.title}</span>
<button
onClick={(ev) => { ev.stopPropagation(); e.deleteConversation(conv.id); }}
className="hidden shrink-0 rounded p-0.5 text-muted-foreground hover:text-red-400 group-hover:block"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
</div>
))}
{e.incognito && (
<div className="flex flex-col items-center justify-center py-12 text-center">
<EyeOff className="mb-3 h-8 w-8 text-muted-foreground/40" />
<p className="text-sm text-muted-foreground">Incognito mode</p>
<p className="mt-1 text-xs text-muted-foreground/60">Chat history is not saved</p>
</div>
)}
</div>
<div className="border-t border-white/[0.06] p-3">
<button
onClick={e.toggleIncognito}
className={cn(
"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm transition-colors",
e.incognito
? "bg-violet-500/15 text-violet-400"
: "text-muted-foreground hover:bg-white/[0.04] hover:text-foreground",
)}
>
<EyeOff className="h-4 w-4" />
Incognito Mode
</button>
</div>
</aside>
{/* Main area */}
<div className="flex flex-1 flex-col overflow-hidden">
{/* Top bar */}
<div className="flex h-14 items-center justify-between border-b border-white/[0.06] px-4">
<div className="flex items-center gap-3">
<button
onClick={() => e.setSidebarOpen(!e.sidebarOpen)}
className="rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-white/[0.04] hover:text-foreground"
>
{e.sidebarOpen ? <X className="h-4 w-4" /> : <MessageSquare className="h-4 w-4" />}
</button>
{/* Model selector */}
<div className="relative">
<button
onClick={() => e.setModelMenuOpen(!e.modelMenuOpen)}
className="flex items-center gap-2 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors hover:bg-white/[0.04]"
>
{e.currentModelType === "image" ? (
<Palette className="h-3.5 w-3.5 text-violet-400" />
) : e.currentModelType === "audio" ? (
<Mic className="h-3.5 w-3.5 text-emerald-400" />
) : (
<Sparkles className="h-3.5 w-3.5 text-blue-400" />
)}
{e.model || "Select model"}
<ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
</button>
{e.modelMenuOpen && (
<>
<div className="fixed inset-0 z-40" onClick={() => { e.setModelMenuOpen(false); e.setModelSearch(""); }} />
<div className="absolute left-0 top-full z-50 mt-1 max-h-[70vh] w-[calc(100vw-2rem)] overflow-hidden rounded-xl border border-white/[0.08] bg-[hsl(220,16%,7%)] shadow-2xl sm:w-[28rem]">
<div className="sticky top-0 z-10 border-b border-white/[0.06] bg-[hsl(220,16%,7%)] p-2">
<input
type="text"
placeholder="Search models..."
value={e.modelSearch}
onChange={(ev) => e.setModelSearch(ev.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"
/>
</div>
<div className="max-h-[calc(70vh-3rem)] overflow-y-auto p-1">
{e.filteredModels.some((m) => e.favourites.includes(m.id)) && (
<>
<p className="px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">Favourites</p>
{e.filteredModels.filter((m) => e.favourites.includes(m.id)).map((m) => (
<ModelMenuItem key={`fav-${m.id}`} m={m} model={e.model} isDefault={m.id === e.defaultModel} isFavourite
onSelect={() => { e.setModel(m.id); e.setModelMenuOpen(false); e.setModelSearch(""); }}
onToggleFav={() => e.toggleFavourite(m.id)} onSetDefault={() => e.setAsDefault(m.id)} />
))}
<div className="my-1 border-t border-white/[0.06]" />
<p className="px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">All Models</p>
</>
)}
{e.filteredModels.filter((m) => !e.favourites.includes(m.id)).map((m) => (
<ModelMenuItem key={m.id} m={m} model={e.model} isDefault={m.id === e.defaultModel} isFavourite={false}
onSelect={() => { e.setModel(m.id); e.setModelMenuOpen(false); e.setModelSearch(""); }}
onToggleFav={() => e.toggleFavourite(m.id)} onSetDefault={() => e.setAsDefault(m.id)} />
))}
</div>
</div>
</>
)}
</div>
{e.providerForModel && (
<span className="text-xs text-muted-foreground">via {e.providerForModel}</span>
)}
</div>
<div className="flex items-center gap-2">
{e.model && (
<button
onClick={() => voiceCall.startCall(e.model)}
className="rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-white/[0.04] hover:text-green-400"
title="Voice call"
>
<Phone className="h-4 w-4" />
</button>
)}
{e.incognito && (
<div className="flex items-center gap-1.5 rounded-full bg-violet-500/15 px-3 py-1 text-xs text-violet-400">
<EyeOff className="h-3 w-3" />
Incognito
</div>
)}
<button
onClick={() => e.setSettingsOpen(!e.settingsOpen)}
className={cn(
"rounded-lg p-1.5 transition-colors hover:bg-white/[0.04]",
e.settingsOpen ? "text-blue-400" : "text-muted-foreground hover:text-foreground",
)}
title="Advanced settings"
>
<Settings className="h-4 w-4" />
</button>
</div>
</div>
{/* Advanced settings panel */}
{e.settingsOpen && (
<div className="border-b border-white/[0.06] bg-white/[0.02] px-4 py-4 overflow-y-auto max-h-[40vh]">
<div className="mx-auto max-w-3xl space-y-4">
{e.currentModelType === "chat" && (
<>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">System Prompt</label>
<textarea
value={e.systemPrompt} onChange={(ev) => e.setSystemPrompt(ev.target.value)}
onBlur={e.saveChatSettings} placeholder="You are a helpful assistant..." rows={2}
className="w-full resize-none rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-2 text-sm outline-none placeholder:text-muted-foreground/40 focus:border-blue-500/30"
/>
</div>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Temperature {e.temperature !== null ? e.temperature.toFixed(1) : "default"}</label>
<input type="range" min="0" max="2" step="0.1" value={e.temperature ?? 1}
onChange={(ev) => e.setTemperature(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-blue-500" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Max Tokens</label>
<input type="number" min="1" max="200000" value={e.maxTokens ?? ""} onChange={(ev) => e.setMaxTokens(ev.target.value ? parseInt(ev.target.value) : null)}
onBlur={e.saveChatSettings} placeholder="default"
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none placeholder:text-muted-foreground/40 focus:border-blue-500/30" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Top P {e.topP !== null ? e.topP.toFixed(2) : "default"}</label>
<input type="range" min="0" max="1" step="0.01" value={e.topP ?? 1}
onChange={(ev) => e.setTopP(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-blue-500" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Freq. Penalty {e.frequencyPenalty !== null ? e.frequencyPenalty.toFixed(1) : "default"}</label>
<input type="range" min="-2" max="2" step="0.1" value={e.frequencyPenalty ?? 0}
onChange={(ev) => e.setFrequencyPenalty(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-blue-500" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Pres. Penalty {e.presencePenalty !== null ? e.presencePenalty.toFixed(1) : "default"}</label>
<input type="range" min="-2" max="2" step="0.1" value={e.presencePenalty ?? 0}
onChange={(ev) => e.setPresencePenalty(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-blue-500" />
</div>
</div>
</>
)}
{e.currentModelType === "audio" && e.providerForModel !== "elevenlabs" && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Voice</label>
<select value={e.audioVoice} onChange={(ev) => { e.setAudioVoice(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
{["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"].map((v) => (<option key={v} value={v}>{v}</option>))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Speed {e.audioSpeed.toFixed(2)}x</label>
<input type="range" min="0.25" max="4" step="0.05" value={e.audioSpeed}
onChange={(ev) => e.setAudioSpeed(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-emerald-500" />
</div>
</div>
)}
{e.currentModelType === "audio" && e.providerForModel === "elevenlabs" && (
<div className="space-y-3">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Voice</label>
<select value={e.elevenVoiceId} onChange={(ev) => { e.setElevenVoiceId(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
{e.elevenVoices.length === 0 && <option value="">Loading voices...</option>}
{e.elevenVoices.map((v) => (<option key={v.voice_id} value={v.voice_id}>{v.name} ({v.category})</option>))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Speed {e.elevenSpeed.toFixed(2)}x</label>
<input type="range" min="0.5" max="2" step="0.05" value={e.elevenSpeed}
onChange={(ev) => e.setElevenSpeed(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-emerald-500" />
</div>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Stability {e.elevenStability.toFixed(2)}</label>
<input type="range" min="0" max="1" step="0.01" value={e.elevenStability}
onChange={(ev) => e.setElevenStability(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-emerald-500" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Similarity {e.elevenSimilarityBoost.toFixed(2)}</label>
<input type="range" min="0" max="1" step="0.01" value={e.elevenSimilarityBoost}
onChange={(ev) => e.setElevenSimilarityBoost(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-emerald-500" />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Style {e.elevenStyle.toFixed(2)}</label>
<input type="range" min="0" max="1" step="0.01" value={e.elevenStyle}
onChange={(ev) => e.setElevenStyle(parseFloat(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-emerald-500" />
</div>
</div>
</div>
)}
{e.currentModelType === "image" && (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Size</label>
<select value={e.imageSize} onChange={(ev) => { e.setImageSize(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
{["1024x1024", "1024x1792", "1792x1024", "256x256", "512x512"].map((s) => (<option key={s} value={s}>{s}</option>))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Quality</label>
<select value={e.imageQuality} onChange={(ev) => { e.setImageQuality(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
{["auto", "high", "medium", "low", "standard", "hd"].map((q) => (<option key={q} value={q}>{q}</option>))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Style</label>
<select value={e.imageStyle} onChange={(ev) => { e.setImageStyle(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
{["vivid", "natural"].map((s) => (<option key={s} value={s}>{s}</option>))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Images ({e.imageN})</label>
<input type="range" min="1" max="4" step="1" value={e.imageN}
onChange={(ev) => e.setImageN(parseInt(ev.target.value))} onMouseUp={e.saveChatSettings} onTouchEnd={e.saveChatSettings} className="w-full accent-violet-500" />
</div>
</div>
)}
</div>
</div>
)}
{/* Messages area */}
<div ref={e.scrollRef} className="flex-1 overflow-y-auto">
{e.currentMessages.length === 0 && !e.submitting ? (
<div className="flex h-full flex-col items-center justify-center px-4">
<div className={cn(
"mb-6 rounded-2xl p-4",
e.currentModelType === "image" ? "bg-violet-500/10" : e.currentModelType === "audio" ? "bg-emerald-500/10" : "bg-blue-500/10",
)}>
{e.currentModelType === "image" ? <Palette className="h-8 w-8 text-violet-400" />
: e.currentModelType === "audio" ? <Mic className="h-8 w-8 text-emerald-400" />
: <Sparkles className="h-8 w-8 text-blue-400" />}
</div>
<h2 className="text-xl font-semibold">
{e.incognito ? "Incognito Chat"
: e.currentModelType === "image" ? "Generate Images"
: e.currentModelType === "audio" ? "Text to Speech"
: "Start a conversation"}
</h2>
<p className="mt-2 max-w-md text-center text-sm text-muted-foreground">
{e.incognito ? "Messages in this session won't be saved. Close or switch to normal mode to clear."
: e.currentModelType === "image" ? "Describe the image you want to create and the model will generate it for you."
: e.currentModelType === "audio" ? "Enter text and the model will convert it to natural-sounding speech."
: "Send a message to begin. Your conversation will be saved automatically."}
</p>
</div>
) : (
<div className="mx-auto max-w-3xl px-4 py-6">
{e.currentMessages.map((msg, idx) => (
<div key={msg.id ?? `${msg.role}-${idx}`} className="mb-6">
<MessageBubble msg={msg} variant="classic" />
</div>
))}
{e.submitting && (
<div className="mb-6 flex gap-3">
<div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-white/[0.06]">
{e.currentModelType === "image" ? <Palette className="h-3.5 w-3.5 text-violet-400" />
: e.currentModelType === "audio" ? <Mic className="h-3.5 w-3.5 text-emerald-400" />
: <Sparkles className="h-3.5 w-3.5 text-blue-400" />}
</div>
<div className="min-w-0 flex-1">
{e.streamingText ? (
<div>
<MarkdownContent content={e.streamingText} />
<span className="ml-0.5 inline-block h-4 w-[3px] animate-pulse bg-blue-400 align-middle" />
</div>
) : e.currentModelType === "image" ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<div className="h-2 w-2 animate-pulse rounded-full bg-violet-400" />Generating image...
</div>
) : e.currentModelType === "audio" ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<div className="h-2 w-2 animate-pulse rounded-full bg-emerald-400" />Generating audio...
</div>
) : (
<div className="flex items-center gap-1.5">
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400" />
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400 [animation-delay:150ms]" />
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400 [animation-delay:300ms]" />
</div>
)}
{e.streamingProviderId && (
<div className="mt-2 text-xs text-muted-foreground/60">{e.streamingProviderId}</div>
)}
</div>
</div>
)}
</div>
)}
</div>
{/* Input area */}
<div
className="border-t border-white/[0.06] px-4 py-3"
onDragOver={(ev) => { ev.preventDefault(); ev.stopPropagation(); }}
onDrop={(ev) => { ev.preventDefault(); ev.stopPropagation(); if (ev.dataTransfer.files.length) e.addImageFiles(ev.dataTransfer.files); }}
>
<form onSubmit={e.handleSubmit} className="relative mx-auto max-w-3xl">
<div className="relative rounded-2xl border border-white/[0.08] bg-white/[0.03] transition-colors focus-within:border-blue-500/30 focus-within:bg-white/[0.04]">
{e.pendingImages.length > 0 && (
<div className="flex flex-wrap gap-2 px-3 pt-3">
{e.pendingImages.map((img, i) => (
<div key={i} className="group relative">
<img src={img.image_url.url} alt={`Pending ${i + 1}`} className="h-16 w-16 rounded-lg border border-white/[0.08] object-cover" />
<button type="button" onClick={() => e.removePendingImage(i)}
className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-white opacity-0 transition-opacity group-hover:opacity-100">
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<PendingFileChips files={e.pendingFiles} onRemove={e.removePendingFile} />
<ResizableTextarea
ref={resizableRef}
value={e.input}
onChange={(v) => e.setInput(v)}
onKeyDown={(ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); e.handleSubmit(); } }}
onPaste={(ev) => {
const items = ev.clipboardData.items;
const imageFiles: File[] = [];
for (const item of Array.from(items)) {
if (item.type.startsWith("image/")) { const file = item.getAsFile(); if (file) imageFiles.push(file); }
}
if (imageFiles.length) { ev.preventDefault(); e.addImageFiles(imageFiles); }
}}
placeholder={
e.pendingImages.length ? "Add a message about these images..."
: e.currentModelType === "image" ? "Describe the image you want to generate..."
: e.currentModelType === "audio" ? "Enter text to convert to speech..."
: "Send a message..."
}
className="px-4 py-3 pr-32"
/>
<input ref={e.fileInputRef} type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple className="hidden"
onChange={(ev) => { if (ev.target.files?.length) e.addImageFiles(ev.target.files); ev.target.value = ""; }} />
<div className="absolute bottom-2 right-2 flex items-center gap-1">
{!e.submitting && (
<>
<button type="button" onClick={onToggleMode}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-white/[0.06] hover:text-foreground"
title="Alternative UI">
<Smartphone className="h-4 w-4" />
</button>
<FileAttachButton
onFiles={(files) => e.addFiles(files)}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-white/[0.06] hover:text-foreground"
/>
<MicrophoneButton
isListening={speech.isListening}
isSupported={speech.isSupported}
onToggle={() => {
if (speech.isListening) speech.stopListening();
else speech.startListening(resizableRef.current?.selectionStart ?? e.input.length);
}}
className="h-8 w-8"
/>
<button type="button" onClick={() => e.fileInputRef.current?.click()}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-white/[0.06] hover:text-foreground" title="Upload image">
<ImageIcon className="h-4 w-4" />
</button>
</>
)}
{e.submitting ? (
<button type="button" onClick={e.stopGeneration}
className="flex h-8 w-8 items-center justify-center rounded-lg bg-white/[0.1] text-foreground transition-colors hover:bg-white/[0.15]">
<Square className="h-3.5 w-3.5" />
</button>
) : (
<button type="submit" disabled={(!e.input.trim() && !e.pendingImages.length) || !e.model}
className="flex h-8 w-8 items-center justify-center rounded-lg bg-blue-500 text-white transition-colors hover:bg-blue-400 disabled:opacity-30 disabled:hover:bg-blue-500">
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
</div>
<p className="mt-2 text-center text-[11px] text-muted-foreground/40">
{e.model}{e.incognito ? " \u00b7 Incognito" : ""}
{speech.interimText && <span className="ml-2 text-blue-400/60 italic">{speech.interimText}</span>}
</p>
</form>
</div>
</div>
{voiceCall.callState !== "idle" && (
<VoiceCallUI
callState={voiceCall.callState}
callModel={voiceCall.callModel}
callModelName={voiceCall.callModelName}
callDuration={voiceCall.callDuration}
isMuted={voiceCall.isMuted}
isDeafened={voiceCall.isDeafened}
showSubtitles={voiceCall.showSubtitles}
subtitleText={voiceCall.subtitleText}
subtitleProgress={voiceCall.subtitleProgress}
userSpeechText={voiceCall.userSpeechText}
activePopups={voiceCall.activePopups}
isAudioPlaying={voiceCall.isAudioPlaying}
onToggleMute={voiceCall.toggleMute}
onToggleDeafen={voiceCall.toggleDeafen}
onToggleSubtitles={voiceCall.toggleSubtitles}
onEndCall={voiceCall.endCall}
onDismissPopup={voiceCall.dismissPopup}
/>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
"use client";
import { useEffect } from "react";
const STORAGE_KEY = "chat-custom-css";
const STYLE_ID = "custom-chat-css";
export function CustomCSSInjector() {
useEffect(() => {
const css = localStorage.getItem(STORAGE_KEY) ?? "";
if (!css) return;
let el = document.getElementById(STYLE_ID);
if (!el) {
el = document.createElement("style");
el.id = STYLE_ID;
document.head.appendChild(el);
}
el.textContent = css;
}, []);
return null;
}
+58
View File
@@ -0,0 +1,58 @@
"use client";
import { Paperclip, X } from "lucide-react";
function formatSize(bytes: number) {
if (bytes < 1024) return `${bytes}B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
export function FileAttachButton({
onFiles,
className,
}: {
onFiles: (files: FileList) => void;
className?: string;
}) {
return (
<button
type="button"
onClick={() => {
const input = document.createElement("input");
input.type = "file";
input.multiple = true;
input.onchange = () => { if (input.files?.length) onFiles(input.files); };
input.click();
}}
className={className}
title="Attach file"
>
<Paperclip className="h-4 w-4" />
</button>
);
}
export function PendingFileChips({
files,
onRemove,
}: {
files: File[];
onRemove: (index: number) => void;
}) {
if (!files.length) return null;
return (
<div className="flex flex-wrap gap-1.5 px-3 pt-2">
{files.map((file, i) => (
<div key={i} className="flex items-center gap-1.5 rounded-lg bg-white/[0.06] px-2.5 py-1 text-xs text-muted-foreground">
<span className="max-w-[120px] truncate">{file.name}</span>
<span className="text-muted-foreground/50">{formatSize(file.size)}</span>
<button type="button" onClick={() => onRemove(i)} className="text-muted-foreground/50 hover:text-foreground">
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
);
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export function MarkdownContent({ content }: { content: string }) {
return (
<div className="prose-chat text-sm leading-relaxed">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ children }) => <p className="mb-3 last:mb-0">{children}</p>,
h1: ({ children }) => <h1 className="mb-3 mt-5 text-xl font-bold first:mt-0">{children}</h1>,
h2: ({ children }) => <h2 className="mb-2 mt-4 text-lg font-semibold first:mt-0">{children}</h2>,
h3: ({ children }) => <h3 className="mb-2 mt-3 text-base font-semibold first:mt-0">{children}</h3>,
ul: ({ children }) => <ul className="mb-3 ml-4 list-disc space-y-1">{children}</ul>,
ol: ({ children }) => <ol className="mb-3 ml-4 list-decimal space-y-1">{children}</ol>,
li: ({ children }) => <li className="pl-1">{children}</li>,
blockquote: ({ children }) => (
<blockquote className="my-3 border-l-2 border-blue-500/40 pl-4 text-muted-foreground italic">
{children}
</blockquote>
),
code: ({ className, children, ...props }) => {
const isBlock = className?.includes("language-");
if (isBlock) {
const lang = className?.replace("language-", "") ?? "";
return (
<div className="group relative my-3 overflow-hidden rounded-xl border border-white/[0.06] bg-[hsl(220,16%,5%)]">
{lang && (
<div className="flex items-center justify-between border-b border-white/[0.06] px-4 py-1.5 text-xs text-muted-foreground">
<span>{lang}</span>
<button
onClick={() => navigator.clipboard.writeText(String(children).replace(/\n$/, ""))}
className="opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"
>
Copy
</button>
</div>
)}
<pre className="overflow-x-auto p-4 text-[13px] leading-relaxed">
<code className={className} {...props}>{children}</code>
</pre>
</div>
);
}
return (
<code className="rounded-md bg-white/[0.06] px-1.5 py-0.5 text-[13px] text-blue-300" {...props}>
{children}
</code>
);
},
pre: ({ children }) => <>{children}</>,
img: ({ src, alt }) => (
<img
src={src}
alt={alt ?? "Image"}
className="my-3 max-h-80 rounded-xl border border-white/[0.06] object-contain"
/>
),
a: ({ href, children }) => (
<a href={href} target="_blank" rel="noopener noreferrer" className="text-blue-400 underline underline-offset-2 hover:text-blue-300">
{children}
</a>
),
table: ({ children }) => (
<div className="my-3 overflow-x-auto rounded-lg border border-white/[0.06]">
<table className="w-full text-sm">{children}</table>
</div>
),
thead: ({ children }) => <thead className="border-b border-white/[0.06] bg-white/[0.02]">{children}</thead>,
th: ({ children }) => <th className="px-3 py-2 text-left text-xs font-medium text-muted-foreground">{children}</th>,
td: ({ children }) => <td className="border-t border-white/[0.04] px-3 py-2">{children}</td>,
hr: () => <hr className="my-4 border-white/[0.06]" />,
strong: ({ children }) => <strong className="font-semibold text-foreground">{children}</strong>,
}}
>
{content}
</ReactMarkdown>
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
"use client";
import { Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";
import { AudioPlayer } from "./AudioPlayer";
import { MarkdownContent } from "./MarkdownContent";
import type { ChatMessage } from "./types";
export function MessageBubble({ msg, variant = "classic" }: { msg: ChatMessage; variant?: "classic" | "messenger" | "phone" }) {
const isMessenger = variant === "messenger" || variant === "phone";
if (msg.role === "user") {
return (
<div className="flex justify-end">
<div className={cn(
"max-w-[80%] rounded-2xl px-4 py-3 text-sm text-white",
isMessenger ? "rounded-br-md bg-blue-500" : "rounded-br-md bg-blue-500",
)}>
{msg.images?.length ? (
<div className={cn("mb-2 grid gap-2", msg.images.length === 1 ? "grid-cols-1" : "grid-cols-2")}>
{msg.images.map((img, i) => (
<img key={i} src={img.image_url.url} alt={`Uploaded ${i + 1}`} className="max-h-60 rounded-lg object-cover" />
))}
</div>
) : null}
<div className="whitespace-pre-wrap">{msg.content}</div>
{isMessenger && msg.createdAt && (
<div className="mt-1 text-right text-[10px] text-white/50">
{new Date(msg.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</div>
)}
</div>
</div>
);
}
return (
<div className={cn("flex gap-3", isMessenger && "")}>
{!isMessenger && (
<div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-white/[0.06]">
<Sparkles className="h-3.5 w-3.5 text-blue-400" />
</div>
)}
<div className={cn(
"min-w-0",
isMessenger ? "max-w-[80%] rounded-2xl rounded-bl-md bg-[hsl(220,16%,12%)] px-4 py-3" : "flex-1",
)}>
{msg.generatedImages?.length ? (
<div className="space-y-3">
{msg.content && msg.content !== "Generated image" && (
<p className="text-sm text-muted-foreground italic">{msg.content}</p>
)}
<div className={cn("grid gap-2", msg.generatedImages.length === 1 ? "grid-cols-1" : "grid-cols-2")}>
{msg.generatedImages.map((img, i) => (
<a key={i} href={img.b64_json ? `data:image/png;base64,${img.b64_json}` : img.url} target="_blank" rel="noopener noreferrer" className="group relative overflow-hidden rounded-xl border border-white/[0.06]">
<img src={img.b64_json ? `data:image/png;base64,${img.b64_json}` : img.url} alt={img.revised_prompt || "Generated image"} className="max-h-[500px] w-full object-contain transition-transform group-hover:scale-[1.02]" />
</a>
))}
</div>
{msg.generatedImages[0]?.revised_prompt && (
<p className="text-xs text-muted-foreground/60 italic">{msg.generatedImages[0].revised_prompt}</p>
)}
</div>
) : msg.audioB64 ? (
<AudioPlayer src={`data:${msg.audioContentType ?? "audio/mpeg"};base64,${msg.audioB64}`} />
) : (
<MarkdownContent content={msg.content} />
)}
{!isMessenger && (msg.providerId || msg.tokensIn != null) && (
<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground/60">
{msg.providerId && <span>{msg.providerId}</span>}
{msg.model && <span>{msg.model}</span>}
{msg.tokensIn != null && msg.tokensOut != null && <span>{msg.tokensIn + msg.tokensOut} tokens</span>}
</div>
)}
{isMessenger && msg.createdAt && (
<div className="mt-1 text-[10px] text-muted-foreground/50">
{new Date(msg.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</div>
)}
</div>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
import { Mic, MicOff } from "lucide-react";
import { cn } from "@/lib/utils";
export function MicrophoneButton({
isListening,
isSupported,
onToggle,
className,
size = "default",
}: {
isListening: boolean;
isSupported: boolean;
onToggle: () => void;
className?: string;
size?: "default" | "lg";
}) {
if (!isSupported) return null;
const iconSize = size === "lg" ? "h-5 w-5" : "h-4 w-4";
return (
<button
type="button"
onClick={onToggle}
className={cn(
"relative flex items-center justify-center rounded-full transition-all",
isListening
? "bg-red-500/20 text-red-400 hover:bg-red-500/30"
: "text-muted-foreground hover:bg-white/[0.06] hover:text-foreground",
className,
)}
title={isListening ? "Stop recording" : "Voice input"}
>
{/* Pulsing ring when recording */}
{isListening && (
<span className="absolute inset-0 animate-ping rounded-full bg-red-500/20" style={{ animationDuration: "1.5s" }} />
)}
{isListening ? <MicOff className={cn(iconSize, "relative z-10")} /> : <Mic className={iconSize} />}
</button>
);
}
+70
View File
@@ -0,0 +1,70 @@
"use client";
import { Check, Star } from "lucide-react";
import { cn } from "@/lib/utils";
import type { ModelOption } from "./types";
export function ModelMenuItem({
m,
model,
isDefault,
isFavourite,
onSelect,
onToggleFav,
onSetDefault,
}: {
m: ModelOption;
model: string;
isDefault: boolean;
isFavourite: boolean;
onSelect: () => void;
onToggleFav: () => void;
onSetDefault: () => void;
}) {
return (
<div
className={cn(
"group flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left text-sm transition-colors",
m.id === model
? "bg-blue-500/10 text-blue-400"
: "text-foreground hover:bg-white/[0.04]",
)}
>
<button onClick={onSelect} className="flex min-w-0 flex-1 items-center gap-2">
{isDefault && <Check className="h-3.5 w-3.5 shrink-0 text-emerald-400" />}
<span className="truncate">{m.id}</span>
{m.modelType === "image" && (
<span className="shrink-0 rounded bg-violet-500/15 px-1.5 py-0.5 text-[10px] font-medium text-violet-400">IMG</span>
)}
{m.modelType === "audio" && (
<span className="shrink-0 rounded bg-emerald-500/15 px-1.5 py-0.5 text-[10px] font-medium text-emerald-400">TTS</span>
)}
</button>
<span className="shrink-0 text-xs text-muted-foreground">{m.providerId}</span>
<button
onClick={(e) => { e.stopPropagation(); onSetDefault(); }}
title={isDefault ? "Remove as default" : "Set as default"}
className={cn(
"shrink-0 rounded p-1 transition-colors",
isDefault
? "text-emerald-400 hover:text-emerald-300"
: "text-muted-foreground/30 hover:text-emerald-400 md:opacity-0 md:group-hover:opacity-100",
)}
>
<Check className="h-3.5 w-3.5" />
</button>
<button
onClick={(e) => { e.stopPropagation(); onToggleFav(); }}
title={isFavourite ? "Remove from favourites" : "Add to favourites"}
className={cn(
"shrink-0 rounded p-1 transition-colors",
isFavourite
? "text-amber-400 hover:text-amber-300"
: "text-muted-foreground/30 hover:text-amber-400 md:opacity-0 md:group-hover:opacity-100",
)}
>
<Star className={cn("h-3.5 w-3.5", isFavourite && "fill-current")} />
</button>
</div>
);
}
+148
View File
@@ -0,0 +1,148 @@
"use client";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import { GripHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
const LINE_HEIGHT = 20;
const MAX_AUTO_LINES = 8;
const MIN_LINES = 1;
const PADDING = 16; // vertical padding inside textarea
interface ResizableTextareaProps {
value: string;
onChange: (value: string) => void;
onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
onPaste?: (e: React.ClipboardEvent<HTMLTextAreaElement>) => void;
placeholder?: string;
className?: string;
wrapperClassName?: string;
}
export interface ResizableTextareaHandle {
textarea: HTMLTextAreaElement | null;
selectionStart: number;
}
export const ResizableTextarea = forwardRef<ResizableTextareaHandle, ResizableTextareaProps>(
function ResizableTextarea({ value, onChange, onKeyDown, onPaste, placeholder, className, wrapperClassName }, ref) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [manualHeight, setManualHeight] = useState<number | null>(null);
const [showDragHandle, setShowDragHandle] = useState(false);
const isDraggingRef = useRef(false);
const startYRef = useRef(0);
const startHeightRef = useRef(0);
useImperativeHandle(ref, () => ({
get textarea() { return textareaRef.current; },
get selectionStart() { return textareaRef.current?.selectionStart ?? 0; },
}));
// Auto-resize
useEffect(() => {
const el = textareaRef.current;
if (!el) return;
if (manualHeight !== null) {
el.style.height = manualHeight + "px";
el.style.overflowY = "auto";
setShowDragHandle(true);
return;
}
el.style.height = "auto";
const scrollH = el.scrollHeight;
const maxAutoH = MAX_AUTO_LINES * LINE_HEIGHT + PADDING;
const lines = Math.max(1, Math.round((scrollH - PADDING) / LINE_HEIGHT));
if (lines > MAX_AUTO_LINES) {
el.style.height = maxAutoH + "px";
el.style.overflowY = "auto";
setShowDragHandle(true);
} else {
el.style.height = scrollH + "px";
el.style.overflowY = "hidden";
setShowDragHandle(lines >= MAX_AUTO_LINES);
}
}, [value, manualHeight]);
// Reset manual height when input is cleared
useEffect(() => {
if (!value) setManualHeight(null);
}, [value]);
// Drag logic
const onDragStart = useCallback((clientY: number) => {
const el = textareaRef.current;
if (!el) return;
isDraggingRef.current = true;
startYRef.current = clientY;
startHeightRef.current = el.offsetHeight;
document.body.style.cursor = "ns-resize";
document.body.style.userSelect = "none";
}, []);
const onDragMove = useCallback((clientY: number) => {
if (!isDraggingRef.current) return;
const delta = startYRef.current - clientY;
const minH = MIN_LINES * LINE_HEIGHT + PADDING;
const maxH = window.innerHeight * 0.55;
setManualHeight(Math.max(minH, Math.min(maxH, startHeightRef.current + delta)));
}, []);
const onDragEnd = useCallback(() => {
isDraggingRef.current = false;
document.body.style.cursor = "";
document.body.style.userSelect = "";
}, []);
const handleMouseDown = useCallback((ev: React.MouseEvent) => {
ev.preventDefault();
onDragStart(ev.clientY);
const move = (e: MouseEvent) => onDragMove(e.clientY);
const up = () => { onDragEnd(); window.removeEventListener("mousemove", move); window.removeEventListener("mouseup", up); };
window.addEventListener("mousemove", move);
window.addEventListener("mouseup", up);
}, [onDragStart, onDragMove, onDragEnd]);
const handleTouchStart = useCallback((ev: React.TouchEvent) => {
const t = ev.touches[0];
if (!t) return;
onDragStart(t.clientY);
const move = (e: TouchEvent) => { e.preventDefault(); if (e.touches[0]) onDragMove(e.touches[0].clientY); };
const end = () => { onDragEnd(); window.removeEventListener("touchmove", move); window.removeEventListener("touchend", end); };
window.addEventListener("touchmove", move, { passive: false });
window.addEventListener("touchend", end);
}, [onDragStart, onDragMove, onDragEnd]);
return (
<div className={cn("relative", wrapperClassName)}>
{/* Drag handle */}
{showDragHandle && (
<div
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
className="flex cursor-ns-resize items-center justify-center py-1 touch-none select-none"
>
<div className="flex items-center gap-0.5 rounded-full bg-white/[0.06] px-3 py-0.5">
<GripHorizontal className="h-3 w-3 text-muted-foreground/40" />
</div>
</div>
)}
<textarea
ref={textareaRef}
value={value}
onChange={(ev) => onChange(ev.target.value)}
onKeyDown={onKeyDown}
onPaste={onPaste}
placeholder={placeholder}
rows={1}
className={cn(
"block w-full resize-none bg-transparent text-sm outline-none placeholder:text-muted-foreground/50",
className,
)}
/>
</div>
);
},
);
+100
View File
@@ -0,0 +1,100 @@
"use client";
import { Search, Star } from "lucide-react";
import { useState } from "react";
import { cn } from "@/lib/utils";
import type { ModelOption } from "../types";
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
function getColor(id: string) {
const colors = [
"bg-blue-500/20 text-blue-400", "bg-emerald-500/20 text-emerald-400",
"bg-violet-500/20 text-violet-400", "bg-amber-500/20 text-amber-400",
"bg-rose-500/20 text-rose-400", "bg-cyan-500/20 text-cyan-400",
];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
export function ContactsList({
models,
favourites,
selectedModel,
onSelect,
}: {
models: ModelOption[];
favourites: string[];
selectedModel: string;
onSelect: (modelId: string) => void;
}) {
const [search, setSearch] = useState("");
const filtered = search
? models.filter((m) => m.id.toLowerCase().includes(search.toLowerCase()))
: models;
const starred = filtered.filter((m) => favourites.includes(m.id));
const rest = filtered.filter((m) => !favourites.includes(m.id));
return (
<div className="flex h-full flex-col">
<div className="p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search contacts..."
className="w-full rounded-lg bg-white/[0.04] py-2 pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground/40 focus:bg-white/[0.06]"
/>
</div>
</div>
<div className="flex-1 overflow-y-auto">
{starred.length > 0 && (
<>
<p className="px-4 pb-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">
<Star className="mr-1 inline h-3 w-3" />Starred
</p>
{starred.map((m) => (
<ContactRow key={m.id} m={m} selected={m.id === selectedModel} starred onSelect={() => onSelect(m.id)} />
))}
<div className="my-2 border-t border-white/[0.04]" />
</>
)}
<p className="px-4 pb-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">All Contacts</p>
{rest.map((m) => (
<ContactRow key={m.id} m={m} selected={m.id === selectedModel} starred={false} onSelect={() => onSelect(m.id)} />
))}
</div>
</div>
);
}
function ContactRow({ m, selected, starred, onSelect }: { m: ModelOption; selected: boolean; starred: boolean; onSelect: () => void }) {
return (
<button
onClick={onSelect}
className={cn(
"flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors",
selected ? "bg-blue-500/10" : "hover:bg-white/[0.03]",
)}
>
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-semibold", getColor(m.id))}>
{getInitials(m.id)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className={cn("truncate text-sm font-medium", selected ? "text-blue-400" : "text-foreground")}>{m.id}</span>
{starred && <Star className="h-3 w-3 shrink-0 fill-amber-400 text-amber-400" />}
</div>
<p className="truncate text-xs text-muted-foreground/60">{m.providerId}</p>
</div>
</button>
);
}
@@ -0,0 +1,44 @@
"use client";
import { X } from "lucide-react";
import { useCustomCSS } from "../useCustomCSS";
export function CustomCSSEditor({ onClose }: { onClose: () => void }) {
const { css, setCSS, clearCSS } = useCustomCSS();
return (
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60" onClick={onClose}>
<div className="w-full max-w-lg rounded-2xl border border-white/[0.08] bg-[hsl(220,16%,7%)] shadow-2xl" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between border-b border-white/[0.06] px-5 py-3">
<h3 className="text-sm font-medium">Custom CSS</h3>
<button onClick={onClose} className="rounded-lg p-1 text-muted-foreground hover:text-foreground">
<X className="h-4 w-4" />
</button>
</div>
<div className="p-5">
<textarea
value={css}
onChange={(e) => setCSS(e.target.value)}
placeholder={`/* Custom styles */\n.messenger-ui { }\n.phone-ui { }\n.classic-ui { }`}
rows={12}
className="w-full resize-none rounded-lg border border-white/[0.08] bg-white/[0.03] px-4 py-3 font-mono text-xs text-foreground outline-none placeholder:text-muted-foreground/30 focus:border-blue-500/30"
spellCheck={false}
/>
<div className="mt-3 flex items-center justify-between">
<p className="text-[11px] text-muted-foreground/50">
CSS is applied live and saved to your browser.
</p>
<div className="flex gap-2">
<button onClick={clearCSS} className="rounded-lg px-3 py-1.5 text-xs text-muted-foreground hover:bg-white/[0.04] hover:text-foreground">
Clear
</button>
<button onClick={onClose} className="rounded-lg bg-blue-500/10 px-3 py-1.5 text-xs text-blue-400 hover:bg-blue-500/20">
Done
</button>
</div>
</div>
</div>
</div>
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
import { useEffect, useRef } from "react";
import { MarkdownContent } from "../MarkdownContent";
import { MessageBubble } from "../MessageBubble";
import type { ChatMessage } from "../types";
export function MessageThread({
messages,
submitting,
streamingText,
variant = "messenger",
}: {
messages: ChatMessage[];
submitting: boolean;
streamingText: string;
variant?: "messenger" | "phone";
}) {
const endRef = useRef<HTMLDivElement>(null);
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, submitting, streamingText]);
return (
<div className="flex-1 overflow-y-auto px-4 py-4">
<div className="space-y-4">
{messages.map((msg, idx) => (
<MessageBubble key={msg.id ?? `${msg.role}-${idx}`} msg={msg} variant={variant} />
))}
{submitting && (
<div className="flex gap-3">
<div className="max-w-[80%] rounded-2xl rounded-bl-md bg-[hsl(220,16%,12%)] px-4 py-3">
{streamingText ? (
<div>
<MarkdownContent content={streamingText} />
<span className="ml-0.5 inline-block h-4 w-[3px] animate-pulse bg-blue-400 align-middle" />
</div>
) : (
<div className="flex items-center gap-1.5 py-1">
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400" />
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400 [animation-delay:150ms]" />
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400 [animation-delay:300ms]" />
</div>
)}
</div>
</div>
)}
</div>
<div ref={endRef} />
</div>
);
}
@@ -0,0 +1,66 @@
"use client";
import { useCallback, useRef } from "react";
import { ArrowUp, Square } from "lucide-react";
import { FileAttachButton } from "../FileAttachButton";
import { MicrophoneButton } from "../MicrophoneButton";
import { ResizableTextarea, type ResizableTextareaHandle } from "../ResizableTextarea";
import { useSpeechRecognition } from "../useSpeechRecognition";
import type { ChatEngine } from "../useChatEngine";
export function MessengerInputBar({ engine }: { engine: ChatEngine }) {
const e = engine;
const resizableRef = useRef<ResizableTextareaHandle>(null);
const handleSpeechResult = useCallback((text: string, cursorPos: number) => {
e.setInput(prev => prev.slice(0, cursorPos) + text + prev.slice(cursorPos));
}, [e]);
const speech = useSpeechRecognition(handleSpeechResult);
return (
<div className="border-t border-white/[0.06] bg-[hsl(220,16%,5%)] px-3 py-2">
<div className="flex items-end gap-2">
<FileAttachButton
onFiles={(files) => e.addFiles(files)}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-white/[0.06] hover:text-foreground"
/>
<MicrophoneButton
isListening={speech.isListening}
isSupported={speech.isSupported}
onToggle={() => {
if (speech.isListening) speech.stopListening();
else speech.startListening(resizableRef.current?.selectionStart ?? e.input.length);
}}
className="h-9 w-9 shrink-0"
/>
<div className="min-w-0 flex-1">
<div className="rounded-2xl bg-white/[0.04] focus-within:bg-white/[0.06]">
<ResizableTextarea
ref={resizableRef}
value={e.input}
onChange={(v) => e.setInput(v)}
onKeyDown={(ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); e.handleSubmit(); } }}
placeholder="Message..."
className="px-4 py-2.5"
/>
</div>
</div>
{e.submitting ? (
<button onClick={e.stopGeneration}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white/[0.1] text-foreground">
<Square className="h-3.5 w-3.5" />
</button>
) : (
<button onClick={() => e.handleSubmit()} disabled={(!e.input.trim() && !e.pendingImages.length) || !e.model}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-blue-500 text-white disabled:opacity-30">
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
{speech.isListening && speech.interimText && (
<p className="mt-1 px-2 text-xs text-red-400/70 italic truncate">{speech.interimText}</p>
)}
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
"use client";
import { useState } from "react";
import { Monitor, Palette, Phone } from "lucide-react";
import type { ChatEngine } from "../useChatEngine";
import { ContactsList } from "./ContactsList";
import { MessageThread } from "./MessageThread";
import { MessengerInputBar } from "./MessengerInputBar";
import { CustomCSSEditor } from "./CustomCSSEditor";
import { useVoiceCall } from "../call/useVoiceCall";
import { VoiceCallUI } from "../call/VoiceCallUI";
export function MessengerUI({ engine, onSwitchToClassic }: { engine: ChatEngine; onSwitchToClassic: () => void }) {
const e = engine;
const [cssEditorOpen, setCssEditorOpen] = useState(false);
const voiceCall = useVoiceCall(engine.callSettings);
return (
<div className="messenger-ui flex h-[100dvh] bg-background text-foreground">
{/* Left sidebar — contacts */}
<div className="flex w-[280px] shrink-0 flex-col border-r border-white/[0.06] bg-[hsl(220,16%,5%)]">
<div className="flex h-14 items-center justify-between border-b border-white/[0.06] px-4">
<h2 className="text-sm font-semibold">Chats</h2>
<div className="flex items-center gap-1">
<button onClick={() => setCssEditorOpen(true)} className="rounded-lg p-1.5 text-muted-foreground hover:text-foreground" title="Custom CSS">
<Palette className="h-3.5 w-3.5" />
</button>
<button onClick={onSwitchToClassic} className="rounded-lg p-1.5 text-muted-foreground hover:text-foreground" title="Classic view">
<Monitor className="h-3.5 w-3.5" />
</button>
</div>
</div>
<ContactsList
models={e.sortedModels}
favourites={e.favourites}
selectedModel={e.model}
onSelect={(id) => { e.setModel(id); e.newChat(); }}
/>
</div>
{/* Right panel — thread */}
<div className="flex flex-1 flex-col overflow-hidden">
{/* Thread header */}
<div className="flex h-14 items-center gap-3 border-b border-white/[0.06] px-4">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-500/20 text-xs font-semibold text-blue-400">
{e.model.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{e.model || "Select a contact"}</p>
{e.providerForModel && (
<p className="text-xs text-muted-foreground/60">{e.providerForModel}</p>
)}
</div>
{e.submitting && <div className="h-2 w-2 animate-pulse rounded-full bg-emerald-400" />}
{e.model && (
<button onClick={() => voiceCall.startCall(e.model)} className="rounded-lg p-1.5 text-muted-foreground hover:bg-white/[0.04] hover:text-green-400" title="Call">
<Phone className="h-4 w-4" />
</button>
)}
</div>
{/* Messages */}
<MessageThread
messages={e.currentMessages}
submitting={e.submitting}
streamingText={e.streamingText}
variant="messenger"
/>
{/* Input */}
<MessengerInputBar engine={e} />
</div>
{cssEditorOpen && <CustomCSSEditor onClose={() => setCssEditorOpen(false)} />}
{voiceCall.callState !== "idle" && (
<VoiceCallUI
callState={voiceCall.callState}
callModel={voiceCall.callModel}
callModelName={voiceCall.callModelName}
callDuration={voiceCall.callDuration}
isMuted={voiceCall.isMuted}
isDeafened={voiceCall.isDeafened}
showSubtitles={voiceCall.showSubtitles}
subtitleText={voiceCall.subtitleText}
subtitleProgress={voiceCall.subtitleProgress}
userSpeechText={voiceCall.userSpeechText}
activePopups={voiceCall.activePopups}
isAudioPlaying={voiceCall.isAudioPlaying}
onToggleMute={voiceCall.toggleMute}
onToggleDeafen={voiceCall.toggleDeafen}
onToggleSubtitles={voiceCall.toggleSubtitles}
onEndCall={voiceCall.endCall}
onDismissPopup={voiceCall.dismissPopup}
/>
)}
</div>
);
}
+180
View File
@@ -0,0 +1,180 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import type { ChatEngine } from "../useChatEngine";
import type { Conversation, FriendProfile } from "../types";
import { HomeScreen } from "./phone/HomeScreen";
import { MessagesScreen } from "./phone/MessagesScreen";
import { ContactsScreen } from "./phone/ContactsScreen";
import { ConversationScreen } from "./phone/ConversationScreen";
import { SettingsScreen } from "./phone/SettingsScreen";
import { useVoiceCall } from "../call/useVoiceCall";
import { VoiceCallUI } from "../call/VoiceCallUI";
import { CallHistory } from "../call/CallHistory";
import { CallHistoryDetail } from "../call/CallHistoryDetail";
import { FriendsManager } from "../call/FriendsManager";
import { FriendConversationScreen } from "../call/FriendConversationScreen";
type PhoneScreen = "home" | "messages" | "contacts" | "conversation" | "settings" | "call-history" | "call-history-detail" | "friends" | "friend-chat" | "friend-settings";
export function VirtualPhoneUI({ engine, onSwitchToClassic }: { engine: ChatEngine; onSwitchToClassic: () => void }) {
const [screen, setScreen] = useState<PhoneScreen>("home");
const [selectedCall, setSelectedCall] = useState<Conversation | null>(null);
const [activeFriend, setActiveFriend] = useState<FriendProfile | null>(null);
const [friends, setFriends] = useState<FriendProfile[]>([]);
const voiceCall = useVoiceCall(engine.callSettings);
const loadFriends = useCallback(async () => {
try {
const res = await fetch("/api/chat/friends");
if (res.ok) {
const data = await res.json();
setFriends((data.data ?? []).map((f: Record<string, unknown>) => ({
id: f.id as string, name: f.name as string, modelId: f.modelId as string,
systemPrompt: f.systemPrompt as string | undefined, characterStyle: f.characterStyle as string | undefined,
avatarColor: f.avatarColor as string | undefined, conversationId: f.conversationId as string | undefined,
voiceSettings: f.voiceSettings as FriendProfile["voiceSettings"],
})));
}
} catch { /* skip */ }
}, []);
useEffect(() => { loadFriends(); }, [loadFriends]);
function navigate(s: string) {
setScreen(s as PhoneScreen);
}
function selectContact(modelId: string) {
engine.setModel(modelId);
engine.newChat();
setScreen("conversation");
}
function handleCall(modelId: string) {
voiceCall.startCall(modelId);
}
function handleFriendCall(friend: FriendProfile) {
voiceCall.startCall(friend.modelId, friend);
}
function handleFriendChat(friend: FriendProfile) {
setActiveFriend(friend);
setScreen("friend-chat");
}
function handleFriendSettings(friend: FriendProfile) {
setActiveFriend(friend);
setScreen("friend-settings");
}
function handleSelectCall(conv: Conversation) {
setSelectedCall(conv);
setScreen("call-history-detail");
}
return (
<div className="phone-ui flex h-[100dvh] items-center justify-center bg-black">
<div className="relative flex h-full w-full flex-col overflow-hidden bg-background text-foreground md:h-[740px] md:w-[375px] md:rounded-[3rem] md:border-[3px] md:border-white/[0.08] md:shadow-2xl">
{screen === "home" && <HomeScreen onNavigate={navigate} />}
{screen === "messages" && (
<MessagesScreen
conversations={engine.conversations}
friends={friends}
onSelectConversation={(conv) => {
engine.selectConversation(conv);
setScreen("conversation");
}}
onSelectFriend={(friend) => {
setActiveFriend(friend);
setScreen("friend-chat");
}}
onNewChat={() => setScreen("contacts")}
onBack={() => setScreen("home")}
/>
)}
{screen === "contacts" && (
<ContactsScreen
models={engine.sortedModels}
favourites={engine.favourites}
onSelect={selectContact}
onCall={handleCall}
onBack={() => setScreen("messages")}
/>
)}
{screen === "conversation" && (
<ConversationScreen engine={engine} onBack={() => setScreen("messages")} />
)}
{screen === "settings" && (
<SettingsScreen
onBack={() => setScreen("home")}
onSwitchToClassic={onSwitchToClassic}
incognito={engine.incognito}
onToggleIncognito={engine.toggleIncognito}
callSettings={engine.callSettings}
onCallSettingsChange={(cs) => { engine.setCallSettings(cs); setTimeout(engine.saveChatSettings, 0); }}
/>
)}
{screen === "call-history" && (
<CallHistory onBack={() => setScreen("home")} onSelectCall={handleSelectCall} />
)}
{screen === "call-history-detail" && selectedCall && (
<CallHistoryDetail conversation={selectedCall} onBack={() => setScreen("call-history")} />
)}
{screen === "friends" && (
<FriendsManager
models={engine.sortedModels}
onBack={() => setScreen("home")}
onCall={handleFriendCall}
onChat={handleFriendChat}
/>
)}
{screen === "friend-chat" && activeFriend && (
<FriendConversationScreen
friend={activeFriend}
onBack={() => setScreen("friends")}
onOpenSettings={() => handleFriendSettings(activeFriend)}
/>
)}
{screen === "friend-settings" && activeFriend && (
<FriendsManager
models={engine.sortedModels}
onBack={() => {
// Reload the friend data when coming back from settings
fetch(`/api/chat/friends/${activeFriend.id}`)
.then((r) => r.ok ? r.json() : null)
.then((data) => { if (data?.data) setActiveFriend(data.data as FriendProfile); })
.catch(() => {});
setScreen("friend-chat");
}}
onCall={handleFriendCall}
onChat={handleFriendChat}
/>
)}
{voiceCall.callState !== "idle" && (
<VoiceCallUI
callState={voiceCall.callState}
callModel={voiceCall.callModel}
callModelName={voiceCall.callModelName}
callDuration={voiceCall.callDuration}
isMuted={voiceCall.isMuted}
isDeafened={voiceCall.isDeafened}
showSubtitles={voiceCall.showSubtitles}
subtitleText={voiceCall.subtitleText}
subtitleProgress={voiceCall.subtitleProgress}
userSpeechText={voiceCall.userSpeechText}
activePopups={voiceCall.activePopups}
isAudioPlaying={voiceCall.isAudioPlaying}
onToggleMute={voiceCall.toggleMute}
onToggleDeafen={voiceCall.toggleDeafen}
onToggleSubtitles={voiceCall.toggleSubtitles}
onEndCall={voiceCall.endCall}
onDismissPopup={voiceCall.dismissPopup}
/>
)}
</div>
</div>
);
}
@@ -0,0 +1,97 @@
"use client";
import { ChevronLeft, Phone, Search, Star } from "lucide-react";
import { useState } from "react";
import { cn } from "@/lib/utils";
import type { ModelOption } from "../../types";
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
function getColor(id: string) {
const colors = ["bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500", "bg-rose-500", "bg-cyan-500"];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
export function ContactsScreen({
models,
favourites,
onSelect,
onCall,
onBack,
}: {
models: ModelOption[];
favourites: string[];
onSelect: (modelId: string) => void;
onCall?: (modelId: string) => void;
onBack: () => void;
}) {
const [search, setSearch] = useState("");
const filtered = search ? models.filter((m) => m.id.toLowerCase().includes(search.toLowerCase())) : models;
const starred = filtered.filter((m) => favourites.includes(m.id));
const rest = filtered.filter((m) => !favourites.includes(m.id));
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Contacts</h2>
<div className="w-12" />
</div>
<div className="px-3 pb-2">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<input type="text" value={search} onChange={(e) => setSearch(e.target.value)}
placeholder="Search" className="w-full rounded-lg bg-white/[0.06] py-2 pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground/40" />
</div>
</div>
<div className="flex-1 overflow-y-auto">
{starred.length > 0 && (
<>
<p className="px-4 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">
<Star className="mr-1 inline h-3 w-3 fill-amber-400 text-amber-400" />Starred
</p>
{starred.map((m) => (
<ContactRow key={m.id} m={m} starred onSelect={() => onSelect(m.id)} onCall={onCall ? () => onCall(m.id) : undefined} />
))}
</>
)}
<p className="px-4 pb-1 pt-3 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">All</p>
{rest.map((m) => (
<ContactRow key={m.id} m={m} starred={false} onSelect={() => onSelect(m.id)} onCall={onCall ? () => onCall(m.id) : undefined} />
))}
</div>
</div>
);
}
function ContactRow({ m, starred, onSelect, onCall }: { m: ModelOption; starred: boolean; onSelect: () => void; onCall?: () => void }) {
return (
<div className="flex w-full items-center gap-3 px-4 py-2.5">
<button onClick={onSelect} className="flex flex-1 items-center gap-3 text-left active:bg-white/[0.04]">
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white", getColor(m.id))}>
{getInitials(m.id)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-sm font-medium">{m.id}</span>
{starred && <Star className="h-3 w-3 shrink-0 fill-amber-400 text-amber-400" />}
</div>
<p className="truncate text-xs text-muted-foreground/60">{m.providerId}</p>
</div>
</button>
{onCall && (
<button onClick={onCall} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-green-500/15 text-green-400 transition-colors hover:bg-green-500/25" title="Call">
<Phone className="h-4 w-4" />
</button>
)}
</div>
);
}
@@ -0,0 +1,76 @@
"use client";
import { useCallback, useRef } from "react";
import { ArrowUp, ChevronLeft, Square } from "lucide-react";
import { MicrophoneButton } from "../../MicrophoneButton";
import { ResizableTextarea, type ResizableTextareaHandle } from "../../ResizableTextarea";
import { useSpeechRecognition } from "../../useSpeechRecognition";
import { MessageThread } from "../MessageThread";
import type { ChatEngine } from "../../useChatEngine";
export function ConversationScreen({ engine, onBack }: { engine: ChatEngine; onBack: () => void }) {
const e = engine;
const resizableRef = useRef<ResizableTextareaHandle>(null);
const handleSpeechResult = useCallback((text: string, cursorPos: number) => {
e.setInput(prev => prev.slice(0, cursorPos) + text + prev.slice(cursorPos));
}, [e]);
const speech = useSpeechRecognition(handleSpeechResult);
return (
<div className="flex flex-1 flex-col">
{/* Header */}
<div className="flex items-center gap-2 border-b border-white/[0.06] px-2 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />
</button>
<div className="min-w-0 flex-1 text-center">
<p className="truncate text-sm font-semibold">{e.model}</p>
{e.providerForModel && <p className="text-[10px] text-muted-foreground/60">{e.providerForModel}</p>}
</div>
<div className="w-7" />
</div>
{/* Messages */}
<MessageThread messages={e.currentMessages} submitting={e.submitting} streamingText={e.streamingText} variant="phone" />
{/* Input */}
<div className="border-t border-white/[0.06] bg-[hsl(220,16%,5%)] px-2 py-2">
<div className="flex items-end gap-2">
<MicrophoneButton
isListening={speech.isListening} isSupported={speech.isSupported}
onToggle={() => {
if (speech.isListening) speech.stopListening();
else speech.startListening(resizableRef.current?.selectionStart ?? e.input.length);
}}
className="h-8 w-8 shrink-0"
/>
<div className="min-w-0 flex-1 rounded-2xl bg-white/[0.04]">
<ResizableTextarea
ref={resizableRef}
value={e.input}
onChange={(v) => e.setInput(v)}
onKeyDown={(ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); e.handleSubmit(); } }}
placeholder="Message..."
className="px-3 py-2"
/>
</div>
{e.submitting ? (
<button onClick={e.stopGeneration} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white/[0.1]">
<Square className="h-3.5 w-3.5" />
</button>
) : (
<button onClick={() => e.handleSubmit()} disabled={!e.input.trim() || !e.model}
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-500 text-white disabled:opacity-30">
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
{speech.isListening && speech.interimText && (
<p className="mt-1 px-2 text-xs text-red-400/70 italic truncate">{speech.interimText}</p>
)}
</div>
</div>
);
}
@@ -0,0 +1,28 @@
"use client";
import { Clock, Heart, MessageSquare, Phone, Settings } from "lucide-react";
export function HomeScreen({ onNavigate }: { onNavigate: (screen: string) => void }) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-8 px-6">
<div className="grid grid-cols-3 gap-6">
<AppIcon icon={<MessageSquare className="h-7 w-7" />} label="Messages" color="bg-blue-500" onClick={() => onNavigate("messages")} />
<AppIcon icon={<Phone className="h-7 w-7" />} label="Phone" color="bg-green-500" onClick={() => onNavigate("contacts")} />
<AppIcon icon={<Heart className="h-7 w-7" />} label="Friends" color="bg-pink-500" onClick={() => onNavigate("friends")} />
<AppIcon icon={<Clock className="h-7 w-7" />} label="Recents" color="bg-orange-500" onClick={() => onNavigate("call-history")} />
<AppIcon icon={<Settings className="h-7 w-7" />} label="Settings" color="bg-zinc-600" onClick={() => onNavigate("settings")} />
</div>
</div>
);
}
function AppIcon({ icon, label, color, onClick }: { icon: React.ReactNode; label: string; color: string; onClick: () => void }) {
return (
<button onClick={onClick} className="flex flex-col items-center gap-2">
<div className={`flex h-16 w-16 items-center justify-center rounded-2xl text-white shadow-lg ${color}`}>
{icon}
</div>
<span className="text-xs text-foreground/80">{label}</span>
</button>
);
}
@@ -0,0 +1,141 @@
"use client";
import { useEffect, useState } from "react";
import { ChevronLeft, MessageSquarePlus, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Conversation, FriendProfile } from "../../types";
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
function getColor(id: string) {
const colors = ["bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500", "bg-rose-500", "bg-cyan-500"];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
function timeAgo(dateStr: string) {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "now";
if (mins < 60) return `${mins}m`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h`;
const days = Math.floor(hrs / 24);
if (days < 7) return `${days}d`;
return `${Math.floor(days / 7)}w`;
}
interface MessagesScreenProps {
conversations: Conversation[];
friends: FriendProfile[];
onSelectConversation: (conv: Conversation) => void;
onSelectFriend: (friend: FriendProfile) => void;
onNewChat: () => void;
onBack: () => void;
}
export function MessagesScreen({ conversations, friends, onSelectConversation, onSelectFriend, onNewChat, onBack }: MessagesScreenProps) {
const [search, setSearch] = useState("");
// Build a combined list: friend chats + model chats, sorted by most recent
const friendConvIds = new Set(friends.map((f) => f.conversationId).filter(Boolean));
const modelChats = conversations.filter((c) => !friendConvIds.has(c.id));
const filteredModelChats = search
? modelChats.filter((c) => c.title.toLowerCase().includes(search.toLowerCase()) || c.model.toLowerCase().includes(search.toLowerCase()))
: modelChats;
const filteredFriends = search
? friends.filter((f) => f.name.toLowerCase().includes(search.toLowerCase()) || f.modelId.toLowerCase().includes(search.toLowerCase()))
: friends;
const isEmpty = filteredModelChats.length === 0 && filteredFriends.length === 0;
return (
<div className="flex flex-1 flex-col">
{/* Header */}
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Messages</h2>
<button onClick={onNewChat} className="text-blue-400" title="New chat">
<MessageSquarePlus className="h-5 w-5" />
</button>
</div>
{/* Search */}
<div className="px-3 pb-2">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<input
type="text" value={search} onChange={(e) => setSearch(e.target.value)}
placeholder="Search chats"
className="w-full rounded-lg bg-white/[0.06] py-2 pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground/40"
/>
</div>
</div>
{/* Chat list */}
<div className="flex-1 overflow-y-auto">
{isEmpty && !search && (
<div className="flex flex-col items-center justify-center py-16 text-center px-6">
<MessageSquarePlus className="mb-3 h-8 w-8 text-muted-foreground/30" />
<p className="text-sm text-muted-foreground">No messages yet</p>
<p className="mt-1 text-xs text-muted-foreground/50">Tap the compose button to start a chat</p>
</div>
)}
{isEmpty && search && (
<p className="py-12 text-center text-sm text-muted-foreground/50">No results</p>
)}
{/* Friend chats */}
{filteredFriends.length > 0 && (
<>
<p className="px-4 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">Friends</p>
{filteredFriends.map((f) => (
<button
key={f.id}
onClick={() => onSelectFriend(f)}
className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors active:bg-white/[0.04]"
>
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white", f.avatarColor || "bg-blue-500")}>
{f.name.split(/\s+/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2) || "?"}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{f.name}</p>
<p className="truncate text-xs text-muted-foreground/50">{f.characterStyle || f.modelId}</p>
</div>
</button>
))}
</>
)}
{/* Model chats */}
{filteredModelChats.length > 0 && (
<>
<p className="px-4 pb-1 pt-3 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/50">Recent</p>
{filteredModelChats.map((c) => (
<button
key={c.id}
onClick={() => onSelectConversation(c)}
className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors active:bg-white/[0.04]"
>
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white", getColor(c.model))}>
{getInitials(c.model)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{c.title || c.model}</p>
<p className="truncate text-xs text-muted-foreground/50">{c.model}</p>
</div>
<span className="shrink-0 text-[11px] text-muted-foreground/40">{timeAgo(c.updatedAt)}</span>
</button>
))}
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,120 @@
"use client";
import { useState } from "react";
import { ChevronLeft, ChevronRight, EyeOff, Mic, Monitor, Palette } from "lucide-react";
import { cn } from "@/lib/utils";
import { CustomCSSEditor } from "../CustomCSSEditor";
import type { CallSettings } from "../../types";
import { OPENAI_VOICES } from "../../call/voiceAssignment";
export function SettingsScreen({
onBack,
onSwitchToClassic,
incognito,
onToggleIncognito,
callSettings,
onCallSettingsChange,
}: {
onBack: () => void;
onSwitchToClassic: () => void;
incognito: boolean;
onToggleIncognito: () => void;
callSettings?: CallSettings;
onCallSettingsChange?: (cs: CallSettings) => void;
}) {
const [cssOpen, setCssOpen] = useState(false);
const [voiceCallsOpen, setVoiceCallsOpen] = useState(false);
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Settings</h2>
<div className="w-12" />
</div>
<div className="flex-1 overflow-y-auto px-4 pt-4">
<div className="space-y-1">
<SettingsRow icon={<Monitor className="h-4 w-4" />} label="Switch to Desktop" onClick={onSwitchToClassic} />
<SettingsRow icon={<Palette className="h-4 w-4" />} label="Custom CSS" onClick={() => setCssOpen(true)} />
<SettingsRow
icon={<EyeOff className="h-4 w-4" />}
label="Incognito Mode"
active={incognito}
onClick={onToggleIncognito}
/>
{callSettings && onCallSettingsChange && (
<SettingsRow
icon={<Mic className="h-4 w-4" />}
label="Voice Calls"
onClick={() => setVoiceCallsOpen(!voiceCallsOpen)}
/>
)}
</div>
{voiceCallsOpen && callSettings && onCallSettingsChange && (
<div className="mt-3 space-y-4 rounded-xl bg-white/[0.03] p-4">
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">
Speech Pause Duration: {callSettings.speechPauseDuration}ms
</label>
<input
type="range" min="500" max="3000" step="100"
value={callSettings.speechPauseDuration}
onChange={(ev) => onCallSettingsChange({ ...callSettings, speechPauseDuration: parseInt(ev.target.value) })}
className="w-full accent-blue-500"
/>
</div>
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-muted-foreground">Deafen by Default</label>
<button
onClick={() => onCallSettingsChange({ ...callSettings, deafenByDefault: !callSettings.deafenByDefault })}
className={cn(
"h-6 w-10 rounded-full transition-colors",
callSettings.deafenByDefault ? "bg-blue-500" : "bg-white/20",
)}
>
<div className={cn(
"h-5 w-5 rounded-full bg-white shadow transition-transform",
callSettings.deafenByDefault ? "translate-x-[18px]" : "translate-x-[2px]",
)} />
</button>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">Global Voice Override</label>
<select
value={callSettings.globalVoiceOverride ?? ""}
onChange={(ev) => onCallSettingsChange({ ...callSettings, globalVoiceOverride: ev.target.value || undefined })}
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30"
>
<option value="">Auto (hash-based)</option>
{OPENAI_VOICES.map((v) => (<option key={v} value={v}>{v}</option>))}
</select>
</div>
</div>
)}
</div>
{cssOpen && <CustomCSSEditor onClose={() => setCssOpen(false)} />}
</div>
);
}
function SettingsRow({ icon, label, active, onClick }: { icon: React.ReactNode; label: string; active?: boolean; onClick: () => void }) {
return (
<button
onClick={onClick}
className={cn(
"flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left text-sm transition-colors",
active ? "bg-violet-500/15 text-violet-400" : "bg-white/[0.03] text-foreground active:bg-white/[0.06]",
)}
>
{icon}
<span className="flex-1">{label}</span>
{!active && <ChevronRight className="h-4 w-4 text-muted-foreground/40" />}
{active && <div className="h-2 w-2 rounded-full bg-violet-400" />}
</button>
);
}
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { Captions, Mic, MicOff, PhoneOff, Volume2, VolumeX } from "lucide-react";
import { cn } from "@/lib/utils";
interface CallControlsProps {
isMuted: boolean;
isDeafened: boolean;
showSubtitles: boolean;
onToggleMute: () => void;
onToggleDeafen: () => void;
onToggleSubtitles: () => void;
onEndCall: () => void;
}
export function CallControls({ isMuted, isDeafened, showSubtitles, onToggleMute, onToggleDeafen, onToggleSubtitles, onEndCall }: CallControlsProps) {
return (
<div className="flex items-center justify-center gap-5">
<ControlButton
icon={isMuted ? <MicOff className="h-5 w-5" /> : <Mic className="h-5 w-5" />}
active={isMuted}
activeColor="bg-red-500/20 text-red-400"
onClick={onToggleMute}
label={isMuted ? "Unmute" : "Mute"}
/>
<ControlButton
icon={isDeafened ? <VolumeX className="h-5 w-5" /> : <Volume2 className="h-5 w-5" />}
active={isDeafened}
activeColor="bg-red-500/20 text-red-400"
onClick={onToggleDeafen}
label={isDeafened ? "Undeafen" : "Deafen"}
/>
<ControlButton
icon={<Captions className="h-5 w-5" />}
active={showSubtitles}
activeColor="bg-blue-500/20 text-blue-400"
onClick={onToggleSubtitles}
label="Subtitles"
/>
<button
onClick={onEndCall}
className="flex h-14 w-14 items-center justify-center rounded-full bg-red-500 text-white shadow-lg transition-transform active:scale-95"
title="End call"
>
<PhoneOff className="h-6 w-6" />
</button>
</div>
);
}
function ControlButton({ icon, active, activeColor, onClick, label }: {
icon: React.ReactNode; active: boolean; activeColor: string; onClick: () => void; label: string;
}) {
return (
<button
onClick={onClick}
className={cn(
"flex h-12 w-12 items-center justify-center rounded-full transition-colors",
active ? activeColor : "bg-white/10 text-white hover:bg-white/15",
)}
title={label}
>
{icon}
</button>
);
}
+91
View File
@@ -0,0 +1,91 @@
"use client";
import { useEffect, useState } from "react";
import { ChevronLeft, Clock, Phone } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Conversation } from "../types";
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
function getColor(id: string) {
const colors = ["bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500", "bg-rose-500", "bg-cyan-500"];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
function formatRelativeTime(date: string) {
const diff = Date.now() - new Date(date).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "Just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
function formatDuration(seconds: number) {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${s.toString().padStart(2, "0")}`;
}
interface CallHistoryProps {
onBack: () => void;
onSelectCall: (conv: Conversation) => void;
}
export function CallHistory({ onBack, onSelectCall }: CallHistoryProps) {
const [calls, setCalls] = useState<Conversation[]>([]);
useEffect(() => {
fetch("/api/chat/conversations?type=call")
.then((r) => (r.ok ? r.json() : null))
.then((data) => { if (data?.data) setCalls(data.data); })
.catch(() => {});
}, []);
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Recents</h2>
<div className="w-12" />
</div>
<div className="flex-1 overflow-y-auto">
{calls.length === 0 && (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Phone className="mb-3 h-8 w-8 text-muted-foreground/40" />
<p className="text-sm text-muted-foreground">No recent calls</p>
</div>
)}
{calls.map((call) => (
<button
key={call.id}
onClick={() => onSelectCall(call)}
className="flex w-full items-center gap-3 px-4 py-3 text-left active:bg-white/[0.04]"
>
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white", getColor(call.model))}>
{getInitials(call.model)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{call.model}</p>
<div className="flex items-center gap-2 text-xs text-muted-foreground/60">
<Phone className="h-3 w-3" />
{call.callDuration != null && <span>{formatDuration(call.callDuration)}</span>}
<span>{formatRelativeTime(call.updatedAt)}</span>
</div>
</div>
<Clock className="h-4 w-4 text-muted-foreground/40" />
</button>
))}
</div>
</div>
);
}
@@ -0,0 +1,79 @@
"use client";
import { useEffect, useState } from "react";
import { ChevronLeft, Phone, User } from "lucide-react";
import { cn } from "@/lib/utils";
import { MarkdownContent } from "../MarkdownContent";
import type { ChatMessage, Conversation } from "../types";
function getColor(id: string) {
const colors = ["bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500", "bg-rose-500", "bg-cyan-500"];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
interface CallHistoryDetailProps {
conversation: Conversation;
onBack: () => void;
}
export function CallHistoryDetail({ conversation, onBack }: CallHistoryDetailProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
useEffect(() => {
fetch(`/api/chat/conversations/${conversation.id}/messages`)
.then((r) => (r.ok ? r.json() : null))
.then((data) => { if (data?.data) setMessages(data.data); })
.catch(() => {});
}, [conversation.id]);
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Transcript</h2>
<div className="w-12" />
</div>
<div className="flex items-center gap-3 border-b border-white/[0.06] px-4 py-3">
<div className={cn("flex h-10 w-10 items-center justify-center rounded-full text-xs font-bold text-white", getColor(conversation.model))}>
{getInitials(conversation.model)}
</div>
<div>
<p className="text-sm font-medium">{conversation.model}</p>
<p className="text-xs text-muted-foreground/60">{conversation.title}</p>
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
{messages.map((msg, i) => (
<div key={msg.id ?? i} className="flex gap-3">
<div className={cn(
"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[10px] font-bold",
msg.role === "user" ? "bg-white/10 text-white/60" : cn(getColor(conversation.model), "text-white"),
)}>
{msg.role === "user" ? <User className="h-3.5 w-3.5" /> : getInitials(conversation.model)}
</div>
<div className="min-w-0 flex-1 text-sm">
{msg.role === "user" ? (
<p className="text-white/80">{msg.content}</p>
) : (
<MarkdownContent content={msg.content} />
)}
</div>
</div>
))}
{messages.length === 0 && (
<p className="text-center text-sm text-muted-foreground/60 py-8">No messages in this call</p>
)}
</div>
</div>
);
}
@@ -0,0 +1,33 @@
"use client";
interface CallSubtitlesProps {
userSpeechText: string;
subtitleText: string;
subtitleProgress: number;
}
export function CallSubtitles({ userSpeechText, subtitleText, subtitleProgress }: CallSubtitlesProps) {
if (!userSpeechText && !subtitleText) return null;
const words = subtitleText.split(/\s+/).filter(Boolean);
const revealedCount = Math.ceil(subtitleProgress * words.length);
return (
<div className="absolute inset-x-0 bottom-28 flex flex-col items-center gap-2 px-6">
<div className="max-w-sm rounded-xl bg-black/70 px-4 py-3 backdrop-blur-sm">
{userSpeechText && (
<p className="text-sm italic text-white/60">{userSpeechText}</p>
)}
{subtitleText && (
<p className="mt-1 text-sm text-white">
{words.map((word, i) => (
<span key={i} className={i < revealedCount ? "text-white" : "text-white/30"}>
{i > 0 ? " " : ""}{word}
</span>
))}
</p>
)}
</div>
</div>
);
}
@@ -0,0 +1,26 @@
"use client";
import { X } from "lucide-react";
import { MarkdownContent } from "../MarkdownContent";
import type { VisualPopup } from "../types";
interface CallVisualPopupProps {
popup: VisualPopup;
onDismiss: (id: string) => void;
}
export function CallVisualPopup({ popup, onDismiss }: CallVisualPopupProps) {
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="relative mx-4 max-h-[70vh] w-full max-w-lg overflow-y-auto rounded-2xl border border-white/10 bg-[hsl(220,16%,10%)] p-6 shadow-2xl">
<button
onClick={() => onDismiss(popup.id)}
className="absolute right-3 top-3 rounded-lg p-1.5 text-muted-foreground hover:bg-white/10 hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
<MarkdownContent content={popup.content} />
</div>
</div>
);
}
@@ -0,0 +1,268 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { ArrowUp, ChevronLeft, Settings, Square } from "lucide-react";
import { cn } from "@/lib/utils";
import type { ChatMessage, FriendProfile, ModelOption } from "../types";
import { parseSSELines } from "../parseSSELines";
import { MarkdownContent } from "../MarkdownContent";
import { ResizableTextarea, type ResizableTextareaHandle } from "../ResizableTextarea";
import { MicrophoneButton } from "../MicrophoneButton";
import { useSpeechRecognition } from "../useSpeechRecognition";
const FRIEND_SYSTEM_PROMPT_PREFIX = `You are a friend of the user. You have an ongoing persistent relationship with them — you remember past conversations and build on them.
Stay in character at all times. Be natural, warm, and authentic to your personality.
You are NOT an AI assistant — you are a friend. Don't offer to help with tasks unless asked. Just be a genuine friend who engages in natural conversation.`;
function getInitials(name: string) {
return name.split(/\s+/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2) || "?";
}
interface FriendConversationScreenProps {
friend: FriendProfile;
onBack: () => void;
onOpenSettings: () => void;
}
export function FriendConversationScreen({ friend, onBack, onOpenSettings }: FriendConversationScreenProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState("");
const [submitting, setSubmitting] = useState(false);
const [streamingText, setStreamingText] = useState("");
const abortRef = useRef<AbortController | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const resizableRef = useRef<ResizableTextareaHandle>(null);
const handleSpeechResult = useCallback((text: string, cursorPos: number) => {
setInput(prev => prev.slice(0, cursorPos) + text + prev.slice(cursorPos));
}, []);
const speech = useSpeechRecognition(handleSpeechResult);
// Load existing messages
useEffect(() => {
if (!friend.conversationId) return;
fetch(`/api/chat/conversations/${friend.conversationId}/messages`)
.then((r) => (r.ok ? r.json() : null))
.then((data) => { if (data?.data) setMessages(data.data); })
.catch(() => {});
}, [friend.conversationId]);
// Auto scroll
useEffect(() => {
requestAnimationFrame(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
});
}, [messages, submitting, streamingText]);
function buildSystemPrompt() {
const parts = [FRIEND_SYSTEM_PROMPT_PREFIX];
if (friend.name) parts.push(`Your name is "${friend.name}". Always respond as this character.`);
if (friend.characterStyle) parts.push(`Your personality and style: ${friend.characterStyle}`);
if (friend.systemPrompt) parts.push(friend.systemPrompt);
return parts.join("\n\n");
}
async function ensureConversation(): Promise<string | null> {
if (friend.conversationId) return friend.conversationId;
try {
const res = await fetch(`/api/chat/friends/${friend.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ensureConversation: true }),
});
if (res.ok) {
const data = await res.json();
const convId = data.data?.conversationId as string | undefined;
if (convId) {
friend.conversationId = convId;
return convId;
}
}
} catch { /* skip */ }
return null;
}
async function handleSubmit() {
console.log("[FriendChat handleSubmit]", { input, submitting, conversationId: friend.conversationId, friendId: friend.id });
if (!input.trim() || submitting) return;
const convId = await ensureConversation();
if (!convId) return;
const text = input.trim();
setInput("");
setStreamingText("");
const userMsg: ChatMessage = { role: "user", content: text };
setMessages((prev) => [...prev, userMsg]);
setSubmitting(true);
const abort = new AbortController();
abortRef.current = abort;
try {
const res = await fetch(`/api/chat/conversations/${convId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content: text,
model: friend.modelId,
systemPrompt: buildSystemPrompt(),
}),
signal: abort.signal,
});
if (!res.ok || !res.body) {
setMessages((prev) => prev.slice(0, -1));
setInput(text);
setSubmitting(false);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullText = "";
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.data === "[DONE]" || evt.event === "meta" || evt.event === "done") continue;
try {
const json = JSON.parse(evt.data);
const delta = json.choices?.[0]?.delta;
if (delta?.content) {
fullText += delta.content;
setStreamingText(fullText);
}
} catch { /* skip */ }
}
}
setMessages((prev) => [...prev, { role: "assistant", content: fullText, model: friend.modelId }]);
} catch (err) {
if ((err as Error).name !== "AbortError") {
setMessages((prev) => prev.slice(0, -1));
setInput(text);
}
}
setStreamingText("");
setSubmitting(false);
}
return (
<div className="flex flex-1 flex-col">
{/* Header */}
<div className="flex items-center gap-2 border-b border-white/[0.06] px-2 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />
</button>
<div className={cn("flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold text-white", friend.avatarColor || "bg-blue-500")}>
{getInitials(friend.name)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{friend.name}</p>
<p className="text-[10px] text-muted-foreground/60">{friend.modelId}</p>
</div>
<button onClick={onOpenSettings} className="rounded-lg p-1.5 text-muted-foreground hover:text-foreground">
<Settings className="h-4 w-4" />
</button>
</div>
{/* Messages */}
<div ref={scrollRef} className="flex-1 overflow-y-auto px-3 py-4 space-y-4">
{messages.length === 0 && !submitting && (
<div className="flex flex-col items-center justify-center py-12 text-center">
<div className={cn("flex h-14 w-14 items-center justify-center rounded-full text-lg font-bold text-white mb-3", friend.avatarColor || "bg-blue-500")}>
{getInitials(friend.name)}
</div>
<p className="text-sm text-muted-foreground">Start chatting with {friend.name}</p>
{friend.characterStyle && (
<p className="mt-1 text-xs text-muted-foreground/60 max-w-[200px]">{friend.characterStyle}</p>
)}
</div>
)}
{messages.map((msg, i) => (
<div key={msg.id ?? i} className={cn("flex gap-2", msg.role === "user" ? "justify-end" : "justify-start")}>
{msg.role === "assistant" && (
<div className={cn("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[9px] font-bold text-white", friend.avatarColor || "bg-blue-500")}>
{getInitials(friend.name)}
</div>
)}
<div className={cn(
"max-w-[80%] rounded-2xl px-3 py-2 text-sm",
msg.role === "user"
? "bg-blue-500 text-white rounded-br-sm"
: "bg-white/[0.06] text-foreground rounded-bl-sm",
)}>
{msg.role === "assistant" ? <MarkdownContent content={msg.content} /> : msg.content}
</div>
</div>
))}
{submitting && streamingText && (
<div className="flex gap-2 justify-start">
<div className={cn("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[9px] font-bold text-white", friend.avatarColor || "bg-blue-500")}>
{getInitials(friend.name)}
</div>
<div className="max-w-[80%] rounded-2xl rounded-bl-sm bg-white/[0.06] px-3 py-2 text-sm">
<MarkdownContent content={streamingText} />
<span className="ml-0.5 inline-block h-3 w-[2px] animate-pulse bg-blue-400 align-middle" />
</div>
</div>
)}
{submitting && !streamingText && (
<div className="flex gap-2 justify-start">
<div className={cn("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[9px] font-bold text-white", friend.avatarColor || "bg-blue-500")}>
{getInitials(friend.name)}
</div>
<div className="flex items-center gap-1 rounded-2xl rounded-bl-sm bg-white/[0.06] px-4 py-3">
<div className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/40" />
<div className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/40 [animation-delay:150ms]" />
<div className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/40 [animation-delay:300ms]" />
</div>
</div>
)}
</div>
{/* Input */}
<div className="border-t border-white/[0.06] bg-[hsl(220,16%,5%)] px-2 py-2">
<div className="flex items-end gap-2">
<MicrophoneButton
isListening={speech.isListening} isSupported={speech.isSupported}
onToggle={() => {
if (speech.isListening) speech.stopListening();
else speech.startListening(resizableRef.current?.selectionStart ?? input.length);
}}
className="h-8 w-8 shrink-0"
/>
<div className="min-w-0 flex-1 rounded-2xl bg-white/[0.04]">
<ResizableTextarea
ref={resizableRef}
value={input}
onChange={(v) => setInput(v)}
onKeyDown={(ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); handleSubmit(); } }}
placeholder={`Message ${friend.name}...`}
className="px-3 py-2"
/>
</div>
{submitting ? (
<button onClick={() => abortRef.current?.abort()} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white/[0.1]">
<Square className="h-3.5 w-3.5" />
</button>
) : (
<button onClick={handleSubmit} disabled={!input.trim()}
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-500 text-white disabled:opacity-30">
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
{speech.isListening && speech.interimText && (
<p className="mt-1 px-2 text-xs text-red-400/70 italic truncate">{speech.interimText}</p>
)}
</div>
</div>
);
}
+628
View File
@@ -0,0 +1,628 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronLeft, Edit2, MessageSquare, Phone, Play, Plus, Square, Trash2, UserPlus, X } from "lucide-react";
import { cn } from "@/lib/utils";
import type { FriendProfile, FriendVoiceSettings, ModelOption } from "../types";
import { OPENAI_VOICES } from "./voiceAssignment";
const AVATAR_COLORS = [
"bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500",
"bg-rose-500", "bg-cyan-500", "bg-pink-500", "bg-teal-500",
"bg-indigo-500", "bg-orange-500",
];
const ELEVENLABS_MODELS = [
{ id: "eleven_multilingual_v2", label: "Multilingual v2 (Default)" },
{ id: "eleven_turbo_v2_5", label: "Turbo v2.5" },
{ id: "eleven_turbo_v2", label: "Turbo v2" },
{ id: "eleven_monolingual_v1", label: "Monolingual v1" },
{ id: "eleven_multilingual_v1", label: "Multilingual v1" },
];
const VOICE_PREVIEW_LINES = [
"Hey! It's so good to hear from you. How's your day going?",
"Oh wow, I was just thinking about you! What's new?",
"Well hello there, stranger! Long time no talk.",
"Hi! I just got the funniest idea — you're gonna love this.",
"Hey, perfect timing! I literally just sat down. What's up?",
];
const OPENAI_TTS_MODELS = [
{ id: "tts-1", label: "TTS-1 (Fast)" },
{ id: "tts-1-hd", label: "TTS-1 HD (High Quality)" },
];
function getInitials(name: string) {
return name.split(/\s+/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2) || "?";
}
function parseFriend(f: Record<string, unknown>): FriendProfile {
return {
id: f.id as string,
name: f.name as string,
modelId: f.modelId as string,
systemPrompt: f.systemPrompt as string | undefined,
characterStyle: f.characterStyle as string | undefined,
avatarColor: f.avatarColor as string | undefined,
voiceSettings: f.voiceSettings as FriendVoiceSettings | undefined,
conversationId: f.conversationId as string | undefined,
ttsModel: f.ttsModel as string | undefined,
voiceId: f.voiceId as string | undefined,
};
}
interface FriendsManagerProps {
models: ModelOption[];
onBack: () => void;
onCall?: (friend: FriendProfile) => void;
onChat?: (friend: FriendProfile) => void;
onOpenSettings?: (friend: FriendProfile) => void;
}
export function FriendsManager({ models, onBack, onCall, onChat, onOpenSettings }: FriendsManagerProps) {
const [friends, setFriends] = useState<FriendProfile[]>([]);
const [editing, setEditing] = useState<FriendProfile | null>(null);
const [creating, setCreating] = useState(false);
const loadFriends = useCallback(async () => {
const res = await fetch("/api/chat/friends");
if (res.ok) {
const data = await res.json();
setFriends((data.data ?? []).map((f: Record<string, unknown>) => parseFriend(f)));
}
}, []);
useEffect(() => { loadFriends(); }, [loadFriends]);
async function handleDelete(id: string) {
if (!confirm("Delete this friend? All chat history will be lost.")) return;
await fetch(`/api/chat/friends/${id}`, { method: "DELETE" });
loadFriends();
}
if (editing || creating) {
return (
<FriendEditor
friend={editing}
models={models}
onSave={async (data) => {
if (editing) {
await fetch(`/api/chat/friends/${editing.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
} else {
await fetch("/api/chat/friends", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
}
setEditing(null);
setCreating(false);
loadFriends();
}}
onCancel={() => { setEditing(null); setCreating(false); }}
/>
);
}
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onBack} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Friends</h2>
<button onClick={() => setCreating(true)} className="text-blue-400">
<Plus className="h-5 w-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto">
{friends.length === 0 && (
<div className="flex flex-col items-center justify-center py-16 text-center px-6">
<UserPlus className="mb-3 h-8 w-8 text-muted-foreground/40" />
<p className="text-sm text-muted-foreground">No friends yet</p>
<p className="mt-1 text-xs text-muted-foreground/60">
Create custom contacts with their own personality, voice, and model
</p>
<button
onClick={() => setCreating(true)}
className="mt-4 rounded-lg bg-blue-500/10 px-4 py-2 text-sm text-blue-400 transition-colors hover:bg-blue-500/20"
>
Add Friend
</button>
</div>
)}
{friends.map((f) => (
<div key={f.id} className="flex items-center gap-3 px-4 py-3">
<div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white", f.avatarColor || "bg-blue-500")}>
{getInitials(f.name)}
</div>
<button
onClick={() => onChat?.(f)}
className="min-w-0 flex-1 text-left"
>
<p className="truncate text-sm font-medium">{f.name}</p>
<p className="truncate text-xs text-muted-foreground/60">
{f.characterStyle || f.modelId}
</p>
</button>
<div className="flex items-center gap-0.5">
{onChat && (
<button onClick={() => onChat(f)} className="rounded-full p-1.5 text-blue-400 hover:bg-blue-500/15" title="Message">
<MessageSquare className="h-4 w-4" />
</button>
)}
{onCall && (
<button onClick={() => onCall(f)} className="rounded-full p-1.5 text-green-400 hover:bg-green-500/15" title="Call">
<Phone className="h-4 w-4" />
</button>
)}
<button onClick={() => setEditing(f)} className="rounded-full p-1.5 text-muted-foreground hover:bg-white/10" title="Edit">
<Edit2 className="h-3.5 w-3.5" />
</button>
<button onClick={() => handleDelete(f.id)} className="rounded-full p-1.5 text-muted-foreground hover:text-red-400 hover:bg-red-500/10" title="Delete">
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
))}
</div>
</div>
);
}
function FriendEditor({ friend, models, onSave, onCancel }: {
friend: FriendProfile | null;
models: ModelOption[];
onSave: (data: Partial<FriendProfile>) => void;
onCancel: () => void;
}) {
const [name, setName] = useState(friend?.name ?? "");
const [modelId, setModelId] = useState(friend?.modelId ?? models.find((m) => m.modelType === "chat")?.id ?? "");
const [systemPrompt, setSystemPrompt] = useState(friend?.systemPrompt ?? "");
const [characterStyle, setCharacterStyle] = useState(friend?.characterStyle ?? "");
const [avatarColor, setAvatarColor] = useState(friend?.avatarColor ?? AVATAR_COLORS[0]);
// Voice settings — default to ElevenLabs
const existingVS = friend?.voiceSettings;
const [ttsProvider, setTtsProvider] = useState<"openai" | "elevenlabs">(existingVS?.ttsProvider ?? "elevenlabs");
const [ttsModel, setTtsModel] = useState(existingVS?.ttsModel ?? "eleven_multilingual_v2");
const [openaiVoice, setOpenaiVoice] = useState(existingVS?.openaiVoice ?? "alloy");
const [openaiSpeed, setOpenaiSpeed] = useState(existingVS?.openaiSpeed ?? 1);
const [elevenVoiceId, setElevenVoiceId] = useState(existingVS?.elevenVoiceId ?? "");
const [elevenStability, setElevenStability] = useState(existingVS?.elevenStability ?? 0.5);
const [elevenSimilarityBoost, setElevenSimilarityBoost] = useState(existingVS?.elevenSimilarityBoost ?? 0.75);
const [elevenStyle, setElevenStyle] = useState(existingVS?.elevenStyle ?? 0);
const [elevenSpeed, setElevenSpeed] = useState(existingVS?.elevenSpeed ?? 1);
// Voice preview
const [previewing, setPreviewing] = useState(false);
const previewAudioRef = useRef<HTMLAudioElement | null>(null);
function stopPreview() {
if (previewAudioRef.current) {
previewAudioRef.current.pause();
previewAudioRef.current = null;
}
setPreviewing(false);
}
function buildTTSBody(line: string): Record<string, unknown> {
return ttsProvider === "openai"
? { model: ttsModel, input: line, voice: openaiVoice, ...(openaiSpeed !== 1 ? { speed: openaiSpeed } : {}) }
: {
model: ttsModel, input: line,
voice: elevenVoiceId || "Rachel",
voice_id: elevenVoiceId || undefined,
model_id: ttsModel,
...(elevenStability != null ? { stability: elevenStability } : {}),
...(elevenSimilarityBoost != null ? { similarity_boost: elevenSimilarityBoost } : {}),
...(elevenStyle != null ? { style: elevenStyle } : {}),
...(elevenSpeed != null ? { speed: elevenSpeed } : {}),
};
}
async function playTTSLine(line: string) {
try {
const res = await fetch("/api/chat/generate-audio", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildTTSBody(line)),
});
if (!res.ok) { setPreviewing(false); return; }
const data = await res.json();
if (data.audio?.b64) {
const audio = new Audio(`data:${data.audio.contentType ?? "audio/mpeg"};base64,${data.audio.b64}`);
previewAudioRef.current = audio;
audio.onended = () => setPreviewing(false);
audio.onerror = () => setPreviewing(false);
await audio.play();
} else {
setPreviewing(false);
}
} catch {
setPreviewing(false);
}
}
async function playVoicePreview() {
if (previewing) { stopPreview(); return; }
setPreviewing(true);
const line = VOICE_PREVIEW_LINES[Math.floor(Math.random() * VOICE_PREVIEW_LINES.length)];
await playTTSLine(line);
}
async function playCharacterPreview() {
if (previewing) { stopPreview(); return; }
setPreviewing(true);
try {
const prompt = [
`Generate a single short greeting line (1-2 sentences max) as this character would say it.`,
name ? `Character name: ${name}` : null,
characterStyle ? `Personality: ${characterStyle}` : null,
systemPrompt ? `Character info: ${systemPrompt}` : null,
`Reply with ONLY the greeting line, nothing else. No quotes.`,
].filter(Boolean).join("\n");
const res = await fetch("/api/chat/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: modelId, messages: [{ role: "user", content: prompt }], max_tokens: 100 }),
});
if (!res.ok) { setPreviewing(false); return; }
const data = await res.json();
const line = data.choices?.[0]?.message?.content?.trim();
if (!line) { setPreviewing(false); return; }
await playTTSLine(line);
} catch {
setPreviewing(false);
}
}
const [elevenUseCustomId, setElevenUseCustomId] = useState(
// If the saved voice ID doesn't match any loaded voice, assume custom
!!existingVS?.elevenVoiceId && existingVS.elevenVoiceId.length > 0,
);
const [elevenCustomId, setElevenCustomId] = useState(existingVS?.elevenVoiceId ?? "");
// Load ElevenLabs voices
const [elevenVoices, setElevenVoices] = useState<Array<{ voice_id: string; name: string; category: string }>>([]);
useEffect(() => {
fetch("/api/chat/elevenlabs-voices")
.then((r) => (r.ok ? r.json() : null))
.then((data) => {
if (data?.voices?.length) {
setElevenVoices(data.voices);
const knownIds = new Set(data.voices.map((v: { voice_id: string }) => v.voice_id));
if (elevenVoiceId && !knownIds.has(elevenVoiceId)) {
// Saved ID is not in the list — treat as custom
setElevenUseCustomId(true);
setElevenCustomId(elevenVoiceId);
} else if (!elevenVoiceId && data.voices[0]) {
setElevenVoiceId(data.voices[0].voice_id);
setElevenUseCustomId(false);
} else {
setElevenUseCustomId(false);
}
}
})
.catch(() => {});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// Memory management
const [memoryCount, setMemoryCount] = useState<number | null>(null);
const [showMemory, setShowMemory] = useState(false);
const [memoryMessages, setMemoryMessages] = useState<Array<{ role: string; content: string; createdAt?: string }>>([]);
useEffect(() => {
if (friend?.id) {
fetch(`/api/chat/friends/${friend.id}/memory`)
.then((r) => (r.ok ? r.json() : null))
.then((data) => { if (data?.data) setMemoryCount(data.data.messageCount); })
.catch(() => {});
}
}, [friend?.id]);
async function loadMemory() {
if (!friend?.id) return;
const res = await fetch(`/api/chat/friends/${friend.id}/memory`);
if (res.ok) {
const data = await res.json();
setMemoryMessages(data.data?.messages ?? []);
setShowMemory(true);
}
}
async function clearMemory() {
if (!friend?.id || !confirm("Clear all conversation history? This cannot be undone.")) return;
await fetch(`/api/chat/friends/${friend.id}/memory`, { method: "DELETE" });
setMemoryCount(0);
setMemoryMessages([]);
setShowMemory(false);
}
const chatModels = models.filter((m) => m.modelType === "chat");
function handleSave() {
const voiceSettings: FriendVoiceSettings = {
ttsProvider,
ttsModel,
openaiVoice,
openaiSpeed,
elevenVoiceId: elevenVoiceId || undefined,
elevenStability,
elevenSimilarityBoost,
elevenStyle,
elevenSpeed,
};
onSave({
name, modelId,
systemPrompt: systemPrompt || undefined,
characterStyle: characterStyle || undefined,
avatarColor,
voiceSettings,
});
}
// Memory viewer
if (showMemory) {
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={() => setShowMemory(false)} className="flex items-center text-blue-400 text-sm">
<ChevronLeft className="h-5 w-5" />Back
</button>
<h2 className="flex-1 text-center text-sm font-semibold">Memory ({memoryMessages.length} messages)</h2>
<button onClick={clearMemory} className="text-xs text-red-400">Clear</button>
</div>
<div className="flex-1 overflow-y-auto px-4 py-2 space-y-3">
{memoryMessages.length === 0 && (
<p className="text-center text-sm text-muted-foreground/60 py-8">No messages yet</p>
)}
{memoryMessages.map((msg, i) => (
<div key={i} className={cn("text-xs", msg.role === "user" ? "text-blue-300" : "text-white/70")}>
<span className="font-medium text-muted-foreground/60">{msg.role === "user" ? "You" : friend?.name ?? "Friend"}:</span>{" "}
{msg.content.length > 200 ? msg.content.slice(0, 200) + "..." : msg.content}
</div>
))}
</div>
</div>
);
}
return (
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2 px-3 py-2">
<button onClick={onCancel} className="flex items-center text-blue-400 text-sm">
<X className="h-5 w-5" />
</button>
<h2 className="flex-1 text-center text-sm font-semibold">
{friend ? "Edit Friend" : "New Friend"}
</h2>
<button onClick={handleSave} disabled={!name.trim() || !modelId}
className="text-sm text-blue-400 disabled:text-muted-foreground/40">
Save
</button>
</div>
<div className="flex-1 overflow-y-auto px-4 pt-2 space-y-4 pb-6">
{/* Avatar preview */}
<div className="flex flex-col items-center gap-3">
<div className={cn("flex h-16 w-16 items-center justify-center rounded-full text-xl font-bold text-white", avatarColor)}>
{getInitials(name || "?")}
</div>
<div className="flex gap-1.5 flex-wrap justify-center">
{AVATAR_COLORS.map((c) => (
<button key={c} onClick={() => setAvatarColor(c)} className={cn("h-5 w-5 rounded-full", c, avatarColor === c && "ring-2 ring-white ring-offset-2 ring-offset-[hsl(220,16%,7%)]")} />
))}
</div>
</div>
<Field label="Name">
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Luna, Marcus, Dr. Smith..."
className="input-field" />
</Field>
<Field label="Chat Model">
<select value={modelId} onChange={(e) => setModelId(e.target.value)} className="input-field">
{chatModels.map((m) => <option key={m.id} value={m.id}>{m.id} ({m.providerId})</option>)}
</select>
</Field>
<Field label="Character Style" hint="Brief personality description">
<input value={characterStyle} onChange={(e) => setCharacterStyle(e.target.value)}
placeholder="e.g. Warm and witty, speaks casually, uses humor..."
className="input-field" />
</Field>
<Field label="System Prompt" hint="Custom instructions for this friend">
<textarea value={systemPrompt} onChange={(e) => setSystemPrompt(e.target.value)} rows={3}
placeholder="e.g. You are a supportive friend who loves hiking and cooking..."
className="input-field resize-none" />
</Field>
{/* Voice Settings Section */}
<div className="border-t border-white/[0.06] pt-4">
<p className="mb-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Voice Settings</p>
<Field label="TTS Provider">
<select value={ttsProvider} onChange={(e) => {
const p = e.target.value as "openai" | "elevenlabs";
setTtsProvider(p);
setTtsModel(p === "elevenlabs" ? "eleven_multilingual_v2" : "tts-1");
}} className="input-field">
<option value="elevenlabs">ElevenLabs (Recommended)</option>
<option value="openai">OpenAI</option>
</select>
</Field>
<div className="mt-3">
<Field label="TTS Model">
<select value={ttsModel} onChange={(e) => setTtsModel(e.target.value)} className="input-field">
{ttsProvider === "elevenlabs"
? ELEVENLABS_MODELS.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)
: OPENAI_TTS_MODELS.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)
}
</select>
</Field>
</div>
{ttsProvider === "openai" && (
<div className="mt-3 space-y-3">
<Field label="Voice">
<select value={openaiVoice} onChange={(e) => setOpenaiVoice(e.target.value)} className="input-field">
{OPENAI_VOICES.map((v) => <option key={v} value={v}>{v}</option>)}
</select>
</Field>
<Field label={`Speed: ${openaiSpeed.toFixed(2)}x`}>
<input type="range" min="0.25" max="4" step="0.05" value={openaiSpeed}
onChange={(e) => setOpenaiSpeed(parseFloat(e.target.value))} className="w-full accent-blue-500" />
</Field>
</div>
)}
{ttsProvider === "elevenlabs" && (
<div className="mt-3 space-y-3">
<Field label="Voice">
<div className="flex items-center gap-2 mb-1.5">
<button
type="button"
onClick={() => {
setElevenUseCustomId(false);
if (elevenVoices[0]) setElevenVoiceId(elevenVoices[0].voice_id);
}}
className={cn("rounded-md px-2.5 py-1 text-xs transition-colors", !elevenUseCustomId ? "bg-blue-500/20 text-blue-400" : "bg-white/[0.04] text-muted-foreground")}
>
Browse
</button>
<button
type="button"
onClick={() => {
setElevenUseCustomId(true);
setElevenVoiceId(elevenCustomId);
}}
className={cn("rounded-md px-2.5 py-1 text-xs transition-colors", elevenUseCustomId ? "bg-blue-500/20 text-blue-400" : "bg-white/[0.04] text-muted-foreground")}
>
Voice ID
</button>
</div>
{elevenUseCustomId ? (
<input
value={elevenCustomId}
onChange={(e) => { setElevenCustomId(e.target.value); setElevenVoiceId(e.target.value); }}
placeholder="Paste ElevenLabs voice ID..."
className="input-field font-mono text-xs"
/>
) : (
<select value={elevenVoiceId} onChange={(e) => setElevenVoiceId(e.target.value)} className="input-field">
{elevenVoices.length === 0 && <option value="">Loading voices...</option>}
{elevenVoices.map((v) => (
<option key={v.voice_id} value={v.voice_id}>{v.name} ({v.category})</option>
))}
</select>
)}
</Field>
<Field label={`Stability: ${elevenStability.toFixed(2)}`}>
<input type="range" min="0" max="1" step="0.01" value={elevenStability}
onChange={(e) => setElevenStability(parseFloat(e.target.value))} className="w-full accent-blue-500" />
</Field>
<Field label={`Similarity: ${elevenSimilarityBoost.toFixed(2)}`}>
<input type="range" min="0" max="1" step="0.01" value={elevenSimilarityBoost}
onChange={(e) => setElevenSimilarityBoost(parseFloat(e.target.value))} className="w-full accent-blue-500" />
</Field>
<Field label={`Style: ${elevenStyle.toFixed(2)}`}>
<input type="range" min="0" max="1" step="0.01" value={elevenStyle}
onChange={(e) => setElevenStyle(parseFloat(e.target.value))} className="w-full accent-blue-500" />
</Field>
<Field label={`Speed: ${elevenSpeed.toFixed(2)}x`}>
<input type="range" min="0.5" max="2" step="0.05" value={elevenSpeed}
onChange={(e) => setElevenSpeed(parseFloat(e.target.value))} className="w-full accent-blue-500" />
</Field>
</div>
)}
{/* Voice Preview */}
<div className="mt-4 flex gap-2">
<button
onClick={playVoicePreview}
disabled={previewing}
className="flex flex-1 items-center justify-center gap-1.5 rounded-xl bg-blue-500/10 px-3 py-2.5 text-sm font-medium text-blue-400 transition-colors hover:bg-blue-500/20 disabled:opacity-40"
>
<Play className="h-3.5 w-3.5" />
Generic
</button>
<button
onClick={playCharacterPreview}
disabled={previewing || (!characterStyle && !systemPrompt)}
className="flex flex-1 items-center justify-center gap-1.5 rounded-xl bg-violet-500/10 px-3 py-2.5 text-sm font-medium text-violet-400 transition-colors hover:bg-violet-500/20 disabled:opacity-40"
>
<Play className="h-3.5 w-3.5" />
In Character
</button>
{previewing && (
<button
onClick={stopPreview}
className="flex items-center justify-center rounded-xl bg-red-500/15 px-3 py-2.5 text-red-400 transition-colors hover:bg-red-500/25"
>
<Square className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* Memory Section */}
{friend && (
<div className="border-t border-white/[0.06] pt-4">
<p className="mb-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Memory</p>
<div className="flex items-center justify-between rounded-xl bg-white/[0.03] px-4 py-3">
<div>
<p className="text-sm">Conversation History</p>
<p className="text-xs text-muted-foreground/60">
{memoryCount != null ? `${memoryCount} messages stored` : "Loading..."}
</p>
</div>
<div className="flex gap-2">
<button onClick={loadMemory} className="rounded-lg bg-white/[0.06] px-3 py-1.5 text-xs text-foreground hover:bg-white/[0.1]">
View
</button>
<button onClick={clearMemory} disabled={memoryCount === 0} className="rounded-lg bg-red-500/10 px-3 py-1.5 text-xs text-red-400 hover:bg-red-500/20 disabled:opacity-30">
Reset
</button>
</div>
</div>
</div>
)}
</div>
<style jsx>{`
.input-field {
width: 100%;
border-radius: 0.5rem;
border: 1px solid rgba(255,255,255,0.08);
background: rgba(255,255,255,0.03);
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
}
.input-field:focus {
border-color: rgba(59,130,246,0.3);
}
`}</style>
</div>
);
}
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<div>
<label className="mb-1 block text-xs font-medium text-muted-foreground">{label}</label>
{hint && <p className="mb-1 text-[11px] text-muted-foreground/50">{hint}</p>}
{children}
</div>
);
}
+181
View File
@@ -0,0 +1,181 @@
"use client";
import { Mic, Phone } from "lucide-react";
import { cn } from "@/lib/utils";
import type { CallState, VisualPopup } from "../types";
import { CallControls } from "./CallControls";
import { CallSubtitles } from "./CallSubtitles";
import { CallVisualPopup } from "./CallVisualPopup";
import { useMicLevel } from "./useMicLevel";
function getInitials(id: string) {
return id.split(/[-_/.]/).map((s) => s[0]?.toUpperCase() ?? "").join("").slice(0, 2);
}
function getColor(id: string) {
const colors = ["bg-blue-500", "bg-emerald-500", "bg-violet-500", "bg-amber-500", "bg-rose-500", "bg-cyan-500"];
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return colors[Math.abs(hash) % colors.length];
}
function formatDuration(seconds: number) {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${s.toString().padStart(2, "0")}`;
}
function MicLevelIndicator({ level, isMuted }: { level: number; isMuted: boolean }) {
const bars = 7;
const boosted = Math.min(level * 3, 1); // boost for visibility
return (
<div className="flex flex-col items-center gap-2">
<div className="flex items-end gap-[3px]" style={{ height: 40 }}>
{Array.from({ length: bars }).map((_, i) => {
const barCenter = i / (bars - 1); // 0..1
const dist = Math.abs(barCenter - 0.5) * 2; // 0..1 from center
const barHeight = isMuted ? 4 : Math.max(4, (1 - dist * 0.5) * boosted * 36);
const color = isMuted
? "bg-red-400/40"
: boosted > 0.05
? "bg-green-400"
: "bg-white/20";
return (
<div
key={i}
className={cn("w-[3px] rounded-full transition-all duration-75", color)}
style={{ height: barHeight }}
/>
);
})}
</div>
<div className="flex items-center gap-1.5">
<Mic className={cn("h-3 w-3", isMuted ? "text-red-400" : boosted > 0.05 ? "text-green-400" : "text-white/40")} />
<span className={cn("text-[11px]", isMuted ? "text-red-400" : "text-white/40")}>
{isMuted ? "Muted" : boosted > 0.05 ? "Listening" : "Speak now"}
</span>
</div>
</div>
);
}
interface VoiceCallUIProps {
callState: CallState;
callModel: string;
callModelName?: string;
callDuration: number;
isMuted: boolean;
isDeafened: boolean;
showSubtitles: boolean;
subtitleText: string;
subtitleProgress: number;
userSpeechText: string;
activePopups: VisualPopup[];
isAudioPlaying: boolean;
onToggleMute: () => void;
onToggleDeafen: () => void;
onToggleSubtitles: () => void;
onEndCall: () => void;
onDismissPopup: (id: string) => void;
}
export function VoiceCallUI({
callState, callModel, callModelName, callDuration,
isMuted, isDeafened, showSubtitles,
subtitleText, subtitleProgress, userSpeechText,
activePopups, isAudioPlaying,
onToggleMute, onToggleDeafen, onToggleSubtitles, onEndCall, onDismissPopup,
}: VoiceCallUIProps) {
const micLevel = useMicLevel(callState === "connected" && !isMuted);
if (callState === "idle") return null;
const displayName = callModelName || callModel;
return (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-between bg-gradient-to-b from-[hsl(220,20%,8%)] to-[hsl(220,20%,4%)]">
{/* Top: Model info */}
<div className="flex flex-col items-center pt-20">
<div className={cn("flex h-20 w-20 items-center justify-center rounded-full text-2xl font-bold text-white", getColor(callModel))}>
{getInitials(displayName)}
</div>
<h2 className="mt-4 text-xl font-semibold text-white">{displayName}</h2>
{callModelName && (
<p className="mt-1 text-xs text-white/40">{callModel}</p>
)}
{callState === "ringing" && (
<div className="mt-2 flex items-center gap-2">
<Phone className="h-4 w-4 animate-pulse text-green-400" />
<span className="text-sm text-white/60">Calling...</span>
</div>
)}
{callState === "connected" && (
<div className="mt-2 flex items-center gap-2">
<div className="h-2 w-2 animate-pulse rounded-full bg-green-400" />
<span className="text-sm tabular-nums text-white/60">{formatDuration(callDuration)}</span>
</div>
)}
{callState === "ended" && (
<p className="mt-2 text-sm text-white/60">Call Ended</p>
)}
</div>
{/* Center: Mic level / audio visualization */}
<div className="flex items-center justify-center">
{callState === "connected" && isAudioPlaying && (
<div className="flex items-center gap-1">
{[...Array(5)].map((_, i) => (
<div key={i} className="h-8 w-1 animate-pulse rounded-full bg-white/30" style={{ animationDelay: `${i * 100}ms`, animationDuration: "0.6s" }} />
))}
</div>
)}
{callState === "connected" && !isAudioPlaying && (
<MicLevelIndicator level={micLevel.level} isMuted={isMuted} />
)}
{callState === "ringing" && (
<div className="relative flex items-center justify-center">
<div className="absolute h-24 w-24 animate-ping rounded-full border border-green-400/20" />
<div className="absolute h-16 w-16 animate-ping rounded-full border border-green-400/30" style={{ animationDelay: "300ms" }} />
<Phone className="h-8 w-8 text-green-400" />
</div>
)}
{callState === "connected" && micLevel.hasPermission === false && (
<p className="text-sm text-red-400">Microphone access denied</p>
)}
</div>
{/* Subtitles */}
{showSubtitles && callState === "connected" && (
<CallSubtitles
userSpeechText={userSpeechText}
subtitleText={subtitleText}
subtitleProgress={subtitleProgress}
/>
)}
{/* Bottom: Controls */}
<div className="pb-16">
{callState === "connected" && (
<CallControls
isMuted={isMuted}
isDeafened={isDeafened}
showSubtitles={showSubtitles}
onToggleMute={onToggleMute}
onToggleDeafen={onToggleDeafen}
onToggleSubtitles={onToggleSubtitles}
onEndCall={onEndCall}
/>
)}
</div>
{/* Visual popups */}
{activePopups.length > 0 && (
<CallVisualPopup popup={activePopups[0]} onDismiss={onDismissPopup} />
)}
</div>
);
}
@@ -0,0 +1,11 @@
export function detectVisualContent(text: string): { content: string } | null {
// Detect markdown tables
const tableMatch = text.match(/(\|.+\|[\s\S]*?\|[-:| ]+\|[\s\S]*?\|.+\|)/);
if (tableMatch) return { content: tableMatch[1] };
// Detect code blocks
const codeMatch = text.match(/(```[\s\S]*?```)/);
if (codeMatch) return { content: codeMatch[1] };
return null;
}
@@ -0,0 +1,65 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
export function useCallAudioPlayer() {
const audioRef = useRef<HTMLAudioElement | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const animRef = useRef<number>(0);
useEffect(() => {
return () => {
if (animRef.current) cancelAnimationFrame(animRef.current);
audioRef.current?.pause();
};
}, []);
const tick = useCallback(() => {
const a = audioRef.current;
if (a && !a.paused) {
setCurrentTime(a.currentTime);
setDuration(a.duration || 0);
setProgress(a.duration ? a.currentTime / a.duration : 0);
animRef.current = requestAnimationFrame(tick);
}
}, []);
const playAudio = useCallback((b64: string, contentType: string): Promise<void> => {
return new Promise((resolve) => {
const a = new Audio(`data:${contentType};base64,${b64}`);
audioRef.current = a;
setIsPlaying(true);
setProgress(0);
a.onended = () => {
setIsPlaying(false);
setProgress(1);
if (animRef.current) cancelAnimationFrame(animRef.current);
resolve();
};
a.onerror = () => {
setIsPlaying(false);
if (animRef.current) cancelAnimationFrame(animRef.current);
resolve();
};
a.play().then(() => {
animRef.current = requestAnimationFrame(tick);
}).catch(() => {
setIsPlaying(false);
resolve();
});
});
}, [tick]);
const stop = useCallback(() => {
audioRef.current?.pause();
if (animRef.current) cancelAnimationFrame(animRef.current);
setIsPlaying(false);
}, []);
return { playAudio, isPlaying, currentTime, duration, progress, stop };
}
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
export function useMicLevel(active: boolean) {
const [level, setLevel] = useState(0);
const [stream, setStream] = useState<MediaStream | null>(null);
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const ctxRef = useRef<AudioContext | null>(null);
const analyserRef = useRef<AnalyserNode | null>(null);
const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
const rafRef = useRef<number>(0);
const startMonitoring = useCallback(async () => {
try {
const mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
setStream(mediaStream);
setHasPermission(true);
const ctx = new AudioContext();
const analyser = ctx.createAnalyser();
analyser.fftSize = 256;
analyser.smoothingTimeConstant = 0.5;
const source = ctx.createMediaStreamSource(mediaStream);
source.connect(analyser);
ctxRef.current = ctx;
analyserRef.current = analyser;
sourceRef.current = source;
const dataArray = new Uint8Array(analyser.frequencyBinCount);
function tick() {
analyser.getByteFrequencyData(dataArray);
let sum = 0;
for (let i = 0; i < dataArray.length; i++) sum += dataArray[i];
const avg = sum / dataArray.length / 255; // 0-1
setLevel(avg);
rafRef.current = requestAnimationFrame(tick);
}
rafRef.current = requestAnimationFrame(tick);
} catch {
setHasPermission(false);
}
}, []);
const stopMonitoring = useCallback(() => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
sourceRef.current?.disconnect();
ctxRef.current?.close();
stream?.getTracks().forEach((t) => t.stop());
setStream(null);
setLevel(0);
ctxRef.current = null;
analyserRef.current = null;
sourceRef.current = null;
}, [stream]);
useEffect(() => {
if (active) startMonitoring();
else stopMonitoring();
return () => { stopMonitoring(); };
}, [active]); // eslint-disable-line react-hooks/exhaustive-deps
return { level, hasPermission, stream };
}
+379
View File
@@ -0,0 +1,379 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { CallSettings, CallState, ChatMessage, FriendProfile, VisualPopup } from "../types";
import { parseSSELines } from "../parseSSELines";
import { getVoiceForModel } from "./voiceAssignment";
import { detectVisualContent } from "./detectVisualContent";
import { useCallAudioPlayer } from "./useCallAudioPlayer";
const DEFAULT_CALL_SYSTEM_PROMPT = `You are on a live voice phone call with the user. Behave naturally as if speaking on the phone:
- Keep responses concise and conversational — avoid long monologues.
- Use natural spoken language, not written/formal style. Contractions are fine.
- Don't use markdown formatting, bullet points, or numbered lists — the user is listening, not reading.
- If you need to share something visual (code, tables, structured data), mention it briefly and the system will display it.
- React naturally to what the user says. Use filler words sparingly but naturally.
- If the user seems to have stopped mid-sentence, wait for them to continue rather than jumping in.`;
interface UseVoiceCallReturn {
callState: CallState;
callModel: string;
callModelName: string;
callStartTime: number | null;
callDuration: number;
isMuted: boolean;
isDeafened: boolean;
showSubtitles: boolean;
subtitleText: string;
subtitleProgress: number;
userSpeechText: string;
activePopups: VisualPopup[];
callConversationId: string | null;
callMessages: ChatMessage[];
isAudioPlaying: boolean;
startCall: (modelId: string, friend?: FriendProfile) => void;
endCall: () => void;
toggleMute: () => void;
toggleDeafen: () => void;
toggleSubtitles: () => void;
dismissPopup: (id: string) => void;
}
export function useVoiceCall(callSettings: CallSettings): UseVoiceCallReturn {
const [callState, setCallState] = useState<CallState>("idle");
const [callModel, setCallModel] = useState("");
const [callModelName, setCallModelName] = useState("");
const [callStartTime, setCallStartTime] = useState<number | null>(null);
const [callDuration, setCallDuration] = useState(0);
const [isMuted, setIsMuted] = useState(false);
const [isDeafened, setIsDeafened] = useState(callSettings.deafenByDefault);
const [showSubtitles, setShowSubtitles] = useState(true);
const [subtitleText, setSubtitleText] = useState("");
const [userSpeechText, setUserSpeechText] = useState("");
const [activePopups, setActivePopups] = useState<VisualPopup[]>([]);
const [callConversationId, setCallConversationId] = useState<string | null>(null);
const [callMessages, setCallMessages] = useState<ChatMessage[]>([]);
const audioPlayer = useCallAudioPlayer();
const speechBufferRef = useRef("");
const silenceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const recognitionRef = useRef<any>(null);
const callActiveRef = useRef(false);
const processingRef = useRef(false);
const convIdRef = useRef<string | null>(null);
const friendRef = useRef<FriendProfile | null>(null);
const isDeafenedRef = useRef(isDeafened);
// Keep ref in sync
useEffect(() => { isDeafenedRef.current = isDeafened; }, [isDeafened]);
// Live timer
useEffect(() => {
if (callState !== "connected" || !callStartTime) return;
const id = setInterval(() => {
setCallDuration(Math.floor((Date.now() - callStartTime) / 1000));
}, 1000);
return () => clearInterval(id);
}, [callState, callStartTime]);
const getSystemPrompt = useCallback((isCall: boolean) => {
const friend = friendRef.current;
const parts: string[] = [];
if (isCall) parts.push(DEFAULT_CALL_SYSTEM_PROMPT);
if (friend?.name) parts.push(`Your name is "${friend.name}". Always use this as your identity.`);
if (friend?.characterStyle) parts.push(`Your personality and character style: ${friend.characterStyle}`);
if (friend?.systemPrompt) parts.push(friend.systemPrompt);
if (friend) {
parts.push("You are a friend of the user. You have an ongoing persistent relationship — you remember past conversations and build on them. Stay in character at all times. Be natural and authentic to your personality.");
}
return parts.join("\n\n");
}, []);
const getVoice = useCallback((modelId: string) => {
const friend = friendRef.current;
if (friend?.voiceId) return friend.voiceId;
return getVoiceForModel(modelId, {
global: callSettings.globalVoiceOverride,
perModel: callSettings.perModelVoiceOverrides,
}).voiceId;
}, [callSettings]);
const playTTS = useCallback(async (text: string, modelId: string) => {
if (isDeafenedRef.current || !callActiveRef.current) return;
const friend = friendRef.current;
const vs = friend?.voiceSettings;
// Build TTS request — default to ElevenLabs eleven_multilingual_v2
let ttsBody: Record<string, unknown>;
if (vs?.ttsProvider === "openai") {
ttsBody = {
model: vs.ttsModel || "tts-1",
input: text,
voice: vs.openaiVoice || getVoice(modelId),
...(vs.openaiSpeed != null ? { speed: vs.openaiSpeed } : {}),
};
} else {
// ElevenLabs (default for all calls)
const elevenModel = vs?.ttsModel || "eleven_multilingual_v2";
const elevenVoiceId = vs?.elevenVoiceId || friend?.voiceId || undefined;
ttsBody = {
model: elevenModel,
input: text,
voice: elevenVoiceId || "Rachel",
voice_id: elevenVoiceId || undefined,
model_id: elevenModel,
...(vs?.elevenStability != null ? { stability: vs.elevenStability } : {}),
...(vs?.elevenSimilarityBoost != null ? { similarity_boost: vs.elevenSimilarityBoost } : {}),
...(vs?.elevenStyle != null ? { style: vs.elevenStyle } : {}),
...(vs?.elevenSpeed != null ? { speed: vs.elevenSpeed } : {}),
};
}
try {
const audioRes = await fetch("/api/chat/generate-audio", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ttsBody),
});
if (audioRes.ok) {
const audioData = await audioRes.json();
if (audioData.audio?.b64 && callActiveRef.current) {
await audioPlayer.playAudio(audioData.audio.b64, audioData.audio.contentType ?? "audio/mpeg");
}
}
} catch { /* skip TTS error */ }
}, [getVoice, audioPlayer]);
const sendMessage = useCallback(async (text: string, modelId: string, isGreeting = false) => {
if (!convIdRef.current || processingRef.current) return;
if (!isGreeting && !text.trim()) return;
processingRef.current = true;
if (!isGreeting) {
const userMsg: ChatMessage = { role: "user", content: text };
setCallMessages((prev) => [...prev, userMsg]);
}
try {
const systemPrompt = getSystemPrompt(true);
const content = isGreeting
? "[The user just picked up. Greet them briefly and naturally, like answering a phone call. Keep it to 1-2 short sentences.]"
: text;
const res = await fetch(`/api/chat/conversations/${convIdRef.current}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, model: modelId, systemPrompt }),
});
if (!res.ok || !res.body) {
processingRef.current = false;
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullText = "";
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.data === "[DONE]" || evt.event === "meta" || evt.event === "done") continue;
try {
const json = JSON.parse(evt.data);
const delta = json.choices?.[0]?.delta;
if (delta?.content) {
fullText += delta.content;
setSubtitleText(fullText);
}
} catch { /* skip */ }
}
}
const assistantMsg: ChatMessage = { role: "assistant", content: fullText, model: modelId };
setCallMessages((prev) => [...prev, assistantMsg]);
if (fullText && callActiveRef.current) {
const visual = detectVisualContent(fullText);
if (visual) {
setActivePopups((prev) => [...prev, { id: crypto.randomUUID(), content: visual.content, timestamp: new Date().toISOString() }]);
}
await playTTS(fullText, modelId);
}
setSubtitleText("");
} catch { /* skip */ }
processingRef.current = false;
}, [getSystemPrompt, playTTS]);
const startSTT = useCallback((modelId: string) => {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SR) return;
const recognition = new SR();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = navigator.language || "en-US";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recognition.onresult = (event: any) => {
let interim = "";
let final = "";
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) final += transcript;
else interim += transcript;
}
if (final) {
speechBufferRef.current += final;
setUserSpeechText(speechBufferRef.current);
} else {
setUserSpeechText(speechBufferRef.current + interim);
}
if (silenceTimerRef.current) clearTimeout(silenceTimerRef.current);
silenceTimerRef.current = setTimeout(() => {
if (speechBufferRef.current.trim() && !processingRef.current) {
const t = speechBufferRef.current.trim();
speechBufferRef.current = "";
setUserSpeechText("");
sendMessage(t, modelId);
}
}, callSettings.speechPauseDuration);
};
recognition.onend = () => {
if (callActiveRef.current && !isMuted) {
try { recognition.start(); } catch { /* ignore */ }
}
};
recognition.onerror = () => {
if (callActiveRef.current && !isMuted) {
setTimeout(() => {
try { recognition.start(); } catch { /* ignore */ }
}, 500);
}
};
recognitionRef.current = recognition;
try { recognition.start(); } catch { /* ignore */ }
}, [callSettings.speechPauseDuration, sendMessage, isMuted]);
const startCall = useCallback(async (modelId: string, friend?: FriendProfile) => {
setCallState("ringing");
setCallModel(modelId);
setCallModelName(friend?.name || "");
setCallMessages([]);
setActivePopups([]);
setSubtitleText("");
setUserSpeechText("");
speechBufferRef.current = "";
callActiveRef.current = true;
friendRef.current = friend || null;
setIsDeafened(callSettings.deafenByDefault);
const displayName = friend?.name || modelId;
try {
const res = await fetch("/api/chat/conversations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: modelId, type: "call", title: `Call with ${displayName}` }),
});
if (res.ok) {
const data = await res.json();
setCallConversationId(data.data.id);
convIdRef.current = data.data.id;
}
} catch { /* skip */ }
setTimeout(() => {
if (!callActiveRef.current) return;
setCallState("connected");
setCallStartTime(Date.now());
setCallDuration(0);
startSTT(modelId);
// Model greets the user
sendMessage("", modelId, true);
}, 1500);
}, [callSettings.deafenByDefault, startSTT, sendMessage]);
const endCall = useCallback(async () => {
callActiveRef.current = false;
if (silenceTimerRef.current) clearTimeout(silenceTimerRef.current);
recognitionRef.current?.stop();
audioPlayer.stop();
const displayName = friendRef.current?.name || callModel;
if (convIdRef.current && callDuration > 0) {
const mins = Math.floor(callDuration / 60);
const secs = callDuration % 60;
const durationStr = `${mins}:${secs.toString().padStart(2, "0")}`;
try {
await fetch(`/api/chat/conversations/${convIdRef.current}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: `Call with ${displayName} (${durationStr})`, callDuration }),
});
} catch { /* skip */ }
}
setCallState("ended");
setTimeout(() => {
setCallState("idle");
setCallModel("");
setCallModelName("");
setCallStartTime(null);
setCallConversationId(null);
convIdRef.current = null;
friendRef.current = null;
}, 1500);
}, [callDuration, callModel, audioPlayer]);
const toggleMute = useCallback(() => {
setIsMuted((prev) => {
if (!prev) {
recognitionRef.current?.stop();
} else if (callActiveRef.current) {
startSTT(callModel);
}
return !prev;
});
}, [startSTT, callModel]);
const toggleDeafen = useCallback(() => {
setIsDeafened((prev) => {
if (!prev) audioPlayer.stop();
return !prev;
});
}, [audioPlayer]);
const toggleSubtitles = useCallback(() => {
setShowSubtitles((prev) => !prev);
}, []);
const dismissPopup = useCallback((id: string) => {
setActivePopups((prev) => prev.filter((p) => p.id !== id));
}, []);
return {
callState, callModel, callModelName, callStartTime, callDuration,
isMuted, isDeafened, showSubtitles,
subtitleText, subtitleProgress: audioPlayer.progress,
userSpeechText, activePopups,
callConversationId, callMessages,
isAudioPlaying: audioPlayer.isPlaying,
startCall, endCall, toggleMute, toggleDeafen, toggleSubtitles, dismissPopup,
};
}
@@ -0,0 +1,18 @@
const OPENAI_VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"] as const;
function hashString(id: string): number {
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
return Math.abs(hash);
}
export function getVoiceForModel(
modelId: string,
overrides?: { global?: string; perModel?: Record<string, string> },
): { voiceId: string } {
if (overrides?.perModel?.[modelId]) return { voiceId: overrides.perModel[modelId] };
if (overrides?.global) return { voiceId: overrides.global };
return { voiceId: OPENAI_VOICES[hashString(modelId) % OPENAI_VOICES.length] };
}
export { OPENAI_VOICES };
+27
View File
@@ -0,0 +1,27 @@
export 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;
}
}
const remaining = lines.slice(lastProcessed).join("\n");
return { events, remaining };
}
+83
View File
@@ -0,0 +1,83 @@
export type ModelType = "chat" | "image" | "audio";
export interface ModelOption {
id: string;
providerId: string;
modelType: ModelType;
}
export interface ImagePart {
type: "image_url";
image_url: { url: string; detail?: string };
}
export 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;
}
export interface Conversation {
id: string;
title: string;
model: string;
updatedAt: string;
type?: ConversationType;
callDuration?: number;
}
export type UIMode = "classic" | "messenger" | "phone";
export type ConversationType = "chat" | "call";
export type CallState = "idle" | "ringing" | "connected" | "ended";
export interface CallSettings {
speechPauseDuration: number;
deafenByDefault: boolean;
globalVoiceOverride?: string;
perModelVoiceOverrides?: Record<string, string>;
}
export interface VisualPopup {
id: string;
content: string;
timestamp: string;
}
export interface FriendVoiceSettings {
ttsProvider: "openai" | "elevenlabs";
ttsModel: string;
// OpenAI voice settings
openaiVoice?: string;
openaiSpeed?: number;
// ElevenLabs voice settings
elevenVoiceId?: string;
elevenStability?: number;
elevenSimilarityBoost?: number;
elevenStyle?: number;
elevenSpeed?: number;
}
export interface FriendProfile {
id: string;
name: string;
modelId: string;
systemPrompt?: string;
characterStyle?: string;
avatarColor?: string;
voiceSettings?: FriendVoiceSettings;
// Legacy compat
ttsModel?: string;
voiceId?: string;
// Conversation persistence
conversationId?: string;
}
+732
View File
@@ -0,0 +1,732 @@
"use client";
import { FormEvent, useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { parseSSELines } from "./parseSSELines";
import type { CallSettings, ChatMessage, Conversation, ImagePart, ModelOption, ModelType } from "./types";
export interface ChatEngine {
// Models
models: ModelOption[];
model: string;
setModel: (m: string) => void;
modelMenuOpen: boolean;
setModelMenuOpen: (v: boolean) => void;
modelSearch: string;
setModelSearch: (v: string) => void;
currentModel: ModelOption | undefined;
currentModelType: ModelType;
providerForModel: string | undefined;
sortedModels: ModelOption[];
filteredModels: ModelOption[];
// Preferences
favourites: string[];
defaultModel: string;
toggleFavourite: (modelId: string) => void;
setAsDefault: (modelId: string) => void;
// Conversations
conversations: Conversation[];
activeConversationId: string | null;
currentMessages: ChatMessage[];
newChat: () => void;
selectConversation: (conv: Conversation) => void;
deleteConversation: (id: string) => void;
groupConversations: () => { label: string; items: Conversation[] }[];
// Input
input: string;
setInput: React.Dispatch<React.SetStateAction<string>>;
submitting: boolean;
streamingText: string;
streamingProviderId: string | undefined;
pendingImages: ImagePart[];
setPendingImages: React.Dispatch<React.SetStateAction<ImagePart[]>>;
pendingFiles: File[];
setPendingFiles: React.Dispatch<React.SetStateAction<File[]>>;
handleSubmit: (e?: FormEvent) => void;
stopGeneration: () => void;
addImageFiles: (files: FileList | File[]) => void;
addFiles: (files: FileList | File[]) => void;
removePendingImage: (index: number) => void;
removePendingFile: (index: number) => void;
// Incognito
incognito: boolean;
toggleIncognito: () => void;
// UI
sidebarOpen: boolean;
setSidebarOpen: (v: boolean) => void;
settingsOpen: boolean;
setSettingsOpen: (v: boolean) => void;
scrollRef: React.RefObject<HTMLDivElement | null>;
textareaRef: React.RefObject<HTMLTextAreaElement | null>;
fileInputRef: React.RefObject<HTMLInputElement | null>;
// Advanced settings — chat
systemPrompt: string;
setSystemPrompt: (v: string) => void;
temperature: number | null;
setTemperature: (v: number | null) => void;
maxTokens: number | null;
setMaxTokens: (v: number | null) => void;
topP: number | null;
setTopP: (v: number | null) => void;
frequencyPenalty: number | null;
setFrequencyPenalty: (v: number | null) => void;
presencePenalty: number | null;
setPresencePenalty: (v: number | null) => void;
saveChatSettings: () => void;
// Advanced settings — audio (OpenAI)
audioVoice: string;
setAudioVoice: (v: string) => void;
audioSpeed: number;
setAudioSpeed: (v: number) => void;
// Advanced settings — audio (ElevenLabs)
elevenVoiceId: string;
setElevenVoiceId: (v: string) => void;
elevenStability: number;
setElevenStability: (v: number) => void;
elevenSimilarityBoost: number;
setElevenSimilarityBoost: (v: number) => void;
elevenStyle: number;
setElevenStyle: (v: number) => void;
elevenSpeed: number;
setElevenSpeed: (v: number) => void;
elevenVoices: Array<{ voice_id: string; name: string; category: string }>;
// Advanced settings — image
imageSize: string;
setImageSize: (v: string) => void;
imageQuality: string;
setImageQuality: (v: string) => void;
imageStyle: string;
setImageStyle: (v: string) => void;
imageN: number;
setImageN: (v: number) => void;
// Call settings
callSettings: CallSettings;
setCallSettings: (v: CallSettings) => void;
}
export function useChatEngine(): ChatEngine {
// Models
const [models, setModels] = useState<ModelOption[]>([]);
const [model, setModel] = useState("");
const [modelMenuOpen, setModelMenuOpen] = useState(false);
const [modelSearch, setModelSearch] = useState("");
// Preferences
const [favourites, setFavourites] = useState<string[]>([]);
const [defaultModel, setDefaultModel] = useState("");
// Conversations
const [conversations, setConversations] = useState<Conversation[]>([]);
const [activeConversationId, setActiveConversationId] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
// Input
const [input, setInput] = useState("");
const [submitting, setSubmitting] = useState(false);
const [streamingText, setStreamingText] = useState("");
const [streamingProviderId, setStreamingProviderId] = useState<string | undefined>();
const abortRef = useRef<AbortController | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const [pendingImages, setPendingImages] = useState<ImagePart[]>([]);
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
// Incognito
const [incognito, setIncognito] = useState(false);
const [incognitoHistory, setIncognitoHistory] = useState<ChatMessage[]>([]);
// UI
const [sidebarOpen, setSidebarOpen] = useState(true);
const [settingsOpen, setSettingsOpen] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Advanced settings — chat
const [systemPrompt, setSystemPrompt] = useState("");
const [temperature, setTemperature] = useState<number | null>(null);
const [maxTokens, setMaxTokens] = useState<number | null>(null);
const [topP, setTopP] = useState<number | null>(null);
const [frequencyPenalty, setFrequencyPenalty] = useState<number | null>(null);
const [presencePenalty, setPresencePenalty] = useState<number | null>(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<Array<{ voice_id: string; name: string; category: string }>>([]);
// Call settings
const [callSettings, setCallSettings] = useState<CallSettings>({
speechPauseDuration: 1500,
deafenByDefault: false,
});
// 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;
const currentModel = models.find((m) => m.id === model);
const providerForModel = currentModel?.providerId;
const currentModelType: ModelType = currentModel?.modelType ?? "chat";
// ── 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<string, unknown> } | undefined;
const favs = prefs?.favouriteModels ?? [];
const defModel = prefs?.defaultModel ?? "";
setFavourites(favs);
setDefaultModel(defModel);
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);
if (cs.callSettings && typeof cs.callSettings === "object") {
const c = cs.callSettings as Record<string, unknown>;
setCallSettings((prev) => ({
...prev,
...(typeof c.speechPauseDuration === "number" ? { speechPauseDuration: c.speechPauseDuration } : {}),
...(typeof c.deafenByDefault === "boolean" ? { deafenByDefault: c.deafenByDefault } : {}),
...(typeof c.globalVoiceOverride === "string" ? { globalVoiceOverride: c.globalVoiceOverride } : {}),
...(c.perModelVoiceOverrides && typeof c.perModelVoiceOverrides === "object" ? { perModelVoiceOverrides: c.perModelVoiceOverrides as Record<string, string> } : {}),
}));
}
}
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<string, unknown> = {};
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;
chatSettings.callSettings = callSettings;
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, callSettings]);
// Load ElevenLabs voices
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];
const nextDefault = !next.includes(defaultModel) && defaultModel === modelId ? "" : defaultModel;
savePreferences(next, nextDefault);
}
function setAsDefault(modelId: string) {
const nextDefault = defaultModel === modelId ? "" : modelId;
const nextFavs = nextDefault && !favourites.includes(modelId) ? [...favourites, modelId] : favourites;
savePreferences(nextFavs, nextDefault);
}
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?type=chat");
if (!res.ok) return;
const data = await res.json();
setConversations(data.data ?? []);
}, []);
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 is now handled by ResizableTextarea component
// ── Image helpers ────────────────────────────────────────
function fileToBase64(file: File): Promise<string> {
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 imageTypes = ["image/png", "image/jpeg", "image/gif", "image/webp"];
const maxSize = 20 * 1024 * 1024;
const newParts: ImagePart[] = [];
const newFiles: File[] = [];
for (const file of Array.from(files)) {
if (file.size > maxSize) {
toast.error(`File too large: ${file.name} (max 20 MB)`);
continue;
}
if (imageTypes.includes(file.type)) {
const dataUrl = await fileToBase64(file);
newParts.push({ type: "image_url", image_url: { url: dataUrl } });
} else {
newFiles.push(file);
}
}
if (newParts.length) {
setPendingImages((prev) => [...prev, ...newParts].slice(0, 10));
}
if (newFiles.length) {
setPendingFiles((prev) => [...prev, ...newFiles].slice(0, 10));
}
}
function addFiles(files: FileList | File[]) {
addImageFiles(files);
}
function removePendingImage(index: number) {
setPendingImages((prev) => prev.filter((_, i) => i !== index));
}
function removePendingFile(index: number) {
setPendingFiles((prev) => prev.filter((_, i) => i !== index));
}
function newChat() {
if (incognito) { setIncognitoHistory([]); return; }
setActiveConversationId(null);
setMessages([]);
}
function selectConversation(conv: Conversation) {
if (incognito) setIncognito(false);
setActiveConversationId(conv.id);
if (conv.model) setModel(conv.model);
}
async function deleteConversation(id: string) {
await fetch(`/api/chat/conversations/${id}`, { method: "DELETE" });
if (activeConversationId === id) {
setActiveConversationId(null);
setMessages([]);
}
loadConversations();
}
function toggleIncognito() {
if (!incognito) { setIncognito(true); setIncognitoHistory([]); }
else { setIncognito(false); }
}
function stopGeneration() { abortRef.current?.abort(); }
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 */ }
}
}
return { fullText, providerId, tokensIn, tokensOut };
}
async function handleImageGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages, 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]);
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, 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]);
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); }
}
}
async function handleSubmit(e?: FormEvent) {
e?.preventDefault();
console.log("[handleSubmit]", { input: input.trim(), model, submitting, pendingImages: pendingImages.length });
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([]);
setPendingFiles([]);
setStreamingText("");
setStreamingProviderId(undefined);
const abort = new AbortController();
abortRef.current = abort;
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);
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 */ }
}
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
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);
setMessages((prev) => {
const updated = [...prev];
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);
}
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);
}
return {
models, model, setModel, modelMenuOpen, setModelMenuOpen, modelSearch, setModelSearch,
currentModel, currentModelType, providerForModel, sortedModels, filteredModels,
favourites, defaultModel, toggleFavourite, setAsDefault,
conversations, activeConversationId, currentMessages, newChat, selectConversation, deleteConversation, groupConversations,
input, setInput, submitting, streamingText, streamingProviderId,
pendingImages, setPendingImages, pendingFiles, setPendingFiles,
handleSubmit, stopGeneration, addImageFiles, addFiles, removePendingImage, removePendingFile,
incognito, toggleIncognito,
sidebarOpen, setSidebarOpen, settingsOpen, setSettingsOpen,
scrollRef, textareaRef, fileInputRef,
systemPrompt, setSystemPrompt, temperature, setTemperature, maxTokens, setMaxTokens,
topP, setTopP, frequencyPenalty, setFrequencyPenalty, presencePenalty, setPresencePenalty,
saveChatSettings,
audioVoice, setAudioVoice, audioSpeed, setAudioSpeed,
elevenVoiceId, setElevenVoiceId, elevenStability, setElevenStability,
elevenSimilarityBoost, setElevenSimilarityBoost, elevenStyle, setElevenStyle,
elevenSpeed, setElevenSpeed, elevenVoices,
imageSize, setImageSize, imageQuality, setImageQuality, imageStyle, setImageStyle, imageN, setImageN,
callSettings, setCallSettings,
};
}
+40
View File
@@ -0,0 +1,40 @@
"use client";
import { useCallback, useEffect, useState } from "react";
const STORAGE_KEY = "chat-custom-css";
const STYLE_ID = "custom-chat-css";
export function useCustomCSS() {
const [css, setCssState] = useState("");
useEffect(() => {
const stored = localStorage.getItem(STORAGE_KEY) ?? "";
setCssState(stored);
injectCSS(stored);
}, []);
const setCSS = useCallback((value: string) => {
setCssState(value);
localStorage.setItem(STORAGE_KEY, value);
injectCSS(value);
}, []);
const clearCSS = useCallback(() => {
setCssState("");
localStorage.removeItem(STORAGE_KEY);
injectCSS("");
}, []);
return { css, setCSS, clearCSS };
}
function injectCSS(css: string) {
let el = document.getElementById(STYLE_ID);
if (!el) {
el = document.createElement("style");
el.id = STYLE_ID;
document.head.appendChild(el);
}
el.textContent = css;
}
@@ -0,0 +1,88 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
interface SpeechRecognitionHook {
isListening: boolean;
isSupported: boolean;
startListening: (cursorPos: number) => void;
stopListening: () => void;
interimText: string;
}
export function useSpeechRecognition(
onResult: (text: string, cursorPos: number) => void,
): SpeechRecognitionHook {
const [isListening, setIsListening] = useState(false);
const [isSupported, setIsSupported] = useState(false);
const [interimText, setInterimText] = useState("");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const recognitionRef = useRef<any>(null);
const cursorPosRef = useRef(0);
useEffect(() => {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
setIsSupported(!!SR);
}, []);
const startListening = useCallback((cursorPos: number) => {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SR) return;
cursorPosRef.current = cursorPos;
const recognition = new SR();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = navigator.language || "en-US";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recognition.onresult = (event: any) => {
let interim = "";
let final = "";
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
final += transcript;
} else {
interim += transcript;
}
}
setInterimText(interim);
if (final) {
onResult(final, cursorPosRef.current);
cursorPosRef.current += final.length;
setInterimText("");
}
};
recognition.onerror = () => {
setIsListening(false);
setInterimText("");
};
recognition.onend = () => {
setIsListening(false);
setInterimText("");
};
recognitionRef.current = recognition;
recognition.start();
setIsListening(true);
}, [onResult]);
const stopListening = useCallback(() => {
recognitionRef.current?.stop();
setIsListening(false);
setInterimText("");
}, []);
return { isListening, isSupported, startListening, stopListening, interimText };
}
/* eslint-disable @typescript-eslint/no-explicit-any */
declare global {
interface Window {
SpeechRecognition: any;
webkitSpeechRecognition: any;
}
}
+34
View File
@@ -0,0 +1,34 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { isMobile, isPWA } from "@/lib/detect-os";
import type { UIMode } from "./types";
const STORAGE_KEY = "chat-ui-mode";
function getDefaultMode(): UIMode {
if (typeof window === "undefined") return "classic";
const stored = localStorage.getItem(STORAGE_KEY) as UIMode | null;
if (stored && ["classic", "messenger", "phone"].includes(stored)) return stored;
if (isPWA()) return "phone";
return "classic";
}
export function useUIMode() {
const [mode, setModeState] = useState<UIMode>("classic");
useEffect(() => {
setModeState(getDefaultMode());
}, []);
const setMode = useCallback((m: UIMode) => {
setModeState(m);
localStorage.setItem(STORAGE_KEY, m);
}, []);
const toggleAltMode = useCallback(() => {
setMode(mode === "classic" ? (isMobile() ? "phone" : "messenger") : "classic");
}, [mode, setMode]);
return { mode, setMode, toggleAltMode };
}
@@ -0,0 +1,13 @@
"use client";
import { useEffect } from "react";
export function ServiceWorkerRegistrar() {
useEffect(() => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js").catch(() => {});
}
}, []);
return null;
}
+1
View File
@@ -423,4 +423,5 @@ export const db = {
userPreference: makeModel("userPreference", "user_preferences"),
giftCard: makeModel("giftCard", "gift_cards"),
cryptoPayment: makeModel("cryptoPayment", "crypto_payments"),
friend: makeModel("friend", "friends"),
};
+28
View File
@@ -0,0 +1,28 @@
export type OSType = "windows" | "mac" | "linux" | "ios" | "android" | "unknown";
export function detectOS(): OSType {
if (typeof navigator === "undefined") return "unknown";
const ua = navigator.userAgent;
if (/iPad|iPhone|iPod/.test(ua)) return "ios";
if (/Android/.test(ua)) return "android";
if (/Mac/.test(ua)) return "mac";
if (/Win/.test(ua)) return "windows";
if (/Linux/.test(ua)) return "linux";
return "unknown";
}
export function isMobile(): boolean {
if (typeof window === "undefined") return false;
return window.innerWidth < 768 || /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
}
export function isPWA(): boolean {
if (typeof window === "undefined") return false;
return window.matchMedia("(display-mode: standalone)").matches ||
(navigator as unknown as { standalone?: boolean }).standalone === true;
}
export function applyOSAttribute() {
if (typeof document === "undefined") return;
document.documentElement.setAttribute("data-os", detectOS());
}