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): dock the agent, render its Markdown, and show it thinking

esengine9bed8b001fc6
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index a82d2d4fa..1c3df7aa8 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -39,6 +39,8 @@ import {
} from '@/agent/providers';
import { secretStatus, subscribeSecrets, secretRevision } from '@/store/SecretStore';
import { useSettings } from '@/store/settingsStore';
+import { MarkdownView } from '@/components/MarkdownView';
+import { dockApi } from '@/layout/dockApi';
import { t } from '@/i18n';
const TOOL_ICON: Record<string, typeof Eye> = {
@@ -124,11 +126,14 @@ function Thinking({ text }: { text: string }) {
);
}
-function Prose({ text }: { text: string }) {
+function Prose({ text, streaming }: { text: string; streaming?: boolean }) {
const [copied, setCopied] = useState(false);
return (
<div className="ag-say">
- {text}
+ <MarkdownView text={text} />
+ {/* The caret rides the last paragraph while tokens are still arriving —
+ the difference between "thinking" and "finished" at a glance. */}
+ {streaming && <span className="ag-caret" />}
<button
type="button"
className="ag-say-copy"
@@ -146,9 +151,11 @@ function Prose({ text }: { text: string }) {
}
/** Consecutive tool rows are one hairline-divided block; prose breaks the run. */
-function Entries({ entries, onConfirm }: {
+function Entries({ entries, onConfirm, streaming }: {
entries: readonly AgentEntry[];
onConfirm: (callId: string, allow: boolean) => void;
+ /** The run is still taking events, so the last entry is mid-write. */
+ streaming?: boolean;
}) {
const out: React.ReactNode[] = [];
let run: AgentToolEntry[] = [];
@@ -178,12 +185,27 @@ function Entries({ entries, onConfirm }: {
</div>,
);
} else if (entry.kind === 'thinking') out.push(<Thinking key={i} text={entry.text} />);
- else out.push(<Prose key={i} text={entry.text} />);
+ else out.push(<Prose key={i} text={entry.text} streaming={streaming && i === entries.length - 1} />);
});
flush();
return <>{out}</>;
}
+/** Every row has reported; nothing is in flight but the next model call. */
+const lastIsSettled = (entries: readonly AgentEntry[]): boolean => {
+ const last = entries[entries.length - 1];
+ return last?.kind === 'tool' && (last.state === 'ok' || last.state === 'error' || last.state === 'declined');
+};
+
+function Waiting() {
+ return (
+ <div className="ag-wait-t">
+ <span className="ag-dots"><i /><i /><i /></span>
+ {t('agent.waiting')}
+ </div>
+ );
+}
+
/** Waiting on the first token: a shimmer, not a spinner — it says how much is
* coming, and a spinner in a text column says only "something". */
function Skeleton() {
@@ -223,8 +245,12 @@ function Turn({ turn, isLast, running }: { turn: AgentTurn; isLast: boolean; run
{!folded && (
<div className="ag-tb">
{empty && running && isLast ? <Skeleton /> : (
- <Entries entries={turn.entries} onConfirm={confirmAgentCall} />
+ <Entries entries={turn.entries} onConfirm={confirmAgentCall} streaming={running && isLast} />
)}
+ {/* Between rounds: the last thing that happened was a tool result and
+ the model is being asked again. Without this the transcript looks
+ finished while a request is in flight. */}
+ {running && isLast && turn.entries.length > 0 && lastIsSettled(turn.entries) && <Waiting />}
</div>
)}
</div>
@@ -413,25 +439,19 @@ function Compose() {
);
}
-export function AgentDrawer() {
- const open = useEditorStore((s) => s.agentDrawer);
- const pinned = useEditorStore((s) => s.agentDrawerPinned);
+/**
+ * The conversation itself. Rendered BOTH as a dock panel and as the summoned
+ * drawer — the same arrangement the Content Browser has, because "a surface you
+ * can dock wherever you like" and "a surface you can summon over your work
+ * without rearranging anything" are both wanted, and they are not two features.
+ */
+export function AgentPanel({ docked }: { docked?: boolean }) {
const setOpen = useEditorStore((s) => s.setAgentDrawer);
- const setPinned = useEditorStore((s) => s.setAgentDrawerPinned);
const turns = useAgent((s) => s.turns);
const status = useAgent((s) => s.status);
const logRef = useRef<HTMLDivElement>(null);
const stuck = useRef(true);
- useEffect(() => {
- if (!open || pinned) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') setOpen(false);
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [open, pinned, setOpen]);
-
// Follow the tail only while the reader is already at it — yanking someone
// back down while they read an earlier tool result is the classic log-view bug.
useLayoutEffect(() => {
@@ -439,27 +459,32 @@ export function AgentDrawer() {
if (el && stuck.current) el.scrollTop = el.scrollHeight;
}, [turns]);
- if (!open) return null;
-
- const body = (
- <div className="ag-drawer" onMouseDown={(e) => e.stopPropagation()}>
- <div className="ag-head">
- <span className="ag-ttl">{t('agent.title')}</span>
+ return (
+ <div className="ag-panel">
+ <div className={`ag-head${docked ? ' docked' : ''}`}>
+ {/* Docked, the tab already says Agent — a second title under it is the
+ same word twice and 40px of nothing. */}
+ {!docked && <span className="ag-ttl">{t('agent.title')}</span>}
<span className="ag-sp" />
<button type="button" title={t('agent.newConversation')} onClick={() => void resetAgentSession()}>
<Plus size={14} strokeWidth={2} />
</button>
- <button
- type="button"
- className={pinned ? 'on' : undefined}
- title={t('agent.pin')}
- onClick={() => setPinned(!pinned)}
- >
- <PanelRight size={14} strokeWidth={1.9} />
- </button>
- <button type="button" title={t('agent.close')} onClick={() => setOpen(false)}>
- <X size={14} strokeWidth={2} />
- </button>
+ {!docked && (
+ <>
+ {/* Not a bespoke "pinned" mode any more: it hands the conversation to
+ the dock, where it is an ordinary panel the user can put anywhere. */}
+ <button
+ type="button"
+ title={t('agent.dock')}
+ onClick={() => { setOpen(false); dockApi.openPanel('agent'); }}
+ >
+ <PanelRight size={14} strokeWidth={1.9} />
+ </button>
+ <button type="button" title={t('agent.close')} onClick={() => setOpen(false)}>
+ <X size={14} strokeWidth={2} />
+ </button>
+ </>
+ )}
</div>
<div
@@ -483,13 +508,29 @@ export function AgentDrawer() {
<Compose />
</div>
);
+}
+
+/** The summoned overlay: covers the right-hand panels rather than squeezing the
+ * viewport, and dismisses on Esc or an outside click. */
+export function AgentDrawer() {
+ const open = useEditorStore((s) => s.agentDrawer);
+ const setOpen = useEditorStore((s) => s.setAgentDrawer);
- // Pinned it is a fourth column; floating it dims what is behind, because then
- // it is the thing you are doing.
- if (pinned) return <div className="ag-column">{body}</div>;
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') setOpen(false);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [open, setOpen]);
+
+ if (!open) return null;
return (
<div className="ag-scrim open" onMouseDown={() => setOpen(false)}>
- {body}
+ <div className="ag-drawer" onMouseDown={(e) => e.stopPropagation()}>
+ <AgentPanel />
+ </div>
</div>
);
}
diff --git a/desktop/src/components/MarkdownView.tsx b/desktop/src/components/MarkdownView.tsx
new file mode 100644
index 000000000..b9e837809
--- /dev/null
+++ b/desktop/src/components/MarkdownView.tsx
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file MarkdownView.tsx — what the model wrote, rendered.
+ *
+ * The parse is in markdown.ts and is pure; this is only the mapping onto the
+ * editor's own type scale. A fenced block that is still being written gets a
+ * copy button anyway — the code is usable before the sentence after it arrives.
+ */
+import { useMemo, useState } from 'react';
+import { Copy, Check } from 'lucide-react';
+import { parseBlocks, type Block, type Inline } from './markdown';
+import { t } from '@/i18n';
+
+function Spans({ spans }: { spans: readonly Inline[] }) {
+ return (
+ <>
+ {spans.map((s, i) => {
+ if (s.kind === 'code') return <code className="md-code" key={i}>{s.text}</code>;
+ if (s.kind === 'strong') return <strong key={i}>{s.text}</strong>;
+ if (s.kind === 'em') return <em key={i}>{s.text}</em>;
+ // `_blank` rather than in-app navigation: main's window-open handler
+ // already denies navigation and sends http links to the OS, so this
+ // window can never be replaced by a page the model linked to.
+ if (s.kind === 'link') {
+ return (
+ <a key={i} className="md-link" href={s.href} target="_blank" rel="noreferrer">
+ {s.text || s.href}
+ </a>
+ );
+ }
+ return <span key={i}>{s.text}</span>;
+ })}
+ </>
+ );
+}
+
+function CodeBlock({ block }: { block: Extract<Block, { kind: 'code' }> }) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <div className={`md-pre${block.open ? ' open' : ''}`}>
+ <div className="md-pre-bar">
+ <span className="md-lang">{block.lang}</span>
+ <button
+ type="button"
+ title={t('agent.copy')}
+ onClick={() => {
+ void navigator.clipboard?.writeText(block.text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 900);
+ }}
+ >
+ {copied ? <Check size={11} strokeWidth={2.4} /> : <Copy size={11} strokeWidth={1.9} />}
+ </button>
+ </div>
+ <pre><code>{block.text}</code></pre>
+ </div>
+ );
+}
+
+export function MarkdownView({ text }: { text: string }) {
+ const blocks = useMemo(() => parseBlocks(text), [text]);
+ return (
+ <div className="md">
+ {blocks.map((b, i) => {
+ switch (b.kind) {
+ case 'code':
+ return <CodeBlock key={i} block={b} />;
+ case 'h': {
+ const Tag = (`h${Math.min(b.level + 2, 6)}`) as 'h3';
+ return <Tag className="md-h" key={i}><Spans spans={b.spans} /></Tag>;
+ }
+ case 'list':
+ return b.ordered ? (
+ <ol className="md-list" key={i}>
+ {b.items.map((item, j) => <li key={j}><Spans spans={item} /></li>)}
+ </ol>
+ ) : (
+ <ul className="md-list" key={i}>
+ {b.items.map((item, j) => <li key={j}><Spans spans={item} /></li>)}
+ </ul>
+ );
+ case 'rule':
+ return <hr className="md-rule" key={i} />;
+ default:
+ return <p className="md-p" key={i}><Spans spans={b.spans} /></p>;
+ }
+ })}
+ </div>
+ );
+}
diff --git a/desktop/src/components/markdown.ts b/desktop/src/components/markdown.ts
new file mode 100644
index 000000000..227d80b42
--- /dev/null
+++ b/desktop/src/components/markdown.ts
@@ -0,0 +1,148 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file markdown.ts — the subset a model actually writes, parsed for display.
+ *
+ * Purpose-built rather than a library, for two reasons that both matter here.
+ *
+ * STREAMING. This re-parses on every delta, against text that is by definition
+ * half-finished: a fence that has not closed, a `**` with no partner, a list
+ * item mid-word. Every one of those has to render as the thing it is turning
+ * into, not as an error and not as raw punctuation — so "unterminated" is a
+ * normal state of the input, not a parse failure.
+ *
+ * TYPOGRAPHY. The drawer's whole design is that hierarchy comes from type, not
+ * boxes. Rendering into our own small block/inline model means a heading is the
+ * 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.
+ */
+
+export type Inline =
+ | { kind: 'text'; text: string }
+ | { kind: 'code'; text: string }
+ | { kind: 'strong'; text: string }
+ | { kind: 'em'; text: string }
+ | { kind: 'link'; text: string; href: string };
+
+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 };
+
+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*$/;
+
+/**
+ * Split text into blocks. Total: any input is a valid document, because the
+ * input is a prefix of one.
+ */
+export function parseBlocks(source: string): Block[] {
+ const lines = source.split('\n');
+ const blocks: Block[] = [];
+ let paragraph: string[] = [];
+
+ const flushParagraph = () => {
+ if (paragraph.length === 0) return;
+ // Newlines inside a paragraph are kept as written. A model answering in a
+ // chat writes short lines on purpose; reflowing them the way a document
+ // renderer would loses the shape it chose.
+ blocks.push({ kind: 'p', spans: parseInline(paragraph.join('\n')) });
+ paragraph = [];
+ };
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const fence = FENCE.exec(line);
+ if (fence) {
+ flushParagraph();
+ const lang = fence[1] ?? '';
+ const body: string[] = [];
+ let closed = false;
+ for (i++; i < lines.length; i++) {
+ if (FENCE.test(lines[i])) { closed = true; break; }
+ body.push(lines[i]);
+ }
+ blocks.push({ kind: 'code', lang, text: body.join('\n'), open: !closed });
+ continue;
+ }
+
+ if (RULE.test(line)) {
+ flushParagraph();
+ blocks.push({ kind: 'rule' });
+ continue;
+ }
+
+ const heading = HEADING.exec(line);
+ if (heading) {
+ flushParagraph();
+ blocks.push({ kind: 'h', level: heading[1].length, spans: parseInline(heading[2]) });
+ continue;
+ }
+
+ const bullet = BULLET.exec(line);
+ const numbered = bullet ? null : NUMBERED.exec(line);
+ if (bullet || numbered) {
+ flushParagraph();
+ const ordered = !bullet;
+ const last = blocks[blocks.length - 1];
+ const item = parseInline((bullet ?? numbered)![1]);
+ if (last?.kind === 'list' && last.ordered === ordered) last.items.push(item);
+ else blocks.push({ kind: 'list', ordered, items: [item] });
+ continue;
+ }
+
+ if (line.trim() === '') {
+ flushParagraph();
+ continue;
+ }
+ paragraph.push(line);
+ }
+ flushParagraph();
+ return blocks;
+}
+
+// Code first: its content is literal, so a `**` inside a code span is two stars.
+const INLINE = [
+ { kind: 'code' as const, re: /`([^`\n]+)`/ },
+ { kind: 'link' as const, re: /\[([^\]\n]*)\]\(([^)\s]+)\)/ },
+ { kind: 'strong' as const, re: /\*\*([^*\n]+)\*\*/ },
+ { kind: 'em' as const, re: /(?<![*\w])\*([^*\n]+)\*(?!\*)/ },
+];
+
+/**
+ * Split one block's text into spans. An unterminated marker stays literal text
+ * — mid-stream that is exactly right, because the closing one is still coming
+ * and flickering the styling on and off as it arrives is worse than waiting.
+ */
+export function parseInline(source: string): Inline[] {
+ const spans: Inline[] = [];
+ let rest = source;
+
+ while (rest) {
+ let best: { at: number; len: number; span: Inline } | null = null;
+ for (const { kind, re } of INLINE) {
+ const m = re.exec(rest);
+ if (!m || (best && m.index >= best.at)) continue;
+ const span: Inline = kind === 'link'
+ ? { kind, text: m[1], href: m[2] }
+ : { kind, text: m[1] };
+ best = { at: m.index, len: m[0].length, span };
+ }
+ if (!best) break;
+ if (best.at > 0) spans.push({ kind: 'text', text: rest.slice(0, best.at) });
+ spans.push(best.span);
+ rest = rest.slice(best.at + best.len);
+ }
+ if (rest) spans.push({ kind: 'text', text: rest });
+ return spans;
+}
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index 56a30fb50..8c5b8f57f 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -17,7 +17,7 @@ export const agentMessages = defineMessages({
// — Drawer chrome —
'agent.newConversation': { en: 'New conversation', zh: '新对话' },
- 'agent.pin': { en: 'Pin as a column', zh: '固定成常驻列' },
+ 'agent.dock': { en: 'Move it into the layout', zh: '放进布局里' },
'agent.close': { en: 'Close (Esc)', zh: '关闭 (Esc)' },
'agent.compose': { en: 'Say something…', zh: '说点什么…' },
'agent.compose.busy': { en: 'It is working — this will be the next message…', zh: '正在干活,这条会排到下一轮…' },
diff --git a/desktop/src/layout/panelComponents.tsx b/desktop/src/layout/panelComponents.tsx
index 3b94476c6..584a7a852 100644
--- a/desktop/src/layout/panelComponents.tsx
+++ b/desktop/src/layout/panelComponents.tsx
@@ -32,6 +32,7 @@ import { AnimatorEditor } from '@/panels/AnimatorEditor';
import { BtTreeEditor } from '@/panels/BtTreeEditor';
import { ProfilerPanel } from '@/panels/ProfilerPanel';
import { PluginsPanel } from '@/panels/PluginsPanel';
+import { AgentPanel } from '@/components/AgentDrawer';
/** What a panel renderer is handed: its live panel id and dockview params. */
export interface PanelRenderContext {
@@ -82,6 +83,7 @@ export const PANEL_RENDERERS: Record<string, PanelRenderer> = {
behaviortree: () => <BtTreeEditor />,
profiler: () => <ProfilerPanel />,
plugins: () => <PluginsPanel />,
+ agent: () => <AgentPanel docked />,
game: () => <GamePanel />,
gameClient: ({ params }) => <GameClientPanel realmId={Number(params?.realmId ?? 0)} />,
};
diff --git a/desktop/src/layout/panels.ts b/desktop/src/layout/panels.ts
index 8bfba89f7..0361faf51 100644
--- a/desktop/src/layout/panels.ts
+++ b/desktop/src/layout/panels.ts
@@ -99,6 +99,11 @@ const BOTTOM: PanelDef[] = [
// Opened on demand rather than ensured: most sessions have no plugins, and a
// permanent tab for an empty list is noise.
{ id: 'plugins', title: () => t('plug.panelTitle'), placement: 'bottom', refs: ['log', 'content'] },
+ // The agent docks like everything else — draggable, tabbable beside Details,
+ // poppable to a second screen. The drawer over the workspace is the SAME
+ // panel summoned, exactly as the Content Browser has both. Not ensured: a
+ // permanent tab for a conversation nobody started is noise.
+ { id: 'agent', title: () => t('agent.title'), placement: 'side-right', width: 384 },
];
// Full editing canvases — opened on demand as center tabs beside the Viewport.
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index 55c29bb3d..a59a9562f 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -114,15 +114,13 @@ interface EditorState {
paletteOpen: boolean;
setPaletteOpen: (open: boolean) => void;
- // The built-in agent's conversation. Slides in over the right-hand panels
- // rather than squeezing the viewport: you look at properties or you talk to
- // the agent, and pinning turns the overlay into a fourth column for the times
- // you want both. The conversation itself lives in AgentStore.
+ // The built-in agent's conversation, SUMMONED over the right-hand panels. The
+ // same panel also docks (layout/panels.ts) — the Content Browser arrangement:
+ // one component, a tab you arrange and an overlay you call up without
+ // rearranging anything. The conversation itself lives in AgentStore.
agentDrawer: boolean;
toggleAgentDrawer: () => void;
setAgentDrawer: (open: boolean) => void;
- agentDrawerPinned: boolean;
- setAgentDrawerPinned: (pinned: boolean) => void;
// "New Tilemap" tileset chooser (Entity → New Tilemap): picks the .estileset
// palette for a fresh map, then createTilemapFromTileset does the rest.
@@ -232,8 +230,6 @@ export const useEditorStore = create<EditorState>((set) => ({
agentDrawer: false,
toggleAgentDrawer: () => set((s) => ({ agentDrawer: !s.agentDrawer })),
setAgentDrawer: (agentDrawer) => set({ agentDrawer }),
- agentDrawerPinned: false,
- setAgentDrawerPinned: (agentDrawerPinned) => set({ agentDrawerPinned }),
tilemapPickerOpen: false,
setTilemapPickerOpen: (tilemapPickerOpen) => set({ tilemapPickerOpen }),
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index 92186a581..7ef51cb1e 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -27,16 +27,10 @@
display: flex;
justify-content: flex-end;
}
-/* Pinned: an ordinary flex child of the workspace row — a real fourth column,
- no scrim, nothing dimmed, for when you do want both at once. */
-.ag-column { display: contents; }
-
.ag-drawer {
width: 384px;
max-width: 100vw;
flex: none;
- display: flex;
- flex-direction: column;
min-height: 0;
height: 100%;
background: var(--panel);
@@ -496,3 +490,64 @@
.ag-picker-it:hover { background: var(--hover); }
.ag-picker-it.on { color: var(--text-hi); }
.ag-picker-it.locked, .ag-picker-it.empty { color: var(--text-faint); font-family: var(--font-ui); }
+
+/* ── Markdown ───────────────────────────────────────────────────────────────
+ The model writes it; hierarchy still comes from type rather than boxes, so
+ headings are size and weight and a code block is the editor's own inset. */
+.md > :first-child { margin-top: 0; }
+.md > :last-child { margin-bottom: 0; }
+.md-p { margin: 0 0 9px; white-space: pre-wrap; overflow-wrap: anywhere; }
+.md-h { margin: 14px 0 7px; font-size: var(--fs-md); font-weight: 600; color: var(--text-hi); letter-spacing: -0.01em; }
+.md-list { margin: 0 0 9px; padding-left: 19px; }
+.md-list li { margin: 3px 0; }
+.md-list li::marker { color: var(--text-faint); }
+.md-rule { border: 0; border-top: 1px solid var(--line); margin: 12px 0; }
+.md-code {
+ font: var(--fs-xs) var(--font-mono);
+ padding: 1px 5px;
+ border-radius: 3px;
+ background: var(--inset);
+ color: var(--text-hi);
+ overflow-wrap: anywhere;
+}
+.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; }
+.md-pre-bar {
+ display: flex; align-items: center;
+ height: 24px;
+ padding: 0 4px 0 10px;
+ border-bottom: 1px solid var(--line);
+ font: var(--fs-2xs) var(--font-mono);
+ color: var(--text-faint);
+}
+.md-lang { flex: 1; }
+.md-pre-bar button {
+ width: 22px; height: 20px;
+ display: grid; place-items: center;
+ border-radius: 3px;
+ color: var(--text-faint);
+ transition: color var(--t-fast), background var(--t-fast);
+}
+.md-pre-bar button:hover { color: var(--text-hi); background: var(--hover); }
+.md-pre pre { margin: 0; padding: 9px 10px; overflow-x: auto; }
+.md-pre code { font: var(--fs-xs) / 1.7 var(--font-mono); color: var(--text); }
+/* Still being written — the closing fence has not arrived. */
+.md-pre.open { box-shadow: inset 2px 0 0 var(--nebula); }
+
+/* The caret that rides the tail of the text while tokens arrive. */
+.ag-caret {
+ display: inline-block;
+ width: 6px; height: 13px;
+ margin-left: 2px;
+ vertical-align: -2px;
+ background: var(--text);
+ animation: ag-blink 1.1s steps(2) infinite;
+}
+@keyframes ag-blink { 50% { opacity: 0; } }
+
+/* Docked, it is an ordinary panel: the shell owns the frame. */
+.ag-panel { display: flex; flex-direction: column; min-height: 0; height: 100%; background: var(--panel); }
+.ag-drawer .ag-panel { height: 100%; }
+/* Docked, the dock tab carries the title, so the head is just its actions. */
+.ag-head.docked { height: 30px; border-bottom: 1px solid var(--line-soft); }
diff --git a/desktop/tests/agent-markdown.test.ts b/desktop/tests/agent-markdown.test.ts
new file mode 100644
index 000000000..0de3e292b
--- /dev/null
+++ b/desktop/tests/agent-markdown.test.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Parsing what the model writes. The interesting cases are all PARTIAL:
+ * this re-parses on every streamed delta, so half a fence and an
+ * unmatched `**` are normal inputs, not malformed ones — and each has to
+ * render as the thing it is turning into.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseBlocks, parseInline } from '@/components/markdown';
+
+describe('blocks', () => {
+ it('reads a fenced block with its language', () => {
+ expect(parseBlocks('```ts\nconst a = 1;\n```')).toEqual([
+ { kind: 'code', lang: 'ts', text: 'const a = 1;', open: false },
+ ]);
+ });
+
+ // The closing fence arrives some tokens later. Until then this is a code
+ // block being written — not a paragraph that will later turn into one.
+ it('treats an unclosed fence as a block still being written', () => {
+ const [block] = parseBlocks('```ts\nconst a =');
+ expect(block).toEqual({ kind: 'code', lang: 'ts', text: 'const a =', open: true });
+ });
+
+ it('keeps consecutive list items in one list, and splits kinds', () => {
+ const blocks = parseBlocks('- one\n- two\n\n1. first\n2. second');
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0]).toMatchObject({ kind: 'list', ordered: false });
+ expect(blocks[1]).toMatchObject({ kind: 'list', ordered: true });
+ expect((blocks[0] as { items: unknown[] }).items).toHaveLength(2);
+ });
+
+ it('reads headings by depth', () => {
+ expect(parseBlocks('## Why')[0]).toMatchObject({ kind: 'h', level: 2 });
+ });
+
+ // A model answering in a chat writes short lines on purpose; reflowing them
+ // the way a document renderer would loses the shape it chose.
+ it('keeps the line breaks inside a paragraph', () => {
+ const [block] = parseBlocks('one\ntwo');
+ expect(block).toEqual({ kind: 'p', spans: [{ kind: 'text', text: 'one\ntwo' }] });
+ });
+
+ it('separates paragraphs on a blank line', () => {
+ expect(parseBlocks('a\n\nb')).toHaveLength(2);
+ });
+});
+
+describe('inline spans', () => {
+ it('picks out code, bold, italic and links', () => {
+ expect(parseInline('run `npm t` now')).toEqual([
+ { kind: 'text', text: 'run ' },
+ { kind: 'code', text: 'npm t' },
+ { kind: 'text', text: ' now' },
+ ]);
+ expect(parseInline('**bold**')).toEqual([{ kind: 'strong', text: 'bold' }]);
+ expect(parseInline('*soft*')).toEqual([{ kind: 'em', text: 'soft' }]);
+ expect(parseInline('[docs](https://x.dev)')).toEqual([
+ { kind: 'link', text: 'docs', href: 'https://x.dev' },
+ ]);
+ });
+
+ // Code content is literal — a star inside a code span is a star.
+ it('does not read markup inside a code span', () => {
+ expect(parseInline('`a **b** c`')).toEqual([{ kind: 'code', text: 'a **b** c' }]);
+ });
+
+ // Flickering the styling on as the closing marker lands is worse than waiting.
+ it('leaves an unterminated marker as plain text', () => {
+ expect(parseInline('half **way')).toEqual([{ kind: 'text', text: 'half **way' }]);
+ expect(parseInline('an `open')).toEqual([{ kind: 'text', text: 'an `open' }]);
+ });
+
+ it('prefers bold over italic when both could match', () => {
+ expect(parseInline('**x**')).toEqual([{ kind: 'strong', text: 'x' }]);
+ });
+});