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

fix(web): render GFM tables in chat instead of one run-on paragraph

rayhanhanaputra43e5aa8078b2
diff --git a/web/src/chat-design.css b/web/src/chat-design.css
index 5bac8a2d..5003534c 100644
--- a/web/src/chat-design.css
+++ b/web/src/chat-design.css
@@ -49,6 +49,12 @@ button{color:inherit}button:disabled{cursor:default;opacity:.4}svg.lucide{stroke
.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-table{margin:0 0 .85em;overflow-x:auto;border:1px solid color-mix(in srgb,var(--foreground) 14%,transparent);border-radius:.6em}
+.md-table table{border-collapse:collapse;width:100%;font-size:.92em;font-variant-numeric:tabular-nums}
+.md-table th,.md-table td{padding:.42em .7em;text-align:left;vertical-align:top;border-bottom:1px solid color-mix(in srgb,var(--foreground) 10%,transparent)}
+.md-table thead th{font-weight:600;white-space:nowrap;background:color-mix(in srgb,var(--foreground) 5%,transparent);border-bottom:1px solid color-mix(in srgb,var(--foreground) 16%,transparent)}
+.md-table tbody tr:last-child td{border-bottom:0}
+.md-table :not(pre)>code{font-size:.9em}
.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}
diff --git a/web/src/components/Markdown.test.tsx b/web/src/components/Markdown.test.tsx
new file mode 100644
index 00000000..1e96f46e
--- /dev/null
+++ b/web/src/components/Markdown.test.tsx
@@ -0,0 +1,77 @@
+import { renderToStaticMarkup } from "react-dom/server"
+import { describe, expect, it } from "vitest"
+
+import { Markdown } from "./Markdown"
+
+/* Static rendering only — no DOM needed, so this runs in the default vitest
+ environment alongside the lib tests. */
+const render = (text: string) => renderToStaticMarkup(<Markdown text={text} />)
+
+describe("rendering a chat table", () => {
+ const table = [
+ "| Phase | ms/token |",
+ "|---|---:|",
+ "| moe_total | 126.8 |",
+ "| deltanet | 34.8 |",
+ ].join("\n")
+
+ it("renders a real table rather than a run-on paragraph", () => {
+ const html = render(table)
+ expect(html).toContain("<table>")
+ expect(html).toContain("<th")
+ expect(html).toContain("moe_total")
+ // The regression this fixes: rows joined into one paragraph.
+ expect(html).not.toContain("| moe_total | 126.8 |")
+ })
+
+ it("carries the column alignment from the delimiter row", () => {
+ expect(render(table)).toContain('style="text-align:right"')
+ })
+
+ it("renders inline marks inside cells", () => {
+ const html = render("| a | b |\n|---|---|\n| **bold** | `code` |")
+ expect(html).toContain("<strong>bold</strong>")
+ expect(html).toContain("<code>code</code>")
+ })
+
+ it("keeps surrounding prose as its own blocks", () => {
+ const html = render(`Before.\n\n${table}\n\nAfter.`)
+ expect(html).toContain("<p>Before.</p>")
+ expect(html).toContain("<p>After.</p>")
+ expect(html).toContain("<table>")
+ })
+
+ it("leaves a pipe table inside a fence as literal code", () => {
+ const html = render("```\n| a | b |\n|---|---|\n```")
+ expect(html).not.toContain("<table>")
+ expect(html).toContain("| a | b |")
+ })
+
+ it("does not read a delimiter row as a list item", () => {
+ expect(render(table)).not.toContain("<li>")
+ })
+})
+
+describe("the rest of the subset still renders", () => {
+ it("keeps ordinary text with a single pipe as a paragraph", () => {
+ const html = render("choose a | b at the prompt")
+ expect(html).toContain("<p>")
+ expect(html).not.toContain("<table>")
+ })
+
+ it("still renders lists, headings and fenced code", () => {
+ const html = render("# One\n\n## Two\n\n- one\n- two\n\n```sh\nmake\n```")
+ // Headings are demoted by one level so chat content sits under the page's own h1.
+ expect(html).toContain("<h2>One</h2>")
+ expect(html).toContain("<h3>Two</h3>")
+ expect(html).toContain("<ul>")
+ expect(html).toContain("<li>")
+ expect(html).toContain("make")
+ })
+
+ it("escapes model-written markup instead of injecting it", () => {
+ const html = render("| x |\n|---|\n| <img src=x onerror=alert(1)> |")
+ expect(html).not.toContain("<img")
+ expect(html).toContain("&lt;img")
+ })
+})
diff --git a/web/src/components/Markdown.tsx b/web/src/components/Markdown.tsx
index 2b4b1bb1..77f3c2c4 100644
--- a/web/src/components/Markdown.tsx
+++ b/web/src/components/Markdown.tsx
@@ -1,6 +1,8 @@
import { useState } from "react"
import { Check, Copy } from "lucide-react"
+import { parseTableAt, type Table } from "@/lib/markdown-table"
+
/* A small Markdown subset, rendered as React nodes rather than HTML.
*
* The text comes from a model, so nothing here ever reaches innerHTML: every
@@ -10,9 +12,14 @@ import { Check, Copy } from "lucide-react"
*
* 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.
+ * ordered and unordered lists, blockquotes, horizontal rules and GFM pipe
+ * tables. Not covered: footnotes, raw HTML. Those degrade to the literal text
+ * instead of disappearing, which is the right failure for a reader.
+ *
+ * Tables used to be in that list, but they did not in fact degrade to literal
+ * text: the rows fell through to the paragraph branch and were joined with
+ * spaces, so a table arrived as one run-on line. Parsing them (lib/markdown-table)
+ * is the smaller change.
*/
type Segment = { kind: "code"; lang: string; body: string } | { kind: "text"; body: string }
@@ -79,6 +86,23 @@ function CodeBlock({ lang, body }: { lang: string; body: string }) {
</figure>
}
+function MdTable({ head, align, rows, id }: Table & { id: string }) {
+ const cell = (at: number) => (align[at] ? { textAlign: align[at]! } : undefined)
+ return <div className="md-table">
+ <table>
+ <thead>
+ <tr>{head.map((text, at) =>
+ <th key={at} style={cell(at)}>{inline(text, `${id}-th${at}`)}</th>)}</tr>
+ </thead>
+ <tbody>
+ {rows.map((row, at) =>
+ <tr key={at}>{row.map((text, column) =>
+ <td key={column} style={cell(column)}>{inline(text, `${id}-td${at}-${column}`)}</td>)}</tr>)}
+ </tbody>
+ </table>
+ </div>
+}
+
/** One text segment: block structure, then inline marks inside each block. */
function blocks(source: string, key: string): React.ReactNode[] {
const out: React.ReactNode[] = []
@@ -106,13 +130,24 @@ function blocks(source: string, key: string): React.ReactNode[] {
}
const flushAll = () => { flushParagraph(); flushList(); flushQuote() }
- for (const line of lines) {
+ for (let at = 0; at < lines.length; at++) {
+ const line = lines[at]
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)
if (!line.trim()) { flushAll(); continue }
+ /* Before the list and paragraph branches: a bullet-looking delimiter row
+ such as "|---|---|" must not be read as a list item. */
+ const table = line.includes("|") ? parseTableAt(lines, at) : null
+ if (table) {
+ flushAll()
+ const id = `${key}-t${out.length}`
+ out.push(<MdTable key={id} id={id} head={table.head} align={table.align} rows={table.rows} length={table.length} />)
+ at += table.length - 1
+ continue
+ }
if (/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/.test(line)) { flushAll(); out.push(<hr key={`${key}-hr${out.length}`} />); continue }
if (heading) {
flushAll()
diff --git a/web/src/lib/markdown-table.test.ts b/web/src/lib/markdown-table.test.ts
new file mode 100644
index 00000000..b10eea13
--- /dev/null
+++ b/web/src/lib/markdown-table.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest"
+
+import { parseTableAt, rowAlignments, splitRow } from "./markdown-table"
+
+describe("splitting a row into cells", () => {
+ it("treats the outer pipes as delimiters, not as empty edge cells", () => {
+ expect(splitRow("| a | b |")).toEqual(["a", "b"])
+ expect(splitRow("a | b")).toEqual(["a", "b"])
+ })
+
+ it("keeps a genuinely empty cell", () => {
+ expect(splitRow("| a | | c |")).toEqual(["a", "", "c"])
+ })
+
+ it("reads a backslash-escaped pipe as content", () => {
+ expect(splitRow("| a \\| b | c |")).toEqual(["a | b", "c"])
+ })
+
+ it("does not strip a trailing escaped pipe as a delimiter", () => {
+ expect(splitRow("| a | b \\|")).toEqual(["a", "b |"])
+ })
+})
+
+describe("recognising the delimiter row", () => {
+ it("accepts dashes with optional colon anchors and reads the alignment", () => {
+ expect(rowAlignments("|---|:---|---:|:---:|")).toEqual([null, "left", "right", "center"])
+ })
+
+ it("accepts a single dash per cell and no outer pipes", () => {
+ expect(rowAlignments("- | -")).toEqual([null, null])
+ })
+
+ it("rejects a row that is not all dashes, so ordinary text with a pipe stays text", () => {
+ expect(rowAlignments("| a | b |")).toBeNull()
+ expect(rowAlignments("|--- | x |")).toBeNull()
+ expect(rowAlignments("")).toBeNull()
+ expect(rowAlignments(undefined as unknown as string)).toBeNull()
+ })
+})
+
+describe("parsing a table out of a line array", () => {
+ it("reads the header, alignments, body and the lines it consumed", () => {
+ const lines = ["| Phase | ms |", "|---|---:|", "| moe | 126.8 |", "| attn | 12.2 |", "", "after"]
+ const table = parseTableAt(lines, 0)
+ expect(table).not.toBeNull()
+ expect(table!.head).toEqual(["Phase", "ms"])
+ expect(table!.align).toEqual([null, "right"])
+ expect(table!.rows).toEqual([["moe", "126.8"], ["attn", "12.2"]])
+ expect(table!.length).toBe(4)
+ })
+
+ it("pads a short row so the grid holds", () => {
+ const lines = ["| a | b | c |", "|---|---|---|", "| 1 |"]
+ expect(parseTableAt(lines, 0)!.rows).toEqual([["1", "", ""]])
+ })
+
+ it("keeps the extra cells of a long row rather than dropping content", () => {
+ const lines = ["| a | b |", "|---|---|", "| 1 | 2 | 3 |"]
+ expect(parseTableAt(lines, 0)!.rows).toEqual([["1", "2", "3"]])
+ })
+
+ it("stops at a blank line and at the first line without a pipe", () => {
+ const lines = ["| a |", "|---|", "| 1 |", "prose follows", "| not | part |"]
+ expect(parseTableAt(lines, 0)!.length).toBe(3)
+ })
+
+ it("is null when the second line is not a delimiter", () => {
+ expect(parseTableAt(["a | b", "c | d"], 0)).toBeNull()
+ })
+
+ it("is null for a line with no pipe, and past the end", () => {
+ expect(parseTableAt(["plain", "|---|"], 0)).toBeNull()
+ expect(parseTableAt(["| a |", "|---|"], 9)).toBeNull()
+ })
+
+ it("accepts a header-only table with no body rows", () => {
+ const table = parseTableAt(["| a | b |", "|---|---|"], 0)
+ expect(table!.rows).toEqual([])
+ expect(table!.length).toBe(2)
+ })
+
+ it("finds a table that starts partway down", () => {
+ const lines = ["intro", "", "| a |", "|---|", "| 1 |"]
+ expect(parseTableAt(lines, 2)!.head).toEqual(["a"])
+ })
+})
diff --git a/web/src/lib/markdown-table.ts b/web/src/lib/markdown-table.ts
new file mode 100644
index 00000000..a84a400e
--- /dev/null
+++ b/web/src/lib/markdown-table.ts
@@ -0,0 +1,84 @@
+/* GFM pipe tables, parsed to plain data so the renderer stays a pure mapping.
+ *
+ * Kept out of the component on purpose: this is the part with the edge cases
+ * (escaped pipes, optional outer pipes, ragged rows), and it is testable here
+ * without a DOM. The renderer turns the result into React nodes, so cell text
+ * never reaches innerHTML. */
+
+export type Align = "left" | "center" | "right" | null
+
+export type Table = {
+ head: string[]
+ align: Align[]
+ rows: string[][]
+ /** Lines consumed, so the block loop can skip past the table. */
+ length: number
+}
+
+/* Split one row into cells. The outer pipes are delimiters when present, so
+ they are stripped before splitting rather than left to produce empty edge
+ cells — otherwise "| a | b |" and "a | b" would disagree on column count.
+ A backslash-escaped pipe is content. */
+export function splitRow(line: string): string[] {
+ let text = line.trim()
+ if (text.startsWith("|")) text = text.slice(1)
+ if (text.endsWith("|") && !text.endsWith("\\|")) text = text.slice(0, -1)
+
+ const out: string[] = []
+ let cell = ""
+ for (let at = 0; at < text.length; at++) {
+ if (text[at] === "\\" && text[at + 1] === "|") { cell += "|"; at++; continue }
+ if (text[at] === "|") { out.push(cell); cell = ""; continue }
+ cell += text[at]
+ }
+ out.push(cell)
+ return out.map((item) => item.trim())
+}
+
+/* The delimiter row is what makes a run of pipes a table: every cell has to be
+ dashes, optionally colon-anchored. Anything else and this was ordinary text
+ that happened to contain a pipe. */
+export function rowAlignments(line: string): Align[] | null {
+ if (!line || !line.includes("-")) return null
+ const parts = splitRow(line)
+ if (!parts.length) return null
+
+ const out: Align[] = []
+ for (const part of parts) {
+ const match = /^(:?)-+(:?)$/.exec(part)
+ if (!match) return null
+ const left = match[1] === ":"
+ const right = match[2] === ":"
+ out.push(left && right ? "center" : right ? "right" : left ? "left" : null)
+ }
+ return out
+}
+
+/* Read a table starting at `from`, or null if there is not one there.
+ *
+ * Ragged rows are kept as the model wrote them rather than truncated to the
+ * header width: a short row is padded so the grid holds, and a long one keeps
+ * its extra cells. Dropping them would silently lose content, which is worse
+ * than one wide row. */
+export function parseTableAt(lines: string[], from: number): Table | null {
+ const header = lines[from]
+ if (header === undefined || !header.includes("|")) return null
+
+ const align = rowAlignments(lines[from + 1])
+ if (!align) return null
+
+ const head = splitRow(header)
+ if (!head.length || head.every((cell) => !cell)) return null
+
+ const rows: string[][] = []
+ let at = from + 2
+ for (; at < lines.length; at++) {
+ const line = lines[at]
+ if (!line.trim() || !line.includes("|")) break
+ const row = splitRow(line)
+ while (row.length < head.length) row.push("")
+ rows.push(row)
+ }
+
+ return { head, align, rows, length: at - from }
+}