Compare commits

...
6 Commits
Author SHA1 Message Date
k 70c21698e8 . 2026-09-21 16:38:40 +02:00
k 8038e02303 . 2026-09-21 16:37:40 +02:00
k ad1629164f Update index.ts 2026-09-21 16:35:49 +02:00
k 8f49bb56a2 fixing translations 2026-09-21 16:35:46 +02:00
k efeb11577d . 2026-09-21 16:34:14 +02:00
k 48fb137c13 fixes 2026-09-21 16:31:55 +02:00
19 changed files with 837 additions and 181 deletions
+9
View File
@@ -49,3 +49,12 @@ sur la page share, l' avatar de l'utilisateur ne s'affiche pas -> fix sa
--- improvements:
éviter de ask h24 ollama pour ces modèles quand un utilisateur ce connece. c'est le backend qui sert les demande d el'utilisateurs. iL relay pas sur le ollama. Le backend vas cacher avec un TLL les modèles présent en mémire dans un objet qui est dans le backend. refresh avec un TT: toutes les minutes.
L'administrateur lui, qand il demande les modèles dams le ollama, lui, force un refresh .
--- ADMIN CENTER: SMTP CONNECTIVITY.
Make a SMTP tester in the admin center, and also a viewer of the smtp credentials (default bluring the smtp pasword OBVIOUSLY) And also a SMTP tester , sending a mail to a provided one , to tets the SMTP connectivity
--- ARCHIVED FEATURES:
a way to archive conversaitons with the contetxual menue.
When conversations are archived. it's impossible to write in . only read-only. also, when conversations are archived, they are not anymore visible in the conversations side list. They are still unarchivable and checkable, in a new sub-category options into the settigns modal : "Archiveds Chats"
+5
View File
@@ -103,6 +103,11 @@ Models are addressed as `"driver:model"` (split on the first `:`).
- `OllamaDriver`: model discovery via `GET {OLLAMA_HOST}/api/tags`, chat via
`POST /api/chat` with NDJSON streaming.
- `GET /api/models` is served from an in-memory cache in `DriverRegistry`
(`MODEL_CACHE_TTL_MS` = 60 s) so logins don't hit Ollama every time.
Concurrent misses share one in-flight upstream fetch. Admins pass
`?refresh=1` to force a fresh fetch (used by the "Ollama models" view);
the flag is ignored for non-admins. Admin pull/delete invalidate the cache.
- `ApiDriverBase`: shared OpenAI-compatible `/models` + `/chat/completions`
(SSE) implementation; concrete drivers only set base URL, key, and fallback
model list. A driver is enabled only when its `*_ENABLED` flag is set **and**
+5 -1
View File
@@ -19,6 +19,8 @@ read-only `SharePage` (no auth), everything else renders the authenticated app.
- `lib/api.ts` — typed `fetch` wrapper: Bearer header from `localStorage`,
`{ error }` parsing, `ApiError` with status, auto logout+reload on 401
(except on `/share/*`). `chatStream()` parses SSE `token`/`done`/`error`.
- Boot shows `LoadingScreen` for at least 2.5 s (`MIN_SPLASH_MS` in `App.tsx`)
so the bloom animation always plays, even when the session restores instantly.
- Sending: ensure a server conversation exists (created lazily on first send),
optimistic user message, stream tokens into `streaming`, then append the full
assistant message and refresh the list (server auto-titles new chats).
@@ -50,7 +52,9 @@ read-only `SharePage` (no auth), everything else renders the authenticated app.
tabbed hub (Accounts / Features / Mail) reusing `AdminPanel`, server
feature `Switch`es (`registrationEnabled`, `ocrEnabled` via
`/api/admin/settings`), SMTP status card. Follows the platform theme.
- `SharePage.tsx` — public read-only view, fetches `/api/share/:id` unauthenticated.
- `SharePage.tsx` — public read-only view, fetches `/api/share/:id` unauthenticated
(`{ title, topic, model, authorName, authorAvatarUrl, sharedAt, messages }`);
user messages render the author's avatar via `Avatar` (URL or initials).
- `Markdown.tsx` — `react-markdown` + GFM; code blocks get a language label and
a copy button.
+13 -4
View File
@@ -33,6 +33,10 @@ function reviewIdFromPath(): string | null {
return m ? m[1]! : null;
}
/** Minimum time the boot splash stays visible, so the bloom animation
* actually plays even when the session restores instantly. */
const MIN_SPLASH_MS = 2500;
function applyTheme(theme: string) {
const root = document.documentElement;
const dark =
@@ -43,7 +47,7 @@ function applyTheme(theme: string) {
export function App() {
const [user, setUser] = useState<User | null>(null);
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !REVIEW_ID && !IS_ADMIN_PAGE && !!getToken());
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !REVIEW_ID && !IS_ADMIN_PAGE);
const [models, setModels] = useState<DriverModel[]>([]);
const [model, setModel] = useState("");
const [convs, setConvs] = useState<Conversation[]>([]);
@@ -90,10 +94,15 @@ export function App() {
}
}, []);
// Session restore
// Session restore (boot splash stays at least MIN_SPLASH_MS)
useEffect(() => {
const t0 = Date.now();
const done = () => {
const wait = Math.max(0, MIN_SPLASH_MS - (Date.now() - t0));
window.setTimeout(() => setChecking(false), wait);
};
if (!getToken()) {
setChecking(false);
done();
return;
}
api.verify()
@@ -112,7 +121,7 @@ export function App() {
if (c.conversations.length > 0) setActiveId(c.conversations[0]!.id);
})
.catch(() => {})
.finally(() => setChecking(false));
.finally(done);
}, []);
// Load messages for active conversation
+165 -29
View File
@@ -1,9 +1,9 @@
import { useEffect, useState } from "react";
import { ArrowLeft, Inbox, LayoutDashboard, Mail, ShieldAlert, SlidersHorizontal, Users } from "lucide-react";
import { ArrowLeft, Eye, EyeOff, Inbox, LayoutDashboard, Mail, Send, ShieldAlert, SlidersHorizontal, Users } from "lucide-react";
import { api } from "../lib/api.ts";
import { AdminPanel } from "./AdminPanel.tsx";
import { AccessRequestsPanel } from "./AccessRequests.tsx";
import { FlowerMark, LoadingScreen, Spinner, Switch } from "./ui.tsx";
import { Button, CopyButton, FlowerMark, Input, LoadingScreen, Spinner, Switch } from "./ui.tsx";
import { cn } from "../lib/cn.ts";
type Tab = "accounts" | "access" | "features" | "mail";
@@ -26,7 +26,6 @@ export function AdminCenter() {
const [allowed, setAllowed] = useState<boolean | null>(null);
const [tab, setTab] = useState<Tab>("accounts");
const [settings, setSettings] = useState<{ registrationEnabled: boolean; accessRequestEnabled: boolean; ocrEnabled: boolean } | null>(null);
const [mail, setMail] = useState<{ recovery: boolean; from?: string } | null>(null);
const [error, setError] = useState("");
const [saving, setSaving] = useState(false);
@@ -40,7 +39,6 @@ export function AdminCenter() {
setAllowed(true);
applyTheme(r.user.theme);
api.adminGetSettings().then((s) => setSettings(s.settings)).catch((e) => setError(e instanceof Error ? e.message : "Load failed"));
api.methods().then((m) => setMail(m)).catch(() => {});
})
.catch(() => setAllowed(false));
}, []);
@@ -164,32 +162,170 @@ export function AdminCenter() {
</section>
)}
{tab === "mail" && (
<section className="rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<div className="flex items-center gap-3">
<span className="grid h-10 w-10 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<Mail size={17} />
</span>
<div>
<p className="text-sm font-medium">Key recovery emails</p>
<p className="text-sm opacity-60">
{mail == null ? "Checking…" : mail.recovery ? `Enabled — sent from ${mail.from ?? "the configured sender"}` : "Disabled — set SMTP_HOST on the server to enable"}
</p>
</div>
<span className={cn(
"ml-auto rounded-full px-3 py-1 text-xs font-medium",
mail?.recovery ? "bg-emerald-600/10 text-emerald-700 dark:text-emerald-400" : "bg-stone-200/70 dark:bg-zinc-800",
)}>
{mail?.recovery ? "On" : "Off"}
</span>
</div>
<p className="mt-3 text-sm opacity-60">
SMTP credentials live in the server environment (see <code>docs/OPERATIONS.md</code>), never in this UI.
Users set their recovery address in profile settings or at account creation.
</p>
</section>
)}
{tab === "mail" && <MailPanel />}
</main>
</div>
);
}
type SmtpInfo = {
enabled: boolean;
host: string;
port: number;
secure: boolean;
user: string;
pass: string;
hasPass: boolean;
from: string;
appUrl: string;
};
function MailPanel() {
const [smtp, setSmtp] = useState<SmtpInfo | null>(null);
const [error, setError] = useState("");
const [showPass, setShowPass] = useState(false);
const [to, setTo] = useState("");
const [verifying, setVerifying] = useState(false);
const [sending, setSending] = useState(false);
const [result, setResult] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => {
api.adminMailStatus().then((r) => setSmtp(r.smtp)).catch((e) => setError(e instanceof Error ? e.message : "Load failed"));
}, []);
async function verify() {
setVerifying(true);
setResult(null);
try {
await api.adminMailVerify();
setResult({ ok: true, text: "Connection OK — SMTP host reachable, auth accepted." });
} catch (e) {
setResult({ ok: false, text: e instanceof Error ? e.message : "Verification failed" });
} finally {
setVerifying(false);
}
}
async function sendTest() {
setSending(true);
setResult(null);
try {
const r = await api.adminMailTest(to.trim());
setResult({ ok: true, text: `Test mail sent to ${to.trim()}${r.messageId ? ` (${r.messageId})` : ""}.` });
} catch (e) {
setResult({ ok: false, text: e instanceof Error ? e.message : "Send failed" });
} finally {
setSending(false);
}
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-center gap-3 py-2">
<span className="w-24 shrink-0 text-xs font-medium uppercase tracking-wider opacity-50">{label}</span>
<span className="min-w-0 flex-1 truncate text-sm">{children}</span>
</div>
);
}
return (
<div className="space-y-4">
<section className="rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<div className="flex items-center gap-3">
<span className="grid h-10 w-10 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<Mail size={17} />
</span>
<div>
<p className="text-sm font-medium">Key recovery emails</p>
<p className="text-sm opacity-60">
{smtp == null ? "Checking…" : smtp.enabled ? `Enabled — sent from ${smtp.from}` : "Disabled — set SMTP_HOST on the server to enable"}
</p>
</div>
<span className={cn(
"ml-auto rounded-full px-3 py-1 text-xs font-medium",
smtp?.enabled ? "bg-emerald-600/10 text-emerald-700 dark:text-emerald-400" : "bg-stone-200/70 dark:bg-zinc-800",
)}>
{smtp?.enabled ? "On" : "Off"}
</span>
</div>
{error && <p className="mt-3 text-sm text-red-600 dark:text-red-400" role="alert">{error}</p>}
{!smtp && !error && <p className="mt-3 flex items-center gap-2 text-sm opacity-60"><Spinner size={14} /> Loading…</p>}
{smtp && (
<div className="mt-3 divide-y divide-stone-200/70 rounded-2xl border border-stone-200/70 px-4 dark:divide-zinc-800 dark:border-zinc-800">
<Row label="Host">{smtp.host || <span className="opacity-50">(not set)</span>}</Row>
<Row label="Port">{smtp.port} · {smtp.secure ? "implicit TLS (465)" : "STARTTLS (587)"}</Row>
<Row label="User">{smtp.user || <span className="opacity-50">(no auth)</span>}</Row>
<Row label="Password">
<span className="flex items-center gap-2">
{!smtp.hasPass ? (
<span className="opacity-50">(not set)</span>
) : showPass ? (
<code className="truncate font-mono">{smtp.pass}</code>
) : (
<code className="select-none blur-sm" aria-label="hidden password">••••••••••</code>
)}
{smtp.hasPass && (
<>
<button
type="button"
onClick={() => setShowPass((v) => !v)}
aria-label={showPass ? "Hide SMTP password" : "Show SMTP password"}
className="rounded-full p-1.5 transition hover:bg-stone-200/60 dark:hover:bg-zinc-800"
>
{showPass ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
{showPass && <CopyButton text={smtp.pass} />}
</>
)}
</span>
</Row>
<Row label="From"><span className="truncate">{smtp.from}</span></Row>
<Row label="App URL"><span className="truncate">{smtp.appUrl}</span></Row>
</div>
)}
<p className="mt-3 text-sm opacity-60">
Credentials live in the server environment (see <code>docs/OPERATIONS.md</code>), read-only here.
Users set their recovery address in profile settings or at account creation.
</p>
</section>
<section className="rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<p className="text-sm font-medium">Connectivity test</p>
<p className="mt-0.5 text-sm opacity-60">Verify the connection, then send a real test mail to an address you control.</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
<Button variant="secondary" size="sm" onClick={verify} disabled={verifying || !smtp?.enabled}>
{verifying ? <Spinner size={14} /> : null}
{verifying ? "Verifying…" : "Verify connection"}
</Button>
</div>
<div className="mt-3 flex flex-col gap-2 sm:flex-row">
<Input
type="email"
placeholder="[email protected]"
aria-label="Test recipient email"
value={to}
onChange={(e) => setTo(e.target.value)}
className="flex-1"
/>
<Button size="sm" onClick={sendTest} disabled={sending || !smtp?.enabled || !/^[^\s@]{1,64}@[^\s@]{1,253}\.[^\s@]{2,}$/.test(to.trim())}>
{sending ? <Spinner size={14} /> : <Send size={14} />}
{sending ? "Sending…" : "Send test mail"}
</Button>
</div>
{result && (
<p
role={result.ok ? "status" : "alert"}
className={cn(
"mt-3 rounded-2xl px-4 py-2.5 text-sm",
result.ok
? "bg-emerald-600/10 text-emerald-700 dark:text-emerald-400"
: "bg-red-500/10 text-red-600 dark:text-red-400",
)}
>
{result.text}
</p>
)}
</section>
</div>
);
}
+2 -1
View File
@@ -32,7 +32,8 @@ export function OllamaModelsModal({ open, onClose }: { open: boolean; onClose: (
async function refreshInstalled() {
try {
const res = await api.models();
// Admin view: force a fresh upstream fetch, bypassing the 60s user cache.
const res = await api.models({ refresh: true });
setInstalled(res.models.filter((m) => m.driver === "ollama"));
} catch { /* ignore */ }
}
+1 -1
View File
@@ -89,7 +89,7 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
{totpToken ? (
<form onSubmit={submitTotp} className="mt-6 space-y-3">
<p className="text-center text-sm opacity-70">
{t("login.totpIntro", { user: "@" + totpUsername })}
{t("login.totpIntro", { user: totpUsername })}
</p>
<div className="relative">
<KeyRound size={17} className="pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 text-stone-400 dark:text-zinc-500" />
+1 -1
View File
@@ -65,7 +65,7 @@ export function SharePage({ publicId }: { publicId: string }) {
{chat?.messages.map((m, i) => (
<div key={i} className="flex gap-3">
{m.role === "user"
? <Avatar name={chat.authorName} size={32} />
? <Avatar name={chat.authorName} url={chat.authorAvatarUrl || undefined} size={32} />
: <AssistantAvatar size={32} />}
<div className="min-w-0 max-w-[90%] flex-1">
<div className="mb-1 flex items-center gap-1.5 text-xs opacity-60">
+11 -9
View File
@@ -14,6 +14,7 @@ import {
} from "lucide-react";
import type { Conversation, User } from "../lib/types.ts";
import { api } from "../lib/api.ts";
import { useT } from "../lib/i18n.ts";
import { Avatar, Button, ContextMenu, FlowerMark, IconButton } from "./ui.tsx";
import { cn } from "../lib/cn.ts";
@@ -58,6 +59,7 @@ export function Sidebar({
mobileOpen: boolean;
onCloseMobile: () => void;
}) {
const { t } = useT();
const [menu, setMenu] = useState<MenuState | null>(null);
const [query, setQuery] = useState("");
const [results, setResults] = useState<(Conversation & { snippet: string | null; snippetRole: string | null })[] | null>(null);
@@ -132,12 +134,12 @@ export function Sidebar({
<div className="flex items-center gap-1">
<Button variant="secondary" size="sm" className="flex-1" onClick={onNew}>
<MessageSquarePlus size={16} />
New chat
{t("sidebar.newChat")}
</Button>
<IconButton title="Collapse sidebar" onClick={onToggle} className="hidden md:inline-flex">
<IconButton title={t("sidebar.collapse")} onClick={onToggle} className="hidden md:inline-flex">
<PanelLeftClose size={18} />
</IconButton>
<IconButton title="Close chats" onClick={onCloseMobile} className="md:hidden">
<IconButton title={t("sidebar.closeDrawer")} onClick={onCloseMobile} className="md:hidden">
<X size={18} />
</IconButton>
</div>
@@ -146,13 +148,13 @@ export function Sidebar({
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search chats…"
aria-label="Search conversations"
placeholder={t("sidebar.searchPh")}
aria-label={t("sidebar.searchAria")}
className="w-full rounded-2xl border border-stone-200/70 bg-stone-100 py-2 pl-9 pr-8 text-sm outline-none transition placeholder:text-stone-400 focus:border-accent-500/60 focus:bg-white dark:border-zinc-800 dark:bg-zinc-800/60 dark:placeholder:text-zinc-500 dark:focus:bg-zinc-900"
/>
{query && (
<button
aria-label="Clear search"
aria-label={t("sidebar.clearSearch")}
onClick={() => setQuery("")}
className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-60 transition hover:opacity-100"
>
@@ -164,9 +166,9 @@ export function Sidebar({
<div className="flex-1 space-y-1 overflow-y-auto py-1">
{results !== null ? (
<>
{searching && <p className="px-3 py-4 text-center text-sm opacity-50">Searching…</p>}
{searching && <p className="px-3 py-4 text-center text-sm opacity-50">{t("sidebar.searching")}</p>}
{!searching && results.length === 0 && (
<p className="px-3 py-6 text-center text-sm opacity-50">No match for “{query.trim()}”.</p>
<p className="px-3 py-6 text-center text-sm opacity-50">{t("sidebar.noMatch", { q: query.trim() })}</p>
)}
{results.map((c) => (
<div
@@ -185,7 +187,7 @@ export function Sidebar({
<span className="block truncate">{c.title}</span>
{c.snippet && (
<span className="mt-0.5 block truncate text-xs opacity-60">
{c.snippetRole === "user" ? "you: " : ""}{c.snippet}
{c.snippetRole === "user" ? t("sidebar.youPrefix") : ""}{c.snippet}
</span>
)}
</div>
+122 -109
View File
@@ -5,7 +5,8 @@ import { cn } from "../lib/cn.ts";
import { ACCENT_PRESETS, applyAccent, currentAccent, previewAccent, type AccentState } from "../lib/accent.ts";
import { FEATURES, setFeature, useFeatures } from "../lib/features.ts";
import type { Conversation, FilePreview, User } from "../lib/types.ts";
import { Avatar, bumpCdnVersion, Button, ConfirmDialog, CopyButton, Field, Input, Modal, Picker, Spinner, Toggle } from "./ui.tsx";
import { useT, type StringKey } from "../lib/i18n.ts";
import { Avatar, bumpCdnVersion, Button, ConfirmDialog, CopyButton, Field, Input, LangPicker, Modal, Picker, Spinner, Toggle } from "./ui.tsx";
/* ---------- Rename + topic ---------- */
@@ -18,6 +19,7 @@ export function ConvEditDialog({
onClose: () => void;
onSaved: (c: Conversation) => void;
}) {
const { t } = useT();
const [title, setTitle] = useState("");
const [topic, setTopic] = useState("");
const [busy, setBusy] = useState(false);
@@ -41,28 +43,28 @@ export function ConvEditDialog({
onSaved(res.conversation);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "Save failed");
setError(err instanceof Error ? err.message : t("common.saveFailed"));
} finally {
setBusy(false);
}
}
return (
<Modal open={conv !== null} onClose={onClose} title="Edit conversation" icon={Pencil}>
<Modal open={conv !== null} onClose={onClose} title={t("dlg.editConv")} icon={Pencil}>
<form onSubmit={save} className="space-y-4">
<Field label="Title">
<Field label={t("dlg.fTitle")}>
<Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={120} required />
</Field>
<Field label="Topic" hint="A short theme tag, e.g. cooking, rust, travel.">
<Field label={t("dlg.fTopic")} hint={t("dlg.topicHint")}>
<div className="relative">
<Tag size={15} className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 opacity-40" />
<Input className="pl-10" value={topic} onChange={(e) => setTopic(e.target.value)} maxLength={120} placeholder="No topic" />
<Input className="pl-10" value={topic} onChange={(e) => setTopic(e.target.value)} maxLength={120} placeholder={t("dlg.noTopic")} />
</div>
</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} /> : "Save"}</Button>
<Button variant="secondary" size="sm" type="button" onClick={onClose}>{t("common.cancel")}</Button>
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : t("common.save")}</Button>
</div>
</form>
</Modal>
@@ -72,6 +74,7 @@ export function ConvEditDialog({
/* ---------- Key recovery ---------- */
export function RecoverDialog({ open, onClose, from }: { open: boolean; onClose: () => void; from?: string }) {
const { t } = useT();
const [username, setUsername] = useState("");
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
@@ -94,44 +97,44 @@ export function RecoverDialog({ open, onClose, from }: { open: boolean; onClose:
await api.recover(username.trim().toLowerCase());
setSent(true);
} catch (err) {
setError(err instanceof Error ? err.message : "Request failed");
setError(err instanceof Error ? err.message : t("dlg.reqFailed"));
} finally {
setBusy(false);
}
}
return (
<Modal open={open} onClose={onClose} title="Recover access key" icon={Mail} wide>
<Modal open={open} onClose={onClose} title={t("dlg.recoverTitle")} icon={Mail} wide>
{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).
{t("dlg.recoverSent", {
user: username.trim().toLowerCase() || "…",
fromPart: from ? t("dlg.recoverSentFrom", { from }) : "",
})}
</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.
{t("dlg.spamNote")}
</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.
{t("dlg.noMailNote")}
</p>
<div className="flex justify-end">
<Button size="sm" onClick={onClose}>Done</Button>
<Button size="sm" onClick={onClose}>{t("common.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).
{t("dlg.recoverIntro")}
</p>
<Field label="Username">
<Field label={t("common.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>
<Button variant="secondary" size="sm" type="button" onClick={onClose}>{t("common.cancel")}</Button>
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : t("dlg.sendLink")}</Button>
</div>
</form>
)}
@@ -152,6 +155,7 @@ export function FilePreviewModal({
onClose: () => void;
onAttach: (text: string) => void;
}) {
const { t } = useT();
const [text, setText] = useState("");
useEffect(() => {
@@ -164,24 +168,22 @@ export function FilePreviewModal({
<Modal
open={preview !== null}
onClose={onClose}
title={isOcr ? "Review transcription" : "Review text attachment"}
title={isOcr ? t("dlg.reviewOcr") : t("dlg.reviewText")}
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…"}
{isOcr ? t("dlg.transcribing") : t("dlg.uploadingTools")}
</p>
) : (
<div className="space-y-3">
<p className="rounded-2xl bg-accent-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.</>}
{isOcr ? t("dlg.ocrExpl") : t("dlg.textExpl")}
</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>
<p className="rounded-2xl bg-amber-500/10 px-4 py-2.5 text-sm">{t("dlg.truncWarn")}</p>
)}
<textarea
rows={10}
@@ -190,10 +192,10 @@ export function FilePreviewModal({
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-accent-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>
<span className="text-xs opacity-60">{preview?.name} · {t("dlg.chars", { n: text.length.toLocaleString() })}</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>
<Button variant="secondary" size="sm" onClick={onClose}>{t("common.cancel")}</Button>
<Button size="sm" onClick={() => onAttach(text)} disabled={!text.trim()}>{t("dlg.attachBtn")}</Button>
</div>
</div>
</div>
@@ -213,6 +215,7 @@ export function RegisterDialog({
onClose: () => void;
onDone: (username: string, key: string) => void;
}) {
const { t } = useT();
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [email, setEmail] = useState("");
@@ -243,42 +246,42 @@ export function RegisterDialog({
});
setKey(res.key);
} catch (err) {
setError(err instanceof Error ? err.message : "Registration failed");
setError(err instanceof Error ? err.message : t("dlg.regFailed"));
} finally {
setBusy(false);
}
}
return (
<Modal open={open} onClose={onClose} title="Create an account" icon={UserPlus}>
<Modal open={open} onClose={onClose} title={t("dlg.registerTitle")} icon={UserPlus}>
{key ? (
<div className="space-y-4">
<p className="text-sm opacity-80">
Welcome, <strong>@{username.trim().toLowerCase()}</strong>! Your access key — copy it now, it won't be shown again:
{t("dlg.regWelcome", { user: username.trim().toLowerCase() })}
</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">{key}</code>
<CopyButton text={key} />
</div>
<div className="flex justify-end">
<Button size="sm" onClick={() => { onDone(username.trim().toLowerCase(), key); onClose(); }}>Copy & continue to login</Button>
<Button size="sm" onClick={() => { onDone(username.trim().toLowerCase(), key); onClose(); }}>{t("dlg.regContinue")}</Button>
</div>
</div>
) : (
<form onSubmit={submit} className="space-y-4">
<Field label="Username">
<Field label={t("common.username")}>
<Input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="alice" maxLength={32} required />
</Field>
<Field label="Display name">
<Field label={t("common.displayName")}>
<Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="Alice" maxLength={60} />
</Field>
<Field label="Email (optional, for key recovery)">
<Field label={t("dlg.emailOpt")}>
<Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" />
</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} /> : "Register"}</Button>
<Button variant="secondary" size="sm" type="button" onClick={onClose}>{t("common.cancel")}</Button>
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : t("login.register")}</Button>
</div>
</form>
)}
@@ -289,6 +292,7 @@ export function RegisterDialog({
/* ---------- Share ---------- */
export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClose: () => void }) {
const { t } = useT();
const [url, setUrl] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
@@ -302,7 +306,7 @@ export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClo
setError("");
api.share(conv.id)
.then((r) => setUrl(window.location.origin + r.url))
.catch((err) => setError(err instanceof Error ? err.message : "Share failed"))
.catch((err) => setError(err instanceof Error ? err.message : t("dlg.reqFailed")))
.finally(() => setBusy(false));
}, [conv]);
@@ -313,20 +317,20 @@ export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClo
}
return (
<Modal open={conv !== null} onClose={onClose} title="Share publicly" icon={Globe}>
{busy && <p className="flex items-center gap-2 text-sm opacity-70"><Spinner size={15} /> Creating public link…</p>}
<Modal open={conv !== null} onClose={onClose} title={t("dlg.shareTitle")} icon={Globe}>
{busy && <p className="flex items-center gap-2 text-sm opacity-70"><Spinner size={15} /> {t("dlg.shareCreating")}</p>}
{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
{url && (
<div className="space-y-4">
<p className="text-sm opacity-70">Anyone with this link can read <strong>{conv?.title}</strong>. No login required.</p>
<p className="text-sm opacity-70">{t("dlg.shareIntro", { title: conv?.title ?? "" })}</p>
<div className="flex items-center gap-2 rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm dark:border-zinc-700 dark:bg-zinc-800">
<Link2 size={15} className="shrink-0 opacity-50" />
<span className="min-w-0 flex-1 truncate">{url}</span>
<CopyButton text={url} />
</div>
<div className="flex justify-between">
<Button variant="ghost" size="sm" onClick={unshare}><Unplug size={15} /> Unshare</Button>
<Button size="sm" onClick={onClose}>Done</Button>
<Button variant="ghost" size="sm" onClick={unshare}><Unplug size={15} /> {t("dlg.unshare")}</Button>
<Button size="sm" onClick={onClose}>{t("common.done")}</Button>
</div>
</div>
)}
@@ -347,6 +351,7 @@ export function SettingsModal({
onSaved: (u: User) => void;
onKeyRotated?: () => void;
}) {
const { t } = useT();
const [displayName, setDisplayName] = useState("");
const [avatarUrl, setAvatarUrl] = useState("");
const [email, setEmail] = useState("");
@@ -362,10 +367,10 @@ export function SettingsModal({
// Two-column settings: categories on the left, content on the right.
// Searching filters the category list and jumps to the first match.
const CATS = [
{ id: "profile", title: "Profile", icon: UserIcon, keywords: ["profile", "avatar", "picture", "photo", "name", "display", "email", "account"] },
{ id: "appearance", title: "Appearance", icon: Palette, keywords: ["appearance", "theme", "dark", "light", "color", "colour", "accent", "palette"] },
{ id: "features", title: "Features", icon: Sparkles, keywords: ["features", "thinking", "attachments", "search", "deep", "upload", "ocr", "capabilities", "enable", "disable"] },
{ id: "security", title: "Security", icon: ShieldCheck, keywords: ["security", "key", "rotate", "password", "totp", "2fa", "two", "factor", "authenticator", "passkey", "webauthn"] },
{ id: "profile", title: t("settings.profile"), icon: UserIcon, keywords: ["profile", "avatar", "picture", "photo", "name", "display", "email", "account"] },
{ id: "appearance", title: t("settings.appearance"), icon: Palette, keywords: ["appearance", "theme", "dark", "light", "color", "colour", "accent", "palette", "language", "langue", "idioma", "lingua", "язык"] },
{ id: "features", title: t("settings.features"), icon: Sparkles, keywords: ["features", "thinking", "attachments", "search", "deep", "upload", "ocr", "capabilities", "enable", "disable"] },
{ id: "security", title: t("settings.security"), icon: ShieldCheck, keywords: ["security", "key", "rotate", "password", "totp", "2fa", "two", "factor", "authenticator", "passkey", "webauthn"] },
] as const;
type CatId = (typeof CATS)[number]["id"];
const [cat, setCat] = useState<CatId>("profile");
@@ -392,11 +397,11 @@ export function SettingsModal({
async function uploadFile(f: File) {
if (!user) return;
if (f.size > 5 * 1024 * 1024) {
setUploadError("File too large (max 5MB).");
setUploadError(t("sec.avatarTooBig"));
return;
}
if (!/^image\/(jpeg|png|webp)$/.test(f.type)) {
setUploadError("Only jpg, png or webp images are accepted.");
setUploadError(t("sec.avatarType"));
return;
}
setUploading(true);
@@ -408,7 +413,7 @@ export function SettingsModal({
// preview (this modal, sidebar, chat bubbles) re-fetches immediately.
bumpCdnVersion();
} catch (err) {
setUploadError(err instanceof Error ? err.message : "Upload failed");
setUploadError(err instanceof Error ? err.message : t("attach.uploadFailed"));
} finally {
setUploading(false);
}
@@ -424,28 +429,28 @@ export function SettingsModal({
onSaved(res.user);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "Save failed");
setError(err instanceof Error ? err.message : t("common.saveFailed"));
} finally {
setBusy(false);
}
}
return (
<Modal open={user !== null} onClose={onClose} title="Settings" icon={Settings2} wide>
<Modal open={user !== null} onClose={onClose} title={t("settings.title")} icon={Settings2} wide>
<form onSubmit={save} className="space-y-4">
<div className="relative">
<Search size={15} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 opacity-50" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search settings…"
aria-label="Search settings"
placeholder={t("settings.searchPh")}
aria-label={t("settings.searchAria")}
className="w-full rounded-2xl border border-stone-200/70 bg-stone-100 py-2 pl-9 pr-8 text-sm outline-none transition placeholder:text-stone-400 focus:border-accent-500/60 focus:bg-white dark:border-zinc-800 dark:bg-zinc-800/60 dark:placeholder:text-zinc-500 dark:focus:bg-zinc-900"
/>
{search && (
<button
type="button"
aria-label="Clear settings search"
aria-label={t("settings.clearSearch")}
onClick={() => setSearch("")}
className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-60 transition hover:opacity-100"
>
@@ -486,11 +491,11 @@ export function SettingsModal({
</div>
</div>
<div>
<span className="mb-1.5 block text-sm font-medium opacity-80">Avatar upload</span>
<span className="mb-1.5 block text-sm font-medium opacity-80">{t("settings.avatarUpload")}</span>
<div
role="button"
tabIndex={0}
aria-label="Upload avatar"
aria-label={t("settings.avatarUpload")}
onClick={() => fileRef.current?.click()}
onKeyDown={(e) => e.key === "Enter" && fileRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
@@ -512,8 +517,8 @@ export function SettingsModal({
{uploading ? <Spinner size={17} /> : <ImagePlus size={17} />}
</span>
<span className="min-w-0 flex-1 text-sm">
<span className="block font-medium">{uploading ? "Uploading…" : dragOver ? "Drop it!" : "Drop an image or click to upload"}</span>
<span className="block text-xs opacity-60">jpg · png · webp — max 5MB — 5 changes per 2h</span>
<span className="block font-medium">{uploading ? t("settings.uploading") : dragOver ? t("settings.dropActive") : t("settings.dropIdle")}</span>
<span className="block text-xs opacity-60">{t("settings.avatarHint")}</span>
</span>
</div>
<input
@@ -529,10 +534,10 @@ export function SettingsModal({
/>
{uploadError && <p className="mt-1.5 text-sm text-red-600 dark:text-red-400">{uploadError}</p>}
</div>
<Field label="Display name">
<Field label={t("common.displayName")}>
<Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={60} required />
</Field>
<Field label="Recovery email" hint="Optional. Used only to send you a fresh access key if you lose it.">
<Field label={t("settings.email")} hint={t("settings.emailHint")}>
<Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" />
</Field>
</SettingsPane>
@@ -540,26 +545,29 @@ export function SettingsModal({
{activeCat === "appearance" && (
<SettingsPane>
<Field label="Theme">
<Field label={t("common.theme")}>
<Picker
ariaLabel="Theme"
ariaLabel={t("common.theme")}
value={theme}
onChange={setTheme}
align="left"
options={[
{ value: "auto", label: "Auto (follows system)" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
{ value: "auto", label: t("common.themeAutoFull") },
{ value: "light", label: t("common.light") },
{ value: "dark", label: t("common.dark") },
]}
/>
</Field>
<Field label={t("settings.language")} hint={t("settings.languageHint")}>
<LangPicker align="left" />
</Field>
<AccentSection />
</SettingsPane>
)}
{activeCat === "features" && (
<SettingsPane>
<p className="-mb-2 text-xs opacity-60">Turn composer capabilities on or off. Applied instantly, saved on this device.</p>
<p className="-mb-2 text-xs opacity-60">{t("settings.featHint")}</p>
<FeaturesSection />
</SettingsPane>
)}
@@ -573,13 +581,13 @@ export function SettingsModal({
</div>
{search.trim() && visibleCats.length === 0 && (
<p className="px-2 py-4 text-center text-sm opacity-50">No settings match “{search.trim()}”.</p>
<p className="px-2 py-4 text-center text-sm opacity-50">{t("settings.noMatch", { q: search.trim() })}</p>
)}
{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} /> : "Save"}</Button>
<Button variant="secondary" size="sm" type="button" onClick={onClose}>{t("common.cancel")}</Button>
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : t("common.save")}</Button>
</div>
</form>
</Modal>
@@ -601,6 +609,7 @@ function SettingsPane({ children }: { children: React.ReactNode }) {
/* ---------- Accent color (settings) ---------- */
function AccentSection() {
const { t } = useT();
const [state, setState] = useState<AccentState>(() => currentAccent());
function pick(presetId: string) {
@@ -617,13 +626,15 @@ function AccentSection() {
return (
<div>
<span className="mb-1.5 block text-sm font-medium opacity-80">{t("settings.accent")}</span>
<p className="mb-2 text-xs opacity-60">{t("settings.accentHint")}</p>
<div className="flex flex-wrap items-center gap-2">
{ACCENT_PRESETS.map((p) => (
<button
key={p.id}
type="button"
title={p.label}
aria-label={`Accent: ${p.label}`}
title={t(`accent.preset.${p.id}` as StringKey)}
aria-label={t("settings.accentAria", { label: t(`accent.preset.${p.id}` as StringKey) })}
onClick={() => pick(p.id)}
className={cn(
"h-8 w-8 rounded-full border-2 transition active:scale-90",
@@ -642,12 +653,12 @@ function AccentSection() {
: "border-transparent hover:scale-110",
)}
style={{ background: state.presetId === "custom" ? state.customHex : undefined }}
title="Custom color"
title={t("settings.customColor")}
>
<Sparkles size={14} className={cn("text-white drop-shadow-[0_1px_2px_rgba(0,0,0,0.6)]", state.presetId === "custom" && "opacity-0")} />
<input
type="color"
aria-label="Custom accent color"
aria-label={t("settings.customAria")}
value={state.presetId === "custom" ? state.customHex : "#10b981"}
onChange={(e) => pickCustom(e.target.value)}
onBlur={() => applyAccent(state)} // persist the last previewed value
@@ -662,6 +673,7 @@ function AccentSection() {
/* ---------- Features (settings) ---------- */
function FeaturesSection() {
const { t } = useT();
const flags = useFeatures();
return (
<div>
@@ -677,15 +689,15 @@ function FeaturesSection() {
<Toggle
checked={!!flags[f.key]}
disabled={!f.ready}
label={f.label}
label={t(`feat.${f.key}.label` as StringKey)}
onChange={(v) => setFeature(f.key, v)}
/>
<span className="min-w-0">
<span className="block text-sm font-medium">
{f.label}
{!f.ready && <span className="ml-1.5 text-xs opacity-60">(soon)</span>}
{t(`feat.${f.key}.label` as StringKey)}
{!f.ready && <span className="ml-1.5 text-xs opacity-60">{t("feat.soon")}</span>}
</span>
<span className="block text-xs opacity-60">{f.hint}</span>
<span className="block text-xs opacity-60">{t(`feat.${f.key}.hint` as StringKey)}</span>
</span>
</label>
))}
@@ -697,6 +709,7 @@ function FeaturesSection() {
/* ---------- Security (settings): key rotation, TOTP, passkeys ---------- */
function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
const { t } = useT();
const [totpOn, setTotpOn] = useState<boolean | null>(null);
const [secret, setSecret] = useState<string | null>(null);
const [otpauthUrl, setOtpauthUrl] = useState("");
@@ -723,7 +736,7 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
setRotatedKey(res.key);
setArmingRotate(false);
} catch (err) {
setError(err instanceof Error ? err.message : "Rotation failed");
setError(err instanceof Error ? err.message : t("sec.rotationFailed"));
} finally {
setBusy(false);
}
@@ -738,7 +751,7 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
setOtpauthUrl(res.otpauthUrl);
setCode("");
} catch (err) {
setError(err instanceof Error ? err.message : "Setup failed");
setError(err instanceof Error ? err.message : t("sec.setupFailed"));
} finally {
setBusy(false);
}
@@ -754,7 +767,7 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
setSecret(null);
setCode("");
} catch (err) {
setError(err instanceof Error ? err.message : "Invalid code");
setError(err instanceof Error ? err.message : t("login.totpInvalid"));
} finally {
setBusy(false);
}
@@ -769,7 +782,7 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
setTotpOn(false);
setCode("");
} catch (err) {
setError(err instanceof Error ? err.message : "Invalid code");
setError(err instanceof Error ? err.message : t("login.totpInvalid"));
} finally {
setBusy(false);
}
@@ -783,7 +796,7 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
setConfirmDelete(false);
onKeyRotated?.();
} catch (err) {
setError(err instanceof Error ? err.message : "Delete failed");
setError(err instanceof Error ? err.message : t("sec.deleteFailed"));
} finally {
setBusy(false);
}
@@ -792,25 +805,25 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
return (
<div className="space-y-5">
<div>
<p className="mb-1 flex items-center gap-1.5 text-sm font-medium"><KeyRound size={14} className="opacity-60" /> Access key</p>
<p className="mb-2 text-xs opacity-60">Rotate your access key. Old sessions are revoked immediately — you'll log back in with the new key.</p>
<p className="mb-1 flex items-center gap-1.5 text-sm font-medium"><KeyRound size={14} className="opacity-60" /> {t("sec.accessKey")}</p>
<p className="mb-2 text-xs opacity-60">{t("sec.accessKeyHint")}</p>
<Button size="sm" variant="secondary" disabled={busy} onClick={rotate}>
{armingRotate ? "Click again to confirm rotation" : "Rotate my access key"}
{armingRotate ? t("sec.rotateConfirm") : t("sec.rotate")}
</Button>
</div>
<div>
<p className="mb-1 flex items-center gap-1.5 text-sm font-medium"><ShieldCheck size={14} className="opacity-60" /> Two-factor (TOTP)</p>
{totpOn === null && <p className="flex items-center gap-2 text-sm opacity-60"><Spinner size={14} /> Checking…</p>}
<p className="mb-1 flex items-center gap-1.5 text-sm font-medium"><ShieldCheck size={14} className="opacity-60" /> {t("sec.totp")}</p>
{totpOn === null && <p className="flex items-center gap-2 text-sm opacity-60"><Spinner size={14} /> {t("sec.totpChecking")}</p>}
{totpOn === false && !secret && (
<>
<p className="mb-2 text-xs opacity-60">Add a 6-digit code from your authenticator app on top of your access key.</p>
<Button size="sm" variant="secondary" disabled={busy} onClick={startTotp}>Enable two-factor</Button>
<p className="mb-2 text-xs opacity-60">{t("sec.totpAddHint")}</p>
<Button size="sm" variant="secondary" disabled={busy} onClick={startTotp}>{t("sec.totpEnable")}</Button>
</>
)}
{secret && (
<div className="space-y-2 rounded-2xl border border-stone-200 p-3 dark:border-zinc-700">
<p className="text-xs opacity-70">Add this secret to your authenticator app (or open the otpauth link), then enter a code to confirm:</p>
<p className="text-xs opacity-70">{t("sec.totpSecretHint")}</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 break-all rounded-xl bg-stone-100 px-3 py-2 font-mono text-sm dark:bg-zinc-800">{secret}</code>
<CopyButton text={secret} />
@@ -821,30 +834,30 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
placeholder="000000"
aria-label="Authenticator code"
aria-label={t("login.totpAria")}
inputMode="numeric"
className="text-center tracking-[0.4em]"
/>
<Button size="sm" disabled={busy || code.length !== 6} onClick={confirmTotp}>Confirm</Button>
<Button size="sm" disabled={busy || code.length !== 6} onClick={confirmTotp}>{t("sec.totpConfirm")}</Button>
</div>
</div>
)}
{totpOn === true && (
<div className="flex flex-wrap items-end gap-2">
<div className="min-w-36 flex-1">
<Field label="Disable with a current code">
<Field label={t("sec.totpDisableLabel")}>
<Input
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
placeholder="000000"
aria-label="Current authenticator code"
aria-label={t("login.totpAria")}
inputMode="numeric"
className="text-center tracking-[0.4em]"
/>
</Field>
</div>
<Button size="sm" variant="secondary" disabled={busy || code.length !== 6} onClick={disableTotp} className="!text-red-600 dark:!text-red-400">
Disable 2FA
{t("sec.totpDisable")}
</Button>
</div>
)}
@@ -853,31 +866,31 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
<div className="flex items-center gap-3 rounded-2xl px-1 py-1 opacity-50">
<Fingerprint size={16} />
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">Passkeys <span className="ml-1 text-xs opacity-60">(soon)</span></span>
<span className="block text-xs opacity-60">WebAuthn / platform authenticators — needs a server RP setup.</span>
<span className="block text-sm font-medium">{t("sec.passkeys")} <span className="ml-1 text-xs opacity-60">{t("feat.soon")}</span></span>
<span className="block text-xs opacity-60">{t("sec.passkeysHint")}</span>
</span>
</div>
<div className="rounded-2xl border border-red-500/30 p-3">
<p className="mb-1 flex items-center gap-1.5 text-sm font-medium text-red-600 dark:text-red-400">
<Trash2 size={14} /> Danger zone
<Trash2 size={14} /> {t("sec.danger")}
</p>
<p className="mb-2 text-xs opacity-60">Permanently delete your account with all chats, shares and sessions. Cannot be undone.</p>
<p className="mb-2 text-xs opacity-60">{t("sec.dangerHint")}</p>
<Button size="sm" variant="secondary" disabled={busy} onClick={() => setConfirmDelete(true)} className="!text-red-600 dark:!text-red-400">
Delete my account
{t("sec.deleteMe")}
</Button>
</div>
{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
<Modal open={rotatedKey !== null} onClose={() => {}} title="New access key" icon={KeyRound}>
<Modal open={rotatedKey !== null} onClose={() => {}} title={t("sec.newKeyTitle")} icon={KeyRound}>
<div className="space-y-4">
<p className="text-sm opacity-80">Copy it now — it won't be shown again. Your old sessions are revoked.</p>
<p className="text-sm opacity-80">{t("sec.newKeyHint")}</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 font-mono text-sm dark:bg-zinc-800">{rotatedKey}</code>
{rotatedKey && <CopyButton text={rotatedKey} />}
</div>
<Button size="sm" className="w-full" onClick={() => onKeyRotated?.()}>Done — log me out</Button>
<Button size="sm" className="w-full" onClick={() => onKeyRotated?.()}>{t("sec.newKeyDone")}</Button>
</div>
</Modal>
@@ -885,9 +898,9 @@ function SecuritySection({ onKeyRotated }: { onKeyRotated?: () => void }) {
open={confirmDelete}
onClose={() => setConfirmDelete(false)}
onConfirm={removeAccount}
title="Delete your account?"
message="This permanently removes your account with all conversations, shares and sessions. This cannot be undone."
confirmLabel="Delete forever"
title={t("sec.deleteTitle")}
message={t("sec.deleteMsg")}
confirmLabel={t("sec.deleteForever")}
/>
</div>
);
+3 -1
View File
@@ -11,9 +11,10 @@ type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
size?: "sm" | "md" | "lg" | "icon";
};
export function Button({ variant = "primary", size = "md", className, ...props }: ButtonProps) {
export function Button({ variant = "primary", size = "md", type = "button", className, ...props }: ButtonProps) {
return (
<button
type={type}
className={cn(
"inline-flex items-center justify-center gap-2 rounded-full font-medium transition active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50",
size === "sm" && "px-3.5 py-1.5 text-sm",
@@ -566,6 +567,7 @@ export function CopyButton({ text, label }: { text: string; label?: string }) {
const [done, setDone] = useState(false);
return (
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(text).then(() => {
setDone(true);
+9 -1
View File
@@ -121,6 +121,13 @@ export const api = {
adminPatchSettings: (patch: { registrationEnabled?: boolean; accessRequestEnabled?: boolean; ocrEnabled?: boolean }) =>
req<{ settings: { registrationEnabled: boolean; accessRequestEnabled: boolean; ocrEnabled: boolean } }>("/api/admin/settings", { method: "PATCH", body: JSON.stringify(patch) }),
/** Admin: SMTP credentials viewer (password included, blur it by default) + connectivity. */
adminMailStatus: () =>
req<{ smtp: { enabled: boolean; host: string; port: number; secure: boolean; user: string; pass: string; hasPass: boolean; from: string; appUrl: string } }>("/api/admin/mail"),
adminMailVerify: () => req<{ ok: boolean }>("/api/admin/mail/verify", { method: "POST", body: JSON.stringify({}) }),
adminMailTest: (to: string) =>
req<{ ok: boolean; messageId: string }>("/api/admin/mail/test", { method: "POST", body: JSON.stringify({ to }) }),
convs: () => req<{ conversations: Conversation[] }>("/api/conversations"),
/** Search your old chats (titles, topics and message content). */
searchConvs: (q: string) =>
@@ -139,7 +146,8 @@ export const api = {
unshare: (id: string) => req<{ ok: boolean }>(`/api/conversations/${id}/share`, { method: "DELETE" }),
publicShare: (publicId: string) => req<SharedChat>(`/api/share/${publicId}`, {}, false),
models: () => req<{ models: DriverModel[] }>("/api/models"),
models: (opts: { refresh?: boolean } = {}) =>
req<{ models: DriverModel[] }>(`/api/models${opts.refresh ? "?refresh=1" : ""}`),
/** Access-request wishlist (public, no auth). */
accessRequest: (a: { username: string; email: string; message: string }) =>
+4 -19
View File
@@ -7,25 +7,10 @@ import { useSyncExternalStore } from "react";
*/
export type FeatureKey = "thinking" | "attachments" | "deepSearch";
export const FEATURES: { key: FeatureKey; label: string; hint: string; ready: boolean }[] = [
{
key: "thinking",
label: "Thinking",
hint: "Ask the model to reason step-by-step before answering.",
ready: true,
},
{
key: "attachments",
label: "Attachments",
hint: "Attach images (OCR transcription) and text files to messages.",
ready: true,
},
{
key: "deepSearch",
label: "Deep search",
hint: "Let the assistant search the web for fresh sources. Coming soon.",
ready: false,
},
export const FEATURES: { key: FeatureKey; ready: boolean }[] = [
{ key: "thinking", ready: true },
{ key: "attachments", ready: true },
{ key: "deepSearch", ready: false },
];
const STORAGE_KEY = "ka:features";
+325
View File
@@ -1201,6 +1201,114 @@ const ru: Dict = {
"app.deleteConvTitle": "Удалить разговор?",
"app.deleteConvMsg": "«{title}» и сообщения удалятся.",
"settings.language": "Язык",
"settings.languageHint": "Язык интерфейса. Сразу, на этом устройстве.",
"settings.security": "Безопасность",
"sec.accessKey": "Ключ доступа",
"sec.accessKeyHint":
"Смените ключ. Старые сессии отзовутся сразу — войдёте с новым.",
"sec.rotate": "Сменить мой ключ",
"sec.rotateConfirm": "Нажмите ещё раз для подтверждения",
"sec.rotationFailed": "Не сменилось",
"sec.totp": "Двухфакторка (TOTP)",
"sec.totpChecking": "Проверяем…",
"sec.totpAddHint":
"Добавьте 6-значный код из приложения поверх ключа.",
"sec.totpEnable": "Включить двухфакторку",
"sec.totpSecretHint":
"Добавьте секрет в приложение (или откройте otpauth-ссылку) и введите код:",
"sec.totpConfirm": "Подтвердить",
"sec.totpDisableLabel": "Отключить текущим кодом",
"sec.totpDisable": "Выключить 2FA",
"sec.setupFailed": "Не настроилось",
"sec.passkeys": "Пасскеи",
"sec.passkeysHint":
"WebAuthn / системные ключи — нужен RP на сервере.",
"sec.danger": "Опасная зона",
"sec.dangerHint":
"Навсегда удалит аккаунт с чатами, ссылками и сессиями. Без возврата.",
"sec.deleteMe": "Удалить мой аккаунт",
"sec.deleteFailed": "Не удалилось",
"sec.newKeyTitle": "Новый ключ доступа",
"sec.newKeyHint":
"Скопируйте сейчас — больше не покажем. Старые сессии отозваны.",
"sec.newKeyDone": "Готово — выйти",
"sec.deleteTitle": "Удалить ваш аккаунт?",
"sec.deleteMsg":
"Навсегда удалит аккаунт с разговорами, ссылками и сессиями. Без возврата.",
"sec.deleteForever": "Удалить навсегда",
"sec.avatarTooBig": "Файл слишком большой (макс. 5 МБ).",
"sec.avatarType": "Только картинки jpg, png или webp.",
"center.tabAccess": "Доступ",
"access.status.pending": "Ожидает",
"access.status.reviewing": "На проверке",
"access.status.accepted": "Принята",
"access.status.refused": "Отклонена",
"access.filter.all": "все",
"access.filter.pending": "ожидают",
"access.filter.reviewing": "на проверке",
"access.filter.accepted": "приняты",
"access.filter.refused": "отклонены",
"access.refresh": "Обновить",
"access.refreshAria": "Обновить заявки",
"access.empty": "Заявок нет. Лист ожидания пуст.",
"access.emptyFiltered": "С таким статусом ничего нет.",
"access.msgOne": "1 сообщение",
"access.msgMany": "{n} сообщений",
"access.accountCreated": "Аккаунт создан — ключ показан раз, копируйте:",
"access.replyPh": "Ответить (уйдёт по email)…",
"access.replyAria": "Ответить заявителю",
"access.reasonLabel": "Причина (уйдёт с решением)",
"access.reasonPh": "Необязательная причина…",
"access.btnReviewing": "На проверку",
"access.btnAccept": "Принять",
"access.btnRefuse": "Отклонить",
"access.closedNote": "Тикет закрыт ({status}).",
"access.reasonWord": "Причина",
"access.youAdmin": "Вы (админ)",
"access.sendFailed": "Не отправилось",
"access.updateFailed": "Не обновилось",
"review.title": "Заявка на доступ",
"review.loadingTicket": "Загружаем тикет…",
"review.notFound": "Тикет не найден",
"review.notFoundSub":
"Ссылка неизвестна. Проверьте URL из письма или подайте заявку со входа.",
"review.adminNote": "Заметка админа:",
"review.acceptedHint":
"Аккаунт создан — проверьте письмо с ключом и входите.",
"review.closedHint":
"Тикет закрыт. Письма не читаются — при нужде подайте новую заявку.",
"review.replyPh": "Изложите свой случай…",
"review.replyAria": "Ответить в тикет",
"review.mailHint":
"Письма — в одну сторону: отвечайте здесь, не по email.",
"review.status.pending": "Ждёт проверки",
"review.status.reviewing": "На проверке",
"review.status.accepted": "Принята",
"review.status.refused": "Отклонена",
"review.admin": "Админ",
"review.you": "Вы",
"review.requestTitle": "Запросить доступ",
"review.requestIntro":
"Займите имя и расскажите, зачем вам сюда. Админ разберёт каждую заявку — следите за тикетом и почтой.",
"review.emailHint": "Обязательно — статусы и ответы придут сюда.",
"review.whyLabel": "Почему вам дать доступ?",
"review.whyHint": "10+ символов. Это откроет тикет.",
"review.whyPh": "Я хочу…",
"review.sendRequest": "Отправить заявку",
"review.received": "Заявка получена",
"review.reserved":
"@{user} занято вами, пока админ проверяет. Письмо с тикетом уже летит.",
"review.copyLink": "Копировать ссылку",
"review.openTicket": "Открыть мой тикет",
"admin.editUserTitle": "Править @{user}",
"admin.avatarUrl": "URL аватара",
};
const it: Dict = {
@@ -1492,6 +1600,115 @@ const it: Dict = {
"app.deleteConvTitle": "Eliminare conversazione?",
"app.deleteConvMsg": "«{title}» e i suoi messaggi saranno eliminati.",
"settings.language": "Lingua",
"settings.languageHint":
"Lingua dell'interfaccia. Subito, su questo dispositivo.",
"settings.security": "Sicurezza",
"sec.accessKey": "Chiave di accesso",
"sec.accessKeyHint":
"Ruota la tua chiave. Le vecchie sessioni sono revocate subito — rientri con la nuova.",
"sec.rotate": "Ruota la mia chiave",
"sec.rotateConfirm": "Clicca di nuovo per confermare",
"sec.rotationFailed": "Rotazione fallita",
"sec.totp": "Doppio fattore (TOTP)",
"sec.totpChecking": "Verifica…",
"sec.totpAddHint":
"Aggiungi un codice a 6 cifre dall'app oltre alla chiave.",
"sec.totpEnable": "Attiva doppio fattore",
"sec.totpSecretHint":
"Aggiungi questo segreto all'app (o apri il link otpauth) e inserisci un codice:",
"sec.totpConfirm": "Conferma",
"sec.totpDisableLabel": "Disattiva con un codice attuale",
"sec.totpDisable": "Disattiva 2FA",
"sec.setupFailed": "Configurazione fallita",
"sec.passkeys": "Passkey",
"sec.passkeysHint":
"WebAuthn / autenticatori di sistema — serve RP sul server.",
"sec.danger": "Zona pericolosa",
"sec.dangerHint":
"Elimina account con chat, condivisioni e sessioni. Irreversibile.",
"sec.deleteMe": "Elimina il mio account",
"sec.deleteFailed": "Eliminazione fallita",
"sec.newKeyTitle": "Nuova chiave di accesso",
"sec.newKeyHint":
"Copiala ora — non sarà più mostrata. Le vecchie sessioni sono revocate.",
"sec.newKeyDone": "Fatto — esci",
"sec.deleteTitle": "Eliminare il tuo account?",
"sec.deleteMsg":
"Rimuove per sempre account con conversazioni, condivisioni e sessioni. Irreversibile.",
"sec.deleteForever": "Elimina per sempre",
"sec.avatarTooBig": "File troppo grande (max 5MB).",
"sec.avatarType": "Solo immagini jpg, png o webp.",
"center.tabAccess": "Accesso",
"access.status.pending": "In attesa",
"access.status.reviewing": "In revisione",
"access.status.accepted": "Accettata",
"access.status.refused": "Rifiutata",
"access.filter.all": "tutti",
"access.filter.pending": "in attesa",
"access.filter.reviewing": "in revisione",
"access.filter.accepted": "accettati",
"access.filter.refused": "rifiutati",
"access.refresh": "Aggiorna",
"access.refreshAria": "Aggiorna richieste",
"access.empty": "Nessuna richiesta. La lista è vuota.",
"access.emptyFiltered": "Nulla con questo stato.",
"access.msgOne": "1 messaggio",
"access.msgMany": "{n} messaggi",
"access.accountCreated": "Account creato — chiave unica, copiala ora:",
"access.replyPh": "Rispondi (arriva via email)…",
"access.replyAria": "Rispondi al richiedente",
"access.reasonLabel": "Motivo (inviato con la decisione)",
"access.reasonPh": "Motivo opzionale…",
"access.btnReviewing": "In revisione",
"access.btnAccept": "Accetta",
"access.btnRefuse": "Rifiuta",
"access.closedNote": "Ticket chiuso ({status}).",
"access.reasonWord": "Motivo",
"access.youAdmin": "Tu (admin)",
"access.sendFailed": "Invio fallito",
"access.updateFailed": "Aggiornamento fallito",
"review.title": "Richiesta di accesso",
"review.loadingTicket": "Carico ticket…",
"review.notFound": "Ticket non trovato",
"review.notFoundSub":
"Link sconosciuto. Controlla l'URL della tua email o richiedi accesso dal login.",
"review.adminNote": "Nota admin:",
"review.acceptedHint":
"Account creato — controlla l'email con la chiave e accedi.",
"review.closedHint":
"Ticket chiuso. Le email non si leggono — se serve, richiedi di nuovo.",
"review.replyPh": "Perora la tua causa…",
"review.replyAria": "Rispondi al tuo ticket",
"review.mailHint":
"Le email sono a senso unico — rispondi qui, non via email.",
"review.status.pending": "In attesa di revisione",
"review.status.reviewing": "In revisione",
"review.status.accepted": "Accettata",
"review.status.refused": "Rifiutata",
"review.admin": "Admin",
"review.you": "Tu",
"review.requestTitle": "Richiedi accesso",
"review.requestIntro":
"Riserva un nome e spiega perché vuoi entrare. Un admin valuta ogni richiesta — segui il filo sul tuo ticket e via email.",
"review.emailHint": "Obbligatoria — avvisi e risposte arrivano qui.",
"review.whyLabel": "Perché darti accesso?",
"review.whyHint": "10+ caratteri. Questo apre il tuo ticket.",
"review.whyPh": "Voglio…",
"review.sendRequest": "Invia richiesta",
"review.received": "Richiesta ricevuta",
"review.reserved":
"@{user} è riservato mentre un admin valuta. Un'email col tuo ticket è in viaggio.",
"review.copyLink": "Copia link",
"review.openTicket": "Apri il mio ticket",
"admin.editUserTitle": "Modifica @{user}",
"admin.avatarUrl": "URL avatar",
};
const pt: Dict = {
@@ -1775,6 +1992,114 @@ const pt: Dict = {
"app.deleteConvTitle": "Eliminar conversa?",
"app.deleteConvMsg": "«{title}» e mensagens serão eliminados.",
"settings.language": "Idioma",
"settings.languageHint": "Idioma da interface. Na hora, neste dispositivo.",
"settings.security": "Segurança",
"sec.accessKey": "Chave de acesso",
"sec.accessKeyHint":
"Roda a tua chave. Sessões antigas morrem na hora — entras com a nova.",
"sec.rotate": "Rodar a minha chave",
"sec.rotateConfirm": "Clica de novo para confirmar",
"sec.rotationFailed": "Falha ao rodar",
"sec.totp": "Dois fatores (TOTP)",
"sec.totpChecking": "A verificar…",
"sec.totpAddHint":
"Adiciona um código de 6 dígitos da app além da chave.",
"sec.totpEnable": "Ativar dois fatores",
"sec.totpSecretHint":
"Adiciona este segredo à app (ou abre o link otpauth) e escreve um código:",
"sec.totpConfirm": "Confirmar",
"sec.totpDisableLabel": "Desligar com um código atual",
"sec.totpDisable": "Desligar 2FA",
"sec.setupFailed": "Falha ao configurar",
"sec.passkeys": "Passkeys",
"sec.passkeysHint":
"WebAuthn / autenticadores do sistema — precisa RP no servidor.",
"sec.danger": "Zona perigosa",
"sec.dangerHint":
"Elimina a conta com chats, partilhas e sessões. Sem volta.",
"sec.deleteMe": "Eliminar a minha conta",
"sec.deleteFailed": "Falha ao eliminar",
"sec.newKeyTitle": "Nova chave de acesso",
"sec.newKeyHint":
"Copia agora — não será mostrada de novo. Sessões antigas morrem.",
"sec.newKeyDone": "Pronto — sair",
"sec.deleteTitle": "Eliminar a tua conta?",
"sec.deleteMsg":
"Remove para sempre a conta com conversas, partilhas e sessões. Sem volta.",
"sec.deleteForever": "Eliminar para sempre",
"sec.avatarTooBig": "Ficheiro muito grande (máx. 5MB).",
"sec.avatarType": "Só imagens jpg, png ou webp.",
"center.tabAccess": "Acesso",
"access.status.pending": "Pendente",
"access.status.reviewing": "Em revisão",
"access.status.accepted": "Aceite",
"access.status.refused": "Recusado",
"access.filter.all": "todos",
"access.filter.pending": "pendentes",
"access.filter.reviewing": "em revisão",
"access.filter.accepted": "aceites",
"access.filter.refused": "recusados",
"access.refresh": "Atualizar",
"access.refreshAria": "Atualizar pedidos",
"access.empty": "Sem pedidos. A lista está vazia.",
"access.emptyFiltered": "Nada com este estado.",
"access.msgOne": "1 mensagem",
"access.msgMany": "{n} mensagens",
"access.accountCreated": "Conta criada — chave única, copia agora:",
"access.replyPh": "Responder (chega por email)…",
"access.replyAria": "Responder ao requerente",
"access.reasonLabel": "Motivo (enviado com a decisão)",
"access.reasonPh": "Motivo opcional…",
"access.btnReviewing": "Em revisão",
"access.btnAccept": "Aceitar",
"access.btnRefuse": "Recusar",
"access.closedNote": "Ticket fechado ({status}).",
"access.reasonWord": "Motivo",
"access.youAdmin": "Tu (admin)",
"access.sendFailed": "Falha ao enviar",
"access.updateFailed": "Falha ao atualizar",
"review.title": "Pedido de acesso",
"review.loadingTicket": "A carregar ticket…",
"review.notFound": "Ticket não encontrado",
"review.notFoundSub":
"Link desconhecido. Vê o URL do teu email ou pede acesso no login.",
"review.adminNote": "Nota do admin:",
"review.acceptedHint":
"Conta criada — vê o email com a chave e entra.",
"review.closedHint":
"Ticket fechado. Emails não são lidos — se preciso, pede de novo.",
"review.replyPh": "Defende o teu caso…",
"review.replyAria": "Responder ao teu ticket",
"review.mailHint":
"Emails são de sentido único — responde aqui, não por email.",
"review.status.pending": "Pendente de revisão",
"review.status.reviewing": "Em revisão",
"review.status.accepted": "Aceite",
"review.status.refused": "Recusado",
"review.admin": "Admin",
"review.you": "Tu",
"review.requestTitle": "Pedir acesso",
"review.requestIntro":
"Reserva um nome e diz porque queres entrar. Um admin revê cada pedido — segues o fio no teu ticket e por email.",
"review.emailHint": "Obrigatório — avisos e respostas chegam aqui.",
"review.whyLabel": "Porque dar-te acesso?",
"review.whyHint": "10+ caracteres. Isto abre o teu ticket.",
"review.whyPh": "Quero…",
"review.sendRequest": "Enviar pedido",
"review.received": "Pedido recebido",
"review.reserved":
"@{user} fica reservado enquanto um admin revê. Um email com o teu ticket vai a caminho.",
"review.copyLink": "Copiar link",
"review.openTicket": "Abrir o meu ticket",
"admin.editUserTitle": "Editar @{user}",
"admin.avatarUrl": "URL do avatar",
};
const dicts: Record<LangId, Dict> = { en, es, fr, ru, it, pt };
+1
View File
@@ -50,6 +50,7 @@ export interface SharedChat {
topic: string;
model: string;
authorName: string;
authorAvatarUrl: string;
sharedAt: number;
messages: ChatMessage[];
}
+2 -1
View File
@@ -387,7 +387,7 @@ export function deleteShare(convId: string): void {
getDb().query("DELETE FROM shares WHERE conv_id = ?").run(convId);
}
export function getShareByPublic(publicId: string): { conv: ConversationRow; messages: MessageRow[]; authorName: string; sharedAt: number } | null {
export function getShareByPublic(publicId: string): { conv: ConversationRow; messages: MessageRow[]; authorName: string; authorAvatarUrl: string; sharedAt: number } | null {
const d = getDb();
const s = d.query("SELECT * FROM shares WHERE public_id = ?").get(publicId) as { conv_id: string; created_at: number } | null;
if (!s) return null;
@@ -398,6 +398,7 @@ export function getShareByPublic(publicId: string): { conv: ConversationRow; mes
conv,
messages: getMessages(conv.id).filter((m) => m.role !== "system"),
authorName: author?.display_name || "Someone",
authorAvatarUrl: author?.avatar_url || "",
sharedAt: s.created_at,
};
}
+38
View File
@@ -10,8 +10,16 @@ import type { DriverModel, LLMDriver } from "./types.ts";
*/
const PRIORITY = ["ollama", "mistral", "glm", "puppeteer-openai", "deepseek", "anthropic", "openai"];
/** How long the user-facing model list stays in memory before re-hitting upstream. */
export const MODEL_CACHE_TTL_MS = 60_000;
export class DriverRegistry {
private drivers: Map<string, LLMDriver>;
// In-memory model list cache: user requests are served from here so we
// don't hit Ollama (/api/tags) on every login. Refreshed at most once
// per MODEL_CACHE_TTL_MS; admins can force a refresh.
private modelsCache: { models: DriverModel[]; at: number } | null = null;
private modelsInflight: Promise<DriverModel[]> | null = null;
constructor() {
const all: LLMDriver[] = [
@@ -49,6 +57,36 @@ export class DriverRegistry {
return out;
}
/**
* Cached variant of listAllModels for user-facing requests.
* - Serves the in-memory list when fresher than MODEL_CACHE_TTL_MS.
* - Otherwise refetches upstream once (concurrent callers share the
* same in-flight promise instead of hammering Ollama).
* - `force=true` bypasses the cache (admin "Ollama models" view).
*/
async listAllModelsCached(force = false): Promise<DriverModel[]> {
const now = Date.now();
if (!force && this.modelsCache && now - this.modelsCache.at < MODEL_CACHE_TTL_MS) {
return this.modelsCache.models;
}
if (!force && this.modelsInflight) return this.modelsInflight;
const p = this.listAllModels().then((models) => {
this.modelsCache = { models, at: Date.now() };
return models;
}).finally(() => {
if (this.modelsInflight === p) this.modelsInflight = null;
});
// Only share the promise for non-forced loads; a forced admin refresh
// always goes upstream even if a user load is in flight.
if (!force) this.modelsInflight = p;
return p;
}
/** Drop the cached model list (e.g. after an admin pull/delete). */
invalidateModelsCache(): void {
this.modelsCache = null;
}
/**
* Split a fully-qualified "driver:model" id.
* "ollama:llama3.1:8b" -> driver "ollama", model "llama3.1:8b".
+53 -4
View File
@@ -69,7 +69,7 @@ import type { OllamaDriver } from "./drivers/ollama.ts";
import { DriverRegistry } from "./drivers/registry.ts";
import { createHash, randomBytes } from "node:crypto";
import { statSync } from "node:fs";
import { mailEnabled, sendAccessMessageEmail, sendAccessReceivedEmail, sendAccessStatusEmail, sendRecoveryEmail } from "./mail.ts";
import { mailEnabled, sendAccessMessageEmail, sendAccessReceivedEmail, sendAccessStatusEmail, sendRecoveryEmail, sendSmtpTestMail, smtpStatus, verifySmtp } from "./mail.ts";
import {
CDN_NAMESPACES,
cdnFile,
@@ -198,6 +198,7 @@ const server = Bun.serve({
topic: s.conv.topic,
model: s.conv.model,
authorName: s.authorName,
authorAvatarUrl: s.authorAvatarUrl,
sharedAt: s.sharedAt,
messages: s.messages.map((m) => ({ role: m.role, content: m.content })),
});
@@ -768,16 +769,21 @@ const server = Bun.serve({
// Passthrough of the NDJSON progress lines (status/digest/completed/total).
const dec = new TextDecoder();
let buf = "";
let pulledOk = true;
for await (const chunk of res.body) {
if (req.signal.aborted) break;
if (req.signal.aborted) { pulledOk = false; break; }
buf += dec.decode(chunk, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (line && !send(JSON.parse(line))) break;
if (line && !send(JSON.parse(line))) { pulledOk = false; break; }
}
if (!pulledOk) break;
}
// A new model landed on the Ollama host: drop the cached list
// so the next user request picks it up (subject to TTL).
if (pulledOk && !req.signal.aborted) registry.invalidateModelsCache();
send({ status: "done" });
} catch (e) {
if (!req.signal.aborted && !clientGone) send({ error: (e as Error).message });
@@ -812,6 +818,7 @@ const server = Bun.serve({
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return json({ error: `ollama /api/delete failed: ${res.status}` }, 502);
registry.invalidateModelsCache();
return json({ ok: true });
} catch (e) {
return json({ error: (e as Error).message }, 502);
@@ -869,6 +876,42 @@ const server = Bun.serve({
return json({ error: "not found" }, 404);
}
// --- admin: SMTP connectivity (viewer + tester) ---
if (path === "/api/admin/mail" && req.method === "GET") {
if (!admin) return json({ error: "forbidden" }, 403);
return json({ smtp: smtpStatus() });
}
if (path === "/api/admin/mail/verify" && req.method === "POST") {
if (!admin) return json({ error: "forbidden" }, 403);
try {
await verifySmtp();
return json({ ok: true });
} catch (e) {
return json({ error: (e as Error).message }, 502);
}
}
if (path === "/api/admin/mail/test" && req.method === "POST") {
if (!admin) return json({ error: "forbidden" }, 403);
const ip = clientIp(req, server);
if (isRateLimited(ip)) return json({ error: "too many attempts, try again later" }, 429);
const { ok, body } = await readJson(req);
const to = ok ? validEmail(body.to) : null;
if (!to) {
recordAttempt(ip);
return json({ error: "to: valid email address required" }, 400);
}
try {
const messageId = await sendSmtpTestMail(to);
clearAttempts(ip);
return json({ ok: true, messageId });
} catch (e) {
recordAttempt(ip);
return json({ error: (e as Error).message }, 502);
}
}
// --- conversations (server-persisted, per account) ---
if (path === "/api/conversations" && req.method === "GET") {
return json({ conversations: listConversations(user.id) });
@@ -967,7 +1010,13 @@ const server = Bun.serve({
}
if (path === "/api/models" && req.method === "GET") {
const models = await registry.listAllModels();
// User-facing list is served from an in-memory cache (TTL 60s) so
// every login doesn't hit Ollama. Admins pass ?refresh=1 to force
// a fresh upstream fetch (Ollama models view).
const wantRefresh = /^(1|true|yes)$/i.test(
url.searchParams.get("refresh") ?? url.searchParams.get("force") ?? "",
);
const models = await registry.listAllModelsCached(wantRefresh && admin);
return json({ models });
}
+68
View File
@@ -8,6 +8,74 @@ export function mailEnabled(): boolean {
return config.smtpHost.length > 0;
}
/** Sanitized snapshot for the Admin Center mail viewer (admin-only route). */
export function smtpStatus(): {
enabled: boolean;
host: string;
port: number;
secure: boolean;
user: string;
pass: string;
hasPass: boolean;
from: string;
appUrl: string;
} {
return {
enabled: mailEnabled(),
host: config.smtpHost,
port: config.smtpPort,
secure: config.smtpSecure,
user: config.smtpUser,
pass: config.smtpPass,
hasPass: config.smtpPass.length > 0,
from: config.smtpFrom,
appUrl: config.appUrl,
};
}
/** Verify SMTP connectivity (connect + auth, no mail sent). Throws on failure. */
export async function verifySmtp(): Promise<void> {
if (!mailEnabled()) throw new Error("SMTP_HOST not set — mail is disabled");
const mailer = await loadMailer();
if (!mailer) throw new Error("nodemailer not installed — run `bun install` for email support");
const t = mailer.createTransport({
host: config.smtpHost,
port: config.smtpPort,
secure: config.smtpSecure,
auth: config.smtpUser ? { user: config.smtpUser, pass: config.smtpPass } : undefined,
});
try {
await t.verify();
} finally {
t.close();
}
}
/** Send a connectivity test mail to `to`. Throws on failure, returns messageId. */
export async function sendSmtpTestMail(to: string): Promise<string> {
if (!mailEnabled()) throw new Error("SMTP_HOST not set — mail is disabled");
const mailer = await loadMailer();
if (!mailer) throw new Error("nodemailer not installed — run `bun install` for email support");
const t = mailer.createTransport({
host: config.smtpHost,
port: config.smtpPort,
secure: config.smtpSecure,
auth: config.smtpUser ? { user: config.smtpUser, pass: config.smtpPass } : undefined,
});
try {
const info = await t.sendMail({
from: config.smtpFrom,
to,
subject: "KisAssistant — SMTP test",
text: "This is a KisAssistant SMTP connectivity test. If you received it, outgoing mail works.",
html: `<p>This is a <strong>KisAssistant</strong> SMTP connectivity test. If you received it, outgoing mail works.</p>`,
});
return info.messageId ?? "";
} finally {
t.close();
}
}
// Lazy import: the backend boots (and serves) fine without node_modules
// installed; SMTP is only needed when actually sending.
async function loadMailer(): Promise<typeof import("nodemailer") | null> {