| 1 | //! Row builders for the dock views that are not work rows: files, notepad, |
| 2 | //! context, git, and price. Each returns ordinary [`WorkRow`]s so the one |
| 3 | //! row/hitbox pipeline in `render/` paints, selects, and clicks them exactly |
| 4 | //! like a to-do or a sub-agent — a view is a subset of one row grammar, not |
| 5 | //! a second widget system. |
| 6 | |
| 7 | use crate::tui::app::{App, SidebarRowAction}; |
| 8 | use codewhale_engine::agent_roster::format_tokens; |
| 9 | use codewhale_localization::{MessageId, tr}; |
| 10 | |
| 11 | use super::model::{RailPanel, WorkRow, WorkRowId, WorkTone}; |
| 12 | |
| 13 | /// Views whose tab always shows once the dock is up: the fact views have |
| 14 | /// something to say in every session, so they are always one click away. |
| 15 | pub(super) const fn view_always_has_content(panel: RailPanel) -> bool { |
| 16 | matches!( |
| 17 | panel, |
| 18 | RailPanel::Context | RailPanel::Git | RailPanel::Price | RailPanel::Terminal |
| 19 | ) |
| 20 | } |
| 21 | |
| 22 | /// Files this session edited or read, even before TASKS has been projected. |
| 23 | pub(super) fn files_touched_count(app: &mut App) -> usize { |
| 24 | app.work_surface.file_activity = super::model::settled_file_activity(app); |
| 25 | let activity = &app.work_surface.file_activity; |
| 26 | edited_files(activity).len() + activity.read.len() |
| 27 | } |
| 28 | |
| 29 | pub(super) fn notepad_has_text(app: &App) -> bool { |
| 30 | !app.workspace_notes.is_empty() |
| 31 | } |
| 32 | |
| 33 | /// Each edited file once, newest receipt last. Direct writes without a |
| 34 | /// mutation receipt have no diff to inspect. |
| 35 | fn edited_files( |
| 36 | activity: &super::model::SettledFileActivity, |
| 37 | ) -> Vec<(String, Option<&crate::tui::history::FileMutationReceipt>)> { |
| 38 | let mut files = Vec::new(); |
| 39 | for path in &activity.write { |
| 40 | if !files.iter().any(|(existing, _)| existing == path) { |
| 41 | files.push((path.clone(), None)); |
| 42 | } |
| 43 | } |
| 44 | for receipt in &activity.mutations { |
| 45 | for file in &receipt.files { |
| 46 | files.retain(|(path, _)| path != &file.path); |
| 47 | files.push((file.path.clone(), Some(receipt))); |
| 48 | } |
| 49 | } |
| 50 | files |
| 51 | } |
| 52 | |
| 53 | /// The FILES view: what this session changed (with each change's size and |
| 54 | /// its evidence one Enter away), then what it read (#6565). |
| 55 | pub(super) fn files_rows(app: &mut App) -> Vec<WorkRow> { |
| 56 | app.work_surface.file_activity = super::model::settled_file_activity(app); |
| 57 | let activity = app.work_surface.file_activity.clone(); |
| 58 | let mut out = Vec::new(); |
| 59 | let edited = edited_files(&activity); |
| 60 | if !edited.is_empty() { |
| 61 | out.push(heading( |
| 62 | "files:edited", |
| 63 | format!( |
| 64 | "{} {}", |
| 65 | tr(activity.locale, MessageId::FileActivityEditedLabel), |
| 66 | edited.len() |
| 67 | ), |
| 68 | )); |
| 69 | for (path, receipt) in &edited { |
| 70 | let Some(receipt) = receipt else { |
| 71 | out.push(WorkRow { |
| 72 | mark: "✎", |
| 73 | tone: WorkTone::Success, |
| 74 | ..note_row(&format!("files:edit:{path}"), path) |
| 75 | }); |
| 76 | continue; |
| 77 | }; |
| 78 | let across = if receipt.files.len() > 1 { |
| 79 | tr(activity.locale, MessageId::FileMutationAcrossFiles) |
| 80 | .replace("{count}", &receipt.files.len().to_string()) |
| 81 | } else { |
| 82 | String::new() |
| 83 | }; |
| 84 | out.push(WorkRow { |
| 85 | id: WorkRowId(format!("files:edit:{path}")), |
| 86 | mark: "✎", |
| 87 | label: path.clone(), |
| 88 | detail: format!("+{} −{}{across}", receipt.added, receipt.deleted), |
| 89 | tone: WorkTone::Success, |
| 90 | selectable: true, |
| 91 | primary_action: Some(SidebarRowAction::InspectWork { |
| 92 | title: format!( |
| 93 | "{} · {path}", |
| 94 | tr(activity.locale, MessageId::ApprovalLabelFile) |
| 95 | ), |
| 96 | body: super::model::settled_mutation_body( |
| 97 | std::slice::from_ref(*receipt), |
| 98 | activity.inline_diff_mode, |
| 99 | activity.locale, |
| 100 | ), |
| 101 | stop_action: None, |
| 102 | }), |
| 103 | agent: None, |
| 104 | }); |
| 105 | } |
| 106 | } |
| 107 | if !activity.read.is_empty() { |
| 108 | out.push(heading( |
| 109 | "files:read", |
| 110 | format!( |
| 111 | "{} {}", |
| 112 | tr(activity.locale, MessageId::FileActivityReadLabel), |
| 113 | activity.read.len() |
| 114 | ), |
| 115 | )); |
| 116 | for path in &activity.read { |
| 117 | out.push(WorkRow { |
| 118 | id: WorkRowId(format!("files:read:{path}")), |
| 119 | mark: "·", |
| 120 | label: path.clone(), |
| 121 | detail: String::new(), |
| 122 | tone: WorkTone::Muted, |
| 123 | selectable: false, |
| 124 | primary_action: None, |
| 125 | agent: None, |
| 126 | }); |
| 127 | } |
| 128 | } |
| 129 | app.work_surface.latest_rows = out.clone(); |
| 130 | out |
| 131 | } |
| 132 | |
| 133 | /// The NOTES view: the workspace notes `/note` keeps, one row each; Enter |
| 134 | /// shows the whole note. |
| 135 | pub(super) fn notepad_rows(app: &mut App) -> Vec<WorkRow> { |
| 136 | let out = app |
| 137 | .workspace_notes |
| 138 | .iter() |
| 139 | .enumerate() |
| 140 | .map(|(index, note)| { |
| 141 | let number = index + 1; |
| 142 | let first_line = note.lines().map(str::trim).find(|line| !line.is_empty()); |
| 143 | WorkRow { |
| 144 | id: WorkRowId(format!("notes:{number}")), |
| 145 | mark: "▪", |
| 146 | label: codewhale_engine::agent_roster::one_line(first_line.unwrap_or_default()), |
| 147 | detail: format!("/note show {number}"), |
| 148 | tone: WorkTone::Live, |
| 149 | selectable: true, |
| 150 | primary_action: Some(SidebarRowAction::Command(format!("/note show {number}"))), |
| 151 | agent: None, |
| 152 | } |
| 153 | }) |
| 154 | .collect::<Vec<_>>(); |
| 155 | app.work_surface.latest_rows = out.clone(); |
| 156 | out |
| 157 | } |
| 158 | |
| 159 | fn heading(id: &str, label: String) -> WorkRow { |
| 160 | WorkRow { |
| 161 | id: WorkRowId(id.to_string()), |
| 162 | mark: "▾", |
| 163 | label, |
| 164 | detail: String::new(), |
| 165 | tone: WorkTone::Heading, |
| 166 | selectable: false, |
| 167 | primary_action: None, |
| 168 | agent: None, |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// The context view: the budget, not a fact list. Used/limit and the |
| 173 | /// compaction threshold from the same snapshot the footer meter reads, a |
| 174 | /// gauge, the automatic threshold, then the breakdown available per frame — |
| 175 | /// system prompt, tool schemas, conversation, tool output, files read — and |
| 176 | /// the one action that exists as a command, `/compact`. |
| 177 | pub(super) fn context_rows(app: &mut App) -> Vec<WorkRow> { |
| 178 | let Some((used, max, percent)) = crate::tui::ui::context_usage_snapshot(app) else { |
| 179 | app.work_surface.latest_rows.clear(); |
| 180 | return Vec::new(); |
| 181 | }; |
| 182 | let used = u64::try_from(used).unwrap_or(0); |
| 183 | let threshold = app.auto_compact_threshold_percent.round().clamp(0.0, 100.0) as u8; |
| 184 | let fact = |id: &str, label: String, detail: &str| WorkRow { |
| 185 | id: WorkRowId(format!("context:{id}")), |
| 186 | mark: "·", |
| 187 | label, |
| 188 | detail: detail.to_string(), |
| 189 | tone: WorkTone::Muted, |
| 190 | selectable: false, |
| 191 | primary_action: None, |
| 192 | agent: None, |
| 193 | }; |
| 194 | let mut out = vec![WorkRow { |
| 195 | id: WorkRowId("context:budget".to_string()), |
| 196 | mark: "◔", |
| 197 | label: format!( |
| 198 | "{} of {} · {}%", |
| 199 | format_tokens(used), |
| 200 | format_tokens(u64::from(max)), |
| 201 | percent.round() as u8 |
| 202 | ), |
| 203 | detail: "/context for the full source map".to_string(), |
| 204 | tone: if app.auto_compact && used >= app.compact_threshold as u64 { |
| 205 | WorkTone::Attention |
| 206 | } else { |
| 207 | WorkTone::Live |
| 208 | }, |
| 209 | selectable: true, |
| 210 | primary_action: Some(SidebarRowAction::Command("/context".to_string())), |
| 211 | agent: None, |
| 212 | }]; |
| 213 | out.push(fact("gauge", gauge(percent, 24), "")); |
| 214 | let mut automatic = if app.auto_compact && max > 0 { |
| 215 | let effective = (app.compact_threshold as f64 * 100.0 / f64::from(max)) |
| 216 | .clamp(0.0, 100.0) |
| 217 | .round() as u8; |
| 218 | fact( |
| 219 | "automatic", |
| 220 | format!("auto ~{effective}% · target {threshold}%"), |
| 221 | "Current route; live token counts and other routes may differ", |
| 222 | ) |
| 223 | } else if app.auto_compact { |
| 224 | fact( |
| 225 | "automatic", |
| 226 | format!("auto threshold unavailable · target {threshold}%"), |
| 227 | "The current route's context window is unavailable", |
| 228 | ) |
| 229 | } else { |
| 230 | fact( |
| 231 | "automatic", |
| 232 | "automatic compaction off".to_string(), |
| 233 | "Use /compact to make room manually", |
| 234 | ) |
| 235 | }; |
| 236 | automatic.selectable = true; |
| 237 | automatic.primary_action = Some(SidebarRowAction::Command("/context".to_string())); |
| 238 | out.push(automatic); |
| 239 | |
| 240 | // Breakdown from what is already counted per frame: the system prompt |
| 241 | // estimate the footer meter uses and the per-message token cache. No |
| 242 | // text is re-scanned here; a message is tool output when every block in |
| 243 | // it is a tool result. |
| 244 | let system_tokens = codewhale_engine::compaction::estimate_input_tokens_conservative( |
| 245 | &[], |
| 246 | app.system_prompt.as_ref(), |
| 247 | ); |
| 248 | let tools = app |
| 249 | .session |
| 250 | .last_tool_catalog |
| 251 | .as_ref() |
| 252 | .map(|catalog| catalog.len()) |
| 253 | .unwrap_or(0); |
| 254 | let (conversation, tool_output, messages) = message_split(app); |
| 255 | out.push(fact( |
| 256 | "system", |
| 257 | format!( |
| 258 | "system + tools · {} · {tools} tools", |
| 259 | format_tokens(system_tokens as u64) |
| 260 | ), |
| 261 | "", |
| 262 | )); |
| 263 | out.push(fact( |
| 264 | "conversation", |
| 265 | format!( |
| 266 | "conversation · {messages} · {}", |
| 267 | format_tokens(conversation) |
| 268 | ), |
| 269 | "", |
| 270 | )); |
| 271 | out.push(fact( |
| 272 | "tool-output", |
| 273 | format!("tool output · {}", format_tokens(tool_output)), |
| 274 | "", |
| 275 | )); |
| 276 | let read = super::model::settled_file_activity(app).read; |
| 277 | if !read.is_empty() { |
| 278 | out.push(fact( |
| 279 | "files", |
| 280 | format!("files read · {}", read.len()), |
| 281 | &read.join(", "), |
| 282 | )); |
| 283 | } |
| 284 | out.push(WorkRow { |
| 285 | id: WorkRowId("context:compact".to_string()), |
| 286 | mark: "▸", |
| 287 | label: "compact now".to_string(), |
| 288 | detail: "/compact".to_string(), |
| 289 | tone: WorkTone::Live, |
| 290 | selectable: true, |
| 291 | primary_action: Some(SidebarRowAction::Command("/compact".to_string())), |
| 292 | agent: None, |
| 293 | }); |
| 294 | app.work_surface.latest_rows = out.clone(); |
| 295 | out |
| 296 | } |
| 297 | |
| 298 | /// `████████░░░░░░░░` — `width` cells, filled to `percent`. |
| 299 | fn gauge(percent: f64, width: usize) -> String { |
| 300 | let filled = ((percent / 100.0) * width as f64) |
| 301 | .round() |
| 302 | .clamp(0.0, width as f64) as usize; |
| 303 | let mut bar = String::with_capacity(width * 3); |
| 304 | for _ in 0..filled { |
| 305 | bar.push('█'); |
| 306 | } |
| 307 | for _ in filled..width { |
| 308 | bar.push('░'); |
| 309 | } |
| 310 | bar |
| 311 | } |
| 312 | |
| 313 | /// `(conversation tokens, tool-output tokens, message count)` from the |
| 314 | /// per-message estimate cache the meter already maintains. Messages the |
| 315 | /// cache has not seen yet count as zero rather than being re-estimated on |
| 316 | /// the render path. |
| 317 | fn message_split(app: &App) -> (u64, u64, usize) { |
| 318 | let cache = app.context_token_cache.borrow(); |
| 319 | let mut conversation = 0u64; |
| 320 | let mut tool_output = 0u64; |
| 321 | for (index, message) in app.api_messages.iter().enumerate() { |
| 322 | let tokens = cache |
| 323 | .message_tokens |
| 324 | .get(index) |
| 325 | .map(|tokens| (*tokens as u64).saturating_mul(3).div_ceil(2)) |
| 326 | .unwrap_or(0); |
| 327 | let all_tool_results = !message.content.is_empty() |
| 328 | && message.content.iter().all(|block| { |
| 329 | matches!( |
| 330 | block, |
| 331 | codewhale_models::ContentBlock::ToolResult { .. } |
| 332 | | codewhale_models::ContentBlock::ToolSearchToolResult { .. } |
| 333 | | codewhale_models::ContentBlock::CodeExecutionToolResult { .. } |
| 334 | | codewhale_models::ContentBlock::WebSearchToolResult { .. } |
| 335 | | codewhale_models::ContentBlock::WebFetchToolResult { .. } |
| 336 | ) |
| 337 | }); |
| 338 | if all_tool_results { |
| 339 | tool_output = tool_output.saturating_add(tokens); |
| 340 | } else { |
| 341 | conversation = conversation.saturating_add(tokens); |
| 342 | } |
| 343 | } |
| 344 | (conversation, tool_output, app.api_messages.len()) |
| 345 | } |
| 346 | |
| 347 | /// The GIT view, from the cached repository probe (never git on the render |
| 348 | /// path): the branch and where it stands against its upstream, the changes |
| 349 | /// with their paths one Enter away, linked worktrees, and the last commits. |
| 350 | /// Before the first probe it says so; "not a git repository" only when the |
| 351 | /// probe found none, and a git failure is named (#6565). |
| 352 | pub(super) fn git_rows(app: &mut App) -> Vec<WorkRow> { |
| 353 | let out = git_rows_for( |
| 354 | &codewhale_engine::git_status::cached_status(), |
| 355 | &app.workspace, |
| 356 | ); |
| 357 | app.work_surface.latest_rows = out.clone(); |
| 358 | out |
| 359 | } |
| 360 | |
| 361 | fn git_rows_for( |
| 362 | snap: &codewhale_engine::git_status::GitStatusSnapshot, |
| 363 | workspace: &std::path::Path, |
| 364 | ) -> Vec<WorkRow> { |
| 365 | let probed_here = snap.probed_workspace.as_deref() == Some(workspace); |
| 366 | if !probed_here || snap.fetched_at.is_none() { |
| 367 | vec![note_row("git:state", "reading git status…")] |
| 368 | } else if let Some(error) = snap.error.as_deref() { |
| 369 | vec![note_row("git:state", error)] |
| 370 | } else { |
| 371 | git_state_rows(snap) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | fn note_row(id: &str, text: &str) -> WorkRow { |
| 376 | WorkRow { |
| 377 | id: WorkRowId(id.to_string()), |
| 378 | mark: "·", |
| 379 | label: text.to_string(), |
| 380 | detail: String::new(), |
| 381 | tone: WorkTone::Muted, |
| 382 | selectable: false, |
| 383 | primary_action: None, |
| 384 | agent: None, |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | fn git_state_rows(snap: &codewhale_engine::git_status::GitStatusSnapshot) -> Vec<WorkRow> { |
| 389 | let mut out = Vec::new(); |
| 390 | let branch = match (snap.branch.as_deref(), snap.detached) { |
| 391 | (Some(id), true) => format!("detached at {id}"), |
| 392 | (Some(branch), false) => branch.to_string(), |
| 393 | (None, _) => "no commits yet".to_string(), |
| 394 | }; |
| 395 | let upstream = if snap.detached { |
| 396 | String::new() |
| 397 | } else if !snap.has_upstream { |
| 398 | " · no upstream".to_string() |
| 399 | } else if snap.ahead == 0 && snap.behind == 0 { |
| 400 | " · up to date".to_string() |
| 401 | } else { |
| 402 | format!(" · ↑{} ↓{}", snap.ahead, snap.behind) |
| 403 | }; |
| 404 | let location = snap |
| 405 | .remote_slug |
| 406 | .clone() |
| 407 | .or_else(|| snap.repository_name.clone()) |
| 408 | .unwrap_or_default(); |
| 409 | out.push(WorkRow { |
| 410 | id: WorkRowId("git:branch".to_string()), |
| 411 | mark: "⎇", |
| 412 | label: format!("{branch}{upstream}"), |
| 413 | detail: location, |
| 414 | tone: WorkTone::Live, |
| 415 | selectable: true, |
| 416 | primary_action: Some(SidebarRowAction::Command("/diff".to_string())), |
| 417 | agent: None, |
| 418 | }); |
| 419 | let changes = snap.changes.summary(); |
| 420 | let body = if snap.changed_paths.is_empty() { |
| 421 | "Working tree clean.".to_string() |
| 422 | } else { |
| 423 | let listed = snap |
| 424 | .changed_paths |
| 425 | .iter() |
| 426 | .map(|path| format!("{} {}", path.code, path.path)) |
| 427 | .collect::<Vec<_>>() |
| 428 | .join("\n"); |
| 429 | let tail = if snap.changed_path_count > snap.changed_paths.len() { |
| 430 | "\n… and more; /diff for everything".to_string() |
| 431 | } else { |
| 432 | String::new() |
| 433 | }; |
| 434 | format!("{listed}{tail}") |
| 435 | }; |
| 436 | out.push(WorkRow { |
| 437 | id: WorkRowId("git:changes".to_string()), |
| 438 | mark: if snap.changes.conflicts > 0 { |
| 439 | "!" |
| 440 | } else { |
| 441 | "±" |
| 442 | }, |
| 443 | label: changes, |
| 444 | detail: String::new(), |
| 445 | tone: if snap.changes.conflicts > 0 { |
| 446 | WorkTone::Attention |
| 447 | } else if snap.dirty { |
| 448 | WorkTone::Live |
| 449 | } else { |
| 450 | WorkTone::Muted |
| 451 | }, |
| 452 | selectable: true, |
| 453 | primary_action: Some(SidebarRowAction::InspectWork { |
| 454 | title: "Git · changes".to_string(), |
| 455 | body, |
| 456 | stop_action: None, |
| 457 | }), |
| 458 | agent: None, |
| 459 | }); |
| 460 | let linked: Vec<_> = snap |
| 461 | .worktrees |
| 462 | .iter() |
| 463 | .filter(|worktree| !worktree.bare && Some(&worktree.path) != snap.root.as_ref()) |
| 464 | .collect(); |
| 465 | if !linked.is_empty() { |
| 466 | out.push(heading( |
| 467 | "git:worktrees", |
| 468 | format!("Worktrees {}", linked.len()), |
| 469 | )); |
| 470 | for worktree in linked { |
| 471 | out.push(WorkRow { |
| 472 | id: WorkRowId(format!("git:worktree:{}", worktree.path.display())), |
| 473 | mark: "·", |
| 474 | label: worktree |
| 475 | .branch |
| 476 | .clone() |
| 477 | .unwrap_or_else(|| "detached".to_string()), |
| 478 | detail: format!( |
| 479 | "{}{}", |
| 480 | worktree.path.display(), |
| 481 | if worktree.locked { " · locked" } else { "" } |
| 482 | ), |
| 483 | tone: WorkTone::Muted, |
| 484 | selectable: false, |
| 485 | primary_action: None, |
| 486 | agent: None, |
| 487 | }); |
| 488 | } |
| 489 | } |
| 490 | if !snap.recent_commits.is_empty() { |
| 491 | out.push(heading("git:commits", "Recent commits".to_string())); |
| 492 | for commit in &snap.recent_commits { |
| 493 | out.push(WorkRow { |
| 494 | id: WorkRowId(format!("git:commit:{}", commit.hash)), |
| 495 | mark: "·", |
| 496 | label: format!("{} {}", commit.hash, commit.subject), |
| 497 | detail: commit.when.clone(), |
| 498 | tone: WorkTone::Muted, |
| 499 | selectable: false, |
| 500 | primary_action: None, |
| 501 | agent: None, |
| 502 | }); |
| 503 | } |
| 504 | } |
| 505 | out |
| 506 | } |
| 507 | |
| 508 | /// The price view. One number everywhere: the session total is the same |
| 509 | /// `displayed_session_cost_for_currency` the footer chip prints, through the |
| 510 | /// same `App::format_cost_amount`; per-agent rows come from the roster's |
| 511 | /// usage receipts (`cost_microusd`, absent = no receipt, never `0`). |
| 512 | pub(super) fn price_rows(app: &mut App) -> Vec<WorkRow> { |
| 513 | let mut out = Vec::new(); |
| 514 | let session = app.session_cost_label(); |
| 515 | out.push(WorkRow { |
| 516 | id: WorkRowId("price:session".to_string()), |
| 517 | mark: "$", |
| 518 | label: format!("session · {session}"), |
| 519 | detail: "/cost for the full ledger".to_string(), |
| 520 | tone: WorkTone::Live, |
| 521 | selectable: true, |
| 522 | primary_action: Some(SidebarRowAction::Command("/cost".to_string())), |
| 523 | agent: None, |
| 524 | }); |
| 525 | let roster = app.current_agent_roster().to_vec(); |
| 526 | let priced: Vec<_> = roster |
| 527 | .iter() |
| 528 | .filter(|row| row.cost_microusd.is_some()) |
| 529 | .collect(); |
| 530 | if !priced.is_empty() { |
| 531 | let total = priced |
| 532 | .iter() |
| 533 | .filter_map(|row| row.cost_microusd) |
| 534 | .fold(0u64, u64::saturating_add); |
| 535 | out.push(WorkRow { |
| 536 | id: WorkRowId("price:agents".to_string()), |
| 537 | mark: "·", |
| 538 | label: format!( |
| 539 | "agents · {}", |
| 540 | app.format_cost_amount(total as f64 / 1_000_000.0) |
| 541 | ), |
| 542 | detail: format!("{} of {} agents priced", priced.len(), roster.len()), |
| 543 | tone: WorkTone::Muted, |
| 544 | selectable: false, |
| 545 | primary_action: None, |
| 546 | agent: None, |
| 547 | }); |
| 548 | for row in priced { |
| 549 | let cost = row.cost_microusd.unwrap_or(0) as f64 / 1_000_000.0; |
| 550 | out.push(WorkRow { |
| 551 | id: WorkRowId(format!("price:agent:{}", row.worker_id)), |
| 552 | mark: row.state.glyph(), |
| 553 | label: format!(" {} · {}", row.display_name, app.format_cost_amount(cost)), |
| 554 | detail: row.model.clone(), |
| 555 | tone: WorkTone::Muted, |
| 556 | selectable: true, |
| 557 | primary_action: Some(SidebarRowAction::OpenAgentDetail { |
| 558 | agent_id: row.worker_id.clone(), |
| 559 | }), |
| 560 | agent: None, |
| 561 | }); |
| 562 | } |
| 563 | } |
| 564 | let rates = crate::tui::session_metrics::cache_rates(app); |
| 565 | if let Some(rates) = rates.labelled("parent", "agents", "combined") { |
| 566 | out.push(WorkRow { |
| 567 | id: WorkRowId("price:cache".to_string()), |
| 568 | mark: "·", |
| 569 | label: format!("cache hit · {rates}"), |
| 570 | detail: "/cache for per-turn cache telemetry".to_string(), |
| 571 | tone: WorkTone::Muted, |
| 572 | selectable: true, |
| 573 | primary_action: Some(SidebarRowAction::Command("/cache".to_string())), |
| 574 | agent: None, |
| 575 | }); |
| 576 | } |
| 577 | if let Some(rate) = codewhale_engine::pricing::model_rate_label( |
| 578 | app.api_provider, |
| 579 | &app.model, |
| 580 | app.cost_display_currency(app.cost_currency), |
| 581 | ) { |
| 582 | out.push(WorkRow { |
| 583 | id: WorkRowId("price:rate".to_string()), |
| 584 | mark: "·", |
| 585 | label: format!("{} · {rate}", app.model), |
| 586 | detail: "per million tokens, in / out".to_string(), |
| 587 | tone: WorkTone::Muted, |
| 588 | selectable: false, |
| 589 | primary_action: None, |
| 590 | agent: None, |
| 591 | }); |
| 592 | } |
| 593 | app.work_surface.latest_rows = out.clone(); |
| 594 | out |
| 595 | } |
| 596 | |
| 597 | #[cfg(test)] |
| 598 | mod tests { |
| 599 | use super::*; |
| 600 | use codewhale_engine::git_status::{ |
| 601 | ChangeCounts, ChangedPath, GitStatusSnapshot, RecentCommit, WorktreeEntry, |
| 602 | }; |
| 603 | use std::path::{Path, PathBuf}; |
| 604 | use std::time::Instant; |
| 605 | |
| 606 | fn app() -> App { |
| 607 | crate::tui::app::App::new( |
| 608 | crate::tui::test_support::test_tui_options(PathBuf::from("/repo")), |
| 609 | &codewhale_runtime::config::Config::default(), |
| 610 | ) |
| 611 | } |
| 612 | |
| 613 | #[test] |
| 614 | fn the_git_view_names_its_state_honestly() { |
| 615 | let workspace = Path::new("/repo"); |
| 616 | // Before the first probe for this workspace. |
| 617 | let rows = git_rows_for(&GitStatusSnapshot::default(), workspace); |
| 618 | assert_eq!(rows[0].label, "reading git status…"); |
| 619 | let other = GitStatusSnapshot { |
| 620 | probed_workspace: Some(PathBuf::from("/elsewhere")), |
| 621 | fetched_at: Some(Instant::now()), |
| 622 | ..GitStatusSnapshot::default() |
| 623 | }; |
| 624 | assert_eq!( |
| 625 | git_rows_for(&other, workspace)[0].label, |
| 626 | "reading git status…" |
| 627 | ); |
| 628 | // Only a probe that found no repository says so. |
| 629 | let outside = GitStatusSnapshot { |
| 630 | probed_workspace: Some(workspace.to_path_buf()), |
| 631 | fetched_at: Some(Instant::now()), |
| 632 | error: Some("not a git repository".to_string()), |
| 633 | ..GitStatusSnapshot::default() |
| 634 | }; |
| 635 | assert_eq!( |
| 636 | git_rows_for(&outside, workspace)[0].label, |
| 637 | "not a git repository" |
| 638 | ); |
| 639 | let broken = GitStatusSnapshot { |
| 640 | error: Some("git unavailable: No such file".to_string()), |
| 641 | ..outside |
| 642 | }; |
| 643 | assert_eq!( |
| 644 | git_rows_for(&broken, workspace)[0].label, |
| 645 | "git unavailable: No such file" |
| 646 | ); |
| 647 | } |
| 648 | |
| 649 | #[test] |
| 650 | fn the_git_view_shows_branch_changes_worktrees_and_commits() { |
| 651 | let workspace = Path::new("/repo"); |
| 652 | let snap = GitStatusSnapshot { |
| 653 | probed_workspace: Some(workspace.to_path_buf()), |
| 654 | fetched_at: Some(Instant::now()), |
| 655 | root: Some(PathBuf::from("/repo")), |
| 656 | repository_name: Some("repo".to_string()), |
| 657 | remote_slug: Some("owner/repo".to_string()), |
| 658 | branch: Some("main".to_string()), |
| 659 | has_upstream: true, |
| 660 | ahead: 2, |
| 661 | behind: 1, |
| 662 | dirty: true, |
| 663 | changes: ChangeCounts { |
| 664 | staged: 1, |
| 665 | modified: 1, |
| 666 | untracked: 0, |
| 667 | conflicts: 0, |
| 668 | }, |
| 669 | changed_path_count: 2, |
| 670 | changed_paths: vec![ |
| 671 | ChangedPath { |
| 672 | code: "M ".to_string(), |
| 673 | path: "src/lib.rs".to_string(), |
| 674 | }, |
| 675 | ChangedPath { |
| 676 | code: " M".to_string(), |
| 677 | path: "README.md".to_string(), |
| 678 | }, |
| 679 | ], |
| 680 | worktrees: vec![ |
| 681 | WorktreeEntry { |
| 682 | path: PathBuf::from("/repo"), |
| 683 | branch: Some("main".to_string()), |
| 684 | bare: false, |
| 685 | locked: false, |
| 686 | }, |
| 687 | WorktreeEntry { |
| 688 | path: PathBuf::from("/repo/.cw-worktrees/agent-a"), |
| 689 | branch: Some("agent-a".to_string()), |
| 690 | bare: false, |
| 691 | locked: true, |
| 692 | }, |
| 693 | ], |
| 694 | recent_commits: vec![RecentCommit { |
| 695 | hash: "abc1234".to_string(), |
| 696 | subject: "fix: a thing".to_string(), |
| 697 | when: "3 hours ago".to_string(), |
| 698 | }], |
| 699 | ..GitStatusSnapshot::default() |
| 700 | }; |
| 701 | let rows = git_rows_for(&snap, workspace); |
| 702 | let labels = rows |
| 703 | .iter() |
| 704 | .map(|row| row.label.as_str()) |
| 705 | .collect::<Vec<_>>(); |
| 706 | assert_eq!( |
| 707 | labels, |
| 708 | [ |
| 709 | "main · ↑2 ↓1", |
| 710 | "1 staged, 1 modified", |
| 711 | "Worktrees 1", |
| 712 | "agent-a", |
| 713 | "Recent commits", |
| 714 | "abc1234 fix: a thing", |
| 715 | ] |
| 716 | ); |
| 717 | assert_eq!(rows[0].detail, "owner/repo"); |
| 718 | let Some(SidebarRowAction::InspectWork { body, .. }) = rows[1].primary_action.as_ref() |
| 719 | else { |
| 720 | panic!("changes row opens its paths"); |
| 721 | }; |
| 722 | assert_eq!(body, "M src/lib.rs\n M README.md"); |
| 723 | assert!( |
| 724 | rows[3].detail.ends_with("agent-a · locked"), |
| 725 | "{}", |
| 726 | rows[3].detail |
| 727 | ); |
| 728 | |
| 729 | let no_upstream = GitStatusSnapshot { |
| 730 | has_upstream: false, |
| 731 | ..snap.clone() |
| 732 | }; |
| 733 | assert_eq!( |
| 734 | git_rows_for(&no_upstream, workspace)[0].label, |
| 735 | "main · no upstream" |
| 736 | ); |
| 737 | let detached = GitStatusSnapshot { |
| 738 | branch: Some("abc1234".to_string()), |
| 739 | detached: true, |
| 740 | ..snap |
| 741 | }; |
| 742 | assert_eq!( |
| 743 | git_rows_for(&detached, workspace)[0].label, |
| 744 | "detached at abc1234" |
| 745 | ); |
| 746 | } |
| 747 | |
| 748 | #[test] |
| 749 | fn git_more_means_unlisted_paths() { |
| 750 | use codewhale_engine::git_status::{MAX_CHANGED_PATHS, parse_porcelain_v2}; |
| 751 | for count in [1, MAX_CHANGED_PATHS, MAX_CHANGED_PATHS + 1] { |
| 752 | let mut raw = "# branch.head main\0".to_string(); |
| 753 | for index in 0..count { |
| 754 | raw.push_str(&format!( |
| 755 | "1 MM N... 100644 100644 100644 aaa bbb file-{index}\0" |
| 756 | )); |
| 757 | } |
| 758 | let status = parse_porcelain_v2(&raw).unwrap(); |
| 759 | let rows = git_state_rows(&GitStatusSnapshot { |
| 760 | changes: status.changes, |
| 761 | changed_paths: status.changed_paths, |
| 762 | changed_path_count: status.changed_path_count, |
| 763 | ..GitStatusSnapshot::default() |
| 764 | }); |
| 765 | let Some(SidebarRowAction::InspectWork { body, .. }) = &rows[1].primary_action else { |
| 766 | panic!("changes opens path details"); |
| 767 | }; |
| 768 | assert_eq!( |
| 769 | body.contains("and more"), |
| 770 | count > MAX_CHANGED_PATHS, |
| 771 | "{count}" |
| 772 | ); |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | fn record_file(app: &mut App, id: &str, action: &str, path: &str, diff: Option<String>) { |
| 777 | use crate::tui::tool_routing::{handle_tool_call_complete, handle_tool_call_started}; |
| 778 | use codewhale_engine::tools::spec::ToolResult; |
| 779 | let input = serde_json::json!({"action": action, "path": path, "content": "new"}); |
| 780 | handle_tool_call_started(app, id, "File", &input); |
| 781 | let mut result = ToolResult::success("ok"); |
| 782 | if let Some(diff) = diff { |
| 783 | result = result.with_metadata(serde_json::json!({"mutation": { |
| 784 | "diff": diff, "files": [{"path": path, "outcome": "updated"}], |
| 785 | }})); |
| 786 | } |
| 787 | handle_tool_call_complete(app, id, "File", &Ok(result)); |
| 788 | app.flush_active_cell(); |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn files_and_badge_follow_current_history_without_opening_tasks() { |
| 793 | for badge_first in [false, true] { |
| 794 | let mut app = app(); |
| 795 | app.current_session_id = Some("session-a".into()); |
| 796 | record_file(&mut app, "first", "write", "first.rs", None); |
| 797 | if badge_first { |
| 798 | assert_eq!(files_touched_count(&mut app), 1); |
| 799 | } else { |
| 800 | assert!( |
| 801 | files_rows(&mut app) |
| 802 | .iter() |
| 803 | .any(|row| row.label == "first.rs") |
| 804 | ); |
| 805 | } |
| 806 | record_file(&mut app, "second", "read", "second.rs", None); |
| 807 | if badge_first { |
| 808 | assert_eq!(files_touched_count(&mut app), 2); |
| 809 | } else { |
| 810 | assert!( |
| 811 | files_rows(&mut app) |
| 812 | .iter() |
| 813 | .any(|row| row.label == "second.rs") |
| 814 | ); |
| 815 | } |
| 816 | // Keep the old projection, as a session switch can, but replace |
| 817 | // the transcript that owns the next session's activity. |
| 818 | app.history.clear(); |
| 819 | app.current_session_id = Some("session-b".into()); |
| 820 | if badge_first { |
| 821 | assert_eq!(files_touched_count(&mut app), 0); |
| 822 | assert!(files_rows(&mut app).is_empty()); |
| 823 | } else { |
| 824 | assert!(files_rows(&mut app).is_empty()); |
| 825 | assert_eq!(files_touched_count(&mut app), 0); |
| 826 | } |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn failed_git_status_reports_the_error_in_the_view_and_composer() { |
| 832 | use codewhale_engine::git_status::{context_line, probe_status}; |
| 833 | let dir = tempfile::tempdir().unwrap(); |
| 834 | let workspace = dir.path(); |
| 835 | let init = std::process::Command::new("git") |
| 836 | .args(["init", "--initial-branch=main"]) |
| 837 | .current_dir(workspace) |
| 838 | .output() |
| 839 | .unwrap(); |
| 840 | assert!(init.status.success()); |
| 841 | let clean = probe_status(workspace); |
| 842 | assert!(clean.error.is_none(), "{clean:?}"); |
| 843 | assert!(context_line(&clean).unwrap().contains("clean")); |
| 844 | std::fs::write(workspace.join(".git/index"), b"broken index").unwrap(); |
| 845 | let failed = probe_status(workspace); |
| 846 | assert!(failed.root.is_some(), "root discovery still succeeds"); |
| 847 | let error = failed |
| 848 | .error |
| 849 | .as_deref() |
| 850 | .expect("status failure must be recorded"); |
| 851 | assert!(error.contains("git status failed"), "{error}"); |
| 852 | assert!(error.contains("index"), "{error}"); |
| 853 | assert_eq!(context_line(&failed).as_deref(), Some(error)); |
| 854 | let rows = git_rows_for(&failed, workspace); |
| 855 | assert_eq!(rows.len(), 1); |
| 856 | assert_eq!(rows[0].label, error); |
| 857 | assert!(!rows[0].label.contains("clean")); |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn files_include_successful_writes_without_receipts() { |
| 862 | use crate::tui::tool_routing::{handle_tool_call_complete, handle_tool_call_started}; |
| 863 | use codewhale_engine::tools::spec::ToolResult; |
| 864 | let mut app = app(); |
| 865 | for (id, action, path) in [("write", "write", "new.rs"), ("edit", "edit", "edited.rs")] { |
| 866 | let input = serde_json::json!({"action": action, "path": path, "content": "new"}); |
| 867 | handle_tool_call_started(&mut app, id, "File", &input); |
| 868 | handle_tool_call_complete(&mut app, id, "File", &Ok(ToolResult::success("ok"))); |
| 869 | app.flush_active_cell(); |
| 870 | } |
| 871 | assert_eq!(files_touched_count(&mut app), 2); |
| 872 | let rows = files_rows(&mut app); |
| 873 | for path in ["new.rs", "edited.rs"] { |
| 874 | let row = rows |
| 875 | .iter() |
| 876 | .find(|row| row.label == path) |
| 877 | .expect("write row"); |
| 878 | assert!(!row.selectable); |
| 879 | assert!(row.primary_action.is_none()); |
| 880 | assert!(row.detail.is_empty()); |
| 881 | } |
| 882 | // A receipt for an already-listed write adds its diff, not a second row. |
| 883 | record_file( |
| 884 | &mut app, |
| 885 | "receipt", |
| 886 | "edit", |
| 887 | "edited.rs", |
| 888 | Some("--- a/edited.rs\n+++ b/edited.rs\n@@ -0,0 +1 @@\n+new\n".into()), |
| 889 | ); |
| 890 | let rows = files_rows(&mut app); |
| 891 | assert_eq!(files_touched_count(&mut app), 2); |
| 892 | assert_eq!( |
| 893 | rows.iter().filter(|row| row.label == "edited.rs").count(), |
| 894 | 1 |
| 895 | ); |
| 896 | assert!( |
| 897 | rows.iter() |
| 898 | .find(|row| row.label == "edited.rs") |
| 899 | .unwrap() |
| 900 | .selectable |
| 901 | ); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn the_files_view_lists_edits_with_their_size_then_reads() { |
| 906 | let mut app = app(); |
| 907 | assert!(files_rows(&mut app).is_empty()); |
| 908 | assert_eq!(files_touched_count(&mut app), 0); |
| 909 | let diff = format!( |
| 910 | "--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1,3 +1,12 @@\n{}{}", |
| 911 | "-old\n".repeat(3), |
| 912 | "+new\n".repeat(12), |
| 913 | ); |
| 914 | record_file(&mut app, "edit", "edit", "src/lib.rs", Some(diff)); |
| 915 | record_file(&mut app, "read", "read", "Cargo.toml", None); |
| 916 | let rows = files_rows(&mut app); |
| 917 | let labels = rows |
| 918 | .iter() |
| 919 | .map(|row| row.label.as_str()) |
| 920 | .collect::<Vec<_>>(); |
| 921 | assert_eq!(labels, ["Edited 1", "src/lib.rs", "Read 1", "Cargo.toml"]); |
| 922 | assert_eq!(rows[1].detail, "+12 −3"); |
| 923 | assert!(rows[1].selectable); |
| 924 | assert_eq!(files_touched_count(&mut app), 2); |
| 925 | } |
| 926 | |
| 927 | #[test] |
| 928 | fn the_notes_view_lists_each_note_and_opens_it() { |
| 929 | let mut app = app(); |
| 930 | assert!(!notepad_has_text(&app)); |
| 931 | assert!(notepad_rows(&mut app).is_empty()); |
| 932 | app.workspace_notes = vec![ |
| 933 | "Ship the docs fix\nwith the link audit".to_string(), |
| 934 | "Ask about the flaky test".to_string(), |
| 935 | ]; |
| 936 | assert!(notepad_has_text(&app)); |
| 937 | let rows = notepad_rows(&mut app); |
| 938 | assert_eq!(rows[0].label, "Ship the docs fix"); |
| 939 | assert!(matches!( |
| 940 | rows[1].primary_action.as_ref(), |
| 941 | Some(SidebarRowAction::Command(command)) if command == "/note show 2" |
| 942 | )); |
| 943 | } |
| 944 | } |
| 945 |