返回 CodeWhale
mod.rs
根目录 / crates / tui / src / tui / work_surface / render / mod.rs
1 //! Painting the work surface, and the two files it leans on.
2 //!
3 //! - [`layout`] answers *where and how tall* — placement fallback, the height
4 //! and cap arithmetic, and the side-rail split.
5 //! - [`rows`] answers *what one row says* — the sub-agent column layout, its
6 //! degradation tiers, and row styling.
7 //!
8 //! What stays here is the paint itself: the strip, the side rail, the dock
9 //! tab row, the divider and scrollbar chrome, and the strip header content
10 //! (goal title, to-do receipt) that height and paint must both agree on.
11 //! Every view — work rows and fact rows alike — goes through the one row
12 //! loop below; there is no second line-list renderer.
13
14 use std::collections::HashMap;
15
16 use ratatui::{
17 Frame,
18 layout::Rect,
19 prelude::Widget,
20 style::{Color, Modifier, Style},
21 text::{Line, Span},
22 widgets::{Block, BorderType, Borders, Paragraph},
23 };
24 use unicode_width::UnicodeWidthStr;
25
26 use crate::tui::app::{App, SidebarHoverRow, SidebarHoverSection};
27 use codewhale_localization::MessageId;
28 use codewhale_palette::{ChromeInk, chrome_style};
29 use codewhale_tui_kit::ui_text::truncate_line_to_width;
30
31 use super::model::{
32 DockTabHitbox, DockTabTarget, RailPanel, WorkHitbox, WorkRow, WorkSurfacePlacement, WorkTone,
33 plan_step_row_ids, visible_rows_for, visible_rows_for_panel,
34 };
35
36 mod layout;
37 mod rows;
38
39 #[cfg(test)]
40 mod body_tests;
41 #[cfg(test)]
42 mod dock_tabs_tests;
43
44 pub(crate) use layout::collapse_strip;
45 pub use layout::{height, split_chat};
46
47 use rows::{
48 AGENT_ROLE_GUTTER, AgentRowTier, agent_identity, agent_identity_cap, agent_identity_column,
49 agent_receipt, agent_row_styles, agent_status_column, layout_agent_row, row_style,
50 };
51
52 pub fn render(frame: &mut Frame, area: Rect, app: &mut App) {
53 render_with_ascii(
54 frame,
55 area,
56 app,
57 crate::tui::color_compat::ascii_safe_enabled(),
58 );
59 }
60
61 pub(super) fn render_with_ascii(frame: &mut Frame, area: Rect, app: &mut App, ascii: bool) {
62 if area.width == 0 || area.height == 0 {
63 collapse_strip(app);
64 return;
65 }
66
67 if let Some(previous) = app.work_surface.last_area {
68 app.sidebar_hover
69 .sections
70 .retain(|section| section.content_area != previous);
71 }
72
73 let placement = app.work_surface.effective_placement;
74 // Off renders no rail; height()/split_chat() never hand us an area for it.
75 if placement == WorkSurfacePlacement::Off {
76 collapse_strip(app);
77 return;
78 }
79 let framed = area.width >= 4 && area.height >= 3;
80 let body_area = if framed {
81 Rect {
82 x: area.x.saturating_add(1),
83 y: area.y.saturating_add(1),
84 width: area.width.saturating_sub(2),
85 height: area.height.saturating_sub(2),
86 }
87 } else if placement.is_strip() {
88 Rect {
89 y: area.y.saturating_add(1),
90 height: area.height.saturating_sub(1),
91 ..area
92 }
93 } else {
94 area
95 };
96 let tab_area = if framed {
97 Rect::new(
98 area.x.saturating_add(1),
99 area.y,
100 area.width.saturating_sub(2),
101 1,
102 )
103 } else {
104 Rect::new(area.x, area.y, area.width, 1)
105 };
106
107 let show_tabs = framed || placement.is_strip();
108 if !show_tabs {
109 app.work_surface.dock_tabs.clear();
110 app.work_surface.pressed_tab = None;
111 app.work_surface.hovered_tab = None;
112 }
113
114 super::model::resolve_view(app);
115 let rows = visible_rows_for_panel(app);
116 if app.work_surface.panel == RailPanel::Terminal {
117 let border_color = render_frame(frame, area, placement, ascii, app);
118 if show_tabs {
119 render_dock_tabs_with_ascii(frame, tab_area, app, ascii);
120 register_dock_targets(app);
121 }
122 if framed && !ascii {
123 light_workbar_edge(
124 area,
125 frame.buffer_mut(),
126 &app.work_surface.dock_tabs,
127 app.work_surface.panel,
128 border_color,
129 app.ui_theme.accent_primary,
130 app.ui_theme.composer_bg,
131 );
132 }
133 super::terminal::render(frame, body_area, app);
134 app.work_surface.last_area = Some(area);
135 return;
136 }
137 let todo_ordinals = if placement.is_strip() {
138 todo_ordinals(&rows)
139 } else {
140 HashMap::new()
141 };
142 let ordinal_width = todo_ordinals.len().max(1).to_string().len();
143 let todo_ids = plan_step_row_ids(app);
144 let goal_title = placement.is_strip().then(|| top_goal_title(app)).flatten();
145 let todo_progress = placement
146 .is_strip()
147 .then(|| top_todo_progress(app, &rows))
148 .flatten();
149 // Pin goal title, then progress receipt, above the scrollable rows.
150 // A compact strip keeps its last usable row for content, ahead of headers.
151 // Body geometry has one shared owner; Engine still supplies viewport,
152 // caller rows, goal/progress truth and the remembered scroll offset.
153 let body_layout = codewhale_ratatui::WorkbarLayout::for_body(
154 body_area,
155 rows.len(),
156 app.work_surface.scroll_offset,
157 goal_title.is_some(),
158 todo_progress.is_some(),
159 );
160 let goal_height = body_layout.goal_height;
161 let fold_progress = progress_shares_goal_row(body_area.width, goal_height > 0);
162 let progress_height = body_layout.progress_height;
163 let content_area = body_layout.content;
164 let overflow = body_layout.overflow;
165 let more_row = body_layout.more_row;
166 let list_rows = body_layout.visible_rows;
167 app.work_surface.visible_rows = list_rows;
168 app.work_surface.total_rows = rows.len();
169 // A redraw clamps the viewport, never reveals the remembered selection.
170 app.work_surface.clamp_viewport(&rows);
171
172 let border_color = render_frame(frame, area, placement, ascii, app);
173 if show_tabs {
174 render_dock_tabs_with_ascii(frame, tab_area, app, ascii);
175 register_dock_targets(app);
176 }
177 if framed && !ascii {
178 light_workbar_edge(
179 area,
180 frame.buffer_mut(),
181 &app.work_surface.dock_tabs,
182 app.work_surface.panel,
183 border_color,
184 app.ui_theme.accent_primary,
185 app.ui_theme.composer_bg,
186 );
187 }
188
189 if let Some((goal_text, goal_style)) = goal_title.filter(|_| goal_height > 0) {
190 let full_width = usize::from(content_area.width);
191 // Wide strips carry the receipt right-aligned on the goal row rather
192 // than spending a second row announcing a count.
193 let receipt = todo_progress.as_deref().filter(|_| fold_progress);
194 let reserved = receipt
195 .map(|text| UnicodeWidthStr::width(text).saturating_add(2))
196 .unwrap_or(0);
197 let goal_text = truncate_line_to_width(&goal_text, full_width.saturating_sub(reserved));
198 let mut spans = vec![Span::styled(
199 goal_text.clone(),
200 goal_style.bg(app.ui_theme.composer_bg),
201 )];
202 if let Some(receipt) = receipt {
203 let gap = full_width
204 .saturating_sub(UnicodeWidthStr::width(goal_text.as_str()))
205 .saturating_sub(UnicodeWidthStr::width(receipt));
206 spans.push(Span::styled(
207 format!("{}{receipt}", " ".repeat(gap)),
208 Style::default()
209 .fg(app.ui_theme.text_muted)
210 .bg(app.ui_theme.composer_bg),
211 ));
212 }
213 Paragraph::new(Line::from(spans)).render(
214 Rect {
215 y: body_area.y,
216 height: 1,
217 ..content_area
218 },
219 frame.buffer_mut(),
220 );
221 }
222
223 if let Some(progress) = todo_progress.filter(|_| progress_height > 0) {
224 let progress = truncate_line_to_width(&progress, usize::from(content_area.width));
225 // Muted, not accent: accent_primary means "selected" everywhere else
226 // in the strip, and spending it on a static count makes the actual
227 // selection hard to find.
228 Paragraph::new(Line::from(Span::styled(
229 progress,
230 Style::default()
231 .fg(app.ui_theme.text_muted)
232 .bg(app.ui_theme.composer_bg),
233 )))
234 .render(
235 Rect {
236 y: body_area.y.saturating_add(goal_height),
237 height: 1,
238 ..content_area
239 },
240 frame.buffer_mut(),
241 );
242 }
243
244 let start = app.work_surface.scroll_offset;
245 let visible = rows.iter().skip(start).take(list_rows).collect::<Vec<_>>();
246 let identity_cap = agent_identity_cap(usize::from(content_area.width));
247 let identity_column = agent_identity_column(&visible, identity_cap);
248 let status_column = agent_status_column(&visible);
249 let mut lines = Vec::with_capacity(visible.len().saturating_add(1));
250 let mut hover_rows = Vec::new();
251 let mut hitboxes = Vec::new();
252 for (visible_index, row) in visible.iter().enumerate() {
253 let row_y = content_area.y.saturating_add(visible_index as u16);
254 let selected =
255 app.work_surface.focused && app.work_surface.selected.as_ref() == Some(&row.id);
256 let hovered = app.work_surface.hovered.as_ref() == Some(&row.id);
257 let opened = app.work_surface.opened.as_ref() == Some(&row.id);
258 let style = row_style(app, row, selected, hovered, opened);
259 let compact_owner = if placement.is_strip() {
260 todo_ordinals
261 .get(&row.id.0)
262 .map(|ordinal| format!("{ordinal:>ordinal_width$} · "))
263 .unwrap_or_default()
264 } else {
265 String::new()
266 };
267 let mark = if opened && row.selectable {
268 "▾"
269 } else {
270 row.mark
271 };
272 // Agent focus marker: while a worker is focused every row gains a
273 // two-cell gutter and the focused worker's row shows the selection
274 // glyph in it, so the addressed fork is visible at the left edge.
275 let focus_gutter = if app.agent_focus.is_some() {
276 let focused = row
277 .id
278 .0
279 .strip_prefix("worker:")
280 .is_some_and(|id| app.agent_focus.as_ref().is_some_and(|f| f.is(id)));
281 if focused {
282 "❯ ".to_string()
283 } else {
284 " ".to_string()
285 }
286 } else {
287 String::new()
288 };
289 let prefix = if row.tone == WorkTone::Heading {
290 format!("{focus_gutter}{} ", mark)
291 } else {
292 format!("{focus_gutter}{compact_owner}{mark} ")
293 };
294
295 // Sub-agent rows own their own column layout: glyph, agent type,
296 // objective, right-aligned elapsed and tokens. They stay ordinary
297 // rows in every other respect — same hitbox, same selection, same
298 // primary action.
299 if let Some(facts) = row.agent.as_ref() {
300 let queued = row
301 .id
302 .0
303 .strip_prefix("worker:")
304 .and_then(|id| crate::tui::agent_focus::queued_suffix(app, id))
305 .map(|queued| format!(" · {queued}"));
306 let queued_width = queued.as_deref().map(UnicodeWidthStr::width).unwrap_or(0);
307 let laid_out = layout_agent_row(
308 usize::from(content_area.width).saturating_sub(queued_width),
309 UnicodeWidthStr::width(prefix.as_str()),
310 &agent_identity(row, identity_cap),
311 identity_column,
312 status_column,
313 facts,
314 );
315 let (normal, muted) = agent_row_styles(app, selected, hovered, opened);
316 let display = format!(
317 "{prefix}{}{}{}{}{}{}{}",
318 laid_out.role,
319 if laid_out.role.is_empty() {
320 String::new()
321 } else {
322 " ".repeat(AGENT_ROLE_GUTTER)
323 },
324 laid_out.status,
325 if laid_out.status.is_empty() {
326 String::new()
327 } else {
328 " ".repeat(AGENT_ROLE_GUTTER)
329 },
330 laid_out.objective,
331 " ".repeat(laid_out.gap),
332 laid_out.receipt,
333 );
334 let mut spans = vec![Span::styled(prefix.clone(), normal)];
335 if !laid_out.role.is_empty() {
336 spans.push(Span::styled(
337 format!("{}{}", laid_out.role, " ".repeat(AGENT_ROLE_GUTTER)),
338 muted,
339 ));
340 }
341 if !laid_out.status.is_empty() {
342 spans.push(Span::styled(
343 format!("{}{}", laid_out.status, " ".repeat(AGENT_ROLE_GUTTER)),
344 muted,
345 ));
346 }
347 spans.push(Span::styled(laid_out.objective.clone(), normal));
348 spans.push(Span::styled(
349 format!("{}{}", " ".repeat(laid_out.gap), laid_out.receipt),
350 muted,
351 ));
352 if let Some(queued) = queued.as_deref() {
353 // Truthful `· N queued`: follow-ups the running child has not
354 // yet folded into its next round. Amber: a message is waiting
355 // on a busy agent, the one thing on this row that needs you.
356 spans.push(Span::styled(
357 queued.to_string(),
358 Style::default()
359 .fg(app.ui_theme.warning)
360 .bg(normal.bg.unwrap_or(app.ui_theme.composer_bg)),
361 ));
362 }
363 lines.push(Line::from(spans));
364
365 hitboxes.push(WorkHitbox {
366 id: row.id.clone(),
367 row_y,
368 });
369 hover_rows.push(SidebarHoverRow {
370 row_y,
371 display_text: display,
372 full_text: format!("{} · {}", row.label, row.detail),
373 detail: Some(row.detail.clone()),
374 is_truncated: laid_out.objective != facts.objective
375 || laid_out.receipt != agent_receipt(facts, AgentRowTier::Full),
376 click_action: row.primary_action.clone(),
377 stop_action: None,
378 stop_zone_start_col: None,
379 stop_zone_end_col: None,
380 });
381 continue;
382 }
383
384 let detail_candidate = if row.tone != WorkTone::Heading && content_area.width >= 44 {
385 format!(" {}", row.detail)
386 } else {
387 String::new()
388 };
389 let prefix_width = UnicodeWidthStr::width(prefix.as_str());
390 let row_width = usize::from(content_area.width);
391 let detail_room = if todo_ids.contains(&row.id.0) {
392 UnicodeWidthStr::width(detail_candidate.as_str())
393 .min(row_width.saturating_sub(prefix_width) / 2)
394 } else {
395 0
396 };
397 let label_budget = row_width.saturating_sub(prefix_width + detail_room).max(1);
398 let label = truncate_line_to_width(&row.label, label_budget);
399 let detail_budget =
400 row_width.saturating_sub(prefix_width + UnicodeWidthStr::width(label.as_str()));
401 let detail = if detail_budget >= 4 {
402 truncate_line_to_width(&detail_candidate, detail_budget)
403 } else {
404 String::new()
405 };
406 let detail_width = UnicodeWidthStr::width(detail.as_str());
407 let gap = usize::from(content_area.width)
408 .saturating_sub(prefix_width + UnicodeWidthStr::width(label.as_str()) + detail_width);
409 let primary = format!("{prefix}{label}");
410 let secondary = format!("{}{detail}", " ".repeat(gap));
411 let display = format!("{primary}{secondary}");
412 if detail.is_empty() {
413 lines.push(Line::from(Span::styled(display.clone(), style)));
414 } else {
415 let detail_bg = style.bg.unwrap_or(app.ui_theme.composer_bg);
416 let base_fg = if opened {
417 app.ui_theme.accent_primary
418 } else {
419 app.ui_theme.text_muted
420 };
421 let detail_fg = if selected || hovered {
422 codewhale_palette::enforce_contrast(base_fg, detail_bg, 4.5)
423 } else {
424 base_fg
425 };
426 let mut detail_style = Style::default().fg(detail_fg).bg(detail_bg);
427 if opened {
428 detail_style = detail_style.add_modifier(Modifier::UNDERLINED);
429 }
430 lines.push(Line::from(vec![
431 Span::styled(primary, style),
432 Span::styled(secondary, detail_style),
433 ]));
434 }
435
436 hitboxes.push(WorkHitbox {
437 id: row.id.clone(),
438 row_y,
439 });
440
441 if row.selectable {
442 hover_rows.push(SidebarHoverRow {
443 row_y,
444 display_text: display,
445 full_text: format!("{} · {}", row.label, row.detail),
446 detail: Some(row.detail.clone()),
447 is_truncated: label != row.label || detail != detail_candidate,
448 click_action: row.primary_action.clone(),
449 stop_action: None,
450 stop_zone_start_col: None,
451 stop_zone_end_col: None,
452 });
453 }
454 }
455
456 if visible.is_empty() && app.work_surface.explicit_view && content_area.height > 0 {
457 // An explicitly opened view with nothing in it says so, once, so
458 // cycling never lands on a blank band.
459 lines.push(Line::from(Span::styled(
460 truncate_line_to_width(
461 empty_view_hint(app.work_surface.panel),
462 usize::from(content_area.width),
463 ),
464 Style::default()
465 .fg(app.ui_theme.text_muted)
466 .bg(app.ui_theme.composer_bg),
467 )));
468 }
469
470 if more_row {
471 // Right-aligned under the receipt column, muted like every other
472 // secondary figure. Scrolled to the bottom there is nothing below, so
473 // the reserved row stays blank rather than claiming a count of zero.
474 let remaining = rows
475 .len()
476 .saturating_sub(start.saturating_add(visible.len()));
477 let text = if remaining == 0 {
478 String::new()
479 } else {
480 truncate_line_to_width(
481 &format!("↓ {remaining} more"),
482 usize::from(content_area.width),
483 )
484 };
485 let pad = usize::from(content_area.width).saturating_sub(UnicodeWidthStr::width(&*text));
486 lines.push(Line::from(Span::styled(
487 format!("{}{text}", " ".repeat(pad)),
488 Style::default()
489 .fg(app.ui_theme.text_muted)
490 .bg(app.ui_theme.composer_bg),
491 )));
492 }
493
494 Paragraph::new(lines).render(content_area, frame.buffer_mut());
495 if overflow {
496 let scrollbar_x = if placement == WorkSurfacePlacement::Left {
497 body_area.right().saturating_sub(1)
498 } else {
499 area.right().saturating_sub(1)
500 };
501 let track_color = if placement == WorkSurfacePlacement::Left {
502 app.ui_theme.border
503 } else {
504 border_color
505 };
506 render_scrollbar(
507 frame,
508 Rect {
509 x: scrollbar_x,
510 y: content_area.y,
511 width: 1,
512 height: content_area.height,
513 },
514 list_rows,
515 rows.len(),
516 track_color,
517 ascii,
518 app,
519 );
520 }
521
522 app.work_surface.last_area = Some(area);
523 app.work_surface.hitboxes = hitboxes;
524 app.sidebar_hover.sections.push(SidebarHoverSection {
525 content_area,
526 lines: visible.iter().map(|row| row.label.clone()).collect(),
527 rows: hover_rows,
528 });
529 // The tab badges projected the other views on the way here; the rows
530 // a click resolves against are the ones this frame painted.
531 app.work_surface.latest_rows = rows;
532 }
533
534 /// What an explicitly opened, empty view says on its one row.
535 fn empty_view_hint(panel: RailPanel) -> &'static str {
536 match panel {
537 RailPanel::Agents => "no agents have run this session",
538 RailPanel::Tasks => "no to-dos yet",
539 RailPanel::Background => "nothing running in the background",
540 RailPanel::Terminal => "",
541 RailPanel::Files => "no files touched this session",
542 RailPanel::Notepad => "/note add <text> to keep a note",
543 RailPanel::Context => "context budget unknown",
544 // The Git view always paints its own state row ("reading git
545 // status…", "not a git repository", "git unavailable: …").
546 RailPanel::Git => "reading git status…",
547 RailPanel::Price => "no priced turns yet",
548 }
549 }
550
551 /// Active goal as the Top strip's only title. Uses the same
552 /// paused/active/terminal resolution as the ocean header chip so a goal set
553 /// via `create_goal` is either visible everywhere or nowhere. Returns
554 /// `None` when no live goal exists — Top then paints no title row at all.
555 pub(super) fn top_goal_title(app: &App) -> Option<(String, Style)> {
556 let (objective, paused) = crate::tui::footer_ui::active_goal_chip_state(app)?;
557 let flat = objective.trim().replace(['\n', '\r'], " ");
558 if flat.is_empty() {
559 return None;
560 }
561 let text = if paused {
562 format!("Goal (paused): {flat}")
563 } else {
564 format!("Goal: {flat}")
565 };
566 let style = if paused {
567 Style::default()
568 .fg(app.ui_theme.warning)
569 .add_modifier(Modifier::BOLD)
570 } else {
571 Style::default()
572 .fg(app.ui_theme.status_working)
573 .add_modifier(Modifier::BOLD)
574 };
575 Some((text, style))
576 }
577
578 fn todo_ordinals(rows: &[WorkRow]) -> HashMap<String, usize> {
579 rows.iter()
580 .filter(|row| row.id.0.starts_with("graph:"))
581 .enumerate()
582 .map(|(index, row)| (row.id.0.clone(), index.saturating_add(1)))
583 .collect()
584 }
585
586 /// Shared goal/receipt folding rule used by both height and body painting.
587 pub(super) fn progress_shares_goal_row(width: u16, has_goal_title: bool) -> bool {
588 codewhale_ratatui::WorkbarLayout::progress_shares_goal_row(width, has_goal_title)
589 }
590
591 pub(super) fn top_todo_progress(app: &App, rows: &[WorkRow]) -> Option<String> {
592 let todos = rows
593 .iter()
594 .filter(|row| row.id.0.starts_with("graph:"))
595 .collect::<Vec<_>>();
596 let total = todos.len();
597 if total == 0 {
598 return None;
599 }
600 let completed = todos
601 .iter()
602 .filter(|row| row.tone == WorkTone::Success)
603 .count();
604 let remaining = total.saturating_sub(completed);
605 let label = format!("{} ·", app.tr(MessageId::SidebarTodoLabel));
606 Some(
607 app.tr(MessageId::WorkSurfaceTodoProgress)
608 .replace("{label}", &label)
609 .replace("{completed}", &completed.to_string())
610 .replace("{total}", &total.to_string())
611 .replace("{remaining}", &remaining.to_string()),
612 )
613 }
614
615 const ASCII_BORDER: ratatui::symbols::border::Set<'static> = ratatui::symbols::border::Set {
616 top_left: "+",
617 top_right: "+",
618 bottom_left: "+",
619 bottom_right: "+",
620 vertical_left: "|",
621 vertical_right: "|",
622 horizontal_top: "-",
623 horizontal_bottom: "-",
624 };
625
626 fn render_frame(
627 frame: &mut Frame,
628 area: Rect,
629 placement: WorkSurfacePlacement,
630 ascii: bool,
631 app: &App,
632 ) -> Color {
633 let resize_active = app.work_surface.resizing || app.work_surface.divider_hovered;
634 let border_color = if resize_active || app.work_surface.focused {
635 app.ui_theme.accent_primary
636 } else {
637 app.ui_theme.border
638 };
639 let bg = app.ui_theme.composer_bg;
640 if area.width >= 4 && area.height >= 3 {
641 let mut block = Block::default()
642 .borders(Borders::ALL)
643 .border_type(BorderType::Rounded)
644 .border_style(Style::default().fg(border_color).bg(bg))
645 .style(Style::default().bg(bg));
646 if ascii {
647 block = block.border_set(ASCII_BORDER);
648 }
649 block.render(area, frame.buffer_mut());
650 if resize_active && !ascii {
651 let buf = frame.buffer_mut();
652 match placement {
653 WorkSurfacePlacement::Top => {
654 let y = area.bottom().saturating_sub(1);
655 for x in area.left().saturating_add(1)..area.right().saturating_sub(1) {
656 if let Some(cell) = buf.cell_mut((x, y)) {
657 cell.set_symbol("━").set_fg(border_color).set_bg(bg);
658 }
659 }
660 }
661 WorkSurfacePlacement::Bottom => {
662 let y = area.top();
663 for x in area.left().saturating_add(1)..area.right().saturating_sub(1) {
664 if let Some(cell) = buf.cell_mut((x, y)) {
665 cell.set_symbol("━").set_fg(border_color).set_bg(bg);
666 }
667 }
668 }
669 WorkSurfacePlacement::Left | WorkSurfacePlacement::Right => {
670 let x = if placement == WorkSurfacePlacement::Left {
671 area.right().saturating_sub(1)
672 } else {
673 area.left()
674 };
675 for y in area.top().saturating_add(1)..area.bottom().saturating_sub(1) {
676 if let Some(cell) = buf.cell_mut((x, y)) {
677 cell.set_symbol("┃").set_fg(border_color).set_bg(bg);
678 }
679 }
680 }
681 WorkSurfacePlacement::Off => {}
682 }
683 }
684 } else {
685 Block::default()
686 .style(Style::default().bg(bg))
687 .render(area, frame.buffer_mut());
688 }
689 border_color
690 }
691
692 fn light_workbar_edge(
693 area: Rect,
694 buf: &mut ratatui::buffer::Buffer,
695 dock_tabs: &[DockTabHitbox],
696 active_panel: RailPanel,
697 border: Color,
698 accent: Color,
699 ground: Color,
700 ) {
701 if area.width < 12
702 || area.height < 3
703 || !matches!(
704 (border, accent, ground),
705 (Color::Rgb(..), Color::Rgb(..), Color::Rgb(..))
706 )
707 || !buf
708 .cell((area.x, area.y))
709 .is_some_and(|cell| cell.symbol() == "╭")
710 {
711 return;
712 }
713 let shades = [0.85, 0.68, 0.48, 0.30, 0.16, 0.06].map(|strength| {
714 codewhale_ratatui::color::contrast_safe_oklab_mix(border, accent, ground, strength, 3.0)
715 });
716 let x = area.left();
717 let y = area.top();
718 for (dy, weight) in [(0, 1), (1, 3), (2, 5)] {
719 let Some(cell) = buf.cell_mut((x, y.saturating_add(dy))) else {
720 continue;
721 };
722 if matches!(cell.symbol(), "╭" | "│") && cell.fg == border {
723 cell.set_fg(shades[weight]);
724 }
725 }
726 let anchor = dock_tabs
727 .iter()
728 .find(|tab| tab.target == DockTabTarget::Panel(active_panel))
729 .map(|tab| tab.area.right())
730 .unwrap_or_else(|| x.saturating_add(1));
731 let reach = area.width.div_ceil(5).clamp(8, 22);
732 let last = anchor
733 .saturating_add(reach)
734 .min(area.right().saturating_sub(1));
735 for column in anchor..last {
736 let Some(cell) = buf.cell_mut((column, y)) else {
737 continue;
738 };
739 if cell.symbol() != "─" || cell.fg != border || !cell.modifier.is_empty() {
740 break;
741 }
742 let band = usize::from(column - anchor) * shades.len() / usize::from(reach);
743 cell.set_fg(shades[band]);
744 }
745 }
746
747 // Engine supplies the caller's available panels, exact close semantics and
748 // live theme. The kit owns the one fitted paint/hitbox plan.
749 fn kit_panel(panel: RailPanel) -> codewhale_ratatui::WorkbarPanel {
750 use codewhale_ratatui::WorkbarPanel as P;
751 match panel {
752 RailPanel::Tasks => P::Tasks,
753 RailPanel::Agents => P::Fleet,
754 RailPanel::Background => P::Jobs,
755 RailPanel::Terminal => P::Terminal,
756 RailPanel::Files => P::Files,
757 RailPanel::Notepad => P::Notes,
758 RailPanel::Context => P::Context,
759 RailPanel::Git => P::Git,
760 RailPanel::Price => P::Cost,
761 }
762 }
763
764 fn native_target(target: codewhale_ratatui::DockTabTarget) -> DockTabTarget {
765 use codewhale_ratatui::{DockTabTarget as T, WorkbarPanel as P};
766 match target {
767 T::Close => DockTabTarget::Close,
768 T::Panel(panel) => DockTabTarget::Panel(match panel {
769 P::Tasks => RailPanel::Tasks,
770 P::Fleet => RailPanel::Agents,
771 P::Jobs => RailPanel::Background,
772 P::Terminal => RailPanel::Terminal,
773 P::Files => RailPanel::Files,
774 P::Notes => RailPanel::Notepad,
775 P::Context => RailPanel::Context,
776 P::Git => RailPanel::Git,
777 P::Cost => RailPanel::Price,
778 }),
779 }
780 }
781
782 #[cfg(test)]
783 fn render_dock_tabs(frame: &mut Frame, area: Rect, app: &mut App) {
784 render_dock_tabs_with_ascii(
785 frame,
786 area,
787 app,
788 crate::tui::color_compat::ascii_safe_enabled(),
789 );
790 }
791
792 fn render_dock_tabs_with_ascii(frame: &mut Frame, area: Rect, app: &mut App, ascii: bool) {
793 use codewhale_ratatui::{DockTabRow, DockTabStyles, DockTabTarget as T, WorkbarTab};
794 let entries = RailPanel::ORDER
795 .into_iter()
796 .filter_map(|panel| {
797 let count = dock_tab_count(app, panel);
798 let useful = count.is_some_and(|count| count > 0)
799 || super::views::view_always_has_content(panel);
800 (useful || panel == app.work_surface.panel).then_some(WorkbarTab {
801 panel: kit_panel(panel),
802 count,
803 })
804 })
805 .collect::<Vec<_>>();
806 let close_mark = if ascii { "x" } else { "×" };
807 // Name Esc only while Engine's actual keyboard action closes this dock.
808 let esc_closes = app.work_surface.panel != RailPanel::Terminal
809 && app.work_surface.focused
810 && !super::interaction::opened_detail_on_screen(app)
811 && (app.work_surface.explicit_view || !visible_rows_for_panel(app).is_empty());
812 let close = if esc_closes && area.width >= 60 {
813 format!(" Esc {close_mark} ")
814 } else {
815 format!(" {close_mark} ")
816 };
817 let active_fg = codewhale_palette::enforce_contrast(
818 app.ui_theme.accent_primary,
819 app.ui_theme.composer_bg,
820 4.5,
821 );
822 let row = DockTabRow {
823 tabs: &entries,
824 active: kit_panel(app.work_surface.panel),
825 bottom: false,
826 close: close.into(),
827 hovered: app.work_surface.hovered_tab.map(|target| match target {
828 DockTabTarget::Panel(panel) => T::Panel(kit_panel(panel)),
829 DockTabTarget::Close => T::Close,
830 }),
831 pressed: app
832 .work_surface
833 .pressed_tab
834 .and_then(|target| match target {
835 DockTabTarget::Panel(panel) => Some(kit_panel(panel)),
836 DockTabTarget::Close => None,
837 }),
838 styles: DockTabStyles {
839 idle: chrome_style(&app.ui_theme, ChromeInk::Metadata).bg(app.ui_theme.composer_bg),
840 active: Style::default()
841 .fg(active_fg)
842 .bg(app.ui_theme.composer_bg)
843 .add_modifier(Modifier::BOLD),
844 hovered: Style::default()
845 .fg(app.ui_theme.text_body)
846 .bg(app.ui_theme.elevated_bg)
847 .add_modifier(Modifier::UNDERLINED),
848 close: chrome_style(&app.ui_theme, ChromeInk::MetadataHint)
849 .bg(app.ui_theme.composer_bg),
850 close_hovered: chrome_style(&app.ui_theme, ChromeInk::Info)
851 .bg(app.ui_theme.elevated_bg)
852 .add_modifier(Modifier::UNDERLINED),
853 },
854 };
855 let plan = row.plan(area);
856 plan.paint(frame.buffer_mut());
857 app.work_surface.dock_tabs = plan
858 .hitboxes()
859 .into_iter()
860 .map(|(target, area)| DockTabHitbox {
861 target: native_target(target),
862 area,
863 })
864 .collect();
865 }
866
867 /// The badge on a view's tab: how many rows of *work* it holds. `None` for
868 /// the fact views (context, git, price), which never badge.
869 fn dock_tab_count(app: &mut App, panel: RailPanel) -> Option<usize> {
870 match panel {
871 RailPanel::Agents => Some(
872 visible_rows_for(app, panel)
873 .iter()
874 .filter(|row| row.id.0.starts_with("worker:"))
875 .count(),
876 ),
877 RailPanel::Tasks => Some(
878 visible_rows_for(app, panel)
879 .iter()
880 .filter(|row| row.id.0.starts_with("graph:"))
881 .count(),
882 ),
883 // Group headings (`▾ Shells N`) are selectable doors, not jobs.
884 RailPanel::Background => Some(
885 visible_rows_for(app, panel)
886 .iter()
887 .filter(|row| row.selectable && !row.id.0.starts_with("section:"))
888 .count(),
889 ),
890 RailPanel::Files => Some(super::views::files_touched_count(app)),
891 RailPanel::Notepad => Some(usize::from(super::views::notepad_has_text(app))),
892 RailPanel::Terminal => None,
893 RailPanel::Context | RailPanel::Git | RailPanel::Price => None,
894 }
895 }
896
897 fn register_dock_targets(app: &mut App) {
898 let targets = app.work_surface.dock_tabs.clone();
899 for hitbox in targets {
900 let (id, action) = match hitbox.target {
901 DockTabTarget::Panel(panel) => {
902 use crate::tui::tideline::InteractionTargetId as Id;
903 let id = match panel {
904 RailPanel::Agents => Id::DOCK_TAB_AGENTS,
905 RailPanel::Tasks => Id::DOCK_TAB_TASKS,
906 RailPanel::Background => Id::DOCK_TAB_BACKGROUND,
907 RailPanel::Terminal => Id::DOCK_TAB_TERMINAL,
908 RailPanel::Files => Id::DOCK_TAB_FILES,
909 RailPanel::Notepad => Id::DOCK_TAB_NOTEPAD,
910 RailPanel::Context => Id::DOCK_TAB_CONTEXT,
911 RailPanel::Git => Id::DOCK_TAB_GIT,
912 RailPanel::Price => Id::DOCK_TAB_PRICE,
913 };
914 (
915 id,
916 crate::tui::tideline::InteractionAction::ShowDockPanel(panel),
917 )
918 }
919 DockTabTarget::Close => (
920 crate::tui::tideline::InteractionTargetId::DOCK_CLOSE,
921 crate::tui::tideline::InteractionAction::DismissDock,
922 ),
923 };
924 app.viewport
925 .interaction_targets
926 .register(crate::tui::tideline::InteractionTarget {
927 id,
928 area: hitbox.area,
929 focus: crate::tui::tideline::InteractionFocus::Direct,
930 keyboard_action: Some(action),
931 mouse_action: Some(action),
932 inspect_detail: crate::tui::tideline::InspectDetail::Route,
933 });
934 }
935 }
936
937 fn render_scrollbar(
938 frame: &mut Frame,
939 area: Rect,
940 visible: usize,
941 total: usize,
942 track_color: Color,
943 ascii: bool,
944 app: &App,
945 ) {
946 let (thumb, track) = if ascii { ("#", "|") } else { ("┃", "│") };
947 codewhale_ratatui::WorkbarScrollbar {
948 offset: app.work_surface.scroll_offset,
949 visible,
950 total,
951 thumb,
952 track,
953 thumb_style: Style::default()
954 .fg(app.ui_theme.status_working)
955 .bg(app.ui_theme.composer_bg),
956 track_style: Style::default()
957 .fg(track_color)
958 .bg(app.ui_theme.composer_bg),
959 }
960 .paint(area, frame.buffer_mut());
961 }
962
962 lines RUST