//! Sidebar context usage and cost for the session family. use std::cell::RefCell; use opencode_api::generated::{ModelInfo, SessionMessageCompaction, SessionMessageInfo}; use opencode_plugin::abi::v2::{Node, Place, Surface}; use opencode_plugin::abi::{self, Changed, Placement, Span}; use opencode_plugin::slot; use super::{hidden, kept}; pub fn plugin() -> abi::Plugin { abi::Plugin { id: "opencode.sidebar.context", setup } } const ROOT: &str = "context"; fn setup(setup: &mut abi::Setup) -> Result<(), String> { let last: RefCell> = RefCell::default(); let surface = Surface::new("context", Place::Slot(Placement::append(slot::SIDEBAR_CONTENT)), move |cx| { let Some(session) = cx.input.slot.as_ref().and_then(|slot| slot.session_id.as_deref()) else { return hidden(ROOT); }; let changed = &cx.input.changed; let mut last = last.borrow_mut(); let fresh = changed.all || last.as_ref().is_none_or(|last| last.session != session); let last = match &mut *last { Some(last) if !fresh => last, last => last.insert(Last::new(session)), }; let model = last.update(cx.read, changed, fresh); if !fresh && last.shown == Some(model) { return kept(ROOT); } last.shown = Some(model); model.map_or_else(|| hidden(ROOT), |model| view(model).with_id(ROOT)) }); setup.surface(surface); Ok(()) } pub type Model = Option<(Option, f64)>; /// What the section last read for its session. It reads the session again only when its info or status changed, /// the models when its location changed, and the messages when their list changed or a message changed in place from /// the one the last usage came from on. Its family also counts the busy subagents, the scripts, and the shells, which /// it reads again when a location changed. #[derive(Default)] pub struct Last { session: String, location: Option, boundary: Option, models: Option>, usage: Option, from: usize, after: Vec<(String, u64)>, cost: f64, /// The IDs of the session's family at the last cost read. family: Vec, /// Subagents that run or own running background jobs. pub running: usize, pub shells: usize, /// Code Mode scripts the session runs in the background. pub scripts: usize, pub shown: Option, } impl Last { pub fn new(session: &str) -> Self { Self { session: session.to_owned(), ..Self::default() } } pub fn session(&self) -> &str { &self.session } pub fn update(&mut self, read: &dyn abi::Read, changed: &Changed, fresh: bool) -> Model { let info = fresh || changed.session(&self.session); if info { let session = read.session(&self.session).map(|session| session.info); self.location = session .as_ref() .map(|info| abi::LocationRef { directory: info.location.directory.0.clone(), workspace: None }); self.boundary = session.and_then(|info| info.revert).map(|revert| revert.message_id.0); } let family = |id: &String| *id == self.session || self.family.contains(id); if fresh || !changed.locations.is_empty() || changed.sessions.iter().any(|id| { family(id) || read .session(id) .and_then(|session| session.info.parent_id) .is_some_and(|parent| family(&parent.0)) }) { let family = read.family(&self.session); // A subagent with background jobs running in its tree still has work running (TS `busyCounts`). let running = |member: &&abi::Member| { member.id != self.session && (member.status == abi::SessionStatus::Running || member.jobs > 0) }; self.running = family.members.iter().filter(running).count(); self.shells = family.shells; self.scripts = family.scripts; self.family = family.members.into_iter().map(|member| member.id).collect(); self.cost = family.cost; } let models = info || self.location.as_ref().is_some_and(|location| changed.location(location)); if models { self.models = self.location.as_ref().and_then(|location| read.models(Some(location))); } let mut stale = models || changed.list(&self.session); // Re-read only changed messages that can affect usage; streamed text alone does not invalidate the total. for (session, id) in &changed.messages { if stale { break; } let Some((_, was)) = self.after.iter().find(|(after, _)| after == id) else { continue }; if *session == self.session { read.message(&self.session, id, &mut |message| stale = message.map(mark) != Some(*was)); } } if stale { (self.usage, self.from) = match self.location { Some(_) => { let mut found = (None, 0); read.messages(&self.session, &mut |messages| { found = usage(messages, self.models.as_deref(), self.boundary.as_deref()); let after = messages.get(found.1..).unwrap_or_default(); self.after = after.iter().map(|message| (message.id().to_owned(), mark(message))).collect(); }); found } None => { self.after.clear(); (None, 0) } }; } (self.usage.is_some() || self.cost > 0.0).then_some((self.usage, self.cost)) } } fn view((usage, cost): (Option, f64)) -> Node { let muted = |text: String| Node::text([Span::new(text).fg("text.muted")]); let mut children = vec![Node::text([Span::new("Context").fg("text.base").bold()])]; if let Some(usage) = usage { children.push(muted(format!("{} tokens", grouped(usage.tokens)))); if let Some(percent) = usage.percent { children.push(muted(format!("{percent}% used"))); } } if cost > 0.0 { children.push(muted(format!("{} spent", money(cost)))); } Node::column(children) } /// The context use of the last reply with tokens (`contextUsage`). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Usage { pub tokens: f64, pub percent: Option, } /// `contextUsage`: the last assistant message with tokens after the last completed compaction and before /// `boundary`, and the index of the first message a change in place could change it from. pub fn usage( messages: &[SessionMessageInfo], models: Option<&[ModelInfo]>, boundary: Option<&str>, ) -> (Option, usize) { let end = match boundary { Some(boundary) => match messages.iter().position(|message| message.id() == boundary) { Some(end) => end, None => return (None, 0), }, None => messages.len(), }; let start = messages[..end] .iter() .rposition(|message| matches!(message, SessionMessageInfo::Compaction(SessionMessageCompaction::Completed(_)))) .map_or(0, |index| index + 1); let found = messages[start..end].iter().enumerate().rev().find_map(|(index, message)| match message { SessionMessageInfo::Assistant(message) => Some((start + index, &message.model, message.tokens.as_ref()?)), _ => None, }); let Some((index, model, tokens)) = found else { return (None, start) }; let total = tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write; if total <= 0.0 { return (None, index); } let context = models .unwrap_or_default() .iter() .find(|item| item.provider_id == model.provider_id && item.id == model.id) .map(|model| model.limit.context) .filter(|context| *context > 0); let percent = context.map(|context| (total / context as f64 * 100.0).round() as i64); (Some(Usage { tokens: total, percent }), index) } fn mark(message: &SessionMessageInfo) -> u64 { use std::hash::{Hash, Hasher}; let mut hasher = std::collections::hash_map::DefaultHasher::new(); match message { SessionMessageInfo::Compaction(SessionMessageCompaction::Completed(_)) => 1.hash(&mut hasher), SessionMessageInfo::Assistant(message) => { 2.hash(&mut hasher); (&message.model.provider_id, &message.model.id).hash(&mut hasher); if let Some(tokens) = &message.tokens { let counts = [tokens.input, tokens.output, tokens.reasoning, tokens.cache.read, tokens.cache.write]; counts.map(f64::to_bits).hash(&mut hasher); } } _ => 0.hash(&mut hasher), } hasher.finish() } pub fn money(value: f64) -> String { let cents = (value.abs() * 100.0).round() as u64; let sign = if value < 0.0 { "-" } else { "" }; format!("{sign}${}.{:02}", grouped((cents / 100) as f64), cents % 100) } pub fn grouped(value: f64) -> String { let digits = format!("{}", value.round() as i64); let (sign, digits) = digits.split_at(usize::from(digits.starts_with('-'))); let mut out = String::new(); for (index, digit) in digits.chars().enumerate() { if index > 0 && (digits.len() - index) % 3 == 0 { out.push(','); } out.push(digit); } format!("{sign}{out}") } #[cfg(test)] mod tests { use super::*; use std::cell::Cell; #[test] fn formats_like_intl() { assert_eq!(money(0.0), "$0.00"); assert_eq!(money(1234.567), "$1,234.57"); assert_eq!(money(0.005), "$0.01"); assert_eq!(grouped(999.0), "999"); assert_eq!(grouped(12345.0), "12,345"); assert_eq!(grouped(1234567.0), "1,234,567"); } struct Store { families: Cell, } impl abi::Read for Store { fn theme_mode(&self) -> abi::ThemeMode { abi::ThemeMode::Dark } fn color(&self, _token: &str) -> Option { None } fn session(&self, id: &str) -> Option { let parent = match id { "ses_a" => None, "ses_b" => Some("ses_a"), "ses_new" => Some("ses_b"), _ => None, }; let info = serde_json::from_value(serde_json::json!({ "id": id, "parentID": parent, "title": id, "projectID": "project", "cost": 0, "tokens": { "input": 0, "output": 0, "reasoning": 0, "cache": { "read": 0, "write": 0 } }, "time": { "created": 1, "updated": 1 }, "location": { "directory": "/project" }, })) .unwrap(); Some(abi::Session { info, status: abi::SessionStatus::Idle }) } fn family(&self, _id: &str) -> abi::Family { self.families.set(self.families.get() + 1); let member = |id: &str| abi::Member { id: id.to_owned(), parent: None, status: abi::SessionStatus::Idle, updated: 1.0, jobs: 0, }; abi::Family { members: vec![member("ses_a"), member("ses_b")], cost: 1.0, shells: 0, scripts: 0 } } } #[test] fn the_cost_skips_sessions_outside_the_family() { let store = Store { families: Cell::new(0) }; let mut last = Last::new("ses_a"); last.update(&store, &Changed::everything(), true); assert_eq!(store.families.get(), 1); let changed = |id: &str| Changed { sessions: vec![id.to_owned()], ..Changed::default() }; last.update(&store, &changed("ses_other"), false); assert_eq!(store.families.get(), 1); last.update(&store, &changed("ses_b"), false); assert_eq!(store.families.get(), 2); last.update(&store, &changed("ses_new"), false); assert_eq!(store.families.get(), 3); } }