惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
M
MIT News - Artificial intelligence
美团技术团队
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
有赞技术团队
有赞技术团队
L
LangChain Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
S
SegmentFault 最新的问题
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
B
Blog
I
InfoQ

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
[type='CNAME'] crashed my Textual TUI: why escaping user ...
Nazarii Ahapevych · 2026-06-29 · via DEV Community

The setup

I have been building a small tool called claude-relay. It passes messages between terminal sessions running on the same machine: one session finishes a piece of work, sends a short message, another session picks it up. Think of it as a tiny local message queue with a chat-style front end.

That front end is a terminal UI built with Textual and Rich. It lists incoming messages and renders the selected one as a chat bubble. The catch is that the message bodies are not clean strings I wrote. They are whatever a session decided to send: shell output, stack traces, Terraform plans, ticket IDs. The TUI has to render arbitrary text from outside my control. That is the detail that turned out to matter.

The crash

One day a message arrived with a Terraform error in the body. I selected it, and the entire UI died:

MarkupError: Expected markup value (found "='CNAME'] but it already exists]\n").

The text that triggered it was completely ordinary:

Error: [type='CNAME'] but it already exists

A bracketed token inside an error message. Harmless in a log file. But Textual and Rich treat square brackets as markup, so that one message took down the whole interface. Worse, any message containing brackets would do the same, and brackets are everywhere in developer output: ticket tags, type hints, array syntax, that Terraform error. The tool was unusable the moment real data flowed through it.

Why a bracket is a bomb

Rich uses [...] for inline styling: [b]bold[/b], [dim]quiet[/dim], [red]alert[/red]. Textual renders on top of Rich, so any string you hand to a widget's update() runs through that markup parser first.

My message bubble was built the obvious way:

child.update(f"[b]{direction}[/b]\n{msg.body}")

When msg.body contains [type='CNAME'], the parser sees a tag named type='CNAME', cannot make sense of it, and throws. The fix looked trivial. It took four commits and three wrong turns to actually get right.

Wrong turn 1: escape the user content

The textbook move is to escape anything that came from outside, and Rich ships rich.markup.escape() for exactly this. I wrapped every user-supplied field in it (from_peer, to_peer, subject, body) across eight files.

It still crashed.

The reason took a while to surface. Textual 8.x no longer renders through Rich's markup tokeniser. It has its own visualize path, and that path does not honour Rich's backslash-escape convention. escape() dutifully turned [ into \[, and Textual's parser choked anyway. Escaping is parser-specific: an escape that satisfies one tokeniser means nothing to another.

Wrong turn 2: my own template had brackets in it

While chasing the user content, I missed that I had planted brackets myself. My truncation suffix read:

"\n[dim]…[truncated, press Enter to view full][/dim]"

[truncated, press Enter to view full] is a bracketed phrase sitting inside [dim]...[/dim]. The parser reads it as a nested tag. The call was crashing on a string I wrote, not on any user data. Swapping the inner brackets for parentheses fixed that case:

"\n[dim](truncated, press Enter to view full)[/dim]"

The lesson I keep relearning: the parser parses your templates too, not only the data you pour into them.

The fix that holds: never let the parser see user text

Here is the actual answer, stated plainly. Stop mixing the two worlds. Parse markup only for the parts you control, and append everything from outside as literal text that never reaches the parser.

In practice that means building a rich.text.Text object instead of a markup string. Static.update() accepts a Text renderable and prints it as-is:

rendered = Text.from_markup(header)   # only the parts WE control
rendered.append("\n")
rendered.append(body_text)            # user content, literal: parser never sees it
child.update(rendered)

Brackets in the body now render as brackets, because the body is never parsed as markup at all.

Wrong turn 3: even Text composition has a trap

I applied the same idea to the message-detail view and it crashed again:

MarkupError: closing tag '[/b]' doesn't match any open tag

I had built the title as a chain of from_markup calls:

# each from_markup() parses on its own, so the lone [/b] has nothing to close
title = Text.from_markup("[b]")
title.append(subject)
title.append_text(Text.from_markup("[/b] ..."))

Text.from_markup() is a parser, not a concatenator. Each call parses independently, so a dangling [/b] in a later call has no matching open tag. The fix is to drop markup syntax for programmatic styling and use the API directly:

title = Text()
title.append(subject, style="bold")
title.append(f"   ({msg.state.value})", style="dim")

No parser involved. No way to crash.

Where it landed

After those four commits the TUI renders arbitrary message bodies cleanly. The rule I walked away with is simple: markup syntax is a template language, and the programmatic Text API is for code. The moment you split [b]...[/b] across function calls or interpolate a variable into a markup string, you are writing code, so take the code path. Markup strings are safe only for fully self-contained, balanced literals: a fixed help line, a status glyph like [yellow]●[/yellow].

One more thing that made this hard to catch: these bugs hide from your tests. Textual's run_test(headless=True) renders to a virtual screen that does not exercise the same path as a real terminal launch. Every one of these crashes appeared only when I ran the real app against real data. My regression tests now feed the renderer the genuinely nasty inputs on purpose: [type='CNAME'], [ABC-1234], list[int], a markdown link.

It is the same discipline as escaping on output in HTML. Trust no string with brackets that came from outside your code, and remember the parser is just as happy to choke on a bracket you wrote yourself.