A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
pa-tui: queue browse walks user-typed items only (#3636)
Sebastian Müllera3d3fac89d66
diff --git a/crates/pa-tui/src/queued.rs b/crates/pa-tui/src/queued.rsindex 1156068cca..456f44ba7f 100644--- a/crates/pa-tui/src/queued.rs+++ b/crates/pa-tui/src/queued.rs@@ -1,8 +1,9 @@//! The queued-message strip above the prompt dock (see [`render_queue`]). Sanctioned divergence-//! (operator request Kevin 2026-09-24; directives 2026-09-25, 2026-09-28): internal prompts-//! condense into one counted row by origin instead of preview rows; child status notices and-//! engine-minted continuations classify by wire-typed provenance only (user-typed look-alikes stay-//! human rows); browse walks every item; edits are human-origin only.+//! (operator request Kevin 2026-09-24; directive 2026-09-25): internal prompts condense into one+//! counted row by origin instead of preview rows; child status notices and engine-minted+//! continuations classify by wire-typed provenance only (user-typed look-alikes stay human rows).+//! The browse walks the user-typed items only (operator decision 2026-10-16): internal prompts are+//! a separate channel, shown only as the condensed row.use crate::theme::{Theme, ThemeColor};use crate::width::{pad_line, truncate_line};@@ -170,10 +171,10 @@ pub struct QueuedMessages {/// "Starting" row until the turn's rows land; not browsable.pub starting: Option<String>,/// Which parked items are RLM child status notices, by lane index (wire-typed- /// provenance): folded into the condensed count, still browseable.+ /// provenance): folded into the condensed count.pub rlm_child_status: QueueLaneIndices,/// Which parked items are engine-minted internal prompts, by lane index (the second wire-typed- /// provenance rider); folded into the condensed count, read-only.+ /// provenance rider); folded into the condensed count.pub injected_prompts: QueueLaneIndices,}@@ -230,19 +231,20 @@ impl QueueLane {}}-/// One addressable queue item (TS `QueueSelectionItem`). `internal` marks an internal prompt, which-/// the browse walks READ-ONLY; `false` is the human row the edit affordances apply to.+/// One addressable user-typed queue item (TS `QueueSelectionItem`).#[derive(Debug, Clone, PartialEq, Eq)]pub struct QueueSelectionItem {pub lane: QueueLane,+ /// The real lane index the mutations address.pub index: usize,+ /// The 0-based position among the lane's user-typed items (the strip's visible rows).+ pub position: usize,pub text: String,- pub internal: bool,}/// The strip rows: the "Starting" row of a preparing turn above a truncated dim preview per/// human-typed queued message, the condensed internal-prompt row, and the queue hint. Empty input-/// renders no rows; a preparing turn alone renders its row but never the hint.+/// renders no rows; the hint renders only when a human-typed message is parked.#[must_use]pub fn render_queue(theme: &Theme,@@ -258,21 +260,20 @@ pub fn render_queue(rows.push(preview_row(theme, STARTING_LABEL, starting, width));}// The human-typed previews render individually, so what the user parked stays explicit above- // the condensed row; child status notices classify by typed provenance here.- for (lane, index, message) in queued_items(queue) {- if queued_item_origin(message, queue, lane, index).is_none() {- let label = match lane {- QueueLane::Steering => STEERING_LABEL,- QueueLane::FollowUp => FOLLOW_UP_LABEL,- };- rows.push(preview_row(theme, label, message, width));- }+ // the condensed row.+ let user_items = flatten(queue);+ for item in &user_items {+ let label = match item.lane {+ QueueLane::Steering => STEERING_LABEL,+ QueueLane::FollowUp => FOLLOW_UP_LABEL,+ };+ rows.push(preview_row(theme, label, &item.text, width));}if let Some(counts) = condensed_counts(queue) {rows.push(condensed_row(theme, &counts, width));}- if queue.is_empty() {- // A starting row alone carries no parked messages to browse.+ if user_items.is_empty() {+ // A starting row or internal prompts alone carry no user-typed messages to browse.return rows;}let hint = format!("\u{2570}\u{2500} {browse_key} to browse and edit queued messages");@@ -287,23 +288,14 @@ pub fn render_queue(rows}-/// The browse header text: the lane, its 1-based index, and the effective keys for the affordances;-/// an internal prompt renders the read-only phrasing instead.+/// The browse header text: the lane, the item's 1-based position among the lane's user-typed rows,+/// and the effective keys for the affordances.#[must_use]pub fn browse_header_text(selected: &QueueSelectionItem, key_display: &QueueBrowseKeys) -> String {- if selected.internal {- return format!(- "{} {} \u{00b7} {}/{} browse \u{00b7} read-only internal prompt",- selected.lane.display_name(),- selected.index + 1,- key_display.navigate_older,- key_display.navigate_newer,- );- }format!("{} {} \u{00b7} {}/{} browse \u{00b7} {}/{} reorder \u{00b7} enter steers \u{00b7} {} queues \u{00b7} empty deletes",selected.lane.display_name(),- selected.index + 1,+ selected.position + 1,key_display.navigate_older,key_display.navigate_newer,key_display.move_earlier,@@ -429,8 +421,25 @@ impl QueueSelection {}}+ /// The real lane index of the user item next to the selection in its lane, one step earlier+ /// (`direction < 0`) or later; `None` when the selection has no user neighbor there.+ #[must_use]+ pub fn reorder_target(&self, direction: i64) -> Option<usize> {+ let cursor = self.cursor?;+ let lane = self.items[cursor].lane;+ let neighbor = if direction < 0 {+ cursor.checked_sub(1)?+ } else {+ cursor + 1+ };+ self.items+ .get(neighbor)+ .filter(|item| item.lane == lane)+ .map(|item| item.index)+ }+/// Re-point the selection after a mutation or queue update: the selection- /// survives only when the addressed item is unchanged (TS `refreshAt`).+ /// survives only when the addressed user-typed item is unchanged (TS `refreshAt`).pub fn refresh_at(&mut self,queue: &QueuedMessages,@@ -439,14 +448,11 @@ impl QueueSelection {expected_text: &str,) -> Option<String> {self.items = flatten(queue);- let cursor = match lane {- QueueLane::Steering => Some(index),- QueueLane::FollowUp => queue.steering.len().checked_add(index),- };- let selected = cursor.and_then(|cursor| self.items.get(cursor));- if selected.is_some_and(|item| {- item.lane == lane && item.index == index && item.text == expected_text- }) {+ let cursor = self+ .items+ .iter()+ .position(|item| item.lane == lane && item.index == index);+ if cursor.is_some_and(|cursor| self.items[cursor].text == expected_text) {self.cursor = cursor;None} else {@@ -464,11 +470,7 @@ impl QueueSelection {/// Mirror one applied lane move locally: swap the item with its neighbor so the strip and the/// selection update without waiting for the `session_action_update` event.-pub fn mirror_lane_move(queue: &mut QueuedMessages, lane: QueueLane, index: usize, target: i64) {- if target < 0 {- return;- }- let target = target as usize;+pub fn mirror_lane_move(queue: &mut QueuedMessages, lane: QueueLane, index: usize, target: usize) {let lane_items = match lane {QueueLane::Steering => &mut queue.steering,QueueLane::FollowUp => &mut queue.follow_ups,@@ -499,22 +501,19 @@ pub fn mirror_lane_move(queue: &mut QueuedMessages, lane: QueueLane, index: usiz}}+/// The browsable items: the user-typed queue items, lane-by-lane, oldest-first.fn flatten(queue: &QueuedMessages) -> Vec<QueueSelectionItem> {- let item = |lane: QueueLane, index: usize, text: &str| QueueSelectionItem {- lane,- index,- text: text.to_string(),- internal: queued_item_origin(text, queue, lane, index).is_some(),- };- let steering = queue- .steering- .iter()- .enumerate()- .map(|(index, text)| item(QueueLane::Steering, index, text));- let follow_up = queue- .follow_ups- .iter()- .enumerate()- .map(|(index, text)| item(QueueLane::FollowUp, index, text));- steering.chain(follow_up).collect()+ let mut items: Vec<QueueSelectionItem> = Vec::new();+ for (lane, index, text) in queued_items(queue) {+ if queued_item_origin(text, queue, lane, index).is_none() {+ let position = items.iter().filter(|item| item.lane == lane).count();+ items.push(QueueSelectionItem {+ lane,+ index,+ position,+ text: text.to_string(),+ });+ }+ }+ items}diff --git a/crates/pa-tui/src/queued/tests.rs b/crates/pa-tui/src/queued/tests.rsindex c150e61c22..5a7d87fdf6 100644--- a/crates/pa-tui/src/queued/tests.rs+++ b/crates/pa-tui/src/queued/tests.rs@@ -212,8 +212,8 @@ fn internal_prompts_condense_into_one_counted_row() {let rows = render_queue(&theme(), &queue, "alt+up", 80);assert_eq!(rows.len(),- 3,- "spacer + the one condensed row + hint, no per-prompt rows"+ 2,+ "spacer + the one condensed row, no per-prompt rows and no browse hint");let text: String = rows[1].iter().map(|span| span.content.as_str()).collect();assert_eq!(@@ -297,7 +297,7 @@ fn condensed_row_counts_each_origin_with_correct_plurals() {injected_prompts: QueueLaneIndices::default(),};let rows = render_queue(&theme(), &queue, "alt+up", 80);- assert_eq!(rows.len(), 3);+ assert_eq!(rows.len(), 2);let text: String = rows[1].iter().map(|span| span.content.as_str()).collect();assert_eq!(text.trim(),@@ -316,7 +316,7 @@ fn one_queued_agent_message_reads_singular() {injected_prompts: QueueLaneIndices::default(),};let rows = render_queue(&theme(), &queue, "alt+up", 80);- assert_eq!(rows.len(), 3);+ assert_eq!(rows.len(), 2);let text: String = rows[1].iter().map(|span| span.content.as_str()).collect();assert_eq!(text.trim(), "1 agent message queued");}@@ -334,7 +334,7 @@ fn condensed_row_truncates_to_the_width() {injected_prompts: QueueLaneIndices::default(),};let rows = render_queue(&theme(), &queue, "alt+up", 30);- assert_eq!(rows.len(), 3);+ assert_eq!(rows.len(), 2);let text: String = rows[1].iter().map(|span| span.content.as_str()).collect();assert!(text.trim_end().ends_with("..."),@@ -346,27 +346,92 @@ fn condensed_row_truncates_to_the_width() {);}+fn keys() -> QueueBrowseKeys {+ QueueBrowseKeys {+ navigate_older: "alt+up".to_string(),+ navigate_newer: "alt+down".to_string(),+ move_earlier: "ctrl+alt+up".to_string(),+ move_later: "ctrl+alt+down".to_string(),+ follow_up: "alt+enter".to_string(),+ }+}++/// The browse walks only the user-typed items: the agent message between them stays in the+/// condensed row, the selection keeps the real lane indices the mutations send, and the header+/// numbers the item among the lane's user rows (the strip's visible rows).#[test]-fn internal_prompts_stay_browseable_when_condensed() {+fn browse_walks_only_the_user_typed_items() {let queue = QueuedMessages {steering: vec![- "Heartbeat prompt: nudge".to_string(),"turn right".to_string(),+ "Agent message received: from child".to_string(),+ "then summarize".to_string(),],- follow_ups: vec!["then summarize".to_string()],+ follow_ups: Vec::new(),starting: None,rlm_child_status: QueueLaneIndices::default(),injected_prompts: QueueLaneIndices::default(),};+ let header = |selection: &QueueSelection| {+ let text = browse_header_text(selection.selected().unwrap(), &keys());+ text.split(" \u{00b7} ").next().unwrap().to_string()+ };let mut selection = QueueSelection::default();- // Browsing still walks every queued item newest-first, the condensed- // internal prompt included: draft -> follow-up -> steering, newest to oldest.let text = selection.browse(&queue, "draft", QueueBrowseDirection::Older);assert_eq!(text.as_deref(), Some("then summarize"));+ assert_eq!(+ selection.selected().map(|item| (item.lane, item.index)),+ Some((QueueLane::Steering, 2))+ );+ assert_eq!(header(&selection), "steering 2");let text = selection.browse(&queue, "", QueueBrowseDirection::Older);assert_eq!(text.as_deref(), Some("turn right"));- let text = selection.browse(&queue, "", QueueBrowseDirection::Older);- assert_eq!(text.as_deref(), Some("Heartbeat prompt: nudge"));+ assert_eq!(+ selection.selected().map(|item| (item.lane, item.index)),+ Some((QueueLane::Steering, 0))+ );+ assert_eq!(header(&selection), "steering 1");+ assert_eq!(+ selection.browse(&queue, "", QueueBrowseDirection::Older),+ None,+ "the agent message is never walked; the oldest user row is the boundary"+ );+ let text = selection.browse(&queue, "", QueueBrowseDirection::Newer);+ assert_eq!(text.as_deref(), Some("then summarize"));+ let text = selection.browse(&queue, "", QueueBrowseDirection::Newer);+ assert_eq!(text.as_deref(), Some("draft"));+ assert!(!selection.is_browsing());+}++/// A reorder exchanges the user item with the adjacent user item of its lane; the internal item+/// between them keeps its position.+#[test]+fn reorder_targets_the_adjacent_user_item() {+ let mut queue = QueuedMessages {+ steering: vec![+ "user A".to_string(),+ "Agent message received: from child".to_string(),+ "user B".to_string(),+ ],+ follow_ups: Vec::new(),+ starting: None,+ rlm_child_status: QueueLaneIndices::default(),+ injected_prompts: QueueLaneIndices::default(),+ };+ let mut selection = QueueSelection::default();+ selection.browse(&queue, "draft", QueueBrowseDirection::Older);+ assert_eq!(selection.reorder_target(-1), Some(0));+ selection.browse(&queue, "", QueueBrowseDirection::Older);+ assert_eq!(+ selection.reorder_target(-1),+ None,+ "no user item sits earlier in the lane"+ );+ mirror_lane_move(&mut queue, QueueLane::Steering, 2, 0);+ assert_eq!(+ queue.steering,+ vec!["user B", "Agent message received: from child", "user A"]+ );}#[test]@@ -438,6 +503,38 @@ fn refresh_keeps_a_matching_selection_and_drops_a_stale_one() {assert!(!selection.is_browsing());}+#[test]+fn refresh_finds_a_user_item_past_interleaved_internal_items() {+ let queue = QueuedMessages {+ steering: vec![+ "Heartbeat prompt: nudge".to_string(),+ "turn right".to_string(),+ ],+ follow_ups: vec![+ "Background command finished: ls".to_string(),+ "then summarize".to_string(),+ ],+ starting: None,+ rlm_child_status: QueueLaneIndices::default(),+ injected_prompts: QueueLaneIndices::default(),+ };+ let mut selection = QueueSelection::default();+ selection.browse(&queue, "draft", QueueBrowseDirection::Older);+ assert_eq!(+ selection.refresh_at(&queue, QueueLane::FollowUp, 1, "then summarize"),+ None+ );+ assert_eq!(+ selection.selected().map(|item| (item.lane, item.index)),+ Some((QueueLane::FollowUp, 1))+ );+ assert_eq!(+ selection.refresh_at(&queue, QueueLane::Steering, 0, "Heartbeat prompt: nudge"),+ Some("draft".to_string()),+ "an internal item is never selected"+ );+}+#[test]fn mirror_lane_move_swaps_within_the_lane_only() {let mut queue = QueuedMessages {@@ -454,12 +551,6 @@ fn mirror_lane_move_swaps_within_the_lane_only() {vec!["later"],"the other lane is untouched");- mirror_lane_move(&mut queue, QueueLane::FollowUp, 0, -1);- assert_eq!(- queue.follow_ups,- vec!["later"],- "a negative target is a noop"- );mirror_lane_move(&mut queue, QueueLane::FollowUp, 0, 7);assert_eq!(queue.follow_ups,@@ -513,45 +604,15 @@ fn browse_header_quotes_lane_index_and_keys() {let selected = QueueSelectionItem {lane: QueueLane::Steering,index: 0,+ position: 0,text: "turn right".to_string(),- internal: false,- };- let keys = QueueBrowseKeys {- navigate_older: "alt+up".to_string(),- navigate_newer: "alt+down".to_string(),- move_earlier: "ctrl+alt+up".to_string(),- move_later: "ctrl+alt+down".to_string(),- follow_up: "alt+enter".to_string(),};assert_eq!(- browse_header_text(&selected, &keys),+ browse_header_text(&selected, &keys()),"steering 1 \u{00b7} alt+up/alt+down browse \u{00b7} ctrl+alt+up/ctrl+alt+down reorder \u{00b7} enter steers \u{00b7} alt+enter queues \u{00b7} empty deletes");}-/// The read-only header (the operator's edit-scope directive): an internal-/// item browses, but the header never offers the edit affordances.-#[test]-fn an_internal_item_headers_read_only() {- let internal_notice = QueueSelectionItem {- lane: QueueLane::FollowUp,- index: 1,- text: "[child-exited: no-reply child:lane]".to_string(),- internal: true,- };- let keys = QueueBrowseKeys {- navigate_older: "alt+up".to_string(),- navigate_newer: "alt+down".to_string(),- move_earlier: "ctrl+alt+up".to_string(),- move_later: "ctrl+alt+down".to_string(),- follow_up: "alt+enter".to_string(),- };- assert_eq!(- browse_header_text(&internal_notice, &keys),- "follow-up 2 \u{00b7} alt+up/alt+down browse \u{00b7} read-only internal prompt"- );-}-/// The queue-fold bug (operator 2026-09-25): many child exits parked behind one busy turn rendered/// as that many user-like rows. The wire-typed provenance folds them into the counted row — one row/// however many notices queue, with the human previews untouched.@@ -735,38 +796,6 @@ fn mixed_origins_count_child_status_in_the_fixed_order() {);}-/// The browse affordance still walks the parked notices (the operator's inspectability-/// requirement): the selection walks every item, oldest-first down the follow-up lane.-#[test]-fn browse_still_walks_the_parked_notices() {- let queue = QueuedMessages {- steering: Vec::new(),- follow_ups: vec![- "[child-exited: no-reply child:lane]\n\nLast assistant text: done".to_string(),- "then summarize".to_string(),- ],- starting: None,- rlm_child_status: QueueLaneIndices {- steering: Vec::new(),- follow_up: vec![0],- },- injected_prompts: QueueLaneIndices::default(),- };- let mut selection = QueueSelection::default();- let text = selection.browse(&queue, "draft", QueueBrowseDirection::Older);- assert_eq!(text.as_deref(), Some("then summarize"));- let text = selection.browse(&queue, "", QueueBrowseDirection::Older);- assert_eq!(- text.as_deref(),- Some("[child-exited: no-reply child:lane]\n\nLast assistant text: done"),- "the notice is walkable with its full detail"- );- assert!(- selection.selected().is_some_and(|item| item.internal),- "the walked notice carries the read-only origin"- );-}-/// The operator's mission case (2026-09-28), stated exactly: seven child-exited follow-ups parked/// behind one busy turn plus one user steering message render as the user message's row plus the/// one summary row — NO child-exit item rows.@@ -889,13 +918,19 @@ fn an_only_internal_queue_renders_just_the_summary_row() {},};let rows = render_queue(&theme(), &queue, "alt+up", 80);- assert_eq!(rows.len(), 3, "spacer + the condensed row + hint");+ assert_eq!(rows.len(), 2, "spacer + the condensed row, no browse hint");let text: String = rows[1].iter().map(|span| span.content.as_str()).collect();assert_eq!(text.trim(),"1 heartbeat and 1 other internal prompt queued","every parked item counts; none renders its own row");+ let mut selection = QueueSelection::default();+ assert_eq!(+ selection.browse(&queue, "draft", QueueBrowseDirection::Older),+ None+ );+ assert!(!selection.is_browsing());}/// The spoof regression for the second rider: provenance is the ONLY classifier — a user-typed@@ -968,10 +1003,10 @@ fn mixed_origins_count_the_injected_continuations_as_other() {);}-/// The browse keeps walking internal items while its edit affordances apply-/// to the user items: every walked item carries its origin for the gates.+/// The browse skips every internal origin across both lanes: labeled prompts, child status notices+/// and injected continuations.#[test]-fn browse_items_carry_their_origin_for_the_edit_gate() {+fn browse_skips_every_internal_origin() {let queue = QueuedMessages {steering: vec!["Heartbeat prompt: nudge".to_string(),@@ -999,49 +1034,15 @@ fn browse_items_carry_their_origin_for_the_edit_gate() {.as_deref(),Some("then summarize"));- assert!(- !selection.selected().unwrap().internal,- "the user row stays editable"- );- assert_eq!(- selection- .browse(&queue, "", QueueBrowseDirection::Older)- .as_deref(),- Some("[child-exited: no-reply child:lane]")- );- assert!(- selection.selected().unwrap().internal,- "the child-status notice browses read-only"- );- assert_eq!(- selection- .browse(&queue, "", QueueBrowseDirection::Older)- .as_deref(),- Some("[goal: continuation]\n\nKeep driving the goal.")- );- assert!(- selection.selected().unwrap().internal,- "the injected continuation browses read-only"- );assert_eq!(selection.browse(&queue, "", QueueBrowseDirection::Older).as_deref(),Some("turn right"));- assert!(- !selection.selected().unwrap().internal,- "the user row stays editable"- );assert_eq!(- selection- .browse(&queue, "", QueueBrowseDirection::Older)- .as_deref(),- Some("Heartbeat prompt: nudge")- );- assert!(- selection.selected().unwrap().internal,- "the labeled heartbeat browses read-only"+ selection.browse(&queue, "", QueueBrowseDirection::Older),+ None);}diff --git a/crates/pa-tui/src/session_ui/queue.rs b/crates/pa-tui/src/session_ui/queue.rsindex 0862f43705..f22cf763d5 100644--- a/crates/pa-tui/src/session_ui/queue.rs+++ b/crates/pa-tui/src/session_ui/queue.rs@@ -1,7 +1,6 @@-//! Browsing, reordering, and editing the parked steering/follow-up messages. The browse walks every-//! parked item (the full queue stays inspectable), but the reorder/apply gates are user-origin only-//! (operator directive 2026-09-28: internal prompts render read-only — the system owns them); see-//! [`crate::queued::QueueSelectionItem::internal`].+//! Browsing, reordering, and editing the parked steering/follow-up messages. The browse walks the+//! user-typed items only (operator decision 2026-10-16): internal prompts are a separate channel,+//! shown only as the strip's condensed row.use super::{anyhow, AgentView, DaemonCommand, Duration, Map, QueueBrowseDirection, QueueLane, Result,SessionUi, Value, UI_REQUEST_TIMEOUT_MS,@@ -73,8 +72,9 @@ impl SessionUi {.map(str::to_string))}- /// Reorder the selected message one slot earlier/later in its lane; the move is mirrored- /// locally — the `session_action_update` event may land after the response.+ /// Swap the selected message with the adjacent user message in its lane (a silent no-op at the+ /// lane's first/last user message); the move is mirrored locally — the `session_action_update`+ /// event may land after the response.pub(crate) async fn move_queue_selection(&mut self,direction: i64,@@ -83,38 +83,34 @@ impl SessionUi {let Some(selected) = self.queue_selection.selected().cloned() else {return Ok(());};- // An internal item never reorders (a human reorder of a child-exit notice- // could mis-steer the agent); the selection stays for the read-only browse.- if selected.internal {- self.note("Internal prompts are read-only; reorder not applied", view);+ // Internal items keep their positions: the swap partner is the adjacent user item, so+ // the daemon's move direction spans any internal items between the two.+ let Some(target) = self.queue_selection.reorder_target(direction) else {return Ok(());- }+ };let status = self.queue_mutation(selected.lane,selected.index,&selected.text,- serde_json::json!({ "type": "move", "direction": direction }),+ serde_json::json!({ "type": "move", "direction": target as i64 - selected.index as i64 }),).await;match status {Ok(Some(status)) if status == "applied" => {self.emit_queue_edit("reorder");- let target = selected.index as i64 + direction;crate::queued::mirror_lane_move(&mut view.queued,selected.lane,selected.index,target,);- if target >= 0 {- self.queue_selection.refresh_at(- &view.queued,- selected.lane,- target as usize,- &selected.text,- );- }+ self.queue_selection.refresh_at(+ &view.queued,+ selected.lane,+ target,+ &selected.text,+ );self.sync_queue_selection(view);self.dirty = true;}@@ -138,19 +134,6 @@ impl SessionUi {let Some(selected) = self.queue_selection.selected().cloned() else {return Ok(());};- // An internal prompt is never steered, re-queued, or deleted through the browse (see the- // module doc). The refusal follows the failed-edit contract: the typed text stays in the- // editor, the note says why, the selection stays.- if selected.internal {- view.editor.set_text(text);- self.note(- "Internal prompts are read-only; edit kept in the editor",- view,- );- self.sync_queue_selection(view);- self.dirty = true;- return Ok(());- }let trimmed = text.trim();// `images` stays absent on a replace: the server keeps the item's// attachments (some markers cannot be resolved by this client).diff --git a/crates/pa-tui/src/view/tests.rs b/crates/pa-tui/src/view/tests.rsindex aff3cf0982..59f193835d 100644--- a/crates/pa-tui/src/view/tests.rs+++ b/crates/pa-tui/src/view/tests.rs@@ -253,8 +253,8 @@ fn hint_rows_carry_the_platform_alt_label() {v.queue_selected = Some(crate::queued::QueueSelectionItem {lane: crate::queued::QueueLane::Steering,index: 0,+ position: 0,text: "turn right".to_string(),- internal: false,});let frame = v.render_frame(80, 24);let joined = frame.iter().map(text_of).collect::<Vec<_>>().join("\n");@@ -1428,8 +1428,8 @@ fn browse_header_pair_sits_below_the_editor_top_row() {v.queue_selected = Some(crate::queued::QueueSelectionItem {lane: crate::queued::QueueLane::Steering,index: 0,+ position: 0,text: "turn right".to_string(),- internal: false,});let frame = v.render_frame(80, 24);let joined: Vec<String> = frame.iter().map(text_of).collect();diff --git a/scripts/review_draft_disconnect_parity.py b/scripts/review_draft_disconnect_parity.pyindex ca0bf43928..3404fcd127 100644--- a/scripts/review_draft_disconnect_parity.py+++ b/scripts/review_draft_disconnect_parity.py@@ -223,6 +223,10 @@ class Supervisor:self.thread = threading.Thread(target=self.accept, daemon=True)self.thread.start()+ def extra_command(self, command, response):+ """Subclass-owned protocol additions, handled before unknown-command errors."""+ return False+def send(self, sock, data):sock.sendall((json.dumps(data) + "\n").encode())@@ -408,6 +412,8 @@ class Supervisor:if not isinstance(command.get("enabled"), bool):raise RuntimeError("set_auto_compaction requires a boolean")response.pop("data", None)+ elif self.extra_command(command, response):+ passelse:self.errors.append(f"unexpected command: {name}")response.update(success=False, error=f"Unsupported fixture command: {name}")diff --git a/scripts/review_queue_browse_parity.py b/scripts/review_queue_browse_parity.pynew file mode 100644index 0000000000..e913e17f5e--- /dev/null+++ b/scripts/review_queue_browse_parity.py@@ -0,0 +1,233 @@+#!/usr/bin/env python3+"""Actual ordinary TS/Rust PTY queue browsing and mutation comparison.++Operator-requested delta: Rust visits only user rows and swaps with the adjacent+user row; TS visits every projected item. Full decoded styled frames and raw+ANSI are retained, without claiming layout equality. A protocol fixture controls+only the queue snapshot; both clients parse real input and construct mutations.+"""+import argparse+import copy+import json+import os+import select+from pathlib import Path+import subprocess+import sys+import tempfile+import time++from review_agent_bounce_parity import Client+from review_dock_screen import DockScreen+from review_draft_disconnect_parity import Supervisor, Terminal, digest, env_for, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish++USER_A, USER_B = 'QUEUE_BROWSE_USER_A', 'QUEUE_BROWSE_USER_B'+INTERNAL = 'Agent message received: QUEUE_BROWSE_INTERNAL'+DRAFT = 'QUEUE_BROWSE_DRAFT'+OLDER, NEWER, LATER = '\x1b[1;3A', '\x1b[1;3B', '\x1b[1;7B'+++def check_mutation(kind, command):+ expected = {'type': 'mutate_queued_message', 'activeSessionId': 's1',+ 'lane': 'steering', 'index': 0, 'expectedText': USER_A,+ 'mutation': {'type': 'move', 'direction': 1 if kind == 'ts' else 2}}+ # TS places its request ID inside the command as well as its envelope.+ # Retain that raw transport ID, compare only the addressed mutation here.+ if 'id' in command:+ assert isinstance(command['id'], str) and command['id'], command+ assert {key: value for key, value in command.items() if key != 'id'} == expected, command+++class QueueSupervisor(Supervisor):+ def __init__(self, path, hello, root, internal_only):+ self.queue = {'steering': [INTERNAL] if internal_only else [USER_A, INTERNAL, USER_B], 'followUp': []}+ self.mutations = []+ super().__init__(path, hello, 'queue-browse', root)++ def actions(self):+ return {'queuedCount': len(self.queue['steering']), 'steering': self.queue['steering'][:], 'followUps': []}++ def send(self, sock, data):+ data = copy.deepcopy(data)+ name = data.get('command')+ if data.get('type') == 'daemon_hello':+ # Advertise the actual queue-mutation protocol this subclass owns.+ # The shared draft-only server deliberately omits this capability.+ data['serverCapabilities'] = ['session_input_admission', 'queue_message_mutation']+ if data.get('type') == 'response':+ if name == 'attach':+ data['data']['snapshot']['state']['sessionActions'] = self.actions()+ elif name in ('get_state', 'get_connection_state'):+ data['data']['sessionActions'] = self.actions()+ super().send(sock, data)+++ def extra_command(self, command, response):+ name = command['type']+ if name == 'get_queue':+ response['data'] = copy.deepcopy(self.queue)+ return True+ if name != 'mutate_queued_message':+ return False+ assert command['lane'] == 'steering', command+ assert command['mutation']['type'] == 'move', command+ index = command['index']+ assert self.queue['steering'][index] == command['expectedText'], command+ target = index + command['mutation']['direction']+ assert 0 <= target < len(self.queue['steering']), command+ self.queue['steering'][index], self.queue['steering'][target] = self.queue['steering'][target], self.queue['steering'][index]+ self.mutations.append(copy.deepcopy(command))+ response['data'] = {'status': 'applied'}+ return True+++def discover_hello(binary, root, env, observed):+ path = root / 'hello.sock'+ scope = OwnedProcesses(binary, root, path)+ daemon = client = None+ with open(root / 'hello.log', 'wb') as log:+ try:+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, command)+ client = Client(path, daemon)+ hello = client.hello+ assert hello.get('schemaId'), hello+ assert 'queue_message_mutation' in hello.get('serverCapabilities', []), hello+ observed['hello'] = hello+ finally:+ finish(scope, client, daemon, observed)+ assert observed['cleanup_verified'], observed+ return hello+++def frame(terminal):+ return {'text': terminal.screen.text(), 'styles': terminal.screen.styles,+ 'unsupported_sgr': terminal.screen.unsupported_sgr[:],+ 'unsupported_terminal': terminal.screen.unsupported_terminal[:]}+++def observe(binary, kind, root, internal_only, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ hello_cleanup = observed['hello_discovery'] = {}+ hello = discover_hello(binary, root, env, hello_cleanup)+ server = QueueSupervisor(root / 'ui.sock', hello, root, internal_only)+ scope = OwnedProcesses(binary, root, server.path)+ terminal = None+ observed['frames'] = {}+ try:+ command = [str(binary), '--daemon-socket', str(server.path)]+ terminal = Terminal(command, root, env)+ terminal.screen = DockScreen()+ scope.register(terminal.process, command)+ def snap(label, predicate):+ terminal.wait(label, lambda: predicate(terminal.screen.text()), server)+ observed['frames'][label] = copy.deepcopy(frame(terminal))+ snap('initial', lambda text: server.attaches > 0 and (INTERNAL in text if kind == 'ts' else '1 agent message' in text))+ terminal.send(DRAFT)+ snap('draft', lambda text: DRAFT in text)+ if internal_only:+ if kind == 'rust':+ assert 'to browse and edit queued messages' not in terminal.screen.text()+ terminal.send(OLDER)+ if kind == 'rust':+ # The next typed character is an input-order barrier: Alt+Up was+ # handled before this character, so no absence-by-sleep assertion.+ terminal.send('_BARRIER')+ snap('internal_only_input', lambda text: DRAFT + '_BARRIER' in text)+ assert 'enter steers' not in terminal.screen.text()+ else:+ snap('internal_only_input', lambda text: 'steering 1' in text and 'enter steers' in text)+ else:+ terminal.send(OLDER)+ snap('newest', lambda text: ('steering 3' if kind == 'ts' else 'steering 2') in text and 'enter steers' in text)+ terminal.send(OLDER)+ snap('older', lambda text: ('steering 2' if kind == 'ts' else 'steering 1') in text and 'enter steers' in text)+ terminal.send(OLDER)+ if kind == 'ts':+ snap('oldest', lambda text: 'steering 1' in text and 'enter steers' in text)+ else:+ # At the oldest boundary, an input barrier proves the no-op was+ # processed; restore text so the reorder expectedText stays original.+ terminal.send('_BARRIER')+ snap('oldest', lambda text: USER_A + '_BARRIER' in text)+ terminal.send('\x7f' * len('_BARRIER'))+ snap('oldest_restored', lambda text: USER_A + '_BARRIER' not in text and 'steering 1' in text)+ terminal.send(LATER)+ terminal.wait('reorder command', lambda: len(server.mutations) == 1, server)+ check_mutation(kind, server.mutations[0])+ snap('reordered', lambda text: ('steering 2' if kind == 'ts' else 'steering 2') in text and 'enter steers' in text)+ expected = [INTERNAL, USER_A, USER_B] if kind == 'ts' else [USER_B, INTERNAL, USER_A]+ assert server.queue == {'steering': expected, 'followUp': []}, server.queue+ assert not server.prompts, 'browse submitted a prompt'+ assert not terminal.screen.unsupported_sgr and not terminal.screen.unsupported_terminal, 'unsupported terminal sequences'+ observed['behavior_verified'] = True+ finally:+ try:+ if terminal:+ if terminal.process.poll() is None:+ terminal.send('\x03\x03')+ deadline = time.monotonic() + 8+ while terminal.process.poll() is None and time.monotonic() < deadline:+ terminal.pump()+ # Drain already-readable final output after process exit too.+ while select.select([terminal.master], [], [], 0)[0]:+ before = len(terminal.raw)+ terminal.pump()+ if len(terminal.raw) == before:+ break # PTY EOF remains readable.+ observed['raw_ansi_complete_hex'] = bytes(terminal.raw).hex()+ observed['ui_exit_code'] = terminal.process.poll()+ # Do not call the older Terminal.close() force-stop helper.+ # Strict cleanup observes graceful exit or leaves this case RED.+ os.close(terminal.master)+ finally:+ try:+ server.close()+ finally:+ observed['commands'] = server.commands+ observed['mutations'] = server.mutations+ observed['queue_after'] = server.queue+ observed['fixture_errors'] = server.errors+ finish(scope, None, None, observed)+ assert observed['cleanup_verified'], observed+ assert not server.errors, server.errors+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', required=True, type=Path)+ args = parser.parse_args()+ receipt = {'verified': False, 'scope': __doc__, 'runs': {},+ 'not_verified': ['real daemon queue admission (separate queue_priority fixture)',+ 'pixel/font equality', 'delete/replace/attachments', 'wire-typed child and continuation riders (Rust units)']}+ try:+ assert sys.platform == 'linux', 'hosted Linux only'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'reference archive mismatch'+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-qbrowse-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ for internal_only in (False, True):+ label = kind + ('_internal_only' if internal_only else '_mixed')+ observed = receipt['runs'][label] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / label, internal_only, observed)+ except Exception as error:+ observed['error'] = str(error)+ assert all(run.get('behavior_verified') and run.get('cleanup_verified') and 'error' not in run+ for run in receipt['runs'].values()), 'actual PTY comparison failed'+ receipt['verified'] = True+ except Exception as error:+ receipt['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2))+ print(json.dumps({'verified': receipt['verified'], 'error': receipt.get('error')}))+ return 0 if receipt['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/test_review_queue_browse_parity.py b/scripts/test_review_queue_browse_parity.pynew file mode 100644index 0000000000..3a408f4020--- /dev/null+++ b/scripts/test_review_queue_browse_parity.py@@ -0,0 +1,42 @@+import unittest+from review_queue_browse_parity import check_mutation, QueueSupervisor, USER_A, USER_B, INTERNAL+++class QueueBrowseGuardTest(unittest.TestCase):+ def command(self, direction):+ return {'type': 'mutate_queued_message', 'activeSessionId': 's1', 'lane': 'steering',+ 'index': 0, 'expectedText': USER_A, 'mutation': {'type': 'move', 'direction': direction}}++ def test_compares_actual_mutation_target_with_explicit_ts_delta(self):+ check_mutation('ts', {**self.command(1), 'id': 'actual-transport-request'})+ check_mutation('rust', self.command(2))+ with self.assertRaises(AssertionError):+ check_mutation('rust', self.command(1))+ with self.assertRaises(AssertionError):+ check_mutation('ts', self.command(2))++ def test_rejects_wrong_source_lane_text_or_index(self):+ for field, value in [('lane', 'followUp'), ('index', 1), ('expectedText', 'wrong')]:+ command = self.command(2)+ command[field] = value+ with self.assertRaises(AssertionError):+ check_mutation('rust', command)+++ def test_subclass_handles_its_commands_without_transient_transport_errors(self):+ server = QueueSupervisor.__new__(QueueSupervisor)+ server.queue = {'steering': [USER_A, INTERNAL, USER_B], 'followUp': []}+ server.mutations, server.errors = [], []+ response = {'success': True, 'data': {}}+ self.assertTrue(server.extra_command({'type': 'get_queue'}, response))+ self.assertEqual(response['data'], server.queue)+ self.assertIsNot(response['data']['steering'], server.queue['steering'])+ self.assertTrue(server.extra_command(self.command(2), response))+ self.assertEqual(response['data'], {'status': 'applied'})+ self.assertEqual(server.queue, {'steering': [USER_B, INTERNAL, USER_A], 'followUp': []})+ self.assertEqual(server.errors, [])+ self.assertFalse(server.extra_command({'type': 'unsupported'}, response))+++if __name__ == '__main__':+ unittest.main()