返回资讯中心
外部精选
软件工程
#开发者实时流

Building a thread UI on hard mode – Zed

When you use Delta, one of the first differences you’ll notice is that threads don’t use the familiar chat UI. Instead of a message box and bubbles, you just start writing your prompt in a blank box, and when you press …

Hacker News 最新intstarstar2026/11/10 · 7 天前30 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

When you use Delta, one of the first differences you’ll notice is that threads don’t use the familiar chat UI. Instead of a message box and bubbles, you just start writing your prompt in a blank box, and when you press enter, the agent replies right underneath it. You can freely move the cursor from your composer into the agent response and its tool calls, and start typing to annotate any part of it (even terminals).

That’s because the thread is a document that your team and agents collaborate on. The code changes are part of it, so any line of code leads back to the conversation that made it.

To make that work, we had to build a new kind of editor.

Our team has a lot of experience building fast text editors. So for Delta, we started with a very similar architecture to Zed’s editor, which involves a hierarchy of indexes that map the buffer to the screen, updated incrementally as the text changes.

After a number of iterations, we kept running into bugs where those indexes drifted from what the thread should look like.

A code editor mostly draws the buffer’s text so the indexes can follow its edits. By contrast, a thread is full of richer, stateful elements like tool calls that change status as they run, terminals streaming live output, and foldable cards. Each of them changes what we draw without touching the text, and the indexes had to keep up with all of them.

So we had to start over and ask: what is the least state we can get away with?

Let’s build an editor from first principles.

The simplest thing an editor needs to do is show and edit plain text. This part is easy.

To store the text, we’ll use DeltaDB’s Buffer, a text CRDT powered by a Rope. The library takes care of replicating edits across all collaborators and merging them without conflicts. Antonio wrote about how DeltaDB works in more detail.

struct Editor { buffer: Replica<Buffer>, focus_handle: FocusHandle, selection: Range<usize>, }

To draw it, we skip flexbox and implement GPUI’s Element trait, which gives us full control over drawing. It works in three phases: request_layout sizes the element, prepaint works out what to draw, and paint draws it. Most of the magic happens in prepaint, where we walk the buffer line by line, shape each line, and carry a y position down the screen:

type PrepaintState = Vec<(ShapedLine, Pixels)>;

fn prepaint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) -> Self::PrepaintState { let snapshot = self.buffer.update(|buffer, cx| buffer.as_snapshot(cx)); let mut lines = Vec::new(); let mut y = bounds.origin.y;

for line in snapshot.text().as_rope().lines() { let run = TextRun { len: line.len(), font: FONT.clone(), color: TEXT_COLOR, ..Default::default() }; lines.push((window.text_system().shape_line(line, FONT_SIZE, &[run]), y)); y += LINE_HEIGHT; }

lines }

Shaping turns the text into positioned glyphs we can draw and measure. The Vec of shaped lines is our PrepaintState, and paint draws each line at its y.

To make it editable, we implement GPUI’s EntityInputHandler trait, which connects us to the platform’s text input. This is what the other two fields are for: the focus handle lets the window route keystrokes to us, and selection is the byte range where the next one goes. When the user types, the platform hands us the text, and we insert it there:

fn replace_text_in_range(&mut self, range_utf16: Option<Range<usize>>, text: &str, window: &mut Window, cx: &mut Context<Self>) { let range = range_utf16 .map(|range| self.range_from_utf16(&range)) .unwrap_or(self.selection.clone()); self.buffer.update(|buffer, cx| buffer.edit([(range.clone(), text)], cx)); self.selection = range.start + text.len()..range.start + text.len(); cx.notify(); }

The edit goes straight into the buffer, and cx.notify() requests another frame which will paint the updated text.

At this point we have something resembling a plain text input, with very little state. We’ll try to keep it that way.

0:00

0:00

0:00

SettingsQualityAuto

Audio

Speed1×

CaptionsOff

Typing into the basic plain-text editor.

Of course, a lot is missing: a cursor, soft wrapping, scrolling (that last one will turn out to matter a great deal).

Plain text is great, but a Delta thread needs rich text: Markdown, code blocks, tool cards. Should we build those into the editor? The same editor also powers surfaces that aren’t threads, like the file pane, and each surface wants something different.

That’s a good sign the editor shouldn’t be the one deciding. Instead, we’ll give it a formatter: a function we write that reads the buffer and tells the editor how it should look. It receives a DocumentBuilder, which lets it style ranges of the buffer. This simple one captures messages and iterates over them, making each author’s range bold:

let editor = cx.new(|cx| Editor::new(buffer, cx)); editor.update(cx, |editor, _| { editor.set_formatter(move |doc: &mut DocumentBuilder| { // Each message knows the byte range of its author. for message in &messages { doc.run(message.author_range.clone(), TextStyleRefinement { font_weight: Some(FontWeight::BOLD), ..Default::default() }); } }); });

The doc.run call simply records the specified range and TextStyleRefinement into a Vec.

Our prepaint now calls the formatter first. Then, instead of shaping each line as one run, it splits the line wherever a styled range starts or ends. The ranges are sorted up front, so we only pass over them once. paint doesn’t change yet.

In Delta, the real DocumentBuilder goes much further. For example, it can omit text (hiding Markdown’s **), replace it (rendering < as <), draw blocks and tables, mark regions read-only, add gutter decorations like author avatars, and embed GPUI elements.

All of it is attached to ranges of the buffer, so the cursor reaches everything: you can select across a table or comment on a tool card just like plain text. Event handlers attach to ranges too, which enables some really interesting interactivity.

Notice that the editor still keeps almost no state. It’s an immediate-mode UI, so for every frame, the formatter describes the thread from scratch.

But what happens when the document gets really long and becomes taller than the window? We have new problems to solve, and extra state.

We know the editor has to remember where the reader is, so we’re going to need more state. But what’s the least we can get away with?

The first thing you might try is a pixel position, which is how far down the document the screen starts:

struct Editor { // ... scroll_top: Pixels, }

That works until something above the screen changes.

In a Delta thread, that happens all the time. Teammates can add comments anywhere, or a tool call updates, or the window resizes so the text rewraps. Each change pushes everything below it down, and what you’re reading slides away.

screen

This is exactly the kind of jank we work hard to avoid at Zed. And we can make it impossible by construction, thanks to one of the coolest features of DeltaDB’s Buffer: the BufferAnchor.

An anchor identifies a character by the insertion that typed it and how far into that insertion it is. That identity never changes, so the buffer can always find the character and work out its current offset.

We store an anchor to the first buffer line visible on screen, and the pixel offset from the top of that line to the top of the screen:

struct Editor { // ... scroll_anchor: BufferAnchor, scroll_offset: Pixels, }

Now when something above the screen changes, the screen moves with that line. Selections are anchors too, so your cursor stays put when someone else types.

screen

Now prepaint can start at the anchored line and lay out downward until the screen is full. This lets us skip laying out anything offscreen.

But the formatter still describes the whole document from scratch on every frame.

That’s a lot of formatting to do on every frame while you scroll and type, and while agents and terminals stream output.

Fortunately for us, the screen is only so tall: 40–60 lines on a laptop, maybe 120 on vertical monitors. Because the scroll position is an anchor, you can’t tell whether we format anything you’ve scrolled past or haven’t reached yet.

The editor can resolve scroll_anchor to a buffer offset and pass it to the formatter, which can then skip everything before it.

In our example, messages is in the same order as the buffer, and each message also knows its full range, so we can binary-search for the first one that reaches the screen:

editor.set_formatter(move |doc: &mut DocumentBuilder| { let start = doc.start_offset(); let first = messages.partition_point(|message| { message.range.end <= start }); for message in &messages[first..] { // Style the message as in step 2. } });

screen

Great! Now all messages above the screen are skipped.

In Delta, messages are stored in a B+ tree we can seek through efficiently. A single message can hold several pages’ worth of Markdown and tool calls, so we skip at a much finer grain than whole messages.

By indexing enclosing Markdown blocks (code fences, tables, and so on), we can skip most of the work for offscreen lines. The same applies to inline diffs, terminal output, and most tools with significant output.

But what about the messages below the screen?

Unfortunately for us, while the editor knows the height of the screen, it doesn’t know ahead of time how much of the buffer it will take to fill it. That depends on the formatting itself! The formatter might set a completely different font size (like Markdown headings), hide text altogether, turn soft wrapping on or off, insert a 300px image, and so on.

We can solve this by having the formatter yield to the editor at the end of each message:

editor.set_formatter(move |doc: &mut DocumentBuilder| { let start = doc.start_offset(); let first = messages.partition_point(|message| { message.range.end <= start }); for message in &messages[first..] { // Style the message as in step 2. if doc.commit_to(message.range.end).is_break() { break; } } });

skippednever formattedContinuescreen

doc.commit_to tells the editor that we’ve finished formatting everything up to the end of this message, so it can lay out those lines using the styles gathered so far. Once the screen is full, it returns ControlFlow::Break, and the formatter stops.

As with skipping, Delta commits at a much finer grain than whole messages. Even deep within nested content, there are convenient boundaries where we can yield to the editor and stop once the screen is full.

At this point, you can scroll through a long thread without breaking a sweat. We got away with this without any retained layout indexes to keep in sync, right? RIGHT?!

Bad news: scrollbars exist, and they want to know the total height of the thread.

This frustrated me at first; we have an editor that can completely power the thread UI, in a way that’s much easier to reason about than with previous iterations, and now we have to think about scrollbars!

The scrollbar is not how I navigate the thread. Most of the time I’m interested in a small area around the tail, so I can easily swipe my trackpad through it.

Even for bigger jumps, there are better tools than a scrollbar. Sometimes I’m looking for a specific message or event and I have a rough idea of where that is in the timeline, so I use the rail, which I can scrub through like a scrollbar while getting nice previews and haptic feedback on my trackpad. Or, I remember some bit of prose or code, and I use search (⌘F, or ctrl-f on Windows and Linux) to find it. We can easily come up with scroll anchors for those locations.

Still, a scrollbar tells you something the rail and search can’t: how much content is above and below you, at a glance. So we had to figure it out.

A common shortcut apps take is to size the scrollbar to just the items rendered so far.

You scroll up, older items appear, and the thumb shrinks and jumps under you. E

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →