update
This commit is contained in:
+89
-6
@@ -1,12 +1,13 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, clearToken, getToken } from "./lib/api.ts";
|
||||
import type { ChatMessage, Conversation, DriverModel, User } from "./lib/types.ts";
|
||||
import type { Attachment, ChatMessage, Conversation, DriverModel, FilePreview, User } from "./lib/types.ts";
|
||||
import { Login } from "./components/Login.tsx";
|
||||
import { Sidebar } from "./components/Sidebar.tsx";
|
||||
import { Chat } from "./components/Chat.tsx";
|
||||
import { ConvEditDialog, SettingsModal, ShareModal } from "./components/dialogs.tsx";
|
||||
import { ConvEditDialog, FilePreviewModal, SettingsModal, ShareModal } from "./components/dialogs.tsx";
|
||||
import { AdminPanel } from "./components/AdminPanel.tsx";
|
||||
import { SharePage } from "./components/SharePage.tsx";
|
||||
import { ResetPage } from "./components/ResetPage.tsx";
|
||||
import { ConfirmDialog } from "./components/ui.tsx";
|
||||
|
||||
function shareIdFromPath(): string | null {
|
||||
@@ -16,6 +17,12 @@ function shareIdFromPath(): string | null {
|
||||
|
||||
// Module-level: the path never changes without a full reload, so hook order stays stable.
|
||||
const SHARE_ID = typeof window !== "undefined" ? shareIdFromPath() : null;
|
||||
const RESET_TOKEN = typeof window !== "undefined" ? resetTokenFromPath() : null;
|
||||
|
||||
function resetTokenFromPath(): string | null {
|
||||
const m = window.location.pathname.match(/^\/reset\/([A-Za-z0-9_-]{6,80})\/?$/);
|
||||
return m ? m[1]! : null;
|
||||
}
|
||||
|
||||
function applyTheme(theme: string) {
|
||||
const root = document.documentElement;
|
||||
@@ -27,7 +34,7 @@ function applyTheme(theme: string) {
|
||||
|
||||
export function App() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [checking, setChecking] = useState(!SHARE_ID && !!getToken());
|
||||
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !!getToken());
|
||||
const [models, setModels] = useState<DriverModel[]>([]);
|
||||
const [model, setModel] = useState("");
|
||||
const [convs, setConvs] = useState<Conversation[]>([]);
|
||||
@@ -42,8 +49,16 @@ export function App() {
|
||||
const [deleteConv, setDeleteConv] = useState<Conversation | null>(null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [adminOpen, setAdminOpen] = useState(false);
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [attachError, setAttachError] = useState<string | null>(null);
|
||||
const [filePreview, setFilePreview] = useState<FilePreview | null>(null);
|
||||
const [previewBusy, setPreviewBusy] = useState(false);
|
||||
const [ocrAvailable, setOcrAvailable] = useState(false);
|
||||
|
||||
// Public share route: no auth needed. SHARE_ID is constant for the page lifetime.
|
||||
// Public routes: no auth needed. IDs are constant for the page lifetime.
|
||||
if (RESET_TOKEN) {
|
||||
return <ResetPage token={RESET_TOKEN} />;
|
||||
}
|
||||
if (SHARE_ID) {
|
||||
return <SharePage publicId={SHARE_ID} />;
|
||||
}
|
||||
@@ -71,7 +86,12 @@ export function App() {
|
||||
.then(async (res) => {
|
||||
setUser(res.user);
|
||||
applyTheme(res.user.theme);
|
||||
const [m, c] = await Promise.all([api.models().catch(() => ({ models: [] })), api.convs().catch(() => ({ conversations: [] }))]);
|
||||
const [m, c, t] = await Promise.all([
|
||||
api.models().catch(() => ({ models: [] })),
|
||||
api.convs().catch(() => ({ conversations: [] })),
|
||||
api.tools().catch(() => ({ tools: [] as { name: string; available: boolean }[] })),
|
||||
]);
|
||||
setOcrAvailable(t.tools.some((x) => x.name === "ocr" && x.available));
|
||||
setModels(m.models);
|
||||
if (m.models.length > 0) setModel(m.models[0]!.id);
|
||||
setConvs(c.conversations);
|
||||
@@ -106,6 +126,7 @@ export function App() {
|
||||
setModels(m.models);
|
||||
if (m.models.length > 0) setModel(m.models[0]!.id);
|
||||
}).catch(() => {});
|
||||
api.tools().then((t) => setOcrAvailable(t.tools.some((x) => x.name === "ocr" && x.available))).catch(() => {});
|
||||
refreshConvs();
|
||||
}
|
||||
|
||||
@@ -116,6 +137,8 @@ export function App() {
|
||||
setConvs([]);
|
||||
setMessages([]);
|
||||
setActiveId(null);
|
||||
setAttachments([]);
|
||||
setFilePreview(null);
|
||||
}
|
||||
|
||||
async function newChat() {
|
||||
@@ -140,8 +163,14 @@ export function App() {
|
||||
}
|
||||
}
|
||||
const userMsg: ChatMessage = { role: "user", content: text };
|
||||
// Attachments travel as reviewed text blocks appended to the message.
|
||||
const blocks = attachments.map((a) =>
|
||||
`[attached ${a.kind === "ocr" ? "image transcription" : "text file"}: ${a.name}]\n\`\`\`text\n${a.text}\n\`\`\``,
|
||||
);
|
||||
if (blocks.length > 0) userMsg.content = [text, ...blocks].filter(Boolean).join("\n\n");
|
||||
const history = [...messages, userMsg];
|
||||
setMessages(history);
|
||||
setAttachments([]);
|
||||
setSending(true);
|
||||
setStreaming("");
|
||||
let full = "";
|
||||
@@ -161,8 +190,51 @@ export function App() {
|
||||
}
|
||||
}
|
||||
|
||||
async function removeConv(c: Conversation) {
|
||||
/** Platform-tools upload flow: image -> OCR, text -> CDN, both previewed before attach. */
|
||||
async function handlePickFile(kind: "ocr" | "text", file: File) {
|
||||
if (!user) return;
|
||||
setAttachError(null);
|
||||
if (kind === "ocr" && file.size > 5 * 1024 * 1024) {
|
||||
setAttachError("Image too large (max 5MB).");
|
||||
return;
|
||||
}
|
||||
if (kind === "text" && file.size > 500 * 1024) {
|
||||
setAttachError("Text file too large (max 500KB).");
|
||||
return;
|
||||
}
|
||||
setFilePreview({ name: file.name, kind, text: "", truncated: false });
|
||||
setPreviewBusy(true);
|
||||
try {
|
||||
if (kind === "ocr") {
|
||||
const r = await api.ocrImage(file);
|
||||
setFilePreview({ name: file.name, kind, text: r.text, truncated: r.truncated });
|
||||
} else {
|
||||
const key = `${user.id}-${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
|
||||
const put = await fetch(`/cdn/text/${key}`, {
|
||||
method: "PUT",
|
||||
headers: { Authorization: `Bearer ${getToken()}`, "Content-Type": "text/plain" },
|
||||
body: file,
|
||||
});
|
||||
const pdata = (await put.json().catch(() => ({}))) as { error?: string; url?: string };
|
||||
if (!put.ok || !pdata.url) throw new Error(pdata.error || `Upload failed (${put.status})`);
|
||||
const text = await (await fetch(pdata.url)).text();
|
||||
setFilePreview({ name: file.name, kind, text, truncated: false });
|
||||
}
|
||||
} catch (e) {
|
||||
setFilePreview(null);
|
||||
setAttachError(e instanceof Error ? e.message : "Upload failed");
|
||||
} finally {
|
||||
setPreviewBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function attachPreviewText(text: string) {
|
||||
if (!filePreview || !text.trim()) return;
|
||||
setAttachments((prev) => [...prev, { id: crypto.randomUUID(), name: filePreview.name, kind: filePreview.kind, text }]);
|
||||
setFilePreview(null);
|
||||
}
|
||||
|
||||
async function removeConv(c: Conversation) { try {
|
||||
await api.deleteConv(c.id);
|
||||
if (activeId === c.id) {
|
||||
setActiveId(null);
|
||||
@@ -218,6 +290,17 @@ export function App() {
|
||||
sidebarCollapsed={sidebarCollapsed}
|
||||
onExpandSidebar={() => setSidebarCollapsed(false)}
|
||||
onOpenNav={() => setMobileNav(true)}
|
||||
attachments={attachments}
|
||||
attachError={attachError}
|
||||
ocrAvailable={ocrAvailable}
|
||||
onRemoveAttachment={(id) => setAttachments((prev) => prev.filter((a) => a.id !== id))}
|
||||
onPickFile={handlePickFile}
|
||||
/>
|
||||
<FilePreviewModal
|
||||
preview={filePreview}
|
||||
busy={previewBusy}
|
||||
onClose={() => { if (!previewBusy) setFilePreview(null); }}
|
||||
onAttach={attachPreviewText}
|
||||
/>
|
||||
|
||||
<ConvEditDialog
|
||||
|
||||
@@ -16,6 +16,7 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
|
||||
// create form
|
||||
const [username, setUsername] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
|
||||
async function refresh() {
|
||||
setBusy(true);
|
||||
@@ -43,10 +44,11 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
try {
|
||||
const res = await api.adminCreate({ username: username.trim().toLowerCase(), displayName: displayName.trim() || undefined });
|
||||
const res = await api.adminCreate({ username: username.trim().toLowerCase(), displayName: displayName.trim() || undefined, email: email.trim() || undefined });
|
||||
setFreshKey({ username: res.user.username, key: res.key });
|
||||
setUsername("");
|
||||
setDisplayName("");
|
||||
setEmail("");
|
||||
setShowCreate(false);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
@@ -103,6 +105,9 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
|
||||
<div className="min-w-40 flex-1">
|
||||
<Field label="Display name"><Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="Alice" /></Field>
|
||||
</div>
|
||||
<div className="min-w-40 flex-1">
|
||||
<Field label="Email (recovery)"><Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" /></Field>
|
||||
</div>
|
||||
<Button size="sm" type="submit">Create</Button>
|
||||
<Button size="sm" variant="ghost" type="button" onClick={() => setShowCreate(false)}>Cancel</Button>
|
||||
</form>
|
||||
@@ -148,6 +153,7 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
|
||||
function EditUserDialog({ user, onClose, onSaved }: { user: User | null; onClose: () => void; onSaved: () => void }) {
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [avatarUrl, setAvatarUrl] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [theme, setTheme] = useState("auto");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
@@ -155,6 +161,7 @@ function EditUserDialog({ user, onClose, onSaved }: { user: User | null; onClose
|
||||
if (user) {
|
||||
setDisplayName(user.displayName);
|
||||
setAvatarUrl(user.avatarUrl);
|
||||
setEmail(user.email);
|
||||
setTheme(user.theme);
|
||||
setError("");
|
||||
}
|
||||
@@ -164,7 +171,7 @@ function EditUserDialog({ user, onClose, onSaved }: { user: User | null; onClose
|
||||
e.preventDefault();
|
||||
if (!user) return;
|
||||
try {
|
||||
await api.adminPatch(user.id, { displayName: displayName.trim(), avatarUrl: avatarUrl.trim(), theme });
|
||||
await api.adminPatch(user.id, { displayName: displayName.trim(), avatarUrl: avatarUrl.trim(), email: email.trim(), theme });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
@@ -177,6 +184,7 @@ function EditUserDialog({ user, onClose, onSaved }: { user: User | null; onClose
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<Field label="Display name"><Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={60} required /></Field>
|
||||
<Field label="Avatar URL"><Input value={avatarUrl} onChange={(e) => setAvatarUrl(e.target.value)} placeholder="https://…" /></Field>
|
||||
<Field label="Email (recovery)"><Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" /></Field>
|
||||
<Field label="Theme">
|
||||
<Picker
|
||||
ariaLabel="Theme"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { BookOpen, Bot, Cpu, Menu, PanelLeftOpen, SendHorizontal, Share2, User as UserIcon } from "lucide-react";
|
||||
import type { ChatMessage, Conversation, DriverModel, User } from "../lib/types.ts";
|
||||
import { BookOpen, Bot, Cpu, FileText, Menu, PanelLeftOpen, Paperclip, ScanText, SendHorizontal, Share2, User as UserIcon, X } from "lucide-react";
|
||||
import type { Attachment, ChatMessage, Conversation, DriverModel, User } from "../lib/types.ts";
|
||||
import { Avatar, IconButton, LOGO_URL, Logo, Picker, type PickerGroup, Spinner } from "./ui.tsx";
|
||||
import { Markdown } from "./Markdown.tsx";
|
||||
import { cn } from "../lib/cn.ts";
|
||||
@@ -43,6 +43,11 @@ export function Chat({
|
||||
sidebarCollapsed,
|
||||
onExpandSidebar,
|
||||
onOpenNav,
|
||||
attachments,
|
||||
attachError,
|
||||
ocrAvailable,
|
||||
onRemoveAttachment,
|
||||
onPickFile,
|
||||
}: {
|
||||
user: User;
|
||||
conv: Conversation | null;
|
||||
@@ -57,10 +62,18 @@ export function Chat({
|
||||
sidebarCollapsed: boolean;
|
||||
onExpandSidebar: () => void;
|
||||
onOpenNav: () => void;
|
||||
attachments: Attachment[];
|
||||
attachError: string | null;
|
||||
ocrAvailable: boolean;
|
||||
onRemoveAttachment: (id: string) => void;
|
||||
onPickFile: (kind: "ocr" | "text", file: File) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState("");
|
||||
const [attachOpen, setAttachOpen] = useState(false);
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const imgRef = useRef<HTMLInputElement>(null);
|
||||
const txtRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const modelGroups: PickerGroup[] = (() => {
|
||||
const byDriver = new Map<string, { value: string; label: string; hint: string }[]>();
|
||||
@@ -162,7 +175,73 @@ export function Chat({
|
||||
</div>
|
||||
|
||||
<div className="px-4 pb-[max(0.5rem,env(safe-area-inset-bottom))] sm:px-8">
|
||||
<form onSubmit={submit} className="mx-auto flex w-full max-w-3xl items-end gap-2 rounded-[1.75rem] border border-stone-200 bg-white p-2 pl-5 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<div className="mx-auto w-full max-w-3xl">
|
||||
{attachError && (
|
||||
<p className="mb-2 rounded-2xl bg-red-500/10 px-4 py-2 text-sm text-red-600 dark:text-red-400" role="alert">{attachError}</p>
|
||||
)}
|
||||
{attachments.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-2">
|
||||
{attachments.map((a) => (
|
||||
<span key={a.id} className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-emerald-600/30 bg-emerald-600/10 py-1 pl-3 pr-1.5 text-xs font-medium dark:border-emerald-500/30 dark:bg-emerald-500/10">
|
||||
{a.kind === "ocr" ? <ScanText size={13} /> : <FileText size={13} />}
|
||||
<span className="max-w-40 truncate">{a.name}</span>
|
||||
<button onClick={() => onRemoveAttachment(a.id)} aria-label={`Remove ${a.name}`} className="rounded-full p-1 transition hover:bg-black/10 dark:hover:bg-white/10">
|
||||
<X size={13} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative mx-auto w-full max-w-3xl">
|
||||
{attachOpen && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setAttachOpen(false)} />
|
||||
<div className="absolute bottom-full left-0 z-50 mb-2 w-80 max-w-[calc(100vw-2rem)] rounded-3xl border border-stone-200 bg-white p-2 shadow-2xl dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<button
|
||||
onClick={() => { setAttachOpen(false); imgRef.current?.click(); }}
|
||||
disabled={!ocrAvailable}
|
||||
className="flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left transition hover:bg-stone-100 disabled:opacity-50 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
|
||||
<ScanText size={16} />
|
||||
</span>
|
||||
<span>
|
||||
<span className="block text-sm font-medium">Transcribe image {ocrAvailable ? "" : "(unavailable)"}</span>
|
||||
<span className="block text-xs opacity-60">JPG, PNG, WEBP — OCR on the server, you review the text first</span>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setAttachOpen(false); txtRef.current?.click(); }}
|
||||
className="flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left transition hover:bg-stone-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
|
||||
<FileText size={16} />
|
||||
</span>
|
||||
<span>
|
||||
<span className="block text-sm font-medium">Attach text file</span>
|
||||
<span className="block text-xs opacity-60">TXT or Markdown, max 500KB</span>
|
||||
</span>
|
||||
</button>
|
||||
<p className="px-3 pb-1.5 pt-2 text-xs opacity-60">
|
||||
Uploads go through platform tools only. Images are sent to the model as reviewed text — never as raw images.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<form onSubmit={submit} className="mx-auto flex w-full max-w-3xl items-end gap-2 rounded-[1.75rem] border border-stone-200 bg-white p-2 pl-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAttachOpen((o) => !o)}
|
||||
aria-label="Attach a file"
|
||||
title="Attach a file"
|
||||
className="grid h-10 w-10 shrink-0 place-items-center rounded-full transition hover:bg-stone-100 active:scale-95 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<Paperclip size={17} className="opacity-70" />
|
||||
</button>
|
||||
<input ref={imgRef} type="file" accept="image/jpeg,image/png,image/webp" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) onPickFile("ocr", f); e.target.value = ""; }} />
|
||||
<input ref={txtRef} type="file" accept=".txt,.md,text/plain,text/markdown" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) onPickFile("text", f); e.target.value = ""; }} />
|
||||
<textarea
|
||||
ref={taRef}
|
||||
rows={1}
|
||||
@@ -180,7 +259,7 @@ export function Chat({
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!draft.trim() || sending}
|
||||
disabled={(!draft.trim() && attachments.length === 0) || sending}
|
||||
aria-label="Send"
|
||||
className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-emerald-600 text-white shadow transition hover:bg-emerald-500 active:scale-95 disabled:opacity-40 dark:bg-emerald-500 dark:text-zinc-950 dark:hover:bg-emerald-400"
|
||||
>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { ArrowRight, KeyRound, ShieldCheck, User, Zap } from "lucide-react";
|
||||
import { api, setToken } from "../lib/api.ts";
|
||||
import type { User as UserType } from "../lib/types.ts";
|
||||
import { Button, Input, Logo, Spinner } from "./ui.tsx";
|
||||
import { RecoverDialog } from "./dialogs.tsx";
|
||||
|
||||
const PERKS = [
|
||||
{ icon: ShieldCheck, text: "Private by design — no cookies, no tracking" },
|
||||
@@ -14,6 +15,16 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
const [key, setKey] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recoverOpen, setRecoverOpen] = useState(false);
|
||||
const [recoveryOn, setRecoveryOn] = useState(false);
|
||||
const [recoveryFrom, setRecoveryFrom] = useState<string | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
api.methods().then((m) => {
|
||||
setRecoveryOn(m.recovery);
|
||||
setRecoveryFrom(m.from);
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -78,6 +89,12 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
{busy ? <Spinner /> : (<>Unlock <ArrowRight size={17} /></>)}
|
||||
</Button>
|
||||
</form>
|
||||
{recoveryOn && (
|
||||
<button onClick={() => setRecoverOpen(true)} className="mt-3 w-full text-center text-sm opacity-60 transition hover:opacity-100 hover:underline">
|
||||
Forgot your access key?
|
||||
</button>
|
||||
)}
|
||||
<RecoverDialog open={recoverOpen} onClose={() => setRecoverOpen(false)} from={recoveryFrom} />
|
||||
|
||||
<ul className="mt-6 space-y-2 border-t border-stone-200/70 pt-5 dark:border-zinc-800">
|
||||
{PERKS.map((p) => (
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { KeyRound, MailWarning, Sparkles } from "lucide-react";
|
||||
import { api } from "../lib/api.ts";
|
||||
import { Button, CopyButton, Logo, Spinner } from "./ui.tsx";
|
||||
|
||||
type State =
|
||||
| { kind: "loading" }
|
||||
| { kind: "invalid" }
|
||||
| { kind: "ready"; username: string }
|
||||
| { kind: "working" }
|
||||
| { kind: "done"; key: string }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
/** Public one-time key reset page: /reset/:token */
|
||||
export function ResetPage({ token }: { token: string }) {
|
||||
const [state, setState] = useState<State>({ kind: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
api.resetCheck(token)
|
||||
.then((r) => setState({ kind: "ready", username: r.username }))
|
||||
.catch(() => setState({ kind: "invalid" }));
|
||||
}, [token]);
|
||||
|
||||
async function consume() {
|
||||
setState({ kind: "working" });
|
||||
try {
|
||||
const r = await api.resetConsume(token);
|
||||
setState({ kind: "done", key: r.key });
|
||||
} catch (err) {
|
||||
setState({ kind: "error", message: err instanceof Error ? err.message : "Reset failed" });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid min-h-full place-items-center bg-gradient-to-br from-stone-100 via-stone-50 to-emerald-100/60 p-6 dark:from-zinc-950 dark:via-zinc-950 dark:to-emerald-950/40">
|
||||
<div className="w-full max-w-sm rounded-[2rem] border border-white/60 bg-white/80 p-8 text-center shadow-2xl backdrop-blur-xl dark:border-zinc-700/60 dark:bg-zinc-900/80">
|
||||
<Logo size={56} className="mx-auto mb-4 rounded-[1.2rem] shadow-lg" />
|
||||
{state.kind === "loading" && <p className="flex items-center justify-center gap-2 text-sm opacity-60"><Spinner size={15} /> Checking link…</p>}
|
||||
{state.kind === "invalid" && (
|
||||
<div className="space-y-3">
|
||||
<p className="flex items-center justify-center gap-2 font-semibold"><MailWarning size={18} className="text-red-500" /> Link invalid</p>
|
||||
<p className="text-sm opacity-70">This reset link is unknown, already used, or expired. Request a new one from the login page.</p>
|
||||
<Button size="sm" onClick={() => (window.location.href = "/")}>Back to login</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.kind === "ready" && (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-bold">Reset key for @{state.username}?</h1>
|
||||
<p className="text-sm opacity-70">This issues a fresh access key immediately. Your old key stops working.</p>
|
||||
<Button variant="gradient" size="lg" className="w-full" onClick={consume}>
|
||||
<KeyRound size={16} /> Issue new key
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.kind === "working" && <p className="flex items-center justify-center gap-2 text-sm opacity-60"><Spinner size={15} /> Issuing…</p>}
|
||||
{state.kind === "done" && (
|
||||
<div className="space-y-4">
|
||||
<h1 className="flex items-center justify-center gap-2 text-xl font-bold"><Sparkles size={18} className="text-emerald-500" /> New key ready</h1>
|
||||
<p className="text-sm opacity-70">Copy it now — it won't be shown again. Then log in with it.</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 truncate rounded-2xl bg-stone-100 px-3 py-2.5 text-sm dark:bg-zinc-800">{state.key}</code>
|
||||
<CopyButton text={state.key} />
|
||||
</div>
|
||||
<Button size="lg" className="w-full" onClick={() => (window.location.href = "/")}>Go to login</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.kind === "error" && (
|
||||
<div className="space-y-3">
|
||||
<p className="font-semibold text-red-600 dark:text-red-400">Reset failed</p>
|
||||
<p className="text-sm opacity-70">{state.message}</p>
|
||||
<Button size="sm" onClick={() => (window.location.href = "/")}>Back to login</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -148,7 +148,7 @@ export function Sidebar({
|
||||
}}
|
||||
onTouchEnd={cancelPress}
|
||||
className={cn(
|
||||
"group flex cursor-pointer items-center gap-2 rounded-2xl px-3 py-2.5 text-sm transition",
|
||||
"group flex cursor-pointer select-none items-center gap-2 rounded-2xl px-3 py-2.5 text-sm transition [-webkit-touch-callout:none]",
|
||||
c.id === activeId
|
||||
? "bg-emerald-600/10 font-medium text-emerald-900 dark:bg-emerald-500/10 dark:text-emerald-100"
|
||||
: "hover:bg-stone-200/50 dark:hover:bg-zinc-800/70",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Globe, ImagePlus, Link2, Pencil, Settings2, Tag, Unplug } from "lucide-react";
|
||||
import { Globe, FileText, ImagePlus, Link2, Mail, Pencil, ScanText, Settings2, Tag, Unplug } from "lucide-react";
|
||||
import { api } from "../lib/api.ts";
|
||||
import { cn } from "../lib/cn.ts";
|
||||
import type { Conversation, User } from "../lib/types.ts";
|
||||
import type { Conversation, FilePreview, User } from "../lib/types.ts";
|
||||
import { Avatar, Button, CopyButton, Field, Input, Modal, Picker, Spinner } from "./ui.tsx";
|
||||
|
||||
/* ---------- Rename + topic ---------- */
|
||||
@@ -67,6 +67,139 @@ export function ConvEditDialog({
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Key recovery ---------- */
|
||||
|
||||
export function RecoverDialog({ open, onClose, from }: { open: boolean; onClose: () => void; from?: string }) {
|
||||
const [username, setUsername] = useState("");
|
||||
const [sent, setSent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setUsername("");
|
||||
setSent(false);
|
||||
setError("");
|
||||
}
|
||||
}, [open ]);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await api.recover(username.trim().toLowerCase());
|
||||
setSent(true);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Request failed");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Recover access key" icon={Mail}>
|
||||
{sent ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm opacity-80">
|
||||
If <strong>@{username.trim().toLowerCase() || "…"}</strong> exists and has a recovery
|
||||
email, a reset link is on its way{from ? <> from <strong>{from}</strong></> : ""} (valid 60 minutes, single use).
|
||||
</p>
|
||||
<p className="rounded-2xl bg-amber-500/10 px-4 py-2.5 text-sm opacity-90 dark:bg-amber-500/10">
|
||||
Check your inbox — and your spam folder, the message may have landed there.
|
||||
</p>
|
||||
<p className="text-sm opacity-70">
|
||||
Nothing arrives? Then no recovery email is set on your account and the
|
||||
reset is not possible — please contact the site administrator.
|
||||
</p>
|
||||
<div className="flex justify-end">
|
||||
<Button size="sm" onClick={onClose}>Done</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<p className="text-sm opacity-70">
|
||||
Enter your username. You'll receive a link that issues a fresh key
|
||||
(the old one stops working).
|
||||
</p>
|
||||
<Field label="Username">
|
||||
<Input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="alice" required />
|
||||
</Field>
|
||||
{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="secondary" size="sm" type="button" onClick={onClose}>Cancel</Button>
|
||||
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : "Send reset link"}</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- File preview (pre-transcription review) ---------- */
|
||||
|
||||
export function FilePreviewModal({
|
||||
preview,
|
||||
busy,
|
||||
onClose,
|
||||
onAttach,
|
||||
}: {
|
||||
preview: FilePreview | null;
|
||||
busy: boolean;
|
||||
onClose: () => void;
|
||||
onAttach: (text: string) => void;
|
||||
}) {
|
||||
const [text, setText] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (preview) setText(preview.text);
|
||||
}, [preview]);
|
||||
|
||||
const isOcr = preview?.kind === "ocr";
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={preview !== null}
|
||||
onClose={onClose}
|
||||
title={isOcr ? "Review transcription" : "Review text attachment"}
|
||||
icon={isOcr ? ScanText : FileText}
|
||||
wide
|
||||
>
|
||||
{busy ? (
|
||||
<p className="flex items-center gap-2 py-8 text-sm opacity-70">
|
||||
<Spinner size={16} />
|
||||
{isOcr ? "Transcribing the image on the server (OCR)…" : "Uploading through platform tools…"}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="rounded-2xl bg-emerald-600/10 px-4 py-2.5 text-sm opacity-90">
|
||||
{isOcr
|
||||
? <>The image was transcribed to text on the server — <strong>the model receives this text, never the image</strong>. Fix any reading mistakes below, then attach.</>
|
||||
: <>The file was uploaded through platform tools. <strong>Its text content is attached to your message.</strong> Edit below if needed, then attach.</>}
|
||||
</p>
|
||||
{preview?.truncated && (
|
||||
<p className="rounded-2xl bg-amber-500/10 px-4 py-2.5 text-sm">Transcription truncated to the server limit — the end is missing.</p>
|
||||
)}
|
||||
<textarea
|
||||
rows={10}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
className="w-full resize-y rounded-2xl border border-stone-200 bg-stone-50 p-4 font-mono text-[13px] leading-relaxed outline-none focus:border-emerald-500 dark:border-zinc-700 dark:bg-zinc-800"
|
||||
/>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs opacity-60">{preview?.name} · {text.length.toLocaleString()} chars</span>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={onClose}>Cancel</Button>
|
||||
<Button size="sm" onClick={() => onAttach(text)} disabled={!text.trim()}>Attach to message</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Share ---------- */
|
||||
|
||||
export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClose: () => void }) {
|
||||
@@ -128,6 +261,7 @@ export function SettingsModal({
|
||||
}) {
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [avatarUrl, setAvatarUrl] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [theme, setTheme] = useState("auto");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
@@ -140,6 +274,7 @@ export function SettingsModal({
|
||||
if (user) {
|
||||
setDisplayName(user.displayName);
|
||||
setAvatarUrl(user.avatarUrl);
|
||||
setEmail(user.email);
|
||||
setTheme(user.theme);
|
||||
setError("");
|
||||
setUploadError("");
|
||||
@@ -174,7 +309,7 @@ export function SettingsModal({
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await api.updateMe({ displayName: displayName.trim(), avatarUrl: avatarUrl.trim(), theme });
|
||||
const res = await api.updateMe({ displayName: displayName.trim(), avatarUrl: avatarUrl.trim(), email: email.trim(), theme });
|
||||
onSaved(res.user);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
@@ -244,6 +379,9 @@ export function SettingsModal({
|
||||
<Field label="Avatar URL" hint="Host an image on catbox.moe (or anywhere) and paste the direct link here. Empty = initials.">
|
||||
<Input value={avatarUrl} onChange={(e) => setAvatarUrl(e.target.value)} placeholder="https://…" inputMode="url" />
|
||||
</Field>
|
||||
<Field label="Recovery email" hint="Optional. Used only to send you a fresh access key if you lose it.">
|
||||
<Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" />
|
||||
</Field>
|
||||
<Field label="Theme">
|
||||
<Picker
|
||||
ariaLabel="Theme"
|
||||
|
||||
@@ -5,9 +5,19 @@
|
||||
html, body, #root {
|
||||
height: 100%;
|
||||
}
|
||||
/* Mobile browser chrome (URL bar) shrinks the visible area — dynamic
|
||||
viewport units keep the app glued to the real screen height. */
|
||||
@supports (height: 100dvh) {
|
||||
html, body, #root {
|
||||
height: 100dvh;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-stone-100 text-stone-900 antialiased dark:bg-zinc-950 dark:text-zinc-100;
|
||||
/* Kill the 300ms tap delay, keep gestures app-like. */
|
||||
touch-action: manipulation;
|
||||
overscroll-behavior-y: none;
|
||||
}
|
||||
|
||||
/* slim scrollbars */
|
||||
|
||||
+28
-3
@@ -46,16 +46,22 @@ export const api = {
|
||||
verify: () => req<{ ok: boolean; user: User }>("/api/auth/verify"),
|
||||
logout: () => req<{ ok: boolean }>("/api/auth/logout", { method: "POST" }).catch(() => ({ ok: true as const })),
|
||||
|
||||
methods: () => req<{ recovery: boolean; from?: string }>("/api/auth/methods", {}, false),
|
||||
recover: (username: string) =>
|
||||
req<{ ok: boolean }>("/api/auth/recover", { method: "POST", body: JSON.stringify({ username }) }, false),
|
||||
resetCheck: (token: string) => req<{ ok: boolean; username: string }>(`/api/auth/reset/${token}`, {}, false),
|
||||
resetConsume: (token: string) => req<{ key: string }>(`/api/auth/reset/${token}`, { method: "POST" }, false),
|
||||
|
||||
me: () => req<{ user: User }>("/api/me"),
|
||||
updateMe: (patch: { displayName?: string; avatarUrl?: string; theme?: string }) =>
|
||||
updateMe: (patch: { displayName?: string; avatarUrl?: string; theme?: string; email?: string }) =>
|
||||
req<{ user: User }>("/api/me", { method: "PATCH", body: JSON.stringify(patch) }),
|
||||
|
||||
adminList: () => req<{ users: User[] }>("/api/admin/users"),
|
||||
adminCreate: (u: { username: string; displayName?: string; avatarUrl?: string; theme?: string }) =>
|
||||
adminCreate: (u: { username: string; displayName?: string; avatarUrl?: string; theme?: string; email?: string }) =>
|
||||
req<{ user: User; key: string }>("/api/admin/users", { method: "POST", body: JSON.stringify(u) }),
|
||||
adminDelete: (id: string) => req<{ ok: boolean }>(`/api/admin/users/${id}`, { method: "DELETE" }),
|
||||
adminRegenerate: (id: string) => req<{ key: string }>(`/api/admin/users/${id}/regenerate`, { method: "POST" }),
|
||||
adminPatch: (id: string, patch: { displayName?: string; avatarUrl?: string; theme?: string }) =>
|
||||
adminPatch: (id: string, patch: { displayName?: string; avatarUrl?: string; theme?: string; email?: string }) =>
|
||||
req<{ user: User }>(`/api/admin/users/${id}`, { method: "PATCH", body: JSON.stringify(patch) }),
|
||||
|
||||
convs: () => req<{ conversations: Conversation[] }>("/api/conversations"),
|
||||
@@ -73,6 +79,25 @@ export const api = {
|
||||
|
||||
models: () => req<{ models: DriverModel[] }>("/api/models"),
|
||||
|
||||
tools: () => req<{ tools: { name: string; description: string; available: boolean; reason: string | null }[] }>("/api/tools"),
|
||||
|
||||
/** Send an image to the platform OCR tool. Returns editable text (never the raw image). */
|
||||
ocrImage: async (file: File): Promise<{ text: string; truncated: boolean; chars: number }> => {
|
||||
const res = await fetch("/api/tools/ocr", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${getToken()}`, "Content-Type": file.type || "application/octet-stream" },
|
||||
body: file,
|
||||
});
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
window.location.reload();
|
||||
throw new ApiError(401, "Session expired.");
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as { error?: string; text?: string; truncated?: boolean; chars?: number };
|
||||
if (!res.ok) throw new ApiError(res.status, data.error || `OCR failed (${res.status})`);
|
||||
return { text: data.text ?? "", truncated: !!data.truncated, chars: data.chars ?? 0 };
|
||||
},
|
||||
|
||||
/** Avatar upload to the local CDN. Returns the public /cdn/… URL. */
|
||||
uploadAvatar: async (userId: string, file: File): Promise<{ url: string }> => {
|
||||
const res = await fetch(`/cdn/avatar/${userId}`, {
|
||||
|
||||
@@ -4,6 +4,7 @@ export interface User {
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
theme: string;
|
||||
email: string;
|
||||
createdAt: number;
|
||||
isAdmin: boolean;
|
||||
}
|
||||
@@ -30,6 +31,20 @@ export interface DriverModel {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: "ocr" | "text";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface FilePreview {
|
||||
name: string;
|
||||
kind: "ocr" | "text";
|
||||
text: string;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export interface SharedChat {
|
||||
title: string;
|
||||
topic: string;
|
||||
|
||||
Reference in New Issue
Block a user