diff --git a/Cargo.lock b/Cargo.lock index b1a2286a4..60b0995b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2619,6 +2619,7 @@ name = "engram-egress-proto" version = "0.1.0" dependencies = [ "engram-core", + "engram-transport", "nix 0.32.0", "serde", "serde_json", @@ -2803,6 +2804,7 @@ dependencies = [ "bincode", "chrono", "engram-ids", + "engram-transport", "proptest", "serde", "serde_json", @@ -2866,6 +2868,7 @@ dependencies = [ "engram-telemetry", "engram-testkit", "engram-tls", + "engram-transport", "engram-uffd-handler", "futures", "futures-util", diff --git a/crates/engram-agentd/src/proto.rs b/crates/engram-agentd/src/proto.rs index cce19c580..8f9272596 100644 --- a/crates/engram-agentd/src/proto.rs +++ b/crates/engram-agentd/src/proto.rs @@ -608,17 +608,13 @@ where R: AsyncReadExt + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(std::io::Error::new( + let body = engram_transport::framing::read(r, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!("frame length {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; + ) + }) + .await?; bincode::deserialize(&body) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}"))) } @@ -632,19 +628,13 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > MAX_MSG_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, - format!( - "encoded frame {} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})", - body.len() - ), - )); - } - let len = (body.len() as u32).to_be_bytes(); - w.write_all(&len).await?; - w.write_all(&body).await?; - Ok(()) + format!("encoded frame {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), + ) + }) + .await } #[cfg(test)] diff --git a/crates/engram-egress-proto/Cargo.toml b/crates/engram-egress-proto/Cargo.toml index d763853e6..ee29acdd2 100644 --- a/crates/engram-egress-proto/Cargo.toml +++ b/crates/engram-egress-proto/Cargo.toml @@ -23,6 +23,7 @@ unused_dependencies = "allow" disallowed_methods = "deny" [dependencies] +engram-transport.workspace = true engram-core.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/engram-egress-proto/src/lib.rs b/crates/engram-egress-proto/src/lib.rs index 8f316467e..b3ec1d2f8 100644 --- a/crates/engram-egress-proto/src/lib.rs +++ b/crates/engram-egress-proto/src/lib.rs @@ -40,7 +40,7 @@ pub mod manifest; use engram_core::types::egress::SessionEgressPolicy; use engram_core::{SandboxId, SessionId}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; /// Bump on any wire-incompatible change. A mismatch in `Hello` /// position is never adopted — the caller kills and respawns. @@ -184,14 +184,7 @@ where R: AsyncRead + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(oversize(len)); - } - let mut buf = vec![0u8; len]; - r.read_exact(&mut buf).await?; + let buf = engram_transport::framing::read(r, MAX_MSG_BYTES, oversize).await?; serde_json::from_slice(&buf) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } @@ -203,11 +196,7 @@ where T: Serialize, { let body = serde_json::to_vec(msg)?; - if body.len() > MAX_MSG_BYTES { - return Err(oversize(body.len())); - } - w.write_all(&(body.len() as u32).to_be_bytes()).await?; - w.write_all(&body).await?; + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, oversize).await?; w.flush().await } @@ -218,14 +207,7 @@ where R: std::io::Read, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf)?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(oversize(len)); - } - let mut buf = vec![0u8; len]; - r.read_exact(&mut buf)?; + let buf = engram_transport::framing::read_sync(r, MAX_MSG_BYTES, oversize)?; serde_json::from_slice(&buf) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } @@ -237,11 +219,7 @@ where T: Serialize, { let body = serde_json::to_vec(msg)?; - if body.len() > MAX_MSG_BYTES { - return Err(oversize(body.len())); - } - w.write_all(&(body.len() as u32).to_be_bytes())?; - w.write_all(&body)?; + engram_transport::framing::write_sync(w, &body, MAX_MSG_BYTES, oversize)?; w.flush() } diff --git a/crates/engram-harness-claude/src/main.rs b/crates/engram-harness-claude/src/main.rs index ad462ba2c..f92834bac 100644 --- a/crates/engram-harness-claude/src/main.rs +++ b/crates/engram-harness-claude/src/main.rs @@ -53,6 +53,13 @@ mod adapter { use engram_harness_sdk::browser_view; use engram_harness_sdk::questions::{Answers, Question}; use engram_harness_sdk::state::StateDir; + use engram_harness_sdk::tool_manifest::manifest_from_env; + #[cfg(test)] + use engram_harness_sdk::tool_manifest::{ + parse_tool_manifest, with_browser_view, NativeBindings, + }; + pub use engram_harness_sdk::tool_manifest::{ManifestTool, ToolExecution, ToolManifest}; + use engram_harness_sdk::{emit, QueuedPrompt}; use nix::sys::signal::{kill, Signal}; use nix::unistd::Pid; use serde_json::Value; @@ -75,71 +82,6 @@ mod adapter { StateDir::new(&cli.state_dir) } - /// ADR 0089 P2: the orchestrator's model-facing tool manifest. The main - /// harness parses `ENGRAM_TOOLS` once at startup and carries this typed - /// value across every claude respawn. The transient MCP bridge parses its - /// own inherited copy because it is a self-invoked process with no shared - /// address space. - pub type ToolManifest = Vec; - - #[derive(Clone, Debug, serde::Deserialize)] - #[serde(rename_all = "camelCase")] - pub struct ManifestTool { - pub name: String, - pub description: String, - pub input_schema: Value, - pub execution: ToolExecution, - #[serde(default)] - pub native_bindings: NativeBindings, - } - - #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] - #[serde(rename_all = "snake_case")] - pub enum ToolExecution { - Sync, - Deferred, - } - - #[derive(Clone, Debug, Default, serde::Deserialize)] - pub struct NativeBindings { - pub claude: Option, - } - - fn parse_tool_manifest(raw: &str) -> serde_json::Result { - serde_json::from_str(raw) - } - - fn manifest_from_env() -> ToolManifest { - let manifest = match std::env::var("ENGRAM_TOOLS") { - Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { - Ok(manifest) => manifest, - Err(e) => { - tracing::error!(error = %e, "invalid ENGRAM_TOOLS manifest; exposing no injected tools"); - Vec::new() - } - }, - _ => Vec::new(), - }; - with_browser_view(manifest, browser_view::enabled()) - } - - fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { - if enabled - && !manifest - .iter() - .any(|tool| tool.name == browser_view::TOOL_NAME) - { - manifest.push(ManifestTool { - name: browser_view::TOOL_NAME.into(), - description: browser_view::TOOL_DESCRIPTION.into(), - input_schema: browser_view::input_schema(), - execution: ToolExecution::Sync, - native_bindings: NativeBindings::default(), - }); - } - manifest - } - fn injected_tools(manifest: &ToolManifest) -> impl Iterator { manifest .iter() @@ -488,16 +430,6 @@ mod adapter { .await } - /// Push an event to the connection pump. Bounded send: while - /// disconnected the pump can't drain, so this backpressures — - /// pausing the engine (and, transitively, claude via its stdout - /// pipe) rather than losing events. The run resumes when a - /// connection reattaches. Errors only if the receiver is gone, - /// i.e. the process is tearing down; treat as a debug no-op. - async fn emit(evt_tx: &mpsc::Sender, ev: HarnessEvent) { - engram_harness_sdk::emit(evt_tx, ev).await; - } - /// ADR 0054 Flavor B: the hook↔harness socket server and its shared /// state. The harness is a long-lived **server**; each `PreToolUse` /// hook invocation (the `hook-bridge` subcommand) is a transient @@ -1920,7 +1852,7 @@ mod adapter { apply_prompt_mode(&cli, mode.as_deref()); seen_prompt_ids.insert(prompt_id.clone()); pending.push_back(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -2251,31 +2183,6 @@ mod adapter { generations: GenerationLedger, } - /// A prompt waiting in the harness-owned queue (Phase 1b — type-ahead - /// / steering). The harness is the single-writer owner: it buffers - /// these in memory and writes one to claude's stdin only at the - /// consumption boundary (the running turn's `result`). `prompt_id` - /// carries the client/coord-minted id used to correlate the queue - /// events and the eventual `RunStarted{prompt_id}` — issue #535 (d): - /// every prompt, first or follow-up, now arrives via `HarnessCommand:: - /// Prompt`, so this is always `Some` in practice (the historical `None` - /// case was the env-seeded initial prompt, deleted). Kept `Option` - /// rather than force-unwrapping at each read site — a defensive `None` - /// costs nothing here and this isn't a wire type. - struct QueuedPrompt { - prompt_id: Option, - text: String, - /// ADR 0107: the mode directive THIS prompt carried, applied when its - /// turn starts. It has to ride the prompt rather than a process-global - /// latch: with type-ahead the queue holds several prompts, so latching - /// on arrival let a later prompt's mode decide an earlier prompt's turn - /// — including the unsafe direction, where a prompt sent during a - /// read-only pass ran with full write access because a later prompt had - /// switched back to build (PR #927 review). `None` = "no directive", - /// which inherits the session's current mode rather than resetting it. - mode: Option, - } - /// Latch a prompt's mode directive at the moment its turn begins. Returns /// the mode the next turn must run under (the stamp, post-write). fn apply_prompt_mode(cli: &Cli, mode: Option<&str>) -> String { @@ -2562,8 +2469,15 @@ mod adapter { Some(qp) => { if let Some(s) = stdin.as_mut() { turn = Some( - start_turn(evt_tx, s, cli, qp.prompt_id, &qp.text, current_run_id) - .await, + start_turn( + evt_tx, + s, + cli, + Some(qp.prompt_id), + &qp.text, + current_run_id, + ) + .await, ); } // A respawn-surviving queue can hold more than one @@ -2897,7 +2811,7 @@ mod adapter { { tracing::info!( prompt_id = - qp.prompt_id.as_deref().unwrap_or(""), + qp.prompt_id.as_str(), current = %process_mode, "mode change at consumption boundary: clean respawn" ); @@ -2912,7 +2826,7 @@ mod adapter { evt_tx, s, cli, - qp.prompt_id, + Some(qp.prompt_id), &qp.text, current_run_id, ) @@ -3077,7 +2991,7 @@ mod adapter { // process picks its argv off the stamp. apply_prompt_mode(cli, mode.as_deref()); pending.push_front(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -3181,7 +3095,7 @@ mod adapter { ) .await; pending.push_back(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -3266,7 +3180,7 @@ mod adapter { let summary = Some(truncate_str(&text, MAX_ARGS_SUMMARY_BYTES)); let found = match pending .iter_mut() - .find(|q| q.prompt_id.as_deref() == Some(prompt_id.as_str())) + .find(|q| q.prompt_id == prompt_id) { Some(qp) => { qp.text = text; @@ -3287,7 +3201,7 @@ mod adapter { Some(HarnessCommand::DequeueQueued { prompt_id }) => { let before = pending.len(); pending - .retain(|q| q.prompt_id.as_deref() != Some(prompt_id.as_str())); + .retain(|q| q.prompt_id != prompt_id); if pending.len() != before { emit(evt_tx, HarnessEvent::PromptDequeued { prompt_id }).await; } else { @@ -7284,6 +7198,7 @@ mod adapter { execution: ToolExecution::Deferred, native_bindings: NativeBindings { claude: Some("AskUserQuestion".into()), + ..Default::default() }, } } @@ -8854,6 +8769,7 @@ async fn main() -> std::process::ExitCode { mod tests { use super::adapter::*; use engram_harness_proto::{FileChange, HarnessEvent}; + use engram_harness_sdk::tool_manifest::NativeBindings; use std::collections::HashMap; #[test] @@ -9709,6 +9625,7 @@ mod tests { execution: ToolExecution::Deferred, native_bindings: NativeBindings { claude: Some("ExitPlanMode".into()), + ..Default::default() }, }]; let deferred_names = deferred_tool_names(&manifest); diff --git a/crates/engram-harness-codex/src/main.rs b/crates/engram-harness-codex/src/main.rs index dad0c4e00..40d29f305 100644 --- a/crates/engram-harness-codex/src/main.rs +++ b/crates/engram-harness-codex/src/main.rs @@ -13,6 +13,9 @@ use engram_harness_sdk::browser_view; use engram_harness_sdk::parked::{ParkedCall, ParkedCallKind, ParkedCallStore}; use engram_harness_sdk::questions::{Answers, Question, QuestionOption}; use engram_harness_sdk::state::StateDir; +use engram_harness_sdk::tool_manifest::{manifest_from_env, ToolExecution, ToolManifest}; +#[cfg(test)] +use engram_harness_sdk::tool_manifest::{parse_tool_manifest, with_browser_view}; use engram_harness_sdk::{emit, Channels, ConnectionConfig, QueuedPrompt}; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; @@ -23,107 +26,11 @@ const MAX_SUMMARY: usize = 4096; const MAX_OAUTH_BUNDLE_BYTES: usize = 256 * 1024; const OPENAI_CODEX_PROVIDER: &str = "openai-codex"; -type ToolManifest = Vec; - -#[derive(Clone, Debug)] -struct ManifestTool { - name: String, - description: String, - input_schema: Value, - execution: ToolExecution, - codex_native_binding: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ToolExecution { - Sync, - Deferred, -} - -fn parse_tool_manifest(raw: &str) -> Result { - let value: Value = serde_json::from_str(raw).map_err(|error| error.to_string())?; - let entries = value - .as_array() - .ok_or("ENGRAM_TOOLS must be a JSON array")?; - entries - .iter() - .map(|entry| { - let object = entry - .as_object() - .ok_or("ENGRAM_TOOLS entries must be objects")?; - let required_string = |field: &str| { - object - .get(field) - .and_then(Value::as_str) - .map(str::to_owned) - .ok_or_else(|| format!("ENGRAM_TOOLS entry missing string {field}")) - }; - let execution = match required_string("execution")?.as_str() { - "sync" => ToolExecution::Sync, - "deferred" => ToolExecution::Deferred, - other => return Err(format!("invalid ENGRAM_TOOLS execution {other}")), - }; - let codex_native_binding = match object.get("nativeBindings") { - None => None, - Some(Value::Object(bindings)) => match bindings.get("codex") { - None | Some(Value::Null) => None, - Some(Value::String(binding)) => Some(binding.clone()), - Some(_) => { - return Err("ENGRAM_TOOLS nativeBindings.codex must be a string".to_string()) - } - }, - Some(_) => return Err("ENGRAM_TOOLS nativeBindings must be an object".to_string()), - }; - Ok(ManifestTool { - name: required_string("name")?, - description: required_string("description")?, - input_schema: object - .get("inputSchema") - .cloned() - .ok_or("ENGRAM_TOOLS entry missing inputSchema")?, - execution, - codex_native_binding, - }) - }) - .collect() -} - -fn manifest_from_env() -> ToolManifest { - let manifest = match std::env::var("ENGRAM_TOOLS") { - Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { - Ok(manifest) => manifest, - Err(error) => { - tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no dynamic tools"); - Vec::new() - } - }, - _ => Vec::new(), - }; - with_browser_view(manifest, browser_view::enabled()) -} - -fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { - if enabled - && !manifest - .iter() - .any(|tool| tool.name == browser_view::TOOL_NAME) - { - manifest.push(ManifestTool { - name: browser_view::TOOL_NAME.into(), - description: browser_view::TOOL_DESCRIPTION.into(), - input_schema: browser_view::input_schema(), - execution: ToolExecution::Sync, - codex_native_binding: None, - }); - } - manifest -} - fn dynamic_tools(manifest: &ToolManifest) -> Value { Value::Array( manifest .iter() - .filter(|tool| tool.codex_native_binding.is_none()) + .filter(|tool| tool.native_bindings.codex.is_none()) .map(|tool| { json!({ "name": tool.name, @@ -1329,7 +1236,7 @@ async fn handle_dynamic_tool_call( }; let Some(tool) = manifest .iter() - .find(|tool| tool.name == tool_name && tool.codex_native_binding.is_none()) + .find(|tool| tool.name == tool_name && tool.native_bindings.codex.is_none()) else { tracing::error!(%call_id, %tool_name, "Codex requested an undeclared dynamic tool"); let _ = server @@ -1870,7 +1777,7 @@ async fn handle_message( let native_tool = tools .manifest .iter() - .find(|tool| tool.codex_native_binding.as_deref() == Some("requestUserInput")) + .find(|tool| tool.native_bindings.codex.as_deref() == Some("requestUserInput")) .map(|tool| tool.name.clone()); let tool_name = native_tool.unwrap_or_else(|| { tracing::warn!( diff --git a/crates/engram-harness-proto/Cargo.toml b/crates/engram-harness-proto/Cargo.toml index cad31e375..d281b7f79 100644 --- a/crates/engram-harness-proto/Cargo.toml +++ b/crates/engram-harness-proto/Cargo.toml @@ -14,6 +14,7 @@ workspace = true path = "src/lib.rs" [dependencies] +engram-transport.workspace = true async-trait.workspace = true bincode.workspace = true chrono.workspace = true diff --git a/crates/engram-harness-proto/src/lib.rs b/crates/engram-harness-proto/src/lib.rs index ac9f5c1f2..2c5019778 100644 --- a/crates/engram-harness-proto/src/lib.rs +++ b/crates/engram-harness-proto/src/lib.rs @@ -875,25 +875,19 @@ pub struct RelayAck { // ---- Framing ----------------------------------------------------------- -/// Read one length-prefixed bincode frame. Mirrors -/// `engram-agentd::proto::read_msg` so adapters can share a single -/// codec. +/// Read one length-prefixed bincode frame. pub async fn read_msg(r: &mut R) -> std::io::Result where R: AsyncReadExt + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(std::io::Error::new( + let body = engram_transport::framing::read(r, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!("harness frame length {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; + ) + }) + .await?; bincode::deserialize(&body) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}"))) } @@ -907,19 +901,13 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > MAX_MSG_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, - format!( - "encoded harness frame {} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})", - body.len() - ), - )); - } - let len = (body.len() as u32).to_be_bytes(); - w.write_all(&len).await?; - w.write_all(&body).await?; - Ok(()) + format!("encoded harness frame {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), + ) + }) + .await } #[cfg(test)] diff --git a/crates/engram-harness-sdk/src/lib.rs b/crates/engram-harness-sdk/src/lib.rs index cf4152d82..c46240c49 100644 --- a/crates/engram-harness-sdk/src/lib.rs +++ b/crates/engram-harness-sdk/src/lib.rs @@ -12,6 +12,7 @@ pub mod parked; pub mod plan; pub mod questions; pub mod state; +pub mod tool_manifest; pub mod turn_context; use std::collections::{HashSet, VecDeque}; @@ -674,13 +675,7 @@ async fn pump_events( pub struct QueuedPrompt { pub prompt_id: String, pub text: String, - /// ADR 0107: the mode directive THIS prompt carried, applied when its turn - /// starts. It rides the prompt rather than a process-global latch because - /// the queue holds several prompts under type-ahead: latching on arrival - /// let a later prompt's mode decide an earlier prompt's turn, including - /// the unsafe direction where a prompt sent during a read-only pass ran - /// with full write access (PR #927 review). `None` inherits the session's - /// current mode rather than resetting it. + /// Applied when this prompt starts. `None` inherits the session mode. pub mode: Option, } diff --git a/crates/engram-harness-sdk/src/tool_manifest.rs b/crates/engram-harness-sdk/src/tool_manifest.rs new file mode 100644 index 000000000..f78906422 --- /dev/null +++ b/crates/engram-harness-sdk/src/tool_manifest.rs @@ -0,0 +1,145 @@ +//! Tool manifests and built-in browser tools shared by harness adapters. + +use crate::browser_view; +use serde_json::Value; + +pub type ToolManifest = Vec; + +/// One entry of the orchestrator's `ENGRAM_TOOLS` manifest. +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ManifestTool { + pub name: String, + pub description: String, + pub input_schema: Value, + pub execution: ToolExecution, + #[serde(default)] + pub native_bindings: NativeBindings, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolExecution { + Sync, + Deferred, +} + +/// The provider-native tool that stands in for a manifest tool. +#[derive(Clone, Debug, Default, serde::Deserialize)] +pub struct NativeBindings { + pub claude: Option, + pub codex: Option, +} + +pub fn parse_tool_manifest(raw: &str) -> serde_json::Result { + serde_json::from_str(raw) +} + +/// The `ENGRAM_TOOLS` manifest plus the built-in browser tool. An invalid +/// manifest exposes no injected tools. +pub fn manifest_from_env() -> ToolManifest { + let manifest = match std::env::var("ENGRAM_TOOLS") { + Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { + Ok(manifest) => manifest, + Err(error) => { + tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no injected tools"); + Vec::new() + } + }, + _ => Vec::new(), + }; + with_browser_view(manifest, browser_view::enabled()) +} + +pub fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { + if enabled + && !manifest + .iter() + .any(|tool| tool.name == browser_view::TOOL_NAME) + { + manifest.push(ManifestTool { + name: browser_view::TOOL_NAME.into(), + description: browser_view::TOOL_DESCRIPTION.into(), + input_schema: browser_view::input_schema(), + execution: ToolExecution::Sync, + native_bindings: NativeBindings::default(), + }); + } + manifest +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn tool() -> Value { + json!({"name":"ask", "description":"Ask a question", "inputSchema":{}, + "execution":"deferred", "nativeBindings":{ + "claude":"AskUserQuestion", "codex":"requestUserInput" + }}) + } + + #[test] + fn manifests_keep_every_providers_native_binding() { + let manifest = parse_tool_manifest(&json!([tool()]).to_string()).unwrap(); + assert_eq!(manifest[0].name, "ask"); + assert_eq!(manifest[0].execution, ToolExecution::Deferred); + assert_eq!( + manifest[0].native_bindings.claude.as_deref(), + Some("AskUserQuestion") + ); + assert_eq!( + manifest[0].native_bindings.codex.as_deref(), + Some("requestUserInput") + ); + } + + #[test] + fn malformed_manifests_are_rejected() { + for raw in ["not json", "{}", "[null]", "[{}]"] { + assert!(parse_tool_manifest(raw).is_err()); + } + for field in ["name", "description", "execution", "nativeBindings"] { + let mut entry = tool(); + entry[field] = json!(123); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); + } + for provider in ["claude", "codex"] { + let mut entry = tool(); + entry["nativeBindings"][provider] = json!(123); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); + } + let mut entry = tool(); + entry.as_object_mut().unwrap().remove("inputSchema"); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); + } + + #[test] + fn bindings_are_optional() { + let mut entry = tool(); + entry.as_object_mut().unwrap().remove("nativeBindings"); + let manifest = parse_tool_manifest(&json!([entry]).to_string()).unwrap(); + assert!(manifest[0].native_bindings.claude.is_none()); + assert!(manifest[0].native_bindings.codex.is_none()); + let mut entry = tool(); + entry["nativeBindings"] = json!({"codex": null, "other": {"x": 1}}); + let manifest = parse_tool_manifest(&json!([entry]).to_string()).unwrap(); + assert!(manifest[0].native_bindings.claude.is_none()); + assert!(manifest[0].native_bindings.codex.is_none()); + } + + #[test] + fn browser_tool_is_optional_and_never_replaces_an_existing_entry() { + assert!(with_browser_view(Vec::new(), false).is_empty()); + let mut manifest = with_browser_view(Vec::new(), true); + assert_eq!(manifest.len(), 1); + assert_eq!(manifest[0].name, browser_view::TOOL_NAME); + assert_eq!(manifest[0].input_schema, browser_view::input_schema()); + manifest[0].description = "Custom browser tool".into(); + let manifest = with_browser_view(manifest, true); + assert_eq!(manifest.len(), 1); + assert_eq!(manifest[0].description, "Custom browser tool"); + assert_eq!(with_browser_view(manifest, false).len(), 1); + } +} diff --git a/crates/engram-host-agent/Cargo.toml b/crates/engram-host-agent/Cargo.toml index e94602d74..496ce9105 100644 --- a/crates/engram-host-agent/Cargo.toml +++ b/crates/engram-host-agent/Cargo.toml @@ -42,6 +42,7 @@ engram-chunk-store.workspace = true engram-fill.workspace = true engram-substrate-proto.workspace = true engram-migrate-proto.workspace = true +engram-transport.workspace = true engram-storage-local.workspace = true engram-blob-client.workspace = true engram-cloud-sql.workspace = true diff --git a/crates/engram-host-agent/src/migrate_peer.rs b/crates/engram-host-agent/src/migrate_peer.rs index 54aa54a95..5acf9e9d5 100644 --- a/crates/engram-host-agent/src/migrate_peer.rs +++ b/crates/engram-host-agent/src/migrate_peer.rs @@ -41,7 +41,7 @@ use engram_migrate_proto::{ read_frame, write_frame, FromSource, SealBitmap, ToSource, PROTO_VERSION, }; use sha2::{Digest, Sha256}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::AsyncWriteExt; use tokio::sync::{Notify, Semaphore}; use crate::dirty_map::GuestVma; @@ -724,21 +724,16 @@ pub(crate) async fn read_body_async(r: &mut R) -> std::io::Result> where R: tokio::io::AsyncRead + Unpin, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > engram_migrate_proto::MAX_FRAME_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::read(r, engram_migrate_proto::MAX_FRAME_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!( "frame length {len} exceeds MAX_FRAME_BYTES ({})", engram_migrate_proto::MAX_FRAME_BYTES ), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; - Ok(body) + ) + }) + .await } /// Write one length-prefixed frame asynchronously (mirror of @@ -753,18 +748,16 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > engram_migrate_proto::MAX_FRAME_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, engram_migrate_proto::MAX_FRAME_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!( - "encoded frame {} exceeds MAX_FRAME_BYTES ({})", - body.len(), + "encoded frame {len} exceeds MAX_FRAME_BYTES ({})", engram_migrate_proto::MAX_FRAME_BYTES ), - )); - } - w.write_all(&(body.len() as u32).to_be_bytes()).await?; - w.write_all(&body).await?; + ) + }) + .await?; w.flush().await?; Ok(()) } diff --git a/crates/engram-transport/Cargo.toml b/crates/engram-transport/Cargo.toml index 179624a60..7f6476988 100644 --- a/crates/engram-transport/Cargo.toml +++ b/crates/engram-transport/Cargo.toml @@ -16,8 +16,6 @@ tokio.workspace = true tracing.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } -# vsock is a Linux-only kernel feature. The transport compiles only on -# Linux; on macOS / other hosts the crate is an empty shell so the -# workspace cargo check stays green everywhere. +# Vsock requires Linux. Framing and transport traits are cross-platform. [target.'cfg(target_os = "linux")'.dependencies] tokio-vsock = "0.7" diff --git a/crates/engram-transport/src/framing.rs b/crates/engram-transport/src/framing.rs new file mode 100644 index 000000000..00d37af31 --- /dev/null +++ b/crates/engram-transport/src/framing.rs @@ -0,0 +1,145 @@ +//! Four-byte big-endian length prefixes with caller-owned limits and errors. +//! The prefix counts the body only, not itself. + +use std::io; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +/// Read a frame. Reject the length before allocating or reading the body. +/// Not cancel safe: dropping the future mid-frame loses the stream position. +pub async fn read( + reader: &mut R, + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result> { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix).await?; + let mut body = vec![0; body_len(prefix, max_bytes, oversize)?]; + reader.read_exact(&mut body).await?; + Ok(body) +} + +/// Write a frame without flushing. Reject oversized bodies before writing. +pub async fn write( + writer: &mut W, + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<()> { + writer + .write_all(&prefix(body, max_bytes, oversize)?) + .await?; + writer.write_all(body).await +} + +/// Blocking [`read`]. +pub fn read_sync( + reader: &mut R, + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result> { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix)?; + let mut body = vec![0; body_len(prefix, max_bytes, oversize)?]; + reader.read_exact(&mut body)?; + Ok(body) +} + +/// Blocking [`write`]. +pub fn write_sync( + writer: &mut W, + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<()> { + writer.write_all(&prefix(body, max_bytes, oversize)?)?; + writer.write_all(body) +} + +fn body_len( + prefix: [u8; 4], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result { + let len = u32::from_be_bytes(prefix) as usize; + if len > max_bytes { + return Err(oversize(len)); + } + Ok(len) +} + +fn prefix( + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<[u8; 4]> { + let len = body.len(); + match u32::try_from(len) { + Ok(wire) if len <= max_bytes => Ok(wire.to_be_bytes()), + _ => Err(oversize(len)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn oversize(len: usize) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, format!("too large: {len}")) + } + + #[tokio::test] + async fn frames_keep_the_wire_bytes_and_boundaries() { + let mut wire = Vec::new(); + write(&mut wire, b"abc", 3, oversize).await.unwrap(); + write(&mut wire, b"", 3, oversize).await.unwrap(); + assert_eq!(wire, b"\0\0\0\x03abc\0\0\0\0"); + let mut reader = wire.as_slice(); + assert_eq!(read(&mut reader, 3, oversize).await.unwrap(), b"abc"); + assert!(read(&mut reader, 3, oversize).await.unwrap().is_empty()); + assert!(reader.is_empty()); + } + + #[tokio::test] + async fn limits_reject_before_body_io() { + let mut reader = &b"\0\0\0\x04body"[..]; + let error = read(&mut reader, 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "too large: 4"); + assert_eq!(reader, b"body"); + let mut wire = Vec::new(); + let error = write(&mut wire, b"body", 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "too large: 4"); + assert!(wire.is_empty()); + } + + #[tokio::test] + async fn truncated_frames_preserve_io_errors() { + let wire = b"\0\0\0\x03abc"; + for end in 0..wire.len() { + let error = read(&mut &wire[..end], 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + } + } + + #[test] + fn sync_and_async_frames_share_the_wire_format() { + let mut wire = Vec::new(); + write_sync(&mut wire, b"abc", 3, oversize).unwrap(); + assert_eq!(wire, b"\0\0\0\x03abc"); + assert_eq!( + read_sync(&mut wire.as_slice(), 3, oversize).unwrap(), + b"abc" + ); + let error = write_sync(&mut Vec::new(), b"body", 3, oversize).unwrap_err(); + assert_eq!(error.to_string(), "too large: 4"); + let mut reader = &b"\0\0\0\x04body"[..]; + let error = read_sync(&mut reader, 3, oversize).unwrap_err(); + assert_eq!(error.to_string(), "too large: 4"); + assert_eq!(reader, b"body"); + for end in 0..wire.len() { + let error = read_sync(&mut &wire[..end], 3, oversize).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + } + } +} diff --git a/crates/engram-transport/src/lib.rs b/crates/engram-transport/src/lib.rs index 2f1494dfa..b2f4dad75 100644 --- a/crates/engram-transport/src/lib.rs +++ b/crates/engram-transport/src/lib.rs @@ -5,21 +5,6 @@ //! bind / dial without knowing which VMM is hosting the VM. One impl //! ships: `VsockTransport` (virtio-vsock), used by **both** backends. //! -//! # Why vsock everywhere -//! -//! - **Firecracker** exposes virtio-vsock as its only host↔guest -//! programmatic channel. (FC also has a 16550A serial UART, but no -//! virtio-console device — see the FAQ.) -//! -//! - **Apple Virtualization.framework (VZ)** exposes a real -//! `VZVirtioSocketDevice`. VZ briefly bridged these channels over a -//! multi-port virtio-console (single byte stream per port → head-of-line -//! blocking on the ADR 0066 port relay) because generic arm64 -//! cloud-image kernels ship `CONFIG_VIRTIO_VSOCKETS` as a *module*. -//! But the Kata guest kernel VZ actually boots (`just pull-kernel`) -//! ships it built-in, so ADR 0066 Phase 2 migrated VZ back to real -//! vsock — the console transport is retired. -//! //! # Selection //! //! The [`from_env`] factory reads `ENGRAM_TRANSPORT` (default @@ -34,15 +19,9 @@ //! per connection) with no head-of-line blocking — the property the //! ADR 0066 port relay depends on. //! -//! # Cross-platform shell +//! # Platform support //! -//! The impl is Linux-only. On macOS / other hosts the crate compiles -//! to an empty shell — the in-VM binaries themselves are Linux-only -//! too (the workspace's `engram-agentd` / `engram-harness-*` binaries -//! already wrap their `main` in `#[cfg(target_os = "linux")]`), so -//! this just keeps `cargo check --workspace` green on Apple Silicon. - -#![cfg_attr(not(target_os = "linux"), allow(dead_code))] +//! Vsock is Linux-only. Framing and transport traits are available on all hosts. use std::io; use std::pin::Pin; @@ -53,6 +32,8 @@ use tokio::io::{AsyncRead, AsyncWrite}; #[cfg(target_os = "linux")] mod vsock; +pub mod framing; + #[cfg(target_os = "linux")] pub use vsock::VsockTransport; @@ -66,10 +47,7 @@ impl AsyncReadWrite for T {} /// Owned duplex byte stream over the chosen transport. pub type BoxedStream = Pin>; -/// Connection-accepting half of a [`Transport`]. Yields a fresh -/// stream per [`accept`](Listener::accept) call on transports that -/// support it (vsock); yields the stream once then EOFs on those -/// that don't (virtio-console). +/// Connection-accepting half of a [`Transport`]. Each accept yields a fresh stream. #[async_trait] pub trait Listener: Send { async fn accept(&mut self) -> io::Result; @@ -88,15 +66,18 @@ pub trait Transport: Send + Sync { /// Build a [`Transport`] from the `ENGRAM_TRANSPORT` env var. /// -/// Defaults to `vsock` if unset. Every bake sets `ENGRAM_TRANSPORT=vsock`; -/// the knob stays a seam for a future non-vsock backend but today only -/// `vsock` is valid (the virtio-console transport was retired in ADR 0066 -/// Phase 2). +/// Defaults to `vsock` if unset. Only `vsock` is supported. #[cfg(target_os = "linux")] pub fn from_env() -> io::Result> { - let raw = std::env::var("ENGRAM_TRANSPORT").unwrap_or_else(|_| "vsock".into()); - match raw.as_str() { - "vsock" => Ok(Box::new(VsockTransport)), + let raw = std::env::var("ENGRAM_TRANSPORT").ok(); + parse_transport(raw.as_deref())?; + Ok(Box::new(VsockTransport)) +} + +#[cfg(any(target_os = "linux", test))] +fn parse_transport(raw: Option<&str>) -> io::Result<()> { + match raw.unwrap_or("vsock") { + "vsock" => Ok(()), other => Err(io::Error::new( io::ErrorKind::InvalidInput, format!("unknown ENGRAM_TRANSPORT={other:?}; expected vsock"), @@ -115,7 +96,6 @@ pub fn from_env() -> io::Result> { } #[cfg(test)] -#[cfg(target_os = "linux")] mod tests { use super::*; @@ -123,18 +103,22 @@ mod tests { /// reject unknown values with a clear error message. #[test] fn from_env_defaults_to_vsock_and_rejects_garbage() { - // SAFETY for std::env::set_var: this test is single-threaded - // (one #[test] per module call), but cargo test runs tests in - // parallel by default. We avoid races by not actually reading - // env in this test — we'd test the parse logic separately if - // we exposed it. For now the contract is documented and the - // dispatch is trivial. - // The doc-test above is the actual coverage. + assert!(parse_transport(None).is_ok()); + assert!(parse_transport(Some("vsock")).is_ok()); + for raw in ["", "garbage", "console", "VSOCK", " vsock"] { + let error = parse_transport(Some(raw)).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert_eq!( + error.to_string(), + format!("unknown ENGRAM_TRANSPORT={raw:?}; expected vsock") + ); + } } /// Smoke: VsockTransport impls Send+Sync so it can ride in /// `Box`. #[test] + #[cfg(target_os = "linux")] fn transports_are_send_sync() { fn assert_send_sync() {} assert_send_sync::(); diff --git a/crates/engram-tui/src/app.rs b/crates/engram-tui/src/app.rs index 2d0487fa1..75a508580 100644 --- a/crates/engram-tui/src/app.rs +++ b/crates/engram-tui/src/app.rs @@ -695,7 +695,6 @@ pub enum Screen { #[derive(Debug)] pub struct App { - pub screen: Screen, pub sessions: SessionList, pub attached: Option, /// The palette overlay (Ctrl+P) reuses the session list with this @@ -737,9 +736,16 @@ pub struct App { } impl App { + /// The attached session is the single source of screen state. + pub fn screen(&self) -> Screen { + match self.attached { + Some(_) => Screen::Attached, + None => Screen::Sessions, + } + } + pub fn new(inline: bool, width: u16, height: u16) -> Self { App { - screen: Screen::Sessions, sessions: SessionList { loading: true, ..Default::default() @@ -786,7 +792,7 @@ impl App { /// is on screen, 15 s for the terminal's records alone, doubled per /// failed load in a row up to a minute. pub fn poll_interval(&self) -> Duration { - let base = if self.screen == Screen::Sessions || self.palette { + let base = if self.screen() == Screen::Sessions || self.palette { 5 } else { 15 @@ -797,7 +803,7 @@ impl App { /// Is anything showing the session list: the terminal's records, the /// list, or the palette? pub fn wants_poll(&self) -> bool { - self.program_status || self.screen == Screen::Sessions || self.palette + self.program_status || self.screen() == Screen::Sessions || self.palette } pub fn note(&mut self, text: impl Into) { @@ -828,7 +834,6 @@ impl App { .as_ref() .is_some_and(|a| a.session_id == session_id) { - self.screen = Screen::Attached; self.palette = false; return; } @@ -848,7 +853,6 @@ impl App { self.attach_seq += 1; self.unseen = None; self.inbox.opened(session_id); - self.screen = Screen::Attached; self.palette = false; self.cmds.push(Cmd::Attach { session_id: session_id.to_string(), @@ -861,7 +865,6 @@ impl App { } self.attach_seq += 1; self.unseen = None; - self.screen = Screen::Sessions; self.sessions.filter.clear(); self.sessions.loading = true; self.cmds.push(Cmd::LoadSessions); @@ -948,7 +951,7 @@ impl App { NewStage::Prompt => ns.composer.paste(&text), NewStage::Pick => ns.filter.push_str(text.trim()), } - } else if self.screen == Screen::Attached && !self.palette { + } else if self.screen() == Screen::Attached && !self.palette { if let Some(a) = &mut self.attached { if let Some(sh) = a.shell.as_ref().filter(|s| s.focused && s.connected) { let mut out = Vec::with_capacity(text.len() + 12); @@ -973,9 +976,6 @@ impl App { let Some(a) = &mut self.attached else { return; }; - if self.screen != Screen::Attached { - return; - } // The transcript row under the pointer, clamped into the rows // the last frame showed (a drag past the edge keeps selecting). let hit = |a: &Attached, clamp: bool| -> Option<(usize, u16, u16)> { @@ -1054,7 +1054,7 @@ impl App { } return; } - if self.screen == Screen::Attached + if self.screen() == Screen::Attached && !self.palette && self .attached @@ -1093,7 +1093,7 @@ impl App { } if self.new_session.is_some() { self.new_session_key(action); - } else if self.screen == Screen::Sessions || self.palette { + } else if self.screen() == Screen::Sessions || self.palette { self.list_key(action); } else if self.attached.as_ref().is_some_and(|a| a.search.is_some()) { self.search_key(action); diff --git a/crates/engram-tui/src/render.rs b/crates/engram-tui/src/render.rs index 4797dd145..ac2e628d6 100644 --- a/crates/engram-tui/src/render.rs +++ b/crates/engram-tui/src/render.rs @@ -8,7 +8,7 @@ use ratatui::layout::{Position, Rect}; use ratatui::style::{Color, Modifier, Style}; use unicode_segmentation::UnicodeSegmentation; -use crate::app::{shell_pane_rows, App, Attached, NewSession, NewStage, Screen}; +use crate::app::{shell_pane_rows, App, Attached, NewSession, NewStage}; use crate::keymap::BINDINGS; use crate::markdown::{flags, Run}; use crate::palette::{is_light, Palette}; @@ -1408,8 +1408,8 @@ fn draw_footer(buf: &mut Buffer, area: Rect, app: &App, th: &Theme) { put(buf, area.x, y, hint, w, th.dim); return; } - match (&app.attached, app.screen) { - (Some(a), Screen::Attached) => { + match &app.attached { + Some(a) => { let s = status_word(a); let st = if a.reducer.awaiting_decision() { th.warn @@ -1461,7 +1461,7 @@ fn draw_footer(buf: &mut Buffer, area: Rect, app: &App, th: &Theme) { put(buf, area.x + cx, y, short, avail, th.dim); } } - _ => { + None => { let n = app.sessions.rows.len(); cx += put(buf, area.x, y, " ", 1, th.dim); cx += put_num(buf, area.x + cx, y, n as u64, th.dim); @@ -1813,6 +1813,98 @@ fn draw_help(buf: &mut Buffer, area: Rect, th: &Theme) { shade(buf, r, th); } +fn draw_attached_fullscreen( + buf: &mut Buffer, + body: Rect, + footer: Rect, + a: &mut Attached, + th: &Theme, + scratch: &mut Vec<(usize, u16)>, +) -> (Option, bool) { + let width = body.width.saturating_sub(2).max(1); + a.composer.layout(width); + let composer_rows = a.composer.rows().len().clamp(1, 8) as u16; + let queue_rows = (a.reducer.queued.len() as u16).min(4); + // The composer and its queue sit between two rules when the + // screen has the rows for them. + let rules = u16::from(body.height >= 8); + let rule_below = Rect { + y: body.bottom().saturating_sub(1), + height: rules, + ..body + }; + let composer = Rect { + y: body.bottom().saturating_sub(rules + composer_rows), + height: composer_rows.min(body.height), + ..body + }; + let queue = Rect { + y: composer.y.saturating_sub(queue_rows), + height: queue_rows.min(composer.y - body.y), + ..body + }; + let rule_above = Rect { + y: queue.y.saturating_sub(rules), + height: rules, + ..body + }; + let title_h = u16::from(body.height > 4); + let shell_rows = if a.shell.is_some() { + shell_pane_rows(body.height).min(rule_above.y.saturating_sub(body.y + title_h)) + } else { + 0 + }; + let shell = Rect { + y: rule_above.y.saturating_sub(shell_rows), + height: shell_rows, + ..body + }; + let slash_h = slash_rows(a.composer.text()).min(shell.y.saturating_sub(body.y + title_h)); + let slash = Rect { + y: shell.y.saturating_sub(slash_h), + height: slash_h, + ..body + }; + let transcript = Rect { + y: body.y + title_h, + height: slash.y.saturating_sub(body.y + title_h), + ..body + }; + a.page_rows = transcript.height; + if title_h == 1 { + put( + buf, + body.x + 1, + body.y, + &a.title, + body.width.saturating_sub(1), + th.accent, + ); + } + let want_older = draw_transcript(buf, transcript, a, th, scratch); + if slash.height > 0 { + draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); + shade(buf, slash, th); + } + draw_rule(buf, rule_above, th); + draw_queue(buf, queue, a, th); + let mut cursor = Some(draw_composer(buf, composer, a, th)); + draw_rule(buf, rule_below, th); + if shell.height > 0 { + if let Some(c) = draw_shell(buf, shell, a, th) { + cursor = Some(c); + } + } + if let Some(s) = &a.search { + let qx = 2 + display_width(&s.query) as u16; + cursor = Some(Position::new( + footer.x + qx.min(footer.width.saturating_sub(1)), + footer.y, + )); + } + (cursor, want_older) +} + /// Fullscreen frame: transcript, queue rail, composer, footer; the /// session list or palette over it. Returns the cursor position and /// whether the transcript walk wants older history. @@ -1836,99 +1928,13 @@ pub fn draw_fullscreen( height: area.height - 1, ..area }; - let mut cursor = None; - let mut want_older = false; - match app.screen { - Screen::Sessions => draw_sessions(buf, body, app, th, "engrams · sessions"), - Screen::Attached => { - let a = app - .attached - .as_mut() - .expect("attached screen has a session"); - let width = body.width.saturating_sub(2).max(1); - a.composer.layout(width); - let composer_rows = a.composer.rows().len().clamp(1, 8) as u16; - let queue_rows = (a.reducer.queued.len() as u16).min(4); - // The composer and its queue sit between two rules when the - // screen has the rows for them. - let rules = u16::from(body.height >= 8); - let rule_below = Rect { - y: body.bottom().saturating_sub(1), - height: rules, - ..body - }; - let composer = Rect { - y: body.bottom().saturating_sub(rules + composer_rows), - height: composer_rows.min(body.height), - ..body - }; - let queue = Rect { - y: composer.y.saturating_sub(queue_rows), - height: queue_rows.min(composer.y - body.y), - ..body - }; - let rule_above = Rect { - y: queue.y.saturating_sub(rules), - height: rules, - ..body - }; - let title_h = u16::from(body.height > 4); - let shell_rows = if a.shell.is_some() { - shell_pane_rows(body.height).min(rule_above.y.saturating_sub(body.y + title_h)) - } else { - 0 - }; - let shell = Rect { - y: rule_above.y.saturating_sub(shell_rows), - height: shell_rows, - ..body - }; - let slash_h = - slash_rows(a.composer.text()).min(shell.y.saturating_sub(body.y + title_h)); - let slash = Rect { - y: shell.y.saturating_sub(slash_h), - height: slash_h, - ..body - }; - let transcript = Rect { - y: body.y + title_h, - height: slash.y.saturating_sub(body.y + title_h), - ..body - }; - a.page_rows = transcript.height; - if title_h == 1 { - put( - buf, - body.x + 1, - body.y, - &a.title, - body.width.saturating_sub(1), - th.accent, - ); - } - want_older = draw_transcript(buf, transcript, a, th, scratch); - if slash.height > 0 { - draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); - shade(buf, slash, th); - } - draw_rule(buf, rule_above, th); - draw_queue(buf, queue, a, th); - cursor = Some(draw_composer(buf, composer, a, th)); - draw_rule(buf, rule_below, th); - if shell.height > 0 { - if let Some(c) = draw_shell(buf, shell, a, th) { - cursor = Some(c); - } - } - if let Some(s) = &a.search { - let qx = 2 + display_width(&s.query) as u16; - cursor = Some(Position::new( - footer.x + qx.min(footer.width.saturating_sub(1)), - footer.y, - )); - } + let (mut cursor, want_older) = match app.attached.as_mut() { + None => { + draw_sessions(buf, body, app, th, "engrams · sessions"); + (None, false) } - } + Some(a) => draw_attached_fullscreen(buf, body, footer, a, th, scratch), + }; draw_footer(buf, footer, app, th); if app.palette { let h = (app.sessions.rows.len() as u16 + 2).clamp(3, body.height.saturating_sub(2).max(3)); @@ -1964,6 +1970,56 @@ pub fn draw_fullscreen( (cursor, want_older) } +fn draw_attached_inline( + buf: &mut Buffer, + body: Rect, + a: &mut Attached, + th: &Theme, + scratch: &mut Vec<(usize, u16)>, +) -> Option { + let width = body.width.saturating_sub(2).max(1); + a.composer.layout(width); + let composer_rows = a.composer.rows().len().clamp(1, 6) as u16; + let queue_rows = (a.reducer.queued.len() as u16).min(2); + let composer = Rect { + y: body.bottom().saturating_sub(composer_rows), + height: composer_rows.min(body.height), + ..body + }; + let queue = Rect { + y: composer.y.saturating_sub(queue_rows), + height: queue_rows.min(composer.y - body.y), + ..body + }; + // One rule above the composer; the viewport is short. + let rule_above = Rect { + y: queue.y.saturating_sub(1), + height: u16::from(body.height >= 4 && queue.y > body.y), + ..body + }; + let slash_h = slash_rows(a.composer.text()).min(rule_above.y.saturating_sub(body.y)); + let slash = Rect { + y: rule_above.y.saturating_sub(slash_h), + height: slash_h, + ..body + }; + let live = Rect { + y: body.y, + height: slash.y.saturating_sub(body.y), + ..body + }; + a.scroll_up = 0; + a.page_rows = live.height; + draw_transcript(buf, live, a, th, scratch); + if slash.height > 0 { + draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); + shade(buf, slash, th); + } + draw_rule(buf, rule_above, th); + draw_queue(buf, queue, a, th); + Some(draw_composer(buf, composer, a, th)) +} + /// Inline (native scrollback) viewport: the in-flight cells, the queue /// rail, the composer and the footer. Finalized cells were already /// written above it by `commit_inline`. @@ -1987,57 +2043,13 @@ pub fn draw_inline( height: area.height - 1, ..area }; - let mut cursor = None; - match app.screen { - Screen::Sessions => draw_sessions(buf, body, app, th, "engrams · sessions"), - Screen::Attached => { - let a = app - .attached - .as_mut() - .expect("attached screen has a session"); - let width = body.width.saturating_sub(2).max(1); - a.composer.layout(width); - let composer_rows = a.composer.rows().len().clamp(1, 6) as u16; - let queue_rows = (a.reducer.queued.len() as u16).min(2); - let composer = Rect { - y: body.bottom().saturating_sub(composer_rows), - height: composer_rows.min(body.height), - ..body - }; - let queue = Rect { - y: composer.y.saturating_sub(queue_rows), - height: queue_rows.min(composer.y - body.y), - ..body - }; - // One rule above the composer; the viewport is short. - let rule_above = Rect { - y: queue.y.saturating_sub(1), - height: u16::from(body.height >= 4 && queue.y > body.y), - ..body - }; - let slash_h = slash_rows(a.composer.text()).min(rule_above.y.saturating_sub(body.y)); - let slash = Rect { - y: rule_above.y.saturating_sub(slash_h), - height: slash_h, - ..body - }; - let live = Rect { - y: body.y, - height: slash.y.saturating_sub(body.y), - ..body - }; - a.scroll_up = 0; - a.page_rows = live.height; - draw_transcript(buf, live, a, th, scratch); - if slash.height > 0 { - draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); - shade(buf, slash, th); - } - draw_rule(buf, rule_above, th); - draw_queue(buf, queue, a, th); - cursor = Some(draw_composer(buf, composer, a, th)); + let mut cursor = match app.attached.as_mut() { + None => { + draw_sessions(buf, body, app, th, "engrams · sessions"); + None } - } + Some(a) => draw_attached_inline(buf, body, a, th, scratch), + }; draw_footer(buf, footer, app, th); if app.palette { fill(buf, body, Style::new()); diff --git a/crates/engram-tui/tests/new_session.rs b/crates/engram-tui/tests/new_session.rs index 4707c7748..343cb958b 100644 --- a/crates/engram-tui/tests/new_session.rs +++ b/crates/engram-tui/tests/new_session.rs @@ -85,7 +85,7 @@ fn n_lists_profiles_and_enter_creates_the_task() { "Write the release notes.".into(), ))))); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Attached); + assert_eq!(app.screen(), Screen::Attached); let a = app.attached.as_ref().unwrap(); assert_eq!(a.session_id, "s-new"); assert_eq!(a.title, "Write the release notes."); @@ -119,7 +119,7 @@ fn a_failed_create_reopens_the_prompt_with_the_error() { assert_eq!(app.new_session.as_ref().unwrap().stage, NewStage::Pick); key(&mut app, KeyCode::Esc, KeyModifiers::NONE); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Sessions); + assert_eq!(app.screen(), Screen::Sessions); } #[test] @@ -133,5 +133,52 @@ fn the_picker_opens_over_an_attached_session_too() { // Ctrl+C closes it and the draft underneath is untouched. key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Attached); + assert_eq!(app.screen(), Screen::Attached); +} + +#[test] +fn screen_and_both_renderers_follow_attach_switch_and_detach() { + use engram_tui::render::draw_inline; + use ratatui::buffer::Buffer; + use ratatui::layout::Rect; + + let mut app = App::new(false, 60, 16); + let area = Rect::new(0, 0, 60, 16); + let theme = Theme::new(false); + let mut scratch = Vec::new(); + for session in [ + None, + Some("s-first"), + Some("s-first"), + Some("s-second"), + None, + ] { + match session { + Some(id) => app.attach(id), + None if app.attached.is_some() => { + key(&mut app, KeyCode::Char('d'), KeyModifiers::CONTROL); + } + None => {} + } + assert_eq!( + app.attached.as_ref().map(|a| a.session_id.as_str()), + session + ); + assert_eq!( + app.screen(), + if session.is_some() { + Screen::Attached + } else { + Screen::Sessions + } + ); + let mut fullscreen = Buffer::empty(area); + let mut inline = Buffer::empty(area); + let (cursor, _) = draw_fullscreen(&mut fullscreen, area, &mut app, &theme, &mut scratch); + assert_eq!(cursor.is_some(), session.is_some()); + assert_eq!( + draw_inline(&mut inline, area, &mut app, &theme, &mut scratch).is_some(), + session.is_some() + ); + } } diff --git a/crates/engram-tui/tests/slash.rs b/crates/engram-tui/tests/slash.rs index 38d43dd9a..88c0cdd44 100644 --- a/crates/engram-tui/tests/slash.rs +++ b/crates/engram-tui/tests/slash.rs @@ -112,7 +112,7 @@ fn enter_runs_the_named_command() { type_str(&mut app, "/sessions"); key(&mut app, KeyCode::Enter); - assert_eq!(app.screen, Screen::Sessions); + assert_eq!(app.screen(), Screen::Sessions); } #[test]