feat: add interactive WIP terminal client

This commit is contained in:
2026-09-30 10:35:05 +09:00
parent 347b92b28a
commit db2a51c824
14 changed files with 5141 additions and 13 deletions
+919
View File
@@ -0,0 +1,919 @@
//! Pure application state, selection, modal, focus, and key reducer.
use std::collections::{BTreeMap, BTreeSet};
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
use wip_protocol::{InterfaceDescriptor, Object, Value};
use crate::editor::ArgumentEditor;
const MAX_PRESENTATION_ENTRIES: usize = 2048;
const MAX_PRESENTATION_INTERFACES: usize = 256;
/// A terminal-independent key understood by the reducer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKey {
/// Up arrow or `k`.
Up,
/// Down arrow or `j`.
Down,
/// Left arrow or `h`.
Left,
/// Right arrow or `l`.
Right,
/// Focus the next pane.
Tab,
/// Activate the selected item.
Enter,
/// Close the current modal or return to the tree.
Escape,
/// Delete one editor character.
Backspace,
/// Refresh the selected Entry.
Refresh,
/// Retry a truncated tree with a larger limit.
IncreaseLimit,
/// Cancel the newest cancel-safe retrieval.
CancelRead,
/// Show key help.
Help,
/// Quit the application.
Quit,
/// Reconnect after startup or transport failure.
Reconnect,
/// A printable editor character.
Character(char),
}
/// Pane receiving navigation keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
/// Worldspace tree.
Tree,
/// Selected Entry metadata.
Entry,
/// Interfaces and operations.
Operations,
/// Recent result and diagnostic history.
History,
}
impl Focus {
fn next(self) -> Self {
match self {
Self::Tree => Self::Entry,
Self::Entry => Self::Operations,
Self::Operations => Self::History,
Self::History => Self::Tree,
}
}
}
/// Connection lifecycle shown without relying on color.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionState {
/// No request has been attempted.
Disconnected,
/// Initial root request or reconnect is in progress.
Connecting,
/// The root was observed successfully.
Connected,
/// Connection failed; reconnect and exit remain available.
Failed(String),
}
/// Presentation-safe observation state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewState {
/// No observation has been requested.
Unloaded,
/// One request is in flight.
Loading(u64),
/// The observation is current.
Fresh,
/// The retained value needs reobservation.
Stale,
/// The latest attempt failed.
Error(String),
}
impl From<&ObservationState> for ViewState {
fn from(value: &ObservationState) -> Self {
match value {
ObservationState::Loading(id) => Self::Loading(id.get()),
ObservationState::Fresh => Self::Fresh,
ObservationState::Stale => Self::Stale,
ObservationState::Error(error) => Self::Error(error.to_string()),
}
}
}
/// One materialized tree Entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryView {
/// Canonical WIP path.
pub path: String,
/// Latest object when retained by the client runtime.
pub object: Option<Object>,
/// Object observation state.
pub state: ViewState,
/// Direct child paths in Host order.
pub children: Vec<String>,
/// Expansion observation state.
pub tree_state: ViewState,
/// Whether the user expanded this row.
pub expanded: bool,
/// Whether the observed child list is incomplete.
pub truncated: bool,
/// Current bounded expansion limit.
pub limit: u32,
}
impl EntryView {
fn placeholder(path: impl Into<String>, default_limit: u32) -> Self {
Self {
path: path.into(),
object: None,
state: ViewState::Unloaded,
children: Vec::new(),
tree_state: ViewState::Unloaded,
expanded: false,
truncated: false,
limit: default_limit,
}
}
}
/// Cached interface descriptor state used by presentation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceView {
/// Opaque interface reference.
pub reference: String,
/// Descriptor when accepted by the client runtime.
pub descriptor: Option<InterfaceDescriptor>,
/// Descriptor observation state.
pub state: ViewState,
}
/// Stable result/diagnostic category.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HistoryKind {
/// A descriptor-validated operation result.
Success,
/// A valid Host-declared failure.
DomainFailure,
/// An invalid protocol response.
ProtocolError,
/// Network or TLS failure.
TransportFailure,
/// Client-local validation or capacity failure.
ClientFailure,
/// Dispatch occurred but execution or commit is uncertain.
OutcomeUnknown,
/// Informational request state.
Information,
}
/// One bounded recent result or diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryItem {
/// Explicit outcome category.
pub kind: HistoryKind,
/// Short bounded heading.
pub title: String,
/// Bounded, terminal-safe detail.
pub detail: String,
/// Navigation target only when declared as descriptor `Entry`.
pub entry_target: Option<String>,
}
/// Kind of request currently in flight.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InFlightKind {
/// Object refresh.
Object(String),
/// Tree expansion or refresh.
Tree(String),
/// Descriptor fetch.
Interface(String),
/// Explicit operation call.
Operation {
/// Target path.
path: String,
/// Interface reference.
interface: String,
/// Operation name.
operation: String,
/// Whether the transport dispatch boundary was crossed.
dispatched: bool,
},
}
impl InFlightKind {
/// Whether dropping the response is a safe cancellation operation.
#[must_use]
pub fn cancel_safe(&self) -> bool {
!matches!(self, Self::Operation { .. })
}
}
/// Active overlay.
#[derive(Debug, Clone, PartialEq)]
pub enum Modal {
/// No overlay.
None,
/// Keyboard help.
Help,
/// Descriptor-driven field editor.
Editor(ArgumentEditor),
/// Explicit pre-execution confirmation.
Confirm {
/// Editor retained when confirmation is cancelled.
editor: ArgumentEditor,
/// Validated arguments that will be sent.
arguments: BTreeMap<String, Value>,
},
}
/// Side effect requested by the pure reducer.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
/// Expand one node lazily.
Expand {
/// Tree root path.
path: String,
/// Maximum returned nodes.
limit: u32,
},
/// Reobserve an Entry and its direct children.
Refresh {
/// Selected path.
path: String,
/// Current tree limit.
limit: u32,
},
/// Retrieve one interface descriptor.
FetchInterface(String),
/// Execute only after explicit confirmation.
Execute {
/// Entry target.
path: String,
/// Interface reference.
interface: String,
/// Operation name.
operation: String,
/// Descriptor-validated arguments.
arguments: BTreeMap<String, Value>,
},
/// Cancel the newest safe retrieval.
CancelRead,
/// Reconnect and fetch the root.
Reconnect,
/// Navigate to a descriptor-declared Entry result.
NavigateEntry(String),
/// Exit normally.
Quit,
}
/// Complete presentation model.
#[derive(Debug, Clone, PartialEq)]
pub struct App {
/// Effective endpoint label (never credential material).
pub endpoint: String,
/// Connection lifecycle.
pub connection: ConnectionState,
/// Materialized tree nodes by path.
pub entries: BTreeMap<String, EntryView>,
/// Selected Entry path.
pub selected_path: String,
/// Focused pane.
pub focus: Focus,
/// Interface descriptor views by opaque reference.
pub interfaces: BTreeMap<String, InterfaceView>,
/// Selected row in the flattened interface/operation view.
pub operation_cursor: usize,
/// Selected recent-history row.
pub history_cursor: usize,
/// Active overlay.
pub modal: Modal,
/// In-flight requests keyed by client request identity.
pub in_flight: BTreeMap<u64, InFlightKind>,
/// Recent result and diagnostic history, newest first.
pub history: Vec<HistoryItem>,
/// Maximum retained presentation history.
pub history_limit: usize,
/// Default node limit for lazy expansion.
pub default_tree_limit: u32,
/// One-line status for local action feedback.
pub status: String,
}
impl App {
/// Creates a disconnected model with `/` selected.
#[must_use]
pub fn new(endpoint: impl Into<String>) -> Self {
let default_tree_limit = 64;
let mut entries = BTreeMap::new();
entries.insert("/".into(), EntryView::placeholder("/", default_tree_limit));
Self {
endpoint: endpoint.into(),
connection: ConnectionState::Disconnected,
entries,
selected_path: "/".into(),
focus: Focus::Tree,
interfaces: BTreeMap::new(),
operation_cursor: 0,
history_cursor: 0,
modal: Modal::None,
in_flight: BTreeMap::new(),
history: Vec::new(),
history_limit: 64,
default_tree_limit,
status: "press ? for help".into(),
}
}
/// Applies one key and returns requested effects without performing I/O.
pub fn reduce(&mut self, key: InputKey) -> Vec<Action> {
match std::mem::replace(&mut self.modal, Modal::None) {
Modal::Help => {
if !matches!(key, InputKey::Escape | InputKey::Help) {
self.modal = Modal::Help;
}
return Vec::new();
}
Modal::Editor(mut editor) => {
match key {
InputKey::Escape => {}
InputKey::Up => {
editor.previous_field();
self.modal = Modal::Editor(editor);
}
InputKey::Down | InputKey::Tab => {
editor.next_field();
self.modal = Modal::Editor(editor);
}
InputKey::Backspace => {
editor.backspace();
self.modal = Modal::Editor(editor);
}
InputKey::Character(character) => {
editor.insert(character);
self.modal = Modal::Editor(editor);
}
InputKey::Enter => match editor.validate() {
Ok(arguments) => self.modal = Modal::Confirm { editor, arguments },
Err(_) => self.modal = Modal::Editor(editor),
},
_ => self.modal = Modal::Editor(editor),
}
return Vec::new();
}
Modal::Confirm { editor, arguments } => match key {
InputKey::Escape => {
self.modal = Modal::Editor(editor);
return Vec::new();
}
InputKey::Enter | InputKey::Character('e') => {
let action = Action::Execute {
path: self.selected_path.clone(),
interface: editor.interface.clone(),
operation: editor.operation.name.clone(),
arguments,
};
self.status = "operation dispatched; automatic retry is disabled".into();
return vec![action];
}
_ => {
self.modal = Modal::Confirm { editor, arguments };
return Vec::new();
}
},
Modal::None => {}
}
if key == InputKey::Help {
self.modal = Modal::Help;
return Vec::new();
}
if key == InputKey::Quit {
return vec![Action::Quit];
}
if key == InputKey::Reconnect {
return vec![Action::Reconnect];
}
if key == InputKey::CancelRead {
return vec![Action::CancelRead];
}
if key == InputKey::Tab {
self.focus = self.focus.next();
return Vec::new();
}
match self.focus {
Focus::Tree => self.reduce_tree(key),
Focus::Operations => self.reduce_operations(key),
Focus::History => self.reduce_history(key),
Focus::Entry => {
if key == InputKey::Escape {
self.focus = Focus::Tree;
} else if key == InputKey::Refresh {
return vec![self.refresh_action()];
}
Vec::new()
}
}
}
fn reduce_tree(&mut self, key: InputKey) -> Vec<Action> {
let visible = self.visible_paths();
let position = visible
.iter()
.position(|path| path == &self.selected_path)
.unwrap_or(0);
match key {
InputKey::Up if position > 0 => self.selected_path = visible[position - 1].clone(),
InputKey::Down if position + 1 < visible.len() => {
self.selected_path = visible[position + 1].clone();
}
InputKey::Right | InputKey::Enter => {
let node = self
.entries
.entry(self.selected_path.clone())
.or_insert_with(|| {
EntryView::placeholder(&self.selected_path, self.default_tree_limit)
});
node.expanded = true;
if !matches!(node.tree_state, ViewState::Fresh) || node.truncated {
return vec![Action::Expand {
path: node.path.clone(),
limit: node.limit,
}];
}
}
InputKey::Left => {
let node = self
.entries
.get_mut(&self.selected_path)
.expect("selected Entry exists");
if node.expanded {
node.expanded = false;
} else if self.selected_path != "/" {
self.selected_path = parent_path(&self.selected_path);
}
}
InputKey::Refresh => return vec![self.refresh_action()],
InputKey::IncreaseLimit => {
let node = self
.entries
.get_mut(&self.selected_path)
.expect("selected exists");
node.limit = node.limit.saturating_mul(2).max(1);
node.expanded = true;
return vec![Action::Expand {
path: node.path.clone(),
limit: node.limit,
}];
}
_ => {}
}
self.operation_cursor = 0;
Vec::new()
}
fn reduce_operations(&mut self, key: InputKey) -> Vec<Action> {
let rows = self.operation_rows();
match key {
InputKey::Up => self.operation_cursor = self.operation_cursor.saturating_sub(1),
InputKey::Down if self.operation_cursor + 1 < rows.len() => self.operation_cursor += 1,
InputKey::Refresh => return vec![self.refresh_action()],
InputKey::Escape => self.focus = Focus::Tree,
InputKey::Enter => {
if let Some(row) = rows.get(self.operation_cursor) {
if let Some(operation_name) = &row.operation {
if let Some(interface) = self.interfaces.get(&row.interface)
&& let Some(descriptor) = &interface.descriptor
&& let Some(operation) = descriptor
.operations
.iter()
.find(|operation| operation.name == *operation_name)
{
self.modal = Modal::Editor(ArgumentEditor::new(
row.interface.clone(),
descriptor.clone(),
operation.clone(),
));
}
} else {
return vec![Action::FetchInterface(row.interface.clone())];
}
}
}
_ => {}
}
Vec::new()
}
fn reduce_history(&mut self, key: InputKey) -> Vec<Action> {
match key {
InputKey::Up => self.history_cursor = self.history_cursor.saturating_sub(1),
InputKey::Down if self.history_cursor + 1 < self.history.len() => {
self.history_cursor += 1;
}
InputKey::Enter => {
if let Some(path) = self
.history
.get(self.history_cursor)
.and_then(|item| item.entry_target.clone())
{
return vec![Action::NavigateEntry(path)];
}
}
InputKey::Escape => self.focus = Focus::Tree,
_ => {}
}
Vec::new()
}
fn refresh_action(&self) -> Action {
let limit = self
.entries
.get(&self.selected_path)
.map_or(self.default_tree_limit, |entry| entry.limit);
Action::Refresh {
path: self.selected_path.clone(),
limit,
}
}
/// Records a pending request separately by interaction type.
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
match &kind {
InFlightKind::Object(path) => {
self.ensure_entry(path).state = ViewState::Loading(id);
}
InFlightKind::Tree(path) => {
let entry = self.ensure_entry(path);
entry.state = ViewState::Loading(id);
entry.tree_state = ViewState::Loading(id);
}
InFlightKind::Interface(reference) => {
self.ensure_interface(reference).state = ViewState::Loading(id);
}
InFlightKind::Operation { .. } => {}
}
self.in_flight.insert(id, kind);
}
/// Marks an operation as handed to the transport.
pub fn request_dispatched(&mut self, id: u64) {
if let Some(InFlightKind::Operation { dispatched, .. }) = self.in_flight.get_mut(&id) {
*dispatched = true;
}
}
/// Removes a completed request identity.
pub fn request_finished(&mut self, id: u64) -> Option<InFlightKind> {
self.in_flight.remove(&id)
}
/// Applies an object observation from `wip-client`.
pub fn apply_object(&mut self, observation: ObjectObservation) {
let entry = self.ensure_entry(&observation.path);
entry.object = observation.object;
entry.state = ViewState::from(&observation.state);
}
/// Applies a lazy tree observation and ensures child placeholders exist.
pub fn apply_tree(&mut self, observation: TreeObservation) {
let children = observation.children.clone();
let entry = self.ensure_entry(&observation.path);
entry.children = children.clone();
entry.truncated = observation.truncated;
entry.tree_state = ViewState::from(&observation.state);
entry.expanded = true;
for path in children {
self.ensure_entry(&path);
}
}
/// Applies one interface observation from `wip-client`.
pub fn apply_interface(&mut self, observation: InterfaceObservation) {
let view = self.ensure_interface(&observation.reference);
*view = InterfaceView {
reference: observation.reference,
descriptor: observation.descriptor,
state: ViewState::from(&observation.state),
};
}
/// Replaces current Entry details from the client's current snapshot.
pub fn sync_object(&mut self, path: &str, observation: Option<ObjectObservation>) {
match observation {
Some(observation) => self.apply_object(observation),
None => {
let entry = self.ensure_entry(path);
entry.object = None;
entry.state = ViewState::Stale;
}
}
}
/// Selects a known or newly discovered descriptor-declared Entry path.
pub fn navigate_entry(&mut self, path: impl Into<String>) {
let path = path.into();
self.ensure_entry(&path);
self.selected_path = path;
self.focus = Focus::Tree;
}
/// Adds one bounded recent item.
pub fn push_history(&mut self, item: HistoryItem) {
self.history.insert(0, item);
self.history.truncate(self.history_limit);
self.history_cursor = 0;
}
/// Returns visible tree paths in display order.
#[must_use]
pub fn visible_paths(&self) -> Vec<String> {
let mut visible = Vec::new();
let mut seen = BTreeSet::new();
self.collect_visible("/", &mut seen, &mut visible);
if !seen.contains(&self.selected_path) && self.entries.contains_key(&self.selected_path) {
visible.push(self.selected_path.clone());
}
visible
}
fn collect_visible(&self, path: &str, seen: &mut BTreeSet<String>, visible: &mut Vec<String>) {
if !seen.insert(path.to_owned()) {
return;
}
visible.push(path.to_owned());
let Some(entry) = self.entries.get(path) else {
return;
};
if entry.expanded {
for child in &entry.children {
self.collect_visible(child, seen, visible);
}
}
}
/// Returns flattened interface headers and operations for the selected Entry.
#[must_use]
pub fn operation_rows(&self) -> Vec<OperationRow> {
let Some(object) = self
.entries
.get(&self.selected_path)
.filter(|entry| entry.state == ViewState::Fresh)
.and_then(|entry| entry.object.as_ref())
else {
return Vec::new();
};
let mut rows = Vec::new();
for reference in &object.interfaces {
rows.push(OperationRow {
interface: reference.clone(),
operation: None,
});
if let Some(descriptor) = self
.interfaces
.get(reference)
.filter(|view| view.state == ViewState::Fresh)
.and_then(|view| view.descriptor.as_ref())
{
rows.extend(descriptor.operations.iter().map(|operation| OperationRow {
interface: reference.clone(),
operation: Some(operation.name.clone()),
}));
}
}
rows
}
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
let candidate = self
.entries
.iter()
.find(|(candidate, entry)| {
candidate.as_str() != "/"
&& candidate.as_str() != self.selected_path
&& matches!(
entry.state,
ViewState::Unloaded | ViewState::Stale | ViewState::Error(_)
)
})
.or_else(|| {
self.entries.iter().find(|(candidate, entry)| {
candidate.as_str() != "/"
&& candidate.as_str() != self.selected_path
&& !matches!(entry.state, ViewState::Loading(_))
})
})
.map(|(candidate, _)| candidate.clone());
if let Some(candidate) = candidate {
self.entries.remove(&candidate);
for entry in self.entries.values_mut() {
entry.children.retain(|child| child != &candidate);
}
}
}
self.entries
.entry(path.to_owned())
.or_insert_with(|| EntryView::placeholder(path, self.default_tree_limit))
}
fn ensure_interface(&mut self, reference: &str) -> &mut InterfaceView {
if !self.interfaces.contains_key(reference)
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
{
let protected = self
.entries
.get(&self.selected_path)
.and_then(|entry| entry.object.as_ref())
.map(|object| object.interfaces.iter().cloned().collect::<BTreeSet<_>>())
.unwrap_or_default();
let candidate = self
.interfaces
.iter()
.find(|(candidate, interface)| {
!protected.contains(*candidate)
&& !matches!(interface.state, ViewState::Loading(_))
})
.or_else(|| {
self.interfaces
.iter()
.find(|(_, interface)| !matches!(interface.state, ViewState::Loading(_)))
})
.map(|(candidate, _)| candidate.clone());
if let Some(candidate) = candidate {
self.interfaces.remove(&candidate);
}
}
self.interfaces
.entry(reference.to_owned())
.or_insert_with(|| InterfaceView {
reference: reference.to_owned(),
descriptor: None,
state: ViewState::Unloaded,
})
}
}
/// One row in the combined Interface and Operation pane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationRow {
/// Interface reference, which participates in operation identity.
pub interface: String,
/// Operation name, or `None` for the interface heading.
pub operation: Option<String>,
}
/// Returns the canonical parent of a non-root path.
#[must_use]
pub fn parent_path(path: &str) -> String {
match path.rsplit_once('/') {
Some(("", _)) | None => "/".into(),
Some((parent, _)) => parent.into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
fn object(name: &str, interfaces: &[&str]) -> Object {
Object {
name: name.into(),
description: Some(format!("{name} description")),
interfaces: interfaces.iter().map(|value| (*value).into()).collect(),
r#ref: None,
validator: None,
}
}
#[test]
fn tree_navigation_expansion_parent_and_limit_are_pure() {
let mut app = App::new("https://example.test/wip");
app.apply_tree(TreeObservation {
path: "/".into(),
children: vec!["/a".into(), "/b".into()],
truncated: true,
revision: request_id(),
state: ObservationState::Fresh,
});
assert_eq!(app.visible_paths(), ["/", "/a", "/b"]);
app.reduce(InputKey::Down);
assert_eq!(app.selected_path, "/a");
app.reduce(InputKey::Left);
assert_eq!(app.selected_path, "/");
assert!(matches!(
app.reduce(InputKey::IncreaseLimit).as_slice(),
[Action::Expand { path, limit: 128 }] if path == "/"
));
}
#[test]
fn focus_modal_and_explicit_confirmation_gate_execution() {
let mut app = App::new("https://example.test/wip");
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(object("", &["iface"])),
validator: None,
state: ObservationState::Fresh,
});
let descriptor = InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types: vec![],
operations: vec![OperationDeclaration {
name: "ping".into(),
documentation: None,
parameters: vec![],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::Unit,
},
}],
};
app.apply_interface(InterfaceObservation {
reference: "iface".into(),
descriptor: Some(descriptor),
validator: None,
state: ObservationState::Fresh,
});
app.focus = Focus::Operations;
app.operation_cursor = 1;
assert!(app.reduce(InputKey::Enter).is_empty());
assert!(matches!(app.modal, Modal::Editor(_)));
assert!(app.reduce(InputKey::Enter).is_empty());
assert!(matches!(app.modal, Modal::Confirm { .. }));
assert!(matches!(
app.reduce(InputKey::Enter).as_slice(),
[Action::Execute { operation, .. }] if operation == "ping"
));
}
#[test]
fn presentation_maps_enforce_client_sized_hard_bounds() {
let mut app = App::new("https://example.test/wip");
for index in 0..(MAX_PRESENTATION_ENTRIES + 100) {
app.navigate_entry(format!("/discovered-{index}"));
app.selected_path = "/".into();
}
assert!(app.entries.len() <= MAX_PRESENTATION_ENTRIES);
assert!(app.entries.contains_key("/"));
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
app.apply_interface(InterfaceObservation {
reference: format!("interface-{index}"),
descriptor: None,
validator: None,
state: ObservationState::Fresh,
});
}
assert!(app.interfaces.len() <= MAX_PRESENTATION_INTERFACES);
}
#[test]
fn result_navigation_only_uses_explicit_entry_target() {
let mut app = App::new("https://example.test/wip");
app.push_history(HistoryItem {
kind: HistoryKind::Success,
title: "string".into(),
detail: "/looks/like/a/path".into(),
entry_target: None,
});
app.focus = Focus::History;
assert!(app.reduce(InputKey::Enter).is_empty());
app.push_history(HistoryItem {
kind: HistoryKind::Success,
title: "Entry".into(),
detail: "/actual".into(),
entry_target: Some("/actual".into()),
});
assert_eq!(
app.reduce(InputKey::Enter),
vec![Action::NavigateEntry("/actual".into())]
);
}
fn request_id() -> wip_client::RequestId {
// A request identity has no public constructor; derive one through the runtime.
let mut client = wip_client::Client::new(
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
wip_https::Limits::new(1024, 1024, 8, 8).unwrap(),
);
let session = client
.open_session(
"https://example.test/wip",
wip_client::SecurityContext::new("test"),
)
.unwrap();
client.prepare_fetch(&session, "/").unwrap().id
}
}
+315
View File
@@ -0,0 +1,315 @@
//! Secure-by-default command-line and environment configuration.
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::time::Duration;
use wip_https::url::Url;
/// Credential wrapper whose debug output is always redacted.
#[derive(Clone)]
pub struct Secret(String);
impl Secret {
pub(crate) fn expose(&self) -> &str {
&self.0
}
}
impl Debug for Secret {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("Secret([REDACTED])")
}
}
/// Validated runtime configuration.
#[derive(Clone)]
pub struct Config {
/// Canonical logical HTTPS endpoint used by `wip-client`.
logical_endpoint: String,
/// Actual request origin; differs only for explicit loopback development HTTP.
transport_endpoint: String,
/// Non-secret cache partition identity.
security_context: String,
/// Bounded network timeout.
timeout: Duration,
/// Optional complete Authorization header value, never rendered or logged.
authorization: Option<Secret>,
/// Whether loopback request URIs are deliberately downgraded to HTTP.
development_http: bool,
}
impl Debug for Config {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Config")
.field("logical_endpoint", &self.logical_endpoint)
.field("transport_endpoint", &self.transport_endpoint)
.field("security_context", &self.security_context)
.field("timeout", &self.timeout)
.field("authorization", &self.authorization)
.field("development_http", &self.development_http)
.finish()
}
}
impl Config {
/// Returns the canonical HTTPS endpoint used for protocol request construction.
#[must_use]
pub fn logical_endpoint(&self) -> &str {
&self.logical_endpoint
}
/// Returns the validated effective transport endpoint shown in the UI.
#[must_use]
pub fn transport_endpoint(&self) -> &str {
&self.transport_endpoint
}
/// Returns the non-secret session cache partition identity.
#[must_use]
pub fn security_context(&self) -> &str {
&self.security_context
}
/// Returns the end-to-end request timeout.
#[must_use]
pub const fn timeout(&self) -> Duration {
self.timeout
}
/// Whether explicit loopback development HTTP is enabled.
#[must_use]
pub const fn development_http(&self) -> bool {
self.development_http
}
pub(crate) fn authorization(&self) -> Option<&Secret> {
self.authorization.as_ref()
}
/// Parses process arguments and supported environment variables.
///
/// Endpoint precedence is `--endpoint`, a positional endpoint, then
/// `WIP_ENDPOINT`. Authorization is read only from the variable named by
/// `--authorization-env` (default `WIP_AUTHORIZATION`).
pub fn from_env() -> Result<Self, ConfigError> {
let arguments = std::env::args().skip(1).collect::<Vec<_>>();
let endpoint_env = std::env::var("WIP_ENDPOINT").ok();
let security_context = std::env::var("WIP_SECURITY_CONTEXT").ok();
Self::parse(arguments, endpoint_env, security_context, |name| {
std::env::var(name).ok()
})
}
/// Parses supplied values; exposed to make startup policy independently testable.
pub fn parse<I, S, F>(
arguments: I,
endpoint_env: Option<String>,
security_context_env: Option<String>,
mut read_secret: F,
) -> Result<Self, ConfigError>
where
I: IntoIterator<Item = S>,
S: Into<String>,
F: FnMut(&str) -> Option<String>,
{
let mut endpoint = None;
let mut allow_http = false;
let mut timeout = Duration::from_secs(30);
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
let mut iter = arguments.into_iter().map(Into::into);
while let Some(argument) = iter.next() {
match argument.as_str() {
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
"--allow-http" => allow_http = true,
"--security-context" => {
security_context = next_value(&mut iter, "--security-context")?;
}
"--authorization-env" => {
authorization_env = next_value(&mut iter, "--authorization-env")?;
}
"--timeout" => {
let raw = next_value(&mut iter, "--timeout")?;
let seconds = raw
.parse::<u64>()
.ok()
.filter(|seconds| *seconds > 0)
.ok_or_else(|| {
ConfigError::Invalid("--timeout must be a positive integer".into())
})?;
timeout = Duration::from_secs(seconds);
}
"--help" | "-h" => return Err(ConfigError::Help),
value if value.starts_with('-') => {
return Err(ConfigError::Invalid(format!("unknown option {value}")));
}
value if endpoint.is_none() => endpoint = Some(value.to_owned()),
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
}
}
let endpoint = endpoint
.or(endpoint_env)
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
let mut actual = Url::parse(&endpoint)
.map_err(|_| ConfigError::Invalid("endpoint is not a valid absolute URL".into()))?;
if actual.query().is_some()
|| actual.fragment().is_some()
|| actual.host_str().is_none()
|| !actual.username().is_empty()
|| actual.password().is_some()
{
return Err(ConfigError::Invalid(
"endpoint must be an absolute URL without userinfo, query, or fragment".into(),
));
}
if !actual.path().ends_with('/') {
let path = format!("{}/", actual.path());
actual.set_path(&path);
}
let development_http = actual.scheme() == "http";
match actual.scheme() {
"https" => {}
"http" if allow_http && loopback_host(&actual) => {}
"http" if !allow_http => {
return Err(ConfigError::Invalid(
"plain HTTP requires the explicit --allow-http development option".into(),
));
}
"http" => {
return Err(ConfigError::Invalid(
"development HTTP is restricted to loopback endpoints".into(),
));
}
_ => return Err(ConfigError::Invalid("endpoint must use HTTPS".into())),
}
let transport_endpoint = actual.to_string();
let mut logical = actual;
if development_http {
logical
.set_scheme("https")
.expect("http and https are interchangeable hierarchical schemes");
}
// Let the binding enforce all remaining canonical endpoint rules.
let logical_endpoint = wip_https::Endpoint::parse(logical.as_str())
.map_err(|error| ConfigError::Invalid(error.to_string()))?
.to_string();
if security_context.is_empty() {
return Err(ConfigError::Invalid(
"security context must not be empty".into(),
));
}
let authorization = read_secret(&authorization_env)
.filter(|value| !value.is_empty())
.map(Secret);
Ok(Self {
logical_endpoint,
transport_endpoint,
security_context,
timeout,
authorization,
development_http,
})
}
/// Returns concise command usage without mentioning credential values.
#[must_use]
pub const fn usage() -> &'static str {
"usage: wip-tui [--endpoint] URL [--allow-http] [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
URL may also be supplied as WIP_ENDPOINT; HTTPS is required unless loopback HTTP is explicitly enabled."
}
}
fn next_value(
iter: &mut impl Iterator<Item = String>,
option: &str,
) -> Result<String, ConfigError> {
iter.next()
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
}
fn loopback_host(url: &Url) -> bool {
match url.host() {
Some(wip_https::url::Host::Ipv4(address)) => address.is_loopback(),
Some(wip_https::url::Host::Ipv6(address)) => address.is_loopback(),
Some(wip_https::url::Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"),
None => false,
}
}
/// Startup configuration failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
/// Help was requested.
Help,
/// A safe, non-secret configuration diagnostic.
Invalid(String),
}
impl Display for ConfigError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Help => formatter.write_str(Config::usage()),
Self::Invalid(detail) => write!(formatter, "{detail}\n{}", Config::usage()),
}
}
}
impl Error for ConfigError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn https_is_default_and_secrets_are_redacted() {
let config = Config::parse(
["https://example.test/wip", "--authorization-env", "TOKEN"],
None,
None,
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
)
.unwrap();
assert_eq!(config.logical_endpoint(), "https://example.test/wip/");
let debug = format!("{config:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("secret-value"));
}
#[test]
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
for arguments in [
vec!["https://user:password@example.test/wip"],
vec!["http://user:password@localhost:3000/wip", "--allow-http"],
] {
let error = Config::parse(arguments, None, None, |_| None).unwrap_err();
assert!(error.to_string().contains("without userinfo"));
assert!(!error.to_string().contains("password"));
}
}
#[test]
fn http_requires_explicit_loopback_development_mode() {
assert!(Config::parse(["http://localhost:3000/wip"], None, None, |_| None).is_err());
let config = Config::parse(
["http://127.0.0.1:3000/wip", "--allow-http"],
None,
None,
|_| None,
)
.unwrap();
assert_eq!(config.logical_endpoint(), "https://127.0.0.1:3000/wip/");
assert_eq!(config.transport_endpoint(), "http://127.0.0.1:3000/wip/");
assert!(config.development_http());
assert!(
Config::parse(
["http://example.test/wip", "--allow-http"],
None,
None,
|_| None,
)
.is_err()
);
}
}
+628
View File
@@ -0,0 +1,628 @@
//! Descriptor-driven operation argument editing and validation.
use std::collections::BTreeMap;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use wip_protocol::{InterfaceDescriptor, OperationDeclaration, TypeExpr, Value};
const MAX_FIELD_INPUT_BYTES: usize = 256 * 1024;
/// One editable top-level operation parameter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgumentField {
/// Parameter name.
pub name: String,
/// Whether the parameter must be supplied.
pub required: bool,
/// Canonical descriptor type.
pub r#type: TypeExpr,
/// User-entered text.
pub input: String,
/// Field-local validation diagnostic.
pub diagnostic: Option<String>,
}
/// Marker returned when one or more field diagnostics prevent submission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidArguments;
/// Pure, terminal-independent editor built from an operation descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgumentEditor {
/// Opaque interface reference selected for the call.
pub interface: String,
/// Selected operation declaration.
pub operation: OperationDeclaration,
/// Complete descriptor used to resolve named types.
pub descriptor: InterfaceDescriptor,
/// Top-level parameter fields in declaration order.
pub fields: Vec<ArgumentField>,
/// Index of the active field.
pub cursor: usize,
}
impl ArgumentEditor {
/// Builds an editor whose fields preserve descriptor order.
#[must_use]
pub fn new(
interface: impl Into<String>,
descriptor: InterfaceDescriptor,
operation: OperationDeclaration,
) -> Self {
let fields = operation
.parameters
.iter()
.map(|parameter| ArgumentField {
name: parameter.name.clone(),
required: parameter.required,
r#type: parameter.r#type.clone(),
input: if parameter.required && parameter.r#type == TypeExpr::Unit {
"null".into()
} else {
String::new()
},
diagnostic: None,
})
.collect();
Self {
interface: interface.into(),
operation,
descriptor,
fields,
cursor: 0,
}
}
/// Moves to the preceding field without wrapping.
pub fn previous_field(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
/// Moves to the following field without wrapping.
pub fn next_field(&mut self) {
if self.cursor + 1 < self.fields.len() {
self.cursor += 1;
}
}
/// Appends one printable character to the active field.
pub fn insert(&mut self, character: char) {
if !character.is_control()
&& let Some(field) = self.fields.get_mut(self.cursor)
{
if field.input.len().saturating_add(character.len_utf8()) <= MAX_FIELD_INPUT_BYTES {
field.input.push(character);
field.diagnostic = None;
} else {
field.diagnostic = Some("field input reached the 256 KiB limit".into());
}
}
}
/// Removes one scalar value from the active field.
pub fn backspace(&mut self) {
if let Some(field) = self.fields.get_mut(self.cursor) {
field.input.pop();
field.diagnostic = None;
}
}
/// Validates all fields and returns protocol values when every field is valid.
///
/// Invalid or missing values are retained as field-local diagnostics. Optional
/// blank fields are omitted from the resulting argument map.
pub fn validate(&mut self) -> Result<BTreeMap<String, Value>, InvalidArguments> {
let mut arguments = BTreeMap::new();
let mut invalid = false;
for field in &mut self.fields {
field.diagnostic = None;
if field.input.len() > MAX_FIELD_INPUT_BYTES {
field.diagnostic = Some("field input exceeds the 256 KiB limit".into());
invalid = true;
continue;
}
if field.input.trim().is_empty() {
if field.required {
field.diagnostic = Some("required value is missing".into());
invalid = true;
}
continue;
}
match parse_value(
&self.descriptor,
&field.r#type,
field.input.trim(),
&field.name,
) {
Ok(value) => {
arguments.insert(field.name.clone(), value);
}
Err(error) => {
field.diagnostic = Some(error);
invalid = true;
}
}
}
if invalid {
return Err(InvalidArguments);
}
if let Err(error) = self
.descriptor
.validate_arguments(&self.operation.name, &arguments)
{
if let Some(field) = self.fields.get_mut(self.cursor) {
field.diagnostic = Some(error.to_string());
}
return Err(InvalidArguments);
}
Ok(arguments)
}
}
/// Returns a compact canonical spelling for a type expression.
#[must_use]
pub fn type_name(r#type: &TypeExpr) -> String {
match r#type {
TypeExpr::Unit => "Unit".into(),
TypeExpr::Boolean => "Boolean".into(),
TypeExpr::Integer => "Integer".into(),
TypeExpr::Number => "Number".into(),
TypeExpr::String => "String".into(),
TypeExpr::Bytes => "Bytes(base64)".into(),
TypeExpr::Json => "Json".into(),
TypeExpr::Entry => "Entry".into(),
TypeExpr::Named { name } => name.clone(),
TypeExpr::Record { fields } => format!(
"Record{{{}}}",
fields
.iter()
.map(|field| format!(
"{}{}: {}",
field.name,
if field.required { "" } else { "?" },
type_name(&field.r#type)
))
.collect::<Vec<_>>()
.join(", ")
),
TypeExpr::List { items } => format!("List<{}>", type_name(items)),
TypeExpr::Enum { cases } => format!(
"Enum<{}>",
cases
.iter()
.map(|case| case.name.as_str())
.collect::<Vec<_>>()
.join(" | ")
),
TypeExpr::Union { cases } => format!(
"Union<{}>",
cases
.iter()
.map(|case| case.name.as_str())
.collect::<Vec<_>>()
.join(" | ")
),
}
}
fn parse_value(
descriptor: &InterfaceDescriptor,
r#type: &TypeExpr,
input: &str,
field: &str,
) -> Result<Value, String> {
if let TypeExpr::Named { name } = r#type {
let declaration = descriptor
.types
.iter()
.find(|declaration| declaration.name == *name)
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
return parse_value(descriptor, &declaration.definition, input, field);
}
let value = match r#type {
TypeExpr::Unit => {
if matches!(input, "null" | "()") {
Value::Unit
} else {
return Err(format!("{field}: expected null"));
}
}
TypeExpr::Boolean => input
.parse::<bool>()
.map(Value::Boolean)
.map_err(|_| format!("{field}: expected true or false"))?,
TypeExpr::Integer => input
.parse::<i64>()
.map(Value::Integer)
.map_err(|_| format!("{field}: expected a signed integer"))?,
TypeExpr::Number => {
let number = input
.parse::<f64>()
.map_err(|_| format!("{field}: expected a finite number"))?;
if !number.is_finite() {
return Err(format!("{field}: expected a finite number"));
}
Value::Number(number)
}
TypeExpr::String => Value::String(parse_string(input)),
TypeExpr::Bytes => Value::Bytes(
STANDARD
.decode(input)
.map_err(|_| format!("{field}: expected RFC 4648 base64"))?,
),
TypeExpr::Entry => {
let path = parse_string(input);
wip_protocol::validate_path(&path)
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
Value::String(path)
}
TypeExpr::Enum { cases } => {
let case = parse_string(input);
if !cases.iter().any(|candidate| candidate.name == case) {
return Err(format!("{field}: unknown enum case {case}"));
}
Value::String(case)
}
TypeExpr::Json => {
let json = serde_json::from_str(input)
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
json_to_untyped(&json, field)?
}
TypeExpr::Record { .. } | TypeExpr::List { .. } | TypeExpr::Union { .. } => {
let json = serde_json::from_str(input)
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
json_to_typed(descriptor, r#type, &json, field)?
}
TypeExpr::Named { .. } => unreachable!("named types handled above"),
};
descriptor
.validate_value(r#type, &value)
.map_err(|error| format!("{field}: {error}"))?;
Ok(value)
}
fn parse_string(input: &str) -> String {
serde_json::from_str::<String>(input).unwrap_or_else(|_| input.to_owned())
}
fn json_to_typed(
descriptor: &InterfaceDescriptor,
r#type: &TypeExpr,
json: &serde_json::Value,
field: &str,
) -> Result<Value, String> {
if let TypeExpr::Named { name } = r#type {
let declaration = descriptor
.types
.iter()
.find(|declaration| declaration.name == *name)
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
return json_to_typed(descriptor, &declaration.definition, json, field);
}
match r#type {
TypeExpr::Unit if json.is_null() => Ok(Value::Unit),
TypeExpr::Boolean => json
.as_bool()
.map(Value::Boolean)
.ok_or_else(|| format!("{field}: expected boolean")),
TypeExpr::Integer => json
.as_i64()
.map(Value::Integer)
.ok_or_else(|| format!("{field}: expected integer")),
TypeExpr::Number => json
.as_f64()
.filter(|value| value.is_finite())
.map(Value::Number)
.ok_or_else(|| format!("{field}: expected finite number")),
TypeExpr::String => json
.as_str()
.map(|value| Value::String(value.into()))
.ok_or_else(|| format!("{field}: expected string")),
TypeExpr::Bytes => json
.as_str()
.ok_or_else(|| format!("{field}: expected base64 string"))
.and_then(|value| {
STANDARD
.decode(value)
.map(Value::Bytes)
.map_err(|_| format!("{field}: expected RFC 4648 base64"))
}),
TypeExpr::Entry => {
let path = json
.as_str()
.ok_or_else(|| format!("{field}: expected Entry string"))?;
wip_protocol::validate_path(path)
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
Ok(Value::String(path.into()))
}
TypeExpr::Enum { cases } => {
let case = json
.as_str()
.ok_or_else(|| format!("{field}: expected enum string"))?;
if !cases.iter().any(|candidate| candidate.name == case) {
return Err(format!("{field}: unknown enum case {case}"));
}
Ok(Value::String(case.into()))
}
TypeExpr::Json => json_to_untyped(json, field),
TypeExpr::List { items } => json
.as_array()
.ok_or_else(|| format!("{field}: expected array"))?
.iter()
.enumerate()
.map(|(index, item)| {
json_to_typed(descriptor, items, item, &format!("{field}[{index}]"))
})
.collect::<Result<Vec<_>, _>>()
.map(Value::List),
TypeExpr::Record { fields } => {
let object = json
.as_object()
.ok_or_else(|| format!("{field}: expected object"))?;
for name in object.keys() {
if !fields.iter().any(|candidate| candidate.name == *name) {
return Err(format!("{field}.{name}: unknown field"));
}
}
let mut values = BTreeMap::new();
for declaration in fields {
match object.get(&declaration.name) {
Some(value) => {
values.insert(
declaration.name.clone(),
json_to_typed(
descriptor,
&declaration.r#type,
value,
&format!("{field}.{}", declaration.name),
)?,
);
}
None if declaration.required => {
return Err(format!(
"{field}.{}: required field is missing",
declaration.name
));
}
None => {}
}
}
Ok(Value::Record(values))
}
TypeExpr::Union { cases } => {
let object = json
.as_object()
.ok_or_else(|| format!("{field}: expected union object"))?;
if object.keys().any(|name| name != "$case" && name != "value") {
return Err(format!("{field}: union accepts only $case and value"));
}
let case_name = object
.get("$case")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{field}.$case: required string is missing"))?;
let case = cases
.iter()
.find(|candidate| candidate.name == case_name)
.ok_or_else(|| format!("{field}.$case: unknown union case {case_name}"))?;
let mut values = BTreeMap::from([("$case".into(), Value::String(case_name.into()))]);
match (&case.payload, object.get("value")) {
(Some(payload), Some(value)) => {
values.insert(
"value".into(),
json_to_typed(descriptor, payload, value, &format!("{field}.value"))?,
);
}
(Some(_), None) => {
return Err(format!("{field}.value: required payload is missing"));
}
(None, Some(_)) => {
return Err(format!("{field}.value: payload-free case has a value"));
}
(None, None) => {}
}
Ok(Value::Record(values))
}
TypeExpr::Named { .. } => unreachable!("named types handled above"),
_ => Err(format!(
"{field}: value does not match {}",
type_name(r#type)
)),
}
}
fn json_to_untyped(json: &serde_json::Value, field: &str) -> Result<Value, String> {
match json {
serde_json::Value::Null => Ok(Value::Unit),
serde_json::Value::Bool(value) => Ok(Value::Boolean(*value)),
serde_json::Value::Number(value) => {
if let Some(integer) = value.as_i64() {
Ok(Value::Integer(integer))
} else {
value
.as_f64()
.filter(|number| number.is_finite())
.map(Value::Number)
.ok_or_else(|| format!("{field}: number is not finite"))
}
}
serde_json::Value::String(value) => Ok(Value::String(value.clone())),
serde_json::Value::Array(values) => values
.iter()
.enumerate()
.map(|(index, value)| json_to_untyped(value, &format!("{field}[{index}]")))
.collect::<Result<Vec<_>, _>>()
.map(Value::List),
serde_json::Value::Object(values) => values
.iter()
.map(|(name, value)| {
json_to_untyped(value, &format!("{field}.{name}"))
.map(|value| (name.clone(), value))
})
.collect::<Result<BTreeMap<_, _>, _>>()
.map(Value::Record),
}
}
#[cfg(test)]
mod tests {
use super::*;
use wip_protocol::{
EnumCase, FieldDeclaration, INTERFACE_FORMAT_V1, ParameterDeclaration, ReturnDeclaration,
TypeDeclaration, UnionCase,
};
fn descriptor(
parameters: Vec<ParameterDeclaration>,
types: Vec<TypeDeclaration>,
) -> InterfaceDescriptor {
InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types,
operations: vec![OperationDeclaration {
name: "run".into(),
documentation: None,
parameters,
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::Unit,
},
}],
}
}
#[test]
fn validates_every_canonical_shape_and_reports_fields() {
let parameters = vec![
parameter("unit", true, TypeExpr::Unit),
parameter("flag", true, TypeExpr::Boolean),
parameter("count", true, TypeExpr::Integer),
parameter("number", true, TypeExpr::Number),
parameter("text", true, TypeExpr::String),
parameter("bytes", true, TypeExpr::Bytes),
parameter("entry", true, TypeExpr::Entry),
parameter("json", true, TypeExpr::Json),
parameter(
"list",
true,
TypeExpr::List {
items: Box::new(TypeExpr::Integer),
},
),
parameter(
"record",
true,
TypeExpr::Record {
fields: vec![FieldDeclaration {
name: "name".into(),
required: true,
documentation: None,
r#type: TypeExpr::String,
}],
},
),
parameter(
"choice",
true,
TypeExpr::Enum {
cases: vec![EnumCase {
name: "yes".into(),
documentation: None,
}],
},
),
parameter(
"union",
true,
TypeExpr::Union {
cases: vec![UnionCase {
name: "some".into(),
documentation: None,
payload: Some(TypeExpr::Integer),
}],
},
),
parameter(
"named",
true,
TypeExpr::Named {
name: "Alias".into(),
},
),
];
let descriptor = descriptor(
parameters,
vec![TypeDeclaration {
name: "Alias".into(),
documentation: None,
definition: TypeExpr::String,
}],
);
let operation = descriptor.operations[0].clone();
let mut editor = ArgumentEditor::new("test", descriptor, operation);
let inputs = [
"null",
"true",
"7",
"2.5",
"hello",
"aGk=",
"/item",
"{\"safe\":true}",
"[1,2]",
"{\"name\":\"n\"}",
"yes",
"{\"$case\":\"some\",\"value\":4}",
"value",
];
for (field, input) in editor.fields.iter_mut().zip(inputs) {
field.input = input.into();
}
let values = editor.validate().expect("valid values");
assert_eq!(values["bytes"], Value::Bytes(b"hi".to_vec()));
assert_eq!(values["entry"], Value::String("/item".into()));
assert!(editor.fields.iter().all(|field| field.diagnostic.is_none()));
}
#[test]
fn missing_invalid_and_optional_fields_are_field_local() {
let descriptor = descriptor(
vec![
parameter("required", true, TypeExpr::Integer),
parameter("optional", false, TypeExpr::Boolean),
],
vec![],
);
let operation = descriptor.operations[0].clone();
let mut editor = ArgumentEditor::new("test", descriptor, operation);
editor.fields[1].input = "not-a-bool".into();
assert_eq!(editor.validate(), Err(InvalidArguments));
assert!(
editor.fields[0]
.diagnostic
.as_deref()
.unwrap()
.contains("required")
);
assert!(
editor.fields[1]
.diagnostic
.as_deref()
.unwrap()
.contains("true or false")
);
editor.fields[0].input = "1".into();
editor.fields[1].input.clear();
assert_eq!(editor.validate().unwrap().len(), 1);
}
fn parameter(name: &str, required: bool, r#type: TypeExpr) -> ParameterDeclaration {
ParameterDeclaration {
name: name.into(),
required,
documentation: None,
r#type,
}
}
}
+10
View File
@@ -0,0 +1,10 @@
//! Presentation and terminal interaction for stateful WIP client sessions.
#![deny(missing_docs)]
pub mod app;
pub mod config;
pub mod editor;
pub mod render;
pub mod runtime;
pub mod terminal;
+6
View File
@@ -0,0 +1,6 @@
fn main() {
if let Err(error) = wip_tui::runtime::run_from_env() {
eprintln!("wip-tui: {error}");
std::process::exit(1);
}
}
+715
View File
@@ -0,0 +1,715 @@
//! Deterministic bounded rendering for real and test terminal backends.
use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap};
use crate::app::{App, ConnectionState, Focus, HistoryKind, Modal, OperationRow, ViewState};
use crate::editor::type_name;
const MAX_RENDER_TEXT: usize = 512;
/// Draws the complete application without mutating it.
pub fn draw(frame: &mut Frame<'_>, app: &App) {
let area = frame.area();
if area.width < 48 || area.height < 14 {
frame.render_widget(
Paragraph::new("wip-tui\nTerminal is too small. Resize to at least 48 x 14.\nq: quit")
.block(
Block::default()
.borders(Borders::ALL)
.title(" Minimum size "),
)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
area,
);
return;
}
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(2),
Constraint::Min(8),
Constraint::Length(2),
])
.split(area);
render_header(frame, vertical[0], app);
let columns = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(38), Constraint::Percentage(62)])
.split(vertical[1]);
render_tree(frame, columns[0], app);
let right = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(31),
Constraint::Percentage(39),
Constraint::Percentage(30),
])
.split(columns[1]);
render_selected(frame, right[0], app);
render_operations(frame, right[1], app);
render_history(frame, right[2], app);
render_footer(frame, vertical[2], app);
render_modal(frame, app);
}
fn render_header(frame: &mut Frame<'_>, area: Rect, app: &App) {
let connection = match &app.connection {
ConnectionState::Disconnected => "DISCONNECTED",
ConnectionState::Connecting => "CONNECTING",
ConnectionState::Connected => "CONNECTED",
ConnectionState::Failed(_) => "FAILED (R reconnect / q quit)",
};
let text = format!(
" wip-tui {} [{}] in-flight: {}",
sanitize(&app.endpoint),
connection,
app.in_flight.len()
);
frame.render_widget(
Paragraph::new(text).style(Style::default().add_modifier(Modifier::BOLD)),
area,
);
}
fn render_tree(frame: &mut Frame<'_>, area: Rect, app: &App) {
let rows = app.visible_paths().into_iter().map(|path| {
let node = app.entries.get(&path);
let selected = path == app.selected_path;
let depth = if path == "/" {
0
} else {
path.trim_start_matches('/').split('/').count()
};
let marker = node.map_or('·', |node| if node.expanded { '▼' } else { '▶' });
let label = node.and_then(|node| node.object.as_ref()).map_or_else(
|| path.clone(),
|object| {
if path == "/" {
"/".into()
} else {
object.name.clone()
}
},
);
let mut suffix = node.map_or_else(
|| " [unloaded]".into(),
|node| {
let tree = match &node.tree_state {
ViewState::Loading(_) => " [loading children]",
ViewState::Stale => " [stale children]",
ViewState::Error(_) => " [failed children]",
ViewState::Fresh if node.children.is_empty() => " [empty]",
_ => "",
};
let incomplete = if node.truncated {
" [truncated: + to increase limit]"
} else {
""
};
let object = state_suffix(&node.state);
format!("{object}{tree}{incomplete}")
},
);
suffix = sanitize(&suffix);
let style = if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else {
Style::default()
};
ListItem::new(Line::from(vec![
Span::raw(" ".repeat(depth)),
Span::raw(format!("{marker} {}", sanitize(&label))),
Span::styled(suffix, state_style(node.map(|value| &value.state))),
]))
.style(style)
});
frame.render_widget(
List::new(rows).block(focused_block(" Worldspace tree ", app.focus == Focus::Tree)),
area,
);
}
fn render_selected(frame: &mut Frame<'_>, area: Rect, app: &App) {
let mut lines = vec![Line::from(format!(
"Path: {}",
sanitize(&app.selected_path)
))];
if let Some(entry) = app.entries.get(&app.selected_path) {
lines.push(Line::from(format!("State: {}", state_label(&entry.state))));
if entry.state == ViewState::Fresh {
if let Some(object) = &entry.object {
lines.push(Line::from(format!("Name: {}", sanitize(&object.name))));
lines.push(Line::from(format!(
"Description: {}",
object
.description
.as_deref()
.map(sanitize)
.unwrap_or_else(|| "(none)".into())
)));
lines.push(Line::from(format!(
"Interfaces (ordered): {}",
if object.interfaces.is_empty() {
"(none)".into()
} else {
object
.interfaces
.iter()
.map(|value| sanitize(value))
.collect::<Vec<_>>()
.join(", ")
}
)));
}
} else {
lines.push(Line::from(
"No current object metadata; refresh required (old metadata hidden).",
));
}
if entry.truncated {
lines.push(Line::styled(
"TRUNCATED: this is not a complete subtree.",
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD),
));
}
}
frame.render_widget(
Paragraph::new(lines)
.block(focused_block(" Selected Entry ", app.focus == Focus::Entry))
.wrap(Wrap { trim: false }),
area,
);
}
fn render_operations(frame: &mut Frame<'_>, area: Rect, app: &App) {
let rows = app.operation_rows();
let items = rows.iter().enumerate().map(|(index, row)| {
let (text, style) = operation_line(app, row);
let selected = app.focus == Focus::Operations && index == app.operation_cursor;
ListItem::new(text).style(if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else {
style
})
});
let title = " Interfaces / Operations (Enter: load or edit) ";
if rows.is_empty() {
frame.render_widget(
Paragraph::new("No declared interfaces or no current object.")
.block(focused_block(title, app.focus == Focus::Operations)),
area,
);
} else {
frame.render_widget(
List::new(items).block(focused_block(title, app.focus == Focus::Operations)),
area,
);
}
}
fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
if let Some(name) = &row.operation {
let descriptor = app
.interfaces
.get(&row.interface)
.and_then(|view| view.descriptor.as_ref());
let declaration = descriptor.and_then(|descriptor| {
descriptor
.operations
.iter()
.find(|operation| operation.name == *name)
});
let signature = declaration.map_or_else(
|| format!(" ({}, {})", row.interface, name),
|operation| {
let parameters = operation
.parameters
.iter()
.map(|parameter| {
format!(
"{}{}: {}",
parameter.name,
if parameter.required { "" } else { "?" },
type_name(&parameter.r#type)
)
})
.collect::<Vec<_>>()
.join(", ");
let documentation = operation
.documentation
.as_ref()
.map(|documentation| format!(" — {}", documentation.summary))
.unwrap_or_default();
format!(
" ({}, {}) ({parameters}) -> {}{}",
row.interface,
name,
type_name(&operation.returns.r#type),
documentation
)
},
);
(Line::from(sanitize(&signature)), Style::default())
} else {
let interface = app.interfaces.get(&row.interface);
let state = interface.map_or("unloaded".into(), |view| state_label(&view.state));
let documentation = interface
.filter(|view| view.state == ViewState::Fresh)
.and_then(|view| view.descriptor.as_ref())
.and_then(|descriptor| descriptor.documentation.as_ref())
.map(|documentation| format!(" — {}", sanitize(&documentation.summary)))
.unwrap_or_default();
(
Line::from(format!(
"Interface {} [{}]{}",
sanitize(&row.interface),
state,
documentation
)),
Style::default().add_modifier(Modifier::BOLD),
)
}
}
fn render_history(frame: &mut Frame<'_>, area: Rect, app: &App) {
let items = app.history.iter().enumerate().map(|(index, item)| {
let label = match item.kind {
HistoryKind::Success => "SUCCESS",
HistoryKind::DomainFailure => "HOST FAILURE",
HistoryKind::ProtocolError => "PROTOCOL ERROR",
HistoryKind::TransportFailure => "TRANSPORT FAILURE",
HistoryKind::ClientFailure => "CLIENT FAILURE",
HistoryKind::OutcomeUnknown => "OUTCOME UNKNOWN",
HistoryKind::Information => "INFO",
};
let link = item
.entry_target
.as_ref()
.map_or("", |_| " [Enter: go to Entry]");
let text = format!(
"[{label}] {}: {}{link}",
sanitize(&item.title),
sanitize(&item.detail)
);
let selected = app.focus == Focus::History && index == app.history_cursor;
ListItem::new(text).style(if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else if item.kind == HistoryKind::OutcomeUnknown {
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
} else {
Style::default()
})
});
let block = focused_block(
" Recent results / diagnostics ",
app.focus == Focus::History,
);
if app.history.is_empty() {
frame.render_widget(Paragraph::new("No results yet.").block(block), area);
} else {
frame.render_widget(List::new(items).block(block), area);
}
}
fn render_footer(frame: &mut Frame<'_>, area: Rect, app: &App) {
let help = " ↑↓/jk move ←→/hl parent/expand Tab focus Enter select r refresh + larger tree c cancel read ? help q quit ";
let text = format!("{}\n{}", help, sanitize(&app.status));
frame.render_widget(
Paragraph::new(text).style(Style::default().fg(Color::DarkGray)),
area,
);
}
fn render_modal(frame: &mut Frame<'_>, app: &App) {
match &app.modal {
Modal::None => {}
Modal::Help => {
let area = centered(frame.area(), 76, 70);
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(
"Keyboard help\n\n↑/↓ or j/k move selection / editor field\n←/→ or h/l collapse/expand or parent\nTab next pane\nEnter load interface, edit operation, confirm execute\nr refresh selected Entry and subtree\n+ increase truncated tree limit and retry\nc cancel newest retrieval (never cancels a sent operation)\nR reconnect after failure\nEsc close modal\nq quit\n\nOperations are never sent until the confirmation screen is accepted.",
)
.block(Block::default().borders(Borders::ALL).title(" Help "))
.wrap(Wrap { trim: false }),
area,
);
}
Modal::Editor(editor) => {
let area = centered(frame.area(), 86, 78);
frame.render_widget(Clear, area);
let mut lines = vec![Line::from(format!(
"Target: {} Operation: ({}, {})",
sanitize(&app.selected_path),
sanitize(&editor.interface),
sanitize(&editor.operation.name)
))];
if editor.fields.is_empty() {
lines.push(Line::from("(no parameters)"));
}
for (index, field) in editor.fields.iter().enumerate() {
let cursor = if index == editor.cursor { ">" } else { " " };
let requirement = if field.required {
"required"
} else {
"optional"
};
lines.push(Line::from(format!(
"{cursor} {} [{requirement}, {}] = {}",
sanitize(&field.name),
sanitize(&type_name(&field.r#type)),
sanitize(&field.input)
)));
if let Some(diagnostic) = &field.diagnostic {
lines.push(Line::styled(
format!(" ERROR: {}", sanitize(diagnostic)),
Style::default().fg(Color::Red),
));
}
}
lines.push(Line::from(""));
lines.push(Line::from("Enter: validate and review Esc: cancel"));
frame.render_widget(
Paragraph::new(lines)
.block(
Block::default()
.borders(Borders::ALL)
.title(" Argument editor "),
)
.wrap(Wrap { trim: false }),
area,
);
}
Modal::Confirm { editor, arguments } => {
let area = centered(frame.area(), 82, 58);
frame.render_widget(Clear, area);
let mut lines = vec![
Line::styled(
"EXPLICIT EXECUTION CONFIRMATION",
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD),
),
Line::from(format!("Entry: {}", sanitize(&app.selected_path))),
Line::from(format!("Interface: {}", sanitize(&editor.interface))),
Line::from(format!("Operation: {}", sanitize(&editor.operation.name))),
Line::from("Input values:"),
];
for (name, value) in arguments {
lines.push(Line::from(format!(
" {} = {}",
sanitize(name),
sanitize(&bounded_value(value))
)));
}
lines.push(Line::from(""));
lines.push(Line::styled(
"Enter/e: EXECUTE ONCE Esc: back to editor",
Style::default().add_modifier(Modifier::BOLD),
));
frame.render_widget(
Paragraph::new(lines)
.block(Block::default().borders(Borders::ALL).title(" Confirm "))
.wrap(Wrap { trim: false }),
area,
);
}
}
}
fn focused_block(title: &'static str, focused: bool) -> Block<'static> {
let style = if focused {
Style::default().fg(Color::Cyan)
} else {
Style::default()
};
Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(style)
}
fn centered(area: Rect, percent_x: u16, percent_y: u16) -> Rect {
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(area);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(vertical[1])[1]
}
fn state_suffix(state: &ViewState) -> &'static str {
match state {
ViewState::Unloaded => " [unloaded]",
ViewState::Loading(_) => " [loading]",
ViewState::Fresh => "",
ViewState::Stale => " [stale: refresh required]",
ViewState::Error(_) => " [error]",
}
}
fn state_label(state: &ViewState) -> String {
match state {
ViewState::Unloaded => "unloaded".into(),
ViewState::Loading(id) => format!("loading request #{id}"),
ViewState::Fresh => "fresh".into(),
ViewState::Stale => "stale — refresh required".into(),
ViewState::Error(error) => format!("error — {}", sanitize(error)),
}
}
fn state_style(state: Option<&ViewState>) -> Style {
match state {
Some(ViewState::Stale) => Style::default().fg(Color::Yellow),
Some(ViewState::Error(_)) => Style::default().fg(Color::Red),
Some(ViewState::Loading(_)) => Style::default().fg(Color::Blue),
_ => Style::default(),
}
}
/// Replaces terminal control characters and bounds user/remote text by Unicode scalars.
#[must_use]
pub fn sanitize(input: &str) -> String {
let mut output = String::new();
for (count, character) in input.chars().enumerate() {
if count >= MAX_RENDER_TEXT {
output.push('…');
break;
}
if character.is_control() && !matches!(character, '\n' | '\t') {
output.push('�');
} else {
output.push(character);
}
}
output
}
/// Formats a protocol value with strict byte and collection bounds.
#[must_use]
pub fn bounded_value(value: &wip_protocol::Value) -> String {
bounded_value_at(value, 0)
}
fn bounded_value_at(value: &wip_protocol::Value, depth: usize) -> String {
if depth >= 8 {
return "…".into();
}
match value {
wip_protocol::Value::Unit => "null".into(),
wip_protocol::Value::Boolean(value) => value.to_string(),
wip_protocol::Value::Integer(value) => value.to_string(),
wip_protocol::Value::Number(value) => value.to_string(),
wip_protocol::Value::String(value) => format!("{:?}", sanitize(value)),
wip_protocol::Value::Bytes(bytes) => {
let shown = bytes
.iter()
.take(32)
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
if bytes.len() > 32 {
format!("bytes[{}]: {shown}…", bytes.len())
} else {
format!("bytes[{}]: {shown}", bytes.len())
}
}
wip_protocol::Value::Record(values) => {
let mut fields = values
.iter()
.take(16)
.map(|(name, value)| {
format!("{}: {}", sanitize(name), bounded_value_at(value, depth + 1))
})
.collect::<Vec<_>>();
if values.len() > 16 {
fields.push("…".into());
}
format!("{{{}}}", fields.join(", "))
}
wip_protocol::Value::List(values) => {
let mut items = values
.iter()
.take(16)
.map(|value| bounded_value_at(value, depth + 1))
.collect::<Vec<_>>();
if values.len() > 16 {
items.push("…".into());
}
format!("[{}]", items.join(", "))
}
}
}
#[cfg(test)]
mod tests {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use super::*;
use crate::app::{EntryView, HistoryItem};
use crate::editor::ArgumentEditor;
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState};
use wip_protocol::{
INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, OperationDeclaration,
ParameterDeclaration, ReturnDeclaration, TypeExpr,
};
fn rendered(app: &App, width: u16, height: u16) -> String {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).unwrap();
terminal.draw(|frame| draw(frame, app)).unwrap();
terminal
.backend()
.buffer()
.content
.iter()
.map(|cell| cell.symbol())
.collect::<Vec<_>>()
.chunks(width as usize)
.map(|line| line.concat())
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn snapshot_contains_non_color_state_markers_and_hides_validators() {
let mut app = App::new("https://example.test/wip/");
app.connection = ConnectionState::Connected;
app.entries.get_mut("/").unwrap().truncated = true;
app.entries.get_mut("/").unwrap().state = ViewState::Stale;
app.push_history(HistoryItem {
kind: HistoryKind::OutcomeUnknown,
title: "replace".into(),
detail: "execution and side effects are unknown; refresh before deciding again".into(),
entry_target: None,
});
let snapshot = rendered(&app, 110, 30);
assert!(snapshot.contains("truncated"));
assert!(snapshot.contains("stale"));
assert!(snapshot.contains("OUTCOME UNKNOWN"));
assert!(!snapshot.contains("validator"));
}
#[test]
fn snapshots_cover_selected_operation_editor_and_failure_categories() {
let mut app = App::new("https://example.test/wip/");
app.connection = ConnectionState::Connected;
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(Object {
name: String::new(),
description: Some("public root description".into()),
interfaces: vec!["demo-interface".into()],
r#ref: None,
validator: Some(b"must-not-render".to_vec()),
}),
validator: Some(b"must-not-render".to_vec()),
state: ObservationState::Fresh,
});
let descriptor = InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types: vec![],
operations: vec![OperationDeclaration {
name: "run".into(),
documentation: None,
parameters: vec![ParameterDeclaration {
name: "count".into(),
required: true,
documentation: None,
r#type: TypeExpr::Integer,
}],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::String,
},
}],
};
app.apply_interface(InterfaceObservation {
reference: "demo-interface".into(),
descriptor: Some(descriptor.clone()),
validator: Some(b"must-not-render".to_vec()),
state: ObservationState::Fresh,
});
for (kind, title) in [
(HistoryKind::Success, "result"),
(HistoryKind::ProtocolError, "invalid response"),
(HistoryKind::TransportFailure, "network"),
(HistoryKind::ClientFailure, "local"),
] {
app.push_history(HistoryItem {
kind,
title: title.into(),
detail: "bounded detail".into(),
entry_target: None,
});
}
let snapshot = rendered(&app, 140, 40);
assert!(snapshot.contains("public root description"));
assert!(snapshot.contains("(demo-interface, run)"));
assert!(snapshot.contains("SUCCESS"));
assert!(snapshot.contains("PROTOCOL ERROR"));
assert!(snapshot.contains("TRANSPORT FAILURE"));
assert!(snapshot.contains("CLIENT FAILURE"));
assert!(!snapshot.contains("must-not-render"));
let mut editor = ArgumentEditor::new(
"demo-interface",
descriptor.clone(),
descriptor.operations[0].clone(),
);
editor.fields[0].diagnostic = Some("expected integer".into());
app.modal = Modal::Editor(editor);
let snapshot = rendered(&app, 140, 40);
assert!(snapshot.contains("Argument editor"));
assert!(snapshot.contains("count [required, Integer]"));
assert!(snapshot.contains("ERROR: expected integer"));
}
#[test]
fn tiny_terminal_has_a_safe_fallback() {
let snapshot = rendered(&App::new("https://example.test/"), 30, 8);
assert!(snapshot.contains("too small"));
}
#[test]
fn control_characters_and_large_bytes_are_bounded() {
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
let display = bounded_value(&wip_protocol::Value::Bytes(vec![7; 1000]));
assert!(display.starts_with("bytes[1000]"));
assert!(display.ends_with('…'));
}
#[test]
fn entry_view_type_remains_constructible_for_external_snapshots() {
let entry = EntryView {
path: "/".into(),
object: None,
state: ViewState::Unloaded,
children: vec![],
tree_state: ViewState::Unloaded,
expanded: false,
truncated: false,
limit: 1,
};
assert_eq!(entry.path, "/");
}
}
File diff suppressed because it is too large Load Diff
+132
View File
@@ -0,0 +1,132 @@
//! Terminal lifecycle guard and crossterm input translation.
use std::io::{self, Stdout};
use std::sync::Arc;
use crossterm::cursor::{Hide, Show};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use crate::app::InputKey;
type PanicHook = dyn for<'a> Fn(&std::panic::PanicHookInfo<'a>) + Send + Sync + 'static;
/// RAII owner of raw mode, alternate screen, cursor visibility, and panic recovery.
pub struct TerminalGuard {
terminal: Terminal<CrosstermBackend<Stdout>>,
previous_hook: Arc<PanicHook>,
}
impl TerminalGuard {
/// Enters terminal UI mode, restoring partial setup on failure.
pub fn enter() -> io::Result<Self> {
enable_raw_mode()?;
let mut stdout = io::stdout();
if let Err(error) = execute!(stdout, EnterAlternateScreen, Hide) {
let _ = disable_raw_mode();
return Err(error);
}
let terminal = match Terminal::new(CrosstermBackend::new(stdout)) {
Ok(terminal) => terminal,
Err(error) => {
restore_terminal();
return Err(error);
}
};
let previous_hook: Arc<PanicHook> = std::panic::take_hook().into();
let panic_hook = Arc::clone(&previous_hook);
let terminal_owner = std::thread::current().id();
std::panic::set_hook(Box::new(move |information| {
if std::thread::current().id() == terminal_owner {
restore_terminal();
}
panic_hook(information);
}));
Ok(Self {
terminal,
previous_hook,
})
}
/// Returns the ratatui terminal for drawing.
pub fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
&mut self.terminal
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let previous = Arc::clone(&self.previous_hook);
std::panic::set_hook(Box::new(move |information| previous(information)));
restore_terminal();
}
}
fn restore_terminal() {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
}
/// Converts one crossterm key event into a terminal-independent reducer key.
///
/// When `editing` is true, printable command letters remain text input and only
/// Ctrl-C/Escape retain global meaning.
#[must_use]
pub fn translate_key(event: KeyEvent, editing: bool) -> Option<InputKey> {
if event.modifiers.contains(KeyModifiers::CONTROL) && event.code == KeyCode::Char('c') {
return Some(InputKey::Quit);
}
let key = match event.code {
KeyCode::Up => InputKey::Up,
KeyCode::Down => InputKey::Down,
KeyCode::Left => InputKey::Left,
KeyCode::Right => InputKey::Right,
KeyCode::Tab => InputKey::Tab,
KeyCode::Enter => InputKey::Enter,
KeyCode::Esc => InputKey::Escape,
KeyCode::Backspace => InputKey::Backspace,
KeyCode::Char(character) if editing => InputKey::Character(character),
KeyCode::Char('k') => InputKey::Up,
KeyCode::Char('j') => InputKey::Down,
KeyCode::Char('h') => InputKey::Left,
KeyCode::Char('l') => InputKey::Right,
KeyCode::Char('r') => InputKey::Refresh,
KeyCode::Char('R') => InputKey::Reconnect,
KeyCode::Char('+') | KeyCode::Char('=') => InputKey::IncreaseLimit,
KeyCode::Char('c') => InputKey::CancelRead,
KeyCode::Char('?') => InputKey::Help,
KeyCode::Char('q') => InputKey::Quit,
KeyCode::Char(character) => InputKey::Character(character),
_ => return None,
};
Some(key)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn editing_keeps_command_letters_as_text_but_ctrl_c_quits() {
assert_eq!(
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), true),
Some(InputKey::Character('q'))
);
assert_eq!(
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), false),
Some(InputKey::Quit)
);
assert_eq!(
translate_key(
KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
true
),
Some(InputKey::Quit)
);
}
}