diff --git a/docs/plans/drawer-session-model.md b/docs/plans/drawer-session-model.md new file mode 100644 index 0000000..53da2e7 --- /dev/null +++ b/docs/plans/drawer-session-model.md @@ -0,0 +1,36 @@ +# Plan: workspaces drawer — stable order, reorder, real move, end-session-without-quit + +Status: PLAN + root-cause evidence (2026-11-20). #127 (merged) only removed the "active session hoisted to top" symptom; it did not fix the model. Nothing below is implemented yet. + +## Owner requirements +1. Drawer rows never rearrange on their own. +2. Reorder sessions and windows-within-a-session by drag and drop AND by keyboard (all surfaces: colon, CLI, RPC, MCP, palette: UNI-R01). +3. Moving a window between sessions works correctly (drag, keyboard, all surfaces). +4. Closing the last window can close the session without terminating bilterm. + +## Root causes (reproduced headlessly on origin/main 3f6c620; throwaway tests, not committed) +R1 — three unrelated orderings, none authoritative. + - `navigator_drawer_rows` (src/wm/drawer/navigator.rs) emits `daemon_state.session_tree.nodes` order, then `list_sessions()` (session_order.toml, then name), then unsaved sessions by name. + - `:session move|reorder` (session_manager.rs:408/447) writes only `session_order.toml`. + - Evidence: after `create_new_session` zeta, alpha: drawer `[zeta, alpha, default]` vs session_order `[default, zeta, alpha]`; `move_session_in_order("alpha","top")` yields order `[alpha, default, zeta]` but the drawer still shows `[zeta, alpha, default]`. So reorder is invisible, and a session changes group (tree -> saved -> unsaved) when it is saved, parked, attached to the tree, or restored, which reads as "rearranging itself". +R2 — window order is not state. `ordered_pane_ids` = `split_tree.leaves()` (live) / pane id sort (parked, navigator.rs push_bg_panes) / BTreeMap id (saved). The live and parked orders differ, split/close/move reshuffles leaves, and there is no Action to reorder windows at all (no Swap/Reorder variant in src/action.rs). +R3 — moving a window into a session that exists only on disk loses that session's windows. `move_window_to_session` (window_manage.rs:395) does `background_sessions.entry(target).or_insert_with(..)` building a `BackgroundSessionState` with EMPTY `panes` (only the saved split_tree/z_order), then the `else` branch resets `split_tree`/`z_stack` to just the moved pane. Repro: other.toml with 2 windows; move window 1 into it with switch=true -> session has 1 pane, expected 3. The next save overwrites other.toml: silent data loss. Parked (live) targets work; the existing test only covers a live target. +R4 — closing the last window of the only session quits. `session_on_empty` defaults to `End`; with no other session `end_active_session_and_move_on` returns None, so `fall_back_to_parked_session` is false and the loops quit via `app.all_panes_exited()` (src/app.rs:248; gui_window.rs:592; gui_font/linux_x11.rs:838; gui_macos.rs:719). `:close` on the only window is already safe (replaces it). `:session on-empty keep` exists but is opt-in, config-only on some surfaces, and the quit decision is duplicated in four loops. +R5 — no drag-and-drop in the drawer: mouse_wm.rs has only window/modal/resize drags; the drawer has `resizing_drag` only. Keyboard reorder exists only as `ops.rs:297` (`move_session_in_order` via menu) and is invisible because of R1. + +## Architecture change +A. One authoritative, persisted session model: `SessionOrder` owned by WindowManager: ordered `Vec` covering live, parked and saved sessions, plus per-session `window_order: Vec`. The drawer, `:session list`, RPC/MCP and tabs ALL read it; session_tree gives grouping only (parent/collapsed), never order. New sessions append; nothing reorders implicitly (save/park/restore/rename keep the slot; rename rewrites it; delete removes it). +B. Window order = explicit `window_order` per session (live and parked share one type; saved TOML gains `window_order`, absent -> legacy leaf order). split/close/move edit it deterministically (new window right after its source; moved window appended). +C. Hydrate before mutate: `move_window_to_session` loads a saved-only target into a full `BackgroundSessionState` (spawn/headless panes per saved layout, same path as switch) or refuses; never builds an empty state. Make move atomic with rollback (extends the `switch_to_session_preserving_panes` rollback pattern). +D. Single exit policy function `WindowManager::should_quit()` replacing the four `all_panes_exited()` checks; default `session_on_empty = keep-last` (keep the final session open and empty instead of quitting; explicit `:quit`/`:session kill` of the last session still quits, headless `-c` runs keep old behavior). `end` remains configurable. +E. New Actions (all surfaces): `SessionMove{name, to: Pos}` (exists, route through the single model), `WindowMove{id, to: Pos}` (within session), `WindowMoveToSession{id, session, index?}`, `DrawerReorder` ops. Drag in drawer lowers to these (GUI wgpu + TUI mouse), with a drop-indicator row and Esc to cancel; keyboard: `Alt+Shift+Up/Down` reorder the selected row, `Alt+Shift+Left/Right` (or `m`) move window to prev/next session; colon `:session move`, `:window move`, `:window send `; RPC `session.move`, `window.move`; MCP tools; palette entries. + +## Milestones (each: tests fail before / pass after; scripts/verify.sh PASS; PR only, owner merges) +- M1 (bug fix, small): R3 hydrate-before-move + data-loss test; R4 `should_quit()` + keep-last default. +- M2 (model): `SessionOrder` + `window_order`, migrate drawer/list/RPC to it; regression tests that no operation (save, park, switch, restore, rename, tree attach) changes row order; old goldens unchanged. +- M3 (surfaces): Window/Session move Actions + colon/CLI/RPC/MCP/palette, keyboard reorder in the drawer. +- M4 (mouse): drag and drop in TUI and GUI incl. cross-session drop onto a session row; selection stays on the moved row. +- M5 (verification): real TUI + X11 GUI drive, Windows/macOS compile. + +## Tests to write first +Order stable across save/park/switch/restore/rename (R1); `session move` visible in drawer (R1); window reorder live and parked agree (R2); move into saved-only session keeps all windows, and on failure the source is untouched (R3); last window of last session exiting keeps bilterm alive and drawer shows an empty session (R4); drag lowers to the same Action as the keyboard path (R5). diff --git a/src/wm/window_manage.rs b/src/wm/window_manage.rs index 3580f2f..8cd315a 100644 --- a/src/wm/window_manage.rs +++ b/src/wm/window_manage.rs @@ -400,7 +400,7 @@ impl WindowManager { ) -> Result { let target_clean = target_session.trim(); validate_session_path(target_clean)?; - let cur_session = self.config.history_session.trim(); + let cur_session = self.config.history_session.trim().to_string(); let target_id = window_id.unwrap_or_else(|| self.active_pane_id()); if target_clean == cur_session { @@ -417,6 +417,10 @@ impl WindowManager { return Err(format!("Window {target_id} not found in active session")); } + // Hydrate a saved-only target into a live parked session BEFORE touching the source, so a + // failure leaves the source session exactly as it was. + self.hydrate_saved_session(target_clean)?; + // Capture single-step undo snapshot before mutating self.capture_topology_undo( &format!("move window {target_id} to session '{target_clean}'"), @@ -527,6 +531,54 @@ impl WindowManager { } } + /// Ensures `target` is a live parked session. A session that exists only as a saved layout is + /// restored through the normal restore path into a full [`BackgroundSessionState`], then the + /// active session is put back. On any failure the active session is untouched. + fn hydrate_saved_session(&mut self, target: &str) -> Result<(), String> { + if self + .window_manage + .background_sessions + .get(target) + .is_some_and(|bg| !bg.panes.is_empty()) + { + return Ok(()); + } + let on_disk = self + .resolve_session_dir() + .map(|d| d.join(format!("{target}.toml")).is_file()) + .unwrap_or(false); + if !on_disk && !self.layout_profiles_mem.contains_key(target) { + // Known by name only (no layout anywhere): the attach below starts it fresh. + return Ok(()); + } + // A stale empty parked entry would block parking the restored panes. + self.window_manage.background_sessions.remove(target); + let cur_session = self.config.history_session.clone(); + let cur_profile = self.config.active_layout_profile.clone(); + self.park_active_session(); + self.config.history_session = target.to_string(); + self.config.active_layout_profile = target.to_string(); + let built = if on_disk { + self.restore_session(target).map_err(|e| e.to_string()) + } else { + self.switch_layout_profile(target).map_err(|e| e.to_string()) + }; + if built.is_err() || self.panes.is_empty() { + self.panes.clear(); + self.activate_parked_session(&cur_session); + self.config.active_layout_profile = cur_profile; + self.reflow_default_viewport(); + return Err(built + .err() + .unwrap_or_else(|| format!("Target session '{target}' has no windows"))); + } + self.park_active_session(); + self.activate_parked_session(&cur_session); + self.config.active_layout_profile = cur_profile; + self.reflow_default_viewport(); + Ok(()) + } + /// Loads a `SavedWorkspaceSession` from in-memory cache or disk if available. pub(crate) fn load_session_snapshot_any(&self, session: &str) -> Option { let clean = sanitize_profile_name(session); diff --git a/src/wm/window_manage_bulk.rs b/src/wm/window_manage_bulk.rs index a7a7dd9..70a63c2 100644 --- a/src/wm/window_manage_bulk.rs +++ b/src/wm/window_manage_bulk.rs @@ -460,7 +460,7 @@ impl WindowManager { /// Makes the parked session `name` the active one; `false` when no live session is parked /// under that name. The caller parks the outgoing session first. - fn activate_parked_session(&mut self, name: &str) -> bool { + pub(crate) fn activate_parked_session(&mut self, name: &str) -> bool { let Some(bg) = self.window_manage.background_sessions.remove(name) else { return false; }; diff --git a/tests/session_move_saved_target.rs b/tests/session_move_saved_target.rs new file mode 100644 index 0000000..58b9718 --- /dev/null +++ b/tests/session_move_saved_target.rs @@ -0,0 +1,109 @@ +//! Moving a window into a session that exists only on disk must keep that session's windows +//! (drawer plan R3) and must be atomic: on failure the source session is untouched. + +use std::sync::Mutex; + +use bilterm::wm::split_tree::SplitDirection; +use bilterm::wm::WindowManager; + +static ENV_LOCK: Mutex<()> = Mutex::new(()); + +fn isolated(f: impl FnOnce(&std::path::Path) -> T) -> T { + let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = tempfile::tempdir().unwrap(); + unsafe { + std::env::set_var("XDG_CONFIG_HOME", dir.path()); + std::env::set_var("XDG_STATE_HOME", dir.path()); + } + f(dir.path()) +} + +fn headless(dir: &std::path::Path) -> WindowManager { + let mut wm = WindowManager::new_headless(24, 80); + wm.config_mut().session_dir = Some(dir.join("sessions").to_string_lossy().into_owned()); + wm +} + +fn mark(wm: &mut WindowManager, id: usize, text: &str) { + wm.pane_mut(id).unwrap().process_pty_output(format!("{text}\r\n").as_bytes()); +} + +/// Saves a 2-window session `name` to disk only. +fn save_two_window_session(dir: &std::path::Path, name: &str) { + let mut other = headless(dir); + other.split_focused(SplitDirection::Vertical).unwrap(); + assert_eq!(other.pane_count(), 2); + other.save_session(name).unwrap(); +} + +/// Source "default" with two windows (so moving one leaves it non-empty). +fn source_with_two(dir: &std::path::Path) -> WindowManager { + let mut wm = headless(dir); + mark(&mut wm, 1, "SRC_ONE"); + wm.split_focused(SplitDirection::Vertical).unwrap(); + wm +} + +fn saved_pane_count(dir: &std::path::Path, name: &str) -> usize { + let mut probe = headless(dir); + probe.restore_session(name).unwrap() +} + +#[test] +fn saved_only_target_keeps_all_windows_with_switch() { + isolated(|dir| { + save_two_window_session(dir, "other"); + let mut wm = source_with_two(dir); + wm.move_window_to_session(Some(1), "other", true).unwrap(); + assert_eq!(wm.config().history_session, "other"); + assert_eq!(wm.pane_count(), 3, "saved windows were lost"); + assert_eq!(wm.window_manage().background_sessions["default"].panes.len(), 1); + }); +} + +#[test] +fn saved_only_target_keeps_all_windows_without_switch() { + isolated(|dir| { + save_two_window_session(dir, "other"); + let mut wm = source_with_two(dir); + wm.move_window_to_session(Some(1), "other", false).unwrap(); + assert_eq!(wm.config().history_session, "default"); + assert_eq!(wm.pane_count(), 1); + assert_eq!(wm.window_manage().background_sessions["other"].panes.len(), 3); + // Saving the target afterwards must not shrink it on disk. + wm.switch_or_create_session("other").unwrap(); + wm.save_session("other").unwrap(); + assert_eq!(saved_pane_count(dir, "other"), 3); + }); +} + +#[test] +fn failed_hydration_leaves_source_intact() { + isolated(|dir| { + save_two_window_session(dir, "newer"); + let path = dir.join("sessions").join("newer.toml"); + let text = std::fs::read_to_string(&path).unwrap(); + let version = text.lines().find(|l| l.starts_with("format_version")).unwrap(); + std::fs::write(&path, text.replace(version, "format_version = 9999")).unwrap(); + + let mut wm = source_with_two(dir); + assert!(wm.move_window_to_session(Some(1), "newer", true).is_err()); + assert_eq!(wm.config().history_session, "default"); + assert_eq!(wm.pane_count(), 2, "source lost its window"); + assert!(wm.pane(1).unwrap().vt().snapshot().contents().contains("SRC_ONE")); + assert!(wm.window_manage().background_sessions.is_empty()); + }); +} + +#[test] +fn live_target_behavior_unchanged() { + isolated(|dir| { + let mut wm = headless(dir); + wm.create_new_session(Some("b"), false).unwrap(); + wm.split_focused(SplitDirection::Vertical).unwrap(); + // active "b" has 2 panes; "default" is parked with 1. + wm.move_window_to_session(Some(2), "default", false).unwrap(); + assert_eq!(wm.pane_count(), 1); + assert_eq!(wm.window_manage().background_sessions["default"].panes.len(), 2); + }); +}