From 97db53aabdbeee08e78c58858450f8cdbb4e5685 Mon Sep 17 00:00:00 2001 From: Angel-Mario Savin Date: Mon, 2 Nov 2026 13:56:01 +0200 Subject: [PATCH] Close a session when its process ends and leave its worktree --- src/app/headless.rs | 118 +++++++++++++++++++++++++++++++++++ src/app/sessions.rs | 25 ++++---- src/panels/workspace_view.rs | 34 +--------- 3 files changed, 133 insertions(+), 44 deletions(-) diff --git a/src/app/headless.rs b/src/app/headless.rs index 1eaa57b..9222096 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -1610,3 +1610,121 @@ fn a_missing_claude_offers_the_setup_window() { } assert_eq!(cx.update(|app| app.windows().len()), 2, "the workspace and one setup window"); } + +/// A process that ends by itself closes the session the way the X does. A clean exit says nothing, a non-zero +/// exit is a toast, and the worktree stays: Claude Code already asked on `/exit`, and the X is the path that offers. +#[test] +fn a_process_that_ends_closes_the_session_and_leaves_its_worktree() { + let data = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let work = tempfile::tempdir().unwrap(); + let repo_dir = dunce::canonicalize(work.path()).unwrap().join("proj"); + let git = |args: &[&str]| std::process::Command::new("git").args(args).current_dir(&repo_dir).output().unwrap(); + std::fs::create_dir_all(&repo_dir).unwrap(); + for args in [&["init", "-q", "-b", "main"][..], &["config", "user.email", "t@t"], &["config", "user.name", "t"], &["commit", "-q", "--allow-empty", "-m", "one"]] { + git(args); + } + let folder = crate::git::worktree::folder(&repo_dir, "fix"); + let added = git(&["worktree", "add", "-q", "-b", "worktree-fix", &folder.to_string_lossy()]); + assert!(added.status.success(), "{}", String::from_utf8_lossy(&added.stderr)); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![repo_dir.clone()], cx)))) + .unwrap(); + let project = ws.read_with(&cx, |ws, _| ws.store.data.projects[0].id.clone()); + let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + }; + let exit_spec = |code: i32| -> SpawnSpec { + let args = if cfg!(windows) { + vec!["/c".into(), format!("exit {code}")] + } else { + vec!["-c".into(), format!("exit {code}")] + }; + SpawnSpec { program: if cfg!(windows) { "cmd.exe" } else { "/bin/sh" }.into(), args, cwd: Some(folder.clone()), ..Default::default() } + }; + let start_one = |cx: &mut TestAppContext, title: &str, spec: SpawnSpec| -> String { + let title = title.to_string(); + let id = new_id(); + let record = SessionRecord { + id: id.clone(), + kind: SessionKind::Claude, + title, + custom_title: None, + auto_title: None, + project_id: Some(project.clone()), + cwd: folder.clone(), + created_at: now(), + last_active: now(), + exit_code: None, + hidden: false, + // Present, so closing it keeps the history record instead of treating it as an empty new session. + claude: Some(ClaudeMeta { session_id: id.clone(), external: ExternalState::Present, ..Default::default() }), + }; + step(cx, &|ws, w, cx| ws.start(record.clone(), spec.clone(), true, w, cx)); + id + }; + // Pump until the view is gone. A late removal dialog is spawned off the UI thread, so keep going after the close. + let until_closed = |cx: &mut TestAppContext, id: &str| { + let started = std::time::Instant::now(); + loop { + step(cx, &|_, _, _| {}); + let gone = ws.read_with(cx, |ws, _| ws.live_view(id).is_none()); + if gone { + let rest = std::time::Instant::now(); + while rest.elapsed() < Duration::from_secs(1) { + step(cx, &|_, _, _| {}); + cx.executor().advance_clock(Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); + let offered = ws.read_with(cx, |ws, _| ws.modal.is_some()); + assert!(!offered, "a process that ended by itself offered to remove the worktree"); + } + return; + } + assert!(started.elapsed() < Duration::from_secs(10), "the session stayed open after its process ended"); + cx.executor().advance_clock(Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); + } + }; + + let clean = start_one(&mut cx, "Fix login", exit_spec(0)); + until_closed(&mut cx, &clean); + let (code, toast) = ws.read_with(&cx, |ws, _| (ws.store.session(&clean).map(|s| s.exit_code), ws.toast.as_ref().map(|t| t.text.clone()))); + assert_eq!(code, Some(Some(0)), "a clean exit is kept on the history record"); + assert_eq!(toast, None, "a clean exit says nothing"); + assert!(folder.exists(), "the worktree stays"); + + let bad = start_one(&mut cx, "Broken", exit_spec(1)); + until_closed(&mut cx, &bad); + let (code, toast) = ws.read_with(&cx, |ws, _| (ws.store.session(&bad).map(|s| s.exit_code), ws.toast.as_ref().map(|t| t.text.clone()))); + assert_eq!(code, Some(Some(1))); + assert_eq!(toast.as_deref(), Some("Broken ended (exit code 1)")); + + let missing = new_id(); + let record = SessionRecord { + id: missing.clone(), + kind: SessionKind::Claude, + title: "Missing".into(), + custom_title: None, + auto_title: None, + project_id: Some(project), + cwd: folder.clone(), + created_at: now(), + last_active: now(), + exit_code: None, + hidden: false, + claude: Some(ClaudeMeta { session_id: missing.clone(), external: ExternalState::Present, ..Default::default() }), + }; + let spec = SpawnSpec { program: "definitely-not-a-real-program-claudiu".into(), args: vec![], cwd: Some(folder), ..Default::default() }; + step(&mut cx, &|ws, w, cx| ws.start(record.clone(), spec.clone(), true, w, cx)); + until_closed(&mut cx, &missing); + let toast = ws.read_with(&cx, |ws, _| ws.toast.as_ref().map(|t| t.text.clone())); + assert!(toast.as_deref().is_some_and(|t| t.starts_with("Could not start Missing:")), "{toast:?}"); +} diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 561c290..b31040f 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -342,21 +342,22 @@ impl Workspace { self.recent.push(id.clone()); } - fn on_exit(&mut self, id: &str, code: Option, _window: &mut Window, cx: &mut Context) { - if let Some(err) = self.live_view(id).and_then(|v| v.read(cx).start_error()) { - let program = self.store.session(id).map(|r| r.display_title().to_string()).unwrap_or_default(); - self.toast(format!("Could not start {program}: {err}"), true, cx); - } - if self.logins.remove(id) { - self.refresh_accounts(cx); - } + /// The process ended by itself. Close the session the way the X does, so the terminal does not stay up behind a + /// "Session ended" bar. A non-zero exit is a toast, because that output goes away with the view; a clean exit + /// says nothing. This does not offer to remove a worktree: `/exit` already asked inside Claude Code, and the X + /// (`close_live`) is the path that kills the process before that prompt. + fn on_exit(&mut self, id: &str, code: Option, window: &mut Window, cx: &mut Context) { + let start_error = self.live_view(id).and_then(|v| v.read(cx).start_error()); + let title = self.store.session(id).map(|r| r.display_title().to_string()).unwrap_or_else(|| "Session".into()); if let Some(rec) = self.store.session_mut(id) { rec.exit_code = Some(code.unwrap_or(0)); - rec.last_active = now(); } - self.drop_if_empty(id); - self.store.save_if_dirty(); - cx.notify(); + self.end_live(id, window, cx); + if let Some(err) = start_error { + self.toast(format!("Could not start {title}: {err}"), true, cx); + } else if let Some(code) = code.filter(|c| *c != 0) { + self.toast(format!("{title} ended (exit code {code})"), true, cx); + } } /// Clicking a session: running -> show its terminal; past -> open it right away (no intermediate page). diff --git a/src/panels/workspace_view.rs b/src/panels/workspace_view.rs index befd3a5..4c03fc8 100644 --- a/src/panels/workspace_view.rs +++ b/src/panels/workspace_view.rs @@ -187,39 +187,10 @@ impl Workspace { // ------------------------------------------------------------------ the shown session - fn render_session(&mut self, cx: &mut Context) -> AnyElement { + fn render_session(&mut self, _cx: &mut Context) -> AnyElement { let blank = || div().size_full().bg(hsla(theme::TERMINAL_BG)).into_any_element(); let Some(id) = self.active.clone() else { return blank() }; let Some(term) = self.live_view(&id).cloned() else { return blank() }; - let rec = self.store.session(&id).cloned(); - let exit = term.read(cx).exit_code; - let is_claude = rec.as_ref().is_some_and(|r| r.kind == SessionKind::Claude); - let rid = id.clone(); - - let banner = exit.map(|code| { - let label = match code { - Some(0) | None => "Session ended".to_string(), - Some(c) => format!("Session ended (exit code {c})"), - }; - div() - .absolute() - .bottom(px(12.0)) - .left(px(12.0)) - .right(px(12.0)) - .flex() - .items_center() - .justify_between() - .px(px(12.0)) - .py(px(8.0)) - .rounded(px(8.0)) - .bg(hsla(0x181818)) - .border_1() - .border_color(hsla(0x2a2a2a)) - .child(div().text_size(crate::panels::scale::px(12.5)).text_color(hsla(theme::TEXT_DIM)).child(label)) - .children(is_claude.then(|| { - button("ended-act", "Resume", true).on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::Resume(rid.clone()), window, cx))) - })) - }); let pane = fade_in( div() @@ -231,8 +202,7 @@ impl Workspace { .min_w_0() .min_h_0() .bg(hsla(theme::TERMINAL_BG)) - .child(div().flex_1().min_h_0().p(px(6.0)).child(term)) - .children(banner), + .child(div().flex_1().min_h_0().p(px(6.0)).child(term)), format!("pane-in-{id}"), 150, 0.4,