Skip to content

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

Rust

Stop rows showing twice after compaction; hold queued work during navigate and fork (#3643)

Sebastian Müller7e3117ba8571
diff --git a/crates/pa-daemon/src/branch_navigation.rs b/crates/pa-daemon/src/branch_navigation.rs
index b8761e2197..18e770aca1 100644
--- a/crates/pa-daemon/src/branch_navigation.rs
+++ b/crates/pa-daemon/src/branch_navigation.rs
@@ -569,6 +569,9 @@ impl Worker {
/// fork file, retire the live runtime, swap the store, prewarm the replacement.
/// Tree moves (`navigate_tree`) never run this teardown.
pub(crate) async fn handle_fork(&self, payload: &Value) -> DaemonResponse {
+ // The pause spans settle and replacement: no steer admits on the
+ // branch being left.
+ let _queued_work = self.hold_queued_work_pause("fork");
let (forked, selected_text) = match self.tree_navigation.prepare_fork(payload).await {
Ok(prepared) => prepared,
Err(response) => return response,
diff --git a/crates/pa-daemon/src/compaction.rs b/crates/pa-daemon/src/compaction.rs
index d15ef0f572..24f7ffc68f 100644
--- a/crates/pa-daemon/src/compaction.rs
+++ b/crates/pa-daemon/src/compaction.rs
@@ -249,26 +249,9 @@ impl CompactionManager {
/// Persist the post-compaction `ipython_state` row and broadcast its `message_start`/
/// `message_end` pair (TS `appendCustomMessageEntry`).
fn persist_and_emit_ipython_state(&self, message: &Value) {
- {
- let mut core = self.core.lock().unwrap();
- if let Some(store) = core.store.as_mut() {
- let _ = store.persist_entry(
- "custom_message",
- json!({
- "customType": message.get("customType").cloned().unwrap_or(Value::Null),
- "content": message.get("content").cloned().unwrap_or(Value::Null),
- "display": message.get("display").cloned().unwrap_or(Value::Bool(true)),
- "details": message.get("details").cloned().unwrap_or(Value::Null),
- }),
- );
- }
- }
- for event_type in ["message_start", "message_end"] {
- let _ = self.emit_session_event(json!({
- "type": event_type,
- "message": message,
- }));
- }
+ let mut core = self.core.lock().unwrap();
+ crate::worker::persist_custom_row(&mut core, message);
+ crate::worker::broadcast_custom_row_locked(&mut core, &self.events, message);
}
/// Sequence and broadcast one compaction `session_event` frame.
@@ -289,8 +272,8 @@ impl CompactionManager {
rest: Map::default(),
};
let payload = serde_json::to_vec(&outbound)?;
- drop(core);
self.events.send(OutboundFrame::session_event(payload));
+ drop(core);
Ok(())
}
}
@@ -448,6 +431,76 @@ fn compaction_end_event(outcome: &CompactionOutcome, custom_instructions: Option
mod tests {
use super::*;
+ #[tokio::test]
+ async fn custom_rows_on_each_side_of_collapse_appear_once_in_wire_order() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join("session.jsonl");
+ std::fs::write(
+ &path,
+ concat!(
+ r#"{"type":"session","id":"collapse-order","version":3,"timestamp":"2026-01-01T00:00:00.000Z","cwd":"/tmp"}"#,
+ "\n",
+ ),
+ )
+ .unwrap();
+ let worker = crate::worker::Worker::new(
+ crate::worker::WorkerConfig {
+ socket_path: dir.path().join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: "collapse-order".to_string(),
+ agent_dir: dir.path().join("agent"),
+ recovery_journal_path: dir.path().join("recovery.jsonl"),
+ script: Some(json!({ "responses": ["ack"] })),
+ telemetry_disabled: Some(true),
+ },
+ None,
+ );
+ worker.core.lock().unwrap().store =
+ Some(crate::session_store::SessionFile::open(&path).unwrap());
+ let mut subscription = worker.events.subscribe();
+ let row = |content| {
+ json!({
+ "role": "custom", "customType": "notice", "content": content,
+ "display": true, "details": null,
+ })
+ };
+ let before = row("before collapse");
+ let after = row("after collapse");
+ worker.emit_custom_row(&before);
+ let result = json!({ "summary": "collapsed history", "tokensBefore": 1234 });
+ worker
+ .compaction
+ .emit_session_event(compaction_end_success("manual", &result, false, None))
+ .unwrap();
+ worker.emit_custom_row(&after);
+ let frames: Vec<Value> = (0..5)
+ .map(|_| serde_json::from_slice(&subscription.try_recv().unwrap().payload).unwrap())
+ .collect();
+ let expected_events = [
+ json!({ "type": "message_start", "message": before }),
+ json!({ "type": "message_end", "message": before }),
+ json!({
+ "type": "compaction_end", "reason": "manual",
+ "result": { "summary": "collapsed history", "tokensBefore": 1234 },
+ "aborted": false, "willRetry": false,
+ }),
+ json!({ "type": "message_start", "message": after }),
+ json!({ "type": "message_end", "message": after }),
+ ];
+ let actual: Vec<Value> = frames.iter().map(|frame| frame["event"].clone()).collect();
+ assert_eq!(actual, expected_events);
+ let sequences: Vec<Value> = frames
+ .iter()
+ .map(|frame| frame["meta"]["sequence"].clone())
+ .collect();
+ assert_eq!(
+ sequences,
+ vec![json!(1), json!(2), json!(3), json!(4), json!(5)]
+ );
+ }
+
#[test]
fn compaction_result_value_mirrors_the_ts_datakeys() {
let result = pa_core::session_engine::compaction_exec::CompactionResult {
diff --git a/crates/pa-daemon/src/session_input_pause.rs b/crates/pa-daemon/src/session_input_pause.rs
index 35f91f4107..9fe174ec08 100644
--- a/crates/pa-daemon/src/session_input_pause.rs
+++ b/crates/pa-daemon/src/session_input_pause.rs
@@ -114,7 +114,59 @@ impl InputPauseTable {
}
}
+/// The owner identity of a daemon-internal queued-work pause.
+const INTERNAL_PAUSE_OWNER: &str = "worker-internal";
+
+/// A held queued-work pause for one daemon-internal flow (TS
+/// `_navigateTree`'s `acquireQueuedWorkPause`): the runner parks queued input
+/// until the guard drops, which releases through the wire handler's lift.
+pub(crate) struct QueuedWorkPause<'a> {
+ worker: &'a Worker,
+ pause_id: String,
+}
+
impl Worker {
+ /// Hold the queued-work pause for one daemon-internal flow. The lease
+ /// key carries a fresh uuid so concurrent flows hold distinct pauses.
+ pub(crate) fn hold_queued_work_pause(&self, purpose: &str) -> QueuedWorkPause<'_> {
+ let lease_key = format!("internal-{purpose}-{}", uuid::Uuid::new_v4());
+ let pause_id = self.input_pauses.acquire(
+ &self.config.active_session_id,
+ INTERNAL_PAUSE_OWNER,
+ &lease_key,
+ );
+ // The runner re-evaluates its admission gate and parks.
+ self.idle_notify.notify_waiters();
+ QueuedWorkPause {
+ worker: self,
+ pause_id,
+ }
+ }
+
+ /// One release lift shared by the wire handler and the internal guard:
+ /// every `Released` outcome wakes the runner and re-evaluates the owed
+ /// goal continuation.
+ fn release_session_pause(
+ &self,
+ pause_id: &str,
+ owner_client_id: &str,
+ active_session_id: &str,
+ ) -> ReleaseOutcome {
+ match self
+ .input_pauses
+ .release(pause_id, owner_client_id, active_session_id)
+ {
+ ReleaseOutcome::Released => {
+ self.work_notify.notify_one();
+ if let Some(engine) = self.agent_engine.as_ref() {
+ engine.retry_owed_goal_continuation();
+ }
+ ReleaseOutcome::Released
+ }
+ other => other,
+ }
+ }
+
/// `acquire_session_input_pause`: the pause id wire object `{ pauseId
/// }`, with the dedupe on the identical lease.
pub(crate) fn handle_acquire_session_input_pause(&self, payload: &Value) -> DaemonResponse {
@@ -170,20 +222,10 @@ impl Worker {
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
- match self
- .input_pauses
- .release(pause_id, &owner_client_id, &active_session_id)
- {
- ReleaseOutcome::Released => {
- // The gate lifted: queued input admits again, and the held
- // goal-continuation deferral re-evaluates.
- self.work_notify.notify_one();
- if let Some(engine) = self.agent_engine.as_ref() {
- engine.retry_owed_goal_continuation();
- }
+ match self.release_session_pause(pause_id, &owner_client_id, &active_session_id) {
+ ReleaseOutcome::Released | ReleaseOutcome::Unknown => {
response_success(None, "release_session_input_pause", None)
}
- ReleaseOutcome::Unknown => response_success(None, "release_session_input_pause", None),
ReleaseOutcome::OwnedByAnotherClient => response_failure(
None,
"release_session_input_pause",
@@ -202,6 +244,16 @@ impl Worker {
}
}
+impl Drop for QueuedWorkPause<'_> {
+ fn drop(&mut self) {
+ let _ = self.worker.release_session_pause(
+ &self.pause_id,
+ INTERNAL_PAUSE_OWNER,
+ &self.worker.config.active_session_id,
+ );
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index 86a1b591d8..0ee063d342 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -40,8 +40,9 @@ use create::{active_session_id_of, worker_server_capabilities};
// session_summary/SummaryInputs serve the in-crate test modules only, so allow the unused import.
#[allow(unused_imports)]
pub(crate) use summary::{
- compact_action_label, emit_worker_event_with, persist_custom_row, push_roster_delta,
- session_snapshot, session_summary, RosterPushContext, SummaryInputs,
+ broadcast_custom_row_locked, compact_action_label, emit_worker_event_locked,
+ emit_worker_event_with, persist_custom_row, push_roster_delta, session_snapshot,
+ session_summary, RosterPushContext, SummaryInputs,
};
use turn::TurnRunner;
@@ -921,8 +922,8 @@ fn emit_refinement_row(
review_session_id: &str,
message: &Value,
) -> bool {
+ let mut core = core.lock().unwrap();
{
- let mut core = core.lock().unwrap();
let Some(store) = core.store.as_mut() else {
return false;
};
@@ -943,16 +944,7 @@ fn emit_refinement_row(
}),
);
}
- emit_worker_event_with(
- core,
- events,
- json!({ "type": "message_start", "message": message }),
- );
- emit_worker_event_with(
- core,
- events,
- json!({ "type": "message_end", "message": message }),
- );
+ broadcast_custom_row_locked(&mut core, events, message);
true
}
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index 8aef0523ff..be735dbd5c 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -227,7 +227,10 @@ impl Worker {
/// `navigate_tree` with the reload's announcement: announced before the
/// response reaches the client, so surfaces never show the pre-navigation goal.
+ /// The whole navigation runs under the queued-work pause (TS
+ /// `_navigateTree`'s `acquireQueuedWorkPause` + `waitForIdle`).
async fn handle_navigate_tree(&self, payload: &Value) -> DaemonResponse {
+ let _queued_work = self.hold_queued_work_pause("navigate");
let response = self.tree_navigation.navigate_tree(payload).await;
if response.success {
if let Some(goal) = self.engine.goal_update_after_rebuild() {
@@ -812,8 +815,8 @@ impl Worker {
// commands run concurrently, so a second lock scope here could
// interleave another command's writes between the name and its
// notice, ordering the notice against a contradicted name history.
- // The broadcast (the client frames) runs after the lock drops, in
- // the `session_info_changed` order TS emits.
+ // The frames share that lock so a compaction cannot include the
+ // notice before its broadcast; `session_info_changed` still comes first.
let renamed_notice = previous
.as_deref()
.filter(|previous| *previous != name)
@@ -836,20 +839,20 @@ impl Worker {
if let Some(notice) = renamed_notice.as_ref() {
persist_custom_row(&mut core, notice);
}
+ // `session_info_changed` makes every attached client re-read the name.
+ super::emit_worker_event_locked(
+ &mut core,
+ &self.events,
+ serde_json::json!({ "type": "session_info_changed", "name": name }),
+ );
+ if let Some(notice) = renamed_notice.as_ref() {
+ super::broadcast_custom_row_locked(&mut core, &self.events, notice);
+ }
drop(core);
- // `session_info_changed` makes every attached client re-read
- // the name.
- self.emit_worker_event(serde_json::json!({
- "type": "session_info_changed",
- "name": name,
- }));
// The sender identity follows the live name.
if let Ok(summary_value) = serde_json::to_value(&summary) {
self.engine.set_session_summary(summary_value);
}
- if let Some(notice) = renamed_notice.as_ref() {
- self.broadcast_custom_row(notice);
- }
response_success(
None,
command,
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index 54a0a4ed44..983db81849 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -183,20 +183,9 @@ impl Worker {
/// Record one durable custom row and broadcast its `message_start`/`message_end`
/// pair (rows the session appends outside a turn).
pub(crate) fn emit_custom_row(&self, message: &Value) {
- {
- let mut core = self.core.lock().unwrap();
- persist_custom_row(&mut core, message);
- }
- self.broadcast_custom_row(message);
- }
-
- /// Broadcast one recorded custom row's `message_start`/`message_end`
- /// pair (the frames attached clients render for it). Runs OUTSIDE
- /// the `core` lock: a caller that persisted the row under its own
- /// lock scope broadcasts after releasing it.
- pub(crate) fn broadcast_custom_row(&self, message: &Value) {
- self.emit_worker_event(json!({ "type": "message_start", "message": message }));
- self.emit_worker_event(json!({ "type": "message_end", "message": message }));
+ let mut core = self.core.lock().unwrap();
+ persist_custom_row(&mut core, message);
+ broadcast_custom_row_locked(&mut core, &self.events, message);
}
/// Sequence and broadcast one `session_event` for the queue projection.
@@ -279,12 +268,33 @@ pub(crate) fn persist_custom_row(
}
}
+/// Broadcast a persisted custom row without releasing its store lock: a
+/// compaction replacement cannot include the row before its live frames.
+pub(crate) fn broadcast_custom_row_locked(
+ core: &mut SessionCore,
+ events: &EventPump,
+ message: &Value,
+) {
+ for event_type in ["message_start", "message_end"] {
+ emit_worker_event_locked(
+ core,
+ events,
+ json!({ "type": event_type, "message": message }),
+ );
+ }
+}
+
pub(crate) fn emit_worker_event_with(
core: &Arc<Mutex<SessionCore>>,
events: &Arc<EventPump>,
event: Value,
) {
let mut core = core.lock().unwrap();
+ emit_worker_event_locked(&mut core, events, event);
+}
+
+/// Sequence and enqueue an event while its caller still owns the session store lock.
+pub(crate) fn emit_worker_event_locked(core: &mut SessionCore, events: &EventPump, event: Value) {
let sequence = core.last_event_sequence + 1;
core.last_event_sequence = sequence;
let meta = create_daemon_event_meta(
@@ -301,7 +311,6 @@ pub(crate) fn emit_worker_event_with(
rest: Map::default(),
};
let payload = serde_json::to_vec(&outbound).unwrap_or_default();
- drop(core);
events.send(OutboundFrame::session_event(payload));
}
diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rs
index b09353c6af..5d548b7932 100644
--- a/crates/pa-daemon/src/worker/tests.rs
+++ b/crates/pa-daemon/src/worker/tests.rs
@@ -109,6 +109,7 @@ mod abort_boundary_tests;
mod connection_state_tests;
mod goal_tests;
mod kill_broadcast_tests;
+mod navigation_pause_tests;
mod queue_tests;
mod sidecar_exit_tests;
mod summary_tests;
diff --git a/crates/pa-daemon/src/worker/tests/navigation_pause_tests.rs b/crates/pa-daemon/src/worker/tests/navigation_pause_tests.rs
new file mode 100644
index 0000000000..8193ff28f8
--- /dev/null
+++ b/crates/pa-daemon/src/worker/tests/navigation_pause_tests.rs
@@ -0,0 +1,226 @@
+//! The navigation/fork queued-work pause (TS `_navigateTree`'s
+//! `acquireQueuedWorkPause` + `waitForIdle`): a steer parked behind the
+//! interrupted turn stays parked while the navigation settles and swaps,
+//! then delivers on the navigated-to branch.
+use super::*;
+
+const TURN_DELAY_MS: u64 = 1500;
+const SUMMARY_DELAY_MS: u64 = 600;
+const STEER_TEXT: &str = "steer mid-turn";
+
+fn seeded_session(dir: &std::path::Path) -> std::path::PathBuf {
+ let path = dir.join("sessions").join("nav-pause.jsonl");
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ let message = json!({ "role": "user", "content": "first prompt", "timestamp": 10u64 });
+ std::fs::write(
+ &path,
+ format!(
+ "{{\"type\":\"session\",\"version\":3,\"id\":\"nav-pause-session\",\"timestamp\":\"2026-01-01T00:00:00.000Z\",\"cwd\":\"/tmp\"}}\n\
+ {{\"type\":\"message\",\"message\":{},\"id\":\"m1\",\"parentId\":null,\"timestamp\":\"2026-01-01T00:00:00.000Z\"}}\n",
+ serde_json::to_string(&message).unwrap(),
+ ),
+ )
+ .unwrap();
+ path
+}
+
+async fn navigation_worker(dir: &std::path::Path, path: &std::path::Path) -> Arc<Worker> {
+ let config = WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: "nav-pause-session".to_string(),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({
+ // The branch-summary delay holds the navigation open; whichever
+ // response the aborted turn leaves, the steer's reply comes from
+ // this list, so the post-flow assertion stays structural.
+ "responses": [
+ { "text": "first scripted reply", "delayMs": TURN_DELAY_MS },
+ { "text": "second scripted reply", "delayMs": 2500 },
+ ],
+ "branchSummary": { "responses": [
+ { "summary": "the abandoned branch summary", "delayMs": SUMMARY_DELAY_MS },
+ ]},
+ })),
+ };
+ let worker = Arc::new(Worker::new(config, None));
+ let created = worker
+ .dispatch(
+ "create",
+ &json!({
+ "cwd": dir.to_string_lossy(),
+ "sessionDir": dir.join("sessions").to_string_lossy(),
+ "sessionPath": path.to_string_lossy(),
+ "name": "nav-pause",
+ }),
+ )
+ .await;
+ assert!(created.success, "create failed: {created:?}");
+ worker
+}
+
+/// Poll the connection state until the predicate holds, panicking with the
+/// last state on the deadline.
+async fn wait_for_state(
+ worker: &Worker,
+ what: &str,
+ deadline: Duration,
+ predicate: impl Fn(&Value) -> bool,
+) {
+ let start = std::time::Instant::now();
+ loop {
+ let response = worker.dispatch("get_connection_state", &json!({})).await;
+ assert!(
+ response.success,
+ "get_connection_state failed: {response:?}"
+ );
+ let state = response.data.expect("connection state data");
+ if predicate(&state) {
+ return;
+ }
+ assert!(
+ start.elapsed() < deadline,
+ "timed out waiting for {what}; last state: {state}"
+ );
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+}
+
+fn steer_parked(state: &Value) -> bool {
+ state
+ .get("sessionActions")
+ .and_then(|actions| actions.get("steering"))
+ .and_then(Value::as_array)
+ .is_some_and(|lane| lane.iter().any(|text| text == STEER_TEXT))
+}
+
+/// The transcript's string-content rows.
+async fn transcript_texts(worker: &Worker) -> Vec<String> {
+ let response = worker.dispatch("get_messages", &json!({})).await;
+ assert!(response.success, "get_messages failed: {response:?}");
+ response.data.expect("get_messages data")["messages"]
+ .as_array()
+ .expect("messages array")
+ .iter()
+ .filter_map(|message| {
+ message
+ .get("content")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .collect()
+}
+
+/// A steer parked behind the interrupted turn stays parked while the
+/// navigation settles and swaps — never admitted on the abandoned branch —
+/// and delivers on the navigated-to branch after the flow.
+#[tokio::test]
+async fn a_parked_steer_delivers_only_after_the_navigation() {
+ let dir = std::env::temp_dir().join(format!("pa-nav-pause-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = seeded_session(&dir);
+ let worker = navigation_worker(&dir, &path).await;
+
+ // The slow turn holds the session busy; the steer parks behind it.
+ let turn = {
+ let worker = Arc::clone(&worker);
+ tokio::spawn(async move {
+ worker
+ .dispatch("prompt_and_wait", &json!({ "message": "run one" }))
+ .await
+ })
+ };
+ wait_for_state(
+ &worker,
+ "the turn to start",
+ Duration::from_secs(3),
+ |state| state.get("isStreaming").and_then(Value::as_bool) == Some(true),
+ )
+ .await;
+ let queued = worker
+ .dispatch(
+ "prompt",
+ &json!({ "message": STEER_TEXT, "streamingBehavior": "steer" }),
+ )
+ .await;
+ assert!(queued.success, "steer failed: {queued:?}");
+ wait_for_state(
+ &worker,
+ "the steer to park",
+ Duration::from_secs(3),
+ steer_parked,
+ )
+ .await;
+
+ // The navigation interrupts the turn and summarizes the abandoned branch.
+ let navigation = {
+ let worker = Arc::clone(&worker);
+ tokio::spawn(async move {
+ worker
+ .dispatch(
+ "navigate_tree",
+ &json!({ "targetId": "m1", "summarize": true }),
+ )
+ .await
+ })
+ };
+
+ // Witness the interrupted turn's settle, then hold the window: while the
+ // branch-summary delay keeps the navigation in flight, the parked steer
+ // must stay parked and nothing may run.
+ wait_for_state(
+ &worker,
+ "the turn to settle",
+ Duration::from_secs(3),
+ |state| state.get("isStreaming").and_then(Value::as_bool) == Some(false),
+ )
+ .await;
+ let start = std::time::Instant::now();
+ while !navigation.is_finished() {
+ let response = worker.dispatch("get_connection_state", &json!({})).await;
+ let state = response.data.expect("connection state data");
+ assert!(
+ state.get("isStreaming").and_then(Value::as_bool) != Some(true),
+ "the parked steer was admitted inside the navigation window: {state}"
+ );
+ assert!(
+ steer_parked(&state),
+ "the steer left the queue mid-navigation: {state}"
+ );
+ assert!(
+ start.elapsed() < Duration::from_secs(5),
+ "the navigation never completed"
+ );
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ let navigated = navigation.await.expect("navigation task");
+ assert!(navigated.success, "navigate_tree failed: {navigated:?}");
+
+ // The released pause delivers the steer on the navigated-to branch; the
+ // abandoned branch's rows are gone.
+ let deadline = std::time::Instant::now() + Duration::from_secs(8);
+ let texts = loop {
+ let texts = transcript_texts(&worker).await;
+ if texts.len() >= 2 {
+ break texts;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the steer never delivered on the navigated-to branch: {texts:?}"
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ };
+ assert_eq!(
+ texts[0], STEER_TEXT,
+ "the steer's row leads the new branch: {texts:?}"
+ );
+ assert!(
+ !texts.iter().any(|text| text.contains("run one")),
+ "the abandoned rows must not survive the navigation: {texts:?}"
+ );
+ drop(turn);
+}
diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rs
index 2abb59bfd3..db9ec5dcd0 100644
--- a/crates/pa-daemon/src/worker/turn.rs
+++ b/crates/pa-daemon/src/worker/turn.rs
@@ -993,13 +993,13 @@ impl TurnRunner {
let payload = serde_json::to_vec(&outbound).unwrap_or_default();
direct_payloads.push(payload);
}
- drop(core);
- // Direct frames go out immediately (flushing the parked update
- // first, preserving event-sequence order); a pure-update batch
- // stays parked for the flusher.
+ // Direct frames go out while their sequence still owns the
+ // store lock, so another row cannot overtake them.
+ // Flush the parked update first; pure updates stay parked.
if !direct_payloads.is_empty() {
turn_coalescer.send_direct(&direct_payloads, &events);
}
+ drop(core);
// The waiting response must observe the frames'
// sequences and resolves only after the idle flip.
if let Some(result) = done_result {
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index d285d20558..aabaf0e1fe 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -539,6 +539,26 @@ impl SessionUi {
std::time::Instant::now().checked_sub(std::time::Duration::from_millis(age))
}
+ /// The one transcript replacement: clear the chat, render the entries,
+ /// and re-register decoded pending tool cards.
+ pub(crate) fn replace_transcript(&mut self, entries: Vec<ChatEntry>, view: &mut AgentView) {
+ view.clear_chat();
+ self.last_status_index = None;
+ self.pressed_click = None;
+ self.pending_tools.clear();
+ self.aborted_tools.clear();
+ for entry in entries {
+ view.push_entry(entry);
+ }
+ for entry in &view.chat {
+ if let ChatEntry::Tool(card) = entry {
+ if card.result.is_none() || card.result_partial {
+ self.pending_tools.insert(card.id.clone());
+ }
+ }
+ }
+ }
+
/// Fold the pending snapshot into the view (fresh transcript, footer
/// labels). Called after attach and after every session switch.
pub(crate) fn rebuild_view(&mut self, view: &mut AgentView, kind: &RebuildKind) {
@@ -591,16 +611,8 @@ impl SessionUi {
self.speed_stats = None;
view.chrome.speed_text = None;
}
- view.clear_chat();
- self.last_status_index = None;
- self.pressed_click = None;
- self.pending_tools.clear();
- self.aborted_tools.clear();
- if let Some(items) = self.pending_snapshot.take() {
- for entry in items {
- view.push_entry(entry);
- }
- }
+ let snapshot = self.pending_snapshot.take().unwrap_or_default();
+ self.replace_transcript(snapshot, view);
if let Some(message) = self.pending_model_fallback_message.take() {
view.push_entry(ChatEntry::Status {
text: format!("\u{26a0} {message}"),
@@ -608,15 +620,6 @@ impl SessionUi {
});
self.last_status_index = None;
}
- // The rebuild re-registers the live tool cards (the resumed turn's streamed calls re-enter
- // the pending map): a post-reconnect failure frame can still settle them.
- for entry in &view.chat {
- if let ChatEntry::Tool(card) = entry {
- if card.result.is_none() || card.result_partial {
- self.pending_tools.insert(card.id.clone());
- }
- }
- }
if let Some(model) = self.pending_model.take() {
view.chrome.model_id = Some(model);
view.chrome.model_provider = self.pending_model_provider.take();
diff --git a/crates/pa-tui/tests/queued_compaction_dup_headless.rs b/crates/pa-tui/tests/queued_compaction_dup_headless.rs
new file mode 100644
index 0000000000..66f64d62f3
--- /dev/null
+++ b/crates/pa-tui/tests/queued_compaction_dup_headless.rs
@@ -0,0 +1,421 @@
+//! Headless e2e for the compaction-window queued prompt: a queued prompt
+//! renders once and the compaction path never refetches. The mock still
+//! answers `get_messages`, so a refetch would be recorded.
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+
+use pa_tui::interactive::{
+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,
+ SessionSelection, UiMode,
+};
+use serde_json::{json, Value};
+
+const QUEUED_TEXT: &str = "queued while compacting";
+const SUMMARY_TEXT: &str = "the compacted summary";
+
+fn session_event(event: &Value, sequence: u64) -> Value {
+ json!({
+ "type": "session_event",
+ "activeSessionId": "s1",
+ "event": event,
+ "meta": { "sequence": sequence, "generation": "s1" },
+ })
+}
+
+/// The compaction summary message the store walk synthesizes.
+fn compaction_summary_message() -> Value {
+ json!({
+ "role": "compactionSummary",
+ "summary": SUMMARY_TEXT,
+ "tokensBefore": 100u64,
+ "retainedMessageCount": 0u64,
+ "timestamp": 300u64,
+ })
+}
+
+/// The manual compaction's settled pair, then the queued prompt's delivery
+/// frames — one burst, in wire order.
+fn compaction_and_queued_frames() -> Vec<Value> {
+ let user_message = json!({
+ "role": "user",
+ "content": QUEUED_TEXT,
+ "timestamp": 400u64,
+ });
+ vec![
+ session_event(
+ &json!({ "type": "compaction_start", "reason": "manual" }),
+ 1,
+ ),
+ session_event(
+ &json!({
+ "type": "compaction_end",
+ "reason": "manual",
+ "result": {
+ "summary": SUMMARY_TEXT,
+ "firstKeptEntryId": "e1",
+ "tokensBefore": 100,
+ },
+ "aborted": false,
+ "willRetry": false,
+ }),
+ 2,
+ ),
+ session_event(
+ &json!({ "type": "message_start", "message": user_message }),
+ 3,
+ ),
+ session_event(
+ &json!({ "type": "message_end", "message": user_message }),
+ 4,
+ ),
+ session_event(&json!({ "type": "turn_end" }), 5),
+ session_event(&json!({ "type": "agent_end" }), 6),
+ ]
+}
+
+/// A compaction pair with no turn frames around it: the settled-compaction
+/// refresh must fire on the transition alone.
+fn compaction_only_frames() -> Vec<Value> {
+ vec![
+ session_event(
+ &json!({ "type": "compaction_start", "reason": "manual" }),
+ 1,
+ ),
+ session_event(
+ &json!({
+ "type": "compaction_end",
+ "reason": "manual",
+ "result": {
+ "summary": SUMMARY_TEXT,
+ "firstKeptEntryId": "e1",
+ "tokensBefore": 100,
+ },
+ "aborted": false,
+ "willRetry": false,
+ }),
+ 2,
+ ),
+ ]
+}
+
+struct MockSupervisor {
+ listener: UnixListener,
+}
+
+impl MockSupervisor {
+ /// Serve one client connection; returns the command types it saw.
+ /// `attach_frames` rides the wire right after the attach response.
+ fn serve(self, attach_frames: &[Value]) -> Vec<String> {
+ let (stream, _) = self.listener.accept().expect("accept mock client");
+ let mut writer = stream.try_clone().expect("clone mock socket");
+ let mut reader = BufReader::new(stream);
+
+ let hello = json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ "clientId": "mock",
+ });
+ write_json(&mut writer, &hello);
+
+ let mut commands = Vec::new();
+ let mut line = String::new();
+ loop {
+ line.clear();
+ match reader.read_line(&mut line) {
+ Ok(0) | Err(_) => break,
+ Ok(_) => {}
+ }
+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {
+ continue;
+ };
+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");
+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);
+ let command_type = command
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ commands.push(command_type.clone());
+ match command_type.as_str() {
+ "create" => write_json(&mut writer, &create_response(id)),
+ "attach" => {
+ write_json(&mut writer, &attach_response(id));
+ for frame in attach_frames {
+ write_json(&mut writer, frame);
+ }
+ }
+ // The PRE-FIX tree's rebuild fetch: the queued row is already
+ // persisted, so the fetched transcript contains it too.
+ "get_messages" => write_json(&mut writer, &raced_fetch_response(id)),
+ command => write_json(&mut writer, &generic_response(id, command)),
+ }
+ }
+ commands
+ }
+}
+
+fn attach_response(id: &str) -> Value {
+ json!({
+ "type": "response",
+ "id": id,
+ "command": "attach",
+ "success": true,
+ "data": {
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "activeSessionId": "s1",
+ "snapshot": {
+ "activeSessionId": "s1",
+ "summary": { "id": "s1", "cwd": "/tmp" },
+ "state": {
+ "activeSessionId": "s1",
+ "cwd": "/tmp",
+ "sessionId": "sess-1",
+ "sessionName": "compaction race",
+ "model": null,
+ "isStreaming": false,
+ "isCompacting": false,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": [],
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ "replay": { "status": "complete", "toSequence": 0 },
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ "client": { "id": "mock", "capabilities": [] },
+ },
+ })
+}
+
+/// The `create` response: a fresh durable session identity.
+fn create_response(id: &str) -> Value {
+ json!({
+ "type": "response", "id": id, "command": "create",
+ "success": true,
+ "data": {
+ "activeSessionId": "s1",
+ "sessionId": "sess-1",
+ "sessionFile": "/tmp/sess-1.jsonl",
+ },
+ })
+}
+
+/// The raced transcript fetch the PRE-FIX tree issues.
+fn raced_fetch_response(id: &str) -> Value {
+ json!({
+ "type": "response", "id": id, "command": "get_messages",
+ "success": true,
+ "data": {
+ "messages": [
+ compaction_summary_message(),
+ { "role": "user", "content": QUEUED_TEXT, "timestamp": 400 },
+ ],
+ },
+ })
+}
+
+/// The catch-all success envelope every other command answers with.
+fn generic_response(id: &str, command: &str) -> Value {
+ json!({
+ "type": "response", "id": id, "command": command,
+ "success": true, "data": {},
+ })
+}
+
+fn write_json(writer: &mut UnixStream, value: &Value) {
+ let mut line = serde_json::to_string(value).expect("serialize mock frame");
+ line.push('\n');
+ writer.write_all(line.as_bytes()).expect("write mock frame");
+ writer.flush().expect("flush mock frame");
+}
+
+fn options(socket: PathBuf) -> InteractiveOptions {
+ InteractiveOptions {
+ models: None,
+ socket_path: socket,
+ cwd: PathBuf::from("/tmp"),
+ session_dir: None,
+ script_path: None,
+ model_selection: ModelSelection::default(),
+ model_catalog: Vec::new(),
+ model_configured_providers: std::collections::HashSet::default(),
+ model_recent_models: Vec::new(),
+ default_thinking_level: None,
+ no_session: false,
+ session: SessionSelection::New,
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: false,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: None,
+ client_auth: None,
+ traces: None,
+ provider_auth: None,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ prompt_stash: std::sync::Arc::default(),
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: None,
+ }
+}
+
+/// The queued row renders once and the compaction path never refetches.
+#[test]
+fn a_row_racing_the_post_compaction_collapse_renders_once() {
+ // The ambient TMUX variable adds a startup notice to the
+ // transcript; scrub it so the run is the same inside tmux and out.
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor {
+ listener: UnixListener::bind(&socket).expect("bind mock socket"),
+ };
+ let handle = std::thread::spawn(move || supervisor.serve(&compaction_and_queued_frames()));
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![HeadlessStep::WaitRender {
+ needle: QUEUED_TEXT.to_string(),
+ timeout_ms: 5000,
+ }],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ let commands = handle.join().expect("mock supervisor finished");
+
+ let final_frame = outcome.frames.last().expect("at least one rendered frame");
+ assert_eq!(
+ final_frame.matches(QUEUED_TEXT).count(),
+ 1,
+ "the queued row renders once:\n{final_frame}"
+ );
+ assert_eq!(
+ final_frame.matches(SUMMARY_TEXT).count(),
+ 1,
+ "the compaction summary row renders once:\n{final_frame}"
+ );
+ assert!(
+ !commands.iter().any(|command| command == "get_messages"),
+ "the compaction path never refetches the transcript; commands seen: {commands:?}"
+ );
+}
+
+/// A compaction with no turn frames around it still refreshes the tray's
+/// context usage: the mock must see the stats command land after the
+/// collapse.
+#[test]
+fn a_settled_compaction_refreshes_the_tray_stats() {
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor {
+ listener: UnixListener::bind(&socket).expect("bind mock socket"),
+ };
+ let handle = std::thread::spawn(move || supervisor.serve(&compaction_only_frames()));
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![HeadlessStep::WaitRender {
+ needle: SUMMARY_TEXT.to_string(),
+ timeout_ms: 5000,
+ }],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ let commands = handle.join().expect("mock supervisor finished");
+ outcome.frames.last().expect("at least one rendered frame");
+ let stats = commands
+ .iter()
+ .filter(|command| *command == "get_session_stats")
+ .count();
+ assert_eq!(
+ stats, 2,
+ "the compaction transition refreshes the tray on top of the exit hint; commands: {commands:?}"
+ );
+}
+
+/// Replay both sides of the daemon's atomic custom-row/collapse ordering.
+#[test]
+fn custom_rows_before_and_after_collapse_render_once() {
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor {
+ listener: UnixListener::bind(&socket).expect("bind mock socket"),
+ };
+ let before = json!({
+ "role": "custom", "customType": "notice", "content": "custom before collapse",
+ "display": true, "timestamp": 299,
+ });
+ let after = json!({
+ "role": "custom", "customType": "notice", "content": "custom after collapse",
+ "display": true, "timestamp": 301,
+ });
+ let frames = vec![
+ session_event(
+ &json!({ "type": "compaction_start", "reason": "manual" }),
+ 1,
+ ),
+ session_event(&json!({ "type": "message_start", "message": before }), 2),
+ session_event(&json!({ "type": "message_end", "message": before }), 3),
+ session_event(
+ &json!({
+ "type": "compaction_end", "reason": "manual",
+ "result": { "summary": SUMMARY_TEXT, "tokensBefore": 100 },
+ "aborted": false, "willRetry": false,
+ }),
+ 4,
+ ),
+ session_event(&json!({ "type": "message_start", "message": after }), 5),
+ session_event(&json!({ "type": "message_end", "message": after }), 6),
+ ];
+ let handle = std::thread::spawn(move || supervisor.serve(&frames));
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![HeadlessStep::WaitRender {
+ needle: "custom after collapse".to_string(),
+ timeout_ms: 5000,
+ }],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("custom collapse replay");
+ let commands = handle.join().expect("mock supervisor finished");
+ let frame = outcome.frames.last().expect("a rendered frame");
+ for text in [
+ "custom before collapse",
+ "custom after collapse",
+ SUMMARY_TEXT,
+ ] {
+ assert_eq!(frame.matches(text).count(), 1, "{text}: {frame}");
+ }
+ assert!(!commands.iter().any(|command| command == "get_messages"));
+}