From 156c75834363ca91ae8ee981ffde684f586dc59a Mon Sep 17 00:00:00 2001 From: hishboy Date: Fri, 4 Sep 2026 11:48:58 +0000 Subject: [PATCH] fix(sidebar): keep the focus window unique Signed-off-by: hishboy --- CHANGELOG.md | 3 + DECISIONS.md | 1 + .../crates/chief-cli/src/sidebar/effects.rs | 344 ++++++++-- .../crates/chief-cli/src/sidebar/tests.rs | 590 +++++++++++++++++- 4 files changed, 891 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3356e9..8563489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +- **fix(sidebar): one failed focus-window census can no longer freeze every company action.** The permanent focus window was created after a client-side read: two sidebar owners could both observe absence, and a tmux error was also indistinguishable from absence. Both paths could mint `__focus__` twice. The actuator then correctly failed closed on the ambiguous topology before step zero, which left new people at `starting` and kept settled people on the glass. + **Creation is now decided inside tmux's serialized command queue.** The create, ownership tags, and parked-notice tag are one guarded batch. A stale or empty client read therefore resolves to the winner instead of creating a second window. Sessions already in the broken state self-repair only by removing an inactive window proved, again at the mutation boundary, to contain exactly Chief's rail and parked notice; an active, person-owned, unknown, or changed window is never deleted. Live-tmux tests pin simultaneous creation, a failed census, the observed two-inactive-window incident, active-window choice, unknown state, and both sides of the delete race. + - **fix(sidebar): the rail is built with the cursor and hands it straight back.** A bare `chief` opened the company with the cursor in the sidebar instead of in the person's pane, so the first thing the operator typed went to furniture. Both rail-mint sites — the attach frame (`attach.rs::rail_mint_argv`) and the actuator's repair batch (`actuate/interpret.rs`) — run `split-window` with no `-d`, which is deliberate: every write that follows names a WINDOW, and tmux resolves a window target to its active pane, so the new rail must be active while it is tagged and resized. The frame therefore ends, and only ends, with `select-pane -l` at that window: the last pane, which a split makes the pane that was active before it — measured on tmux 3.7c, and true even when the split targeted some other pane, so the cursor returns to the operator and never to the split target. Pinned at both sites by an argv test that fails if the selection is dropped or moved ahead of the tag, and by two REAL-tmux tests that ask the server which pane is active after the frame runs (`a_real_rail_mint_leaves_the_person_pane_active`, `real_rail_repair_leaves_the_person_pane_active_and_not_the_rail`). Both were run as controls with the selection removed and both fail there, reporting the rail as the active pane — which is the operator's report reproduced exactly. diff --git a/DECISIONS.md b/DECISIONS.md index 11e58ca..3a78ce9 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -112,3 +112,4 @@ - 2026-08-25 — The licence is Apache-2.0, single: not MIT, not MIT/Apache dual, not source-available, and with a DCO rather than a CLA. The Rust dependency licence allowlist is permissive-only and names no denials. `apps/web` ships MARKED as a non-working example rather than deleted — it is the only worked example of the second host the daemon/client split exists for, so deleting the broken app destroys the reference implementation of the hardest part of the architecture. Relicensing costs nothing today with one rights holder and needs unanimous consent the moment there is a second contributor. Enforced by the LICENSE and NOTICE files and by `apps/chiefd/deny.toml`; there is no test, and this is the one entry that does not name one, deliberately — the decision is about a legal instrument, not about code behaviour. - 2026-08-25 — CHANGELOG.md and DECISIONS.md start FRESH in the public tree, and the private ledger is archived rather than published. Those two files had grown to about 16,800 lines of internal narrative — detailed incident write-ups, named hosts, and roughly thirty-six leaked machine names — written for the people who were in the room. The rejected alternative was a mass rewording of shipped entries through the `doc-append-only` guard's per-entry exception registry, which would have taught every future contributor that an append-only file may be reworded when the reason seems good enough. That is a repeal of the rule, not an exception to it. The same philosophy as the `plans/` ruling, applied to the same kind of content: the history is kept, and it is kept private. What still BINDS the code is carried forward as new dated entries below; `CLAUDE.md` and `AGENTS.md` already carry the organization model, the operator wake lease and the placement rule, and duplicating them here would create two sources for one rule. The guard treats this as a ONE-TIME reset, detected by the first line of this entry and of the changelog's, so ordinary append-only resumes from the very next commit with no exception left behind to rot. - 2026-09-03 — The sidebar rail is furniture and never takes the operator's cursor. It is minted active on purpose — the tag and the resize that follow the split name a WINDOW, which tmux resolves to the active pane — so every mint frame ends with `select-pane -l`, restoring the pane that was active before the split. The rejected alternative was `split-window -d`, which cannot work without a second tmux invocation to name the pane the split has not reported yet, and a rail that is observable untagged is the gap that once put two rails in one window. Pinned by `the_rail_frame_hands_the_cursor_back_after_every_other_write` and `a_real_rail_mint_leaves_the_person_pane_active` (`attach.rs`) and by `a_repaired_rail_gives_the_cursor_back_after_it_is_tagged` and `real_rail_repair_leaves_the_person_pane_active_and_not_the_rail` (`actuate/interpret/tests.rs`). +- 2026-09-04 — A session has one permanent focus window, and its creation decision belongs to tmux's serialized command queue; an unreadable client census is never authority to create a duplicate. Recovery may delete only an inactive focus window proved at the mutation boundary to contain Chief's exact parked rail and notice, while active, person-owned, unknown, or changed content remains fail-closed. Pinned by `concurrent_real_tmux_focus_ensures_mint_one_window`, `an_empty_client_census_cannot_duplicate_an_existing_real_focus_window`, `a_real_inactive_duplicate_made_only_of_focus_furniture_is_repaired`, `a_real_duplicate_with_unknown_local_state_is_left_for_fail_closed_planning`, `a_duplicate_that_changes_after_snapshot_is_not_deleted`, and `a_keeper_that_changes_after_snapshot_preserves_the_other_focus_window` (`sidebar/tests.rs`). diff --git a/apps/chiefd/crates/chief-cli/src/sidebar/effects.rs b/apps/chiefd/crates/chief-cli/src/sidebar/effects.rs index 59033a6..99836b7 100644 --- a/apps/chiefd/crates/chief-cli/src/sidebar/effects.rs +++ b/apps/chiefd/crates/chief-cli/src/sidebar/effects.rs @@ -240,6 +240,15 @@ pub fn window_department_id(tmux: &dyn Tmux, pane_id: &str) -> Option { /// department mints none at all (`placement.rs`'s empty-department rule), and a /// department whose people all stopped loses its window the same way. pub fn department_window(tmux: &dyn Tmux, session: &str, department_id: &str) -> Option { + department_windows(tmux, session, department_id).into_iter().next() +} + +/// Every tmux window carrying one logical window id. +/// +/// Most callers require one answer and use [`department_window`]. The focus +/// owner must see the complete set: taking the first duplicate hides the exact +/// topology that makes the actuator fail closed. +fn department_windows(tmux: &dyn Tmux, session: &str, department_id: &str) -> Vec { tmux.run(&[ "list-windows", "-t", @@ -249,8 +258,10 @@ pub fn department_window(tmux: &dyn Tmux, session: &str, department_id: &str) -> ]) .lines() .filter_map(|line| line.split_once('\t')) - .find(|(_, logical)| logical.trim() == department_id) + .filter(|(_, logical)| logical.trim() == department_id) .map(|(window, _)| window.trim().to_owned()) + .filter(|window| window.starts_with('@')) + .collect() } /// A run of tmux WRITES issued as one invocation. @@ -2185,6 +2196,28 @@ fn local_focus_panes( tmux: &dyn Tmux, session: &str, organization: &str, +) -> Option> { + let focus = local_focus_scope(tmux, session, organization)?; + if focus.len() != 2 + || focus.iter().any(|pane| { + pane.window != focus[0].window + || pane.session_id != focus[0].session_id + || pane.window_panes != "2" + }) + { + return None; + } + Some(focus) +} + +/// Every pane in every fully and locally owned focus window. +/// +/// A caller gets no partial answer. One unreadable pane, one inherited window +/// tag, or one foreign scope makes the whole observation unusable. +fn local_focus_scope( + tmux: &dyn Tmux, + session: &str, + organization: &str, ) -> Option> { let listed = tmux.run(&["list-panes", "-s", "-t", session, "-F", "#{pane_id}"]); let pane_ids = @@ -2254,15 +2287,6 @@ fn local_focus_panes( focus.push(snapshot); } } - if focus.len() != 2 - || focus.iter().any(|pane| { - pane.window != focus[0].window - || pane.session_id != focus[0].session_id - || pane.window_panes != "2" - }) - { - return None; - } Some(focus) } @@ -2280,6 +2304,7 @@ fn clean_focus_rail(pane: &LocalFocusPane) -> bool { tags::WAKING_DESIRED_SEEN, tags::MINTING, tags::SLEEPING_PERSON, + tags::DEPARTMENT_CARD, WAKING_RECOVERY_READY, ] .iter() @@ -2380,6 +2405,14 @@ fn exact_local_option_shell(scope: &str, target: &str, option: &str, value: &str ) } +fn exact_local_user_option_count_shell(scope: &str, target: &str, count: usize) -> String { + let scope = if scope.is_empty() { String::new() } else { format!(" {scope}") }; + format!( + "tmux show-options{scope} -t {} 2>/dev/null | awk '$1 ~ /^@/ {{ found++ }} END {{ exit found == {count} ? 0 : 1 }}'", + shell_word(target), + ) +} + fn probe_absent_local_option( probes: &mut Batch, cleanup: &mut Batch, @@ -2963,7 +2996,12 @@ pub struct Parked<'a> { /// Called on every company read, which is off the click path. Answers the /// window, or `None` when tmux would not mint one. pub fn ensure_focus_window(tmux: &dyn Tmux, session: &str, parked: &Parked) -> Option { - let Some(window) = department_window(tmux, session, FOCUS_WINDOW_ID) else { + let mut windows = department_windows(tmux, session, FOCUS_WINDOW_ID); + if windows.len() > 1 { + let window = repair_duplicate_focus_windows(tmux, session, parked.organization, &windows)?; + windows = vec![window]; + } + let Some(window) = windows.into_iter().next() else { let canonical = canonical_geometry(tmux, session); return mint_parked_focus_window(tmux, session, parked, canonical); }; @@ -3008,6 +3046,226 @@ pub fn ensure_focus_window(tmux: &dyn Tmux, session: &str, parked: &Parked) -> O Some(window) } +#[derive(Clone, Copy)] +enum FocusFurniture { + Rail, + Notice, +} + +fn focus_furniture(pane: &LocalFocusPane) -> Option { + let rail_options = BTreeMap::from([(tags::SIDEBAR.to_owned(), "1".to_owned())]); + if clean_focus_rail(pane) && pane.pane_options == rail_options { + return Some(FocusFurniture::Rail); + } + let notice_options = BTreeMap::from([(tags::ASLEEP.to_owned(), FOCUS_WINDOW_ID.to_owned())]); + (pane.pane_options == notice_options).then_some(FocusFurniture::Notice) +} + +/// Repair the old check-then-mint race, but only where every removed byte is +/// proven to be disposable focus furniture. +fn repair_duplicate_focus_windows( + tmux: &dyn Tmux, + session: &str, + organization: &str, + observed: &[String], +) -> Option { + let panes = local_focus_scope(tmux, session, organization)?; + let mut by_window = BTreeMap::>::new(); + for pane in &panes { + by_window.entry(pane.window.clone()).or_default().push(pane); + } + let observed = observed.iter().cloned().collect::>(); + if by_window.keys().cloned().collect::>() != observed { + return None; + } + + let mut removable = BTreeSet::new(); + let mut non_removable = BTreeSet::new(); + let mut active = BTreeSet::new(); + for (window, panes) in &by_window { + let expected = panes.len().to_string(); + let exact_window_options = BTreeMap::from([ + (tags::ORGANIZATION.to_owned(), organization.to_owned()), + (tags::WINDOW.to_owned(), FOCUS_WINDOW_ID.to_owned()), + ]); + let roles = panes.iter().map(|pane| focus_furniture(pane)).collect::>>(); + let exact_count = !panes.is_empty() + && panes.iter().all(|pane| pane.window_panes == expected) + && panes.iter().all(|pane| pane.window_options == exact_window_options) + && roles.as_ref().is_some_and(|roles| { + roles.iter().filter(|role| matches!(role, FocusFurniture::Notice)).count() == 1 + && roles.iter().filter(|role| matches!(role, FocusFurniture::Rail)).count() == 1 + }); + let active_read = tmux.run(&["display-message", "-p", "-t", window, "#{window_active}"]); + match active_read.trim() { + "0" => { + if exact_count { + removable.insert(window.clone()); + } else { + non_removable.insert(window.clone()); + } + } + "1" => { + active.insert(window.clone()); + if exact_count { + removable.insert(window.clone()); + } else { + non_removable.insert(window.clone()); + } + } + _ => return None, + } + } + if active.len() > 1 { + return None; + } + let keeper = if let Some(active) = active.into_iter().next() { + if observed.iter().any(|window| window != &active && !removable.contains(window)) { + return None; + } + active + } else if non_removable.len() == 1 { + non_removable.into_iter().next()? + } else if non_removable.is_empty() { + removable + .iter() + .filter_map(|window| { + window.strip_prefix('@')?.parse::().ok().map(|id| (id, window)) + }) + .min_by_key(|(id, _)| *id) + .map(|(_, window)| window.clone())? + } else { + return None; + }; + for window in observed.iter().filter(|window| **window != keeper) { + if !removable.contains(window) + || !kill_duplicate_focus_furniture( + tmux, + session, + organization, + &keeper, + window, + by_window.get(window)?, + ) + { + return None; + } + } + let remaining = department_windows(tmux, session, FOCUS_WINDOW_ID); + if remaining != [keeper.clone()] { + return None; + } + tracing::warn!( + event = "sidebar.focus.duplicates.repaired", + session, + keeper = %keeper, + observed = ?observed, + "removed duplicate focus windows contained only exact parked furniture; inactive \ + duplicates were repaired before the next actuator plan" + ); + Some(keeper) +} + +fn kill_duplicate_focus_furniture( + tmux: &dyn Tmux, + session: &str, + organization: &str, + keeper: &str, + window: &str, + panes: &[&LocalFocusPane], +) -> bool { + let generation = invalidate_viewport_topology(tmux, session); + let Some(generation) = generation else { return false }; + let success = format!("chief-focus-duplicate-reaped:{}", uuid::Uuid::new_v4().simple()); + let equals = + |field: &str, value: &str| format!("#{{==:#{{{field}}},{}}}", super::tmux_static(value)); + let and = |left: String, right: String| format!("#{{&&:{left},{right}}}"); + let mut action = Batch::new(); + action.push(&["kill-window", "-t", window]); + action.push(&["display-message", "-p", "-t", session, &success]); + let expected = panes.len().to_string(); + for pane in panes.iter().rev() { + let Some(role) = focus_furniture(pane) else { + refresh_viewport_topology(tmux, session, &generation); + return false; + }; + let (sidebar, asleep) = match role { + FocusFurniture::Rail => ("1", ""), + FocusFurniture::Notice => ("", FOCUS_WINDOW_ID), + }; + let predicate = [ + equals("session_id", &pane.session_id), + equals("window_id", window), + equals("window_active", "0"), + equals("window_panes", &expected), + equals("pane_id", &pane.pane), + equals("pane_pid", &pane.pid), + equals("pane_dead", "0"), + equals(tags::ORGANIZATION, organization), + equals(tags::WINDOW, FOCUS_WINDOW_ID), + equals(tags::SIDEBAR, sidebar), + equals(tags::ASLEEP, asleep), + equals(tags::PERSON, ""), + equals(tags::LAUNCH_HASH, ""), + equals(tags::WAKING_PERSON, ""), + equals(tags::WAKE_CLAIM, ""), + equals(tags::WAKING_PENDING, ""), + equals(tags::WAKING_DESIRED_SEEN, ""), + equals(tags::MINTING, ""), + equals(tags::SLEEPING_PERSON, ""), + equals(tags::DEPARTMENT_CARD, ""), + ] + .into_iter() + .rev() + .reduce(|right, left| and(left, right)); + let Some(predicate) = predicate else { + refresh_viewport_topology(tmux, session, &generation); + return false; + }; + let mut guarded = Batch::new(); + guarded.push(&[ + "if-shell", + "-F", + "-t", + &pane.pane, + &predicate, + &action.command_string(), + "", + ]); + action = guarded; + } + // The keeper is part of the mutation boundary too. If it stops being this + // company's focus window after selection, deleting another focus window + // can remove the last valid candidate. The server must refuse that stale + // repair and let the next pass take a new snapshot. + let local_scope = [ + exact_local_option_shell("", &panes[0].session_id, tags::ORGANIZATION, organization), + exact_local_option_shell("-w", keeper, tags::ORGANIZATION, organization), + exact_local_option_shell("-w", keeper, tags::WINDOW, FOCUS_WINDOW_ID), + exact_local_option_shell("-w", window, tags::ORGANIZATION, organization), + exact_local_option_shell("-w", window, tags::WINDOW, FOCUS_WINDOW_ID), + exact_local_user_option_count_shell("-w", window, 2), + ] + .into_iter() + .chain(panes.iter().flat_map(|pane| { + let (option, value) = match focus_furniture(pane) { + Some(FocusFurniture::Rail) => (tags::SIDEBAR, "1"), + Some(FocusFurniture::Notice) => (tags::ASLEEP, FOCUS_WINDOW_ID), + None => (tags::PERSON, "__never__"), + }; + [ + exact_local_option_shell("-p", &pane.pane, option, value), + exact_local_user_option_count_shell("-p", &pane.pane, 1), + ] + })) + .collect::>() + .join(" && "); + let output = + tmux.run(&["if-shell", "-t", &panes[0].pane, &local_scope, &action.command_string(), ""]); + refresh_viewport_topology(tmux, session, &generation); + output.lines().any(|line| line.trim() == success) +} + /// One live focus-pane snapshot. Every non-rail body counts as furnishing, /// including a pane between process spawn and identity publication. fn focus_pane_snapshot(tmux: &dyn Tmux, window: &str) -> Vec<(String, bool)> { @@ -3379,22 +3637,38 @@ fn mint_parked_focus_window( ) -> Option { let last = format!("{session}:$"); let topology_generation = invalidate_viewport_topology(tmux, session)?; + let mut mint = Batch::new(); + mint.push(&[ + "new-window", + "-d", + "-a", + "-n", + PARKED_WINDOW_NAME, + "-t", + &last, + "-P", + "-F", + "#{window_id}", + "sh", + "-c", + &parked_script(), + ]); + // Identity is part of the create queue. The window cannot be visible as a + // candidate between these commands, and the first pane cannot be mistaken + // for a person before its furniture tag arrives. + mint.push(&["set-option", "-w", "-t", &last, tags::ORGANIZATION, parked.organization]); + mint.push(&["set-option", "-w", "-t", &last, tags::WINDOW, FOCUS_WINDOW_ID]); + mint.push(&["set-option", "-p", "-t", &last, tags::ASLEEP, FOCUS_WINDOW_ID]); + + // THE SERVER-SIDE CREATE-IF-ABSENT. A client-side list followed by + // `new-window` lets two rail processes both observe absence. Tmux evaluates + // this loop and, when it is empty, runs the complete mint in one command + // queue. A competing queue then sees the first window's logical tag and + // takes the empty branch. + let matches = ["#{W:#{?#{==:#{", tags::WINDOW, "},", FOCUS_WINDOW_ID, "},1,}}"].concat(); + let absent = format!("#{{==:{matches},}}"); let window = tmux - .run(&[ - "new-window", - "-d", - "-a", - "-n", - PARKED_WINDOW_NAME, - "-t", - &last, - "-P", - "-F", - "#{window_id}", - "sh", - "-c", - &parked_script(), - ]) + .run(&["if-shell", "-F", "-t", session, &absent, &mint.command_string(), ""]) .lines() .next() .map(str::trim) @@ -3402,23 +3676,9 @@ fn mint_parked_focus_window( .map(ToOwned::to_owned); let Some(window) = window else { refresh_viewport_topology(tmux, session, &topology_generation); - return None; + let windows = department_windows(tmux, session, FOCUS_WINDOW_ID); + return (windows.len() == 1).then(|| windows[0].clone()); }; - tmux.run(&[ - "set-option", - "-w", - "-t", - &window, - tags::ORGANIZATION, - parked.organization, - ";", - "set-option", - "-w", - "-t", - &window, - tags::WINDOW, - FOCUS_WINDOW_ID, - ]); // The window's ONE pane is the notice `new-window` just started. It carries // no person tag and never will: it is furniture, and the converge audit must // read it as furniture rather than adopting it as somebody. diff --git a/apps/chiefd/crates/chief-cli/src/sidebar/tests.rs b/apps/chiefd/crates/chief-cli/src/sidebar/tests.rs index fa4d35d..f1a357a 100644 --- a/apps/chiefd/crates/chief-cli/src/sidebar/tests.rs +++ b/apps/chiefd/crates/chief-cli/src/sidebar/tests.rs @@ -2951,7 +2951,7 @@ fn a_stale_focus_mint_uses_the_active_window_and_keeps_the_rail_at_26() { let tmux = RecordingTmux::answering(&[ ("list-windows -t org-acme_", "@0\texecutive"), ("display-message -p -t org-acme_ -F #{window_width}", "240\t55\texecutive"), - ("new-window -d", "@7"), + ("'new-window' '-d'", "@7"), ("list-panes -t @7", "%80\t\t0"), (COLUMNS_OPTION, "26"), ("split-window -h -b -l 26", "%90"), @@ -2965,7 +2965,7 @@ fn a_stale_focus_mint_uses_the_active_window_and_keeps_the_rail_at_26() { assert_eq!(effects::ensure_focus_window(&tmux, "org-acme_", &parked), Some("@7".into())); let calls = tmux.calls(); - assert_eq!(calls.iter().filter(|call| call.starts_with("new-window")).count(), 1); + assert_eq!(calls.iter().filter(|call| call.contains("new-window")).count(), 1); assert_eq!(calls.iter().filter(|call| call.starts_with("split-window")).count(), 1); assert!(calls.iter().any(|call| call.contains("split-window -h -b -l 26"))); let repair = calls @@ -3150,18 +3150,27 @@ fn a_session_with_no_focus_window_mints_exactly_one_parked_one() { assert_eq!(window.as_deref(), Some("@7")); let calls = tmux.calls(); - let minted = calls.iter().find(|call| call.starts_with("new-window")).expect("the mint"); + let minted = calls.iter().find(|call| call.contains("new-window")).expect("the mint"); + assert!( + minted.starts_with("if-shell -F -t org-acme_") + && minted.contains("#{W:#{?#{==:#{@organization_window_id},__focus__},1,}}") + && minted.contains("#{==:#{W:") + && minted.contains("'new-window'") + && minted.contains("'@organization_window_id' '__focus__'") + && minted.contains("'@chief_asleep_for' '__focus__'"), + "absence is checked by tmux and the complete identity is published in that same queue: {minted}" + ); assert!( minted.contains("-d") && minted.contains("-a") && minted.contains("org-acme_:$"), "DETACHED, so the glass never moves, and appended LAST so no index shuffles: \ {minted}" ); assert!( - calls.iter().any(|call| call.contains("@organization_window_id __focus__")), + calls.iter().any(|call| call.contains("'@organization_window_id' '__focus__'")), "the window carries the logical id converge audits it by: {calls:?}" ); assert!( - calls.iter().any(|call| call.contains("@chief_asleep_for __focus__")), + calls.iter().any(|call| call.contains("'@chief_asleep_for' '__focus__'")), "and its one pane is tagged as the rail's own FURNITURE — never as a person, \ which converge would adopt: {calls:?}" ); @@ -4484,6 +4493,577 @@ impl Tmux for SocketTmux { } } +struct FirstWindowReadTmux { + inner: SocketTmux, + first: std::sync::atomic::AtomicBool, + replacement: Option, + gate: Option>, +} + +impl Tmux for FirstWindowReadTmux { + fn run(&self, args: &[&str]) -> String { + let first_focus_read = args.first() == Some(&"list-windows") + && args.last().is_some_and(|format| format.contains(tags::WINDOW)) + && self.first.swap(false, std::sync::atomic::Ordering::SeqCst); + let answer = self.inner.run(args); + if first_focus_read { + if let Some(gate) = &self.gate { + gate.wait(); + } + return self.replacement.clone().unwrap_or(answer); + } + answer + } +} + +struct MutatingDuplicateTmux { + inner: SocketTmux, + target: String, + option: &'static str, + value: &'static str, + once: std::sync::atomic::AtomicBool, +} + +impl Tmux for MutatingDuplicateTmux { + fn run(&self, args: &[&str]) -> String { + if args.first() == Some(&"if-shell") + && !args.contains(&"-F") + && args.iter().any(|arg| arg.contains("kill-window")) + && self.once.swap(false, std::sync::atomic::Ordering::SeqCst) + { + tmux_ok( + &self.inner.socket, + &["set-option", "-w", "-t", &self.target, self.option, self.value], + ); + } + self.inner.run(args) + } +} + +/// Two independent rail processes can both observe the first company read. +/// The create decision belongs to tmux's one command queue, so that race still +/// publishes one logical focus window. +#[test] +fn concurrent_real_tmux_focus_ensures_mint_one_window() { + let Some(server) = live_server("focus-mint-cas") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "-x", + "200", + "-y", + "50", + "-n", + "Executive", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let first_reads = std::sync::Arc::new(std::sync::Barrier::new(2)); + let results = std::thread::scope(|scope| { + let mut handles = Vec::new(); + for _ in 0..2 { + let socket = socket.clone(); + let first_reads = first_reads.clone(); + handles.push(scope.spawn(move || { + let tmux = FirstWindowReadTmux { + inner: SocketTmux { socket }, + first: std::sync::atomic::AtomicBool::new(true), + replacement: None, + gate: Some(first_reads), + }; + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ) + })); + } + handles + .into_iter() + .map(|handle| handle.join().expect("the focus ensure does not panic")) + .collect::>() + }); + assert!( + results.iter().all(Option::is_some) && results[0] == results[1], + "both concurrent owners must resolve the same focus window: {results:?}" + ); + let focus = tmux_out( + &socket, + &["list-windows", "-t", session, "-F", &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW)], + ); + assert_eq!( + focus.lines().filter(|line| line.ends_with("\t__focus__")).count(), + 1, + "two simultaneous owners must publish one focus window: {focus:?}" + ); +} + +#[test] +fn an_empty_client_census_cannot_duplicate_an_existing_real_focus_window() { + let Some(server) = live_server("focus-mint-empty-read") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let (original, _) = tagged_focus_window(&socket, session, true); + let tmux = FirstWindowReadTmux { + inner: SocketTmux { socket: socket.clone() }, + first: std::sync::atomic::AtomicBool::new(true), + replacement: Some(String::new()), + gate: None, + }; + + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + Some(original.clone()) + ); + assert!( + !tmux.first.load(std::sync::atomic::Ordering::SeqCst), + "the test must force the first focus census to answer empty" + ); + assert_eq!( + tmux_out( + &socket, + &[ + "list-windows", + "-t", + session, + "-F", + &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW), + ], + ) + .lines() + .filter(|line| line.ends_with("\t__focus__")) + .map(str::to_owned) + .collect::>(), + [format!("{original}\t__focus__")], + "a failed client read cannot authorize a second focus window" + ); +} + +fn tagged_focus_window(socket: &str, session: &str, first: bool) -> (String, String) { + let window = if first { + tmux_out(socket, &["display-message", "-p", "-t", session, "#{window_id}"]) + } else { + tmux_out( + socket, + &[ + "new-window", + "-d", + "-a", + "-t", + &format!("{session}:$"), + "-P", + "-F", + "#{window_id}", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ) + }; + let pane = tmux_out(socket, &["display-message", "-p", "-t", &window, "#{pane_id}"]); + let rail = tmux_out( + socket, + &[ + "split-window", + "-h", + "-b", + "-l", + "26", + "-t", + &pane, + "-P", + "-F", + "#{pane_id}", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok( + socket, + &[ + "set-option", + "-w", + "-t", + &window, + tags::ORGANIZATION, + "acme", + ";", + "set-option", + "-w", + "-t", + &window, + tags::WINDOW, + placement::FOCUS_WINDOW_ID, + ";", + "set-option", + "-p", + "-t", + &pane, + tags::ASLEEP, + placement::FOCUS_WINDOW_ID, + ";", + "set-option", + "-p", + "-t", + &rail, + tags::SIDEBAR, + "1", + ], + ); + (window, pane) +} + +#[test] +fn a_real_inactive_duplicate_made_only_of_focus_furniture_is_repaired() { + let Some(server) = live_server("focus-duplicate-repair") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let (older, _) = tagged_focus_window(&socket, session, true); + let (keeper, keeper_body) = tagged_focus_window(&socket, session, false); + let ordinary = tmux_out( + &socket, + &[ + "new-window", + "-d", + "-a", + "-t", + &format!("{session}:$"), + "-P", + "-F", + "#{window_id}", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + let tmux = SocketTmux { socket: socket.clone() }; + tmux_ok( + &socket, + &[ + "set-option", + "-p", + "-u", + "-t", + &keeper_body, + tags::ASLEEP, + ";", + "set-option", + "-p", + "-t", + &keeper_body, + tags::SLEEPING_PERSON, + "nia", + ], + ); + tmux_ok(&socket, &["select-window", "-t", &keeper]); + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + Some(keeper.clone()), + "the newer active legitimate body is the keeper; the older parked duplicate is deleted" + ); + let windows = tmux_out( + &socket, + &["list-windows", "-t", session, "-F", &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW)], + ); + assert_eq!( + windows + .lines() + .filter(|line| line.ends_with("\t__focus__")) + .map(str::to_owned) + .collect::>(), + [format!("{keeper}\t__focus__")], + "the active newer focus survives instead of the lower numeric id: {windows:?}" + ); + assert!(!windows.lines().any(|line| line.starts_with(&older))); + + tmux_ok( + &socket, + &[ + "set-option", + "-p", + "-u", + "-t", + &keeper_body, + tags::SLEEPING_PERSON, + ";", + "set-option", + "-p", + "-t", + &keeper_body, + tags::ASLEEP, + placement::FOCUS_WINDOW_ID, + ], + ); + let (newer, _) = tagged_focus_window(&socket, session, false); + tmux_ok(&socket, &["select-window", "-t", &ordinary]); + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + Some(keeper.clone()) + ); + let windows = tmux_out( + &socket, + &["list-windows", "-t", session, "-F", &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW)], + ); + assert_eq!( + windows + .lines() + .filter(|line| line.ends_with("\t__focus__")) + .map(str::to_owned) + .collect::>(), + [format!("{keeper}\t__focus__")], + "with all focus windows inactive and parked, the lower numeric id survives: {windows:?}" + ); + assert!(!windows.lines().any(|line| line.starts_with(&newer))); + assert!(windows.lines().any(|line| line.starts_with(&ordinary))); +} + +#[test] +fn a_real_duplicate_with_unknown_local_state_is_left_for_fail_closed_planning() { + let Some(server) = live_server("focus-duplicate-unknown") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let (active, _) = tagged_focus_window(&socket, session, true); + let (unknown, _) = tagged_focus_window(&socket, session, false); + tmux_ok(&socket, &["set-option", "-w", "-t", &unknown, "@chief_unknown", "1"]); + tmux_ok(&socket, &["select-window", "-t", &active]); + let tmux = SocketTmux { socket: socket.clone() }; + + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + None + ); + assert_eq!( + tmux_out(&socket, &["list-windows", "-t", session, "-F", "#{window_id}"]).lines().count(), + 2, + "unknown ownership is never repaired by deletion" + ); +} + +#[test] +fn a_duplicate_that_changes_after_snapshot_is_not_deleted() { + let Some(server) = live_server("focus-duplicate-cas") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let _ = tagged_focus_window(&socket, session, true); + let (candidate, _) = tagged_focus_window(&socket, session, false); + let ordinary = tmux_out( + &socket, + &[ + "new-window", + "-d", + "-a", + "-t", + &format!("{session}:$"), + "-P", + "-F", + "#{window_id}", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["select-window", "-t", &ordinary]); + let tmux = MutatingDuplicateTmux { + inner: SocketTmux { socket: socket.clone() }, + target: candidate, + option: "@chief_unknown", + value: "1", + once: std::sync::atomic::AtomicBool::new(true), + }; + + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + None + ); + assert!( + !tmux.once.load(std::sync::atomic::Ordering::SeqCst), + "the mutation must land after the snapshot and before the delete CAS" + ); + let focus = tmux_out( + &socket, + &["list-windows", "-t", session, "-F", &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW)], + ); + assert_eq!(focus.lines().filter(|line| line.ends_with("\t__focus__")).count(), 2); +} + +#[test] +fn a_keeper_that_changes_after_snapshot_preserves_the_other_focus_window() { + let Some(server) = live_server("focus-keeper-cas") else { return }; + let socket = server.socket().to_owned(); + let session = "org-acme_"; + tmux_ok( + &socket, + &[ + "new-session", + "-d", + "-s", + session, + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["set-option", "-t", session, tags::ORGANIZATION, "acme"]); + let (keeper, _) = tagged_focus_window(&socket, session, true); + let (candidate, _) = tagged_focus_window(&socket, session, false); + let ordinary = tmux_out( + &socket, + &[ + "new-window", + "-d", + "-a", + "-t", + &format!("{session}:$"), + "-P", + "-F", + "#{window_id}", + "/bin/sh", + "-c", + "while :; do sleep 3600 & wait $!; done", + ], + ); + tmux_ok(&socket, &["select-window", "-t", &ordinary]); + let tmux = MutatingDuplicateTmux { + inner: SocketTmux { socket: socket.clone() }, + target: keeper.clone(), + option: tags::WINDOW, + value: "__changed__", + once: std::sync::atomic::AtomicBool::new(true), + }; + + assert_eq!( + effects::ensure_focus_window( + &tmux, + session, + &effects::Parked { + organization: "acme", + rail_program: None, + company_dir: std::path::Path::new("/company"), + }, + ), + None + ); + assert!( + !tmux.once.load(std::sync::atomic::Ordering::SeqCst), + "the keeper mutation must land after selection and before the delete CAS" + ); + let windows = tmux_out( + &socket, + &["list-windows", "-t", session, "-F", &format!("#{{window_id}}\t#{{{}}}", tags::WINDOW)], + ); + assert!(windows.lines().any(|line| line == format!("{keeper}\t__changed__"))); + assert!( + windows.lines().any(|line| line == format!("{candidate}\t{}", placement::FOCUS_WINDOW_ID)), + "a stale repair must not delete the remaining valid focus candidate: {windows:?}" + ); +} + #[derive(Clone, Copy)] enum OrphanWakingRace { Retag,