From 497c5fb36445e8b5c8f2ea6263fb1764a12ea109 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:43:43 +1000 Subject: [PATCH 1/2] perf(timeline,session-view): eliminate per-frame heap allocation churn during streaming --- apps/desktop/src/shell/view/composer.rs | 22 +- apps/desktop/src/shell/view/session.rs | 29 ++- crates/session-view/src/compaction.rs | 51 +++- crates/session-view/src/copied.rs | 44 ++++ crates/session-view/src/disclosure.rs | 72 +++++- crates/session-view/src/fold.rs | 5 +- crates/session-view/src/jump.rs | 21 +- crates/session-view/src/line_reveal.rs | 146 +++++++---- crates/session-view/src/recall.rs | 10 +- crates/session-view/src/sources_chip.rs | 69 +++-- .../session-view/src/timeline/group_hash.rs | 242 +++++++++++++----- crates/session-view/src/timeline/mod.rs | 3 +- crates/session-view/src/timeline/parts.rs | 67 ++++- crates/session-view/src/timeline/row_build.rs | 206 ++++++++------- .../session-view/src/timeline/row_height.rs | 26 +- .../session-view/src/timeline/turn_cache.rs | 52 +++- crates/session-view/src/timeline/wrap.rs | 24 +- crates/session-view/src/tools/files.rs | 32 ++- crates/session-view/src/tools/mod.rs | 7 +- crates/session-view/src/turn_diff.rs | 46 +++- .../session-view/src/turns/codemode/cache.rs | 59 ++++- crates/session-view/src/turns/labels.rs | 6 +- .../timeline-extras/src/agent_rows/mod.rs | 19 +- features/timeline-extras/src/todos.rs | 110 +++++--- 24 files changed, 998 insertions(+), 370 deletions(-) diff --git a/apps/desktop/src/shell/view/composer.rs b/apps/desktop/src/shell/view/composer.rs index ea64fa6c2..2cbc7eb6d 100644 --- a/apps/desktop/src/shell/view/composer.rs +++ b/apps/desktop/src/shell/view/composer.rs @@ -595,28 +595,34 @@ fn folds( let need = |k: usize| { let t = narrow::Toolbar::after(k); // The add button and its 2 pt margin, the room, and Send. - let mut items = vec![30.0, 0.0, 28.0]; + let (mut sum, mut count) = (30.0 + 0.0 + 28.0_f32, 3usize); + let mut push = |w: f32| { + sum += w; + count += 1; + }; if s.kernel.slots.get(&crate::add_menu::ADD_MENU).shell() { // Exit and its keys (from 640 wide), 6 in and 6 apart, and 10 before Send. let keys = if s.layout.narrow.sm() { 6.0 + narrow::text_w(t!("common.key.esc"), UI_SMALL) + 8.0 } else { 0.0 }; - items.push(narrow::text_w(t!("ui.promptInput.exitShell"), UI_MED) + keys + 12.0 + 10.0); + push(narrow::text_w(t!("ui.promptInput.exitShell"), UI_MED) + keys + 12.0 + 10.0); } if mic && (t.mic || dictating) { - items.push(28.0); + push(28.0); } match (agent, t.agent) { - (Some(name), Agent::Name) => items.push(label(name, t.chevrons)), - (Some(_), Agent::Icon) => items.push(28.0), + (Some(name), Agent::Name) => push(label(name, t.chevrons)), + (Some(_), Agent::Icon) => push(28.0), _ => {} } // The slash takes its 6 pt either side, a little more than the spaces measured. let badge_w = badge.map_or(0.0, |b| 4.0 + 8.0 + narrow::text_w(b, session_view::pickers::view::TRIGGER_BADGE)); let whole = label(model.0, t.chevrons) + if model.1 { 4.0 } else { 0.0 } + badge_w; - items.push(if t.model_whole { whole } else { whole.min(narrow::MODEL_FLOOR) }); + push(if t.model_whole { whole } else { whole.min(narrow::MODEL_FLOOR) }); if t.effort { - items.extend(after.iter().flatten().map(|name| label(name, t.chevrons))); + for name in after.iter().flatten() { + push(label(name, t.chevrons)); + } } - items.iter().sum::() + 2.0 * (items.len() - 1) as f32 + sum + 2.0 * (count - 1) as f32 }; narrow::Toolbar::after(narrow::steps(room, narrow::Toolbar::FOLDS, need)) } diff --git a/apps/desktop/src/shell/view/session.rs b/apps/desktop/src/shell/view/session.rs index f167e028a..339652a41 100644 --- a/apps/desktop/src/shell/view/session.rs +++ b/apps/desktop/src/shell/view/session.rs @@ -71,8 +71,8 @@ pub(super) fn session_body(s: &App, p: &Pal, id: &str, page: El, with_header: bo s.kernel.slots.untracked(&crate::subagents::SHELLS).follow.version(), has_pills, session_view::TimelineHost::more_above(s, shown), - s.opening.as_ref().filter(|o| o.id == shown).and_then(|o| o.error()).map(str::to_owned), - crate::plugin_host::services::timeline::highlighted_row(s, shown).map(str::to_owned), + s.opening.as_ref().filter(|o| o.id == shown).and_then(|o| o.error()), + crate::plugin_host::services::timeline::highlighted_row(s, shown), ), ); let lane = session_view::jump::lane(has_pills); @@ -143,16 +143,29 @@ fn pills(s: &App, p: &Pal, id: &str) -> Vec { // The timeline's edge rises over their row first, so a pill fades in only once nothing is // under it, and goes at once so the edge can come back down (t1129). let enter = |pill: El| pill.transition(rune::Transition::asymmetric(rune::Transition::opacity(), rune::Transition::none())).enter_delay(PILL_WAIT); - let own: Vec = capsule.into_iter().chain(crate::todos::pill(s, p, id).map(|t| t.ml(gap))).collect(); + let todo = crate::todos::pill(s, p, id).map(|t| t.ml(gap)); + let plugin_pills = crate::plugin_host::pill_views(s, p, id); + let own_count = usize::from(capsule.is_some()) + usize::from(todo.is_some()); + let total = own_count + plugin_pills.len(); + if total == 0 { + return Vec::new(); + } + let mut out = Vec::with_capacity(total); + if let Some(c) = capsule { + out.push(enter(c)); + } + if let Some(t) = todo { + out.push(enter(t)); + } // Plugins' pills follow the app's (`SessionPluginPills`), 8 apart. - let gap = if own.is_empty() { 0.0 } else { 8.0 }; + let gap = if own_count == 0 { 0.0 } else { 8.0 }; // Keep each plugin pill's `region_with` placeholder unmodified for Rune's `same_root_el` // flattened-node reuse by applying margin and enter transition to a thin keyed wrapper. - let plugins = crate::plugin_host::pill_views(s, p, id).into_iter().enumerate().map(|(k, pill)| { + for (k, pill) in plugin_pills.into_iter().enumerate() { let wrap_key = pill.key_ref().map_or_else(|| format!("plugin-pill-wrap-{k}"), |name| format!("{name}-wrap")); - el().key(wrap_key).shrink().min_w(0.0).ml(if k == 0 { gap } else { 8.0 }).child(pill) - }); - own.into_iter().chain(plugins).map(enter).collect() + out.push(enter(el().key(wrap_key).shrink().min_w(0.0).ml(if k == 0 { gap } else { 8.0 }).child(pill))); + } + out } /// How long the timeline's edge takes to clear the pills' row (the page's spring). diff --git a/crates/session-view/src/compaction.rs b/crates/session-view/src/compaction.rs index d69edb956..6264fb31c 100644 --- a/crates/session-view/src/compaction.rs +++ b/crates/session-view/src/compaction.rs @@ -25,7 +25,7 @@ use crate::style::{BUBBLE, UI, markdown_tinted, readable}; const CYCLE: f32 = 3.2; /// One row of a compaction in the timeline. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Piece { Quiet, Start, @@ -82,6 +82,41 @@ pub fn view(s: &S, p: &Pal, c: &Compaction, piece: Piece, run: } } +/// Allocation-free memo stamp for a settled (`status != Running`) compaction row. +pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, run: Run) -> u64 { + use std::hash::{DefaultHasher, Hash, Hasher}; + let k = s.knobs(); + let state = (piece == Piece::Quiet) + .then(|| s.expanded().get_parts("cmp-", &c.id, "-quiet")) + .flatten(); + let open = state == Some(crate::disclosure::Disclosure::Open); + let shutting = matches!(state, Some(crate::disclosure::Disclosure::Shutting { .. })); + let tokens = c.tokens.as_ref().map(|t| (t.input, t.output, t.reasoning, t.cache_read, t.cache_write)); + let mut h = DefaultHasher::new(); + ( + &c.id, + std::mem::discriminant(&c.status), + c.manual, + &c.summary, + c.native, + &c.error, + c.created, + tokens, + piece, + run, + [open, shutting, s.reduced_motion()], + [ + crate::style::sticky_top().to_bits(), + crate::disclosure::fold(k).duration.to_bits(), + k.get(&crate::disclosure::FOLD_FEATHER).to_bits(), + k.get(&DIVIDER_GAP).to_bits(), + if open || shutting { crate::genui::width(s).to_bits() } else { 0 }, + ], + ) + .hash(&mut h); + h.finish() +} + /// A compaction the server admitted but hasn't started. pub fn queued(s: &S, p: &Pal, run: Run) -> El { divider(s, p, opencode_i18n::t!("ui.messagePart.compaction.queued"), run) @@ -96,7 +131,7 @@ pub const GROUP: Group = Group::new("Dividers", "dividers", &[DIVIDER_GAP]).unde pub const WORDS: f32 = 16.0; /// What sits beside a divider, on one side. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Beside { /// Rows with no room of their own toward it, as a reply's text: the turn's usual 16. #[default] @@ -108,7 +143,7 @@ pub enum Beside { } /// What sits above and below a divider, and who holds the room over its words. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Run { pub above: Beside, pub below: Beside, @@ -119,7 +154,7 @@ pub struct Run { /// never the lower row (official `timeline-next/spacing.ts` `timelineGaps`, where a divider is a /// row like any other; `packages/app/AGENTS.md` "Rows that load above the reader"): a divider /// that took it on top would change when the row before it loads, and move what is on screen. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Over { /// The divider: it starts the session, and nothing loads above it. #[default] @@ -233,9 +268,9 @@ fn error_card(p: &Pal, message: &str) -> El { fn quiet_view(s: &S, p: &Pal, c: &Compaction, run: Run) -> El { let running = c.status == CompactionStatus::Running; - // Only the active divider needs a phase. Map the work's start to the animation clock; - // no per-poll history of which dividers have mounted is needed. - let start = if running { s.clock() - s.now_ms().saturating_sub(c.created).max(0) as f64 / 1000.0 } else { 0.0 }; + // Only the active divider needs a phase. Read the untracked poll clock and wall clock so + // an active compaction divider never subscribes `timeline-fade` to the 165 Hz frame clock. + let start = if running { s.working_state().poll_clock() - s.now_ms_untracked().saturating_sub(c.created).max(0) as f64 / 1000.0 } else { 0.0 }; let body = summary(c); let expandable = !running && !body.is_empty(); let key = Piece::Quiet.key(&c.id); @@ -332,7 +367,7 @@ fn light(s: &S, p: &Pal, start: f64, end: bool) -> El { let peak = Color { a: p.muted.a * 0.55, ..p.muted }; let clear = Color { a: 0.0, ..p.muted }; let (from, to) = if end { (-SLIDE.0, -SLIDE.1) } else { SLIDE }; - let slide = LoopSpec { delay: loop_delay(s.clock(), start), ..LoopSpec::slide(f64::from(CYCLE), [from, 0.0], [to, 0.0]).easing(travel()) }; + let slide = LoopSpec { delay: loop_delay(s.working_state().poll_clock(), start), ..LoopSpec::slide(f64::from(CYCLE), [from, 0.0], [to, 0.0]).easing(travel()) }; let beam = el() .key("beam") .pin((!end).then_some(0.0), Some(0.0), end.then_some(0.0), None) diff --git a/crates/session-view/src/copied.rs b/crates/session-view/src/copied.rs index c6bc53054..dbf721efd 100644 --- a/crates/session-view/src/copied.rs +++ b/crates/session-view/src/copied.rs @@ -176,12 +176,56 @@ pub fn mark_copied(s: &mut S, key: impl Into, tx: &mut } } +/// Whether any copy button currently shows a tick. +#[inline] +pub fn is_empty(s: &S) -> bool { + s.copied_state().ticks.is_empty() +} + /// Whether copy button `key` shows its tick (`poll` evicts expired entries before view, so view /// memos never read the 60 Hz frame clock). pub fn is_copied(s: &S, key: &str) -> bool { s.copied_state().ticks.contains_key(key) } +/// Allocation-free check for a copy key composed of `prefix` + `suffix`. +pub fn is_copied_prefixed(s: &S, prefix: &str, suffix: &str) -> bool { + let ticks = &s.copied_state().ticks; + if ticks.is_empty() { + return false; + } + let len = prefix.len() + suffix.len(); + ticks.keys().any(|k| k.len() == len && k.starts_with(prefix) && k.ends_with(suffix)) +} + +/// Order-independent hash stamp of all active copy ticks without allocating or sorting a `Vec`. +pub fn stamp(s: &S) -> u64 { + let ticks = &s.copied_state().ticks; + if ticks.is_empty() { + return 0; + } + use std::hash::{DefaultHasher, Hash, Hasher}; + ticks.keys().fold(0u64, |sum, key| { + let mut h = DefaultHasher::new(); + key.hash(&mut h); + sum.wrapping_add(h.finish()) + }) +} + +/// Order-independent hash stamp of active copy ticks whose key contains `needle`. +pub fn stamp_containing(s: &S, needle: &str) -> u64 { + let ticks = &s.copied_state().ticks; + if ticks.is_empty() { + return 0; + } + use std::hash::{DefaultHasher, Hash, Hasher}; + ticks.keys().filter(|k| k.contains(needle)).fold(0u64, |sum, key| { + let mut h = DefaultHasher::new(); + key.hash(&mut h); + sum.wrapping_add(h.finish()) + }) +} + /// The copy buttons showing their ticks now, in order (`poll` evicts expired entries before view). pub fn current(s: &S) -> Vec { if s.copied_state().ticks.is_empty() { diff --git a/crates/session-view/src/disclosure.rs b/crates/session-view/src/disclosure.rs index 35ecfa16c..965403281 100644 --- a/crates/session-view/src/disclosure.rs +++ b/crates/session-view/src/disclosure.rs @@ -127,22 +127,84 @@ impl Disclosures { self.0.get(key).copied() } + /// Allocation-free lookup for a key formed by concatenating `prefix` and `suffix`. + pub fn get_prefixed(&self, prefix: &str, suffix: &str) -> Option { + self.get_parts(prefix, suffix, "") + } + + /// Allocation-free lookup for a key formed by concatenating `a`, `b`, and `c`. + pub fn get_parts(&self, a: &str, b: &str, c: &str) -> Option { + if self.0.is_empty() { + return None; + } + let total = a.len() + b.len() + c.len(); + let mut buf = [0u8; 128]; + if total <= buf.len() { + let ab = a.len() + b.len(); + buf[..a.len()].copy_from_slice(a.as_bytes()); + buf[a.len()..ab].copy_from_slice(b.as_bytes()); + buf[ab..total].copy_from_slice(c.as_bytes()); + if let Ok(key) = std::str::from_utf8(&buf[..total]) { + return self.0.get(key).copied(); + } + } + let mut owned = String::with_capacity(total); + owned.push_str(a); + owned.push_str(b); + owned.push_str(c); + self.0.get(&owned).copied() + } + /// Whether the reader opened `key`. pub fn contains(&self, key: &str) -> bool { self.get(key) == Some(Disclosure::Open) } + /// True when no disclosures have been toggled in any state. + #[inline] + pub fn none_touched(&self) -> bool { + self.0.is_empty() + } + /// What the reader toggled among the keys that start with `prefix`, as a number that moves /// when one of them opens, shuts or follows its default again: for a memo whose row draws /// such a disclosure (`rune::memo` builds again only when its version moves). pub fn stamp(&self, prefix: &str) -> u64 { + self.stamp_parts(prefix, "", "") + } + + /// Like [`Self::stamp`] for a prefix formed by concatenating `a`, `b`, and `c` without + /// allocating a temporary `String`. + pub fn stamp_parts(&self, a: &str, b: &str, c: &str) -> u64 { + if self.0.is_empty() { + return 0; + } use std::hash::{DefaultHasher, Hash, Hasher}; // The map has no order, so the sum of each one's hash. - self.0.iter().filter(|(key, _)| key.starts_with(prefix)).fold(0, |sum, (key, state)| { - let mut h = DefaultHasher::new(); - (key, std::mem::discriminant(state)).hash(&mut h); - sum.wrapping_add(h.finish()) - }) + self.0 + .iter() + .filter(|(key, _)| { + key.strip_prefix(a) + .and_then(|r| r.strip_prefix(b)) + .is_some_and(|r| r.starts_with(c)) + }) + .fold(0, |sum, (key, state)| { + let mut h = DefaultHasher::new(); + (key, std::mem::discriminant(state)).hash(&mut h); + sum.wrapping_add(h.finish()) + }) + } + + /// True when any key starting with `a + b + c` is currently springing shut. + pub fn any_shutting_parts(&self, a: &str, b: &str, c: &str) -> bool { + !self.0.is_empty() + && self.0.iter().any(|(key, state)| { + matches!(state, Disclosure::Shutting { .. }) + && key + .strip_prefix(a) + .and_then(|r| r.strip_prefix(b)) + .is_some_and(|r| r.starts_with(c)) + }) } /// Opens `key`; true when it wasn't open. diff --git a/crates/session-view/src/fold.rs b/crates/session-view/src/fold.rs index dac143fed..1181511c7 100644 --- a/crates/session-view/src/fold.rs +++ b/crates/session-view/src/fold.rs @@ -83,9 +83,12 @@ pub fn place<'a, S: TimelineHost>(s: &'a S, session: &'a str) -> impl Fn(&str) - } } +/// Prefix of [`key`], for allocation-free disclosure lookups. +pub const KEY_PREFIX: &str = "user-expanded:"; + /// The `expanded` key of an opened prompt, Desktop's disclosure key. pub fn key(id: &str) -> String { - format!("user-expanded:{id}") + format!("{KEY_PREFIX}{id}") } /// The width a prompt's words wrap at in a timeline viewport `viewport` points wide: the row is diff --git a/crates/session-view/src/jump.rs b/crates/session-view/src/jump.rs index f153d33f6..534f8f7bb 100644 --- a/crates/session-view/src/jump.rs +++ b/crates/session-view/src/jump.rs @@ -116,7 +116,7 @@ impl Look { /// Moves to shown or hidden at `now`, `rise` points below where it shows; one already there /// stays. `settle`: the seconds the longer curve takes, after which both layers are at rest. /// Under reduced motion it lands at once, with no fade and no rise. - fn show(&self, shown: bool, rise: f32, reduced: bool, now: f64, settle: f64) { + fn show(&self, shown: bool, rise: f32, reduced: bool, now: impl FnOnce() -> f64, settle: f64) { let was = self.moved.get(); if reduced { self.fade.snap(if shown { 1.0 } else { 0.0 }); @@ -125,8 +125,12 @@ impl Look { self.moved.set(Moved { shown, rise: 0.0, at: f64::NEG_INFINITY, by_in: false }); return; } + if shown == was.shown && rise == was.rise { + return; + } + let now = now(); let settled = now - was.at >= settle; - if shown == was.shown && (rise == was.rise || !settled) { + if shown == was.shown && !settled { return; } if settled { @@ -391,7 +395,7 @@ fn rise(s: &S) -> f32 { fn show_look(s: &S, id: &str, shown: bool) { let settle = s.knobs().get(&crate::knobs::JUMP_IN).max(s.knobs().get(&crate::knobs::JUMP_OUT)) as f64; if let Some(look) = s.ends().looks.borrow().get(id) { - look.show(shown, rise(s), s.reduced_motion(), s.clock(), settle); + look.show(shown, rise(s), s.reduced_motion(), || s.clock(), settle); } } @@ -494,7 +498,16 @@ pub fn over_scroll(s: &S, p: &Pal, id: &str, scroll_fade: El, p let shown = s.ends().far(id); // Timeline knobs: 0.15 s in, 0.11 s out, rising 4 pt as it shows (`translate-y-1`). let (enter, leave) = (crate::knobs::jump(s.knobs(), true), crate::knobs::jump(s.knobs(), false)); - let look = s.ends().looks.borrow_mut().entry(id.to_owned()).or_insert_with(|| Look::new(shown, rise(s))).clone(); + let look = { + let mut looks = s.ends().looks.borrow_mut(); + if let Some(existing) = looks.get(id) { + existing.clone() + } else { + let created = Look::new(shown, rise(s)); + looks.insert(id.to_owned(), created.clone()); + created + } + }; show_look(s, id, shown); let target = format!("scroll-{id}"); let session = id.to_owned(); diff --git a/crates/session-view/src/line_reveal.rs b/crates/session-view/src/line_reveal.rs index d72dea6dd..8394a556b 100644 --- a/crates/session-view/src/line_reveal.rs +++ b/crates/session-view/src/line_reveal.rs @@ -4,7 +4,7 @@ //! (`cursor <= arrived`), Markdown-safe (never flashes unclosed `*`, `` ` ``, `[label](url`, or //! dangling block markers), strictly monotonic, and draining over 80 ms when a turn ends. -use std::{cell::Cell, collections::{HashMap, HashSet}}; +use std::{cell::{Cell, RefCell}, collections::{HashMap, HashSet}}; use rune::Tx; @@ -18,19 +18,23 @@ struct PartKey { part: usize, } +type DripMap = HashMap>>; + /// How much of each live streaming text part shows while Adaptive Drip paces batches. #[derive(Clone, Default, PartialEq)] pub struct Hold { - drip: HashMap>>, - poll: Poll, - pending: Vec<(usize, usize)>, + /// Interior-mutable so sub-word cursor ticks and non-text transcript updates never bump + /// `Tracked`; [`poll`] touches `line_hold_mut()` only when visible output changes. + drip: RefCell, + poll: RefCell, + pending: RefCell>, // Bookkeeping only: advancing the clock must not invalidate the timeline's regions. last_poll: Cell, /// Last armed `tx.wake_after` deadline on the app clock (deduplicates sub-frame polls). wake_due: Cell>, /// Keys that already completed a drip so switching tabs back to a live session never replays /// an already-settled short preamble from 0. - seen: HashSet, + seen: RefCell>, } /// A caught-up turn has no timer work. Revisit it only when its inputs change; keep the @@ -169,25 +173,27 @@ impl Drip { impl Hold { /// Bytes of part `part` of `message` in `session` revealed so far while Adaptive Drip runs. pub fn paced(&self, session: &str, message: &str, part: usize) -> Option { - if self.drip.is_empty() { + let drip = self.drip.borrow(); + if drip.is_empty() { return None; } - self.drip.get(session)?.get(message)?.get(&part).map(|d| d.shown) + drip.get(session)?.get(message)?.get(&part).map(|d| d.shown) } /// True while Adaptive Drip is still releasing buffered bytes for `message` in `session`, so /// the turn's `Working` status waits until the final word lands before handing off to `Copy`. pub fn is_draining(&self, session: &str, message: &str) -> bool { - if self.drip.is_empty() { + let drip = self.drip.borrow(); + if drip.is_empty() { return false; } - self.drip.get(session).and_then(|s| s.get(message)) + drip.get(session).and_then(|s| s.get(message)) .is_some_and(|parts| parts.values().any(|d| d.shown < d.last_len)) } /// True when no streaming text parts are currently tracked by Adaptive Drip. pub(crate) fn is_empty(&self) -> bool { - self.drip.is_empty() + self.drip.borrow().is_empty() } } @@ -196,12 +202,12 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { if !crate::experiments::drip(s.knobs()) { let hold = s.line_hold(); hold.wake_due.set(None); - let had_drip = !hold.drip.is_empty(); - if hold.poll != Poll::Unversioned || !hold.pending.is_empty() || had_drip { - let hold = s.line_hold_mut(); - hold.poll = Poll::Unversioned; - hold.pending.clear(); - hold.drip.clear(); + let had_drip = !hold.drip.borrow().is_empty(); + *hold.poll.borrow_mut() = Poll::Unversioned; + hold.pending.borrow_mut().clear(); + if had_drip { + hold.drip.borrow_mut().clear(); + let _ = s.line_hold_mut(); } return had_drip; } @@ -210,7 +216,7 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { return false; }; let live = s.is_session_live(sid); - if !live && s.line_hold().drip.is_empty() { + if !live && s.line_hold().is_empty() { s.line_hold().wake_due.set(None); return false; } @@ -218,84 +224,120 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { let stopped = s.is_session_stopped(sid); let instant = reduced || (!live && stopped); let version = s.transcript_version(sid); - let prior = match &s.line_hold().poll { + let hold = s.line_hold(); + let prior = match &*hold.poll.borrow() { Poll::Current { session, version, live: l, instant: i, len } if session == sid && *l == live && *i == instant => Some((*version, *len)), _ => None, }; - if prior.is_some_and(|(v, _)| Some(v) == version) && s.line_hold().pending.is_empty() { - s.line_hold().last_poll.set(now); - s.line_hold().wake_due.set(None); + if prior.is_some_and(|(v, _)| Some(v) == version) && hold.pending.borrow().is_empty() { + hold.last_poll.set(now); + hold.wake_due.set(None); return false; } let from = prior.map_or(0, |(v, _)| { if Some(v) == version { usize::MAX } else { s.transcript_changed_from(sid, v).unwrap_or(0) } }); - let sid = sid.to_owned(); let step_dt = drip_step(s.display_hz()); - let mut hold = std::mem::take(s.line_hold_mut()); + let last_poll = hold.last_poll.get(); let mut changed = false; + let mut visible_changed = false; let mut next = f64::INFINITY; - let mut live_keys: HashSet<(usize, usize)> = HashSet::new(); let mut checked = None; - s.with_transcript(&sid, |t| { + s.with_transcript(sid, |t| { let from = if prior.is_none_or(|(_, len)| t.messages.len() < len) || t.messages.iter().skip(from).any(|m| matches!(m, opencode_kit::model::Message::User { .. })) { 0 } else { from }; - let mut targets = std::mem::take(&mut hold.pending); - if from == 0 { targets.clear(); } + let mut pending = hold.pending.borrow_mut(); + if from == 0 { pending.clear(); } // Only edited/new messages need discovery. A caught-up old part is revisited if its // message changes; a part still dripping stays in `pending` until it catches up. for (mi, m) in t.messages.iter().enumerate().skip(from).rev() .take_while(|(_, m)| !matches!(**m, opencode_kit::model::Message::User { .. })) { let opencode_kit::model::Message::Assistant(a) = m else { continue }; - targets.extend(a.parts.iter().enumerate().filter_map(|(pi, p)| matches!(p, opencode_kit::model::Part::Text { .. }).then_some((mi, pi)))); + pending.extend(a.parts.iter().enumerate().filter_map(|(pi, p)| matches!(p, opencode_kit::model::Part::Text { .. }).then_some((mi, pi)))); } - targets.sort_unstable(); - targets.dedup(); - for (mi, i) in targets { + pending.sort_unstable(); + pending.dedup(); + let mut drip = hold.drip.borrow_mut(); + let mut seen = hold.seen.borrow_mut(); + let mut keep_len = 0usize; + let mut live_keys = Vec::with_capacity(pending.len()); + for idx in 0..pending.len() { + let (mi, i) = pending[idx]; let Some(opencode_kit::model::Message::Assistant(a)) = t.messages.get(mi) else { continue }; let Some(opencode_kit::model::Part::Text { text }) = a.parts.get(i) else { continue }; if text.trim().is_empty() { continue; } - let key = PartKey { session: sid.clone(), message: a.id.clone(), part: i }; - let existing = hold.drip.get(&sid).and_then(|s| s.get(&a.id)).is_some_and(|p| p.contains_key(&i)); + let existing = drip.get(sid).and_then(|s| s.get(&a.id)).is_some_and(|p| p.contains_key(&i)); if !live && !existing { continue; } - let already_seen = hold.seen.contains(&key); - let d = hold.drip.entry(sid.clone()).or_default().entry(a.id.clone()).or_default().entry(i) - .or_insert_with(|| Drip::new(text.len(), live, already_seen, instant, now)); - // Skipped settled parts still experience the same per-frame dt on their next delta. - if existing { d.last_tick = hold.last_poll.get(); } + let d = if let Some(d) = drip.get_mut(sid).and_then(|s| s.get_mut(&a.id)).and_then(|p| p.get_mut(&i)) { + // Skipped settled parts still experience the same per-frame dt on their next delta. + d.last_tick = last_poll; + d + } else { + visible_changed = true; + let key = PartKey { session: sid.to_owned(), message: a.id.clone(), part: i }; + let already_seen = seen.contains(&key); + let sess_map = match drip.get_mut(sid) { + Some(m) => m, + None => drip.entry(sid.to_owned()).or_default(), + }; + let msg_map = match sess_map.get_mut(&a.id) { + Some(m) => m, + None => sess_map.entry(a.id.clone()).or_default(), + }; + msg_map.entry(i).or_insert_with(|| Drip::new(text.len(), live, already_seen, instant, now)) + }; + let was_draining = d.shown < d.last_len; d.message = mi; let (c, wake) = d.step(text, live, instant, now, step_dt); changed |= c; + visible_changed |= c || (d.shown < d.last_len) != was_draining; if let Some(w) = wake { next = next.min(w); - hold.pending.push((mi, i)); + pending[keep_len] = (mi, i); + keep_len += 1; } - if d.shown >= d.last_len && d.last_len > 0 { - if hold.seen.len() > 256 { hold.seen.clear(); } - hold.seen.insert(key.clone()); + if d.shown >= d.last_len && d.last_len > 0 + && !seen.iter().any(|k| k.part == i && k.message == a.id && k.session == sid) + { + if seen.len() > 256 { seen.clear(); } + seen.insert(PartKey { session: sid.to_owned(), message: a.id.clone(), part: i }); } - live_keys.insert((mi, i)); + live_keys.push((mi, i)); } - hold.drip.retain(|session, messages| { + pending.truncate(keep_len); + drip.retain(|session, messages| { messages.retain(|_, parts| { let before = parts.len(); parts.retain(|&part, d| { - session == &sid && (d.message < from || live_keys.contains(&(d.message, part))) + session == sid && (d.message < from || live_keys.contains(&(d.message, part))) && !matches!(d.phase, DripPhase::Done) }); - changed |= parts.len() != before; + let removed = parts.len() != before; + changed |= removed; + visible_changed |= removed; !parts.is_empty() }); !messages.is_empty() }); checked = Some(t.messages.len()); }); - hold.poll = match (version, checked) { - (Some(version), Some(len)) => Poll::Current { session: sid, version, live, instant, len }, - _ => Poll::Unversioned, - }; + { + let mut poll = hold.poll.borrow_mut(); + match (version, checked) { + (Some(v), Some(len)) => match &mut *poll { + Poll::Current { session, version, live: l, instant: i, len: plen } if session == sid => { + *version = v; + *l = live; + *i = instant; + *plen = len; + } + slot => *slot = Poll::Current { session: sid.to_owned(), version: v, live, instant, len }, + }, + _ => *poll = Poll::Unversioned, + } + } hold.last_poll.set(now); if next.is_finite() { let wait = next.max(0.0); @@ -310,7 +352,9 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { } else { hold.wake_due.set(None); } - *s.line_hold_mut() = hold; + if visible_changed { + let _ = s.line_hold_mut(); + } changed } diff --git a/crates/session-view/src/recall.rs b/crates/session-view/src/recall.rs index 12f69edae..065f578b0 100644 --- a/crates/session-view/src/recall.rs +++ b/crates/session-view/src/recall.rs @@ -52,7 +52,11 @@ pub struct Marks { impl Recall { pub fn marks(&self, session: &str) -> Rc { - self.marks.borrow_mut().entry(session.to_owned()).or_insert_with(|| Rc::new(Marks { + let mut marks = self.marks.borrow_mut(); + if let Some(existing) = marks.get(session) { + return existing.clone(); + } + let created = Rc::new(Marks { view: Live::new([0.0; 4]), stack: Live::new([0.0; 4]), header_h: Cell::new(0.0), @@ -60,7 +64,9 @@ impl Recall { rows: RefCell::default(), touched: Cell::new(0), visible: RefCell::default(), - })).clone() + }); + marks.insert(session.to_owned(), created.clone()); + created } /// Row `key` and where its top stood below the viewport's top (negative when above it): diff --git a/crates/session-view/src/sources_chip.rs b/crates/session-view/src/sources_chip.rs index d4503a9d3..53f151bca 100644 --- a/crates/session-view/src/sources_chip.rs +++ b/crates/session-view/src/sources_chip.rs @@ -35,14 +35,13 @@ pub fn of(t: &Transcript, message: usize) -> Option { let mut seen: Vec = Vec::new(); let mut sites: Vec<(String, String)> = Vec::new(); let mut count = 0; - let mut meet = |url: &str| { - let Some((site, key, host)) = page(url) else { return }; + let mut meet_page = |(site, key, host): (String, String, String)| { if seen.contains(&key) { return; } seen.push(key); count += 1; - if !sites.iter().any(|(s, _)| *s == site) { + if sites.len() < 3 && !sites.iter().any(|(s, _)| *s == site) { sites.push((site, host)); } }; @@ -58,26 +57,29 @@ pub fn of(t: &Transcript, message: usize) -> Option { steps += 1; if matches!(status, ToolStatus::Completed) { for url in results(tool_output(status, metadata).unwrap_or_default()) { - meet(&url); + if let Some(p) = page(url) { + meet_page(p); + } } } } "webfetch" => { - let Some(url) = input["url"].as_str().filter(|u| page(u).is_some()) else { continue }; + let Some(url) = input["url"].as_str() else { continue }; + let Some(p) = page(url) else { continue }; steps += 1; if !matches!(status, ToolStatus::Error) { - meet(url); + meet_page(p); } } _ => {} } } } - sites.truncate(3); (steps > 0).then(|| Chip { prompt: prompt.clone(), count, sites }) } -/// Hashes the source-chip inputs of assistant step `a` into `h` for `projection::shape`. +/// Hashes the source-chip inputs of assistant step `a` into `h` for `projection::shape` without +/// allocating temporary URL or host strings. pub(crate) fn hash_assistant_sources(a: &opencode_kit::model::Assistant, h: &mut impl std::hash::Hasher) { use std::hash::Hash as _; for part in &a.parts { @@ -91,15 +93,15 @@ pub(crate) fn hash_assistant_sources(a: &opencode_kit::model::Assistant, h: &mut std::mem::discriminant(status).hash(h); if matches!(status, ToolStatus::Completed) { for url in results(tool_output(status, metadata).unwrap_or_default()) { - page(&url).hash(h); + hash_page(url, h).hash(h); } } } "webfetch" => { - if let Some(p) = input["url"].as_str().and_then(page) { + if let Some(url) = input["url"].as_str() && page_parts(url).is_some() { 2u8.hash(h); matches!(status, ToolStatus::Error).hash(h); - p.hash(h); + hash_page(url, h); } } _ => {} @@ -107,17 +109,42 @@ pub(crate) fn hash_assistant_sources(a: &opencode_kit::model::Assistant, h: &mut } } +fn page_parts(url: &str) -> Option<(&str, &str, Option<&str>)> { + let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"))?; + let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let host = rest[..end].rsplit('@').next()?.split(':').next()?; + if host.is_empty() { + return None; + } + let tail = rest[end..].split('#').next().unwrap_or_default(); + let (path, query) = tail.split_once('?').map_or((tail, None), |(p, q)| (p, Some(q))); + Some((host, path.trim_end_matches('/'), query)) +} + +fn hash_page(url: &str, h: &mut impl std::hash::Hasher) -> bool { + use std::hash::Hash as _; + let Some((host, path, query)) = page_parts(url) else { + return false; + }; + host.len().hash(h); + for c in host.chars() { + for lc in c.to_lowercase() { + lc.hash(h); + } + } + (path, query).hash(h); + true +} + /// The URLs of a search's `## [title](url)` result headings. -fn results(text: &str) -> Vec { - text.split('\n') - .filter_map(|line| { - if !line.starts_with("## [") || !line.ends_with(')') { - return None; - } - let split = line.rfind("](").filter(|&i| i >= 4)?; - Some(line[split + 2..line.len() - 1].to_owned()) - }) - .collect() +fn results(text: &str) -> impl Iterator { + text.split('\n').filter_map(|line| { + if !line.starts_with("## [") || !line.ends_with(')') { + return None; + } + let split = line.rfind("](").filter(|&i| i >= 4)?; + Some(&line[split + 2..line.len() - 1]) + }) } /// A web page's site (its host without `www.`), its identity (the site, path without a diff --git a/crates/session-view/src/timeline/group_hash.rs b/crates/session-view/src/timeline/group_hash.rs index 3541b3ece..79b4ef9d9 100644 --- a/crates/session-view/src/timeline/group_hash.rs +++ b/crates/session-view/src/timeline/group_hash.rs @@ -88,8 +88,8 @@ impl SessionCache { self.detail_ranges.retain(|&(_, end), _| end <= at); self.version = version; self.len = n; - self.first_id = t.messages.first().map(|m| m.id().to_owned()); - self.last_id = t.messages.last().map(|m| m.id().to_owned()); + sync_opt_str(&mut self.first_id, t.messages.first().map(Message::id)); + sync_opt_str(&mut self.last_id, t.messages.last().map(Message::id)); } fn same_shape(&self, t: &Transcript) -> bool { @@ -103,43 +103,116 @@ impl SessionCache { } } +#[derive(Clone)] +struct OwnedSessionKey(u64, String); + +trait SessionKey { + fn parts(&self) -> (u64, &str); +} + +impl SessionKey for OwnedSessionKey { + fn parts(&self) -> (u64, &str) { (self.0, &self.1) } +} + +impl SessionKey for (u64, &str) { + fn parts(&self) -> (u64, &str) { *self } +} + +impl PartialEq for OwnedSessionKey { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for OwnedSessionKey {} + +impl Hash for OwnedSessionKey { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + +impl<'a> std::borrow::Borrow for OwnedSessionKey { + fn borrow(&self) -> &(dyn SessionKey + 'a) { self } +} + +impl PartialEq for dyn SessionKey + '_ { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for dyn SessionKey + '_ {} + +impl Hash for dyn SessionKey + '_ { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + +fn sync_opt_str(slot: &mut Option, next: Option<&str>) { + match (slot, next) { + (Some(cur), Some(val)) if cur == val => {} + (Some(cur), Some(val)) => { + cur.clear(); + cur.push_str(val); + } + (slot, Some(val)) => *slot = Some(val.to_owned()), + (slot, None) => *slot = None, + } +} + +/// Order-independent, allocation-free stamp of per-block code-wrap overrides scoped to `row_key`. +pub(super) fn code_wrap_stamp(overrides: Option<&HashMap>, row_key: &str) -> u64 { + let Some(overrides) = overrides.filter(|m| !m.is_empty()) else { + return 0; + }; + overrides + .iter() + .filter(|(key, _)| { + key.strip_prefix(row_key).is_some_and(|rest| { + rest.starts_with(':') || rest.starts_with("-md-") || rest.starts_with("-v-") + }) + }) + .fold(0u64, |sum, pair| { + let mut one = DefaultHasher::new(); + pair.hash(&mut one); + sum.wrapping_add(one.finish()) + }) +} + thread_local! { - static CACHE: RefCell> = RefCell::new(SessionLru::new()); + static CACHE: RefCell> = RefCell::new(SessionLru::new()); } -fn sync_entry<'a, S: TimelineHost>( - cache: &'a mut SessionLru<(u64, String), SessionCache, KEPT>, +#[allow(clippy::too_many_arguments)] +fn with_entry( + cache: &mut SessionLru, s: &S, t: &Transcript, version: u64, edits: bool, script_diffs: bool, flatten_cm: bool, -) -> &'a mut SessionCache { - let session_key = (s.transcript_source_id(), t.session.clone()); - let (entry, existed) = cache.get_or_insert_with(session_key, || { - SessionCache::new(version, edits, script_diffs, flatten_cm, t) - }); - if !existed { - return entry; - } - let same_flags = entry.edits == edits && entry.script_diffs == script_diffs && entry.flatten_cm == flatten_cm; - if same_flags && entry.version == version && entry.same_shape(t) { - return entry; - } - if same_flags { - match s.transcript_changed_from(&t.session, entry.version) { - Some(usize::MAX) if entry.same_shape(t) => entry.version = version, - Some(usize::MAX) => entry.reset(version, edits, script_diffs, flatten_cm, t), - Some(at) if at == 0 || entry.first_id.as_deref() == t.messages.first().map(Message::id) => { - entry.invalidate_from(at, version, t); + f: impl FnOnce(&mut SessionCache) -> R, +) -> R { + let source_id = s.transcript_source_id(); + let lookup = (source_id, t.session.as_str()); + if let Some(entry) = cache.get_mut(&lookup as &dyn SessionKey) { + let same_flags = entry.edits == edits && entry.script_diffs == script_diffs && entry.flatten_cm == flatten_cm; + if !(same_flags && entry.version == version && entry.same_shape(t)) { + if same_flags { + match s.transcript_changed_from(&t.session, entry.version) { + Some(usize::MAX) if entry.same_shape(t) => entry.version = version, + Some(usize::MAX) => entry.reset(version, edits, script_diffs, flatten_cm, t), + Some(at) if at == 0 || entry.first_id.as_deref() == t.messages.first().map(Message::id) => { + entry.invalidate_from(at, version, t); + } + _ => entry.reset(version, edits, script_diffs, flatten_cm, t), + } + } else { + entry.reset(version, edits, script_diffs, flatten_cm, t); } - _ => entry.reset(version, edits, script_diffs, flatten_cm, t), } - } else { - entry.reset(version, edits, script_diffs, flatten_cm, t); + return f(entry); } - entry + let entry = cache.insert_or_evict( + OwnedSessionKey(source_id, t.session.clone()), + SessionCache::new(version, edits, script_diffs, flatten_cm, t), + ); + f(entry) } /// Summary hash of the turn slice `range` of `t` for collapsed `c-*` groups, `Events`, and closed @@ -158,25 +231,26 @@ pub(super) fn of( return hash_uncached(&t.messages[range], edits, group); }; CACHE.with_borrow_mut(|cache| { - let entry = sync_entry(cache, s, t, version, edits, script_diffs, flatten_cm); - if let Some(v) = entry.get_range(&range, group) { - return v; - } - let last_tool = (!group).then(|| last_tool_in(&t.messages[range.clone()])).flatten(); - let mut h = DefaultHasher::new(); - (range.end - range.start).hash(&mut h); - for (rel, (slot, m)) in entry.per_msg[range.clone()].iter_mut().zip(&t.messages[range.clone()]).enumerate() { - let trailing_from = (!group).then(|| trailing_text_from(rel, last_tool)).flatten(); - let mh = if has_trailing_text(m, trailing_from) { - message_hash(m, edits, trailing_from) - } else { - *slot.get_or_insert_with(|| message_hash(m, edits, None)) - }; - mh.hash(&mut h); - } - let combined = h.finish(); - entry.ranges.insert((range.start, range.end, group), combined); - combined + with_entry(cache, s, t, version, edits, script_diffs, flatten_cm, |entry| { + if let Some(v) = entry.get_range(&range, group) { + return v; + } + let last_tool = (!group).then(|| last_tool_in(&t.messages[range.clone()])).flatten(); + let mut h = DefaultHasher::new(); + (range.end - range.start).hash(&mut h); + for (rel, (slot, m)) in entry.per_msg[range.clone()].iter_mut().zip(&t.messages[range.clone()]).enumerate() { + let trailing_from = (!group).then(|| trailing_text_from(rel, last_tool)).flatten(); + let mh = if has_trailing_text(m, trailing_from) { + message_hash(m, edits, trailing_from) + } else { + *slot.get_or_insert_with(|| message_hash(m, edits, None)) + }; + mh.hash(&mut h); + } + let combined = h.finish(); + entry.ranges.insert((range.start, range.end, group), combined); + combined + }) }) } @@ -201,20 +275,21 @@ pub(super) fn detail_of( return h.finish(); }; CACHE.with_borrow_mut(|cache| { - let entry = sync_entry(cache, s, t, version, edits, script_diffs, flatten_cm); - if let Some(&v) = entry.detail_ranges.get(&(range.start, range.end)) { - return v; - } - let SessionCache { per_msg_detail, part_detail, detail_ranges, .. } = entry; - let mut h = DefaultHasher::new(); - (range.end - range.start).hash(&mut h); - for (slot, m) in per_msg_detail[range.clone()].iter_mut().zip(&t.messages[range.clone()]) { - let mh = *slot.get_or_insert_with(|| detail_message_hash(m, Some(part_detail))); - mh.hash(&mut h); - } - let combined = h.finish(); - detail_ranges.insert((range.start, range.end), combined); - combined + with_entry(cache, s, t, version, edits, script_diffs, flatten_cm, |entry| { + if let Some(&v) = entry.detail_ranges.get(&(range.start, range.end)) { + return v; + } + let SessionCache { per_msg_detail, part_detail, detail_ranges, .. } = entry; + let mut h = DefaultHasher::new(); + (range.end - range.start).hash(&mut h); + for (slot, m) in per_msg_detail[range.clone()].iter_mut().zip(&t.messages[range.clone()]) { + let mh = *slot.get_or_insert_with(|| detail_message_hash(m, Some(part_detail))); + mh.hash(&mut h); + } + let combined = h.finish(); + detail_ranges.insert((range.start, range.end), combined); + combined + }) }) } @@ -235,11 +310,40 @@ fn detail_part_hash(p: &Part) -> u64 { h.finish() } +pub(super) fn hash_notice_kind(kind: &opencode_kit::model::NoticeKind, h: &mut impl Hasher) { + use opencode_kit::model::NoticeKind; + std::mem::discriminant(kind).hash(h); + match kind { + NoticeKind::Agent { agent, previous } => (agent, previous).hash(h), + NoticeKind::Model { model, previous } => { + (&model.provider, &model.id, &model.variant).hash(h); + if let Some(prev) = previous { + (true, &prev.provider, &prev.id, &prev.variant).hash(h); + } else { + false.hash(h); + } + } + NoticeKind::Moved { directory, previous } => (directory, previous).hash(h), + NoticeKind::Instructions { sources } => sources.hash(h), + NoticeKind::Restart | NoticeKind::Idle => {} + NoticeKind::Finished(f) => { + (&f.agent, f.subagent, std::mem::discriminant(&f.outcome), &f.data, f.required, &f.shell, &f.child).hash(h); + } + NoticeKind::Job { id, description, script, required } => { + (id, description, script.map(|o| std::mem::discriminant(&o)), required).hash(h); + } + NoticeKind::Text(text) => text.hash(h), + } +} + fn detail_message_hash(m: &Message, part_detail: Option<&mut SessionLru>) -> u64 { let mut h = DefaultHasher::new(); match m { Message::User { id, text } => (0u8, id, text).hash(&mut h), - Message::Notice(n) => (1u8, &n.id, format!("{:?}", n.kind)).hash(&mut h), + Message::Notice(n) => { + (1u8, &n.id).hash(&mut h); + hash_notice_kind(&n.kind, &mut h); + } Message::Compaction(c) => (2u8, &c.id, std::mem::discriminant(&c.status), c.manual, &c.summary, c.native, &c.error, c.created).hash(&mut h), Message::Note { id, text, failed, step } => { (3u8, id, text, *failed).hash(&mut h); @@ -326,7 +430,8 @@ fn has_trailing_text(m: &Message, trailing_from: Option) -> bool { fn message_hash(m: &Message, edits: bool, trailing_from: Option) -> u64 { let mut h = DefaultHasher::new(); if let Message::Notice(n) = m { - (3u8, &n.id, format!("{:?}", n.kind)).hash(&mut h); + (3u8, &n.id).hash(&mut h); + hash_notice_kind(&n.kind, &mut h); } let step = match m { Message::Assistant(a) => Some(a), @@ -479,7 +584,7 @@ pub(super) type LookStamp = (usize, u64, bool, bool, bool, u8, &'static str, boo pub(super) type BaseStamp<'a> = (&'a str, LookStamp, u64, [u32; 3], bool); pub(super) type TurnStamp<'a> = (BaseStamp<'a>, [u32; 3], crate::detail::Detail, [bool; 5]); pub(super) type GroupInnerStamp = (u64, u64, u64); -pub(super) type ToolsAuxStamp<'a> = (Option<&'a str>, u64, u64, Option, Vec, u64); +pub(super) type ToolsAuxStamp<'a> = (Option<&'a str>, u64, u64, Option, u64, u64); /// Shared memo-key context computed once per [`super::RowSpec::build`] so `TurnText`, `Group`, /// `Events`, `Subagent`, `Question`, `Thought`, `Calls`, `User`, `TurnFooter`, and `TurnTail` @@ -539,19 +644,20 @@ impl<'a> RowMemoContext<'a> { group_key: Option<&str>, steps: &[Step<'_>], ) -> ToolsAuxStamp<'s> { + let expanded = s.expanded(); let group_inner = group_key.map(|gk| { ( - s.expanded().stamp("r-"), - s.expanded().stamp(&format!("{gk}:events:")), + expanded.stamp("r-"), + expanded.stamp_parts(gk, ":events:", ""), s.shell_output_version(), ) }); ( s.session_directory(self.base.0), - s.expanded().stamp("tool:"), - s.expanded().stamp("execute-details:"), + expanded.stamp("tool:"), + expanded.stamp("execute-details:"), group_inner, - crate::copied::current(s), + crate::copied::stamp(s), calls_aux_stamp(s, steps), ) } diff --git a/crates/session-view/src/timeline/mod.rs b/crates/session-view/src/timeline/mod.rs index 694a3ff6c..10774abbe 100644 --- a/crates/session-view/src/timeline/mod.rs +++ b/crates/session-view/src/timeline/mod.rs @@ -161,7 +161,8 @@ pub fn turn_of(t: &Transcript, message: usize) -> (usize, usize) { let mut c = c.borrow_mut(); let same = c.0.as_ref().is_some_and(|(s, n, l)| *s == t.session && *n == t.messages.len() && l.as_deref() == last); if !same { - c.1 = t.messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::User { .. })).map(|(i, _)| i).collect(); + c.1.clear(); + c.1.extend(t.messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::User { .. })).map(|(i, _)| i)); c.0 = Some((t.session.clone(), t.messages.len(), last.map(str::to_owned))); } (c.1.partition_point(|&i| i < message) + 1, c.1.len()) diff --git a/crates/session-view/src/timeline/parts.rs b/crates/session-view/src/timeline/parts.rs index 98a38c0c7..ad12d645a 100644 --- a/crates/session-view/src/timeline/parts.rs +++ b/crates/session-view/src/timeline/parts.rs @@ -296,9 +296,11 @@ pub(super) const META: TextStyle = TextStyle::new(12.0, 440.0).lh(18.0).tracking /// last text of the last reply with any (`copyContentID`). pub fn footer_text(t: &Transcript, message: usize, part: usize) -> bool { let text = |p: &Part| matches!(p, Part::Text { text } if !text.trim().is_empty()); - let last = t.messages.iter().rposition(|m| matches!(m, Message::Assistant(a) if a.parts.iter().any(text))); - last == Some(message) - && matches!(&t.messages[message], Message::Assistant(a) if a.parts.iter().rposition(text) == Some(part)) + let Some(Message::Assistant(a)) = t.messages.get(message) else { return false }; + if a.parts.iter().rposition(text) != Some(part) { + return false; + } + !t.messages[message + 1..].iter().any(|m| matches!(m, Message::Assistant(a) if a.parts.iter().any(text))) } /// Whether part `part` of message `message` ends a turn a later prompt follows: the last text of @@ -317,11 +319,13 @@ pub fn turn_footer_text(t: &Transcript, message: usize, part: usize) -> bool { /// The hover group part `part` of message `mi` shares with its turn's tail, a row of its own, /// as Desktop shows a footer while its text part is hovered: a finished turn's own /// ([`settled_hover`]), or the running turn's ([`REPLY_HOVER`], `footer`: [`footer_text`]). +/// Allocation-free predicate matching [`reply_hover`] for `RowContent::TurnText` memo keys. +pub(super) fn has_reply_hover(t: &Transcript, mi: usize, part: usize, live: bool, footer: bool) -> bool { + footer || (!live && turn_footer_text(t, mi, part)) +} + pub fn reply_hover(t: &Transcript, mi: usize, part: usize, live: bool, footer: bool) -> Option { - if (!live && turn_footer_text(t, mi, part)) || footer { - return Some(settled_hover(t.messages[mi].id())); - } - None + has_reply_hover(t, mi, part, live, footer).then(|| settled_hover(t.messages[mi].id())) } /// The hover group of a finished turn whose reply is message `id`. @@ -409,15 +413,60 @@ fn sent_time_tooltip(at_ms: i64, now_ms: i64) -> String { }) } +/// Lightweight memo stamp for [`reply_meta`]: avoids formatting duration, tokens/sec, and +/// sent-time tooltip strings into a temporary `Vec` on every settled footer's memo hit. +pub(super) fn reply_meta_stamp(s: &S, t: &Transcript, message: usize) -> u64 { + use std::hash::{DefaultHasher, Hash, Hasher}; + let mut h = DefaultHasher::new(); + let narrow = crate::style::narrow(); + narrow.hash(&mut h); + let model = (!narrow).then(|| { + t.messages[..=message].iter().rev().find_map(|m| match m { + Message::Assistant(a) => a.model.as_ref(), + _ => None, + }) + }).flatten(); + if let Some(m) = model.filter(|m| !m.id.is_empty() || !m.provider.is_empty()) { + (true, s.model_name(m), &m.variant).hash(&mut h); + } else { + false.hash(&mut h); + } + let prompt = t.messages[..message].iter().rposition(|m| matches!(m, Message::User { .. } | Message::Note { .. })); + let started = prompt.and_then(|i| match &t.messages[i] { + Message::User { id, .. } => model::user_created(id), + _ => None, + }); + let from = prompt.map_or(0, |i| i + 1); + let first_step = t.messages[from..=message].iter().find_map(|m| match m { + Message::Assistant(a) if a.created > 0 => Some(a.created), + _ => None, + }); + let end = t.messages[message..].iter().position(|m| matches!(m, Message::User { .. } | Message::Note { .. })).map_or(t.messages.len(), |n| message + n); + let done = t.messages[from..end].iter().rev().find_map(|m| match m { + Message::Assistant(a) => a.completed, + _ => None, + }); + if let (Some(done), Some(since)) = (done, started.or(first_step)) { + let total = ((done - since).max(0) as f64 / 1000.0).round() as i64; + let tip_key = (done > 0).then(|| (done, s.now_minute_ms())); + (true, total, tip_key).hash(&mut h); + } else { + false.hash(&mut h); + } + let last = t.messages[message..end].iter().rposition(|m| matches!(m, Message::Assistant(_))).map_or(message, |n| message + n); + model::turn::tokens_per_second(&t.messages, last).map(f64::to_bits).hash(&mut h); + h.finish() +} + pub(super) fn reply_meta(s: &S, t: &Transcript, message: usize) -> Vec<(String, bool, Option)> { let mut items = Vec::new(); let model = t.messages[..=message].iter().rev().find_map(|m| match m { - Message::Assistant(a) => a.model.clone(), + Message::Assistant(a) => a.model.as_ref(), _ => None, }); // A narrow window leaves out the model (`message-content.tsx:1172`). if let Some(m) = model.filter(|m| (!m.id.is_empty() || !m.provider.is_empty()) && !crate::style::narrow()) { - items.push((s.model_name(&m), false, None)); + items.push((s.model_name(m), false, None)); if !m.variant.is_empty() && m.variant != "default" { let mut v = m.variant.chars(); items.push((v.next().map(|c| c.to_uppercase().chain(v).collect()).unwrap_or_default(), true, None)); diff --git a/crates/session-view/src/timeline/row_build.rs b/crates/session-view/src/timeline/row_build.rs index 3c1492cd5..6f02e3c78 100644 --- a/crates/session-view/src/timeline/row_build.rs +++ b/crates/session-view/src/timeline/row_build.rs @@ -21,7 +21,7 @@ use super::row_height::{ }; use super::{ EAGER_ROWS, Place, Projection, ROW_BUILDS, RowContent, RowSpec, TurnRowKind, attachments, - entries, footer_text, parts, prompt_dir, prompt_meta, reply_hover, rhythm, settled_tail, + entries, footer_text, parts, prompt_dir, reply_hover, rhythm, settled_tail, turn_of, turn_tail, user_bubble, }; use crate::TimelineHost; @@ -59,7 +59,7 @@ impl RowSpec { /// Rune's `same_root_el` flattened-node reuse while preserving exact `{row_key}/{child}` paths. fn memo_row(&self, p: &Pal, shell: Option>, ver: impl Hash, build: impl FnOnce() -> El) -> El { let sv = shell.map(|sh| (sh.highlighted, sh.shaped, sh.mark_id, sh.focus_key)); - rune::memo(self.key.clone(), (ver, sv), || { + rune::memo(self.key.as_str(), (ver, sv), || { ROW_BUILDS.set(ROW_BUILDS.get() + 1); self.apply_shell(p, shell, build()) }) @@ -111,28 +111,8 @@ impl RowSpec { s.line_hold().paced(&t.session, &a.id, *part), ); let has_fence = scan.has(FLAG_FENCE); - let copied = has_fence.then(|| crate::copied::current(s)); - let wrap = has_fence.then(|| { - let default = s.wrap_code_blocks(); - let overrides = s - .code_wrap_overrides() - .filter(|m| !m.is_empty()) - .map(|m| { - let mut v: Vec<(String, bool)> = m - .iter() - .filter(|(k, _)| { - k.strip_prefix(self.key.as_str()).is_some_and(|rest| { - rest.starts_with(':') || rest.starts_with("-md-") || rest.starts_with("-v-") - }) - }) - .map(|(k, &on)| (k.clone(), on)) - .collect(); - v.sort(); - v - }) - .unwrap_or_default(); - (default, overrides) - }); + let copied = has_fence.then(|| crate::copied::stamp(s)); + let wrap = has_fence.then(|| (s.wrap_code_blocks(), group_hash::code_wrap_stamp(s.code_wrap_overrides(), &self.key))); let has_math = scan.has(FLAG_MATH); if has_math && let Some(m) = s.math_client() { m.hold(); @@ -145,9 +125,9 @@ impl RowSpec { let pictures = (scan.has(FLAG_IMG) || scan.has(FLAG_LINK) || favicons).then(|| { let m = s.media_store(); let directory = s.active_session_id().and_then(|id| s.session_directory(id)); - (m.markdown.version(), m.viewing.as_ref().map(|v| v.id.clone()), directory, favicons) + (m.markdown.version(), m.viewing.as_ref().map(|v| v.id.as_str()), directory, favicons) }); - let own = reply_hover(t, *message, *part, *live, footer); + let own = parts::has_reply_hover(t, *message, *part, *live, footer).then(|| t.messages[*message].id()); let chips = scan.has(FLAG_SES).then(|| crate::session_chips::version(s, body)); let code = (!*live && scan.has(FLAG_TICK)).then(|| s.code_links_version()); let videos = (!*live && scan.has(FLAG_VIDEO)).then(|| { @@ -196,6 +176,7 @@ impl RowSpec { *start + first.entry as usize..*start + last.entry as usize + 1 }); let mut can_memo = true; + let mut cached_steps = None; let open_aux = if open || shutting { match group.as_ref().and_then(|at| steps_from_locs(at, &t.messages[*start..range.end], script_diffs)) { Some(steps) => { @@ -208,7 +189,9 @@ impl RowSpec { can_memo = false; None } else { - Some(cx.tools_aux(s, Some(&self.key), &steps)) + let aux = cx.tools_aux(s, Some(&self.key), &steps); + cached_steps = Some(steps); + Some(aux) } } None => { @@ -232,12 +215,11 @@ impl RowSpec { (group.is_none().then_some(*block), group), [live, open, shutting, after], [pt.to_bits(), fade.to_bits()], - s.expanded().stamp("r-"), open_aux, ); return self.memo_row(p, shell, ver, || { if let Some(at) = group - && let Some(steps) = steps_from_locs(at, &t.messages[*start..range.end], script_diffs) + && let Some(steps) = cached_steps.or_else(|| steps_from_locs(at, &t.messages[*start..range.end], script_diffs)) { let extra_after = extra_after_for(&steps, after); return self.wrap(s, turns::group(s, p, &t.session, &self.key, &steps, at, *start..range.end, live, fade, &extra_after).pt(*pt)); @@ -271,22 +253,20 @@ impl RowSpec { if let Some(at) = loc { let mi = *start + at.entry as usize; if let Some(step) = at.step(&t.messages[*start..(mi + 1).min(t.messages.len())], script_diffs) { - let resolved = step_event(&step).and_then(|e| { - let title = e.title.as_deref().unwrap_or(""); - s.resolve_subagent(&t.session, e.session.as_deref(), title) - .map(str::to_owned) - .filter(|_| s.can_open_subagent()) - }); + let can_open = s.can_open_subagent(); + let resolved = can_open + .then(|| step_event(&step)) + .flatten() + .and_then(|e| s.resolve_subagent(&t.session, e.session.as_deref(), e.title.as_deref().unwrap_or("")).map(str::to_owned)); let ver = ( turn_cx, group_hash::detail_of(s, t, mi..mi + 1, &detail, script_diffs, flatten_cm), *at, - resolved, - s.can_open_subagent(), + resolved.as_deref(), + can_open, pt.to_bits(), ); return self.memo_row(p, shell, ver, || { - let Some(step) = at.step(&t.messages[*start..(mi + 1).min(t.messages.len())], script_diffs) else { return self.wrap(s, col()) }; self.wrap(s, turns::subagent_row(s, p, &t.session, &step).pt(*pt)) }); } @@ -295,23 +275,21 @@ impl RowSpec { TurnRowKind::Question => { if let Some(at) = loc { let mi = *start + at.entry as usize; - if let Some(Step::Tool { id, .. }) = at.step(&t.messages[*start..(mi + 1).min(t.messages.len())], script_diffs) { - let qkey = format!("question-{id}"); - let open = crate::disclosure::is_open(s, &qkey, true); - let shutting = crate::disclosure::is_shutting(s, &qkey); - let err_stamp = s.expanded().stamp(&crate::tools::key(id)); + if let Some(Step::Tool { id, status, input, metadata, .. }) = at.step(&t.messages[*start..(mi + 1).min(t.messages.len())], script_diffs) { + let expanded = s.expanded(); + let qstate = expanded.get_prefixed("question-", id); + let open = qstate.is_none_or(|d| d == crate::disclosure::Disclosure::Open); + let shutting = matches!(qstate, Some(crate::disclosure::Disclosure::Shutting { .. })); + let err_stamp = expanded.stamp_parts("tool:", id, ""); let ver = ( turn_cx, group_hash::detail_of(s, t, mi..mi + 1, &detail, script_diffs, flatten_cm), *at, ([open, shutting], err_stamp), pt.to_bits(), - (s.tool_row_action_version(id), s.session_directory(&t.session), crate::copied::current(s)), + (s.tool_row_action_version(id), s.session_directory(&t.session), crate::copied::stamp(s)), ); return self.memo_row(p, shell, ver, || { - let Some(Step::Tool { id, status, input, metadata, .. }) = - at.step(&t.messages[*start..(mi + 1).min(t.messages.len())], script_diffs) - else { return self.wrap(s, col()) }; self.wrap(s, crate::question_row::view(s, p, &t.session, id, status, input, metadata).pt(*pt)) }); } @@ -322,35 +300,53 @@ impl RowSpec { && let Some((first, last)) = at.first().zip(at.last()) { let range = *start + first.entry as usize..*start + last.entry as usize + 1; - if let Some(steps) = steps_from_locs(at, &t.messages[*start..range.end], script_diffs) { - let rkey = match steps.first() { - Some(Step::Thought { msg, index, .. }) => format!("r-{msg}-{index}"), - _ => String::new(), - }; - let open = !rkey.is_empty() - && crate::disclosure::is_open(s, &rkey, detail.expanded(Category::Thinking)); - let shutting = !rkey.is_empty() && crate::disclosure::is_shutting(s, &rkey); - if (open || shutting) && steps_may_have_math(&steps) - && let Some(m) = s.math_client() - { - m.hold(); + let slice = &t.messages[*start..range.end]; + let default_open = detail.expanded(Category::Thinking); + let first_step = first.step(slice, script_diffs); + let (open, shutting) = match first_step { + Some(Step::Thought { msg, index, .. }) => { + if s.expanded().none_touched() { + (default_open, false) + } else { + let rkey = format!("r-{msg}-{index}"); + let o = crate::disclosure::is_open(s, &rkey, default_open); + (o, !o && crate::disclosure::is_shutting(s, &rkey)) + } } - if !(open || shutting) || !steps_have_async_markdown(&steps) { - let copied = (open || shutting).then(|| crate::copied::current(s)); - let ver = ( - turn_cx, - group_hash::of(s, t, range.clone(), true, &detail, script_diffs, flatten_cm), - group, - [live, *thinking, open, shutting], - [pt.to_bits(), fade.to_bits()], - copied, - ); - return self.memo_row(p, shell, ver, || { - let Some(steps) = steps_from_locs(at, &t.messages[*start..range.end], script_diffs) else { return self.wrap(s, col()) }; - self.wrap(s, turns::thought_row(s, p, &steps, live, *thinking, fade, *pt)) - }); + _ => (false, false), + }; + let mut cached_steps = None; + let mut can_memo = first_step.is_some(); + if can_memo && (open || shutting) { + match steps_from_locs(at, slice, script_diffs) { + Some(steps) => { + if steps_may_have_math(&steps) && let Some(m) = s.math_client() { + m.hold(); + } + if steps_have_async_markdown(&steps) { + can_memo = false; + } else { + cached_steps = Some(steps); + } + } + None => can_memo = false, } } + if can_memo { + let copied = (open || shutting).then(|| crate::copied::stamp(s)); + let ver = ( + turn_cx, + group_hash::of(s, t, range.clone(), true, &detail, script_diffs, flatten_cm), + group, + [live, *thinking, open, shutting], + [pt.to_bits(), fade.to_bits()], + copied, + ); + return self.memo_row(p, shell, ver, || { + let Some(steps) = cached_steps.or_else(|| steps_from_locs(at, slice, script_diffs)) else { return self.wrap(s, col()) }; + self.wrap(s, turns::thought_row(s, p, &steps, live, *thinking, fade, *pt)) + }); + } } } TurnRowKind::Calls { kind: ckind, after_changes, script_loc } => { @@ -360,12 +356,13 @@ impl RowSpec { let lo_entry = script_loc.map_or(first.entry, |sl| sl.entry.min(first.entry)); let hi_entry = script_loc.map_or(last.entry, |sl| sl.entry.max(last.entry)); let range = *start + lo_entry as usize..*start + hi_entry as usize + 1; - if let Some(steps) = steps_from_locs(at, &t.messages[*start..range.end], script_diffs) + let slice = &t.messages[*start..range.end]; + if let Some(steps) = steps_from_locs(at, slice, script_diffs) && !calls_busy(&steps, live) { let after = flat_exec && *after_changes; let eff_script = script_loc.filter(|_| flat_exec); - let aux = cx.tools_aux(s, Some(&self.key), &steps); + let aux = cx.tools_aux(s, None, &steps); let ver = ( turn_cx, group_hash::detail_of(s, t, range.clone(), &detail, script_diffs, flatten_cm), @@ -375,8 +372,6 @@ impl RowSpec { aux, ); return self.memo_row(p, shell, ver, || { - let slice = &t.messages[*start..range.end]; - let Some(steps) = steps_from_locs(at, slice, script_diffs) else { return self.wrap(s, col()) }; let script_step = eff_script.and_then(|sl| sl.step(slice, script_diffs)); let out_after = match &script_step { Some(st) => turns::output_after_from_script(st, &steps), @@ -398,8 +393,9 @@ impl RowSpec { && opencode_kit::mention::user_mentions(id).is_empty() && !text.contains("ses_") { - let prompt = crate::fold::key(id); - let open = s.expanded().contains(&prompt); + let expanded = s.expanded(); + let prompt_state = expanded.get_prefixed(crate::fold::KEY_PREFIX, id); + 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); let viewport = if fold_user && crate::fold::needs_viewport(text) { @@ -408,9 +404,8 @@ impl RowSpec { crate::fold::default_viewport() }; let resolved_fold = crate::fold::Fold { viewport, past }; - let shutting = crate::disclosure::is_shutting(s, &prompt); - let quotes = s.expanded().stamp(&format!("quote-open:{id}:")); - let meta = prompt_meta(s, t, Some(*message)); + let shutting = matches!(prompt_state, Some(crate::disclosure::Disclosure::Shutting { .. })); + let quotes = expanded.stamp_parts("quote-open:", id, ":"); let (turn, more) = if s.assistive() { (turn_of(t, *message), s.more_above(&t.session)) } else { @@ -424,18 +419,17 @@ impl RowSpec { quotes, [viewport.to_bits(), top.to_bits()], s.user_status_version(id), - &meta, (turn, more), ); return self.memo_row(p, shell, ver, || { let run = Place { above: *above, below: *below, top: *top, fold: resolved_fold }; - self.wrap_turn(s, turn, more, text, user_bubble(s, p, &t.session, id, text, run, 0.0, None, None, &meta)) + self.wrap_turn(s, turn, more, text, user_bubble(s, p, &t.session, id, text, run, 0.0, None, None, &[])) }); } } RowContent::TurnFooter { reply, anchor, interrupted, sources } => { let keep_copy = reply.is_some() && latest_copy == *reply; - let meta = reply.map(|i| parts::reply_meta(s, t, i)); + let meta = reply.map(|i| parts::reply_meta_stamp(s, t, i)); let chip = reply.filter(|_| *sources && !*interrupted).and_then(|i| parts::sources_of(s, t, i)); let favicons = (chip.is_some() && k.get(&crate::knobs::SOURCES_ICONS) > 0.5) .then(|| s.media_store().markdown.version()); @@ -448,7 +442,7 @@ impl RowSpec { cx.base, ids, [*interrupted, *sources, keep_copy], - crate::copied::current(s), + crate::copied::stamp(s), (meta, chip), (favicons, footer_ver, footer_info), ); @@ -528,8 +522,8 @@ impl RowSpec { let last_text = reply.and_then(|i| parts::last_reply_text(&t.messages[i])); let copy_y = parts::footer_top(last_text, sources.is_some()); let footer = super::tail::lane_footer(last_text, has_text, interrupted, sources.is_some()); - let meta = reply.filter(|_| shown || interrupted || footer_vis).map(|i| parts::reply_meta(s, t, i)); - let copied = crate::copied::is_copied(s, &format!("copy-{copy_id}")); + let meta = reply.filter(|_| shown || interrupted || footer_vis).map(|i| parts::reply_meta_stamp(s, t, i)); + let copied = crate::copied::is_copied_prefixed(s, "copy-", copy_id); let footer_ver = s.message_footer_version(); let footer_info = (footer_ver != 0) .then(|| super::tail::turn_footer_info(t, reply.unwrap_or(*anchor), !*busy)) @@ -564,6 +558,38 @@ impl RowSpec { }); } } + RowContent::TurnDiff { idle, from, files, pt } => { + let id = t.messages[*idle].id(); + let state = s.turn_diff(&t.session, from); + let expanded = s.expanded(); + let show_state = expanded.get_prefixed("turn-diff:", id); + let open = show_state == Some(crate::disclosure::Disclosure::Open); + let shutting = matches!(show_state, Some(crate::disclosure::Disclosure::Shutting { .. })); + let fold = [crate::style::sticky_top().to_bits(), crate::disclosure::fold(k).duration.to_bits(), k.get(&crate::disclosure::FOLD_FEATHER).to_bits()]; + let ver = ( + cx.base, + (id, from.as_str(), files.as_slice(), pt.to_bits()), + (fold, [open, shutting], expanded.stamp_parts("tool:turn-diff-", id, ""), s.session_directory(&t.session), crate::copied::stamp(s)), + crate::turn_diff::state_stamp(&state, open || shutting), + ); + return self.memo_row(p, shell, ver, || { + self.wrap(s, crate::turn_diff::view_state(s, p, &t.session, id, from, files, *pt, state)) + }); + } + RowContent::TurnDivider(run) => { + let ver = (cx.base, *run, k.get(&crate::compaction::DIVIDER_GAP).to_bits()); + return self.memo_row(p, shell, ver, || { + self.wrap(s, crate::compaction::divider_of(s, p, text(opencode_i18n::t!("ui.message.interrupted")).key("label").font(UI).color(p.faint), *run)) + }); + } + RowContent::Compaction { message, piece, run } => { + if let Message::Compaction(c) = &t.messages[*message] + && c.status != model::CompactionStatus::Running + { + let ver = (cx.base, crate::compaction::memo_stamp(s, c, *piece, *run)); + return self.memo_row(p, shell, ver, || self.wrap(s, crate::compaction::view(s, p, c, *piece, *run))); + } + } _ => {} } } @@ -597,7 +623,7 @@ impl RowSpec { glow, None, crate::user_parts::quotes_on_message(s, p, id, text, false), - &prompt_meta(s, t, Some(*message)), + &[], ); if !s.assistive() { return self.wrap(s, bubble); @@ -623,7 +649,7 @@ impl RowSpec { if needs_vp { crate::fold::viewport(s, &t.session) } else { crate::fold::default_viewport() } }); let run = Place { above: *above, below: *below, top: *top, fold: crate::fold::Fold { viewport, past } }; - user_bubble(s, p, &t.session, id, &label, run, 0.0, Some(pending_key), cards, &prompt_meta(s, t, None)) + user_bubble(s, p, &t.session, id, &label, run, 0.0, Some(pending_key), cards, &[]) } None => col(), } diff --git a/crates/session-view/src/timeline/row_height.rs b/crates/session-view/src/timeline/row_height.rs index 41717826e..e4d591237 100644 --- a/crates/session-view/src/timeline/row_height.rs +++ b/crates/session-view/src/timeline/row_height.rs @@ -128,9 +128,10 @@ 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 = expanded.get_prefixed(crate::fold::KEY_PREFIX, id); + 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); let viewport = if fold_user && crate::fold::needs_viewport(text) { @@ -138,18 +139,16 @@ pub(super) fn shape(s: &S, t: &Transcript, r: &RowSpec, layout: } 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)) { + let quotes = expanded.stamp_parts("quote-open:", id, ":"); + if expanded.any_shutting_parts("quote-open:", id, ":") { return None; } - let meta = super::prompt_meta(s, t, Some(*message)); let mut h = DefaultHasher::new(); ( layout, &t.session, &r.key, id.as_str(), text.as_str(), [*above, *below, fold_user, open, past, 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); return Some(h.finish()); @@ -168,16 +167,7 @@ pub(super) fn shape(s: &S, t: &Transcript, r: &RowSpec, layout: (layout, &t.session, &r.key, &a.id, part, scan.hash, body.len(), pt.to_bits(), r.room_under(s).to_bits(), s.diagrams().hidden_in(body), s.expanded().stamp(&r.key)).hash(&mut h); // Same row-local keys as the Markdown element memo, without sorting/copying strings. - let overrides = s.code_wrap_overrides().map_or(0u64, |overrides| { - overrides.iter().filter(|(key, _)| key.strip_prefix(r.key.as_str()).is_some_and(|rest| - rest.starts_with(':') || rest.starts_with("-md-") || rest.starts_with("-v-"))) - .fold(0u64, |sum, pair| { - let mut one = DefaultHasher::new(); - pair.hash(&mut one); - sum.wrapping_add(one.finish()) - }) - }); - overrides.hash(&mut h); + super::group_hash::code_wrap_stamp(s.code_wrap_overrides(), &r.key).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); diff --git a/crates/session-view/src/timeline/turn_cache.rs b/crates/session-view/src/timeline/turn_cache.rs index 2ef086176..afd793658 100644 --- a/crates/session-view/src/timeline/turn_cache.rs +++ b/crates/session-view/src/timeline/turn_cache.rs @@ -47,8 +47,47 @@ pub(super) struct PrefixHit { pub aborted: bool, } +#[derive(Clone)] +struct OwnedTurnKey(u64, String, String); + +trait TurnKey { + fn parts(&self) -> (u64, &str, &str); +} + +impl TurnKey for OwnedTurnKey { + fn parts(&self) -> (u64, &str, &str) { (self.0, &self.1, &self.2) } +} + +impl TurnKey for (u64, &str, &str) { + fn parts(&self) -> (u64, &str, &str) { *self } +} + +impl PartialEq for OwnedTurnKey { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for OwnedTurnKey {} + +impl std::hash::Hash for OwnedTurnKey { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + +impl<'a> std::borrow::Borrow for OwnedTurnKey { + fn borrow(&self) -> &(dyn TurnKey + 'a) { self } +} + +impl PartialEq for dyn TurnKey + '_ { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for dyn TurnKey + '_ {} + +impl std::hash::Hash for dyn TurnKey + '_ { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + thread_local! { - static TURNS: RefCell> = RefCell::new(SessionLru::new()); + static TURNS: RefCell> = RefCell::new(SessionLru::new()); } fn flags_of(detail: &Detail, script_diffs: bool, flatten: bool, turn_diffs: bool) -> Flags { @@ -75,9 +114,9 @@ pub(super) fn prefix( return None; } let flags = flags_of(detail, script_diffs, flatten, turn_diffs); - let key = (s.transcript_source_id(), t.session.clone(), t.messages.get(start)?.id().to_owned()); + let lookup = (s.transcript_source_id(), t.session.as_str(), t.messages.get(start)?.id()); TURNS.with_borrow(|cache| { - let turn = cache.get(&key).filter(|k| k.start == start && k.flags == flags)?; + let turn = cache.get(&lookup as &dyn TurnKey).filter(|k| k.start == start && k.flags == flags)?; let from = if turn.version == version { usize::MAX } else { @@ -143,10 +182,12 @@ pub(super) fn rows( }; return super::turn_rows(&mut out.pending, all, start, end, live, detail, script_diffs, flatten); } - let key = (s.transcript_source_id(), t.session.clone(), t.messages[start].id().to_owned()); + let source_id = s.transcript_source_id(); + let msg_id = t.messages[start].id(); + let lookup = (source_id, t.session.as_str(), msg_id); let flags = flags_of(detail, script_diffs, flatten, turn_diffs); let mut turn = TURNS - .with_borrow_mut(|cache| cache.remove(&key)) + .with_borrow_mut(|cache| cache.remove(&lookup as &dyn TurnKey)) .filter(|k| k.start == start && k.flags == flags) .unwrap_or(Turn { version, start, flags, chunks: Vec::new() }); let from = if turn.version == version { @@ -215,6 +256,7 @@ pub(super) fn rows( flatten, ); turn.version = version; + let key = OwnedTurnKey(source_id, t.session.clone(), msg_id.to_owned()); TURNS.with_borrow_mut(|cache| { cache.insert_or_evict(key, turn); }); diff --git a/crates/session-view/src/timeline/wrap.rs b/crates/session-view/src/timeline/wrap.rs index 6e872ba18..9897becc7 100644 --- a/crates/session-view/src/timeline/wrap.rs +++ b/crates/session-view/src/timeline/wrap.rs @@ -33,19 +33,20 @@ impl RowSpec { /// changed-files row (`td-`) opens its `turn-diff:{id}`, and a turn's group keeps what its /// block was built with (`RowContent::Turn`'s `fold`: a group of thoughts alone opens by /// its first thought's row, work alone by its events row). - pub(super) fn disclosure(&self) -> String { + pub(super) fn disclosure(&self) -> std::borrow::Cow<'_, str> { + use std::borrow::Cow; if let RowContent::Turn { fold, .. } = &self.content && !fold.is_empty() { - return fold.clone(); + return Cow::Borrowed(fold.as_str()); } - let fit = |head: &str, next: &str| self.key.strip_prefix(head).map(|rest| format!("{next}{rest}")); + let fit = |head: &str, next: &str| self.key.strip_prefix(head).map(|rest| Cow::Owned(format!("{next}{rest}"))); fit("th-", "r-") .or_else(|| fit("q-", "question-")) .or_else(|| fit("p-", "tool:")) .or_else(|| fit("n-", "ev-")) .or_else(|| fit("td-", "turn-diff:")) - .unwrap_or_else(|| self.key.clone()) + .unwrap_or(Cow::Borrowed(self.key.as_str())) } /// Whether the fold this row holds is springing shut, so the row clips what it shows while @@ -71,12 +72,15 @@ impl RowSpec { if !matches!(self.content, RowContent::User { .. } | RowContent::Pending { .. }) { return None; } - let prompt = crate::fold::key(id); - let prompt_present = s.expanded().get(&prompt).is_some(); - let prompt_shutting = prompt_present && crate::disclosure::is_shutting(s, &prompt); - let prefix = format!("quote-open:{id}:"); - let quote_open = s.expanded().iter().any(|k| k.starts_with(&prefix)); - let quote_shutting = s.expanded().touched().any(|(k, _)| k.starts_with(&prefix) && crate::disclosure::is_shutting(s, k)); + let expanded = s.expanded(); + if expanded.none_touched() { + return None; + } + let prompt_state = expanded.get_prefixed(crate::fold::KEY_PREFIX, id); + let prompt_present = prompt_state.is_some(); + let prompt_shutting = matches!(prompt_state, Some(crate::disclosure::Disclosure::Shutting { .. })); + let quote_open = expanded.iter().any(|k| k.strip_prefix("quote-open:").and_then(|r| r.strip_prefix(id)).is_some_and(|r| r.starts_with(':'))); + let quote_shutting = expanded.any_shutting_parts("quote-open:", id, ":"); (prompt_present || quote_open || quote_shutting).then_some(prompt_shutting || quote_shutting) } diff --git a/crates/session-view/src/tools/files.rs b/crates/session-view/src/tools/files.rs index ec3b568c1..ce1e2fe68 100644 --- a/crates/session-view/src/tools/files.rs +++ b/crates/session-view/src/tools/files.rs @@ -184,10 +184,38 @@ pub fn shut_group(s: &S, p: &Pal, cx: Ctx, calls: &[Call], show group_with(s, p, cx, calls, false, (shown, closing)) } +/// Like [`shut_group`] directly over a borrowed slice of `FileDiff.Info` JSON objects (for +/// `turn_diff`), avoiding cloning the slice into a synthetic `serde_json::Value` each frame. +pub fn shut_files(s: &S, p: &Pal, cx: Ctx, call_id: &str, files: &[Value], shown: usize, closing: bool) -> El { + let call = Call { + id: call_id, + name: "patch", + status: &opencode_kit::model::ToolStatus::Completed, + input: &Value::Null, + metadata: &Value::Null, + }; + let single = [call]; + group_entries(s, p, cx, &call, &single, files.iter().filter_map(|f| changed(&call, f)), false, (shown, closing)) +} + fn group_with(s: &S, p: &Pal, cx: Ctx, calls: &[Call], open: bool, split: (usize, bool)) -> El { let Some(first) = calls.first() else { return col() }; - let mut items: Vec = Vec::new(); - for e in calls.iter().flat_map(entries) { + group_entries(s, p, cx, first, calls, calls.iter().flat_map(entries), open, split) +} + +#[allow(clippy::too_many_arguments)] +fn group_entries<'a, S: TimelineHost>( + s: &S, + p: &Pal, + cx: Ctx, + first: &Call<'a>, + calls: &[Call<'a>], + entries: impl Iterator>, + open: bool, + split: (usize, bool), +) -> El { + let mut items: Vec> = Vec::new(); + for e in entries { match items.iter_mut().find(|i| i.path == e.path) { Some(i) => i.entries.push(e), None => items.push(Item { path: e.path, entries: vec![e] }), diff --git a/crates/session-view/src/tools/mod.rs b/crates/session-view/src/tools/mod.rs index 66db6ccd6..53a073fdc 100644 --- a/crates/session-view/src/tools/mod.rs +++ b/crates/session-view/src/tools/mod.rs @@ -40,7 +40,7 @@ use crate::style::{HOVER_FADE, TOOL_CODE, UI, arrow, readable}; pub use console::{console_open, follow as shell_follow}; pub use details::overlay as details_overlay; -pub use files::{draws_card as file_draws_card, group as file_group, is_file_tool, shut_group}; +pub use files::{draws_card as file_draws_card, group as file_group, is_file_tool, shut_files, shut_group}; pub use execute::script_output_text; pub use lists::{read_group, skill_group, skill_name}; pub use plain::strip_ansi; @@ -310,7 +310,6 @@ fn cached_with(s: &S, p: &Pal, cx: Ctx, calls: &[Call], after_c let flatten = s.flatten_code_mode(); let flat = s.full_codemode(cx.session) && !flatten; (s.full_codemode(cx.session), flatten, after_changes).hash(&mut h); - let copied = crate::copied::current(s); for c in calls { (c.id, c.name, std::mem::discriminant(c.status), s.tool_row_action_version(c.id)).hash(&mut h); fingerprint(c.input, &mut h); @@ -325,8 +324,8 @@ fn cached_with(s: &S, p: &Pal, cx: Ctx, calls: &[Call], after_c // Each part of it the reader touched, and how it stands: open, shut or folding shut // read apart from one another, and from one never touched (a shut that opens by default // must rebuild as shut the moment its fold lands, or its console never unmounts). - s.expanded().stamp(&key(c.id)).hash(&mut h); - copied.iter().filter(|k| k.contains(c.id)).for_each(|k| k.hash(&mut h)); + s.expanded().stamp_parts("tool:", c.id, "").hash(&mut h); + crate::copied::stamp_containing(s, c.id).hash(&mut h); } // The memo keys its root with its own id, so the row keeps its keys one level down. rune::memo(format!("tm-{}", first.id), h.finish(), || col().w_full().child(build())) diff --git a/crates/session-view/src/turn_diff.rs b/crates/session-view/src/turn_diff.rs index 0e4af32ed..5d69c6c8e 100644 --- a/crates/session-view/src/turn_diff.rs +++ b/crates/session-view/src/turn_diff.rs @@ -30,10 +30,47 @@ const COUNT: TextStyle = TextStyle::new(11.0, 440.0).lh(11.0).tracking(0.05); /// Diff unavailable: 13 at 440 on the compact line. const NOTE: TextStyle = TextStyle::new(13.0, 440.0).lh(16.0); +/// Allocation-free content stamp of a [`State`] for `RowContent::TurnDiff` memoization. +pub(crate) fn state_stamp(state: &State<'_>, all_or_shutting: bool) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = rustc_hash::FxHasher::default(); + match state { + State::Loading => 0u8.hash(&mut h), + State::Failed => 1u8.hash(&mut h), + State::Ready(d) => { + (2u8, d.len()).hash(&mut h); + // The header totals additions and deletions across all files even when collapsed. + let (adds, dels) = d.iter().fold((0u64, 0u64), |(a, r), f| { + (a + f["additions"].as_u64().unwrap_or(0), r + f["deletions"].as_u64().unwrap_or(0)) + }); + (adds, dels).hash(&mut h); + let shown = if all_or_shutting { *d } else { &d[..d.len().min(LIMIT)] }; + shown.len().hash(&mut h); + for f in shown { + ( + f["file"].as_str(), + f["status"].as_str(), + f["additions"].as_u64(), + f["deletions"].as_u64(), + f["patch"].as_str(), + ) + .hash(&mut h); + } + } + } + h.finish() +} + /// The run that ended at message `id`, from prompt `from`, which changed `files`, `pt` under /// the row above. pub fn view(s: &S, p: &Pal, session: &str, id: &str, from: &str, files: &[String], pt: f32) -> El { let state = s.turn_diff(session, from); + view_state(s, p, session, id, from, files, pt, state) +} + +/// Like [`view`], reusing an already-fetched [`State`] so a memo miss avoids a second lookup. +#[allow(clippy::too_many_arguments)] +pub(crate) fn view_state(s: &S, p: &Pal, session: &str, id: &str, from: &str, files: &[String], pt: f32, state: State<'_>) -> El { let diffs = match state { State::Ready(d) => Some(d), _ => None, @@ -79,13 +116,12 @@ pub fn view(s: &S, p: &Pal, session: &str, id: &str, from: &str if let Some(d) = diffs { // The first five files always stand. Shutting, only the ones past them fold away, in a // wrapper of no height under the row's clip: the row springs from N files to five rather - // than collapsing to none and springing back. - let files: Vec = if all || shutting { d.to_vec() } else { d.iter().take(LIMIT).cloned().collect() }; - let metadata = serde_json::json!({ "files": files }); + // than collapsing to none and springing back. Borrow `d` directly instead of cloning + // every `FileDiff.Info` JSON entry into a temporary `Vec`. + let slice = if all || shutting { d } else { &d[..d.len().min(LIMIT)] }; let call_id = format!("turn-diff-{id}"); - let call = crate::tools::Call { id: &call_id, name: "patch", status: &opencode_kit::model::ToolStatus::Completed, input: &Value::Null, metadata: &metadata }; let cx = crate::tools::Ctx { session, live: false, sticky: crate::style::sticky_top() }; - c = c.child(crate::tools::shut_group(s, p, cx, &[call], LIMIT, shutting && !all)); + c = c.child(crate::tools::shut_files(s, p, cx, &call_id, slice, LIMIT, shutting && !all)); } c } diff --git a/crates/session-view/src/turns/codemode/cache.rs b/crates/session-view/src/turns/codemode/cache.rs index 38f1da48e..0160ed907 100644 --- a/crates/session-view/src/turns/codemode/cache.rs +++ b/crates/session-view/src/turns/codemode/cache.rs @@ -13,7 +13,45 @@ use serde_json::Value; use super::SyntheticTool; -type Key = (String, bool, bool); +#[derive(Clone)] +struct OwnedKey(String, bool, bool); + +trait KeyRef { + fn parts(&self) -> (&str, bool, bool); +} + +impl KeyRef for OwnedKey { + fn parts(&self) -> (&str, bool, bool) { (&self.0, self.1, self.2) } +} + +impl KeyRef for (&str, bool, bool) { + fn parts(&self) -> (&str, bool, bool) { *self } +} + +impl PartialEq for OwnedKey { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for OwnedKey {} + +impl Hash for OwnedKey { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + +impl<'a> std::borrow::Borrow for OwnedKey { + fn borrow(&self) -> &(dyn KeyRef + 'a) { self } +} + +impl PartialEq for dyn KeyRef + '_ { + fn eq(&self, other: &Self) -> bool { self.parts() == other.parts() } +} + +impl Eq for dyn KeyRef + '_ {} + +impl Hash for dyn KeyRef + '_ { + fn hash(&self, state: &mut H) { self.parts().hash(state); } +} + type Parts = Option]>>; struct Part { @@ -23,8 +61,8 @@ struct Part { #[derive(Default)] struct Cache { - parts: HashMap, - order: VecDeque, + parts: HashMap, + order: VecDeque, } thread_local! { @@ -43,27 +81,32 @@ pub(in crate::turns) fn flatten( std::mem::discriminant(status).hash(&mut h); hash_json(metadata, &mut h); for file in files { - (&file.mime, &file.name, &file.media, &file.bytes).hash(&mut h); + let b: &[u8] = &file.bytes; + (&file.mime, &file.name, &file.media, b.len(), &b[..b.len().min(32)], &b[b.len().saturating_sub(32)..]).hash(&mut h); } let version = h.finish(); - let key = (id.to_owned(), script_diffs, execute_block); + let lookup = (id, script_diffs, execute_block); CACHE.with_borrow_mut(|cache| { - if let Some(part) = cache.parts.get(&key) + if let Some(part) = cache.parts.get(&lookup as &dyn KeyRef) && part.version == version { return part.parts.clone(); } let parts = super::flatten_execute_parts(id, status, metadata, files, script_diffs, execute_block) .map(|parts| parts.into_iter().map(Rc::new).collect::>()); - if !cache.parts.contains_key(&key) { + if let Some(part) = cache.parts.get_mut(&lookup as &dyn KeyRef) { + part.version = version; + part.parts = parts.clone(); + } else { if cache.parts.len() >= KEPT && let Some(old) = cache.order.pop_front() { cache.parts.remove(&old); } + let key = OwnedKey(id.to_owned(), script_diffs, execute_block); cache.order.push_back(key.clone()); + cache.parts.insert(key, Part { version, parts: parts.clone() }); } - cache.parts.insert(key, Part { version, parts: parts.clone() }); parts }) } diff --git a/crates/session-view/src/turns/labels.rs b/crates/session-view/src/turns/labels.rs index c22b011ce..9a9906bf9 100644 --- a/crates/session-view/src/turns/labels.rs +++ b/crates/session-view/src/turns/labels.rs @@ -146,10 +146,14 @@ fn render_car(s: &S, p: &Pal, group_key: &str, car: &Car, trail pub(super) fn activity_words(s: &S, p: &Pal, key: &str, a: &activity::Activity) -> El { let seen_before = SEEN_GROUPS.with(|g| { let mut set = g.borrow_mut(); + if set.contains(key) { + return true; + } if set.len() > 1024 { set.clear(); } - !set.insert(key.to_owned()) + set.insert(key.to_owned()); + false }); let mut track = row() diff --git a/features/timeline-extras/src/agent_rows/mod.rs b/features/timeline-extras/src/agent_rows/mod.rs index 3c53cbedf..7bb87500a 100644 --- a/features/timeline-extras/src/agent_rows/mod.rs +++ b/features/timeline-extras/src/agent_rows/mod.rs @@ -352,13 +352,24 @@ pub fn poll(host: &mut dyn AgentRowsHost, tx: &mut Tx) -> bool { /// came before them; None when we saw none. pub(crate) fn steps_in(host: &dyn AgentRowsHost, child: &str, from: Option, to: Option) -> Option<(Vec, usize)> { let log = host.agent_rows().steps.get(child)?; - let mine: Vec<&String> = log.list.iter().filter(|s| from.is_none_or(|f| s.0 >= f) && to.is_none_or(|t| s.0 < t)).map(|s| &s.1).collect(); + let mut ring: [&str; KEEP] = [""; KEEP]; + let mut matched = 0usize; + for (at, step) in &log.list { + if from.is_none_or(|f| *at >= f) && to.is_none_or(|t| *at < t) { + ring[matched % KEEP] = step.as_str(); + matched += 1; + } + } // Steps the log let go of came before every step it kept: count them when the window // reaches back past the newest of them. let dropped = if log.dropped > 0 && from.is_none_or(|f| f <= log.dropped_at) { log.dropped } else { 0 }; - let count = mine.len() + if mine.is_empty() { 0 } else { dropped }; - let shown: Vec = mine[mine.len().saturating_sub(KEEP)..].iter().map(|s| (*s).clone()).collect(); - let n = shown.len(); + let count = matched + if matched == 0 { 0 } else { dropped }; + let n = matched.min(KEEP); + let start = matched - n; + let mut shown = Vec::with_capacity(n); + for i in start..matched { + shown.push(ring[i % KEEP].to_owned()); + } Some((shown, count - n)) } diff --git a/features/timeline-extras/src/todos.rs b/features/timeline-extras/src/todos.rs index ee448b68d..bf768b8eb 100644 --- a/features/timeline-extras/src/todos.rs +++ b/features/timeline-extras/src/todos.rs @@ -5,6 +5,7 @@ use std::cell::RefCell; use std::collections::HashMap; +use std::rc::Rc; use std::time::Duration; use opencode_kit::model::{Message, Part, ToolStatus, Transcript}; @@ -64,8 +65,8 @@ pub trait TodosHost: opencode_kernel::AppEnv { } } -/// The session, transcripts version and revert a plan was read at; the plan; the message it is in. -type PlanCache = Option<((String, u64, Option), Vec, Option)>; +/// The session, transcripts version and revert a plan was read at; the shared plan; the message it is in. +type PlanCache = Option<((String, u64, Option), Rc<[Todo]>, Option)>; thread_local! { /// The open session's plan, and the session, transcripts version and revert it was read at. @@ -124,41 +125,65 @@ pub fn current(todos: &[Todo]) -> Option<&Todo> { .or(todos.first()) } -/// The plan the pill shows: only while the session runs and work is left, so a finished or -/// abandoned plan never lingers. -pub fn shown_todos(host: &dyn TodosHost, id: &str) -> Vec { +fn empty_todos() -> Rc<[Todo]> { + thread_local! { + static EMPTY: Rc<[Todo]> = Rc::from([]); + } + EMPTY.with(Rc::clone) +} + +/// Shared-slice fast path for [`shown_todos`], avoiding per-poll and per-frame `Vec` clones. +fn shown_todos_rc(host: &dyn TodosHost, id: &str) -> Rc<[Todo]> { if !host.is_session_running(id) { - return Vec::new(); + return empty_todos(); } - let Some(t) = host.transcript(id) else { return Vec::new() }; + let Some(t) = host.transcript(id) else { return empty_todos() }; let revert = host.session_revert(id); // Every poll asks: the plan is read once per version of the transcripts, not by walking // a long session back to its last plan each frame. let t_ver = host.transcript_version(id); let todos = PLAN.with_borrow_mut(|kept| { - if let Some((_, todos, _)) = - kept.as_ref().filter(|((sid, ver, rev), ..)| sid == id && *ver == t_ver && rev.as_deref() == revert) + if let Some(((sid, ver, rev), todos, at)) = kept.as_mut() + && sid == id + && rev.as_deref() == revert { - return todos.clone(); + if *ver == t_ver { + return Rc::clone(todos); + } + // A streamed reply's writes change only the messages from the one they name on + // (`transcript_changed_from`): a plan found above them stands unless a newer one follows. + let from = host + .transcript_changed_from(id, *ver) + .filter(|&low| at.is_none_or(|pos| pos < low)) + .unwrap_or(0); + *ver = t_ver; + match latest_plan(&t.messages[..t.visible_len(revert)], from) { + Some((pos, input)) => { + *todos = Rc::from(parse(input)); + *at = Some(pos); + } + None if from > 0 => {} + None => { + *todos = empty_todos(); + *at = None; + } + } + return Rc::clone(todos); } - // A streamed reply's writes change only the messages from the one they name on - // (`transcript_changed_from`): a plan found above them stands unless a newer one follows. - let from = kept - .as_ref() - .filter(|((sid, _, rev), ..)| sid == id && rev.as_deref() == revert) - .and_then(|((_, since, _), _, at)| host.transcript_changed_from(id, *since).filter(|&low| at.is_none_or(|at| at < low))) - .unwrap_or(0); - let (todos, at) = match latest_plan(&t.messages[..t.visible_len(revert)], from) { - Some((at, input)) => (parse(input), Some(at)), - None => match kept.take().filter(|_| from > 0) { - Some((_, todos, at)) => (todos, at), - None => (Vec::new(), None), - }, + let (todos, at): (Rc<[Todo]>, Option) = match latest_plan(&t.messages[..t.visible_len(revert)], 0) { + Some((at, input)) => (Rc::from(parse(input)), Some(at)), + None => (empty_todos(), None), }; - *kept = Some(((id.to_owned(), t_ver, revert.map(str::to_owned)), todos.clone(), at)); + *kept = Some(((id.to_owned(), t_ver, revert.map(str::to_owned)), Rc::clone(&todos), at)); todos }); - if todos.iter().all(Todo::finished) { Vec::new() } else { todos } + if todos.iter().all(Todo::finished) { empty_todos() } else { todos } +} + +/// The plan the pill shows: only while the session runs and work is left, so a finished or +/// abandoned plan never lingers. +pub fn shown_todos(host: &dyn TodosHost, id: &str) -> Vec { + shown_todos_rc(host, id).to_vec() } pub const CLOSE: Knob = Knob::new("Todo ring", 0.0, 0.8, 0.4).step(0.01).label("Ring closes in").about("Seconds a finished todo's fill takes to close"); @@ -255,25 +280,34 @@ pub fn sync(host: &mut dyn TodosHost, now: f64, tx: &mut Tx) -> bool { return true; } } - let id = id_ref.to_owned(); - let revert_owned = revert_ref.map(str::to_owned); - let todos = shown_todos(host, &id); + let todos = shown_todos_rc(host, id_ref); let (secs, bounce) = (host.knobs().get(&CLOSE), host.knobs().get(&BOUNCE)); // Every poll comes here: with no fill growing and the list as last seen, nothing below // changes, so the ticks aren't written. let seen = host.todo_ticks(); - let quiet = seen.session == id + let quiet = seen.session == id_ref && seen.growing.is_empty() && seen.seen.len() == todos.len() - && seen.seen.iter().zip(&todos).all(|((c, st), t)| *c == t.content && *st == t.status); + && seen.seen.iter().zip(todos.iter()).all(|((c, st), t)| *c == t.content && *st == t.status); if quiet { - *seen.seen_ver.borrow_mut() = Some((running, has_t, t_ver, revert_owned)); + let mut sv = seen.seen_ver.borrow_mut(); + match &mut *sv { + Some((r, ht, v, rev)) if rev.as_deref() == revert_ref => { + *r = running; + *ht = has_t; + *v = t_ver; + } + slot => *slot = Some((running, has_t, t_ver, revert_ref.map(str::to_owned))), + } + drop(sv); if !host.todo_open() || current(&todos).is_some() { return false; } host.set_todo_open(false); return true; } + let id = id_ref.to_owned(); + let revert_owned = revert_ref.map(str::to_owned); let reduced = host.reduced_motion(); let ticks = host.todo_ticks_mut(); let was_filling = ticks.growing.values().any(|f| f.at(ticks.now).is_some()); @@ -337,12 +371,13 @@ pub fn toggle_pill(host: &mut dyn TodosHost, id: &str, tx: &mut Tx) { /// The pill: the current todo's glyph and words, cut with a fade past 260, and "+2" when more /// than one is in progress. pub fn pill(host: &H, p: &Pal, id: &str) -> Option { + let chip = pill_shell(host, p, id)?; let sid = id.to_owned(); - pill_shell(host, p, id).map(|chip| chip.on_press_tx(move |s: &mut H, tx: &mut Tx| toggle_pill(s, &sid, tx))) + Some(chip.on_press_tx(move |s: &mut H, tx: &mut Tx| toggle_pill(s, &sid, tx))) } fn pill_shell(host: &dyn TodosHost, p: &Pal, id: &str) -> Option { - let todos = shown_todos(host, id); + let todos = shown_todos_rc(host, id); let now = current(&todos)?; let more = todos.iter().filter(|t| t.status == Status::InProgress).count().saturating_sub(1); let mut chip = host.todo_chip(p, "todo-pill", label(&todos), host.todo_open()) @@ -383,12 +418,13 @@ fn build_panel_content(host: &dyn TodosHost, p: &Pal, id: &str) -> Option Option El { @@ -415,7 +451,7 @@ fn build_panel_frame(knobs: &Knobs, p: &Pal, width: f32, label: String, rows: El /// Keeps the todo in progress in view when the list opens or the plan moves on. pub fn reveal_current(host: &dyn TodosHost, id: &str, tx: &mut Tx) { - if let Some(k) = shown_todos(host, id).iter().position(|t| t.status == Status::InProgress) { + if let Some(k) = shown_todos_rc(host, id).iter().position(|t| t.status == Status::InProgress) { tx.scroll_into_view_in("todo-scroll", format!("todo-{k}")); } } From 7f3b45a14312dd71d28b803e10df261f15918c9a Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:01:49 +1000 Subject: [PATCH 2/2] fix(session-view): address 4-model review findings on cache identity, compaction memo, and shell tail --- crates/session-view/src/compaction.rs | 22 +++++++++++-- crates/session-view/src/copied.rs | 6 ---- crates/session-view/src/line_reveal.rs | 2 +- crates/session-view/src/sources_chip.rs | 18 ++++++----- .../session-view/src/timeline/group_hash.rs | 31 +++++++++++-------- crates/session-view/src/timeline/mod.rs | 2 +- crates/session-view/src/timeline/parts.rs | 6 ++-- crates/session-view/src/timeline/row_build.rs | 6 ++-- crates/session-view/src/tools/mod.rs | 9 ++++-- crates/session-view/src/turn_diff.rs | 5 +-- .../session-view/src/turns/codemode/cache.rs | 7 +++-- 11 files changed, 70 insertions(+), 44 deletions(-) diff --git a/crates/session-view/src/compaction.rs b/crates/session-view/src/compaction.rs index 6264fb31c..7fd979af6 100644 --- a/crates/session-view/src/compaction.rs +++ b/crates/session-view/src/compaction.rs @@ -83,7 +83,9 @@ pub fn view(s: &S, p: &Pal, c: &Compaction, piece: Piece, run: } /// Allocation-free memo stamp for a settled (`status != Running`) compaction row. -pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, run: Run) -> u64 { +/// Returns `None` when an expanded/shutting summary contains async Markdown (math or Mermaid) +/// so pending rasterization and lightbox transitions rebuild cleanly, matching `Group`/`Thought`. +pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, run: Run) -> Option { use std::hash::{DefaultHasher, Hash, Hasher}; let k = s.knobs(); let state = (piece == Piece::Quiet) @@ -91,6 +93,20 @@ pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, r .flatten(); let open = state == Some(crate::disclosure::Disclosure::Open); let shutting = matches!(state, Some(crate::disclosure::Disclosure::Shutting { .. })); + let hidden_diagrams = if open || shutting { + let body = summary(c); + if rune_kit::math::may_have_math(body) + && let Some(m) = s.math_client() + { + m.hold(); + } + if crate::timeline::group_hash::has_async_markdown(body) { + return None; + } + Some(s.diagrams().hidden_in(body)) + } else { + None + }; let tokens = c.tokens.as_ref().map(|t| (t.input, t.output, t.reasoning, t.cache_read, t.cache_write)); let mut h = DefaultHasher::new(); ( @@ -104,7 +120,7 @@ pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, r tokens, piece, run, - [open, shutting, s.reduced_motion()], + ([open, shutting, s.reduced_motion()], hidden_diagrams), [ crate::style::sticky_top().to_bits(), crate::disclosure::fold(k).duration.to_bits(), @@ -114,7 +130,7 @@ pub(crate) fn memo_stamp(s: &S, c: &Compaction, piece: Piece, r ], ) .hash(&mut h); - h.finish() + Some(h.finish()) } /// A compaction the server admitted but hasn't started. diff --git a/crates/session-view/src/copied.rs b/crates/session-view/src/copied.rs index dbf721efd..ff543c002 100644 --- a/crates/session-view/src/copied.rs +++ b/crates/session-view/src/copied.rs @@ -176,12 +176,6 @@ pub fn mark_copied(s: &mut S, key: impl Into, tx: &mut } } -/// Whether any copy button currently shows a tick. -#[inline] -pub fn is_empty(s: &S) -> bool { - s.copied_state().ticks.is_empty() -} - /// Whether copy button `key` shows its tick (`poll` evicts expired entries before view, so view /// memos never read the 60 Hz frame clock). pub fn is_copied(s: &S, key: &str) -> bool { diff --git a/crates/session-view/src/line_reveal.rs b/crates/session-view/src/line_reveal.rs index 8394a556b..b311cb3c5 100644 --- a/crates/session-view/src/line_reveal.rs +++ b/crates/session-view/src/line_reveal.rs @@ -311,7 +311,7 @@ pub fn poll(s: &mut S, now: f64, tx: &mut Tx) -> bool { messages.retain(|_, parts| { let before = parts.len(); parts.retain(|&part, d| { - session == sid && (d.message < from || live_keys.contains(&(d.message, part))) + session == sid && (d.message < from || live_keys.binary_search(&(d.message, part)).is_ok()) && !matches!(d.phase, DripPhase::Done) }); let removed = parts.len() != before; diff --git a/crates/session-view/src/sources_chip.rs b/crates/session-view/src/sources_chip.rs index 53f151bca..c5e5988cd 100644 --- a/crates/session-view/src/sources_chip.rs +++ b/crates/session-view/src/sources_chip.rs @@ -93,15 +93,21 @@ pub(crate) fn hash_assistant_sources(a: &opencode_kit::model::Assistant, h: &mut std::mem::discriminant(status).hash(h); if matches!(status, ToolStatus::Completed) { for url in results(tool_output(status, metadata).unwrap_or_default()) { - hash_page(url, h).hash(h); + match page_parts(url) { + Some(parts) => { + true.hash(h); + hash_page_parts(parts, h); + } + None => false.hash(h), + } } } } "webfetch" => { - if let Some(url) = input["url"].as_str() && page_parts(url).is_some() { + if let Some(parts) = input["url"].as_str().and_then(page_parts) { 2u8.hash(h); matches!(status, ToolStatus::Error).hash(h); - hash_page(url, h); + hash_page_parts(parts, h); } } _ => {} @@ -121,11 +127,8 @@ fn page_parts(url: &str) -> Option<(&str, &str, Option<&str>)> { Some((host, path.trim_end_matches('/'), query)) } -fn hash_page(url: &str, h: &mut impl std::hash::Hasher) -> bool { +fn hash_page_parts((host, path, query): (&str, &str, Option<&str>), h: &mut impl std::hash::Hasher) { use std::hash::Hash as _; - let Some((host, path, query)) = page_parts(url) else { - return false; - }; host.len().hash(h); for c in host.chars() { for lc in c.to_lowercase() { @@ -133,7 +136,6 @@ fn hash_page(url: &str, h: &mut impl std::hash::Hasher) -> bool { } } (path, query).hash(h); - true } /// The URLs of a search's `## [title](url)` result headings. diff --git a/crates/session-view/src/timeline/group_hash.rs b/crates/session-view/src/timeline/group_hash.rs index 79b4ef9d9..11190e67d 100644 --- a/crates/session-view/src/timeline/group_hash.rs +++ b/crates/session-view/src/timeline/group_hash.rs @@ -299,7 +299,8 @@ fn detail_part_hash(p: &Part) -> u64 { Part::Tool { id, name, title, status, input, files, metadata } => { (0u8, id, name, title, std::mem::discriminant(status), files.len()).hash(&mut h); for f in files { - (&f.mime, &f.name, &f.media, f.bytes.len()).hash(&mut h); + let inline = f.media.is_none().then(|| f.bytes.as_ptr() as usize); + (&f.mime, &f.name, &f.media, f.bytes.len(), inline).hash(&mut h); } hash_json(input, &mut h); hash_json(metadata, &mut h); @@ -311,23 +312,26 @@ fn detail_part_hash(p: &Part) -> u64 { } pub(super) fn hash_notice_kind(kind: &opencode_kit::model::NoticeKind, h: &mut impl Hasher) { - use opencode_kit::model::NoticeKind; + use opencode_kit::model::{Finished, ModelRef, NoticeKind}; + let hash_model = |m: &ModelRef, h: &mut _| { + let ModelRef { id, provider, variant } = m; + (id, provider, variant).hash(h); + }; std::mem::discriminant(kind).hash(h); match kind { NoticeKind::Agent { agent, previous } => (agent, previous).hash(h), NoticeKind::Model { model, previous } => { - (&model.provider, &model.id, &model.variant).hash(h); + hash_model(model, h); + previous.is_some().hash(h); if let Some(prev) = previous { - (true, &prev.provider, &prev.id, &prev.variant).hash(h); - } else { - false.hash(h); + hash_model(prev, h); } } NoticeKind::Moved { directory, previous } => (directory, previous).hash(h), NoticeKind::Instructions { sources } => sources.hash(h), NoticeKind::Restart | NoticeKind::Idle => {} - NoticeKind::Finished(f) => { - (&f.agent, f.subagent, std::mem::discriminant(&f.outcome), &f.data, f.required, &f.shell, &f.child).hash(h); + NoticeKind::Finished(Finished { agent, subagent, outcome, data, required, shell, child }) => { + (agent, subagent, std::mem::discriminant(outcome), data, required, shell, child).hash(h); } NoticeKind::Job { id, description, script, required } => { (id, description, script.map(|o| std::mem::discriminant(&o)), required).hash(h); @@ -524,7 +528,7 @@ pub(super) fn steps_from_locs<'a>( locs.iter().map(|loc| loc.step(messages, script_diffs)).collect() } -pub(super) fn has_async_markdown(body: &str) -> bool { +pub(crate) fn has_async_markdown(body: &str) -> bool { body.contains("mermaid") || rune_kit::math::may_have_math(body) } @@ -564,10 +568,11 @@ pub(super) fn calls_aux_stamp(s: &S, steps: &[Step<'_>]) -> u64 input: t.input, metadata: t.metadata, }; - crate::tools::shell_follow(&call, |_| false) - .and_then(|(id, _)| s.shell_output(id)) - .map(str::len) - .hash(&mut h); + if let Some((id, _)) = crate::tools::shell_follow(&call, |_| false) { + (true, s.shell_output_version(), s.shell_output(id).map(str::len)).hash(&mut h); + } else { + false.hash(&mut h); + } } } else if let Step::Change { msg, script, index, .. } = st { s.tool_row_action_version(&crate::tools::script::change_id(msg, script, *index)).hash(&mut h); diff --git a/crates/session-view/src/timeline/mod.rs b/crates/session-view/src/timeline/mod.rs index 10774abbe..75d3d6649 100644 --- a/crates/session-view/src/timeline/mod.rs +++ b/crates/session-view/src/timeline/mod.rs @@ -13,7 +13,7 @@ use crate::turns::{self, Block, Entry, Step}; pub mod attachments; mod delivery; mod dividers; -mod group_hash; +pub(crate) mod group_hash; mod lru; pub mod parts; mod projection; diff --git a/crates/session-view/src/timeline/parts.rs b/crates/session-view/src/timeline/parts.rs index ad12d645a..7995c3212 100644 --- a/crates/session-view/src/timeline/parts.rs +++ b/crates/session-view/src/timeline/parts.rs @@ -316,14 +316,14 @@ pub fn turn_footer_text(t: &Transcript, message: usize, part: usize) -> bool { !t.messages[message + 1..message + 1 + next].iter().any(|m| matches!(m, Message::Assistant(a) if a.parts.iter().any(text))) } -/// The hover group part `part` of message `mi` shares with its turn's tail, a row of its own, -/// as Desktop shows a footer while its text part is hovered: a finished turn's own -/// ([`settled_hover`]), or the running turn's ([`REPLY_HOVER`], `footer`: [`footer_text`]). /// Allocation-free predicate matching [`reply_hover`] for `RowContent::TurnText` memo keys. pub(super) fn has_reply_hover(t: &Transcript, mi: usize, part: usize, live: bool, footer: bool) -> bool { footer || (!live && turn_footer_text(t, mi, part)) } +/// The hover group part `part` of message `mi` shares with its turn's tail, a row of its own, +/// as Desktop shows a footer while its text part is hovered: a finished turn's own +/// ([`settled_hover`]), or the running turn's ([`REPLY_HOVER`], `footer`: [`footer_text`]). pub fn reply_hover(t: &Transcript, mi: usize, part: usize, live: bool, footer: bool) -> Option { has_reply_hover(t, mi, part, live, footer).then(|| settled_hover(t.messages[mi].id())) } diff --git a/crates/session-view/src/timeline/row_build.rs b/crates/session-view/src/timeline/row_build.rs index 6f02e3c78..ca02c0a5a 100644 --- a/crates/session-view/src/timeline/row_build.rs +++ b/crates/session-view/src/timeline/row_build.rs @@ -569,7 +569,7 @@ impl RowSpec { let ver = ( cx.base, (id, from.as_str(), files.as_slice(), pt.to_bits()), - (fold, [open, shutting], expanded.stamp_parts("tool:turn-diff-", id, ""), s.session_directory(&t.session), crate::copied::stamp(s)), + (fold, [open, shutting], expanded.stamp_parts("tool:turn-diff-", id, "/"), s.session_directory(&t.session)), crate::turn_diff::state_stamp(&state, open || shutting), ); return self.memo_row(p, shell, ver, || { @@ -585,9 +585,9 @@ impl RowSpec { RowContent::Compaction { message, piece, run } => { if let Message::Compaction(c) = &t.messages[*message] && c.status != model::CompactionStatus::Running + && let Some(stamp) = crate::compaction::memo_stamp(s, c, *piece, *run) { - let ver = (cx.base, crate::compaction::memo_stamp(s, c, *piece, *run)); - return self.memo_row(p, shell, ver, || self.wrap(s, crate::compaction::view(s, p, c, *piece, *run))); + return self.memo_row(p, shell, (cx.base, stamp), || self.wrap(s, crate::compaction::view(s, p, c, *piece, *run))); } } _ => {} diff --git a/crates/session-view/src/tools/mod.rs b/crates/session-view/src/tools/mod.rs index 53a073fdc..905b9788e 100644 --- a/crates/session-view/src/tools/mod.rs +++ b/crates/session-view/src/tools/mod.rs @@ -319,8 +319,13 @@ fn cached_with(s: &S, p: &Pal, cx: Ctx, calls: &[Call], after_c } else { fingerprint(c.metadata, &mut h); } - // The output the host read from the call's shell (`console::follow`). - console::follow(c, |_| false).and_then(|(id, _)| s.shell_output(id)).map(str::len).hash(&mut h); + // The output the host read from the call's shell (`console::follow`). Include + // `shell_output_version` so rolling tails capped at 64 KiB still invalidate inner memos. + if let Some((id, _)) = console::follow(c, |_| false) { + (true, s.shell_output_version(), s.shell_output(id).map(str::len)).hash(&mut h); + } else { + false.hash(&mut h); + } // Each part of it the reader touched, and how it stands: open, shut or folding shut // read apart from one another, and from one never touched (a shut that opens by default // must rebuild as shut the moment its fold lands, or its console never unmounts). diff --git a/crates/session-view/src/turn_diff.rs b/crates/session-view/src/turn_diff.rs index 5d69c6c8e..fb7855239 100644 --- a/crates/session-view/src/turn_diff.rs +++ b/crates/session-view/src/turn_diff.rs @@ -44,14 +44,15 @@ pub(crate) fn state_stamp(state: &State<'_>, all_or_shutting: bool) -> u64 { (a + f["additions"].as_u64().unwrap_or(0), r + f["deletions"].as_u64().unwrap_or(0)) }); (adds, dels).hash(&mut h); + let present = |f: &Value, k: &str| f.get(k).filter(|v| v.is_number()).map(crate::activity::rules::count); let shown = if all_or_shutting { *d } else { &d[..d.len().min(LIMIT)] }; shown.len().hash(&mut h); for f in shown { ( f["file"].as_str(), f["status"].as_str(), - f["additions"].as_u64(), - f["deletions"].as_u64(), + present(f, "additions"), + present(f, "deletions"), f["patch"].as_str(), ) .hash(&mut h); diff --git a/crates/session-view/src/turns/codemode/cache.rs b/crates/session-view/src/turns/codemode/cache.rs index 0160ed907..9fc248f18 100644 --- a/crates/session-view/src/turns/codemode/cache.rs +++ b/crates/session-view/src/turns/codemode/cache.rs @@ -81,8 +81,11 @@ pub(in crate::turns) fn flatten( std::mem::discriminant(status).hash(&mut h); hash_json(metadata, &mut h); for file in files { - let b: &[u8] = &file.bytes; - (&file.mime, &file.name, &file.media, b.len(), &b[..b.len().min(32)], &b[b.len().saturating_sub(32)..]).hash(&mut h); + // When `media` is `Some`, it is already a content hash; for inline bytes, cached + // `SyntheticTool` entries retain cloned `Arc<[u8]>` handles so allocation addresses + // cannot be reused (no ABA) while the cache entry stays alive. + let inline = file.media.is_none().then(|| (file.bytes.as_ptr() as usize, file.bytes.len())); + (&file.mime, &file.name, &file.media, inline).hash(&mut h); } let version = h.finish(); let lookup = (id, script_diffs, execute_block);