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/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/effects.rs b/src/app/effects.rs index 9e884bb..6edfea8 100644 --- a/src/app/effects.rs +++ b/src/app/effects.rs @@ -9,7 +9,20 @@ pub enum UiIntent { KeyChar(char), Backspace, Submit, + InsertNewline, ClearInput, + MoveCursorLeft, + MoveCursorRight, + MoveCursorUp, + MoveCursorDown, + MoveCursorHome, + MoveCursorEnd, + RecallPreviousHistory, + RecallNextHistory, + CycleInputMode, + PrevCommandSuggestion, + NextCommandSuggestion, + AcceptCommandSuggestion, NextFocus, PrevFocus, NextTab, diff --git a/src/app/store.rs b/src/app/store.rs index c41e9c8..daf6ed8 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, slash_command_suggestions, 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, 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}; @@ -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 { @@ -336,13 +350,23 @@ 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() { @@ -357,15 +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); - match parse_input(&raw) { + let raw = self.state.ui.input.take_buffer(); + self.state.ui.command_palette_cursor = 0; + 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()); @@ -374,7 +409,59 @@ 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); + } + UiIntent::NextCommandSuggestion => { + self.move_command_palette_cursor(true); + } + UiIntent::AcceptCommandSuggestion => { + self.accept_command_suggestion(); } UiIntent::NextFocus => { if self.state.ui.modal.is_some() { @@ -446,7 +533,8 @@ impl AppStore { None => Vec::new(), }; } - self.state.ui.input_buffer.clear(); + self.state.ui.input.clear(); + self.state.ui.command_palette_cursor = 0; } } Vec::new() @@ -461,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( @@ -508,6 +596,143 @@ impl AppStore { Vec::new() } ParsedInput::AiPrompt { prompt, kind } => self.prepare_ai_request(prompt, kind), + ParsedInput::ApplyAiProposal(index) => self.apply_ai_proposal(index), + } + } + + 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 len = self.active_suggestion_len(); + if len == 0 { + self.state.ui.command_palette_cursor = 0; + return; + } + + 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 len = self.active_suggestion_len(); + if len == 0 { + self.state.ui.command_palette_cursor = 0; + return; + } + 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 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(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) { + 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(), } } @@ -565,6 +790,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 +855,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 +877,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 +1166,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..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 { @@ -20,6 +96,39 @@ pub enum ParsedInput { prompt: String, kind: AiRequestKind, }, + 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 { @@ -29,12 +138,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 +188,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/domain/app.rs b/src/domain/app.rs index 32a4f0f..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,197 @@ 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), pub approval_cursor: usize, @@ -124,7 +310,8 @@ 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), approval_cursor: 0, @@ -150,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 0f9ba5c..935644c 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,11 @@ 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)) + } 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::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) @@ -182,6 +247,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/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..a3905d3 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1,5 +1,6 @@ +pub mod keys; pub mod terminal; pub mod theme; -mod views; +pub mod views; pub use views::render; diff --git a/src/ui/theme.rs b/src/ui/theme.rs index ee48db8..b2759e6 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -2,37 +2,117 @@ 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); +// 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_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); +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).fg(TEXT_PRIMARY) +} + +pub fn chrome_surface() -> Style { + Style::default().bg(BG_BASE).fg(TEXT_PRIMARY) +} 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_FOCUS } else { BG_PANEL }) + .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 { PANEL_FOCUS } else { TEXT_MUTED }) - .add_modifier(Modifier::BOLD) + .fg(if focused { TEXT_PRIMARY } else { TEXT_MUTED }) + .add_modifier(Modifier::ITALIC) } pub fn section_title() -> Style { - Style::default().fg(TEXT_MUTED).add_modifier(Modifier::BOLD) + 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) } +pub fn primary_emphasis() -> Style { + Style::default() + .fg(TEXT_PRIMARY) + .add_modifier(Modifier::BOLD) +} + pub fn muted() -> Style { Style::default().fg(TEXT_MUTED) } @@ -45,13 +125,67 @@ 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 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(Color::White, ACCENT) +} + pub fn status_badge(bg: Color) -> Style { + pill(Color::White, bg) +} + +pub fn quiet_badge() -> Style { + Style::default().fg(TEXT_MUTED).bg(BG_ELEVATED) +} + +pub fn focus_badge() -> Style { Style::default() - .fg(Color::Black) - .bg(bg) + .fg(Color::White) + .bg(ACCENT) .add_modifier(Modifier::BOLD) } +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_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 { ACCENT_SOFT } else { BG_PANEL }); + if selected { + style = style.add_modifier(Modifier::BOLD); + } + style +} + +pub fn command_palette_summary(selected: bool) -> Style { + Style::default().fg(if selected { TEXT_MUTED } else { TEXT_SUBTLE }) +} + pub fn notification_color(level: NotificationLevel) -> Color { match level { NotificationLevel::Info => INFO, @@ -85,9 +219,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 d0cbd9a..6e7838c 100644 --- a/src/ui/views/command_pane.rs +++ b/src/ui/views/command_pane.rs @@ -1,392 +1,811 @@ 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, BorderType, Borders, Padding, Paragraph, Wrap}; use ratatui::Frame; -use crate::domain::{AiMessageRole, AiStatus, AppState, ApprovalMode}; +use crate::commands::{slash_command_suggestions, SlashCommandSpec}; +use crate::domain::{AiStatus, AppState, ApprovalMode, InputMode}; use crate::shared::time::format_timestamp; -use crate::ui::theme; +use crate::ui::{keys, theme}; +// Intent suggestions shown while typing a non-slash command. +#[derive(Clone)] +pub(crate) struct IntentSuggestion { + pub mode: &'static str, // SHELL / BG / AI / HIST + pub cmd: String, + pub hint: String, +} + +// 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 / AI ", theme::panel_title(focused))) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)); - let inner = block.inner(area); - frame.render_widget(block, area); + // 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; + + // 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_slash = visible_command_suggestions(&slash_suggestions, state); + let intent_suggestions = intent_suggestions(state); + + 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 { + (running_items.len() as u16) + 3 + }; + 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 { + (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 { + 14 + } else { + 0 + }; + + 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, + 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::Min(0), Constraint::Length(5)]) - .split(inner); + .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), + Constraint::Min(0), + ]) + .split(column); - let top = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(4), Constraint::Min(0)]) - .split(sections[0]); + if running_h > 0 { + render_running_strip(frame, sections[0], &running_items); + } + if headline_h > 0 { + render_headline(frame, sections[1], state, dim); + } + render_prompt(frame, sections[3], state, dim); - 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); + if suggestion_h > 0 { + if slash_h > 0 { + render_slash_suggestions(frame, sections[5], &visible_slash); + } else { + 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); + } else if chips_h > 0 { + render_recent_chips(frame, sections[7], state); + } } -fn render_input(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { - let content_width = area.width.saturating_sub(6) as usize; - let visible_input = visible_input_text(&state.ui.input_buffer, content_width.max(8)); +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::prompt_question() + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled(text, style)])), + area, + ); + } +} - let lines = vec![ - Line::from(vec![ - Span::styled(" $ ", theme::status_badge(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() { - "Start typing a shell command or use /help for slash commands." - } else { - "Enter runs the command. Tab changes focus. Alt+Left/Right switches dashboard tabs." - }, - 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()), +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 = buf.trim_start().starts_with('/'); + + let arrow_color = if dim { + theme::subtle() + } else { + theme::accent() + }; + let arrow_char = if slash { + "/" + } else { + match mode { + InputMode::Shell => "▸", + InputMode::AiAssist | InputMode::AiDiagnose => "✦", + } + }; + + 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_type(BorderType::Rounded) + .border_style(theme::prompt_border()) + .style(theme::prompt_surface()) + .padding(Padding::new(3, 3, 1, 1)); + 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); + + 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::prompt_placeholder()), + Span::styled("█", theme::prompt_cursor(dim)), + ] + } else { + vec![ + Span::styled(format!("{arrow_char} "), arrow_color), Span::styled( - if focused { "command" } else { "other" }, - if focused { - theme::accent() - } else { + display, + if dim { theme::muted() + } else { + theme::primary_emphasis() }, ), - ]), - ]; + ] + }; + frame.render_widget( - Paragraph::new(lines).block( - Block::default() - .title(Span::styled(" Input ", theme::section_title())) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)), - ), - area, + Paragraph::new(Line::from(spans)).wrap(Wrap { trim: false }), + inner, ); } -fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); +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}█") +} - if let Some(approval) = state - .approvals - .pending +fn render_running_strip(frame: &mut Frame<'_>, area: Rect, items: &[RunItem]) { + // Heading row. + let heading = Rect { + x: area.x, + y: area.y, + width: area.width, + height: 1, + }; + frame.render_widget( + Paragraph::new(Line::from(vec![Span::styled("RUNNING", theme::subtle())])), + heading, + ); + + // 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 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); + } +} + +struct RunItem { + name: String, + cmd: String, + pid: Option, + uptime: String, + port: Option, +} + +fn running_items(state: &AppState) -> Vec { + state + .services + .registry .iter() - .find(|request| matches!(request.mode, ApprovalMode::InlineReview)) - { - lines.push(Line::from(vec![ - Span::styled("REVIEW ", theme::status_badge(theme::WARN)), + .filter(|s| { + matches!( + s.health, + crate::domain::ServiceHealth::Healthy | crate::domain::ServiceHealth::Starting + ) + }) + .take(3) + .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_slash_suggestions( + frame: &mut Frame<'_>, + area: Rect, + suggestions: &[(bool, &SlashCommandSpec)], +) { + 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 pill = Span::styled( + " SLASH ", + if *selected { + theme::focus_badge() + } else { + theme::quiet_badge() + }, + ); + let cmd_style = if *selected { + theme::primary_emphasis() + } else { + theme::muted() + }; + 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(" "), - Span::styled( - format!( - "#{} [{}] {}", - approval.command_id, - approval.class.label(), - approval.summary - ), - theme::primary(), - ), - ])); - lines.push(Line::from(vec![ - Span::styled("Enter", theme::accent()), - Span::styled(" approve", theme::muted()), + pill, Span::raw(" "), - Span::styled("Esc", theme::accent()), - 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::accent()), - Span::styled(" run command", theme::muted()), + Span::styled(cmd_text, cmd_style), Span::raw(" "), - Span::styled("Ctrl+L", theme::accent()), - Span::styled(" clear input", theme::muted()), - ])); + 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: false }), area); +} - 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)), +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 == selected_idx; + 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( - format!( - "[{}] {}", - format_timestamp(notification.created_at), - notification.message - ), - 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()), - ])); + 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) - .block(Block::default().title(Span::styled(" Activity ", theme::section_title()))) - .wrap(Wrap { trim: false }), - area, - ); + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); } -fn render_history(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); - - 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()), - ])); +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(); + } + if state.ui.input.mode.ai_kind().is_some() { + return Vec::new(); } - for record in state + 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() - .take(state.config.ui.history_preview.max(6)) + .find(|c| c.raw.starts_with(buf) && c.raw != buf) { - 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)), - Span::raw(" "), - Span::styled(record.raw.clone(), theme::primary()), - ])); + out.push(IntentSuggestion { + mode: "HIST", + cmd: truncate(&hist.raw, 60), + hint: "from history".into(), + }); } - let block = Block::default().title(Span::styled(" Recent Commands ", theme::section_title())); - frame.render_widget( - Paragraph::new(lines) - .block(block) - .wrap(Wrap { trim: false }), - area, - ); + out } -fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { - let mut lines = Vec::new(); - 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), - }; +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() +} - lines.push(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()) +fn render_context_card(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + // 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) + .border_style(if is_ai { + theme::accent() } else { - Span::styled(" model:default", theme::muted()) - }, - ])); + 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); - if let Some(request) = state.ai.requests.last() { - lines.push(Line::from(vec![ - Span::styled( - format!("{} ", request.kind.label().to_ascii_uppercase()), - theme::accent(), - ), + 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 stays inside the reserved card area so rendering never spills into adjacent panes. + if let Some(hint) = footer_hint { + let hint_rect = Rect { + x: area.x + 2, + y: area.y.saturating_add(area.height.saturating_sub(2)), + width: area.width.saturating_sub(2), + height: 1, + }; + frame.render_widget(Paragraph::new(hint), hint_rect); + } +} + +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 header = vec![ Span::styled( - visible_input_text(&request.prompt, area.width.saturating_sub(12) as usize), - theme::primary(), + 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(), + theme::primary_emphasis(), + )]), + Line::raw(""), + Line::from(vec![Span::styled( + truncate(&approval.detail, 280), + theme::muted(), + )]), + ]; + 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)); } - 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 state.ui.input.mode.ai_kind().is_some() + || matches!( + state.ai.status, + AiStatus::Running | AiStatus::Queued | AiStatus::Failed | AiStatus::Completed + ) + { + 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 right_label = match state.ai.status { + AiStatus::Running | AiStatus::Queued => "streaming…", + AiStatus::Failed => "error", + AiStatus::Completed => "done", + _ => "", + }; + 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::from(vec![Span::styled( + truncate(err, 300), + theme::error_accent(), )])); - } - 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(), - )])); + } else if let Some(resp) = state.ai.last_response.as_ref() { + // Big serif italic opener from summary. + body.push(Line::from(vec![Span::styled( + truncate(&resp.summary, 160), + theme::italic_serif(), + )])); + 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 let Some(response) = state.ai.last_response.as_ref() { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - response.summary.clone(), - theme::primary(), - )])); - lines.push(Line::from(vec![Span::styled( - truncate_multiline(&response.message, area.width.saturating_sub(4) as usize), - theme::muted(), + if !resp.proposals.is_empty() { + body.push(Line::raw("")); + // dashed divider + body.push(Line::from(vec![Span::styled( + "─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─", + theme::subtle(), )])); - if !response.recommendations.is_empty() { - lines.push(Line::raw("")); - lines.push(Line::from(vec![Span::styled( - "Recommendations", - theme::section_title(), - )])); - 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.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(), - ), - ])); - } + 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(" ")); } - } 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("")); - lines.push(Line::from(vec![Span::styled( - "Use /ai for assistance or /diagnose for grounded diagnosis.", - theme::muted(), - )])); + body.push(Line::from(chips)); } + } else if let Some(req) = state.ai.requests.last() { + 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(), + )])); } + + 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 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::muted(), + )])] + }; + return (header, body, None); } + ( + 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, + ) +} + +fn render_recent_chips(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + if area.height == 0 { + return; + } + let mut recents: Vec = state + .commands + .records + .iter() + .rev() + .take(3) + .map(|c| truncate(&c.raw, 24)) + .collect(); + if recents.is_empty() { + 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())]; + let last = recents.len().saturating_sub(1); + for (i, r) in recents.into_iter().enumerate() { + spans.push(Span::styled(format!(" {r} "), theme::quiet_badge())); + if i != last { + spans.push(Span::styled(" ", theme::subtle())); + } + } frame.render_widget( - Paragraph::new(lines) - .block(Block::default().title(Span::styled(" AI Response ", theme::section_title()))) - .wrap(Wrap { trim: false }), + Paragraph::new(Line::from(spans)).wrap(Wrap { trim: true }), area, ); } -fn visible_input_text(input: &str, max_chars: usize) -> String { - if input.is_empty() { - return "Type a shell command".to_string(); +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", } +} - let chars = input.chars().collect::>(); - if chars.len() <= max_chars { - return input.to_string(); +fn truncate(value: &str, max_chars: usize) -> String { + let joined = value.lines().collect::>().join(" "); + if joined.chars().count() <= max_chars { + return joined; } - - let tail = chars[chars.len().saturating_sub(max_chars - 1)..] - .iter() - .collect::(); - format!("…{tail}") + let kept: String = joined.chars().take(max_chars.saturating_sub(1)).collect(); + format!("{kept}…") } -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_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(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) + .take(visible_len) + .enumerate() + .map(|(offset, suggestion)| (visible_start + offset == selection, *suggestion)) + .collect() } diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs index ea7272f..68e20c0 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}; @@ -9,46 +9,305 @@ 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(" Dashboard ", theme::panel_title(focused))) - .borders(Borders::ALL) + .borders(Borders::LEFT) .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)); + .style(theme::panel_surface(focused)) + .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_tabs(frame, sections[0], state); - render_context(frame, sections[1], 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()), - 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 +316,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 +328,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 +345,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 +357,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 +379,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 +392,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 +404,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 +422,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 +435,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 +451,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 +463,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 +489,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 +500,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 +511,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,68 +533,153 @@ fn test_lines(state: &AppState) -> Vec> { lines } +#[allow(dead_code)] +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() + 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(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() + }, + )); + } + spans.push(Span::raw(" ")); + } + + // Underline marker row below. + let tab_line = Line::from(spans); + + // Build underline segment roughly beneath active tab name. + let active_idx = 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::muted()) - } - }) - .collect::>(); + .position(|t| *t == state.ui.dashboard_tab) + .unwrap_or(0); + let underline = build_tab_underline(state, active_idx, area.width as usize); - let mut content = Vec::new(); - for (index, tab) in tabs.into_iter().enumerate() { - if index > 0 { - content.push(Span::raw(" ")); + frame.render_widget(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()), + ]; } - content.push(tab); + acc.push_str(&" ".repeat(block_len + 4)); } - content.push(Span::raw(" ")); - content.push(Span::styled("Left/Right", theme::accent())); - content.push(Span::styled(" switch tabs", theme::muted())); + vec![Span::raw(acc)] +} - frame.render_widget( - Paragraph::new(Line::from(content)).block(Block::default()), - area, - ); +#[allow(dead_code)] +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 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 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 263c414..b043e03 100644 --- a/src/ui/views/event_stream.rs +++ b/src/ui/views/event_stream.rs @@ -1,92 +1,96 @@ use ratatui::layout::Rect; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::widgets::{Block, Paragraph}; use ratatui::Frame; -use crate::domain::{AppState, TimelineKind}; -use crate::shared::time::format_timestamp; -use crate::ui::theme; +use crate::domain::AppState; +use crate::ui::{keys, 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) { + frame.render_widget(Block::default().style(theme::chrome_surface()), area); - frame.render_widget( - Paragraph::new(lines) - .block( - Block::default() - .title(Span::styled(" Event Stream ", theme::panel_title(focused))) - .borders(Borders::ALL) - .border_style(theme::pane_border(focused)) - .style(theme::primary().bg(theme::BG_BASE)), - ) - .wrap(Wrap { trim: false }), - area, - ); -} + let latest = state + .timeline + .entries + .iter() + .next_back() + .map(|e| truncate_end(&e.message, 60)) + .unwrap_or_else(|| "quiet — waiting on you".to_string()); + let count = state.timeline.entries.len(); -fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { - let mut collapsed: Vec = Vec::new(); + let left_spans = vec![ + Span::raw(" "), + Span::styled("▸ ", theme::subtle()), + Span::styled(latest, theme::muted()), + Span::styled(format!(" · {count}"), theme::subtle()), + ]; - 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 right_spans = vec![ + Span::styled(format!(" {} ", keys::meta("O")), theme::keycap()), + Span::styled(" ops", theme::muted()), + Span::raw(" "), + Span::styled(format!(" {} ", keys::meta("L")), theme::keycap()), + Span::styled(" activity", theme::muted()), + Span::raw(" "), + Span::styled(format!(" {} ", keys::meta("/")), theme::keycap()), + Span::styled(" ai", theme::muted()), + Span::raw(" "), + Span::styled(format!(" {} ", keys::meta("K")), theme::keycap()), + Span::styled(" commands", theme::muted()), + Span::raw(" "), + ]; - if collapsed.is_empty() { - return vec![Line::from(vec![Span::styled( - "No events yet. Run a command to populate the timeline.", - theme::muted(), - )])]; + 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, + ); } - 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(entry.message, theme::primary()), - ]; - if entry.count > 1 { - spans.push(Span::raw(" ")); - spans.push(Span::styled(format!("×{}", entry.count), theme::muted())); - } - Line::from(spans) - }) - .collect() + let mid = area.width / 2; + let left_area = Rect { + x: area.x, + y: content_y, + width: mid, + height: 1, + }; + let right_area = Rect { + x: area.x + mid, + y: content_y, + width: area.width.saturating_sub(mid), + height: 1, + }; + + 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, + ); } -struct CollapsedEntry { - at: std::time::SystemTime, - last_seen: std::time::SystemTime, - kind: TimelineKind, - message: String, - count: usize, +fn truncate_end(value: &str, max_chars: usize) -> String { + let joined = value.lines().collect::>().join(" "); + if joined.chars().count() <= max_chars { + return joined; + } + let kept = joined + .chars() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{kept}…") } diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs index 4fc0ff9..072038f 100644 --- a/src/ui/views/mod.rs +++ b/src/ui/views/mod.rs @@ -1,51 +1,59 @@ mod command_pane; + +pub(crate) use command_pane::intent_suggestions; mod dashboard; mod event_stream; 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::app_surface()), frame.area()); + let layout = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(3), - Constraint::Min(12), - Constraint::Length(state.config.ui.event_stream_height), + Constraint::Length(3), // top identity bar + hairline + Constraint::Min(8), // main stage + Constraint::Length(2), // bottom activity rail + hairline ]) .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), - ]) - .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/modal.rs b/src/ui/views/modal.rs index de3daff..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."), @@ -52,7 +74,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, ); @@ -69,16 +92,23 @@ 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"), 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("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"), @@ -93,7 +123,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, ); @@ -107,7 +138,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, ); @@ -115,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 30a9757..a0744c0 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -1,12 +1,14 @@ -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::{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 @@ -18,95 +20,110 @@ 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" + + 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 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(branch_display, theme::status_context()), + ] } 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", + vec![ + Span::raw(" "), + Span::styled("forge", theme::italic_serif()), + Span::styled(" / ", theme::subtle()), + Span::styled(project, theme::status_context()), + Span::styled(" / ", theme::subtle()), + Span::styled(branch_display, theme::status_context()), + ] }; - 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 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 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, }; - 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), - ]) - .split(area); + // Two paragraphs: left-aligned + right-aligned, matching the sparse wireframe bar. + let mid = text_area.width / 2; + let left_area = Rect { + x: text_area.x, + y: text_area.y, + width: mid, + height: 1, + }; + let right_area = Rect { + x: text_area.x + mid, + y: text_area.y, + width: text_area.width.saturating_sub(mid), + height: 1, + }; frame.render_widget( - Block::default() - .borders(Borders::BOTTOM) - .border_style(theme::pane_border(false)), - area, + Paragraph::new(Line::from(left)).style(theme::chrome_surface()), + left_area, + ); + frame.render_widget( + Paragraph::new(Line::from(right)) + .alignment(ratatui::layout::Alignment::Right) + .style(theme::chrome_surface()), + right_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 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]); -} - -fn badge<'a>(label: &'a str, value: &'a str, bg: ratatui::style::Color) -> Span<'a> { - Span::styled(format!(" {label}:{value} "), theme::status_badge(bg)) + 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 { @@ -138,59 +155,11 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { format!("{start}…{end}") } -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()), - Span::styled(" approve", theme::muted()), - Span::raw(" "), - Span::styled("Esc", theme::accent()), - 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()), - ]) - } - 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::DashboardPane => Line::from(vec![ - Span::styled("Left/Right", theme::accent()), - Span::styled(" switch tabs", theme::muted()), - Span::raw(" "), - Span::styled("Tab", theme::accent()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("F1", theme::accent()), - Span::styled(" help", theme::muted()), - ]), - crate::domain::FocusTarget::EventStream => Line::from(vec![ - Span::styled("Tab", theme::accent()), - Span::styled(" next pane", theme::muted()), - Span::raw(" "), - Span::styled("F1", theme::accent()), - Span::styled(" help", theme::muted()), - ]), - crate::domain::FocusTarget::Modal => Line::from(vec![ - Span::styled("Esc", theme::accent()), - Span::styled(" close", theme::muted()), - ]), - }, - } +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 2afa756..797d918 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -1,16 +1,19 @@ 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, ParsedInput}; +use forge::commands::{parse_input, slash_command_suggestions, 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, InputMode, 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 +90,17 @@ 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()); + + let suggestions = slash_command_suggestions("/"); + assert!(!suggestions.is_empty()); + assert!(suggestions.iter().any(|command| command.usage == "/help")); } #[test] @@ -214,10 +228,70 @@ 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_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(); - 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(), @@ -233,10 +307,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(); @@ -293,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)) + }) +}