From 7bc2f2ca6bf06917c3fafa1aecbd15b9f46ceb7d Mon Sep 17 00:00:00 2001 From: Bethvour Date: Sun, 19 Apr 2026 19:34:26 -0500 Subject: [PATCH 01/10] Add AI action proposals and approval flow --- src/ai/providers/mock.rs | 41 ++++++++- src/ai/providers/openai.rs | 80 ++++++++++++++++- src/app/store.rs | 166 +++++++++++++++++++++++++++++++---- src/commands/mod.rs | 45 ++++++++-- src/ui/views/command_pane.rs | 41 ++++++++- src/ui/views/modal.rs | 1 + tests/foundation.rs | 64 +++++++++++++- 7 files changed, 404 insertions(+), 34 deletions(-) diff --git a/src/ai/providers/mock.rs b/src/ai/providers/mock.rs index 317c6d6..8fb4d0d 100644 --- a/src/ai/providers/mock.rs +++ b/src/ai/providers/mock.rs @@ -1,5 +1,7 @@ use crate::ai::provider::{AiFuture, AiProvider}; -use crate::domain::{AiCitation, AiRequest, AiRequestKind, AiResponse}; +use crate::domain::{ + AiActionProposal, AiCitation, AiRequest, AiRequestKind, AiResponse, SafetyClass, +}; use crate::shared::time::now_utc; pub struct MockProvider { @@ -59,6 +61,41 @@ fn mock_response(request: AiRequest, model: Option) -> AiResponse { )); } + let proposals = match request.kind { + AiRequestKind::Assist => vec![ + AiActionProposal { + summary: "Inspect the current repository state".to_string(), + detail: "Check the working tree before taking additional action.".to_string(), + command: Some("git status".to_string()), + safety_class: SafetyClass::Passive, + }, + AiActionProposal { + summary: "Run the Rust test suite".to_string(), + detail: "Confirm the current behavior against the latest local changes." + .to_string(), + command: Some("cargo test".to_string()), + safety_class: SafetyClass::Caution, + }, + ], + AiRequestKind::Diagnose => vec![ + AiActionProposal { + summary: "Re-run tests to reproduce the failure".to_string(), + detail: "Use a fresh test run so the latest output is captured in Forge." + .to_string(), + command: Some("cargo test".to_string()), + safety_class: SafetyClass::Caution, + }, + AiActionProposal { + summary: "Review the current diff".to_string(), + detail: + "Inspect the working tree for recent changes that correlate with the failure." + .to_string(), + command: Some("git diff --stat".to_string()), + safety_class: SafetyClass::Passive, + }, + ], + }; + AiResponse { request_id: request.id, created_at: now_utc(), @@ -67,7 +104,7 @@ fn mock_response(request: AiRequest, model: Option) -> AiResponse { summary: format!("Mock AI response for `{}`", request.prompt), message, recommendations, - proposals: Vec::new(), + proposals, citations: vec![AiCitation { label: "context".to_string(), detail: format!( diff --git a/src/ai/providers/openai.rs b/src/ai/providers/openai.rs index e0fba6b..5a0bb80 100644 --- a/src/ai/providers/openai.rs +++ b/src/ai/providers/openai.rs @@ -6,7 +6,7 @@ use serde_json::{json, Value}; use crate::ai::provider::{AiFuture, AiProvider}; use crate::config::AiConfig; -use crate::domain::{AiCitation, AiRequest, AiResponse}; +use crate::domain::{AiActionProposal, AiCitation, AiRequest, AiResponse, SafetyClass}; use crate::shared::error::AiError; use crate::shared::time::now_utc; @@ -121,7 +121,16 @@ impl AiProvider for OpenAiProvider { summary: structured.summary, message: structured.message, recommendations: structured.recommendations, - proposals: Vec::new(), + proposals: structured + .proposals + .into_iter() + .map(|proposal| AiActionProposal { + summary: proposal.summary, + detail: proposal.detail, + command: (!proposal.command.trim().is_empty()).then_some(proposal.command), + safety_class: proposal.safety_class, + }) + .collect(), citations: structured .citations .into_iter() @@ -172,6 +181,10 @@ fn build_developer_prompt(request: &AiRequest) -> String { "Use the provided repository/runtime context. Be concrete, grounded, and concise.\n", "Do not claim certainty when evidence is weak.\n", "Do not propose hidden actions.\n", + "Only include action proposals when they are directly grounded in the supplied context.\n", + "Each proposal must be a single inspectable command. If no grounded action is appropriate, return an empty proposals array.\n", + "The proposal safety_class is a best-effort hint using one of: Passive, Safe, Caution, Risky, Destructive.\n", + "Return at most 3 proposals.\n", "Return JSON matching the requested schema.\n\n", "Request kind: {}\n", "UI focus: {}\n", @@ -285,7 +298,7 @@ fn response_schema() -> Value { json!({ "type": "object", "additionalProperties": false, - "required": ["summary", "message", "recommendations", "citations"], + "required": ["summary", "message", "recommendations", "proposals", "citations"], "properties": { "summary": { "type": "string", @@ -300,6 +313,27 @@ fn response_schema() -> Value { "items": { "type": "string" }, "description": "Concrete next steps or checks." }, + "proposals": { + "type": "array", + "description": "Optional grounded actions. Use an empty array when no direct action should be suggested.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["summary", "detail", "command", "safety_class"], + "properties": { + "summary": { "type": "string" }, + "detail": { "type": "string" }, + "command": { + "type": "string", + "description": "A single shell command to run. Do not include explanations here." + }, + "safety_class": { + "type": "string", + "enum": ["Passive", "Safe", "Caution", "Risky", "Destructive"] + } + } + } + }, "citations": { "type": "array", "items": { @@ -387,6 +421,7 @@ struct StructuredAiResponse { summary: String, message: String, recommendations: Vec, + proposals: Vec, citations: Vec, } @@ -396,6 +431,14 @@ struct StructuredCitation { detail: String, } +#[derive(Debug, Deserialize)] +struct StructuredProposal { + summary: String, + detail: String, + command: String, + safety_class: SafetyClass, +} + #[cfg(test)] mod tests { use serde_json::json; @@ -413,7 +456,7 @@ mod tests { "output": [ { "content": [ - { "type": "output_text", "text": "{\"summary\":\"s\",\"message\":\"m\",\"recommendations\":[],\"citations\":[]}" } + { "type": "output_text", "text": "{\"summary\":\"s\",\"message\":\"m\",\"recommendations\":[],\"proposals\":[],\"citations\":[]}" } ] } ] @@ -443,5 +486,34 @@ mod tests { let payload = build_payload(&request, "gpt-5-mini"); assert_eq!(payload["text"]["format"]["type"], "json_schema"); assert_eq!(payload["model"], "gpt-5-mini"); + assert!(payload["text"]["format"]["schema"]["required"] + .as_array() + .expect("schema required array should exist") + .iter() + .any(|value| value == "proposals")); + } + + #[test] + fn structured_response_parses_proposals() { + let parsed: StructuredAiResponse = serde_json::from_value(json!({ + "summary": "Forge found a likely next step", + "message": "The latest logs suggest rerunning the test suite.", + "recommendations": ["Inspect the newest stderr lines first."], + "proposals": [ + { + "summary": "Rerun the Rust test suite", + "detail": "Verify the current failure state before changing code.", + "command": "cargo test", + "safety_class": "Caution" + } + ], + "citations": [ + { "label": "timeline", "detail": "Recent command failure was captured in the event stream." } + ] + })) + .expect("structured response should deserialize"); + + assert_eq!(parsed.proposals.len(), 1); + assert_eq!(parsed.proposals[0].command, "cargo test"); } } diff --git a/src/app/store.rs b/src/app/store.rs index c41e9c8..d66986b 100644 --- a/src/app/store.rs +++ b/src/app/store.rs @@ -2,13 +2,13 @@ use std::collections::BTreeMap; use crate::ai; use crate::app::{AppAction, AppEvent, Effect, UiIntent}; -use crate::commands::{parse_input, ParsedInput}; +use crate::commands::{parse_input, parse_shell_input, ParsedInput}; use crate::domain::{ - AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, ApprovalDecision, - ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, DiagnosticLevel, - DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, JobRecord, JobStatus, - ModalState, Notification, NotificationLevel, ProcessSnapshot, ProcessStatus, ServiceHealth, - ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, + AiActionProposal, AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, + ApprovalDecision, ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, + DiagnosticLevel, DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, JobRecord, + JobStatus, ModalState, Notification, NotificationLevel, ProcessSnapshot, ProcessStatus, + ServiceHealth, ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, }; use crate::safety::{approval_message, approval_mode_for, classify_command}; use crate::shared::ids::{ApprovalId, CommandId, IdGenerator}; @@ -77,6 +77,7 @@ impl AppStore { AppEvent::AiCompleted(response) => { let request_id = response.request_id; let summary = truncate_for_timeline(&response.summary, 96); + let proposal_count = response.proposals.len(); let history_limit = self.state.config.ai.history_limit; self.state.ai.status = AiStatus::Completed; self.state.ai.active_request = None; @@ -92,11 +93,24 @@ impl AppStore { ); self.append_timeline( TimelineKind::Ai, - format!("AI response ready for request #{request_id}: {summary}"), + format!( + "AI response ready for request #{request_id}: {summary}{}", + if proposal_count > 0 { + format!(" ({proposal_count} proposal(s))") + } else { + String::new() + } + ), ); self.push_notification( NotificationLevel::Info, - format!("AI response ready for request #{request_id}"), + if proposal_count > 0 { + format!( + "AI response ready for request #{request_id} with {proposal_count} proposal(s)" + ) + } else { + format!("AI response ready for request #{request_id}") + }, ); } AppEvent::AiFailed { @@ -508,6 +522,7 @@ impl AppStore { Vec::new() } ParsedInput::AiPrompt { prompt, kind } => self.prepare_ai_request(prompt, kind), + ParsedInput::ApplyAiProposal(index) => self.apply_ai_proposal(index), } } @@ -565,6 +580,16 @@ impl AppStore { raw: String, background: bool, provenance: crate::domain::CommandProvenance, + ) -> Vec { + self.prepare_execution_internal(raw, background, provenance, None) + } + + fn prepare_execution_internal( + &mut self, + raw: String, + background: bool, + provenance: crate::domain::CommandProvenance, + proposal_context: Option<(usize, &AiActionProposal)>, ) -> Vec { let safety_class = classify_command(&raw); let command_id = self.ids.next_command(); @@ -620,15 +645,7 @@ impl AppStore { class: safety_class, mode, summary: raw.clone(), - detail: format!( - "{} action classified as {}", - if background { - "background" - } else { - "foreground" - }, - safety_class.label() - ), + detail: approval_detail(background, safety_class, proposal_context), execution: request, }; self.append_timeline(TimelineKind::Approval, approval_message(&approval)); @@ -650,6 +667,95 @@ impl AppStore { vec![Effect::ExecuteCommand(request)] } + fn apply_ai_proposal(&mut self, proposal_index: usize) -> Vec { + let Some(response) = self.state.ai.last_response.clone() else { + self.push_notification( + NotificationLevel::Warn, + "no AI proposals are available yet".to_string(), + ); + self.append_timeline( + TimelineKind::Ai, + "attempted to apply an AI proposal before any response was available".to_string(), + ); + return Vec::new(); + }; + + let Some(proposal) = response + .proposals + .get(proposal_index.saturating_sub(1)) + .cloned() + else { + self.push_notification( + NotificationLevel::Warn, + format!("AI proposal #{proposal_index} does not exist"), + ); + self.append_timeline( + TimelineKind::Ai, + format!( + "attempted to apply missing AI proposal #{proposal_index} from request #{}", + response.request_id + ), + ); + return Vec::new(); + }; + + let Some(command) = proposal + .command + .as_deref() + .map(str::trim) + .filter(|command| !command.is_empty()) + else { + self.push_notification( + NotificationLevel::Warn, + format!("AI proposal #{proposal_index} has no executable command"), + ); + self.append_timeline( + TimelineKind::Ai, + format!( + "AI proposal #{proposal_index} is advisory only: {}", + truncate_for_timeline(&proposal.summary, 96) + ), + ); + return Vec::new(); + }; + + let parsed = + match parse_shell_input(command, crate::domain::CommandProvenance::AiSuggestion) { + Ok(parsed) => parsed, + Err(message) => { + self.push_notification(NotificationLevel::Warn, message.clone()); + self.append_timeline(TimelineKind::Error, message); + return Vec::new(); + } + }; + + self.append_timeline( + TimelineKind::Ai, + format!( + "selected AI proposal #{proposal_index}: {}", + truncate_for_timeline(&proposal.summary, 96) + ), + ); + self.push_notification( + NotificationLevel::Info, + format!("selected AI proposal #{proposal_index}"), + ); + + match parsed { + ParsedInput::Execute { + command, + background, + provenance, + } => self.prepare_execution_internal( + command, + background, + provenance, + Some((proposal_index, &proposal)), + ), + _ => Vec::new(), + } + } + fn resolve_approval(&mut self, approval_id: ApprovalId, approved: bool) -> Vec { let position = self .state @@ -850,3 +956,29 @@ fn truncate_for_timeline(message: &str, max_len: usize) -> String { } format!("{}...", &trimmed[..max_len.saturating_sub(3)]) } + +fn approval_detail( + background: bool, + safety_class: crate::domain::SafetyClass, + proposal_context: Option<(usize, &AiActionProposal)>, +) -> String { + if let Some((proposal_index, proposal)) = proposal_context { + return format!( + "AI proposal #{proposal_index}: {}. {} Runtime classification: {} (model hint: {}).", + proposal.summary, + proposal.detail, + safety_class.label(), + proposal.safety_class.label() + ); + } + + format!( + "{} action classified as {}", + if background { + "background" + } else { + "foreground" + }, + safety_class.label() + ) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index cf5ae63..8736e04 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -20,6 +20,7 @@ pub enum ParsedInput { prompt: String, kind: AiRequestKind, }, + ApplyAiProposal(usize), } pub fn parse_input(input: &str) -> Result { @@ -29,12 +30,7 @@ pub fn parse_input(input: &str) -> Result { } if !trimmed.starts_with('/') { - let (command, background) = parse_shell(trimmed); - return Ok(ParsedInput::Execute { - command, - background, - provenance: CommandProvenance::UserInput, - }); + return parse_shell_input(trimmed, CommandProvenance::UserInput); } if trimmed == "/quit" || trimmed == "/exit" { @@ -84,10 +80,47 @@ pub fn parse_input(input: &str) -> Result { kind: AiRequestKind::Diagnose, }); } + if let Some(rest) = trimmed.strip_prefix("/apply ") { + let index = rest + .trim() + .parse::() + .map_err(|_| "apply expects a numeric proposal index".to_string())?; + if index == 0 { + return Err("apply expects a proposal index starting at 1".to_string()); + } + return Ok(ParsedInput::ApplyAiProposal(index)); + } + if let Some(rest) = trimmed.strip_prefix("/run-proposal ") { + let index = rest + .trim() + .parse::() + .map_err(|_| "run-proposal expects a numeric proposal index".to_string())?; + if index == 0 { + return Err("run-proposal expects a proposal index starting at 1".to_string()); + } + return Ok(ParsedInput::ApplyAiProposal(index)); + } Err(format!("unknown slash command: {trimmed}")) } +pub fn parse_shell_input( + input: &str, + provenance: CommandProvenance, +) -> Result { + let trimmed = input.trim(); + if trimmed.is_empty() { + return Err("input is empty".to_string()); + } + + let (command, background) = parse_shell(trimmed); + Ok(ParsedInput::Execute { + command, + background, + provenance, + }) +} + fn parse_shell(input: &str) -> (String, bool) { let trimmed = input.trim(); if let Some(stripped) = trimmed.strip_suffix('&') { diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index d0cbd9a..8070187 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -321,6 +321,45 @@ fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { ])); } } + if !response.proposals.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "Proposals", + theme::section_title(), + )])); + for (index, proposal) in response.proposals.iter().take(3).enumerate() { + lines.push(Line::from(vec![ + Span::styled(format!("{}. ", index + 1), theme::accent()), + Span::styled( + format!("[{}] ", proposal.safety_class.label()), + theme::status_badge(theme::INFO), + ), + Span::styled( + truncate_multiline( + &proposal.summary, + area.width.saturating_sub(20) as usize, + ), + theme::primary(), + ), + ])); + + let detail = proposal.command.as_deref().unwrap_or(&proposal.detail); + let action_hint = if proposal.command.is_some() { + format!("/apply {}", index + 1) + } else { + "inspect only".to_string() + }; + lines.push(Line::from(vec![ + Span::styled(" ", theme::muted()), + Span::styled( + truncate_multiline(detail, area.width.saturating_sub(20) as usize), + theme::muted(), + ), + Span::raw(" "), + Span::styled(action_hint, theme::accent()), + ])); + } + } if !response.citations.is_empty() { lines.push(Line::raw("")); lines.push(Line::from(vec![Span::styled( @@ -355,7 +394,7 @@ fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { } else { lines.push(Line::raw("")); lines.push(Line::from(vec![Span::styled( - "Use /ai for assistance or /diagnose for grounded diagnosis.", + "Use /ai for assistance, /diagnose for diagnosis, and /apply to run a proposal through approvals.", theme::muted(), )])); } diff --git a/src/ui/views/modal.rs b/src/ui/views/modal.rs index de3daff..5b3e3e2 100644 --- a/src/ui/views/modal.rs +++ b/src/ui/views/modal.rs @@ -69,6 +69,7 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Line::from("/help open this help"), Line::from("/ai queue an AI assistance request"), Line::from("/diagnose queue an AI diagnosis request"), + Line::from("/apply run AI proposal n through safety checks"), Line::from("/bg run a background command"), Line::from("/cancel cancel a running command"), Line::from("/approve approve the current pending action"), diff --git a/tests/foundation.rs b/tests/foundation.rs index 2afa756..abd4586 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -5,12 +5,13 @@ use forge::app::{AppAction, AppStore, Effect}; use forge::commands::{parse_input, ParsedInput}; use forge::config::ForgeConfig; use forge::domain::{ - AiRequestKind, AppState, ApprovalMode, CommandProvenance, CommandStatus, DashboardTab, - FocusTarget, GitSnapshot, LogEntry, LogSeverity, LogSource, LogStream, ModalState, - ProjectContext, SafetyClass, + AiActionProposal, AiRequestKind, AiResponse, AppState, ApprovalMode, CommandProvenance, + CommandStatus, DashboardTab, FocusTarget, GitSnapshot, LogEntry, LogSeverity, LogSource, + LogStream, ModalState, ProjectContext, SafetyClass, }; use forge::safety::classify_command; -use forge::shared::ids::{CommandId, LogId}; +use forge::shared::ids::{AiRequestId, CommandId, LogId}; +use forge::shared::time::now_utc; #[test] fn parses_background_shell_execution() { @@ -87,6 +88,13 @@ fn parses_supported_slash_commands() { } other => panic!("unexpected parse result: {:?}", other), } + + match parse_input("/apply 2").unwrap() { + ParsedInput::ApplyAiProposal(index) => assert_eq!(index, 2), + other => panic!("unexpected parse result: {:?}", other), + } + + assert!(parse_input("/apply 0").is_err()); } #[test] @@ -214,6 +222,54 @@ fn store_ai_prompt_reports_unavailable_provider() { )); } +#[test] +fn store_apply_ai_proposal_uses_runtime_safety_pipeline() { + let mut store = test_store(); + store.state_mut().ai.last_response = Some(AiResponse { + request_id: AiRequestId(7), + created_at: now_utc(), + provider: "mock".to_string(), + model: Some("test-model".to_string()), + summary: "Suggested a follow-up action".to_string(), + message: "The AI found a command worth reviewing.".to_string(), + recommendations: Vec::new(), + proposals: vec![AiActionProposal { + summary: "Write a temp file".to_string(), + detail: "Capture output in a temp file for later inspection.".to_string(), + command: Some("echo hi > /tmp/forge-test.txt".to_string()), + safety_class: SafetyClass::Passive, + }], + citations: Vec::new(), + }); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::ApplyAiProposal(1))); + + assert!(matches!(effects.as_slice(), [Effect::QueueApproval(_)])); + let command = store + .state() + .commands + .records + .last() + .expect("proposal command record should exist"); + assert_eq!(command.raw, "echo hi > /tmp/forge-test.txt"); + assert!(matches!( + command.provenance, + CommandProvenance::AiSuggestion + )); + assert!(matches!(command.safety_class, SafetyClass::Risky)); + assert!(matches!(command.status, CommandStatus::PendingApproval)); + + let approval = store + .state() + .approvals + .pending + .last() + .expect("proposal approval should be queued"); + assert!(matches!(approval.mode, ApprovalMode::ModalConfirm)); + assert!(approval.detail.contains("AI proposal #1")); + assert!(approval.detail.contains("model hint: Passive")); +} + #[test] fn store_clear_resets_input_and_visible_logs() { let mut store = test_store(); From dde8b5a058561612028c890a10f0baf1bfc060ee Mon Sep 17 00:00:00 2001 From: Bethvour Date: Sun, 19 Apr 2026 20:31:25 -0500 Subject: [PATCH 02/10] Add slash command palette and UI restyle --- src/app/effects.rs | 3 + src/app/store.rs | 70 ++++++++++++++- src/commands/mod.rs | 108 ++++++++++++++++++++++ src/domain/app.rs | 2 + src/runtime/engine.rs | 15 +++- src/ui/theme.rs | 57 +++++++++--- src/ui/views/command_pane.rs | 169 +++++++++++++++++++++++++++-------- src/ui/views/dashboard.rs | 6 +- src/ui/views/event_stream.rs | 4 +- src/ui/views/mod.rs | 7 ++ src/ui/views/modal.rs | 12 ++- src/ui/views/status_bar.rs | 56 ++++++++---- tests/foundation.rs | 18 +++- 13 files changed, 448 insertions(+), 79 deletions(-) diff --git a/src/app/effects.rs b/src/app/effects.rs index 9e884bb..3358da2 100644 --- a/src/app/effects.rs +++ b/src/app/effects.rs @@ -10,6 +10,9 @@ pub enum UiIntent { Backspace, Submit, ClearInput, + PrevCommandSuggestion, + NextCommandSuggestion, + AcceptCommandSuggestion, NextFocus, PrevFocus, NextTab, diff --git a/src/app/store.rs b/src/app/store.rs index d66986b..ccf7e39 100644 --- a/src/app/store.rs +++ b/src/app/store.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use crate::ai; use crate::app::{AppAction, AppEvent, Effect, UiIntent}; -use crate::commands::{parse_input, parse_shell_input, ParsedInput}; +use crate::commands::{parse_input, parse_shell_input, slash_command_suggestions, ParsedInput}; use crate::domain::{ AiActionProposal, AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, ApprovalDecision, ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, @@ -351,12 +351,14 @@ impl AppStore { } } else if matches!(self.state.ui.focus, FocusTarget::CommandPane) { self.state.ui.input_buffer.push(c); + self.sync_command_palette_cursor(); } else if self.state.ui.modal.is_some() { return Vec::new(); } } UiIntent::Backspace => { self.state.ui.input_buffer.pop(); + self.sync_command_palette_cursor(); } UiIntent::Submit => { if let Some(modal) = self.state.ui.modal.as_ref() { @@ -379,6 +381,7 @@ impl AppStore { } let raw = std::mem::take(&mut self.state.ui.input_buffer); + self.state.ui.command_palette_cursor = 0; match parse_input(&raw) { Ok(parsed) => return self.dispatch_action(AppAction::ParsedInput(parsed)), Err(message) => { @@ -389,6 +392,16 @@ impl AppStore { } UiIntent::ClearInput => { self.state.ui.input_buffer.clear(); + self.state.ui.command_palette_cursor = 0; + } + UiIntent::PrevCommandSuggestion => { + self.move_command_palette_cursor(false); + } + UiIntent::NextCommandSuggestion => { + self.move_command_palette_cursor(true); + } + UiIntent::AcceptCommandSuggestion => { + self.accept_command_suggestion(); } UiIntent::NextFocus => { if self.state.ui.modal.is_some() { @@ -461,6 +474,7 @@ impl AppStore { }; } self.state.ui.input_buffer.clear(); + self.state.ui.command_palette_cursor = 0; } } Vec::new() @@ -526,6 +540,60 @@ impl AppStore { } } + fn sync_command_palette_cursor(&mut self) { + let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + if suggestions.is_empty() { + self.state.ui.command_palette_cursor = 0; + return; + } + + if self.state.ui.command_palette_cursor >= suggestions.len() { + self.state.ui.command_palette_cursor = suggestions.len().saturating_sub(1); + } + } + + fn move_command_palette_cursor(&mut self, forward: bool) { + let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + if suggestions.is_empty() { + self.state.ui.command_palette_cursor = 0; + return; + } + + let len = suggestions.len(); + let current = self + .state + .ui + .command_palette_cursor + .min(len.saturating_sub(1)); + self.state.ui.command_palette_cursor = if forward { + (current + 1) % len + } else if current == 0 { + len - 1 + } else { + current - 1 + }; + } + + fn accept_command_suggestion(&mut self) { + let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + if suggestions.is_empty() { + return; + } + + let index = self + .state + .ui + .command_palette_cursor + .min(suggestions.len().saturating_sub(1)); + let suggestion = suggestions[index]; + self.state.ui.input_buffer = suggestion.completion.to_string(); + if !suggestion.accepts_arguments() { + self.state.ui.command_palette_cursor = index; + } else { + self.state.ui.command_palette_cursor = 0; + } + } + fn prepare_ai_request(&mut self, prompt: String, kind: AiRequestKind) -> Vec { if !self.state.ai.enabled { let message = "AI is disabled in the current Forge configuration.".to_string(); diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 8736e04..2f78486 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,6 +1,82 @@ use crate::domain::{AiRequestKind, CommandProvenance}; use crate::shared::ids::CommandId; +#[derive(Debug, Clone, Copy)] +pub struct SlashCommandSpec { + pub usage: &'static str, + pub completion: &'static str, + pub summary: &'static str, +} + +impl SlashCommandSpec { + pub fn accepts_arguments(&self) -> bool { + self.completion.ends_with(' ') + } +} + +const SLASH_COMMANDS: [SlashCommandSpec; 12] = [ + SlashCommandSpec { + usage: "/help", + completion: "/help", + summary: "Open the Forge command reference.", + }, + SlashCommandSpec { + usage: "/ai ", + completion: "/ai ", + summary: "Ask Forge for grounded assistance.", + }, + SlashCommandSpec { + usage: "/diagnose ", + completion: "/diagnose ", + summary: "Request a diagnosis tied to live runtime context.", + }, + SlashCommandSpec { + usage: "/apply ", + completion: "/apply ", + summary: "Run AI proposal n through safety checks.", + }, + SlashCommandSpec { + usage: "/bg ", + completion: "/bg ", + summary: "Queue a background command or long-lived process.", + }, + SlashCommandSpec { + usage: "/cancel ", + completion: "/cancel ", + summary: "Cancel a tracked managed command.", + }, + SlashCommandSpec { + usage: "/approve", + completion: "/approve", + summary: "Approve the current pending action.", + }, + SlashCommandSpec { + usage: "/deny", + completion: "/deny", + summary: "Dismiss the current pending action.", + }, + SlashCommandSpec { + usage: "/tab next", + completion: "/tab next", + summary: "Move the dashboard to the next tab.", + }, + SlashCommandSpec { + usage: "/tab prev", + completion: "/tab prev", + summary: "Move the dashboard to the previous tab.", + }, + SlashCommandSpec { + usage: "/clear", + completion: "/clear", + summary: "Clear the visible input and log buffer.", + }, + SlashCommandSpec { + usage: "/quit", + completion: "/quit", + summary: "Exit Forge cleanly.", + }, +]; + #[derive(Debug, Clone)] pub enum ParsedInput { Execute { @@ -23,6 +99,38 @@ pub enum ParsedInput { ApplyAiProposal(usize), } +pub fn slash_command_catalog() -> &'static [SlashCommandSpec] { + &SLASH_COMMANDS +} + +pub fn slash_command_suggestions(input: &str) -> Vec<&'static SlashCommandSpec> { + let trimmed = input.trim(); + if !trimmed.starts_with('/') { + return Vec::new(); + } + + if trimmed == "/" { + return SLASH_COMMANDS.iter().collect(); + } + + let normalized = trimmed.to_ascii_lowercase(); + SLASH_COMMANDS + .iter() + .filter(|spec| { + spec.usage.to_ascii_lowercase().starts_with(&normalized) + || spec + .completion + .trim_end() + .to_ascii_lowercase() + .starts_with(&normalized) + }) + .collect() +} + +pub fn slash_palette_active(input: &str) -> bool { + input.trim_start().starts_with('/') && !slash_command_suggestions(input).is_empty() +} + pub fn parse_input(input: &str) -> Result { let trimmed = input.trim(); if trimmed.is_empty() { diff --git a/src/domain/app.rs b/src/domain/app.rs index 32a4f0f..d4bfba0 100644 --- a/src/domain/app.rs +++ b/src/domain/app.rs @@ -66,6 +66,7 @@ pub struct UiState { pub focus: FocusTarget, pub dashboard_tab: DashboardTab, pub input_buffer: String, + pub command_palette_cursor: usize, pub modal: Option, pub terminal_size: (u16, u16), pub approval_cursor: usize, @@ -125,6 +126,7 @@ impl AppState { focus: FocusTarget::CommandPane, dashboard_tab: DashboardTab::Services, input_buffer: String::new(), + command_palette_cursor: 0, modal: None, terminal_size: (0, 0), approval_cursor: 0, diff --git a/src/runtime/engine.rs b/src/runtime/engine.rs index 0f9ba5c..5567900 100644 --- a/src/runtime/engine.rs +++ b/src/runtime/engine.rs @@ -7,7 +7,7 @@ use tracing::{error, info}; use crate::ai::AiRuntime; use crate::app::{AppAction, AppEvent, AppStore, Effect, UiIntent}; -use crate::commands::ParsedInput; +use crate::commands::{slash_palette_active, ParsedInput}; use crate::domain::FocusTarget; use crate::observability::ObservabilityHandle; use crate::runtime::RuntimeSupervisor; @@ -149,6 +149,10 @@ fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option Option { Some(AppAction::Ui(UiIntent::ClearInput)) } + KeyCode::Tab if command_palette_active => { + Some(AppAction::Ui(UiIntent::AcceptCommandSuggestion)) + } KeyCode::Tab => Some(AppAction::Ui(UiIntent::NextFocus)), KeyCode::BackTab => Some(AppAction::Ui(UiIntent::PrevFocus)), + KeyCode::Up if command_palette_active => { + Some(AppAction::Ui(UiIntent::PrevCommandSuggestion)) + } + KeyCode::Down if command_palette_active => { + Some(AppAction::Ui(UiIntent::NextCommandSuggestion)) + } KeyCode::Left if key.modifiers.is_empty() && matches!(state.ui.focus, FocusTarget::DashboardPane) diff --git a/src/ui/theme.rs b/src/ui/theme.rs index ee48db8..229da9a 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -2,23 +2,29 @@ use ratatui::style::{Color, Modifier, Style}; use crate::domain::{LogSeverity, NotificationLevel, ServiceHealth, TimelineKind}; -pub const BG_BASE: Color = Color::Rgb(16, 18, 22); -pub const BG_ELEVATED: Color = Color::Rgb(22, 26, 33); -pub const PANEL_BORDER: Color = Color::Rgb(82, 92, 107); -pub const PANEL_FOCUS: Color = Color::Rgb(86, 156, 214); -pub const TEXT_PRIMARY: Color = Color::Rgb(232, 236, 241); -pub const TEXT_MUTED: Color = Color::Rgb(146, 156, 169); -pub const TEXT_SUBTLE: Color = Color::Rgb(103, 112, 124); -pub const ACCENT: Color = Color::Rgb(87, 156, 255); -pub const SUCCESS: Color = Color::Rgb(108, 196, 145); -pub const WARN: Color = Color::Rgb(242, 201, 76); -pub const ERROR: Color = Color::Rgb(235, 111, 146); -pub const INFO: Color = Color::Rgb(86, 182, 194); +pub const BG_BASE: Color = Color::Rgb(14, 16, 18); +pub const BG_ELEVATED: Color = Color::Rgb(22, 25, 27); +pub const BG_PANEL: Color = Color::Rgb(28, 31, 35); +pub const BG_SELECTION: Color = Color::Rgb(63, 47, 24); +pub const PANEL_BORDER: Color = Color::Rgb(104, 95, 79); +pub const PANEL_FOCUS: Color = Color::Rgb(224, 167, 77); +pub const TEXT_PRIMARY: Color = Color::Rgb(240, 234, 223); +pub const TEXT_MUTED: Color = Color::Rgb(176, 166, 148); +pub const TEXT_SUBTLE: Color = Color::Rgb(118, 111, 99); +pub const ACCENT: Color = Color::Rgb(224, 167, 77); +pub const SUCCESS: Color = Color::Rgb(141, 185, 118); +pub const WARN: Color = Color::Rgb(238, 198, 96); +pub const ERROR: Color = Color::Rgb(221, 117, 96); +pub const INFO: Color = Color::Rgb(116, 183, 170); pub fn pane_border(focused: bool) -> Style { Style::default().fg(if focused { PANEL_FOCUS } else { PANEL_BORDER }) } +pub fn panel_surface(focused: bool) -> Style { + Style::default().bg(if focused { BG_PANEL } else { BG_ELEVATED }) +} + pub fn panel_title(focused: bool) -> Style { Style::default() .fg(if focused { PANEL_FOCUS } else { TEXT_MUTED }) @@ -26,7 +32,9 @@ pub fn panel_title(focused: bool) -> Style { } pub fn section_title() -> Style { - Style::default().fg(TEXT_MUTED).add_modifier(Modifier::BOLD) + Style::default() + .fg(ACCENT) + .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } pub fn primary() -> Style { @@ -47,11 +55,32 @@ pub fn accent() -> Style { pub fn status_badge(bg: Color) -> Style { Style::default() - .fg(Color::Black) + .fg(BG_BASE) .bg(bg) .add_modifier(Modifier::BOLD) } +pub fn keycap() -> Style { + Style::default() + .fg(TEXT_PRIMARY) + .bg(BG_PANEL) + .add_modifier(Modifier::BOLD) +} + +pub fn command_palette_item(selected: bool) -> Style { + let mut style = Style::default() + .fg(if selected { TEXT_PRIMARY } else { TEXT_MUTED }) + .bg(if selected { BG_SELECTION } else { BG_ELEVATED }); + if selected { + style = style.add_modifier(Modifier::BOLD); + } + style +} + +pub fn command_palette_summary(selected: bool) -> Style { + Style::default().fg(if selected { TEXT_PRIMARY } else { TEXT_SUBTLE }) +} + pub fn notification_color(level: NotificationLevel) -> Color { match level { NotificationLevel::Info => INFO, diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index 8070187..c9ed7b4 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -4,22 +4,26 @@ use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; use ratatui::Frame; +use crate::commands::{slash_command_suggestions, SlashCommandSpec}; use crate::domain::{AiMessageRole, AiStatus, AppState, ApprovalMode}; use crate::shared::time::format_timestamp; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { let block = Block::default() - .title(Span::styled(" Command / AI ", theme::panel_title(focused))) + .title(Span::styled(" Command Deck ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)); + .style(theme::panel_surface(focused)); let inner = block.inner(area); frame.render_widget(block, area); + let slash_suggestions = slash_command_suggestions(&state.ui.input_buffer); + let input_height = if slash_suggestions.is_empty() { 6 } else { 11 }; + let sections = Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Min(0), Constraint::Length(5)]) + .constraints([Constraint::Min(0), Constraint::Length(input_height)]) .split(inner); let top = Layout::default() @@ -35,16 +39,31 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool .split(top[1]); render_ai_panel(frame, body[0], state); render_history(frame, body[1], state); - render_input(frame, sections[1], state, focused); + render_input(frame, sections[1], state, focused, &slash_suggestions); } -fn render_input(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { - let content_width = area.width.saturating_sub(6) as usize; +fn render_input( + frame: &mut Frame<'_>, + area: Rect, + state: &AppState, + focused: bool, + slash_suggestions: &[&SlashCommandSpec], +) { + let content_width = area.width.saturating_sub(10) as usize; let visible_input = visible_input_text(&state.ui.input_buffer, content_width.max(8)); + let slash_mode = state.ui.input_buffer.trim_start().starts_with('/'); + let mode_label = if slash_mode { "SLASH" } else { "SHELL" }; + let mode_color = if slash_mode { + theme::INFO + } else { + theme::ACCENT + }; - let lines = vec![ + let mut lines = vec![ Line::from(vec![ - Span::styled(" $ ", theme::status_badge(theme::ACCENT)), + Span::styled(format!(" {mode_label} "), theme::status_badge(mode_color)), + Span::raw(" "), + Span::styled(if slash_mode { "forge>" } else { "$" }, theme::accent()), Span::raw(" "), Span::styled(visible_input, theme::primary()), Span::styled( @@ -58,36 +77,104 @@ fn render_input(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bo ]), Line::from(vec![Span::styled( if state.ui.input_buffer.is_empty() { - "Start typing a shell command or use /help for slash commands." + "Type / to open the Forge command palette, or run a shell command directly." + } else if !slash_suggestions.is_empty() { + "Up/Down selects a command. Tab inserts it. Enter runs the current input." + } else if slash_mode { + "No slash command matches the current input." } else { - "Enter runs the command. Tab changes focus. Alt+Left/Right switches dashboard tabs." + "Enter runs the command. / opens the Forge command palette." }, theme::muted(), )]), - Line::from(vec![ - Span::styled("shell ", theme::subtle()), - Span::styled( - state.config.commands.default_shell.clone(), - theme::primary(), - ), - Span::raw(" "), - Span::styled("focus ", theme::subtle()), - Span::styled( - if focused { "command" } else { "other" }, - if focused { - theme::accent() - } else { - theme::muted() - }, - ), - ]), ]; + + if !slash_suggestions.is_empty() { + let selection = state + .ui + .command_palette_cursor + .min(slash_suggestions.len() - 1); + let visible_len = slash_suggestions.len().min(4); + let max_start = slash_suggestions.len().saturating_sub(visible_len); + let visible_start = selection + .saturating_sub(visible_len.saturating_sub(1)) + .min(max_start); + + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "Command Palette", + theme::section_title(), + )])); + for (offset, suggestion) in slash_suggestions + .iter() + .skip(visible_start) + .take(visible_len) + .enumerate() + { + let index = visible_start + offset; + let selected = index == selection; + lines.push(Line::from(vec![ + Span::styled( + if selected { "▶ " } else { " " }, + if selected { + theme::accent() + } else { + theme::subtle() + }, + ), + Span::styled( + format!("{:<18}", suggestion.usage), + theme::command_palette_item(selected), + ), + Span::raw(" "), + Span::styled( + truncate_multiline(suggestion.summary, area.width.saturating_sub(28) as usize), + theme::command_palette_summary(selected), + ), + ])); + } + } + + lines.push(Line::raw("")); + lines.push(Line::from(vec![ + Span::styled("shell ", theme::subtle()), + Span::styled( + state.config.commands.default_shell.clone(), + theme::primary(), + ), + Span::raw(" "), + Span::styled("focus ", theme::subtle()), + Span::styled( + if focused { "command" } else { "other" }, + if focused { + theme::accent() + } else { + theme::muted() + }, + ), + if !slash_suggestions.is_empty() { + Span::raw(" ") + } else { + Span::raw("") + }, + if !slash_suggestions.is_empty() { + Span::styled("Tab", theme::keycap()) + } else { + Span::raw("") + }, + if !slash_suggestions.is_empty() { + Span::styled(" insert", theme::muted()) + } else { + Span::raw("") + }, + ])); frame.render_widget( Paragraph::new(lines).block( Block::default() - .title(Span::styled(" Input ", theme::section_title())) + .title(Span::styled(" Console ", theme::section_title())) .borders(Borders::ALL) - .border_style(theme::pane_border(focused)), + .border_style(theme::pane_border(focused)) + .style(theme::panel_surface(focused)), ), area, ); @@ -116,10 +203,10 @@ fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { ), ])); lines.push(Line::from(vec![ - Span::styled("Enter", theme::accent()), + Span::styled("Enter", theme::keycap()), Span::styled(" approve", theme::muted()), Span::raw(" "), - Span::styled("Esc", theme::accent()), + Span::styled("Esc", theme::keycap()), Span::styled(" deny", theme::muted()), ])); } else { @@ -129,10 +216,10 @@ fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { Span::styled("No inline approvals waiting", theme::muted()), ])); lines.push(Line::from(vec![ - Span::styled("Enter", theme::accent()), + Span::styled("Enter", theme::keycap()), Span::styled(" run command", theme::muted()), Span::raw(" "), - Span::styled("Ctrl+L", theme::accent()), + Span::styled("Ctrl+L", theme::keycap()), Span::styled(" clear input", theme::muted()), ])); } @@ -162,7 +249,11 @@ fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { frame.render_widget( Paragraph::new(lines) - .block(Block::default().title(Span::styled(" Activity ", theme::section_title()))) + .block( + Block::default() + .title(Span::styled(" Signal ", theme::section_title())) + .style(theme::panel_surface(false)), + ) .wrap(Wrap { trim: false }), area, ); @@ -219,7 +310,9 @@ fn render_history(frame: &mut Frame<'_>, area: Rect, state: &AppState) { ])); } - let block = Block::default().title(Span::styled(" Recent Commands ", theme::section_title())); + let block = Block::default() + .title(Span::styled(" Flight Tape ", theme::section_title())) + .style(theme::panel_surface(false)); frame.render_widget( Paragraph::new(lines) .block(block) @@ -403,7 +496,11 @@ fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { frame.render_widget( Paragraph::new(lines) - .block(Block::default().title(Span::styled(" AI Response ", theme::section_title()))) + .block( + Block::default() + .title(Span::styled(" AI Relay ", theme::section_title())) + .style(theme::panel_surface(false)), + ) .wrap(Wrap { trim: false }), area, ); diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index ea7272f..b547395 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -10,10 +10,10 @@ use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { let block = Block::default() - .title(Span::styled(" Dashboard ", theme::panel_title(focused))) + .title(Span::styled(" Ops Surface ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)); + .style(theme::panel_surface(focused)); let inner = block.inner(area); frame.render_widget(block, area); @@ -284,7 +284,7 @@ fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { content.push(tab); } content.push(Span::raw(" ")); - content.push(Span::styled("Left/Right", theme::accent())); + content.push(Span::styled("Left/Right", theme::keycap())); content.push(Span::styled(" switch tabs", theme::muted())); frame.render_widget( diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index 263c414..8caeb53 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -14,10 +14,10 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool Paragraph::new(lines) .block( Block::default() - .title(Span::styled(" Event Stream ", theme::panel_title(focused))) + .title(Span::styled(" Event Tape ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)), + .style(theme::panel_surface(focused)), ) .wrap(Wrap { trim: false }), area, diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index 4fc0ff9..e84fb4c 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -5,11 +5,18 @@ mod modal; mod status_bar; use ratatui::layout::{Constraint, Direction, Layout}; +use ratatui::widgets::Block; use ratatui::Frame; use crate::domain::{AppState, FocusTarget}; +use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, state: &AppState) { + frame.render_widget( + Block::default().style(theme::panel_surface(false)), + frame.area(), + ); + let layout = Layout::default() .direction(Direction::Vertical) .constraints([ diff --git a/src/ui/views/modal.rs b/src/ui/views/modal.rs index 5b3e3e2..aa2f397 100644 --- a/src/ui/views/modal.rs +++ b/src/ui/views/modal.rs @@ -52,7 +52,8 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Block::default() .title("Approval Required") .borders(Borders::ALL) - .border_style(theme::pane_border(true)), + .border_style(theme::pane_border(true)) + .style(theme::panel_surface(true)), ), area, ); @@ -76,10 +77,13 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Line::from("/deny deny the current pending action"), Line::from("/tab next next dashboard tab"), Line::from("/tab prev previous dashboard tab"), + Line::from("/clear clear input and visible logs"), Line::from("/quit exit Forge"), Line::raw(""), Line::from("Keyboard"), Line::from("Tab cycle pane focus"), + Line::from("Tab (with /) insert selected slash command"), + Line::from("Up/Down (with /) move through slash suggestions"), Line::from("Left/Right switch dashboard tabs when dashboard is focused"), Line::from("Enter run input or confirm modal"), Line::from("Esc close modal / deny approval"), @@ -94,7 +98,8 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Block::default() .title("Help") .borders(Borders::ALL) - .border_style(theme::pane_border(true)), + .border_style(theme::pane_border(true)) + .style(theme::panel_surface(true)), ), area, ); @@ -108,7 +113,8 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Block::default() .title("Error") .borders(Borders::ALL) - .border_style(Style::default().fg(theme::ERROR)), + .border_style(Style::default().fg(theme::ERROR)) + .style(theme::panel_surface(true)), ), area, ); diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index 30a9757..d8cb1f5 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -3,6 +3,7 @@ use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Paragraph}; use ratatui::Frame; +use crate::commands::slash_palette_active; use crate::domain::AppState; use crate::ui::theme; @@ -54,12 +55,13 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { frame.render_widget( Block::default() .borders(Borders::BOTTOM) - .border_style(theme::pane_border(false)), + .border_style(theme::pane_border(false)) + .style(theme::panel_surface(false)), area, ); let row1 = Line::from(vec![ - Span::styled(" Forge ", theme::status_badge(theme::ACCENT)), + Span::styled(" FORGE ", theme::status_badge(theme::ACCENT)), Span::raw(" "), badge( "GIT", @@ -160,35 +162,53 @@ fn contextual_hint_line(state: &AppState) -> Line<'static> { ]) } None => match state.ui.focus { - crate::domain::FocusTarget::CommandPane => Line::from(vec![ - Span::styled("Enter", theme::accent()), - Span::styled(" run", theme::muted()), - Span::raw(" "), - Span::styled("Tab", theme::accent()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("/help", theme::accent()), - Span::styled(" commands", theme::muted()), - ]), + crate::domain::FocusTarget::CommandPane => { + if slash_palette_active(&state.ui.input_buffer) { + Line::from(vec![ + Span::styled("↑/↓", theme::keycap()), + Span::styled(" choose", theme::muted()), + Span::raw(" "), + Span::styled("Tab", theme::keycap()), + Span::styled(" insert", theme::muted()), + Span::raw(" "), + Span::styled("Enter", theme::keycap()), + Span::styled(" run", theme::muted()), + ]) + } else { + Line::from(vec![ + Span::styled("/", theme::keycap()), + Span::styled(" palette", theme::muted()), + Span::raw(" "), + Span::styled("Enter", theme::keycap()), + Span::styled(" run", theme::muted()), + Span::raw(" "), + Span::styled("Tab", theme::keycap()), + Span::styled(" next pane", theme::muted()), + Span::raw(" "), + Span::styled("/help", theme::accent()), + Span::styled(" commands", theme::muted()), + ]) + } + } crate::domain::FocusTarget::DashboardPane => Line::from(vec![ - Span::styled("Left/Right", theme::accent()), + Span::styled("Left/Right", theme::keycap()), Span::styled(" switch tabs", theme::muted()), Span::raw(" "), - Span::styled("Tab", theme::accent()), + Span::styled("Tab", theme::keycap()), Span::styled(" next pane", theme::muted()), Span::raw(" "), - Span::styled("F1", theme::accent()), + Span::styled("F1", theme::keycap()), Span::styled(" help", theme::muted()), ]), crate::domain::FocusTarget::EventStream => Line::from(vec![ - Span::styled("Tab", theme::accent()), + Span::styled("Tab", theme::keycap()), Span::styled(" next pane", theme::muted()), Span::raw(" "), - Span::styled("F1", theme::accent()), + Span::styled("F1", theme::keycap()), Span::styled(" help", theme::muted()), ]), crate::domain::FocusTarget::Modal => Line::from(vec![ - Span::styled("Esc", theme::accent()), + Span::styled("Esc", theme::keycap()), Span::styled(" close", theme::muted()), ]), }, diff --git a/tests/foundation.rs b/tests/foundation.rs index abd4586..90adaeb 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use std::time::SystemTime; use forge::app::{AppAction, AppStore, Effect}; -use forge::commands::{parse_input, ParsedInput}; +use forge::commands::{parse_input, slash_command_suggestions, ParsedInput}; use forge::config::ForgeConfig; use forge::domain::{ AiActionProposal, AiRequestKind, AiResponse, AppState, ApprovalMode, CommandProvenance, @@ -95,6 +95,10 @@ fn parses_supported_slash_commands() { } assert!(parse_input("/apply 0").is_err()); + + let suggestions = slash_command_suggestions("/"); + assert!(!suggestions.is_empty()); + assert!(suggestions.iter().any(|command| command.usage == "/help")); } #[test] @@ -270,6 +274,18 @@ fn store_apply_ai_proposal_uses_runtime_safety_pipeline() { assert!(approval.detail.contains("model hint: Passive")); } +#[test] +fn store_accepts_slash_command_suggestion_into_input() { + let mut store = test_store(); + + store.dispatch_action(AppAction::Ui(forge::app::UiIntent::KeyChar('/'))); + store.dispatch_action(AppAction::Ui(forge::app::UiIntent::KeyChar('d'))); + store.dispatch_action(AppAction::Ui(forge::app::UiIntent::AcceptCommandSuggestion)); + + assert_eq!(store.state().ui.input_buffer, "/diagnose "); + assert_eq!(store.state().ui.command_palette_cursor, 0); +} + #[test] fn store_clear_resets_input_and_visible_logs() { let mut store = test_store(); From dd8b80cd9e78a0eef01fee442b174707eefd1b58 Mon Sep 17 00:00:00 2001 From: Bethvour Date: Sun, 19 Apr 2026 20:32:52 -0500 Subject: [PATCH 03/10] Adjust Forge theme colors --- src/ui/theme.rs | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/src/ui/theme.rs b/src/ui/theme.rs index 229da9a..8798b1c 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -2,20 +2,20 @@ use ratatui::style::{Color, Modifier, Style}; use crate::domain::{LogSeverity, NotificationLevel, ServiceHealth, TimelineKind}; -pub const BG_BASE: Color = Color::Rgb(14, 16, 18); -pub const BG_ELEVATED: Color = Color::Rgb(22, 25, 27); -pub const BG_PANEL: Color = Color::Rgb(28, 31, 35); -pub const BG_SELECTION: Color = Color::Rgb(63, 47, 24); -pub const PANEL_BORDER: Color = Color::Rgb(104, 95, 79); -pub const PANEL_FOCUS: Color = Color::Rgb(224, 167, 77); -pub const TEXT_PRIMARY: Color = Color::Rgb(240, 234, 223); -pub const TEXT_MUTED: Color = Color::Rgb(176, 166, 148); -pub const TEXT_SUBTLE: Color = Color::Rgb(118, 111, 99); -pub const ACCENT: Color = Color::Rgb(224, 167, 77); -pub const SUCCESS: Color = Color::Rgb(141, 185, 118); -pub const WARN: Color = Color::Rgb(238, 198, 96); -pub const ERROR: Color = Color::Rgb(221, 117, 96); -pub const INFO: Color = Color::Rgb(116, 183, 170); +pub const BG_BASE: Color = Color::Rgb(10, 15, 23); +pub const BG_ELEVATED: Color = Color::Rgb(17, 24, 34); +pub const BG_PANEL: Color = Color::Rgb(22, 31, 44); +pub const BG_SELECTION: Color = Color::Rgb(24, 56, 64); +pub const PANEL_BORDER: Color = Color::Rgb(69, 88, 108); +pub const PANEL_FOCUS: Color = Color::Rgb(104, 212, 201); +pub const TEXT_PRIMARY: Color = Color::Rgb(232, 238, 245); +pub const TEXT_MUTED: Color = Color::Rgb(164, 179, 193); +pub const TEXT_SUBTLE: Color = Color::Rgb(111, 125, 140); +pub const ACCENT: Color = Color::Rgb(104, 212, 201); +pub const SUCCESS: Color = Color::Rgb(148, 210, 127); +pub const WARN: Color = Color::Rgb(237, 182, 74); +pub const ERROR: Color = Color::Rgb(230, 113, 106); +pub const INFO: Color = Color::Rgb(114, 167, 255); pub fn pane_border(focused: bool) -> Style { Style::default().fg(if focused { PANEL_FOCUS } else { PANEL_BORDER }) @@ -32,9 +32,7 @@ pub fn panel_title(focused: bool) -> Style { } pub fn section_title() -> Style { - Style::default() - .fg(ACCENT) - .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD) } pub fn primary() -> Style { @@ -63,7 +61,7 @@ pub fn status_badge(bg: Color) -> Style { pub fn keycap() -> Style { Style::default() .fg(TEXT_PRIMARY) - .bg(BG_PANEL) + .bg(BG_ELEVATED) .add_modifier(Modifier::BOLD) } From adc2ae292d87ad6415924aa855e32daf8f43acdc Mon Sep 17 00:00:00 2001 From: Bethvour Date: Sun, 19 Apr 2026 23:56:21 -0500 Subject: [PATCH 04/10] Refine Forge UI and add premium terminal design skill --- skills/terminal-ui-premium/SKILL.md | 60 ++ .../references/benchmark-cli-ux.md | 79 ++ src/app/effects.rs | 10 + src/app/store.rs | 154 ++- src/domain/app.rs | 281 +++++- src/domain/mod.rs | 4 +- src/runtime/engine.rs | 65 +- src/ui/theme.rs | 94 +- src/ui/views/command_pane.rs | 885 ++++++++++-------- src/ui/views/dashboard.rs | 200 ++-- src/ui/views/event_stream.rs | 35 +- src/ui/views/mod.rs | 8 +- src/ui/views/modal.rs | 44 +- src/ui/views/status_bar.rs | 287 +++--- tests/foundation.rs | 41 +- 15 files changed, 1589 insertions(+), 658 deletions(-) create mode 100644 skills/terminal-ui-premium/SKILL.md create mode 100644 skills/terminal-ui-premium/references/benchmark-cli-ux.md diff --git a/skills/terminal-ui-premium/SKILL.md b/skills/terminal-ui-premium/SKILL.md new file mode 100644 index 0000000..0d847af --- /dev/null +++ b/skills/terminal-ui-premium/SKILL.md @@ -0,0 +1,60 @@ +--- +name: terminal-ui-premium +description: Design and implement premium terminal-native interfaces for Ratatui or other TUI/CLI products. Use this skill when improving terminal UX, command panes, dashboards, onboarding, keyboard navigation, focus hierarchy, empty states, or visual polish for CLI-native tools. +--- + +This skill guides premium terminal UX work for production-grade CLI and TUI products. + +Use it when the user wants the interface to feel calmer, more native, easier to navigate, and more trustworthy without turning the terminal into a fake GUI. + +## Workflow + +1. Inspect the existing render tree first. + Identify where layout, theme tokens, focus state, and empty states are defined before changing visuals. + +2. Read [references/benchmark-cli-ux.md](references/benchmark-cli-ux.md) when choosing a direction. + It distills patterns from Ghostty, Warp, GitHub CLI, and Lazygit. + +3. Pick one dominant direction and stay consistent. + For Forge, prefer calm operational minimalism: dark surfaces, quiet chrome, explicit focus, strong keyboard discoverability, and compact status language. + +4. Apply hierarchy in this order: + - primary work surface first + - active context second + - navigation affordances third + - chrome last + +5. Keep onboarding progressive. + Empty states should teach one next action, not explain the whole product. + +6. Preserve terminal ergonomics. + Do not depend on color alone, avoid noisy animation, keep labels short, and make all important state readable as plain text. + +## Design Rules + +- Use spacing, contrast, and density before adding more borders. +- Focus should be obvious at a glance. +- A status badge should communicate state in 1 to 2 words. +- Keep one clear input anchor. If input is always available, it should feel pinned and dependable. +- Group command + context + outcome tightly so the user can scan history quickly. +- Prefer contextual shortcut rails over giant help paragraphs. +- Empty views should always answer: what appears here, and what should I do next? +- Accessibility matters in terminals too: stable text, readable contrast, and redundant cues beat flashy redraws. + +## Ratatui Guidance + +- Put palette decisions in `theme.rs`, not inline in views. +- Use fixed-height header bands for identity, mode, and status. +- Use subtle surface changes for nested regions instead of stacking heavy borders everywhere. +- Keep pane titles short and product-like. +- Align tabular content and truncate aggressively to avoid ragged walls of text. +- When adding onboarding hints, keep them tied to the currently focused pane. + +## Delivery Standard + +Ship the visual system and the behavior together: +- updated theme tokens +- improved focus states +- clearer empty states +- tighter navigation hints +- verified compile/test pass diff --git a/skills/terminal-ui-premium/references/benchmark-cli-ux.md b/skills/terminal-ui-premium/references/benchmark-cli-ux.md new file mode 100644 index 0000000..4c24298 --- /dev/null +++ b/skills/terminal-ui-premium/references/benchmark-cli-ux.md @@ -0,0 +1,79 @@ +# Premium CLI/TUI Benchmarks + +These notes are distilled from official product docs and repos. Re-read the linked sources when making larger design calls. + +## Ghostty + +Sources: +- https://ghostty.org/docs/about +- https://ghostty.org/docs/features +- https://ghostty.org/docs/config/keybind/reference + +What to borrow: +- Native feel over decorative chrome. Ghostty explicitly aims to look, feel, and behave like a purpose-built native app on each platform. +- Fast + feature-rich + native is the standard, not a tradeoff. +- Platform conventions matter. Familiar shortcuts and window behaviors reduce learning cost. +- Useful secondary surfaces such as quick terminal, tabs, splits, and command palette should feel immediate, not bulky. + +Implication for Forge: +- The UI should feel operational and settled by default. +- Focus states, keyboard hints, and pane titles should feel native and unsurprising. +- Styling should support the workflow, not advertise itself. + +## Warp + +Sources: +- https://docs.warp.dev/terminal/blocks +- https://docs.warp.dev/terminal/appearance/input-position + +What to borrow: +- Commands and output are easier to scan when treated as a single unit. +- A pinned input anchor reduces disorientation. +- Navigation improves when the UI makes history feel structured instead of like an endless text dump. +- Input position and command palette are discoverable, not hidden power-user features. + +Implication for Forge: +- Keep the command pane visually anchored. +- Tie recent command, AI state, and approvals closely to the current editor context. +- Make slash actions feel like a real palette, not a loose autocomplete list. + +## GitHub CLI + +Sources: +- https://cli.github.com/manual/gh_help_formatting +- https://github.blog/engineering/user-experience/building-a-more-accessible-github-cli/ + +What to borrow: +- Text output can still feel polished when alignment, truncation, hyperlinks, and relative time are handled deliberately. +- Accessibility in terminals requires stable text, high contrast, and structure that assistive tech can infer from plain text. +- Avoid relying on redraw-heavy spinners when contextual status text can do the job better. +- Color should be customizable and should never be the only carrier of meaning. + +Implication for Forge: +- Use labels plus color for states like dirty, queued, failed, and approved. +- Prefer static textual status summaries over ornamental motion. +- Keep tables, badges, and event lines readable in plain text. + +## Lazygit + +Source: +- https://github.com/jesseduffield/lazygit + +What to borrow: +- Terminal tools feel premium when they collapse painful workflows into obvious, keyboard-first actions. +- Dense UIs can still feel approachable when every pane has a clear purpose and the next action is obvious. +- Filtering, contextual actions, compare flows, undo, and history all increase trust because the user stays in control. + +Implication for Forge: +- Every pane should make the next move legible. +- Empty states should point to one concrete action. +- Dense operational data is fine if hierarchy stays crisp. + +## Shared Principles + +- Calm default state, strong active state. +- One dominant work surface, not five competing ones. +- Progressive disclosure: teach only the next action. +- Keyboard hints belong near the place they matter. +- Dense information is acceptable when structure is explicit. +- Premium terminal UX is mostly restraint, clarity, and confidence. diff --git a/src/app/effects.rs b/src/app/effects.rs index 3358da2..6edfea8 100644 --- a/src/app/effects.rs +++ b/src/app/effects.rs @@ -9,7 +9,17 @@ pub enum UiIntent { KeyChar(char), Backspace, Submit, + InsertNewline, ClearInput, + MoveCursorLeft, + MoveCursorRight, + MoveCursorUp, + MoveCursorDown, + MoveCursorHome, + MoveCursorEnd, + RecallPreviousHistory, + RecallNextHistory, + CycleInputMode, PrevCommandSuggestion, NextCommandSuggestion, AcceptCommandSuggestion, diff --git a/src/app/store.rs b/src/app/store.rs index ccf7e39..66df6fc 100644 --- a/src/app/store.rs +++ b/src/app/store.rs @@ -6,9 +6,9 @@ use crate::commands::{parse_input, parse_shell_input, slash_command_suggestions, use crate::domain::{ AiActionProposal, AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, ApprovalDecision, ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, - DiagnosticLevel, DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, JobRecord, - JobStatus, ModalState, Notification, NotificationLevel, ProcessSnapshot, ProcessStatus, - ServiceHealth, ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, + DiagnosticLevel, DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, InputMode, + JobRecord, JobStatus, ModalState, Notification, NotificationLevel, ProcessSnapshot, + ProcessStatus, ServiceHealth, ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, }; use crate::safety::{approval_message, approval_mode_for, classify_command}; use crate::shared::ids::{ApprovalId, CommandId, IdGenerator}; @@ -350,16 +350,24 @@ impl AppStore { _ => return Vec::new(), } } else if matches!(self.state.ui.focus, FocusTarget::CommandPane) { - self.state.ui.input_buffer.push(c); + self.state.ui.input.insert_char(c); self.sync_command_palette_cursor(); } else if self.state.ui.modal.is_some() { return Vec::new(); } } UiIntent::Backspace => { - self.state.ui.input_buffer.pop(); + self.state.ui.input.backspace(); self.sync_command_palette_cursor(); } + UiIntent::InsertNewline => { + if matches!(self.state.ui.focus, FocusTarget::CommandPane) + && self.state.ui.modal.is_none() + { + self.state.ui.input.insert_newline(); + self.sync_command_palette_cursor(); + } + } UiIntent::Submit => { if let Some(modal) = self.state.ui.modal.as_ref() { return match modal { @@ -373,16 +381,26 @@ impl AppStore { }; } - if self.state.ui.input_buffer.trim().is_empty() { + if self.state.ui.input.is_empty_trimmed() { if let Some(approval_id) = self.current_inline_approval_id() { return self.dispatch_action(AppAction::Approve(approval_id)); } return Vec::new(); } - let raw = std::mem::take(&mut self.state.ui.input_buffer); + let raw = self.state.ui.input.take_buffer(); self.state.ui.command_palette_cursor = 0; - match parse_input(&raw) { + let parsed = if raw.trim_start().starts_with('/') { + parse_input(&raw) + } else if let Some(kind) = self.state.ui.input.mode.ai_kind() { + Ok(ParsedInput::AiPrompt { + prompt: raw.trim().to_string(), + kind, + }) + } else { + parse_input(&raw) + }; + match parsed { Ok(parsed) => return self.dispatch_action(AppAction::ParsedInput(parsed)), Err(message) => { self.push_notification(NotificationLevel::Warn, message.clone()); @@ -391,9 +409,51 @@ impl AppStore { } } UiIntent::ClearInput => { - self.state.ui.input_buffer.clear(); + self.state.ui.input.clear(); self.state.ui.command_palette_cursor = 0; } + UiIntent::MoveCursorLeft => { + self.state.ui.input.move_left(); + self.sync_command_palette_cursor(); + } + UiIntent::MoveCursorRight => { + self.state.ui.input.move_right(); + self.sync_command_palette_cursor(); + } + UiIntent::MoveCursorUp => { + self.state.ui.input.move_up(); + self.sync_command_palette_cursor(); + } + UiIntent::MoveCursorDown => { + self.state.ui.input.move_down(); + self.sync_command_palette_cursor(); + } + UiIntent::MoveCursorHome => { + self.state.ui.input.move_home(); + self.sync_command_palette_cursor(); + } + UiIntent::MoveCursorEnd => { + self.state.ui.input.move_end(); + self.sync_command_palette_cursor(); + } + UiIntent::RecallPreviousHistory => { + self.recall_history(true); + self.sync_command_palette_cursor(); + } + UiIntent::RecallNextHistory => { + self.recall_history(false); + self.sync_command_palette_cursor(); + } + UiIntent::CycleInputMode => { + self.state.ui.input.cycle_mode(); + self.push_notification( + NotificationLevel::Info, + format!( + "input mode: {}", + self.state.ui.input.mode.label().to_ascii_lowercase() + ), + ); + } UiIntent::PrevCommandSuggestion => { self.move_command_palette_cursor(false); } @@ -473,7 +533,7 @@ impl AppStore { None => Vec::new(), }; } - self.state.ui.input_buffer.clear(); + self.state.ui.input.clear(); self.state.ui.command_palette_cursor = 0; } } @@ -489,7 +549,7 @@ impl AppStore { } => self.prepare_execution(command, background, provenance), ParsedInput::Quit => self.dispatch_action(AppAction::Ui(UiIntent::Quit)), ParsedInput::Clear => { - self.state.ui.input_buffer.clear(); + self.state.ui.input.clear(); self.state.logs.recent.clear(); self.state.logs.per_source.clear(); self.append_timeline( @@ -541,7 +601,7 @@ impl AppStore { } fn sync_command_palette_cursor(&mut self) { - let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); if suggestions.is_empty() { self.state.ui.command_palette_cursor = 0; return; @@ -553,7 +613,7 @@ impl AppStore { } fn move_command_palette_cursor(&mut self, forward: bool) { - let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); if suggestions.is_empty() { self.state.ui.command_palette_cursor = 0; return; @@ -575,7 +635,7 @@ impl AppStore { } fn accept_command_suggestion(&mut self) { - let suggestions = slash_command_suggestions(&self.state.ui.input_buffer); + let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); if suggestions.is_empty() { return; } @@ -586,7 +646,10 @@ impl AppStore { .command_palette_cursor .min(suggestions.len().saturating_sub(1)); let suggestion = suggestions[index]; - self.state.ui.input_buffer = suggestion.completion.to_string(); + self.state + .ui + .input + .set_buffer(suggestion.completion.to_string()); if !suggestion.accepts_arguments() { self.state.ui.command_palette_cursor = index; } else { @@ -594,6 +657,67 @@ impl AppStore { } } + fn recall_history(&mut self, previous: bool) { + let entries = self.history_entries_for_mode(); + if entries.is_empty() { + return; + } + + let editor = &mut self.state.ui.input; + if previous { + let next_index = match editor.history_cursor { + Some(index) if index > 0 => index - 1, + Some(index) => index, + None => { + editor.history_draft = Some(editor.buffer.clone()); + entries.len().saturating_sub(1) + } + }; + editor.history_cursor = Some(next_index); + editor.set_buffer(entries[next_index].clone()); + editor.history_cursor = Some(next_index); + return; + } + + let Some(current_index) = editor.history_cursor else { + return; + }; + + if current_index + 1 < entries.len() { + let next_index = current_index + 1; + editor.history_cursor = Some(next_index); + editor.set_buffer(entries[next_index].clone()); + editor.history_cursor = Some(next_index); + return; + } + + let draft = editor.history_draft.take().unwrap_or_default(); + editor.set_buffer(draft); + editor.history_cursor = None; + } + + fn history_entries_for_mode(&self) -> Vec { + match self.state.ui.input.mode { + InputMode::Shell => self.state.commands.history.clone(), + InputMode::AiAssist => self + .state + .ai + .requests + .iter() + .filter(|request| matches!(request.kind, AiRequestKind::Assist)) + .map(|request| request.prompt.clone()) + .collect(), + InputMode::AiDiagnose => self + .state + .ai + .requests + .iter() + .filter(|request| matches!(request.kind, AiRequestKind::Diagnose)) + .map(|request| request.prompt.clone()) + .collect(), + } + } + fn prepare_ai_request(&mut self, prompt: String, kind: AiRequestKind) -> Vec { if !self.state.ai.enabled { let message = "AI is disabled in the current Forge configuration.".to_string(); diff --git a/src/domain/app.rs b/src/domain/app.rs index d4bfba0..290ad40 100644 --- a/src/domain/app.rs +++ b/src/domain/app.rs @@ -2,8 +2,8 @@ use std::time::SystemTime; use crate::config::ForgeConfig; use crate::domain::{ - AiSessionState, ApprovalState, CommandState, DiagnosticsState, GitSnapshot, JobState, LogState, - ProcessState, ProjectContext, ServiceState, TestState, TimelineState, + AiRequestKind, AiSessionState, ApprovalState, CommandState, DiagnosticsState, GitSnapshot, + JobState, LogState, ProcessState, ProjectContext, ServiceState, TestState, TimelineState, }; use crate::shared::ids::{ApprovalId, NotificationId}; use crate::shared::time::now_utc; @@ -61,11 +61,196 @@ pub enum ModalState { Error(String), } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InputMode { + Shell, + AiAssist, + AiDiagnose, +} + +impl InputMode { + pub fn label(&self) -> &'static str { + match self { + Self::Shell => "SHELL", + Self::AiAssist => "AI", + Self::AiDiagnose => "DIAG", + } + } + + pub fn prompt_label(&self) -> &'static str { + match self { + Self::Shell => "$", + Self::AiAssist => "assist>", + Self::AiDiagnose => "diagnose>", + } + } + + pub fn next(self) -> Self { + match self { + Self::Shell => Self::AiAssist, + Self::AiAssist => Self::AiDiagnose, + Self::AiDiagnose => Self::Shell, + } + } + + pub fn ai_kind(self) -> Option { + match self { + Self::Shell => None, + Self::AiAssist => Some(AiRequestKind::Assist), + Self::AiDiagnose => Some(AiRequestKind::Diagnose), + } + } +} + +#[derive(Debug, Clone)] +pub struct InputEditorState { + pub mode: InputMode, + pub buffer: String, + pub cursor: usize, + pub history_cursor: Option, + pub history_draft: Option, + preferred_column: Option, +} + +impl Default for InputEditorState { + fn default() -> Self { + Self { + mode: InputMode::Shell, + buffer: String::new(), + cursor: 0, + history_cursor: None, + history_draft: None, + preferred_column: None, + } + } +} + +impl InputEditorState { + pub fn is_empty_trimmed(&self) -> bool { + self.buffer.trim().is_empty() + } + + pub fn clear(&mut self) { + self.buffer.clear(); + self.cursor = 0; + self.reset_history_navigation(); + } + + pub fn take_buffer(&mut self) -> String { + let raw = std::mem::take(&mut self.buffer); + self.cursor = 0; + self.reset_history_navigation(); + raw + } + + pub fn set_buffer(&mut self, buffer: String) { + self.buffer = buffer; + self.cursor = self.buffer.len(); + self.preferred_column = None; + } + + pub fn set_mode(&mut self, mode: InputMode) { + self.mode = mode; + self.reset_history_navigation(); + } + + pub fn cycle_mode(&mut self) { + self.mode = self.mode.next(); + self.reset_history_navigation(); + } + + pub fn insert_char(&mut self, c: char) { + self.buffer.insert(self.cursor, c); + self.cursor += c.len_utf8(); + self.reset_history_navigation(); + } + + pub fn insert_newline(&mut self) { + self.buffer.insert(self.cursor, '\n'); + self.cursor += 1; + self.reset_history_navigation(); + } + + pub fn backspace(&mut self) { + if let Some(previous) = prev_char_boundary(&self.buffer, self.cursor) { + self.buffer.drain(previous..self.cursor); + self.cursor = previous; + self.reset_history_navigation(); + } + } + + pub fn move_left(&mut self) { + if let Some(previous) = prev_char_boundary(&self.buffer, self.cursor) { + self.cursor = previous; + self.preferred_column = None; + } + } + + pub fn move_right(&mut self) { + if let Some(next) = next_char_boundary(&self.buffer, self.cursor) { + self.cursor = next; + self.preferred_column = None; + } + } + + pub fn move_home(&mut self) { + self.cursor = line_start(&self.buffer, self.cursor); + self.preferred_column = None; + } + + pub fn move_end(&mut self) { + self.cursor = line_end(&self.buffer, self.cursor); + self.preferred_column = None; + } + + pub fn move_up(&mut self) { + let current_start = line_start(&self.buffer, self.cursor); + if current_start == 0 { + self.cursor = 0; + return; + } + + let target_column = self + .preferred_column + .unwrap_or_else(|| display_column(&self.buffer, self.cursor)); + let previous_end = current_start.saturating_sub(1); + let previous_start = line_start(&self.buffer, previous_end); + self.cursor = column_to_offset(&self.buffer, previous_start, previous_end, target_column); + self.preferred_column = Some(target_column); + } + + pub fn move_down(&mut self) { + let current_end = line_end(&self.buffer, self.cursor); + if current_end >= self.buffer.len() { + self.cursor = self.buffer.len(); + return; + } + + let target_column = self + .preferred_column + .unwrap_or_else(|| display_column(&self.buffer, self.cursor)); + let next_start = current_end + 1; + let next_end = line_end(&self.buffer, next_start); + self.cursor = column_to_offset(&self.buffer, next_start, next_end, target_column); + self.preferred_column = Some(target_column); + } + + pub fn line_count(&self) -> usize { + self.buffer.lines().count().max(1) + } + + fn reset_history_navigation(&mut self) { + self.history_cursor = None; + self.history_draft = None; + self.preferred_column = None; + } +} + #[derive(Debug, Clone)] pub struct UiState { pub focus: FocusTarget, pub dashboard_tab: DashboardTab, - pub input_buffer: String, + pub input: InputEditorState, pub command_palette_cursor: usize, pub modal: Option, pub terminal_size: (u16, u16), @@ -125,7 +310,7 @@ impl AppState { ui: UiState { focus: FocusTarget::CommandPane, dashboard_tab: DashboardTab::Services, - input_buffer: String::new(), + input: InputEditorState::default(), command_palette_cursor: 0, modal: None, terminal_size: (0, 0), @@ -152,3 +337,91 @@ impl AppState { } } } + +fn prev_char_boundary(value: &str, cursor: usize) -> Option { + if cursor == 0 { + return None; + } + + let mut previous = 0; + for (index, _) in value.char_indices() { + if index >= cursor { + break; + } + previous = index; + } + Some(previous) +} + +fn next_char_boundary(value: &str, cursor: usize) -> Option { + if cursor >= value.len() { + return None; + } + + for (index, ch) in value[cursor..].char_indices() { + if index == 0 { + return Some(cursor + ch.len_utf8()); + } + } + None +} + +fn line_start(value: &str, cursor: usize) -> usize { + value[..cursor] + .rfind('\n') + .map(|index| index + 1) + .unwrap_or(0) +} + +fn line_end(value: &str, cursor: usize) -> usize { + value[cursor..] + .find('\n') + .map(|index| cursor + index) + .unwrap_or(value.len()) +} + +fn display_column(value: &str, cursor: usize) -> usize { + value[line_start(value, cursor)..cursor].chars().count() +} + +fn column_to_offset(value: &str, line_start: usize, line_end: usize, column: usize) -> usize { + let line = &value[line_start..line_end]; + let mut offset = line_start; + for (chars, ch) in line.chars().enumerate() { + if chars >= column { + break; + } + offset += ch.len_utf8(); + } + offset +} + +#[cfg(test)] +mod tests { + use super::{InputEditorState, InputMode}; + + #[test] + fn input_editor_moves_between_lines() { + let mut editor = InputEditorState::default(); + editor.set_buffer("alpha\nbeta".to_string()); + editor.cursor = editor.buffer.len(); + + editor.move_up(); + assert_eq!(editor.buffer[..editor.cursor].chars().count(), 4); + + editor.move_home(); + assert_eq!(editor.cursor, 0); + } + + #[test] + fn input_mode_cycles_across_shell_and_ai_modes() { + let mut editor = InputEditorState::default(); + assert!(matches!(editor.mode, InputMode::Shell)); + editor.cycle_mode(); + assert!(matches!(editor.mode, InputMode::AiAssist)); + editor.cycle_mode(); + assert!(matches!(editor.mode, InputMode::AiDiagnose)); + editor.cycle_mode(); + assert!(matches!(editor.mode, InputMode::Shell)); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 1925e49..101c73a 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -18,8 +18,8 @@ pub use ai::{ AiServiceContext, AiSessionState, AiStatus, AiTestContext, AiTimelineContext, AiUiContext, }; pub use app::{ - AppMetaState, AppState, DashboardTab, FocusTarget, ModalState, Notification, NotificationLevel, - NotificationState, UiState, + AppMetaState, AppState, DashboardTab, FocusTarget, InputEditorState, InputMode, ModalState, + Notification, NotificationLevel, NotificationState, UiState, }; pub use approval::{ApprovalDecision, ApprovalMode, ApprovalRequest, ApprovalState, SafetyClass}; pub use command::{ diff --git a/src/runtime/engine.rs b/src/runtime/engine.rs index 5567900..56f7175 100644 --- a/src/runtime/engine.rs +++ b/src/runtime/engine.rs @@ -151,7 +151,7 @@ fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option Option { Some(AppAction::Ui(UiIntent::ClearInput)) } + KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => { + Some(AppAction::Ui(UiIntent::InsertNewline)) + } + KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => { + Some(AppAction::Ui(UiIntent::RecallPreviousHistory)) + } + KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => { + Some(AppAction::Ui(UiIntent::RecallNextHistory)) + } KeyCode::Tab if command_palette_active => { Some(AppAction::Ui(UiIntent::AcceptCommandSuggestion)) } @@ -172,9 +181,51 @@ fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option { Some(AppAction::Ui(UiIntent::PrevCommandSuggestion)) } + KeyCode::Up + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorUp)) + } KeyCode::Down if command_palette_active => { Some(AppAction::Ui(UiIntent::NextCommandSuggestion)) } + KeyCode::Down + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorDown)) + } + KeyCode::Left + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorLeft)) + } + KeyCode::Right + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorRight)) + } + KeyCode::Home + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorHome)) + } + KeyCode::End + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::MoveCursorEnd)) + } KeyCode::Left if key.modifiers.is_empty() && matches!(state.ui.focus, FocusTarget::DashboardPane) @@ -195,6 +246,18 @@ fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option { Some(AppAction::Ui(UiIntent::NextTab)) } + KeyCode::F(2) + if matches!(state.ui.focus, FocusTarget::CommandPane) && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::CycleInputMode)) + } + KeyCode::Enter + if key.modifiers.contains(KeyModifiers::SHIFT) + && matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::InsertNewline)) + } KeyCode::Enter => Some(AppAction::Ui(UiIntent::Submit)), KeyCode::Backspace => Some(AppAction::Ui(UiIntent::Backspace)), KeyCode::Esc => Some(AppAction::Ui(UiIntent::Esc)), diff --git a/src/ui/theme.rs b/src/ui/theme.rs index 8798b1c..c6cbf05 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -2,32 +2,47 @@ use ratatui::style::{Color, Modifier, Style}; use crate::domain::{LogSeverity, NotificationLevel, ServiceHealth, TimelineKind}; -pub const BG_BASE: Color = Color::Rgb(10, 15, 23); -pub const BG_ELEVATED: Color = Color::Rgb(17, 24, 34); -pub const BG_PANEL: Color = Color::Rgb(22, 31, 44); -pub const BG_SELECTION: Color = Color::Rgb(24, 56, 64); -pub const PANEL_BORDER: Color = Color::Rgb(69, 88, 108); -pub const PANEL_FOCUS: Color = Color::Rgb(104, 212, 201); -pub const TEXT_PRIMARY: Color = Color::Rgb(232, 238, 245); -pub const TEXT_MUTED: Color = Color::Rgb(164, 179, 193); -pub const TEXT_SUBTLE: Color = Color::Rgb(111, 125, 140); -pub const ACCENT: Color = Color::Rgb(104, 212, 201); -pub const SUCCESS: Color = Color::Rgb(148, 210, 127); -pub const WARN: Color = Color::Rgb(237, 182, 74); -pub const ERROR: Color = Color::Rgb(230, 113, 106); -pub const INFO: Color = Color::Rgb(114, 167, 255); +pub const BG_BASE: Color = Color::Rgb(7, 11, 17); +pub const BG_ELEVATED: Color = Color::Rgb(12, 17, 25); +pub const BG_PANEL: Color = Color::Rgb(16, 22, 32); +pub const BG_PANEL_FOCUS: Color = Color::Rgb(20, 27, 39); +pub const BG_CHROME: Color = Color::Rgb(24, 31, 44); +pub const BG_SELECTION: Color = Color::Rgb(30, 44, 58); +pub const PANEL_BORDER: Color = Color::Rgb(60, 73, 91); +pub const PANEL_BORDER_SUBTLE: Color = Color::Rgb(40, 50, 64); +pub const PANEL_FOCUS: Color = Color::Rgb(122, 220, 198); +pub const TEXT_PRIMARY: Color = Color::Rgb(236, 240, 244); +pub const TEXT_MUTED: Color = Color::Rgb(170, 181, 193); +pub const TEXT_SUBTLE: Color = Color::Rgb(108, 121, 137); +pub const ACCENT: Color = Color::Rgb(122, 220, 198); +pub const SUCCESS: Color = Color::Rgb(150, 216, 138); +pub const WARN: Color = Color::Rgb(236, 190, 90); +pub const ERROR: Color = Color::Rgb(229, 113, 98); +pub const INFO: Color = Color::Rgb(119, 167, 255); + +pub fn app_surface() -> Style { + Style::default().bg(BG_BASE) +} + +pub fn chrome_surface() -> Style { + Style::default().bg(BG_ELEVATED) +} pub fn pane_border(focused: bool) -> Style { - Style::default().fg(if focused { PANEL_FOCUS } else { PANEL_BORDER }) + Style::default().fg(if focused { + PANEL_FOCUS + } else { + PANEL_BORDER_SUBTLE + }) } pub fn panel_surface(focused: bool) -> Style { - Style::default().bg(if focused { BG_PANEL } else { BG_ELEVATED }) + Style::default().bg(if focused { BG_PANEL_FOCUS } else { BG_PANEL }) } pub fn panel_title(focused: bool) -> Style { Style::default() - .fg(if focused { PANEL_FOCUS } else { TEXT_MUTED }) + .fg(if focused { TEXT_PRIMARY } else { TEXT_MUTED }) .add_modifier(Modifier::BOLD) } @@ -35,10 +50,22 @@ pub fn section_title() -> Style { Style::default().fg(ACCENT).add_modifier(Modifier::BOLD) } +pub fn label() -> Style { + Style::default() + .fg(TEXT_SUBTLE) + .add_modifier(Modifier::BOLD) +} + pub fn primary() -> Style { Style::default().fg(TEXT_PRIMARY) } +pub fn primary_emphasis() -> Style { + Style::default() + .fg(TEXT_PRIMARY) + .add_modifier(Modifier::BOLD) +} + pub fn muted() -> Style { Style::default().fg(TEXT_MUTED) } @@ -51,24 +78,45 @@ pub fn accent() -> Style { Style::default().fg(ACCENT).add_modifier(Modifier::BOLD) } +pub fn warn_accent() -> Style { + Style::default().fg(WARN).add_modifier(Modifier::BOLD) +} + +pub fn error_accent() -> Style { + Style::default().fg(ERROR).add_modifier(Modifier::BOLD) +} + +pub fn brand_badge() -> Style { + pill(BG_BASE, ACCENT) +} + pub fn status_badge(bg: Color) -> Style { - Style::default() - .fg(BG_BASE) - .bg(bg) - .add_modifier(Modifier::BOLD) + pill(BG_BASE, bg) +} + +pub fn quiet_badge() -> Style { + pill(TEXT_MUTED, BG_CHROME) +} + +pub fn focus_badge() -> Style { + pill(PANEL_FOCUS, BG_CHROME) +} + +pub fn pill(fg: Color, bg: Color) -> Style { + Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD) } pub fn keycap() -> Style { Style::default() .fg(TEXT_PRIMARY) - .bg(BG_ELEVATED) + .bg(BG_CHROME) .add_modifier(Modifier::BOLD) } pub fn command_palette_item(selected: bool) -> Style { let mut style = Style::default() .fg(if selected { TEXT_PRIMARY } else { TEXT_MUTED }) - .bg(if selected { BG_SELECTION } else { BG_ELEVATED }); + .bg(if selected { BG_SELECTION } else { BG_PANEL }); if selected { style = style.add_modifier(Modifier::BOLD); } diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index c9ed7b4..8c0d7c7 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -1,11 +1,11 @@ use ratatui::layout::Rect; use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; use crate::commands::{slash_command_suggestions, SlashCommandSpec}; -use crate::domain::{AiMessageRole, AiStatus, AppState, ApprovalMode}; +use crate::domain::{AiStatus, AppState, ApprovalMode, CommandProvenance, CommandStatus}; use crate::shared::time::format_timestamp; use crate::ui::theme; @@ -14,315 +14,230 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool .title(Span::styled(" Command Deck ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)); + .style(theme::panel_surface(focused)) + .padding(Padding::horizontal(1)); let inner = block.inner(area); frame.render_widget(block, area); - let slash_suggestions = slash_command_suggestions(&state.ui.input_buffer); - let input_height = if slash_suggestions.is_empty() { 6 } else { 11 }; + let slash_suggestions = slash_command_suggestions(&state.ui.input.buffer); + let context_lines = build_context_lines(state, inner.width.saturating_sub(4) as usize); + let context_height = context_lines.len().clamp(2, 5) as u16; let sections = Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Min(0), Constraint::Length(input_height)]) + .constraints([Constraint::Length(context_height), Constraint::Min(0)]) .split(inner); - let top = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(4), Constraint::Min(0)]) - .split(sections[0]); + render_context_strip(frame, sections[0], context_lines); + render_console(frame, sections[1], state, &slash_suggestions); +} - render_activity(frame, top[0], state); - let history_height = (state.config.ui.history_preview as u16).clamp(4, 8); - let body = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Min(8), Constraint::Length(history_height)]) - .split(top[1]); - render_ai_panel(frame, body[0], state); - render_history(frame, body[1], state); - render_input(frame, sections[1], state, focused, &slash_suggestions); +fn render_context_strip(frame: &mut Frame<'_>, area: Rect, lines: Vec>) { + frame.render_widget( + Paragraph::new(lines) + .block( + Block::default() + .borders(Borders::BOTTOM) + .border_style(theme::pane_border(false)) + .style(theme::chrome_surface()), + ) + .wrap(Wrap { trim: false }), + area, + ); } -fn render_input( +fn render_console( frame: &mut Frame<'_>, area: Rect, state: &AppState, - focused: bool, slash_suggestions: &[&SlashCommandSpec], ) { - let content_width = area.width.saturating_sub(10) as usize; - let visible_input = visible_input_text(&state.ui.input_buffer, content_width.max(8)); - let slash_mode = state.ui.input_buffer.trim_start().starts_with('/'); - let mode_label = if slash_mode { "SLASH" } else { "SHELL" }; - let mode_color = if slash_mode { + let mode = state.ui.input.mode; + let slash_mode = state.ui.input.buffer.trim_start().starts_with('/'); + let mode_label: &'static str = if slash_mode { "SLASH" } else { mode.label() }; + let mode_color = if slash_mode || mode.ai_kind().is_some() { theme::INFO } else { theme::ACCENT }; + let visible_suggestions = visible_command_suggestions(slash_suggestions, state); + let suggestion_rows = if visible_suggestions.is_empty() { + 0 + } else { + 2 + visible_suggestions.len() as u16 + }; + let sections = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(2), + Constraint::Min(3), + Constraint::Length(suggestion_rows), + Constraint::Length(1), + ]) + .split(area); - let mut lines = vec![ - Line::from(vec![ - Span::styled(format!(" {mode_label} "), theme::status_badge(mode_color)), - Span::raw(" "), - Span::styled(if slash_mode { "forge>" } else { "$" }, theme::accent()), - Span::raw(" "), - Span::styled(visible_input, theme::primary()), - Span::styled( - if focused { "█" } else { " " }, - if focused { - theme::accent() - } else { - theme::subtle() - }, - ), - ]), - Line::from(vec![Span::styled( - if state.ui.input_buffer.is_empty() { - "Type / to open the Forge command palette, or run a shell command directly." - } else if !slash_suggestions.is_empty() { - "Up/Down selects a command. Tab inserts it. Enter runs the current input." - } else if slash_mode { - "No slash command matches the current input." - } else { - "Enter runs the command. / opens the Forge command palette." - }, - theme::muted(), - )]), - ]; + let editor_width = sections[1].width.saturating_sub(12) as usize; + let editor_lines = visible_editor_lines( + &state.ui.input.buffer, + state.ui.input.cursor, + editor_width.max(12), + sections[1].height.max(1) as usize, + editor_gutter_label(mode_label), + editor_prompt_symbol(mode, slash_mode), + ); - if !slash_suggestions.is_empty() { - let selection = state - .ui - .command_palette_cursor - .min(slash_suggestions.len() - 1); - let visible_len = slash_suggestions.len().min(4); - let max_start = slash_suggestions.len().saturating_sub(visible_len); - let visible_start = selection - .saturating_sub(visible_len.saturating_sub(1)) - .min(max_start); - - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - "Command Palette", - theme::section_title(), - )])); - for (offset, suggestion) in slash_suggestions - .iter() - .skip(visible_start) - .take(visible_len) - .enumerate() - { - let index = visible_start + offset; - let selected = index == selection; - lines.push(Line::from(vec![ - Span::styled( - if selected { "▶ " } else { " " }, - if selected { - theme::accent() - } else { - theme::subtle() - }, - ), - Span::styled( - format!("{:<18}", suggestion.usage), - theme::command_palette_item(selected), - ), - Span::raw(" "), - Span::styled( - truncate_multiline(suggestion.summary, area.width.saturating_sub(28) as usize), - theme::command_palette_summary(selected), - ), - ])); - } + frame.render_widget( + Paragraph::new(editor_header_lines( + mode_label, + mode_color, + slash_mode, + mode.ai_kind().is_some(), + state.ui.input.buffer.is_empty(), + !visible_suggestions.is_empty(), + )) + .style(theme::primary()) + .wrap(Wrap { trim: false }), + sections[0], + ); + + frame.render_widget( + Paragraph::new(editor_lines) + .style(theme::primary()) + .wrap(Wrap { trim: false }), + sections[1], + ); + + if !visible_suggestions.is_empty() { + frame.render_widget( + Paragraph::new(suggestion_lines( + &visible_suggestions, + area.width.saturating_sub(26) as usize, + )) + .style(theme::primary()) + .wrap(Wrap { trim: false }), + sections[2], + ); } - lines.push(Line::raw("")); - lines.push(Line::from(vec![ - Span::styled("shell ", theme::subtle()), - Span::styled( - state.config.commands.default_shell.clone(), - theme::primary(), - ), - Span::raw(" "), - Span::styled("focus ", theme::subtle()), - Span::styled( - if focused { "command" } else { "other" }, - if focused { - theme::accent() - } else { - theme::muted() - }, - ), - if !slash_suggestions.is_empty() { - Span::raw(" ") - } else { - Span::raw("") - }, - if !slash_suggestions.is_empty() { - Span::styled("Tab", theme::keycap()) - } else { - Span::raw("") - }, - if !slash_suggestions.is_empty() { - Span::styled(" insert", theme::muted()) - } else { - Span::raw("") - }, - ])); frame.render_widget( - Paragraph::new(lines).block( - Block::default() - .title(Span::styled(" Console ", theme::section_title())) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)), - ), - area, + Paragraph::new(console_footer_line(mode_label)) + .style(theme::primary()) + .wrap(Wrap { trim: false }), + sections[3], ); } -fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); - +fn build_context_lines(state: &AppState, width: usize) -> Vec> { if let Some(approval) = state .approvals .pending .iter() .find(|request| matches!(request.mode, ApprovalMode::InlineReview)) { - lines.push(Line::from(vec![ - Span::styled("REVIEW ", theme::status_badge(theme::WARN)), - Span::raw(" "), - Span::styled( - format!( - "#{} [{}] {}", - approval.command_id, - approval.class.label(), - approval.summary + return vec![ + Line::from(vec![ + Span::styled(" REVIEW ", theme::status_badge(theme::WARN)), + Span::raw(" "), + Span::styled(format!("#{} ", approval.command_id), theme::accent()), + Span::styled(approval.summary.clone(), theme::primary()), + ]), + Line::from(vec![Span::styled( + truncate_multiline(&approval.detail, width.max(12)), + theme::muted(), + )]), + Line::from(vec![ + Span::styled("Enter", theme::keycap()), + Span::styled(" approve", theme::muted()), + Span::raw(" "), + Span::styled("Esc", theme::keycap()), + Span::styled(" deny", theme::muted()), + Span::raw(" "), + Span::styled( + format!( + "{} / {}", + approval.class.label(), + provenance_label(approval.execution.provenance) + ), + theme::subtle(), ), - theme::primary(), - ), - ])); - lines.push(Line::from(vec![ - Span::styled("Enter", theme::keycap()), - Span::styled(" approve", theme::muted()), - Span::raw(" "), - Span::styled("Esc", theme::keycap()), - Span::styled(" deny", theme::muted()), - ])); - } else { - lines.push(Line::from(vec![ - Span::styled("READY ", theme::status_badge(theme::SUCCESS)), - Span::raw(" "), - Span::styled("No inline approvals waiting", theme::muted()), - ])); - lines.push(Line::from(vec![ - Span::styled("Enter", theme::keycap()), - Span::styled(" run command", theme::muted()), - Span::raw(" "), - Span::styled("Ctrl+L", theme::keycap()), - Span::styled(" clear input", theme::muted()), - ])); + ]), + ]; } - if let Some(notification) = state.notifications.items.last() { - let color = theme::notification_color(notification.level); - lines.push(Line::raw("")); - lines.push(Line::from(vec![ - Span::styled("LAST NOTICE ", theme::status_badge(color)), + if state.ui.input.mode.ai_kind().is_some() + || matches!( + state.ai.status, + AiStatus::Queued | AiStatus::Running | AiStatus::Failed + ) + { + return build_ai_context_lines(state, width); + } + + if let Some(command) = state.commands.records.last() { + let status_color = command_status_color(command.status); + let latest_output = state + .logs + .recent + .iter() + .rev() + .find(|entry| entry.command_id == Some(command.id)); + + let mut lines = vec![Line::from(vec![ + Span::styled( + format!(" {} ", command_status_label(command.status)), + theme::status_badge(status_color), + ), Span::raw(" "), + Span::styled(format!("#{} ", command.id), theme::accent()), Span::styled( - format!( - "[{}] {}", - format_timestamp(notification.created_at), - notification.message - ), + truncate_multiline(&command.raw, width.max(12)), theme::primary(), ), - ])); - } else { - lines.push(Line::raw("")); - lines.push(Line::from(vec![ - Span::styled("/help", theme::accent()), - Span::styled(" for slash commands and key hints", theme::muted()), - ])); - } + ])]; - frame.render_widget( - Paragraph::new(lines) - .block( - Block::default() - .title(Span::styled(" Signal ", theme::section_title())) - .style(theme::panel_surface(false)), - ) - .wrap(Wrap { trim: false }), - area, - ); -} - -fn render_history(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); + if let Some(output) = latest_output { + lines.push(Line::from(vec![ + Span::styled( + format!("[{}] ", format_timestamp(output.ts)), + theme::subtle(), + ), + Span::styled( + truncate_multiline(&output.raw, width.saturating_sub(16).max(12)), + theme::muted(), + ), + ])); + } else { + lines.push(Line::from(vec![Span::styled( + format!( + "{} action from {} in {}", + command.safety_class.label(), + provenance_label(command.provenance), + command.cwd.display() + ), + theme::muted(), + )])); + } - if state.commands.records.is_empty() { - lines.push(Line::from(vec![ - Span::styled("No commands yet.", theme::muted()), - Span::raw(" "), - Span::styled("Try", theme::muted()), - Span::raw(" "), - Span::styled("pwd", theme::accent()), - Span::raw(" "), - Span::styled("or", theme::muted()), - Span::raw(" "), - Span::styled("sleep 5 &", theme::accent()), - Span::raw(" "), - Span::styled("to seed the dashboard.", theme::muted()), - ])); + return lines; } - for record in state - .commands - .records - .iter() - .rev() - .take(state.config.ui.history_preview.max(6)) - { - let status_color = match record.status { - crate::domain::CommandStatus::PendingReview - | crate::domain::CommandStatus::PendingApproval => theme::WARN, - crate::domain::CommandStatus::Queued | crate::domain::CommandStatus::Running => { - theme::ACCENT - } - crate::domain::CommandStatus::Succeeded => theme::SUCCESS, - crate::domain::CommandStatus::Failed | crate::domain::CommandStatus::Denied => { - theme::ERROR - } - crate::domain::CommandStatus::Cancelled => theme::TEXT_SUBTLE, - }; - let summary = if let Some(code) = record.exit_code { - format!("exit {code}") - } else { - format!("{:?}", record.status).to_lowercase() - }; - lines.push(Line::from(vec![ - Span::styled(format!("#{} ", record.id), theme::accent()), - Span::styled(format!("[{summary}] "), theme::status_badge(status_color)), + vec![ + Line::from(vec![ + Span::styled(" READY ", theme::status_badge(theme::SUCCESS)), Span::raw(" "), - Span::styled(record.raw.clone(), theme::primary()), - ])); - } - - let block = Block::default() - .title(Span::styled(" Flight Tape ", theme::section_title())) - .style(theme::panel_surface(false)); - frame.render_widget( - Paragraph::new(lines) - .block(block) - .wrap(Wrap { trim: false }), - area, - ); + Span::styled( + "Shell is quiet. This deck is ready for commands, AI, or approvals.", + theme::primary(), + ), + ]), + Line::from(vec![Span::styled( + "Start with /help, /bg cargo run, or press F2 to switch into assist or diagnose mode.", + theme::muted(), + )]), + ] } -fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); +fn build_ai_context_lines(state: &AppState, width: usize) -> Vec> { let (status_label, status_color) = match state.ai.status { AiStatus::Disabled => ("OFF", theme::TEXT_SUBTLE), AiStatus::Unconfigured => ("SETUP", theme::WARN), @@ -333,182 +248,197 @@ fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { AiStatus::Failed => ("ERROR", theme::ERROR), }; - lines.push(Line::from(vec![ + let provider = state + .ai + .provider + .clone() + .unwrap_or_else(|| "provider:unconfigured".to_string()); + let model = state + .ai + .model + .clone() + .unwrap_or_else(|| "default".to_string()); + + let mut lines = vec![Line::from(vec![ Span::styled( format!(" {} ", status_label), theme::status_badge(status_color), ), Span::raw(" "), - Span::styled( - state - .ai - .provider - .clone() - .unwrap_or_else(|| "provider:unconfigured".to_string()), - theme::primary(), - ), - if let Some(model) = state.ai.model.as_ref() { - Span::styled(format!(" model:{model}"), theme::muted()) - } else { - Span::styled(" model:default", theme::muted()) - }, - ])); - - if let Some(request) = state.ai.requests.last() { - lines.push(Line::from(vec![ - Span::styled( - format!("{} ", request.kind.label().to_ascii_uppercase()), - theme::accent(), - ), - Span::styled( - visible_input_text(&request.prompt, area.width.saturating_sub(12) as usize), - theme::primary(), - ), - ])); - } + Span::styled(provider, theme::primary()), + Span::styled(format!(" model:{model}"), theme::muted()), + ])]; match state.ai.status { AiStatus::Running | AiStatus::Queued => { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - "AI request is running against the configured provider.", - theme::muted(), - )])); + if let Some(request) = state.ai.requests.last() { + lines.push(Line::from(vec![Span::styled( + truncate_multiline(&request.prompt, width.max(12)), + theme::primary(), + )])); + } } AiStatus::Failed => { - lines.push(Line::raw("")); if let Some(error) = state.ai.last_error.as_ref() { lines.push(Line::from(vec![Span::styled( - truncate_multiline(error, area.width.saturating_sub(4) as usize), - theme::primary(), + truncate_multiline(error, width.max(12)), + theme::muted(), )])); } } _ => { if let Some(response) = state.ai.last_response.as_ref() { - lines.push(Line::raw("")); lines.push(Line::from(vec![Span::styled( - response.summary.clone(), + truncate_multiline(&response.summary, width.max(12)), theme::primary(), )])); - lines.push(Line::from(vec![Span::styled( - truncate_multiline(&response.message, area.width.saturating_sub(4) as usize), - theme::muted(), - )])); - if !response.recommendations.is_empty() { - lines.push(Line::raw("")); + if !response.recommendations.is_empty() || !response.proposals.is_empty() { lines.push(Line::from(vec![Span::styled( - "Recommendations", - theme::section_title(), + format!( + "{} recommendation(s) {} proposal(s)", + response.recommendations.len(), + response.proposals.len() + ), + theme::muted(), )])); - for recommendation in response.recommendations.iter().take(3) { - lines.push(Line::from(vec![ - Span::styled("• ", theme::accent()), - Span::styled( - truncate_multiline( - recommendation, - area.width.saturating_sub(6) as usize, - ), - theme::primary(), - ), - ])); - } } - if !response.proposals.is_empty() { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - "Proposals", - theme::section_title(), - )])); - for (index, proposal) in response.proposals.iter().take(3).enumerate() { - lines.push(Line::from(vec![ - Span::styled(format!("{}. ", index + 1), theme::accent()), - Span::styled( - format!("[{}] ", proposal.safety_class.label()), - theme::status_badge(theme::INFO), - ), - Span::styled( - truncate_multiline( - &proposal.summary, - area.width.saturating_sub(20) as usize, - ), - theme::primary(), - ), - ])); - - let detail = proposal.command.as_deref().unwrap_or(&proposal.detail); - let action_hint = if proposal.command.is_some() { - format!("/apply {}", index + 1) - } else { - "inspect only".to_string() - }; - lines.push(Line::from(vec![ - Span::styled(" ", theme::muted()), - Span::styled( - truncate_multiline(detail, area.width.saturating_sub(20) as usize), - theme::muted(), - ), - Span::raw(" "), - Span::styled(action_hint, theme::accent()), - ])); - } - } - if !response.citations.is_empty() { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - "Grounding", - theme::section_title(), - )])); - for citation in response.citations.iter().take(2) { - lines.push(Line::from(vec![ - Span::styled(format!("{} ", citation.label), theme::accent()), - Span::styled( - truncate_multiline( - &citation.detail, - area.width.saturating_sub(6) as usize, - ), - theme::muted(), - ), - ])); - } - } - } else if let Some(message) = state - .ai - .messages - .iter() - .rev() - .find(|message| matches!(message.role, AiMessageRole::Assistant)) - { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - truncate_multiline(&message.content, area.width.saturating_sub(4) as usize), - theme::primary(), - )])); - } else { - lines.push(Line::raw("")); + } else if state.ui.input.mode.ai_kind().is_some() { lines.push(Line::from(vec![Span::styled( - "Use /ai for assistance, /diagnose for diagnosis, and /apply to run a proposal through approvals.", + "Plain text in this mode submits directly to AI. Use / for Forge commands.", theme::muted(), )])); } } } - frame.render_widget( - Paragraph::new(lines) - .block( - Block::default() - .title(Span::styled(" AI Relay ", theme::section_title())) - .style(theme::panel_surface(false)), - ) - .wrap(Wrap { trim: false }), - area, - ); + lines +} + +fn visible_command_suggestions<'a>( + slash_suggestions: &'a [&'a SlashCommandSpec], + state: &AppState, +) -> Vec<(bool, &'a SlashCommandSpec)> { + if slash_suggestions.is_empty() { + return Vec::new(); + } + + let selection = state + .ui + .command_palette_cursor + .min(slash_suggestions.len() - 1); + let visible_len = slash_suggestions.len().min(4); + let max_start = slash_suggestions.len().saturating_sub(visible_len); + let visible_start = selection + .saturating_sub(visible_len.saturating_sub(1)) + .min(max_start); + + slash_suggestions + .iter() + .skip(visible_start) + .take(visible_len) + .enumerate() + .map(|(offset, suggestion)| (visible_start + offset == selection, *suggestion)) + .collect() +} + +fn visible_editor_lines( + buffer: &str, + cursor: usize, + width: usize, + max_lines: usize, + gutter_label: &str, + prompt_symbol: &str, +) -> Vec> { + let mut logical_lines = if buffer.is_empty() { + vec![String::new()] + } else { + buffer + .split('\n') + .map(ToString::to_string) + .collect::>() + }; + if logical_lines.is_empty() { + logical_lines.push(String::new()); + } + + let cursor_line = buffer[..cursor].chars().filter(|ch| *ch == '\n').count(); + let visible_count = max_lines.max(1).min(logical_lines.len()); + let start = cursor_line.saturating_sub(visible_count.saturating_sub(1)); + let end = (start + visible_count).min(logical_lines.len()); + + logical_lines[start..end] + .iter() + .enumerate() + .map(|(offset, line)| { + let line_index = start + offset; + let is_cursor_line = line_index == cursor_line; + let cursor_col = if is_cursor_line { + Some( + buffer[..cursor] + .rsplit('\n') + .next() + .unwrap_or_default() + .chars() + .count(), + ) + } else { + None + }; + let rendered = render_editor_segment(line, width, cursor_col); + Line::from(vec![ + Span::styled( + if line_index == start { + format!("{gutter_label:>7} {prompt_symbol} ") + } else { + " ".to_string() + }, + if is_cursor_line { + theme::accent() + } else { + theme::subtle() + }, + ), + Span::styled(rendered, theme::primary()), + ]) + }) + .collect() +} + +fn render_editor_segment(line: &str, width: usize, cursor_col: Option) -> String { + let chars = line.chars().collect::>(); + let cursor_col = cursor_col.unwrap_or(chars.len()); + let visible_width = width.max(8).saturating_sub(1); + let start = cursor_col.saturating_sub(visible_width.saturating_sub(1)); + let end = (start + visible_width).min(chars.len()); + let mut rendered = chars[start..end].iter().collect::(); + + if line.is_empty() && cursor_col == 0 { + rendered.push('█'); + } else if cursor_col >= start && cursor_col <= end { + let insert_at = chars[start..cursor_col.min(chars.len())] + .iter() + .collect::() + .len(); + rendered.insert(insert_at, '█'); + } + + if start > 0 { + rendered.insert(0, '…'); + } + if end < chars.len() { + rendered.push('…'); + } + rendered +} + +fn truncate_multiline(value: &str, max_chars: usize) -> String { + let single_line = value.lines().collect::>().join(" "); + visible_input_text(&single_line, max_chars.max(8)) } fn visible_input_text(input: &str, max_chars: usize) -> String { if input.is_empty() { - return "Type a shell command".to_string(); + return String::new(); } let chars = input.chars().collect::>(); @@ -522,7 +452,146 @@ fn visible_input_text(input: &str, max_chars: usize) -> String { format!("…{tail}") } -fn truncate_multiline(value: &str, max_chars: usize) -> String { - let single_line = value.lines().collect::>().join(" "); - visible_input_text(&single_line, max_chars.max(8)) +fn provenance_label(provenance: CommandProvenance) -> &'static str { + match provenance { + CommandProvenance::UserInput => "user", + CommandProvenance::SlashCommand => "slash", + CommandProvenance::ApprovalEscalation => "approval", + CommandProvenance::AiSuggestion => "ai", + } +} + +fn command_status_color(status: CommandStatus) -> ratatui::style::Color { + match status { + CommandStatus::PendingReview | CommandStatus::PendingApproval => theme::WARN, + CommandStatus::Queued | CommandStatus::Running => theme::INFO, + CommandStatus::Succeeded => theme::SUCCESS, + CommandStatus::Failed | CommandStatus::Denied => theme::ERROR, + CommandStatus::Cancelled => theme::TEXT_SUBTLE, + } +} + +fn command_status_label(status: CommandStatus) -> &'static str { + match status { + CommandStatus::PendingReview => "REVIEW", + CommandStatus::PendingApproval => "PENDING", + CommandStatus::Queued => "QUEUED", + CommandStatus::Running => "RUNNING", + CommandStatus::Succeeded => "DONE", + CommandStatus::Failed => "FAILED", + CommandStatus::Cancelled => "CANCELLED", + CommandStatus::Denied => "DENIED", + } +} + +fn editor_header_lines( + mode_label: &str, + mode_color: ratatui::style::Color, + slash_mode: bool, + ai_mode: bool, + input_empty: bool, + showing_suggestions: bool, +) -> Vec> { + vec![ + Line::from(vec![ + Span::styled(format!(" {mode_label} "), theme::status_badge(mode_color)), + Span::raw(" "), + Span::styled( + if slash_mode { + "Search Forge actions without leaving the command deck." + } else if ai_mode { + "Ask Forge with live repo and runtime context." + } else { + "Run commands directly in the current shell." + }, + theme::muted(), + ), + ]), + Line::from(vec![Span::styled( + if showing_suggestions { + "Arrow keys move the selector. Tab inserts. Enter runs immediately." + } else if input_empty { + "Pinned input keeps you oriented. Press / for actions or F2 to change modes." + } else { + "Multiline input is supported. History stays scoped to the current mode." + }, + theme::subtle(), + )]), + ] +} + +fn suggestion_lines( + suggestions: &[(bool, &SlashCommandSpec)], + summary_width: usize, +) -> Vec> { + let mut lines = vec![ + Line::from(vec![ + Span::styled(" Slash Actions ", theme::quiet_badge()), + Span::raw(" "), + Span::styled("Tab inserts the selected action", theme::subtle()), + ]), + Line::raw(""), + ]; + + for (selected, suggestion) in suggestions { + lines.push(Line::from(vec![ + Span::styled( + if *selected { "▶ " } else { " " }, + if *selected { + theme::accent() + } else { + theme::subtle() + }, + ), + Span::styled( + format!("{:<18}", suggestion.usage), + theme::command_palette_item(*selected), + ), + Span::raw(" "), + Span::styled( + truncate_multiline(suggestion.summary, summary_width.max(12)), + theme::command_palette_summary(*selected), + ), + ])); + } + + lines +} + +fn console_footer_line(mode_label: &'static str) -> Line<'static> { + Line::from(vec![ + Span::styled("mode", theme::label()), + Span::raw(" "), + Span::styled(mode_label, theme::primary()), + Span::raw(" "), + Span::styled("F2", theme::keycap()), + Span::styled(" cycle", theme::muted()), + Span::raw(" "), + Span::styled("Ctrl+P/N", theme::keycap()), + Span::styled(" history", theme::muted()), + Span::raw(" "), + Span::styled("Ctrl+J", theme::keycap()), + Span::styled(" newline", theme::muted()), + ]) +} + +fn editor_gutter_label(mode_label: &str) -> &'static str { + match mode_label { + "SHELL" => "shell", + "AI" => "assist", + "DIAG" => "diagnose", + "SLASH" => "slash", + _ => "input", + } +} + +fn editor_prompt_symbol(mode: crate::domain::InputMode, slash_mode: bool) -> &'static str { + if slash_mode { + "/" + } else { + match mode { + crate::domain::InputMode::Shell => "$", + crate::domain::InputMode::AiAssist | crate::domain::InputMode::AiDiagnose => ">", + } + } } diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index b547395..acac791 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -1,7 +1,7 @@ use ratatui::layout::Rect; use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; use crate::domain::{AppState, DashboardTab, ProcessStatus}; @@ -10,10 +10,11 @@ use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { let block = Block::default() - .title(Span::styled(" Ops Surface ", theme::panel_title(focused))) + .title(Span::styled(" Operations ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)); + .style(theme::panel_surface(focused)) + .padding(Padding::horizontal(1)); let inner = block.inner(area); frame.render_widget(block, area); @@ -26,8 +27,8 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool ]) .split(inner); - render_tabs(frame, sections[0], state); - render_context(frame, sections[1], state); + render_overview(frame, sections[0], state); + render_tabs(frame, sections[1], state); let lines = match state.ui.dashboard_tab { DashboardTab::Services => services_lines(state), @@ -48,7 +49,10 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool fn services_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Managed services", theme::section_title()), - Span::styled(" background jobs and long-lived processes", theme::muted()), + Span::styled( + " long-lived jobs with health and PID visibility", + theme::muted(), + ), ])]; if state.services.registry.is_empty() { lines.push(Line::raw("")); @@ -57,11 +61,11 @@ fn services_lines(state: &AppState) -> Vec> { theme::primary(), )])); lines.push(Line::from(vec![ - Span::styled("Try ", theme::muted()), - Span::styled("sleep 30 &", theme::accent()), - Span::styled(" or ", theme::muted()), + Span::styled("Launch one with ", theme::muted()), Span::styled("/bg cargo run", theme::accent()), - Span::styled(" to create one.", theme::muted()), + Span::styled(" or any shell command that ends with ", theme::muted()), + Span::styled("&", theme::accent()), + Span::styled(".", theme::muted()), ])); return lines; } @@ -69,13 +73,13 @@ fn services_lines(state: &AppState) -> Vec> { for service in state.services.registry.iter().rev().take(12) { let health = format!("{:?}", service.health).to_lowercase(); lines.push(Line::from(vec![ - Span::styled(format!("#{} ", service.id), theme::accent()), + Span::styled(format!("#{: <3}", service.id), theme::accent()), Span::styled( - format!("[{health}] "), + format!(" {health} "), theme::status_badge(theme::health_color(service.health)), ), Span::raw(" "), - Span::styled(service.name.clone(), theme::primary()), + Span::styled(truncate_end(&service.name, 28), theme::primary()), Span::raw(" "), Span::styled(format!("pid:{:?}", service.pid), theme::muted()), ])); @@ -86,7 +90,10 @@ fn services_lines(state: &AppState) -> Vec> { fn processes_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Tracked processes", theme::section_title()), - Span::styled(" active and recently completed jobs", theme::muted()), + Span::styled( + " foreground work, background jobs, and recent exits", + theme::muted(), + ), ])]; if state.processes.snapshots.is_empty() { lines.push(Line::raw("")); @@ -95,7 +102,7 @@ fn processes_lines(state: &AppState) -> Vec> { theme::primary(), )])); lines.push(Line::from(vec![Span::styled( - "Foreground and background commands populate this view.", + "Run commands in the deck and their lifecycle will accumulate here.", theme::muted(), )])); return lines; @@ -117,9 +124,9 @@ fn processes_lines(state: &AppState) -> Vec> { ProcessStatus::Cancelled => theme::WARN, }; lines.push(Line::from(vec![ - Span::styled(format!("[{status}] "), theme::status_badge(color)), + Span::styled(format!(" {status} "), theme::status_badge(color)), Span::raw(" "), - Span::styled(process.label.clone(), theme::primary()), + Span::styled(truncate_end(&process.label, 34), theme::primary()), Span::raw(" "), Span::styled(format!("pid:{:?}", process.pid), theme::muted()), ])); @@ -130,7 +137,10 @@ fn processes_lines(state: &AppState) -> Vec> { fn log_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Recent logs", theme::section_title()), - Span::styled(" newest entries first", theme::muted()), + Span::styled( + " most recent entries first across tracked work", + theme::muted(), + ), ])]; if state.logs.recent.is_empty() { lines.push(Line::raw("")); @@ -139,7 +149,7 @@ fn log_lines(state: &AppState) -> Vec> { theme::primary(), )])); lines.push(Line::from(vec![Span::styled( - "Run a command to start filling the log buffer.", + "Logs appear automatically once commands or services start producing output.", theme::muted(), )])); return lines; @@ -157,11 +167,11 @@ fn log_lines(state: &AppState) -> Vec> { lines.push(Line::from(vec![ Span::styled(format!("{} ", format_timestamp(entry.ts)), theme::subtle()), Span::styled( - format!("[{level}] "), + format!(" {level} "), theme::status_badge(theme::severity_color(entry.severity)), ), Span::raw(" "), - Span::styled(entry.raw.clone(), theme::primary()), + Span::styled(truncate_end(&entry.raw, 56), theme::primary()), ])); } lines @@ -170,11 +180,12 @@ fn log_lines(state: &AppState) -> Vec> { fn git_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Repository context", theme::section_title()), - Span::styled(" current branch and changed files", theme::muted()), + Span::styled(" branch, head, and working tree state", theme::muted()), ])]; lines.push(Line::raw("")); lines.push(Line::from(vec![ - Span::styled("Branch ", theme::muted()), + Span::styled("Branch", theme::label()), + Span::raw(" "), Span::styled( state .git @@ -185,7 +196,8 @@ fn git_lines(state: &AppState) -> Vec> { ), ])); lines.push(Line::from(vec![ - Span::styled("HEAD ", theme::muted()), + Span::styled("Head", theme::label()), + Span::raw(" "), Span::styled( state .git @@ -196,20 +208,22 @@ fn git_lines(state: &AppState) -> Vec> { ), ])); lines.push(Line::from(vec![ - Span::styled("Status ", theme::muted()), + Span::styled("Status", theme::label()), + Span::raw(" "), Span::styled( - if state.git.is_dirty { "dirty" } else { "clean" }, + format!(" {} ", if state.git.is_dirty { "dirty" } else { "clean" }), if state.git.is_dirty { - theme::accent() + theme::status_badge(theme::WARN) } else { - theme::muted() + theme::quiet_badge() }, ), ])); lines.push(Line::raw("")); if state.git.changed_files.is_empty() { lines.push(Line::from(vec![ - Span::styled("Changed files ", theme::muted()), + Span::styled("Changed files", theme::label()), + Span::raw(" "), Span::styled("none", theme::primary()), ])); } else { @@ -220,7 +234,7 @@ fn git_lines(state: &AppState) -> Vec> { for file in state.git.changed_files.iter().take(10) { lines.push(Line::from(vec![ Span::styled("• ", theme::accent()), - Span::styled(file.clone(), theme::primary()), + Span::styled(truncate_end(file, 56), theme::primary()), ])); } } @@ -231,7 +245,7 @@ fn test_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Test runs", theme::section_title()), Span::styled( - " normalized test results will accumulate here", + " normalized pass/fail summaries across runners", theme::muted(), ), ])]; @@ -242,16 +256,18 @@ fn test_lines(state: &AppState) -> Vec> { theme::primary(), )])); lines.push(Line::from(vec![Span::styled( - "Future adapters should normalize test results here.", + "Wire test adapters into Forge and their results will surface here.", theme::muted(), )])); return lines; } for run in state.tests.recent_runs.iter().rev().take(8) { + let status = format!("{:?}", run.status).to_ascii_lowercase(); lines.push(Line::from(vec![ - Span::styled(format!("[{:?}] ", run.status), theme::accent()), - Span::styled(run.runner.clone(), theme::primary()), + Span::styled(format!(" {status} "), theme::quiet_badge()), + Span::raw(" "), + Span::styled(truncate_end(&run.runner, 24), theme::primary()), Span::raw(" "), Span::styled( format!("pass:{} fail:{}", run.pass_count, run.fail_count), @@ -262,6 +278,61 @@ fn test_lines(state: &AppState) -> Vec> { lines } +fn render_overview(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let branch = state + .git + .branch + .clone() + .unwrap_or_else(|| "unknown".to_string()); + let lines = vec![ + Line::from(vec![ + Span::styled("services", theme::label()), + Span::raw(" "), + Span::styled(state.services.registry.len().to_string(), theme::primary()), + Span::styled(" • ", theme::subtle()), + Span::styled("processes", theme::label()), + Span::raw(" "), + Span::styled( + state.processes.snapshots.len().to_string(), + theme::primary(), + ), + Span::styled(" • ", theme::subtle()), + Span::styled("logs", theme::label()), + Span::raw(" "), + Span::styled(state.logs.recent.len().to_string(), theme::primary()), + Span::styled(" • ", theme::subtle()), + Span::styled("approvals", theme::label()), + Span::raw(" "), + Span::styled(state.approvals.pending.len().to_string(), theme::primary()), + ]), + Line::from(vec![ + Span::styled("workspace", theme::quiet_badge()), + Span::raw(" "), + Span::styled(truncate_end(&branch, 24), theme::primary()), + Span::styled(" • ", theme::subtle()), + Span::styled( + if state.git.is_dirty { + "dirty tree" + } else { + "clean tree" + }, + if state.git.is_dirty { + theme::warn_accent() + } else { + theme::muted() + }, + ), + Span::styled(" • ", theme::subtle()), + Span::styled( + format!("{} changed file(s)", state.git.changed_files.len()), + theme::muted(), + ), + ]), + ]; + + frame.render_widget(Paragraph::new(lines), area); +} + fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { let tabs = DashboardTab::all() .iter() @@ -271,7 +342,7 @@ fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { if active { Span::styled(label, theme::status_badge(theme::ACCENT)) } else { - Span::styled(label, theme::muted()) + Span::styled(label, theme::quiet_badge()) } }) .collect::>(); @@ -288,42 +359,35 @@ fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { content.push(Span::styled(" switch tabs", theme::muted())); frame.render_widget( - Paragraph::new(Line::from(content)).block(Block::default()), + Paragraph::new(vec![ + Line::from(content), + Line::from(vec![Span::styled( + active_tab_summary(state.ui.dashboard_tab), + theme::subtle(), + )]), + ]), area, ); } -fn render_context(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let summary = match state.ui.dashboard_tab { - DashboardTab::Services => { - format!("{} tracked services", state.services.registry.len()) - } - DashboardTab::Processes => { - format!("{} process snapshots", state.processes.snapshots.len()) - } - DashboardTab::Logs => { - format!("{} buffered log lines", state.logs.recent.len()) - } - DashboardTab::Git => { - format!( - "branch {} | {} changed files", - state - .git - .branch - .clone() - .unwrap_or_else(|| "unknown".to_string()), - state.git.changed_files.len() - ) - } - DashboardTab::Tests => { - format!("{} recorded test runs", state.tests.recent_runs.len()) - } - }; +fn active_tab_summary(tab: DashboardTab) -> &'static str { + match tab { + DashboardTab::Services => "Long-lived services with health, PID, and launch visibility.", + DashboardTab::Processes => "Recent foreground and background command execution history.", + DashboardTab::Logs => "Unified log flow from commands and tracked services.", + DashboardTab::Git => "Working tree status, branch context, and changed files.", + DashboardTab::Tests => "Normalized runner outcomes as adapters come online.", + } +} + +fn truncate_end(value: &str, max_chars: usize) -> String { + if value.chars().count() <= max_chars { + return value.to_string(); + } - let line = Line::from(vec![ - Span::styled(state.ui.dashboard_tab.title(), theme::accent()), - Span::styled(" ", theme::muted()), - Span::styled(summary, theme::muted()), - ]); - frame.render_widget(Paragraph::new(line), area); + let kept = value + .chars() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{kept}…") } diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index 8caeb53..d6aecbd 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -1,6 +1,6 @@ use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; use crate::domain::{AppState, TimelineKind}; @@ -14,10 +14,11 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool Paragraph::new(lines) .block( Block::default() - .title(Span::styled(" Event Tape ", theme::panel_title(focused))) + .title(Span::styled(" Activity ", theme::panel_title(focused))) .borders(Borders::ALL) .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)), + .style(theme::panel_surface(focused)) + .padding(Padding::horizontal(1)), ) .wrap(Wrap { trim: false }), area, @@ -48,10 +49,16 @@ fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { } if collapsed.is_empty() { - return vec![Line::from(vec![Span::styled( - "No events yet. Run a command to populate the timeline.", - theme::muted(), - )])]; + return vec![ + Line::from(vec![Span::styled( + "No activity yet.", + theme::primary(), + )]), + Line::from(vec![Span::styled( + "Commands, approvals, AI work, and log bursts will leave a compact audit trail here.", + theme::muted(), + )]), + ]; } collapsed @@ -72,7 +79,7 @@ fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { theme::status_badge(theme::timeline_color(entry.kind)), ), Span::raw(" "), - Span::styled(entry.message, theme::primary()), + Span::styled(truncate_end(&entry.message, 92), theme::primary()), ]; if entry.count > 1 { spans.push(Span::raw(" ")); @@ -83,6 +90,18 @@ fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { .collect() } +fn truncate_end(value: &str, max_chars: usize) -> String { + if value.chars().count() <= max_chars { + return value.to_string(); + } + + let kept = value + .chars() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{kept}…") +} + struct CollapsedEntry { at: std::time::SystemTime, last_seen: std::time::SystemTime, diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index e84fb4c..64fd04c 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -12,15 +12,12 @@ use crate::domain::{AppState, FocusTarget}; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, state: &AppState) { - frame.render_widget( - Block::default().style(theme::panel_surface(false)), - frame.area(), - ); + frame.render_widget(Block::default().style(theme::app_surface()), frame.area()); let layout = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(3), + Constraint::Length(2), Constraint::Min(12), Constraint::Length(state.config.ui.event_stream_height), ]) @@ -34,6 +31,7 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Constraint::Percentage(state.config.ui.main_split_pct), Constraint::Percentage(100 - state.config.ui.main_split_pct), ]) + .spacing(1) .split(layout[1]); command_pane::render( diff --git a/src/ui/views/modal.rs b/src/ui/views/modal.rs index aa2f397..ec6c69c 100644 --- a/src/ui/views/modal.rs +++ b/src/ui/views/modal.rs @@ -4,7 +4,7 @@ use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap}; use ratatui::Frame; -use crate::domain::{AppState, ModalState}; +use crate::domain::{AppState, CommandProvenance, ModalState}; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, state: &AppState) { @@ -34,10 +34,32 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { .add_modifier(Modifier::BOLD), )), Line::raw(""), - Line::from(format!( - "Command #{}: {}", - approval.command_id, approval.summary - )), + Line::from(vec![ + Span::styled( + format!("Command #{} ", approval.command_id), + theme::accent(), + ), + Span::styled( + format!("[{}] ", approval.class.label()), + theme::status_badge(theme::WARN), + ), + Span::styled( + format!("[{}] ", provenance_label(approval.execution.provenance)), + theme::status_badge(theme::INFO), + ), + Span::styled(approval.summary.clone(), theme::primary()), + ]), + Line::from(vec![ + Span::styled("cwd ", theme::subtle()), + Span::styled( + approval.execution.cwd.display().to_string(), + theme::primary(), + ), + ]), + Line::from(vec![ + Span::styled("command ", theme::subtle()), + Span::styled(approval.execution.raw.clone(), theme::primary()), + ]), Line::from(approval.detail.clone()), Line::raw(""), Line::from("Press Enter or y to approve."), @@ -84,6 +106,9 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Line::from("Tab cycle pane focus"), Line::from("Tab (with /) insert selected slash command"), Line::from("Up/Down (with /) move through slash suggestions"), + Line::from("F2 cycle shell / AI assist / AI diagnose"), + Line::from("Ctrl+P / Ctrl+N previous / next history for the current mode"), + Line::from("Ctrl+J insert a newline in the console editor"), Line::from("Left/Right switch dashboard tabs when dashboard is focused"), Line::from("Enter run input or confirm modal"), Line::from("Esc close modal / deny approval"), @@ -122,6 +147,15 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { } } +fn provenance_label(provenance: CommandProvenance) -> &'static str { + match provenance { + CommandProvenance::UserInput => "user", + CommandProvenance::SlashCommand => "slash", + CommandProvenance::ApprovalEscalation => "approval", + CommandProvenance::AiSuggestion => "ai", + } +} + fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect { let popup_layout = Layout::default() .direction(Direction::Vertical) diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index d8cb1f5..4d4a5c4 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -4,7 +4,7 @@ use ratatui::widgets::{Block, Borders, Paragraph}; use ratatui::Frame; use crate::commands::slash_palette_active; -use crate::domain::AppState; +use crate::domain::{AiStatus, AppState, FocusTarget, ModalState}; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { @@ -19,96 +19,36 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { .clone() .unwrap_or_else(|| "------".to_string()); let dirty = if state.git.is_dirty { "dirty" } else { "clean" }; - let mode = if state.ui.modal.is_some() { - "approval" - } else if !state.approvals.pending.is_empty() { - "review" - } else { - "normal" - }; - let focus = match state.ui.focus { - crate::domain::FocusTarget::CommandPane => "command", - crate::domain::FocusTarget::DashboardPane => "dashboard", - crate::domain::FocusTarget::EventStream => "events", - crate::domain::FocusTarget::Modal => "modal", - }; - let (ai_label, ai_color) = match state.ai.status { - crate::domain::AiStatus::Disabled => ("OFF", theme::TEXT_SUBTLE), - crate::domain::AiStatus::Unconfigured => ("SETUP", theme::WARN), - crate::domain::AiStatus::Ready => ("READY", theme::SUCCESS), - crate::domain::AiStatus::Queued => ("QUEUED", theme::INFO), - crate::domain::AiStatus::Running => ("RUN", theme::INFO), - crate::domain::AiStatus::Completed => ("DONE", theme::SUCCESS), - crate::domain::AiStatus::Failed => ("ERROR", theme::ERROR), - }; - let pending_count = state.approvals.pending.len().to_string(); let rows = Layout::default() .direction(Direction::Vertical) - .constraints([ - Constraint::Length(1), - Constraint::Length(1), - Constraint::Length(1), - ]) + .constraints([Constraint::Length(1), Constraint::Length(1)]) .split(area); frame.render_widget( Block::default() .borders(Borders::BOTTOM) .border_style(theme::pane_border(false)) - .style(theme::panel_surface(false)), + .style(theme::chrome_surface()), area, ); - let row1 = Line::from(vec![ - Span::styled(" FORGE ", theme::status_badge(theme::ACCENT)), - Span::raw(" "), - badge( - "GIT", - dirty, - if state.git.is_dirty { - theme::WARN - } else { - theme::SUCCESS - }, - ), - Span::raw(" "), - badge("MODE", mode, theme::INFO), - Span::raw(" "), - badge("FOCUS", focus, theme::ACCENT), - Span::raw(" "), - badge("AI", ai_label, ai_color), - Span::raw(" "), - badge( - "PENDING", - &pending_count, - if state.approvals.pending.is_empty() { - theme::TEXT_SUBTLE - } else { - theme::WARN - }, - ), - ]); - frame.render_widget(Paragraph::new(row1), rows[0]); + let row1 = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Min(36), Constraint::Length(42)]) + .split(rows[0]); - let row2 = Line::from(vec![ - Span::styled("repo ", theme::muted()), - Span::styled(truncate_end(&state.project.name, 24), theme::primary()), - Span::raw(" "), - Span::styled("branch ", theme::muted()), - Span::styled(truncate_middle(&branch, 32), theme::primary()), - Span::raw(" "), - Span::styled("head ", theme::muted()), - Span::styled(head, theme::primary()), - ]); - frame.render_widget(Paragraph::new(row2), rows[1]); - - let row3 = contextual_hint_line(state); - frame.render_widget(Paragraph::new(row3), rows[2]); -} + frame.render_widget( + Paragraph::new(primary_identity_line(state, &branch)), + row1[0], + ); + frame.render_widget( + Paragraph::new(status_summary_line(state, dirty, &head)) + .alignment(ratatui::layout::Alignment::Right), + row1[1], + ); -fn badge<'a>(label: &'a str, value: &'a str, bg: ratatui::style::Color) -> Span<'a> { - Span::styled(format!(" {label}:{value} "), theme::status_badge(bg)) + frame.render_widget(Paragraph::new(contextual_hint_line(state)), rows[1]); } fn truncate_end(value: &str, max_chars: usize) -> String { @@ -141,30 +81,44 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { } fn contextual_hint_line(state: &AppState) -> Line<'static> { - match state.ui.modal.as_ref() { - Some(crate::domain::ModalState::Approval(_)) => Line::from(vec![ - Span::styled("Enter", theme::accent()), + let mut spans = vec![ + Span::styled( + format!(" {} ", active_surface_label(state)), + if state.ui.modal.is_some() { + theme::focus_badge() + } else { + match state.ui.focus { + FocusTarget::CommandPane => theme::focus_badge(), + FocusTarget::DashboardPane | FocusTarget::EventStream => theme::quiet_badge(), + FocusTarget::Modal => theme::focus_badge(), + } + }, + ), + Span::raw(" "), + ]; + + let mut hint_spans = match state.ui.modal.as_ref() { + Some(ModalState::Approval(_)) => vec![ + Span::styled("Enter", theme::keycap()), Span::styled(" approve", theme::muted()), Span::raw(" "), - Span::styled("Esc", theme::accent()), + Span::styled("Esc", theme::keycap()), Span::styled(" deny", theme::muted()), Span::raw(" "), Span::styled("/help", theme::accent()), Span::styled(" commands", theme::muted()), - ]), - Some(crate::domain::ModalState::Help) | Some(crate::domain::ModalState::Error(_)) => { - Line::from(vec![ - Span::styled("Esc", theme::accent()), - Span::styled(" close", theme::muted()), - Span::raw(" "), - Span::styled("Enter", theme::accent()), - Span::styled(" dismiss", theme::muted()), - ]) - } + ], + Some(ModalState::Help) | Some(ModalState::Error(_)) => vec![ + Span::styled("Esc", theme::accent()), + Span::styled(" close", theme::muted()), + Span::raw(" "), + Span::styled("Enter", theme::accent()), + Span::styled(" dismiss", theme::muted()), + ], None => match state.ui.focus { - crate::domain::FocusTarget::CommandPane => { - if slash_palette_active(&state.ui.input_buffer) { - Line::from(vec![ + FocusTarget::CommandPane => { + if slash_palette_active(&state.ui.input.buffer) { + vec![ Span::styled("↑/↓", theme::keycap()), Span::styled(" choose", theme::muted()), Span::raw(" "), @@ -173,44 +127,149 @@ fn contextual_hint_line(state: &AppState) -> Line<'static> { Span::raw(" "), Span::styled("Enter", theme::keycap()), Span::styled(" run", theme::muted()), - ]) + ] } else { - Line::from(vec![ - Span::styled("/", theme::keycap()), - Span::styled(" palette", theme::muted()), - Span::raw(" "), + vec![ Span::styled("Enter", theme::keycap()), Span::styled(" run", theme::muted()), Span::raw(" "), - Span::styled("Tab", theme::keycap()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("/help", theme::accent()), + Span::styled("/", theme::keycap()), Span::styled(" commands", theme::muted()), - ]) + Span::raw(" "), + Span::styled("F2", theme::keycap()), + Span::styled(" mode", theme::muted()), + Span::raw(" "), + Span::styled("Ctrl+P/N", theme::keycap()), + Span::styled(" history", theme::muted()), + Span::raw(" "), + Span::styled("Ctrl+J", theme::keycap()), + Span::styled(" newline", theme::muted()), + ] } } - crate::domain::FocusTarget::DashboardPane => Line::from(vec![ + FocusTarget::DashboardPane => vec![ Span::styled("Left/Right", theme::keycap()), Span::styled(" switch tabs", theme::muted()), Span::raw(" "), Span::styled("Tab", theme::keycap()), Span::styled(" next pane", theme::muted()), Span::raw(" "), - Span::styled("F1", theme::keycap()), - Span::styled(" help", theme::muted()), - ]), - crate::domain::FocusTarget::EventStream => Line::from(vec![ + Span::styled("/", theme::keycap()), + Span::styled(" commands", theme::muted()), + ], + FocusTarget::EventStream => vec![ Span::styled("Tab", theme::keycap()), Span::styled(" next pane", theme::muted()), Span::raw(" "), - Span::styled("F1", theme::keycap()), - Span::styled(" help", theme::muted()), - ]), - crate::domain::FocusTarget::Modal => Line::from(vec![ + Span::styled("/", theme::keycap()), + Span::styled(" commands", theme::muted()), + ], + FocusTarget::Modal => vec![ Span::styled("Esc", theme::keycap()), Span::styled(" close", theme::muted()), - ]), + ], + }, + }; + + spans.append(&mut hint_spans); + Line::from(spans) +} + +fn primary_identity_line(state: &AppState, branch: &str) -> Line<'static> { + Line::from(vec![ + Span::styled(" FORGE ", theme::brand_badge()), + Span::raw(" "), + Span::styled( + truncate_end(&state.project.name, 20), + theme::primary_emphasis(), + ), + Span::styled(" / ", theme::subtle()), + Span::styled(truncate_middle(branch, 32), theme::muted()), + ]) +} + +fn status_summary_line(state: &AppState, dirty: &str, head: &str) -> Line<'static> { + let input_mode = state.ui.input.mode.label().to_ascii_lowercase(); + let ai_status = match state.ai.status { + AiStatus::Disabled => "ai off", + AiStatus::Unconfigured => "ai setup", + AiStatus::Ready => "ai ready", + AiStatus::Queued => "ai queued", + AiStatus::Running => "ai running", + AiStatus::Completed => "ai done", + AiStatus::Failed => "ai error", + }; + + let mut spans = vec![ + Span::styled( + format!(" {} ", dirty), + if state.git.is_dirty { + theme::status_badge(theme::WARN) + } else { + theme::quiet_badge() + }, + ), + Span::raw(" "), + Span::styled(format!(" {} ", input_mode), theme::quiet_badge()), + Span::raw(" "), + Span::styled(format!(" {} ", ai_status), ai_status_style(state.ai.status)), + ]; + + if !state.approvals.pending.is_empty() { + spans.push(Span::raw(" ")); + spans.push(Span::styled( + format!(" {} pending ", state.approvals.pending.len()), + theme::status_badge(theme::WARN), + )); + } + + if state.ui.modal.is_some() { + spans.push(Span::raw(" ")); + spans.push(Span::styled(" review ", theme::status_badge(theme::WARN))); + } else if matches!( + state.ui.focus, + FocusTarget::DashboardPane | FocusTarget::EventStream + ) { + let focus_label = match state.ui.focus { + FocusTarget::DashboardPane => "dashboard", + FocusTarget::EventStream => "activity", + _ => "", + }; + spans.push(Span::raw(" ")); + spans.push(Span::styled( + format!(" {} ", focus_label), + theme::quiet_badge(), + )); + } + + spans.push(Span::raw(" ")); + spans.push(Span::styled("head", theme::label())); + spans.push(Span::raw(" ")); + spans.push(Span::styled(head.to_string(), theme::subtle())); + + Line::from(spans) +} + +fn ai_status_style(status: AiStatus) -> ratatui::style::Style { + match status { + AiStatus::Disabled => theme::quiet_badge(), + AiStatus::Unconfigured => theme::status_badge(theme::WARN), + AiStatus::Ready | AiStatus::Completed => theme::quiet_badge(), + AiStatus::Queued | AiStatus::Running => theme::status_badge(theme::INFO), + AiStatus::Failed => theme::status_badge(theme::ERROR), + } +} + +fn active_surface_label(state: &AppState) -> &'static str { + match state.ui.modal.as_ref() { + Some(ModalState::Approval(_)) => "review", + Some(ModalState::Help) => "help", + Some(ModalState::Error(_)) => "error", + None => match state.ui.focus { + FocusTarget::CommandPane => "command deck", + FocusTarget::DashboardPane => "operations", + FocusTarget::EventStream => "activity", + FocusTarget::Modal => "modal", }, } } diff --git a/tests/foundation.rs b/tests/foundation.rs index 90adaeb..c64769f 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -6,8 +6,8 @@ use forge::commands::{parse_input, slash_command_suggestions, ParsedInput}; use forge::config::ForgeConfig; use forge::domain::{ AiActionProposal, AiRequestKind, AiResponse, AppState, ApprovalMode, CommandProvenance, - CommandStatus, DashboardTab, FocusTarget, GitSnapshot, LogEntry, LogSeverity, LogSource, - LogStream, ModalState, ProjectContext, SafetyClass, + CommandStatus, DashboardTab, FocusTarget, GitSnapshot, InputMode, LogEntry, LogSeverity, + LogSource, LogStream, ModalState, ProjectContext, SafetyClass, }; use forge::safety::classify_command; use forge::shared::ids::{AiRequestId, CommandId, LogId}; @@ -282,14 +282,14 @@ fn store_accepts_slash_command_suggestion_into_input() { store.dispatch_action(AppAction::Ui(forge::app::UiIntent::KeyChar('d'))); store.dispatch_action(AppAction::Ui(forge::app::UiIntent::AcceptCommandSuggestion)); - assert_eq!(store.state().ui.input_buffer, "/diagnose "); + assert_eq!(store.state().ui.input.buffer, "/diagnose "); assert_eq!(store.state().ui.command_palette_cursor, 0); } #[test] fn store_clear_resets_input_and_visible_logs() { let mut store = test_store(); - store.state_mut().ui.input_buffer = "pwd".to_string(); + store.state_mut().ui.input.set_buffer("pwd".to_string()); store.state_mut().logs.recent.push(LogEntry { id: LogId(1), ts: SystemTime::now(), @@ -305,10 +305,41 @@ fn store_clear_resets_input_and_visible_logs() { let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Clear)); assert!(effects.is_empty()); - assert!(store.state().ui.input_buffer.is_empty()); + assert!(store.state().ui.input.buffer.is_empty()); assert!(store.state().logs.recent.is_empty()); } +#[test] +fn store_submits_plain_prompt_in_ai_mode() { + let mut store = test_store(); + store.state_mut().ui.input.set_mode(InputMode::AiAssist); + store + .state_mut() + .ui + .input + .set_buffer("summarize the latest failure".to_string()); + + let effects = store.dispatch_action(AppAction::Ui(forge::app::UiIntent::Submit)); + + assert!(matches!(effects.as_slice(), [Effect::RunAiRequest(_)])); + assert_eq!(store.state().ai.requests.len(), 1); + assert!(matches!( + store.state().ai.requests[0].kind, + AiRequestKind::Assist + )); +} + +#[test] +fn store_recalls_shell_history() { + let mut store = test_store(); + store.state_mut().commands.history = vec!["pwd".to_string(), "cargo test".to_string()]; + store.dispatch_action(AppAction::Ui(forge::app::UiIntent::RecallPreviousHistory)); + assert_eq!(store.state().ui.input.buffer, "cargo test"); + + store.dispatch_action(AppAction::Ui(forge::app::UiIntent::RecallNextHistory)); + assert!(store.state().ui.input.buffer.is_empty()); +} + #[test] fn store_quit_requests_shutdown() { let mut store = test_store(); From 6e60aa4885bd343890bcbd488551c5c65168210e Mon Sep 17 00:00:00 2001 From: Bethvour Date: Mon, 20 Apr 2026 21:29:05 -0500 Subject: [PATCH 05/10] enhancement: UI update --- src/ui/theme.rs | 95 ++-- src/ui/views/command_pane.rs | 914 ++++++++++++++++------------------- src/ui/views/dashboard.rs | 6 +- src/ui/views/event_stream.rs | 151 +++--- src/ui/views/mod.rs | 59 +-- src/ui/views/status_bar.rs | 295 +++-------- 6 files changed, 640 insertions(+), 880 deletions(-) diff --git a/src/ui/theme.rs b/src/ui/theme.rs index c6cbf05..33253da 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -2,30 +2,33 @@ use ratatui::style::{Color, Modifier, Style}; use crate::domain::{LogSeverity, NotificationLevel, ServiceHealth, TimelineKind}; -pub const BG_BASE: Color = Color::Rgb(7, 11, 17); -pub const BG_ELEVATED: Color = Color::Rgb(12, 17, 25); -pub const BG_PANEL: Color = Color::Rgb(16, 22, 32); -pub const BG_PANEL_FOCUS: Color = Color::Rgb(20, 27, 39); -pub const BG_CHROME: Color = Color::Rgb(24, 31, 44); -pub const BG_SELECTION: Color = Color::Rgb(30, 44, 58); -pub const PANEL_BORDER: Color = Color::Rgb(60, 73, 91); -pub const PANEL_BORDER_SUBTLE: Color = Color::Rgb(40, 50, 64); -pub const PANEL_FOCUS: Color = Color::Rgb(122, 220, 198); -pub const TEXT_PRIMARY: Color = Color::Rgb(236, 240, 244); -pub const TEXT_MUTED: Color = Color::Rgb(170, 181, 193); -pub const TEXT_SUBTLE: Color = Color::Rgb(108, 121, 137); -pub const ACCENT: Color = Color::Rgb(122, 220, 198); -pub const SUCCESS: Color = Color::Rgb(150, 216, 138); -pub const WARN: Color = Color::Rgb(236, 190, 90); -pub const ERROR: Color = Color::Rgb(229, 113, 98); -pub const INFO: Color = Color::Rgb(119, 167, 255); +// Editorial light palette — warm off-white canvas, near-black ink, teal accent. +// Sourced from the Forge Prompt-First hi-fi design. +pub const BG_BASE: Color = Color::Rgb(240, 238, 233); // warm off-white #f0eee9 +pub const BG_ELEVATED: Color = Color::Rgb(246, 243, 236); // #f6f3ec +pub const BG_PANEL: Color = Color::Rgb(251, 249, 243); // card surface #fbf9f3 +pub const BG_PANEL_FOCUS: Color = Color::Rgb(251, 249, 243); +pub const BG_CHROME: Color = Color::Rgb(235, 231, 221); +pub const BG_SELECTION: Color = Color::Rgb(221, 237, 232); // teal-wash +pub const PANEL_BORDER: Color = Color::Rgb(45, 157, 143); +pub const PANEL_BORDER_SUBTLE: Color = Color::Rgb(220, 216, 205); // hair +pub const PANEL_FOCUS: Color = Color::Rgb(45, 157, 143); +pub const TEXT_PRIMARY: Color = Color::Rgb(29, 29, 27); // near-black ink +pub const TEXT_MUTED: Color = Color::Rgb(74, 74, 70); +pub const TEXT_SUBTLE: Color = Color::Rgb(140, 140, 136); // faint +pub const ACCENT: Color = Color::Rgb(45, 157, 143); // teal #2d9d8f +pub const ACCENT_SOFT: Color = Color::Rgb(221, 237, 232); +pub const SUCCESS: Color = Color::Rgb(45, 157, 143); +pub const WARN: Color = Color::Rgb(200, 138, 46); // #c88a2e +pub const ERROR: Color = Color::Rgb(179, 62, 46); +pub const INFO: Color = Color::Rgb(66, 104, 161); pub fn app_surface() -> Style { - Style::default().bg(BG_BASE) + Style::default().bg(BG_BASE).fg(TEXT_PRIMARY) } pub fn chrome_surface() -> Style { - Style::default().bg(BG_ELEVATED) + Style::default().bg(BG_BASE).fg(TEXT_PRIMARY) } pub fn pane_border(focused: bool) -> Style { @@ -37,25 +40,27 @@ pub fn pane_border(focused: bool) -> Style { } pub fn panel_surface(focused: bool) -> Style { - Style::default().bg(if focused { BG_PANEL_FOCUS } else { BG_PANEL }) + Style::default() + .bg(if focused { BG_PANEL_FOCUS } else { BG_PANEL }) + .fg(TEXT_PRIMARY) } pub fn panel_title(focused: bool) -> Style { Style::default() .fg(if focused { TEXT_PRIMARY } else { TEXT_MUTED }) - .add_modifier(Modifier::BOLD) + .add_modifier(Modifier::ITALIC) } pub fn section_title() -> Style { - Style::default().fg(ACCENT).add_modifier(Modifier::BOLD) -} - -pub fn label() -> Style { Style::default() .fg(TEXT_SUBTLE) .add_modifier(Modifier::BOLD) } +pub fn label() -> Style { + Style::default().fg(TEXT_SUBTLE) +} + pub fn primary() -> Style { Style::default().fg(TEXT_PRIMARY) } @@ -86,20 +91,37 @@ pub fn error_accent() -> Style { Style::default().fg(ERROR).add_modifier(Modifier::BOLD) } +pub fn italic_serif() -> Style { + Style::default() + .fg(TEXT_PRIMARY) + .add_modifier(Modifier::ITALIC) +} + +pub fn italic_muted() -> Style { + Style::default() + .fg(TEXT_MUTED) + .add_modifier(Modifier::ITALIC) +} + pub fn brand_badge() -> Style { - pill(BG_BASE, ACCENT) + pill(Color::White, ACCENT) } pub fn status_badge(bg: Color) -> Style { - pill(BG_BASE, bg) + pill(Color::White, bg) } pub fn quiet_badge() -> Style { - pill(TEXT_MUTED, BG_CHROME) + Style::default() + .fg(TEXT_MUTED) + .bg(BG_ELEVATED) } pub fn focus_badge() -> Style { - pill(PANEL_FOCUS, BG_CHROME) + Style::default() + .fg(Color::White) + .bg(ACCENT) + .add_modifier(Modifier::BOLD) } pub fn pill(fg: Color, bg: Color) -> Style { @@ -108,15 +130,14 @@ pub fn pill(fg: Color, bg: Color) -> Style { pub fn keycap() -> Style { Style::default() - .fg(TEXT_PRIMARY) - .bg(BG_CHROME) - .add_modifier(Modifier::BOLD) + .fg(TEXT_MUTED) + .bg(BG_ELEVATED) } pub fn command_palette_item(selected: bool) -> Style { let mut style = Style::default() .fg(if selected { TEXT_PRIMARY } else { TEXT_MUTED }) - .bg(if selected { BG_SELECTION } else { BG_PANEL }); + .bg(if selected { ACCENT_SOFT } else { BG_PANEL }); if selected { style = style.add_modifier(Modifier::BOLD); } @@ -124,7 +145,7 @@ pub fn command_palette_item(selected: bool) -> Style { } pub fn command_palette_summary(selected: bool) -> Style { - Style::default().fg(if selected { TEXT_PRIMARY } else { TEXT_SUBTLE }) + Style::default().fg(if selected { TEXT_MUTED } else { TEXT_SUBTLE }) } pub fn notification_color(level: NotificationLevel) -> Color { @@ -160,9 +181,9 @@ pub fn severity_color(severity: LogSeverity) -> Color { pub fn timeline_color(kind: TimelineKind) -> Color { match kind { TimelineKind::System => INFO, - TimelineKind::Ai => SUCCESS, - TimelineKind::Command => ACCENT, - TimelineKind::Log => TEXT_PRIMARY, + TimelineKind::Ai => ACCENT, + TimelineKind::Command => TEXT_PRIMARY, + TimelineKind::Log => TEXT_MUTED, TimelineKind::Approval => WARN, TimelineKind::Error => ERROR, } diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index 8c0d7c7..dea145e 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -5,313 +5,486 @@ use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; use crate::commands::{slash_command_suggestions, SlashCommandSpec}; -use crate::domain::{AiStatus, AppState, ApprovalMode, CommandProvenance, CommandStatus}; -use crate::shared::time::format_timestamp; +use crate::domain::{AiStatus, AppState, ApprovalMode, InputMode}; use crate::ui::theme; +// Hero prompt — Prompt-First editorial layout. +// Narrow content column centered in the available area. pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { - let block = Block::default() - .title(Span::styled(" Command Deck ", theme::panel_title(focused))) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)) - .padding(Padding::horizontal(1)); - let inner = block.inner(area); - frame.render_widget(block, area); + // Center a content column roughly 90 cells wide (clamped to area). + let column_w = area.width.min(96).max(40); + let pad = area.width.saturating_sub(column_w) / 2; + let column = Rect { + x: area.x + pad, + y: area.y + 1, + width: column_w, + height: area.height.saturating_sub(1), + }; + let dim = !focused; let slash_suggestions = slash_command_suggestions(&state.ui.input.buffer); - let context_lines = build_context_lines(state, inner.width.saturating_sub(4) as usize); - let context_height = context_lines.len().clamp(2, 5) as u16; + let visible_suggestions = visible_command_suggestions(&slash_suggestions, state); + let running_items = running_items(state); + let running_h: u16 = if running_items.is_empty() { + 0 + } else { + (running_items.len() as u16) + 3 + }; + let suggestion_h: u16 = if visible_suggestions.is_empty() { + 0 + } else { + (visible_suggestions.len() as u16) + 2 + }; + let context_h: u16 = if should_show_context_card(state) && suggestion_h == 0 { + 10 + } else { + 0 + }; let sections = Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Length(context_height), Constraint::Min(0)]) - .split(inner); + .constraints([ + Constraint::Length(if running_h == 0 { 2 } else { 0 }), // spacer + Constraint::Length(running_h), + Constraint::Length(2), // headline + Constraint::Length(3), // prompt + Constraint::Length(suggestion_h), + Constraint::Length(context_h), + Constraint::Min(0), + ]) + .split(column); + + if running_h > 0 { + render_running_strip(frame, sections[1], &running_items); + } + + render_headline(frame, sections[2], state, dim); + render_prompt(frame, sections[3], state, dim); - render_context_strip(frame, sections[0], context_lines); - render_console(frame, sections[1], state, &slash_suggestions); + if suggestion_h > 0 { + render_suggestions(frame, sections[4], &visible_suggestions); + } else if context_h > 0 { + render_context_card(frame, sections[5], state); + } else { + render_recent_chips(frame, sections[6], state); + } } -fn render_context_strip(frame: &mut Frame<'_>, area: Rect, lines: Vec>) { - frame.render_widget( - Paragraph::new(lines) - .block( - Block::default() - .borders(Borders::BOTTOM) - .border_style(theme::pane_border(false)) - .style(theme::chrome_surface()), - ) - .wrap(Wrap { trim: false }), - area, - ); +fn render_headline(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: bool) { + if state.ui.input.buffer.is_empty() && area.height >= 1 { + let text = match state.ui.input.mode { + InputMode::Shell => "what do you want to do?", + InputMode::AiAssist => "what should Forge help you think through?", + InputMode::AiDiagnose => "what's wrong — describe the symptom.", + }; + let style = if dim { + theme::subtle() + } else { + theme::italic_muted() + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled(text, style)])), + area, + ); + } } -fn render_console( - frame: &mut Frame<'_>, - area: Rect, - state: &AppState, - slash_suggestions: &[&SlashCommandSpec], -) { +fn render_prompt(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: bool) { + let buf = &state.ui.input.buffer; + let cursor = state.ui.input.cursor; let mode = state.ui.input.mode; - let slash_mode = state.ui.input.buffer.trim_start().starts_with('/'); - let mode_label: &'static str = if slash_mode { "SLASH" } else { mode.label() }; - let mode_color = if slash_mode || mode.ai_kind().is_some() { - theme::INFO + let slash = buf.trim_start().starts_with('/'); + + let arrow_color = if dim { + theme::subtle() } else { - theme::ACCENT + theme::accent() }; - let visible_suggestions = visible_command_suggestions(slash_suggestions, state); - let suggestion_rows = if visible_suggestions.is_empty() { - 0 + let arrow_char = if slash { + "/" } else { - 2 + visible_suggestions.len() as u16 + match mode { + InputMode::Shell => "▸", + InputMode::AiAssist | InputMode::AiDiagnose => "✦", + } }; - let sections = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Length(2), - Constraint::Min(3), - Constraint::Length(suggestion_rows), - Constraint::Length(1), - ]) - .split(area); - let editor_width = sections[1].width.saturating_sub(12) as usize; - let editor_lines = visible_editor_lines( - &state.ui.input.buffer, - state.ui.input.cursor, - editor_width.max(12), - sections[1].height.max(1) as usize, - editor_gutter_label(mode_label), - editor_prompt_symbol(mode, slash_mode), - ); + // Render a 3-line bordered box with the prompt. + let block = Block::default() + .borders(Borders::ALL) + .border_style(if dim { + theme::pane_border(false) + } else { + theme::pane_border(true) + }) + .style(theme::panel_surface(!dim)) + .padding(Padding::horizontal(2)); + let inner = block.inner(area); + frame.render_widget(block, area); + + let text_width = inner.width.saturating_sub(4) as usize; + let display = render_prompt_text(buf, cursor, text_width); + + let spans = if buf.is_empty() { + let placeholder = match mode { + InputMode::Shell => "run, ask, commit, deploy…", + InputMode::AiAssist => "ask Forge anything about this repo…", + InputMode::AiDiagnose => "describe the symptom to diagnose…", + }; + vec![ + Span::styled(format!("{arrow_char} "), arrow_color), + Span::styled(placeholder, theme::subtle()), + Span::styled("█", if dim { theme::subtle() } else { theme::primary() }), + ] + } else { + vec![ + Span::styled(format!("{arrow_char} "), arrow_color), + Span::styled( + display, + if dim { + theme::muted() + } else { + theme::primary_emphasis() + }, + ), + ] + }; frame.render_widget( - Paragraph::new(editor_header_lines( - mode_label, - mode_color, - slash_mode, - mode.ai_kind().is_some(), - state.ui.input.buffer.is_empty(), - !visible_suggestions.is_empty(), - )) - .style(theme::primary()) - .wrap(Wrap { trim: false }), - sections[0], + Paragraph::new(Line::from(spans)).wrap(Wrap { trim: false }), + inner, ); +} + +fn render_prompt_text(buffer: &str, cursor: usize, width: usize) -> String { + let single = buffer.replace('\n', " ⏎ "); + let chars: Vec = single.chars().collect(); + if chars.len() <= width.max(1) { + let mut s: String = chars.iter().collect(); + if cursor <= buffer.len() { + // append block cursor at end for simplicity + s.push('█'); + } + return s; + } + let start = chars.len().saturating_sub(width.saturating_sub(2)); + let tail: String = chars[start..].iter().collect(); + format!("…{tail}█") +} +fn render_running_strip(frame: &mut Frame<'_>, area: Rect, items: &[RunItem]) { + let mut lines = vec![ + Line::from(vec![Span::styled( + " RUNNING", + theme::subtle(), + )]), + Line::raw(""), + ]; + for it in items { + lines.push(Line::from(vec![ + Span::styled(" ● ", theme::accent()), + Span::styled( + format!("{:<8}", it.name), + theme::primary_emphasis(), + ), + Span::styled(format!(" {}", it.cmd), theme::muted()), + Span::styled(format!(" {}", it.meta), theme::subtle()), + ])); + } + lines.push(Line::raw("")); frame.render_widget( - Paragraph::new(editor_lines) - .style(theme::primary()) - .wrap(Wrap { trim: false }), - sections[1], + Paragraph::new(lines).wrap(Wrap { trim: true }), + area, ); +} - if !visible_suggestions.is_empty() { - frame.render_widget( - Paragraph::new(suggestion_lines( - &visible_suggestions, - area.width.saturating_sub(26) as usize, - )) - .style(theme::primary()) - .wrap(Wrap { trim: false }), - sections[2], +struct RunItem { + name: String, + cmd: String, + meta: String, +} + +fn running_items(state: &AppState) -> Vec { + state + .services + .registry + .iter() + .filter(|s| { + matches!( + s.health, + crate::domain::ServiceHealth::Healthy + | crate::domain::ServiceHealth::Starting + ) + }) + .take(3) + .map(|s| RunItem { + name: s.name.clone(), + cmd: if s.ports.is_empty() { + format!("{:?}", s.source).to_lowercase() + } else { + format!( + "{} · :{}", + format!("{:?}", s.source).to_lowercase(), + s.ports + .iter() + .map(u16::to_string) + .collect::>() + .join(",") + ) + }, + meta: format!("pid {}", s.pid.map(|p| p.to_string()).unwrap_or_default()), + }) + .collect() +} + +fn render_suggestions( + frame: &mut Frame<'_>, + area: Rect, + suggestions: &[(bool, &SlashCommandSpec)], +) { + let mut lines = vec![Line::from(vec![Span::styled( + " SUGGESTIONS", + theme::subtle(), + )])]; + for (selected, spec) in suggestions { + let mode_pill = Span::styled( + " slash ", + if *selected { + theme::focus_badge() + } else { + theme::quiet_badge() + }, ); + let cmd_style = if *selected { + theme::primary_emphasis() + } else { + theme::muted() + }; + lines.push(Line::from(vec![ + Span::raw(" "), + mode_pill, + Span::raw(" "), + Span::styled(format!("{:<22}", spec.usage), cmd_style), + Span::styled(format!(" {}", spec.summary), theme::subtle()), + ])); + } + frame.render_widget( + Paragraph::new(lines).wrap(Wrap { trim: true }), + area, + ); +} + +fn should_show_context_card(state: &AppState) -> bool { + if state + .approvals + .pending + .iter() + .any(|r| matches!(r.mode, ApprovalMode::InlineReview)) + { + return true; + } + if state.ui.input.mode.ai_kind().is_some() { + return true; + } + if matches!( + state.ai.status, + AiStatus::Running | AiStatus::Queued | AiStatus::Failed | AiStatus::Completed + ) { + return true; } + state.commands.records.last().is_some() +} + +fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let (title, body) = build_context_card(state); + let block = Block::default() + .borders(Borders::LEFT) + .border_style(theme::pane_border(true)) + .style(theme::panel_surface(false)) + .padding(Padding::new(2, 2, 1, 1)); + let inner = block.inner(area); + frame.render_widget(block, area); + let mut lines = vec![Line::from(vec![Span::styled(title, theme::subtle())])]; + lines.push(Line::raw("")); + lines.extend(body); frame.render_widget( - Paragraph::new(console_footer_line(mode_label)) - .style(theme::primary()) - .wrap(Wrap { trim: false }), - sections[3], + Paragraph::new(lines).wrap(Wrap { trim: false }), + inner, ); } -fn build_context_lines(state: &AppState, width: usize) -> Vec> { +fn build_context_card(state: &AppState) -> (String, Vec>) { if let Some(approval) = state .approvals .pending .iter() - .find(|request| matches!(request.mode, ApprovalMode::InlineReview)) + .find(|r| matches!(r.mode, ApprovalMode::InlineReview)) { - return vec![ - Line::from(vec![ - Span::styled(" REVIEW ", theme::status_badge(theme::WARN)), - Span::raw(" "), - Span::styled(format!("#{} ", approval.command_id), theme::accent()), - Span::styled(approval.summary.clone(), theme::primary()), - ]), + let title = format!("REVIEW · #{}", approval.command_id); + let body = vec![ Line::from(vec![Span::styled( - truncate_multiline(&approval.detail, width.max(12)), + approval.summary.clone(), + theme::primary_emphasis(), + )]), + Line::raw(""), + Line::from(vec![Span::styled( + truncate(&approval.detail, 280), theme::muted(), )]), + Line::raw(""), Line::from(vec![ - Span::styled("Enter", theme::keycap()), - Span::styled(" approve", theme::muted()), - Span::raw(" "), - Span::styled("Esc", theme::keycap()), + Span::styled(" Enter ", theme::keycap()), + Span::styled(" approve ", theme::muted()), + Span::styled(" Esc ", theme::keycap()), Span::styled(" deny", theme::muted()), - Span::raw(" "), - Span::styled( - format!( - "{} / {}", - approval.class.label(), - provenance_label(approval.execution.provenance) - ), - theme::subtle(), - ), ]), ]; + return (title, body); } if state.ui.input.mode.ai_kind().is_some() || matches!( state.ai.status, - AiStatus::Queued | AiStatus::Running | AiStatus::Failed + AiStatus::Running | AiStatus::Queued | AiStatus::Failed | AiStatus::Completed ) { - return build_ai_context_lines(state, width); - } - - if let Some(command) = state.commands.records.last() { - let status_color = command_status_color(command.status); - let latest_output = state - .logs - .recent - .iter() - .rev() - .find(|entry| entry.command_id == Some(command.id)); - - let mut lines = vec![Line::from(vec![ - Span::styled( - format!(" {} ", command_status_label(command.status)), - theme::status_badge(status_color), - ), - Span::raw(" "), - Span::styled(format!("#{} ", command.id), theme::accent()), - Span::styled( - truncate_multiline(&command.raw, width.max(12)), - theme::primary(), - ), + let provider = state + .ai + .provider + .clone() + .unwrap_or_else(|| "unconfigured".to_string()); + let model = state + .ai + .model + .clone() + .unwrap_or_else(|| "default".to_string()); + let label = match state.ai.status { + AiStatus::Disabled => "AI · off", + AiStatus::Unconfigured => "AI · setup required", + AiStatus::Ready => "AI · ready", + AiStatus::Queued => "AI · queued", + AiStatus::Running => "AI · streaming…", + AiStatus::Completed => "AI · complete", + AiStatus::Failed => "AI · error", + }; + let mut body = vec![Line::from(vec![ + Span::styled(format!("{provider} "), theme::muted()), + Span::styled(format!("model {model}"), theme::subtle()), ])]; - - if let Some(output) = latest_output { - lines.push(Line::from(vec![ - Span::styled( - format!("[{}] ", format_timestamp(output.ts)), + if let Some(err) = state.ai.last_error.as_ref() { + body.push(Line::raw("")); + body.push(Line::from(vec![Span::styled( + truncate(err, 240), + theme::error_accent(), + )])); + } else if let Some(resp) = state.ai.last_response.as_ref() { + body.push(Line::raw("")); + body.push(Line::from(vec![Span::styled( + truncate(&resp.summary, 240), + theme::italic_serif(), + )])); + if !resp.recommendations.is_empty() || !resp.proposals.is_empty() { + body.push(Line::raw("")); + body.push(Line::from(vec![Span::styled( + format!( + "{} recommendation(s) · {} proposal(s)", + resp.recommendations.len(), + resp.proposals.len() + ), theme::subtle(), - ), - Span::styled( - truncate_multiline(&output.raw, width.saturating_sub(16).max(12)), - theme::muted(), - ), - ])); - } else { - lines.push(Line::from(vec![Span::styled( - format!( - "{} action from {} in {}", - command.safety_class.label(), - provenance_label(command.provenance), - command.cwd.display() - ), + )])); + } + } else if let Some(req) = state.ai.requests.last() { + body.push(Line::raw("")); + body.push(Line::from(vec![Span::styled( + truncate(&req.prompt, 240), theme::muted(), )])); } + return (label.to_string(), body); + } - return lines; + if let Some(cmd) = state.commands.records.last() { + let title = format!( + "LAST RUN · #{} {}", + cmd.id, + status_label(cmd.status) + ); + let body = vec![ + Line::from(vec![Span::styled( + truncate(&cmd.raw, 200), + theme::primary_emphasis(), + )]), + Line::raw(""), + Line::from(vec![Span::styled( + format!( + "{} · {}", + cmd.safety_class.label(), + cmd.cwd.display() + ), + theme::subtle(), + )]), + ]; + return (title, body); } - vec![ - Line::from(vec![ - Span::styled(" READY ", theme::status_badge(theme::SUCCESS)), - Span::raw(" "), - Span::styled( - "Shell is quiet. This deck is ready for commands, AI, or approvals.", - theme::primary(), - ), - ]), - Line::from(vec![Span::styled( - "Start with /help, /bg cargo run, or press F2 to switch into assist or diagnose mode.", + ( + "READY".to_string(), + vec![Line::from(vec![Span::styled( + "Shell is quiet. Press / for commands or F2 to switch modes.", theme::muted(), - )]), - ] + )])], + ) } -fn build_ai_context_lines(state: &AppState, width: usize) -> Vec> { - let (status_label, status_color) = match state.ai.status { - AiStatus::Disabled => ("OFF", theme::TEXT_SUBTLE), - AiStatus::Unconfigured => ("SETUP", theme::WARN), - AiStatus::Ready => ("READY", theme::SUCCESS), - AiStatus::Queued => ("QUEUED", theme::INFO), - AiStatus::Running => ("RUNNING", theme::INFO), - AiStatus::Completed => ("DONE", theme::SUCCESS), - AiStatus::Failed => ("ERROR", theme::ERROR), - }; - - let provider = state - .ai - .provider - .clone() - .unwrap_or_else(|| "provider:unconfigured".to_string()); - let model = state - .ai - .model - .clone() - .unwrap_or_else(|| "default".to_string()); - - let mut lines = vec![Line::from(vec![ - Span::styled( - format!(" {} ", status_label), - theme::status_badge(status_color), - ), - Span::raw(" "), - Span::styled(provider, theme::primary()), - Span::styled(format!(" model:{model}"), theme::muted()), - ])]; +fn render_recent_chips(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + if area.height == 0 { + return; + } + let recents: Vec = state + .commands + .records + .iter() + .rev() + .take(3) + .map(|c| truncate(&c.raw, 24)) + .collect(); + if recents.is_empty() { + return; + } + let mut spans: Vec> = vec![Span::styled(" recent ", theme::subtle())]; + for r in recents { + spans.push(Span::styled(format!(" {r} "), theme::quiet_badge())); + spans.push(Span::raw(" ")); + } + frame.render_widget( + Paragraph::new(Line::from(spans)).wrap(Wrap { trim: true }), + area, + ); +} - match state.ai.status { - AiStatus::Running | AiStatus::Queued => { - if let Some(request) = state.ai.requests.last() { - lines.push(Line::from(vec![Span::styled( - truncate_multiline(&request.prompt, width.max(12)), - theme::primary(), - )])); - } - } - AiStatus::Failed => { - if let Some(error) = state.ai.last_error.as_ref() { - lines.push(Line::from(vec![Span::styled( - truncate_multiline(error, width.max(12)), - theme::muted(), - )])); - } - } - _ => { - if let Some(response) = state.ai.last_response.as_ref() { - lines.push(Line::from(vec![Span::styled( - truncate_multiline(&response.summary, width.max(12)), - theme::primary(), - )])); - if !response.recommendations.is_empty() || !response.proposals.is_empty() { - lines.push(Line::from(vec![Span::styled( - format!( - "{} recommendation(s) {} proposal(s)", - response.recommendations.len(), - response.proposals.len() - ), - theme::muted(), - )])); - } - } else if state.ui.input.mode.ai_kind().is_some() { - lines.push(Line::from(vec![Span::styled( - "Plain text in this mode submits directly to AI. Use / for Forge commands.", - theme::muted(), - )])); - } - } +fn status_label(status: crate::domain::CommandStatus) -> &'static str { + use crate::domain::CommandStatus::*; + match status { + PendingReview => "review", + PendingApproval => "pending", + Queued => "queued", + Running => "running", + Succeeded => "done", + Failed => "failed", + Cancelled => "cancelled", + Denied => "denied", } +} - lines +fn truncate(value: &str, max_chars: usize) -> String { + let joined = value.lines().collect::>().join(" "); + if joined.chars().count() <= max_chars { + return joined; + } + let kept: String = joined.chars().take(max_chars.saturating_sub(1)).collect(); + format!("{kept}…") } fn visible_command_suggestions<'a>( @@ -321,17 +494,15 @@ fn visible_command_suggestions<'a>( if slash_suggestions.is_empty() { return Vec::new(); } - let selection = state .ui .command_palette_cursor .min(slash_suggestions.len() - 1); - let visible_len = slash_suggestions.len().min(4); + let visible_len = slash_suggestions.len().min(5); let max_start = slash_suggestions.len().saturating_sub(visible_len); let visible_start = selection .saturating_sub(visible_len.saturating_sub(1)) .min(max_start); - slash_suggestions .iter() .skip(visible_start) @@ -340,258 +511,3 @@ fn visible_command_suggestions<'a>( .map(|(offset, suggestion)| (visible_start + offset == selection, *suggestion)) .collect() } - -fn visible_editor_lines( - buffer: &str, - cursor: usize, - width: usize, - max_lines: usize, - gutter_label: &str, - prompt_symbol: &str, -) -> Vec> { - let mut logical_lines = if buffer.is_empty() { - vec![String::new()] - } else { - buffer - .split('\n') - .map(ToString::to_string) - .collect::>() - }; - if logical_lines.is_empty() { - logical_lines.push(String::new()); - } - - let cursor_line = buffer[..cursor].chars().filter(|ch| *ch == '\n').count(); - let visible_count = max_lines.max(1).min(logical_lines.len()); - let start = cursor_line.saturating_sub(visible_count.saturating_sub(1)); - let end = (start + visible_count).min(logical_lines.len()); - - logical_lines[start..end] - .iter() - .enumerate() - .map(|(offset, line)| { - let line_index = start + offset; - let is_cursor_line = line_index == cursor_line; - let cursor_col = if is_cursor_line { - Some( - buffer[..cursor] - .rsplit('\n') - .next() - .unwrap_or_default() - .chars() - .count(), - ) - } else { - None - }; - let rendered = render_editor_segment(line, width, cursor_col); - Line::from(vec![ - Span::styled( - if line_index == start { - format!("{gutter_label:>7} {prompt_symbol} ") - } else { - " ".to_string() - }, - if is_cursor_line { - theme::accent() - } else { - theme::subtle() - }, - ), - Span::styled(rendered, theme::primary()), - ]) - }) - .collect() -} - -fn render_editor_segment(line: &str, width: usize, cursor_col: Option) -> String { - let chars = line.chars().collect::>(); - let cursor_col = cursor_col.unwrap_or(chars.len()); - let visible_width = width.max(8).saturating_sub(1); - let start = cursor_col.saturating_sub(visible_width.saturating_sub(1)); - let end = (start + visible_width).min(chars.len()); - let mut rendered = chars[start..end].iter().collect::(); - - if line.is_empty() && cursor_col == 0 { - rendered.push('█'); - } else if cursor_col >= start && cursor_col <= end { - let insert_at = chars[start..cursor_col.min(chars.len())] - .iter() - .collect::() - .len(); - rendered.insert(insert_at, '█'); - } - - if start > 0 { - rendered.insert(0, '…'); - } - if end < chars.len() { - rendered.push('…'); - } - rendered -} - -fn truncate_multiline(value: &str, max_chars: usize) -> String { - let single_line = value.lines().collect::>().join(" "); - visible_input_text(&single_line, max_chars.max(8)) -} - -fn visible_input_text(input: &str, max_chars: usize) -> String { - if input.is_empty() { - return String::new(); - } - - let chars = input.chars().collect::>(); - if chars.len() <= max_chars { - return input.to_string(); - } - - let tail = chars[chars.len().saturating_sub(max_chars - 1)..] - .iter() - .collect::(); - format!("…{tail}") -} - -fn provenance_label(provenance: CommandProvenance) -> &'static str { - match provenance { - CommandProvenance::UserInput => "user", - CommandProvenance::SlashCommand => "slash", - CommandProvenance::ApprovalEscalation => "approval", - CommandProvenance::AiSuggestion => "ai", - } -} - -fn command_status_color(status: CommandStatus) -> ratatui::style::Color { - match status { - CommandStatus::PendingReview | CommandStatus::PendingApproval => theme::WARN, - CommandStatus::Queued | CommandStatus::Running => theme::INFO, - CommandStatus::Succeeded => theme::SUCCESS, - CommandStatus::Failed | CommandStatus::Denied => theme::ERROR, - CommandStatus::Cancelled => theme::TEXT_SUBTLE, - } -} - -fn command_status_label(status: CommandStatus) -> &'static str { - match status { - CommandStatus::PendingReview => "REVIEW", - CommandStatus::PendingApproval => "PENDING", - CommandStatus::Queued => "QUEUED", - CommandStatus::Running => "RUNNING", - CommandStatus::Succeeded => "DONE", - CommandStatus::Failed => "FAILED", - CommandStatus::Cancelled => "CANCELLED", - CommandStatus::Denied => "DENIED", - } -} - -fn editor_header_lines( - mode_label: &str, - mode_color: ratatui::style::Color, - slash_mode: bool, - ai_mode: bool, - input_empty: bool, - showing_suggestions: bool, -) -> Vec> { - vec![ - Line::from(vec![ - Span::styled(format!(" {mode_label} "), theme::status_badge(mode_color)), - Span::raw(" "), - Span::styled( - if slash_mode { - "Search Forge actions without leaving the command deck." - } else if ai_mode { - "Ask Forge with live repo and runtime context." - } else { - "Run commands directly in the current shell." - }, - theme::muted(), - ), - ]), - Line::from(vec![Span::styled( - if showing_suggestions { - "Arrow keys move the selector. Tab inserts. Enter runs immediately." - } else if input_empty { - "Pinned input keeps you oriented. Press / for actions or F2 to change modes." - } else { - "Multiline input is supported. History stays scoped to the current mode." - }, - theme::subtle(), - )]), - ] -} - -fn suggestion_lines( - suggestions: &[(bool, &SlashCommandSpec)], - summary_width: usize, -) -> Vec> { - let mut lines = vec![ - Line::from(vec![ - Span::styled(" Slash Actions ", theme::quiet_badge()), - Span::raw(" "), - Span::styled("Tab inserts the selected action", theme::subtle()), - ]), - Line::raw(""), - ]; - - for (selected, suggestion) in suggestions { - lines.push(Line::from(vec![ - Span::styled( - if *selected { "▶ " } else { " " }, - if *selected { - theme::accent() - } else { - theme::subtle() - }, - ), - Span::styled( - format!("{:<18}", suggestion.usage), - theme::command_palette_item(*selected), - ), - Span::raw(" "), - Span::styled( - truncate_multiline(suggestion.summary, summary_width.max(12)), - theme::command_palette_summary(*selected), - ), - ])); - } - - lines -} - -fn console_footer_line(mode_label: &'static str) -> Line<'static> { - Line::from(vec![ - Span::styled("mode", theme::label()), - Span::raw(" "), - Span::styled(mode_label, theme::primary()), - Span::raw(" "), - Span::styled("F2", theme::keycap()), - Span::styled(" cycle", theme::muted()), - Span::raw(" "), - Span::styled("Ctrl+P/N", theme::keycap()), - Span::styled(" history", theme::muted()), - Span::raw(" "), - Span::styled("Ctrl+J", theme::keycap()), - Span::styled(" newline", theme::muted()), - ]) -} - -fn editor_gutter_label(mode_label: &str) -> &'static str { - match mode_label { - "SHELL" => "shell", - "AI" => "assist", - "DIAG" => "diagnose", - "SLASH" => "slash", - _ => "input", - } -} - -fn editor_prompt_symbol(mode: crate::domain::InputMode, slash_mode: bool) -> &'static str { - if slash_mode { - "/" - } else { - match mode { - crate::domain::InputMode::Shell => "$", - crate::domain::InputMode::AiAssist | crate::domain::InputMode::AiDiagnose => ">", - } - } -} diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index acac791..aed681f 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -10,11 +10,11 @@ use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { let block = Block::default() - .title(Span::styled(" Operations ", theme::panel_title(focused))) - .borders(Borders::ALL) + .title(Span::styled(" operations ", theme::panel_title(focused))) + .borders(Borders::LEFT) .border_style(theme::pane_border(focused)) .style(theme::panel_surface(focused)) - .padding(Padding::horizontal(1)); + .padding(Padding::new(2, 2, 1, 1)); let inner = block.inner(area); frame.render_widget(block, area); diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index d6aecbd..a563a49 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -1,111 +1,78 @@ use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; +use ratatui::widgets::Paragraph; use ratatui::Frame; -use crate::domain::{AppState, TimelineKind}; -use crate::shared::time::format_timestamp; +use crate::domain::AppState; use crate::ui::theme; -pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { - let lines = build_timeline_lines(state, area.height.saturating_sub(2) as usize); +pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: bool) { + let latest = state + .timeline + .entries + .iter() + .rev() + .next() + .map(|e| truncate_end(&e.message, 60)) + .unwrap_or_else(|| "quiet — waiting on you".to_string()); + let count = state.timeline.entries.len(); - frame.render_widget( - Paragraph::new(lines) - .block( - Block::default() - .title(Span::styled(" Activity ", theme::panel_title(focused))) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)) - .style(theme::panel_surface(focused)) - .padding(Padding::horizontal(1)), - ) - .wrap(Wrap { trim: false }), - area, - ); -} + let left_spans = vec![ + Span::raw(" "), + Span::styled("▸ ", theme::subtle()), + Span::styled(latest, theme::muted()), + Span::styled(format!(" · {count}"), theme::subtle()), + ]; -fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { - let mut collapsed: Vec = Vec::new(); + let right_spans = vec![ + Span::styled(" Tab ", theme::keycap()), + Span::styled(" ops", theme::muted()), + Span::raw(" "), + Span::styled(" Ctrl+L ", theme::keycap()), + Span::styled(" activity", theme::muted()), + Span::raw(" "), + Span::styled(" / ", theme::keycap()), + Span::styled(" commands", theme::muted()), + Span::raw(" "), + Span::styled(" F2 ", theme::keycap()), + Span::styled(" mode", theme::muted()), + Span::raw(" "), + ]; - for entry in state.timeline.entries.iter().rev() { - if let Some(last) = collapsed.last_mut() { - if last.kind == entry.kind && last.message == entry.message { - last.count += 1; - last.last_seen = entry.at; - continue; - } - } - collapsed.push(CollapsedEntry { - at: entry.at, - last_seen: entry.at, - kind: entry.kind, - message: entry.message.clone(), - count: 1, - }); - if collapsed.len() >= limit { - break; - } - } + let mid = area.width / 2; + let left_area = Rect { + x: area.x, + y: area.y, + width: mid, + height: 1, + }; + let right_area = Rect { + x: area.x + mid, + y: area.y, + width: area.width.saturating_sub(mid), + height: 1, + }; - if collapsed.is_empty() { - return vec![ - Line::from(vec![Span::styled( - "No activity yet.", - theme::primary(), - )]), - Line::from(vec![Span::styled( - "Commands, approvals, AI work, and log bursts will leave a compact audit trail here.", - theme::muted(), - )]), - ]; - } - - collapsed - .into_iter() - .map(|entry| { - let kind = match entry.kind { - TimelineKind::System => "SYSTEM", - TimelineKind::Ai => "AI", - TimelineKind::Command => "COMMAND", - TimelineKind::Log => "LOG", - TimelineKind::Approval => "APPROVAL", - TimelineKind::Error => "ERROR", - }; - let mut spans = vec![ - Span::styled(format!("{} ", format_timestamp(entry.at)), theme::subtle()), - Span::styled( - format!(" {kind} "), - theme::status_badge(theme::timeline_color(entry.kind)), - ), - Span::raw(" "), - Span::styled(truncate_end(&entry.message, 92), theme::primary()), - ]; - if entry.count > 1 { - spans.push(Span::raw(" ")); - spans.push(Span::styled(format!("×{}", entry.count), theme::muted())); - } - Line::from(spans) - }) - .collect() + frame.render_widget( + Paragraph::new(Line::from(left_spans)).style(theme::chrome_surface()), + left_area, + ); + frame.render_widget( + Paragraph::new(Line::from(right_spans)) + .alignment(ratatui::layout::Alignment::Right) + .style(theme::chrome_surface()), + right_area, + ); } fn truncate_end(value: &str, max_chars: usize) -> String { - if value.chars().count() <= max_chars { - return value.to_string(); + let joined = value.lines().collect::>().join(" "); + if joined.chars().count() <= max_chars { + return joined; } - - let kept = value + let kept = joined .chars() .take(max_chars.saturating_sub(1)) .collect::(); format!("{kept}…") } - -struct CollapsedEntry { - at: std::time::SystemTime, - last_seen: std::time::SystemTime, - kind: TimelineKind, - message: String, - count: usize, -} diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index 64fd04c..f06a38e 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -17,40 +17,41 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { let layout = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(2), - Constraint::Min(12), - Constraint::Length(state.config.ui.event_stream_height), + Constraint::Length(1), // minimal top bar + Constraint::Min(8), // main stage + Constraint::Length(1), // bottom rail (collapsed activity + hints) ]) .split(frame.area()); status_bar::render(frame, layout[0], state); - let main = Layout::default() - .direction(Direction::Horizontal) - .constraints([ - Constraint::Percentage(state.config.ui.main_split_pct), - Constraint::Percentage(100 - state.config.ui.main_split_pct), - ]) - .spacing(1) - .split(layout[1]); - - command_pane::render( - frame, - main[0], - state, - matches!(state.ui.focus, FocusTarget::CommandPane), - ); - dashboard::render( - frame, - main[1], - state, - matches!(state.ui.focus, FocusTarget::DashboardPane), - ); - event_stream::render( - frame, - layout[2], - state, - matches!(state.ui.focus, FocusTarget::EventStream), + let ops_open = matches!( + state.ui.focus, + FocusTarget::DashboardPane | FocusTarget::EventStream ); + + if ops_open { + // Drawer-over-prompt layout: left 48% dimmed prompt, right 52% ops. + let main = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Percentage(48), Constraint::Percentage(52)]) + .split(layout[1]); + command_pane::render(frame, main[0], state, false); + dashboard::render( + frame, + main[1], + state, + matches!(state.ui.focus, FocusTarget::DashboardPane), + ); + } else { + command_pane::render( + frame, + layout[1], + state, + matches!(state.ui.focus, FocusTarget::CommandPane), + ); + } + + event_stream::render(frame, layout[2], state, false); modal::render(frame, state); } diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index 4d4a5c4..bdc2cd9 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -1,10 +1,9 @@ -use ratatui::layout::{Constraint, Direction, Layout, Rect}; +use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Paragraph}; +use ratatui::widgets::Paragraph; use ratatui::Frame; -use crate::commands::slash_palette_active; -use crate::domain::{AiStatus, AppState, FocusTarget, ModalState}; +use crate::domain::AppState; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { @@ -20,35 +19,85 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { .unwrap_or_else(|| "------".to_string()); let dirty = if state.git.is_dirty { "dirty" } else { "clean" }; - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(1), Constraint::Length(1)]) - .split(area); + let project = truncate_end(&state.project.name, 18); + + let running = state + .services + .registry + .iter() + .filter(|s| { + matches!( + s.health, + crate::domain::ServiceHealth::Healthy + | crate::domain::ServiceHealth::Starting + | crate::domain::ServiceHealth::Degraded + ) + }) + .count(); + + let left = vec![ + Span::raw(" "), + Span::styled("forge", theme::italic_serif()), + Span::styled(" / ", theme::subtle()), + Span::styled(project, theme::muted()), + Span::styled(" / ", theme::subtle()), + Span::styled(truncate_middle(&branch, 22), theme::muted()), + ]; - frame.render_widget( - Block::default() - .borders(Borders::BOTTOM) - .border_style(theme::pane_border(false)) - .style(theme::chrome_surface()), - area, - ); + let mut right: Vec> = Vec::new(); + if running > 0 { + right.push(Span::styled("●", theme::accent())); + right.push(Span::raw(" ")); + right.push(Span::styled( + format!("{running} running"), + theme::primary(), + )); + right.push(Span::styled(" · ", theme::subtle())); + } + right.push(Span::styled( + dirty, + if state.git.is_dirty { + theme::warn_accent() + } else { + theme::muted() + }, + )); + right.push(Span::styled(" · ", theme::subtle())); + right.push(Span::styled(truncate_end(&head, 8), theme::subtle())); + right.push(Span::raw(" ")); + + let mut spans = left; + spans.extend(right); + + // Two paragraphs: left-aligned + right-aligned — split area in half. + let mid = area.width / 2; + let left_area = Rect { + x: area.x, + y: area.y, + width: mid, + height: 1, + }; + let right_area = Rect { + x: area.x + mid, + y: area.y, + width: area.width.saturating_sub(mid), + height: 1, + }; - let row1 = Layout::default() - .direction(Direction::Horizontal) - .constraints([Constraint::Min(36), Constraint::Length(42)]) - .split(rows[0]); + // Extract left portion from our combined spans — actually we built them separately + let left_spans = spans[..6].to_vec(); + let right_spans = spans[6..].to_vec(); frame.render_widget( - Paragraph::new(primary_identity_line(state, &branch)), - row1[0], + Paragraph::new(Line::from(left_spans)).style(theme::chrome_surface()), + left_area, ); frame.render_widget( - Paragraph::new(status_summary_line(state, dirty, &head)) - .alignment(ratatui::layout::Alignment::Right), - row1[1], + Paragraph::new(Line::from(right_spans)) + .alignment(ratatui::layout::Alignment::Right) + .style(theme::chrome_surface()), + right_area, ); - - frame.render_widget(Paragraph::new(contextual_hint_line(state)), rows[1]); } fn truncate_end(value: &str, max_chars: usize) -> String { @@ -79,197 +128,3 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { .collect::(); format!("{start}…{end}") } - -fn contextual_hint_line(state: &AppState) -> Line<'static> { - let mut spans = vec![ - Span::styled( - format!(" {} ", active_surface_label(state)), - if state.ui.modal.is_some() { - theme::focus_badge() - } else { - match state.ui.focus { - FocusTarget::CommandPane => theme::focus_badge(), - FocusTarget::DashboardPane | FocusTarget::EventStream => theme::quiet_badge(), - FocusTarget::Modal => theme::focus_badge(), - } - }, - ), - Span::raw(" "), - ]; - - let mut hint_spans = match state.ui.modal.as_ref() { - Some(ModalState::Approval(_)) => vec![ - Span::styled("Enter", theme::keycap()), - Span::styled(" approve", theme::muted()), - Span::raw(" "), - Span::styled("Esc", theme::keycap()), - Span::styled(" deny", theme::muted()), - Span::raw(" "), - Span::styled("/help", theme::accent()), - Span::styled(" commands", theme::muted()), - ], - Some(ModalState::Help) | Some(ModalState::Error(_)) => vec![ - Span::styled("Esc", theme::accent()), - Span::styled(" close", theme::muted()), - Span::raw(" "), - Span::styled("Enter", theme::accent()), - Span::styled(" dismiss", theme::muted()), - ], - None => match state.ui.focus { - FocusTarget::CommandPane => { - if slash_palette_active(&state.ui.input.buffer) { - vec![ - Span::styled("↑/↓", theme::keycap()), - Span::styled(" choose", theme::muted()), - Span::raw(" "), - Span::styled("Tab", theme::keycap()), - Span::styled(" insert", theme::muted()), - Span::raw(" "), - Span::styled("Enter", theme::keycap()), - Span::styled(" run", theme::muted()), - ] - } else { - vec![ - Span::styled("Enter", theme::keycap()), - Span::styled(" run", theme::muted()), - Span::raw(" "), - Span::styled("/", theme::keycap()), - Span::styled(" commands", theme::muted()), - Span::raw(" "), - Span::styled("F2", theme::keycap()), - Span::styled(" mode", theme::muted()), - Span::raw(" "), - Span::styled("Ctrl+P/N", theme::keycap()), - Span::styled(" history", theme::muted()), - Span::raw(" "), - Span::styled("Ctrl+J", theme::keycap()), - Span::styled(" newline", theme::muted()), - ] - } - } - FocusTarget::DashboardPane => vec![ - Span::styled("Left/Right", theme::keycap()), - Span::styled(" switch tabs", theme::muted()), - Span::raw(" "), - Span::styled("Tab", theme::keycap()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("/", theme::keycap()), - Span::styled(" commands", theme::muted()), - ], - FocusTarget::EventStream => vec![ - Span::styled("Tab", theme::keycap()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("/", theme::keycap()), - Span::styled(" commands", theme::muted()), - ], - FocusTarget::Modal => vec![ - Span::styled("Esc", theme::keycap()), - Span::styled(" close", theme::muted()), - ], - }, - }; - - spans.append(&mut hint_spans); - Line::from(spans) -} - -fn primary_identity_line(state: &AppState, branch: &str) -> Line<'static> { - Line::from(vec![ - Span::styled(" FORGE ", theme::brand_badge()), - Span::raw(" "), - Span::styled( - truncate_end(&state.project.name, 20), - theme::primary_emphasis(), - ), - Span::styled(" / ", theme::subtle()), - Span::styled(truncate_middle(branch, 32), theme::muted()), - ]) -} - -fn status_summary_line(state: &AppState, dirty: &str, head: &str) -> Line<'static> { - let input_mode = state.ui.input.mode.label().to_ascii_lowercase(); - let ai_status = match state.ai.status { - AiStatus::Disabled => "ai off", - AiStatus::Unconfigured => "ai setup", - AiStatus::Ready => "ai ready", - AiStatus::Queued => "ai queued", - AiStatus::Running => "ai running", - AiStatus::Completed => "ai done", - AiStatus::Failed => "ai error", - }; - - let mut spans = vec![ - Span::styled( - format!(" {} ", dirty), - if state.git.is_dirty { - theme::status_badge(theme::WARN) - } else { - theme::quiet_badge() - }, - ), - Span::raw(" "), - Span::styled(format!(" {} ", input_mode), theme::quiet_badge()), - Span::raw(" "), - Span::styled(format!(" {} ", ai_status), ai_status_style(state.ai.status)), - ]; - - if !state.approvals.pending.is_empty() { - spans.push(Span::raw(" ")); - spans.push(Span::styled( - format!(" {} pending ", state.approvals.pending.len()), - theme::status_badge(theme::WARN), - )); - } - - if state.ui.modal.is_some() { - spans.push(Span::raw(" ")); - spans.push(Span::styled(" review ", theme::status_badge(theme::WARN))); - } else if matches!( - state.ui.focus, - FocusTarget::DashboardPane | FocusTarget::EventStream - ) { - let focus_label = match state.ui.focus { - FocusTarget::DashboardPane => "dashboard", - FocusTarget::EventStream => "activity", - _ => "", - }; - spans.push(Span::raw(" ")); - spans.push(Span::styled( - format!(" {} ", focus_label), - theme::quiet_badge(), - )); - } - - spans.push(Span::raw(" ")); - spans.push(Span::styled("head", theme::label())); - spans.push(Span::raw(" ")); - spans.push(Span::styled(head.to_string(), theme::subtle())); - - Line::from(spans) -} - -fn ai_status_style(status: AiStatus) -> ratatui::style::Style { - match status { - AiStatus::Disabled => theme::quiet_badge(), - AiStatus::Unconfigured => theme::status_badge(theme::WARN), - AiStatus::Ready | AiStatus::Completed => theme::quiet_badge(), - AiStatus::Queued | AiStatus::Running => theme::status_badge(theme::INFO), - AiStatus::Failed => theme::status_badge(theme::ERROR), - } -} - -fn active_surface_label(state: &AppState) -> &'static str { - match state.ui.modal.as_ref() { - Some(ModalState::Approval(_)) => "review", - Some(ModalState::Help) => "help", - Some(ModalState::Error(_)) => "error", - None => match state.ui.focus { - FocusTarget::CommandPane => "command deck", - FocusTarget::DashboardPane => "operations", - FocusTarget::EventStream => "activity", - FocusTarget::Modal => "modal", - }, - } -} From e9e4031dcc59c5236a66220ffd5e100bdbfa5731 Mon Sep 17 00:00:00 2001 From: Bethvour Date: Mon, 20 Apr 2026 22:44:16 -0500 Subject: [PATCH 06/10] ui: tighten command pane layout and compact status bar context --- src/ui/views/command_pane.rs | 72 +++++++++++++++++++++++------------- src/ui/views/status_bar.rs | 34 ++++++++++++----- 2 files changed, 71 insertions(+), 35 deletions(-) diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index dea145e..1c3fe90 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -11,20 +11,25 @@ use crate::ui::theme; // Hero prompt — Prompt-First editorial layout. // Narrow content column centered in the available area. pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { - // Center a content column roughly 90 cells wide (clamped to area). - let column_w = area.width.min(96).max(40); - let pad = area.width.saturating_sub(column_w) / 2; - let column = Rect { - x: area.x + pad, - y: area.y + 1, - width: column_w, - height: area.height.saturating_sub(1), - }; + // Center a narrow content column (design: ~760px, i.e. ~60% of viewport). + let column_w = area.width.saturating_mul(60) / 100; + let column_w = column_w.clamp(48, 92); + let x_pad = area.width.saturating_sub(column_w) / 2; - let dim = !focused; + // Vertically center the hero group (headline + prompt + chips). + let running_items = running_items(state); let slash_suggestions = slash_command_suggestions(&state.ui.input.buffer); let visible_suggestions = visible_command_suggestions(&slash_suggestions, state); - let running_items = running_items(state); + + let headline_h: u16 = if state.ui.input.buffer.is_empty() { 2 } else { 0 }; + let prompt_h: u16 = 5; + let chips_h: u16 = if visible_suggestions.is_empty() + && !should_show_context_card(state) + { + 2 + } else { + 0 + }; let running_h: u16 = if running_items.is_empty() { 0 } else { @@ -41,32 +46,45 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool 0 }; + let group_h = running_h + headline_h + prompt_h + suggestion_h + context_h + chips_h; + let y_pad = area.height.saturating_sub(group_h) * 42 / 100; + + let column = Rect { + x: area.x + x_pad, + y: area.y + y_pad, + width: column_w, + height: area.height.saturating_sub(y_pad), + }; + + let dim = !focused; + let sections = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(if running_h == 0 { 2 } else { 0 }), // spacer Constraint::Length(running_h), - Constraint::Length(2), // headline - Constraint::Length(3), // prompt + Constraint::Length(headline_h), + Constraint::Length(prompt_h), Constraint::Length(suggestion_h), Constraint::Length(context_h), + Constraint::Length(chips_h), Constraint::Min(0), ]) .split(column); if running_h > 0 { - render_running_strip(frame, sections[1], &running_items); + render_running_strip(frame, sections[0], &running_items); } - - render_headline(frame, sections[2], state, dim); - render_prompt(frame, sections[3], state, dim); + if headline_h > 0 { + render_headline(frame, sections[1], state, dim); + } + render_prompt(frame, sections[2], state, dim); if suggestion_h > 0 { - render_suggestions(frame, sections[4], &visible_suggestions); + render_suggestions(frame, sections[3], &visible_suggestions); } else if context_h > 0 { - render_context_card(frame, sections[5], state); - } else { - render_recent_chips(frame, sections[6], state); + render_context_card(frame, sections[4], state); + } else if chips_h > 0 { + render_recent_chips(frame, sections[5], state); } } @@ -118,7 +136,7 @@ fn render_prompt(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: bool) theme::pane_border(true) }) .style(theme::panel_surface(!dim)) - .padding(Padding::horizontal(2)); + .padding(Padding::new(3, 3, 1, 1)); let inner = block.inner(area); frame.render_widget(block, area); @@ -442,7 +460,7 @@ fn render_recent_chips(frame: &mut Frame<'_>, area: Rect, state: &AppState) { if area.height == 0 { return; } - let recents: Vec = state + let mut recents: Vec = state .commands .records .iter() @@ -451,7 +469,11 @@ fn render_recent_chips(frame: &mut Frame<'_>, area: Rect, state: &AppState) { .map(|c| truncate(&c.raw, 24)) .collect(); if recents.is_empty() { - return; + recents = vec![ + "cargo run --debug".into(), + "git push origin main".into(), + "bg cargo test --watch".into(), + ]; } let mut spans: Vec> = vec![Span::styled(" recent ", theme::subtle())]; for r in recents { diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index bdc2cd9..75514b4 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -35,14 +35,27 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }) .count(); - let left = vec![ - Span::raw(" "), - Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), - Span::styled(project, theme::muted()), - Span::styled(" / ", theme::subtle()), - Span::styled(truncate_middle(&branch, 22), theme::muted()), - ]; + let short_branch = branch + .rsplit_once('/') + .map(|(_, tail)| tail.to_string()) + .unwrap_or_else(|| branch.clone()); + let left = if project.eq_ignore_ascii_case("forge") { + vec![ + Span::raw(" "), + Span::styled("forge", theme::italic_serif()), + Span::styled(" / ", theme::subtle()), + Span::styled(truncate_middle(&short_branch, 24), theme::muted()), + ] + } else { + vec![ + Span::raw(" "), + Span::styled("forge", theme::italic_serif()), + Span::styled(" / ", theme::subtle()), + Span::styled(project, theme::muted()), + Span::styled(" / ", theme::subtle()), + Span::styled(truncate_middle(&short_branch, 22), theme::muted()), + ] + }; let mut right: Vec> = Vec::new(); if running > 0 { @@ -66,6 +79,7 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { right.push(Span::styled(truncate_end(&head, 8), theme::subtle())); right.push(Span::raw(" ")); + let left_len = left.len(); let mut spans = left; spans.extend(right); @@ -85,8 +99,8 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }; // Extract left portion from our combined spans — actually we built them separately - let left_spans = spans[..6].to_vec(); - let right_spans = spans[6..].to_vec(); + let left_spans = spans[..left_len].to_vec(); + let right_spans = spans[left_len..].to_vec(); frame.render_widget( Paragraph::new(Line::from(left_spans)).style(theme::chrome_surface()), From 19699aa4e619825a4a53d87ecccb6a352589c06c Mon Sep 17 00:00:00 2001 From: Bethvour Date: Mon, 20 Apr 2026 23:24:30 -0500 Subject: [PATCH 07/10] ui: add intent suggestions and dashboard/status polish --- src/ui/keys.rs | 36 +++ src/ui/mod.rs | 1 + src/ui/views/command_pane.rs | 483 ++++++++++++++++++++++++++--------- src/ui/views/dashboard.rs | 379 ++++++++++++++++++++++++--- src/ui/views/event_stream.rs | 14 +- 5 files changed, 748 insertions(+), 165 deletions(-) create mode 100644 src/ui/keys.rs diff --git a/src/ui/keys.rs b/src/ui/keys.rs new file mode 100644 index 0000000..4533556 --- /dev/null +++ b/src/ui/keys.rs @@ -0,0 +1,36 @@ +// OS-aware keycap labels. Mac renders ⌘·⇧·⌃·⌥ glyphs; other platforms +// fall back to spelled-out "Ctrl" / "Shift" / "Alt" like standard CLI help. + +#[cfg(target_os = "macos")] +pub fn meta(key: &str) -> String { + format!("⌘{key}") +} + +#[cfg(not(target_os = "macos"))] +pub fn meta(key: &str) -> String { + format!("Ctrl+{key}") +} + +#[cfg(target_os = "macos")] +pub fn ctrl(key: &str) -> String { + format!("⌃{key}") +} + +#[cfg(not(target_os = "macos"))] +pub fn ctrl(key: &str) -> String { + format!("Ctrl+{key}") +} + +pub fn enter() -> &'static str { + "↵" +} + +#[cfg(target_os = "macos")] +pub fn up_meta() -> String { + "⌘↑".to_string() +} + +#[cfg(not(target_os = "macos"))] +pub fn up_meta() -> String { + "Ctrl+↑".to_string() +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs index a3af0b1..b730eb6 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1,3 +1,4 @@ +pub mod keys; pub mod terminal; pub mod theme; mod views; diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index 1c3fe90..283ede1 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -6,7 +6,16 @@ use ratatui::Frame; use crate::commands::{slash_command_suggestions, SlashCommandSpec}; use crate::domain::{AiStatus, AppState, ApprovalMode, InputMode}; -use crate::ui::theme; +use crate::shared::time::format_timestamp; +use crate::ui::{keys, theme}; + +// Intent suggestions shown while typing a non-slash command. +#[derive(Clone)] +struct IntentSuggestion { + mode: &'static str, // SHELL / BG / AI / HIST + cmd: String, + hint: String, +} // Hero prompt — Prompt-First editorial layout. // Narrow content column centered in the available area. @@ -19,11 +28,13 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool // Vertically center the hero group (headline + prompt + chips). let running_items = running_items(state); let slash_suggestions = slash_command_suggestions(&state.ui.input.buffer); - let visible_suggestions = visible_command_suggestions(&slash_suggestions, state); + let visible_slash = visible_command_suggestions(&slash_suggestions, state); + let intent_suggestions = intent_suggestions(state); let headline_h: u16 = if state.ui.input.buffer.is_empty() { 2 } else { 0 }; let prompt_h: u16 = 5; - let chips_h: u16 = if visible_suggestions.is_empty() + let chips_h: u16 = if visible_slash.is_empty() + && intent_suggestions.is_empty() && !should_show_context_card(state) { 2 @@ -35,13 +46,19 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool } else { (running_items.len() as u16) + 3 }; - let suggestion_h: u16 = if visible_suggestions.is_empty() { + let slash_h: u16 = if visible_slash.is_empty() { + 0 + } else { + (visible_slash.len() as u16) + 2 + }; + let intent_h: u16 = if intent_suggestions.is_empty() { 0 } else { - (visible_suggestions.len() as u16) + 2 + (intent_suggestions.len() as u16) + 2 }; + let suggestion_h = slash_h + intent_h; let context_h: u16 = if should_show_context_card(state) && suggestion_h == 0 { - 10 + 14 } else { 0 }; @@ -80,7 +97,11 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool render_prompt(frame, sections[2], state, dim); if suggestion_h > 0 { - render_suggestions(frame, sections[3], &visible_suggestions); + if slash_h > 0 { + render_slash_suggestions(frame, sections[3], &visible_slash); + } else { + render_intent_suggestions(frame, sections[3], &intent_suggestions); + } } else if context_h > 0 { render_context_card(frame, sections[4], state); } else if chips_h > 0 { @@ -191,35 +212,66 @@ fn render_prompt_text(buffer: &str, cursor: usize, width: usize) -> String { } fn render_running_strip(frame: &mut Frame<'_>, area: Rect, items: &[RunItem]) { - let mut lines = vec![ - Line::from(vec![Span::styled( - " RUNNING", - theme::subtle(), - )]), - Line::raw(""), - ]; - for it in items { - lines.push(Line::from(vec![ - Span::styled(" ● ", theme::accent()), - Span::styled( - format!("{:<8}", it.name), - theme::primary_emphasis(), - ), - Span::styled(format!(" {}", it.cmd), theme::muted()), - Span::styled(format!(" {}", it.meta), theme::subtle()), - ])); - } - lines.push(Line::raw("")); + // Heading row. + let heading = Rect { + x: area.x, + y: area.y, + width: area.width, + height: 1, + }; frame.render_widget( - Paragraph::new(lines).wrap(Wrap { trim: true }), - area, + Paragraph::new(Line::from(vec![Span::styled("RUNNING", theme::subtle())])), + heading, ); + + // One bordered row per running item. + let mut y = area.y + 2; + for it in items { + if y >= area.y + area.height { + break; + } + let row = Rect { + x: area.x, + y, + width: area.width, + height: 1, + }; + let block = Block::default() + .borders(Borders::ALL) + .border_style(theme::pane_border(false)) + .style(theme::panel_surface(false)); + // Draw a 3-cell tall framed row by overlaying inner text. + let framed = Rect { + x: area.x, + y, + width: area.width, + height: 1, + }; + let _ = (block, framed); + let meta = format!( + "pid {} · {} · {}", + it.pid.as_deref().unwrap_or("—"), + it.uptime, + it.port.as_deref().unwrap_or("—"), + ); + let spans = vec![ + Span::styled("● ", theme::accent()), + Span::styled(format!("{:<8}", it.name), theme::primary_emphasis()), + Span::styled(format!(" {}", truncate(&it.cmd, 40)), theme::muted()), + Span::styled(format!(" {}", meta), theme::subtle()), + Span::styled(" logs ↗", theme::subtle()), + ]; + frame.render_widget(Paragraph::new(Line::from(spans)), row); + y += 1; + } } struct RunItem { name: String, cmd: String, - meta: String, + pid: Option, + uptime: String, + port: Option, } fn running_items(state: &AppState) -> Vec { @@ -235,38 +287,53 @@ fn running_items(state: &AppState) -> Vec { ) }) .take(3) - .map(|s| RunItem { - name: s.name.clone(), - cmd: if s.ports.is_empty() { - format!("{:?}", s.source).to_lowercase() - } else { - format!( - "{} · :{}", - format!("{:?}", s.source).to_lowercase(), - s.ports - .iter() - .map(u16::to_string) - .collect::>() - .join(",") - ) - }, - meta: format!("pid {}", s.pid.map(|p| p.to_string()).unwrap_or_default()), + .map(|s| { + let uptime = s + .last_seen + .elapsed() + .map(|d| { + let secs = d.as_secs(); + if secs < 60 { + format!("{secs}s") + } else if secs < 3600 { + format!("{}m {}s", secs / 60, secs % 60) + } else { + format!("{}h {}m", secs / 3600, (secs % 3600) / 60) + } + }) + .unwrap_or_else(|_| "—".to_string()); + let port = s.ports.first().map(|p| format!(":{p}")); + let cmd = state + .commands + .records + .iter() + .find(|c| Some(c.id) == s.linked_command) + .map(|c| c.raw.clone()) + .unwrap_or_else(|| format!("{:?} service", s.source).to_lowercase()); + RunItem { + name: s.name.clone(), + cmd, + pid: s.pid.map(|p| p.to_string()), + uptime, + port, + } }) .collect() } -fn render_suggestions( +fn render_slash_suggestions( frame: &mut Frame<'_>, area: Rect, suggestions: &[(bool, &SlashCommandSpec)], ) { - let mut lines = vec![Line::from(vec![Span::styled( - " SUGGESTIONS", - theme::subtle(), - )])]; + let mut lines = vec![ + Line::from(vec![Span::styled("SUGGESTIONS", theme::subtle())]), + Line::raw(""), + ]; + let width = area.width as usize; for (selected, spec) in suggestions { - let mode_pill = Span::styled( - " slash ", + let pill = Span::styled( + " SLASH ", if *selected { theme::focus_badge() } else { @@ -278,18 +345,109 @@ fn render_suggestions( } else { theme::muted() }; - lines.push(Line::from(vec![ + let hint = truncate(spec.summary, 28); + let cmd_text = format!("{:<22}", truncate(spec.usage, 22)); + let used = 1 + 7 + 2 + 22 + 2 + hint.chars().count(); + let spacer = " ".repeat(width.saturating_sub(used).saturating_sub(6)); + let mut spans = vec![ + Span::raw(" "), + pill, Span::raw(" "), - mode_pill, + Span::styled(cmd_text, cmd_style), Span::raw(" "), - Span::styled(format!("{:<22}", spec.usage), cmd_style), - Span::styled(format!(" {}", spec.summary), theme::subtle()), - ])); + Span::styled(hint, theme::subtle()), + Span::raw(spacer), + ]; + if *selected { + spans.push(Span::styled(format!(" {} ", keys::enter()), theme::keycap())); + } + lines.push(Line::from(spans)); } - frame.render_widget( - Paragraph::new(lines).wrap(Wrap { trim: true }), - area, - ); + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); +} + +fn render_intent_suggestions(frame: &mut Frame<'_>, area: Rect, items: &[IntentSuggestion]) { + let mut lines = vec![ + Line::from(vec![Span::styled("SUGGESTIONS", theme::subtle())]), + Line::raw(""), + ]; + let width = area.width as usize; + for (i, it) in items.iter().enumerate() { + let selected = i == 0; + let pill_style = if selected { + theme::focus_badge() + } else { + theme::quiet_badge() + }; + let pill_text = format!(" {:<5}", it.mode); + let cmd_style = if selected { + theme::primary_emphasis() + } else { + theme::muted() + }; + let cmd_text = truncate(&it.cmd, 32); + let hint = truncate(&it.hint, 30); + let used = 1 + pill_text.chars().count() + 2 + cmd_text.chars().count() + 2 + hint.chars().count(); + let spacer = " ".repeat(width.saturating_sub(used).saturating_sub(6)); + let mut spans = vec![ + Span::raw(" "), + Span::styled(pill_text, pill_style), + Span::raw(" "), + Span::styled(cmd_text, cmd_style), + Span::raw(spacer), + Span::styled(hint, theme::subtle()), + Span::raw(" "), + ]; + if selected { + spans.push(Span::styled(format!(" {} ", keys::enter()), theme::keycap())); + } + lines.push(Line::from(spans)); + } + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); +} + +fn intent_suggestions(state: &AppState) -> Vec { + let buf = state.ui.input.buffer.trim(); + if buf.is_empty() || buf.starts_with('/') { + return Vec::new(); + } + if state.ui.input.mode.ai_kind().is_some() { + return Vec::new(); + } + + let mut out = vec![ + IntentSuggestion { + mode: "SHELL", + cmd: truncate(buf, 60), + hint: "run in current shell".into(), + }, + IntentSuggestion { + mode: "BG", + cmd: format!("bg {}", truncate(buf, 56)), + hint: "manage as long-lived service".into(), + }, + IntentSuggestion { + mode: "AI", + cmd: format!("ai: what does {} do", truncate(buf.split_whitespace().next().unwrap_or(buf), 40)), + hint: "ask the assistant".into(), + }, + ]; + + if let Some(hist) = state + .commands + .records + .iter() + .rev() + .find(|c| c.raw.starts_with(buf) && c.raw != buf) + { + out.push(IntentSuggestion { + mode: "HIST", + cmd: truncate(&hist.raw, 60), + hint: "from history".into(), + }); + } + + out } fn should_show_context_card(state: &AppState) -> bool { @@ -314,32 +472,70 @@ fn should_show_context_card(state: &AppState) -> bool { } fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let (title, body) = build_context_card(state); + // AI cards use a left-accent border; everything else uses a hairline all-around box. + let is_ai = state.ui.input.mode.ai_kind().is_some() + || matches!( + state.ai.status, + AiStatus::Running | AiStatus::Queued | AiStatus::Failed | AiStatus::Completed + ); + let (header_spans, body, footer_hint) = build_context_card(state); + let borders = if is_ai { + Borders::LEFT + } else { + Borders::ALL + }; let block = Block::default() - .borders(Borders::LEFT) - .border_style(theme::pane_border(true)) + .borders(borders) + .border_style(if is_ai { + theme::accent() + } else { + theme::pane_border(false) + }) .style(theme::panel_surface(false)) .padding(Padding::new(2, 2, 1, 1)); let inner = block.inner(area); frame.render_widget(block, area); - let mut lines = vec![Line::from(vec![Span::styled(title, theme::subtle())])]; + let mut lines = vec![Line::from(header_spans)]; lines.push(Line::raw("")); lines.extend(body); frame.render_widget( Paragraph::new(lines).wrap(Wrap { trim: false }), inner, ); + + // Hint line below the card (only when there is vertical room). + if let Some(hint) = footer_hint { + if area.y + area.height + 1 < area.y + area.height { + return; + } + let hint_rect = Rect { + x: area.x + 2, + y: area.y + area.height, + width: area.width.saturating_sub(2), + height: 1, + }; + frame.render_widget(Paragraph::new(hint), hint_rect); + } } -fn build_context_card(state: &AppState) -> (String, Vec>) { +fn build_context_card( + state: &AppState, +) -> (Vec>, Vec>, Option>) { if let Some(approval) = state .approvals .pending .iter() .find(|r| matches!(r.mode, ApprovalMode::InlineReview)) { - let title = format!("REVIEW · #{}", approval.command_id); + let header = vec![ + Span::styled( + format!(" REVIEW · #{} ", approval.command_id), + theme::status_badge(theme::WARN), + ), + Span::raw(" "), + Span::styled(approval.class.label().to_string(), theme::subtle()), + ]; let body = vec![ Line::from(vec![Span::styled( approval.summary.clone(), @@ -350,15 +546,14 @@ fn build_context_card(state: &AppState) -> (String, Vec>) { truncate(&approval.detail, 280), theme::muted(), )]), - Line::raw(""), - Line::from(vec![ - Span::styled(" Enter ", theme::keycap()), - Span::styled(" approve ", theme::muted()), - Span::styled(" Esc ", theme::keycap()), - Span::styled(" deny", theme::muted()), - ]), ]; - return (title, body); + let footer = Line::from(vec![ + Span::styled(format!(" {} ", keys::enter()), theme::keycap()), + Span::styled(" approve ", theme::muted()), + Span::styled(" Esc ", theme::keycap()), + Span::styled(" deny", theme::muted()), + ]); + return (header, body, Some(footer)); } if state.ui.input.mode.ai_kind().is_some() @@ -377,82 +572,138 @@ fn build_context_card(state: &AppState) -> (String, Vec>) { .model .clone() .unwrap_or_else(|| "default".to_string()); - let label = match state.ai.status { - AiStatus::Disabled => "AI · off", - AiStatus::Unconfigured => "AI · setup required", - AiStatus::Ready => "AI · ready", - AiStatus::Queued => "AI · queued", - AiStatus::Running => "AI · streaming…", - AiStatus::Completed => "AI · complete", - AiStatus::Failed => "AI · error", + let right_label = match state.ai.status { + AiStatus::Running | AiStatus::Queued => "streaming…", + AiStatus::Failed => "error", + AiStatus::Completed => "done", + _ => "", }; - let mut body = vec![Line::from(vec![ - Span::styled(format!("{provider} "), theme::muted()), - Span::styled(format!("model {model}"), theme::subtle()), - ])]; + let header = vec![ + Span::styled(" AI ", theme::focus_badge()), + Span::raw(" "), + Span::styled( + format!("{} · model {}", provider, model), + theme::subtle(), + ), + Span::raw(" "), + Span::styled(right_label, theme::subtle()), + ]; + + let mut body: Vec> = Vec::new(); if let Some(err) = state.ai.last_error.as_ref() { - body.push(Line::raw("")); body.push(Line::from(vec![Span::styled( - truncate(err, 240), + truncate(err, 300), theme::error_accent(), )])); } else if let Some(resp) = state.ai.last_response.as_ref() { - body.push(Line::raw("")); + // Big serif italic opener from summary. body.push(Line::from(vec![Span::styled( - truncate(&resp.summary, 240), + truncate(&resp.summary, 160), theme::italic_serif(), )])); - if !resp.recommendations.is_empty() || !resp.proposals.is_empty() { + if !resp.recommendations.is_empty() { + body.push(Line::raw("")); + for (i, rec) in resp.recommendations.iter().take(3).enumerate() { + body.push(Line::from(vec![ + Span::styled( + format!("{}. ", i + 1), + theme::subtle(), + ), + Span::styled(truncate(rec, 220), theme::muted()), + ])); + } + } + if !resp.proposals.is_empty() { body.push(Line::raw("")); + // dashed divider body.push(Line::from(vec![Span::styled( - format!( - "{} recommendation(s) · {} proposal(s)", - resp.recommendations.len(), - resp.proposals.len() - ), + "─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─", theme::subtle(), )])); + body.push(Line::raw("")); + let mut chips: Vec> = + vec![Span::styled("suggested actions ", theme::subtle())]; + for p in resp.proposals.iter().take(3) { + chips.push(Span::styled( + format!(" ▸ {} ", truncate(&p.summary, 22)), + theme::accent(), + )); + chips.push(Span::raw(" ")); + } + body.push(Line::from(chips)); } } else if let Some(req) = state.ai.requests.last() { - body.push(Line::raw("")); body.push(Line::from(vec![Span::styled( truncate(&req.prompt, 240), theme::muted(), )])); + } else { + body.push(Line::from(vec![Span::styled( + "Ask Forge with live repo and runtime context.", + theme::muted(), + )])); } - return (label.to_string(), body); + + let footer = Line::from(vec![ + Span::styled(format!(" {} ", keys::enter()), theme::keycap()), + Span::styled(" apply first action ", theme::muted()), + Span::styled(" Esc ", theme::keycap()), + Span::styled(" dismiss ", theme::muted()), + Span::styled(format!(" {} ", keys::up_meta()), theme::keycap()), + Span::styled(" revise question", theme::muted()), + ]); + return (header, body, Some(footer)); } if let Some(cmd) = state.commands.records.last() { - let title = format!( - "LAST RUN · #{} {}", - cmd.id, - status_label(cmd.status) - ); - let body = vec![ - Line::from(vec![Span::styled( - truncate(&cmd.raw, 200), - theme::primary_emphasis(), - )]), - Line::raw(""), - Line::from(vec![Span::styled( + let when_src = cmd + .started_at + .or(cmd.ended_at) + .unwrap_or_else(crate::shared::time::now_utc); + let when = format_timestamp(when_src); + let exit = cmd + .exit_code + .map(|c| format!("exit {c}")) + .unwrap_or_else(|| status_label(cmd.status).to_string()); + let header = vec![ + Span::styled( + format!("LAST RUN · {}", truncate(&cmd.raw, 32).to_uppercase()), + theme::subtle(), + ), + Span::raw(" "), + Span::styled(format!("{when} · {exit}"), theme::subtle()), + ]; + let body = if let Some(output) = state + .logs + .recent + .iter() + .rev() + .find(|e| e.command_id == Some(cmd.id)) + { + vec![Line::from(vec![Span::styled( + truncate(&output.raw, 260), + theme::muted(), + )])] + } else { + vec![Line::from(vec![Span::styled( format!( "{} · {}", cmd.safety_class.label(), cmd.cwd.display() ), - theme::subtle(), - )]), - ]; - return (title, body); + theme::muted(), + )])] + }; + return (header, body, None); } ( - "READY".to_string(), + vec![Span::styled("READY", theme::subtle())], vec![Line::from(vec![Span::styled( "Shell is quiet. Press / for commands or F2 to switch modes.", theme::muted(), )])], + None, ) } diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index aed681f..8161674 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -9,43 +9,295 @@ use crate::shared::time::format_timestamp; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { + // Outer drawer surface with subtle left hairline. let block = Block::default() - .title(Span::styled(" operations ", theme::panel_title(focused))) .borders(Borders::LEFT) .border_style(theme::pane_border(focused)) .style(theme::panel_surface(focused)) - .padding(Padding::new(2, 2, 1, 1)); + .padding(Padding::new(3, 3, 1, 1)); let inner = block.inner(area); frame.render_widget(block, area); let sections = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(2), - Constraint::Length(2), - Constraint::Min(8), + Constraint::Length(2), // drawer header + Constraint::Length(2), // tabs + Constraint::Length(1), // tab underline / spacer + Constraint::Min(6), // content + Constraint::Length(3), // footer hint ]) .split(inner); - render_overview(frame, sections[0], state); + render_drawer_header(frame, sections[0]); render_tabs(frame, sections[1], state); + render_tabs_separator(frame, sections[2]); - let lines = match state.ui.dashboard_tab { - DashboardTab::Services => services_lines(state), - DashboardTab::Processes => processes_lines(state), - DashboardTab::Logs => log_lines(state), - DashboardTab::Git => git_lines(state), - DashboardTab::Tests => test_lines(state), - }; + match state.ui.dashboard_tab { + DashboardTab::Services => render_services(frame, sections[3], state), + DashboardTab::Processes => render_lines(frame, sections[3], processes_lines(state)), + DashboardTab::Logs => render_lines(frame, sections[3], log_lines(state)), + DashboardTab::Git => render_lines(frame, sections[3], git_lines(state)), + DashboardTab::Tests => render_lines(frame, sections[3], test_lines(state)), + } + + render_drawer_footer(frame, sections[4], state); +} +fn render_lines(frame: &mut Frame<'_>, area: Rect, lines: Vec>) { frame.render_widget( Paragraph::new(lines) .block(Block::default()) .wrap(Wrap { trim: false }), - sections[2], + area, + ); +} + +fn render_drawer_header(frame: &mut Frame<'_>, area: Rect) { + let mid = area.width / 2; + let left = Rect { + x: area.x, + y: area.y, + width: mid, + height: 1, + }; + let right = Rect { + x: area.x + mid, + y: area.y, + width: area.width.saturating_sub(mid), + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled( + "operations", + theme::italic_serif(), + )])), + left, + ); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled(" Esc ", theme::keycap()), + Span::styled(" close", theme::muted()), + ])) + .alignment(ratatui::layout::Alignment::Right), + right, ); } +fn render_tabs_separator(frame: &mut Frame<'_>, area: Rect) { + // Render a hairline under the tab row. + let line = "─".repeat(area.width as usize); + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled(line, theme::subtle())])), + area, + ); +} + +fn render_services(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + if state.services.registry.is_empty() { + let lines = vec![ + Line::raw(""), + Line::from(vec![Span::styled( + "No managed services yet.", + theme::muted(), + )]), + Line::raw(""), + Line::from(vec![ + Span::styled("Launch one with ", theme::subtle()), + Span::styled("/bg cargo run", theme::accent()), + Span::styled(" or any shell command that ends with ", theme::subtle()), + Span::styled("&", theme::accent()), + Span::styled(".", theme::subtle()), + ]), + ]; + render_lines(frame, area, lines); + return; + } + + let mut y = area.y; + for (i, s) in state.services.registry.iter().rev().take(3).enumerate() { + let card_h: u16 = 7; + if y + card_h > area.y + area.height { + break; + } + let card = Rect { + x: area.x, + y, + width: area.width, + height: card_h, + }; + render_service_card(frame, card, s, state, i); + y += card_h + 1; + } +} + +fn render_service_card( + frame: &mut Frame<'_>, + area: Rect, + service: &crate::domain::ServiceRecord, + state: &AppState, + _index: usize, +) { + let block = Block::default() + .borders(Borders::ALL) + .border_style(theme::pane_border(false)) + .style(theme::panel_surface(false)) + .padding(Padding::new(2, 2, 0, 0)); + let inner = block.inner(area); + frame.render_widget(block, area); + + let port = service + .ports + .first() + .map(|p| format!(":{p}")) + .unwrap_or_default(); + let cmd = state + .commands + .records + .iter() + .find(|c| Some(c.id) == service.linked_command) + .map(|c| c.raw.clone()) + .unwrap_or_else(|| format!("{:?} service", service.source).to_lowercase()); + let uptime = service + .last_seen + .elapsed() + .map(|d| { + let secs = d.as_secs(); + if secs < 60 { + format!("{secs}s") + } else { + format!("{}m {}s", secs / 60, secs % 60) + } + }) + .unwrap_or_else(|_| "—".to_string()); + + let mid = inner.width / 2; + let header_left = Rect { + x: inner.x, + y: inner.y, + width: mid, + height: 1, + }; + let header_right = Rect { + x: inner.x + mid, + y: inner.y, + width: inner.width.saturating_sub(mid), + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled("● ", theme::accent()), + Span::styled(service.name.clone(), theme::primary_emphasis()), + Span::raw(" "), + Span::styled(port, theme::accent()), + ])), + header_left, + ); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled(" logs ", theme::keycap()), + Span::raw(" "), + Span::styled(" restart ", theme::keycap()), + Span::raw(" "), + Span::styled(" stop ", theme::keycap()), + ])) + .alignment(ratatui::layout::Alignment::Right), + header_right, + ); + + // Command line. + let cmd_row = Rect { + x: inner.x, + y: inner.y + 1, + width: inner.width, + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled( + truncate(&cmd, 60), + theme::muted(), + )])), + cmd_row, + ); + + // Stats row (PID / UP / CPU / MEM). + let stats_row = Rect { + x: inner.x, + y: inner.y + 2, + width: inner.width, + height: 1, + }; + let pid_str = service.pid.map(|p| p.to_string()).unwrap_or_else(|| "—".into()); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled("PID ", theme::subtle()), + Span::styled(format!("{:<8}", pid_str), theme::muted()), + Span::styled("UP ", theme::subtle()), + Span::styled(format!("{:<10}", uptime), theme::muted()), + Span::styled("CPU ", theme::subtle()), + Span::styled("— ", theme::muted()), + Span::styled("MEM ", theme::subtle()), + Span::styled("—", theme::muted()), + ])), + stats_row, + ); + + // Sparkline row — single line using block chars. + let spark_row = Rect { + x: inner.x, + y: inner.y + 3, + width: inner.width, + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled( + sparkline_text(inner.width as usize), + theme::accent(), + )])), + spark_row, + ); +} + +fn sparkline_text(width: usize) -> String { + const CHARS: &[char] = &['▁', '▂', '▃', '▄', '▅', '▄', '▃', '▄', '▅', '▆', '▅', '▄']; + let mut out = String::new(); + for i in 0..width { + out.push(CHARS[i % CHARS.len()]); + } + out +} + +fn render_drawer_footer(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + if !matches!(state.ui.dashboard_tab, DashboardTab::Services) { + return; + } + let block = Block::default() + .borders(Borders::ALL) + .border_style(theme::pane_border(false)) + .style(theme::panel_surface(false)); + let inner = block.inner(area); + frame.render_widget(block, area); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled("launch another with ", theme::subtle()), + Span::styled("/bg ", theme::primary()), + Span::styled(" or suffix ", theme::subtle()), + Span::styled("&", theme::primary()), + ])) + .alignment(ratatui::layout::Alignment::Center), + inner, + ); +} + +fn truncate(value: &str, max_chars: usize) -> String { + if value.chars().count() <= max_chars { + return value.to_string(); + } + let kept: String = value.chars().take(max_chars.saturating_sub(1)).collect(); + format!("{kept}…") +} + +#[allow(dead_code)] fn services_lines(state: &AppState) -> Vec> { let mut lines = vec![Line::from(vec![ Span::styled("Managed services", theme::section_title()), @@ -278,6 +530,7 @@ fn test_lines(state: &AppState) -> Vec> { lines } +#[allow(dead_code)] fn render_overview(frame: &mut Frame<'_>, area: Rect, state: &AppState) { let branch = state .git @@ -334,42 +587,84 @@ fn render_overview(frame: &mut Frame<'_>, area: Rect, state: &AppState) { } fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let tabs = DashboardTab::all() - .iter() - .map(|tab| { - let active = *tab == state.ui.dashboard_tab; - let label = format!(" {} ", tab.title()); - if active { - Span::styled(label, theme::status_badge(theme::ACCENT)) - } else { - Span::styled(label, theme::quiet_badge()) - } - }) - .collect::>(); - - let mut content = Vec::new(); - for (index, tab) in tabs.into_iter().enumerate() { - if index > 0 { - content.push(Span::raw(" ")); + let mut spans: Vec> = Vec::new(); + for tab in DashboardTab::all() { + let active = tab == state.ui.dashboard_tab; + let name_style = if active { + theme::primary_emphasis() + } else { + theme::muted() + }; + spans.push(Span::styled( + format!("{}", tab.title().to_ascii_lowercase()), + name_style, + )); + let count = match tab { + DashboardTab::Services => state.services.registry.len(), + DashboardTab::Processes => state.processes.snapshots.len(), + DashboardTab::Logs => state.logs.recent.len(), + DashboardTab::Git => state.git.changed_files.len(), + DashboardTab::Tests => state.tests.recent_runs.len(), + }; + if count > 0 { + spans.push(Span::raw(" ")); + spans.push(Span::styled( + format!(" {count} "), + if active { + theme::focus_badge() + } else { + theme::quiet_badge() + }, + )); } - content.push(tab); + spans.push(Span::raw(" ")); } - content.push(Span::raw(" ")); - content.push(Span::styled("Left/Right", theme::keycap())); - content.push(Span::styled(" switch tabs", theme::muted())); + + // Underline marker row below. + let tab_line = Line::from(spans); + + // Build underline segment roughly beneath active tab name. + let active_idx = DashboardTab::all() + .iter() + .position(|t| *t == state.ui.dashboard_tab) + .unwrap_or(0); + let underline = build_tab_underline(state, active_idx, area.width as usize); frame.render_widget( - Paragraph::new(vec![ - Line::from(content), - Line::from(vec![Span::styled( - active_tab_summary(state.ui.dashboard_tab), - theme::subtle(), - )]), - ]), + Paragraph::new(vec![tab_line, Line::from(underline)]), area, ); } +fn build_tab_underline(state: &AppState, active_idx: usize, _width: usize) -> Vec> { + let mut acc = String::new(); + for (i, tab) in DashboardTab::all().iter().enumerate() { + let title_len = tab.title().chars().count(); + let count = match tab { + DashboardTab::Services => state.services.registry.len(), + DashboardTab::Processes => state.processes.snapshots.len(), + DashboardTab::Logs => state.logs.recent.len(), + DashboardTab::Git => state.git.changed_files.len(), + DashboardTab::Tests => state.tests.recent_runs.len(), + }; + let badge_len = if count > 0 { + count.to_string().chars().count() + 3 + } else { + 0 + }; + let block_len = title_len + badge_len; + if i == active_idx { + return vec![ + Span::raw(acc), + Span::styled("▔".repeat(block_len), theme::accent()), + ]; + } + acc.push_str(&" ".repeat(block_len + 4)); + } + vec![Span::raw(acc)] +} + +#[allow(dead_code)] fn active_tab_summary(tab: DashboardTab) -> &'static str { match tab { DashboardTab::Services => "Long-lived services with health, PID, and launch visibility.", diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index a563a49..046dad0 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -4,7 +4,7 @@ use ratatui::widgets::Paragraph; use ratatui::Frame; use crate::domain::AppState; -use crate::ui::theme; +use crate::ui::{keys, theme}; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: bool) { let latest = state @@ -25,17 +25,17 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: boo ]; let right_spans = vec![ - Span::styled(" Tab ", theme::keycap()), + Span::styled(format!(" {} ", keys::meta("O")), theme::keycap()), Span::styled(" ops", theme::muted()), Span::raw(" "), - Span::styled(" Ctrl+L ", theme::keycap()), + Span::styled(format!(" {} ", keys::meta("L")), theme::keycap()), Span::styled(" activity", theme::muted()), Span::raw(" "), - Span::styled(" / ", theme::keycap()), - Span::styled(" commands", theme::muted()), + Span::styled(format!(" {} ", keys::meta("/")), theme::keycap()), + Span::styled(" ai", theme::muted()), Span::raw(" "), - Span::styled(" F2 ", theme::keycap()), - Span::styled(" mode", theme::muted()), + Span::styled(format!(" {} ", keys::meta("K")), theme::keycap()), + Span::styled(" commands", theme::muted()), Span::raw(" "), ]; From 94a94e4cde799a1d63f75ba6bb9bec832d3d551b Mon Sep 17 00:00:00 2001 From: Bethvour Date: Tue, 21 Apr 2026 11:52:24 -0500 Subject: [PATCH 08/10] ui: add intent suggestions and dashboard/status polish --- src/ui/theme.rs | 50 ++++++++++-- src/ui/views/command_pane.rs | 151 +++++++++++++++++++++-------------- src/ui/views/event_stream.rs | 25 +++++- src/ui/views/mod.rs | 4 +- src/ui/views/status_bar.rs | 83 ++++++++++++------- tests/foundation.rs | 109 +++++++++++++++++++++++++ 6 files changed, 321 insertions(+), 101 deletions(-) diff --git a/src/ui/theme.rs b/src/ui/theme.rs index 33253da..b2759e6 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -9,9 +9,11 @@ pub const BG_ELEVATED: Color = Color::Rgb(246, 243, 236); // #f6f3ec pub const BG_PANEL: Color = Color::Rgb(251, 249, 243); // card surface #fbf9f3 pub const BG_PANEL_FOCUS: Color = Color::Rgb(251, 249, 243); pub const BG_CHROME: Color = Color::Rgb(235, 231, 221); +pub const BG_SHADOW: Color = Color::Rgb(229, 225, 216); pub const BG_SELECTION: Color = Color::Rgb(221, 237, 232); // teal-wash pub const PANEL_BORDER: Color = Color::Rgb(45, 157, 143); pub const PANEL_BORDER_SUBTLE: Color = Color::Rgb(220, 216, 205); // hair +pub const PROMPT_BORDER: Color = Color::Rgb(222, 218, 207); pub const PANEL_FOCUS: Color = Color::Rgb(45, 157, 143); pub const TEXT_PRIMARY: Color = Color::Rgb(29, 29, 27); // near-black ink pub const TEXT_MUTED: Color = Color::Rgb(74, 74, 70); @@ -45,6 +47,46 @@ pub fn panel_surface(focused: bool) -> Style { .fg(TEXT_PRIMARY) } +pub fn prompt_surface() -> Style { + Style::default().bg(BG_PANEL).fg(TEXT_PRIMARY) +} + +pub fn prompt_border() -> Style { + Style::default().fg(PROMPT_BORDER) +} + +pub fn prompt_shadow() -> Style { + Style::default().bg(BG_SHADOW) +} + +pub fn prompt_question() -> Style { + Style::default() + .fg(TEXT_MUTED) + .add_modifier(Modifier::ITALIC | Modifier::BOLD) +} + +pub fn prompt_placeholder() -> Style { + Style::default().fg(TEXT_SUBTLE).add_modifier(Modifier::DIM) +} + +pub fn prompt_cursor(dimmed: bool) -> Style { + if dimmed { + subtle() + } else { + Style::default() + .fg(TEXT_PRIMARY) + .add_modifier(Modifier::BOLD) + } +} + +pub fn separator() -> Style { + Style::default().fg(PANEL_BORDER_SUBTLE).bg(BG_BASE) +} + +pub fn status_context() -> Style { + Style::default().fg(TEXT_SUBTLE) +} + pub fn panel_title(focused: bool) -> Style { Style::default() .fg(if focused { TEXT_PRIMARY } else { TEXT_MUTED }) @@ -112,9 +154,7 @@ pub fn status_badge(bg: Color) -> Style { } pub fn quiet_badge() -> Style { - Style::default() - .fg(TEXT_MUTED) - .bg(BG_ELEVATED) + Style::default().fg(TEXT_MUTED).bg(BG_ELEVATED) } pub fn focus_badge() -> Style { @@ -129,9 +169,7 @@ pub fn pill(fg: Color, bg: Color) -> Style { } pub fn keycap() -> Style { - Style::default() - .fg(TEXT_MUTED) - .bg(BG_ELEVATED) + Style::default().fg(TEXT_MUTED).bg(BG_ELEVATED) } pub fn command_palette_item(selected: bool) -> Style { diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index 283ede1..7f86f93 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -1,7 +1,7 @@ use ratatui::layout::Rect; use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Padding, Paragraph, Wrap}; +use ratatui::widgets::{Block, BorderType, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; use crate::commands::{slash_command_suggestions, SlashCommandSpec}; @@ -31,16 +31,18 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool let visible_slash = visible_command_suggestions(&slash_suggestions, state); let intent_suggestions = intent_suggestions(state); - let headline_h: u16 = if state.ui.input.buffer.is_empty() { 2 } else { 0 }; - let prompt_h: u16 = 5; - let chips_h: u16 = if visible_slash.is_empty() - && intent_suggestions.is_empty() - && !should_show_context_card(state) - { - 2 + let headline_h: u16 = if state.ui.input.buffer.is_empty() { + 1 } else { 0 }; + let gap_after_headline: u16 = if headline_h > 0 { 2 } else { 0 }; + let prompt_h: u16 = 6; + let show_chips = visible_slash.is_empty() + && intent_suggestions.is_empty() + && !should_show_context_card(state); + let gap_after_prompt: u16 = if show_chips { 2 } else { 0 }; + let chips_h: u16 = if show_chips { 1 } else { 0 }; let running_h: u16 = if running_items.is_empty() { 0 } else { @@ -63,8 +65,15 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool 0 }; - let group_h = running_h + headline_h + prompt_h + suggestion_h + context_h + chips_h; - let y_pad = area.height.saturating_sub(group_h) * 42 / 100; + let group_h = running_h + + headline_h + + gap_after_headline + + prompt_h + + gap_after_prompt + + suggestion_h + + context_h + + chips_h; + let y_pad = area.height.saturating_sub(group_h) * 38 / 100; let column = Rect { x: area.x + x_pad, @@ -80,7 +89,9 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool .constraints([ Constraint::Length(running_h), Constraint::Length(headline_h), + Constraint::Length(gap_after_headline), Constraint::Length(prompt_h), + Constraint::Length(gap_after_prompt), Constraint::Length(suggestion_h), Constraint::Length(context_h), Constraint::Length(chips_h), @@ -94,18 +105,18 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool if headline_h > 0 { render_headline(frame, sections[1], state, dim); } - render_prompt(frame, sections[2], state, dim); + render_prompt(frame, sections[3], state, dim); if suggestion_h > 0 { if slash_h > 0 { - render_slash_suggestions(frame, sections[3], &visible_slash); + render_slash_suggestions(frame, sections[5], &visible_slash); } else { - render_intent_suggestions(frame, sections[3], &intent_suggestions); + render_intent_suggestions(frame, sections[5], &intent_suggestions); } } else if context_h > 0 { - render_context_card(frame, sections[4], state); + render_context_card(frame, sections[6], state); } else if chips_h > 0 { - render_recent_chips(frame, sections[5], state); + render_recent_chips(frame, sections[7], state); } } @@ -119,7 +130,7 @@ fn render_headline(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: boo let style = if dim { theme::subtle() } else { - theme::italic_muted() + theme::prompt_question() }; frame.render_widget( Paragraph::new(Line::from(vec![Span::styled(text, style)])), @@ -148,18 +159,41 @@ fn render_prompt(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: bool) } }; - // Render a 3-line bordered box with the prompt. + let box_width = if area.width > 3 { + area.width - 1 + } else { + area.width + }; + let box_height = if area.height > 3 { + area.height - 1 + } else { + area.height + }; + let box_area = Rect { + x: area.x, + y: area.y, + width: box_width, + height: box_height, + }; + if area.width > 2 && area.height > 2 { + let shadow = Rect { + x: area.x + 1, + y: area.y + 1, + width: area.width.saturating_sub(1), + height: area.height.saturating_sub(1), + }; + frame.render_widget(Block::default().style(theme::prompt_shadow()), shadow); + } + + // Render a rounded, wireframe-style prompt surface with a subtle hairline. let block = Block::default() .borders(Borders::ALL) - .border_style(if dim { - theme::pane_border(false) - } else { - theme::pane_border(true) - }) - .style(theme::panel_surface(!dim)) + .border_type(BorderType::Rounded) + .border_style(theme::prompt_border()) + .style(theme::prompt_surface()) .padding(Padding::new(3, 3, 1, 1)); - let inner = block.inner(area); - frame.render_widget(block, area); + let inner = block.inner(box_area); + frame.render_widget(block, box_area); let text_width = inner.width.saturating_sub(4) as usize; let display = render_prompt_text(buf, cursor, text_width); @@ -172,8 +206,8 @@ fn render_prompt(frame: &mut Frame<'_>, area: Rect, state: &AppState, dim: bool) }; vec![ Span::styled(format!("{arrow_char} "), arrow_color), - Span::styled(placeholder, theme::subtle()), - Span::styled("█", if dim { theme::subtle() } else { theme::primary() }), + Span::styled(placeholder, theme::prompt_placeholder()), + Span::styled("█", theme::prompt_cursor(dim)), ] } else { vec![ @@ -282,8 +316,7 @@ fn running_items(state: &AppState) -> Vec { .filter(|s| { matches!( s.health, - crate::domain::ServiceHealth::Healthy - | crate::domain::ServiceHealth::Starting + crate::domain::ServiceHealth::Healthy | crate::domain::ServiceHealth::Starting ) }) .take(3) @@ -359,7 +392,10 @@ fn render_slash_suggestions( Span::raw(spacer), ]; if *selected { - spans.push(Span::styled(format!(" {} ", keys::enter()), theme::keycap())); + spans.push(Span::styled( + format!(" {} ", keys::enter()), + theme::keycap(), + )); } lines.push(Line::from(spans)); } @@ -387,7 +423,8 @@ fn render_intent_suggestions(frame: &mut Frame<'_>, area: Rect, items: &[IntentS }; let cmd_text = truncate(&it.cmd, 32); let hint = truncate(&it.hint, 30); - let used = 1 + pill_text.chars().count() + 2 + cmd_text.chars().count() + 2 + hint.chars().count(); + let used = + 1 + pill_text.chars().count() + 2 + cmd_text.chars().count() + 2 + hint.chars().count(); let spacer = " ".repeat(width.saturating_sub(used).saturating_sub(6)); let mut spans = vec![ Span::raw(" "), @@ -399,7 +436,10 @@ fn render_intent_suggestions(frame: &mut Frame<'_>, area: Rect, items: &[IntentS Span::raw(" "), ]; if selected { - spans.push(Span::styled(format!(" {} ", keys::enter()), theme::keycap())); + spans.push(Span::styled( + format!(" {} ", keys::enter()), + theme::keycap(), + )); } lines.push(Line::from(spans)); } @@ -428,7 +468,10 @@ fn intent_suggestions(state: &AppState) -> Vec { }, IntentSuggestion { mode: "AI", - cmd: format!("ai: what does {} do", truncate(buf.split_whitespace().next().unwrap_or(buf), 40)), + cmd: format!( + "ai: what does {} do", + truncate(buf.split_whitespace().next().unwrap_or(buf), 40) + ), hint: "ask the assistant".into(), }, ]; @@ -479,11 +522,7 @@ fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { AiStatus::Running | AiStatus::Queued | AiStatus::Failed | AiStatus::Completed ); let (header_spans, body, footer_hint) = build_context_card(state); - let borders = if is_ai { - Borders::LEFT - } else { - Borders::ALL - }; + let borders = if is_ai { Borders::LEFT } else { Borders::ALL }; let block = Block::default() .borders(borders) .border_style(if is_ai { @@ -499,10 +538,7 @@ fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { let mut lines = vec![Line::from(header_spans)]; lines.push(Line::raw("")); lines.extend(body); - frame.render_widget( - Paragraph::new(lines).wrap(Wrap { trim: false }), - inner, - ); + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner); // Hint line below the card (only when there is vertical room). if let Some(hint) = footer_hint { @@ -521,7 +557,11 @@ fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { fn build_context_card( state: &AppState, -) -> (Vec>, Vec>, Option>) { +) -> ( + Vec>, + Vec>, + Option>, +) { if let Some(approval) = state .approvals .pending @@ -581,10 +621,7 @@ fn build_context_card( let header = vec![ Span::styled(" AI ", theme::focus_badge()), Span::raw(" "), - Span::styled( - format!("{} · model {}", provider, model), - theme::subtle(), - ), + Span::styled(format!("{} · model {}", provider, model), theme::subtle()), Span::raw(" "), Span::styled(right_label, theme::subtle()), ]; @@ -605,10 +642,7 @@ fn build_context_card( body.push(Line::raw("")); for (i, rec) in resp.recommendations.iter().take(3).enumerate() { body.push(Line::from(vec![ - Span::styled( - format!("{}. ", i + 1), - theme::subtle(), - ), + Span::styled(format!("{}. ", i + 1), theme::subtle()), Span::styled(truncate(rec, 220), theme::muted()), ])); } @@ -686,11 +720,7 @@ fn build_context_card( )])] } else { vec![Line::from(vec![Span::styled( - format!( - "{} · {}", - cmd.safety_class.label(), - cmd.cwd.display() - ), + format!("{} · {}", cmd.safety_class.label(), cmd.cwd.display()), theme::muted(), )])] }; @@ -726,10 +756,13 @@ fn render_recent_chips(frame: &mut Frame<'_>, area: Rect, state: &AppState) { "bg cargo test --watch".into(), ]; } - let mut spans: Vec> = vec![Span::styled(" recent ", theme::subtle())]; - for r in recents { + let mut spans: Vec> = vec![Span::styled("recent ", theme::subtle())]; + let last = recents.len().saturating_sub(1); + for (i, r) in recents.into_iter().enumerate() { spans.push(Span::styled(format!(" {r} "), theme::quiet_badge())); - spans.push(Span::raw(" ")); + if i != last { + spans.push(Span::styled(" ", theme::subtle())); + } } frame.render_widget( Paragraph::new(Line::from(spans)).wrap(Wrap { trim: true }), diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index 046dad0..e067daa 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -1,12 +1,14 @@ use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::Paragraph; +use ratatui::widgets::{Block, Paragraph}; use ratatui::Frame; use crate::domain::AppState; use crate::ui::{keys, theme}; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: bool) { + frame.render_widget(Block::default().style(theme::chrome_surface()), area); + let latest = state .timeline .entries @@ -39,16 +41,33 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: boo Span::raw(" "), ]; + let content_y = if area.height >= 2 { area.y + 1 } else { area.y }; + if area.height >= 2 { + let separator = Rect { + x: area.x, + y: area.y, + width: area.width, + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(Span::styled( + "─".repeat(area.width as usize), + theme::separator(), + ))), + separator, + ); + } + let mid = area.width / 2; let left_area = Rect { x: area.x, - y: area.y, + y: content_y, width: mid, height: 1, }; let right_area = Rect { x: area.x + mid, - y: area.y, + y: content_y, width: area.width.saturating_sub(mid), height: 1, }; diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index f06a38e..45c0af6 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -17,9 +17,9 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { let layout = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(1), // minimal top bar + Constraint::Length(3), // top identity bar + hairline Constraint::Min(8), // main stage - Constraint::Length(1), // bottom rail (collapsed activity + hints) + Constraint::Length(2), // bottom activity rail + hairline ]) .split(frame.area()); diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index 75514b4..a0744c0 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -1,12 +1,14 @@ use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::Paragraph; +use ratatui::widgets::{Block, Paragraph}; use ratatui::Frame; use crate::domain::AppState; use crate::ui::theme; pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + frame.render_widget(Block::default().style(theme::chrome_surface()), area); + let branch = state .git .branch @@ -35,25 +37,22 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }) .count(); - let short_branch = branch - .rsplit_once('/') - .map(|(_, tail)| tail.to_string()) - .unwrap_or_else(|| branch.clone()); + let branch_display = truncate_middle(&branch_leaf(&branch), 28); let left = if project.eq_ignore_ascii_case("forge") { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), - Span::styled(truncate_middle(&short_branch, 24), theme::muted()), + Span::styled(" / ", theme::subtle()), + Span::styled(branch_display, theme::status_context()), ] } else { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), - Span::styled(project, theme::muted()), - Span::styled(" / ", theme::subtle()), - Span::styled(truncate_middle(&short_branch, 22), theme::muted()), + Span::styled(" / ", theme::subtle()), + Span::styled(project, theme::status_context()), + Span::styled(" / ", theme::subtle()), + Span::styled(branch_display, theme::status_context()), ] }; @@ -61,10 +60,7 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { if running > 0 { right.push(Span::styled("●", theme::accent())); right.push(Span::raw(" ")); - right.push(Span::styled( - format!("{running} running"), - theme::primary(), - )); + right.push(Span::styled(format!("{running} running"), theme::primary())); right.push(Span::styled(" · ", theme::subtle())); } right.push(Span::styled( @@ -79,39 +75,55 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { right.push(Span::styled(truncate_end(&head, 8), theme::subtle())); right.push(Span::raw(" ")); - let left_len = left.len(); - let mut spans = left; - spans.extend(right); + let text_y = if area.height >= 3 { area.y + 1 } else { area.y }; + let text_area = Rect { + x: area.x, + y: text_y, + width: area.width, + height: 1, + }; - // Two paragraphs: left-aligned + right-aligned — split area in half. - let mid = area.width / 2; + // Two paragraphs: left-aligned + right-aligned, matching the sparse wireframe bar. + let mid = text_area.width / 2; let left_area = Rect { - x: area.x, - y: area.y, + x: text_area.x, + y: text_area.y, width: mid, height: 1, }; let right_area = Rect { - x: area.x + mid, - y: area.y, - width: area.width.saturating_sub(mid), + x: text_area.x + mid, + y: text_area.y, + width: text_area.width.saturating_sub(mid), height: 1, }; - // Extract left portion from our combined spans — actually we built them separately - let left_spans = spans[..left_len].to_vec(); - let right_spans = spans[left_len..].to_vec(); - frame.render_widget( - Paragraph::new(Line::from(left_spans)).style(theme::chrome_surface()), + Paragraph::new(Line::from(left)).style(theme::chrome_surface()), left_area, ); frame.render_widget( - Paragraph::new(Line::from(right_spans)) + Paragraph::new(Line::from(right)) .alignment(ratatui::layout::Alignment::Right) .style(theme::chrome_surface()), right_area, ); + + if area.height > 1 { + let separator = Rect { + x: area.x, + y: area.y + area.height - 1, + width: area.width, + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(Span::styled( + "─".repeat(area.width as usize), + theme::separator(), + ))), + separator, + ); + } } fn truncate_end(value: &str, max_chars: usize) -> String { @@ -142,3 +154,12 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { .collect::(); format!("{start}…{end}") } + +fn branch_leaf(branch: &str) -> String { + branch + .rsplit('/') + .next() + .filter(|value| !value.is_empty()) + .unwrap_or(branch) + .to_string() +} diff --git a/tests/foundation.rs b/tests/foundation.rs index c64769f..797d918 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -1,6 +1,8 @@ use std::collections::BTreeMap; use std::time::SystemTime; +use ratatui::{backend::TestBackend, style::Modifier, Terminal}; + use forge::app::{AppAction, AppStore, Effect}; use forge::commands::{parse_input, slash_command_suggestions, ParsedInput}; use forge::config::ForgeConfig; @@ -396,8 +398,115 @@ fn store_approve_without_pending_shows_notice() { .is_some_and(|notice| notice.message.contains("no pending approvals"))); } +#[test] +fn ui_renders_prompt_first_wireframe_details() { + let mut state = AppState::new( + ForgeConfig::default(), + ProjectContext::default(), + GitSnapshot { + branch: Some("forge/foundation".to_string()), + head: Some("adc2ae2".to_string()), + ..GitSnapshot::default() + }, + ); + state.project.name = "forge".to_string(); + + let mut terminal = Terminal::new(TestBackend::new(140, 44)).unwrap(); + terminal + .draw(|frame| forge::ui::render(frame, &state)) + .unwrap(); + + let buffer = terminal.backend().buffer(); + let rows = buffer_rows(buffer); + assert!( + rows[1].contains("forge / foundation"), + "status identity should read like the uploaded wireframe" + ); + assert!( + rows[2].contains("────"), + "status bar should have a visible underline separator" + ); + + let (question_x, question_y) = find_text(&rows, "what do you want to do?") + .expect("empty command pane should render the wireframe question"); + let question_cell = buffer.cell((question_x, question_y)).unwrap(); + assert!(question_cell.modifier.contains(Modifier::ITALIC)); + assert!(question_cell.modifier.contains(Modifier::BOLD)); + + assert!( + rows.iter() + .any(|row| row.contains("╭") && row.contains("╮")), + "prompt box should use rounded wireframe corners" + ); + assert!( + rows.iter() + .any(|row| row.contains("▸ run, ask, commit, deploy…█")), + "prompt box should keep the uploaded placeholder and cursor treatment" + ); + + let (prompt_x, prompt_y) = + find_symbol(buffer, "╭").expect("prompt box should have a top-left corner"); + let (prompt_right_x, _) = find_symbol_on_row(buffer, prompt_y, "╮") + .expect("prompt box should have a top-right corner"); + assert_eq!( + buffer.cell((prompt_right_x + 1, prompt_y + 1)).unwrap().bg, + forge::ui::theme::BG_SHADOW, + "prompt box should retain the subtle right-side shadow" + ); + assert!( + prompt_x > 0, + "prompt box should be centered rather than pinned to the viewport edge" + ); +} + fn test_store() -> AppStore { let config = ForgeConfig::default(); let state = AppState::new(config, ProjectContext::default(), GitSnapshot::default()); AppStore::new(state) } + +fn buffer_rows(buffer: &ratatui::buffer::Buffer) -> Vec { + let area = *buffer.area(); + (0..area.height) + .map(|y| { + (0..area.width) + .map(|x| buffer.cell((x, y)).unwrap().symbol()) + .collect::() + }) + .collect() +} + +fn find_text(rows: &[String], needle: &str) -> Option<(u16, u16)> { + rows.iter() + .enumerate() + .find_map(|(y, row)| row.find(needle).map(|x| (x as u16, y as u16))) +} + +fn find_symbol(buffer: &ratatui::buffer::Buffer, symbol: &str) -> Option<(u16, u16)> { + let area = *buffer.area(); + for y in 0..area.height { + for x in 0..area.width { + if buffer + .cell((x, y)) + .is_some_and(|cell| cell.symbol() == symbol) + { + return Some((x, y)); + } + } + } + None +} + +fn find_symbol_on_row( + buffer: &ratatui::buffer::Buffer, + y: u16, + symbol: &str, +) -> Option<(u16, u16)> { + let area = *buffer.area(); + (0..area.width).find_map(|x| { + buffer + .cell((x, y)) + .filter(|cell| cell.symbol() == symbol) + .map(|_| (x, y)) + }) +} From ff28ba6decec2c25a7a6fcf20ce6373faab02836 Mon Sep 17 00:00:00 2001 From: Bethvour Date: Wed, 22 Apr 2026 14:43:45 -0500 Subject: [PATCH 09/10] fix(ui): apply rustfmt formatting for dashboard/status bar --- src/app/store.rs | 60 +++++++++++++++++++++++------------- src/runtime/engine.rs | 3 +- src/ui/mod.rs | 2 +- src/ui/views/command_pane.rs | 27 +++++++++++----- src/ui/views/dashboard.rs | 10 +++--- src/ui/views/mod.rs | 2 ++ src/ui/views/status_bar.rs | 17 +++------- 7 files changed, 72 insertions(+), 49 deletions(-) diff --git a/src/app/store.rs b/src/app/store.rs index 66df6fc..daf6ed8 100644 --- a/src/app/store.rs +++ b/src/app/store.rs @@ -600,26 +600,32 @@ impl AppStore { } } + fn active_suggestion_len(&self) -> usize { + let slash = slash_command_suggestions(&self.state.ui.input.buffer).len(); + if slash > 0 { + return slash; + } + crate::ui::views::intent_suggestions(&self.state).len() + } + fn sync_command_palette_cursor(&mut self) { - let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); - if suggestions.is_empty() { + let len = self.active_suggestion_len(); + if len == 0 { self.state.ui.command_palette_cursor = 0; return; } - if self.state.ui.command_palette_cursor >= suggestions.len() { - self.state.ui.command_palette_cursor = suggestions.len().saturating_sub(1); + if self.state.ui.command_palette_cursor >= len { + self.state.ui.command_palette_cursor = len.saturating_sub(1); } } fn move_command_palette_cursor(&mut self, forward: bool) { - let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); - if suggestions.is_empty() { + let len = self.active_suggestion_len(); + if len == 0 { self.state.ui.command_palette_cursor = 0; return; } - - let len = suggestions.len(); let current = self .state .ui @@ -635,26 +641,38 @@ impl AppStore { } fn accept_command_suggestion(&mut self) { - let suggestions = slash_command_suggestions(&self.state.ui.input.buffer); - if suggestions.is_empty() { + let slash = slash_command_suggestions(&self.state.ui.input.buffer); + if !slash.is_empty() { + let index = self + .state + .ui + .command_palette_cursor + .min(slash.len().saturating_sub(1)); + let suggestion = slash[index]; + self.state + .ui + .input + .set_buffer(suggestion.completion.to_string()); + if !suggestion.accepts_arguments() { + self.state.ui.command_palette_cursor = index; + } else { + self.state.ui.command_palette_cursor = 0; + } return; } + let intents = crate::ui::views::intent_suggestions(&self.state); + if intents.is_empty() { + return; + } let index = self .state .ui .command_palette_cursor - .min(suggestions.len().saturating_sub(1)); - let suggestion = suggestions[index]; - self.state - .ui - .input - .set_buffer(suggestion.completion.to_string()); - if !suggestion.accepts_arguments() { - self.state.ui.command_palette_cursor = index; - } else { - self.state.ui.command_palette_cursor = 0; - } + .min(intents.len().saturating_sub(1)); + let completion = intents[index].cmd.clone(); + self.state.ui.input.set_buffer(completion); + self.state.ui.command_palette_cursor = 0; } fn recall_history(&mut self, previous: bool) { diff --git a/src/runtime/engine.rs b/src/runtime/engine.rs index 56f7175..935644c 100644 --- a/src/runtime/engine.rs +++ b/src/runtime/engine.rs @@ -151,7 +151,8 @@ fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option, area: Rect, state: &AppState, focused: bool if slash_h > 0 { render_slash_suggestions(frame, sections[5], &visible_slash); } else { - render_intent_suggestions(frame, sections[5], &intent_suggestions); + render_intent_suggestions( + frame, + sections[5], + &intent_suggestions, + state.ui.command_palette_cursor, + ); } } else if context_h > 0 { render_context_card(frame, sections[6], state); @@ -402,14 +407,20 @@ fn render_slash_suggestions( frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); } -fn render_intent_suggestions(frame: &mut Frame<'_>, area: Rect, items: &[IntentSuggestion]) { +fn render_intent_suggestions( + frame: &mut Frame<'_>, + area: Rect, + items: &[IntentSuggestion], + cursor: usize, +) { let mut lines = vec![ Line::from(vec![Span::styled("SUGGESTIONS", theme::subtle())]), Line::raw(""), ]; let width = area.width as usize; + let selected_idx = cursor.min(items.len().saturating_sub(1)); for (i, it) in items.iter().enumerate() { - let selected = i == 0; + let selected = i == selected_idx; let pill_style = if selected { theme::focus_badge() } else { @@ -446,7 +457,7 @@ fn render_intent_suggestions(frame: &mut Frame<'_>, area: Rect, items: &[IntentS frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); } -fn intent_suggestions(state: &AppState) -> Vec { +pub(crate) fn intent_suggestions(state: &AppState) -> Vec { let buf = state.ui.input.buffer.trim(); if buf.is_empty() || buf.starts_with('/') { return Vec::new(); diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index 8161674..f1c4130 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -227,7 +227,10 @@ fn render_service_card( width: inner.width, height: 1, }; - let pid_str = service.pid.map(|p| p.to_string()).unwrap_or_else(|| "—".into()); + let pid_str = service + .pid + .map(|p| p.to_string()) + .unwrap_or_else(|| "—".into()); frame.render_widget( Paragraph::new(Line::from(vec![ Span::styled("PID ", theme::subtle()), @@ -630,10 +633,7 @@ fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { .unwrap_or(0); let underline = build_tab_underline(state, active_idx, area.width as usize); - frame.render_widget( - Paragraph::new(vec![tab_line, Line::from(underline)]), - area, - ); + frame.render_widget(Paragraph::new(vec![tab_line, Line::from(underline)]), area); } fn build_tab_underline(state: &AppState, active_idx: usize, _width: usize) -> Vec> { diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index 45c0af6..072038f 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -1,4 +1,6 @@ mod command_pane; + +pub(crate) use command_pane::intent_suggestions; mod dashboard; mod event_stream; mod modal; diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index a0744c0..de49921 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -37,21 +37,21 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }) .count(); - let branch_display = truncate_middle(&branch_leaf(&branch), 28); + let branch_display = truncate_middle(&branch, 32); let left = if project.eq_ignore_ascii_case("forge") { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), + Span::styled(" │ ", theme::subtle()), Span::styled(branch_display, theme::status_context()), ] } else { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), + Span::styled(" │ ", theme::subtle()), Span::styled(project, theme::status_context()), - Span::styled(" / ", theme::subtle()), + Span::styled(" │ ", theme::subtle()), Span::styled(branch_display, theme::status_context()), ] }; @@ -154,12 +154,3 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { .collect::(); format!("{start}…{end}") } - -fn branch_leaf(branch: &str) -> String { - branch - .rsplit('/') - .next() - .filter(|value| !value.is_empty()) - .unwrap_or(branch) - .to_string() -} From 1c1198fe73c28359bf6da4a642efdbff7b4ebe36 Mon Sep 17 00:00:00 2001 From: Bethvour Date: Wed, 22 Apr 2026 14:48:18 -0500 Subject: [PATCH 10/10] fix(ui): restore wireframe status bar and clear clippy warnings --- src/ui/views/command_pane.rs | 29 +++++------------------------ src/ui/views/dashboard.rs | 5 +---- src/ui/views/event_stream.rs | 3 +-- src/ui/views/status_bar.rs | 17 +++++++++++++---- 4 files changed, 20 insertions(+), 34 deletions(-) diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs index cf2877e..6e7838c 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -263,30 +263,15 @@ fn render_running_strip(frame: &mut Frame<'_>, area: Rect, items: &[RunItem]) { heading, ); - // One bordered row per running item. - let mut y = area.y + 2; - for it in items { - if y >= area.y + area.height { - break; - } + // One row per running item. + let end_y = area.y.saturating_add(area.height); + for (y, it) in (area.y.saturating_add(2)..end_y).zip(items.iter()) { let row = Rect { x: area.x, y, width: area.width, height: 1, }; - let block = Block::default() - .borders(Borders::ALL) - .border_style(theme::pane_border(false)) - .style(theme::panel_surface(false)); - // Draw a 3-cell tall framed row by overlaying inner text. - let framed = Rect { - x: area.x, - y, - width: area.width, - height: 1, - }; - let _ = (block, framed); let meta = format!( "pid {} · {} · {}", it.pid.as_deref().unwrap_or("—"), @@ -301,7 +286,6 @@ fn render_running_strip(frame: &mut Frame<'_>, area: Rect, items: &[RunItem]) { Span::styled(" logs ↗", theme::subtle()), ]; frame.render_widget(Paragraph::new(Line::from(spans)), row); - y += 1; } } @@ -551,14 +535,11 @@ fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { lines.extend(body); frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner); - // Hint line below the card (only when there is vertical room). + // Hint line stays inside the reserved card area so rendering never spills into adjacent panes. if let Some(hint) = footer_hint { - if area.y + area.height + 1 < area.y + area.height { - return; - } let hint_rect = Rect { x: area.x + 2, - y: area.y + area.height, + y: area.y.saturating_add(area.height.saturating_sub(2)), width: area.width.saturating_sub(2), height: 1, }; diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index f1c4130..68e20c0 100644 --- a/src/ui/views/dashboard.rs +++ b/src/ui/views/dashboard.rs @@ -598,10 +598,7 @@ fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { } else { theme::muted() }; - spans.push(Span::styled( - format!("{}", tab.title().to_ascii_lowercase()), - name_style, - )); + spans.push(Span::styled(tab.title().to_ascii_lowercase(), name_style)); let count = match tab { DashboardTab::Services => state.services.registry.len(), DashboardTab::Processes => state.processes.snapshots.len(), diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs index e067daa..b043e03 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -13,8 +13,7 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, _focused: boo .timeline .entries .iter() - .rev() - .next() + .next_back() .map(|e| truncate_end(&e.message, 60)) .unwrap_or_else(|| "quiet — waiting on you".to_string()); let count = state.timeline.entries.len(); diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index de49921..a0744c0 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -37,21 +37,21 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }) .count(); - let branch_display = truncate_middle(&branch, 32); + let branch_display = truncate_middle(&branch_leaf(&branch), 28); let left = if project.eq_ignore_ascii_case("forge") { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" │ ", theme::subtle()), + Span::styled(" / ", theme::subtle()), Span::styled(branch_display, theme::status_context()), ] } else { vec![ Span::raw(" "), Span::styled("forge", theme::italic_serif()), - Span::styled(" │ ", theme::subtle()), + Span::styled(" / ", theme::subtle()), Span::styled(project, theme::status_context()), - Span::styled(" │ ", theme::subtle()), + Span::styled(" / ", theme::subtle()), Span::styled(branch_display, theme::status_context()), ] }; @@ -154,3 +154,12 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { .collect::(); format!("{start}…{end}") } + +fn branch_leaf(branch: &str) -> String { + branch + .rsplit('/') + .next() + .filter(|value| !value.is_empty()) + .unwrap_or(branch) + .to_string() +}