diff --git a/crates/session-view/src/lib.rs b/crates/session-view/src/lib.rs index 238686d03..f0f9cd1a7 100644 --- a/crates/session-view/src/lib.rs +++ b/crates/session-view/src/lib.rs @@ -612,7 +612,11 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { /// (only those: `rune_kit::math::version`) swap from the code fallback to the rendered equation /// without waiting for user input. pub fn poll_math(s: &S) -> bool { - s.math_client().is_some_and(rune_kit::math::Client::changed) + let changed = s.math_client().is_some_and(rune_kit::math::Client::changed); + if changed { + timeline::note_math_changed(); + } + changed } /// All ⌘⇧K knob groups owned by `session-view`. diff --git a/crates/session-view/src/recall.rs b/crates/session-view/src/recall.rs index 12f69edae..50eef4508 100644 --- a/crates/session-view/src/recall.rs +++ b/crates/session-view/src/recall.rs @@ -11,6 +11,7 @@ use std::rc::Rc; use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_MARK_ID: AtomicU64 = AtomicU64::new(1); +static NEXT_MARKS_ID: AtomicU64 = AtomicU64::new(1); use rune::{El, Live}; @@ -39,6 +40,7 @@ struct RowMark { /// One timeline's last drawn frame. pub struct Marks { + id: u64, view: Live<[f32; 4]>, stack: Live<[f32; 4]>, header_h: Cell, @@ -47,18 +49,24 @@ pub struct Marks { /// virtual list still mounts above and below the viewport keep theirs. rows: RefCell, touched: Cell, + /// Monotonic counter bumped whenever any shaped row mark is rotated/cleared, changes target + /// width/height, or is evicted from the LRU. Paired with `id` so `forget`/`retain` followed + /// by recreation produces a distinct stamp. + resting_gen: Rc>, visible: RefCell>, } impl Recall { pub fn marks(&self, session: &str) -> Rc { self.marks.borrow_mut().entry(session.to_owned()).or_insert_with(|| Rc::new(Marks { + id: NEXT_MARKS_ID.fetch_add(1, Ordering::Relaxed), view: Live::new([0.0; 4]), stack: Live::new([0.0; 4]), header_h: Cell::new(0.0), at_top: Cell::new(false), rows: RefCell::default(), touched: Cell::new(0), + resting_gen: Rc::new(Cell::new(0)), visible: RefCell::default(), })).clone() } @@ -178,11 +186,25 @@ impl Marks { } let mark = rows.get_mut(key).unwrap(); mark.touched = at; - if mark.shape != shape { mark.target.set([0.0; 4]); } - mark.shape = shape; + if mark.shape != shape { + mark.target.set([0.0; 4]); + mark.shape = shape; + self.bump_resting(); + } mark.id } + /// Unique identity and monotonic resting-height mark generation for this session's `Marks`. + #[inline] + pub fn resting_stamp(&self) -> (u64, u64) { + (self.id, self.resting_gen.get()) + } + + #[inline] + fn bump_resting(&self) { + self.resting_gen.set(self.resting_gen.get().wrapping_add(1)); + } + /// Attaches `drawn_rect_into` (and `on_layout_any` when `shaped`) for a mark prepared via /// [`Self::prepare_row`], allowing callers to run this inside a `rune::memo` closure. pub fn attach_row(&self, key: &str, el: El, shaped: bool) -> El { @@ -191,7 +213,16 @@ impl Marks { let el = el.drawn_rect_into(&mark.drawn); if !shaped { return el; } let target = mark.target.clone(); - el.on_layout_any(move |rect, tx| { target.set(rect); tx.live_only(); }) + let resting = self.resting_gen.clone(); + el.on_layout_any(move |rect, tx| { + let prev = target.get(); + if target.set(rect) + && (prev[2].to_bits() != rect[2].to_bits() || prev[3].to_bits() != rect[3].to_bits()) + { + resting.set(resting.get().wrapping_add(1)); + } + tx.live_only(); + }) } /// Last-drawn geometry and reusable layout measurements have different lifetimes. @@ -232,7 +263,17 @@ impl Marks { let cut = whens.len() - ROWS_KEPT; let (_, oldest_kept, _) = whens.select_nth_unstable(cut); let oldest_kept = *oldest_kept; - rows.retain(|_, mark| mark.touched >= oldest_kept); + let mut dropped_shaped = false; + rows.retain(|_, mark| { + let keep = mark.touched >= oldest_kept; + if !keep && mark.shape.is_some() { + dropped_shaped = true; + } + keep + }); + if dropped_shaped { + self.bump_resting(); + } } } } diff --git a/crates/session-view/src/timeline/mod.rs b/crates/session-view/src/timeline/mod.rs index 694a3ff6c..14560b3de 100644 --- a/crates/session-view/src/timeline/mod.rs +++ b/crates/session-view/src/timeline/mod.rs @@ -29,6 +29,7 @@ pub use dividers::divider_runs; pub use parts::*; pub use tail::*; pub use projection::{Projection, TurnMeta, poll as projection_poll, rows, wanted as projection_wanted}; +pub(crate) use row_height::note_math_changed; thread_local! { pub static ROW_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -250,6 +251,13 @@ pub fn timeline(s: &S, p: &Pal, id: &str, t: Option<&Transcript // A projection kept from the last build has the keys it had: the list needn't ask each // row's again. let version = specs.generation; + // Skip scanning `0..specs.len()` in `sync_known_heights_checked` on steady-state commits + // (composer typing, `plugin:perf` ticks, unchanged warm tab returns) for hosts that expose + // a transcript version. Unversioned hosts (e.g. storyboards) omit the stamp and keep + // per-commit scanning. + let heights_ver = s + .transcript_version(&id) + .map(|tv| row_height::heights_version(s, &id, tv, &specs, &marks, layout)); stack = stack.virtual_rows( n, 80.0, @@ -292,6 +300,9 @@ pub fn timeline(s: &S, p: &Pal, id: &str, t: Option<&Transcript let r = height_keys.get(i)?; height_marks.height_for(&r.key, || row_height::shape(s, t, r, layout)) }).flatten()); + if let Some(hv) = heights_ver { + stack = stack.virtual_row_heights_version(hv); + } } if t.is_none() { if let Some(head)=s.partial_output(id) { diff --git a/crates/session-view/src/timeline/projection.rs b/crates/session-view/src/timeline/projection.rs index 91415e21e..2dc305ddf 100644 --- a/crates/session-view/src/timeline/projection.rs +++ b/crates/session-view/src/timeline/projection.rs @@ -50,6 +50,11 @@ pub struct Projection { /// Which projection made the rows: a virtual list keeps the keys of the last commit given /// the same one (`El::virtual_rows_version`). pub generation: u64, + /// Monotonic counter incremented on every newly constructed `Projection`, even when + /// `same_keys` reuses `generation`, so `El::virtual_row_heights_version` invalidates when + /// per-row fields (`live`, `streaming`, `pt`, `under`, `divider`, `above`, `below`, `top`) + /// change under identical keys. + pub content_generation: u64, } impl Projection { @@ -74,7 +79,9 @@ impl Projection { GENERATION.set(g); g }); - let mut p = Projection { spans, starts, len, seams: Vec::new(), turns, older, generation }; + let content_generation = CONTENT_GENERATION.get().wrapping_add(1); + CONTENT_GENERATION.set(content_generation); + let mut p = Projection { spans, starts, len, seams: Vec::new(), turns, older, generation, content_generation }; p.seams = p.space_seams(t, prev); // The first row with messages still to land above takes no room over it: the row that // lands above it brings the room between them (`rhythm::space_at`), so the first row is @@ -293,6 +300,8 @@ thread_local! { static SESSIONS: RefCell> = RefCell::new(SessionLru::new()); /// Each projection's number; 0 is the empty one. static GENERATION: Cell = const { Cell::new(0) }; + /// Each constructed projection's content number; 0 is the empty default. + static CONTENT_GENERATION: Cell = const { Cell::new(0) }; /// Moves when a partial projection was filled in, so the timeline's region builds again. static WANTED: Cell = const { Cell::new(0) }; } diff --git a/crates/session-view/src/timeline/row_height.rs b/crates/session-view/src/timeline/row_height.rs index 41717826e..9f82e4c5a 100644 --- a/crates/session-view/src/timeline/row_height.rs +++ b/crates/session-view/src/timeline/row_height.rs @@ -118,6 +118,132 @@ pub(super) fn layout(s: &S, p: &Pal, scroll_key: &str) -> u64 { h.finish() } +thread_local! { + /// UI-thread `Tracked` cell touched when `crate::poll_math` reports a finished LaTeX render, + /// so `VirtualList::sync_known_heights_checked` invalidates cached scans for timelines with + /// resting math rows even while the enclosing `timeline-fade` region is reused. + static MATH_GEN: rune::Tracked<()> = rune::Tracked::new(()); +} + +/// Records that at least one background display-math render finished on this thread. +pub(crate) fn note_math_changed() { + MATH_GEN.with(rune::Tracked::touch); +} + +#[inline] +fn record_math_read() { + MATH_GEN.with(|m| rune::Tracked::token(m).record()); +} + +#[inline] +fn math_version() -> u64 { + MATH_GEN.with(rune::Tracked::version) +} + +/// Version stamp for `El::virtual_row_heights_version`. +/// +/// Pauses `Tracked` recording so reading version inputs never subscribes the enclosing +/// `timeline-fade` region to extra cells (`media_store`, `speech`, etc.). Covers every +/// non-`Tracked` / session-wide input read inside `.virtual_row_heights(...)`, +/// `Marks::height_for`, `layout`, and `shape` so steady-state commits (composer keystrokes, +/// `plugin:perf` ticks, warm tab returns) skip scanning `0..specs.len()`. +/// +/// `Tracked` cells read by `shape` (`expanded`, `code_wrap_overrides`, `working_state`, +/// `line_hold`, `diagrams`, `media_store`, `user_status_version`, `model_name`, `user_glow_at`, +/// and `MATH_GEN`) are captured per-scan by Rune's `tracked_reads` inside +/// `sync_known_heights_checked` (including across warm `RecentVirtuals` restores), avoiding both +/// `timeline-fade` over-invalidation and `O(disclosures)` scans on streaming deltas. +pub(super) fn heights_version( + s: &S, + session: &str, + transcript_ver: u64, + specs: &super::Projection, + marks: &crate::recall::Marks, + layout: u64, +) -> u64 { + let _paused = rune::tracked::Paused::new(); + let media = s.media_store(); + let mut h = DefaultHasher::new(); + ( + (session, transcript_ver, specs.generation, specs.content_generation, specs.len()), + (layout, marks.resting_stamp(), [crate::style::narrow(), s.fold_user_messages(), s.assistive()]), + (opencode_kit::model::prompt_extras_generation(), crate::diagram::shown_id()), + (media.markdown.version(), media.videos.version(), math_version()), + ) + .hash(&mut h); + h.finish() +} + +/// Stack-buffered lookup for `user-expanded:{id}` (`crate::fold::key`) without heap allocation +/// for typical message IDs. +fn with_fold_key(id: &str, f: impl FnOnce(&str) -> R) -> R { + const PREFIX: &str = "user-expanded:"; + let mut buf = [0u8; 96]; + if id.len() <= buf.len() - PREFIX.len() { + let len = PREFIX.len() + id.len(); + buf[..PREFIX.len()].copy_from_slice(PREFIX.as_bytes()); + buf[PREFIX.len()..len].copy_from_slice(id.as_bytes()); + if let Ok(key) = std::str::from_utf8(&buf[..len]) { + return f(key); + } + } + f(&crate::fold::key(id)) +} + +/// Zero-alloc order-independent stamp of `quote-open:{id}:*` disclosures; `None` while any +/// matching quote card is still springing shut. +fn quote_open_stamp(expanded: &crate::disclosure::Disclosures, id: &str) -> Option { + let mut sum = 0u64; + for (k, _) in expanded.touched() { + let matched = k + .strip_prefix("quote-open:") + .and_then(|rest| rest.strip_prefix(id)) + .is_some_and(|rest| rest.starts_with(':')); + if !matched { + continue; + } + let Some(state) = expanded.get(k) else { continue }; + if matches!(state, crate::disclosure::Disclosure::Shutting { .. }) { + return None; + } + let mut h = DefaultHasher::new(); + (k, std::mem::discriminant(&state)).hash(&mut h); + sum = sum.wrapping_add(h.finish()); + } + Some(sum) +} + +/// Hashes the same inputs as `super::prompt_meta(s, t, Some(message))` without allocating a `Vec`, +/// cloning `ModelRef`s, or scanning earlier messages when the turn already carries a model. +fn hash_prompt_meta(s: &S, t: &Transcript, message: usize, h: &mut DefaultHasher) { + fn model_of(m: &Message) -> Option<&opencode_kit::model::ModelRef> { + match m { + Message::Assistant(a) => a.model.as_ref().filter(|m| !m.id.is_empty() || !m.provider.is_empty()), + _ => None, + } + } + if crate::style::narrow() { + false.hash(h); + return; + } + let end = t.messages[message + 1..] + .iter() + .position(|m| matches!(m, Message::User { .. } | Message::Note { .. })) + .map_or(t.messages.len(), |n| message + 1 + n); + let found = t.messages[message + 1..end] + .iter() + .rev() + .find_map(model_of) + .or_else(|| t.messages[..message].iter().rev().find_map(model_of)); + match found { + Some(m) => { + let variant = (!m.variant.is_empty() && m.variant != "default").then_some(m.variant.as_str()); + (true, s.model_name(m), variant).hash(h); + } + None => false.hash(h), + } +} + pub(super) fn shape(s: &S, t: &Transcript, r: &RowSpec, layout: u64) -> Option { if let RowContent::User { message, above, below, top } = &r.content { let Message::User { id, text, .. } = t.messages.get(*message)? else { return None }; @@ -128,30 +254,30 @@ pub(super) fn shape(s: &S, t: &Transcript, r: &RowSpec, layout: { return None; } - let prompt = crate::fold::key(id); - if crate::disclosure::is_shutting(s, &prompt) { return None; } - let open = s.expanded().contains(&prompt); + let expanded = s.expanded(); + let prompt_state = with_fold_key(id, |k| expanded.get(k)); + if matches!(prompt_state, Some(crate::disclosure::Disclosure::Shutting { .. })) { + return None; + } + let open = prompt_state == Some(crate::disclosure::Disclosure::Open); let fold_user = s.fold_user_messages(); - let past = fold_user && open && crate::fold::is_past(&t.session, id); + // `fold::is_past` only selects the click-to-collapse scroll anchor (`fold::toggle`), + // never rendered height; `row_build` still keys its row memo on it. let viewport = if fold_user && crate::fold::needs_viewport(text) { crate::fold::viewport(s, &t.session) } else { crate::fold::default_viewport() }; - let quote_prefix = format!("quote-open:{id}:"); - let quotes = s.expanded().stamp("e_prefix); - if s.expanded().touched().any(|(k, _)| k.starts_with("e_prefix) && crate::disclosure::is_shutting(s, k)) { - return None; - } - let meta = super::prompt_meta(s, t, Some(*message)); + let quotes = quote_open_stamp(expanded, id)?; let mut h = DefaultHasher::new(); ( layout, &t.session, &r.key, id.as_str(), text.as_str(), - [*above, *below, fold_user, open, past, s.assistive()], + [*above, *below, fold_user, open, s.assistive()], [top.to_bits(), viewport.to_bits(), r.room_under(s).to_bits()], - quotes, s.user_status_version(id), &meta, + quotes, s.user_status_version(id), ) .hash(&mut h); + hash_prompt_meta(s, t, *message, &mut h); return Some(h.finish()); } let RowContent::TurnText { message, part, live: false, pt } = &r.content else { return None }; @@ -179,7 +305,12 @@ pub(super) fn shape(s: &S, t: &Transcript, r: &RowSpec, layout: }); overrides.hash(&mut h); // Async media/math can resize text without a transcript edit. - (s.media_store().markdown.version(), s.media_store().videos.version(), - rune_kit::math::version(&r.key)).hash(&mut h); + let math_ver = if scan.has(FLAG_MATH) { + record_math_read(); + rune_kit::math::version(&r.key) + } else { + 0 + }; + (s.media_store().markdown.version(), s.media_store().videos.version(), math_ver).hash(&mut h); Some(h.finish()) }