#[path = "app_boot.rs"]
mod boot;
#[path = "app_run.rs"]
mod run;
use crate::config::{Config, Recipe, ScriptCommand, model::UiPane};
use crate::container::Backend;
use crate::container::devcontainer::DevcontainerBackend;
use crate::runtime::Executor;
use crate::tui::dialogs::Modal;
use crate::tui::dialogs::args_prompt::ArgsPrompt;
use crate::tui::dialogs::confirm::{ConfirmAction, ConfirmDialog};
use crate::tui::dialogs::switcher::{
NewFormField, NewWorktreeForm, SwitcherConfirm, WorktreeRow, WorktreeSwitcher,
};
use crate::tui::editor::ResolvedEditor;
use crate::tui::palette::Palette;
use crate::tui::runner::RunState;
use crate::tui::services::ServicePane;
use crate::tui::views::control_center::state::{Item, ItemKind};
use crate::tui::views::diff::state::{BodyMode, DiffFile, DiffLine, DiffView, ReadLine};
use crate::tui::views::terminals::state::{TerminalsRow, TerminalsView, TmuxWindow};
use crate::tui::watchers::{WatcherError, WatcherPane};
use ratatui::layout::Rect;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
ControlCenter,
Terminals,
Diff,
}
impl View {
pub fn tag(self) -> &'static str {
match self {
View::ControlCenter => "control",
View::Terminals => "terminals",
View::Diff => "diff",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClickTarget {
SidebarItem(usize),
TerminalsRow(usize),
DiffFile(usize),
PaletteRow(usize),
SwitcherRow(usize),
}
#[derive(Debug, Clone)]
pub enum LaunchRejection {
NoExecutor,
AlreadyRunning,
NotRunnable(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Normal,
Palette,
Confirm,
ArgsPrompt,
WorktreeSwitcher,
}
pub type RunKey = (ItemKind, String);
fn shell_escape(s: String) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('\'');
for c in s.chars() {
if c == '\'' {
out.push_str(r"'\''");
} else {
out.push(c);
}
}
out.push('\'');
out
}
#[derive(Debug, Clone)]
pub struct AttachRequest {
pub session: String,
pub window: String,
pub create_with: Option<String>,
pub ensure: Option<EnsureDevcontainer>,
pub window_name: Option<String>,
pub window_options: Vec<(String, String)>,
}
#[derive(Clone)]
pub struct EnsureDevcontainer {
pub backend: Arc<DevcontainerBackend>,
}
impl std::fmt::Debug for EnsureDevcontainer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EnsureDevcontainer")
.field("container", &self.backend.container_name())
.finish()
}
}
#[derive(Debug, Clone)]
pub struct KillWindow {
pub session: String,
pub index: u32,
}
#[derive(Debug)]
pub enum Command {
SwitchWorktree(PathBuf),
AttachTmux(AttachRequest),
KillTmuxWindow(KillWindow),
OpenLazygit,
OpenEditor { target: PathBuf },
EmitBell,
}
#[derive(Debug)]
pub enum Message {
TmuxProbeResult(bool),
DiffReloaded(DiffPreload),
DiffFileLoaded { path: String, lines: Vec<DiffLine> },
ReadFileLoaded { path: String, lines: Vec<ReadLine> },
}
#[derive(Debug)]
pub struct DiffPreload {
pub trunk: Option<String>,
pub anchor: Option<String>,
pub anchor_short: Option<String>,
pub branch: Option<String>,
pub lazygit_available: bool,
pub files: Result<Vec<DiffFile>, String>,
}
pub struct WatcherSpawnResult {
pub name: String,
pub pane: Result<WatcherPane, WatcherError>,
}
#[derive(Default)]
pub struct BootChannels {
pub discover_rx: Option<oneshot::Receiver<Vec<String>>>,
pub diff_rx: Option<oneshot::Receiver<DiffPreload>>,
pub watcher_rx: Option<mpsc::UnboundedReceiver<WatcherSpawnResult>>,
}
pub struct App {
config: Arc<Config>,
items: Vec<Item>,
selected: usize,
quit: bool,
executor: Option<Executor>,
backend: Option<Arc<dyn Backend>>,
devcontainer: Option<Arc<DevcontainerBackend>>,
runs: BTreeMap<RunKey, RunState>,
lifecycle_run: Option<RunState>,
services: BTreeMap<String, ServicePane>,
watchers: BTreeMap<String, WatcherPane>,
pub(crate) flash_message: Option<String>,
modal: Option<Modal>,
commands: Vec<Command>,
message_tx: mpsc::UnboundedSender<Message>,
message_rx: mpsc::UnboundedReceiver<Message>,
project_root: PathBuf,
branch: Option<String>,
view: View,
terminals: TerminalsView,
diff: DiffView,
diagnostics: Vec<String>,
boot: BootChannels,
worker: Option<crate::tui::worker::WorkerHandle>,
pub sidebar_item_rects: std::cell::RefCell<Vec<Rect>>,
pub confirm_yes_rect: std::cell::Cell<Option<Rect>>,
pub confirm_no_rect: std::cell::Cell<Option<Rect>>,
pub last_click: Option<(std::time::Instant, ClickTarget)>,
editor: ResolvedEditor,
}
pub const DOUBLE_CLICK_WINDOW: Duration = Duration::from_millis(400);
impl App {
pub fn new(config: Arc<Config>) -> Self {
let items = build_items(&config);
let services = collect_service_panes(&config);
let terminals = TerminalsView::default_for(&config);
let (message_tx, message_rx) = mpsc::unbounded_channel();
Self {
config,
items,
selected: 0,
quit: false,
executor: None,
backend: None,
devcontainer: None,
runs: BTreeMap::new(),
lifecycle_run: None,
services,
watchers: BTreeMap::new(),
flash_message: None,
modal: None,
commands: Vec::new(),
message_tx,
message_rx,
project_root: PathBuf::from("."),
branch: None,
view: View::ControlCenter,
terminals,
diff: DiffView::default(),
diagnostics: Vec::new(),
boot: BootChannels::default(),
worker: None,
sidebar_item_rects: std::cell::RefCell::new(Vec::new()),
confirm_yes_rect: std::cell::Cell::new(None),
confirm_no_rect: std::cell::Cell::new(None),
last_click: None,
editor: ResolvedEditor {
argv: vec!["vim".to_owned()],
mode: crate::tui::editor::LaunchMode::Terminal,
opens_directory: true,
},
}
}
pub fn view(&self) -> View {
self.view
}
pub fn switch_view(&mut self, view: View) {
self.view = view;
}
pub fn with_project_root(mut self, project_root: &Path) -> Self {
self.project_root = project_root.to_path_buf();
self
}
pub fn project_root(&self) -> &Path {
&self.project_root
}
pub fn with_branch(mut self, branch: Option<String>) -> Self {
self.branch = branch;
self
}
pub fn branch(&self) -> Option<&str> {
self.branch.as_deref()
}
pub fn with_executor(mut self, executor: Executor) -> Self {
self.executor = Some(executor);
self
}
pub fn with_backend(mut self, backend: Arc<dyn Backend>) -> Self {
self.backend = Some(backend);
self
}
pub fn backend(&self) -> Option<&Arc<dyn Backend>> {
self.backend.as_ref()
}
pub fn with_devcontainer(mut self, devcontainer: Arc<DevcontainerBackend>) -> Self {
self.devcontainer = Some(devcontainer);
self
}
pub fn devcontainer(&self) -> Option<&Arc<DevcontainerBackend>> {
self.devcontainer.as_ref()
}
pub fn services(&self) -> &BTreeMap<String, ServicePane> {
&self.services
}
pub fn services_mut(&mut self) -> &mut BTreeMap<String, ServicePane> {
&mut self.services
}
pub fn selected_service(&self) -> Option<&ServicePane> {
let item = self.selected_item()?;
if item.kind != ItemKind::Service {
return None;
}
self.services.get(&item.name)
}
pub fn watchers(&self) -> &BTreeMap<String, WatcherPane> {
&self.watchers
}
pub fn selected_watcher(&self) -> Option<&WatcherPane> {
let item = self.selected_item()?;
if item.kind != ItemKind::Watcher {
return None;
}
self.watchers.get(&item.name)
}
pub fn items(&self) -> &[Item] {
&self.items
}
pub fn selected_index(&self) -> usize {
self.selected
}
pub fn selected_item(&self) -> Option<&Item> {
self.items.get(self.selected)
}
pub fn config(&self) -> &Config {
&self.config
}
pub fn should_quit(&self) -> bool {
self.quit
}
pub fn quit(&mut self) {
self.quit = true;
}
pub fn select_next(&mut self) {
if self.items.is_empty() {
return;
}
self.selected = (self.selected + 1).min(self.items.len() - 1);
}
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
pub fn select_first(&mut self) {
self.selected = 0;
}
pub fn select_last(&mut self) {
if !self.items.is_empty() {
self.selected = self.items.len() - 1;
}
}
pub fn select_at(&mut self, idx: usize) {
if self.items.is_empty() {
return;
}
self.selected = idx.min(self.items.len() - 1);
}
pub fn selected_recipe(&self) -> Option<&Recipe> {
let item = self.selected_item()?;
if item.kind != ItemKind::Recipe {
return None;
}
self.config.commands.get(&item.name)
}
pub fn selected_script(&self) -> Option<&ScriptCommand> {
let item = self.selected_item()?;
if item.kind != ItemKind::Script {
return None;
}
self.config.scripts.get(&item.name)
}
pub fn run_for(&self, kind: ItemKind, name: &str) -> Option<&RunState> {
self.runs.get(&(kind, name.to_string()))
}
pub fn selected_run(&self) -> Option<&RunState> {
let item = self.selected_item()?;
self.run_for(item.kind, &item.name)
}
pub fn lifecycle_run(&self) -> Option<&RunState> {
self.lifecycle_run.as_ref()
}
pub fn mode(&self) -> Mode {
match &self.modal {
None => Mode::Normal,
Some(Modal::Palette(_)) => Mode::Palette,
Some(Modal::Confirm(_)) => Mode::Confirm,
Some(Modal::ArgsPrompt(_)) => Mode::ArgsPrompt,
Some(Modal::Switcher(_)) => Mode::WorktreeSwitcher,
}
}
pub fn palette(&self) -> Option<&Palette> {
match &self.modal {
Some(Modal::Palette(p)) => Some(p),
_ => None,
}
}
pub fn open_palette(&mut self) {
self.modal = Some(Modal::Palette(Palette::new(&self.items)));
}
pub fn close_palette(&mut self) {
self.modal = None;
}
pub fn palette_mut(&mut self) -> Option<&mut Palette> {
match &mut self.modal {
Some(Modal::Palette(p)) => Some(p),
_ => None,
}
}
pub fn confirm_palette(&mut self) -> Option<Result<(), LaunchRejection>> {
let palette = self.palette()?;
let m = palette.selected_match()?;
let args = palette.parsed_args();
let item_idx = m.item_index;
self.close_palette();
self.selected = item_idx;
let item = self.items.get(item_idx).cloned()?;
if matches!(item.kind, ItemKind::Service | ItemKind::Watcher) {
let kind = match item.kind {
ItemKind::Service => "service",
ItemKind::Watcher => "watcher",
_ => unreachable!(),
};
return Some(Err(LaunchRejection::NotRunnable(format!(
"{kind} `{}` can't be launched from the palette",
item.name
))));
}
Some(self.try_launch_selected_with_args(args))
}
pub fn open_kill_restart_confirm(&mut self) {
let Some(item) = self.selected_item().cloned() else {
return;
};
let key: RunKey = (item.kind, item.name.clone());
if self.runs.get(&key).is_none_or(|r| r.is_done()) {
return;
}
self.modal = Some(Modal::Confirm(ConfirmDialog {
title: format!("`{}` is running", item.name),
body: "Kill and restart?".into(),
yes_focused: true,
action: ConfirmAction::KillAndRestart { key },
}));
}
pub fn confirm_dialog(&self) -> Option<&ConfirmDialog> {
match &self.modal {
Some(Modal::Confirm(d)) => Some(d),
_ => None,
}
}
pub fn confirm_dialog_mut(&mut self) -> Option<&mut ConfirmDialog> {
match &mut self.modal {
Some(Modal::Confirm(d)) => Some(d),
_ => None,
}
}
pub fn confirm_toggle_focus(&mut self) {
if let Some(c) = self.confirm_dialog_mut() {
c.yes_focused = !c.yes_focused;
}
}
pub fn selected_accepts_args(&self) -> bool {
let Some(item) = self.selected_item() else {
return false;
};
match item.kind {
ItemKind::Recipe => self
.config
.commands
.get(&item.name)
.is_some_and(|r| r.forward_args),
ItemKind::Script => self
.config
.scripts
.get(&item.name)
.is_some_and(|s| s.forward_args),
_ => false,
}
}
pub fn open_args_prompt(&mut self) {
let Some(item) = self.selected_item().cloned() else {
return;
};
if !self.selected_accepts_args() {
return;
}
self.modal = Some(Modal::ArgsPrompt(ArgsPrompt {
item_name: item.name,
kind: item.kind,
input: String::new(),
}));
}
pub fn args_prompt(&self) -> Option<&ArgsPrompt> {
match &self.modal {
Some(Modal::ArgsPrompt(p)) => Some(p),
_ => None,
}
}
fn args_prompt_mut(&mut self) -> Option<&mut ArgsPrompt> {
match &mut self.modal {
Some(Modal::ArgsPrompt(p)) => Some(p),
_ => None,
}
}
pub fn args_prompt_push_char(&mut self, c: char) {
if let Some(p) = self.args_prompt_mut() {
p.input.push(c);
}
}
pub fn args_prompt_pop_char(&mut self) {
if let Some(p) = self.args_prompt_mut() {
p.input.pop();
}
}
pub fn args_prompt_resolve(&mut self, accept: bool) -> Option<Result<(), LaunchRejection>> {
let prompt = match self.modal.take() {
Some(Modal::ArgsPrompt(p)) => p,
other => {
self.modal = other;
return None;
}
};
if !accept {
return None;
}
let args = if prompt.input.trim().is_empty() {
Vec::new()
} else {
shell_words::split(&prompt.input).unwrap_or_default()
};
if let Some(idx) = self
.items
.iter()
.position(|i| i.kind == prompt.kind && i.name == prompt.item_name)
{
self.selected = idx;
}
Some(self.try_launch_selected_with_args(args))
}
pub fn open_worktree_switcher(&mut self, entries: Vec<WorktreeRow>) {
let selected = entries.iter().position(|e| e.is_current).unwrap_or(0);
self.modal = Some(Modal::Switcher(WorktreeSwitcher {
entries,
selected,
creating: None,
row_rects: std::cell::RefCell::new(Vec::new()),
}));
}
pub fn switcher(&self) -> Option<&WorktreeSwitcher> {
match &self.modal {
Some(Modal::Switcher(s)) => Some(s),
_ => None,
}
}
pub fn switcher_mut(&mut self) -> Option<&mut WorktreeSwitcher> {
match &mut self.modal {
Some(Modal::Switcher(s)) => Some(s),
_ => None,
}
}
pub fn close_switcher(&mut self) {
self.modal = None;
}
pub fn switcher_confirm(&mut self) -> SwitcherConfirm {
let Some(s) = self.switcher() else {
return SwitcherConfirm::NoOp;
};
if s.selected == s.new_row_index() {
return SwitcherConfirm::OpenCreateForm;
}
let row = s.entries[s.selected].clone();
if !row.is_current {
self.queue(Command::SwitchWorktree(row.path));
}
self.close_switcher();
SwitcherConfirm::Switched
}
pub fn open_create_form(
&mut self,
branches: Vec<crate::runtime::BranchEntry>,
parent_override: Option<std::path::PathBuf>,
) {
let parent = parent_override.unwrap_or_else(|| match self.project_root.parent() {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ => self.project_root.clone(),
});
let Some(s) = self.switcher_mut() else {
return;
};
let filtered: Vec<usize> = (0..branches.len()).collect();
let form = NewWorktreeForm {
branch_input: String::new(),
path_input: String::new(),
path_dirty: false,
parent,
branches,
filtered,
selected: 0,
focus: NewFormField::Branch,
error: None,
};
s.creating = Some(form);
}
pub fn switcher_form_mut(&mut self) -> Option<&mut NewWorktreeForm> {
self.switcher_mut().and_then(|s| s.creating.as_mut())
}
pub fn switcher_form(&self) -> Option<&NewWorktreeForm> {
self.switcher().and_then(|s| s.creating.as_ref())
}
pub fn switcher_form_cancel(&mut self) {
if let Some(s) = self.switcher_mut() {
s.creating = None;
}
}
pub fn switcher_form_snapshot(&self) -> Option<NewWorktreeForm> {
self.switcher_form().cloned()
}
pub fn switcher_form_finish(&mut self, result: Result<PathBuf, String>) {
match result {
Ok(path) => {
self.queue(Command::SwitchWorktree(path));
self.close_switcher();
}
Err(msg) => {
if let Some(form) = self.switcher_mut().and_then(|s| s.creating.as_mut()) {
form.error = Some(msg);
}
}
}
}
pub fn terminals(&self) -> &TerminalsView {
&self.terminals
}
pub fn terminals_mut(&mut self) -> &mut TerminalsView {
&mut self.terminals
}
pub fn terminals_rows(&self) -> Vec<TerminalsRow> {
let mut rows = Vec::new();
for name in self.services.keys() {
rows.push(TerminalsRow::Service(name.clone()));
}
for w in &self.terminals.windows {
if w.name.starts_with("svc:") {
continue;
}
rows.push(TerminalsRow::Window(w.clone()));
}
rows.push(TerminalsRow::NewSentinel);
rows
}
pub fn terminals_set_windows(&mut self, windows: Vec<TmuxWindow>) {
let non_service_windows = windows
.iter()
.filter(|w| !w.name.starts_with("svc:"))
.count();
let total_after = self.services.len() + non_service_windows + 1;
self.terminals.set_windows(windows, total_after);
if self.terminals.take_pending_bell() {
self.queue(Command::EmitBell);
}
}
pub fn discard_pending_tmux_snapshots(&mut self) {
let Some(w) = self.worker.as_mut() else {
return;
};
loop {
match w.snap_rx.try_recv() {
Ok(crate::tui::worker::WorkerSnapshot::TmuxWindows(_)) => continue,
Ok(crate::tui::worker::WorkerSnapshot::ServiceStatus { name, status }) => {
if let Some(pane) = self.services.get_mut(&name) {
pane.status = Some(status);
}
}
Err(mpsc::error::TryRecvError::Empty) => break,
Err(mpsc::error::TryRecvError::Disconnected) => {
self.worker = None;
break;
}
}
}
}
pub fn terminals_select_next(&mut self) {
let total = self.terminals_rows().len();
self.terminals.select_next(total);
}
pub fn terminals_select_at(&mut self, idx: usize) {
let total = self.terminals_rows().len();
self.terminals.select_at(idx, total);
}
pub fn terminals_confirm(&mut self) {
let rows = self.terminals_rows();
let Some(row) = rows.get(self.terminals.selected).cloned() else {
return;
};
match row {
TerminalsRow::Service(name) => {
if let Err(msg) = self.queue_service_attach(&name) {
self.flash(msg);
}
}
TerminalsRow::Window(window) => {
let session = self.terminals.session_name.clone();
self.queue(Command::AttachTmux(AttachRequest {
session,
window: window.index.to_string(),
create_with: None,
ensure: None,
window_name: None,
window_options: Vec::new(),
}));
}
TerminalsRow::NewSentinel => {
self.queue_new_shell();
}
}
}
pub fn queue_new_shell(&mut self) {
let session = self.terminals.session_name.clone();
let (create_with, ensure, window_name, window_options) =
if let Some(dc) = &self.devcontainer {
let workspace = dc.workspace_folder().to_string();
let cmd = format!(
"docker exec -it {name} sh -c 'cd {cwd} && exec ${{SHELL:-/bin/sh}}'",
name = dc.container_name(),
cwd = shell_escape(workspace.clone()),
);
(
Some(cmd),
Some(EnsureDevcontainer {
backend: Arc::clone(dc),
}),
Some("dc".to_string()),
vec![("@croft_workspace".to_string(), workspace)],
)
} else {
let cmd = format!(
"cd {} && exec ${{SHELL:-/bin/sh}}",
shell_escape(self.project_root.display().to_string())
);
(Some(cmd), None, None, Vec::new())
};
self.queue(Command::AttachTmux(AttachRequest {
session,
window: "croft-new".to_string(),
create_with,
ensure,
window_name,
window_options,
}));
}
pub fn terminals_kill_selected(&mut self) {
let rows = self.terminals_rows();
let Some(row) = rows.get(self.terminals.selected) else {
return;
};
let TerminalsRow::Window(window) = row else {
return;
};
let session = self.terminals.session_name.clone();
let name = window.name.clone();
let index = window.index;
self.modal = Some(Modal::Confirm(ConfirmDialog {
title: format!("close `{name}`?"),
body: "the tmux window and any running processes will end.".into(),
yes_focused: true,
action: ConfirmAction::KillTmuxWindow {
session,
index,
name,
},
}));
}
pub fn queue_service_attach(&mut self, service: &str) -> Result<(), String> {
if self
.config
.services
.systemd
.iter()
.any(|s| s.name == service)
{
return Err(format!(
"`{service}` is a systemd unit — no interactive shell to attach to"
));
}
if self
.config
.services
.custom
.iter()
.any(|s| s.name == service)
{
return Err(format!(
"`{service}` is a custom service — create a custom terminal instead"
));
}
let session = self.terminals.session_name.clone();
let window = format!("svc:{service}");
let create_with = Some(format!(
"docker compose exec -it {service} sh -c 'exec ${{SHELL:-/bin/sh}}'"
));
self.queue(Command::AttachTmux(AttachRequest {
session,
window,
create_with,
ensure: None,
window_name: None,
window_options: Vec::new(),
}));
self.view = View::Terminals;
Ok(())
}
pub fn diagnostic(&mut self, msg: impl Into<String>) {
self.diagnostics.push(msg.into());
}
pub fn drain_diagnostics(&mut self) -> Vec<String> {
std::mem::take(&mut self.diagnostics)
}
pub fn queue(&mut self, cmd: Command) {
self.commands.push(cmd);
}
pub fn drain_commands(&mut self) -> Vec<Command> {
std::mem::take(&mut self.commands)
}
pub fn message_tx(&self) -> mpsc::UnboundedSender<Message> {
self.message_tx.clone()
}
pub fn drain_messages(&mut self) {
while let Ok(msg) = self.message_rx.try_recv() {
self.apply_message(msg);
}
}
fn apply_message(&mut self, msg: Message) {
match msg {
Message::TmuxProbeResult(ok) => {
self.terminals.set_tmux_available(ok);
}
Message::DiffReloaded(preload) => {
self.apply_diff_preload(preload);
self.request_diff_for_selected();
}
Message::DiffFileLoaded { path, lines } => {
self.diff.set_cache(path, lines);
if self.diff.body_mode == BodyMode::Read {
self.request_read_for_selected();
}
}
Message::ReadFileLoaded { path, lines } => {
let annotated = match self.diff.cache_for(&path) {
Some(diff_lines) => {
crate::tui::views::diff::git::annotate_read_with_diff(lines, diff_lines)
}
None => lines,
};
self.diff.set_read_cache(path, annotated);
}
}
}
pub fn request_tmux_probe(&self) {
if self.terminals.tmux_available.is_some() {
return;
}
let tx = self.message_tx();
tokio::spawn(async move {
let ok = tokio::process::Command::new("tmux")
.arg("-V")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.stdin(std::process::Stdio::null())
.status()
.await
.map(|s| s.success())
.unwrap_or(false);
let _ = tx.send(Message::TmuxProbeResult(ok));
});
}
pub fn request_diff_reload(&self) {
let tx = self.message_tx();
let project_root = self.project_root.clone();
let configured_base = self.config.diff.base.clone();
let lazygit_available = self.diff.lazygit_available;
tokio::spawn(async move {
let trunk =
crate::runtime::detect_trunk(&project_root, configured_base.as_deref()).await;
let anchor = match trunk.as_deref() {
Some(t) => crate::runtime::merge_base(&project_root, t).await,
None => None,
};
let branch = crate::tui::views::diff::git::current_branch(&project_root).await;
let anchor_short = anchor
.as_deref()
.map(|sha| sha.chars().take(7).collect::<String>());
let files =
crate::tui::views::diff::git::load_diff_files(&project_root, anchor.as_deref())
.await;
let _ = tx.send(Message::DiffReloaded(DiffPreload {
trunk,
anchor,
anchor_short,
branch,
lazygit_available,
files,
}));
});
}
pub fn request_diff_for_selected(&self) {
let Some(file) = self.diff.selected_file().cloned() else {
return;
};
if self.diff.cache_for(&file.path).is_some() {
return;
}
let tx = self.message_tx();
let project_root = self.project_root.clone();
let anchor = self.diff.anchor.clone();
tokio::spawn(async move {
let lines = crate::tui::views::diff::git::load_diff_for_file(
&project_root,
&file,
anchor.as_deref(),
)
.await;
let _ = tx.send(Message::DiffFileLoaded {
path: file.path,
lines,
});
});
}
pub fn request_read_for_selected(&self) {
let Some(file) = self.diff.selected_file().cloned() else {
return;
};
if self.diff.read_cache_for(&file.path).is_some() {
return;
}
if self.diff.cache_for(&file.path).is_none() {
self.request_diff_for_selected();
}
let tx = self.message_tx();
let project_root = self.project_root.clone();
let anchor = self.diff.anchor.clone();
tokio::spawn(async move {
let lines = crate::tui::views::diff::git::load_read_for_file(
&project_root,
&file,
anchor.as_deref(),
)
.await;
let _ = tx.send(Message::ReadFileLoaded {
path: file.path,
lines,
});
});
}
pub fn flash(&mut self, msg: impl Into<String>) {
self.flash_message = Some(msg.into());
}
pub fn clear_flash(&mut self) {
self.flash_message = None;
}
pub fn flash_message(&self) -> Option<&str> {
self.flash_message.as_deref()
}
pub fn diff(&self) -> &DiffView {
&self.diff
}
pub fn diff_mut(&mut self) -> &mut DiffView {
&mut self.diff
}
pub fn request_lazygit(&mut self) {
self.queue(Command::OpenLazygit);
}
pub fn request_open_in_editor(&mut self, target: PathBuf) {
self.queue(Command::OpenEditor { target });
}
pub fn request_open_worktree_in_editor(&mut self) {
let root = self.project_root.clone();
self.request_open_in_editor(root);
}
pub fn with_editor(mut self, editor: ResolvedEditor) -> Self {
self.editor = editor;
self
}
pub fn editor(&self) -> &ResolvedEditor {
&self.editor
}
pub fn confirm_resolve(&mut self, accept: bool) -> Option<LaunchRejection> {
let d = match self.modal.take() {
Some(Modal::Confirm(d)) => d,
other => {
self.modal = other;
return None;
}
};
self.confirm_yes_rect.set(None);
self.confirm_no_rect.set(None);
if !accept {
return None;
}
match d.action {
ConfirmAction::KillAndRestart { key } => {
if let Some(idx) = self
.items
.iter()
.position(|i| i.kind == key.0 && i.name == key.1)
{
self.selected = idx;
}
self.force_relaunch_selected().err()
}
ConfirmAction::KillTmuxWindow { session, index, .. } => {
self.queue(Command::KillTmuxWindow(KillWindow { session, index }));
None
}
}
}
pub fn tick_watchers(&mut self) {
let Some(executor) = self.executor.clone() else {
return;
};
for pane in self.watchers.values_mut() {
pane.tick(&executor);
}
}
}
fn unique_watcher_name(base: &str, idx: usize, existing: &BTreeMap<String, WatcherPane>) -> String {
let primary = format!("watch:{base}");
if !existing.contains_key(&primary) {
return primary;
}
format!("watch:{base}:{idx}")
}
fn build_items(config: &Config) -> Vec<Item> {
build_items_from(config, &collect_service_panes(config), &BTreeMap::new())
}
fn runtime_row_label(config: &Config) -> Option<&'static str> {
use crate::config::model::Backend as B;
match config.runtime.backend {
B::None => None,
B::Compose => Some("compose"),
B::Docker => Some("docker"),
B::Podman => Some("podman"),
}
}
fn build_items_from(
config: &Config,
services: &BTreeMap<String, ServicePane>,
watchers: &BTreeMap<String, WatcherPane>,
) -> Vec<Item> {
let mut items = Vec::new();
if let Some(name) = runtime_row_label(config) {
items.push(Item {
name: name.to_string(),
kind: ItemKind::Runtime,
});
}
let mut emitted_services: std::collections::BTreeSet<&str> = Default::default();
for pane in &config.ui.panes {
if let UiPane::Service { service, .. } = pane
&& services.contains_key(service)
&& emitted_services.insert(service.as_str())
{
items.push(Item {
name: service.clone(),
kind: ItemKind::Service,
});
}
}
for name in services.keys() {
if emitted_services.insert(name.as_str()) {
items.push(Item {
name: name.clone(),
kind: ItemKind::Service,
});
}
}
for name in watchers.keys() {
items.push(Item {
name: name.clone(),
kind: ItemKind::Watcher,
});
}
items.extend(config.commands.keys().map(|name| Item {
name: name.clone(),
kind: ItemKind::Recipe,
}));
items.extend(config.scripts.keys().map(|name| Item {
name: name.clone(),
kind: ItemKind::Script,
}));
items
}
fn collect_service_panes(config: &Config) -> BTreeMap<String, ServicePane> {
let mut out = BTreeMap::new();
for pane in &config.ui.panes {
if let UiPane::Service { service, .. } = pane {
out.entry(service.clone())
.or_insert_with(|| ServicePane::new(service.clone()));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::views::diff::state::{
BodyMode, DiffFocus, DiffLine, DiffLineKind, DiffStatus, ReadLine, ReadLineKind,
};
use pretty_assertions::assert_eq;
fn drained_attach(app: &mut App) -> Option<AttachRequest> {
app.drain_commands().into_iter().find_map(|c| match c {
Command::AttachTmux(r) => Some(r),
_ => None,
})
}
fn drained_switch(app: &mut App) -> Option<PathBuf> {
app.drain_commands().into_iter().find_map(|c| match c {
Command::SwitchWorktree(p) => Some(p),
_ => None,
})
}
fn drained_kill_window(app: &mut App) -> Option<KillWindow> {
app.drain_commands().into_iter().find_map(|c| match c {
Command::KillTmuxWindow(k) => Some(k),
_ => None,
})
}
fn drained_emit_bell(app: &mut App) -> bool {
app.drain_commands()
.into_iter()
.any(|c| matches!(c, Command::EmitBell))
}
fn cfg() -> Arc<Config> {
Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[command.up]
run = "true"
[command.test]
run = "true"
desc = "Run tests"
"#,
)
.unwrap(),
)
}
#[test]
fn build_items_orders_services_recipes_scripts() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[command.up]
run = "true"
[[ui.pane]]
type = "service"
service = "app"
"#,
)
.unwrap(),
);
let app = App::new(cfg);
assert_eq!(app.items().len(), 2);
assert_eq!(app.items()[0].kind, ItemKind::Service);
assert_eq!(app.items()[0].name, "app");
assert_eq!(app.items()[1].kind, ItemKind::Recipe);
}
#[test]
fn container_row_appears_when_backend_configured() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "compose"
[command.up]
run = "true"
"#,
)
.unwrap(),
);
let app = App::new(cfg);
assert_eq!(app.items()[0].kind, ItemKind::Runtime);
assert_eq!(app.items()[0].name, "compose");
}
#[test]
fn no_container_row_when_backend_none() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[command.up]
run = "true"
"#,
)
.unwrap(),
);
let app = App::new(cfg);
assert!(app.items().iter().all(|i| i.kind != ItemKind::Runtime));
}
#[test]
fn collect_service_panes_picks_up_ui_services() {
let cfg = crate::config::parse_str(
r#"
[[ui.pane]]
type = "service"
service = "app"
[[ui.pane]]
type = "service"
service = "worker"
"#,
)
.unwrap();
let panes = collect_service_panes(&cfg);
assert_eq!(panes.len(), 2);
assert!(panes.contains_key("app"));
assert!(panes.contains_key("worker"));
}
#[test]
fn launch_rejects_service_selection() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[[ui.pane]]
type = "service"
service = "app"
"#,
)
.unwrap(),
);
let backend: Arc<dyn crate::container::Backend> =
Arc::new(crate::container::null::NullBackend);
let executor = Executor::new(backend, Arc::clone(&cfg), std::path::Path::new("/tmp"));
let mut app = App::new(cfg).with_executor(executor);
let err = app.try_launch_selected().unwrap_err();
match err {
LaunchRejection::NotRunnable(msg) => assert!(msg.contains("service panes")),
other => panic!("unexpected: {other:?}"),
}
}
#[test]
fn navigation_clamps_at_bounds() {
let mut app = App::new(cfg());
app.select_prev();
assert_eq!(app.selected_index(), 0);
app.select_next();
assert_eq!(app.selected_index(), 1);
app.select_next();
assert_eq!(app.selected_index(), 1);
app.select_first();
assert_eq!(app.selected_index(), 0);
app.select_last();
assert_eq!(app.selected_index(), 1);
}
#[test]
fn quit_flag_propagates() {
let mut app = App::new(cfg());
assert!(!app.should_quit());
app.quit();
assert!(app.should_quit());
}
#[test]
fn truly_empty_config_has_no_items() {
let cfg = Arc::new(
crate::config::parse_str(
r#"[runtime]
backend = "none""#,
)
.unwrap(),
);
let app = App::new(cfg);
assert_eq!(app.items().len(), 0);
assert!(app.selected_item().is_none());
}
#[test]
fn launch_without_executor_is_rejected() {
let mut app = App::new(cfg());
let err = app.try_launch_selected().unwrap_err();
assert!(matches!(err, LaunchRejection::NoExecutor));
}
#[test]
fn launch_rejects_in_container_recipe() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[command.shell]
in = "app"
run = "/bin/sh"
"#,
)
.unwrap(),
);
let backend: Arc<dyn crate::container::Backend> =
Arc::new(crate::container::null::NullBackend);
let executor = Executor::new(backend, Arc::clone(&cfg), std::path::Path::new("/tmp"));
let mut app = App::new(cfg).with_executor(executor);
let err = app.try_launch_selected().unwrap_err();
match err {
LaunchRejection::NotRunnable(msg) => assert!(msg.contains("in-container")),
other => panic!("unexpected: {other:?}"),
}
}
fn rows() -> Vec<WorktreeRow> {
vec![
WorktreeRow {
path: PathBuf::from("/repo"),
branch: Some("main".into()),
slug: "main".into(),
is_current: true,
},
WorktreeRow {
path: PathBuf::from("/repo-feature"),
branch: Some("feature".into()),
slug: "feature".into(),
is_current: false,
},
]
}
#[test]
fn switcher_open_preselects_current_row() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
assert_eq!(app.mode(), Mode::WorktreeSwitcher);
let s = app.switcher().unwrap();
assert_eq!(s.selected, 0);
}
#[test]
fn switcher_confirm_on_current_row_no_pending_switch() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
let outcome = app.switcher_confirm();
assert_eq!(outcome, SwitcherConfirm::Switched);
assert!(drained_switch(&mut app).is_none());
assert_eq!(app.mode(), Mode::Normal);
}
#[test]
fn switcher_confirm_on_other_row_queues_switch() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
let outcome = app.switcher_confirm();
assert_eq!(outcome, SwitcherConfirm::Switched);
assert_eq!(
drained_switch(&mut app),
Some(PathBuf::from("/repo-feature"))
);
}
#[test]
fn switcher_navigation_extends_to_new_row_sentinel() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
assert_eq!(app.switcher().unwrap().selected, 2);
app.switcher_mut().unwrap().select_next();
assert_eq!(app.switcher().unwrap().selected, 2);
}
#[test]
fn switcher_confirm_on_new_row_signals_open_form() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
let outcome = app.switcher_confirm();
assert_eq!(outcome, SwitcherConfirm::OpenCreateForm);
assert!(app.switcher().unwrap().creating.is_none());
app.open_create_form(Vec::new(), None);
assert_eq!(app.mode(), Mode::WorktreeSwitcher);
assert!(app.switcher().unwrap().creating.is_some());
}
#[test]
fn switcher_form_finish_ok_queues_switch() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
app.open_create_form(Vec::new(), None);
app.switcher_form_finish(Ok(PathBuf::from("/repo-new")));
assert_eq!(drained_switch(&mut app), Some(PathBuf::from("/repo-new")));
assert_eq!(app.mode(), Mode::Normal);
}
#[test]
fn switcher_form_finish_err_keeps_form_open_with_error() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
app.open_create_form(Vec::new(), None);
app.switcher_form_finish(Err("git: branch already exists".into()));
assert_eq!(app.mode(), Mode::WorktreeSwitcher);
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.error.as_deref(), Some("git: branch already exists"));
}
#[test]
fn terminals_default_has_no_windows() {
let app = App::new(cfg());
assert!(app.terminals().windows.is_empty());
let rows = app.terminals_rows();
assert!(matches!(
rows.last().unwrap(),
crate::tui::app::TerminalsRow::NewSentinel
));
}
#[test]
fn terminals_set_windows_populates_rows() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![
crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
},
crate::tui::app::TmuxWindow {
index: 1,
name: "vim".into(),
cwd: None,
has_bell: false,
workspace: None,
},
]);
let rows = app.terminals_rows();
assert_eq!(rows.len(), 3);
assert!(matches!(
rows[0],
crate::tui::app::TerminalsRow::Window(ref w) if w.name == "zsh"
));
}
#[test]
fn terminals_set_windows_filters_service_windows() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![
crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
},
crate::tui::app::TmuxWindow {
index: 1,
name: "svc:app".into(),
cwd: None,
has_bell: false,
workspace: None,
},
]);
let rows = app.terminals_rows();
assert_eq!(rows.len(), 2);
assert!(matches!(
rows[0],
crate::tui::app::TerminalsRow::Window(ref w) if w.name == "zsh"
));
assert!(matches!(
rows[1],
crate::tui::app::TerminalsRow::NewSentinel
));
}
#[test]
fn terminals_set_windows_arms_bell_on_false_to_true_transition() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
assert!(!drained_emit_bell(&mut app));
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: true,
workspace: None,
}]);
assert!(drained_emit_bell(&mut app), "fresh bell should arm emit");
assert!(!drained_emit_bell(&mut app));
}
#[test]
fn terminals_set_windows_does_not_rearm_bell_while_set() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: true,
workspace: None,
}]);
assert!(drained_emit_bell(&mut app), "first observation arms");
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: true,
workspace: None,
}]);
assert!(
!drained_emit_bell(&mut app),
"still-set bell should not re-arm"
);
}
#[test]
fn silence_next_bell_suppresses_one_emit_and_then_rearms() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals_mut().silence_next_bell();
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: true,
workspace: None,
}]);
assert!(
!drained_emit_bell(&mut app),
"silence flag should suppress this one emit"
);
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: true,
workspace: None,
}]);
assert!(
drained_emit_bell(&mut app),
"silence is single-shot — next transition should arm"
);
}
#[test]
fn terminals_confirm_on_sentinel_queues_new_shell() {
let mut app = App::new(cfg());
app.terminals_confirm();
let req = drained_attach(&mut app).unwrap();
assert_eq!(req.window, "croft-new");
assert!(req.create_with.as_deref().unwrap().contains("SHELL"));
}
#[test]
fn terminals_confirm_on_window_queues_attach_by_index() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 3,
name: "vim".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals.selected = 0;
app.terminals_confirm();
let req = drained_attach(&mut app).unwrap();
assert_eq!(req.window, "3");
assert!(req.create_with.is_none());
}
#[test]
fn queue_new_shell_matches_sentinel_confirm() {
let mut from_shortcut = App::new(cfg());
from_shortcut.queue_new_shell();
let req_shortcut = drained_attach(&mut from_shortcut).unwrap();
let mut from_sentinel = App::new(cfg());
from_sentinel.terminals_confirm();
let req_sentinel = drained_attach(&mut from_sentinel).unwrap();
assert_eq!(req_shortcut.session, req_sentinel.session);
assert_eq!(req_shortcut.window, req_sentinel.window);
assert_eq!(req_shortcut.create_with, req_sentinel.create_with);
assert_eq!(req_shortcut.window, "croft-new");
}
#[test]
fn terminals_kill_selected_opens_confirm_modal() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals.selected = 0;
app.terminals_kill_selected();
assert_eq!(app.mode(), Mode::Confirm);
assert!(drained_kill_window(&mut app).is_none());
let dialog = app.confirm_dialog().unwrap();
assert!(dialog.title.contains("zsh"));
assert!(dialog.yes_focused);
}
#[test]
fn confirm_resolve_yes_queues_kill() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals.selected = 0;
app.terminals_kill_selected();
let rejection = app.confirm_resolve(true);
assert!(rejection.is_none());
let kill = drained_kill_window(&mut app).unwrap();
assert_eq!(kill.index, 0);
}
#[test]
fn confirm_resolve_no_skips_kill() {
let mut app = App::new(cfg());
app.terminals_set_windows(vec![crate::tui::app::TmuxWindow {
index: 0,
name: "zsh".into(),
cwd: None,
has_bell: false,
workspace: None,
}]);
app.terminals.selected = 0;
app.terminals_kill_selected();
app.confirm_resolve(false);
assert!(drained_kill_window(&mut app).is_none());
}
#[test]
fn terminals_kill_on_sentinel_is_noop() {
let mut app = App::new(cfg());
app.terminals.selected = app.terminals_rows().len() - 1;
app.terminals_kill_selected();
assert_eq!(app.mode(), Mode::Normal);
assert!(app.confirm_dialog().is_none());
}
#[test]
fn diff_line_kind_classifies_known_prefixes() {
assert_eq!(
DiffLineKind::classify("@@ -1,5 +1,5 @@"),
DiffLineKind::Hunk
);
assert_eq!(
DiffLineKind::classify("diff --git a/x b/x"),
DiffLineKind::Header
);
assert_eq!(DiffLineKind::classify("--- a/x"), DiffLineKind::Header);
assert_eq!(DiffLineKind::classify("+++ b/x"), DiffLineKind::Header);
assert_eq!(DiffLineKind::classify("+ added"), DiffLineKind::Added);
assert_eq!(DiffLineKind::classify("- removed"), DiffLineKind::Removed);
assert_eq!(DiffLineKind::classify(" context"), DiffLineKind::Context);
assert_eq!(DiffLineKind::classify(""), DiffLineKind::Context);
}
#[test]
fn queue_service_attach_jumps_view_and_sets_request() {
let mut app = App::new(cfg());
app.queue_service_attach("app").unwrap();
assert_eq!(app.view(), View::Terminals);
let req = drained_attach(&mut app).unwrap();
assert_eq!(req.window, "svc:app");
assert!(
req.create_with
.as_deref()
.unwrap()
.contains("docker compose")
);
}
#[test]
fn queue_service_attach_rejects_systemd_service() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[[services.systemd]]
name = "postgres"
unit = "postgresql.service"
"#,
)
.unwrap(),
);
let mut app = App::new(cfg);
let err = app.queue_service_attach("postgres").unwrap_err();
assert!(err.contains("systemd"), "msg: {err}");
assert_eq!(app.view(), View::ControlCenter);
assert!(drained_attach(&mut app).is_none());
}
#[test]
fn queue_service_attach_rejects_custom_service() {
let cfg = Arc::new(
crate::config::parse_str(
r#"
[runtime]
backend = "none"
[[services.custom]]
name = "tunnel"
status = "true"
start = "true"
stop = "true"
"#,
)
.unwrap(),
);
let mut app = App::new(cfg);
let err = app.queue_service_attach("tunnel").unwrap_err();
assert!(err.contains("custom"), "msg: {err}");
}
fn df(path: &str, status: DiffStatus) -> DiffFile {
DiffFile {
path: path.into(),
status,
additions: 0,
deletions: 0,
binary: false,
old_path: None,
}
}
#[test]
fn diff_select_clamps_at_bounds() {
let mut app = App::new(cfg());
app.diff_mut().set_files(vec![
df("a", DiffStatus::Modified),
df("b", DiffStatus::Added),
]);
app.diff_mut().select_next();
assert_eq!(app.diff().selected, 1);
app.diff_mut().select_next();
assert_eq!(app.diff().selected, 1);
app.diff_mut().select_prev();
assert_eq!(app.diff().selected, 0);
app.diff_mut().select_prev();
assert_eq!(app.diff().selected, 0);
}
#[test]
fn select_at_clamps_to_last_item() {
let mut app = App::new(cfg());
let last = app.items().len() - 1;
app.select_at(usize::MAX);
assert_eq!(app.selected_index(), last);
app.select_at(0);
assert_eq!(app.selected_index(), 0);
}
#[test]
fn diff_select_at_clamps() {
let mut app = App::new(cfg());
app.diff_mut().set_files(vec![
df("a", DiffStatus::Modified),
df("b", DiffStatus::Added),
]);
app.diff_mut().select_at(usize::MAX);
assert_eq!(app.diff().selected, 1);
app.diff_mut().select_at(0);
assert_eq!(app.diff().selected, 0);
}
#[test]
fn terminals_select_at_clamps() {
let mut app = App::new(cfg());
let last = app.terminals_rows().len() - 1;
app.terminals_select_at(usize::MAX);
assert_eq!(app.terminals().selected, last);
app.terminals_select_at(0);
assert_eq!(app.terminals().selected, 0);
}
#[test]
fn diff_body_h_scroll_by_clamps_at_zero() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff.body_width.set(20);
app.diff_mut().set_cache(
"a".into(),
vec![DiffLine {
kind: DiffLineKind::Context,
text: format!(" {}", "x".repeat(200)),
old_lineno: Some(1),
new_lineno: Some(1),
spans: vec![],
}],
);
assert_eq!(app.diff().body_h_scroll(), 0);
app.diff_mut().body_h_scroll_by(-5);
assert_eq!(app.diff().body_h_scroll(), 0);
app.diff_mut().body_h_scroll_by(12);
assert_eq!(app.diff().body_h_scroll(), 12);
app.diff_mut().body_h_scroll_by(-20);
assert_eq!(app.diff().body_h_scroll(), 0);
}
#[test]
fn diff_body_h_scroll_clamps_at_longest_line() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff.body_width.set(20);
app.diff_mut().set_cache(
"a".into(),
vec![DiffLine {
kind: DiffLineKind::Context,
text: format!(" {}", "x".repeat(30)),
old_lineno: Some(1),
new_lineno: Some(1),
spans: vec![],
}],
);
app.diff_mut().body_h_scroll_by(9999);
assert_eq!(app.diff().body_h_scroll(), 16);
app.diff_mut().body_h_scroll_by(50);
assert_eq!(app.diff().body_h_scroll(), 16);
app.diff.body_width.set(100);
assert_eq!(app.diff().body_h_scroll(), 0);
}
#[test]
fn diff_toggle_wrap_on_clears_h_scroll_for_active_file() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff.body_width.set(20);
app.diff_mut().set_cache(
"a".into(),
vec![DiffLine {
kind: DiffLineKind::Context,
text: format!(" {}", "x".repeat(100)),
old_lineno: Some(1),
new_lineno: Some(1),
spans: vec![],
}],
);
assert!(!app.diff().wrap);
app.diff_mut().body_h_scroll_by(16);
assert_eq!(app.diff().body_h_scroll(), 16);
app.diff_mut().toggle_wrap();
assert!(app.diff().wrap);
assert_eq!(app.diff().body_h_scroll(), 0);
app.diff_mut().toggle_wrap();
assert!(!app.diff().wrap);
assert_eq!(app.diff().body_h_scroll(), 0);
}
#[test]
fn diff_mark_stale_clears_cache() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff_mut().set_cache("a".into(), vec![]);
assert!(app.diff().cache_for("a").is_some());
app.diff_mut().mark_stale();
assert!(app.diff().cache_for("a").is_none());
assert!(!app.diff().loaded);
}
#[test]
fn diff_focus_toggles() {
let mut app = App::new(cfg());
assert_eq!(app.diff().focus(), DiffFocus::Files);
app.diff_mut().toggle_focus();
assert_eq!(app.diff().focus(), DiffFocus::Body);
app.diff_mut().toggle_focus();
assert_eq!(app.diff().focus(), DiffFocus::Files);
}
#[test]
fn diff_jump_hunk_skips_to_next_at_marker() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff.body_height.set(2);
app.diff_mut().set_cache(
"a".into(),
vec![
DiffLine {
kind: DiffLineKind::Header,
text: "diff --git a/a b/a".into(),
old_lineno: None,
new_lineno: None,
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Hunk,
text: "@@ -1,3 +1,3 @@".into(),
old_lineno: None,
new_lineno: None,
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Context,
text: " ctx".into(),
old_lineno: Some(1),
new_lineno: Some(1),
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Hunk,
text: "@@ -10,3 +10,3 @@".into(),
old_lineno: None,
new_lineno: None,
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Context,
text: " ctx2".into(),
old_lineno: Some(10),
new_lineno: Some(10),
spans: vec![],
},
],
);
app.diff_mut().jump_hunk_next();
assert_eq!(app.diff().body_scroll(), 1);
app.diff_mut().jump_hunk_next();
assert_eq!(app.diff().body_scroll(), 3);
app.diff_mut().jump_hunk_next();
assert_eq!(app.diff().body_scroll(), 3);
app.diff_mut().jump_hunk_prev();
assert_eq!(app.diff().body_scroll(), 1);
app.diff_mut().jump_hunk_prev();
assert_eq!(app.diff().body_scroll(), 1);
}
#[test]
fn body_mode_toggles_diff_and_read() {
let mut app = App::new(cfg());
assert_eq!(app.diff().body_mode(), BodyMode::Diff);
app.diff_mut().toggle_body_mode();
assert_eq!(app.diff().body_mode(), BodyMode::Read);
app.diff_mut().toggle_body_mode();
assert_eq!(app.diff().body_mode(), BodyMode::Diff);
}
#[test]
fn diff_mark_stale_clears_read_cache() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff_mut().set_read_cache(
"a".into(),
vec![ReadLine {
kind: ReadLineKind::Plain,
lineno: 1,
text: "x".into(),
spans: vec![],
}],
);
assert!(app.diff().read_cache_for("a").is_some());
app.diff_mut().mark_stale();
assert!(app.diff().read_cache_for("a").is_none());
}
#[test]
fn scroll_routes_to_active_mode() {
let mut app = App::new(cfg());
app.diff_mut()
.set_files(vec![df("a", DiffStatus::Modified)]);
app.diff.body_height.set(1);
app.diff_mut().set_cache(
"a".into(),
vec![
DiffLine {
kind: DiffLineKind::Context,
text: " a".into(),
old_lineno: Some(1),
new_lineno: Some(1),
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Context,
text: " b".into(),
old_lineno: Some(2),
new_lineno: Some(2),
spans: vec![],
},
DiffLine {
kind: DiffLineKind::Context,
text: " c".into(),
old_lineno: Some(3),
new_lineno: Some(3),
spans: vec![],
},
],
);
let read_lines: Vec<ReadLine> = (1..=5)
.map(|i| ReadLine {
kind: ReadLineKind::Plain,
lineno: i,
text: format!("line{i}"),
spans: vec![],
})
.collect();
app.diff_mut().set_read_cache("a".into(), read_lines);
use crate::tui::shared::scroll::Axis;
app.diff_mut().body_scroll_by(2);
assert_eq!(app.diff().body_scroll(), 2);
assert_eq!(app.diff().diff_scroll.get("a", Axis::Vertical), 2);
assert_eq!(app.diff().read_scroll.get("a", Axis::Vertical), 0);
app.diff_mut().toggle_body_mode();
assert_eq!(app.diff().body_mode(), BodyMode::Read);
assert_eq!(app.diff().body_scroll(), 0);
app.diff_mut().body_scroll_by(3);
assert_eq!(app.diff().body_scroll(), 3);
assert_eq!(app.diff().read_scroll.get("a", Axis::Vertical), 3);
assert_eq!(app.diff().diff_scroll.get("a", Axis::Vertical), 2);
app.diff_mut().toggle_body_mode();
assert_eq!(app.diff().body_scroll(), 2);
}
#[test]
fn diff_g_chord_fires_on_second_press() {
let mut app = App::new(cfg());
assert!(!app.diff_mut().consume_g_chord());
assert!(app.diff_mut().consume_g_chord());
assert!(!app.diff_mut().consume_g_chord());
}
#[test]
fn switcher_form_focus_toggles_between_path_and_branch() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
app.open_create_form(Vec::new(), None);
let initial = app.switcher().unwrap().creating.as_ref().unwrap().focus;
app.switcher_form_mut().unwrap().toggle_focus();
let toggled = app.switcher().unwrap().creating.as_ref().unwrap().focus;
assert_ne!(initial, toggled);
}
#[test]
fn switcher_form_path_auto_syncs_from_branch() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
app.open_create_form(Vec::new(), None);
for c in "feat/auth".chars() {
app.switcher_form_mut().unwrap().push_char(c);
}
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.branch_input, "feat/auth");
assert!(
form.path_input.ends_with("/feat-auth"),
"{}",
form.path_input
);
assert!(!form.path_dirty);
app.switcher_form_mut().unwrap().toggle_focus();
app.switcher_form_mut().unwrap().push_char('/');
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert!(form.path_dirty);
let dirty_path = form.path_input.clone();
app.switcher_form_mut().unwrap().toggle_focus();
app.switcher_form_mut().unwrap().push_char('-');
app.switcher_form_mut().unwrap().push_char('v');
app.switcher_form_mut().unwrap().push_char('2');
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.branch_input, "feat/auth-v2");
assert_eq!(form.path_input, dirty_path);
}
#[test]
fn switcher_form_arrow_navigation_moves_selection() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
app.open_create_form(
vec![
crate::runtime::BranchEntry {
name: "main".into(),
remote_only: false,
},
crate::runtime::BranchEntry {
name: "feat-x".into(),
remote_only: false,
},
crate::runtime::BranchEntry {
name: "feat-y".into(),
remote_only: false,
},
],
None,
);
let sel = |a: &App| a.switcher().unwrap().creating.as_ref().unwrap().selected;
assert_eq!(sel(&app), 0);
app.switcher_form_mut().unwrap().select_next();
assert_eq!(sel(&app), 1);
app.switcher_form_mut().unwrap().select_next();
assert_eq!(sel(&app), 2);
app.switcher_form_mut().unwrap().select_next();
assert_eq!(sel(&app), 2);
app.switcher_form_mut().unwrap().select_prev();
assert_eq!(sel(&app), 1);
}
#[test]
fn switcher_form_filter_and_sentinel() {
let mut app = App::new(cfg());
app.open_worktree_switcher(rows());
app.switcher_mut().unwrap().select_next();
app.switcher_mut().unwrap().select_next();
app.switcher_confirm();
let branches = vec![
crate::runtime::BranchEntry {
name: "main".into(),
remote_only: false,
},
crate::runtime::BranchEntry {
name: "feat-x".into(),
remote_only: false,
},
crate::runtime::BranchEntry {
name: "feat-y".into(),
remote_only: false,
},
];
app.open_create_form(branches, None);
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.filtered.len(), 3);
assert!(!form.show_create_sentinel());
for c in "feat".chars() {
app.switcher_form_mut().unwrap().push_char(c);
}
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.filtered.len(), 2);
assert!(form.show_create_sentinel());
assert_eq!(form.total_options(), 3);
app.switcher_form_mut().unwrap().push_char('-');
app.switcher_form_mut().unwrap().push_char('x');
let form = app.switcher().unwrap().creating.as_ref().unwrap();
assert_eq!(form.filtered.len(), 1);
assert!(!form.show_create_sentinel());
}
}