A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
perf(pa-tui): drive the subagent dock from its events, not every wake (#3611)
Sebastian Müller527ba0aa21e6
diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rsindex adc5ee14c6..09bf3b86a0 100644--- a/crates/pa-tui/src/agents_view_forest/tests.rs+++ b/crates/pa-tui/src/agents_view_forest/tests.rs@@ -805,7 +805,7 @@ fn an_active_query_ranks_hits_globally_ancestors_sink_last() {let by_name = |name: &str| {filtered.iter()- .find(|record| record.search.name == name)+ .find(|record| crate::agents_view_state::record_search_text(record).name == name).unwrap_or_else(|| panic!("missing record {name}"))};assert!(by_name("policy sweep").search_score.is_some());diff --git a/crates/pa-tui/src/agents_view_state.rs b/crates/pa-tui/src/agents_view_state.rsindex 6e2dcd416a..76b5d75166 100644--- a/crates/pa-tui/src/agents_view_state.rs+++ b/crates/pa-tui/src/agents_view_state.rs@@ -58,9 +58,6 @@ pub struct UnifiedRecord {/// Every key this record is reachable by (selection survival).pub aliases: Vec<String>,pub section: Section,- /// The picker's match targets: the SESSION column's title, the- /// durable session id, and the cwd (see `agents_view_search`).- pub search: SessionSearchText,/// The query-relevance score behind the ranked list (lower is better);/// `None` for retained ancestors and unqueried rosters.pub search_score: Option<f64>,@@ -154,7 +151,7 @@ fn session_search_name(summary: &Value) -> String {/// The picker targets of one unified record: the SESSION column's own title as the name target,/// plus the durable session id and the cwd. Daemon data wins; a saved row fills the gaps.-fn record_search_text(record: &UnifiedRecord) -> SessionSearchText {+pub(crate) fn record_search_text(record: &UnifiedRecord) -> SessionSearchText {let summary = summary_for_record(record);let pick = |daemon: Option<&str>, saved: Option<&str>| {daemon@@ -208,18 +205,15 @@ pub fn reconcile_unified_sessions(roster: &[Value], saved: &[Value]) -> Vec<Uniffor alias in &aliases {by_alias.insert(alias.clone(), index);}- let mut record = UnifiedRecord {+ let record = UnifiedRecord {daemon: Some(summary),saved: None,status,identity,aliases,section,- search: SessionSearchText::default(),search_score: None,};- let search = record_search_text(&record);- record.search = search;records.push(record);}@@ -242,26 +236,21 @@ pub fn reconcile_unified_sessions(roster: &[Value], saved: &[Value]) -> Vec<Unif}by_alias.insert(alias.clone(), index);}- let search = record_search_text(record);- record.search = search;continue;}let index = records.len();for alias in &aliases {by_alias.insert(alias.clone(), index);}- let mut record = UnifiedRecord {+ let record = UnifiedRecord {daemon: None,saved: Some(row.clone()),status: None,identity,aliases,section: Section::Inactive,- search: SessionSearchText::default(),search_score: None,};- let search = record_search_text(&record);- record.search = search;records.push(record);}records@@ -484,7 +473,7 @@ pub fn filter_unified_sessions(for index in 0..records.len() {// Every directly matching record carries its score, even one// already retained as an ancestor of an earlier hit.- let Some(score) = score_search(&records[index].search, query) else {+ let Some(score) = score_search(&record_search_text(&records[index]), query) else {continue;};scores[index] = Some(score);@@ -706,8 +695,8 @@ mod tests {assert_eq!(records.len(), 1);assert_eq!(records[0].section, Section::Idle);assert_eq!(records[0].identity, "file:/x/s1.jsonl");- assert_eq!(records[0].search.name, "Bug fix");- assert_eq!(records[0].search.id, "s1");+ assert_eq!(record_search_text(&records[0]).name, "Bug fix");+ assert_eq!(record_search_text(&records[0]).id, "s1");let summary = summary_for_record(&records[0]);assert_eq!(summary["firstMessage"], "fix the bug");assert_eq!(summary["sessionName"], "Bug fix");@@ -874,17 +863,17 @@ mod tests {"parentSessionPath": "/x/parent.jsonl",})];let records = reconcile_unified_sessions(&[], &saved);- let targets = &records[0].search;+ let targets = record_search_text(&records[0]);for query in ["alpha", "roster", "ROSTER", "api-server", "sess-al"] {let parsed = parse_search_query(query);assert!(- score_search(targets, &parsed).is_some(),+ score_search(&targets, &parsed).is_some(),"query {query:?} should match the restricted corpus");}// Partial words need the fuzzy path on the name (ordered// subsequence).- assert!(score_search(targets, &parse_search_query("rtwr")).is_some());+ assert!(score_search(&targets, &parse_search_query("rtwr")).is_some());// Content fields are gone from the picker: first messages, the capped transcript, and// file paths never match.for query in [@@ -898,7 +887,7 @@ mod tests {] {let parsed = parse_search_query(query);assert!(- score_search(targets, &parsed).is_none(),+ score_search(&targets, &parsed).is_none(),"query {query:?} must not match content or path fields");}@@ -928,11 +917,12 @@ mod tests {assert_eq!(records.len(), 1);// Daemon data wins for the merged targets; the saved transcript// stays out of the corpus.- assert_eq!(records[0].search.name, "tuned retry policy");- assert_eq!(records[0].search.id, "s1");- assert_eq!(records[0].search.cwd, "/work/retry");- assert!(score_search(&records[0].search, &parse_search_query("retry")).is_some());- assert!(score_search(&records[0].search, &parse_search_query("backoff")).is_none());+ let targets = record_search_text(&records[0]);+ assert_eq!(targets.name, "tuned retry policy");+ assert_eq!(targets.id, "s1");+ assert_eq!(targets.cwd, "/work/retry");+ assert!(score_search(&targets, &parse_search_query("retry")).is_some());+ assert!(score_search(&targets, &parse_search_query("backoff")).is_none());}#[test]@@ -1120,7 +1110,7 @@ mod tests {}),)];let records = reconcile_unified_sessions(&roster, &[]);- assert_eq!(records[0].search.name, "hey");+ assert_eq!(record_search_text(&records[0]).name, "hey");for query in ["hey", "HEY", "Hey"] {let filtered = filter_unified_sessions(&records, &parse_search_query(query));assert_eq!(@@ -1156,18 +1146,15 @@ mod tests {let records = reconcile_unified_sessions(&roster, &[]);let title = session_title(&summary_for_record(&records[0]));let visible = truncate_text(&title, SESSION_TITLE_MAX_CELLS);- assert_eq!(records[0].search.name, visible);+ let targets = record_search_text(&records[0]);+ assert_eq!(targets.name, visible);assert!(- score_search(- &records[0].search,- &parse_search_query("agents view search")- )- .is_some(),+ score_search(&targets, &parse_search_query("agents view search")).is_some(),"the visible title head matches");for query in ["backoff ceiling", "queue lane", "CI is red"] {assert!(- score_search(&records[0].search, &parse_search_query(query)).is_none(),+ score_search(&targets, &parse_search_query(query)).is_none(),"{query:?} lives past the column clip and must not match");}@@ -1209,14 +1196,19 @@ mod tests {"firstMessage": "orchestrate the fleet", "messageCount": 2,})];let records = reconcile_unified_sessions(&roster, &saved);- assert_eq!(records[0].search.name, "gateway worker");- assert_eq!(records[1].search.name, "deploy the gateway now");- assert_eq!(records[2].search.name, "gateway");- assert_eq!(records[3].search.name, "orchestrate the fleet");+ let names: Vec<String> = records+ .iter()+ .map(record_search_text)+ .map(|targets| targets.name)+ .collect();+ assert_eq!(names[0], "gateway worker");+ assert_eq!(names[1], "deploy the gateway now");+ assert_eq!(names[2], "gateway");+ assert_eq!(names[3], "orchestrate the fleet");for record in &records {let title = session_title(&summary_for_record(record));assert_eq!(- record.search.name,+ record_search_text(record).name,truncate_text(&title, SESSION_TITLE_MAX_CELLS),"the corpus equals the SESSION column's title");@@ -1237,14 +1229,15 @@ mod tests {}),)];let records = reconcile_unified_sessions(&roster, &[]);- assert_eq!(records[0].search.name, "gateway worker");+ let targets = record_search_text(&records[0]);+ assert_eq!(targets.name, "gateway worker");assert!(- score_search(&records[0].search, &parse_search_query("gateway")).is_some(),+ score_search(&targets, &parse_search_query("gateway")).is_some(),"the name still matches");for query in ["deploy", "backoff", "flaky"] {assert!(- score_search(&records[0].search, &parse_search_query(query)).is_none(),+ score_search(&targets, &parse_search_query(query)).is_none(),"{query:?} lives in the first prompt, not the displayed title");}diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex 13264e256d..cf14a570d5 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -1930,8 +1930,6 @@ async fn run_interactive_surface(}}- session.sync_goal_tray(&mut view);-// Spinner animation: the wall clock drives the phase, not the render rate — the frame gate// below caps renders, and only a phase change dirties the frame.let animating = session.turn_activediff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rsindex 6f0a14adf7..c96b78b27b 100644--- a/crates/pa-tui/src/session_ui/lifecycle.rs+++ b/crates/pa-tui/src/session_ui/lifecycle.rs@@ -626,7 +626,6 @@ impl SessionUi {view.queue_selected = None;view.chrome.chat_name = self.session_display();view.chrome.context = self.context;- self.update_subagent_summary(view);// The rebuilt transcript invalidates the announcement row tracking;// the goal state itself carries over (seeded at attach).self.goal_view.reset_row_tracking();diff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rsindex cdd6c827a7..54b42ff6bc 100644--- a/crates/pa-tui/src/session_ui/panels.rs+++ b/crates/pa-tui/src/session_ui/panels.rs@@ -248,6 +248,7 @@ impl SessionUi {self.open_scoped_agents_view(view);} else {self.subagents_focused = false;+ self.update_subagent_summary(view);self.note("The agents view needs a daemon-hosted session; start normally (without --no-session) to browse sessions",view,diff --git a/crates/pa-tui/src/subagents.rs b/crates/pa-tui/src/subagents.rsindex 49789aaf58..5454beb27b 100644--- a/crates/pa-tui/src/subagents.rs+++ b/crates/pa-tui/src/subagents.rs@@ -229,25 +229,6 @@ pub fn descendant_positions_with_depth(positions}-/// The descendant positions of `parent`, depth-free (the flat-/// consumers).-#[must_use]-pub fn descendant_positions(summaries: &[&Value], parent: &SessionIdentity) -> Vec<usize> {- descendant_positions_with_depth(summaries, parent)- .into_iter()- .map(|(position, _)| position)- .collect()-}--/// The summaries that descend from `parent`.-#[must_use]-pub fn descendant_rows<'a>(summaries: &[&'a Value], parent: &SessionIdentity) -> Vec<&'a Value> {- descendant_positions(summaries, parent)- .into_iter()- .map(|position| summaries[position])- .collect()-}-/// The roster entries that descend from `parent`, with each entry's/// depth below it (1 = a direct child).///@@ -273,15 +254,6 @@ pub fn descendant_entries_with_depth<'a>(.collect()}-/// The roster entries that descend from `parent`.-#[must_use]-pub fn descendant_entries<'a>(roster: &'a [Value], parent: &SessionIdentity) -> Vec<&'a Value> {- descendant_entries_with_depth(roster, parent)- .into_iter()- .map(|(entry, _)| entry)- .collect()-}-/// The roster status of one entry: the supervisor's classification,/// with the shared formula as the fallback (TS `rosterStatus ??/// classifySessionRosterStatus`).diff --git a/crates/pa-tui/tests/dock_arrows_headless.rs b/crates/pa-tui/tests/dock_arrows_headless.rsindex d131cc1f8f..916456f484 100644--- a/crates/pa-tui/tests/dock_arrows_headless.rs+++ b/crates/pa-tui/tests/dock_arrows_headless.rs@@ -2,6 +2,8 @@//! directive 2026-09-26): every rendered section is one press away in//! both directions (empty sections visited, cycle wraps), and entering//! opens its view; the TS dock has no section traversal (Rust divergence).+//! The event-driven pins below hold the dock's update contract: every dock+//! input repaints on its own daemon event, never on a per-wake recompute.#![cfg(unix)]// Casts: structurally bounded terminal-layout arithmetic; guarded conversions add panic paths.#![allow(@@ -39,14 +41,28 @@ struct MockSupervisor {/// The live `goal_update` event to serve on attach (`None` mounts no goal row — the all-zero/// dock).goal: Option<Value>,+ /// Successive `roster_subscribe` snapshots, one per attach; an exhausted list keeps serving+ /// the last one, and an empty list serves the empty roster.+ roster: Vec<Value>,+ /// Live frames to push right after the `roster_subscribe` response (the events the dock pins+ /// drive): each attach re-sends them.+ pushes: Vec<Value>,}impl MockSupervisor {- fn bind(socket: &std::path::Path, heartbeats: Option<Value>, goal: Option<Value>) -> Self {+ fn bind(+ socket: &std::path::Path,+ heartbeats: Option<Value>,+ goal: Option<Value>,+ roster: Vec<Value>,+ pushes: Vec<Value>,+ ) -> Self {MockSupervisor {listener: UnixListener::bind(socket).expect("bind mock socket"),heartbeats,goal,+ roster,+ pushes,}}@@ -82,6 +98,7 @@ impl MockSupervisor {write_json(&mut writer, &hello);let mut line = String::new();+ let mut subscribe = 0usize;loop {line.clear();match reader.read_line(&mut line) {@@ -134,6 +151,28 @@ impl MockSupervisor {}),);}+ "roster_subscribe" => {+ let snapshot = self+ .roster+ .get(subscribe)+ .or_else(|| self.roster.last())+ .cloned()+ .unwrap_or_else(|| json!({}));+ subscribe += 1;+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "roster_subscribe",+ "success": true,+ "data": snapshot,+ }),+ );+ for frame in &self.pushes {+ write_json(&mut writer, frame);+ }+ }_ => {write_json(&mut writer,@@ -305,13 +344,25 @@ fn run_plan(steps: Vec<HeadlessStep>,heartbeats: Option<Value>,goal: Option<Value>,+) -> pa_tui::interactive::InteractiveOutcome {+ run_plan_with_roster(steps, heartbeats, goal, Vec::new(), Vec::new())+}++/// `run_plan` plus the `roster_subscribe` snapshots and the live frames pushed after each+/// subscription reply (the event-driven dock pins' mock surface).+fn run_plan_with_roster(+ steps: Vec<HeadlessStep>,+ heartbeats: Option<Value>,+ goal: Option<Value>,+ roster: Vec<Value>,+ pushes: Vec<Value>,) -> pa_tui::interactive::InteractiveOutcome {// The ambient TMUX variable adds a startup notice; scrub it so runs are 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::bind(&socket, heartbeats, goal);+ let supervisor = MockSupervisor::bind(&socket, heartbeats, goal, roster, pushes);let handle = std::thread::spawn(move || supervisor.serve());let runtime = tokio::runtime::Builder::new_multi_thread()@@ -540,3 +591,171 @@ fn an_all_zero_dock_renders_and_opens_the_empty_scoped_agents_view() {}));}++/// The attached session's own roster row: the family root the title cost bills.+fn parent_row() -> Value {+ json!({+ "agentId": "s1",+ "status": "idle",+ "summary": {+ "sessionId": "sess-1",+ "activeSessionId": "s1",+ "sessionFile": "/tmp/sess-1.jsonl",+ "lifecycle": "live",+ "runtimeKind": "top-level",+ },+ })+}++/// One direct subagent of the attached session: the dock's running count and the family cost.+fn child_row(id: &str, status: &str, cost: f64) -> Value {+ json!({+ "agentId": id,+ "status": status,+ "summary": {+ "sessionId": format!("{id}-sess"),+ "activeSessionId": format!("{id}-live"),+ "sessionFile": format!("/tmp/{id}.jsonl"),+ "lifecycle": "live",+ "runtimeKind": "subagent",+ "parentActiveSessionId": "s1",+ "usage": { "cost": cost },+ },+ })+}++/// One `roster_update` push (the supervisor's live roster deltas).+fn roster_push(changed: &[Value]) -> Value {+ json!({ "type": "roster_update", "changed": changed, "removed": [], "resync": false })+}++/// The `roster_subscribe` snapshot reply's data object.+fn roster_snapshot(rows: &[Value]) -> Value {+ json!({ "roster": rows })+}++/// One `goal_update` session event that starts pursuing a goal.+fn goal_event_push(seconds: u64) -> Value {+ json!({+ "type": "session_event",+ "activeSessionId": "s1",+ "event": {+ "type": "goal_update",+ "goal": {+ "active": true,+ "status": "active",+ "goalId": "g-dock",+ "objective": "ship the event-driven dock",+ "tokensUsed": 0,+ "timeUsedSeconds": seconds,+ "continuationsUsed": 0,+ },+ },+ })+}++/// The dock's event-driven update contract, pinned ahead of the run loop's per-wake recompute+/// removal: a `roster_update` push alone repaints the running count and the title's family cost.+#[test]+fn a_roster_push_alone_remounts_the_dock_count_and_the_title_cost() {+ let steps = vec![+ HeadlessStep::WaitRender {+ needle: "\u{25c6} 1 subagents".to_string(),+ timeout_ms: 5_000,+ },+ HeadlessStep::WaitRender {+ needle: "$0.42".to_string(),+ timeout_ms: 5_000,+ },+ ];+ let pushes = vec![roster_push(&[+ parent_row(),+ child_row("c1", "running", 0.42),+ ])];+ let outcome = run_plan_with_roster(steps, None, None, Vec::new(), pushes);+ let last = outcome.frames.last().cloned().unwrap_or_default();+ assert!(+ last.contains("\u{25c6} 1 subagents") && last.contains("$0.42"),+ "the roster push repainted the dock's running count and the title's family cost:\n{}",+ outcome.frames.join("\n")+ );+}++/// A `goal_update` event alone mounts the dock's goal row.+#[test]+fn b_a_goal_update_alone_mounts_the_dock_goal_row() {+ let steps = vec![HeadlessStep::WaitRender {+ needle: "shells \u{b7} Pursuing goal (12s)".to_string(),+ timeout_ms: 5_000,+ }];+ let pushes = vec![goal_event_push(12)];+ let outcome = run_plan_with_roster(steps, None, None, Vec::new(), pushes);+ let last = outcome.frames.last().cloned().unwrap_or_default();+ assert!(+ last.contains("shells \u{b7} Pursuing goal (12s)"),+ "the goal update mounted the dock's goal row:\n{}",+ outcome.frames.join("\n")+ );+}++/// A child's settle — the roster push flipping it running to idle — drops the dock's running count+/// on its own event.+#[test]+fn c_a_child_settle_alone_drops_the_dock_running_count() {+ let steps = vec![HeadlessStep::WaitRender {+ needle: "\u{25c6} 0 subagents".to_string(),+ timeout_ms: 5_000,+ }];+ let roster = vec![roster_snapshot(&[+ parent_row(),+ child_row("c1", "running", 0.42),+ ])];+ let pushes = vec![roster_push(&[child_row("c1", "idle", 0.42)])];+ let outcome = run_plan_with_roster(steps, None, None, roster, pushes);+ let last = outcome.frames.last().cloned().unwrap_or_default();+ assert!(+ last.contains("\u{25c6} 0 subagents"),+ "the settle push dropped the dock's running count:\n{}",+ outcome.frames.join("\n")+ );+}++/// The attach fold: the `roster_subscribe` snapshot's running counts mount in the open's FIRST+/// frame, and a session switch's fresh snapshot re-mounts them in the switch's first rebuilt+/// frame — the counts follow the newly attached session.+#[test]+fn d_the_attach_mounts_the_snapshot_counts_in_its_first_frame_and_a_switch_follows() {+ let steps = vec![+ HeadlessStep::WaitRender {+ needle: "\u{25c6} 2 subagents".to_string(),+ timeout_ms: 5_000,+ },+ HeadlessStep::Submit("/new".to_string()),+ HeadlessStep::WaitRender {+ needle: "\u{25c6} 1 subagents".to_string(),+ timeout_ms: 5_000,+ },+ ];+ let roster = vec![+ roster_snapshot(&[+ parent_row(),+ child_row("c1", "running", 0.42),+ child_row("c2", "running", 0.1),+ ]),+ roster_snapshot(&[parent_row(), child_row("c1", "running", 0.42)]),+ ];+ let outcome = run_plan_with_roster(steps, None, None, roster, Vec::new());+ let first_count = outcome+ .frames+ .iter()+ .position(|frame| frame.contains("\u{25c6} 1 subagents"));+ let first_note = outcome+ .frames+ .iter()+ .position(|frame| frame.contains("started session s1"));+ assert!(+ matches!((first_count, first_note), (Some(count), Some(note)) if count <= note),+ "the switch's first rebuilt frame carries the new snapshot's counts:\n{}",+ outcome.frames.join("\n")+ );+}diff --git a/scripts/review_dock_events_parity.py b/scripts/review_dock_events_parity.pynew file mode 100644index 0000000000..1ce29771a2--- /dev/null+++ b/scripts/review_dock_events_parity.py@@ -0,0 +1,267 @@+#!/usr/bin/env python3+"""Hosted actual TS/Rust TUI dock reactions, styled frames and raw ANSI.++Both ordinary clients receive controlled protocol-7 roster/goal events after+observable attach. No headless flags, provider or live sessions are used. The+receipt records full-frame differences instead of normalizing TS's boxed dock+into Rust's one-line dock. Behavioral assertions cover event-driven refresh;+full-frame/style equality is reported separately and never claimed by them.+"""+import argparse+import json+import os+import re+from pathlib import Path+import sys+import tempfile+import threading++from review_dock_screen import DockScreen+from review_draft_disconnect_parity import (+ Supervisor, Terminal, actual_hello, digest, env_for, TS_ARCHIVE_SHA256,+)+++def parent():+ return {'agentId': 's1', 'status': 'idle', 'summary': {+ 'sessionId': 'fixture-durable', 'activeSessionId': 's1', 'sessionFile': '/fixture/root.jsonl',+ 'lifecycle': 'live', 'runtimeKind': 'top-level', 'usage': {'cost': 0}}}+++def child(ident, status, cost):+ return {'agentId': ident, 'status': status, 'summary': {+ 'sessionId': ident + '-durable', 'activeSessionId': ident + '-active',+ 'sessionFile': '/fixture/' + ident + '.jsonl', 'sessionName': ident,+ 'lifecycle': 'live', 'runtimeKind': 'subagent', 'parentActiveSessionId': 's1',+ 'parentSessionPath': '/fixture/root.jsonl', 'usage': {'cost': cost},+ 'activity': 'working' if status == 'running' else 'idle',+ 'isSessionActive': status == 'running'}}+++def usage(cost):+ return {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'totalTokens': 0,+ 'cost': {'input': 0, 'output': cost, 'cacheRead': 0, 'cacheWrite': 0, 'total': cost}}+++class DockSupervisor(Supervisor):+ def __init__(self, path, hello, root):+ assert 'agent_roster' in hello.get('serverCapabilities', []), 'actual binary does not advertise roster protocol'+ self.roster = [parent(), child('c1', 'running', 0.42)]+ self.write_lock = threading.Lock()+ self.emitted = []+ self.context_responses = []+ super().__init__(path, hello, 'dock', root)++ def send(self, sock, data):+ if data.get('type') == 'daemon_hello':+ # The inherited draft fixture advertises only prompt admission.+ # This fixture also implements roster snapshot/deltas; TS gates+ # both on agent_roster (pinned daemon-protocol.ts:798,1214).+ data = dict(data, serverCapabilities=['session_input_admission', 'agent_roster'])+ elif data.get('type') == 'response' and data.get('command') == 'roster_subscribe':+ data = dict(data, data={'roster': self.roster})+ elif data.get('type') == 'response' and data.get('command') == 'attach':+ data['data']['snapshot']['state']['sessionName'] = 'Dock fixture'+ data['data']['snapshot']['summary'].update(sessionId='fixture-durable',+ activeSessionId='s1', sessionFile='/fixture/root.jsonl', sessionName='Dock fixture')+ elif data.get('type') == 'response' and data.get('command') == 'get_context_tree':+ # TS's top bar reads the context tree, whereas Rust reads roster+ # usage. Both protocol views must describe the same fixture family.+ children = [{+ 'id': row['summary']['sessionId'], 'label': row['agentId'],+ 'status': 'active' if row['status'] == 'running' else 'completed',+ 'ownUsage': usage(row['summary']['usage']['cost']),+ 'totalUsage': usage(row['summary']['usage']['cost']), 'children': []}+ for row in self.roster if row['agentId'] != 's1']+ data = dict(data, data={'id': 'root', 'label': 'Dock fixture', 'status': 'active',+ 'ownUsage': usage(0), 'totalUsage': usage(sum(+ node['totalUsage']['cost']['total'] for node in children)), 'children': children})+ self.context_responses.append(data)+ with self.write_lock:+ super().send(sock, data)++ def emit(self, frame):+ self.emitted.append(frame)+ # These are ordinary broadcast events, not prompt replies or key input.+ for sock in list(self.sockets):+ try:+ self.send(sock, frame)+ except (BrokenPipeError, OSError):+ pass # A closed startup discovery connection is not a subscriber.++ def roster_delta(self, changed, removed=(), resync=False):+ if resync:+ self.roster = []+ rows = {row['agentId']: row for row in self.roster}+ rows.update({row['agentId']: row for row in changed})+ for ident in removed:+ rows.pop(ident, None)+ self.roster = list(rows.values())+ self.emit({'type': 'roster_update', 'changed': changed, 'removed': list(removed), 'resync': resync})++ def goal(self, status):+ self.emit({'type': 'session_event', 'activeSessionId': 's1', 'event': {+ 'type': 'goal_update', 'goal': {'active': True, 'status': status,+ 'goalId': 'dock-goal', 'objective': 'Dock fixture objective', 'tokensUsed': 0,+ 'timeUsedSeconds': 12, 'continuationsUsed': 0}}})+++def running_visible(text, kind, count):+ label = 'running' if kind == 'ts' else 'subagents'+ return re.search(r'(?<!\d)' + str(count) + r'\s+' + label + r'\b', text) is not None+++def ts_dock_visible(text):+ # The actual TS dock header, not an arbitrary occurrence of "subagents":+ # its optional-ripgrep startup warning mentions that word after removal.+ return re.search(r'^\s*╭─\s+subagents\b', text, re.MULTILINE) is not None+++def visible_cost(text):+ costs = re.findall(r'\$(\d+\.\d{2})(?!\d)', text)+ assert len(costs) == 1, 'fixture frame must paint one unambiguous title cost'+ return costs[0]+++def cost_ready(text, expected):+ try:+ return visible_cost(text) == expected+ except AssertionError:+ return False # A partial repaint is not a completed frame.+++def capture(terminal, root, offset):+ return {'text': terminal.screen.text().replace(str(root), '<fixture-root>'),+ 'dock_styled_rows': terminal.screen.dock_styles(),+ 'raw_ansi_since_previous_hex': bytes(terminal.raw[offset:]).hex(),+ 'unsupported_sgr': terminal.screen.unsupported_sgr.copy(),+ 'keyboard_controls': terminal.screen.keyboard_controls.copy(),+ 'unsupported_terminal': terminal.screen.unsupported_terminal.copy()}+++def run_case(binary, kind, root, observed):+ root.mkdir()+ env = env_for(root, kind)+ hello = actual_hello(binary, root, env)+ server = DockSupervisor(root / 'fixture.sock', hello, root)+ terminal = None+ observed['frames'] = {}+ offset = 0+ try:+ terminal = Terminal([str(binary), '--daemon-socket', str(server.path)], root, env)+ terminal.screen = DockScreen()+ def snap(name, predicate):+ nonlocal offset+ terminal.wait(name, lambda: predicate(terminal.screen.text()), server)+ # Require two unchanged captures of the affected dock attributes;+ # this is observable frame readiness rather than a fixed sleep.+ previous = terminal.screen.dock_styles()+ stable = [0]+ def ready():+ nonlocal previous+ current = terminal.screen.dock_styles()+ stable[0] = stable[0] + 1 if current == previous else 0+ previous = current+ return stable[0] >= 2 and predicate(terminal.screen.text())+ terminal.wait(name + ' stable dock', ready, server)+ observed['frames'][name] = capture(terminal, root, offset)+ offset = len(terminal.raw)+ snap('snapshot', lambda text: server.attaches >= 1 and running_visible(text, kind, 1) and '$0.42' in text)+ server.roster_delta([child('c2', 'running', 0.49)])+ # Pinned TS refreshTopBarCost fetches on initial bind/turn-end/status,+ # not roster-only updates (interactive-mode.ts:1899,5771,6326). Do not+ # invent a turn-end event to make its cached title match Rust's live one.+ ts_cached_cost = '0.42'+ snap('roster_added', lambda text: running_visible(text, kind, 2)+ and cost_ready(text, ts_cached_cost if kind == 'ts' else '0.91'))+ server.goal('active')+ snap('goal_active', lambda text: 'Pursuing goal (12s)' in text)+ before_focus = terminal.screen.dock_styles()+ terminal.send('\x1b[B') # Same ordinary Down key from an empty editor.+ terminal.wait('dock focus changes rendered attributes',+ lambda: terminal.screen.dock_styles() != before_focus, server)+ snap('dock_focused', lambda text: running_visible(text, kind, 2))+ assert observed['frames']['dock_focused']['dock_styled_rows'] != before_focus+ terminal.send('\x1b')+ terminal.wait('Escape restores editor focus', lambda: terminal.screen.dock_styles() == before_focus, server)+ terminal.send('DOCK_EDITOR_FOCUS_PROBE')+ snap('editor_restored', lambda text: 'DOCK_EDITOR_FOCUS_PROBE' in text)+ terminal.send('\x15') # Clear draft without submitting a prompt.+ terminal.wait('draft cleared', lambda: 'DOCK_EDITOR_FOCUS_PROBE' not in terminal.screen.text(), server)+ server.roster_delta([child('c1', 'idle', 0.42)], removed=['c2'])+ snap('child_settled', lambda text: running_visible(text, kind, 0) and '$0.42' in text)+ server.roster_delta([], removed=['c1'])+ snap('child_removed', lambda text: cost_ready(text, ts_cached_cost if kind == 'ts' else '0.00')+ and (not ts_dock_visible(text) if kind == 'ts' else running_visible(text, kind, 0)))+ server.roster_delta([parent(), child('c3', 'running', 0.73)], resync=True)+ snap('roster_restored', lambda text: running_visible(text, kind, 1)+ and cost_ready(text, ts_cached_cost if kind == 'ts' else '0.73'))+ server.goal('paused')+ snap('goal_paused', lambda text: 'Goal paused (12s)' in text)+ assert not server.prompts, 'focus interactions accidentally submitted a prompt'+ assert not terminal.screen.unsupported_sgr, 'unsupported SGR makes attribute evidence incomplete'+ assert not terminal.screen.unsupported_terminal, 'unsupported terminal geometry makes frame evidence incomplete'+ observed['title_costs'] = {phase: visible_cost(frame['text']) for phase, frame in observed['frames'].items()}+ expected_costs = {'snapshot': '0.42', 'roster_added': '0.91', 'goal_active': '0.91',+ 'dock_focused': '0.91', 'editor_restored': '0.91', 'child_settled': '0.42',+ 'child_removed': '0.00', 'roster_restored': '0.73', 'goal_paused': '0.73'}+ if kind == 'ts':+ expected_costs = {phase: ts_cached_cost for phase in expected_costs}+ assert observed['title_costs'] == expected_costs, 'actual title cost reaction differs from pinned source'+ observed['behavior_verified'] = True+ finally:+ try:+ if terminal:+ observed['raw_ansi_complete_hex'] = bytes(terminal.raw).hex()+ terminal.close()+ finally:+ try:+ server.close()+ finally:+ observed['emitted_events'] = server.emitted+ observed['commands'] = server.commands+ observed['context_responses'] = server.context_responses+ observed['fixture_errors'] = server.errors+ assert not server.errors, server.errors+ observed['cleanup_verified'] = True+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ receipt = {'verified': False, 'runs': {}, 'scope': __doc__,+ 'frame_scope': '120x40 decoded text + dock SGR cells and complete raw ANSI, not pixels/font rendering.',+ 'preexisting_ts_limitation': 'Pinned TS uses a boxed running/idle/inactive dock; Rust uses a one-line fixed-group dock. Layouts are not normalized into equality.',+ 'preexisting_cost_difference': 'TS binds initial family cost from get_context_tree and does not refresh it on roster-only events. Rust refreshes cost from the live roster. Exact phase costs asserted and retained without normalization or synthetic refresh events.',+ 'not_verified': ['frame/style equality', 'actual daemon roster production', 'new-session/no-session fallback', 'agents-view lazy query search']}+ try:+ assert sys.platform == 'linux', 'hosted Linux binary fixture only'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive mismatch'+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-dock-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()+ observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ run_case(binary, kind, Path(folder) / kind, observed)+ except Exception as error:+ observed['error'] = str(error)+ assert all('error' not in run for run in receipt['runs'].values()), 'actual binary scenario failed'+ frames = receipt['runs']['ts']['frames']+ assert frames.keys() == receipt['runs']['rust']['frames'].keys(), 'different phases executed'+ receipt['frame_diffs'] = {phase: {+ 'text_equal': frame['text'] == receipt['runs']['rust']['frames'][phase]['text'],+ 'dock_attributes_equal': frame['dock_styled_rows'] == receipt['runs']['rust']['frames'][phase]['dock_styled_rows']}+ for phase, frame in frames.items()}+ receipt['verified'] = True # Only the explicitly scoped reaction assertions.+ 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/review_dock_screen.py b/scripts/review_dock_screen.pynew file mode 100644index 0000000000..ce123d61ee--- /dev/null+++ b/scripts/review_dock_screen.py@@ -0,0 +1,228 @@+#!/usr/bin/env python3+"""SGR-aware variant of the existing binary comparator's Screen.++Supports the cursor/erase/color vocabulary already used by its terminal capture.+Unsupported SGR is disclosed; raw ANSI is the audit ground truth. This does not+claim a complete terminal emulator or pixel-exact font rendering.+"""+import codecs+import re+import unicodedata++class DockScreen:+ """Existing xterm cell capture with explicit per-cell SGR attributes."""+ def __init__(self, width=120, height=40):+ self.width, self.height = width, height+ self.cells = [[" "] * width for _ in range(height)]+ self.styles = [[{} for _ in range(width)] for _ in range(height)]+ self.sgr = {}+ self.unsupported_sgr = []+ self.unsupported_terminal = []+ self.keyboard_controls = []+ self.autowrap = True+ self.alternate = None+ self.row = self.col = 0+ self.saved = (0, 0, {})+ self.pending = ""+ self.decoder = codecs.getincrementaldecoder("utf-8")("replace")++ def text(self):+ return "\n".join("".join(row).rstrip() for row in self.cells)++ def feed(self, data):+ self.pending += self.decoder.decode(data)+ replies = []+ while self.pending:+ if self.pending[0] == "\x1b":+ if len(self.pending) < 2:+ break+ if self.pending[1] in "]P_^":+ end = re.search(r"\x07|\x1b\\", self.pending[2:])+ if end is None:+ break+ sequence = self.pending[:2 + end.end()]+ # OSC titles/hyperlinks do not move terminal cells. DCS,+ # APC and PM can carry graphics or sixel: never silently+ # accept their unknown effect on the captured frame.+ payload = self.pending[2:2 + end.start()]+ osc_kind = payload.split(';', 1)[0]+ # Pinned TS asks for the default foreground/background via+ # OSC10;? / OSC11;? (actual failed hosted receipt). Queries+ # do not paint or set a color; a legacy PTY may stay silent.+ # Color-setting variants remain unsupported and fail closed.+ color_query = payload in ('10;?', '11;?')+ if self.pending[1] != ']' or (not color_query and osc_kind not in ('0', '1', '2', '7', '8', '52', '133')):+ self.unsupported_terminal.append(sequence)+ self.pending = self.pending[2 + end.end():]+ continue+ if self.pending[1] == "[":+ match = re.match(r"\x1b\[([0-?]*)([ -/]*)([@-~])", self.pending)+ if match is None:+ break+ params, intermediate, command = match.groups()+ sequence = self.pending[:match.end()]+ self.pending = self.pending[match.end():]+ nums = [int(x) if x.isdigit() else 0 for x in params.lstrip("?<>").split(";")]+ n = nums[0] or 1+ if intermediate and not (command == 'q' and intermediate == ' '):+ self.unsupported_terminal.append(sequence)+ continue+ # Actual hosted TS/Rust captures contain these keyboard+ # protocol controls. They do not paint cells and must not+ # be interpreted as SGR4 (underline) after stripping >.+ if command == 'm' and params in ('>4;0', '>4;1', '>4;2'):+ self.keyboard_controls.append(sequence)+ continue+ if command == 'u' and params == '?':+ self.keyboard_controls.append(sequence)+ # Even a zero-flags reply advertises Kitty support to+ # crossterm (vendor terminal/sys/unix.rs:255). This PTY+ # emits legacy keys: stay silent on the Kitty query.+ # The following DA1 query's response settles non-Kitty+ # through KeyboardEnhancementFlagsFilter instead.+ continue+ if command == 'u' and (re.fullmatch(r'[>=]\d+(?:;\d+)?', params)+ or re.fullmatch(r'<\d*', params)):+ self.keyboard_controls.append(sequence)+ continue+ if params.startswith(('?', '<', '>')) and command not in 'hlnc':+ self.unsupported_terminal.append(sequence)+ continue+ if command == "m": self.apply_sgr(nums)+ elif command in "Hf":+ self.row = min(self.height - 1, max(0, (nums[0] or 1) - 1))+ self.col = min(self.width - 1, max(0, ((nums[1] if len(nums) > 1 else 1) or 1) - 1))+ elif command == "A": self.row = max(0, self.row - n)+ elif command == "B": self.row = min(self.height - 1, self.row + n)+ elif command == "C": self.col = min(self.width - 1, self.col + n)+ elif command == "D": self.col = max(0, self.col - n)+ elif command == "G": self.col = min(self.width - 1, n - 1)+ elif command == "J":+ if nums[0] == 2:+ self.cells = [[" "] * self.width for _ in range(self.height)]+ self.styles = [[dict(self.sgr) for _ in range(self.width)] for _ in range(self.height)]+ elif nums[0] == 0:+ self.cells[self.row][self.col:] = [" "] * (self.width - self.col)+ self.styles[self.row][self.col:] = [dict(self.sgr) for _ in range(self.width - self.col)]+ for row in range(self.row + 1, self.height):+ self.cells[row] = [" "] * self.width+ self.styles[row] = [dict(self.sgr) for _ in range(self.width)]+ elif nums[0] != 3: # ED3 clears scrollback, not visible cells.+ self.unsupported_terminal.append(sequence)+ elif command == "K":+ if nums[0] not in (0, 1, 2):+ self.unsupported_terminal.append(sequence)+ continue+ start, end = (0, self.width) if nums[0] == 2 else ((0, self.col + 1) if nums[0] == 1 else (self.col, self.width))+ self.cells[self.row][start:end] = [" "] * (end - start)+ self.styles[self.row][start:end] = [dict(self.sgr) for _ in range(end - start)]+ elif command == "P":+ line = self.cells[self.row]+ line[self.col:] = (line[self.col + n:] + [" "] * n)[:self.width - self.col]+ styles = self.styles[self.row]+ styles[self.col:] = (styles[self.col + n:] + [dict(self.sgr) for _ in range(n)])[:self.width - self.col]+ elif command == "X":+ end = min(self.width, self.col + n)+ self.cells[self.row][self.col:end] = [" "] * (end - self.col)+ self.styles[self.row][self.col:end] = [dict(self.sgr) for _ in range(end - self.col)]+ elif command == "n" and nums[0] == 6:+ replies.append(f"\x1b[{self.row + 1};{self.col + 1}R".encode())+ elif command == "c": replies.append(b"\x1b[?1;2c")+ elif command in 'hl' and params.startswith('?'):+ for mode in nums:+ if mode == 7:+ self.autowrap = command == 'h'+ elif mode == 1049:+ if command == 'h' and self.alternate is None:+ self.alternate = (self.cells, self.styles, self.row, self.col,+ dict(self.sgr), self.autowrap)+ self.cells = [[' '] * self.width for _ in range(self.height)]+ self.styles = [[{} for _ in range(self.width)] for _ in range(self.height)]+ self.row = self.col = 0+ elif command == 'l' and self.alternate is not None:+ self.cells, self.styles, self.row, self.col, self.sgr, self.autowrap = self.alternate+ self.alternate = None+ elif mode not in (12, 25, 1000, 1002, 1003, 1004, 1006, 2004, 2026):+ self.unsupported_terminal.append(sequence)+ elif command == 'q' and intermediate == ' ':+ pass # Cursor presentation, not cell geometry.+ else:+ self.unsupported_terminal.append(sequence)+ continue+ command = self.pending[1]+ if command in '()' and len(self.pending) < 3:+ break+ self.pending = self.pending[2:]+ if command == "7": self.saved = (self.row, self.col, dict(self.sgr))+ elif command == "8":+ self.row, self.col, saved_sgr = self.saved+ self.sgr = dict(saved_sgr)+ elif command in "()" and self.pending:+ charset = self.pending[0]+ self.pending = self.pending[1:]+ if charset != 'B':+ self.unsupported_terminal.append('\x1b' + command + charset)+ else:+ self.unsupported_terminal.append('\x1b' + command)+ continue+ char, self.pending = self.pending[0], self.pending[1:]+ if char == "\r": self.col = 0+ elif char == "\n":+ self.row += 1+ if self.row >= self.height:+ self.cells.pop(0); self.cells.append([" "] * self.width)+ self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])+ self.row = self.height - 1+ elif char == "\b": self.col = max(0, self.col - 1)+ elif char == '\t': self.col = min(self.width - 1, ((self.col // 8) + 1) * 8)+ elif char >= " " and not unicodedata.combining(char):+ if self.col >= self.width:+ if self.autowrap:+ self.col = 0+ self.row += 1+ if self.row == self.height:+ self.cells.pop(0); self.cells.append([' '] * self.width)+ self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])+ self.row = self.height - 1+ else:+ self.col = self.width - 1+ self.cells[self.row][self.col] = char+ self.styles[self.row][self.col] = dict(self.sgr)+ self.col += 2 if unicodedata.east_asian_width(char) in "WF" else 1+ elif char not in ('\x00', '\x07') and not unicodedata.combining(char):+ self.unsupported_terminal.append(char)+ return replies++ def apply_sgr(self, nums):+ i = 0+ while i < len(nums):+ value = nums[i]+ if value == 0:+ self.sgr = {}+ elif value in (1, 2, 3, 4, 7, 9):+ self.sgr[str(value)] = True+ elif value in (22, 23, 24, 27, 29):+ for key in {22: ('1', '2'), 23: ('3',), 24: ('4',), 27: ('7',), 29: ('9',)}[value]:+ self.sgr.pop(key, None)+ elif 30 <= value <= 37 or 90 <= value <= 97:+ self.sgr['fg'] = ['ansi', value]+ elif 40 <= value <= 47 or 100 <= value <= 107:+ self.sgr['bg'] = ['ansi', value]+ elif value in (39, 49):+ self.sgr.pop('fg' if value == 39 else 'bg', None)+ elif value in (38, 48) and i + 1 < len(nums):+ count = {5: 1, 2: 3}.get(nums[i + 1])+ if count is not None and i + 2 + count <= len(nums):+ self.sgr['fg' if value == 38 else 'bg'] = nums[i + 1:i + 2 + count]+ i += 1 + count+ else:+ self.unsupported_sgr.append(nums[i:])+ break+ else:+ self.unsupported_sgr.append([value])+ i += 1++ def dock_styles(self):+ return [{"text": ''.join(row).rstrip(), "styles": [dict(style) for style in self.styles[index]]}+ for index, row in enumerate(self.cells)+ if 'subagents' in ''.join(row) or 'running' in ''.join(row)]diff --git a/scripts/test_review_dock_events_parity.py b/scripts/test_review_dock_events_parity.pynew file mode 100644index 0000000000..3696329b45--- /dev/null+++ b/scripts/test_review_dock_events_parity.py@@ -0,0 +1,169 @@+#!/usr/bin/env python3+import unittest+from pathlib import Path+import tempfile+import json+import threading+from unittest.mock import Mock, patch++from review_dock_events_parity import DockSupervisor, child, cost_ready, parent, run_case, running_visible, ts_dock_visible, visible_cost+from review_dock_screen import DockScreen+++class CaptureTests(unittest.TestCase):+ def test_style_only_focus_change_is_observable(self):+ screen = DockScreen(width=20, height=3)+ screen.feed(b'1 subagents')+ before = screen.dock_styles()+ screen.feed(b'\r\x1b[48;2;1;2;3m1 subagents\x1b[0m')+ self.assertEqual(before[0]['text'], screen.dock_styles()[0]['text'])+ self.assertNotEqual(before, screen.dock_styles())+ self.assertEqual(screen.styles[0][0]['bg'], [2, 1, 2, 3])++ def test_erase_and_reset_remove_stale_style(self):+ screen = DockScreen(width=20, height=3)+ screen.feed(b'\x1b[7m1 subagents\x1b[0m\r\x1b[2K')+ self.assertEqual(screen.styles[0], [{}] * 20)+ self.assertEqual(screen.text().strip(), '')++ def test_partial_ansi_does_not_repaint_until_complete(self):+ screen = DockScreen(width=20, height=3)+ screen.feed(b'\x1b[48;2;1;')+ self.assertEqual(screen.text().strip(), '')+ screen.feed(b'2;3m1 subagents')+ self.assertEqual(screen.styles[0][0]['bg'], [2, 1, 2, 3])++ def test_count_predicate_distinguishes_events_and_layouts(self):+ self.assertTrue(running_visible('1 running', 'ts', 1))+ self.assertFalse(running_visible('1 running', 'ts', 2))+ self.assertTrue(running_visible('2 subagents', 'rust', 2))++ def test_count_has_integer_boundaries(self):+ for kind, label in [('ts', 'running'), ('rust', 'subagents')]:+ self.assertFalse(running_visible('10 ' + label, kind, 0))+ self.assertFalse(running_visible('12 ' + label, kind, 2))+ self.assertTrue(running_visible('● 0 ' + label + ' ·', kind, 0))++ def test_unknown_geometry_is_recorded(self):+ screen = DockScreen()+ screen.feed(b'\x1b[3S\x1b[1;5r\x1b[L\x1bM\x1b[1J')+ self.assertEqual(screen.unsupported_terminal,+ ['\x1b[3S', '\x1b[1;5r', '\x1b[L', '\x1bM', '\x1b[1J'])++ def test_harmless_modes_title_and_cursor_style_are_allowed(self):+ screen = DockScreen()+ screen.feed(b'\x1b[?25l\x1b[?1006h\x1b[?2004h\x1b[2 q\x1b]2;fixture title\x07')+ self.assertEqual(screen.unsupported_terminal, [])++ def test_alternate_buffer_restores_cells_and_styles(self):+ screen = DockScreen(width=20, height=3)+ screen.feed(b'\x1b[31m1 subagents\x1b[?1049h')+ self.assertEqual(screen.text().strip(), '')+ screen.feed(b'\x1b[32m2 subagents\x1b[?1049l')+ self.assertEqual(screen.text().strip(), '1 subagents')+ self.assertEqual(screen.styles[0][0]['fg'], ['ansi', 31])+ self.assertEqual(screen.sgr['fg'], ['ansi', 31])++ def test_partial_charset_and_palette_change_are_not_silently_ignored(self):+ screen = DockScreen()+ screen.feed(b'\x1b(')+ self.assertEqual(screen.unsupported_terminal, [])+ screen.feed(b'B\x1b]4;1;rgb:00/00/00\x07')+ self.assertEqual(screen.unsupported_terminal, ['\x1b]4;1;rgb:00/00/00\x07'])++ def test_server_closes_when_terminal_cleanup_raises(self):+ server = Mock(path=Path('/fixture.sock'), emitted=[], commands=[], errors=[])+ terminal = Mock(raw=bytearray())+ terminal.wait.side_effect = RuntimeError('initial readiness failed')+ terminal.close.side_effect = RuntimeError('terminal cleanup failed')+ with tempfile.TemporaryDirectory() as folder, \+ patch('review_dock_events_parity.actual_hello', return_value={}), \+ patch('review_dock_events_parity.DockSupervisor', return_value=server), \+ patch('review_dock_events_parity.Terminal', return_value=terminal):+ observed = {}+ with self.assertRaisesRegex(RuntimeError, 'terminal cleanup failed'):+ run_case(Path('/fixture-binary'), 'rust', Path(folder) / 'case', observed)+ server.close.assert_called_once()+ self.assertNotIn('cleanup_verified', observed)++ def test_actual_keyboard_controls_do_not_corrupt_sgr(self):+ screen = DockScreen()+ screen.feed(b'\x1b[31;1m')+ before = dict(screen.sgr)+ replies = screen.feed(b'\x1b[>4;0m\x1b[?u\x1b[>1u\x1b[<u1 subagents')+ self.assertEqual(screen.sgr, before)+ self.assertEqual(screen.styles[0][0], before)+ self.assertNotIn('4', screen.styles[0][0])+ self.assertEqual(replies, [])+ self.assertEqual(screen.keyboard_controls,+ ['\x1b[>4;0m', '\x1b[?u', '\x1b[>1u', '\x1b[<u'])+ self.assertEqual(screen.unsupported_terminal, [])++ def test_partial_keyboard_query_never_advertises_kitty_support(self):+ screen = DockScreen()+ self.assertEqual(screen.feed(b'\x1b[?'), [])+ self.assertEqual(screen.keyboard_controls, [])+ self.assertEqual(screen.feed(b'u'), [])+ self.assertEqual(screen.feed(b'\x1b[>9;0m'), [])+ self.assertEqual(screen.unsupported_terminal, ['\x1b[>9;0m'])++ def test_full_crossterm_probe_gets_only_non_kitty_da1_reply(self):+ screen = DockScreen()+ screen.feed(b'\x1b[31m1 subagents')+ before = screen.dock_styles()+ cursor = (screen.row, screen.col)+ replies = screen.feed(b'\x1b[?u\x1b[c')+ self.assertEqual(replies, [b'\x1b[?1;2c'])+ self.assertFalse(any(reply.endswith(b'u') for reply in replies))+ self.assertEqual(screen.dock_styles(), before)+ self.assertEqual((screen.row, screen.col), cursor)+ self.assertEqual(screen.unsupported_terminal, [])++ def test_dock_hello_advertises_implemented_roster_capability(self):+ server = DockSupervisor.__new__(DockSupervisor)+ server.write_lock = threading.Lock()+ sock = Mock()+ server.send(sock, {'type': 'daemon_hello', 'serverCapabilities': ['session_input_admission']})+ wire = json.loads(sock.sendall.call_args.args[0])+ self.assertEqual(wire['serverCapabilities'], ['session_input_admission', 'agent_roster'])++ def test_context_tree_and_roster_describe_same_family_usage(self):+ server = DockSupervisor.__new__(DockSupervisor)+ server.write_lock = threading.Lock()+ server.roster = [parent(), child('c1', 'running', 0.42), child('c2', 'running', 0.49)]+ server.context_responses = []+ sock = Mock()+ server.send(sock, {'type': 'response', 'command': 'get_context_tree', 'success': True, 'data': {}})+ tree = json.loads(sock.sendall.call_args.args[0])['data']+ self.assertAlmostEqual(tree['totalUsage']['cost']['total'], 0.91)+ self.assertEqual([node['ownUsage']['cost']['total'] for node in tree['children']], [0.42, 0.49])+ self.assertEqual(len(server.context_responses), 1)++ def test_cost_probe_rejects_ambiguity(self):+ self.assertEqual(visible_cost('Dock fixture $0.42'), '0.42')+ with self.assertRaises(AssertionError):+ visible_cost('no cost')+ with self.assertRaises(AssertionError):+ visible_cost('$0.42 and $0.91')+ self.assertFalse(cost_ready('partial repaint $0.', '0.42'))+ self.assertTrue(cost_ready('Dock fixture $0.42', '0.42'))++ def test_startup_warning_cannot_make_removed_dock_look_present(self):+ warning = 'Prime Agent\n and subagents remain available.\n >\n← manage'+ self.assertIn('subagents', warning)+ self.assertFalse(ts_dock_visible(warning))+ self.assertTrue(ts_dock_visible(warning + '\n╭─ subagents ───╮\n│ ● 0 running │'))++ def test_exact_default_color_queries_do_not_mutate_capture(self):+ screen = DockScreen()+ screen.feed(b'\x1b[31m1 subagents')+ before = screen.dock_styles()+ self.assertEqual(screen.feed(b'\x1b]10;?\x1b\\\x1b]11;?\x07'), [])+ self.assertEqual(screen.dock_styles(), before)+ self.assertEqual(screen.unsupported_terminal, [])+ screen.feed(b'\x1b]10;#abcdef\x1b\\')+ self.assertEqual(screen.unsupported_terminal, ['\x1b]10;#abcdef\x1b\\'])+++if __name__ == '__main__':+ unittest.main()