Compare commits

...
2 Commits
Author SHA1 Message Date
k c05aa7a211 update 2026-09-21 13:36:25 +02:00
k 59402b250c update 2026-09-21 13:05:25 +02:00
29 changed files with 1350 additions and 86 deletions
+6 -1
View File
@@ -43,12 +43,17 @@ RATE_LIMIT_MAX=5
RATE_LIMIT_WINDOW_MIN=10
# --- drivers ---
# Priority (global): ollama -> mistral -> puppeteer-openai(stub) -> deepseek -> anthropic -> openai
# Priority (global): ollama -> mistral -> glm -> puppeteer-openai(stub) -> deepseek -> anthropic -> openai
OLLAMA_HOST=http://10.66.66.4:11434
OLLAMA_ENABLED=true
# Stubs below: leave empty to keep disabled. Implemented last per spec.
MISTRAL_API_KEY=
MISTRAL_ENABLED=false
# GLM (Zhipu AI, OpenAI-compatible). Key from https://z.ai ; mainland China
# users point GLM_BASE_URL at https://open.bigmodel.cn/api/paas/v4 instead.
GLM_API_KEY=
GLM_ENABLED=false
# GLM_BASE_URL=https://api.z.ai/api/paas/v4
DEEPSEEK_API_KEY=
DEEPSEEK_ENABLED=false
ANTHROPIC_API_KEY=
+7 -4
View File
@@ -9,8 +9,8 @@ accounts, server-side chats and public shares. No cookies — Bearer keys in
Driver priority:
```
1. ollama → 2. mistral API → 3. puppeteer-openai (stub, not implemented)
→ 4. deepseek → 5. anthropic → 6. openai
1. ollama → 2. mistral API → 3. glm API → 4. puppeteer-openai (stub, not implemented)
→ 5. deepseek → 6. anthropic → 7. openai
```
Docs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) (backend, drivers, DB) ·
@@ -51,12 +51,14 @@ from the **Accounts** panel (each gets a one-time access key to hand over).
| Method | Route | Auth | Notes |
|---|---|---|---|
| POST | `/api/auth/login` | rate-limited (5/10min/IP) | `{username, key}` → `{token, expiresAt, user}` |
| POST | `/api/auth/register` | public, rate-limited | self-registration (403 when disabled by admin) → `{user, key}` |
| GET | `/api/auth/verify` | Bearer | → `{ok, user}` |
| POST | `/api/auth/logout` | Bearer | revokes token |
| GET/PATCH | `/api/me` | Bearer | profile: displayName, avatarUrl, theme |
| GET/POST | `/api/admin/users` | admin | create returns `{user, key}` (key shown once) |
| PATCH/DELETE | `/api/admin/users/:id` | admin | edit profile / delete + cascade |
| POST | `/api/admin/users/:id/regenerate` | admin | new key, old sessions revoked |
| GET/PATCH | `/api/admin/settings` | admin | feature flags: registrationEnabled, ocrEnabled |
| GET/POST | `/api/conversations` | Bearer | server-persisted chats (title, topic, model) |
| GET/PATCH/DELETE | `/api/conversations/:id` | owner | incl. messages on GET |
| POST/GET/DELETE | `/api/conversations/:id/share` | owner | public link `/share/:publicId` |
@@ -70,8 +72,9 @@ reply into that conversation (ownership enforced) and auto-titles new chats.
## Database (SQLite, Bun native)
`$DATA_DIR/kisassistant.db` (WAL mode). Tables: `users` (id, username,
display_name, avatar_url, theme, key_hash), `sessions` (hashed Bearer tokens),
`conversations` (id, user, title, topic, model), `messages`, `shares`
display_name, avatar_url, theme, email, key_hash), `sessions` (hashed Bearer tokens),
`conversations` (id, user, title, topic, model), `messages`, `shares`,
`resets` (recovery tokens), `settings` (feature flags)
(conv ↔ public id). No migration system — schema is created idempotently at boot.
## Drivers (backend layout)
+29
View File
@@ -0,0 +1,29 @@
---- HIGH PRIORITY
Loading screen with animation instead of just : "Loading..."
Like a flower that "loading" like circle animation, or beautiful disapearing/appearing animation
or even a beautiful flower in svgs that got built block by block
or something original but in the actual theme and Adapative to phone
--- Settings modal.
make a better settings overview,with larger modal in screen . with categories, section for searching
--- UPLOAD URL FOR PFP MUST BE A READ ONLY IN USER . NOW CAUSE OF THE OWN CDN. USER SHOULDNT SEE THAT VALUE /EDIT IT ANYMORe.
--- UPDATE ABOUT REGISTRATION
Another feature for rehistration.:
A WishList. Like you reserv username, mail (needed)
in AdminCenter, a specific category for wish access : accepting/refusing/review a request.
Can refusing with a reason / accepting with reason / reviewing :
- make a /review page
the user want to being granted access can arguing about why him
- admin can see messages, responding, like a minimal ticket syste,
and so accepting reusing.
- the user is who want to earn access receive emails about the current status of the situation
Refusing -with reasons etc
Accepting - with/without reasons etc
mail or reviewing
each new message in the conversations makes a new mail forwarded by (like real ticket)
precise that theses mail arent the official way and need to be responded into the official site (chat.kisakay.com/review)
makes beautiful simple easy - by design HTML for each type of mail
+6 -1
View File
@@ -46,6 +46,7 @@ Created idempotently at boot in `getDb()` (no migration framework; keep it so).
| `users` | `id, username UNIQUE, display_name, avatar_url, theme, email, key_hash, created_at`. The `admin` row is bootstrapped (its `key_hash` is unused — admin auth goes through `APP_PASSWORD`). |
| `sessions` | `token_hash PK, user_id, created_at, expires_at`. Bearer tokens, 256-bit, hashed with sha256. Expired rows are purged lazily on access. |
| `resets` | `token_hash PK, user_id, created_at, expires_at`. One-time key-recovery tokens (single use, consumed on POST). |
| `settings` | `key PK, value, updated_at`. Admin-controlled feature flags (`registration_enabled` default off, `tools_ocr_enabled` default on). |
| `conversations` | `id, user_id, title, topic, model, created_at, updated_at`. |
| `messages` | `id AUTOINCREMENT, conv_id → conversations ON DELETE CASCADE, role, content, created_at`. |
| `shares` | `conv_id PK → conversations ON DELETE CASCADE, public_id UNIQUE, created_at`. |
@@ -58,6 +59,10 @@ conversations → sessions → user) inside a transaction.
- `POST /api/auth/login { username, key }`, sliding-window rate limit per IP
(`RATE_LIMIT_MAX` / `RATE_LIMIT_WINDOW_MIN`, default 5 per 10 min) + 400 ms
delay on failure. Success clears the IP counter and issues a fresh token.
- `POST /api/auth/register { username, displayName?, email? }` — public
self-registration, guarded by the `registration_enabled` setting (403 when
off), same rate limit and validation as admin creation. Returns `{user, key}`
with the key shown once.
- `admin` is authenticated against `APP_PASSWORD` (timing-safe); users against
their `ka_…` access key (timing-safe against the stored hash).
- Keys are generated with `crypto.randomBytes` (`ka_` + 24 bytes base64url) and
@@ -93,7 +98,7 @@ only ever sees reviewed text blocks, never raw files.
## Drivers`src/drivers/`: `LLMDriver` interface (`listModels`, `chat`, `chatStream`),
`DriverRegistry` with global priority
`ollama → mistral → puppeteer-openai (stub) → deepseek → anthropic → openai`.
`ollama → mistral → glm → puppeteer-openai (stub) → deepseek → anthropic → openai`.
Models are addressed as `"driver:model"` (split on the first `:`).
- `OllamaDriver`: model discovery via `GET {OLLAMA_HOST}/api/tags`, chat via
+6 -1
View File
@@ -43,7 +43,12 @@ read-only `SharePage` (no auth), everything else renders the authenticated app.
copy, unshare), `SettingsModal` (display name, avatar upload box with
drag & drop, avatar URL, theme).
- `AdminPanel.tsx` — No-KYC account management: create (key shown once),
regenerate (revokes sessions), edit, delete with confirm.
regenerate (revokes sessions), edit, delete with confirm. Renders bare
(no modal shell) when embedded in the Admin Center page.
- `AdminCenter.tsx` — `/admin` route (admin gate + locked screen otherwise):
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.
- `Markdown.tsx` — `react-markdown` + GFM; code blocks get a language label and
a copy button.
+17 -1
View File
@@ -24,7 +24,8 @@ Copy `.env.example` to `.env`. Full list:
| `RESET_TTL_MIN` | `60` | reset-link lifetime (single use) |
| `RATE_LIMIT_MAX` / `RATE_LIMIT_WINDOW_MIN` | `5` / `10` | login rate limit per IP |
| `OLLAMA_HOST` / `OLLAMA_ENABLED` | `http://10.66.66.4:11434` / `true` | local-model driver |
| `MISTRAL_*`, `DEEPSEEK_*`, `ANTHROPIC_*`, `OPENAI_*` | disabled | API drivers: set `*_ENABLED=true` **and** `*_API_KEY` |
| `MISTRAL_*`, `GLM_*`, `DEEPSEEK_*`, `ANTHROPIC_*`, `OPENAI_*` | disabled | API drivers: set `*_ENABLED=true` **and** `*_API_KEY` |
| `GLM_BASE_URL` | `https://api.z.ai/api/paas/v4` | Zhipu platform override (mainland China: `https://open.bigmodel.cn/api/paas/v4`) |
## Local development
@@ -51,6 +52,21 @@ unshare. See `AGENTS.md`.
5. Rotate a compromised key with the regenerate button (old sessions die);
delete removes the account with all its chats and shares.
## Admin Center (`/admin`) & self-registration
The sidebar **Admin Center** button (admin only) opens the `/admin` page with
three tabs: **Accounts** (same manager as before, incl. the Ollama model
catalog), **Features** (server-side switches), **Mail** (SMTP status).
- `registration_enabled` (default off): when on, the login page shows a
working **Register** button — anyone can create an account (key shown once)
via `POST /api/auth/register`. When off, the button is greyed with the
tooltip *"Registration currently disabled on this platform"* and the
endpoint answers 403. Flipped live, no restart.
- `tools_ocr_enabled` (default on): admin kill-switch for the OCR tool.
- Flags live in the `settings` SQLite table, edited via
`GET/PATCH /api/admin/settings` (admin Bearer only).
## Key recovery via email (optional)
Set the `SMTP_*` vars (and the real public `APP_URL`) to enable it; otherwise
+14 -6
View File
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useState } from "react";
import { api, clearToken, getToken } from "./lib/api.ts";
import { featureEnabled, THINKING_SYSTEM_PROMPT } from "./lib/features.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, FilePreviewModal, SettingsModal, ShareModal } from "./components/dialogs.tsx";
import { AdminPanel } from "./components/AdminPanel.tsx";
import { AdminCenter } from "./components/AdminCenter.tsx";
import { SharePage } from "./components/SharePage.tsx";
import { ResetPage } from "./components/ResetPage.tsx";
import { ConfirmDialog } from "./components/ui.tsx";
@@ -18,6 +19,7 @@ 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;
const IS_ADMIN_PAGE = typeof window !== "undefined" && /^\/admin\/?$/.test(window.location.pathname);
function resetTokenFromPath(): string | null {
const m = window.location.pathname.match(/^\/reset\/([A-Za-z0-9_-]{6,80})\/?$/);
@@ -34,7 +36,7 @@ function applyTheme(theme: string) {
export function App() {
const [user, setUser] = useState<User | null>(null);
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !!getToken());
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !IS_ADMIN_PAGE && !!getToken());
const [models, setModels] = useState<DriverModel[]>([]);
const [model, setModel] = useState("");
const [convs, setConvs] = useState<Conversation[]>([]);
@@ -48,7 +50,6 @@ export function App() {
const [shareConv, setShareConv] = useState<Conversation | null>(null);
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);
@@ -56,6 +57,9 @@ export function App() {
const [ocrAvailable, setOcrAvailable] = useState(false);
// Public routes: no auth needed. IDs are constant for the page lifetime.
if (IS_ADMIN_PAGE) {
return <AdminCenter />;
}
if (RESET_TOKEN) {
return <ResetPage token={RESET_TOKEN} />;
}
@@ -175,7 +179,12 @@ export function App() {
setStreaming("");
let full = "";
try {
await api.chatStream({ model, messages: history, conversationId: convId! }, (t) => {
// "Thinking" feature flag: decorate the outgoing payload only — the
// system message is never shown nor persisted client-side.
const outMessages = featureEnabled("thinking")
? [{ role: "system", content: THINKING_SYSTEM_PROMPT } as ChatMessage, ...history]
: history;
await api.chatStream({ model, messages: outMessages, conversationId: convId! }, (t) => {
full += t;
setStreaming(full);
});
@@ -271,7 +280,7 @@ export function App() {
onShare={setShareConv}
onDelete={setDeleteConv}
onOpenSettings={() => { setSettingsOpen(true); setMobileNav(false); }}
onOpenAdmin={() => { setAdminOpen(true); setMobileNav(false); }}
onOpenAdmin={() => { window.location.href = "/admin"; }}
onLogout={logout}
mobileOpen={mobileNav}
onCloseMobile={() => setMobileNav(false)}
@@ -326,7 +335,6 @@ export function App() {
applyTheme(u.theme);
}}
/>
<AdminPanel open={adminOpen} onClose={() => setAdminOpen(false)} />
</div>
);
}
+168
View File
@@ -0,0 +1,168 @@
import { useEffect, useState } from "react";
import { ArrowLeft, LayoutDashboard, Mail, ShieldAlert, SlidersHorizontal, Users } from "lucide-react";
import { api } from "../lib/api.ts";
import { AdminPanel } from "./AdminPanel.tsx";
import { Logo, Spinner, Switch } from "./ui.tsx";
import { cn } from "../lib/cn.ts";
type Tab = "accounts" | "features" | "mail";
function applyTheme(theme: string) {
const root = document.documentElement;
const dark = theme === "dark" || (theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
root.classList.toggle("dark", dark);
root.style.colorScheme = dark ? "dark" : "light";
}
const TABS: { id: Tab; label: string; icon: typeof Users }[] = [
{ id: "accounts", label: "Accounts", icon: Users },
{ id: "features", label: "Features", icon: SlidersHorizontal },
{ id: "mail", label: "Mail", icon: Mail },
];
export function AdminCenter() {
const [allowed, setAllowed] = useState<boolean | null>(null);
const [tab, setTab] = useState<Tab>("accounts");
const [settings, setSettings] = useState<{ registrationEnabled: boolean; ocrEnabled: boolean } | null>(null);
const [mail, setMail] = useState<{ recovery: boolean; from?: string } | null>(null);
const [error, setError] = useState("");
const [saving, setSaving] = useState(false);
useEffect(() => {
api.verify()
.then((r) => {
if (!r.user.isAdmin) {
setAllowed(false);
return;
}
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));
}, []);
async function toggle(patch: { registrationEnabled?: boolean; ocrEnabled?: boolean }) {
setSaving(true);
setError("");
try {
const res = await api.adminPatchSettings(patch);
setSettings(res.settings);
} catch (e) {
setError(e instanceof Error ? e.message : "Save failed");
} finally {
setSaving(false);
}
}
if (allowed === null) {
return <div className="grid min-h-full place-items-center text-sm opacity-60"><Spinner /> Checking admin access…</div>;
}
if (!allowed) {
return (
<div className="grid min-h-full place-items-center p-6">
<div className="w-full max-w-sm rounded-[2rem] border border-stone-200 bg-white p-8 text-center shadow-xl dark:border-zinc-800 dark:bg-zinc-900">
<ShieldAlert size={28} className="mx-auto mb-3 text-red-500" />
<h1 className="text-lg font-bold">Admins only</h1>
<p className="mt-1 text-sm opacity-60">Log in with the admin account to open the Admin Center.</p>
<a href="/" className="mt-4 inline-block rounded-full bg-accent-600 px-5 py-2.5 text-sm font-medium text-white dark:bg-accent-500 dark:text-zinc-950">Back to login</a>
</div>
</div>
);
}
return (
<div className="min-h-full">
<header className="border-b border-stone-200/70 bg-white/70 backdrop-blur dark:border-zinc-800 dark:bg-zinc-900/70">
<div className="mx-auto flex w-full max-w-4xl items-center gap-3 px-4 py-3">
<a href="/" aria-label="Back to chat" className="rounded-full p-2 transition hover:bg-stone-200/60 dark:hover:bg-zinc-800">
<ArrowLeft size={18} />
</a>
<Logo size={32} className="rounded-xl" />
<h1 className="flex items-center gap-2 text-lg font-bold tracking-tight">
<LayoutDashboard size={18} className="text-accent-600 dark:text-accent-400" />
Admin Center
</h1>
</div>
<div className="mx-auto w-full max-w-4xl px-4 pb-3">
<div className="flex gap-1 overflow-x-auto rounded-full border border-stone-200/70 bg-stone-100/70 p-1 dark:border-zinc-800 dark:bg-zinc-900">
{TABS.map((t) => (
<button
key={t.id}
onClick={() => setTab(t.id)}
className={cn(
"flex flex-1 items-center justify-center gap-2 whitespace-nowrap rounded-full px-4 py-2 text-sm font-medium transition",
tab === t.id
? "bg-white text-stone-900 shadow dark:bg-zinc-800 dark:text-zinc-100"
: "opacity-60 hover:opacity-100",
)}
>
<t.icon size={15} />
{t.label}
</button>
))}
</div>
</div>
</header>
<main className="mx-auto w-full max-w-4xl space-y-4 px-4 py-6">
{error && <p className="rounded-2xl bg-red-500/10 px-4 py-2.5 text-sm text-red-600 dark:text-red-400" role="alert">{error}</p>}
{tab === "accounts" && (
<section className="rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<AdminPanel open bare onClose={() => {}} />
</section>
)}
{tab === "features" && (
<section className="space-y-3">
<div className="flex items-center gap-4 rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">Public registration</p>
<p className="text-sm opacity-60">Show the Register button on the login page. Off = admin-created accounts only.</p>
</div>
<Switch label="Public registration" checked={settings?.registrationEnabled ?? false} onChange={(v) => toggle({ registrationEnabled: v })} />
</div>
<div className="flex items-center gap-4 rounded-3xl border border-stone-200/70 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">OCR tool</p>
<p className="text-sm opacity-60">Server-side image transcription for attachments. Requires the tesseract binary.</p>
</div>
<Switch label="OCR tool" checked={settings?.ocrEnabled ?? false} onChange={(v) => toggle({ ocrEnabled: v })} />
</div>
{saving && <p className="flex items-center gap-2 text-sm opacity-60"><Spinner size={14} /> Saving…</p>}
{!settings && !error && <p className="flex items-center gap-2 text-sm opacity-60"><Spinner size={14} /> Loading…</p>}
</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>
)}
</main>
</div>
);
}
+197 -10
View File
@@ -1,10 +1,184 @@
import { useEffect, useState } from "react";
import { KeyRound, Pencil, RefreshCw, Trash2, UserPlus, Users } from "lucide-react";
import { useEffect, useState, type FC, type ReactNode } from "react";
import { Bot, Download, HardDrive, KeyRound, Pencil, RefreshCw, Trash2, UserPlus, Users } from "lucide-react";
import { api } from "../lib/api.ts";
import type { User } from "../lib/types.ts";
import type { DriverModel, User } from "../lib/types.ts";
import { Avatar, Button, ConfirmDialog, CopyButton, Field, Input, Modal, Picker, Spinner } from "./ui.tsx";
export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => void }) {
/** Curated Ollama library catalog (admin downloads only). */
const OLLAMA_CATALOG: { name: string; desc: string; sizes: string[] }[] = [
{ name: "llama3.2", desc: "Meta's compact everyday model", sizes: ["1b", "3b"] },
{ name: "llama3.1", desc: "Meta's general-purpose workhorse", sizes: ["8b", "70b"] },
{ name: "qwen2.5", desc: "Alibaba's multilingual all-rounder", sizes: ["0.5b", "1.5b", "7b", "14b", "32b"] },
{ name: "gemma2", desc: "Google's efficient open model", sizes: ["2b", "9b", "27b"] },
{ name: "mistral", desc: "Mistral 7B — fast and capable", sizes: ["7b"] },
{ name: "phi3", desc: "Microsoft's small research model", sizes: ["3.8b", "14b"] },
{ name: "deepseek-r1", desc: "Reasoning model (chain-of-thought)", sizes: ["1.5b", "7b", "8b", "14b", "32b"] },
{ name: "codellama", desc: "Code completion and chat", sizes: ["7b", "13b", "34b"] },
{ name: "llava", desc: "Vision model (image understanding)", sizes: ["7b", "13b", "34b"] },
{ name: "nomic-embed-text", desc: "Text embeddings", sizes: [] },
];
/* ---------- Ollama model catalog (admin) ---------- */
export function OllamaModelsModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const [installed, setInstalled] = useState<DriverModel[]>([]);
const [pullName, setPullName] = useState("");
const [pullStatus, setPullStatus] = useState("");
const [pullPct, setPullPct] = useState<number | null>(null);
const [pulling, setPulling] = useState(false);
const [error, setError] = useState("");
const [deleteModel, setDeleteModel] = useState<string | null>(null);
const [sizeOverrides, setSizeOverrides] = useState<Record<string, string>>({});
async function refreshInstalled() {
try {
const res = await api.models();
setInstalled(res.models.filter((m) => m.driver === "ollama"));
} catch { /* ignore */ }
}
useEffect(() => {
if (open) {
setError("");
setPullStatus("");
setPullPct(null);
setPulling(false);
refreshInstalled();
}
}, [open]);
async function pull(fullName: string) {
if (pulling || !fullName.trim()) return;
setPulling(true);
setError("");
setPullStatus("Contacting Ollama…");
setPullPct(null);
try {
await api.ollamaPull(fullName.trim(), (p) => {
if (p.error) { setError(p.error); return; }
setPullStatus(p.status || "Pulling…");
if (p.total && p.completed) setPullPct(Math.min(100, Math.round((p.completed / p.total) * 100)));
else setPullPct(null);
});
setPullStatus("Done");
setPullPct(100);
await refreshInstalled();
} catch (err) {
setError(err instanceof Error ? err.message : "Pull failed");
} finally {
setPulling(false);
}
}
async function removeModel(name: string) {
try {
await api.ollamaDelete(name);
await refreshInstalled();
} catch (err) {
setError(err instanceof Error ? err.message : "Delete failed");
}
}
return (
<>
<Modal open={open} onClose={pulling ? () => {} : onClose} title="Ollama models" icon={Bot}>
<p className="mb-4 text-sm opacity-70">
Download models from the Ollama library to your Ollama host, or remove local ones. Admin only.
</p>
{error && <p className="mb-3 rounded-2xl bg-red-50 px-4 py-2.5 text-sm text-red-600 dark:bg-red-950/40 dark:text-red-400" role="alert">{error}</p>}
{pulling && (
<div className="mb-4 rounded-2xl border border-accent-500/40 bg-accent-50 p-4 dark:bg-accent-950/30">
<p className="mb-2 flex items-center gap-2 text-sm font-medium">
<Download size={15} className="animate-bounce" />
Pulling {pullName}
</p>
<p className="mb-2 truncate text-xs opacity-70">{pullStatus}</p>
{pullPct !== null && (
<div className="h-2 overflow-hidden rounded-full bg-stone-200 dark:bg-zinc-800">
<div className="h-full rounded-full bg-accent-600 transition-all dark:bg-accent-500" style={{ width: `${pullPct}%` }} />
</div>
)}
</div>
)}
<div className="mb-4 flex flex-wrap items-end gap-2 rounded-2xl border border-stone-200 p-3 dark:border-zinc-700">
<div className="min-w-52 flex-1">
<Field label="Custom model tag" hint="e.g. llama3.2:3b, or a full library name">
<Input
value={pullName}
onChange={(e) => setPullName(e.target.value)}
placeholder="llama3.2:3b"
disabled={pulling}
onKeyDown={(e) => e.key === "Enter" && pull(pullName)}
/>
</Field>
</div>
<Button size="sm" onClick={() => pull(pullName)} disabled={pulling || !pullName.trim()}>
{pulling ? <Spinner size={15} /> : <Download size={15} />} Pull
</Button>
</div>
<p className="mb-2 flex items-center gap-1.5 text-sm font-medium"><HardDrive size={14} /> Installed ({installed.length})</p>
<ul className="mb-5 space-y-1.5">
{installed.length === 0 && <li className="text-sm opacity-50">No local Ollama models yet.</li>}
{installed.map((m) => (
<li key={m.id} className="flex items-center gap-3 rounded-2xl border border-stone-200/70 px-3.5 py-2 dark:border-zinc-800">
<span className="min-w-0 flex-1 truncate text-sm font-medium">{m.label || m.id}</span>
<button
title={`Delete ${m.label || m.id}`}
onClick={() => setDeleteModel(m.label || m.id)}
className="rounded-full p-2 text-red-600 transition hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40"
>
<Trash2 size={15} />
</button>
</li>
))}
</ul>
<p className="mb-2 flex items-center gap-1.5 text-sm font-medium"><Download size={14} /> Catalog</p>
<ul className="space-y-1.5">
{OLLAMA_CATALOG.map((m) => {
const size = sizeOverrides[m.name] ?? (m.sizes.length > 0 ? m.sizes[0]! : "");
const tag = size ? `${m.name}:${size}` : m.name;
return (
<li key={m.name} className="flex flex-wrap items-center gap-2 rounded-2xl border border-stone-200/70 px-3.5 py-2 dark:border-zinc-800">
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{m.name}</span>
<span className="block text-xs opacity-50">{m.desc}</span>
</span>
{m.sizes.length > 0 && (
<span className="w-24 shrink-0">
<Picker
ariaLabel={`${m.name} size`}
value={size}
onChange={(v) => setSizeOverrides((prev) => ({ ...prev, [m.name]: v }))}
align="right"
options={m.sizes.map((s) => ({ value: s, label: s }))}
/>
</span>
)}
<Button size="sm" variant="secondary" onClick={() => { setPullName(tag); pull(tag); }} disabled={pulling}>
<Download size={14} /> Pull
</Button>
</li>
);
})}
</ul>
</Modal>
<ConfirmDialog
open={deleteModel !== null}
onClose={() => setDeleteModel(null)}
title={`Delete ${deleteModel}?`}
message="The model is removed from the Ollama host. Pull it again anytime."
onConfirm={() => deleteModel && removeModel(deleteModel)}
/>
</>
);
}
export function AdminPanel({ open, onClose, bare }: { open: boolean; onClose: () => void; bare?: boolean }) {
const [users, setUsers] = useState<User[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
@@ -12,6 +186,7 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
const [freshKey, setFreshKey] = useState<{ username: string; key: string } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<User | null>(null);
const [editTarget, setEditTarget] = useState<User | null>(null);
const [modelsOpen, setModelsOpen] = useState(false);
// create form
const [username, setUsername] = useState("");
@@ -32,13 +207,13 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
}
useEffect(() => {
if (open) {
if (open || bare) {
refresh();
setShowCreate(false);
setFreshKey(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open ]);
}, [open, bare ]);
async function create(e: React.FormEvent) {
e.preventDefault();
@@ -75,16 +250,22 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
}
}
// Bare mode embeds the same manager in the /admin Center page instead
// of a modal — no logic duplicated.
const Shell: FC<{ children: ReactNode }> = bare
? ({ children }) => <div className="min-w-0 flex-1 space-y-1">{children}</div>
: ({ children }) => <Modal open={open} onClose={onClose} title="Accounts" icon={Users} wide>{children}</Modal>;
return (
<>
<Modal open={open} onClose={onClose} title="Accounts" icon={Users} wide>
<Shell>
<p className="mb-4 text-sm opacity-70">
No-KYC accounts: you create a username, hand the access key to its owner once. Keys are stored hashed — regenerate to rotate.
</p>
{error && <p className="mb-3 rounded-2xl bg-red-50 px-4 py-2.5 text-sm text-red-600 dark:bg-red-950/40 dark:text-red-400">{error}</p>}
{freshKey && (
<div className="mb-4 rounded-2xl border border-emerald-500/40 bg-emerald-50 p-4 dark:bg-emerald-950/30">
<div className="mb-4 rounded-2xl border border-accent-500/40 bg-accent-50 p-4 dark:bg-accent-950/30">
<p className="mb-2 flex items-center gap-2 text-sm font-medium"><KeyRound size={15} /> Key for @{freshKey.username} — shown once, copy it now:</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded-xl bg-white px-3 py-2 text-sm dark:bg-zinc-900">{freshKey.key}</code>
@@ -94,9 +275,14 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
)}
{!showCreate ? (
<Button variant="secondary" size="sm" onClick={() => setShowCreate(true)} className="mb-3">
<div className="mb-3 flex flex-wrap gap-2">
<Button variant="secondary" size="sm" onClick={() => setShowCreate(true)}>
<UserPlus size={15} /> New account
</Button>
<Button variant="secondary" size="sm" onClick={() => setModelsOpen(true)}>
<Bot size={15} /> Ollama models
</Button>
</div>
) : (
<form onSubmit={create} className="mb-4 flex flex-wrap items-end gap-2 rounded-2xl border border-stone-200 p-3 dark:border-zinc-700">
<div className="min-w-40 flex-1">
@@ -135,7 +321,7 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
))}
</ul>
)}
</Modal>
</Shell>
<ConfirmDialog
open={deleteTarget !== null}
@@ -146,6 +332,7 @@ export function AdminPanel({ open, onClose }: { open: boolean; onClose: () => vo
/>
<EditUserDialog user={editTarget} onClose={() => setEditTarget(null)} onSaved={refresh} />
<OllamaModelsModal open={modelsOpen} onClose={() => setModelsOpen(false)} />
</>
);
}
+10 -6
View File
@@ -4,6 +4,7 @@ import type { Attachment, ChatMessage, Conversation, DriverModel, User } from ".
import { Avatar, IconButton, LOGO_URL, Logo, Picker, type PickerGroup, Spinner } from "./ui.tsx";
import { Markdown } from "./Markdown.tsx";
import { cn } from "../lib/cn.ts";
import { useFeatures } from "../lib/features.ts";
function MessageBubble({ msg, authorAvatar, authorName }: { msg: ChatMessage; authorAvatar?: string; authorName: string }) {
const isUser = msg.role === "user";
@@ -16,7 +17,7 @@ function MessageBubble({ msg, authorAvatar, authorName }: { msg: ChatMessage; au
{isUser ? "You" : "KisAssistant"}
</div>
{isUser ? (
<div className="whitespace-pre-wrap rounded-3xl rounded-tr-lg bg-emerald-600 px-4 py-2.5 text-[15px] text-white dark:bg-emerald-500 dark:text-zinc-950">
<div className="whitespace-pre-wrap rounded-3xl rounded-tr-lg bg-accent-600 px-4 py-2.5 text-[15px] text-white dark:bg-accent-500 dark:text-zinc-950">
{msg.content}
</div>
) : (
@@ -70,6 +71,7 @@ export function Chat({
}) {
const [draft, setDraft] = useState("");
const [attachOpen, setAttachOpen] = useState(false);
const features = useFeatures();
const boxRef = useRef<HTMLDivElement>(null);
const taRef = useRef<HTMLTextAreaElement>(null);
const imgRef = useRef<HTMLInputElement>(null);
@@ -182,7 +184,7 @@ export function Chat({
{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">
<span key={a.id} className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-accent-600/30 bg-accent-600/10 py-1 pl-3 pr-1.5 text-xs font-medium dark:border-accent-500/30 dark:bg-accent-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">
@@ -203,7 +205,7 @@ export function Chat({
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">
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<ScanText size={16} />
</span>
<span>
@@ -215,7 +217,7 @@ export function Chat({
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">
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<FileText size={16} />
</span>
<span>
@@ -231,15 +233,17 @@ export function Chat({
)}
</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">
{features.attachments && (
<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"
className="grid h-10 w-10 shrink-0 -translate-y-[2px] 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
@@ -261,7 +265,7 @@ export function Chat({
type="submit"
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"
className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-accent-600 text-white shadow transition hover:bg-accent-500 active:scale-95 disabled:opacity-40 dark:bg-accent-500 dark:text-zinc-950 dark:hover:bg-accent-400"
>
<SendHorizontal size={17} />
</button>
+29 -5
View File
@@ -1,9 +1,9 @@
import { useEffect, useState } from "react";
import { ArrowRight, KeyRound, ShieldCheck, User, Zap } from "lucide-react";
import { ArrowRight, KeyRound, ShieldCheck, User, UserPlus, 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";
import { RecoverDialog, RegisterDialog } from "./dialogs.tsx";
const PERKS = [
{ icon: ShieldCheck, text: "Private by design — no cookies, no tracking" },
@@ -18,11 +18,14 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
const [recoverOpen, setRecoverOpen] = useState(false);
const [recoveryOn, setRecoveryOn] = useState(false);
const [recoveryFrom, setRecoveryFrom] = useState<string | undefined>(undefined);
const [registerOpen, setRegisterOpen] = useState(false);
const [registrationOn, setRegistrationOn] = useState(false);
useEffect(() => {
api.methods().then((m) => {
setRecoveryOn(m.recovery);
setRecoveryFrom(m.from);
setRegistrationOn(m.registration);
}).catch(() => {});
}, []);
@@ -43,9 +46,9 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
}
return (
<div className="grid min-h-full place-items-center overflow-y-auto 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="grid min-h-full place-items-center overflow-y-auto bg-gradient-to-br from-stone-100 via-stone-50 to-accent-100/60 p-6 dark:from-zinc-950 dark:via-zinc-950 dark:to-accent-950/40">
<div className="w-full max-w-sm">
<div className="rounded-[2rem] border border-white/60 bg-white/80 p-8 shadow-2xl shadow-emerald-900/5 backdrop-blur-xl dark:border-zinc-700/60 dark:bg-zinc-900/80">
<div className="rounded-[2rem] border border-white/60 bg-white/80 p-8 shadow-2xl shadow-accent-900/5 backdrop-blur-xl dark:border-zinc-700/60 dark:bg-zinc-900/80">
<div className="mb-2 flex flex-col items-center text-center">
<Logo size={68} className="mb-4 rounded-[1.5rem] shadow-lg shadow-red-900/20" />
<h1 className="text-2xl font-bold tracking-tight">Welcome back</h1>
@@ -89,6 +92,27 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
{busy ? <Spinner /> : (<>Unlock <ArrowRight size={17} /></>)}
</Button>
</form>
<div className="mt-4 flex items-center gap-3 text-xs opacity-40">
<span className="h-px flex-1 bg-current" />
New here?
<span className="h-px flex-1 bg-current" />
</div>
<Button
variant="secondary"
size="lg"
className="mt-3 w-full"
disabled={!registrationOn}
title={registrationOn ? "Create an account" : "Registration currently disabled on this platform"}
onClick={() => setRegisterOpen(true)}
>
<UserPlus size={16} />
Register
</Button>
<RegisterDialog
open={registerOpen}
onClose={() => setRegisterOpen(false)}
onDone={(u, k) => { setUsername(u); setKey(k); }}
/>
{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?
@@ -99,7 +123,7 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
<ul className="mt-6 space-y-2 border-t border-stone-200/70 pt-5 dark:border-zinc-800">
{PERKS.map((p) => (
<li key={p.text} className="flex items-center gap-2.5 text-[13px] opacity-70">
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<p.icon size={14} />
</span>
{p.text}
+2 -2
View File
@@ -32,7 +32,7 @@ export function ResetPage({ token }: { token: string }) {
}
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="grid min-h-full place-items-center bg-gradient-to-br from-stone-100 via-stone-50 to-accent-100/60 p-6 dark:from-zinc-950 dark:via-zinc-950 dark:to-accent-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>}
@@ -55,7 +55,7 @@ export function ResetPage({ token }: { token: string }) {
{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>
<h1 className="flex items-center justify-center gap-2 text-xl font-bold"><Sparkles size={18} className="text-accent-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>
+1 -1
View File
@@ -29,7 +29,7 @@ export function SharePage({ publicId }: { publicId: string }) {
</p>
)}
</div>
<a href="/" className="rounded-full bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-500 dark:bg-emerald-500 dark:text-zinc-950">
<a href="/" className="rounded-full bg-accent-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-accent-500 dark:bg-accent-500 dark:text-zinc-950">
Open KisAssistant
</a>
</div>
+5 -5
View File
@@ -1,5 +1,6 @@
import { useRef, useState } from "react";
import {
LayoutDashboard,
MessageSquarePlus,
MoreVertical,
PanelLeftClose,
@@ -8,7 +9,6 @@ import {
Share2,
Tag,
Trash2,
Users,
X,
} from "lucide-react";
import type { Conversation, User } from "../lib/types.ts";
@@ -150,7 +150,7 @@ export function Sidebar({
className={cn(
"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"
? "bg-accent-600/10 font-medium text-accent-900 dark:bg-accent-500/10 dark:text-accent-100"
: "hover:bg-stone-200/50 dark:hover:bg-zinc-800/70",
)}
>
@@ -199,9 +199,9 @@ export function Sidebar({
</button>
<div className="flex gap-1.5">
{user.isAdmin && (
<Button variant="secondary" size="sm" className="flex-1" onClick={onOpenAdmin} title="Manage accounts">
<Users size={15} />
Accounts
<Button variant="secondary" size="sm" className="flex-1" onClick={onOpenAdmin} title="Open the Admin Center">
<LayoutDashboard size={15} />
Admin Center
</Button>
)}
<Button variant="ghost" size="sm" className={user.isAdmin ? "" : "flex-1"} onClick={onLogout}>
+204 -7
View File
@@ -1,9 +1,11 @@
import { useEffect, useRef, useState } from "react";
import { Globe, FileText, ImagePlus, Link2, Mail, Pencil, ScanText, Settings2, Tag, Unplug } from "lucide-react";
import { Globe, FileText, ImagePlus, Link2, Mail, Palette, Pencil, ScanText, Settings2, Sparkles, Tag, Unplug, UserPlus } from "lucide-react";
import { api } from "../lib/api.ts";
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, Button, CopyButton, Field, Input, Modal, Picker, Spinner } from "./ui.tsx";
import { Avatar, bumpCdnVersion, Button, CopyButton, Field, Input, Modal, Picker, Spinner, Toggle } from "./ui.tsx";
/* ---------- Rename + topic ---------- */
@@ -173,7 +175,7 @@ export function FilePreviewModal({
</p>
) : (
<div className="space-y-3">
<p className="rounded-2xl bg-emerald-600/10 px-4 py-2.5 text-sm opacity-90">
<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.</>}
@@ -185,7 +187,7 @@ export function FilePreviewModal({
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"
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>
@@ -200,6 +202,90 @@ export function FilePreviewModal({
);
}
/* ---------- Self-registration ---------- */
export function RegisterDialog({
open,
onClose,
onDone,
}: {
open: boolean;
onClose: () => void;
onDone: (username: string, key: string) => void;
}) {
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [email, setEmail] = useState("");
const [key, setKey] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
if (open) {
setUsername("");
setDisplayName("");
setEmail("");
setKey(null);
setError("");
}
}, [open ]);
async function submit(e: React.FormEvent) {
e.preventDefault();
if (busy) return;
setBusy(true);
setError("");
try {
const res = await api.register({
username: username.trim().toLowerCase(),
displayName: displayName.trim() || undefined,
email: email.trim() || undefined,
});
setKey(res.key);
} catch (err) {
setError(err instanceof Error ? err.message : "Registration failed");
} finally {
setBusy(false);
}
}
return (
<Modal open={open} onClose={onClose} title="Create an account" 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:
</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>
</div>
</div>
) : (
<form onSubmit={submit} className="space-y-4">
<Field label="Username">
<Input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="alice" maxLength={32} required />
</Field>
<Field label="Display name">
<Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="Alice" maxLength={60} />
</Field>
<Field label="Email (optional, for key recovery)">
<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>
</div>
</form>
)}
</Modal>
);
}
/* ---------- Share ---------- */
export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClose: () => void }) {
@@ -296,6 +382,9 @@ export function SettingsModal({
try {
const res = await api.uploadAvatar(user.id, f);
setAvatarUrl(res.url); // applied when you press Save
// Same URL path every upload -> bump the CDN version so every <Avatar>
// preview (this modal, sidebar, chat bubbles) re-fetches immediately.
bumpCdnVersion();
} catch (err) {
setUploadError(err instanceof Error ? err.message : "Upload failed");
} finally {
@@ -348,11 +437,11 @@ export function SettingsModal({
className={cn(
"flex cursor-pointer items-center gap-3 rounded-3xl border-2 border-dashed px-4 py-3.5 transition",
dragOver
? "border-emerald-500 bg-emerald-500/10"
: "border-stone-200 hover:border-emerald-500/60 hover:bg-stone-50 dark:border-zinc-700 dark:hover:bg-zinc-800/60",
? "border-accent-500 bg-accent-500/10"
: "border-stone-200 hover:border-accent-500/60 hover:bg-stone-50 dark:border-zinc-700 dark:hover:bg-zinc-800/60",
)}
>
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
{uploading ? <Spinner size={17} /> : <ImagePlus size={17} />}
</span>
<span className="min-w-0 flex-1 text-sm">
@@ -395,6 +484,8 @@ export function SettingsModal({
]}
/>
</Field>
<AccentSection />
<FeaturesSection />
{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>
@@ -404,3 +495,109 @@ export function SettingsModal({
</Modal>
);
}
/* ---------- Accent color (settings) ---------- */
function AccentSection() {
const [state, setState] = useState<AccentState>(() => currentAccent());
function pick(presetId: string) {
const next = { ...state, presetId };
setState(next);
applyAccent(next);
}
function pickCustom(hex: string) {
const next = { presetId: "custom", customHex: hex };
setState(next);
previewAccent(hex);
}
return (
<div>
<span className="mb-1.5 flex items-center gap-1.5 text-sm font-medium opacity-80">
<Palette size={14} />
Accent color
</span>
<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}`}
onClick={() => pick(p.id)}
className={cn(
"h-8 w-8 rounded-full border-2 transition active:scale-90",
state.presetId === p.id
? "border-stone-900 dark:border-white"
: "border-transparent hover:scale-110",
)}
style={{ backgroundColor: p.base }}
/>
))}
<label
className={cn(
"relative grid h-8 w-8 cursor-pointer place-items-center overflow-hidden rounded-full border-2 transition active:scale-90",
state.presetId === "custom"
? "border-stone-900 dark:border-white"
: "border-transparent hover:scale-110",
)}
style={{ background: state.presetId === "custom" ? state.customHex : undefined }}
title="Custom color"
>
<Sparkles size={14} className={cn("mix-blend-difference text-white", state.presetId === "custom" && "opacity-0")} />
<input
type="color"
aria-label="Custom accent color"
value={state.presetId === "custom" ? state.customHex : "#10b981"}
onChange={(e) => pickCustom(e.target.value)}
onBlur={() => applyAccent(state)} // persist the last previewed value
className="absolute inset-0 cursor-pointer opacity-0"
/>
</label>
</div>
<p className="mt-1.5 text-xs opacity-60">Applied instantly, saved on this device.</p>
</div>
);
}
/* ---------- Features (settings) ---------- */
function FeaturesSection() {
const flags = useFeatures();
return (
<div>
<span className="mb-1.5 flex items-center gap-1.5 text-sm font-medium opacity-80">
<Sparkles size={14} />
Features
</span>
<div className="space-y-1">
{FEATURES.map((f) => (
<label
key={f.key}
className={cn(
"flex items-center gap-3 rounded-2xl px-3 py-2 transition",
f.ready ? "cursor-pointer hover:bg-stone-100 dark:hover:bg-zinc-800" : "opacity-50",
)}
>
<Toggle
checked={!!flags[f.key]}
disabled={!f.ready}
label={f.label}
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>}
</span>
<span className="block text-xs opacity-60">{f.hint}</span>
</span>
</label>
))}
</div>
<p className="mt-1.5 text-xs opacity-60">Applied instantly, saved on this device.</p>
</div>
);
}
+104 -13
View File
@@ -19,8 +19,8 @@ export function Button({ variant = "primary", size = "md", className, ...props }
size === "md" && "px-5 py-2.5 text-sm",
size === "lg" && "px-6 py-3 text-base",
size === "icon" && "h-9 w-9",
variant === "primary" && "bg-emerald-600 text-white shadow-sm hover:bg-emerald-500 dark:bg-emerald-500 dark:hover:bg-emerald-400 dark:text-zinc-950",
variant === "gradient" && "bg-gradient-to-r from-emerald-600 to-teal-500 text-white shadow-lg shadow-emerald-600/25 hover:from-emerald-500 hover:to-teal-400 dark:from-emerald-500 dark:to-teal-400 dark:text-zinc-950",
variant === "primary" && "bg-accent-600 text-white shadow-sm hover:bg-accent-500 dark:bg-accent-500 dark:hover:bg-accent-400 dark:text-zinc-950",
variant === "gradient" && "bg-gradient-to-r from-accent-600 to-teal-500 text-white shadow-lg shadow-accent-600/25 hover:from-accent-500 hover:to-teal-400 dark:from-accent-500 dark:to-teal-400 dark:text-zinc-950",
variant === "secondary" && "border border-stone-200 bg-white hover:bg-stone-50 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:bg-zinc-800",
variant === "ghost" && "hover:bg-stone-200/60 dark:hover:bg-zinc-800",
variant === "danger" && "bg-red-600 text-white hover:bg-red-500",
@@ -53,10 +53,10 @@ export function Input({ variant = "default", className, ...props }: React.InputH
className={cn(
"w-full text-sm outline-none transition placeholder:text-stone-400 dark:placeholder:text-zinc-500",
variant === "default" &&
"rounded-2xl border border-stone-200 bg-white px-4 py-2.5 focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 dark:border-zinc-700 dark:bg-zinc-900",
"rounded-2xl border border-stone-200 bg-white px-4 py-2.5 focus:border-accent-500 focus:ring-2 focus:ring-accent-500/20 dark:border-zinc-700 dark:bg-zinc-900",
// soft: onboarding-style pill field, blends into rounded cards
variant === "soft" &&
"rounded-full border border-transparent bg-stone-100 px-5 py-3 focus:border-emerald-500/60 focus:bg-white focus:ring-4 focus:ring-emerald-500/15 dark:bg-zinc-800/80 dark:focus:bg-zinc-900",
"rounded-full border border-transparent bg-stone-100 px-5 py-3 focus:border-accent-500/60 focus:bg-white focus:ring-4 focus:ring-accent-500/15 dark:bg-zinc-800/80 dark:focus:bg-zinc-900",
className,
)}
{...props}
@@ -170,12 +170,12 @@ export function Picker({
onClick={() => setOpen((o) => !o)}
className={cn(
"flex max-w-56 items-center gap-2 rounded-full border border-stone-200 bg-white py-2 pl-3.5 pr-3 text-sm font-medium shadow-sm transition",
"hover:border-emerald-500/60 hover:shadow disabled:cursor-not-allowed disabled:opacity-50",
"hover:border-accent-500/60 hover:shadow disabled:cursor-not-allowed disabled:opacity-50",
"dark:border-zinc-700 dark:bg-zinc-900",
open && "border-emerald-500 ring-2 ring-emerald-500/20",
open && "border-accent-500 ring-2 ring-accent-500/20",
)}
>
{Icon && <Icon size={15} className="shrink-0 text-emerald-600 dark:text-emerald-400" />}
{Icon && <Icon size={15} className="shrink-0 text-accent-600 dark:text-accent-400" />}
<span className="truncate">{selected?.label ?? placeholder}</span>
<ChevronDown size={15} className={cn("shrink-0 opacity-50 transition-transform", open && "rotate-180")} />
</button>
@@ -208,7 +208,7 @@ export function Picker({
className={cn(
"flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm transition",
active
? "bg-emerald-600/10 font-medium text-emerald-900 dark:bg-emerald-500/10 dark:text-emerald-100"
? "bg-accent-600/10 font-medium text-accent-900 dark:bg-accent-500/10 dark:text-accent-100"
: "hover:bg-stone-100 dark:hover:bg-zinc-800",
)}
>
@@ -216,7 +216,7 @@ export function Picker({
<span className="block truncate">{o.label}</span>
{o.hint && <span className="block truncate text-xs opacity-50">{o.hint}</span>}
</span>
{active && <Check size={15} className="shrink-0 text-emerald-600 dark:text-emerald-400" />}
{active && <Check size={15} className="shrink-0 text-accent-600 dark:text-accent-400" />}
</button>
);
})}
@@ -297,7 +297,7 @@ export function Modal({
</div>
<div className="mb-4 flex items-center gap-2.5">
{Icon && (
<span className="grid h-9 w-9 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
<span className="grid h-9 w-9 place-items-center rounded-full bg-accent-600/10 text-accent-600 dark:text-accent-400">
<Icon size={18} />
</span>
)}
@@ -401,8 +401,36 @@ export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; it
/* ---------- Avatar ---------- */
// Uploaded avatars reuse the same /cdn/avatar/<userId> path, so the <img> URL
// never changes and browsers keep serving the stale cached file. A global
// version counter (bumped after each successful upload) cache-busts every
// /cdn/ URL rendered by <Avatar>, refreshing previews app-wide instantly.
let cdnVersion = 0;
const cdnVersionListeners = new Set<() => void>();
/** Call after a successful CDN upload so every <Avatar> re-fetches the file. */
export function bumpCdnVersion(): void {
cdnVersion++;
cdnVersionListeners.forEach((l) => l());
}
function useCdnVersion(): number {
const [v, setV] = useState(cdnVersion);
useEffect(() => {
const l = () => setV(cdnVersion);
cdnVersionListeners.add(l);
return () => { cdnVersionListeners.delete(l); };
}, []);
return v;
}
function withCdnVersion(url: string, v: number): string {
if (!url.startsWith("/cdn/")) return url;
return `${url}${url.includes("?") ? "&" : "?"}v=${v}`;
}
const GRADIENTS = [
"from-emerald-500 to-teal-600",
"from-accent-500 to-teal-600",
"from-violet-500 to-purple-600",
"from-amber-500 to-orange-600",
"from-sky-500 to-cyan-600",
@@ -410,8 +438,9 @@ const GRADIENTS = [
];
export function Avatar({ name, url, size = 36 }: { name: string; url?: string; size?: number }) {
const cdnV = useCdnVersion();
if (url) {
return <img src={url} alt={name} width={size} height={size} className="rounded-full object-cover" style={{ width: size, height: size }} />;
return <img src={withCdnVersion(url, cdnV)} alt={name} width={size} height={size} className="rounded-full object-cover" style={{ width: size, height: size }} />;
}
const initial = (name.trim()[0] || "?").toUpperCase();
const g = GRADIENTS[(name.charCodeAt(0) || 0) % GRADIENTS.length];
@@ -443,12 +472,74 @@ export function Logo({ size = 36, className }: { size?: number; className?: stri
);
}
/* ---------- Switch (feature toggle) ---------- */
export function Switch({ checked, onChange, label }: { checked: boolean; onChange: (v: boolean) => void; label: string }) {
return (
<button
type="button"
role="switch"
aria-checked={checked}
aria-label={label}
onClick={() => onChange(!checked)}
className={cn(
"relative h-6 w-11 shrink-0 rounded-full transition",
checked ? "bg-emerald-600 dark:bg-emerald-500" : "bg-stone-300 dark:bg-zinc-700",
)}
>
<span
className={cn(
"absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-all",
checked ? "left-[1.375rem]" : "left-0.5",
)}
/>
</button>
);
}
/* ---------- Misc ---------- */
export function Spinner({ size = 18 }: { size?: number }) {
return <Loader2 size={size} className="animate-spin" />;
}
/** Accessible on/off switch (emerald→accent colored when on). */
export function Toggle({
checked,
onChange,
label,
disabled = false,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label: string;
disabled?: boolean;
}) {
return (
<button
type="button"
role="switch"
aria-checked={checked}
aria-label={label}
disabled={disabled}
onClick={() => onChange(!checked)}
className={cn(
"relative h-6 w-11 shrink-0 rounded-full border transition disabled:opacity-40",
checked
? "border-transparent bg-accent-600 dark:bg-accent-500"
: "border-stone-300 bg-stone-200 dark:border-zinc-600 dark:bg-zinc-700",
)}
>
<span
className={cn(
"absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-all dark:bg-zinc-100",
checked ? "left-[1.4rem]" : "left-0.5",
)}
/>
</button>
);
}
export function CopyButton({ text, label = "Copy" }: { text: string; label?: string }) {
const [done, setDone] = useState(false);
return (
@@ -461,7 +552,7 @@ export function CopyButton({ text, label = "Copy" }: { text: string; label?: str
}}
className="inline-flex items-center gap-1.5 rounded-full border border-stone-200 bg-white px-3 py-1.5 text-xs font-medium transition hover:bg-stone-50 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:bg-zinc-800"
>
{done ? <Check size={13} className="text-emerald-500" /> : <Copy size={13} />}
{done ? <Check size={13} className="text-accent-500" /> : <Copy size={13} />}
{done ? "Copied" : label}
</button>
);
+17 -2
View File
@@ -2,6 +2,21 @@
@tailwind components;
@tailwind utilities;
/* Accent palette defaults (emerald). Overridden at runtime by lib/accent.ts
from the user's saved accent color / custom pick. Values are RGB triplets. */
:root {
--ka-accent-50: 236 253 245;
--ka-accent-100: 209 250 229;
--ka-accent-200: 167 243 208;
--ka-accent-300: 110 231 183;
--ka-accent-400: 52 211 153;
--ka-accent-500: 16 185 129;
--ka-accent-600: 5 150 105;
--ka-accent-700: 4 120 87;
--ka-accent-800: 6 95 70;
--ka-accent-900: 6 78 59;
}
html, body, #root {
height: 100%;
}
@@ -59,12 +74,12 @@ body {
@apply bg-stone-200/50 dark:bg-zinc-800;
}
.md a {
@apply text-emerald-600 underline dark:text-emerald-400;
@apply text-accent-600 underline dark:text-accent-400;
}
.md ul { @apply list-disc pl-5; }
.md ol { @apply list-decimal pl-5; }
.md blockquote {
@apply border-l-4 border-emerald-500/50 pl-3 italic opacity-80;
@apply border-l-4 border-accent-500/50 pl-3 italic opacity-80;
}
.typing-cursor::after {
+117
View File
@@ -0,0 +1,117 @@
/**
* Runtime accent color (settings → accent color). Predefined palettes plus a
* custom picker; shades 50–900 are derived from a single base hex via HSL and
* written to the --ka-accent-* CSS variables that back Tailwind's `accent`
* palette. Persisted per-browser (localStorage), like the feature flags.
*/
export type AccentShades = Record<"50" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900", string>;
export interface AccentPreset {
id: string;
label: string;
base: string; // hex, used as the 500 shade and to derive the ramp
}
export const ACCENT_PRESETS: AccentPreset[] = [
{ id: "emerald", label: "Emerald", base: "#10b981" },
{ id: "rose", label: "Rose", base: "#f43f5e" },
{ id: "blue", label: "Blue", base: "#3b82f6" },
{ id: "violet", label: "Violet", base: "#8b5cf6" },
{ id: "amber", label: "Yellow", base: "#f59e0b" },
{ id: "orange", label: "Orange", base: "#f97316" },
{ id: "teal", label: "Teal", base: "#14b8a6" },
{ id: "pink", label: "Pink", base: "#ec4899" },
];
const STORAGE_KEY = "ka:accent";
const SHADE_KEYS = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"] as const;
// Lightness ramps for 50→900 around a mid 500 (HSL L values in %).
const RAMP: Record<(typeof SHADE_KEYS)[number], number> = {
"50": 97, "100": 93, "200": 86, "300": 76, "400": 64,
"500": 52, "600": 45, "700": 38, "800": 30, "900": 24,
};
function hexToHsl(hex: string): { h: number; s: number; l: number } {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
if (!m) return { h: 160, s: 84, l: 52 }; // emerald fallback
const n = parseInt(m[1]!, 16);
const r = ((n >> 16) & 255) / 255, g = ((n >> 8) & 255) / 255, b = (n & 255) / 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h = 0, s = 0;
const l = (max + min) / 2;
if (max !== min) {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) * 60;
else if (max === g) h = ((b - r) / d + 2) * 60;
else h = ((r - g) / d + 4) * 60;
}
return { h, s: s * 100, l: l * 100 };
}
function hslToRgbTriplet(h: number, s: number, l: number): string {
const sn = s / 100, ln = l / 100;
const c = (1 - Math.abs(2 * ln - 1)) * sn;
const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
const m = ln - c / 2;
let r = 0, g = 0, b = 0;
if (h < 60) [r, g, b] = [c, x, 0];
else if (h < 120) [r, g, b] = [x, c, 0];
else if (h < 180) [r, g, b] = [0, c, x];
else if (h < 240) [r, g, b] = [0, x, c];
else if (h < 300) [r, g, b] = [x, 0, c];
else [r, g, b] = [c, 0, x];
const to = (v: number) => Math.round((v + m) * 255);
return `${to(r)} ${to(g)} ${to(b)}`;
}
/** Build the 50–900 ramp from a base hex (HSL ramp, emerald-style). */
export function shadesFor(baseHex: string): AccentShades {
const { h, s } = hexToHsl(baseHex);
const out = {} as AccentShades;
for (const k of SHADE_KEYS) {
// Keep saturation lively at the light end, richer at the dark end.
const sat = k === "50" || k === "100" ? s * 0.9 : s;
out[k] = hslToRgbTriplet(h, sat, RAMP[k]);
}
return out;
}
export interface AccentState {
/** preset id, or "custom" */
presetId: string;
/** hex for custom (ignored for presets — they derive from their base) */
customHex: string;
}
export function currentAccent(): AccentState {
try {
const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as AccentState | null;
if (raw && typeof raw.presetId === "string") return raw;
} catch { /* ignore */ }
return { presetId: "emerald", customHex: "#10b981" };
}
export function applyAccent(state: AccentState): void {
const preset = ACCENT_PRESETS.find((p) => p.id === state.presetId);
const base = preset ? preset.base : (/^#?[0-9a-f]{6}$/i.test(state.customHex) ? state.customHex : "#10b981");
const shades = shadesFor(base);
const root = document.documentElement;
for (const k of SHADE_KEYS) root.style.setProperty(`--ka-accent-${k}`, shades[k]);
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch { /* ignore */ }
}
/** Preview without persisting (used while the picker is open). */
export function previewAccent(baseHex: string): void {
const shades = shadesFor(baseHex);
const root = document.documentElement;
for (const k of SHADE_KEYS) root.style.setProperty(`--ka-accent-${k}`, shades[k]);
}
// Restore the saved accent on load.
if (typeof document !== "undefined") {
applyAccent(currentAccent());
}
+45 -1
View File
@@ -46,7 +46,9 @@ 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),
methods: () => req<{ recovery: boolean; from?: string; registration: boolean }>("/api/auth/methods", {}, false),
register: (u: { username: string; displayName?: string; email?: string }) =>
req<{ user: User; key: string }>("/api/auth/register", { method: "POST", body: JSON.stringify(u) }, 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),
@@ -64,6 +66,10 @@ export const api = {
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) }),
adminGetSettings: () => req<{ settings: { registrationEnabled: boolean; ocrEnabled: boolean } }>("/api/admin/settings"),
adminPatchSettings: (patch: { registrationEnabled?: boolean; ocrEnabled?: boolean }) =>
req<{ settings: { registrationEnabled: boolean; ocrEnabled: boolean } }>("/api/admin/settings", { method: "PATCH", body: JSON.stringify(patch) }),
convs: () => req<{ conversations: Conversation[] }>("/api/conversations"),
createConv: (c: { title?: string; topic?: string; model?: string }) =>
req<{ conversation: Conversation }>("/api/conversations", { method: "POST", body: JSON.stringify(c) }),
@@ -79,6 +85,44 @@ export const api = {
models: () => req<{ models: DriverModel[] }>("/api/models"),
/** Admin: stream an Ollama /api/pull as NDJSON progress events. */
ollamaPull: async (
name: string,
onProgress: (p: { status?: string; digest?: string; total?: number; completed?: number; error?: string }) => void,
): Promise<void> => {
const res = await fetch("/api/admin/ollama/pull", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}` },
body: JSON.stringify({ name }),
});
if (res.status === 401) {
clearToken();
window.location.reload();
throw new ApiError(401, "Session expired.");
}
if (!res.ok || !res.body) {
const err = (await res.json().catch(() => ({}))) as { error?: string };
throw new ApiError(res.status, err.error || `Pull failed (${res.status})`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop() ?? "";
for (const line of lines) {
const t = line.trim();
if (t) onProgress(JSON.parse(t));
}
}
},
/** Admin: delete a local Ollama model (frees disk on the Ollama host). */
ollamaDelete: (name: string) => req<{ ok: boolean }>(`/api/admin/ollama/models/${encodeURIComponent(name)}`, { method: "DELETE" }),
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). */
+80
View File
@@ -0,0 +1,80 @@
import { useSyncExternalStore } from "react";
/**
* Per-browser feature flags (localStorage). Gate optional composer
* capabilities; kept client-side on purpose — they only change what the
* UI offers / what prompt decorations are sent, never auth or data access.
*/
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,
},
];
const STORAGE_KEY = "ka:features";
const DEFAULTS: Record<FeatureKey, boolean> = {
thinking: false,
attachments: true,
deepSearch: false,
};
function load(): Record<FeatureKey, boolean> {
try {
const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}") as Partial<Record<FeatureKey, boolean>>;
return { ...DEFAULTS, ...raw };
} catch {
return { ...DEFAULTS };
}
}
let flags = load();
const listeners = new Set<() => void>();
function persist() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(flags));
} catch {
// private mode etc. — flags just won't survive a reload
}
listeners.forEach((l) => l());
}
export function featureEnabled(key: FeatureKey): boolean {
return flags[key];
}
export function setFeature(key: FeatureKey, value: boolean) {
flags = { ...flags, [key]: value };
persist();
}
export function useFeatures(): Record<FeatureKey, boolean> {
return useSyncExternalStore(
(cb) => {
listeners.add(cb);
return () => { listeners.delete(cb); };
},
() => flags,
);
}
/** System message prepended to /api/chat when the "thinking" flag is on. */
export const THINKING_SYSTEM_PROMPT =
"Think step-by-step before answering. Start with a short 'Thoughts' section showing your reasoning, then give the final answer under an 'Answer' heading.";
+16
View File
@@ -7,6 +7,22 @@ export default {
fontFamily: {
sans: ["Inter Variable", "Inter", "ui-sans-serif", "system-ui", "sans-serif"],
},
/* Accent palette backed by CSS variables so the user can recolor the
UI at runtime (settings → accent color). Defaults = emerald. */
colors: {
accent: {
50: "rgb(var(--ka-accent-50) / <alpha-value>)",
100: "rgb(var(--ka-accent-100) / <alpha-value>)",
200: "rgb(var(--ka-accent-200) / <alpha-value>)",
300: "rgb(var(--ka-accent-300) / <alpha-value>)",
400: "rgb(var(--ka-accent-400) / <alpha-value>)",
500: "rgb(var(--ka-accent-500) / <alpha-value>)",
600: "rgb(var(--ka-accent-600) / <alpha-value>)",
700: "rgb(var(--ka-accent-700) / <alpha-value>)",
800: "rgb(var(--ka-accent-800) / <alpha-value>)",
900: "rgb(var(--ka-accent-900) / <alpha-value>)",
},
},
},
},
plugins: [],
+6
View File
@@ -42,6 +42,12 @@ export const config = {
openaiApiKey: env("OPENAI_API_KEY", ""),
openaiEnabled: envBool("OPENAI_ENABLED", false),
glmApiKey: env("GLM_API_KEY", ""),
glmEnabled: envBool("GLM_ENABLED", false),
// Zhipu has two platforms: international (api.z.ai, default) and
// mainland China (open.bigmodel.cn) — override for the latter.
glmBaseUrl: env("GLM_BASE_URL", "https://api.z.ai/api/paas/v4"),
// Public docs wiki (served by the hosted git forge, e.g. Gitea wiki pages).
// The app redirects GET /wiki there (302) so the target stays configurable.
wikiUrl: env("WIKI_URL", "https://git.kisakay.com/k/chat/wiki"),
+28
View File
@@ -108,6 +108,11 @@ export function getDb(): Database {
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS settings(
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// Email column added after the initial schema — keep idempotent.
const cols = db.query("PRAGMA table_info(users)").all() as { name: string }[];
@@ -332,6 +337,29 @@ export function deleteUserResets(userId: string): void {
getDb().query("DELETE FROM resets WHERE user_id = ?").run(userId);
}
// --- platform settings (admin-controlled feature flags) ---
export function getSetting(key: string, fallback: string): string {
const r = getDb().query("SELECT value FROM settings WHERE key = ?").get(key) as { value: string } | null;
return r?.value ?? fallback;
}
export function setSetting(key: string, value: string): void {
getDb().query(
"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
).run(key, value, Date.now());
}
/** Public self-registration switch (default off = admin-created accounts only). */
export function isRegistrationEnabled(): boolean {
return getSetting("registration_enabled", "0") === "1";
}
/** Admin kill-switch for the OCR platform tool (default on). */
export function isOcrToolEnabled(): boolean {
return getSetting("tools_ocr_enabled", "1") === "1";
}
// --- public shares ---
export function ensureShare(convId: string): string {
+1 -1
View File
@@ -4,7 +4,7 @@ import { driverLog, fmtBytes, fmtMs } from "./log.ts";
/**
* Base class for OpenAI-compatible HTTP API drivers
* (mistral / deepseek / openai / anthropic adapter).
* (mistral / glm / deepseek / openai / anthropic adapter).
* Only enabled when an API key is configured. Phase 1: disabled stubs.
*/
export abstract class ApiDriverBase implements LLMDriver {
+17
View File
@@ -52,3 +52,20 @@ export class OpenAIDriver extends ApiDriverBase {
});
}
}
/**
* GLM driver (Zhipu AI, OpenAI-compatible endpoint). Priority: after Mistral.
* Docs: https://docs.z.ai — international base is api.z.ai, mainland China
* uses https://open.bigmodel.cn/api/paas/v4 (via GLM_BASE_URL).
*/
export class GlmDriver extends ApiDriverBase {
readonly name = "glm";
constructor() {
super({
baseUrl: config.glmBaseUrl,
apiKey: config.glmApiKey,
enabled: config.glmEnabled,
defaultModels: ["glm-4.7", "glm-4.6", "glm-4.5-air", "glm-4.5-flash"],
});
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ export class OllamaDriver implements LLMDriver {
readonly name = "ollama";
readonly enabled: boolean;
constructor(private host: string = config.ollamaHost, enabled = config.ollamaEnabled) {
constructor(public readonly host: string = config.ollamaHost, enabled = config.ollamaEnabled) {
this.host = host.replace(/\/$/, "");
this.enabled = enabled;
}
+5 -4
View File
@@ -1,14 +1,14 @@
import { AnthropicDriver, DeepSeekDriver, MistralDriver, OpenAIDriver } from "./apis.ts";
import { AnthropicDriver, DeepSeekDriver, GlmDriver, MistralDriver, OpenAIDriver } from "./apis.ts";
import { OllamaDriver } from "./ollama.ts";
import { PuppeteerOpenAIDriver } from "./puppeteer.ts";
import type { DriverModel, LLMDriver } from "./types.ts";
/**
* Global driver priority (per spec):
* 1. ollama (local) -> 2. mistral -> 3. puppeteer-openai (stub)
* -> 4. deepseek -> 5. anthropic -> 6. openai
* 1. ollama (local) -> 2. mistral -> 3. glm -> 4. puppeteer-openai (stub)
* -> 5. deepseek -> 6. anthropic -> 7. openai
*/
const PRIORITY = ["ollama", "mistral", "puppeteer-openai", "deepseek", "anthropic", "openai"];
const PRIORITY = ["ollama", "mistral", "glm", "puppeteer-openai", "deepseek", "anthropic", "openai"];
export class DriverRegistry {
private drivers: Map<string, LLMDriver>;
@@ -17,6 +17,7 @@ export class DriverRegistry {
const all: LLMDriver[] = [
new OllamaDriver(),
new MistralDriver(),
new GlmDriver(),
new PuppeteerOpenAIDriver(),
new DeepSeekDriver(),
new AnthropicDriver(),
+195 -1
View File
@@ -28,19 +28,24 @@ import {
getMessages,
getShareByConv,
getShareByPublic,
getSetting,
getUserById,
getUserByUsername,
isRegistrationEnabled,
listConversations,
listUsers,
peekReset,
setSetting,
toPublicUser,
touchConversation,
updateConversation,
updateUser,
} from "./db.ts";
import type { ChatMessage } from "./drivers/types.ts";
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, sendRecoveryEmail } from "./mail.ts";
import {
CDN_NAMESPACES,
@@ -61,6 +66,8 @@ import { tools } from "./tools/registry.ts";
assertConfig();
const registry = new DriverRegistry();
// Ollama handles admin model pulls/deletes (host is loopback/LAN, no auth).
const ollamaDriver = registry.get("ollama") as OllamaDriver;
await tools.init();
function json(data: unknown, status = 200): Response {
@@ -186,6 +193,28 @@ const server = Bun.serve({
}
const f = await cdnFile(ns, key, ext);
if (!f.exists) return new Response("not found", { status: 404 });
if (ns === "avatar") {
// Same URL, new bytes after a re-upload: force revalidation (ETag)
// so the fresh picture shows immediately without a page refresh.
let etag = "";
try {
const st = statSync(f.path);
etag = `"${st.mtimeMs.toString(36)}-${st.size.toString(36)}"`;
} catch {
// stat failed — serve without ETag
}
if (etag && req.headers.get("if-none-match") === etag) {
return new Response(null, { status: 304 });
}
return new Response(Bun.file(f.path), {
headers: {
"Content-Type": cdnMime(ext),
"Cache-Control": "no-cache",
...(etag ? { ETag: etag } : {}),
"X-Content-Type-Options": "nosniff",
},
});
}
return new Response(Bun.file(f.path), {
headers: {
"Content-Type": cdnMime(ext),
@@ -271,7 +300,50 @@ const server = Bun.serve({
// --- key recovery via email (optional — needs SMTP configured) ---
if (path === "/api/auth/methods" && req.method === "GET") {
return json({ recovery: mailEnabled(), from: mailEnabled() ? config.smtpFrom : undefined });
return json({
recovery: mailEnabled(),
from: mailEnabled() ? config.smtpFrom : undefined,
registration: isRegistrationEnabled(),
});
}
// --- public self-registration (admin can disable it on the fly) ---
if (path === "/api/auth/register" && req.method === "POST") {
const ip = clientIp(req, server);
if (isRateLimited(ip)) return json({ error: "too many attempts, try again later" }, 429);
if (!isRegistrationEnabled()) {
recordAttempt(ip);
return json({ error: "registration is currently disabled on this platform" }, 403);
}
const { ok, body } = await readJson(req);
if (!ok) {
recordAttempt(ip);
return json({ error: "invalid JSON" }, 400);
}
const username = validUsername(body.username);
if (!username) {
recordAttempt(ip);
return json({ error: "username: 2-32 chars [a-z0-9._-], 'admin' reserved" }, 400);
}
if (getUserByUsername(username)) {
recordAttempt(ip);
return json({ error: "username taken" }, 409);
}
const displayName = body.displayName === undefined ? username : cleanStr(body.displayName, 60);
if (displayName === null) {
recordAttempt(ip);
return json({ error: "displayName: 1-60 chars" }, 400);
}
const email = body.email === undefined ? "" : validEmail(body.email);
if (email === null) {
recordAttempt(ip);
return json({ error: "invalid email address" }, 400);
}
const key = newAccessKey();
const created = createUser({ username, displayName, avatarUrl: "", theme: "auto", email, keyHash: hashSecret(key) });
clearAttempts(ip);
// Show the raw key exactly once.
return json({ user: toPublicUser(created), key }, 201);
}
if (path === "/api/auth/recover" && req.method === "POST") {
@@ -424,6 +496,128 @@ const server = Bun.serve({
return json({ error: "not found" }, 404);
}
// --- admin: platform settings (feature flags) ---
if (path === "/api/admin/settings" && req.method === "GET") {
if (!admin) return json({ error: "forbidden" }, 403);
return json({
settings: {
registrationEnabled: isRegistrationEnabled(),
ocrEnabled: getSetting("tools_ocr_enabled", "1") === "1",
},
});
}
if (path === "/api/admin/settings" && req.method === "PATCH") {
if (!admin) return json({ error: "forbidden" }, 403);
const { ok, body } = await readJson(req);
if (!ok) return json({ error: "invalid JSON" }, 400);
if (body.registrationEnabled !== undefined) {
if (typeof body.registrationEnabled !== "boolean") return json({ error: "registrationEnabled must be boolean" }, 400);
setSetting("registration_enabled", body.registrationEnabled ? "1" : "0");
}
if (body.ocrEnabled !== undefined) {
if (typeof body.ocrEnabled !== "boolean") return json({ error: "ocrEnabled must be boolean" }, 400);
setSetting("tools_ocr_enabled", body.ocrEnabled ? "1" : "0");
}
return json({
settings: {
registrationEnabled: isRegistrationEnabled(),
ocrEnabled: getSetting("tools_ocr_enabled", "1") === "1",
},
});
}
// --- admin: Ollama model management (pull from the library, delete) ---
// Pull streams Ollama's NDJSON progress straight to the admin client.
if (path === "/api/admin/ollama/pull" && req.method === "POST") {
if (!admin) return json({ error: "forbidden" }, 403);
const { ok, body } = await readJson(req);
if (!ok) return json({ error: "invalid JSON" }, 400);
const name = typeof body.name === "string" ? body.name.trim() : "";
if (!/^[a-z0-9._:\/-]{1,100}$/i.test(name)) return json({ error: "invalid model name" }, 400);
if (!ollamaDriver.enabled) return json({ error: "ollama driver is disabled" }, 502);
const abortUpstream = new AbortController();
const onClientAbort = () => abortUpstream.abort();
req.signal.addEventListener("abort", onClientAbort);
let clientGone = false;
const stream = new ReadableStream({
async start(controller) {
const enc = new TextEncoder();
const send = (obj: unknown): boolean => {
if (clientGone || req.signal.aborted) return false;
try {
controller.enqueue(enc.encode(JSON.stringify(obj) + "\n"));
return true;
} catch {
clientGone = true;
return false;
}
};
try {
const res = await fetch(`${ollamaDriver.host}/api/pull`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: name, stream: true }),
signal: abortUpstream.signal,
});
if (!res.ok || !res.body) {
const errText = await res.text().catch(() => "");
send({ error: `ollama /api/pull failed: ${res.status}${errText ? ` — ${errText.slice(0, 200)}` : ""}` });
return;
}
// Passthrough of the NDJSON progress lines (status/digest/completed/total).
const dec = new TextDecoder();
let buf = "";
for await (const chunk of res.body) {
if (req.signal.aborted) 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;
}
}
send({ status: "done" });
} catch (e) {
if (!req.signal.aborted && !clientGone) send({ error: (e as Error).message });
} finally {
req.signal.removeEventListener("abort", onClientAbort);
abortUpstream.abort();
if (!clientGone) {
try { controller.close(); } catch { /* already closed */ }
}
}
},
cancel() {
clientGone = true;
abortUpstream.abort();
},
});
return new Response(stream, {
headers: { "Content-Type": "application/x-ndjson", "Cache-Control": "no-store", "X-Accel-Buffering": "no" },
});
}
// Admin-only model removal (frees disk on the Ollama host).
const ollamaDeleteMatch = path.match(/^\/api\/admin\/ollama\/models\/([a-z0-9._:\/-]{1,100})$/i);
if (ollamaDeleteMatch && req.method === "DELETE") {
if (!admin) return json({ error: "forbidden" }, 403);
if (!ollamaDriver.enabled) return json({ error: "ollama driver is disabled" }, 502);
try {
const res = await fetch(`${ollamaDriver.host}/api/delete`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: ollamaDeleteMatch[1] }),
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return json({ error: `ollama /api/delete failed: ${res.status}` }, 502);
return json({ ok: true });
} catch (e) {
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) });
+6 -2
View File
@@ -1,4 +1,5 @@
import { config } from "../config.ts";
import { isOcrToolEnabled } from "../db.ts";
import { driverLog, fmtMs } from "../drivers/log.ts";
import type { PlatformTool } from "./types.ts";
@@ -62,13 +63,16 @@ export class OcrTool implements PlatformTool {
}
isAvailable(): boolean {
return this.available ?? false;
return (this.available ?? false) && isOcrToolEnabled();
}
unavailableReason(): string | null {
if (this.isAvailable()) return null;
if (!(this.available ?? false)) {
return `tesseract binary not found (looked for "${tessBin()}"). Install tesseract or set TESSERACT_BIN.`;
}
if (!isOcrToolEnabled()) return "OCR is disabled by the administrator (Admin Center → Features).";
return null;
}
async transcribe(image: Uint8Array): Promise<{ text: string; truncated: boolean }> {
if (!this.isAvailable()) throw new Error(this.unavailableReason() ?? "ocr unavailable");