Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(web): keep each reply's finish reason on the message itself
eni96467ec192c0
diff --git a/web/src/App.tsx b/web/src/App.tsxindex 2cf9cf73..9badb41b 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -40,7 +40,7 @@ import { Markdown } from "./components/Markdown"import { NavigationDock, type View } from "./components/NavigationDock"import { Profiling } from "./Profiling"import { persistPublicSettings, stored } from "@/lib/storage"-import { appendDelta, continuation } from "@/lib/transcript"+import { appendDelta, continuable, continuation, setFinish } from "@/lib/transcript"import { cn } from "@/lib/utils"import { useLocale } from "./i18n"@@ -71,12 +71,6 @@ export default function App() {const [health, setHealth] = useState<HealthResponse | null>(null)const [healthError, setHealthError] = useState("")const [lastRun, setLastRun] = useState<StreamChatResult | null>(null)- /* How the last turn ended, for deciding whether it can be continued: "length"- (hit max_tokens) and "aborted" (stopped by hand) are open and continuable;- "stop" (the model closed the turn) is complete, and continuing it only makes- the model re-emit its stop and add nothing. null before any turn / after a- reset. Tracked apart from lastRun because an abort never sets a result. */- const [lastFinish, setLastFinish] = useState<string | null>(null)const [draft, setDraft] = useState("")const [loading, setLoading] = useState(false)const [streamStart, setStreamStart] = useState<number | null>(null)@@ -158,7 +152,7 @@ export default function App() {}, [cacheSlot, kvSlots])// EFFECT #6- useEffect(() => { setLastRun(null); setLastFinish(null) }, [cacheSlot])+ useEffect(() => { setLastRun(null) }, [cacheSlot])// EFFECT #7useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }) }, [messages])@@ -280,19 +274,17 @@ export default function App() {completion: prev.completion + (result.usage?.completion_tokens || 0),}))setLastRun(result)- setLastFinish(result.finishReason)+ updateMessages((current) => setFinish(current, targetId, result.finishReason))setConnected(true)} catch (cause) {/* Drop the target bubble only if it is empty -- a first turn that never gota token. A continued turn already carries the client's opening, so the- `|| item.content` keeps it on the screen through an abort or an error. */- if (controller.signal.aborted) {- setLastFinish("aborted")- updateMessages((current) => current.filter((item) => item.id !== targetId || item.content || item.reasoning))- } else {- setError(cause instanceof Error ? cause.message : "status.generationFailed")- updateMessages((current) => current.filter((item) => item.id !== targetId || item.content || item.reasoning))- }+ `|| item.content` keeps it on the screen through an abort or an error, and+ `|| item.reasoning` keeps a turn stopped while it was still thinking. */+ const finish = controller.signal.aborted ? "aborted" : "error"+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "status.generationFailed")+ updateMessages((current) => setFinish(current, targetId, finish)+ .filter((item) => item.id !== targetId || item.content || item.reasoning))} finally {abortRef.current = nullsetLoading(false)@@ -326,7 +318,7 @@ export default function App() {}const openSettings = (page = "general") => { setSettingsPage(page); setView("settings") }- const clearChat = () => { updateMessages([]); setLastRun(null); setLastFinish(null); setTokPerSec(null); setTtft(null); setTokenCount(0); setTotalTokens({ prompt: 0, completion: 0 }); setError("") }+ const clearChat = () => { updateMessages([]); setLastRun(null); setTokPerSec(null); setTtft(null); setTokenCount(0); setTotalTokens({ prompt: 0, completion: 0 }); setError("") }const newChat = () => {if (loading) returnif (messages.length) setArchives(items => [{ id: message("system", "").id, slot: cacheSlot, messages: [...messages] }, ...items])@@ -344,7 +336,7 @@ export default function App() {const slot = entry.slot < kvSlots ? entry.slot : cacheSlotconst 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); setLastFinish(null); setError(""); setDraft("")+ setConversations(items => ({ ...items, [slot]: entry.messages })); setCacheSlot(slot); setView("chat"); setHistoryOpen(false); setLastRun(null); setError(""); setDraft("")}const empty = messages.length === 0const connectionControls = (<fieldset disabled={loading}><section className="side-section">@@ -460,7 +452,7 @@ export default function App() {<div className="reasoning-body">{item.reasoning}</div></details>: null}{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 retry = resendFrom(messages, index); if (retry) void send(retry.text, retry.previous, retry.pictures, false) }}><RefreshCw /></button>}{index === messages.length - 1 && !loading && supportsContinuation(health) && (lastFinish === "length" || lastFinish === "aborted") && <button className="icon-action" aria-label={t("ui.continue")} title={t("ui.continue")} onClick={() => void continueTurn()}><StepForward /></button>}</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 retry = resendFrom(messages, index); if (retry) void send(retry.text, retry.previous, retry.pictures, false) }}><RefreshCw /></button>}{index === messages.length - 1 && !loading && supportsContinuation(health) && continuable(item) && <button className="icon-action" aria-label={t("ui.continue")} title={t("ui.continue")} onClick={() => void continueTurn()}><StepForward /></button>}</div>}</article>)}<div ref={bottomRef} /></div></div>}<div className="composer-wrap">diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex b2c31e6e..a99792d0 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -12,6 +12,13 @@ export interface ChatMessage {than on the draft, because the transcript is resent on every later turn andthe model has to keep seeing what it was shown. */images?: string[]+ /* How an assistant turn's last generation ended: the server's finish_reason;+ "aborted" / "error" when the client stopped or lost the stream; or+ "incomplete" when the stream closed without a finish_reason, which colibri+ always sends last, so its absence means the reply was cut off. Kept on+ the message so it travels with the transcript through slot switches and+ archives; never sent to the server. */+ finish?: string}interface OpenAIError {diff --git a/web/src/lib/transcript.test.ts b/web/src/lib/transcript.test.tsindex 8f34e64a..321148f5 100644--- a/web/src/lib/transcript.test.ts+++ b/web/src/lib/transcript.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest"import { streamChat, type ChatMessage } from "./api"-import { appendDelta, continuation } from "./transcript"+import { appendDelta, continuable, continuation, setFinish } from "./transcript"afterEach(() => vi.unstubAllGlobals())@@ -13,7 +13,7 @@ const stream = (...deltas: string[]) => new Response(describe("continuing a trailing assistant turn", () => {const transcript: ChatMessage[] = [{ id: "u1", role: "user", content: "Capital of France?" },- { id: "a1", role: "assistant", content: "The capital of France is Par \n" },+ { id: "a1", role: "assistant", content: "The capital of France is Par \n", finish: "length" },]it("resends the transcript ending on that turn and appends to its bubble", async () => {@@ -40,4 +40,32 @@ describe("continuing a trailing assistant turn", () => {expect(continuation(transcript.slice(0, 1))).toBeNull()expect(continuation([...transcript.slice(0, 1), { id: "a1", role: "assistant", content: " \n" }])).toBeNull()})++ it("offers to continue a turn cut off by max_tokens, a stop or an error, not a completed one", () => {+ const reply = transcript[1]+ for (const finish of ["length", "aborted", "error", "incomplete"]) expect(continuable({ ...reply, finish })).toBe(true)+ expect(continuable({ ...reply, finish: "stop" })).toBe(false)+ expect(continuable({ ...reply, finish: undefined })).toBe(false)+ expect(continuable({ ...reply, content: " ", finish: "length" })).toBe(false)+ })++ it("keeps Continue on a reply whose stream closed before its finish_reason", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(+ `data: ${JSON.stringify({ choices: [{ delta: { content: "ís" } }] })}\n\n`,+ { headers: { "content-type": "text/event-stream" } })))+ const result = await streamChat({+ baseUrl: "http://localhost:8000/v1", apiKey: "", model: "m", messages: transcript,+ temperature: 0, maxTokens: 8, enableThinking: false, signal: new AbortController().signal,+ onDelta: () => {},+ })+ const marked = setFinish(transcript, "a1", result.finishReason)+ expect(marked[1].finish).toBe("incomplete")+ expect(continuable(marked[1])).toBe(true)+ })++ it("records the finish on the turn it streamed into, not on others", () => {+ const marked = setFinish(transcript, "a1", "stop")+ expect(marked[1].finish).toBe("stop")+ expect(marked[0].finish).toBeUndefined()+ })})diff --git a/web/src/lib/transcript.ts b/web/src/lib/transcript.tsindex e5d1d070..234d3b32 100644--- a/web/src/lib/transcript.ts+++ b/web/src/lib/transcript.ts@@ -7,6 +7,22 @@ export function appendDelta(messages: ChatMessage[], targetId: string, field: "citem.id === targetId ? { ...item, [field]: (item[field] ?? "") + delta } : item)}+/* Record how the generation streaming into `targetId` ended. A null finish is+ a stream that closed without a finish_reason: colibri always sends one last,+ so the reply was cut off, and is recorded as "incomplete", not as done. */+export function setFinish(messages: ChatMessage[], targetId: string, finish: string | null): ChatMessage[] {+ return messages.map((item) => item.id === targetId ? { ...item, finish: finish ?? "incomplete" } : item)+}++/* An assistant turn is open, and worth continuing, when it hit max_tokens or+ was cut off by a stop, an error, or a stream that closed without saying how+ it finished. "stop" means the model closed the turn,+ and continuing it only makes the model re-emit its stop and add nothing. */+export function continuable(message: ChatMessage): boolean {+ return message.role === "assistant" && !!message.content.trim()+ && ["length", "aborted", "error", "incomplete"].includes(message.finish ?? "")+}+/* The request that continues the trailing assistant turn instead of opening anew one: the transcript ending on that turn, streamed back into the samebubble. Trailing whitespace is stripped because the server refuses it (the