| 1 | use std::any::Any; |
| 2 | use std::collections::BTreeMap; |
| 3 | use std::fs; |
| 4 | use std::io::{Stdout, Write}; |
| 5 | use std::path::{Component, Path, PathBuf}; |
| 6 | |
| 7 | use anyhow::Result; |
| 8 | use codewhale_config::AppMode; |
| 9 | use codewhale_engine::core::engine::EngineHandle; |
| 10 | use codewhale_execpolicy::ApprovalMode; |
| 11 | use codewhale_palette as palette; |
| 12 | use codewhale_runtime::config::Config; |
| 13 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; |
| 14 | use ratatui::{ |
| 15 | Terminal, |
| 16 | buffer::Buffer, |
| 17 | layout::{Constraint, Direction, Layout, Rect}, |
| 18 | style::{Modifier, Style}, |
| 19 | text::{Line, Span}, |
| 20 | widgets::{Paragraph, Widget, Wrap}, |
| 21 | }; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use tempfile::Builder; |
| 24 | |
| 25 | use crate::tui::app::{App, StatusToastLevel}; |
| 26 | use crate::tui::color_compat::ColorCompatBackend; |
| 27 | use crate::tui::external_editor::{EditorOutcome, spawn_editor_for_path}; |
| 28 | use crate::tui::history::HistoryCell; |
| 29 | use crate::tui::views::{ |
| 30 | ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, action_footer_lines, |
| 31 | centered_modal_area, render_modal_rule, render_panel_scroll_rail, render_rounded_modal, |
| 32 | render_wrapped_detail, |
| 33 | }; |
| 34 | |
| 35 | pub(crate) const PANEL_COMMAND_PREFIX: &str = "__plan_artifact:"; |
| 36 | const PANEL_CMD_EDIT: &str = "__plan_artifact:edit"; |
| 37 | const PANEL_CMD_BUILD_ASK: &str = "__plan_artifact:build:ask"; |
| 38 | const PANEL_CMD_BUILD_ACCEPT_EDITS: &str = "__plan_artifact:build:accept-edits"; |
| 39 | const PANEL_CMD_BUILD_AUTO: &str = "__plan_artifact:build:auto"; |
| 40 | |
| 41 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 42 | pub(crate) struct PlanStep { |
| 43 | pub index: usize, |
| 44 | pub number: usize, |
| 45 | pub title: String, |
| 46 | pub checked: Option<bool>, |
| 47 | pub line_number: usize, |
| 48 | } |
| 49 | |
| 50 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 51 | pub(crate) struct PlanNotes { |
| 52 | #[serde(default)] |
| 53 | pub notes: BTreeMap<usize, Vec<String>>, |
| 54 | } |
| 55 | |
| 56 | impl PlanNotes { |
| 57 | pub(crate) fn total_count(&self) -> usize { |
| 58 | self.notes.values().map(Vec::len).sum() |
| 59 | } |
| 60 | |
| 61 | pub(crate) fn for_step(&self, step_index: usize) -> &[String] { |
| 62 | self.notes |
| 63 | .get(&step_index) |
| 64 | .map(Vec::as_slice) |
| 65 | .unwrap_or(&[]) |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn add(&mut self, step_index: usize, note: String) { |
| 69 | let trimmed = note.trim(); |
| 70 | if trimmed.is_empty() { |
| 71 | return; |
| 72 | } |
| 73 | self.notes |
| 74 | .entry(step_index) |
| 75 | .or_default() |
| 76 | .push(trimmed.to_string()); |
| 77 | } |
| 78 | |
| 79 | pub(crate) fn pop(&mut self, step_index: usize) -> Option<String> { |
| 80 | let entry = self.notes.get_mut(&step_index)?; |
| 81 | let popped = entry.pop(); |
| 82 | if entry.is_empty() { |
| 83 | self.notes.remove(&step_index); |
| 84 | } |
| 85 | popped |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 90 | pub(crate) enum PlanViewMode { |
| 91 | Steps, |
| 92 | Raw, |
| 93 | } |
| 94 | |
| 95 | pub(crate) fn validate_session_id(session_id: &str) -> Result<&str, String> { |
| 96 | let trimmed = session_id.trim(); |
| 97 | if trimmed.is_empty() || trimmed != session_id { |
| 98 | return Err("Invalid session id".to_string()); |
| 99 | } |
| 100 | if trimmed.contains('\0') || trimmed.contains('/') || trimmed.contains('\\') { |
| 101 | return Err("Session id contains path separator".to_string()); |
| 102 | } |
| 103 | let mut components = Path::new(trimmed).components(); |
| 104 | match (components.next(), components.next()) { |
| 105 | (Some(Component::Normal(_)), None) => Ok(trimmed), |
| 106 | _ => Err("Invalid session id path component".to_string()), |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | pub(crate) fn plan_artifact_dir(session_id: &str) -> Result<PathBuf, String> { |
| 111 | let valid = validate_session_id(session_id)?; |
| 112 | let home = codewhale_config::codewhale_home().map_err(|err| err.to_string())?; |
| 113 | Ok(home.join("sessions").join(valid)) |
| 114 | } |
| 115 | |
| 116 | pub(crate) fn plan_markdown_path(session_id: &str) -> Result<PathBuf, String> { |
| 117 | Ok(plan_artifact_dir(session_id)?.join("plan.md")) |
| 118 | } |
| 119 | |
| 120 | pub(crate) fn plan_notes_path(session_id: &str) -> Result<PathBuf, String> { |
| 121 | Ok(plan_artifact_dir(session_id)?.join("plan.notes.json")) |
| 122 | } |
| 123 | |
| 124 | fn atomic_write_bytes(path: &Path, bytes: &[u8]) -> Result<(), String> { |
| 125 | let parent = path |
| 126 | .parent() |
| 127 | .ok_or_else(|| format!("Path has no parent directory: {}", path.display()))?; |
| 128 | fs::create_dir_all(parent) |
| 129 | .map_err(|err| format!("Failed to create {}: {err}", parent.display()))?; |
| 130 | if let Ok(meta) = fs::symlink_metadata(path) |
| 131 | && meta.file_type().is_symlink() |
| 132 | { |
| 133 | return Err(format!( |
| 134 | "Refusing to write through symlink: {}", |
| 135 | path.display() |
| 136 | )); |
| 137 | } |
| 138 | let mut tmp = Builder::new() |
| 139 | .prefix(".plan-") |
| 140 | .suffix(".tmp") |
| 141 | .tempfile_in(parent) |
| 142 | .map_err(|err| format!("Failed to create temp file in {}: {err}", parent.display()))?; |
| 143 | tmp.write_all(bytes) |
| 144 | .map_err(|err| format!("Failed to write temp file: {err}"))?; |
| 145 | tmp.as_file() |
| 146 | .sync_all() |
| 147 | .map_err(|err| format!("Failed to sync temp file: {err}"))?; |
| 148 | tmp.persist(path) |
| 149 | .map_err(|err| format!("Failed to persist {}: {}", path.display(), err.error))?; |
| 150 | Ok(()) |
| 151 | } |
| 152 | |
| 153 | pub(crate) fn save_plan_markdown(session_id: &str, markdown: &str) -> Result<PathBuf, String> { |
| 154 | let path = plan_markdown_path(session_id)?; |
| 155 | atomic_write_bytes(&path, markdown.as_bytes())?; |
| 156 | Ok(path) |
| 157 | } |
| 158 | |
| 159 | pub(crate) fn load_plan_markdown(session_id: &str) -> Result<Option<String>, String> { |
| 160 | let path = plan_markdown_path(session_id)?; |
| 161 | if !path.exists() { |
| 162 | return Ok(None); |
| 163 | } |
| 164 | if let Ok(meta) = fs::symlink_metadata(&path) |
| 165 | && meta.file_type().is_symlink() |
| 166 | { |
| 167 | return Err(format!("Refusing to read symlink: {}", path.display())); |
| 168 | } |
| 169 | fs::read_to_string(&path) |
| 170 | .map(Some) |
| 171 | .map_err(|err| format!("Failed to read {}: {err}", path.display())) |
| 172 | } |
| 173 | |
| 174 | pub(crate) fn save_plan_notes(session_id: &str, notes: &PlanNotes) -> Result<PathBuf, String> { |
| 175 | let path = plan_notes_path(session_id)?; |
| 176 | let bytes = serde_json::to_vec_pretty(notes) |
| 177 | .map_err(|err| format!("Failed to serialize plan notes: {err}"))?; |
| 178 | atomic_write_bytes(&path, &bytes)?; |
| 179 | Ok(path) |
| 180 | } |
| 181 | |
| 182 | pub(crate) fn load_plan_notes(session_id: &str) -> Result<PlanNotes, String> { |
| 183 | let path = plan_notes_path(session_id)?; |
| 184 | if !path.exists() { |
| 185 | return Ok(PlanNotes::default()); |
| 186 | } |
| 187 | if let Ok(meta) = fs::symlink_metadata(&path) |
| 188 | && meta.file_type().is_symlink() |
| 189 | { |
| 190 | return Err(format!("Refusing to read symlink: {}", path.display())); |
| 191 | } |
| 192 | let raw = fs::read_to_string(&path) |
| 193 | .map_err(|err| format!("Failed to read {}: {err}", path.display()))?; |
| 194 | serde_json::from_str(&raw).map_err(|err| format!("Failed to parse {}: {err}", path.display())) |
| 195 | } |
| 196 | |
| 197 | fn parse_list_item(line: &str) -> Option<(Option<bool>, String)> { |
| 198 | let trimmed = line.trim_start(); |
| 199 | if let Some(rest) = trimmed |
| 200 | .strip_prefix("- [ ] ") |
| 201 | .or_else(|| trimmed.strip_prefix("* [ ] ")) |
| 202 | .or_else(|| trimmed.strip_prefix("+ [ ] ")) |
| 203 | { |
| 204 | let title = rest.trim(); |
| 205 | return (!title.is_empty()).then(|| (Some(false), title.to_string())); |
| 206 | } |
| 207 | if let Some(rest) = trimmed |
| 208 | .strip_prefix("- [x] ") |
| 209 | .or_else(|| trimmed.strip_prefix("- [X] ")) |
| 210 | .or_else(|| trimmed.strip_prefix("* [x] ")) |
| 211 | .or_else(|| trimmed.strip_prefix("* [X] ")) |
| 212 | .or_else(|| trimmed.strip_prefix("+ [x] ")) |
| 213 | .or_else(|| trimmed.strip_prefix("+ [X] ")) |
| 214 | { |
| 215 | let title = rest.trim(); |
| 216 | return (!title.is_empty()).then(|| (Some(true), title.to_string())); |
| 217 | } |
| 218 | if let Some(rest) = trimmed |
| 219 | .strip_prefix("- ") |
| 220 | .or_else(|| trimmed.strip_prefix("* ")) |
| 221 | .or_else(|| trimmed.strip_prefix("+ ")) |
| 222 | { |
| 223 | let title = rest.trim(); |
| 224 | return (!title.is_empty()).then(|| (None, title.to_string())); |
| 225 | } |
| 226 | let digit_len = trimmed.bytes().take_while(u8::is_ascii_digit).count(); |
| 227 | if digit_len > 0 { |
| 228 | let after_digits = &trimmed[digit_len..]; |
| 229 | if let Some(rest) = after_digits |
| 230 | .strip_prefix(". ") |
| 231 | .or_else(|| after_digits.strip_prefix(") ")) |
| 232 | { |
| 233 | let title = rest.trim(); |
| 234 | return (!title.is_empty()).then(|| (None, title.to_string())); |
| 235 | } |
| 236 | } |
| 237 | None |
| 238 | } |
| 239 | |
| 240 | pub(crate) fn parse_plan_steps(markdown: &str) -> Vec<PlanStep> { |
| 241 | let mut steps = Vec::new(); |
| 242 | let mut in_fence = false; |
| 243 | for (idx, line) in markdown.lines().enumerate() { |
| 244 | let trimmed = line.trim(); |
| 245 | if trimmed.starts_with("```") || trimmed.starts_with("~~~") { |
| 246 | in_fence = !in_fence; |
| 247 | continue; |
| 248 | } |
| 249 | if in_fence { |
| 250 | continue; |
| 251 | } |
| 252 | if let Some((checked, title)) = parse_list_item(line) { |
| 253 | let index = steps.len(); |
| 254 | steps.push(PlanStep { |
| 255 | index, |
| 256 | number: index + 1, |
| 257 | title, |
| 258 | checked, |
| 259 | line_number: idx + 1, |
| 260 | }); |
| 261 | } |
| 262 | } |
| 263 | if !steps.is_empty() { |
| 264 | return steps; |
| 265 | } |
| 266 | |
| 267 | in_fence = false; |
| 268 | for (idx, line) in markdown.lines().enumerate() { |
| 269 | let trimmed = line.trim(); |
| 270 | if trimmed.starts_with("```") || trimmed.starts_with("~~~") { |
| 271 | in_fence = !in_fence; |
| 272 | continue; |
| 273 | } |
| 274 | if in_fence { |
| 275 | continue; |
| 276 | } |
| 277 | if trimmed.starts_with('#') { |
| 278 | let title = trimmed.trim_start_matches('#').trim(); |
| 279 | if !title.is_empty() { |
| 280 | let index = steps.len(); |
| 281 | steps.push(PlanStep { |
| 282 | index, |
| 283 | number: index + 1, |
| 284 | title: title.to_string(), |
| 285 | checked: None, |
| 286 | line_number: idx + 1, |
| 287 | }); |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | if !steps.is_empty() { |
| 292 | return steps; |
| 293 | } |
| 294 | |
| 295 | in_fence = false; |
| 296 | let mut in_paragraph = false; |
| 297 | for (idx, line) in markdown.lines().enumerate() { |
| 298 | let trimmed = line.trim(); |
| 299 | if trimmed.starts_with("```") || trimmed.starts_with("~~~") { |
| 300 | in_fence = !in_fence; |
| 301 | in_paragraph = false; |
| 302 | continue; |
| 303 | } |
| 304 | if in_fence || trimmed.is_empty() { |
| 305 | in_paragraph = false; |
| 306 | continue; |
| 307 | } |
| 308 | if !in_paragraph { |
| 309 | in_paragraph = true; |
| 310 | let index = steps.len(); |
| 311 | steps.push(PlanStep { |
| 312 | index, |
| 313 | number: index + 1, |
| 314 | title: trimmed.to_string(), |
| 315 | checked: None, |
| 316 | line_number: idx + 1, |
| 317 | }); |
| 318 | } |
| 319 | } |
| 320 | steps |
| 321 | } |
| 322 | |
| 323 | pub(crate) fn compose_execution_plan( |
| 324 | markdown: &str, |
| 325 | steps: &[PlanStep], |
| 326 | notes: &PlanNotes, |
| 327 | ) -> String { |
| 328 | let base = markdown.trim(); |
| 329 | if notes.total_count() == 0 { |
| 330 | return base.to_string(); |
| 331 | } |
| 332 | let mut out = base.to_string(); |
| 333 | out.push_str("\n\n## Review Notes\n"); |
| 334 | for (step_idx, step_notes) in ¬es.notes { |
| 335 | let label = steps |
| 336 | .get(*step_idx) |
| 337 | .map(|step| format!("Step {} ({})", step.number, step.title)) |
| 338 | .unwrap_or_else(|| format!("Step {}", step_idx + 1)); |
| 339 | for note in step_notes { |
| 340 | out.push_str(&format!("- {label}: {note}\n")); |
| 341 | } |
| 342 | } |
| 343 | out.trim_end().to_string() |
| 344 | } |
| 345 | |
| 346 | fn sanitize_pasted_note(text: &str) -> String { |
| 347 | let mut out = String::with_capacity(text.len()); |
| 348 | let mut last_was_space = false; |
| 349 | for ch in text.chars() { |
| 350 | if matches!(ch, '\n' | '\r' | '\t') { |
| 351 | if !last_was_space { |
| 352 | out.push(' '); |
| 353 | last_was_space = true; |
| 354 | } |
| 355 | } else if !ch.is_control() { |
| 356 | out.push(ch); |
| 357 | last_was_space = false; |
| 358 | } |
| 359 | } |
| 360 | out |
| 361 | } |
| 362 | |
| 363 | fn char_to_byte_index(text: &str, char_idx: usize) -> usize { |
| 364 | text.char_indices() |
| 365 | .nth(char_idx) |
| 366 | .map_or(text.len(), |(byte_idx, _)| byte_idx) |
| 367 | } |
| 368 | |
| 369 | fn latest_plan_candidate_from_app(app: &App) -> Option<String> { |
| 370 | if let Some(pending) = app.pending_plan_handoff.as_ref() |
| 371 | && app.current_session_id.as_deref() == Some(pending.session_id.as_str()) |
| 372 | && !pending.text.trim().is_empty() |
| 373 | { |
| 374 | return Some(pending.text.clone()); |
| 375 | } |
| 376 | app.history.iter().rev().find_map(|cell| match cell { |
| 377 | HistoryCell::Assistant { |
| 378 | content, |
| 379 | streaming: false, |
| 380 | } if !content.trim().is_empty() => Some(content.clone()), |
| 381 | _ => None, |
| 382 | }) |
| 383 | } |
| 384 | |
| 385 | const BUILD_POSTURES: [(ApprovalMode, &str, &str, &str); 3] = [ |
| 386 | ( |
| 387 | ApprovalMode::Suggest, |
| 388 | "Ask", |
| 389 | "Confirm edits and commands as Work runs", |
| 390 | PANEL_CMD_BUILD_ASK, |
| 391 | ), |
| 392 | ( |
| 393 | ApprovalMode::AcceptEdits, |
| 394 | "Accept Edits", |
| 395 | "Auto-accept workspace edits, ask before commands", |
| 396 | PANEL_CMD_BUILD_ACCEPT_EDITS, |
| 397 | ), |
| 398 | ( |
| 399 | ApprovalMode::Auto, |
| 400 | "Auto-Review", |
| 401 | "Auto-review safe actions against this approved plan", |
| 402 | PANEL_CMD_BUILD_AUTO, |
| 403 | ), |
| 404 | ]; |
| 405 | |
| 406 | pub(crate) struct PlanArtifactView { |
| 407 | pub(crate) session_id: Option<String>, |
| 408 | pub(crate) plan_path: Option<PathBuf>, |
| 409 | pub(crate) markdown: String, |
| 410 | pub(crate) steps: Vec<PlanStep>, |
| 411 | pub(crate) notes: PlanNotes, |
| 412 | pub(crate) view_mode: PlanViewMode, |
| 413 | pub(crate) selected_step: usize, |
| 414 | pub(crate) raw_scroll: usize, |
| 415 | pub(crate) annotation_input: Option<String>, |
| 416 | pub(crate) annotation_cursor: usize, |
| 417 | pub(crate) build_confirm_open: bool, |
| 418 | pub(crate) build_posture_index: usize, |
| 419 | pending_panel_command: Option<String>, |
| 420 | pub(crate) status_notice: Option<(String, StatusToastLevel)>, |
| 421 | pub(crate) saved_on_disk: bool, |
| 422 | } |
| 423 | |
| 424 | impl PlanArtifactView { |
| 425 | pub(crate) fn new( |
| 426 | session_id: Option<String>, |
| 427 | plan_path: Option<PathBuf>, |
| 428 | markdown: String, |
| 429 | notes: PlanNotes, |
| 430 | saved_on_disk: bool, |
| 431 | default_posture: ApprovalMode, |
| 432 | ) -> Self { |
| 433 | let steps = parse_plan_steps(&markdown); |
| 434 | let build_posture_index = match default_posture { |
| 435 | ApprovalMode::AcceptEdits => 1, |
| 436 | ApprovalMode::Auto => 2, |
| 437 | _ => 0, |
| 438 | }; |
| 439 | Self { |
| 440 | session_id, |
| 441 | plan_path, |
| 442 | markdown, |
| 443 | steps, |
| 444 | notes, |
| 445 | view_mode: PlanViewMode::Steps, |
| 446 | selected_step: 0, |
| 447 | raw_scroll: 0, |
| 448 | annotation_input: None, |
| 449 | annotation_cursor: 0, |
| 450 | build_confirm_open: false, |
| 451 | build_posture_index, |
| 452 | pending_panel_command: None, |
| 453 | status_notice: None, |
| 454 | saved_on_disk, |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | pub(crate) fn selected_step_line(&self) -> Option<u32> { |
| 459 | self.steps |
| 460 | .get(self.selected_step) |
| 461 | .and_then(|step| u32::try_from(step.line_number).ok()) |
| 462 | } |
| 463 | |
| 464 | pub(crate) fn save_to_disk(&mut self) -> Result<PathBuf, String> { |
| 465 | let session_id = self |
| 466 | .session_id |
| 467 | .as_deref() |
| 468 | .ok_or_else(|| "No active session id for plan artifact".to_string())?; |
| 469 | if self.markdown.trim().is_empty() { |
| 470 | return Err("No plan content to save yet".to_string()); |
| 471 | } |
| 472 | let path = save_plan_markdown(session_id, &self.markdown)?; |
| 473 | save_plan_notes(session_id, &self.notes)?; |
| 474 | self.plan_path = Some(path.clone()); |
| 475 | self.saved_on_disk = true; |
| 476 | self.status_notice = Some(( |
| 477 | format!("Saved plan to {}", path.display()), |
| 478 | StatusToastLevel::Success, |
| 479 | )); |
| 480 | Ok(path) |
| 481 | } |
| 482 | |
| 483 | pub(crate) fn reload_from_disk(&mut self, notice: Option<(String, StatusToastLevel)>) { |
| 484 | if let Some(session_id) = self.session_id.as_deref() { |
| 485 | match load_plan_markdown(session_id) { |
| 486 | Ok(Some(markdown)) => { |
| 487 | self.markdown = markdown; |
| 488 | self.steps = parse_plan_steps(&self.markdown); |
| 489 | if !self.steps.is_empty() { |
| 490 | self.selected_step = self.selected_step.min(self.steps.len() - 1); |
| 491 | } else { |
| 492 | self.selected_step = 0; |
| 493 | } |
| 494 | self.saved_on_disk = true; |
| 495 | } |
| 496 | Ok(None) => {} |
| 497 | Err(error) => { |
| 498 | self.status_notice = Some((error, StatusToastLevel::Error)); |
| 499 | return; |
| 500 | } |
| 501 | } |
| 502 | if let Ok(notes) = load_plan_notes(session_id) { |
| 503 | self.notes = notes; |
| 504 | } |
| 505 | if let Ok(path) = plan_markdown_path(session_id) { |
| 506 | self.plan_path = Some(path); |
| 507 | } |
| 508 | } |
| 509 | if let Some(notice) = notice { |
| 510 | self.status_notice = Some(notice); |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | fn move_up(&mut self, amount: usize) { |
| 515 | match self.view_mode { |
| 516 | PlanViewMode::Steps => { |
| 517 | self.selected_step = self.selected_step.saturating_sub(amount); |
| 518 | } |
| 519 | PlanViewMode::Raw => { |
| 520 | self.raw_scroll = self.raw_scroll.saturating_sub(amount); |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | fn move_down(&mut self, amount: usize) { |
| 526 | match self.view_mode { |
| 527 | PlanViewMode::Steps => { |
| 528 | if !self.steps.is_empty() { |
| 529 | self.selected_step = |
| 530 | (self.selected_step.saturating_add(amount)).min(self.steps.len() - 1); |
| 531 | } |
| 532 | } |
| 533 | PlanViewMode::Raw => { |
| 534 | let max_line = self.markdown.lines().count().saturating_sub(1); |
| 535 | self.raw_scroll = self.raw_scroll.saturating_add(amount).min(max_line); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn handle_annotation_key(&mut self, key: KeyEvent) -> ViewAction { |
| 541 | match key.code { |
| 542 | KeyCode::Esc => { |
| 543 | self.annotation_input = None; |
| 544 | self.annotation_cursor = 0; |
| 545 | ViewAction::Redraw |
| 546 | } |
| 547 | KeyCode::Enter => { |
| 548 | let text = self.annotation_input.take().unwrap_or_default(); |
| 549 | self.annotation_cursor = 0; |
| 550 | let trimmed = text.trim(); |
| 551 | if !trimmed.is_empty() && !self.steps.is_empty() { |
| 552 | let step_idx = self.selected_step; |
| 553 | self.notes.add(step_idx, trimmed.to_string()); |
| 554 | if let Some(session_id) = self.session_id.as_deref() { |
| 555 | match save_plan_notes(session_id, &self.notes) { |
| 556 | Ok(_) => { |
| 557 | self.status_notice = Some(( |
| 558 | format!("Saved note on step {}", step_idx + 1), |
| 559 | StatusToastLevel::Success, |
| 560 | )); |
| 561 | } |
| 562 | Err(err) => { |
| 563 | self.status_notice = Some((err, StatusToastLevel::Error)); |
| 564 | } |
| 565 | } |
| 566 | } else { |
| 567 | self.status_notice = Some(( |
| 568 | format!("Added note on step {}", step_idx + 1), |
| 569 | StatusToastLevel::Info, |
| 570 | )); |
| 571 | } |
| 572 | } |
| 573 | ViewAction::Redraw |
| 574 | } |
| 575 | KeyCode::Backspace => { |
| 576 | if let Some(input) = self.annotation_input.as_mut() |
| 577 | && self.annotation_cursor > 0 |
| 578 | { |
| 579 | let prev_char = self.annotation_cursor - 1; |
| 580 | let start = char_to_byte_index(input, prev_char); |
| 581 | let end = char_to_byte_index(input, self.annotation_cursor); |
| 582 | input.replace_range(start..end, ""); |
| 583 | self.annotation_cursor = prev_char; |
| 584 | } |
| 585 | ViewAction::Redraw |
| 586 | } |
| 587 | KeyCode::Delete => { |
| 588 | if let Some(input) = self.annotation_input.as_mut() { |
| 589 | let len = input.chars().count(); |
| 590 | if self.annotation_cursor < len { |
| 591 | let start = char_to_byte_index(input, self.annotation_cursor); |
| 592 | let end = char_to_byte_index(input, self.annotation_cursor + 1); |
| 593 | input.replace_range(start..end, ""); |
| 594 | } |
| 595 | } |
| 596 | ViewAction::Redraw |
| 597 | } |
| 598 | KeyCode::Left => { |
| 599 | self.annotation_cursor = self.annotation_cursor.saturating_sub(1); |
| 600 | ViewAction::Redraw |
| 601 | } |
| 602 | KeyCode::Right => { |
| 603 | if let Some(input) = self.annotation_input.as_ref() { |
| 604 | self.annotation_cursor = |
| 605 | (self.annotation_cursor + 1).min(input.chars().count()); |
| 606 | } |
| 607 | ViewAction::Redraw |
| 608 | } |
| 609 | KeyCode::Home => { |
| 610 | self.annotation_cursor = 0; |
| 611 | ViewAction::Redraw |
| 612 | } |
| 613 | KeyCode::End => { |
| 614 | if let Some(input) = self.annotation_input.as_ref() { |
| 615 | self.annotation_cursor = input.chars().count(); |
| 616 | } |
| 617 | ViewAction::Redraw |
| 618 | } |
| 619 | KeyCode::Char(ch) |
| 620 | if !key |
| 621 | .modifiers |
| 622 | .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => |
| 623 | { |
| 624 | if let Some(input) = self.annotation_input.as_mut() { |
| 625 | let byte_idx = char_to_byte_index(input, self.annotation_cursor); |
| 626 | input.insert(byte_idx, ch); |
| 627 | self.annotation_cursor += 1; |
| 628 | } |
| 629 | ViewAction::Redraw |
| 630 | } |
| 631 | _ => ViewAction::None, |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | fn handle_build_confirm_key(&mut self, key: KeyEvent) -> ViewAction { |
| 636 | match key.code { |
| 637 | KeyCode::Esc => { |
| 638 | self.build_confirm_open = false; |
| 639 | ViewAction::Redraw |
| 640 | } |
| 641 | KeyCode::Up | KeyCode::Char('k') => { |
| 642 | self.build_posture_index = self.build_posture_index.saturating_sub(1); |
| 643 | ViewAction::Redraw |
| 644 | } |
| 645 | KeyCode::Down | KeyCode::Char('j') => { |
| 646 | self.build_posture_index = |
| 647 | (self.build_posture_index + 1).min(BUILD_POSTURES.len() - 1); |
| 648 | ViewAction::Redraw |
| 649 | } |
| 650 | KeyCode::Char('1') => { |
| 651 | self.build_posture_index = 0; |
| 652 | ViewAction::Redraw |
| 653 | } |
| 654 | KeyCode::Char('2') => { |
| 655 | self.build_posture_index = 1; |
| 656 | ViewAction::Redraw |
| 657 | } |
| 658 | KeyCode::Char('3') => { |
| 659 | self.build_posture_index = 2; |
| 660 | ViewAction::Redraw |
| 661 | } |
| 662 | KeyCode::Enter | KeyCode::Char('b') => { |
| 663 | if self.markdown.trim().is_empty() { |
| 664 | self.build_confirm_open = false; |
| 665 | self.status_notice = Some(( |
| 666 | "No saved plan to build yet".to_string(), |
| 667 | StatusToastLevel::Warning, |
| 668 | )); |
| 669 | return ViewAction::Redraw; |
| 670 | } |
| 671 | let _ = self.save_to_disk(); |
| 672 | let command = BUILD_POSTURES[self.build_posture_index].3.to_string(); |
| 673 | ViewAction::EmitAndClose(ViewEvent::ExecutePanelCommand { |
| 674 | command, |
| 675 | pager_title: None, |
| 676 | }) |
| 677 | } |
| 678 | _ => ViewAction::None, |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | impl ModalView for PlanArtifactView { |
| 684 | fn kind(&self) -> ModalKind { |
| 685 | ModalKind::PlanArtifact |
| 686 | } |
| 687 | |
| 688 | fn as_any_mut(&mut self) -> &mut dyn Any { |
| 689 | self |
| 690 | } |
| 691 | |
| 692 | fn tick(&mut self) -> ViewAction { |
| 693 | if let Some(command) = self.pending_panel_command.take() { |
| 694 | return ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 695 | command, |
| 696 | pager_title: None, |
| 697 | }); |
| 698 | } |
| 699 | ViewAction::None |
| 700 | } |
| 701 | |
| 702 | fn handle_paste(&mut self, text: &str) -> bool { |
| 703 | let Some(input) = self.annotation_input.as_mut() else { |
| 704 | return false; |
| 705 | }; |
| 706 | let sanitized = sanitize_pasted_note(text); |
| 707 | if sanitized.is_empty() { |
| 708 | return true; |
| 709 | } |
| 710 | let byte_idx = char_to_byte_index(input, self.annotation_cursor); |
| 711 | input.insert_str(byte_idx, &sanitized); |
| 712 | self.annotation_cursor += sanitized.chars().count(); |
| 713 | true |
| 714 | } |
| 715 | |
| 716 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 717 | if self.annotation_input.is_some() { |
| 718 | return self.handle_annotation_key(key); |
| 719 | } |
| 720 | if self.build_confirm_open { |
| 721 | return self.handle_build_confirm_key(key); |
| 722 | } |
| 723 | match key.code { |
| 724 | KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close, |
| 725 | KeyCode::Tab | KeyCode::Char('m') => { |
| 726 | self.view_mode = match self.view_mode { |
| 727 | PlanViewMode::Steps => PlanViewMode::Raw, |
| 728 | PlanViewMode::Raw => PlanViewMode::Steps, |
| 729 | }; |
| 730 | ViewAction::Redraw |
| 731 | } |
| 732 | KeyCode::Up | KeyCode::Char('k') => { |
| 733 | self.move_up(1); |
| 734 | ViewAction::Redraw |
| 735 | } |
| 736 | KeyCode::Down | KeyCode::Char('j') => { |
| 737 | self.move_down(1); |
| 738 | ViewAction::Redraw |
| 739 | } |
| 740 | KeyCode::PageUp => { |
| 741 | self.move_up(8); |
| 742 | ViewAction::Redraw |
| 743 | } |
| 744 | KeyCode::PageDown => { |
| 745 | self.move_down(8); |
| 746 | ViewAction::Redraw |
| 747 | } |
| 748 | KeyCode::Home => { |
| 749 | match self.view_mode { |
| 750 | PlanViewMode::Steps => self.selected_step = 0, |
| 751 | PlanViewMode::Raw => self.raw_scroll = 0, |
| 752 | } |
| 753 | ViewAction::Redraw |
| 754 | } |
| 755 | KeyCode::End => { |
| 756 | match self.view_mode { |
| 757 | PlanViewMode::Steps => { |
| 758 | self.selected_step = self.steps.len().saturating_sub(1); |
| 759 | } |
| 760 | PlanViewMode::Raw => { |
| 761 | self.raw_scroll = self.markdown.lines().count().saturating_sub(1); |
| 762 | } |
| 763 | } |
| 764 | ViewAction::Redraw |
| 765 | } |
| 766 | KeyCode::Char('a') => { |
| 767 | if self.steps.is_empty() { |
| 768 | self.status_notice = Some(( |
| 769 | "No steps to annotate yet".to_string(), |
| 770 | StatusToastLevel::Warning, |
| 771 | )); |
| 772 | } else { |
| 773 | self.view_mode = PlanViewMode::Steps; |
| 774 | self.annotation_input = Some(String::new()); |
| 775 | self.annotation_cursor = 0; |
| 776 | } |
| 777 | ViewAction::Redraw |
| 778 | } |
| 779 | KeyCode::Char('x') => { |
| 780 | if !self.steps.is_empty() |
| 781 | && self.notes.pop(self.selected_step).is_some() |
| 782 | && let Some(session_id) = self.session_id.as_deref() |
| 783 | { |
| 784 | match save_plan_notes(session_id, &self.notes) { |
| 785 | Ok(_) => { |
| 786 | self.status_notice = Some(( |
| 787 | format!("Removed last note on step {}", self.selected_step + 1), |
| 788 | StatusToastLevel::Info, |
| 789 | )); |
| 790 | } |
| 791 | Err(err) => { |
| 792 | self.status_notice = Some((err, StatusToastLevel::Error)); |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | ViewAction::Redraw |
| 797 | } |
| 798 | KeyCode::Char('s') => { |
| 799 | if let Err(err) = self.save_to_disk() { |
| 800 | self.status_notice = Some((err, StatusToastLevel::Error)); |
| 801 | } |
| 802 | ViewAction::Redraw |
| 803 | } |
| 804 | KeyCode::Char('e') => { |
| 805 | if self.session_id.is_none() { |
| 806 | self.status_notice = Some(( |
| 807 | "No active session id to edit plan.md".to_string(), |
| 808 | StatusToastLevel::Warning, |
| 809 | )); |
| 810 | return ViewAction::Redraw; |
| 811 | } |
| 812 | if !self.markdown.trim().is_empty() { |
| 813 | let _ = self.save_to_disk(); |
| 814 | } |
| 815 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 816 | command: PANEL_CMD_EDIT.to_string(), |
| 817 | pager_title: None, |
| 818 | }) |
| 819 | } |
| 820 | KeyCode::Char('b') | KeyCode::Enter => { |
| 821 | if self.markdown.trim().is_empty() { |
| 822 | self.status_notice = Some(( |
| 823 | "No saved plan to build yet".to_string(), |
| 824 | StatusToastLevel::Warning, |
| 825 | )); |
| 826 | } else { |
| 827 | self.build_confirm_open = true; |
| 828 | } |
| 829 | ViewAction::Redraw |
| 830 | } |
| 831 | _ => ViewAction::None, |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 836 | if self.annotation_input.is_some() || self.build_confirm_open { |
| 837 | return ViewAction::None; |
| 838 | } |
| 839 | match mouse.kind { |
| 840 | MouseEventKind::ScrollUp => { |
| 841 | self.move_up(1); |
| 842 | ViewAction::Redraw |
| 843 | } |
| 844 | MouseEventKind::ScrollDown => { |
| 845 | self.move_down(1); |
| 846 | ViewAction::Redraw |
| 847 | } |
| 848 | _ => ViewAction::None, |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 853 | let popup = centered_modal_area(area, 98, 30, 56, 16); |
| 854 | let right_pill = match self.view_mode { |
| 855 | PlanViewMode::Steps => format!("Steps ({})", self.steps.len()), |
| 856 | PlanViewMode::Raw => "Raw Markdown".to_string(), |
| 857 | }; |
| 858 | let status_badge = if self.saved_on_disk { |
| 859 | "saved" |
| 860 | } else { |
| 861 | "unsaved" |
| 862 | }; |
| 863 | let frame = SurfaceFrame::new("Plan Artifact") |
| 864 | .right_pill( |
| 865 | right_pill, |
| 866 | Style::default() |
| 867 | .fg(palette::WHALE_ACTION) |
| 868 | .add_modifier(Modifier::BOLD), |
| 869 | ) |
| 870 | .bottom_right(status_badge, Style::default().fg(palette::TEXT_MUTED)); |
| 871 | let (inner, _) = render_rounded_modal(area, popup, buf, frame); |
| 872 | if inner.width < 10 || inner.height < 6 { |
| 873 | return; |
| 874 | } |
| 875 | |
| 876 | let footer_hints = if self.annotation_input.is_some() { |
| 877 | vec![ |
| 878 | ActionHint::new("Enter", "save note"), |
| 879 | ActionHint::new("Esc", "cancel"), |
| 880 | ] |
| 881 | } else if self.build_confirm_open { |
| 882 | vec![ |
| 883 | ActionHint::new("1/2/3", "posture"), |
| 884 | ActionHint::new("Enter", "start Work"), |
| 885 | ActionHint::new("Esc", "back to review"), |
| 886 | ] |
| 887 | } else { |
| 888 | vec![ |
| 889 | ActionHint::new("Tab", "steps/raw"), |
| 890 | ActionHint::new("a", "annotate"), |
| 891 | ActionHint::new("s", "save"), |
| 892 | ActionHint::new("e", "$EDITOR"), |
| 893 | ActionHint::new("b/Enter", "build plan"), |
| 894 | ActionHint::new("Esc", "close"), |
| 895 | ] |
| 896 | }; |
| 897 | let footer = action_footer_lines(&footer_hints, inner.width); |
| 898 | let footer_height = u16::try_from(footer.len()).unwrap_or(1).max(1); |
| 899 | let notice_height = u16::from(self.status_notice.is_some()); |
| 900 | let overlay_height = if self.annotation_input.is_some() { |
| 901 | 3 |
| 902 | } else if self.build_confirm_open { |
| 903 | 6 |
| 904 | } else { |
| 905 | 0 |
| 906 | }; |
| 907 | |
| 908 | let chunks = Layout::default() |
| 909 | .direction(Direction::Vertical) |
| 910 | .constraints([ |
| 911 | Constraint::Length(1), |
| 912 | Constraint::Length(1), |
| 913 | Constraint::Min(3), |
| 914 | Constraint::Length(overlay_height), |
| 915 | Constraint::Length(notice_height), |
| 916 | Constraint::Length(footer_height), |
| 917 | ]) |
| 918 | .split(inner); |
| 919 | |
| 920 | let path_label = self |
| 921 | .plan_path |
| 922 | .as_ref() |
| 923 | .map(|p| p.display().to_string()) |
| 924 | .or_else(|| self.session_id.clone()) |
| 925 | .unwrap_or_else(|| "no active session".to_string()); |
| 926 | let note_count = self.notes.total_count(); |
| 927 | let header_line = Line::from(vec![ |
| 928 | Span::styled("Session plan: ", Style::default().fg(palette::TEXT_MUTED)), |
| 929 | Span::styled(path_label, Style::default().fg(palette::TEXT_PRIMARY)), |
| 930 | Span::styled( |
| 931 | format!(" ({} steps, {} notes)", self.steps.len(), note_count), |
| 932 | Style::default().fg(palette::TEXT_DIM), |
| 933 | ), |
| 934 | ]); |
| 935 | Paragraph::new(header_line).render(chunks[0], buf); |
| 936 | render_modal_rule(chunks[1], buf); |
| 937 | |
| 938 | let body = chunks[2]; |
| 939 | if self.markdown.trim().is_empty() { |
| 940 | let empty_lines = vec![ |
| 941 | Line::from(Span::styled( |
| 942 | "No saved plan for this session yet.", |
| 943 | Style::default() |
| 944 | .fg(palette::TEXT_PRIMARY) |
| 945 | .add_modifier(Modifier::BOLD), |
| 946 | )), |
| 947 | Line::from(Span::styled( |
| 948 | "Switch to Plan mode (/mode plan) to draft a plan, or press e to author plan.md in $EDITOR.", |
| 949 | Style::default().fg(palette::TEXT_MUTED), |
| 950 | )), |
| 951 | ]; |
| 952 | Paragraph::new(empty_lines) |
| 953 | .wrap(Wrap { trim: false }) |
| 954 | .render(body, buf); |
| 955 | } else { |
| 956 | match self.view_mode { |
| 957 | PlanViewMode::Steps => self.render_steps_body(body, buf), |
| 958 | PlanViewMode::Raw => self.render_raw_body(body, buf), |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | if let Some(input) = self.annotation_input.as_ref() { |
| 963 | let box_area = chunks[3]; |
| 964 | render_modal_rule( |
| 965 | Rect { |
| 966 | height: 1, |
| 967 | ..box_area |
| 968 | }, |
| 969 | buf, |
| 970 | ); |
| 971 | let prompt_area = Rect { |
| 972 | y: box_area.y.saturating_add(1), |
| 973 | height: box_area.height.saturating_sub(1), |
| 974 | ..box_area |
| 975 | }; |
| 976 | let byte_idx = char_to_byte_index(input, self.annotation_cursor); |
| 977 | let before = &input[..byte_idx]; |
| 978 | let after = &input[byte_idx..]; |
| 979 | let lines = vec![ |
| 980 | Line::from(Span::styled( |
| 981 | format!("Add note for Step {}:", self.selected_step + 1), |
| 982 | Style::default() |
| 983 | .fg(palette::WHALE_ACTION) |
| 984 | .add_modifier(Modifier::BOLD), |
| 985 | )), |
| 986 | Line::from(vec![ |
| 987 | Span::styled("> ", Style::default().fg(palette::WHALE_ACTION)), |
| 988 | Span::styled( |
| 989 | before.to_string(), |
| 990 | Style::default().fg(palette::TEXT_PRIMARY), |
| 991 | ), |
| 992 | Span::styled( |
| 993 | "|", |
| 994 | Style::default() |
| 995 | .fg(palette::WHALE_ACTION) |
| 996 | .add_modifier(Modifier::BOLD), |
| 997 | ), |
| 998 | Span::styled( |
| 999 | after.to_string(), |
| 1000 | Style::default().fg(palette::TEXT_PRIMARY), |
| 1001 | ), |
| 1002 | ]), |
| 1003 | ]; |
| 1004 | Paragraph::new(lines).render(prompt_area, buf); |
| 1005 | } else if self.build_confirm_open { |
| 1006 | let box_area = chunks[3]; |
| 1007 | render_modal_rule( |
| 1008 | Rect { |
| 1009 | height: 1, |
| 1010 | ..box_area |
| 1011 | }, |
| 1012 | buf, |
| 1013 | ); |
| 1014 | let confirm_area = Rect { |
| 1015 | y: box_area.y.saturating_add(1), |
| 1016 | height: box_area.height.saturating_sub(1), |
| 1017 | ..box_area |
| 1018 | }; |
| 1019 | let mut lines = vec![Line::from(Span::styled( |
| 1020 | "Approve and build this plan in Work mode (choose permission posture):", |
| 1021 | Style::default() |
| 1022 | .fg(palette::WHALE_ACTION) |
| 1023 | .add_modifier(Modifier::BOLD), |
| 1024 | ))]; |
| 1025 | for (idx, (_, label, desc, _)) in BUILD_POSTURES.iter().enumerate() { |
| 1026 | let selected = idx == self.build_posture_index; |
| 1027 | let marker = if selected { "▸ " } else { " " }; |
| 1028 | let style = if selected { |
| 1029 | Style::default() |
| 1030 | .fg(palette::TEXT_PRIMARY) |
| 1031 | .add_modifier(Modifier::BOLD) |
| 1032 | } else { |
| 1033 | Style::default().fg(palette::TEXT_MUTED) |
| 1034 | }; |
| 1035 | lines.push(Line::from(vec![ |
| 1036 | Span::styled(format!("{marker}{}. {label}", idx + 1), style), |
| 1037 | Span::styled(format!(" — {desc}"), Style::default().fg(palette::TEXT_DIM)), |
| 1038 | ])); |
| 1039 | } |
| 1040 | Paragraph::new(lines).render(confirm_area, buf); |
| 1041 | } |
| 1042 | |
| 1043 | if let Some((notice, level)) = self.status_notice.as_ref() { |
| 1044 | let color = match level { |
| 1045 | StatusToastLevel::Success => palette::STATUS_SUCCESS, |
| 1046 | StatusToastLevel::Warning => palette::STATUS_WARNING, |
| 1047 | StatusToastLevel::Error => palette::STATUS_ERROR, |
| 1048 | StatusToastLevel::Info => palette::WHALE_ACTION, |
| 1049 | }; |
| 1050 | Paragraph::new(Line::from(Span::styled( |
| 1051 | notice.clone(), |
| 1052 | Style::default().fg(color), |
| 1053 | ))) |
| 1054 | .render(chunks[4], buf); |
| 1055 | } |
| 1056 | |
| 1057 | Paragraph::new(footer).render(chunks[5], buf); |
| 1058 | } |
| 1059 | } |
| 1060 | |
| 1061 | impl PlanArtifactView { |
| 1062 | fn render_steps_body(&self, body: Rect, buf: &mut Buffer) { |
| 1063 | let notes_for_selected = self.notes.for_step(self.selected_step); |
| 1064 | let detail_height = if notes_for_selected.is_empty() { |
| 1065 | 2 |
| 1066 | } else { |
| 1067 | (notes_for_selected.len() + 2).min(6) as u16 |
| 1068 | }; |
| 1069 | let split = Layout::default() |
| 1070 | .direction(Direction::Vertical) |
| 1071 | .constraints([Constraint::Min(3), Constraint::Length(detail_height)]) |
| 1072 | .split(body); |
| 1073 | |
| 1074 | let visible_rows = usize::from(split[0].height).max(1); |
| 1075 | let offset = self |
| 1076 | .selected_step |
| 1077 | .saturating_sub(visible_rows.saturating_sub(1)); |
| 1078 | let content_area = |
| 1079 | render_panel_scroll_rail(split[0], buf, self.steps.len(), offset, visible_rows, true); |
| 1080 | |
| 1081 | let mut list_lines = Vec::new(); |
| 1082 | for step in self.steps.iter().skip(offset).take(visible_rows) { |
| 1083 | let selected = step.index == self.selected_step; |
| 1084 | let marker = if selected { "▸ " } else { " " }; |
| 1085 | let badge = match step.checked { |
| 1086 | Some(true) => "[x] ", |
| 1087 | Some(false) => "[ ] ", |
| 1088 | None => "", |
| 1089 | }; |
| 1090 | let note_count = self.notes.for_step(step.index).len(); |
| 1091 | let note_tag = if note_count == 1 { |
| 1092 | " [1 note]".to_string() |
| 1093 | } else if note_count > 1 { |
| 1094 | format!(" [{note_count} notes]") |
| 1095 | } else { |
| 1096 | String::new() |
| 1097 | }; |
| 1098 | let title_style = if selected { |
| 1099 | Style::default() |
| 1100 | .fg(palette::TEXT_PRIMARY) |
| 1101 | .add_modifier(Modifier::BOLD) |
| 1102 | } else { |
| 1103 | Style::default().fg(palette::TEXT_MUTED) |
| 1104 | }; |
| 1105 | list_lines.push(Line::from(vec![ |
| 1106 | Span::styled( |
| 1107 | format!("{marker}{}. {badge}", step.number), |
| 1108 | if selected { |
| 1109 | Style::default() |
| 1110 | .fg(palette::WHALE_ACTION) |
| 1111 | .add_modifier(Modifier::BOLD) |
| 1112 | } else { |
| 1113 | Style::default().fg(palette::TEXT_DIM) |
| 1114 | }, |
| 1115 | ), |
| 1116 | Span::styled(step.title.clone(), title_style), |
| 1117 | Span::styled(note_tag, Style::default().fg(palette::STATUS_WARNING)), |
| 1118 | ])); |
| 1119 | } |
| 1120 | Paragraph::new(list_lines).render(content_area, buf); |
| 1121 | |
| 1122 | let detail_area = split[1]; |
| 1123 | render_modal_rule( |
| 1124 | Rect { |
| 1125 | height: 1, |
| 1126 | ..detail_area |
| 1127 | }, |
| 1128 | buf, |
| 1129 | ); |
| 1130 | let notes_rect = Rect { |
| 1131 | y: detail_area.y.saturating_add(1), |
| 1132 | height: detail_area.height.saturating_sub(1), |
| 1133 | ..detail_area |
| 1134 | }; |
| 1135 | let mut detail_lines = Vec::new(); |
| 1136 | if notes_for_selected.is_empty() { |
| 1137 | detail_lines.push(Line::from(Span::styled( |
| 1138 | "No notes on this step. Press a to add an inline review note.", |
| 1139 | Style::default().fg(palette::TEXT_DIM), |
| 1140 | ))); |
| 1141 | } else { |
| 1142 | for (idx, note) in notes_for_selected.iter().enumerate() { |
| 1143 | detail_lines.push(Line::from(vec![ |
| 1144 | Span::styled( |
| 1145 | format!("Note {}: ", idx + 1), |
| 1146 | Style::default() |
| 1147 | .fg(palette::STATUS_WARNING) |
| 1148 | .add_modifier(Modifier::BOLD), |
| 1149 | ), |
| 1150 | Span::styled(note.clone(), Style::default().fg(palette::TEXT_PRIMARY)), |
| 1151 | ])); |
| 1152 | } |
| 1153 | } |
| 1154 | Paragraph::new(detail_lines) |
| 1155 | .wrap(Wrap { trim: false }) |
| 1156 | .render(notes_rect, buf); |
| 1157 | } |
| 1158 | |
| 1159 | fn render_raw_body(&self, body: Rect, buf: &mut Buffer) { |
| 1160 | let lines: Vec<Line<'static>> = self |
| 1161 | .markdown |
| 1162 | .lines() |
| 1163 | .enumerate() |
| 1164 | .map(|(idx, line)| { |
| 1165 | Line::from(vec![ |
| 1166 | Span::styled( |
| 1167 | format!("{:>3} ", idx + 1), |
| 1168 | Style::default().fg(palette::TEXT_DIM), |
| 1169 | ), |
| 1170 | Span::styled(line.to_string(), Style::default().fg(palette::TEXT_PRIMARY)), |
| 1171 | ]) |
| 1172 | }) |
| 1173 | .collect(); |
| 1174 | let total = lines.len(); |
| 1175 | let visible = usize::from(body.height).max(1); |
| 1176 | let content_area = |
| 1177 | render_panel_scroll_rail(body, buf, total, self.raw_scroll, visible, true); |
| 1178 | let _ = render_wrapped_detail(lines, content_area, buf, self.raw_scroll); |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | pub(crate) fn open_from_app(app: &mut App, arg: Option<&str>) { |
| 1183 | let subcommand = arg |
| 1184 | .map(str::trim) |
| 1185 | .filter(|s| !s.is_empty()) |
| 1186 | .map(str::to_ascii_lowercase); |
| 1187 | let session_id = app.current_session_id.clone(); |
| 1188 | |
| 1189 | let (disk_markdown, disk_notes, plan_path, mut saved_on_disk) = |
| 1190 | if let Some(sid) = session_id.as_deref() { |
| 1191 | let md = load_plan_markdown(sid).ok().flatten(); |
| 1192 | let notes = load_plan_notes(sid).unwrap_or_default(); |
| 1193 | let path = plan_markdown_path(sid).ok(); |
| 1194 | let on_disk = md.is_some(); |
| 1195 | (md, notes, path, on_disk) |
| 1196 | } else { |
| 1197 | (None, PlanNotes::default(), None, false) |
| 1198 | }; |
| 1199 | |
| 1200 | let markdown = disk_markdown |
| 1201 | .or_else(|| latest_plan_candidate_from_app(app)) |
| 1202 | .unwrap_or_default(); |
| 1203 | |
| 1204 | let mut notice = None; |
| 1205 | if !saved_on_disk |
| 1206 | && !markdown.trim().is_empty() |
| 1207 | && let Some(sid) = session_id.as_deref() |
| 1208 | && save_plan_markdown(sid, &markdown).is_ok() |
| 1209 | { |
| 1210 | saved_on_disk = true; |
| 1211 | } |
| 1212 | |
| 1213 | if subcommand.as_deref() == Some("save") { |
| 1214 | match session_id.as_deref() { |
| 1215 | Some(sid) if !markdown.trim().is_empty() => match save_plan_markdown(sid, &markdown) { |
| 1216 | Ok(path) => { |
| 1217 | let _ = save_plan_notes(sid, &disk_notes); |
| 1218 | saved_on_disk = true; |
| 1219 | let msg = format!("Saved session plan to {}", path.display()); |
| 1220 | app.push_status_toast(msg.clone(), StatusToastLevel::Success, Some(6_000)); |
| 1221 | notice = Some((msg, StatusToastLevel::Success)); |
| 1222 | } |
| 1223 | Err(err) => { |
| 1224 | app.push_status_toast(err.clone(), StatusToastLevel::Error, Some(8_000)); |
| 1225 | notice = Some((err, StatusToastLevel::Error)); |
| 1226 | } |
| 1227 | }, |
| 1228 | Some(_) => { |
| 1229 | let msg = "No plan output to save yet.".to_string(); |
| 1230 | app.push_status_toast(msg.clone(), StatusToastLevel::Warning, Some(6_000)); |
| 1231 | notice = Some((msg, StatusToastLevel::Warning)); |
| 1232 | } |
| 1233 | None => { |
| 1234 | let msg = "No active session to save a plan for.".to_string(); |
| 1235 | app.push_status_toast(msg.clone(), StatusToastLevel::Warning, Some(6_000)); |
| 1236 | notice = Some((msg, StatusToastLevel::Warning)); |
| 1237 | } |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | let mut view = PlanArtifactView::new( |
| 1242 | session_id, |
| 1243 | plan_path, |
| 1244 | markdown, |
| 1245 | disk_notes, |
| 1246 | saved_on_disk, |
| 1247 | app.agent_approval_baseline(), |
| 1248 | ); |
| 1249 | view.status_notice = notice; |
| 1250 | |
| 1251 | match subcommand.as_deref() { |
| 1252 | Some("edit") => { |
| 1253 | view.pending_panel_command = Some(PANEL_CMD_EDIT.to_string()); |
| 1254 | } |
| 1255 | Some("build") => { |
| 1256 | if view.markdown.trim().is_empty() { |
| 1257 | view.status_notice = Some(( |
| 1258 | "No saved plan to build yet".to_string(), |
| 1259 | StatusToastLevel::Warning, |
| 1260 | )); |
| 1261 | } else if should_never_auto_skip_plan_review(app.mode, app.agent_approval_baseline()) { |
| 1262 | view.build_confirm_open = true; |
| 1263 | } |
| 1264 | } |
| 1265 | _ => {} |
| 1266 | } |
| 1267 | |
| 1268 | if app.view_stack.top_kind() == Some(ModalKind::PlanArtifact) { |
| 1269 | let _ = app.view_stack.pop(); |
| 1270 | } |
| 1271 | app.view_stack.push(view); |
| 1272 | app.needs_redraw = true; |
| 1273 | } |
| 1274 | |
| 1275 | pub(crate) async fn handle_panel_command( |
| 1276 | terminal: &mut Terminal<ColorCompatBackend<Stdout>>, |
| 1277 | app: &mut App, |
| 1278 | config: &mut Config, |
| 1279 | engine_handle: &mut EngineHandle, |
| 1280 | command: &str, |
| 1281 | ) -> Result<()> { |
| 1282 | match command { |
| 1283 | PANEL_CMD_EDIT => { |
| 1284 | let Some(session_id) = app.current_session_id.clone() else { |
| 1285 | app.push_status_toast( |
| 1286 | "No active session for plan.md".to_string(), |
| 1287 | StatusToastLevel::Warning, |
| 1288 | Some(6_000), |
| 1289 | ); |
| 1290 | return Ok(()); |
| 1291 | }; |
| 1292 | let path = match plan_markdown_path(&session_id) { |
| 1293 | Ok(path) => path, |
| 1294 | Err(err) => { |
| 1295 | app.push_status_toast(err, StatusToastLevel::Error, Some(8_000)); |
| 1296 | return Ok(()); |
| 1297 | } |
| 1298 | }; |
| 1299 | let selected_line = if app.view_stack.top_kind() == Some(ModalKind::PlanArtifact) { |
| 1300 | let mut popped = app.view_stack.pop(); |
| 1301 | let line = popped |
| 1302 | .as_mut() |
| 1303 | .and_then(|view| view.as_any_mut().downcast_mut::<PlanArtifactView>()) |
| 1304 | .and_then(|view| view.selected_step_line()); |
| 1305 | if let Some(view) = popped { |
| 1306 | app.view_stack.push_boxed(view); |
| 1307 | } |
| 1308 | line |
| 1309 | } else { |
| 1310 | None |
| 1311 | }; |
| 1312 | if !path.exists() { |
| 1313 | let seed = latest_plan_candidate_from_app(app).unwrap_or_default(); |
| 1314 | if let Err(err) = save_plan_markdown(&session_id, &seed) { |
| 1315 | app.push_status_toast(err, StatusToastLevel::Error, Some(8_000)); |
| 1316 | return Ok(()); |
| 1317 | } |
| 1318 | } |
| 1319 | let outcome = spawn_editor_for_path( |
| 1320 | terminal, |
| 1321 | app.use_mouse_capture, |
| 1322 | app.use_bracketed_paste, |
| 1323 | &path, |
| 1324 | selected_line, |
| 1325 | ); |
| 1326 | let notice = match outcome { |
| 1327 | Ok(EditorOutcome::Edited(_)) => ( |
| 1328 | format!("Reloaded edited {}", path.display()), |
| 1329 | StatusToastLevel::Success, |
| 1330 | ), |
| 1331 | Ok(EditorOutcome::Unchanged) => { |
| 1332 | ("No changes in plan.md".to_string(), StatusToastLevel::Info) |
| 1333 | } |
| 1334 | Ok(EditorOutcome::Cancelled) => ( |
| 1335 | "Editor cancelled; plan.md unchanged".to_string(), |
| 1336 | StatusToastLevel::Warning, |
| 1337 | ), |
| 1338 | Err(err) => ( |
| 1339 | format!("Failed to launch $EDITOR: {err}"), |
| 1340 | StatusToastLevel::Error, |
| 1341 | ), |
| 1342 | }; |
| 1343 | if app.view_stack.top_kind() == Some(ModalKind::PlanArtifact) |
| 1344 | && let Some(mut boxed) = app.view_stack.pop() |
| 1345 | { |
| 1346 | if let Some(view) = boxed.as_any_mut().downcast_mut::<PlanArtifactView>() { |
| 1347 | view.reload_from_disk(Some(notice.clone())); |
| 1348 | } |
| 1349 | app.view_stack.push_boxed(boxed); |
| 1350 | } |
| 1351 | app.push_status_toast(notice.0, notice.1, Some(6_000)); |
| 1352 | app.needs_redraw = true; |
| 1353 | Ok(()) |
| 1354 | } |
| 1355 | PANEL_CMD_BUILD_ASK | PANEL_CMD_BUILD_ACCEPT_EDITS | PANEL_CMD_BUILD_AUTO => { |
| 1356 | let posture = match command { |
| 1357 | PANEL_CMD_BUILD_ASK => ApprovalMode::Suggest, |
| 1358 | PANEL_CMD_BUILD_ACCEPT_EDITS => ApprovalMode::AcceptEdits, |
| 1359 | PANEL_CMD_BUILD_AUTO => ApprovalMode::Auto, |
| 1360 | _ => ApprovalMode::Suggest, |
| 1361 | }; |
| 1362 | let (markdown, notes) = if let Some(sid) = app.current_session_id.as_deref() { |
| 1363 | let md = load_plan_markdown(sid) |
| 1364 | .ok() |
| 1365 | .flatten() |
| 1366 | .or_else(|| latest_plan_candidate_from_app(app)) |
| 1367 | .unwrap_or_default(); |
| 1368 | let notes = load_plan_notes(sid).unwrap_or_default(); |
| 1369 | (md, notes) |
| 1370 | } else { |
| 1371 | ( |
| 1372 | latest_plan_candidate_from_app(app).unwrap_or_default(), |
| 1373 | PlanNotes::default(), |
| 1374 | ) |
| 1375 | }; |
| 1376 | if markdown.trim().is_empty() { |
| 1377 | app.push_status_toast( |
| 1378 | "No saved plan to build".to_string(), |
| 1379 | StatusToastLevel::Warning, |
| 1380 | Some(6_000), |
| 1381 | ); |
| 1382 | return Ok(()); |
| 1383 | } |
| 1384 | let steps = parse_plan_steps(&markdown); |
| 1385 | let combined = compose_execution_plan(&markdown, &steps, ¬es); |
| 1386 | super::ui::build_saved_plan_in_work_mode(app, config, engine_handle, posture, combined) |
| 1387 | .await |
| 1388 | } |
| 1389 | _ => Ok(()), |
| 1390 | } |
| 1391 | } |
| 1392 | |
| 1393 | pub(crate) fn should_never_auto_skip_plan_review( |
| 1394 | _mode: AppMode, |
| 1395 | _work_posture: ApprovalMode, |
| 1396 | ) -> bool { |
| 1397 | true |
| 1398 | } |
| 1399 |