Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): the agent's answers render tables

esenginecd4853cb4b12
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7ca90c7f2..9e0a0baab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -131,6 +131,15 @@ published separately; it ships inside the editor.
— which is exactly the part a preview exists to show. Strike-all takes a batch apart in
one gesture, and an emptied one disables Apply instead of offering "Apply 0", which the
kernel would have treated as a decline anyway.
+- **The agent's answers render markdown tables.** Asked to compare a few entities or
+ field values a model reaches for one, and the fallback was a paragraph of raw pipes
+ wrapped in a 384px column — the least readable thing the renderer could produce. Column
+ alignment is honoured, an escaped `\|` stays content, a ragged row is fitted to the
+ header rather than shifting its cells, and cells go through the same inline parse as
+ prose, so a code span naming an entity is still a way into the scene. The table scrolls
+ inside its own box: the transcript never scrolls sideways as a whole. As everywhere
+ else in this parser, a half-arrived table is not an error — a header stays a paragraph
+ until its divider lands, so nothing flickers through being a narrower table first.
- **A run that was cut off says so, and can be carried on.** The turn loop is bounded so a
model that keeps calling tools cannot spin forever, and reaching that bound was reported
as an ordinary end of turn — on screen, a run cut off mid-task looked exactly like one
diff --git a/desktop/src/components/MarkdownView.tsx b/desktop/src/components/MarkdownView.tsx
index abbee9ae9..d23b9744c 100644
--- a/desktop/src/components/MarkdownView.tsx
+++ b/desktop/src/components/MarkdownView.tsx
@@ -10,6 +10,7 @@
import { useMemo, useState } from 'react';
import { Copy, Check } from 'lucide-react';
import { parseBlocks, type Block, type Inline } from './markdown';
+import type { Align } from './markdown';
import { peekEntities } from '@/store/AgentStore';
import { useSelection } from '@/store/selectionStore';
import { t } from '@/i18n';
@@ -84,6 +85,46 @@ function CodeBlock({ block }: { block: Extract<Block, { kind: 'code' }> }) {
);
}
+/**
+ * A comparison the model laid out in columns.
+ *
+ * It scrolls inside its own box rather than widening anything: the drawer is
+ * 384px and most tables want more, and a transcript that scrolls sideways as a
+ * whole would take every paragraph with it. Cells do not wrap for the same
+ * reason — a wrapped table in a narrow column stops being a table.
+ *
+ * Cells go through the same inline parse as prose, so a code span naming an
+ * entity is still a way into the scene.
+ */
+function Table({ block, entity }: {
+ block: Extract<Block, { kind: 'table' }>;
+ entity?: (name: string) => number | null;
+}) {
+ const at = (i: number): Align => block.align[i] ?? 'left';
+ return (
+ <div className="md-tw">
+ <table className="md-table">
+ <thead>
+ <tr>
+ {block.head.map((cell, i) => (
+ <th key={i} style={{ textAlign: at(i) }}><Spans spans={cell} entity={entity} /></th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {block.rows.map((row, r) => (
+ <tr key={r}>
+ {row.map((cell, i) => (
+ <td key={i} style={{ textAlign: at(i) }}><Spans spans={cell} entity={entity} /></td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
export function MarkdownView({ text, entity, caret }: {
text: string;
/** Resolve a code span to a scene entity, making it clickable. */
@@ -107,6 +148,11 @@ export function MarkdownView({ text, entity, caret }: {
switch (b.kind) {
case 'code':
return <CodeBlock key={i} block={b} />;
+ // No caret: a table announces that it is still being written by
+ // growing a row at a time, and a block-level caret under it would sit
+ // on its own line — the stray blinking box this design avoids.
+ case 'table':
+ return <Table key={i} block={b} entity={entity} />;
case 'h': {
const Tag = (`h${Math.min(b.level + 2, 6)}`) as 'h3';
return <Tag className="md-h" key={i}><Spans spans={b.spans} entity={entity} />{tail(i)}</Tag>;
diff --git a/desktop/src/components/markdown.ts b/desktop/src/components/markdown.ts
index 227d80b42..3cd90ef6f 100644
--- a/desktop/src/components/markdown.ts
+++ b/desktop/src/components/markdown.ts
@@ -16,9 +16,14 @@
* editor's heading and a code span is the editor's mono — instead of importing
* a stylesheet built for a document and then fighting it.
*
- * Deliberately NOT supported: tables, blockquotes, images, footnotes, HTML.
- * They do not appear in this transcript, and each one is more surface to get
- * subtly wrong on partial input.
+ * Deliberately NOT supported: blockquotes, images, footnotes, HTML. They do not
+ * appear in this transcript, and each one is more surface to get subtly wrong on
+ * partial input.
+ *
+ * Tables WERE on that list and should not have been: asked to compare a handful
+ * of entities or field values, a model reaches for one, and the fallback — a
+ * paragraph of raw pipes, wrapped in a 384px column — is the least readable
+ * thing this renderer can produce.
*/
export type Inline =
@@ -28,19 +33,74 @@ export type Inline =
| { kind: 'em'; text: string }
| { kind: 'link'; text: string; href: string };
+export type Align = 'left' | 'center' | 'right';
+
export type Block =
| { kind: 'p'; spans: Inline[] }
| { kind: 'h'; level: number; spans: Inline[] }
| { kind: 'list'; ordered: boolean; items: Inline[][] }
| { kind: 'rule' }
/** `open` while the closing fence has not arrived — still being written. */
- | { kind: 'code'; lang: string; text: string; open: boolean };
+ | { kind: 'code'; lang: string; text: string; open: boolean }
+ /** Rows are already fitted to the header's width, so rendering never has to
+ * ask what a ragged row means. */
+ | { kind: 'table'; align: Align[]; head: Inline[][]; rows: Inline[][][] };
const FENCE = /^\s*```(\S*)\s*$/;
const HEADING = /^(#{1,4})\s+(.*)$/;
const BULLET = /^\s*[-*+]\s+(.*)$/;
const NUMBERED = /^\s*\d+[.)]\s+(.*)$/;
const RULE = /^\s*([-*_])\1{2,}\s*$/;
+/**
+ * A leading pipe is REQUIRED of a table row, though the standard would also take
+ * `a | b`. Without it an ordinary sentence that happens to contain a pipe
+ * ("group them by A | B") turns into a one-row table as soon as the line under
+ * it looks like a rule — and being wrong in that direction is unrecoverable for
+ * the reader, while being wrong the other way just leaves a paragraph.
+ */
+const TABLE_ROW = /^\s*\|/;
+const DIVIDER_CELL = /^:?-+:?$/;
+
+/**
+ * `| a | b |` → `['a', 'b']`, with `\|` kept as a literal pipe.
+ *
+ * The trailing empty cell a closing pipe produces is dropped; interior empty
+ * cells are not, because `| a | | c |` is a three-column row with a blank in
+ * the middle and squeezing it would shift every cell after it left.
+ */
+function cells(line: string): string[] {
+ const out: string[] = [];
+ const s = line.trim();
+ let cur = '';
+ for (let i = s.startsWith('|') ? 1 : 0; i < s.length; i++) {
+ if (s[i] === '\\' && s[i + 1] === '|') { cur += '|'; i++; continue; }
+ if (s[i] === '|') { out.push(cur.trim()); cur = ''; continue; }
+ cur += s[i];
+ }
+ if (cur.trim() !== '') out.push(cur.trim());
+ return out;
+}
+
+/**
+ * The `|---|:--:|` line as per-column alignment, or null if that is not what
+ * this line is.
+ *
+ * `width` must match, which is what keeps a half-written divider from briefly
+ * rendering as a narrower table: mid-stream `|--` parses as one perfectly good
+ * column, and the header above it has three.
+ */
+function alignments(line: string, width: number): Align[] | null {
+ const parts = cells(line);
+ if (parts.length !== width || !parts.every((p) => DIVIDER_CELL.test(p))) return null;
+ return parts.map((p) => {
+ if (p.startsWith(':') && p.endsWith(':')) return 'center';
+ return p.endsWith(':') ? 'right' : 'left';
+ });
+}
+
+/** A row as the header's width, padded or truncated — never ragged. */
+const fit = (row: string[], width: number): string[] =>
+ Array.from({ length: width }, (_, i) => row[i] ?? '');
/**
* Split text into blocks. Total: any input is a valid document, because the
@@ -82,6 +142,24 @@ export function parseBlocks(source: string): Block[] {
continue;
}
+ // A table is only a table once its divider has arrived. Until then the
+ // header is an ordinary paragraph — which is exactly what it looks like,
+ // and what it may still turn out to be.
+ if (TABLE_ROW.test(line)) {
+ const head = cells(line);
+ const align = alignments(lines[i + 1] ?? '', head.length);
+ if (align) {
+ flushParagraph();
+ const rows: Inline[][][] = [];
+ for (i += 2; i < lines.length && TABLE_ROW.test(lines[i]); i++) {
+ rows.push(fit(cells(lines[i]), head.length).map(parseInline));
+ }
+ i--; // the loop's own i++ must land on the line that ended the table
+ blocks.push({ kind: 'table', align, head: head.map(parseInline), rows });
+ continue;
+ }
+ }
+
const heading = HEADING.exec(line);
if (heading) {
flushParagraph();
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index 73f726d22..aad7dcb61 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -646,6 +646,18 @@
color: var(--text-hi);
overflow-wrap: anywhere;
}
+/* A comparison in columns. Hairlines DIVIDE the rows; nothing encloses the
+ table, and it has no fill of its own — the same rule the tool rows follow.
+ It scrolls inside its own box, because the drawer is narrower than most
+ tables want to be and the transcript must not scroll sideways as a whole. */
+.md-tw { margin: 0 0 10px; overflow-x: auto; overscroll-behavior-x: contain; }
+.md-table { border-collapse: collapse; font-size: var(--fs-xs); line-height: 1.65; }
+.md-table th, .md-table td { padding: 5px 16px 5px 0; white-space: nowrap; vertical-align: baseline; }
+.md-table th:last-child, .md-table td:last-child { padding-right: 0; }
+.md-table th { color: var(--text-hi); font-weight: 500; border-bottom: 1px solid var(--line-strong); }
+.md-table td { color: var(--text); border-bottom: 1px solid var(--line); }
+.md-table tr:last-child td { border-bottom: 0; }
+
.md-link { color: var(--star-hi); text-decoration: none; border-bottom: 1px solid var(--star-soft); }
.md-link:hover { border-bottom-color: var(--star-hi); }
.md-pre { margin: 0 0 10px; border-radius: var(--r-sm); background: var(--inset); overflow: hidden; }
diff --git a/desktop/tests/agent-markdown.test.ts b/desktop/tests/agent-markdown.test.ts
index 0de3e292b..bb16c7f03 100644
--- a/desktop/tests/agent-markdown.test.ts
+++ b/desktop/tests/agent-markdown.test.ts
@@ -47,6 +47,74 @@ describe('blocks', () => {
});
});
+/**
+ * Tables, which a model reaches for whenever it compares a few entities. Every
+ * case here is either a partial one (the input is always a prefix) or a way of
+ * being ragged that must not become a wrong-looking table.
+ */
+describe('tables', () => {
+ const table = (src: string) => parseBlocks(src)[0];
+ const text = (cell: { kind: string; text?: string }[]) => cell.map((s) => s.text ?? '').join('');
+
+ it('reads a header, its alignment and its rows', () => {
+ const block = table('| Entity | Kind |\n| --- | ---: |\n| Player | Sprite |\n| Ground | Tilemap |');
+ expect(block.kind).toBe('table');
+ if (block.kind !== 'table') return;
+ expect(block.align).toEqual(['left', 'right']);
+ expect(block.head.map(text)).toEqual(['Entity', 'Kind']);
+ expect(block.rows.map((r) => r.map(text))).toEqual([['Player', 'Sprite'], ['Ground', 'Tilemap']]);
+ });
+
+ it('reads the three alignments', () => {
+ const block = table('| a | b | c |\n| :-- | :-: | --: |\n| 1 | 2 | 3 |');
+ expect(block.kind === 'table' && block.align).toEqual(['left', 'center', 'right']);
+ });
+
+ // The header arrives a whole line before the divider does. Rendering it as a
+ // one-column table and then replacing it is a flicker; it is a paragraph, and
+ // it may still turn out to be one.
+ it('is still a paragraph until the divider arrives', () => {
+ expect(table('| Entity | Kind |').kind).toBe('p');
+ expect(table('| Entity | Kind |\n| --').kind).toBe('p');
+ });
+
+ it('takes the divider only when it is as wide as the header', () => {
+ expect(table('| a | b |\n| --- |').kind).toBe('p');
+ expect(table('| a | b |\n| --- | --- |').kind).toBe('table');
+ });
+
+ it('fits a ragged row to the header rather than leaving a hole', () => {
+ const block = table('| a | b | c |\n| - | - | - |\n| 1 |\n| 1 | 2 | 3 | 4 |');
+ expect(block.kind === 'table' && block.rows.map((r) => r.map(text)))
+ .toEqual([['1', '', ''], ['1', '2', '3']]);
+ });
+
+ it('keeps an empty cell in the middle instead of shifting the row left', () => {
+ const block = table('| a | b | c |\n| - | - | - |\n| 1 | | 3 |');
+ expect(block.kind === 'table' && block.rows[0].map(text)).toEqual(['1', '', '3']);
+ });
+
+ it('reads an escaped pipe as content, not as a boundary', () => {
+ const block = table('| key | value |\n| - | - |\n| mode | a \\| b |');
+ expect(block.kind === 'table' && block.rows[0].map(text)).toEqual(['mode', 'a | b']);
+ });
+
+ it('parses cells as inline, so a code span in one still resolves', () => {
+ const block = table('| what | where |\n| - | - |\n| `Player` | scene |');
+ expect(block.kind === 'table' && block.rows[0][0]).toEqual([{ kind: 'code', text: 'Player' }]);
+ });
+
+ it('ends at the first line that is not a row', () => {
+ const blocks = parseBlocks('| a |\n| - |\n| 1 |\nafter the table');
+ expect(blocks.map((b) => b.kind)).toEqual(['table', 'p']);
+ });
+
+ // A sentence with a pipe in it, above something that looks like a rule.
+ it('does not turn prose containing a pipe into a table', () => {
+ expect(parseBlocks('group them by A | B\n---').map((b) => b.kind)).toEqual(['p', 'rule']);
+ });
+});
+
describe('inline spans', () => {
it('picks out code, bold, italic and links', () => {
expect(parseInline('run `npm t` now')).toEqual([