README Source History Refs Reviews Compare Notes Search Review guide Prove the RPC frontend surface sufficient — except on reattach 09d7f4b0e3f4401a9a205707806525689c2bfbd2
Claude <noreply@anthropic.com > · 17 Jul 2026
SSH signature · not checked
Browse files Compare with HEAD
The claim that a full UI is buildable on smith rpc alone was asserted,
not tested. A headless client reconstructing a whole session's UI state
from the wire alone proves it holds for a frontend present from the
start: transcript, tool views, steering queue, tree, leaf, model, cost,
fold, and secret placeholders all deep-equal ground truth, and 34
EngineEvent variants classify cleanly as 25 notifications, 4 requests,
5 TUI-private.
But it fails for mid-session attach: the notification stream is a live
tail with no replay, so a late client cannot rebuild the ephemeral
steering queue and run status that are never session entries. session/
dump recovers persisted state only. The fix is a session/snapshot
driver method, plus two payload guarantees the reconstruction leans on
(session_compact must carry its covered span, session_tree its node
fields).
Adds prototypes/p28-rpc-frontend-sufficiency.
Changed files (3) Diff layout Auto Unified Split
prototypes/p28-rpc-frontend-sufficiency/Cargo.lock Added new file mode 100644+107 / −0 text lines
8 + source = "registry+https://github.com/rust-lang/crates.io-index" 9 + checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" 14 + source = "registry+https://github.com/rust-lang/crates.io-index" 15 + checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" 18 + name = "p28-rpc-frontend-sufficiency" 28 + source = "registry+https://github.com/rust-lang/crates.io-index" 29 + checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" 37 + source = "registry+https://github.com/rust-lang/crates.io-index" 38 + checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" 46 + source = "registry+https://github.com/rust-lang/crates.io-index" 47 + checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" 56 + source = "registry+https://github.com/rust-lang/crates.io-index" 57 + checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" 65 + source = "registry+https://github.com/rust-lang/crates.io-index" 66 + checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" 76 + source = "registry+https://github.com/rust-lang/crates.io-index" 77 + checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" 89 + source = "registry+https://github.com/rust-lang/crates.io-index" 90 + checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" 98 + name = "unicode-ident" 100 + source = "registry+https://github.com/rust-lang/crates.io-index" 101 + checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" 106 + source = "registry+https://github.com/rust-lang/crates.io-index" 107 + checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" prototypes/p28-rpc-frontend-sufficiency/Cargo.toml Added new file mode 100644+9 / −0 text lines
2 + name = "p28-rpc-frontend-sufficiency" 8 + serde = { version = "1" , features = ["derive" ] }prototypes/p28-rpc-frontend-sufficiency/src/main.rs Added new file mode 100644+1222 / −0 text lines
24 + use serde_json::{json, Value};25 + use std::collections::HashMap;26 + use std::sync::atomic::{AtomicU64, Ordering};27 + use std::sync::mpsc::{channel, Receiver, Sender};28 + use std::sync::{Arc, Mutex};42 + #[derive(Debug, Clone)]48 + type Handler = Arc<dyn Fn (& Arc<Endpoint>, &str , Value) -> Result <Value, RpcError> + Send + Sync >;49 + type NotifySink = Arc<dyn Fn (& Arc<Endpoint>, &str , Value) + Send + Sync >;50 + type Tap = Arc<Mutex<Vec <String >>>;53 + out: Mutex<Sender<String >>,55 + pending: Mutex<HashMap<u64 , Sender<Result <Value, RpcError>>>>,60 + fn new (out: Sender<String >, tap: Option <Tap>) -> Arc<Self > {62 + out: Mutex::new(out),63 + next_id: AtomicU64::new(1 ),64 + pending: Mutex::new(HashMap::new()),69 + fn start (self: & Arc<Self >, inbound: Receiver<String >, handler: Handler, notify: NotifySink) {70 + let ep = self.clone ();71 + thread::spawn(move || {72 + for line in inbound {73 + let msg: Value = match serde_json::from_str(& line) {77 + if msg.get ("method" ).is_some () {78 + let method = msg["method" ].as_str ().unwrap_or ("" ).to_string ();79 + let params = msg.get ("params" ).cloned ().unwrap_or (Value::Null);80 + match msg.get ("id" ).and_then (Value::as_u64) {82 + let ep2 = ep.clone ();83 + let h = handler.clone ();84 + thread::spawn(move || {85 + let res = h (& ep2, & method, params);86 + ep2.send_response (id, res);89 + None => notify (& ep, & method, params),91 + } else if let Some (id) = msg.get ("id" ).and_then (Value::as_u64) {92 + let res = match msg.get ("error" ) {93 + Some (err) => Err (RpcError {94 + code: err.get ("code" ).and_then (Value::as_i64).unwrap_or (- 1 ),97 + .and_then (Value::as_str)101 + None => Ok (msg.get ("result" ).cloned ().unwrap_or (Value::Null)),103 + if let Some (tx) = ep.pending.lock ().unwrap ().remove (& id) {104 + let _ = tx.send (res);111 + fn call (& self, method: &str , params: Value) -> Result <Value, RpcError> {112 + let id = self.next_id.fetch_add (1 , Ordering::SeqCst);113 + let (tx, rx) = channel ();114 + self.pending.lock ().unwrap ().insert (id, tx);115 + self.send (json! ({"jsonrpc" : "2.0" , "id" : id, "method" : method, "params" : params}));116 + rx.recv ().unwrap_or (Err (RpcError {118 + message: "transport closed" .into (),122 + fn notify (& self, method: &str , params: Value) {123 + self.send (json! ({"jsonrpc" : "2.0" , "method" : method, "params" : params}));126 + fn send_response (& self, id: u64 , res: Result <Value, RpcError>) {127 + let msg = match res {128 + Ok (v) => json! ({"jsonrpc" : "2.0" , "id" : id, "result" : v}),130 + json! ({"jsonrpc" : "2.0" , "id" : id, "error" : {"code" : e.code, "message" : e.message}})136 + fn send (& self, v: Value) {137 + let line = v.to_string ();138 + if let Some (t) = & self.tap {139 + t.lock ().unwrap ().push (line.clone ());141 + let _ = self.out.lock ().unwrap ().send (line);150 + #[derive(Clone, Copy, PartialEq, Eq)]161 + fn tag (& self) -> &'static str {163 + Shape::Notification => "notification" ,164 + Shape::Request => "request" ,165 + Shape::PrivateOmitted => "frontend-private-omitted" ,173 + fn project (method: &str ) -> Shape {177 + | "session_before_switch" 178 + | "session_before_fork" 179 + | "session_before_compact" => Shape::Request,181 + "panel_toggle" | "resize" | "ui_selection" | "ui_focus" | "ui_scroll" => {182 + Shape::PrivateOmitted185 + _ => Shape::Notification,195 + #[derive(Serialize, PartialEq, Clone, Debug, Default)]201 + #[derive(Serialize, PartialEq, Clone, Debug)]212 + #[derive(Serialize, PartialEq, Clone, Debug)]218 + #[derive(Serialize, PartialEq, Clone, Debug)]226 + #[derive(Serialize, PartialEq, Clone, Debug, Default)]230 + total_cost_micros: u64 ,233 + #[derive(Serialize, PartialEq, Clone, Debug, Default)]239 + #[derive(Serialize, PartialEq, Clone, Debug, Default)]242 + parent: Option <String >,246 + #[derive(Serialize, PartialEq, Clone, Debug, Default)]248 + transcript: Vec <Msg>,249 + tools: Vec <ToolView>,250 + queue: Vec <QueueItem>,251 + tree: Vec <TreeNode>,254 + secret_labels: Vec <(u64 , String)>,260 + errors: Vec <String >,264 + fn tool_mut (&mut self, id: &str ) -> Option <&mut ToolView> {265 + self.tools.iter_mut ().find (|t| t.id == id)277 + state: Mutex<UiState>,279 + streaming: Mutex<HashMap<String , (String, String)>>,280 + blocking_replies: Mutex<Vec <(String, Value)>>, 284 + fn new (window: u64 ) -> Arc<Self > {285 + let mut st = UiState::default();286 + st.context.window = window;288 + state: Mutex::new(st),289 + streaming: Mutex::new(HashMap::new()),290 + blocking_replies: Mutex::new(Vec ::new()),295 + fn on_notification (& self, method: &str , p: Value) {296 + let mut s = self.state.lock ().unwrap ();298 + "message_start" => {299 + let id = p["id" ].as_str ().unwrap_or ("" ).to_string ();300 + let role = p["role" ].as_str ().unwrap_or ("assistant" ).to_string ();301 + self.streaming.lock ().unwrap ().insert (id, (role, String ::new()));304 + let id = p["id" ].as_str ().unwrap_or ("" );305 + if let Some (acc) = self.streaming.lock ().unwrap ().get_mut (id) {306 + acc.1. push_str (p["text" ].as_str ().unwrap_or ("" ));309 + "thinking_delta" => {310 + let id = p["id" ].as_str ().unwrap_or ("" );311 + let mut stream = self.streaming.lock ().unwrap ();313 + .entry (format! ("think:{id}" ))314 + .or_insert_with (|| ("thinking" .to_string (), String ::new()));315 + acc.1. push_str (p["text" ].as_str ().unwrap_or ("" ));318 + let id = p["id" ].as_str ().unwrap_or ("" );320 + if let Some ((role, text)) = self.streaming.lock ().unwrap ().remove (& format! ("think:{id}" )) {321 + s.transcript.push (Msg { role, text });323 + if let Some ((role, text)) = self.streaming.lock ().unwrap ().remove (id) {324 + s.transcript.push (Msg { role, text });327 + "tool_execution_start" => {328 + s.tools.push (ToolView {329 + id: p["id" ].as_str ().unwrap_or ("" ).to_string (),330 + name: p["name" ].as_str ().unwrap_or ("" ).to_string (),331 + input: p.get ("input" ).cloned ().unwrap_or (Value::Null),332 + status: "running" .into (),333 + output: String ::new(),338 + "tool_execution_update" => {339 + let id = p["id" ].as_str ().unwrap_or ("" ).to_string ();340 + if let Some (t) = s.tool_mut (& id) {341 + t.progress = p["progress" ].as_u64 ().unwrap_or (0 );344 + "tool_execution_end" => {345 + let id = p["id" ].as_str ().unwrap_or ("" ).to_string ();346 + let out = p["output" ].as_str ().unwrap_or ("" ).to_string ();347 + let err = p["is_error" ].as_bool ().unwrap_or (false );348 + if let Some (t) = s.tool_mut (& id) {349 + t.status = "done" .into ();355 + let node = & p["node" ];356 + s.tree.push (TreeNode {357 + id: node["id" ].as_str ().unwrap_or ("" ).to_string (),358 + parent: node["parent" ].as_str ().map (|x| x.to_string ()),359 + kind: node["kind" ].as_str ().unwrap_or ("" ).to_string (),361 + if let Some (l) = p["leaf" ].as_str () {362 + s.leaf = l.to_string ();366 + if let Some (l) = p["leaf" ].as_str () {367 + s.leaf = l.to_string ();370 + "session_compact" => {372 + summary_id: p["summary_id" ].as_str ().unwrap_or ("" ).to_string (),373 + start: p["start" ].as_str ().unwrap_or ("" ).to_string (),374 + end: p["end" ].as_str ().unwrap_or ("" ).to_string (),375 + outcome: p["outcome" ].as_str ().unwrap_or ("" ).to_string (),378 + "secret_registered" => {379 + let id = p["id" ].as_u64 ().unwrap_or (0 );380 + let label = p["label" ].as_str ().unwrap_or ("" ).to_string ();381 + s.secret_labels.push ((id, label));383 + "steer_enqueue" => s.queue.push (QueueItem {384 + kind: "steer" .into (),385 + text: p["text" ].as_str ().unwrap_or ("" ).to_string (),387 + "followup_enqueue" => s.queue.push (QueueItem {388 + kind: "followup" .into (),389 + text: p["text" ].as_str ().unwrap_or ("" ).to_string (),391 + "steer_deliver" | "followup_deliver" => {392 + let text = p["text" ].as_str ().unwrap_or ("" );393 + if let Some (pos) = s.queue.iter ().position (|q| q.text == text) {394 + s.queue.remove (pos);398 + if let Some (m) = p["model" ].as_str () {399 + s.model = m.to_string ();401 + if let Some (pr) = p["provider" ].as_str () {402 + s.provider = pr.to_string ();405 + "error" => s.errors.push (p["message" ].as_str ().unwrap_or ("" ).to_string ()),407 + "agent_start" | "agent_end" | "turn_start" | "turn_end" | "message_update" 408 + | "session_open" | "session_fork" | "shutdown" => {}416 + fn on_request (& self, method: &str , p: Value) -> Result <Value, RpcError> {417 + let reply = match method {418 + "tool_call" => json! ({ "block" : false }),419 + "session_before_switch" | "session_before_fork" | "session_before_compact" => {420 + json! ({ "block" : false })423 + return Err (RpcError {425 + message: format! ("client answers no blocking method {other}" ),429 + self.blocking_replies432 + .push ((method.to_string (), p));437 + fn refresh_usage (& self, ep: & Endpoint) {438 + if let Ok (v) = ep.call ("getContextUsage" , Value::Null) {439 + let mut s = self.state.lock ().unwrap ();440 + s.cost.input_tokens = v["input_tokens" ].as_u64 ().unwrap_or (0 );441 + s.cost.output_tokens = v["output_tokens" ].as_u64 ().unwrap_or (0 );442 + s.cost.total_cost_micros = v["total_cost_micros" ].as_u64 ().unwrap_or (0 );443 + s.context.used = v["context_used" ].as_u64 ().unwrap_or (0 );444 + s.context.window = v["context_window" ].as_u64 ().unwrap_or (s.context.window);450 + fn attach_snapshot (& self, ep: & Endpoint) -> bool {451 + match ep.call ("session/snapshot" , Value::Null) {453 + let mut s = self.state.lock ().unwrap ();454 + s.queue = v["queue" ]458 + .map (|q| QueueItem {459 + kind: q["kind" ].as_str ().unwrap_or ("" ).to_string (),460 + text: q["text" ].as_str ().unwrap_or ("" ).to_string (),464 + .unwrap_or_default ();483 + secrets: Vec <(u64 , String, String)>, 484 + turn_input_tokens: u64 ,485 + open_msg_id: Option <String >,489 + fn new (server: Arc<Endpoint>, window: u64 ) -> Self {490 + let mut truth = UiState::default();491 + truth.context.window = window;498 + secrets: Vec ::new(),499 + turn_input_tokens: 0 ,507 + fn emit (& self, method: &str , params: Value) -> Option <Value> {508 + match project (method) {509 + Shape::Notification => {510 + self.ep.notify (method, params);513 + Shape::Request => match self.ep.call (method, params) {515 + Err (_ ) => Some (json! ({"block" : false })),517 + Shape::PrivateOmitted => None , 521 + fn next_entry (&mut self, kind: &str ) -> String {523 + let id = format! ("e{}" , self.entry_no);524 + let parent = self.truth.tree.last ().map (|n| n.id.clone ());525 + self.truth.tree.push (TreeNode {527 + parent: parent.clone (),528 + kind: kind.to_string (),530 + self.truth.leaf = id.clone ();533 + json! ({"node" : {"id" : id, "parent" : parent, "kind" : kind}, "leaf" : id}),539 + fn mask (& self, text: &str ) -> String {542 + let mut secrets = self.secrets.clone ();543 + secrets.sort_by_key (|(_, pt, _)| std::cmp::Reverse(pt.len ()));544 + let mut out = text.to_string ();545 + for (id, pt, _ ) in secrets {546 + out = out.replace (& pt, & format! ("smith:sec:{id}" ));551 + fn charge (&mut self, input: u64 , output: u64 ) {552 + self.turn_input_tokens += input;553 + self.truth.cost.input_tokens += input;554 + self.truth.cost.output_tokens += output;556 + self.truth.cost.total_cost_micros += input + output;557 + self.truth.context.used = self.truth.cost.input_tokens + self.truth.cost.output_tokens;562 + fn open (&mut self, model: &str , provider: &str ) {563 + self.truth.model = model.to_string ();564 + self.truth.provider = provider.to_string ();565 + self.emit ("session_open" , json! ({"session_id" : "01HSESSP28" }));566 + self.emit ("model_select" , json! ({"model" : model, "provider" : provider}));567 + self.emit ("agent_start" , Value::Null);570 + fn user_says (&mut self, text: &str ) {571 + self.emit ("turn_start" , Value::Null);572 + let masked = self.mask (text);573 + self.truth.transcript.push (Msg {574 + role: "user" .into (),575 + text: masked.clone (),578 + let id = format! ("m{}" , self.msg_no);579 + self.emit ("message_start" , json! ({"id" : id, "role" : "user" }));580 + self.emit ("text_delta" , json! ({"id" : id, "text" : masked}));581 + self.emit ("message_end" , json! ({"id" : id}));582 + self.next_entry ("user" );583 + self.charge (text.len () as u64 / 4 + 1 , 0 );586 + fn assistant_thinks (&mut self, chunks: & [&str ]) {588 + let id = format! ("m{}" , self.msg_no);589 + self.emit ("message_start" , json! ({"id" : id, "role" : "assistant" }));590 + let mut think = String ::new();592 + let m = self.mask (c);594 + self.emit ("thinking_delta" , json! ({"id" : id, "text" : m}));596 + self.truth.transcript.push (Msg {597 + role: "thinking" .into (),601 + self.open_msg_id = Some (id);604 + fn assistant_says (&mut self, chunks: & [&str ]) {606 + let id = self.open_msg_id.take ().unwrap_or_else (|| {608 + let id = format! ("m{}" , self.msg_no);609 + self.emit ("message_start" , json! ({"id" : id, "role" : "assistant" }));612 + let mut text = String ::new();614 + let m = self.mask (c);616 + self.emit ("text_delta" , json! ({"id" : id, "text" : m}));618 + self.truth.transcript.push (Msg {619 + role: "assistant" .into (),622 + self.emit ("message_end" , json! ({"id" : id}));623 + self.next_entry ("assistant" );629 + fn tool (&mut self, id: &str , name: &str , input: Value, output: &str , blocking: bool ) -> bool {630 + let masked_out = self.mask (output);633 + .emit ("tool_call" , json! ({"id" : id, "name" : name, "input" : input}))634 + .unwrap_or (json! ({"block" : false }));635 + if reply["block" ].as_bool ().unwrap_or (false ) {637 + self.truth.tools.push (ToolView {640 + input: input.clone (),641 + status: "done" .into (),642 + output: reply["reason" ].as_str ().unwrap_or ("blocked" ).into (),646 + self.emit ("tool_execution_start" , json! ({"id" : id, "name" : name, "input" : input}));648 + "tool_execution_end" ,649 + json! ({"id" : id, "output" : reply["reason" ].as_str ().unwrap_or ("blocked" ), "is_error" : true }),651 + self.next_entry ("tool_result" );655 + self.truth.tools.push (ToolView {658 + input: input.clone (),659 + status: "done" .into (),660 + output: masked_out.clone (),664 + self.emit ("tool_execution_start" , json! ({"id" : id, "name" : name, "input" : input}));665 + self.emit ("tool_execution_update" , json! ({"id" : id, "progress" : 50 }));666 + self.emit ("tool_execution_update" , json! ({"id" : id, "progress" : 100 }));668 + "tool_execution_end" ,669 + json! ({"id" : id, "output" : masked_out, "is_error" : false }),671 + self.next_entry ("tool_result" );672 + self.charge (output.len () as u64 / 4 + 1 , 0 );676 + fn enqueue_steer (&mut self, text: &str ) {677 + self.truth.queue.push (QueueItem {678 + kind: "steer" .into (),681 + self.emit ("steer_enqueue" , json! ({"text" : text}));684 + fn deliver_steer (&mut self, text: &str ) {685 + if let Some (pos) = self.truth.queue.iter ().position (|q| q.text == text) {686 + self.truth.queue.remove (pos);688 + self.emit ("steer_deliver" , json! ({"text" : text}));690 + self.truth.transcript.push (Msg {691 + role: "user" .into (),695 + let id = format! ("m{}" , self.msg_no);696 + self.emit ("message_start" , json! ({"id" : id, "role" : "user" }));697 + self.emit ("text_delta" , json! ({"id" : id, "text" : text}));698 + self.emit ("message_end" , json! ({"id" : id}));699 + self.next_entry ("user" );702 + fn compact (&mut self, start: &str , end: &str , outcome: &str ) {704 + self.emit ("session_before_compact" , json! ({"start" : start, "end" : end}));705 + let summary_id = self.next_entry ("compaction_summary" );706 + self.truth.folds.push (Fold {707 + summary_id: summary_id.clone (),708 + start: start.into (),710 + outcome: outcome.into (),715 + json! ({"summary_id" : summary_id, "start" : start, "end" : end, "outcome" : outcome}),719 + fn switch_leaf (&mut self, target: &str ) {721 + self.emit ("session_before_switch" , json! ({"target" : target}));724 + let sw_id = format! ("e{}" , self.entry_no);725 + let parent = self.truth.tree.last ().map (|n| n.id.clone ());726 + self.truth.tree.push (TreeNode {729 + kind: "leaf_switch" .into (),731 + self.truth.leaf = target.into ();732 + self.emit ("session_leaf" , json! ({"leaf" : target}));736 + json! ({"node" : {"id" : sw_id, "parent" : self.truth.tree[self.truth.tree.len ()- 1 ].parent, "kind" : "leaf_switch" }, "leaf" : target}),740 + fn register_secret (&mut self, plaintext: &str , label: &str ) -> u64 {741 + self.secret_no += 1 ;742 + let id = self.secret_no;743 + self.secrets.push ((id, plaintext.to_string (), label.to_string ()));744 + self.truth.secret_labels.push ((id, label.to_string ()));745 + self.next_entry ("secret_registration" );747 + self.emit ("secret_registered" , json! ({"id" : id, "label" : label}));751 + fn change_model (&mut self, model: &str , provider: &str ) {752 + self.truth.model = model.into ();753 + self.truth.provider = provider.into ();754 + self.next_entry ("model_change" );755 + self.emit ("model_select" , json! ({"model" : model, "provider" : provider}));758 + fn error (&mut self, message: &str ) {759 + self.truth.errors.push (message.into ());760 + self.emit ("error" , json! ({"message" : message}));763 + fn turn_end (&mut self) {764 + self.emit ("turn_end" , Value::Null);767 + fn shutdown (&mut self) {768 + self.emit ("agent_end" , Value::Null);769 + self.emit ("shutdown" , Value::Null);782 + Arc<Endpoint>, // client endpoint (to originate data-method calls)785 + let (c2s_tx, c2s_rx) = channel::<String >();786 + let (s2c_tx, s2c_rx) = channel::<String >();787 + let tap: Tap = Arc::new(Mutex::new(Vec ::new()));789 + let server = Endpoint::new(s2c_tx, Some (tap.clone ()));790 + let client_ep = Endpoint::new(c2s_tx, Some (tap.clone ()));792 + let engine = Arc::new(Mutex::new(Engine::new(server.clone (), window)));793 + let client = Client::new(window);796 + let eng_for_handler = engine.clone ();799 + Arc::new(move | _ep, method, params| server_data_method (& eng_for_handler, method, params)),800 + Arc::new(|_ep, _m, _p| {}),804 + let cl = client.clone ();805 + let cl2 = client.clone ();808 + Arc::new(move | _ep, method, params| cl.on_request (method, params)),809 + Arc::new(move | _ep, method, params| cl2.on_notification (method, params)),812 + (engine, client, client_ep, tap)816 + fn server_data_method (817 + engine: & Arc<Mutex<Engine>>,820 + ) -> Result <Value, RpcError> {821 + let e = engine.lock ().unwrap ();823 + "getContextUsage" => Ok (json! ({824 + "input_tokens" : e.truth.cost.input_tokens,825 + "output_tokens" : e.truth.cost.output_tokens,826 + "total_cost_micros" : e.truth.cost.total_cost_micros,827 + "context_used" : e.truth.context.used,828 + "context_window" : e.truth.context.window,831 + "session/snapshot" => Ok (json! ({832 + "queue" : e.truth.queue.iter ().map (|q| json! ({"kind" : q.kind, "text" : q.text})).collect::<Vec <_ >>(),833 + "leaf" : e.truth.leaf,834 + "model" : e.truth.model,836 + other => Err (RpcError {838 + message: format! ("method not found: {other}" ),843 + fn check (label: &str , cond: bool ) -> bool {844 + println! ("{} {label}" , if cond { "PASS" } else { "FAIL" });850 + thread::sleep(std::time::Duration::from_millis(40 ));858 + fn drive_full_session (engine: & Arc<Mutex<Engine>>) {859 + let mut e = engine.lock ().unwrap ();860 + e.open ("claude-opus-4" , "anthropic" );863 + e.user_says ("summarize the repo and run the linter" );866 + e.assistant_thinks (& ["let me " , "inspect the tree" ]);867 + e.assistant_says (& ["I'll read files " , "then lint." ]);870 + let sid = e.register_secret ("ghp_TOPSECRET_TOKEN_9000" , "github-token" );874 + e.tool ("call-1" , "read_file" , json! ({"path" : "Cargo.toml" }), "edition = 2021" , false );879 + json! ({"path" : ".env" }),880 + "TOKEN=ghp_TOPSECRET_TOKEN_9000" ,884 + e.tool ("call-3" , "run_shell" , json! ({"cmd" : "cargo clippy" }), "0 warnings" , true );889 + e.enqueue_steer ("also check formatting" );890 + e.enqueue_steer ("and fix imports" );891 + e.deliver_steer ("also check formatting" );894 + e.compact ("e1" , "e4" , "fit" );897 + e.switch_leaf ("e2" );900 + e.change_model ("claude-haiku-4" , "anthropic" );903 + e.error ("provider stream reset (retrying)" );906 + e.assistant_says (& ["done: 0 warnings, imports fixed." ]);911 + fn scn_reconstruct () -> bool {912 + let (engine, client, client_ep, tap) = wire (200_000 );913 + drive_full_session (& engine);916 + client.refresh_usage (& client_ep);919 + let truth = engine.lock ().unwrap ().truth.clone ();920 + let recon = client.state.lock ().unwrap ().clone ();924 + "reconstruct: transcript (streamed text + thinking deltas reassembled) equals ground truth" ,925 + truth.transcript == recon.transcript,928 + "reconstruct: tool call/result views equal ground truth (incl. blocked/approved)" ,929 + truth.tools == recon.tools,932 + "reconstruct: steering/follow-up queue snapshot equals ground truth" ,933 + truth.queue == recon.queue,936 + "reconstruct: current leaf + tree nodes equal ground truth" ,937 + truth.leaf == recon.leaf && truth.tree == recon.tree,940 + "reconstruct: compaction fold (summary + covered span) equals ground truth" ,941 + truth.folds == recon.folds && ! recon.folds.is_empty (),944 + "reconstruct: active model/provider equals ground truth" ,945 + truth.model == recon.model && truth.provider == recon.provider,948 + "reconstruct: secret labels (id→label) reconstructed for `‹secret: label›` rendering" ,949 + truth.secret_labels == recon.secret_labels && ! recon.secret_labels.is_empty (),952 + "reconstruct: cost/context indicators equal ground truth (pulled via getContextUsage)" ,953 + truth.cost == recon.cost && truth.context == recon.context && recon.cost.total_cost_micros > 0 ,956 + "reconstruct: error surface equals ground truth" ,957 + truth.errors == recon.errors && ! recon.errors.is_empty (),960 + "reconstruct: FULL UiState deep-equals ground truth built from the RPC stream ALONE" ,961 + serde_json::to_value(& truth).unwrap () == serde_json::to_value(& recon).unwrap (),969 + .any (|line| line.contains ("ghp_TOPSECRET_TOKEN_9000" ));971 + "reconstruct: secret plaintext never crossed the wire (only smith:sec:N placeholders)" ,974 + let saw_placeholder = tap978 + .any (|line| line.contains ("smith:sec:1" ));980 + "reconstruct: masked placeholder smith:sec:1 did cross the wire" ,992 + fn scn_blocking_roundtrip () -> bool {993 + let (engine, client, _ep, _tap) = wire (200_000 );995 + let mut e = engine.lock ().unwrap ();996 + e.open ("claude-opus-4" , "anthropic" );997 + e.user_says ("run the build" );999 + let executed = e.tool ("call-1" , "run_shell" , json! ({"cmd" : "cargo build" }), "ok" , true );1005 + let replies = client.blocking_replies.lock ().unwrap ();1007 + "blocking-roundtrip: client received tool_call as a server→client REQUEST" ,1008 + replies.iter ().any (|(m, _)| m == "tool_call" ),1012 + "blocking-roundtrip: client's allow reply flowed back; engine executed the tool" ,1019 + .any (|t| t.id == "call-1" && t.status == "done" && ! t.is_error),1023 + let (engine2, client2, _ep2, _tap2) = wire (200_000 );1030 + let mut e = engine2.lock ().unwrap ();1031 + e.open ("claude-opus-4" , "anthropic" );1037 + let reply = e.emit (1039 + json! ({"id" : "call-x" , "name" : "rm" , "input" : {"cmd" : "rm -rf /" }}),1042 + "blocking-roundtrip: engine received a structured reply for the blocking request" ,1043 + reply.map (|r| r.get ("block" ).is_some ()).unwrap_or (false ),1055 + fn scn_classify () -> bool {1057 + let variants: & [(&str , &str , &str )] = & [1059 + ("AgentStart" , "agent_start" , "run lifecycle; observers show 'running'" ),1060 + ("AgentEnd" , "agent_end" , "run lifecycle; observers show 'idle'" ),1061 + ("TurnStart" , "turn_start" , "turn lifecycle" ),1062 + ("TurnEnd" , "turn_end" , "turn lifecycle; a natural cost/context refresh point" ),1063 + ("MessageStart" , "message_start" , "opens a transcript message; carries role/id" ),1064 + ("MessageUpdate" , "message_update" , "message metadata update" ),1065 + ("MessageEnd" , "message_end" , "finalizes a transcript message" ),1066 + ("TextDelta" , "text_delta" , "streamed assistant text; reassembled by id" ),1067 + ("ThinkingDelta" , "thinking_delta" , "streamed reasoning; reassembled by id" ),1068 + ("ToolExecutionStart" , "tool_execution_start" , "opens a tool view" ),1069 + ("ToolExecutionUpdate" , "tool_execution_update" , "per-tool streaming progress" ),1070 + ("ToolExecutionEnd" , "tool_execution_end" , "closes a tool view with result" ),1071 + ("ToolCall (BLOCKING)" , "tool_call" , "§9.8 blockable → REQUEST; client answers allow/block/replace" ),1072 + ("Error" , "error" , "error surface" ),1074 + ("SessionOpen" , "session_open" , "session opened/loaded" ),1075 + ("SessionTree" , "session_tree" , "tree node created; carries {id,parent,kind}+leaf" ),1076 + ("SessionLeaf (switch)" , "session_leaf" , "leaf moved (tree navigation)" ),1077 + ("SessionBeforeSwitch (BLOCKING)" , "session_before_switch" , "§9.8 blockable → REQUEST" ),1078 + ("SessionFork" , "session_fork" , "fork completed → new session id" ),1079 + ("SessionBeforeFork (BLOCKING)" , "session_before_fork" , "§9.8 blockable → REQUEST" ),1080 + ("SessionCompact" , "session_compact" , "fold completed; MUST carry summary_id+covered span" ),1081 + ("SessionBeforeCompact (BLOCKING)" , "session_before_compact" , "§9.8 blockable → REQUEST" ),1082 + ("SecretRegistered" , "secret_registered" , "id+label only; plaintext never crosses (§6.7)" ),1084 + ("SteerEnqueue" , "steer_enqueue" , "queue grew (steer)" ),1085 + ("SteerDeliver" , "steer_deliver" , "queue drained (steer) → recorded as entry" ),1086 + ("FollowupEnqueue" , "followup_enqueue" , "queue grew (follow-up)" ),1087 + ("FollowupDeliver" , "followup_deliver" , "queue drained (follow-up)" ),1089 + ("ModelSelect" , "model_select" , "active model/provider changed" ),1090 + ("Shutdown" , "shutdown" , "engine shutting down" ),1092 + ("UiPanelToggle" , "panel_toggle" , "TUI-internal panel visibility" ),1093 + ("UiResize" , "resize" , "TUI-internal terminal resize" ),1094 + ("UiSelection" , "ui_selection" , "TUI-internal cursor/selection" ),1095 + ("UiFocus" , "ui_focus" , "TUI-internal focus" ),1096 + ("UiScroll" , "ui_scroll" , "TUI-internal scroll offset" ),1099 + println! ("-- EngineEvent classification (framing: line-delimited JSON-RPC 2.0) --" );1100 + let (mut n_note, mut n_req, mut n_priv) = (0 , 0 , 0 );1101 + for (variant, method, why) in variants {1102 + let tag = project (method).tag ();1103 + match project (method) {1104 + Shape::Notification => n_note += 1 ,1105 + Shape::Request => n_req += 1 ,1106 + Shape::PrivateOmitted => n_priv += 1 ,1108 + println! (" {variant:<34} {tag:<24} {why}" );1112 + " tally: notification={n_note} request={n_req} frontend-private-omitted={n_priv} (total {})" ,1118 + println! ("-- MISSING: state a real frontend must render, unreachable over the §10.4 surface --" );1119 + let missing: & [(&str , &str , &str )] = & [1121 + "queue snapshot on attach" ,1122 + "session/queue (or session/snapshot.queue)" ,1123 + "queues are ephemeral process state (§6.1); enqueue/deliver notifications track the queue only from empty. A frontend that ATTACHES to a live session (or reconnects after a drop) cannot fetch the current pending steers/follow-ups — no driver method returns them." ,1126 + "in-flight run status on attach" ,1127 + "session/status (or session/snapshot.run)" ,1128 + "AgentStart/TurnStart/ToolExecutionStart already fired before a late attach; there is no method to read 'a turn is active / tool call-3 is executing'. A reconnecting UI cannot show the current run state." ,1131 + "live cost/context indicator" ,1132 + "usage notification (e.g. context_usage event)" ,1133 + "cost/context is reachable ONLY by polling the getContextUsage data method — there is no push event, so a live ticking cost/context meter must poll. Reachable, but not from the stream." ,1136 + for (state, fix, why) in missing {1137 + println! (" MISSING {state}" );1138 + println! (" closes with: {fix}" );1139 + println! (" why: {why}" );1142 + println! ("-- projection guarantees the surface MUST make (else reconstruct FAILS) --" );1143 + println! (" session_compact MUST carry {{summary_id,start,end}} — the covered span (§6.9 fold" );1144 + println! (" is assembly-time, storage-invisible); without it the fold is unrenderable." );1145 + println! (" session_tree MUST carry the node {{id,parent,kind}} + leaf — else tree/leaf nav" );1146 + println! (" beyond the current leaf is unreachable (branches are emergent, §6.5)." );1152 + let (engine, client, client_ep, _tap) = wire (200_000 );1158 + let mut e = engine.lock ().unwrap ();1160 + e.truth.queue.push (QueueItem { kind: "steer" .into (), text: "first steer" .into () });1161 + e.truth.queue.push (QueueItem { kind: "steer" .into (), text: "second steer" .into () });1166 + let before = client.state.lock ().unwrap ().queue.clone ();1167 + let ok_gap = check (1168 + "classify: late-attach client CANNOT reconstruct the queue from notifications alone" ,1172 + let snapped = client.attach_snapshot (& client_ep);1173 + let after = client.state.lock ().unwrap ().queue.clone ();1174 + let truth_q = engine.lock ().unwrap ().truth.queue.clone ();1175 + let ok_fix = check (1176 + "classify: PROPOSED session/snapshot reconstructs the queue → matches ground truth" ,1177 + snapped && after == truth_q && after.len () == 2 ,1180 + let ok_counts = check (1181 + "classify: every EngineEvent variant tagged (14 agent + 9 session + 4 queue + 2 misc + 5 private UI)" ,1182 + variants.len () == 34 && n_req == 4 && n_priv == 5 && n_note == 25 ,1185 + ok_counts && ok_gap && ok_fix1188 + fn main () -> Result <(), Box <dyn std::error::Error>> {1189 + let scenario = std::env::args().nth (1 ).unwrap_or_else (|| "all" .into ());1190 + let run = |name: &str | -> bool {1192 + "classify" => scn_classify (),1193 + "reconstruct" => scn_reconstruct (),1194 + "blocking-roundtrip" => scn_blocking_roundtrip (),1196 + println! ("unknown scenario {other}" );1202 + let ok = if scenario == "all" {1203 + let names = ["classify" , "reconstruct" , "blocking-roundtrip" ];1204 + let mut all = true ;1206 + println! ("== {n} ==" );1217 + println! ("p28 RESULT: '{scenario}' holds" );1220 + Err (format! ("p28 RESULT: '{scenario}' failed" ).into ())