Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

web: workspace redesign, and the brio page on top of it

JustVugga35ca53862da
diff --git a/web/index.html b/web/index.html
index 620a61ea..dc95796e 100644
--- a/web/index.html
+++ b/web/index.html
@@ -5,6 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#080b0d" />
<meta name="description" content="A local interface for the colibrì inference engine" />
+ <link rel="icon" type="image/svg+xml" href="./colibri-icon.svg" />
+ <link rel="apple-touch-icon" href="./colibri-icon.svg" />
<title>colibrì</title>
</head>
<body>
diff --git a/web/public/colibri-icon.svg b/web/public/colibri-icon.svg
new file mode 100644
index 00000000..76838b90
--- /dev/null
+++ b/web/public/colibri-icon.svg
@@ -0,0 +1,50 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 168 168">
+ <rect width="168" height="168" rx="36" fill="#080b0d"/>
+ <g transform="translate(7 21)" shape-rendering="crispEdges">
+ <rect x="56" y="0" width="14" height="14" fill="#d75fd7"/>
+ <rect x="70" y="0" width="14" height="14" fill="#d75fd7"/>
+ <rect x="84" y="0" width="14" height="14" fill="#d75fd7"/>
+ <rect x="42" y="14" width="14" height="14" fill="#d75fd7"/>
+ <rect x="56" y="14" width="14" height="14" fill="#d75fd7"/>
+ <rect x="70" y="14" width="14" height="14" fill="#d75fd7"/>
+ <rect x="84" y="14" width="14" height="14" fill="#d75fd7"/>
+ <rect x="98" y="14" width="14" height="14" fill="#d75fd7"/>
+ <rect x="140" y="14" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="56" y="28" width="14" height="14" fill="#d75fd7"/>
+ <rect x="70" y="28" width="14" height="14" fill="#d75fd7"/>
+ <rect x="84" y="28" width="14" height="14" fill="#d75fd7"/>
+ <rect x="98" y="28" width="14" height="14" fill="#d75fd7"/>
+ <rect x="126" y="28" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="140" y="28" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="0" y="42" width="14" height="14" fill="#ff8700"/>
+ <rect x="14" y="42" width="14" height="14" fill="#ff8700"/>
+ <rect x="28" y="42" width="14" height="14" fill="#ff8700"/>
+ <rect x="42" y="42" width="14" height="14" fill="#ff8700"/>
+ <rect x="56" y="42" width="14" height="14" fill="#00afaf"/>
+ <rect x="70" y="42" width="14" height="14" fill="#00afaf"/>
+ <rect x="84" y="42" width="14" height="14" fill="#fff"/>
+ <rect x="98" y="42" width="14" height="14" fill="#00afaf"/>
+ <rect x="112" y="42" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="126" y="42" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="56" y="56" width="14" height="14" fill="#00afaf"/>
+ <rect x="70" y="56" width="14" height="14" fill="#00afaf"/>
+ <rect x="84" y="56" width="14" height="14" fill="#00afaf"/>
+ <rect x="98" y="56" width="14" height="14" fill="#00afaf"/>
+ <rect x="112" y="56" width="14" height="14" fill="#00afaf"/>
+ <rect x="126" y="56" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="140" y="56" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="70" y="70" width="14" height="14" fill="#00afaf"/>
+ <rect x="84" y="70" width="14" height="14" fill="#00afaf"/>
+ <rect x="98" y="70" width="14" height="14" fill="#00afaf"/>
+ <rect x="112" y="70" width="14" height="14" fill="#00afaf"/>
+ <rect x="126" y="70" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="140" y="70" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="84" y="84" width="14" height="14" fill="#00afaf"/>
+ <rect x="98" y="84" width="14" height="14" fill="#00afaf"/>
+ <rect x="112" y="84" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="126" y="84" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="98" y="98" width="14" height="14" fill="#00afaf"/>
+ <rect x="112" y="98" width="14" height="14" fill="#5fd7d7"/>
+ <rect x="112" y="112" width="14" height="14" fill="#5fd7d7"/>
+ </g>
+</svg>
diff --git a/web/public/fonts/OFL.txt b/web/public/fonts/OFL.txt
new file mode 100644
index 00000000..4bf388b1
--- /dev/null
+++ b/web/public/fonts/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2024 The Bytesized Project Authors (https://github.com/balt-dev/bytesized-gf)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/web/public/fonts/bytesized.ttf b/web/public/fonts/bytesized.ttf
new file mode 100644
index 00000000..9f2abea3
Binary files /dev/null and b/web/public/fonts/bytesized.ttf differ
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 283ae1dd..e2dc7e1d 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -7,7 +7,7 @@ import {
Clock,
Cpu,
Database,
- Feather,
+ Search, SquarePen, History, Settings2, Sun, Moon, X, Download, Copy, ChevronDown, Code2,
Gauge,
Globe,
HardDrive,
@@ -17,15 +17,13 @@ import {
Link2,
LoaderCircle,
MemoryStick,
- ImagePlus,
MessageSquareText,
MonitorDot,
RefreshCw,
SlidersHorizontal,
Timer,
Trash2,
- Zap,
-} from "lucide-react"
+ Zap, ImagePlus} from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
@@ -33,18 +31,20 @@ import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { getHealth, listModels, streamChat, type ChatMessage, type HealthResponse, type StreamChatResult } from "@/lib/api"
import { activeRequests, supportsCacheSlots } from "@/lib/runtime"
-import { Brain } from "./Brain"
+import Brio from "./Brio"
+import { BrainWorkspace } from "./BrainWorkspace"
+import { Brand } from "./components/Brand"
+import { Markdown } from "./components/Markdown"
+import { NavigationDock, type View } from "./components/NavigationDock"
import { Profiling } from "./Profiling"
import { persistPublicSettings, stored } from "@/lib/storage"
-import { Markdown } from "@/components/Markdown"
import { cn } from "@/lib/utils"
import { useLocale } from "./i18n"
-import { REASONING_EFFORT, modelForcesReasoning, reasoningLevelsFor, type ReasoningLevel } from "@/lib/reasoning"
-const message = (role: ChatMessage["role"], content: string): ChatMessage => {
+const message = (role: ChatMessage["role"], content: string, images?: string[]): ChatMessage => {
let id: string
try { id = crypto.randomUUID() } catch { id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { const r = Math.random() * 16 | 0; return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16) }) }
- return { id, role, content }
+ return images?.length ? { id, role, content, images } : { id, role, content }
}
export default function App() {
@@ -62,36 +62,13 @@ export default function App() {
const [model, setModel] = useState(() => stored(localStorage, "colibri.model", "glm-5.2-colibri"))
const [temperature, setTemperature] = useState(0.7)
const [maxTokens, setMaxTokens] = useState(4096)
- const [reasoning, setReasoning] = useState<ReasoningLevel>("off")
+ const [thinking, setThinking] = useState(false)
const [cacheSlot, setCacheSlot] = useState(0)
const [conversations, setConversations] = useState<Record<number, ChatMessage[]>>({ 0: [] })
const [health, setHealth] = useState<HealthResponse | null>(null)
const [healthError, setHealthError] = useState("")
const [lastRun, setLastRun] = useState<StreamChatResult | null>(null)
const [draft, setDraft] = useState("")
- /* Immagini in attesa di partire col prossimo messaggio. Si tengono come
- data: URI perche' e' quello che il server accetta e quello che il browser
- puo' mostrare in anteprima senza inventarsi un percorso su disco. */
- const [attachments, setAttachments] = useState<{ name: string; url: string }[]>([])
- const fileInputRef = useRef<HTMLInputElement>(null)
-
- const attachFiles = async (files: FileList | File[] | null) => {
- if (!files) return
- const images = Array.from(files).filter((file) => file.type.startsWith("image/"))
- if (!images.length) return
- const read = await Promise.all(
- images.map(
- (file) =>
- new Promise<{ name: string; url: string }>((resolve, reject) => {
- const reader = new FileReader()
- reader.onload = () => resolve({ name: file.name, url: String(reader.result) })
- reader.onerror = () => reject(reader.error)
- reader.readAsDataURL(file)
- }),
- ),
- )
- setAttachments((current) => [...current, ...read])
- }
const [loading, setLoading] = useState(false)
const [streamStart, setStreamStart] = useState<number | null>(null)
const [tokenCount, setTokenCount] = useState(0)
@@ -100,7 +77,20 @@ export default function App() {
const [totalTokens, setTotalTokens] = useState({ prompt: 0, completion: 0 })
const [connecting, setConnecting] = useState(false)
const [connected, setConnected] = useState(false)
- const [view, setView] = useState<"chat" | "brain" | "profiling">("chat")
+ const [view, setView] = useState<View>("chat")
+ const [settingsPage, setSettingsPage] = useState("general")
+ const [historyOpen, setHistoryOpen] = useState(false)
+ const [query, setQuery] = useState("")
+ const [archives, setArchives] = useState<Array<{ id: string; slot: number; messages: ChatMessage[] }>>([])
+ const [theme, setTheme] = useState(() => stored(localStorage, "colibri.theme", "dark"))
+ const [copied, setCopied] = useState<string | null>(null)
+ const draftRef = useRef<HTMLTextAreaElement>(null)
+ const fileRef = useRef<HTMLInputElement>(null)
+ /* Pictures wait here until the turn is sent, then travel on the message. */
+ const [pending, setPending] = useState<string[]>([])
+ const historyDialog = useRef<HTMLDialogElement>(null)
+ useEffect(() => { document.documentElement.dataset.theme = theme; try { localStorage.setItem("colibri.theme", theme) } catch {} }, [theme])
+ useEffect(() => { if (historyOpen) historyDialog.current?.showModal(); else historyDialog.current?.close() }, [historyOpen])
const [error, setError] = useState("")
const autoConnected = useRef(false)
const abortRef = useRef<AbortController | null>(null)
@@ -161,15 +151,6 @@ export default function App() {
// EFFECT #6
useEffect(() => { setLastRun(null) }, [cacheSlot])
- /* GLM 5.3 cannot turn reasoning off and has no distinct "medium" (it collapses
- onto High). If the user switches to such a model while "off" or "medium" is
- selected, lift it to a level the model actually honors instead of leaving the
- control on a value it no longer offers. */
- useEffect(() => {
- if (modelForcesReasoning(model))
- setReasoning((level) => (level === "off" || level === "medium" ? "high" : level))
- }, [model])
-
// EFFECT #7
useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }) }, [messages])
@@ -202,35 +183,46 @@ export default function App() {
}
}
- // Auto-connect once when the UI is served by the engine itself. In an
- // effect, not in the render body: a side effect during render breaks under
- // StrictMode double-rendering and concurrent re-renders.
- useEffect(() => {
- if (servedByEngine && !autoConnected.current && !connected) {
- autoConnected.current = true
- connect()
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [servedByEngine, connected])
+ if (servedByEngine && !autoConnected.current && !connected) {
+ autoConnected.current = true
+ setTimeout(() => connect(), 0)
+ }
- const canSend = useMemo(() => draft.trim() && model && !loading, [draft, loading, model])
+ /* A picture becomes a data URI here and nowhere else: the API takes one
+ directly, so there is no upload endpoint, no temporary file and nothing to
+ clean up. Anything that is not an image is ignored rather than refused --
+ a dropped PDF should not interrupt what someone was typing. */
+ const attach = async (files: FileList | File[] | null) => {
+ const pictures = Array.from(files || []).filter(file => file.type.startsWith("image/"))
+ if (!pictures.length) return
+ const read = (file: File) => new Promise<string>((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => resolve(String(reader.result))
+ reader.onerror = () => reject(reader.error)
+ reader.readAsDataURL(file)
+ })
+ try {
+ const urls = await Promise.all(pictures.map(read))
+ setPending(current => [...current, ...urls])
+ } catch { setError("status.serverError") }
+ }
- const send = async () => {
- const content = draft.trim()
- /* Un'immagine da sola e' una domanda valida: "questa cosa e'?" si puo'
- chiedere anche senza scrivere niente. */
- if ((!content && !attachments.length) || loading) return
- const user = message("user", content)
- if (attachments.length) user.images = attachments.map((item) => item.url)
+ const canSend = useMemo(() => (draft.trim() || pending.length) && model && !loading, [draft, loading, model, pending])
+
+ const send = async (text = draft, previous = messages, pictures = pending) => {
+ const content = text.trim()
+ if ((!content && !pictures.length) || loading) return
+ const user = message("user", content, pictures)
const assistant = message("assistant", "")
- const history = [...messages, user]
+ const history = [...previous, user]
setDraft("")
- setAttachments([])
+ setPending([])
setError("")
updateMessages([...history, assistant])
setLoading(true)
setStreamStart(null)
setTokenCount(0)
+ let decodeStart = 0
setTokPerSec(null)
setTtft(null)
const t0 = performance.now()
@@ -246,36 +238,28 @@ export default function App() {
messages: history,
temperature,
maxTokens,
- enableThinking: reasoning !== "off",
- reasoningEffort: reasoning === "off" ? undefined : REASONING_EFFORT[reasoning],
+ enableThinking: thinking,
cacheSlot: supportsCacheSlots(health) ? cacheSlot : undefined,
signal: controller.signal,
- /* Reasoning tokens are tokens: they count toward the rate, and the
- first one is the real time-to-first-token — the answer's first
- token arrives much later on a reasoning model. */
- onReasoning: (delta) => {
- if (firstToken) { setTtft(performance.now() - t0); setStreamStart(performance.now()); firstToken = false }
- count++
- setTokenCount(count)
- const elapsed = (performance.now() - t0) / 1000
- if (elapsed > 0.3) setTokPerSec(count / elapsed)
- updateMessages((current) => current.map((item) =>
- item.id === assistant.id ? { ...item, reasoning: (item.reasoning ?? "") + delta } : item,
- ))
- },
onDelta: (delta) => {
- if (firstToken) { setTtft(performance.now() - t0); setStreamStart(performance.now()); firstToken = false }
+ if (firstToken) { setTtft(performance.now() - t0); setStreamStart(performance.now()); decodeStart = performance.now(); firstToken = false }
count++
setTokenCount(count)
- const elapsed = (performance.now() - t0) / 1000
- if (elapsed > 0.3) setTokPerSec(count / ((performance.now() - t0) / 1000))
+ /* The live rate is DECODE speed: measured from the first token, not
+ from the request, because the prefill wait belongs to TTFT and
+ averaging it in makes the number crawl upward for the whole turn
+ instead of showing what the engine is doing now. */
+ const since = (performance.now() - decodeStart) / 1000
+ if (count > 1 && since > 0.2) setTokPerSec((count - 1) / since)
updateMessages((current) => current.map((item) =>
item.id === assistant.id ? { ...item, content: item.content + delta } : item,
))
},
})
- const finalElapsed = (performance.now() - t0) / 1000
- if (count > 0 && finalElapsed > 0) setTokPerSec(count / finalElapsed)
+ /* The turn's own figure keeps the same meaning as the live one, so the
+ badge does not jump to a different number the moment it stops moving. */
+ const decodeElapsed = (performance.now() - (decodeStart || t0)) / 1000
+ if (count > 1 && decodeElapsed > 0) setTokPerSec((count - 1) / decodeElapsed)
if (result.usage) setTotalTokens(prev => ({
prompt: prev.prompt + (result.usage?.prompt_tokens || 0),
completion: prev.completion + (result.usage?.completion_tokens || 0),
@@ -284,10 +268,10 @@ export default function App() {
setConnected(true)
} catch (cause) {
if (controller.signal.aborted) {
- updateMessages((current) => current.filter((item) => item.id !== assistant.id || item.content || item.reasoning))
+ updateMessages((current) => current.filter((item) => item.id !== assistant.id || item.content))
} else {
setError(cause instanceof Error ? cause.message : "status.generationFailed")
- updateMessages((current) => current.filter((item) => item.id !== assistant.id || item.content || item.reasoning))
+ updateMessages((current) => current.filter((item) => item.id !== assistant.id || item.content))
}
} finally {
abortRef.current = null
@@ -295,26 +279,51 @@ export default function App() {
}
}
- return (
- <div className="app-shell">
- <aside className="sidebar">
- <div className="brand-row">
- <div className="brand-mark"><Feather className="size-5" /></div>
- <div><h1>colibrì</h1><p>{t("brand.tagline")}</p></div>
- </div>
-
- <section className="side-section">
+ const openSettings = (page = "general") => { setSettingsPage(page); setView("settings") }
+ const clearChat = () => { updateMessages([]); setLastRun(null); setTokPerSec(null); setTtft(null); setTokenCount(0); setTotalTokens({ prompt: 0, completion: 0 }); setError("") }
+ const newChat = () => {
+ if (loading) return
+ if (messages.length) setArchives(items => [{ id: message("system", "").id, slot: cacheSlot, messages: [...messages] }, ...items])
+ clearChat(); setDraft(""); setView("chat"); requestAnimationFrame(() => draftRef.current?.focus())
+ }
+ const exportChat = () => {
+ const url = URL.createObjectURL(new Blob([JSON.stringify({ model, messages }, null, 2)], { type: "application/json" }))
+ const anchor = document.createElement("a"); anchor.href = url; anchor.download = "colibri-chat.json"; anchor.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
+ }
+ const copyMessage = async (item: ChatMessage) => {
+ try { await navigator.clipboard.writeText(item.content); setCopied(item.id) } catch { setError(t("ui.copyError")) }
+ }
+ const restoreArchive = (entry: { id: string; slot: number; messages: ChatMessage[] }) => {
+ if (loading) return
+ const slot = entry.slot < kvSlots ? entry.slot : cacheSlot
+ const currentMessages = conversations[slot] || []
+ setArchives(items => [...(currentMessages.length ? [{ id: message("system", "").id, slot, messages: currentMessages }] : []), ...items.filter(item => item.id !== entry.id)])
+ setConversations(items => ({ ...items, [slot]: entry.messages })); setCacheSlot(slot); setView("chat"); setHistoryOpen(false); setLastRun(null); setError(""); setDraft("")
+ }
+ const empty = messages.length === 0
+ const connectionControls = (<fieldset disabled={loading}><section className="side-section">
<div className="section-title"><Link2 className="size-3.5" /> {t("sidebar.connection")}</div>
- <label>{t("sidebar.endpoint")}<Input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} /></label>
- <label>{t("sidebar.apiKey")}<div className="relative"><KeyRound className="field-icon" /><Input className="pl-9" type="password" value={apiKey} placeholder={t("sidebar.apiKeyPlaceholder")} onChange={(event) => setApiKey(event.target.value)} /></div><span className="field-help">{t("sidebar.apiKeyHelp")}</span></label>
+ <label>{t("sidebar.endpoint")}<Input id="endpoint" value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} /></label>
+ <label>{t("sidebar.apiKey")}<div className="relative"><KeyRound className="field-icon" /><Input id="api-key" className="pl-9" type="password" value={apiKey} placeholder={t("sidebar.apiKeyPlaceholder")} onChange={(event) => setApiKey(event.target.value)} /></div><span className="field-help">{t("sidebar.apiKeyHelp")}</span></label>
<Button type="button" variant="secondary" onClick={connect} disabled={connecting}>
{connecting ? <LoaderCircle className="size-4 animate-spin" /> : <RefreshCw className="size-4" />}
{t("sidebar.probe")}
</Button>
<div className={cn("connection-state", connected && "connected")} aria-live="polite"><span />{connected ? t("status.connected") : t("status.notConnected")}</div>
- </section>
-
- <section className="side-section runtime-section" aria-live="polite">
+ </section></fieldset>)
+ const inferenceControls = (<fieldset disabled={loading}><section className="side-section">
+ <div className="section-title"><SlidersHorizontal className="size-3.5" /> {t("sidebar.inference")}</div>
+ <label>{t("sidebar.model")}<select id="model-select" value={model} onChange={(event) => setModel(event.target.value)}>{models.length ? models.map((id) => <option key={id}>{id}</option>) : <option>{model}</option>}</select></label>
+ {health?.kv_slots && health.kv_slots > 1 ? <label>{t("sidebar.kvSession")}<select id="kv-slot" value={cacheSlot} onChange={(event) => setCacheSlot(Number(event.target.value))} disabled={loading}>
+ {Array.from({ length: kvSlots }, (_, slot) => <option key={slot} value={slot}>{t("sidebar.sessionLabel", { slot: slot + 1 })}</option>)}
+ </select><span className="field-help">{t("sidebar.kvSessionHelp")}</span></label> : null}
+ <label><span className="label-line"><span>{t("sidebar.temperature")}</span><code>{temperature.toFixed(1)}</code></span><input id="temperature" className="range" type="range" min="0" max="2" step="0.1" value={temperature} onChange={(event) => setTemperature(Number(event.target.value))} /></label>
+ <label>{t("sidebar.maxTokens")}<Input id="max-tokens" type="number" min={1} max={32768} value={maxTokens} onChange={(event) => { const value = Number(event.target.value); if (Number.isFinite(value)) setMaxTokens(Math.min(32768, Math.max(1, Math.round(value)))) }} /></label>
+ <button type="button" className={cn("toggle-row", thinking && "active")} aria-pressed={thinking} onClick={() => setThinking((value) => !value)}>
+ <span><BrainCircuit className="size-4" /> {t("sidebar.reasoning")}</span><i><b /></i>
+ </button>
+ </section></fieldset>)
+ const runtimeControls = (<><section className="side-section runtime-section" aria-live="polite">
<div className="section-title"><Activity className="size-3.5" /> {t("sidebar.runtime")}</div>
{health?.hwinfo ? <div className="hw-panel">
{health.hwinfo.cpu ? <div className="hw-row"><Cpu className="size-3.5" /><span>{health.hwinfo.cpu}</span></div> : null}
@@ -350,116 +359,100 @@ export default function App() {
</div> : null}
<div className="runtime-foot"><span className="runtime-dot" /> {t("sidebar.schedulerOnline")} <code>{kvSlots} KV</code></div>
</> : <p className="runtime-unavailable">{connected ? (healthError ? t(healthError) : t("status.runtimeUnavailable")) : t("sidebar.runtimeProbe")}</p>}
- </section>
-
- <section className="side-section">
- <div className="section-title"><SlidersHorizontal className="size-3.5" /> {t("sidebar.inference")}</div>
- <label>{t("sidebar.model")}<select value={model} onChange={(event) => setModel(event.target.value)}>{models.length ? models.map((id) => <option key={id}>{id}</option>) : <option>{model}</option>}</select></label>
- {health?.kv_slots && health.kv_slots > 1 ? <label>{t("sidebar.kvSession")}<select value={cacheSlot} onChange={(event) => setCacheSlot(Number(event.target.value))} disabled={loading}>
- {Array.from({ length: kvSlots }, (_, slot) => <option key={slot} value={slot}>{t("sidebar.sessionLabel", { slot: slot + 1 })}</option>)}
- </select><span className="field-help">{t("sidebar.kvSessionHelp")}</span></label> : null}
- <label><span className="label-line"><span>{t("sidebar.temperature")}</span><code>{temperature.toFixed(1)}</code></span><input className="range" type="range" min="0" max="2" step="0.1" value={temperature} onChange={(event) => setTemperature(Number(event.target.value))} /></label>
- <label>{t("sidebar.maxTokens")}<Input type="number" min={1} max={32768} value={maxTokens} onChange={(event) => { const value = Number(event.target.value); if (Number.isFinite(value)) setMaxTokens(Math.min(32768, Math.max(1, Math.round(value)))) }} /></label>
- <label><span className="label-line"><span><BrainCircuit className="size-4" /> {t("sidebar.reasoning")}</span></span>
- <select value={reasoning} onChange={(event) => setReasoning(event.target.value as ReasoningLevel)} disabled={loading}>
- {reasoningLevelsFor(model).map((level) => <option key={level} value={level}>{t(`sidebar.reasoning.${level}`)}</option>)}
- </select>
- </label>
- </section>
-
- <div className="sidebar-foot">
- <div><Cpu className="size-3.5" /><span>{t("sidebar.transport")}</span></div>
- <div className="locale-switcher">
- <Globe className="size-3.5" />
- <select value={locale} onChange={(e) => setLocale(e.target.value)}>
- {locales.map((l) => <option key={l.code} value={l.code}>{l.label}</option>)}
- </select>
- </div>
- </div>
- </aside>
-
- <main className="chat-panel">
- <header className="topbar">
- <div><span className="eyebrow">{t("topbar.activeModel")}</span><strong>{model}</strong></div>
- <div className="view-tabs">
- <button className={view === "chat" ? "active" : ""} onClick={() => setView("chat")}><MessageSquareText className="size-3.5" /> {t("nav.chat")}</button>
- <button className={view === "brain" ? "active" : ""} onClick={() => setView("brain")}><BrainCircuit className="size-3.5" /> {t("nav.brain")}</button>
- <button className={view === "profiling" ? "active" : ""} onClick={() => setView("profiling")}><Gauge className="size-3.5" /> {t("nav.profiling")}</button>
- </div>
- <div className="top-actions">
- {loading && tokenCount > 0 ? <Badge className="badge-live"><Zap className="size-3 flash" /> {t("topbar.tokens", { n: tokenCount })}</Badge> : null}
- {!loading && tokPerSec != null ? <Badge className="badge-speed"><Gauge className="size-3" /> {t("topbar.tokPerSec", { n: tokPerSec.toFixed(1) })}</Badge> : null}
+ </section></>)
+ const metrics = (<div className="live-metrics" aria-live="polite"> {loading && tokenCount > 0 ? <Badge className="badge-live"><Zap className="size-3 flash" /> {t("topbar.tokens", { n: tokenCount })}</Badge> : null}
+ {tokPerSec != null ? <Badge className={cn("badge-speed", loading && "badge-live")}><Gauge className="size-3" /> {t("topbar.tokPerSec", { n: tokPerSec.toFixed(1) })}</Badge> : null}
{!loading && ttft != null ? <Badge><Timer className="size-3" /> TTFT {(ttft/1000).toFixed(1)}s</Badge> : null}
{!loading && lastRun?.usage ? <Badge><Layers className="size-3" /> {lastRun.usage.prompt_tokens}→{lastRun.usage.completion_tokens}</Badge> : null}
{!loading && lastRun?.finishReason === "length" ? <Badge className="badge-warn" title={t("topbar.truncatedHelp")}><AlertTriangle className="size-3" /> {t("topbar.truncated")}</Badge> : null}
{lastRun?.queueWaitMs != null ? <Badge><Clock className="size-3" /> queue {Math.round(lastRun.queueWaitMs)}ms</Badge> : null}
<Badge><MonitorDot className="size-3" /> {t("topbar.slot", { n: cacheSlot + 1 })}</Badge>
- <Button variant="ghost" size="sm" onClick={() => { updateMessages([]); setTokPerSec(null); setTtft(null); setTokenCount(0); setTotalTokens({prompt:0,completion:0}) }} disabled={!messages.length || loading}><Trash2 className="size-3.5" /> {t("topbar.clear")}</Button>
- </div>
- </header>
-
- {view === "brain" ? <Brain baseUrl={baseUrl} apiKey={apiKey} connected={connected} />
- : view === "profiling" ? <Profiling baseUrl={baseUrl} apiKey={apiKey} connected={connected} /> : <>
+</div>)
- <div className="conversation">
- {!messages.length ? (
- <div className="empty-state">
- <div className="orb"><Feather /></div>
- <span className="eyebrow">{t("hero.title")}</span>
- <h2>{t("hero.subtitle")}<br /><em>{t("hero.tagline")}</em></h2>
- <p>{t("hero.description")}</p>
- <div className="suggestions">
- {[t("prompts.routing"), t("prompts.benchmark"), t("prompts.caching")].map((item) => <button key={item} onClick={() => setDraft(item)}>{item}<ArrowUp className="size-3.5 rotate-45" /></button>)}
- </div>
- </div>
- ) : (
- <div className="message-list">
- {messages.map((item) => (
- <article key={item.id} className={cn("message", item.role)}>
- <div className="avatar">{item.role === "user" ? "Y" : <Feather className="size-4" />}</div>
- <div><div className="message-meta">{item.role === "user" ? t("chat.you") : t("chat.colibri")}</div><div className="message-body">{item.reasoning
- ? <details className="reasoning" open={!item.content}>
- <summary>{t("sidebar.reasoning")}</summary>
- <div className="reasoning-body">{item.reasoning}</div>
- </details>
- : null}{item.content
- ? (item.role === "assistant"
- /* User turns stay literal: the person typed those
- characters and expects to see them back. Only the
- model's output is markdown. */
- ? <Markdown source={item.content} />
- : item.content)
- : <span className="typing" aria-label="Generating"><i /><i /><i /></span>}</div></div>
- </article>
- ))}
- <div ref={bottomRef} />
- </div>
- )}
+ return <div className="app-shell redesigned">
+ <aside className="rail" aria-label={t("ui.sidebar")}>
+ <button className="rail-brand" title="colibrì" onClick={() => setView("chat")}><Brand /></button>
+ <button className="rail-button" aria-label={t("ui.newChat")} title={t("ui.newChat")} onClick={newChat} disabled={loading}><SquarePen /></button>
+ <button className="rail-button" aria-label={t("ui.search")} title={t("ui.search")} onClick={() => { setQuery(""); setHistoryOpen(true) }}><Search /></button>
+ <button className="rail-button" aria-label={t("ui.history")} title={t("ui.history")} onClick={() => { setQuery(""); setHistoryOpen(true) }}><History /></button>
+ <div className="rail-bottom">
+ <button className={cn("rail-button", view === "settings" && "active")} aria-label={t("ui.settings")} title={t("ui.settings")} onClick={() => openSettings()}><Settings2 /></button>
+ <button className="rail-button" aria-label={t("ui.theme")} title={t("ui.theme")} onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>{theme === "dark" ? <Sun /> : <Moon />}</button>
+ </div>
+ </aside>
+ <main className={cn("workspace", view === "brain" && "brain-workspace")}>
+ {view !== "brain" && <header className="workspace-topbar">
+ <button className="model-button" onClick={() => openSettings("model")}><span>{model}</span><ChevronDown /></button>
+ <div className="workspace-actions">
+ <button className={cn("connection-state", connected && "connected")} onClick={() => openSettings("connection")}><span />{connected ? t("status.connected") : t("status.notConnected")}</button>
+ {view === "chat" && <><button className="icon-action" aria-label={t("ui.export")} title={t("ui.export")} disabled={empty} onClick={exportChat}><Download /></button><button className="icon-action" aria-label={t("topbar.clear")} title={t("topbar.clear")} disabled={empty || loading} onClick={clearChat}><Trash2 /></button></>}
</div>
-
+ </header>}
+ {view === "settings" ? <section className="settings-page">
+ <header className="page-heading"><span>COLIBRI</span><h1>{t("ui.settings")}</h1><p>{t("ui.settingsIntro")}</p></header>
+ <nav className="settings-tabs" aria-label={t("ui.settings")}>
+ {["general", "model", "connection", "system"].map(id => <button key={id} aria-current={settingsPage === id ? "page" : undefined} onClick={() => setSettingsPage(id)}>{t(`ui.${id}`)}</button>)}
+ </nav>
+ {error && <div className="error-banner" role="alert">{t(error)}</div>}
+ <div className="settings-content">
+ {settingsPage === "general" && <section className="settings-card"><h2>{t("ui.appearance")}</h2><div className="theme-choices">{["dark", "light"].map(value => <button key={value} className={`theme-choice ${value}`} aria-pressed={theme === value} onClick={() => setTheme(value)}><span /><b>{t(`ui.${value}`)}</b></button>)}</div><label className="language-field"><Globe />{t("ui.language")}<select value={locale} onChange={e => setLocale(e.target.value)}>{locales.map(l => <option key={l.code} value={l.code}>{l.label}</option>)}</select></label><p className="settings-help">{t("chat.inputHint")}</p></section>}
+ {settingsPage === "connection" && <section className="settings-card">{connectionControls}</section>}
+ {settingsPage === "model" && <section className="settings-card">{inferenceControls}</section>}
+ {settingsPage === "system" && <section className="settings-card">{runtimeControls}{metrics}</section>}
+ </div>
+ </section> : view === "brain" ? <BrainWorkspace baseUrl={baseUrl} apiKey={apiKey} connected={connected} />
+ : view === "profiling" ? <section className="profiling-workspace"><header className="page-heading"><span>COLIBRI / ENGINE</span><h1>Profiling</h1></header>{metrics}<Profiling baseUrl={baseUrl} apiKey={apiKey} connected={connected} /></section>
+ : <section className={cn("chat-view", empty && "empty")} hidden={view === "brio"}>
+ {empty ? <div className="welcome-brand"><Brand word /></div> : <div className="conversation" role="log" aria-label={t("nav.chat")}>
+ <div className="message-list">{messages.map((item, index) => <article key={item.id} className={cn("message", item.role)}>
+ {item.role !== "user" && <div className="assistant-brand"><Brand /><span>colibrì</span></div>}
+ {item.images?.length ? <div className="message-images">{item.images.map((url, at) =>
+ <img key={at} src={url} alt={t("ui.attachedImage", { n: at + 1 })} />)}</div> : null}
+ <div className="message-body">{item.content ? (item.role === "assistant" ? <Markdown text={item.content} /> : item.content) : <span className="typing" aria-label={t("ui.generating")}><i /><i /><i /></span>}</div>
+ {item.role === "assistant" && item.content && <div className="message-actions"><button className="icon-action" aria-label={t("ui.copy")} title={t("ui.copy")} onClick={() => void copyMessage(item)}><Copy /></button>{copied === item.id && <span role="status">{t("ui.copied")}</span>}{index === messages.length - 1 && !loading && <button className="icon-action" aria-label={t("ui.regenerate")} title={t("ui.regenerate")} onClick={() => { const userIndex = messages.map((m, i) => m.role === "user" && i < index ? i : -1).reduce((a, b) => Math.max(a, b), -1); if (userIndex >= 0) void send(messages[userIndex].content, messages.slice(0, userIndex)) }}><RefreshCw /></button>}</div>}
+ </article>)}<div ref={bottomRef} /></div>
+ </div>}
<div className="composer-wrap">
{error && <div className="error-banner" role="alert">{t(error)}</div>}
- <div className="composer">
- <Textarea value={draft}
- onPaste={(event) => { const files = Array.from(event.clipboardData.files); if (files.length) { event.preventDefault(); void attachFiles(files) } }}
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => { if (event.dataTransfer.files.length) { event.preventDefault(); void attachFiles(event.dataTransfer.files) } }} onChange={(event) => setDraft(event.target.value)} placeholder={t("chat.placeholder")} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send() } }} />
- {attachments.length > 0 && (
- <div className="attachments">
- {attachments.map((item, index) => (
- <span key={item.url + index} className="attachment">
- <img src={item.url} alt={item.name} />
- <button type="button" aria-label={t("chat.removeImage")}
- onClick={() => setAttachments((current) => current.filter((_, at) => at !== index))}>x</button>
- </span>
- ))}
- </div>
- )}
- <div className="composer-foot"><span><MessageSquareText className="size-3.5" /> {t("chat.inputHint")}</span><input ref={fileInputRef} type="file" accept="image/*" multiple hidden onChange={(event) => { void attachFiles(event.target.files); event.target.value = "" }} /><Button variant="ghost" size="icon" aria-label={t("chat.attachImage")} onClick={() => fileInputRef.current?.click()}><ImagePlus className="size-4" /></Button>{loading ? <Button variant="destructive" size="icon" aria-label={t("chat.stop")} onClick={() => abortRef.current?.abort()}><CircleStop className="size-4" /></Button> : <Button size="icon" aria-label={t("chat.send")} disabled={!canSend} onClick={() => void send()}><ArrowUp className="size-4" /></Button>}</div>
- </div>
+ <form className="composer" onSubmit={e => { e.preventDefault(); void send() }}
+ onDragOver={e => { if (e.dataTransfer.types.includes("Files")) e.preventDefault() }}
+ onDrop={e => { if (e.dataTransfer.files.length) { e.preventDefault(); void attach(e.dataTransfer.files) } }}>
+ {pending.length > 0 && <div className="composer-attachments">
+ {pending.map((url, at) => <span key={at} className="attachment">
+ <img src={url} alt={t("ui.attachedImage", { n: at + 1 })} />
+ <button type="button" aria-label={t("ui.removeImage")} title={t("ui.removeImage")}
+ onClick={() => setPending(list => list.filter((_, index) => index !== at))}><X /></button>
+ </span>)}
+ </div>}
+ <Textarea ref={draftRef} id="draft" aria-label={t("chat.placeholder")} value={draft} onChange={e => setDraft(e.target.value)} placeholder={t("chat.placeholder")} onPaste={event => { const files = Array.from(event.clipboardData.files || []); if (files.length) { event.preventDefault(); void attach(files) } }} onKeyDown={event => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send() } }} />
+ <div className="composer-foot">
+ <input ref={fileRef} type="file" accept="image/*" multiple hidden
+ onChange={e => { void attach(e.target.files); e.target.value = "" }} />
+ <button type="button" className="attach-chip" aria-label={t("ui.attachImage")} title={t("ui.attachImage")}
+ onClick={() => fileRef.current?.click()}><ImagePlus /></button>
+ <button type="button" className="reasoning-chip" aria-pressed={thinking} onClick={() => setThinking(value => !value)}><BrainCircuit />{t("sidebar.reasoning")}</button>
+ <button type="button" className="slot-chip" onClick={() => openSettings("model")}><Database />{t("topbar.slot", { n: cacheSlot + 1 })}</button>
+ {loading ? <button type="button" className="send-button" aria-label={t("chat.stop")} onClick={() => abortRef.current?.abort()}><CircleStop /></button> : <button type="submit" className="send-button" aria-label={t("chat.send")} disabled={!canSend}><ArrowUp /></button>}
+ </div>
+ </form>
+ {empty && <div className="suggestions">{[{ key: "routing", Icon: BrainCircuit, label: "idea" }, { key: "benchmark", Icon: Code2, label: "code" }, { key: "caching", Icon: Database, label: "analyze" }].map(({ key, Icon, label }) => <button key={key} onClick={() => { setDraft(t(`prompts.${key}`)); draftRef.current?.focus() }}><Icon />{t(`ui.${label}`)}</button>)}</div>}
+ {!empty && lastRun?.finishReason === "length" && <p className="truncation-note">{t("topbar.truncatedHelp")}</p>}
</div>
- </>}
- </main>
- </div>
- )
+ </section>}
+ <section className="brio-workspace" hidden={view !== "brio"}>
+ <header className="page-heading"><span>COLIBRI / BRIO</span><h1>{t("nav.brio")}</h1></header>
+ <Brio baseUrl={baseUrl} apiKey={apiKey} model={model} connected={connected} />
+ </section>
+ </main>
+ <NavigationDock view={view} onNavigate={setView} loading={loading} />
+ <dialog ref={historyDialog} className="history-dialog" onCancel={() => setHistoryOpen(false)} onClose={() => setHistoryOpen(false)} onClick={e => { if (e.target === e.currentTarget) { const r = e.currentTarget.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) setHistoryOpen(false) } }}>
+ <header><h2>{t("ui.history")}</h2><button className="icon-action" aria-label={t("ui.close")} onClick={() => setHistoryOpen(false)}><X /></button></header>
+ <label className="history-search"><Search /><input aria-label={t("ui.search")} placeholder={t("ui.search")} value={query} onChange={e => setQuery(e.target.value)} /></label>
+ <div className="history-results">
+ {Object.entries(conversations).filter(([slot, items]) => Number(slot) < kvSlots && items.some(m => m.content.toLocaleLowerCase().includes(query.toLocaleLowerCase()))).map(([slot, items]) => <button key={slot} disabled={loading} onClick={() => { setCacheSlot(Number(slot)); setView("chat"); setHistoryOpen(false); setDraft(""); setError("") }}><MessageSquareText /><span>{items.find(m => m.role === "user")?.content.slice(0, 85)}<small>{t("topbar.slot", { n: Number(slot) + 1 })}</small></span></button>)}
+ {archives.filter(entry => entry.messages.some(m => m.content.toLocaleLowerCase().includes(query.toLocaleLowerCase()))).map(entry => <button key={entry.id} disabled={loading} onClick={() => restoreArchive(entry)}><History /><span>{entry.messages.find(m => m.role === "user")?.content.slice(0, 85)}<small>{t("ui.archived")}</small></span></button>)}
+ <p>{t("ui.historyMemory")}</p>
+ </div>
+ </dialog>
+ </div>
}
diff --git a/web/src/Brain.tsx b/web/src/Brain.tsx
index bea0aa6b..a7cac0c9 100644
--- a/web/src/Brain.tsx
+++ b/web/src/Brain.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from "react"
import { BrainCircuit, Flame, Layers } from "lucide-react"
-import { endpoint } from "@/lib/api"
+import { serverEndpoint } from "@/lib/api"
import { useLocale } from "./i18n"
interface ExpertMap { rows: number; cols: number; map: string; hits: string; seq: number }
@@ -30,21 +30,16 @@ export function Brain({ baseUrl, apiKey, connected }: { baseUrl: string; apiKey:
const [atlas, setAtlas] = useState<Record<string, AtlasEntry> | null>(null)
const [tip, setTip] = useState<{ x: number; y: number; row: number; col: number; tier: number; heat: number } | null>(null)
const pulseRef = useRef<Float32Array | null>(null) // per-expert pulse intensity 0..1
+ const usedRef = useRef<Float32Array | null>(null) // per-expert residue: routed at least once this session
const lastSeq = useRef(0)
const rafRef = useRef(0)
// load the expert atlas if published (measured topic affinity, #175)
useEffect(() => {
- // The atlas lives next to the engine's /experts endpoint, not on the page
- // origin: when the UI is hosted elsewhere (dev server, static hosting) a
- // root-relative fetch pointed at the wrong server and the atlas never
- // loaded. Same base + auth as the live expert map above.
- const base = baseUrl.replace(/\/v1\/?$/, "")
- fetch(endpoint(base, "/experts.json"), { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} })
- .then(r => r.ok ? r.json() : null).then(d => {
- if (d?.experts) setAtlas(d.experts)
- }).catch(() => {})
- }, [baseUrl, apiKey])
+ fetch("/experts.json").then(r => r.ok ? r.json() : null).then(d => {
+ if (d?.experts) setAtlas(d.experts)
+ }).catch(() => {})
+ }, [])
// track container size for responsive cell sizing
useEffect(() => {
@@ -64,7 +59,7 @@ export function Brain({ baseUrl, apiKey, connected }: { baseUrl: string; apiKey:
const base = baseUrl.replace(/\/v1\/?$/, "")
const poll = async () => {
try {
- const res = await fetch(endpoint(base, "/experts"), { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} })
+ const res = await fetch(serverEndpoint(base, "/experts"), { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} })
if (!res.ok) throw new Error(`/experts ${res.status}`)
const next = (await res.json()) as ExpertMap
if (disposed || !next.rows) return
@@ -74,10 +69,11 @@ export function Brain({ baseUrl, apiKey, connected }: { baseUrl: string; apiKey:
lastSeq.current = next.seq
const n = next.rows * next.cols
if (!pulseRef.current || pulseRef.current.length !== n) pulseRef.current = new Float32Array(n)
- const p = pulseRef.current
+ if (!usedRef.current || usedRef.current.length !== n) usedRef.current = new Float32Array(n)
+ const p = pulseRef.current, used = usedRef.current
for (let i = 0; i < n; i++) {
const byte = parseInt(next.hits.substr((i >> 3) * 2, 2), 16) || 0
- if (byte & (1 << (i & 7))) p[i] = 1
+ if (byte & (1 << (i & 7))) { p[i] = 1; used[i] = Math.min(1, used[i] + 0.34) }
}
}
} catch { if (!disposed) setProbeErr(true) /* surface repeated failures; keep the last frame */ }
@@ -101,7 +97,7 @@ export function Brain({ baseUrl, apiKey, connected }: { baseUrl: string; apiKey:
const draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
- const p = pulseRef.current
+ const p = pulseRef.current, u = usedRef.current
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const i = r * cols + c
@@ -112,6 +108,13 @@ export function Brain({ baseUrl, apiKey, connected }: { baseUrl: string; apiKey:
// heat scales brightness: cold experts dim, hot experts full colour
const lum = 0.35 + 0.65 * Math.min(heat / 24, 1)
let rr = R * lum, gg = G * lum, bb = B * lum
+ /* An expert this conversation has routed to stays lit, and gets
+ brighter the more turns pick it. The pulse alone decays in about a
+ second while the poll runs every 1.5, so the flash almost always
+ fell between two frames nobody was watching and the grid read as
+ "nothing ever happens". */
+ const seen = u ? u[i] : 0
+ if (seen > 0.01) { const k = 0.5 * (0.25 + 0.75 * seen); rr += (200 - rr) * k; gg += (235 - gg) * k; bb += (210 - bb) * k }
const pulse = p ? p[i] : 0
if (pulse > 0.01) { rr += (255 - rr) * pulse; gg += (255 - gg) * pulse; bb += (255 - bb) * pulse }
ctx.fillStyle = `rgb(${rr | 0},${gg | 0},${bb | 0})`
diff --git a/web/src/BrainWorkspace.tsx b/web/src/BrainWorkspace.tsx
new file mode 100644
index 00000000..6e3a1499
--- /dev/null
+++ b/web/src/BrainWorkspace.tsx
@@ -0,0 +1,139 @@
+import { useEffect, useMemo, useRef, useState } from "react"
+import { ArrowLeft, Focus, Minus, Pause, Play, Plus, Search, SlidersHorizontal, X } from "lucide-react"
+import { Brain } from "./Brain"
+import { useLocale } from "./i18n"
+import { brainTopics } from "./lib/brain-topics"
+import { createCortex, initialCamera, type AtlasEntry, type CortexNode, type ProjectedNode } from "./lib/cortex"
+import "./brain-design.css"
+
+export function BrainWorkspace(props: { baseUrl: string; apiKey: string; connected: boolean }) {
+ const { t } = useLocale()
+ const [mode, setMode] = useState("explore")
+ return <section className="brain-space">
+ <nav className="brain-mode-tabs" aria-label={t("nav.brain")}>
+ <button aria-current={mode === "explore" ? "page" : undefined} onClick={() => setMode("explore")}>{t("ui.explore")}</button>
+ <button aria-current={mode === "live" ? "page" : undefined} onClick={() => setMode("live")}>{t("ui.liveRouting")}</button>
+ </nav>
+ {mode === "explore" ? <BrainExplorer /> : <div className="brain-live"><Brain {...props} /></div>}
+ </section>
+}
+
+function BrainExplorer() {
+ const { t } = useLocale()
+ const canvas = useRef<HTMLCanvasElement>(null)
+ const panelRef = useRef<HTMLElement>(null)
+ const panelToggle = useRef<HTMLButtonElement>(null)
+ const engine = useRef<ReturnType<typeof createCortex> | null>(null)
+ const [atlas, setAtlas] = useState<Record<string, AtlasEntry> | null>(null)
+ const [failed, setFailed] = useState(false)
+ const [retry, setRetry] = useState(0)
+ const [topic, setTopic] = useState<string | null>(null)
+ const [selected, setSelected] = useState<number | null>(null)
+ const [level, setLevel] = useState(0)
+ const [panel, setPanel] = useState(false)
+ const [query, setQuery] = useState("")
+ const [labels, setLabels] = useState<ProjectedNode[]>([])
+ const [paused, setPaused] = useState(() => matchMedia("(prefers-reduced-motion: reduce)").matches)
+ const [tour, setTour] = useState(false)
+ const drag = useRef<{ x: number; y: number; startX: number; startY: number } | null>(null)
+ useEffect(() => {
+ const controller = new AbortController(); setFailed(false)
+ fetch(`${import.meta.env.BASE_URL}experts.json`, { signal: controller.signal }).then(r => { if (!r.ok) throw new Error(String(r.status)); return r.json() }).then(data => { if (!data?.experts || typeof data.experts !== "object") throw new Error("Atlas unavailable"); if (!controller.signal.aborted) setAtlas(data.experts) }).catch(() => { if (!controller.signal.aborted) setFailed(true) })
+ return () => controller.abort()
+ }, [retry])
+ const { topics, nodes } = useMemo(() => {
+ const entries = Object.entries(atlas || {}).filter(([id, value]) => /^\d+:\d+$/.test(id) && value && typeof value.affinity === "object" && value.affinity && typeof value.label === "string")
+ const nodes: CortexNode[] = []
+ const topics = brainTopics.map(topic => {
+ const group = entries.filter(([, entry]) => entry.top === topic.key).sort((a, b) => (b[1].affinity[topic.key] || 0) - (a[1].affinity[topic.key] || 0))
+ const count = Math.min(36, group.length)
+ for (let j = 0; j < count; j++) {
+ const [id, entry] = group[Math.floor(j * group.length / count)]
+ const [layer, expert] = id.split(":").map(Number), u = (j + .5) / count, latitude = Math.acos(1 - 2 * u), longitude = j * 2.39996323, radius = .22 * Math.cbrt(.18 + .82 * ((j * 13) % 36) / 35)
+ nodes.push({ ...entry, id, layer, expert, index: nodes.length, topic: topic.key, x: topic.center[0] + radius * Math.sin(latitude) * Math.cos(longitude), y: topic.center[1] + radius * Math.cos(latitude), z: topic.center[2] + radius * Math.sin(latitude) * Math.sin(longitude) })
+ }
+ return { ...topic, count: group.length }
+ })
+ return { topics, nodes }
+ }, [atlas])
+ useEffect(() => {
+ if (!canvas.current || !nodes.length) return
+ const renderer = createCortex(canvas.current, topics, nodes, setLabels); engine.current = renderer
+ return () => { renderer.dispose(); engine.current = null }
+ }, [topics, nodes])
+ useEffect(() => { engine.current?.pause(paused) }, [paused, nodes])
+ useEffect(() => {
+ const preference = matchMedia("(prefers-reduced-motion: reduce)")
+ const change = () => setPaused(preference.matches)
+ preference.addEventListener("change", change)
+ return () => preference.removeEventListener("change", change)
+ }, [])
+ useEffect(() => {
+ const target = topics.find(item => item.key === topic)
+ const node = selected === null ? null : nodes[selected]
+ engine.current?.move(level === 0 || !target ? initialCamera : level === 2 && node ? { ...initialCamera, x: node.x, y: node.y, z: node.z, distance: .43, pitch: -.1 } : { ...initialCamera, x: target.center[0], y: target.center[1], z: target.center[2], distance: .86, pitch: -.1 }, level, topic, selected)
+ }, [level, topic, selected, topics, nodes])
+ const closePanel = () => { if (panelRef.current?.contains(document.activeElement)) panelToggle.current?.focus(); setPanel(false) }
+ useEffect(() => {
+ const escape = (e: KeyboardEvent) => { if (e.key === "Escape") { if (panelRef.current?.contains(document.activeElement)) panelToggle.current?.focus(); setPanel(false) } }
+ document.addEventListener("keydown", escape); return () => document.removeEventListener("keydown", escape)
+ }, [])
+ const enterTopic = (key: string, guided = false) => {
+ if (!guided) setTour(false)
+ setTopic(key); setLevel(1); setLabels([])
+ const group = nodes.filter(node => node.topic === key); setSelected(group[Math.floor(group.length * .72)]?.index ?? null)
+ if (!guided && innerWidth > 760) setPanel(true)
+ }
+ const enterExpert = (index: number) => { setTour(false); setSelected(index); setTopic(nodes[index].topic); setLevel(2); setPanel(true) }
+ const reset = () => { setTour(false); setTopic(null); setSelected(null); setLevel(0); setLabels([]); closePanel() }
+ useEffect(() => {
+ if (!tour) return
+ let index = 0
+ const next = () => { if (document.hidden) { setTour(false); return }; if (index >= topics.length) { setTour(false); return }; enterTopic(topics[index++].key, true) }
+ next(); const timer = setInterval(next, 4400)
+ const stop = () => { if (document.hidden) setTour(false) }
+ document.addEventListener("visibilitychange", stop)
+ return () => { clearInterval(timer); document.removeEventListener("visibilitychange", stop) }
+ }, [tour, topics, nodes])
+ useEffect(() => {
+ const el = canvas.current
+ if (!el) return
+ const wheel = (e: WheelEvent) => { e.preventDefault(); setTour(false); engine.current?.zoom(Math.sign(e.deltaY) * .08) }
+ el.addEventListener("wheel", wheel, { passive: false }); return () => el.removeEventListener("wheel", wheel)
+ }, [])
+ const current = selected === null ? null : nodes[selected]
+ return <div className="cortex-explorer">
+ <header className="cortex-heading"><span>BRAIN / ATLAS GLM-5.2</span><h1>{t("ui.enterModel")}</h1></header>
+ <div className="cortex-actions">
+ <button aria-label={t(tour ? "ui.stopTour" : "ui.tour")} title={t(tour ? "ui.stopTour" : "ui.tour")} aria-pressed={tour} disabled={!nodes.length} onClick={() => setTour(value => !value)}>{tour ? <Pause /> : <Play />}<span>{t(tour ? "ui.stopTour" : "ui.tour")}</span></button>
+ <button ref={panelToggle} aria-label={t("ui.topicsDetails")} aria-controls="brain-details" aria-expanded={panel} onClick={() => setPanel(value => !value)}><SlidersHorizontal /><span>{t("ui.topicsDetails")}</span></button>
+ </div>
+ <nav className="cortex-breadcrumb" aria-label={t("ui.position")}><button onClick={reset}>{t("ui.overview")}</button>{topic && <><span>/</span><button onClick={() => enterTopic(topic)}>{t(`topic.${topic}`)}</button></>}{level === 2 && current && <span>/ L{current.layer} · E{current.expert}</span>}</nav>
+ <canvas ref={canvas} tabIndex={0} role="img" aria-label={t("ui.cortexControls")}
+ onPointerDown={e => { if (e.button !== 0) return; setTour(false); closePanel(); drag.current = { x: e.clientX, y: e.clientY, startX: e.clientX, startY: e.clientY }; e.currentTarget.setPointerCapture(e.pointerId) }}
+ onPointerMove={e => { const d = drag.current; if (!d) return; engine.current?.rotate((e.clientX - d.x) * .006, (e.clientY - d.y) * .006); d.x = e.clientX; d.y = e.clientY }}
+ onPointerUp={e => { const d = drag.current; if (d && Math.hypot(e.clientX - d.startX, e.clientY - d.startY) < 5 && level) { const box = e.currentTarget.getBoundingClientRect(), node = engine.current?.closest(e.clientX - box.left, e.clientY - box.top); if (node) enterExpert(node.index) }; drag.current = null; if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId) }}
+ onPointerCancel={() => { drag.current = null }}
+ onKeyDown={e => { if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "+", "-", "=", "Enter", "Escape"].includes(e.key)) { e.preventDefault(); setTour(false); if (e.key === "ArrowLeft") engine.current?.rotate(-.1, 0); if (e.key === "ArrowRight") engine.current?.rotate(.1, 0); if (e.key === "ArrowUp") engine.current?.rotate(0, -.1); if (e.key === "ArrowDown") engine.current?.rotate(0, .1); if (e.key === "+" || e.key === "=") engine.current?.zoom(-.15); if (e.key === "-") engine.current?.zoom(.15); if (e.key === "Escape") reset(); if (e.key === "Enter") { if (!topic) enterTopic(topics[0].key); else if (current) enterExpert(current.index) } } }} />
+ {!atlas && <div className="atlas-state" role="status">{t(failed ? "ui.atlasError" : "ui.atlasLoading")}{failed && <button onClick={() => setRetry(value => value + 1)}>{t("error.retry")}</button>}</div>}
+ {atlas && level === 0 && <div className="cortex-regions">{topics.map((item, i) => <button key={item.key} disabled={!item.count} className={i < 5 ? "left" : "right"} style={{ top: `${18 + (i % 5) * 10.5}%` }} onClick={() => enterTopic(item.key)}>{t(`topic.${item.key}`)}<small>{item.count.toLocaleString()} expert</small></button>)}</div>}
+ {level > 0 && labels.map(node => <button key={node.id} className="cortex-node" aria-label={`Layer ${node.layer}, expert ${node.expert}`} style={{ left: node.x, top: node.y - 18 }} onClick={() => enterExpert(node.index)}>L{node.layer} · E{node.expert}</button>)}
+ <div className="cortex-caption"><span>{topic ? t("ui.inside") : `${topics.length} ${t("ui.topics")}`}</span><strong>{level === 2 && current ? `Expert ${current.expert} · layer ${current.layer}` : topic ? t(`topic.${topic}`) : t("ui.chooseRegion")}</strong></div>
+ <div className="cortex-tools">
+ <button disabled={!level} aria-label={t("ui.back")} title={t("ui.back")} onClick={() => { if (level === 2 && topic) enterTopic(topic); else reset() }}><ArrowLeft /></button>
+ <button aria-label={t("ui.overview")} title={t("ui.overview")} onClick={reset}><Focus /></button>
+ <button aria-label={t("ui.zoomOut")} title={t("ui.zoomOut")} onClick={() => { setTour(false); engine.current?.zoom(.2) }}><Minus /></button>
+ <button aria-label={t("ui.zoomIn")} title={t("ui.zoomIn")} onClick={() => { setTour(false); engine.current?.zoom(-.2) }}><Plus /></button>
+ <button aria-label={t(paused ? "ui.resume" : "ui.pause")} title={t(paused ? "ui.resume" : "ui.pause")} aria-pressed={paused} onClick={() => setPaused(value => !value)}>{paused ? <Play /> : <Pause />}</button>
+ </div>
+ <aside ref={panelRef} id="brain-details" className="cortex-details" hidden={!panel} aria-label={t("ui.topicsDetails")}>
+ <header><h2>{t("ui.topicsDetails")}</h2><button className="icon-action" aria-label={t("ui.close")} onClick={closePanel}><X /></button></header>
+ {topic && current && <section className="cortex-expert-details"><span>{t("ui.atlasAffinities")}</span><h3>{t(`topic.${topic}`)}</h3><p>{t(`topic.${topic}.description`)}</p><label>{t("ui.regionExpert")}<select aria-label={t("ui.regionExpert")} value={current.index} onChange={e => enterExpert(Number(e.target.value))}>{nodes.filter(node => node.topic === topic).map(node => <option key={node.id} value={node.index}>Layer {node.layer} · expert {node.expert}</option>)}</select></label><p>{current.label.startsWith("specialist") ? t("ui.specialist") : t("brain.generalist")} · entropy {current.entropy}</p>
+ <div className="cortex-affinities">{Object.entries(current.affinity).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([key, value]) => <div key={key}><span>{t(`topic.${key}`)}<b>{(value * 100).toFixed(1)}%</b></span><i><b style={{ width: `${Math.max(0, Math.min(100, value * 100))}%` }} /></i></div>)}</div>
+ </section>}
+ <label className="cortex-search"><Search /><input type="search" aria-label={t("ui.searchTopic")} placeholder={t("ui.searchTopic")} value={query} onChange={e => setQuery(e.target.value)} /></label>
+ <div className="cortex-topic-list">{topics.filter(item => `${t(`topic.${item.key}`)} ${t(`topic.${item.key}.description`)}`.toLocaleLowerCase().includes(query.toLocaleLowerCase())).map(item => <button key={item.key} disabled={!item.count} aria-pressed={topic === item.key} onClick={() => enterTopic(item.key)}>{t(`topic.${item.key}`)}<small>{item.count.toLocaleString()} expert</small></button>)}</div>
+ <p className="cortex-source">{Object.keys(atlas || {}).length.toLocaleString()} expert · {nodes.length} {t("ui.sample")}<br />{t("ui.atlasNote")}</p>
+ </aside>
+ </div>
+}
diff --git a/web/src/Brio.tsx b/web/src/Brio.tsx
new file mode 100644
index 00000000..63284aa0
--- /dev/null
+++ b/web/src/Brio.tsx
@@ -0,0 +1,175 @@
+import { useRef, useState } from "react"
+import { FileUp, ListChecks, LoaderCircle, Plus, X } from "lucide-react"
+
+import { askBrio, type BrioResponse } from "@/lib/api"
+import { useLocale } from "./i18n"
+
+/* Modalita brio.
+ *
+ * Lo stesso modello con cui si chatta smette di scrivere: gli si da un insieme
+ * chiuso di opzioni e lui dice quanto e probabile ciascuna.
+ *
+ * PERCHE' LE DOMANDE SONO PIU D'UNA. E' la forma in cui questa modalita rende
+ * davvero: il documento si macina UNA volta e resta fotografato nel motore,
+ * poi ogni domanda paga solo i propri token. Misurato su qwen36: la prima
+ * domanda ~60 s, le successive pochi secondi. Una domanda sola non lo mostra,
+ * e le domande si mandano in fila apposta -- cosi i tempi per domanda si
+ * vedono uno per uno mentre arrivano.
+ *
+ * Le altre due cose in evidenza sono quelle che una risposta scritta non puo
+ * dare: l'ENTROPIA (quanto il modello sa di sapere) e i TOKEN GENERATI, zero. */
+
+const LEVEL = (h: number) => (h < 0.4 ? "sure" : h < 0.8 ? "unsure" : "unknown")
+const lines = (text: string) => text.split("\n").map((o) => o.trim()).filter(Boolean)
+
+interface Row {
+ id: number
+ text: string
+ options: string /* vuoto = usa le opzioni comuni */
+ result?: BrioResponse
+ seconds?: number
+ error?: string
+}
+
+let nextId = 1
+const blank = (): Row => ({ id: nextId++, text: "", options: "" })
+const first = (): Row => ({ id: nextId++, text: "", options: "si\nno" })
+
+export default function Brio({ baseUrl, apiKey, model, connected }: {
+ baseUrl: string; apiKey: string; model: string; connected: boolean
+}) {
+ const { t } = useLocale()
+ const [state, setState] = useState("")
+ const [source, setSource] = useState("")
+ const [rows, setRows] = useState<Row[]>([first()])
+ const [running, setRunning] = useState<number | null>(null)
+ const file = useRef<HTMLInputElement>(null)
+
+ /* Ogni domanda porta le SUE opzioni: "quanto e rischioso" vuole
+ * basso/medio/alto, "si firma" vuole si/no, e un insieme unico per tutte
+ * costringerebbe a piegare le domande alla lista invece del contrario. */
+ const asked = rows.filter((row) => row.text.trim() && lines(row.options).length >= 2)
+ const ready = connected && running === null && asked.length > 0
+
+ const patch = (id: number, change: Partial<Row>) =>
+ setRows((all) => all.map((row) => (row.id === id ? { ...row, ...change } : row)))
+
+ const load = async (chosen: File | undefined) => {
+ if (!chosen) return
+ /* Solo testo: un PDF o un .docx qui arriverebbe come byte illeggibili e il
+ * modello leggerebbe spazzatura senza che nessuno se ne accorga. Meglio
+ * dirlo che accettarlo e sbagliare in silenzio. */
+ const text = await chosen.text()
+ if (text.includes("\u0000")) { setSource(t("brio.fileBinary")); return }
+ setState(text)
+ setSource(`${chosen.name} · ${(chosen.size / 1024).toFixed(1)} kB`)
+ }
+
+ const run = async () => {
+ setRows((all) => all.map((row) => ({ ...row, result: undefined, error: undefined, seconds: undefined })))
+ for (const row of asked) {
+ setRunning(row.id)
+ const started = performance.now()
+ try {
+ const result = await askBrio(baseUrl, apiKey, model, state, row.text, lines(row.options))
+ patch(row.id, { result, seconds: (performance.now() - started) / 1000 })
+ } catch (cause) {
+ patch(row.id, { error: cause instanceof Error ? cause.message : String(cause) })
+ }
+ }
+ setRunning(null)
+ }
+
+ return (
+ <div className="brio-page">
+ <section className="brio-card brio-doc">
+ <div className="brio-doc-head">
+ <h2>{t("brio.document")}</h2>
+ <button type="button" onClick={() => file.current?.click()}>
+ <FileUp />{t("brio.upload")}
+ </button>
+ <input ref={file} type="file" hidden accept=".txt,.md,.markdown,.json,.csv,.tsv,.log,.yml,.yaml,.xml,.html,text/*"
+ onChange={(e) => { void load(e.target.files?.[0]); e.target.value = "" }} />
+ </div>
+ <textarea rows={8} value={state} onChange={(e) => { setState(e.target.value); setSource("") }}
+ placeholder={t("brio.documentPlaceholder")} />
+ <p className="brio-meta">
+ {source ? <b>{source} · </b> : null}
+ {state.length.toLocaleString()} {t("brio.chars")} · {t("brio.onceHint")}
+ </p>
+ </section>
+
+ <div className="brio-questions">
+ {rows.map((row, index) => {
+ const own = lines(row.options)
+ const level = row.result ? LEVEL(row.result.entropy) : "sure"
+ return (
+ <section className="brio-card brio-q" key={row.id}>
+ <div className="brio-q-head">
+ <span className="brio-num">{index + 1}</span>
+ <input value={row.text} onChange={(e) => patch(row.id, { text: e.target.value })}
+ placeholder={t("brio.questionPlaceholder")} />
+ {rows.length > 1 ? (
+ <button type="button" className="brio-drop" title={t("brio.removeQuestion")}
+ onClick={() => setRows((all) => all.filter((r) => r.id !== row.id))}><X /></button>
+ ) : null}
+ </div>
+ <textarea className="brio-own" rows={own.length > 2 ? own.length : 2} value={row.options}
+ onChange={(e) => patch(row.id, { options: e.target.value })}
+ placeholder={t("brio.ownOptions")} />
+ {own.length ? (
+ <div className="brio-chips">
+ {own.map((option) => (
+ <button type="button" key={option} title={t("brio.removeOption")}
+ onClick={() => patch(row.id, { options: own.filter((o) => o !== option).join("\n") })}>
+ {option}<X />
+ </button>
+ ))}
+ </div>
+ ) : null}
+ {own.length === 1 ? <p className="brio-warn">{t("brio.needTwo")}</p> : null}
+
+ {running === row.id ? (
+ <p className="brio-running"><LoaderCircle className="brio-spin" />{t("brio.scoring")}</p>
+ ) : row.error ? (
+ <p className="brio-error">{row.error}</p>
+ ) : row.result ? (
+ <div className="brio-answer">
+ <div className="brio-bars">
+ {row.result.choices.map((choice) => (
+ <div className={`brio-bar${choice.option === row.result!.answer ? " top" : ""}`}
+ key={choice.option}>
+ <span className="brio-name">{choice.option}</span>
+ <span className="brio-track">
+ <span className="brio-fill" style={{ width: `${Math.max(1.5, choice.p * 100)}%` }} />
+ </span>
+ <b className="brio-pct">{(choice.p * 100).toFixed(1)}<i>%</i></b>
+ </div>
+ ))}
+ </div>
+ <div className="brio-foot" data-level={level}>
+ <strong>{row.result.answer}</strong>
+ <span>{t("brio.entropy")} {row.result.entropy.toFixed(3)} · {t(`brio.${level}`)}</span>
+ <em>{row.seconds?.toFixed(1)}s · {row.result.usage.read_tokens} {t("brio.readTokens")} ·{" "}
+ <b>{row.result.usage.completion_tokens} {t("brio.generatedTokens")}</b></em>
+ </div>
+ </div>
+ ) : null}
+ </section>
+ )
+ })}
+
+ <div className="brio-actions">
+ <button type="button" className="brio-add" onClick={() => setRows((all) => [...all, blank()])}>
+ <Plus />{t("brio.addQuestion")}
+ </button>
+ <button type="button" className="brio-run" disabled={!ready} onClick={run}>
+ {running !== null ? <LoaderCircle className="brio-spin" /> : <ListChecks />}
+ {running !== null ? t("brio.scoring") : t("brio.scoreAll", { n: asked.length })}
+ </button>
+ </div>
+ {!connected ? <p className="brio-note">{t("brio.offline")}</p> : null}
+ </div>
+ </div>
+ )
+}
diff --git a/web/src/brain-design.css b/web/src/brain-design.css
new file mode 100644
index 00000000..7df2c972
--- /dev/null
+++ b/web/src/brain-design.css
@@ -0,0 +1,8 @@
+.brain-space{position:relative;flex:1;min-height:0;color:#cad8cf;background:#171c19;overflow:hidden}.brain-mode-tabs{position:absolute;top:26px;left:50%;transform:translateX(-50%);z-index:6;display:flex;background:#18231ccc;border:1px solid #ffffff12;border-radius:24px;padding:3px;backdrop-filter:blur(16px)}.brain-mode-tabs button{border:0;border-radius:20px;background:none;color:#91a599;padding:8px 13px;font-size:10px;white-space:nowrap}.brain-mode-tabs button[aria-current]{background:#ffffff0e;color:#dfebe3}
+.cortex-explorer{position:relative;height:100%;background:radial-gradient(ellipse at 50% 45%,#263c345e,transparent 70%),#171c19;overflow:hidden}.cortex-explorer>canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:grab;outline-offset:-4px}.cortex-explorer>canvas:active{cursor:grabbing}.cortex-heading{position:absolute;left:30px;top:26px;z-index:2;pointer-events:none}.cortex-heading>span{font-size:8px;letter-spacing:1.5px;color:#8ca294}.cortex-heading h1{font-size:26px;font-weight:400;letter-spacing:-.6px;margin:8px 0 0}.cortex-actions{position:absolute;top:26px;right:26px;z-index:5;display:flex;gap:8px}.cortex-actions button{display:flex;align-items:center;gap:7px;border:1px solid #829b8d30;background:#223229b8;backdrop-filter:blur(16px);color:#bfcec5;border-radius:24px;padding:9px 12px;font-size:10px}.cortex-actions svg{width:13px;height:13px}.cortex-actions button[aria-expanded=true],.cortex-actions button[aria-pressed=true]{background:#3a5143}.cortex-breadcrumb{position:absolute;top:110px;left:30px;right:20px;z-index:4;display:flex;align-items:center;gap:7px;font-size:10px}.cortex-breadcrumb button{border:1px solid #84998b25;background:#24312ac2;color:#c8d4cd;border-radius:8px;padding:7px 10px}.cortex-breadcrumb span{font-size:9px;color:#a6b9ae}
+.cortex-regions{position:absolute;inset:0;pointer-events:none;z-index:3}.cortex-regions button{position:absolute;pointer-events:auto;min-width:133px;display:block;text-align:left;padding:12px 14px;background:#1c2821b8;border:1px solid #a1beac1f;border-radius:11px;font-size:12px;color:#b7c9be;backdrop-filter:blur(8px)}.cortex-regions .left{left:30px}.cortex-regions .right{right:30px}.cortex-regions small{display:block;font-size:8px;color:#7f9788;margin-top:4px}.cortex-regions button:hover{background:#31483a;color:#f1f8f3;border-color:#b7d4c66b}.cortex-node{position:absolute;transform:translate(-50%,-50%);z-index:3;background:#17221cd9;border:1px solid #809b8b2b;border-radius:7px;padding:6px 8px;color:#acc7b6;font-size:9px;white-space:nowrap}.cortex-node:hover{color:#e2f4e9;border-color:#b2d2bf88}
+.cortex-caption{position:absolute;bottom:116px;left:20px;right:20px;display:grid;gap:9px;text-align:center;pointer-events:none}.cortex-caption span{font-size:9px;letter-spacing:1.4px;text-transform:uppercase;color:#829e8e}.cortex-caption strong{font-size:17px;font-weight:400;color:#c5d8ce}.cortex-tools{position:absolute;bottom:25px;left:28px;z-index:4;display:flex;padding:4px;border-radius:12px;border:1px solid #ffffff12;background:#17221bc9;backdrop-filter:blur(10px)}.cortex-tools button{width:30px;height:30px;border:0;border-radius:8px;background:none;display:grid;place-items:center;color:#b8ccbf}.cortex-tools svg{width:15px;height:15px}.cortex-tools button:hover{background:#314539}
+.cortex-details{position:absolute;right:24px;top:86px;bottom:90px;width:310px;max-width:calc(100% - 32px);padding:18px;background:var(--rail-bg);color:var(--foreground);border:1px solid var(--border);border-radius:22px;z-index:8;overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;box-shadow:0 24px 80px #0005}.cortex-details header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:20px}.cortex-details h2{font-size:12px;font-weight:500;margin:0}.cortex-expert-details{margin-bottom:20px;padding-bottom:20px;border-bottom:1px solid var(--border)}.cortex-expert-details>span{font-size:8px;letter-spacing:1.1px;text-transform:uppercase;color:var(--muted-foreground)}.cortex-expert-details h3{font-size:24px;font-weight:400;margin:12px 0}.cortex-expert-details p{font-size:11px;line-height:1.8;color:var(--muted-foreground)}.cortex-expert-details label{display:grid;gap:9px;font-size:10px;margin:20px 0 10px}.cortex-expert-details select{padding:10px;width:100%;border-radius:8px;border:1px solid var(--border);background:var(--input);font-size:12px}.cortex-affinities{display:grid;gap:13px;margin-top:20px}.cortex-affinities>div>span{display:flex;justify-content:space-between;font-size:11px;color:var(--muted-foreground)}.cortex-affinities b{font-weight:400;color:var(--foreground)}.cortex-affinities i{height:3px;display:block;background:var(--border);margin-top:7px;border-radius:4px;overflow:hidden}.cortex-affinities i>b{height:100%;background:var(--primary);display:block}.cortex-search{display:flex;align-items:center;gap:8px;background:var(--input);border:1px solid var(--border);border-radius:9px;padding:9px;margin-bottom:15px}.cortex-search svg{width:13px;flex-shrink:0}.cortex-search input{font-size:11px;background:none;border:0;min-width:0;width:100%;outline:none}.cortex-search:focus-within{outline:1px solid var(--primary)}.cortex-topic-list{display:grid;grid-template-columns:1fr 1fr;gap:7px}.cortex-topic-list button{border:1px solid transparent;background:var(--secondary);border-radius:8px;padding:10px;text-align:left;font-size:10px}.cortex-topic-list button[aria-pressed=true]{border-color:var(--primary)}.cortex-topic-list small{display:block;color:var(--muted-foreground);font-size:8px;margin-top:4px}.cortex-source{font-size:10px;color:var(--muted-foreground);line-height:1.8;margin:24px 0 0}.atlas-state{position:absolute;top:45%;left:20%;right:20%;text-align:center;font-size:13px;color:#a7b9ae}.atlas-state button{display:block;margin:15px auto;padding:9px 16px;background:#ffffff0f;border:1px solid #ffffff25;border-radius:12px}
+.brain-live{height:100%;padding:85px 24px 80px;color:var(--foreground);background:var(--background);display:flex}.brain-live .brain-page{padding:0;min-height:0}.brain-live .brain-canvas-wrap{min-height:0}.brain-live .brain-head .section-title{color:var(--muted-foreground)}
+@media(max-width:1100px){.brain-mode-tabs{top:85px;left:auto;right:25px;transform:none}.cortex-actions button span{display:none}.cortex-regions button{min-width:105px;font-size:11px}.brain-live{padding-top:145px}}
+@media(max-width:760px){.cortex-heading{left:16px;top:20px}.cortex-heading>span{font-size:7px;letter-spacing:.8px}.cortex-heading h1{font-size:21px}.cortex-actions{right:14px;top:22px;gap:5px}.cortex-actions button{padding:8px}.brain-mode-tabs{top:80px;left:14px;right:auto}.brain-mode-tabs button{padding:7px 11px;font-size:9px}.cortex-breadcrumb{top:126px;left:14px;font-size:9px;gap:4px}.cortex-breadcrumb button{font-size:9px;padding:6px 7px}.cortex-regions button{min-width:70px;max-width:108px;padding:7px 8px;border-radius:7px;font-size:9px;margin-top:44px}.cortex-regions .left{left:12px}.cortex-regions .right{right:12px}.cortex-regions small{display:none}.cortex-caption{bottom:143px}.cortex-caption strong{font-size:13px}.cortex-caption span{font-size:8px}.cortex-tools{bottom:79px;left:50%;transform:translateX(-50%)}.cortex-details{top:auto;bottom:82px;right:12px;width:calc(100% - 24px);max-width:none;max-height:65%;padding:16px}.cortex-expert-details select,.cortex-search input{font-size:16px}.brain-live{padding:130px 12px 78px}.cortex-node{font-size:8px}}
diff --git a/web/src/chat-design.css b/web/src/chat-design.css
new file mode 100644
index 00000000..675e0966
--- /dev/null
+++ b/web/src/chat-design.css
@@ -0,0 +1,140 @@
+@font-face{font-family:Bytesized;src:url('/fonts/bytesized.ttf') format('truetype');font-weight:400;font-display:swap}
+:root{--background:#212121;--foreground:#ececec;--card:#262626;--primary:#b2ccbb;--primary-foreground:#15221a;--secondary:#303030;--muted-foreground:#a1a1a1;--border:#383838;--input:#303030;--rail:76px;--rail-bg:#171717}
+:root[data-theme=light]{color-scheme:light;--background:#fafafa;--foreground:#242424;--card:#fff;--primary:#4e705b;--primary-foreground:#fff;--secondary:#f0f0f0;--muted-foreground:#747474;--border:#dfdfdf;--input:#f0f0f0;--rail-bg:#f0f0f0}
+button{color:inherit}button:disabled{cursor:default;opacity:.4}svg.lucide{stroke-width:1.5}fieldset{border:0;margin:0;padding:0;min-width:0}[hidden]{display:none!important}
+.redesigned.app-shell{height:100vh;height:100dvh;min-height:0;grid-template-columns:var(--rail) minmax(0,1fr);background:var(--background);overflow:hidden}
+.rail{height:100%;display:flex;align-items:center;flex-direction:column;gap:14px;padding:18px 0;background:var(--rail-bg);z-index:20}
+.rail button{display:grid;place-items:center;border:0;background:none;color:var(--muted-foreground);border-radius:13px;flex-shrink:0}
+.rail .rail-brand{width:45px;height:39px;color:var(--foreground);margin-bottom:14px}.rail-button{width:42px;height:42px}.rail-button svg{width:20px;height:20px}.rail .rail-button:hover,.rail .rail-button.active{background:var(--secondary);color:var(--foreground)}
+.rail-bottom{margin-top:auto;display:grid;gap:10px}.rail-bottom:before{content:'';width:20px;height:1px;background:var(--border);justify-self:center;margin:10px 0}
+.colibri-brand{display:inline-flex;align-items:center;color:var(--foreground);flex-shrink:0}.colibri-brand>svg{width:31px;height:29px}.colibri-brand.full{gap:20px}.colibri-brand.full>svg{width:67px;height:60px}.colibri-word{font-family:Bytesized,sans-serif;font-size:70px;line-height:1;text-transform:uppercase;letter-spacing:.02em}
+.workspace{min-width:0;min-height:0;height:100%;display:flex;flex-direction:column;padding-bottom:14px}.workspace.brain-workspace{padding-bottom:0}
+.workspace-topbar{height:64px;flex-shrink:0;padding:0 28px;display:flex;align-items:center;justify-content:space-between;gap:12px}.model-button{display:flex;align-items:center;gap:9px;background:none;border:0;color:var(--muted-foreground);min-width:0;font-size:13px}.model-button span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.model-button svg{width:14px;height:14px}.workspace-actions{display:flex;align-items:center;gap:10px;flex-shrink:0}.workspace-actions .connection-state{border:0;background:none;font-size:10px;color:var(--muted-foreground)}.connection-state.connected span{box-shadow:none}
+.icon-action{width:32px;height:32px;display:inline-grid;place-items:center;border:0;border-radius:8px;background:none;color:var(--muted-foreground);flex-shrink:0}.icon-action svg{width:17px;height:17px}.icon-action:hover{background:var(--secondary);color:var(--foreground)}
+.chat-view{display:flex;flex-direction:column;flex:1;min-height:0}.chat-view.empty{justify-content:center;overflow:auto}.welcome-brand{display:flex;justify-content:center;flex-shrink:0;margin-bottom:32px;padding:0 16px}
+.chat-view .composer-wrap{padding:0 32px 12px;background:none;flex-shrink:0}.chat-view .composer{width:min(760px,100%);border:1px solid transparent;border-radius:26px;background:var(--input);box-shadow:none}.chat-view .composer:focus-within{border-color:color-mix(in srgb,var(--foreground) 25%,transparent)}
+.chat-view .composer textarea{display:block;min-height:88px;max-height:190px;font-size:15px;line-height:1.6;padding:19px 21px 9px;outline:none;resize:vertical;box-shadow:none}.chat-view .composer-foot{gap:8px;justify-content:flex-start;padding:6px 13px 12px}
+.reasoning-chip{display:flex;align-items:center;gap:6px;border:1px solid color-mix(in srgb,var(--foreground) 18%,transparent);border-radius:20px;font-size:11px;padding:7px 10px;background:none;color:var(--muted-foreground)}.reasoning-chip svg{width:15px;height:15px}.reasoning-chip[aria-pressed=true]{background:var(--foreground);color:var(--background)}.slot-chip{margin-left:auto;display:flex;align-items:center;gap:5px;font-size:10px;color:var(--muted-foreground);border:0;background:none}.slot-chip svg{width:13px;height:13px}
+.send-button{border:0;display:grid;place-items:center;width:34px;height:34px;flex-shrink:0;border-radius:50%;background:var(--foreground);color:var(--background)}.send-button svg{width:21px;height:21px}
+.chat-view .suggestions{display:flex;justify-content:center;flex-wrap:wrap;gap:8px;width:min(760px,100%);margin:22px auto 0}.chat-view .suggestions button{min-height:0;display:flex;align-items:center;justify-content:center;gap:7px;padding:10px 13px;font-size:11px;color:var(--muted-foreground);background:none;border:1px solid var(--border);border-radius:24px}.chat-view .suggestions button svg{width:15px;height:15px}.chat-view .suggestions button:hover{background:var(--secondary);transform:none;color:var(--foreground)}
+.chat-view .conversation{flex:1;min-height:0;overflow:auto;overscroll-behavior:contain}.chat-view .message-list{width:min(760px,calc(100% - 64px));padding:26px 0 20px}.chat-view .message{display:flex;flex-direction:column;gap:13px;margin-bottom:30px}.chat-view .message.user{align-items:flex-end}.chat-view .message-body{font-size:15px;line-height:1.8;color:var(--foreground)}.chat-view .message.user .message-body{max-width:85%;padding:11px 19px;border-radius:24px;background:var(--input);color:var(--foreground)}.assistant-brand{display:flex;align-items:center;gap:9px;font-size:13px}.assistant-brand .colibri-brand>svg{width:23px;height:22px}.message-actions{display:flex;align-items:center;gap:3px}.message-actions>span{font-size:10px;color:var(--muted-foreground)}.truncation-note{max-width:760px;margin:8px auto 0;font-size:11px;color:var(--muted-foreground)}
+.navigation-dock{position:fixed;left:calc(50% + var(--rail)/2);top:0;transform:translateX(-50%);width:104px;height:27px;z-index:70;display:flex;align-items:center;justify-content:center;border-radius:0 0 14px 14px;background:var(--card);border:1px solid var(--border);border-top:0;transition:width .3s,height .3s,margin .3s,border-radius .3s,background .25s,box-shadow .25s}.navigation-dock.open{width:300px;height:64px;margin-top:11px;border-radius:34px;background:color-mix(in srgb,var(--card) 88%,transparent);backdrop-filter:blur(24px);box-shadow:0 6px 22px #0000002e;border:1px solid color-mix(in srgb,var(--foreground) 12%,transparent)}.navigation-dock nav{display:flex;gap:18px;align-items:center}.navigation-dock nav button{display:grid;place-items:center;position:relative;border:0;background:none;border-radius:50%;width:46px;height:46px;padding:0;color:var(--muted-foreground);font-size:12px}.navigation-dock nav button:hover,.navigation-dock nav button:focus-visible{color:var(--foreground)}.navigation-dock nav button[aria-current]{background:color-mix(in srgb,var(--foreground) 10%,transparent);color:var(--foreground)}.navigation-dock nav button>span{position:absolute;top:calc(100% + 19px);left:50%;white-space:nowrap;font-size:12px;color:var(--muted-foreground);opacity:0;pointer-events:none;transform:translateX(-50%) translateY(-4px);transition:opacity .18s,transform .18s}.navigation-dock nav button:hover>span,.navigation-dock nav button:focus-visible>span{opacity:1;transform:translateX(-50%) translateY(0)}.navigation-dock nav svg{width:21px;height:21px;flex-shrink:0}.dock-handle{position:absolute;inset:0;width:100%;height:27px;background:none;border:0;display:grid;place-items:center;touch-action:none}.dock-handle span{width:13px;height:13px;border-right:2.5px solid var(--foreground);border-bottom:2.5px solid var(--foreground);border-radius:0 0 3px 0;opacity:.8;transform:translateY(-4px) rotate(45deg);transition:transform .3s,opacity .25s}.navigation-dock.open .dock-handle{top:auto;bottom:-14px;height:18px}.navigation-dock.open .dock-handle span{transform:translateY(3px) rotate(225deg);opacity:.45}.dock-busy{width:4px;height:4px;border-radius:50%;background:#b6dac3;position:absolute;right:8px;top:8px}
+.settings-page,.profiling-workspace,.brio-workspace{flex:1;min-height:0;overflow:auto;padding:28px 44px 32px}.page-heading,.settings-tabs,.settings-content{max-width:1080px;margin:0 auto}.page-heading>span{font-size:9px;letter-spacing:1.5px;color:var(--muted-foreground)}.page-heading h1{font-size:32px;letter-spacing:-.9px;font-weight:450;margin:12px 0 10px}.page-heading p{font-size:13px;line-height:1.7;color:var(--muted-foreground);margin:0}.settings-tabs{display:flex;gap:6px;margin:28px auto 25px;border-bottom:1px solid var(--border);padding-bottom:12px}.settings-tabs button{border:0;border-radius:9px;padding:10px 17px;background:none;color:var(--muted-foreground);font-size:12px}.settings-tabs button[aria-current]{background:var(--secondary);color:var(--foreground)}.settings-card{max-width:730px;border:1px solid var(--border);border-radius:20px;padding:26px;background:var(--card)}.settings-card h2{font-size:16px;font-weight:500;margin:0 0 23px}.settings-card .side-section{gap:20px}.settings-card .section-title{color:var(--muted-foreground);font-size:11px}.settings-card .side-section label{color:var(--muted-foreground);font-size:12px;gap:9px}.settings-card .side-section select{font-size:13px}.settings-card .runtime-grid strong{font-size:24px;font-weight:400}.settings-card .field-help{font-size:11px;line-height:1.6}.settings-card .hw-panel{gap:12px}.settings-card .hw-row{font-size:12px}.settings-card .session-stats{margin:15px 0}.settings-help{font-size:11px;margin:25px 0 0;color:var(--muted-foreground)}.theme-choices{display:flex;gap:14px}.theme-choice{width:145px;padding:10px;background:none;border:1px solid var(--border);border-radius:12px;text-align:left}.theme-choice[aria-pressed=true]{border-color:var(--primary)}.theme-choice>span{display:block;height:80px;background:#212121;border:1px solid #ffffff13;border-radius:7px;box-shadow:inset 23px 0 #171717}.theme-choice.light>span{background:#fff;box-shadow:inset 23px 0 #eee;border-color:#ddd}.theme-choice b{display:block;font-size:12px;font-weight:400;margin-top:10px}.language-field{display:flex;align-items:center;gap:10px;margin-top:26px;font-size:12px}.language-field svg{width:16px}.language-field select{margin-left:auto;border:1px solid var(--border);border-radius:8px;padding:9px;background:var(--input);max-width:180px}
+.live-metrics{display:flex;flex-wrap:wrap;gap:9px;max-width:1080px;margin:18px auto}.live-metrics [data-slot=badge]{gap:6px;font-weight:400;padding:8px 12px}.profiling-workspace .prof-page{max-width:1080px;margin:auto;padding:14px 0;overflow:visible}.prof-head .section-title{color:var(--muted-foreground)}.prof-tiles>div,.prof-shares,.prof-chart,.prof-table-wrap{border-radius:17px;padding:20px;background:var(--card)}.prof-tiles strong{font:400 29px ui-sans-serif,system-ui,sans-serif;letter-spacing:-1px}.prof-charts{gap:16px}.prof-chart{padding:24px}.prof-plot svg{height:160px}.prof-table-wrap{padding:0}.prof-table td{color:var(--foreground)}.prof-share-head,.prof-chart-title,.prof-legend{color:var(--muted-foreground)}.prof-plot:focus-visible{outline:2px solid var(--primary);outline-offset:5px}
+.history-dialog{padding:24px;border:1px solid var(--border);border-radius:22px;width:min(560px,calc(100vw - var(--rail) - 24px));max-height:75dvh;background:var(--card);color:var(--foreground);box-shadow:0 24px 80px #0005}.history-dialog::backdrop{background:#0007;backdrop-filter:blur(6px)}.history-dialog header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}.history-dialog h2{font-size:18px;font-weight:500;margin:0}.history-search{display:flex;gap:10px;align-items:center;padding:12px;border:1px solid var(--border);border-radius:12px}.history-search svg{width:16px;flex-shrink:0}.history-search input{border:0;background:none;outline:none;min-width:0;width:100%;font-size:13px}.history-results{display:grid;gap:7px;margin-top:18px}.history-results>button{display:flex;gap:12px;text-align:left;background:var(--secondary);border:0;border-radius:10px;padding:14px;font-size:12px}.history-results svg{width:17px;flex-shrink:0}.history-results span{overflow-wrap:anywhere}.history-results small{display:block;color:var(--muted-foreground);margin-top:6px;font-size:10px}.history-results>p{color:var(--muted-foreground);font-size:11px;line-height:1.6}
+@media(max-width:760px){:root{--rail:60px}.rail{padding:15px 0;gap:10px}.rail-button{width:38px;height:38px}.rail .rail-brand{margin-bottom:12px}.workspace{padding-bottom:12px}.workspace-topbar{height:58px;padding:0 15px}.workspace-actions{gap:2px}.workspace-actions .connection-state{font-size:0;gap:0;padding:8px}.model-button{font-size:11px}.colibri-brand.full{gap:13px}.colibri-brand.full>svg{width:45px;height:40px}.colibri-word{font-size:48px}.welcome-brand{margin-bottom:26px}.chat-view .composer-wrap{padding:0 14px 12px}.chat-view .composer textarea{font-size:16px;padding:16px 16px 8px;min-height:80px}.chat-view .composer-foot{padding:5px 10px 10px;gap:6px}.reasoning-chip{font-size:10px;padding:6px 8px}.slot-chip{font-size:9px}.chat-view .suggestions{gap:7px;margin-top:18px}.chat-view .suggestions button{font-size:10px;padding:9px 11px}.chat-view .suggestions svg{display:none}.chat-view .message-list{width:calc(100% - 30px)}.chat-view .message-body{font-size:14px}.chat-view .message.user .message-body{max-width:93%}.navigation-dock.open{width:min(300px,calc(100vw - var(--rail) - 16px));height:66px;margin-top:9px}.navigation-dock nav{gap:0}.navigation-dock nav button{grid-auto-flow:row;gap:3px;width:60px;height:52px;border-radius:15px;font-size:9px}.navigation-dock nav button>span{position:static;transform:none;opacity:1;font-size:9px;color:inherit;transition:none}.navigation-dock nav svg{width:19px;height:19px}.settings-page,.profiling-workspace,.brio-workspace{padding:20px 16px}.page-heading h1{font-size:26px}.settings-tabs{gap:3px;flex-wrap:wrap;margin:22px auto 18px}.settings-tabs button{font-size:11px;padding:9px}.settings-card{padding:17px}.theme-choice{width:120px;min-width:0}.language-field{flex-wrap:wrap}.language-field select{font-size:16px}.settings-card input:not([type=range]),.settings-card select{font-size:16px}.prof-tiles{gap:8px}.prof-tiles>div{padding:14px}.prof-tiles strong{font-size:24px}.prof-shares,.prof-chart{padding:15px}.prof-legend{font-size:10px;gap:8px}.live-metrics{gap:6px}.live-metrics [data-slot=badge]{font-size:10px;padding:6px 8px}.history-dialog{padding:18px}}
+@media(max-height:600px){.chat-view.empty{justify-content:flex-start;padding-top:20px}.welcome-brand{margin-top:auto}.chat-view.empty .composer-wrap{margin-bottom:auto}}
+
+/* Markdown inside an assistant turn. The model writes fences, lists and links;
+ rendered as React nodes, never as HTML, so nothing here can inject markup. */
+.md>div>*:first-child{margin-top:0}
+.md>div>*:last-child{margin-bottom:0}
+.md p{margin:0 0 .75em}
+.md h2,.md h3,.md h4,.md h5{margin:1.1em 0 .5em;line-height:1.25;font-weight:600}
+.md h2{font-size:1.18em}.md h3{font-size:1.08em}.md h4{font-size:1em}.md h5{font-size:.95em;opacity:.85}
+.md ul,.md ol{margin:0 0 .75em;padding-left:1.35em}
+.md li{margin:.2em 0}
+.md li::marker{color:var(--primary)}
+.md a{color:var(--primary);text-underline-offset:2px}
+.md blockquote{margin:0 0 .75em;padding:.1em 0 .1em .85em;border-left:2px solid var(--primary);opacity:.9}
+.md hr{border:0;border-top:1px solid color-mix(in srgb,var(--foreground) 18%,transparent);margin:1.1em 0}
+.md :not(pre)>code{background:color-mix(in srgb,var(--foreground) 10%,transparent);padding:.12em .36em;border-radius:.35em;font-size:.92em}
+.md-code{margin:0 0 .85em;border:1px solid color-mix(in srgb,var(--foreground) 14%,transparent);border-radius:.6em;overflow:hidden;background:color-mix(in srgb,var(--foreground) 5%,transparent)}
+.md-code figcaption{display:flex;align-items:center;justify-content:space-between;gap:.5em;padding:.35em .5em .35em .75em;font-size:.78em;letter-spacing:.04em;text-transform:uppercase;opacity:.7;border-bottom:1px solid color-mix(in srgb,var(--foreground) 12%,transparent)}
+.md-code figcaption button{display:inline-flex;align-items:center;justify-content:center;width:1.9em;height:1.9em;border-radius:.4em;color:inherit;opacity:.8}
+.md-code figcaption button:hover{opacity:1;background:color-mix(in srgb,var(--foreground) 10%,transparent)}
+.md-code figcaption svg{width:.95em;height:.95em}
+.md-code pre{margin:0;padding:.75em .85em;overflow-x:auto}
+.md-code code{font-size:.9em;line-height:1.55;white-space:pre}
+
+
+/* Attached pictures: thumbnails while composing, full width once sent. */
+.composer-attachments{display:flex;flex-wrap:wrap;gap:.5rem;padding:.6rem .75rem 0}
+.attachment{position:relative;display:inline-flex}
+.attachment img{width:64px;height:64px;object-fit:cover;border-radius:.5rem;border:1px solid color-mix(in srgb,var(--foreground) 16%,transparent)}
+.attachment button{position:absolute;top:-6px;right:-6px;display:inline-flex;align-items:center;justify-content:center;width:1.25rem;height:1.25rem;border-radius:50%;background:var(--card);border:1px solid color-mix(in srgb,var(--foreground) 22%,transparent);color:inherit}
+.attachment button svg{width:.7rem;height:.7rem}
+.attach-chip{display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;border-radius:.6rem;color:inherit;opacity:.75}
+.attach-chip:hover{opacity:1;background:color-mix(in srgb,var(--foreground) 10%,transparent)}
+.attach-chip svg{width:1.05rem;height:1.05rem}
+.message-images{display:flex;flex-wrap:wrap;gap:.5rem;margin:0 0 .5rem}
+.message-images img{max-width:min(320px,100%);border-radius:.6rem;border:1px solid color-mix(in srgb,var(--foreground) 14%,transparent)}
+
+/* ---- modalita brio -------------------------------------------------------
+ Una colonna sola: il documento in alto, le opzioni comuni, poi le domande
+ una sotto l'altra con la propria risposta sotto. La forma segue il motivo
+ per cui la modalita esiste: il documento si legge una volta e le domande
+ sono tante, quindi il documento sta in cima e le domande si accumulano. */
+.brio-page{max-width:1080px;margin:0 auto;display:grid;gap:14px}
+.brio-card{background:var(--card);border-radius:20px;padding:22px 24px}
+.brio-card h2{font-size:14px;font-weight:500;margin:0}
+.brio-card textarea,.brio-card input{width:100%;display:block;background:var(--input);border:1px solid transparent;border-radius:14px;padding:11px 14px;font:inherit;font-size:13px;line-height:1.6;color:var(--foreground);outline:none;resize:vertical}
+.brio-card textarea::placeholder,.brio-card input::placeholder{color:var(--muted-foreground)}
+.brio-card textarea:focus,.brio-card input:focus{border-color:color-mix(in srgb,var(--foreground) 25%,transparent)}
+
+.brio-doc-head{display:flex;align-items:center;gap:12px;margin-bottom:14px}
+.brio-doc-head h2{margin-right:auto}
+.brio-doc-head button{display:inline-flex;align-items:center;gap:7px;border:1px solid var(--border);border-radius:20px;background:none;color:var(--muted-foreground);font-size:11px;padding:7px 13px}
+.brio-doc-head button:hover{color:var(--foreground);border-color:color-mix(in srgb,var(--foreground) 30%,transparent)}
+.brio-doc-head svg{width:14px;height:14px}
+.brio-meta{margin:10px 0 0;font-size:11px;color:var(--muted-foreground)}
+.brio-meta b{color:var(--foreground);font-weight:400}
+
+.brio-shared h2{margin-bottom:12px}
+.brio-chips{display:flex;flex-wrap:wrap;gap:7px;margin-top:11px}
+.brio-chips button{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--border);border-radius:20px;background:none;color:var(--muted-foreground);font-size:11px;padding:5px 9px 5px 12px}
+.brio-chips button:hover{color:var(--foreground);border-color:color-mix(in srgb,var(--foreground) 30%,transparent)}
+.brio-chips svg{width:12px;height:12px}
+
+.brio-questions{display:grid;gap:12px}
+.brio-q-head{display:flex;align-items:center;gap:11px}
+.brio-num{width:24px;height:24px;flex-shrink:0;display:grid;place-items:center;border-radius:50%;background:var(--secondary);color:var(--muted-foreground);font-size:11px;font-variant-numeric:tabular-nums}
+.brio-q-head input{font-size:14px}
+.brio-drop{width:30px;height:30px;flex-shrink:0;display:grid;place-items:center;border:0;border-radius:9px;background:none;color:var(--muted-foreground)}
+.brio-drop:hover{background:var(--secondary);color:var(--foreground)}
+.brio-drop svg{width:15px;height:15px}
+.brio-own{margin-top:10px;font-size:12px!important;padding:9px 14px!important;line-height:1.7}
+.brio-warn{margin:8px 0 0;font-size:11px;color:#e0b062}
+
+.brio-running{display:flex;align-items:center;gap:9px;margin:16px 0 0;font-size:12px;color:var(--muted-foreground)}
+.brio-running svg{width:15px;height:15px}
+.brio-spin{animation:brio-turn 1s linear infinite}
+@keyframes brio-turn{to{transform:rotate(360deg)}}
+
+.brio-answer{margin-top:18px;padding-top:16px;border-top:1px solid var(--border)}
+.brio-bars{display:grid;gap:2px}
+.brio-bar{display:grid;grid-template-columns:minmax(0,11rem) minmax(0,1fr) 4.4rem;align-items:center;gap:14px;padding:6px 0}
+.brio-name{font-size:13px;color:var(--muted-foreground);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.brio-bar.top .brio-name{color:var(--foreground)}
+.brio-track{height:8px;border-radius:5px;background:var(--secondary);overflow:hidden}
+.brio-fill{display:block;height:100%;border-radius:5px;background:color-mix(in srgb,var(--foreground) 22%,transparent);transition:width .35s ease}
+.brio-bar.top .brio-fill{background:var(--primary)}
+.brio-pct{text-align:right;font:400 15px ui-sans-serif,system-ui,sans-serif;letter-spacing:-.3px;font-variant-numeric:tabular-nums}
+.brio-pct i{font-style:normal;font-size:10px;color:var(--muted-foreground);margin-left:1px}
+
+.brio-foot{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 14px;margin-top:14px}
+.brio-foot strong{font:450 21px ui-sans-serif,system-ui,sans-serif;letter-spacing:-.5px}
+.brio-foot[data-level=sure] strong{color:var(--primary)}
+.brio-foot[data-level=unsure] strong{color:#e0b062}
+.brio-foot[data-level=unknown] strong{color:var(--muted-foreground)}
+.brio-foot span{font-size:11px;color:var(--muted-foreground)}
+.brio-foot em{margin-left:auto;font-style:normal;font-size:11px;color:var(--muted-foreground)}
+.brio-foot em b{color:var(--primary);font-weight:400}
+
+.brio-actions{display:flex;gap:11px;align-items:center;margin-top:2px}
+.brio-add{display:inline-flex;align-items:center;gap:8px;border:1px dashed var(--border);border-radius:26px;background:none;color:var(--muted-foreground);font-size:12px;padding:13px 18px}
+.brio-add:hover{color:var(--foreground);border-color:color-mix(in srgb,var(--foreground) 30%,transparent)}
+.brio-add svg{width:15px;height:15px}
+.brio-run{flex:1;display:flex;align-items:center;justify-content:center;gap:9px;border:0;border-radius:26px;padding:14px;font-size:13px;background:var(--primary);color:var(--primary-foreground)}
+.brio-run svg{width:16px;height:16px}
+.brio-note,.brio-error{font-size:11px;line-height:1.6;margin:12px 0 0;color:var(--muted-foreground)}
+.brio-error{color:var(--destructive,#ff766f)}
+
+@media(max-width:760px){
+ .brio-card{padding:17px;border-radius:17px}
+ .brio-bar{grid-template-columns:minmax(0,7rem) minmax(0,1fr) 3.8rem;gap:10px}
+ .brio-foot em{margin-left:0;flex-basis:100%}
+ .brio-actions{flex-wrap:wrap}
+ .brio-add,.brio-run{flex:1 1 100%;justify-content:center}
+ .brio-card textarea,.brio-card input{font-size:16px}
+}
diff --git a/web/src/components/Brand.tsx b/web/src/components/Brand.tsx
new file mode 100644
index 00000000..2a9269bf
--- /dev/null
+++ b/web/src/components/Brand.tsx
@@ -0,0 +1,26 @@
+/** Original pixel mark from site/index.html; wordmark uses its Bytesized font.
+ *
+ * I colori sono quelli di assets/colibri-icon.svg, non inventati qui: e la
+ * stessa griglia (translate(7 21), celle da 14) quindi le due immagini non
+ * possono divergere per svista. Lo sfondo arrotondato di quel file NON viene
+ * riportato: qui il marchio sta sulla superficie dell'app, che ha gia la sua.
+ *
+ * Le tinte sono fisse e non seguono currentColor: sono sature abbastanza da
+ * reggere sia sul tema scuro sia sul chiaro. La parola accanto invece resta
+ * in currentColor, cosi segue il tema come il resto del testo. */
+export function Brand({ word = false }: { word?: boolean }) {
+ return <span className={word ? "colibri-brand full" : "colibri-brand"} aria-label="colibrì">
+ <svg viewBox="0 21 168 126" aria-hidden="true" stroke="none"><g shapeRendering="crispEdges" stroke="none" transform="translate(7 21)">
+<rect height="14" width="14" x="56" y="0" fill="#d75fd7"></rect><rect height="14" width="14" x="70" y="0" fill="#d75fd7"></rect><rect height="14" width="14" x="84" y="0" fill="#d75fd7"></rect>
+<rect height="14" width="14" x="42" y="14" fill="#d75fd7"></rect><rect height="14" width="14" x="56" y="14" fill="#d75fd7"></rect><rect height="14" width="14" x="70" y="14" fill="#d75fd7"></rect><rect height="14" width="14" x="84" y="14" fill="#d75fd7"></rect><rect height="14" width="14" x="98" y="14" fill="#d75fd7"></rect><rect height="14" width="14" x="140" y="14" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="56" y="28" fill="#d75fd7"></rect><rect height="14" width="14" x="70" y="28" fill="#d75fd7"></rect><rect height="14" width="14" x="84" y="28" fill="#d75fd7"></rect><rect height="14" width="14" x="98" y="28" fill="#d75fd7"></rect><rect height="14" width="14" x="126" y="28" fill="#5fd7d7"></rect><rect height="14" width="14" x="140" y="28" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="0" y="42" fill="#ff8700"></rect><rect height="14" width="14" x="14" y="42" fill="#ff8700"></rect><rect height="14" width="14" x="28" y="42" fill="#ff8700"></rect><rect height="14" width="14" x="42" y="42" fill="#ff8700"></rect><rect height="14" width="14" x="56" y="42" fill="#00afaf"></rect><rect height="14" width="14" x="70" y="42" fill="#00afaf"></rect><rect height="14" width="14" x="84" y="42" fill="#fff"></rect><rect height="14" width="14" x="98" y="42" fill="#00afaf"></rect><rect height="14" width="14" x="112" y="42" fill="#5fd7d7"></rect><rect height="14" width="14" x="126" y="42" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="56" y="56" fill="#00afaf"></rect><rect height="14" width="14" x="70" y="56" fill="#00afaf"></rect><rect height="14" width="14" x="84" y="56" fill="#00afaf"></rect><rect height="14" width="14" x="98" y="56" fill="#00afaf"></rect><rect height="14" width="14" x="112" y="56" fill="#00afaf"></rect><rect height="14" width="14" x="126" y="56" fill="#5fd7d7"></rect><rect height="14" width="14" x="140" y="56" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="70" y="70" fill="#00afaf"></rect><rect height="14" width="14" x="84" y="70" fill="#00afaf"></rect><rect height="14" width="14" x="98" y="70" fill="#00afaf"></rect><rect height="14" width="14" x="112" y="70" fill="#00afaf"></rect><rect height="14" width="14" x="126" y="70" fill="#5fd7d7"></rect><rect height="14" width="14" x="140" y="70" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="84" y="84" fill="#00afaf"></rect><rect height="14" width="14" x="98" y="84" fill="#00afaf"></rect><rect height="14" width="14" x="112" y="84" fill="#5fd7d7"></rect><rect height="14" width="14" x="126" y="84" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="98" y="98" fill="#00afaf"></rect><rect height="14" width="14" x="112" y="98" fill="#5fd7d7"></rect>
+<rect height="14" width="14" x="112" y="112" fill="#5fd7d7"></rect>
+</g></svg>
+ {word && <span className="colibri-word">colibri</span>}
+ </span>
+}
diff --git a/web/src/components/Markdown.tsx b/web/src/components/Markdown.tsx
index 67a805c2..2b4b1bb1 100644
--- a/web/src/components/Markdown.tsx
+++ b/web/src/components/Markdown.tsx
@@ -1,97 +1,146 @@
+import { useState } from "react"
import { Check, Copy } from "lucide-react"
-import { useCallback, useMemo, useState } from "react"
-import { highlight, parseMarkdown, type Block, type Span } from "@/lib/markdown"
-/* Renders an assistant turn the way `coli chat`'s TUI already does: fenced code
- * in a labelled box, real bold, coloured inline code, headings and bullets, and
- * no marker ever visible.
+/* A small Markdown subset, rendered as React nodes rather than HTML.
*
- * Everything below builds React ELEMENTS. Nothing reaches innerHTML, so model
- * output cannot become markup no matter what it contains — the property that
- * makes this safe to point at an untrusted generation without a sanitiser.
+ * The text comes from a model, so nothing here ever reaches innerHTML: every
+ * piece of content ends up as a React text node, which escapes by construction.
+ * That rules out the whole class of "the model wrote a script tag" problems
+ * without a sanitiser to keep honest.
+ *
+ * Covered, because it is what a model actually emits in chat: fenced code with
+ * its language and a copy button, inline code, bold, italic, links, headings,
+ * ordered and unordered lists, blockquotes and horizontal rules. Not covered:
+ * tables, footnotes, raw HTML. Those degrade to the literal text instead of
+ * disappearing, which is the right failure for a reader.
*/
-function Inline({ spans }: { spans: Span[] }) {
- return (
- <>
- {spans.map((span, index) => {
- if (span.kind === "bold") return <strong key={index}>{span.text}</strong>
- if (span.kind === "code") return <code key={index} className="md-inline">{span.text}</code>
- return <span key={index}>{span.text}</span>
- })}
- </>
- )
+type Segment = { kind: "code"; lang: string; body: string } | { kind: "text"; body: string }
+
+/** Split on fenced blocks first: everything inside a fence is literal. */
+function segments(source: string): Segment[] {
+ const out: Segment[] = []
+ const fence = /```([^\n`]*)\n?([\s\S]*?)(?:```|$)/g
+ let last = 0
+ for (let match = fence.exec(source); match; match = fence.exec(source)) {
+ if (match.index > last) out.push({ kind: "text", body: source.slice(last, match.index) })
+ out.push({ kind: "code", lang: match[1].trim(), body: match[2].replace(/\n$/, "") })
+ last = fence.lastIndex
+ }
+ if (last < source.length) out.push({ kind: "text", body: source.slice(last) })
+ return out
+}
+
+/** Inline marks, innermost first so `**a *b* **` does not swallow its own stars. */
+function inline(text: string, key = "i"): React.ReactNode[] {
+ const pattern = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(\*[^*\n]+\*)|(\[[^\]\n]+\]\([^)\s]+\))/
+ const nodes: React.ReactNode[] = []
+ let rest = text
+ let index = 0
+ for (let match = pattern.exec(rest); match; match = pattern.exec(rest)) {
+ if (match.index > 0) nodes.push(rest.slice(0, match.index))
+ const token = match[0]
+ const id = `${key}-${index++}`
+ if (token.startsWith("`")) nodes.push(<code key={id}>{token.slice(1, -1)}</code>)
+ else if (token.startsWith("**")) nodes.push(<strong key={id}>{token.slice(2, -2)}</strong>)
+ else if (token.startsWith("*")) nodes.push(<em key={id}>{token.slice(1, -1)}</em>)
+ else {
+ const cut = token.indexOf("](")
+ const label = token.slice(1, cut)
+ const href = token.slice(cut + 2, -1)
+ const safe = /^(https?:|mailto:)/i.test(href)
+ nodes.push(safe
+ ? <a key={id} href={href} target="_blank" rel="noreferrer noopener">{label}</a>
+ : <span key={id}>{label}</span>)
+ }
+ rest = rest.slice(match.index + token.length)
+ }
+ if (rest) nodes.push(rest)
+ return nodes
}
-function CodeBlock({ lang, text, open }: { lang: string; text: string; open: boolean }) {
+function CodeBlock({ lang, body }: { lang: string; body: string }) {
const [copied, setCopied] = useState(false)
- const tokens = useMemo(() => highlight(text, lang), [text, lang])
+ const copy = async () => {
+ try {
+ await navigator.clipboard.writeText(body)
+ setCopied(true)
+ window.setTimeout(() => setCopied(false), 1200)
+ } catch { /* a denied clipboard is not worth an error state here */ }
+ }
+ return <figure className="md-code">
+ <figcaption>
+ <span>{lang || "text"}</span>
+ <button type="button" onClick={() => void copy()} aria-label="Copy code">
+ {copied ? <Check /> : <Copy />}
+ </button>
+ </figcaption>
+ <pre><code>{body}</code></pre>
+ </figure>
+}
- const copy = useCallback(() => {
- // Clipboard is unavailable over plain http on a non-localhost origin, which
- // is exactly how `coli web --host <lan-ip>` is used. Fail quietly to the
- // textarea path rather than throwing into the console.
- const done = () => { setCopied(true); window.setTimeout(() => setCopied(false), 1200) }
- if (navigator.clipboard?.writeText) {
- navigator.clipboard.writeText(text).then(done, () => undefined)
- return
- }
- const area = document.createElement("textarea")
- area.value = text
- area.setAttribute("readonly", "")
- area.style.position = "fixed"
- area.style.opacity = "0"
- document.body.appendChild(area)
- area.select()
- try { document.execCommand("copy"); done() } catch { /* nothing to do */ }
- document.body.removeChild(area)
- }, [text])
+/** One text segment: block structure, then inline marks inside each block. */
+function blocks(source: string, key: string): React.ReactNode[] {
+ const out: React.ReactNode[] = []
+ const lines = source.split("\n")
+ let paragraph: string[] = []
+ let list: { ordered: boolean; items: string[] } | null = null
+ let quote: string[] = []
+
+ const flushParagraph = () => {
+ if (!paragraph.length) return
+ out.push(<p key={`${key}-p${out.length}`}>{inline(paragraph.join(" "), `${key}-p${out.length}`)}</p>)
+ paragraph = []
+ }
+ const flushList = () => {
+ if (!list) return
+ const items = list.items.map((item, at) => <li key={at}>{inline(item, `${key}-li${at}`)}</li>)
+ out.push(list.ordered ? <ol key={`${key}-l${out.length}`}>{items}</ol>
+ : <ul key={`${key}-l${out.length}`}>{items}</ul>)
+ list = null
+ }
+ const flushQuote = () => {
+ if (!quote.length) return
+ out.push(<blockquote key={`${key}-q${out.length}`}>{inline(quote.join(" "), `${key}-q${out.length}`)}</blockquote>)
+ quote = []
+ }
+ const flushAll = () => { flushParagraph(); flushList(); flushQuote() }
+
+ for (const line of lines) {
+ const heading = /^(#{1,4})\s+(.*)$/.exec(line)
+ const bullet = /^\s*[-*+]\s+(.*)$/.exec(line)
+ const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line)
+ const quoted = /^>\s?(.*)$/.exec(line)
- return (
- <div className="md-code">
- <div className="md-code-head">
- <span>{lang || "code"}</span>
- <button type="button" onClick={copy} aria-label={copied ? "Copied" : "Copy code"}>
- {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
- </button>
- </div>
- <pre>
- <code>
- {tokens.map((token, index) =>
- token.kind === "plain"
- ? <span key={index}>{token.text}</span>
- : <span key={index} className={`tok-${token.kind}`}>{token.text}</span>,
- )}
- {/* An unclosed fence means the answer is still arriving inside it.
- A caret says "more is coming" instead of leaving the box looking
- finished and truncated. */}
- {open ? <span className="md-caret" /> : null}
- </code>
- </pre>
- </div>
- )
+ if (!line.trim()) { flushAll(); continue }
+ if (/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/.test(line)) { flushAll(); out.push(<hr key={`${key}-hr${out.length}`} />); continue }
+ if (heading) {
+ flushAll()
+ const level = heading[1].length
+ const Tag = (["h2", "h3", "h4", "h5"][level - 1] || "h5") as "h2"
+ out.push(<Tag key={`${key}-h${out.length}`}>{inline(heading[2], `${key}-h${out.length}`)}</Tag>)
+ continue
+ }
+ if (quoted) { flushParagraph(); flushList(); quote.push(quoted[1]); continue }
+ if (bullet || numbered) {
+ flushParagraph(); flushQuote()
+ const ordered = Boolean(numbered)
+ const item = (numbered || bullet)![1]
+ if (!list || list.ordered !== ordered) { flushList(); list = { ordered, items: [] } }
+ list.items.push(item)
+ continue
+ }
+ flushList(); flushQuote()
+ paragraph.push(line.trim())
+ }
+ flushAll()
+ return out
}
-export function Markdown({ source }: { source: string }) {
- const blocks = useMemo<Block[]>(() => parseMarkdown(source), [source])
- return (
- <div className="md">
- {blocks.map((block, index) => {
- if (block.kind === "code")
- return <CodeBlock key={index} lang={block.lang} text={block.text} open={block.open} />
- if (block.kind === "h") {
- const Tag = (`h${Math.min(block.level + 2, 6)}`) as "h3" | "h4" | "h5" | "h6"
- return <Tag key={index} className="md-h"><Inline spans={block.spans} /></Tag>
- }
- if (block.kind === "li")
- return (
- <div key={index} className="md-li">
- <span className="md-bullet">{block.ordered ? "›" : "•"}</span>
- <span><Inline spans={block.spans} /></span>
- </div>
- )
- return <p key={index} className="md-p"><Inline spans={block.spans} /></p>
- })}
- </div>
- )
+export function Markdown({ text }: { text: string }) {
+ return <div className="md">
+ {segments(text).map((segment, at) => segment.kind === "code"
+ ? <CodeBlock key={at} lang={segment.lang} body={segment.body} />
+ : <div key={at}>{blocks(segment.body, `s${at}`)}</div>)}
+ </div>
}
diff --git a/web/src/components/NavigationDock.tsx b/web/src/components/NavigationDock.tsx
new file mode 100644
index 00000000..cdad0205
--- /dev/null
+++ b/web/src/components/NavigationDock.tsx
@@ -0,0 +1,45 @@
+import { useEffect, useRef, useState } from "react"
+import { BrainCircuit, Gauge, ListChecks, MessageSquareText } from "lucide-react"
+import { useLocale } from "../i18n"
+
+export type View = "chat" | "brio" | "brain" | "profiling" | "settings"
+
+export function NavigationDock({ view, onNavigate, loading }: { view: View; onNavigate: (view: View) => void; loading: boolean }) {
+ const { t } = useLocale()
+ const [open, setOpen] = useState(false)
+ const wrap = useRef<HTMLDivElement>(null)
+ const handle = useRef<HTMLButtonElement>(null)
+ const timer = useRef<ReturnType<typeof setTimeout>>()
+ const gesture = useRef<number | null>(null)
+ const swipe = useRef(false)
+ const pointerKind = useRef("mouse")
+ const close = (restore = false) => {
+ clearTimeout(timer.current)
+ if (restore || wrap.current?.contains(document.activeElement)) handle.current?.focus()
+ setOpen(false)
+ }
+ useEffect(() => {
+ const outside = (e: PointerEvent) => { if (!wrap.current?.contains(e.target as Node)) close() }
+ const escape = (e: KeyboardEvent) => { if (e.key === "Escape") close() }
+ document.addEventListener("pointerdown", outside)
+ document.addEventListener("keydown", escape)
+ return () => { clearTimeout(timer.current); document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", escape) }
+ }, [])
+ const reveal = () => { clearTimeout(timer.current); setOpen(true) }
+ const hideLater = () => {
+ clearTimeout(timer.current)
+ timer.current = setTimeout(() => { if (!wrap.current?.contains(document.activeElement)) close() }, 850)
+ }
+ return <div ref={wrap} className={`navigation-dock ${open ? "open" : ""}`} onPointerEnter={e => { if (e.pointerType === "mouse") reveal() }} onPointerLeave={hideLater} onBlur={hideLater}>
+ <nav id="workspace-navigation" aria-label={t("ui.navigation")} hidden={!open}>
+ {([{ id: "chat", Icon: MessageSquareText }, { id: "brio", Icon: ListChecks }, { id: "brain", Icon: BrainCircuit }, { id: "profiling", Icon: Gauge }] as const).map(({ id, Icon }) =>
+ <button key={id} aria-current={view === id ? "page" : undefined} onClick={() => { onNavigate(id); close(true) }}><Icon /><span>{t(`nav.${id}`)}</span>{id === "chat" && loading && <i className="dock-busy" />}</button>)}
+ </nav>
+ <button ref={handle} className="dock-handle" aria-label={t("ui.navigation")} aria-expanded={open} aria-controls="workspace-navigation"
+ onClick={e => { if (swipe.current && e.detail !== 0) { swipe.current = false; return }; if (e.detail === 0) { reveal(); requestAnimationFrame(() => wrap.current?.querySelector<HTMLButtonElement>("nav button")?.focus()) } else if (pointerKind.current === "mouse") reveal(); else setOpen(value => !value) }}
+ onPointerDown={e => { pointerKind.current = e.pointerType; gesture.current = e.clientY; swipe.current = false; e.currentTarget.setPointerCapture(e.pointerId) }}
+ onPointerMove={e => { if (e.pointerType === "mouse" && gesture.current === null) reveal(); if (gesture.current !== null && Math.abs(e.clientY - gesture.current) > 15) { swipe.current = true; setOpen(e.clientY > gesture.current) } }}
+ onPointerUp={e => { gesture.current = null; if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId) }}
+ onPointerCancel={() => { gesture.current = null; swipe.current = false }}><span /></button>
+ </div>
+}
diff --git a/web/src/components/ui/textarea.tsx b/web/src/components/ui/textarea.tsx
index 4c440481..89736077 100644
--- a/web/src/components/ui/textarea.tsx
+++ b/web/src/components/ui/textarea.tsx
@@ -2,14 +2,15 @@ import * as React from "react"
import { cn } from "@/lib/utils"
-function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentProps<"textarea">>(function Textarea({ className, ...props }, ref) {
return (
<textarea
+ ref={ref}
data-slot="textarea"
className={cn("min-h-20 w-full resize-none rounded-xl border border-border bg-transparent px-4 py-3 text-sm leading-6 outline-none placeholder:text-muted-foreground focus:border-primary/60", className)}
{...props}
/>
)
-}
+})
export { Textarea }
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 6cdfc3e8..73ca964c 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1,5 +1,114 @@
const en: Record<string, string> = {
+ "ui.settings": "Settings",
+ "ui.settingsIntro": "Your workspace, model and engine connection.",
+ "ui.general": "General",
+ "ui.model": "Model",
+ "ui.connection": "Connection",
+ "ui.system": "System",
+ "ui.appearance": "Appearance",
+ "ui.language": "Language",
+ "ui.dark": "Dark",
+ "ui.light": "Light",
+ "ui.newChat": "New chat",
+ "ui.search": "Search conversations",
+ "ui.history": "Conversations",
+ "ui.sidebar": "Sidebar",
+ "ui.theme": "Change theme",
+ "ui.navigation": "Chat, Brain and Profiling",
+ "ui.export": "Export conversation",
+ "ui.close": "Close",
+ "ui.idea": "Explore an idea",
+ "ui.code": "Write code",
+ "ui.analyze": "Analyze a problem",
+ "ui.generating": "Generating",
+ "ui.copy": "Copy response",
+ "ui.attachImage": "Attach an image",
+ "ui.removeImage": "Remove image",
+ "ui.attachedImage": "Attached image {n}",
+ "ui.copied": "Copied",
+ "ui.copyError": "Could not copy the text. Select the response to copy it.",
+ "ui.regenerate": "Regenerate response",
+ "ui.archived": "Archived conversation",
+ "ui.historyMemory": "Conversations are kept for this open session. Export a conversation to save it.",
+ "ui.explore": "Explore",
+ "ui.liveRouting": "Live routing",
+ "ui.enterModel": "Enter the model.",
+ "ui.tour": "Guided journey",
+ "ui.stopTour": "Stop journey",
+ "ui.topicsDetails": "Topics and details",
+ "ui.position": "Position in the map",
+ "ui.overview": "Overview",
+ "ui.cortexControls": "Explore the brain. Drag or use the arrow keys to rotate; plus and minus to zoom. Enter opens a region; Escape returns to the overview.",
+ "ui.atlasError": "The Expert Atlas could not be loaded.",
+ "ui.atlasLoading": "Loading the Expert Atlas…",
+ "ui.inside": "Inside the region",
+ "ui.topics": "topics",
+ "ui.chooseRegion": "Choose a region to explore.",
+ "ui.back": "Previous view",
+ "ui.zoomOut": "Zoom out",
+ "ui.zoomIn": "Zoom in",
+ "ui.resume": "Resume animation",
+ "ui.pause": "Pause animation",
+ "ui.atlasAffinities": "Atlas affinities",
+ "ui.regionExpert": "Expert in this region",
+ "ui.specialist": "Atlas specialist",
+ "ui.searchTopic": "Search topics",
+ "ui.sample": "in the exploration sample",
+ "ui.atlasNote": "GLM-5.2 atlas from the project. The shape, regions and connections are a visual metaphor. Open Live routing for engine activity.",
+ "topic.code_python": "Python",
+ "topic.code_python.description": "Algorithms, functions and Python programming.",
+ "topic.code_sql": "SQL",
+ "topic.code_sql.description": "Queries, table relationships and data retrieval.",
+ "topic.math_proof": "Mathematics",
+ "topic.math_proof.description": "Proofs, logical steps and mathematical reasoning.",
+ "topic.poetry": "Poetry",
+ "topic.poetry.description": "Verse, imagery and poetic writing.",
+ "topic.casual_chat": "Conversation",
+ "topic.casual_chat.description": "Everyday dialogue, questions and informal answers.",
+ "topic.json_format": "JSON",
+ "topic.json_format.description": "Structured data, schemas and JSON formatting.",
+ "topic.law": "Law",
+ "topic.law.description": "Texts and questions in the legal domain.",
+ "topic.medicine": "Medicine",
+ "topic.medicine.description": "Vocabulary and questions in the medical domain.",
+ "topic.chinese": "Chinese",
+ "topic.chinese.description": "Texts and requests in Chinese.",
+ "topic.german": "German",
+ "topic.german.description": "Texts and requests in German.",
// nav
+ "brio.ask": "The question",
+ "brio.answer": "Answer",
+ "brio.emptyTitle": "No answer yet",
+ "brio.removeOption": "remove this option",
+ "brio.time": "time",
+ "brio.offline": "The engine is unreachable: probe it from the settings.",
+ "brio.document": "Document",
+ "brio.documentPlaceholder": "Paste the text to decide on, or load a file.",
+ "brio.upload": "load a file",
+ "brio.chars": "characters",
+ "brio.onceHint": "read once: every question after the first costs far less",
+ "brio.fileBinary": "not a text file: PDF and Word are not supported yet",
+ "brio.addQuestion": "Add question",
+ "brio.removeQuestion": "remove this question",
+ "brio.ownOptions": "Allowed options for this question, one per line",
+ "brio.needTwo": "a second option is needed, on its own line",
+ "brio.scoreAll": "Answer {{n}}",
+ "nav.brio": "Brio",
+ "brio.sure": "confident",
+ "brio.unsure": "unsure",
+ "brio.unknown": "does not know",
+ "brio.state": "Context",
+ "brio.statePlaceholder": "The state to decide on: a pull request, a message, a case...",
+ "brio.question": "Question",
+ "brio.questionPlaceholder": "What should the reviewer do?",
+ "brio.options": "Allowed options (one per line)",
+ "brio.optionsPlaceholder": "merge\nrequest changes\nclose",
+ "brio.score": "Score the options",
+ "brio.scoring": "reading...",
+ "brio.entropy": "entropy",
+ "brio.readTokens": "tokens read",
+ "brio.generatedTokens": "generated",
+ "brio.hint": "The model writes nothing: it reads how likely each option is and answers with a number. High entropy means it does not know, which is the one thing a written answer cannot tell you.",
"nav.chat": "Chat",
"nav.brain": "Brain",
"nav.profiling": "Profiling",
@@ -47,11 +156,6 @@ const en: Record<string, string> = {
"sidebar.temperature": "Temperature",
"sidebar.maxTokens": "Max output tokens",
"sidebar.reasoning": "Reasoning",
- "sidebar.reasoning.off": "Off",
- "sidebar.reasoning.low": "Low",
- "sidebar.reasoning.medium": "Medium",
- "sidebar.reasoning.high": "High",
- "sidebar.reasoning.max": "Max",
"sidebar.transport": "OpenAI-compatible transport",
// top bar
@@ -77,8 +181,6 @@ const en: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "Message colibrì…",
"chat.inputHint": "Enter to send · Shift+Enter for newline",
- "chat.attachImage": "Attach an image",
- "chat.removeImage": "Remove image",
"chat.stop": "Stop generation",
"chat.send": "Send message",
diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts
index 2738f8a8..c41084ad 100644
--- a/web/src/i18n/index.ts
+++ b/web/src/i18n/index.ts
@@ -3,8 +3,8 @@ import { createElement } from "react"
import en from "./en"
import zhCN from "./zh-CN"
import zhTW from "./zh-TW"
-import it from "./it"
import de from "./de"
+import it from "./it"
const LOCALES = [
{ code: "en", label: "English" },
diff --git a/web/src/i18n/it.ts b/web/src/i18n/it.ts
index e6fba19b..5b1dd425 100644
--- a/web/src/i18n/it.ts
+++ b/web/src/i18n/it.ts
@@ -1,6 +1,115 @@
const it: Record<string, string> = {
+ "ui.settings": "Impostazioni",
+ "ui.settingsIntro": "Il tuo spazio, il modello e la connessione al motore.",
+ "ui.general": "Generale",
+ "ui.model": "Modello",
+ "ui.connection": "Connessione",
+ "ui.system": "Sistema",
+ "ui.appearance": "Aspetto",
+ "ui.language": "Lingua",
+ "ui.dark": "Scuro",
+ "ui.light": "Chiaro",
+ "ui.newChat": "Nuova chat",
+ "ui.search": "Cerca nelle conversazioni",
+ "ui.history": "Conversazioni",
+ "ui.sidebar": "Barra laterale",
+ "ui.theme": "Cambia tema",
+ "ui.navigation": "Chat, Brain e Profiling",
+ "ui.export": "Esporta conversazione",
+ "ui.close": "Chiudi",
+ "ui.idea": "Esplora un’idea",
+ "ui.code": "Scrivi codice",
+ "ui.analyze": "Analizza un problema",
+ "ui.generating": "Generazione in corso",
+ "ui.copy": "Copia risposta",
+ "ui.attachImage": "Allega un'immagine",
+ "ui.removeImage": "Togli l'immagine",
+ "ui.attachedImage": "Immagine allegata {n}",
+ "ui.copied": "Copiato",
+ "ui.copyError": "Non è stato possibile copiare il testo. Seleziona la risposta per copiarla.",
+ "ui.regenerate": "Rigenera risposta",
+ "ui.archived": "Conversazione archiviata",
+ "ui.historyMemory": "Le conversazioni rimangono disponibili durante questa apertura. Esporta una conversazione per salvarla.",
+ "ui.explore": "Esplora",
+ "ui.liveRouting": "Routing live",
+ "ui.enterModel": "Entra nel modello.",
+ "ui.tour": "Viaggio guidato",
+ "ui.stopTour": "Interrompi viaggio",
+ "ui.topicsDetails": "Argomenti e dettagli",
+ "ui.position": "Posizione nella mappa",
+ "ui.overview": "Panoramica",
+ "ui.cortexControls": "Esplora il cervello. Trascina o usa le frecce per ruotare; più e meno per lo zoom. Invio apre una regione; Escape torna alla panoramica.",
+ "ui.atlasError": "Non è stato possibile caricare l’Expert Atlas.",
+ "ui.atlasLoading": "Caricamento Expert Atlas…",
+ "ui.inside": "Dentro la regione",
+ "ui.topics": "argomenti",
+ "ui.chooseRegion": "Scegli una regione da esplorare.",
+ "ui.back": "Vista precedente",
+ "ui.zoomOut": "Allontanati",
+ "ui.zoomIn": "Avvicinati",
+ "ui.resume": "Riprendi animazione",
+ "ui.pause": "Pausa animazione",
+ "ui.atlasAffinities": "Affinità dall’atlante",
+ "ui.regionExpert": "Expert nella regione",
+ "ui.specialist": "Specialista nell’atlante",
+ "ui.searchTopic": "Cerca un argomento",
+ "ui.sample": "nel campione esplorativo",
+ "ui.atlasNote": "Atlante GLM-5.2 del progetto. Forma, regioni e connessioni sono una metafora visiva. Apri Routing live per l’attività del motore.",
+ "topic.code_python": "Python",
+ "topic.code_python.description": "Algoritmi, funzioni e programmazione Python.",
+ "topic.code_sql": "SQL",
+ "topic.code_sql.description": "Query, relazioni tra tabelle e interrogazione dei dati.",
+ "topic.math_proof": "Matematica",
+ "topic.math_proof.description": "Dimostrazioni, passaggi logici e ragionamento matematico.",
+ "topic.poetry": "Poesia",
+ "topic.poetry.description": "Versi, immagini e forme della scrittura poetica.",
+ "topic.casual_chat": "Conversazione",
+ "topic.casual_chat.description": "Dialogo quotidiano, domande e risposte informali.",
+ "topic.json_format": "JSON",
+ "topic.json_format.description": "Dati strutturati, schemi e formattazione JSON.",
+ "topic.law": "Diritto",
+ "topic.law.description": "Testi e quesiti appartenenti al dominio giuridico.",
+ "topic.medicine": "Medicina",
+ "topic.medicine.description": "Lessico e quesiti appartenenti al dominio medico.",
+ "topic.chinese": "Cinese",
+ "topic.chinese.description": "Testi e richieste in lingua cinese.",
+ "topic.german": "Tedesco",
+ "topic.german.description": "Testi e richieste in lingua tedesca.",
+ "brio.ask": "La domanda",
+ "brio.answer": "Risposta",
+ "brio.emptyTitle": "Nessuna risposta ancora",
+ "brio.removeOption": "togli questa opzione",
+ "brio.time": "tempo",
+ "brio.offline": "Il motore non risponde: sondalo dalle impostazioni.",
+ "brio.document": "Documento",
+ "brio.documentPlaceholder": "Incolla qui il testo su cui decidere, oppure carica un file.",
+ "brio.upload": "carica un file",
+ "brio.chars": "caratteri",
+ "brio.onceHint": "si legge una volta sola: le domande dopo la prima costano molto meno",
+ "brio.fileBinary": "file non testuale: PDF e Word non sono ancora supportati",
+ "brio.addQuestion": "Aggiungi domanda",
+ "brio.removeQuestion": "togli questa domanda",
+ "brio.ownOptions": "Opzioni ammesse per questa domanda, una per riga",
+ "brio.needTwo": "serve almeno una seconda opzione, separata da virgola o a capo",
+ "brio.scoreAll": "Rispondi a {{n}}",
+ "nav.brio": "Brio",
+ "brio.sure": "certo",
+ "brio.unsure": "incerto",
+ "brio.unknown": "non sa",
+ "brio.state": "Contesto",
+ "brio.statePlaceholder": "Lo stato su cui decidere: una PR, un messaggio, una pratica...",
+ "brio.question": "Domanda",
+ "brio.questionPlaceholder": "Cosa deve fare il revisore?",
+ "brio.options": "Opzioni ammesse (una per riga)",
+ "brio.optionsPlaceholder": "merge\nrequest changes\nclose",
+ "brio.score": "Assegna le probabilita",
+ "brio.scoring": "sto leggendo...",
+ "brio.entropy": "entropia",
+ "brio.readTokens": "token letti",
+ "brio.generatedTokens": "generati",
+ "brio.hint": "Il modello non genera testo: legge quanto e probabile ogni opzione e lo dice con un numero. Entropia alta vuol dire che non sa, ed e la cosa che una risposta scritta non sa dirti.",
"nav.chat": "Chat",
- "nav.brain": "Cervello",
+ "nav.brain": "Brain",
"nav.profiling": "Profiling",
"brand.tagline": "gigante locale, impronta minima",
@@ -41,11 +150,6 @@ const it: Record<string, string> = {
"sidebar.temperature": "Temperatura",
"sidebar.maxTokens": "Token di output massimi",
"sidebar.reasoning": "Ragionamento",
- "sidebar.reasoning.off": "Off",
- "sidebar.reasoning.low": "Basso",
- "sidebar.reasoning.medium": "Medio",
- "sidebar.reasoning.high": "Alto",
- "sidebar.reasoning.max": "Max",
"sidebar.transport": "Trasporto compatibile OpenAI",
"topbar.activeModel": "MODELLO ATTIVO",
@@ -66,10 +170,8 @@ const it: Record<string, string> = {
"chat.you": "Tu",
"chat.colibri": "colibrì",
- "chat.placeholder": "Scrivi a colibrì…",
+ "chat.placeholder": "Chiedi qualsiasi cosa",
"chat.inputHint": "Invio per inviare · Shift+Invio per andare a capo",
- "chat.attachImage": "Allega un'immagine",
- "chat.removeImage": "Togli l'immagine",
"chat.stop": "Ferma la generazione",
"chat.send": "Invia messaggio",
diff --git a/web/src/i18n/zh-CN.ts b/web/src/i18n/zh-CN.ts
index f9f55413..97de86af 100644
--- a/web/src/i18n/zh-CN.ts
+++ b/web/src/i18n/zh-CN.ts
@@ -41,11 +41,6 @@ const zhCN: Record<string, string> = {
"sidebar.temperature": "温度",
"sidebar.maxTokens": "最大输出 token 数",
"sidebar.reasoning": "推理模式",
- "sidebar.reasoning.off": "关闭",
- "sidebar.reasoning.low": "低",
- "sidebar.reasoning.medium": "中",
- "sidebar.reasoning.high": "高",
- "sidebar.reasoning.max": "最高",
"sidebar.transport": "OpenAI 兼容协议",
"topbar.activeModel": "当前模型",
@@ -68,8 +63,6 @@ const zhCN: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "给 colibrì 发消息…",
"chat.inputHint": "回车发送 · Shift+回车换行",
- "chat.attachImage": "添加图片",
- "chat.removeImage": "移除图片",
"chat.stop": "停止生成",
"chat.send": "发送消息",
diff --git a/web/src/i18n/zh-TW.ts b/web/src/i18n/zh-TW.ts
index 62fb2e48..c59fe94f 100644
--- a/web/src/i18n/zh-TW.ts
+++ b/web/src/i18n/zh-TW.ts
@@ -41,11 +41,6 @@ const zhTW: Record<string, string> = {
"sidebar.temperature": "溫度",
"sidebar.maxTokens": "最大輸出 token 數",
"sidebar.reasoning": "推理模式",
- "sidebar.reasoning.off": "關閉",
- "sidebar.reasoning.low": "低",
- "sidebar.reasoning.medium": "中",
- "sidebar.reasoning.high": "高",
- "sidebar.reasoning.max": "最高",
"sidebar.transport": "OpenAI 相容協定",
"topbar.activeModel": "目前模型",
@@ -68,8 +63,6 @@ const zhTW: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "傳送訊息給 colibrì…",
"chat.inputHint": "Enter 傳送 · Shift+Enter 換行",
- "chat.attachImage": "附加圖片",
- "chat.removeImage": "移除圖片",
"chat.stop": "停止生成",
"chat.send": "傳送訊息",
diff --git a/web/src/index.css b/web/src/index.css
index 0d0887d7..58c30e1a 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -79,16 +79,6 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
.suggestions { width: 100%; display: grid; grid-template-columns: repeat(3, 1fr); gap: 9px; margin-top: 38px; }.suggestions button { display: flex; justify-content: space-between; align-items: center; min-height: 62px; padding: 12px 14px; border: 1px solid var(--border); border-radius: 11px; color: #a5b0b4; background: rgba(13,18,21,.75); text-align: left; font-size: 11px; line-height: 1.4; transition: .2s; }.suggestions button:hover { border-color: rgba(78,214,165,.35); color: var(--foreground); transform: translateY(-2px); }
.message-list { width: min(820px, calc(100% - 48px)); margin: 0 auto; padding: 44px 0 20px; }
.message { display: grid; grid-template-columns: 34px minmax(0,1fr); gap: 14px; margin-bottom: 34px; }.avatar { display: grid; place-items: center; width: 31px; height: 31px; border: 1px solid var(--border); border-radius: 9px; color: #aeb8bc; background: var(--card); font-size: 11px; font-weight: 700; }.message.assistant .avatar { color: var(--primary); border-color: rgba(78,214,165,.25); background: rgba(78,214,165,.06); }.message-meta { height: 27px; color: #7f8c91; font-size: 10px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; }.message-body { color: #d8e0e2; font-size: 14px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }.message.user .message-body { color: #aeb9bd; }
-/* Reasoning models stream their thinking before the answer. It is folded away
- once the answer starts arriving (open={!item.content} in App.tsx), so a long
- chain of thought does not push the reply off the screen. */
-.reasoning { margin-bottom: 14px; border-left: 2px solid rgba(78,214,165,.28); padding-left: 12px; }
-.reasoning > summary { color: #7f8c91; font-size: 10px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; cursor: pointer; list-style: none; }
-.reasoning > summary::-webkit-details-marker { display: none; }
-.reasoning > summary::before { content: "\25B8 "; display: inline-block; transition: transform .15s; }
-.reasoning[open] > summary::before { transform: rotate(90deg); }
-.reasoning > summary:hover { color: #aeb9bd; }
-.reasoning-body { margin-top: 8px; color: #8d989c; font-size: 13px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
.typing { display: inline-flex; gap: 4px; padding-top: 6px; }.typing i { width: 5px; height: 5px; border-radius: 50%; background: var(--primary); animation: pulse 1.1s infinite; }.typing i:nth-child(2) { animation-delay: .15s; }.typing i:nth-child(3) { animation-delay: .3s; }
.composer-wrap { padding: 10px 32px 24px; background: linear-gradient(transparent, var(--background) 24%); }.composer { width: min(820px, 100%); margin: 0 auto; overflow: hidden; border: 1px solid #2a353a; border-radius: 15px; background: rgba(13,18,21,.94); box-shadow: 0 18px 55px rgba(0,0,0,.24); }.composer textarea { min-height: 74px; border: 0; }.composer-foot { display: flex; align-items: center; justify-content: space-between; padding: 0 9px 9px 15px; }.composer-foot > span { display: flex; align-items: center; gap: 6px; color: #56646a; font-size: 9px; }.error-banner { width: min(820px, 100%); margin: 0 auto 8px; padding: 9px 12px; border: 1px solid rgba(255,118,111,.25); border-radius: 9px; color: #ff9d98; background: rgba(255,118,111,.07); font-size: 11px; }
@keyframes pulse { 0%, 70%, 100% { opacity: .25; transform: translateY(0); } 35% { opacity: 1; transform: translateY(-3px); } }
@@ -200,47 +190,3 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
.prof-tiles { grid-template-columns: 1fr 1fr; }
.prof-charts { grid-template-columns: 1fr; }
}
-
-/* --- markdown in the chat pane -------------------------------------------
- * Matches what coli chat's TUI renders: fenced code in a labelled box, real
- * bold, coloured inline code, headings and bullets. The pane sets
- * white-space: pre-wrap for raw text; markdown blocks manage their own
- * whitespace, so .md resets it and the code block turns it back on. */
-.md { white-space: normal; }
-.md > * + * { margin-top: 10px; }
-.md-p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
-.md-h { margin: 0; color: var(--primary); font-weight: 700; font-size: 14px; letter-spacing: .01em; }
-.md-li { display: grid; grid-template-columns: 14px minmax(0,1fr); gap: 6px; white-space: pre-wrap; overflow-wrap: anywhere; }
-.md-bullet { color: var(--primary); line-height: 1.75; }
-.md-inline { padding: 1px 5px; border: 1px solid var(--border); border-radius: 5px; background: rgba(255,255,255,.04); color: #f0b429; font-size: 12.5px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
-
-.md-code { border: 1px solid var(--border); border-radius: 9px; background: rgba(0,0,0,.28); overflow: hidden; }
-.md-code-head { display: flex; align-items: center; justify-content: space-between; padding: 5px 10px; border-bottom: 1px solid var(--border); color: #7f8c91; font-size: 10px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; }
-.md-code-head button { display: grid; place-items: center; padding: 3px; border: 0; border-radius: 5px; background: transparent; color: #7f8c91; cursor: pointer; }
-.md-code-head button:hover { color: #d8e0e2; background: rgba(255,255,255,.06); }
-/* overflow-x on the pre, never on the page: a long line must scroll inside
- * its own box rather than widening the chat column. */
-.md-code pre { margin: 0; padding: 10px 12px; overflow-x: auto; }
-.md-code code { display: block; white-space: pre; color: #cfd8db; font-size: 12.5px; line-height: 1.6; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
-.tok-kw { color: #7aa2f7; }
-.tok-str { color: #9ece6a; }
-.tok-num { color: #ff9e64; }
-.tok-com { color: #6b7780; font-style: italic; }
-.md-caret { display: inline-block; width: 7px; height: 13px; margin-left: 1px; background: var(--primary); opacity: .75; animation: md-blink 1s steps(2) infinite; vertical-align: text-bottom; }
-@keyframes md-blink { 50% { opacity: 0; } }
-
-/* Anteprime delle immagini allegate al messaggio in scrittura. Piccole di
- proposito: servono a ricordare cosa si sta mandando, non a guardarle. */
-.attachments { display: flex; flex-wrap: wrap; gap: .4rem; padding: .4rem .1rem 0; }
-.attachment { position: relative; display: inline-flex; }
-.attachment img {
- width: 3rem; height: 3rem; object-fit: cover; border-radius: .375rem;
- border: 1px solid hsl(var(--border));
-}
-.attachment button {
- position: absolute; top: -.35rem; right: -.35rem; width: 1.15rem; height: 1.15rem;
- line-height: 1; border-radius: 999px; border: 1px solid hsl(var(--border));
- background: hsl(var(--background)); color: hsl(var(--muted-foreground));
- font-size: .7rem; cursor: pointer;
-}
-.attachment button:hover { color: hsl(var(--foreground)); }
diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.ts
index 5fcb5321..e08ee85c 100644
--- a/web/src/lib/api.test.ts
+++ b/web/src/lib/api.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest"
-import { extractSSE, getHealth, getProfile, serverEndpoint, streamChat } from "./api"
+import { askBrio, extractSSE, getHealth, getProfile, serverEndpoint, streamChat } from "./api"
afterEach(() => vi.unstubAllGlobals())
@@ -56,9 +56,7 @@ describe("chat request extensions", () => {
headers: { "content-type": "text/event-stream" },
})
- async function requestBody(
- extra: { cacheSlot?: number; enableThinking?: boolean; reasoningEffort?: string } = {},
- ) {
+ async function requestBody(cacheSlot?: number) {
const fetchMock = vi.fn().mockResolvedValue(completedStream())
vi.stubGlobal("fetch", fetchMock)
await streamChat({
@@ -68,9 +66,8 @@ describe("chat request extensions", () => {
messages: [],
temperature: 0,
maxTokens: 8,
- enableThinking: extra.enableThinking ?? false,
- reasoningEffort: extra.reasoningEffort,
- cacheSlot: extra.cacheSlot,
+ enableThinking: false,
+ cacheSlot,
signal: new AbortController().signal,
onDelta: () => undefined,
})
@@ -82,17 +79,37 @@ describe("chat request extensions", () => {
})
it("sends cache_slot zero when colibrì advertises KV slots", async () => {
- expect(await requestBody({ cacheSlot: 0 })).toMatchObject({ cache_slot: 0 })
+ expect(await requestBody(0)).toMatchObject({ cache_slot: 0 })
})
+})
- it("sends reasoning_effort when reasoning is on", async () => {
- expect(await requestBody({ enableThinking: true, reasoningEffort: "high" }))
- .toMatchObject({ enable_thinking: true, reasoning_effort: "high" })
+describe("askBrio", () => {
+ /* The options must travel as a field, never folded into the prompt: keeping
+ them out of the text is half of what the mode saves, and a refactor that
+ "helpfully" appended them would be invisible in the answer. */
+ it("sends the options as data and posts to the brio endpoint", async () => {
+ const seen: { url?: string; body?: unknown } = {}
+ vi.stubGlobal("fetch", vi.fn(async (url: string, init: RequestInit) => {
+ seen.url = url
+ seen.body = JSON.parse(String(init.body))
+ return new Response(JSON.stringify({
+ answer: "b", entropy: 0.5, normalize: "mean",
+ choices: [{ option: "b", p: 0.7, logprob: -1, mean_logprob: -1, tokens: 1 }],
+ usage: { prompt_tokens: 9, completion_tokens: 0, read_tokens: 2, total_tokens: 11 },
+ }), { status: 200, headers: { "Content-Type": "application/json" } })
+ }))
+ const out = await askBrio("http://x/v1", "", "m", "state", "q?", ["a", "b"])
+ expect(seen.url).toBe("http://x/v1/brio")
+ expect(seen.body).toMatchObject({ model: "m", state: "state", question: "q?", options: ["a", "b"] })
+ expect(out.answer).toBe("b")
+ expect(out.usage.completion_tokens).toBe(0)
})
- it("omits reasoning_effort when reasoning is off, even if a level is passed", async () => {
- const body = await requestBody({ enableThinking: false, reasoningEffort: "high" })
- expect(body).toMatchObject({ enable_thinking: false })
- expect(body).not.toHaveProperty("reasoning_effort")
+ it("surfaces the server's own message instead of a bare status", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(
+ JSON.stringify({ error: { message: "options must be a non-empty array" } }),
+ { status: 400, headers: { "Content-Type": "application/json" } })))
+ await expect(askBrio("http://x/v1", "", "m", "s", "q", ["a"]))
+ .rejects.toThrow("options must be a non-empty array")
})
})
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 3c17b316..b6ed33a6 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -4,15 +4,10 @@ export interface ChatMessage {
id: string
role: ChatRole
content: string
- /* Immagini allegate al turno, come data: URI. Restano sul messaggio e non
- dentro `content` perche' la cronologia le deve poter rimandare al server
- insieme al testo: un secondo turno che parla della foto senza la foto
- riceverebbe una risposta su niente. */
+ /* Data URIs of the pictures attached to this turn. Kept on the message rather
+ than on the draft, because the transcript is resent on every later turn and
+ the model has to keep seeing what it was shown. */
images?: string[]
- /* Reasoning models stream their thinking on a separate delta field before
- the answer. Kept apart from `content` so it can be rendered as its own
- block and excluded from what is sent back as conversation history. */
- reasoning?: string
}
interface OpenAIError {
@@ -152,14 +147,9 @@ export interface StreamChatOptions {
temperature: number
maxTokens: number
enableThinking: boolean
- /* GLM reasoning depth when enableThinking is on: low | medium | high | xhigh.
- The server maps it onto the model's own words (Low/Medium/High/Max); when
- absent it keeps the server default, so a plain on/off client still works. */
- reasoningEffort?: string
cacheSlot?: number
signal: AbortSignal
onDelta: (text: string) => void
- onReasoning?: (text: string) => void
}
export async function streamChat(options: StreamChatOptions): Promise<StreamChatResult> {
@@ -169,24 +159,18 @@ export async function streamChat(options: StreamChatOptions): Promise<StreamChat
signal: options.signal,
body: JSON.stringify({
model: options.model,
- /* Un turno con immagini viaggia nella forma a parti dell'API OpenAI;
- senza, resta la stringa di sempre e nessun server vede una differenza. */
- messages: options.messages.map(({ role, content, images }) =>
- images && images.length
- ? {
- role,
- content: [
- ...(content ? [{ type: "text", text: content }] : []),
- ...images.map((url) => ({ type: "image_url", image_url: { url } })),
- ],
- }
- : { role, content },
- ),
+ /* A turn with pictures goes out in the content-array form the API takes;
+ a plain turn stays a string, so a text-only server sees exactly what it
+ saw before this existed. */
+ messages: options.messages.map(({ role, content, images }) => images?.length
+ ? { role, content: [
+ ...(content ? [{ type: "text", text: content }] : []),
+ ...images.map(url => ({ type: "image_url", image_url: { url } })),
+ ] }
+ : { role, content }),
temperature: options.temperature,
max_completion_tokens: options.maxTokens,
enable_thinking: options.enableThinking,
- ...(options.enableThinking && options.reasoningEffort
- ? { reasoning_effort: options.reasoningEffort } : {}),
...(options.cacheSlot === undefined ? {} : { cache_slot: options.cacheSlot }),
stream: true,
stream_options: { include_usage: true },
@@ -204,14 +188,12 @@ export async function streamChat(options: StreamChatOptions): Promise<StreamChat
const consume = (data: string) => {
if (data === "[DONE]") return
const event = JSON.parse(data) as {
- choices?: Array<{ delta?: { content?: string; reasoning_content?: string }; finish_reason?: string | null }>
+ choices?: Array<{ delta?: { content?: string }; finish_reason?: string | null }>
usage?: TokenUsage | null
}
const choice = event.choices?.[0]
const text = choice?.delta?.content
if (text) options.onDelta(text)
- const reasoning = choice?.delta?.reasoning_content
- if (reasoning) options.onReasoning?.(reasoning)
if (choice?.finish_reason) finishReason = choice.finish_reason
if (event.usage) usage = event.usage
}
@@ -234,3 +216,42 @@ export async function streamChat(options: StreamChatOptions): Promise<StreamChat
queueWaitMs: parsedQueueWait !== null && Number.isFinite(parsedQueueWait) ? parsedQueueWait : null,
}
}
+
+/* Modalita brio: il modello non genera, assegna una probabilita a ogni opzione
+ * ammessa. Il ciclo (fotografia del prefisso condiviso, una lettura per
+ * opzione, normalizzazione per lunghezza) sta nel gateway: qui si manda una
+ * richiesta e si riceve una distribuzione. */
+export interface BrioChoice {
+ option: string
+ p: number
+ logprob: number
+ mean_logprob: number
+ tokens: number
+}
+
+export interface BrioResponse {
+ answer: string
+ entropy: number
+ normalize: "mean" | "sum"
+ choices: BrioChoice[]
+ usage: { prompt_tokens: number; completion_tokens: number; read_tokens: number; total_tokens: number }
+}
+
+export async function askBrio(
+ baseUrl: string,
+ apiKey: string,
+ model: string,
+ state: string,
+ question: string,
+ options: string[],
+ signal?: AbortSignal,
+): Promise<BrioResponse> {
+ const response = await fetch(endpoint(baseUrl, "brio"), {
+ method: "POST",
+ headers: headers(apiKey),
+ body: JSON.stringify({ model, state, question, options }),
+ signal,
+ })
+ if (!response.ok) throw new Error(await responseError(response))
+ return (await response.json()) as BrioResponse
+}
diff --git a/web/src/lib/brain-topics.ts b/web/src/lib/brain-topics.ts
new file mode 100644
index 00000000..615d105c
--- /dev/null
+++ b/web/src/lib/brain-topics.ts
@@ -0,0 +1,82 @@
+export const brainTopics = [
+ {
+ "key": "code_python",
+ "center": [
+ -0.57,
+ -0.25,
+ 0.36
+ ]
+ },
+ {
+ "key": "code_sql",
+ "center": [
+ -0.6,
+ 0.26,
+ 0.2
+ ]
+ },
+ {
+ "key": "math_proof",
+ "center": [
+ 0.53,
+ -0.27,
+ 0.38
+ ]
+ },
+ {
+ "key": "poetry",
+ "center": [
+ 0.61,
+ -0.25,
+ -0.36
+ ]
+ },
+ {
+ "key": "casual_chat",
+ "center": [
+ -0.51,
+ -0.18,
+ -0.52
+ ]
+ },
+ {
+ "key": "json_format",
+ "center": [
+ -0.39,
+ 0.3,
+ -0.47
+ ]
+ },
+ {
+ "key": "law",
+ "center": [
+ 0.46,
+ 0.24,
+ 0.1
+ ]
+ },
+ {
+ "key": "medicine",
+ "center": [
+ 0.59,
+ 0.23,
+ -0.36
+ ]
+ },
+ {
+ "key": "chinese",
+ "center": [
+ -0.36,
+ -0.48,
+ -0.1
+ ]
+ },
+ {
+ "key": "german",
+ "center": [
+ 0.32,
+ -0.48,
+ -0.03
+ ]
+ }
+]
diff --git a/web/src/lib/cortex.ts b/web/src/lib/cortex.ts
new file mode 100644
index 00000000..28017ca0
--- /dev/null
+++ b/web/src/lib/cortex.ts
@@ -0,0 +1,97 @@
+export interface Vec { x:number; y:number; z:number }
+export interface Camera extends Vec { distance:number; yaw:number; pitch:number }
+export interface Topic { key:string; center:number[]; count:number }
+export interface AtlasEntry { affinity:Record<string,number>; top:string; label:string; entropy:number }
+export interface CortexNode extends Vec, AtlasEntry { id:string; index:number; layer:number; expert:number; topic:string }
+interface Projected extends Vec { depth:number; scale:number }
+export interface ProjectedNode extends CortexNode { depth:number; scale:number }
+export const initialCamera:Camera={x:0,y:0,z:0,distance:3.65,yaw:.14,pitch:.87};
+const cortexVertices: (Vec & { shade: number })[] = [], cortexFaces: number[][] = [];
+// Two folded hemispheres separated by a narrow fissure. This is a visual metaphor.
+for(const side of [-1,1]){
+ const offset=cortexVertices.length,rows=68,cols=46;
+ for(let i=0;i<=rows;i++)for(let j=0;j<=cols;j++){
+ const a=.025+(Math.PI-.05)*i/rows,b=-Math.PI/2+Math.PI*j/cols,sa=Math.sin(a),ca=Math.cos(a),sb=Math.sin(b),cb=Math.cos(b);
+ const fold=.055*Math.sin(9*a+2.1*Math.sin(3*b))+.024*Math.sin(9*b+3*Math.cos(5*a));
+ const x=side*(.058+(.98+fold)*sa*cb),y=((sb<0?.78:.56)+fold)*sa*sb-.035*ca,z=(1.10+fold)*ca;
+ cortexVertices.push({x,y,z,shade:.5+.28*Math.sin(9*a+2.1*Math.sin(3*b))+.13*Math.sin(9*b+3*Math.cos(5*a))});
+ }
+ for(let i=0;i<rows;i++)for(let j=0;j<cols;j++){
+ const a=offset+i*(cols+1)+j;cortexFaces.push([a,a+1,a+cols+2,a+cols+1]);
+ }
+}
+
+export function createCortex(canvas:HTMLCanvasElement, topics:Topic[], expertNodes:CortexNode[], onLabels:(nodes:ProjectedNode[])=>void) {
+ const motion=matchMedia('(prefers-reduced-motion: reduce)');
+ const brain:{cam:Camera;paused:boolean;time:number;level:number;topic:string|null;selected:number|null;projected:(ProjectedNode|null)[];shellCache?:{key:string;canvas:HTMLCanvasElement}}={cam:{...initialCamera},paused:motion.matches,time:0,level:0,topic:null,selected:null,projected:[]};
+ let frame=0,last=0,lastLabels=0,disposed=false;
+ let tween:{from:Camera;to:Camera;start:number}|null=null;
+ function request(){if(!disposed && !document.hidden && !frame)frame=requestAnimationFrame(tick)}
+ function tick(time:number){
+ frame=0;if(disposed||document.hidden)return;
+ if(!brain.paused)brain.time+=last?Math.min(40,time-last):0;last=time;
+ if(tween){const t=Math.min(1,(time-tween.start)/1250),ease=1-Math.pow(1-t,3);for(const key of Object.keys(initialCamera) as (keyof Camera)[])brain.cam[key]=tween.from[key]+(tween.to[key]-tween.from[key])*ease;if(t>=1)tween=null}
+ drawBrain();if(!brain.paused||tween)request();
+ }
+function drawBrain(){
+ const box=canvas.getBoundingClientRect(),w=box.width,h=box.height;if(!w||!h)return;
+ const dpr=Math.min(devicePixelRatio||1,2);if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr)}
+ const ctx=canvas.getContext('2d');if(!ctx)return;ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,w,h);
+ const cam=brain.cam,focal=Math.min(w*1.08,h*1.2),cx=w/2,cy=h*.43,cosY=Math.cos(cam.yaw),sinY=Math.sin(cam.yaw),cosP=Math.cos(cam.pitch),sinP=Math.sin(cam.pitch);
+ function project(v: Vec){const dx=v.x-cam.x,dy=v.y-cam.y,dz=v.z-cam.z,x=dx*cosY+dz*sinY,z0=-dx*sinY+dz*cosY,y=dy*cosP-z0*sinP,z=dy*sinP+z0*cosP,depth=cam.distance-z;if(depth<.06)return null;const scale=focal/depth;return {x:cx+x*scale,y:cy+y*scale,z,depth,scale}}
+ const shellOpacity=Math.max(0,Math.min(1,(cam.distance-1.05)/2.1));
+ const glow=ctx.createRadialGradient(cx,cy,0,cx,cy,w*.6);glow.addColorStop(0,'rgba(91,148,114,.055)');glow.addColorStop(1,'rgba(91,148,114,0)');ctx.fillStyle=glow;ctx.fillRect(0,0,w,h);
+ if(shellOpacity>.005){
+ const cacheKey=[w,h,dpr,...Object.values(cam)].join(',');
+ if(!brain.shellCache||brain.shellCache.key!==cacheKey){
+ const surface=brain.shellCache?.canvas||document.createElement('canvas');if(surface.width!==canvas.width||surface.height!==canvas.height){surface.width=canvas.width;surface.height=canvas.height}const surfaceCtx=surface.getContext('2d');if(!surfaceCtx)return;surfaceCtx.setTransform(dpr,0,0,dpr,0,0);surfaceCtx.clearRect(0,0,w,h);
+
+ const projected=cortexVertices.map(project),faces: {face:number[];points:Projected[];z:number}[]=[];
+ for(const face of cortexFaces){const points=face.map(i=>projected[i]).filter((p):p is Projected=>p!==null);if(points.length!==face.length)continue;const z=points.reduce((sum,p)=>sum+p.z,0)/4;faces.push({face,points,z})}
+ faces.sort((a,b)=>a.z-b.z);
+ for(const f of faces){const shade=f.face.reduce((s,i)=>s+cortexVertices[i].shade,0)/4,near=Math.max(.15,Math.min(1,(f.z+1.25)/2.5)),lum=Math.round(30+shade*68+near*13);surfaceCtx.beginPath();f.points.forEach((p,i)=>i?surfaceCtx.lineTo(p.x,p.y):surfaceCtx.moveTo(p.x,p.y));surfaceCtx.closePath();surfaceCtx.fillStyle=`rgba(${lum*.8|0},${lum+16},${lum+3},${shellOpacity})`;surfaceCtx.fill();surfaceCtx.strokeStyle=`rgba(146,185,161,${(.012+shade*.025)*shellOpacity})`;surfaceCtx.lineWidth=.45;surfaceCtx.stroke()}
+ // Fine cortical ridges and the central fissure make the outer form readable.
+ for(let i=0;i<projected.length;i+=2){const p=projected[i];if(!p||p.z<-.2)continue;surfaceCtx.beginPath();surfaceCtx.arc(p.x,p.y,.6,0,Math.PI*2);surfaceCtx.fillStyle=`rgba(173,205,184,${.16*shellOpacity})`;surfaceCtx.fill()}
+ brain.shellCache={key:cacheKey,canvas:surface};
+ }
+ ctx.drawImage(brain.shellCache!.canvas,0,0,w,h);
+ }
+ brain.projected=expertNodes.map(n=>{const p=project(n);return p?{...n,...p}:null});
+ const topicFocused=brain.topic;
+ // Illustrative paths connect nearby sample experts; they are not recorded routes.
+ for(let i=0;i<expertNodes.length;i++){
+ const a=brain.projected[i];if(!a)continue;
+ const inTopic=a.topic===topicFocused,opacity=brain.level?(inTopic?.19:.018):.055;
+ if(a.depth<.10)continue;
+ for(const jump of [1,7]){const group=Math.floor(i/36)*36,b=brain.projected[group+(i%36+jump)%36];if(!b||b.depth<.10)continue;ctx.beginPath();ctx.moveTo(a.x,a.y);const mx=(a.x+b.x)/2,my=(a.y+b.y)/2+Math.sin(i)*Math.min(24,Math.abs(a.x-b.x)*.12);ctx.quadraticCurveTo(mx,my,b.x,b.y);ctx.strokeStyle=`rgba(151,206,170,${opacity})`;ctx.lineWidth=inTopic?.85:.55;ctx.stroke();if(inTopic&&jump===1&&i%4===0){const t=(brain.time*.00010+i*.13)%1,px=(1-t)*(1-t)*a.x+2*(1-t)*t*mx+t*t*b.x,py=(1-t)*(1-t)*a.y+2*(1-t)*t*my+t*t*b.y;ctx.beginPath();ctx.arc(px,py,1.6,0,Math.PI*2);ctx.fillStyle='rgba(192,231,204,.7)';ctx.fill()}}
+ }
+ const visible=brain.projected.filter((p):p is ProjectedNode=>p!==null).sort((a,b)=>a.z-b.z);
+ for(const n of visible){if(n.x<-30||n.x>w+30||n.y<-30||n.y>h+30)continue;const active=n.topic===topicFocused,selected=n.index===brain.selected,size=Math.max(.7,Math.min(selected?6:4.1,(selected?.008:active?.0045:.0026)*n.scale)),alpha=brain.level?(active?.86:.1):.42;if(selected||active&&n.index%5===0){ctx.beginPath();ctx.arc(n.x,n.y,size*3.6,0,Math.PI*2);ctx.fillStyle=`rgba(159,216,183,${selected?.10:.035})`;ctx.fill()}ctx.beginPath();ctx.arc(n.x,n.y,size,0,Math.PI*2);ctx.fillStyle=`rgba(${selected?'220,242,227':active?'175,220,190':'128,177,146'},${alpha})`;ctx.fill();if(selected){ctx.beginPath();ctx.arc(n.x,n.y,size+4,0,Math.PI*2);ctx.strokeStyle='rgba(193,229,206,.55)';ctx.lineWidth=.7;ctx.stroke()}}
+ if(brain.level===0){
+ topics.forEach((topic,i)=>{
+ const p=project({x:topic.center[0],y:topic.center[1],z:topic.center[2]});if(!p)return;const left=i<5,labelW=w<480?80:w<650?92:120,x=left?labelW:w-labelW,y=h*(.18+(i%5)*.105)+16;
+ ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(left?x+12:x-12,y);ctx.lineTo(p.x,p.y);ctx.strokeStyle='rgba(164,198,177,.20)';ctx.lineWidth=.7;ctx.stroke();ctx.beginPath();ctx.arc(p.x,p.y,3,0,Math.PI*2);ctx.fillStyle='#99bca5';ctx.fill();
+ });
+ }
+
+ const occupied: { x: number; y: number }[] = [];
+ const labels = brain.projected.filter((n): n is ProjectedNode => !!n && n.topic === brain.topic && n.x > 40 && n.x < w-40 && n.y > 115 && n.y < h-170).sort((a,b)=>Number(b.index===brain.selected)-Number(a.index===brain.selected)||a.depth-b.depth).filter(n=>{
+ if(occupied.length>=6 || occupied.some(p=>Math.abs(p.x-n.x)<90 && Math.abs(p.y-n.y)<38))return false;
+ occupied.push(n);return true;
+ });
+ if (performance.now()-lastLabels>100 || brain.paused) { onLabels(brain.level && cam.distance<1.5 ? labels : []); lastLabels=performance.now(); }
+}
+
+ const resize=new ResizeObserver(request);resize.observe(canvas);
+ const visibility=()=>{cancelAnimationFrame(frame);frame=0;last=0;if(!document.hidden)request()};
+ const change=()=>{brain.paused=motion.matches;if(motion.matches&&tween){brain.cam={...tween.to};tween=null}request()};
+ document.addEventListener('visibilitychange',visibility);motion.addEventListener('change',change);request();
+ return {
+ move(to:Camera,level:number,topic:string|null,selected:number|null){brain.level=level;brain.topic=topic;brain.selected=selected;if(motion.matches){brain.cam={...to};tween=null}else tween={from:{...brain.cam},to,start:performance.now()};lastLabels=0;request()},
+ rotate(x:number,y:number){tween=null;brain.cam.yaw+=x;brain.cam.pitch=Math.max(-1.1,Math.min(1.1,brain.cam.pitch+y));request()},
+ zoom(delta:number){tween=null;brain.cam.distance=Math.max(.25,Math.min(4.4,brain.cam.distance+delta));request()},
+ pause(value:boolean){brain.paused=value;request()},
+ closest(x:number,y:number){return brain.projected.filter((n):n is ProjectedNode=>!!n&&n.topic===brain.topic&&Math.hypot(n.x-x,n.y-y)<22).sort((a,b)=>Math.hypot(a.x-x,a.y-y)-Math.hypot(b.x-x,b.y-y))[0]},
+ dispose(){disposed=true;cancelAnimationFrame(frame);resize.disconnect();document.removeEventListener('visibilitychange',visibility);motion.removeEventListener('change',change)}
+ }
+}
diff --git a/web/src/lib/markdown.test.ts b/web/src/lib/markdown.test.ts
deleted file mode 100644
index a8c63c78..00000000
--- a/web/src/lib/markdown.test.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { highlight, parseInline, parseMarkdown, type Block } from "./markdown"
-
-const kinds = (blocks: Block[]) => blocks.map((b) => b.kind)
-
-describe("parseInline", () => {
- it("hides the markers, not the text", () => {
- expect(parseInline("a **b** c")).toEqual([
- { kind: "text", text: "a " },
- { kind: "bold", text: "b" },
- { kind: "text", text: " c" },
- ])
- expect(parseInline("run `make check` now")).toEqual([
- { kind: "text", text: "run " },
- { kind: "code", text: "make check" },
- { kind: "text", text: " now" },
- ])
- })
-
- it("leaves a single asterisk alone", () => {
- // 3 * 4, a glob, a footnote. The TUI makes the same call for the same
- // reason: emphasis with one asterisk is rarer than multiplication.
- expect(parseInline("3 * 4 = 12")).toEqual([{ kind: "text", text: "3 * 4 = 12" }])
- })
-
- it("does not swallow the line on an unterminated marker", () => {
- // Mid-stream the model has typed the opening backtick and not the closing
- // one. Eating the rest of the line into a code span would make the answer
- // visibly lurch as the next chunk arrives.
- expect(parseInline("an unclosed ` backtick")).toEqual([
- { kind: "text", text: "an unclosed ` backtick" },
- ])
- expect(parseInline("an unclosed ** bold")).toEqual([
- { kind: "text", text: "an unclosed ** bold" },
- ])
- })
-})
-
-describe("parseMarkdown", () => {
- it("recognises the shapes the TUI recognises", () => {
- const md = [
- "# Title",
- "",
- "Some **prose**.",
- "",
- "- one",
- "- two",
- "1. first",
- "",
- "```python",
- "def f():",
- " return 1",
- "```",
- "",
- "after",
- ].join("\n")
- expect(kinds(parseMarkdown(md))).toEqual(["h", "p", "li", "li", "li", "code", "p"])
- })
-
- it("keeps fenced text verbatim and records the language", () => {
- const blocks = parseMarkdown("```python\nx = '# not a heading'\n```")
- expect(blocks).toHaveLength(1)
- const block = blocks[0]
- if (block.kind !== "code") throw new Error("expected a code block")
- expect(block.lang).toBe("python")
- expect(block.text).toBe("x = '# not a heading'")
- expect(block.open).toBe(false)
- })
-
- it("treats an unclosed fence as open to the end", () => {
- // THE streaming case: the answer stops inside the code block. Leaving the
- // fence unrecognised would print ``` into the prose and render the code as
- // a paragraph, then reflow it when the closing fence arrives.
- const blocks = parseMarkdown("intro\n\n```c\nint main(void) {")
- expect(kinds(blocks)).toEqual(["p", "code"])
- const block = blocks[1]
- if (block.kind !== "code") throw new Error("expected a code block")
- expect(block.open).toBe(true)
- expect(block.text).toBe("int main(void) {")
- })
-
- it("does not interpret markdown inside code", () => {
- const blocks = parseMarkdown("```\n**not bold** and `not code`\n```")
- const block = blocks[0]
- if (block.kind !== "code") throw new Error("expected a code block")
- expect(block.text).toBe("**not bold** and `not code`")
- })
-
- it("survives an empty string and a bare fence", () => {
- expect(parseMarkdown("")).toEqual([])
- expect(kinds(parseMarkdown("```"))).toEqual(["code"])
- })
-})
-
-describe("highlight", () => {
- it("classifies keywords, strings, numbers and comments", () => {
- const toks = highlight('def f():\n return "x" # note\n', "python")
- const of = (k: string) => toks.filter((t) => t.kind === k).map((t) => t.text)
- expect(of("kw")).toContain("def")
- expect(of("kw")).toContain("return")
- expect(of("str")).toContain('"x"')
- expect(of("com")).toContain("# note")
- })
-
- it("uses the language's own comment marker", () => {
- // '#' opens a comment in python and is an operator nowhere in C; getting
- // this wrong paints half a C file grey.
- expect(highlight("int x = 1; // c", "c").some((t) => t.kind === "com" && t.text === "// c")).toBe(true)
- expect(highlight("#include <stdio.h>", "c").some((t) => t.kind === "com")).toBe(false)
- expect(highlight("# a python comment", "python").some((t) => t.kind === "com")).toBe(true)
- })
-
- it("stops an unterminated string at the newline", () => {
- // Mid-stream code is full of these. Painting the rest of the block as a
- // string would make every subsequent line change colour as it arrives.
- const toks = highlight('s = "open\nnext = 1\n', "python")
- const str = toks.find((t) => t.kind === "str")
- expect(str?.text).toBe('"open')
- expect(toks.some((t) => t.kind === "num" && t.text === "1")).toBe(true)
- })
-
- it("leaves an unknown language plain rather than guessing", () => {
- const toks = highlight("def f(): pass", "brainfuck")
- expect(toks.every((t) => t.kind !== "kw")).toBe(true)
- })
-
- it("is lossless: the concatenated tokens are the input", () => {
- // The property that matters most. A highlighter that drops or duplicates a
- // character corrupts the code the user is about to copy.
- for (const [src, lang] of [
- ['def f():\n return "a" # c\n', "python"],
- ["int main(void) { /* x */ return 0; }", "c"],
- ["let x = `t${1}`; // y", "ts"],
- ["", "python"],
- ["no language here", ""],
- ] as const) {
- expect(highlight(src, lang).map((t) => t.text).join("")).toBe(src)
- }
- })
-})
diff --git a/web/src/lib/markdown.ts b/web/src/lib/markdown.ts
deleted file mode 100644
index 8c0e4426..00000000
--- a/web/src/lib/markdown.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-/* Markdown for the chat pane, matching what `coli chat`'s TUI already renders.
- *
- * The TUI (c/coli, class MD) turns ``` into boxed blocks with a language label,
- * **x** into real bold, `x` into coloured inline code, # into headings and "- "
- * into real bullets, and never shows a marker. The web pane showed the raw
- * string: every asterisk, backtick and hash literal, and code as one grey
- * paragraph. This closes that gap.
- *
- * WHY THIS IS PARSED RATHER THAN PULLED IN
- *
- * react-markdown would do it, and brings the whole unified/remark tree with it —
- * roughly forty transitive packages to render bold text, in a project whose six
- * dependencies are all small utilities. It also renders through HTML, which for
- * model output is an XSS surface we would then have to sanitise. The renderer
- * that consumes this builds React elements instead, so untrusted output cannot
- * become markup by construction.
- *
- * STREAMING
- *
- * The TUI holds back partial markers because it writes to a terminal it cannot
- * take back. React re-renders from the accumulated string every chunk, so that
- * problem does not exist here — but an UNCLOSED fence does: mid-stream the text
- * ends inside a code block. `parseMarkdown` treats a fence with no closing pair
- * as open to the end, which is what the user is actually looking at, rather than
- * leaking ``` into the prose.
- */
-
-export type Span =
- | { kind: "text"; text: string }
- | { kind: "bold"; text: string }
- | { kind: "code"; text: string }
-
-export type Block =
- | { kind: "p"; spans: Span[] }
- | { kind: "h"; level: number; spans: Span[] }
- | { kind: "li"; spans: Span[]; ordered: boolean }
- | { kind: "code"; lang: string; text: string; open: boolean }
-
-const FENCE = /^\s*```/
-
-/** Inline: **bold** and `code`. Single * is left alone — it is multiplication,
- * a glob, or a footnote far more often than it is emphasis, and the TUI makes
- * the same call for the same reason. */
-export function parseInline(line: string): Span[] {
- const spans: Span[] = []
- let text = ""
- let i = 0
- const flush = () => {
- if (text) { spans.push({ kind: "text", text }); text = "" }
- }
- while (i < line.length) {
- const ch = line[i]
- if (ch === "`") {
- const end = line.indexOf("`", i + 1)
- if (end > i) {
- flush()
- spans.push({ kind: "code", text: line.slice(i + 1, end) })
- i = end + 1
- continue
- }
- // unterminated: a backtick the model has not closed yet. Show it as text
- // rather than swallowing the rest of the line into a code span.
- text += ch; i++; continue
- }
- if (ch === "*" && line[i + 1] === "*") {
- const end = line.indexOf("**", i + 2)
- if (end > i + 1) {
- flush()
- spans.push({ kind: "bold", text: line.slice(i + 2, end) })
- i = end + 2
- continue
- }
- text += "**"; i += 2; continue
- }
- text += ch; i++
- }
- flush()
- return spans
-}
-
-export function parseMarkdown(source: string): Block[] {
- const lines = source.split("\n")
- const blocks: Block[] = []
- let code: { lang: string; body: string[] } | null = null
- let para: string[] = []
-
- const flushPara = () => {
- if (!para.length) return
- blocks.push({ kind: "p", spans: parseInline(para.join("\n")) })
- para = []
- }
-
- for (const line of lines) {
- if (FENCE.test(line)) {
- if (code) {
- blocks.push({ kind: "code", lang: code.lang, text: code.body.join("\n"), open: false })
- code = null
- } else {
- flushPara()
- code = { lang: line.trim().slice(3).trim().replace(/`/g, ""), body: [] }
- }
- continue
- }
- if (code) { code.body.push(line); continue }
-
- const trimmed = line.trim()
- if (!trimmed) { flushPara(); continue }
-
- const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed)
- if (heading) {
- flushPara()
- blocks.push({ kind: "h", level: heading[1].length, spans: parseInline(heading[2]) })
- continue
- }
- const bullet = /^[-*+]\s+(.*)$/.exec(trimmed)
- if (bullet) {
- flushPara()
- blocks.push({ kind: "li", spans: parseInline(bullet[1]), ordered: false })
- continue
- }
- const numbered = /^\d+[.)]\s+(.*)$/.exec(trimmed)
- if (numbered) {
- flushPara()
- blocks.push({ kind: "li", spans: parseInline(numbered[1]), ordered: true })
- continue
- }
- para.push(line)
- }
-
- // Mid-stream the answer ends inside the fence it has not closed yet. Emit it
- // as an open code block: that is what the user is looking at, and it keeps the
- // ``` out of the prose.
- if (code) blocks.push({ kind: "code", lang: code.lang, text: code.body.join("\n"), open: true })
- flushPara()
- return blocks
-}
-
-/* ---- syntax highlighting -------------------------------------------------
- *
- * Deliberately approximate, and small. A real grammar per language is what
- * highlight.js is for, and it is 100 KB+ for the set people actually paste.
- * Comments, strings, numbers and keywords carry nearly all the readability, so
- * that is what this does; anything it cannot classify stays plain, which
- * degrades to "unhighlighted code" rather than to "wrong colours".
- */
-
-export type Tok = { kind: "plain" | "kw" | "str" | "num" | "com"; text: string }
-
-const KEYWORDS: Record<string, string[]> = {
- python: "def class return if elif else for while in not and or is None True False import from as with try except finally raise lambda yield global nonlocal pass break continue assert del await async".split(" "),
- c: "int char void float double long short unsigned signed const static struct union enum typedef return if else for while do switch case break continue sizeof goto extern inline volatile".split(" "),
- rust: "fn let mut const struct enum impl trait pub use mod match if else for while loop return self Self where async await move ref dyn type unsafe".split(" "),
- go: "func var const type struct interface package import return if else for range switch case defer go chan map select break continue fallthrough".split(" "),
- js: "function const let var return if else for while class extends new this import export from default async await try catch finally throw typeof instanceof null undefined true false".split(" "),
- sh: "if then else elif fi for while do done case esac function return export local readonly set unset echo cd exit".split(" "),
-}
-KEYWORDS.cpp = KEYWORDS.c
-KEYWORDS.h = KEYWORDS.c
-KEYWORDS.typescript = KEYWORDS.js
-KEYWORDS.ts = KEYWORDS.js
-KEYWORDS.tsx = KEYWORDS.js
-KEYWORDS.javascript = KEYWORDS.js
-KEYWORDS.jsx = KEYWORDS.js
-KEYWORDS.py = KEYWORDS.python
-KEYWORDS.bash = KEYWORDS.sh
-KEYWORDS.shell = KEYWORDS.sh
-KEYWORDS.zsh = KEYWORDS.sh
-
-const LINE_COMMENT: Record<string, string> = {
- python: "#", py: "#", sh: "#", bash: "#", shell: "#", zsh: "#", yaml: "#", yml: "#", toml: "#",
-}
-
-export function highlight(text: string, lang: string): Tok[] {
- const key = (lang || "").toLowerCase()
- const words = KEYWORDS[key]
- const lineComment = LINE_COMMENT[key] ?? "//"
- const out: Tok[] = []
- let plain = ""
- const flush = () => { if (plain) { out.push({ kind: "plain", text: plain }); plain = "" } }
-
- let i = 0
- while (i < text.length) {
- const rest = text.slice(i)
-
- if (rest.startsWith(lineComment) || (lineComment === "//" && rest.startsWith("/*"))) {
- const end = rest.startsWith("/*")
- ? (text.indexOf("*/", i + 2) < 0 ? text.length : text.indexOf("*/", i + 2) + 2)
- : (text.indexOf("\n", i) < 0 ? text.length : text.indexOf("\n", i))
- flush(); out.push({ kind: "com", text: text.slice(i, end) }); i = end; continue
- }
-
- const q = text[i]
- if (q === '"' || q === "'" || q === "`") {
- let j = i + 1
- while (j < text.length && text[j] !== q) { if (text[j] === "\\") j++; j++ }
- // Unterminated string: stop at the newline rather than painting the rest
- // of the block. Mid-stream code is full of these.
- const nl = text.indexOf("\n", i)
- const end = j < text.length ? j + 1 : (nl < 0 ? text.length : nl)
- flush(); out.push({ kind: "str", text: text.slice(i, end) }); i = end; continue
- }
-
- if (/[0-9]/.test(q) && !/[A-Za-z_]/.test(text[i - 1] || "")) {
- let j = i
- while (j < text.length && /[0-9a-fA-FxXoObB._]/.test(text[j])) j++
- flush(); out.push({ kind: "num", text: text.slice(i, j) }); i = j; continue
- }
-
- if (words && /[A-Za-z_]/.test(q)) {
- let j = i
- while (j < text.length && /[A-Za-z0-9_]/.test(text[j])) j++
- const word = text.slice(i, j)
- if (words.includes(word)) { flush(); out.push({ kind: "kw", text: word }); i = j; continue }
- plain += word; i = j; continue
- }
-
- plain += q; i++
- }
- flush()
- return out
-}
diff --git a/web/src/lib/reasoning.test.ts b/web/src/lib/reasoning.test.ts
deleted file mode 100644
index 65705b3f..00000000
--- a/web/src/lib/reasoning.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from "vitest"
-
-import { REASONING_EFFORT, modelForcesReasoning, reasoningLevelsFor } from "./reasoning"
-
-describe("modelForcesReasoning", () => {
- it("is true for GLM 5.3 ids and false otherwise", () => {
- expect(modelForcesReasoning("glm-5.3-flash-colibri")).toBe(true)
- expect(modelForcesReasoning("glm-5.2-colibri")).toBe(false)
- expect(modelForcesReasoning("qwen3.8-colibri")).toBe(false)
- })
-})
-
-describe("reasoningLevelsFor", () => {
- it("offers the full ladder (incl. off and medium) for non-forced models", () => {
- expect(reasoningLevelsFor("glm-5.2-colibri")).toEqual([
- "off",
- "low",
- "medium",
- "high",
- "max",
- ])
- })
-
- it("drops off and the redundant medium for GLM 5.3 (template is Low/High/Max)", () => {
- const levels = reasoningLevelsFor("glm-5.3-flash-colibri")
- expect(levels).toEqual(["low", "high", "max"])
- expect(levels).not.toContain("off")
- expect(levels).not.toContain("medium")
- })
-})
-
-describe("REASONING_EFFORT", () => {
- it("maps max onto the engine's xhigh effort", () => {
- expect(REASONING_EFFORT.max).toBe("xhigh")
- expect(REASONING_EFFORT.low).toBe("low")
- })
-})
diff --git a/web/src/lib/reasoning.ts b/web/src/lib/reasoning.ts
deleted file mode 100644
index 3c5bd386..00000000
--- a/web/src/lib/reasoning.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Reasoning depth for GLM. The engine renders enable_thinking + reasoning_effort;
- these levels map onto the words GLM understands (Low/Medium/High/Max), and "off"
- turns thinking off entirely. GLM 5.3 cannot disable reasoning, and its template
- exposes only Low/High/Max (it renders "medium" as High). So for 5.3 both "off" and
- the now-redundant "medium" are dropped -- mirroring the model's own constraint in
- the control instead of offering a level it silently collapses onto High. */
-export type ReasoningLevel = "off" | "low" | "medium" | "high" | "max"
-
-export const REASONING_EFFORT: Record<Exclude<ReasoningLevel, "off">, string> = {
- low: "low", medium: "medium", high: "high", max: "xhigh",
-}
-
-export const modelForcesReasoning = (model: string) => /5\.3/.test(model)
-
-export const reasoningLevelsFor = (model: string): ReasoningLevel[] =>
- modelForcesReasoning(model)
- ? ["low", "high", "max"]
- : ["off", "low", "medium", "high", "max"]
diff --git a/web/src/main.tsx b/web/src/main.tsx
index 894f4f43..8e775c45 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -4,6 +4,7 @@ import App from "./App"
import { ErrorBoundary } from "./ErrorBoundary"
import { LocaleProvider } from "./i18n"
import "./index.css"
+import "./chat-design.css"
createRoot(document.getElementById("root")!).render(
<ErrorBoundary>
diff --git a/web/tests/brio_ui.py b/web/tests/brio_ui.py
new file mode 100644
index 00000000..75c0a151
--- /dev/null
+++ b/web/tests/brio_ui.py
@@ -0,0 +1,70 @@
+"""La vista Brio: presente, raggiungibile, e non rompe la chat accanto."""
+import json, subprocess, sys, threading, time
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from playwright.sync_api import sync_playwright, expect
+
+DIST = Path(__file__).resolve().parent.parent / "dist"
+
+class H(SimpleHTTPRequestHandler):
+ def __init__(self, *a, **k): super().__init__(*a, directory=str(DIST), **k)
+ def log_message(self, *a): pass
+ def do_POST(self):
+ n = int(self.headers.get("Content-Length", 0)); self.rfile.read(n)
+ body = json.dumps({"answer":"request changes","entropy":0.121,"normalize":"mean",
+ "choices":[{"option":"request changes","p":0.974,"logprob":-0.25,"mean_logprob":-0.12,"tokens":2},
+ {"option":"merge","p":0.023,"logprob":-4.0,"mean_logprob":-4.0,"tokens":1}],
+ "usage":{"prompt_tokens":88,"completion_tokens":0,"read_tokens":4,"total_tokens":92}}).encode()
+ self.send_response(200); self.send_header("Content-Type","application/json")
+ self.send_header("Content-Length",str(len(body))); self.end_headers(); self.wfile.write(body)
+ def do_GET(self):
+ if self.path.startswith("/v1/models"):
+ b=json.dumps({"object":"list","data":[{"id":"m","object":"model","created":0,"owned_by":"c"}]}).encode()
+ self.send_response(200); self.send_header("Content-Type","application/json")
+ self.send_header("Content-Length",str(len(b))); self.end_headers(); self.wfile.write(b); return
+ if self.path.startswith("/health"):
+ b=json.dumps({"status":"ok"}).encode()
+ self.send_response(200); self.send_header("Content-Type","application/json")
+ self.send_header("Content-Length",str(len(b))); self.end_headers(); self.wfile.write(b); return
+ super().do_GET()
+
+srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
+threading.Thread(target=srv.serve_forever, daemon=True).start()
+base = f"http://127.0.0.1:{srv.server_address[1]}"
+errs = []
+with sync_playwright() as pw:
+ b = pw.chromium.launch()
+ pg = b.new_page(viewport={"width":1200,"height":800}, locale="en-US")
+ pg.on("pageerror", lambda e: errs.append(str(e)))
+ pg.set_default_timeout(10000)
+ pg.goto(base, wait_until="networkidle")
+ pg.wait_for_timeout(1200)
+ # the endpoint is derived from the page origin, so only the probe is needed
+ pg.get_by_role("button", name="Settings", exact=True).click()
+ pg.locator(".settings-tabs").get_by_role("button", name="Connection", exact=True).click()
+ pg.get_by_role("button", name="Probe server", exact=True).click()
+ expect(pg.locator(".settings-card .connection-state")).to_have_text("Engine reachable")
+
+ def navigate(name):
+ pg.locator(".dock-handle").click()
+ pg.locator(".navigation-dock nav").get_by_role("button", name=name, exact=True).click()
+
+ navigate("Brio")
+ pg.locator(".brio-card textarea").first.fill("The PR touches the engine and has no tests.")
+ pg.locator(".brio-q-head input").first.fill("What should the reviewer do?")
+ pg.locator(".brio-own").first.fill("merge\nrequest changes")
+ pg.locator(".brio-run").click()
+ expect(pg.locator(".brio-bar").first).to_be_visible(timeout=15000)
+ # the chat is still mounted, but it must not be on screen behind brio
+ expect(pg.locator(".chat-view .composer textarea")).to_be_hidden()
+ expect(pg.locator(".brio-foot strong")).to_have_text("request changes")
+ assert "0 generated" in pg.locator(".brio-foot em").inner_text()
+ # torno in chat: la bozza deve essere ancora li, e brio non smontato
+ navigate("Chat")
+ expect(pg.locator(".chat-view .composer textarea")).to_be_visible()
+ # and brio is still mounted behind it: a scoring run must survive the trip
+ assert pg.locator(".brio-bar").count() > 0, "brio was unmounted by going to chat"
+ assert not errs, errs[:2]
+ b.close()
+srv.shutdown()
+print("PASS: brio view reachable, scores, keeps its state behind the chat. No JavaScript errors.")
diff --git a/web/tests/ui_migration.py b/web/tests/ui_migration.py
new file mode 100644
index 00000000..996e9e48
--- /dev/null
+++ b/web/tests/ui_migration.py
@@ -0,0 +1,254 @@
+"""Browser regression check using a local, deterministic OpenAI-compatible fixture.
+
+Run `npm run build`, then `python3 tests/ui_migration.py` (requires Playwright
+and its Chromium browser). No model, API credentials or external server needed.
+"""
+import json
+import threading
+import time
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from playwright.sync_api import sync_playwright, expect
+
+ROOT = Path(__file__).resolve().parents[1]
+requests = []
+cancelled = threading.Event()
+health = {"status": "ok", "kv_slots": 2, "scheduler": {"active": 0, "capacity": 2, "queued": 0, "max_queue": 8, "completed": 12, "rejected": 0, "timed_out": 0, "cancelled": 0}, "tiers": {"vram": 12, "ram": 20, "disk": 30, "vram_gb": 1.2, "ram_gb": 2.3}, "hwinfo": {"cpu": "Fixture CPU", "cores": 8, "gpus": 1, "vram_total_gb": 24, "ram_total_gb": 64, "ram_avail_gb": 32}}
+turn = {"wall_s": 4, "prompt_tokens": 50, "completion_tokens": 20, "expert_disk_s": 2, "expert_wait_s": .5, "expert_matmul_s": 1, "attention_s": .6, "lm_head_s": .4, "forwards": 10}
+
+
+class Handler(SimpleHTTPRequestHandler):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, directory=str(ROOT / "dist"), **kwargs)
+
+ def log_message(self, *_):
+ pass
+
+ def response(self, data, status=200):
+ body = json.dumps(data).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ requests.append(("GET", self.path, self.headers.get("Authorization"), None))
+ if self.path == "/v1/models":
+ self.response({"data": [{"id": "fixture-model"}, {"id": "second-model"}]})
+ elif self.path == "/health":
+ self.response(health)
+ elif self.path == "/experts":
+ self.response({"rows": 3, "cols": 4, "map": "81823f404142808182000102", "hits": "0100", "seq": 1})
+ elif self.path == "/profile":
+ self.response({"seq": 1, "turns": [turn, {**turn, "wall_s": 5}]})
+ else:
+ super().do_GET()
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ requests.append(("POST", self.path, self.headers.get("Authorization"), body))
+ if body["messages"][-1]["content"] == "ERROR":
+ self.response({"error": {"message": "Fixture unavailable"}}, 503)
+ return
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("x-colibri-queue-wait-ms", "12")
+ self.end_headers()
+ slow = body["messages"][-1]["content"] == "SLOW"
+ try:
+ for value in (["Token "] * 80 if slow else ["Risposta ", "dal ", "server."]):
+ self.wfile.write(("data: " + json.dumps({"choices": [{"delta": {"content": value}}]}) + "\n\n").encode())
+ self.wfile.flush()
+ time.sleep(.08 if slow else .12)
+ self.wfile.write(("data: " + json.dumps({"choices": [{"delta": {}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 50, "completion_tokens": 20, "total_tokens": 70}}) + "\n\ndata: [DONE]\n\n").encode())
+ except (BrokenPipeError, ConnectionResetError):
+ cancelled.set()
+
+
+server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+threading.Thread(target=server.serve_forever, daemon=True).start()
+url = f"http://127.0.0.1:{server.server_port}"
+errors = []
+try:
+ with sync_playwright() as p:
+ browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
+ page = browser.new_page(viewport={"width": 1440, "height": 1000}, locale="it-IT", reduced_motion="reduce")
+ page.set_default_timeout(10000)
+ page.on("pageerror", lambda e: errors.append(str(e)))
+ page.goto(url)
+ expect(page.locator(".model-button")).to_contain_text("fixture-model")
+ page.evaluate("document.fonts.ready")
+ assert page.locator(".rail .colibri-word").count() == 0
+
+ def navigate(name):
+ page.locator(".dock-handle").click()
+ page.locator(".navigation-dock nav").get_by_role("button", name=name, exact=True).click()
+
+ def settings(category):
+ page.get_by_role("button", name="Impostazioni", exact=True).click()
+ page.locator(".settings-tabs").get_by_role("button", name=category, exact=True).click()
+
+ settings("Connessione")
+ expect(page.locator("#endpoint")).to_have_value(url + "/v1")
+ page.locator("#api-key").fill("test-only-key")
+ page.get_by_role("button", name="Sonda il server").click()
+ expect(page.locator(".settings-card .connection-state")).to_have_text("Motore raggiungibile")
+ assert page.evaluate("localStorage.getItem('colibri.apiKey')") is None
+ settings("Modello")
+ page.locator("#temperature").fill("0.4")
+ page.locator("#max-tokens").fill("512")
+ page.get_by_role("button", name="Ragionamento", exact=True).click()
+ navigate("Chat")
+ for width, height in [(1440, 1000), (1366, 768), (390, 844), (360, 640)]:
+ page.set_viewport_size({"width": width, "height": height})
+ page.evaluate("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))")
+ logo, box, tips = page.evaluate("['.welcome-brand','.composer','.suggestions'].map(s => document.querySelector(s).getBoundingClientRect().toJSON())")
+ page.screenshot(path=f"/tmp/colibri-integrated-layout-{width}.png")
+ assert logo["y"] + logo["height"] < box["y"]
+ assert box["y"] + box["height"] < tips["y"], (width, logo, box, tips)
+ assert tips["y"] + tips["height"] < height - 65
+ assert page.evaluate("document.documentElement.scrollWidth <= innerWidth")
+ page.set_viewport_size({"width": 1440, "height": 1000})
+ page.screenshot(path="/tmp/colibri-integrated-chat.png")
+ page.get_by_role("button", name="Esplora un’idea").click()
+ expect(page.locator("#draft")).not_to_be_empty()
+ page.locator("#draft").fill("Primo messaggio")
+ page.locator("#draft").press("Shift+Enter")
+ assert "\n" in page.locator("#draft").input_value()
+ page.locator("#draft").press("Enter")
+ expect(page.locator(".message.assistant .message-body")).to_have_text("Risposta dal server.")
+ expect(page.get_by_role("button", name="Invia messaggio")).to_be_visible()
+ body = [r[3] for r in requests if r[0] == "POST"][-1]
+ assert body["cache_slot"] == 0 and body["temperature"] == .4 and body["max_completion_tokens"] == 512 and body["enable_thinking"] is True
+ assert body["stream"] is True and body["stream_options"]["include_usage"] is True
+ assert [r for r in requests if r[0] == "POST"][-1][2] == "Bearer test-only-key"
+ assert page.locator(".composer").bounding_box()["y"] > 700
+ page.get_by_role("button", name="Rigenera risposta").click()
+ expect(page.get_by_role("button", name="Ferma la generazione")).to_be_visible()
+ expect(page.get_by_role("button", name="Invia messaggio")).to_be_visible()
+ assert page.locator(".message.user").count() == 1
+ with page.expect_download() as download:
+ page.get_by_role("button", name="Esporta conversazione").click()
+ data = json.loads(Path(download.value.path()).read_text())
+ assert data["messages"][-1]["content"] == "Risposta dal server."
+ page.screenshot(path="/tmp/colibri-integrated-conversation.png")
+ settings("Modello")
+ page.locator("#kv-slot").select_option("1")
+ navigate("Chat")
+ expect(page.locator(".welcome-brand")).to_be_visible()
+ page.locator("#draft").fill("Slot due")
+ page.locator("#draft").press("Enter")
+ expect(page.get_by_role("button", name="Invia messaggio")).to_be_visible()
+ assert [r[3] for r in requests if r[0] == "POST"][-1]["cache_slot"] == 1
+ settings("Modello")
+ page.locator("#kv-slot").select_option("0")
+ navigate("Chat")
+ expect(page.locator(".message.user")).to_have_text("Primo messaggio")
+ page.get_by_role("button", name="Nuova chat").click()
+ expect(page.locator(".welcome-brand")).to_be_visible()
+ page.get_by_role("button", name="Conversazioni", exact=True).click()
+ page.locator(".history-search input").fill("Primo")
+ page.locator(".history-results button").click()
+ expect(page.locator(".message.user")).to_have_text("Primo messaggio")
+ page.locator("#draft").fill("SLOW")
+ page.locator("#draft").press("Enter")
+ expect(page.locator(".message.assistant").last).to_contain_text("Token")
+ expect(page.get_by_role("button", name="Nuova chat")).to_be_disabled()
+ navigate("Profiling")
+ expect(page.locator(".prof-table tbody tr")).to_have_count(2)
+ page.screenshot(path="/tmp/colibri-integrated-profiling.png")
+ navigate("Chat")
+ page.get_by_role("button", name="Ferma la generazione").click()
+ expect(page.get_by_role("button", name="Invia messaggio")).to_be_visible()
+ assert cancelled.wait(3), "Stop must cancel the actual response stream"
+ page.locator("#draft").fill("ERROR")
+ page.locator("#draft").press("Enter")
+ expect(page.get_by_role("alert")).to_have_text("Fixture unavailable")
+ navigate("Brain")
+ expect(page.locator(".cortex-regions button")).to_have_count(10)
+ assert page.locator(".cortex-explorer canvas").bounding_box()["height"] == 1000
+ page.screenshot(path="/tmp/colibri-integrated-brain.png")
+ page.locator(".cortex-regions button").filter(has_text="Python").click()
+ expect(page.locator(".cortex-details")).to_be_visible()
+ page.get_by_label("Expert nella regione").select_option(index=15)
+ expect(page.locator(".cortex-affinities>div")).to_have_count(4)
+ import re
+ selected_label = page.get_by_label("Expert nella regione").locator("option:checked").inner_text()
+ layer, expert = re.findall(r"\d+", selected_label)
+ entry = json.loads((ROOT / "public/experts.json").read_text())["experts"][f"{layer}:{expert}"]
+ expected = [f"{v * 100:.1f}%" for _, v in sorted(entry["affinity"].items(), key=lambda item: -item[1])[:4]]
+ assert page.locator(".cortex-affinities>div>span>b").all_text_contents() == expected
+ page.screenshot(path="/tmp/colibri-integrated-expert.png")
+ page.locator(".cortex-details").get_by_role("button", name="Chiudi").click()
+ page.get_by_role("button", name="Routing live", exact=True).click()
+ expect(page.locator(".brain-head")).to_contain_text("3 layer × 4 expert")
+ assert any(r[1] == "/experts" and r[2] == "Bearer test-only-key" for r in requests)
+ settings("Sistema")
+ expect(page.locator(".settings-card")).to_contain_text("Fixture CPU")
+ settings("Generale")
+ page.get_by_role("button", name="Chiaro", exact=True).click()
+ expect(page.locator("html")).to_have_attribute("data-theme", "light")
+ page.locator(".language-field select").select_option("en")
+ # :visible, not just .page-heading h1 — since brio mode the workspace
+ # keeps more than one page mounted at a time (hidden, so a scoring run
+ # survives a trip to chat), so a bare heading selector matches several.
+ expect(page.locator(".page-heading h1:visible")).to_have_text("Settings")
+ mobile = browser.new_context(viewport={"width": 360, "height": 640}, has_touch=True, is_mobile=True, locale="it-IT", reduced_motion="reduce")
+ touch = mobile.new_page()
+ touch.on("pageerror", lambda e: errors.append(str(e)))
+ touch.goto(url)
+ touch.locator(".dock-handle").tap()
+ expect(touch.locator(".navigation-dock nav")).to_be_visible()
+ touch.locator(".navigation-dock nav").get_by_role("button", name="Brain", exact=True).tap()
+ expect(touch.locator(".navigation-dock nav")).to_be_hidden()
+ expect(touch.locator(".cortex-regions button")).to_have_count(10)
+ assert touch.locator(".cortex-explorer canvas").bounding_box()["height"] == 640
+ touch.screenshot(path="/tmp/colibri-integrated-mobile-brain.png")
+ touch.get_by_role("button", name="Argomenti e dettagli", exact=True).tap()
+ expect(touch.locator("#brain-details")).to_be_visible()
+ touch.get_by_label("Cerca un argomento").fill("Python")
+ touch.locator(".cortex-topic-list button").tap()
+ touch.get_by_label("Expert nella regione").select_option(index=4)
+ layer, expert = re.findall(r"\d+", touch.get_by_label("Expert nella regione").locator("option:checked").inner_text())
+ mobile_entry = json.loads((ROOT / "public/experts.json").read_text())["experts"][f"{layer}:{expert}"]
+ expect(touch.locator(".cortex-affinities>div")).to_have_count(min(4, len(mobile_entry["affinity"])))
+ touch.locator("#brain-details").get_by_role("button", name="Chiudi").tap()
+ touch.screenshot(path="/tmp/colibri-integrated-mobile-expert.png")
+ # Real touch swipe, then keyboard access to the same collapsed dock.
+ # The dock hangs from the TOP edge now, so the gesture that opens it is a
+ # pull DOWN. It used to sit at the bottom and open on a pull up; swiping
+ # away from the screen edge the dock is attached to is the same motion,
+ # mirrored.
+ handle = touch.locator(".dock-handle").bounding_box()
+ cdp = mobile.new_cdp_session(touch)
+ x, y = handle["x"] + handle["width"] / 2, handle["y"] + handle["height"] / 2
+ cdp.send("Input.dispatchTouchEvent", {"type": "touchStart", "touchPoints": [{"x": x, "y": y}]})
+ cdp.send("Input.dispatchTouchEvent", {"type": "touchMove", "touchPoints": [{"x": x, "y": y + 30}]})
+ cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})
+ expect(touch.locator(".navigation-dock nav")).to_be_visible()
+ touch.keyboard.press("Escape")
+ touch.locator(".dock-handle").focus()
+ touch.locator(".dock-handle").press("Enter")
+ expect(touch.locator(".navigation-dock nav button").first).to_be_focused()
+ touch.keyboard.press("Escape")
+ expect(touch.locator(".navigation-dock nav")).to_be_hidden()
+ mobile.close()
+ # A generic OpenAI-compatible backend may omit /health and KV support.
+ generic = browser.new_page(locale="it-IT")
+ generic.on("pageerror", lambda e: errors.append(str(e)))
+ generic.route("**/health", lambda route: route.fulfill(status=404, body="{}"))
+ generic.goto(url)
+ expect(generic.locator(".model-button")).to_contain_text("fixture-model")
+ generic.locator("#draft").fill("Generic backend")
+ generic.locator("#draft").press("Enter")
+ expect(generic.locator(".message.assistant .message-body")).to_have_text("Risposta dal server.")
+ assert "cache_slot" not in [r[3] for r in requests if r[0] == "POST"][-1]
+ generic.close()
+ assert not errors, errors
+ assert not any(r[1] in ["/v1/health", "/v1/profile", "/v1/experts"] for r in requests)
+ print("PASS: four layouts, connection/auth/model settings, streaming, cancellation, errors, regeneration, export, isolated KV sessions, archive restore, real profile/experts endpoints, immersive atlas, theme and locale. No JavaScript errors.")
+ browser.close()
+finally:
+ server.shutdown()
+ server.server_close()