the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: confirm closing a workspace's last pane in the tui (#5173)
Can Celikdc6b6e5f4283
diff --git a/docs/next/website/src/content/docs/cli-reference.mdx b/docs/next/website/src/content/docs/cli-reference.mdxindex ea0ca2180..d5ee1423c 100644--- a/docs/next/website/src/content/docs/cli-reference.mdx+++ b/docs/next/website/src/content/docs/cli-reference.mdx@@ -198,7 +198,7 @@ herdr tab close <tab_id>A tab is another terminal layout inside a workspace. Without `--workspace`, `tab create` uses the active workspace and fails if none exists. Its JSON response exposes `.result.tab.tab_id` and `.result.root_pane.pane_id`. Closing a workspace's last tab also closes the workspace, matching the TUI close-tab action. If `confirm_close` is enabled and closing the tab would also close a whole worktree group, `tab close` returns a `confirmation_required` error instead.-With `ui.confirm_close` enabled, the TUI asks for confirmation before closing a workspace's last tab from a keybinding or the tab menu. Ordinary CLI/API tab closes remain immediate.+With `ui.confirm_close` enabled, the TUI asks for confirmation before closing a workspace's last tab or its only pane from a keybinding or the tab/pane menu. Ordinary pane closes and CLI/API closes remain immediate.Workspace and tab creation, and pane splitting, leave focus unchanged by default. `--focus` selects the new layout; `--no-focus` states the default explicitly. Without `--cwd`, new terminals follow the configured `terminal.new_cwd` policy, which follows the source pane or workspace by default. Each `--env KEY=VALUE` adds or replaces that variable in the new root shell.diff --git a/docs/next/website/src/content/docs/ja/cli-reference.mdx b/docs/next/website/src/content/docs/ja/cli-reference.mdxindex 446f13745..a2ea967c1 100644--- a/docs/next/website/src/content/docs/ja/cli-reference.mdx+++ b/docs/next/website/src/content/docs/ja/cli-reference.mdx@@ -194,7 +194,7 @@ herdr tab close <tab_id>タブはワークスペース内の別のターミナルレイアウトです。`--workspace` を省略すると、`tab create` はアクティブなワークスペースを使い、存在しなければ失敗します。JSON レスポンスの `.result.tab.tab_id` と `.result.root_pane.pane_id` から ID を取得できます。ワークスペースの最後のタブを閉じると、そのワークスペースも閉じられます。`ui.confirm_close` が有効で、親ワークツリーの最後のタブを閉じるとワークツリーグループ全体が閉じられる場合、`tab close` は `confirmation_required` エラーを返します。-`ui.confirm_close` が有効な場合、キーバインドやタブメニューからワークスペースの最後のタブを閉じる前に、TUI が確認を求めます。通常の CLI/API によるタブの終了は引き続き即座に実行されます。+`ui.confirm_close` が有効な場合、キーバインドやタブ/ペインメニューからワークスペースの最後のタブ、または唯一のペインを閉じる前に、TUI が確認を求めます。通常のペイン終了や CLI/API による終了は引き続き即座に実行されます。ワークスペースとタブの作成、およびペインの分割は、デフォルトではフォーカスを変えません。`--focus` は新しいレイアウトを選択し、`--no-focus` はデフォルトを明示します。`--cwd` がない場合、新しいターミナルは `terminal.new_cwd` の設定に従い、デフォルトでは元のペインまたはワークスペースを引き継ぎます。各 `--env KEY=VALUE` は新しいルートシェルの環境変数を追加または置換します。diff --git a/docs/next/website/src/content/docs/zh-cn/cli-reference.mdx b/docs/next/website/src/content/docs/zh-cn/cli-reference.mdxindex c71c78c54..07cf89252 100644--- a/docs/next/website/src/content/docs/zh-cn/cli-reference.mdx+++ b/docs/next/website/src/content/docs/zh-cn/cli-reference.mdx@@ -194,7 +194,7 @@ herdr tab close <tab_id>标签页是工作区内的另一个终端布局。不指定 `--workspace` 时,`tab create` 使用活动工作区;如果没有活动工作区则失败。JSON 响应中的 `.result.tab.tab_id` 和 `.result.root_pane.pane_id` 是对应 ID。关闭工作区的最后一个标签页也会关闭该工作区。启用 `ui.confirm_close` 时,如果关闭父工作树的最后一个标签页会连带关闭整个工作树组,`tab close` 会返回 `confirmation_required` 错误。-启用 `ui.confirm_close` 时,通过快捷键或标签页菜单关闭工作区的最后一个标签页前,TUI 会要求确认。普通的 CLI/API 标签页关闭操作仍立即执行。+启用 `ui.confirm_close` 时,通过快捷键或标签页/窗格菜单关闭工作区的最后一个标签页或唯一窗格前,TUI 会要求确认。普通的窗格关闭及 CLI/API 关闭操作仍立即执行。创建工作区、标签页和拆分窗格默认不改变焦点。`--focus` 选择新布局;`--no-focus` 显式表达默认行为。不指定 `--cwd` 时,新终端遵循 `terminal.new_cwd` 设置,默认跟随来源窗格或工作区。每个 `--env KEY=VALUE` 在新的根 shell 中添加或替换一个环境变量。diff --git a/src/client/shell/actions.rs b/src/client/shell/actions.rsindex e6d1fa231..83819b0d1 100644--- a/src/client/shell/actions.rs+++ b/src/client/shell/actions.rs@@ -112,6 +112,16 @@ impl ClientShellState {outcome.repaint = true;return;}+ if action == crate::input::KeybindAction::ClosePane {+ if let Some(pane_id) = self+ .snapshot+ .as_deref()+ .and_then(|snapshot| snapshot.focused_pane_id.clone())+ {+ self.request_pane_close(pane_id, outcome);+ }+ return;+ }if action == crate::input::KeybindAction::CloseTab {if let Some(tab_id) = self.snapshot@@ -1051,9 +1061,6 @@ impl ClientShellState {env: Default::default(),}))}- KeybindAction::ClosePane => Some(Method::PaneClose(PaneTarget {- pane_id: focused_pane.clone()?,- })),KeybindAction::CyclePaneNext | KeybindAction::CyclePanePrevious => {let focused_tab = focused_tab?;let panes = snapshotdiff --git a/src/client/shell/context_menu.rs b/src/client/shell/context_menu.rsindex f7d875562..a7d6322c2 100644--- a/src/client/shell/context_menu.rs+++ b/src/client/shell/context_menu.rs@@ -447,9 +447,7 @@ impl ClientShellState {}),outcome,),- ClientContextMenuAction::ClosePane => {- self.push_endpoint_method(Method::PaneClose(PaneTarget { pane_id }), outcome)- }+ ClientContextMenuAction::ClosePane => self.request_pane_close(pane_id, outcome),_ => {}}}diff --git a/src/client/shell/overlay_input.rs b/src/client/shell/overlay_input.rsindex 5ab6e6593..7f797ef7f 100644--- a/src/client/shell/overlay_input.rs+++ b/src/client/shell/overlay_input.rs@@ -1021,6 +1021,40 @@ impl ClientShellState {);}+ pub(super) fn request_pane_close(&mut self, pane_id: String, outcome: &mut ClientShellInput) {+ let target = self.snapshot.as_deref().and_then(|snapshot| {+ let pane = snapshot.panes.iter().find(|pane| pane.pane_id == pane_id)?;+ let tab = snapshot+ .tabs+ .iter()+ .find(|tab| tab.tab_id == pane.tab_id && tab.workspace_id == pane.workspace_id)?;+ (self.config.confirm_close+ && !snapshot+ .panes+ .iter()+ .any(|other| other.tab_id == tab.tab_id && other.pane_id != pane_id)+ && !snapshot.tabs.iter().any(|other| {+ other.workspace_id == tab.workspace_id && other.tab_id != tab.tab_id+ }))+ .then(|| (tab.workspace_id.clone(), tab.tab_id.clone()))+ });+ if let Some((workspace_id, tab_id)) = target {+ if self.open_close_confirmation(workspace_id, Some(tab_id), None) {+ if let Some(ClientShellOverlay::ConfirmClose(confirm)) = self.overlay.as_mut() {+ if let Some(target) = confirm.tab_target.as_mut() {+ target.pane_id = Some(pane_id);+ }+ }+ outcome.repaint = true;+ return;+ }+ }+ self.push_endpoint_method(+ crate::api::schema::Method::PaneClose(crate::api::schema::PaneTarget { pane_id }),+ outcome,+ );+ }+pub(super) fn request_tab_close(&mut self, tab_id: String, outcome: &mut ClientShellInput) {let workspace_id = self.snapshot.as_deref().and_then(|snapshot| {let target = snapshot.tabs.iter().find(|tab| tab.tab_id == tab_id)?;@@ -1057,15 +1091,28 @@ impl ClientShellState {&& tab.workspace_id == target.workspace.workspace_id})})+ || target.pane_id.as_ref().is_some_and(|pane_id| {+ !self.snapshot.as_deref().is_some_and(|snapshot| {+ snapshot.panes.iter().any(|pane| {+ pane.pane_id == *pane_id+ && pane.tab_id == target.tab_id+ && pane.workspace_id == target.workspace.workspace_id+ })+ })+ }){self.receive_endpoint_unavailable(- "Close target changed; try closing the tab again".into(),+ "Close target changed; try closing it again".into(),);return;}- crate::api::schema::Method::TabClose(crate::api::schema::TabTarget {- tab_id: target.tab_id,- })+ if let Some(pane_id) = target.pane_id {+ crate::api::schema::Method::PaneClose(crate::api::schema::PaneTarget { pane_id })+ } else {+ crate::api::schema::Method::TabClose(crate::api::schema::TabTarget {+ tab_id: target.tab_id,+ })+ }} else {crate::api::schema::Method::WorkspaceClose(crate::api::schema::WorkspaceCloseParams {workspace_id: confirm.workspace_id,@@ -1128,7 +1175,11 @@ impl ClientShellState {else {return false;};- Some(ClientTabCloseConfirmation { tab_id, workspace })+ Some(ClientTabCloseConfirmation {+ tab_id,+ workspace,+ pane_id: None,+ })} else {None};diff --git a/src/client/shell/state.rs b/src/client/shell/state.rsindex 19eb19d1e..5a732920c 100644--- a/src/client/shell/state.rs+++ b/src/client/shell/state.rs@@ -565,6 +565,7 @@ pub(super) struct ClientContextMenuItem {#[derive(Debug)]pub(super) struct ClientTabCloseConfirmation {+ pub(super) pane_id: Option<String>,pub(super) tab_id: String,pub(super) workspace: WorkspaceNavigationTarget,}diff --git a/src/client/shell/tests/chrome_context.rs b/src/client/shell/tests/chrome_context.rsindex 1e1d5fc35..1ef98798e 100644--- a/src/client/shell/tests/chrome_context.rs+++ b/src/client/shell/tests/chrome_context.rs@@ -479,8 +479,12 @@ fn close_confirmation_error_becomes_client_owned_overlay_and_stable_workspace_clstate.set_snapshot(Box::new(snapshot()));state.set_pane_surface(surface());let mut close = ClientShellInput::default();- state.record_binding(- crate::input::KeybindMatch::Action(crate::input::KeybindAction::ClosePane),+ // Exercise the server error fallback directly: last-pane keybindings now+ // confirm locally before issuing a request.+ state.push_endpoint_method(+ crate::api::schema::Method::PaneClose(crate::api::schema::PaneTarget {+ pane_id: "pane_1".into(),+ }),&mut close,);let [ClientShellAction::Endpoint { request, .. }] = &close.actions[..] else {diff --git a/src/client/shell/tests/close_pane.rs b/src/client/shell/tests/close_pane.rsnew file mode 100644index 000000000..970afe221--- /dev/null+++ b/src/client/shell/tests/close_pane.rs@@ -0,0 +1,292 @@+use super::*;+use crate::api::schema::Method;+use crossterm::event::{MouseButton, MouseEventKind};++fn close_state(confirm: bool, tab_count: usize) -> ClientShellState {+ let mut projected = snapshot();+ for number in 2..=tab_count {+ let mut tab = projected.tabs[0].clone();+ tab.tab_id = format!("tab_{number}");+ tab.number = number;+ tab.focused = false;+ projected.tabs.push(tab);+ }+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));+ state.config.confirm_close = confirm;+ state.set_snapshot(Box::new(projected));+ state.set_pane_surface(surface());+ state.compose(106, 24).unwrap();+ state+}++fn click(state: &mut ClientShellState, rect: Rect) -> ClientShellInput {+ state.handle_raw_events(vec![crate::raw_input::RawInputEvent::Mouse(MouseEvent {+ kind: MouseEventKind::Down(MouseButton::Left),+ column: rect.x,+ row: rect.y,+ modifiers: KeyModifiers::empty(),+ })])+}++fn request_close(state: &mut ClientShellState, menu: bool) -> ClientShellInput {+ if menu {+ let pane = state.hits.panes[0].rect;+ state.handle_raw_events(vec![crate::raw_input::RawInputEvent::Mouse(MouseEvent {+ kind: MouseEventKind::Down(MouseButton::Right),+ column: pane.x + 1,+ row: pane.y,+ modifiers: KeyModifiers::empty(),+ })]);+ state.compose(106, 24).unwrap();+ let index = match state.overlay.as_ref() {+ Some(ClientShellOverlay::ContextMenu(menu)) => menu+ .items()+ .iter()+ .position(|item| item.action == ClientContextMenuAction::ClosePane)+ .unwrap(),+ _ => panic!("pane menu"),+ };+ let close_row = state.hits.context_menu_rows[index].0;+ click(state, close_row)+ } else {+ let mut outcome = ClientShellInput::default();+ state.record_binding(+ crate::input::KeybindMatch::Action(crate::input::KeybindAction::ClosePane),+ &mut outcome,+ );+ outcome+ }+}++fn assert_no_close(outcome: &ClientShellInput) {+ assert!(outcome.requests.is_empty());+ assert!(outcome.actions.iter().all(|action| {+ !matches!(action, ClientShellAction::Endpoint { request, .. }+ if matches!(request.method, Method::PaneClose(_) | Method::TabClose(_) | Method::WorkspaceClose(_)))+ }));+}++fn assert_pane_close(outcome: &ClientShellInput) {+ let methods = outcome+ .actions+ .iter()+ .filter_map(|action| match action {+ ClientShellAction::Endpoint { request, .. } => Some(&request.method),+ _ => None,+ })+ .filter(|method| !matches!(method, Method::TabFocus(_) | Method::PaneFocus(_)))+ .collect::<Vec<_>>();+ assert!(+ matches!(methods.as_slice(), [Method::PaneClose(target)] if target.pane_id == "pane_1")+ );+}++#[test]+fn last_pane_close_waits_for_keyboard_or_mouse_confirmation() {+ for menu in [false, true] {+ let mut state = close_state(true, 1);+ let requested = request_close(&mut state, menu);+ assert_no_close(&requested);+ assert!(requested.repaint);+ assert!(matches!(+ state.overlay,+ Some(ClientShellOverlay::ConfirmClose(_))+ ));+ let frame = state.compose(106, 24).unwrap();+ let text = frame_rows(&frame).join("\n");+ assert!(text.contains("Close workspace?"));+ assert!(text.contains("1 pane"));+ let accepted = if menu {+ let primary = state.hits.overlay_primary;+ click(&mut state, primary)+ } else {+ state.handle_input_bytes(b"\r")+ };+ assert_pane_close(&accepted);+ assert!(state.overlay.is_none());+ }+}++#[test]+fn last_pane_close_confirmation_can_be_cancelled() {+ for mouse in [false, true] {+ let mut state = close_state(true, 1);+ assert_no_close(&request_close(&mut state, false));+ assert!(matches!(+ state.overlay,+ Some(ClientShellOverlay::ConfirmClose(_))+ ));+ state.compose(106, 24).unwrap();+ let cancelled = if mouse {+ let cancel = state.hits.overlay_cancel;+ click(&mut state, cancel)+ } else {+ state.handle_input_bytes(b"\x1b")+ };+ assert_no_close(&cancelled);+ assert!(state.overlay.is_none());+ }+}++#[test]+fn pane_close_stays_immediate_with_confirmation_disabled_or_other_tabs() {+ for (confirm, tabs) in [(false, 1), (false, 2), (true, 2)] {+ for menu in [false, true] {+ let mut state = close_state(confirm, tabs);+ assert_pane_close(&request_close(&mut state, menu));+ assert!(state.overlay.is_none());+ }+ }+}++#[test]+fn last_pane_confirmation_preserves_target_across_focus_changes_and_new_tabs() {+ let mut state = close_state(true, 1);+ let mut projected = state.snapshot.as_deref().unwrap().clone();+ let mut other_workspace = projected.workspaces[0].clone();+ other_workspace.workspace_id = "ws_2".into();+ other_workspace.active_tab_id = "other_tab".into();+ other_workspace.focused = false;+ projected.workspaces.push(other_workspace);+ let mut other_tab = projected.tabs[0].clone();+ other_tab.workspace_id = "ws_2".into();+ other_tab.tab_id = "other_tab".into();+ other_tab.focused = false;+ projected.tabs.push(other_tab);+ state.set_snapshot(Box::new(projected.clone()));++ assert_no_close(&request_close(&mut state, false));+ assert!(matches!(+ state.overlay,+ Some(ClientShellOverlay::ConfirmClose(_))+ ));+ let mut new_tab = projected.tabs[0].clone();+ new_tab.tab_id = "new_tab".into();+ new_tab.focused = false;+ projected.tabs.push(new_tab);+ let mut new_pane = projected.panes[0].clone();+ new_pane.pane_id = "new_pane".into();+ new_pane.focused = false;+ projected.panes.push(new_pane);+ projected.focused_pane_id = Some("new_pane".into());+ projected.focused_workspace_id = Some("ws_2".into());+ projected.focused_tab_id = Some("other_tab".into());+ for workspace in &mut projected.workspaces {+ workspace.focused = workspace.workspace_id == "ws_2";+ }+ for tab in &mut projected.tabs {+ tab.focused = tab.tab_id == "other_tab";+ }+ state.set_snapshot(Box::new(projected));+ assert_pane_close(&state.handle_input_bytes(b"\r"));+}++#[test]+fn last_pane_confirmation_rejects_missing_moved_or_reconnected_targets() {+ for change in [+ "missing",+ "moved",+ "reconnected",+ "pane_missing",+ "pane_moved",+ "pane_workspace",+ "endpoint",+ ] {+ let mut state = close_state(true, 1);+ assert_no_close(&request_close(&mut state, false));+ assert!(matches!(+ state.overlay,+ Some(ClientShellOverlay::ConfirmClose(_))+ ));+ let mut projected = state.snapshot.as_deref().unwrap().clone();+ match change {+ "missing" => projected.tabs.clear(),+ "moved" => projected.tabs[0].workspace_id = "different_workspace".into(),+ "reconnected" => state.endpoints[0].snapshot_generation = Some(2),+ "pane_missing" => projected.panes.clear(),+ "pane_moved" => projected.panes[0].tab_id = "different_tab".into(),+ "pane_workspace" => projected.panes[0].workspace_id = "different_workspace".into(),+ "endpoint" => {+ state.active_endpoint_id =+ ClientEndpointId::Ssh(crate::client::endpoint::ProfileId::generate())+ }+ _ => unreachable!(),+ }+ if !matches!(change, "reconnected" | "endpoint") {+ state.set_snapshot(Box::new(projected));+ }+ assert_no_close(&state.handle_input_bytes(b"\r"));+ assert!(state.overlay.is_none());+ }+}++#[test]+fn last_pane_close_preserves_parent_group_and_linked_workspace_scope() {+ for linked in [false, true] {+ let mut state = close_state(true, 1);+ let mut projected = state.snapshot.as_deref().unwrap().clone();+ projected.workspaces[0].worktree = Some(ClientShellWorktree {+ key: "repo".into(),+ label: "repo".into(),+ is_linked_worktree: linked,+ });+ let mut sibling = projected.workspaces[0].clone();+ sibling.workspace_id = "ws_2".into();+ sibling.active_tab_id = "tab_2".into();+ sibling.focused = false;+ sibling.worktree.as_mut().unwrap().is_linked_worktree = !linked;+ projected.workspaces.push(sibling);+ let mut tab = projected.tabs[0].clone();+ tab.tab_id = "tab_2".into();+ tab.workspace_id = "ws_2".into();+ tab.focused = false;+ projected.tabs.push(tab);+ state.set_snapshot(Box::new(projected));++ let close = request_close(&mut state, false);+ if linked {+ assert_no_close(&close);+ assert!(matches!(+ state.overlay,+ Some(ClientShellOverlay::ConfirmClose(_))+ ));+ assert_pane_close(&state.handle_input_bytes(b"\r"));+ } else {+ assert_pane_close(&close);+ assert!(state.overlay.is_none());+ let [ClientShellAction::Endpoint { request, .. }] = close.actions.as_slice() else {+ panic!("tab close request");+ };+ state.handle_endpoint_result(+ "boot-1",+ &request.id,+ Err(ClientShellEndpointError {+ code: Some("confirmation_required".into()),+ message: "closing this tab would close a worktree group".into(),+ }),+ );+ assert!(matches!(state.overlay.as_ref(),+ Some(ClientShellOverlay::ConfirmClose(confirm)) if confirm.title == "Close worktree group?"));+ let accepted = state.handle_input_bytes(b"\r");+ assert!(matches!(accepted.actions.as_slice(),+ [ClientShellAction::Endpoint { request, .. }]+ if matches!(&request.method, Method::WorkspaceClose(params)+ if params.workspace_id == "ws_1" && params.close_group)));+ }+ }+}++#[test]+fn ordinary_pane_close_stays_immediate_with_another_pane() {+ for menu in [false, true] {+ let mut state = close_state(true, 1);+ let mut projected = state.snapshot.as_deref().unwrap().clone();+ let mut pane = projected.panes[0].clone();+ pane.pane_id = "pane_2".into();+ pane.focused = false;+ projected.panes.push(pane);+ state.set_snapshot(Box::new(projected));+ assert_pane_close(&request_close(&mut state, menu));+ assert!(state.overlay.is_none());+ }+}diff --git a/src/client/shell/tests/mod.rs b/src/client/shell/tests/mod.rsindex 9d9da64b4..05bfc263a 100644--- a/src/client/shell/tests/mod.rs+++ b/src/client/shell/tests/mod.rs@@ -247,6 +247,7 @@ fn surface_with_popup() -> PaneSurfaceFrame {mod agents_worktrees_notifications;mod chrome_context;+mod close_pane;mod close_tab;mod copy;mod endpoint_requests;