Agent Zero AI framework
Render composer code blocks from typed fences
Alessandrob805773c91ae
diff --git a/tests/test_welcome_composer_static.py b/tests/test_welcome_composer_static.pyindex f31f6a429..c5a4dc8ad 100644--- a/tests/test_welcome_composer_static.py+++ b/tests/test_welcome_composer_static.py@@ -145,13 +145,18 @@ def test_welcome_hover_and_focus_borders_use_neutral_tokens() -> None:assert "border-color: color-mix(in srgb, var(--color-border) 88%, var(--color-text) 12%)" in surfaces-def test_composer_uses_rubik_until_caret_enters_fenced_code() -> None:+def test_composer_creates_visual_code_blocks_from_entered_fence() -> None:chat_bar = _read("webui/components/chat/input/chat-bar-input.html")input_store = _read("webui/components/chat/input/input-store.js")+ assert 'contenteditable="true"' in chat_barassert "font-family: var(--font-family-main" in chat_bar- assert "#chat-input.is-code-context" in chat_bar+ assert ".composer-code-content" in chat_barassert "font-family: var(--font-family-code" in chat_bar- assert "'is-code-context': $store.chatInput.isCodeContext" in chat_bar- assert "_isCaretInsideFence(text, index)" in input_store- assert "matches.length % 2 === 1" in input_store+ assert "FENCE_LINE_RE" in input_store+ assert "_tryCreateCodeBlock($event)" in input_store+ assert 'data-code-block' in input_store+ assert "handlePaste($event)" in input_store+ assert "_insertPlainText(text)" in input_store+ assert "is-code-context" not in chat_bar+ assert "_isCaretInsideFence" not in input_storediff --git a/webui/components/chat/AGENTS.md b/webui/components/chat/AGENTS.mdindex 6203b8976..fc422316c 100644--- a/webui/components/chat/AGENTS.md+++ b/webui/components/chat/AGENTS.md@@ -18,7 +18,7 @@- Use shared API, WebSocket, notification, and attachment helpers where available.- Do not bypass CSRF or WebSocket state-sync expectations.- The shared composer can be mounted on the Welcome screen with no selected chat; sending from that state must create and select a chat context before dispatch.-- Composer text uses the main UI font by default and switches to the code font while the caret is inside an open triple-backtick fenced block.+- Composer text uses the main UI font by default; typing a triple-backtick fence and pressing Enter turns that line into a visual code block that serializes back to fenced Markdown, while pasted fenced Markdown stays plain text.## Work Guidancediff --git a/webui/components/chat/input/chat-bar-input.html b/webui/components/chat/input/chat-bar-input.htmlindex f79ecf8b4..f40494da0 100644--- a/webui/components/chat/input/chat-bar-input.html+++ b/webui/components/chat/input/chat-bar-input.html@@ -24,17 +24,16 @@</div></div>- <!-- Container for textarea and expand button -->+ <!-- Container for composer and expand button --><div id="chat-input-container">- <textarea id="chat-input" :placeholder="$store.chatInput.inputPlaceholder" rows="1"- @keydown.enter="if (!$event.shiftKey && !$event.isComposing && $event.keyCode !== 229) { $event.preventDefault(); $store.chatInput.sendMessage(); }"- @keydown.up="$store.chatInput.historyPrev($event)" @keydown.down="$store.chatInput.historyNext($event)"+ <div id="chat-input" role="textbox" aria-label="Message" aria-multiline="true" contenteditable="true"+ spellcheck="true" :data-placeholder="$store.chatInput.inputPlaceholder"+ @keydown="$store.chatInput.handleKeydown($event)"@input="$store.chatInput.handleInput($event)"- @keyup="$store.chatInput._syncCaretFromEvent($event)"- @click="$store.chatInput._syncCaretFromEvent($event)"- @select="$store.chatInput._syncCaretFromEvent($event)"- :class="{ 'progress-active': $store.chatInput.progressActive, 'is-code-context': $store.chatInput.isCodeContext }"- x-model="$store.chatInput.message"></textarea>+ @paste="$store.chatInput.handlePaste($event)"+ :class="{ 'progress-active': $store.chatInput.progressActive, 'is-empty': !$store.chatInput.message }"+ x-create="$store.chatInput.mountEditor($el)"+ x-destroy="$store.chatInput.unmountEditor($el)"></div><div id="chat-input-progress-placeholder" x-show="$store.chatInput.showProgressPlaceholder"x-html="$store.chatInput.progressPlaceholderHtml":class="{ 'progress-active': $store.chatInput.progressActive }" aria-hidden="true" style="display: none;">@@ -174,6 +173,8 @@padding: 0.68rem 2.2rem 0.68rem 0.1rem;margin: 0;overflow-y: auto;+ white-space: pre-wrap;+ word-break: break-word;scroll-behavior: smooth;resize: none;align-content: center;@@ -183,10 +184,30 @@-webkit-transition: color 0.16s ease, background-color 0.16s ease;}- #chat-input.is-code-context {+ #chat-input.is-empty::before {+ content: attr(data-placeholder);+ color: color-mix(in srgb, var(--color-text) 62%, transparent);+ opacity: 0.78;+ pointer-events: none;+ }++ #chat-input .composer-code-block {+ display: block;+ margin: 0.48rem 0;+ padding: 0.56rem 0.7rem;+ border-radius: 6px;+ background: color-mix(in srgb, var(--color-border) 28%, transparent);+ }++ #chat-input .composer-code-content {+ min-height: 1.35rem;+ margin: 0;+ outline: none;+ white-space: pre-wrap;+ word-break: break-word;font-family: var(--font-family-code, "Roboto Mono", monospace);font-size: 0.94rem;- align-content: start;+ line-height: 1.45;}#chat-input::-webkit-scrollbar {@@ -216,14 +237,8 @@background-color: transparent;}- #chat-input::placeholder {- color: color-mix(in srgb, var(--color-text) 62%, transparent);- opacity: 0.78;- transition: color 0.16s ease;- }-/* Progress ghost text animation — gentle pulse on placeholder */- #chat-input.progress-active::placeholder {+ #chat-input.progress-active.is-empty::before {animation: placeholder-pulse 2s ease-in-out infinite;}diff --git a/webui/components/chat/input/input-store.js b/webui/components/chat/input/input-store.jsindex caf6129b8..ca1fd3ead 100644--- a/webui/components/chat/input/input-store.js+++ b/webui/components/chat/input/input-store.js@@ -7,6 +7,8 @@ import { store as attachmentsStore } from "/components/chat/attachments/attachmeimport { store as chatsStore } from "/components/sidebar/chats/chats-store.js";const ICON_MARKER_RE = /icon:\/\/([a-zA-Z0-9_]+)(\[(?:\\.|[^\]])*\])?/g;+const FENCE_LINE_RE = /^```([A-Za-z0-9_-]*)?$/;+const BLOCK_TAGS = new Set(["DIV", "P", "LI"]);function escapeHTML(value) {return String(value ?? "")@@ -48,7 +50,8 @@ function convertIconMarkersToHtml(value) {const model = {paused: false,- message: "",+ _message: "",+ _editorEl: null,_history: [],_historyIndex: null,_draft: "",@@ -57,7 +60,15 @@ const model = {chatMoreMenuOpen: false,progressText: "",progressActive: false,- _caretIndex: 0,++ get message() {+ return this._message;+ },++ set message(value) {+ this._message = String(value ?? "");+ this._renderEditorFromText(this._message);+ },toggleChatMoreMenu() {this.chatMoreMenuOpen = !this.chatMoreMenuOpen;@@ -85,10 +96,6 @@ const model = {return "Type your message here...";},- get isCodeContext() {- return this._isCaretInsideFence(this.message, this._caretIndex);- },-get showProgressPlaceholder() {return (!!chatsStore.selected &&@@ -135,6 +142,8 @@ const model = {},async sendMessage() {+ this._syncMessageFromEditor();+// Capture sent prompt to per-chat history (bash-style)try { this._pushHistory(this.message); } catch (_e) { /* ignore */ }@@ -149,48 +158,244 @@ const model = {}},+ mountEditor(editor) {+ this._editorEl = editor;+ this._renderEditorFromText(this._message);+ this.adjustTextareaHeight({ target: editor });+ },++ unmountEditor(editor) {+ if (this._editorEl === editor) this._editorEl = null;+ },+_composerTextareas(target = null) {- if (target?.tagName === "TEXTAREA") return [target];- return ["chat-input"]- .map((id) => document.getElementById(id))- .filter(Boolean);+ const editor = target?.closest?.("#chat-input") || this._editorEl || document.getElementById("chat-input");+ return editor ? [editor] : [];},_activeTextarea() {const active = document.activeElement;- if (active?.id === "chat-input") {- return active;+ const activeEditor = active?.closest?.("#chat-input");+ if (activeEditor) {+ return activeEditor;}- return document.getElementById("chat-input");+ return this._editorEl || document.getElementById("chat-input");},- _syncCaretFromEvent($event = null) {- const ta = ($event && $event.target?.tagName === "TEXTAREA")- ? $event.target- : this._activeTextarea();- if (!ta) {- this._caretIndex = this.message.length;- return;+ _renderEditorFromText(text) {+ const editor = this._editorEl;+ if (!editor) return;+ if (editor.textContent !== text || editor.querySelector("[data-code-block]")) {+ editor.textContent = text;+ }+ this._setEditorEmptyState();+ },++ _setEditorEmptyState() {+ const editor = this._editorEl;+ if (editor) editor.classList.toggle("is-empty", !this._message);+ },++ _createCodeBlock(lang = "") {+ const block = document.createElement("div");+ block.className = "composer-code-block";+ block.dataset.codeBlock = "true";+ block.dataset.lang = lang;+ block.contentEditable = "false";++ const code = document.createElement("pre");+ code.className = "composer-code-content";+ code.dataset.codeContent = "true";+ code.contentEditable = "true";+ code.spellcheck = false;+ code.setAttribute("aria-label", "Code block");+ block.append(code);++ return block;+ },++ _plainText(node) {+ if (!node) return "";+ if (node.nodeType === Node.TEXT_NODE) return node.nodeValue || "";+ if (node.nodeType !== Node.ELEMENT_NODE) return "";+ if (node.matches?.("[data-code-block]")) {+ const lang = node.dataset.lang || "";+ const code = this._plainText(node.querySelector("[data-code-content]")).replace(/\n$/, "");+ return "```" + lang + "\n" + code + "\n```";+ }+ if (node.tagName === "BR") return "\n";++ let text = "";+ for (const child of node.childNodes) text += this._plainText(child);+ if (node !== this._editorEl && BLOCK_TAGS.has(node.tagName) && text && !text.endsWith("\n")) {+ text += "\n";+ }+ return text;+ },++ _editorToMarkdown() {+ return this._plainText(this._editorEl).replace(/\n$/, "");+ },++ _syncMessageFromEditor() {+ if (!this._editorEl) return;+ this._message = this._editorToMarkdown();+ this._setEditorEmptyState();+ },++ _isInCodeBlock(target) {+ return Boolean(target?.closest?.("[data-code-content]"));+ },++ _selectionOffsets(editor) {+ const selection = document.getSelection?.();+ if (!selection || selection.rangeCount === 0 || !editor) {+ return { start: this._message.length, end: this._message.length };}- this._caretIndex = Number.isFinite(ta.selectionStart) ? ta.selectionStart : this.message.length;+ const range = selection.getRangeAt(0);+ if (!editor.contains(range.startContainer) || !editor.contains(range.endContainer)) {+ return { start: this._message.length, end: this._message.length };+ }++ const before = range.cloneRange();+ before.selectNodeContents(editor);+ before.setEnd(range.startContainer, range.startOffset);++ const selected = range.cloneRange();+ return {+ start: before.toString().length,+ end: before.toString().length + selected.toString().length,+ };+ },++ _setEditorCaret(offset) {+ const editor = this._activeTextarea();+ const selection = document.getSelection?.();+ if (!editor || !selection) return;++ editor.focus();+ const range = document.createRange();+ let remaining = Math.max(0, Number(offset) || 0);+ const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);+ let node = walker.nextNode();++ while (node) {+ const length = node.nodeValue.length;+ if (remaining <= length) {+ range.setStart(node, remaining);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+ return;+ }+ remaining -= length;+ node = walker.nextNode();+ }++ range.selectNodeContents(editor);+ range.collapse(false);+ selection.removeAllRanges();+ selection.addRange(range);+ },++ _focusCodeBlock(block) {+ queueMicrotask(() => {+ const code = block.querySelector("[data-code-content]");+ const selection = document.getSelection?.();+ if (!code || !selection) return;+ code.focus();+ const range = document.createRange();+ range.selectNodeContents(code);+ range.collapse(false);+ selection.removeAllRanges();+ selection.addRange(range);+ });+ },++ _insertPlainText(text) {+ const selection = document.getSelection?.();+ if (!selection || selection.rangeCount === 0) return false;+ const range = selection.getRangeAt(0);+ range.deleteContents();+ const node = document.createTextNode(text);+ range.insertNode(node);+ range.setStart(node, node.nodeValue.length);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+ return true;},- _isCaretInsideFence(text, index) {- const source = String(text || "");- const caret = Math.max(0, Math.min(source.length, Number(index) || 0));- const matches = source.slice(0, caret).match(/```/g);- return Boolean(matches && matches.length % 2 === 1);+ _tryCreateCodeBlock($event) {+ const editor = this._activeTextarea();+ const selection = document.getSelection?.();+ if (!editor || !selection || selection.rangeCount === 0) return false;++ const range = selection.getRangeAt(0);+ if (!range.collapsed || !editor.contains(range.startContainer)) return false;+ if (this._isInCodeBlock(range.startContainer.parentElement)) return false;++ const before = range.cloneRange();+ before.selectNodeContents(editor);+ before.setEnd(range.startContainer, range.startOffset);++ const after = range.cloneRange();+ after.selectNodeContents(editor);+ after.setStart(range.startContainer, range.startOffset);++ const lineBefore = before.toString().split("\n").pop() || "";+ const lineAfter = (after.toString().split("\n")[0] || "");+ const match = (lineBefore + lineAfter).match(FENCE_LINE_RE);+ if (!match || lineAfter) return false;+ if (range.startContainer.nodeType !== Node.TEXT_NODE || range.startOffset < lineBefore.length) return false;++ $event.preventDefault();+ const editRange = range.cloneRange();+ editRange.setStart(range.startContainer, range.startOffset - lineBefore.length);+ editRange.deleteContents();++ const block = this._createCodeBlock(match[1] || "");+ editRange.insertNode(block);+ block.after(document.createTextNode("\n"));+ this._focusCodeBlock(block);+ this._syncMessageFromEditor();+ this.adjustTextareaHeight({ target: editor });+ return true;},handleInput($event) {- this._syncCaretFromEvent($event);+ this._syncMessageFromEditor();this.adjustTextareaHeight($event);},+ handlePaste($event) {+ const text = $event.clipboardData?.getData("text/plain");+ if (text === undefined) return;+ $event.preventDefault();+ this._insertPlainText(text);+ this.handleInput($event);+ },++ handleKeydown($event) {+ if ($event.isComposing || $event.keyCode === 229) return;++ if ($event.key === "Enter") {+ if (this._isInCodeBlock($event.target)) return;+ if (!$event.shiftKey) {+ if (this._tryCreateCodeBlock($event)) return;+ $event.preventDefault();+ this.sendMessage();+ }+ return;+ }++ if ($event.key === "ArrowUp") this.historyPrev($event);+ if ($event.key === "ArrowDown") this.historyNext($event);+ },+adjustTextareaHeight($event = null) {const target = $event?.target || null;for (const chatInput of this._composerTextareas(target)) {- if (!this.message) chatInput.value = "";chatInput.style.height = "auto";chatInput.style.height = chatInput.scrollHeight + "px";// pick up any layout shift triggered by the height assignment@@ -437,11 +642,10 @@ const model = {_setCaretStart() {queueMicrotask(() => {- const ta = this._activeTextarea();- if (ta) {- try { ta.setSelectionRange(0, 0); } catch (_e) { /* ignore */ }- try { ta.scrollTop = 0; } catch (_e) { /* ignore */ }- this._syncCaretFromEvent({ target: ta });+ const editor = this._activeTextarea();+ if (editor) {+ this._setEditorCaret(0);+ try { editor.scrollTop = 0; } catch (_e) { /* ignore */ }}this.adjustTextareaHeight();});@@ -449,12 +653,10 @@ const model = {_setCaretEnd() {queueMicrotask(() => {- const ta = this._activeTextarea();- if (ta) {- const end = ta.value.length;- try { ta.setSelectionRange(end, end); } catch (_e) { /* ignore */ }- try { ta.scrollTop = ta.scrollHeight; } catch (_e) { /* ignore */ }- this._syncCaretFromEvent({ target: ta });+ const editor = this._activeTextarea();+ if (editor) {+ this._setEditorCaret(editor.innerText.length);+ try { editor.scrollTop = editor.scrollHeight; } catch (_e) { /* ignore */ }}this.adjustTextareaHeight();});@@ -462,10 +664,10 @@ const model = {historyPrev($event) {if ($event && ($event.isComposing || $event.keyCode === 229)) return;- const ta = ($event && $event.target) ? $event.target : this._activeTextarea();- if (!ta) return;- const start = ta.selectionStart;- const end = ta.selectionEnd;+ if (this._isInCodeBlock($event?.target)) return;+ const editor = this._activeTextarea();+ if (!editor) return;+ const { start, end } = this._selectionOffsets(editor);if (start !== 0 || end !== 0) return;$event.preventDefault();this._ensureHistoryLoaded();@@ -484,12 +686,12 @@ const model = {historyNext($event) {if ($event && ($event.isComposing || $event.keyCode === 229)) return;- const ta = ($event && $event.target) ? $event.target : this._activeTextarea();- if (!ta) return;- const value = ta.value;- const start = ta.selectionStart;- const end = ta.selectionEnd;- if (start !== value.length || end !== value.length) return;+ if (this._isInCodeBlock($event?.target)) return;+ const editor = this._activeTextarea();+ if (!editor) return;+ const { start, end } = this._selectionOffsets(editor);+ const valueLength = editor.innerText.length;+ if (start !== valueLength || end !== valueLength) return;$event.preventDefault();if (this._historyIndex === null) return;if (this._historyIndex < this._history.length - 1) {@@ -507,7 +709,6 @@ const model = {this.message = "";attachmentsStore.clearAttachments();this.chatMoreMenuOpen = false;- this._caretIndex = 0;this._historyIndex = null;this._draft = "";this.adjustTextareaHeight();diff --git a/webui/components/modals/full-screen-input/full-screen-store.js b/webui/components/modals/full-screen-input/full-screen-store.jsindex 71b05691a..8ec1551c0 100644--- a/webui/components/modals/full-screen-input/full-screen-store.js+++ b/webui/components/modals/full-screen-input/full-screen-store.js@@ -1,4 +1,5 @@import { createStore } from "/js/AlpineStore.js";+import { store as chatInputStore } from "/components/chat/input/input-store.js";// Store model for the Full-Screen Input Modalconst model = {@@ -18,8 +19,7 @@ const model = {// Open modal with current chat input contentopenModal() {- const chatInput = document.getElementById("chat-input");- this.inputText = chatInput ? chatInput.value : this.inputText;+ this.inputText = chatInputStore.message || "";this.lastSavedState = this.inputText;this.isOpen = true;this.undoStack = [];@@ -34,11 +34,8 @@ const model = {// Close modal and write value back into main chat inputhandleClose() {- const chatInput = document.getElementById("chat-input");- if (chatInput) {- chatInput.value = this.inputText;- chatInput.dispatchEvent(new Event("input")); // trigger auto-resize- }+ chatInputStore.message = this.inputText;+ chatInputStore.adjustTextareaHeight();this.isOpen = false;},@@ -88,4 +85,3 @@ const model = {export const store = createStore("fullScreenInputModal", model);-diff --git a/webui/components/welcome/welcome-screen.html b/webui/components/welcome/welcome-screen.htmlindex f963427a2..299cfba3d 100644--- a/webui/components/welcome/welcome-screen.html+++ b/webui/components/welcome/welcome-screen.html@@ -862,12 +862,12 @@align-content: center;}- .welcome-composer #chat-input:placeholder-shown {+ .welcome-composer #chat-input.is-empty {overflow-y: hidden;scrollbar-width: none;}- .welcome-composer #chat-input:placeholder-shown::-webkit-scrollbar {+ .welcome-composer #chat-input.is-empty::-webkit-scrollbar {display: none;}@@ -938,7 +938,7 @@}@media (max-width: 420px) {- .welcome-composer #chat-input:placeholder-shown {+ .welcome-composer #chat-input.is-empty {min-height: 5rem;padding-top: 0.52rem;padding-bottom: 0.52rem;