Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feed the tray context usage off the attach snapshot (#3334)

kt2ed835646120
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index 6865a43fe5..59ae5cfb8b 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -96,7 +96,18 @@ impl Worker {
goal: self.engine.goal_state_value(),
scoped_models: core.scoped_models.clone(),
active_tool_names: Vec::new(),
- context_usage: None,
+ // TS `createAgentConnectionState` carries `contextUsage:
+ // session.getContextUsage()` in every attach snapshot, so
+ // the client's first frame reads the tray's context usage
+ // off the snapshot instead of blocking on a
+ // `get_session_stats` round-trip (TS fetches stats only
+ // after a turn or compaction settles). The same store walk
+ // `get_session_stats` serves, under the same core lock the
+ // attach already holds: `None` without a model context
+ // window, exactly like the stats response.
+ context_usage: store.and_then(|store| {
+ crate::session_stats::store_context_usage(store, self.engine.model_context_window())
+ }),
}
}
diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rs
index a8d5e7d09a..f7fe594c46 100644
--- a/crates/pa-daemon/src/worker/tests.rs
+++ b/crates/pa-daemon/src/worker/tests.rs
@@ -44,6 +44,7 @@ fn session_events_since(
}
mod abort_boundary_tests;
+mod connection_state_tests;
mod goal_tests;
mod kill_broadcast_tests;
mod queue_tests;
diff --git a/crates/pa-daemon/src/worker/tests/connection_state_tests.rs b/crates/pa-daemon/src/worker/tests/connection_state_tests.rs
new file mode 100644
index 0000000000..b9ea1fac2b
--- /dev/null
+++ b/crates/pa-daemon/src/worker/tests/connection_state_tests.rs
@@ -0,0 +1,140 @@
+//! The attach snapshot's context-usage fill (TS `createAgentConnectionState`
+//! parity): the state block carries `contextUsage` off the same store walk
+//! `get_session_stats` serves, so the client's first frame reads the tray's
+//! usage off the snapshot instead of blocking on a stats round-trip.
+use super::*;
+use crate::engine::{PromptRequest, SessionEngine};
+use crate::worker::WorkerConfig;
+
+/// The scripted harness engine with a resolved model context window: the
+/// tray-usage fill's one input beyond the store.
+struct WindowedEngine;
+impl SessionEngine for WindowedEngine {
+ fn run_prompt(
+ &self,
+ _: usize,
+ _: PromptRequest,
+ _: &dyn Fn() -> bool,
+ _: &mut dyn FnMut(crate::engine::EngineEvent) -> bool,
+ ) {
+ }
+ fn run_side_question(
+ &self,
+ request: crate::engine::SideQuestionRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ sink: &pa_core::session_engine::side_question::SideQuestionSink,
+ ) -> crate::engine::SideQuestionOutcome {
+ crate::engine::ScriptedEngine::default().run_side_question(request, signal, sink)
+ }
+ fn run_compaction(
+ &self,
+ request: crate::engine::CompactionRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ ) -> crate::engine::CompactionOutcome {
+ crate::engine::ScriptedEngine::default().run_compaction(request, signal)
+ }
+ fn run_branch_summary(
+ &self,
+ request: crate::engine::BranchSummaryRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ ) -> crate::engine::BranchSummaryOutcome {
+ crate::engine::ScriptedEngine::default().run_branch_summary(request, signal)
+ }
+ fn rebuild_session_context(
+ &self,
+ _: Vec<pa_types::session::FileEntry>,
+ _: pa_core::session_engine::goal_driver::GoalBranchReload,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+ fn model_context_window(&self) -> Option<u64> {
+ Some(128_000)
+ }
+}
+
+/// The attach snapshot's state carries the tray's context usage exactly as
+/// `get_session_stats` serves it (TS `createAgentConnectionState`'s
+/// `contextUsage: session.getContextUsage()`): the same walk, the same
+/// store, so the snapshot-fed tray row is byte-identical to the row a
+/// blocking stats fetch would have painted.
+#[tokio::test]
+async fn the_attach_state_carries_the_stats_context_usage() {
+ let dir = tempfile::tempdir().unwrap();
+ let session_dir = dir.path().join("sessions");
+ std::fs::create_dir_all(&session_dir).unwrap();
+ let mut worker = Worker::new(
+ WorkerConfig {
+ socket_path: dir.path().join("worker.sock"),
+ supervisor_socket_path: PathBuf::new(),
+ token: "context-usage-test".into(),
+ worker_instance_id: String::new(),
+ active_session_id: "ctx-usage".into(),
+ agent_dir: dir.path().join("agent"),
+ recovery_journal_path: dir.path().join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({"responses":[]})),
+ },
+ None,
+ );
+ worker.engine = std::sync::Arc::new(WindowedEngine);
+ let created = worker
+ .dispatch(
+ "create",
+ &json!({"cwd": "/tmp", "sessionDir": session_dir, "name": "usage"}),
+ )
+ .await;
+ assert!(created.success, "create failed: {created:?}");
+
+ let snapshot_state = {
+ let core = worker.core.lock().unwrap();
+ let sealed = worker.connection_state_locked(&core);
+ serde_json::to_value(&sealed).unwrap()
+ };
+ assert_eq!(
+ snapshot_state.get("contextUsage"),
+ Some(&json!({"tokens": 0, "contextWindow": 128_000, "percent": 0.0})),
+ "the attach state carries the tray usage: {snapshot_state}"
+ );
+
+ // The equivalence the byte-identity oracle rests on: the stats
+ // response serves the very same usage object.
+ let stats = worker.dispatch("get_session_stats", &json!({})).await;
+ assert!(stats.success, "{stats:?}");
+ assert_eq!(
+ stats.data.as_ref().unwrap().get("contextUsage"),
+ snapshot_state.get("contextUsage"),
+ "the snapshot fill equals the stats response"
+ );
+
+ // A model-less engine keeps the field off the wire exactly like a TS
+ // session without a model (the scripted default).
+ let worker = Worker::new(
+ WorkerConfig {
+ socket_path: dir.path().join("worker2.sock"),
+ supervisor_socket_path: PathBuf::new(),
+ token: "context-usage-test-2".into(),
+ worker_instance_id: String::new(),
+ active_session_id: "ctx-usage-2".into(),
+ agent_dir: dir.path().join("agent"),
+ recovery_journal_path: dir.path().join("recovery2.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({"responses":[]})),
+ },
+ None,
+ );
+ worker
+ .dispatch(
+ "create",
+ &json!({"cwd": "/tmp", "sessionDir": session_dir, "name": "usage-2"}),
+ )
+ .await;
+ let modelless = {
+ let core = worker.core.lock().unwrap();
+ let sealed = worker.connection_state_locked(&core);
+ serde_json::to_value(&sealed).unwrap()
+ };
+ assert!(
+ modelless.get("contextUsage").is_none(),
+ "a model-less session omits the field: {modelless}"
+ );
+}
diff --git a/crates/pa-tui/src/chrome.rs b/crates/pa-tui/src/chrome.rs
index c1268fe416..bfeb0232c1 100644
--- a/crates/pa-tui/src/chrome.rs
+++ b/crates/pa-tui/src/chrome.rs
@@ -199,13 +199,28 @@ impl ActivityDock {
}
/// Context usage for the tray label (`N (P%)`).
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextUsage {
pub tokens: u64,
pub context_window: u64,
}
impl ContextUsage {
+ /// The wire shape (TS `SessionStats["contextUsage"]`, served by
+ /// `get_session_stats` and carried by the attach snapshot's state):
+ /// unknown tokens — a session right after a compaction — yield
+ /// `None`, which clears the tray display instead of keeping the
+ /// stale one (TS `patchConnectionState` replaces the snapshot).
+ #[must_use]
+ pub fn from_wire(usage: &Value) -> Option<Self> {
+ let tokens = usage.get("tokens").and_then(Value::as_u64)?;
+ let context_window = usage.get("contextWindow").and_then(Value::as_u64)?;
+ Some(Self {
+ tokens,
+ context_window,
+ })
+ }
+
#[must_use]
pub fn percent(&self) -> f64 {
if self.context_window == 0 {
diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rs
index 6bfc76b099..62dcbda7a3 100644
--- a/crates/pa-tui/src/interactive/run.rs
+++ b/crates/pa-tui/src/interactive/run.rs
@@ -654,8 +654,8 @@ async fn run_interactive_surface(
if headless {
session.osc_sink = crate::clipboard::OscSink::Buffer(Vec::new());
}
- session.refresh_stats().await;
- // The startup catalog fetch: failures stay silent and the snapshot keeps serving the picker.
+ // The tray's context usage came in with the attach snapshot, so the
+ // open path does not block on a stats fetch.
session.spawn_model_catalog_refresh();
session.rebuild_view(&mut view, &crate::session_ui::RebuildKind::Rebind);
// The cross-view layout handoff's adopt (view::handoff): a re-entry whose attach cursor exactly
diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rs
index 919c7d5d69..7551bce61e 100644
--- a/crates/pa-tui/src/session_ui/commands.rs
+++ b/crates/pa-tui/src/session_ui/commands.rs
@@ -102,9 +102,8 @@ impl SessionUi {
pub(super) async fn start_new_session(&mut self, view: &mut AgentView) -> Result<()> {
let id = create_session(&self.client, &self.create_options(), None).await?;
self.attach_session(&id, DockFold::Fresh).await?;
- // The title's pair is session-scoped: fetch the new session's stats before the rebuild
- // copies them into the chrome, or the rebind would ride the session being left's cost.
- self.refresh_stats().await;
+ // The tray's context usage rode the attach snapshot: the
+ // rebuild copies it into the chrome without a stats round-trip.
self.rebuild_view(view, &RebuildKind::Rebind);
// A new session starts with no draft and no prompt history (the submitted
// `/new` drains the draft already).
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index 182072b2ab..e6911a4661 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -475,6 +475,13 @@ impl SessionUi {
self.pending_model = reconstructed.model_id;
self.pending_model_provider = reconstructed.model_provider;
self.pending_thinking_suffix = reconstructed.thinking_suffix;
+ // The tray's context usage follows the attach snapshot (TS
+ // `createAgentConnectionState` carries `contextUsage`, and TS's
+ // open path never blocks its first frame on a `getSessionStats`
+ // fetch — `refreshConnectionContextUsage` runs only after a turn
+ // or compaction settles): the rebuild below re-syncs it into the
+ // chrome exactly like the other reconstructed session fields.
+ self.context = reconstructed.context_usage;
self.last_assistant_text = reconstructed
.chat
.iter()
@@ -713,16 +720,11 @@ impl SessionUi {
else {
return;
};
- // Unknown usage (tokens null right after a compaction, or a response without
- // the field) clears the tray display instead of keeping the stale one.
- self.context = data.get("contextUsage").and_then(|usage| {
- let tokens = usage.get("tokens").and_then(Value::as_u64)?;
- let window = usage.get("contextWindow").and_then(Value::as_u64)?;
- Some(crate::chrome::ContextUsage {
- tokens,
- context_window: window,
- })
- });
+ // Unknown usage (tokens null right after a compaction, or a
+ // response without the field) clears the tray display.
+ self.context = data
+ .get("contextUsage")
+ .and_then(crate::chrome::ContextUsage::from_wire);
self.dirty = true;
}
diff --git a/crates/pa-tui/src/session_ui/sessions_fork.rs b/crates/pa-tui/src/session_ui/sessions_fork.rs
index 3cc697c2f7..40e65847c7 100644
--- a/crates/pa-tui/src/session_ui/sessions_fork.rs
+++ b/crates/pa-tui/src/session_ui/sessions_fork.rs
@@ -439,8 +439,8 @@ impl SessionUi {
self.stash_draft_for_switch(view);
match self.attach_session(&id, DockFold::FirstFrame).await {
Ok(()) => {
- // The rebuilt tray must show the switched-to session's context usage.
- self.refresh_stats().await;
+ // The switched-to session's context usage rode the
+ // attach snapshot.
self.rebuild_view(view, &RebuildKind::Rebind);
self.note(&format!("switched to session {id}"), view);
// The switched-to session's own restore head lands after the switch note, so the
diff --git a/crates/pa-tui/src/snapshot.rs b/crates/pa-tui/src/snapshot.rs
index e510ba0424..9af7fcaeb2 100644
--- a/crates/pa-tui/src/snapshot.rs
+++ b/crates/pa-tui/src/snapshot.rs
@@ -48,6 +48,10 @@ pub struct Reconstructed {
/// The tray effort suffix for that model, when the state's model
/// carries its reasoning level.
pub thinking_suffix: Option<String>,
+ /// The tray's context usage (`state.contextUsage`): the snapshot
+ /// feeds the first frame's tray row without a stats round-trip.
+ /// `None` clears the tray display.
+ pub context_usage: Option<crate::chrome::ContextUsage>,
pub session_name: Option<String>,
/// Session id of the persisted session file.
pub session_id: String,
@@ -323,6 +327,9 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
.and_then(model_identity_value)
.map_or((None, None), |(id, provider)| (Some(id), provider));
let thinking_suffix = state.and_then(crate::chrome::tray_thinking_suffix);
+ let context_usage = state
+ .and_then(|state| state.get("contextUsage"))
+ .and_then(crate::chrome::ContextUsage::from_wire);
let session_name = state
.and_then(|state| state.get("sessionName"))
.and_then(Value::as_str)
@@ -398,6 +405,7 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
model_id,
model_provider,
thinking_suffix,
+ context_usage,
session_name,
session_id,
event_generation,
diff --git a/crates/pa-tui/src/snapshot/tests.rs b/crates/pa-tui/src/snapshot/tests.rs
index 75b702ebc3..f07ee36de5 100644
--- a/crates/pa-tui/src/snapshot/tests.rs
+++ b/crates/pa-tui/src/snapshot/tests.rs
@@ -2001,6 +2001,39 @@ fn attach_snapshot_carries_the_goal_state() {
assert_eq!(goal.objective.as_deref(), Some("keep shipping"));
}
+/// The tray's context usage rides the attach snapshot's state: the
+/// reconstruct hands it to the rebuild that follows every attach.
+#[test]
+fn attach_snapshot_carries_the_tray_context_usage() {
+ let mut attach = slim_attach();
+ attach
+ .get_mut("snapshot")
+ .expect("snapshot")
+ .get_mut("state")
+ .expect("state")["contextUsage"] =
+ json!({ "tokens": 9_400, "contextWindow": 128_000, "percent": 7.34 });
+ let data = attach_data_from_response(attach).unwrap();
+ let reconstructed = reconstruct(&data);
+ let usage = reconstructed.context_usage.expect("snapshot context usage");
+ assert_eq!(usage.tokens, 9_400);
+ assert_eq!(usage.context_window, 128_000);
+
+ // Unknown tokens (a fresh compaction) clear the tray display.
+ let mut attach = slim_attach();
+ attach
+ .get_mut("snapshot")
+ .expect("snapshot")
+ .get_mut("state")
+ .expect("state")["contextUsage"] =
+ json!({ "tokens": null, "contextWindow": 128_000, "percent": null });
+ let data = attach_data_from_response(attach).unwrap();
+ assert_eq!(reconstruct(&data).context_usage, None);
+
+ // A state without the field (a model-less session) stays `None`.
+ let data = attach_data_from_response(slim_attach()).unwrap();
+ assert_eq!(reconstruct(&data).context_usage, None);
+}
+
/// A `role: "toolResult"` message with one 500KB image payload block
/// (the `attach_image` emit's stored shape).
fn image_heavy_tool_result(payload: &str) -> serde_json::Value {