Skip to content

agent: Materialize tool-call diffs lazily, on first view - #65444

Merged
SomeoneToIgnore merged 9 commits into
zed-industries:mainfrom
Vanuan:fix/lazy-diff-materialization
Oct 21, 2026
Merged

SomeoneToIgnore merged 9 commits into
zed-industries:mainfrom
Vanuan:fix/lazy-diff-materialization

Conversation

@Vanuan

@Vanuan Vanuan commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Restoring a thread materialized the diff of every edit in its history, whether or not the card had ever been shown. On long, tool-heavy threads that meant multi-GiB memory spikes just from opening a thread.

Two eager paths on restore:

  • EntryViewState::sync_entry built a diff Editor and a TerminalView for every tool call in the history.
  • acp_thread::Diff::finalized created a Buffer::local(new_text) holding the whole post-edit file, set the language from the file path, and awaited parsing_idle(), retaining the parsed buffer in FinalizedDiff.

Profiling a real 44-thread store (debug build, isolated LD_PRELOAD heap profiler instrumenting only the zed process) attributed ~1.26 GiB to tree-sitter syntax trees and ~3.0 GiB anon to opening a thread, with the dominant stacks under Buffer::reparse / SyntaxSnapshot::reparse_with_ranges reached from Diff::finalized. The diff-editor and terminal widgets were a negligible part of it.

Diffs are now built on first view:

  • EntryViewState::sync_entry no longer builds diff and terminal content views for tool calls whose content is not visible. The history-restore loop calls sync_entry_initial, and expanding a card re-syncs that entry to build its views.
  • acp_thread::Diff::finalized stores only the diff source (path, old_text, new_text). The buffer, rope, multibuffer and tree-sitter parse are built by Diff::resolve, called from AcpThread::resolve_tool_call_diffs(index, cx) when the card first becomes visible. resolve is idempotent, and the accessors reachable before resolution (to_markdown, has_revealed_range) handle the unresolved case.

Same isolated profile, same 44 threads, MPROF_MIN=4096 MPROF_SAMPLE=64:

before after
Pss_Anon after load ~3.0 GiB 478 MiB
Rss 3.4 GiB 997 MiB
tracked live heap (est.) 1933.6 MiB 184.7 MiB
syntax / tree-sitter 1262.8 MiB 7.1 MiB

Opening a second thread kept tree-sitter at ~6 MiB, and expanding one card built only the diff for that card (~12 MiB), so the work is now proportional to what is shown.

Companion PR: #65470 parses thread markdown lazily, on first render. With both changes the same profile goes from 3003 to 1199 MiB VmRSS, and anonymous memory from 2724 to 934 MiB.

Agent-panel resident memory: vanilla vs patched Zed

Still eager on restore, and left for follow-ups: markdown parsing of assistant messages (~245 MiB over two threads), serde_json deserialize and Value::clone of the thread payload (~276 MiB), mermaid rasterization (~59 MiB), and the same lazy treatment for DiffPatch hunks.

Related reports: #65465, #62133, #63720, #59402, #60793, #57478, #57126, #61026, #50889.

Testing

  • cargo check -p agent_ui
  • cargo test -p acp_thread
  • cargo test -p agent_ui

Release Notes:

  • Improved memory usage in the agent panel: tool-call diffs are built and parsed only when a card is first viewed, instead of for every edit in a thread's history.

Restoring a thread eagerly built a diff for every edit in its history.
`Diff::finalized` created a buffer holding the whole post-edit file, set a
language and waited for a full tree-sitter parse (`parsing_idle().await`),
and `EntryViewState` built a diff editor and terminal view for every tool
call regardless of whether its card was shown. On long, tool-heavy threads
this materialized the entire edit history on open, producing multi-GiB
resident-memory spikes.

Profiled on a real 44-thread store (debug build, sampling LD_PRELOAD heap
profiler): ~1.26 GiB in tree-sitter syntax trees and ~3.0 GiB anonymous
memory attributable to merely opening a thread, driven by
`Buffer::reparse` / `SyntaxSnapshot::reparse` under
`edit_session::replay_output -> Diff::finalized` (i.e. agent replay of
past edits, not the UI widgets).

Make tool-call content materialize only when its card is shown:

- `EntryViewState::sync_entry` no longer builds diff/terminal views for
  tool calls whose content is not visible. A restored thread syncs its
  history with `sync_entry_initial`, which skips them; expanding a card
  re-syncs that entry to build its views on demand.
- `acp_thread::Diff::finalized` now stores only the diff source (path +
  old/new text). The buffer, rope, multibuffer and tree-sitter parse are
  built by a new `Diff::resolve`, invoked from
  `AcpThread::resolve_tool_call_diffs` when the card first becomes visible.
  `Diff::resolve` is idempotent and accessors that can be reached before a
  diff is resolved (`to_markdown`, `has_revealed_range`) handle the
  unresolved case.

Measured on the same profile: anonymous memory after load dropped from
~3.0 GiB to 478 MiB and tree-sitter from ~1.26 GiB to ~7 MiB; opening a
second thread kept tree-sitter ~6 MiB (only the expanded card's diff
parses, on demand). Covered by `cargo test -p acp_thread` (270) and
`cargo test -p agent_ui` (515), all passing.
@cla-bot cla-bot Bot added the cla-signed The user has signed the Contributor License Agreement label Oct 10, 2026
@Vanuan

Vanuan commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Resident-memory measurement

Chart: vanilla stable vs a build with both changes — this PR plus the companion
PR #65470. Measured on an isolated copy of a real profile (44 threads; heavy thread
"Windows probe VM handoff verification") with an allocation-level heap profiler.

Agent-panel resident memory: vanilla vs patched Zed

build VmRSS anonymous file-backed
vanilla (stable) 3003 MiB 2724 MiB 279 MiB
patched (this PR + #65470) 1199 MiB 934 MiB 265 MiB

≈ 2.5× less resident, ≈ 2.9× less anonymous. File-backed is essentially
unchanged, so the difference is entirely heap.

This PR's own effect is the diff/tree-sitter half: tree-sitter allocations
1262.8 → 7.1 MiB, because restored, collapsed tool-call diffs are no longer
materialized — and therefore no longer parsed — until first viewed.

Both instances had the same project open when sampled.

Companion PR

Related reports

agent/thread memory

same symptom, different root cause (not addressed here)

@SomeoneToIgnore SomeoneToIgnore left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a few comments on top of CI findings.

Comment thread crates/acp_thread/src/diff.rs Resolved
- A finalized diff that is built eagerly (`PendingDiff::finalize`) no longer
  retains the full file text: the deferred source (`new_text` + language
  registry) now lives in an `Option` consumed by `resolve`, and is `None` when
  the diff is already resolved. Previously every retained live edit kept a full
  copy of its new text (e.g. ~1 GiB for 128 edits of an 8 MiB file).
- Expanding a tool-call card now materializes its views without re-running the
  terminal lifecycle, so expanding a card whose process is still running is no
  longer collapsed again by `TerminalMovedToBackground`.
- Remove a redundant `path.clone()` (clippy::redundant_clone).
@Vanuan

Vanuan commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the review:

You could no longer keep a running command's card open. Some tool cards are for a command that has finished but whose program is still running in the background, and Zed deliberately tucks those away. Because expanding a card re-ran the card's setup, that "tuck away finished background commands" rule fired again — so the card would slam shut the instant you opened it. Expanding now only builds the missing pieces and does not re-run that rule, so the card stays open.

A full copy of each file version was kept for nothing. To show a diff, Zed sometimes keeps a copy of the "after" version of the file. For the diffs we now build immediately, we were still making that copy and then never using it — in your example, ~1 GB for 128 edits of an 8 MB file. That copy is now kept only while it's genuinely still needed and dropped the moment it's been used; diffs that are already built don't make it at all.

Lint. Removed the pointless duplication clippy flagged.

Verified locally: clippy clean, and acp_thread (270) + agent_ui (515) tests pass. Added the missing Release Notes section.

@smitbarmase smitbarmase added area:performance Feedback for performance issues, speed, memory usage, etc area:ai/agent thread Feedback for Zed's Agent Thread labels Oct 13, 2026

@SomeoneToIgnore SomeoneToIgnore left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, please also tidy up the comments as those are overly LLM-esque and verbose (unlike this repo's style).

Comment thread crates/acp_thread/src/diff.rs Resolved
@Baike12

Baike12 commented Oct 13, 2026

Copy link
Copy Markdown

Adding an independent heap-level measurement from macOS that lines up with your root cause.

Environment: Zed Preview 1.24.2 (630334a), macOS 26.0.1, Apple Silicon, 24 GB RAM. One ACP agent thread (Claude Code), 3 projects open, 30 live worktrees.

Peak: after ~5 h the Zed main process reached 75.6 GB physical footprint. At the same instant ps RSS was 87 MB — macOS had compressed essentially all of it, so RSS-based monitoring (including Zed's own zed::reliability logging, which reads RSS via sysinfo) reports nothing.

footprint -p <pid>:

Footprint: 76 GB
  Dirty      Clean  Reclaimable    Regions    Category
  75 GB        0 B          0 B      20307    MALLOC_SMALL

Reclaimable 0 B — every page still referenced.

heap -sortBySize, same process:

All zones: 46915311 nodes (75335341392 bytes)
   COUNT      BYTES       AVG   CLASS_NAME
46861658  75325476688   1607.4   non-object

Two size classes are ~98% of it, and no ObjC/Swift objects are involved (those total a few MB):

size count total
1536 B 42,829,925 61.27 GiB
3584 B 2,331,260 7.78 GiB

A single fixed-size allocation shape, not scattered leakage.

Corroborating foreground hangs in the same session (zed::reliability::hang_detection miniprof traces):

crates/language/src/buffer.rs:1987:32  226.9 ms
crates/language/src/buffer.rs:1687:36  367.2 ms

Those are the Buffer::reparse / SyntaxSnapshot frames your root-cause section names as dominant under Diff::finalized, which is consistent with the fixed 1536-byte shape being retained tree-sitter data.

One caveat for your numbers: your profile is ~3.0 GiB anon for a 44-thread store; this instance reached 75.6 GB from a single thread. Either the edit history is far larger, or there is a second accumulation channel on top of the one this PR closes. Happy to re-run with MallocStackLogging=1 to get typed backtraces if that would help narrow it.

@Vanuan

Vanuan commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@Baike12 Could you measure memory usage on fresh zed instance with historic threads opened? Does it still use 75GB?

`Diff::to_markdown` exported the retained new text for a diff that had not been built, so a thread's markdown changed depending on whether its card had been opened. Reproduce the resolved output from the source text instead.

Also shortens the comments added by the previous commit.
@Vanuan

Vanuan commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Done in d53cacff57: Fixed markdown export for unmaterialized tool-call diffs
Diff::to_markdown exported the retained new text for a diff that had not been built, so a thread's markdown changed depending on whether its card had been opened. Reproduce the resolved output from the source text instead.

Also shortened the comments.

`BufferDiff::set_base_text` normalizes the base text, so line-ending-only edits are not hunks. The deferred export compared the normalized new text against the raw base, which made an unchanged CRLF file export its full text before resolution and nothing after it. Compare both sides normalized.
@Vanuan

Vanuan commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Tests caught a bug in line ending normalization. Please retrigger

Comment thread crates/acp_thread/src/diff.rs Resolved
Comment thread crates/agent_ui/src/entry_view_state.rs Resolved
Comment thread crates/agent_ui/src/entry_view_state.rs Resolved
Comment thread crates/acp_thread/src/diff.rs Resolved
Comment thread crates/acp_thread/src/diff.rs Resolved
Comment thread crates/agent_ui/src/entry_view_state.rs Resolved
@Vanuan

Vanuan commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Some clarifications:

term meaning
diff the change between base_text and new_text for one tool call, owned by Diff
finalized the tool call is no longer live — it has a stable new_text and can be exported at any time
unresolved finalized, but no render state has been built yet; holds only export inputs
deferred source DeferredSource (new text, language registry, cached change flag); the export inputs retained until resolve()
resolved render state (buffer, multibuffer, BufferDiff) has been built; this is one-way
render state the Buffer + MultiBuffer + language + tree-sitter BufferDiff needed to show an editor
export to_markdown() — the transcript representation of the diff
materialize the agent_ui action that builds render state for a card by calling resolve()
live edit a tool call still streaming; PendingDiff must retain its buffer as it arrives

The Problem

Restoring a thread used to finalize every tool-call diff eagerly. Diff::finalized built a normalized Buffer, a MultiBuffer, loaded the language, waited for parsing_idle(), and computed a BufferDiff over the whole file — including for collapsed cards the user never opens. The buffers and their tree-sitter state then stayed resident.

A collapsed card really only needs two things: its path and its markdown text. Render state is only needed once an editor is actually shown. Live edits are a different case — PendingDiff tracks an edit as it streams and genuinely needs its buffer.

The Invariant

A restored diff keeps only the source text it needs to export. Render state is built on first view, and building it must not change the transcript.

state holds built when
PendingDiff buffer, multibuffer, BufferDiff live edit
FinalizedDiff, unresolved path, base_text, DeferredSource thread restore
FinalizedDiff, resolved buffer, multibuffer, BufferDiff first view
flowchart LR
    Start(( )) --> Live

    Live["PendingDiff<br/>(live edit)"]
    Unresolved["FinalizedDiff<br/>(unresolved)"]
    Resolved["FinalizedDiff<br/>(resolved)"]

    Unresolved -->|"Diff::resolve()<br/>on first view"| Resolved
    Live -->|"PendingDiff::finalize()"| Resolved
    Resolved --> End(( ))

    classDef live fill:#2d2210,stroke:#e3b341,stroke-width:1.5px,color:#e3b341
    classDef unresolved fill:#0d1b24,stroke:#39c5cf,stroke-width:1.5px,color:#39c5cf
    classDef resolved fill:#0f2417,stroke:#3fb950,stroke-width:1.5px,color:#3fb950

    class Live live
    class Unresolved unresolved
    class Resolved resolved
Loading

Note the one-way transition: once Resolved, a diff never goes back to Unresolved — same shape as the markdown deferral flag.

Sequence

sequenceDiagram
    autonumber
    participant T as AcpThread
    participant D as Diff
    participant E as EntryViewState
    participant V as ThreadView

    Note over T,D: Restore
    T->>D: Diff::finalized(path, old_text, new_text)
    D->>D: Store base_text and DeferredSource
    V->>E: sync_entry_initial(index)
    Note over E: Collapsed tool call skipped, view ids recorded

    Note over V,D: Expand
    V->>E: materialize_entry(index)
    E->>T: resolve_tool_call_diffs(index)
    T->>D: resolve()
    D->>D: Buffer, MultiBuffer, language, BufferDiff
    E->>V: create_editor_diff

    Note over T,D: Export at any time
    T->>D: to_markdown()
    alt Unresolved
        D->>D: export_before_resolve()
    else Resolved
        D->>D: multibuffer buffers
    end
Loading

The Fix

  1. Deferred state (acp_thread::diff)
    Diff::finalized now stores base_text, an empty resolved cell, and a DeferredSource holding the new text and language registry, and returns. Diff::resolve takes the source once and runs build_finalized: buffer → language → parsing_idle → BufferDiff → excerpts. buffer() and multibuffer() require resolution. PendingDiff::finalize still produces an already-resolved FinalizedDiff, because a live edit has to retain its buffers.

  2. Export consistency (acp_thread::diff)
    Diff::to_markdown falls back to export_before_resolve while unresolved. To match the resolved export, it normalizes both sides and emits an empty body when the texts are equal, since the resolved multibuffer only contains hunk buffers. test_finalized_diff_export_survives_resolution compares both exports for unchanged, changed, CRLF, and add/remove cases.

  3. First view (agent_ui)
    Restores use EntryViewState::sync_entry_initial (ToolCallSync::Restore), which skips views that are not visible; content is still materialized when the card is expanded or awaiting authorization (is_tool_call_content_visible). Skipped view ids are recorded, so a later live sync can create them without emitting NewDiff/NewTerminal. Expanding goes through ThreadView::materialize_tool_call_views → EntryViewState::materialize_entry (ToolCallSync::Materialize), which materializes content but skips terminal lifecycle, so re-syncing can't collapse a finished command whose process is still running. Live updates keep using sync_entry (ToolCallSync::Live).

  4. No transcript change on resolve
    to_markdown produces the same output whether or not the card has been opened. The unresolved path compares normalized new_text against normalized base_text; that parity is what CI caught and what 8631528cad fixed.

Review follow-ups

  • Interrupted-edit state is now derived from Diff::has_changes: unresolved diffs compare normalized base_text/new_text, and Diff::discard_partial_edit resolves on demand. A collapsed restored card keeps its warning and discard action (bb2c8a397e).
  • Restore-skipped view ids are recorded, so a later live sync materializes them without emitting NewDiff/NewTerminal; expand_edit_card only reacts to genuinely new content (d5485e70aa).

Shorten the deferred-diff comments, rename the expansion materialization helper, and replace the two sync booleans with a three-mode enum.
Derive canceled-edit changes from the deferred diff instead of the editor, and resolve on discard so a restored collapsed card keeps its warning and discard action.
Track the view ids skipped during restore so a later sync materializes them without emitting NewDiff or NewTerminal.
Comment thread crates/acp_thread/src/diff.rs Resolved
Read the resolved new buffer until the async multibuffer build completes so has_changes and to_markdown cannot observe an empty pending state.
@Vanuan

Vanuan commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Let me retrace steps from scratch. Below is a collapsed slide show

Details The key change is lazy initialization of diffs in tool calls. So that only diffs that are in viewport and uncollapsed are materialized on demand. Unloading collapsed/invisible diffs and introducing LRU cache is future memory optimization work. image

Lazy loading is divided between the Data Model (holding raw strings) and the UI View State (skipping GPUI editor views). So we introduce unresolved raw strings and resolved diff/buffer/multibuffer state.

image

Now, the diff itself has pending and finalized state (pre-existing behaviour). Pending is the diff agent is currently writing, and finalized is the diff that is finished. For pending state we keep existing behaviour.
For finalized diff we introduce resolved and unresolved (deferred) state.

FinalizedDiff holds a DeferredSource and an EmptyOnceCell. The first time resolve() is called, it loads the data, sets deferred to None, and fills the EmptyOnceCell with the ResolvedFinalized.

image

To export thread to Markdown or check if a file changed, you don't need to build a heavy Buffer. Unresolved diffs can compute both export ready markdown source and has changes flag directly from source diff. Here, we're also normalizing strings to ignore line ending differences.

flowchart LR
    Raw["Unresolved Diff<br/>(base_text vs new_text)"]:::deferred

    Raw -->|"to_markdown()"| Norm1["LineEnding::normalize()<br/>Returns new_text (or '' if equal)"]:::state
    Raw -->|"has_changes()"| Norm2["Cached in OnceCell<bool><br/>(base_text != new_text)"]:::state

    classDef default font-family:monospace,font-size:13px;
    classDef deferred fill:#1e242b,stroke:#4b5563,stroke-dasharray: 4 4,stroke-width:1.5px,color:#9ca3af;
    classDef state fill:#162432,stroke:#38bdf8,stroke-width:1.5px,color:#7dd3fc;
Loading

For UI state machine we introduce ToolCallSync enum. EntryViewState uses three distinct sync modes: restoring, clicking to expand, and live streaming.

%%{init: {
  "theme": "base",
  "themeVariables": {
    "fontFamily": "monospace",
    "fontSize": "13px",
    "clusterBkg": "#0d1117",
    "clusterBorder": "#333"
  }
}}%%
flowchart TB
    subgraph P1["Phase 1 — Restore"]
        direction LR
        R["ToolCallSync::Restore<br/>(sync_entry_initial)"]:::deferred --> R_Act["Skips hidden views<br/>Records IDs in restored_view_ids"]:::deferred
    end

    subgraph P2["Phase 2 — Materialize"]
        direction LR
        M["ToolCallSync::Materialize<br/>(materialize_entry on click)"]:::state --> M_Act["Builds Diff & Editor<br/>No NewDiff event / No terminal collapse"]:::state
    end

    subgraph P3["Phase 3 — Live"]
        direction LR
        L["ToolCallSync::Live<br/>(sync_entry during stream)"]:::visible --> L_Act["Builds Diff & Editor<br/>Emits NewDiff (unless in restored_view_ids)"]:::visible
    end

    P1 --> P2 --> P3

    classDef visible  fill:#122822,stroke:#2bb673,stroke-width:1.5px,color:#86efac
    classDef deferred fill:#1e242b,stroke:#4b5563,stroke-dasharray: 4 4,stroke-width:1.5px,color:#9ca3af
    classDef state    fill:#162432,stroke:#38bdf8,stroke-width:1.5px,color:#7dd3fc

    %% Make arrows prominent
    linkStyle default stroke:#d1d5db,stroke-width:2px,color:#d1d5db
Loading

There's also an edge case for a restored edit that was canceled mid-stream. But I'm not sure if it was introduced by the lazy diff change as I had experienced bugs with rejection before.

flowchart TB
    Card["Collapsed Canceled Edit<br/>(No Editor Built)"]:::deferred
    
    Card --- L1["diff.has_changes()"]:::labelText
    L1 --> Warn["Shows Warning Icon<br/>& 'Discard' Button"]:::eager
    
    Warn --- L2["User Clicks Discard"]:::labelText
    L2 --> Discard["discard_partial_edit()<br/>1. Calls resolve()<br/>2. Resets buffer to base_text"]:::visible

    classDef eager fill:#2d1519,stroke:#e05252,stroke-width:1.5px,color:#ff9999
    classDef visible fill:#122822,stroke:#2bb673,stroke-width:1.5px,color:#86efac
    classDef deferred fill:#1e242b,stroke:#4b5563,stroke-dasharray: 4 4,stroke-width:1.5px,color:#9ca3af
    classDef labelText fill:transparent,stroke:none,color:#d1d5db,font-size:12px
    
    linkStyle default stroke:#d1d5db,stroke-width:2px,color:#d1d5db
Loading

The latest review comment is about a race condition (has_changes or to_markdown called before multibuffer is populated):

%%{init: {
  "theme": "base",
  "themeVariables": {
    "fontFamily": "monospace",
    "fontSize": "13px"
  }
}}%%
flowchart TB
    Resolve["diff.resolve(cx)<br/>(Sets OnceCell to Some immediately)"]:::state --> Async["Async Background Task:<br/>Awaiting language load, parsing & diffs"]:::deferred

    %% Floating text node for the race window
    Async --- L1["⚠️ Window gap (Task still pending)"]:::labelText
    L1 --> Empty["MultiBuffer is empty!"]:::eager

    %% Fan out to the two bugs
    Empty --> Bug1["has_changes() returns false<br/>(relies on empty multibuffer)"]:::eager
    Empty --> Bug2["to_markdown() exports empty string ''<br/>(permanent data loss on sync calls)"]:::eager

    classDef eager     fill:#2d1519,stroke:#e05252,stroke-width:1.5px,color:#ff9999
    classDef visible   fill:#122822,stroke:#2bb673,stroke-width:1.5px,color:#86efac
    classDef deferred  fill:#1e242b,stroke:#4b5563,stroke-dasharray: 4 4,stroke-width:1.5px,color:#9ca3af
    classDef state     fill:#162432,stroke:#38bdf8,stroke-width:1.5px,color:#7dd3fc
    
    %% Style for the floating text node
    classDef labelText fill:transparent,stroke:none,color:#d1d5db,font-size:12px,font-weight:bold

    %% Prominent arrows
    linkStyle default stroke:#d1d5db,stroke-width:2px,color:#d1d5db
Loading

The fix is not to wait on MultBuffer population tasks to finish, and fallback to raw data:

%%{init: {
  "theme": "base",
  "themeVariables": {
    "fontFamily": "monospace",
    "fontSize": "13px"
  }
}}%%
flowchart TB
    Resolve["diff.resolve(cx)<br/>(Sets OnceCell immediately)"]:::state --> Pending["Async Task Pending:<br/>MultiBuffer is empty"]:::deferred

    %% Floating label node between Pending and Fallback
    Pending --- L1["Query: has_changes() / to_markdown()"]:::labelText
    L1 --> Fallback["Fallback to retained text<br/>(base_text & new_text)"]:::visible

    Fallback --> Correct["Returns correct data instantly<br/>(Zero empty exports / No race condition)"]:::visible

    classDef eager     fill:#2d1519,stroke:#e05252,stroke-width:1.5px,color:#ff9999
    classDef visible   fill:#122822,stroke:#2bb673,stroke-width:1.5px,color:#86efac
    classDef deferred  fill:#1e242b,stroke:#4b5563,stroke-dasharray: 4 4,stroke-width:1.5px,color:#9ca3af
    classDef state     fill:#162432,stroke:#38bdf8,stroke-width:1.5px,color:#7dd3fc
    
    %% Style for the floating text nodes
    classDef labelText fill:transparent,stroke:none,color:#d1d5db,font-size:12px

    %% Prominent arrows
    linkStyle default stroke:#d1d5db,stroke-width:2px,color:#d1d5db
Loading

@Vanuan

Vanuan commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

So far, I've been trying to make minimally necessary changes, but if you wish, I could refactor it with first class Unseen / Evicted states rather than awkward booleans? Some drafts below:

image

This proposal introduces new glossary and two state machines for finalized diff:

%%{init: {
  "theme": "base",
  "themeVariables": {
    "fontFamily": "monospace",
    "fontSize": "13px",
    "edgeLabelBackground": "transparent"
  }
}}%%
flowchart TB
    subgraph T3["TIER 3 — View"]
        direction LR
        VU["Unseen"]:::view --> VW["Waiting"]:::wait
        VW -->|"Populated"| VM["Materialized"]:::ready
        VM -->|"Collapse / Evict"| VU
    end

    subgraph T2["TIER 2 — RenderCache (the only mutable state)"]
        direction LR
        CU["Unbuilt"]:::cache -->|"ensure_populated"| CB["Building"]:::cache
        CB -->|"task completes"| CR["Ready"]:::ready
        CR -->|"evict()"| CU
    end

    subgraph T1["TIER 1 — Content (immutable)"]
        direction LR
        C["path · base_text · new_text<br/>has_changes"]:::content
        Q["has_changes()<br/>to_markdown()<br/>needs_update()"]:::query
        C --- Q
    end

    T2 ==>|"DiffEvent::Populated"| T3
    T1 ==>|"read synchronously"| CONS["Consumers<br/>export · search · warning"]:::consumer
    T1 -.->|"seeds buffer"| T2

    %% --- High-Contrast Neon Palette ---
    classDef content  fill:#0f2417,stroke:#3fb950,stroke-width:1.5px,color:#86efac
    classDef query    fill:#122822,stroke:#2bb673,stroke-width:1.5px,color:#86efac
    classDef cache    fill:#0d1b24,stroke:#38bdf8,stroke-width:1.5px,color:#7dd3fc
    classDef ready    fill:#0f2417,stroke:#3fb950,stroke-width:1.5px,color:#86efac
    classDef view     fill:#1e242b,stroke:#64748b,stroke-width:1.5px,color:#e2e8f0
    classDef wait     fill:#2d2210,stroke:#e3b341,stroke-width:1.5px,color:#fef08a
    classDef consumer fill:#2d1b2e,stroke:#c084fc,stroke-width:1.5px,color:#e9d5ff

    %% --- Prominent Arrows ---
    linkStyle default stroke:#d1d5db,stroke-width:2px,color:#d1d5db

    %% --- High-Contrast Subgraph Titles ---
    style T1 fill:#0d1117,stroke:#333,stroke-width:1px,color:#ffffff
    style T2 fill:#0d1117,stroke:#333,stroke-width:1px,color:#ffffff
    style T3 fill:#0d1117,stroke:#333,stroke-width:1px,color:#ffffff
Loading

But I think this is out of scope of this PR, as this PR is only for the initial load, it does not include eviction and cache.

@SomeoneToIgnore SomeoneToIgnore left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.