Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ Always pass `-p tab-atelier` — a bare `cargo deb` in this workspace can packag
- Language (English, French)
- Configurable toggle hotkeys (press any key to register, applied immediately)
- Configurable browser and code editor for opening links
- **Claude-only mode** (right-click → *Claude-only mode*): forces every new tab to launch `claude` in `auto` mode; right-click → *New bash tab* cancels it and drops back to a shell. Also settable at launch with `--claude-only`, or live on a running instance with `tab-atelier claude-only on|off`.
- **Agent-only mode** (right-click → *Agent-only mode: Claude* or *Agent-only mode: catbus*): forces every new tab to launch that agent — `claude` in `auto` mode, or `catbus-agent`; right-click → *New bash tab* cancels it and drops back to a shell. Also settable at launch with `--agent-only claude|catbus`, or live on a running instance with `tab-atelier agent-only claude|catbus|off`. Stored as `agent_only` in `preferences.json`; an older `claude_only: true` is read as `claude`.

**Monitoring**
- Per-tab CPU usage, power draw (watts), energy consumption (Wh), and uptime
Expand Down
55 changes: 55 additions & 0 deletions crates/catbus-agent/src/applink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,40 @@
//! one is logged at `debug` and nothing else happens, because an app that is not running, busy, or
//! gone must not affect a turn.

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

/// Set once at start-up by a process that is in a tab without being the tab's agent.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if user does mix no tui sessions and normal dessions in the tab lifetime?
Does it stay coherent?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fully, as first pushed — good catch. Three cases:

  • One after another (TUI session ends, then a --no-tui one starts, or the reverse): coherent. The last one started is the tab's session. One caveat that this PR does not change: the app restores with catbus-agent --resume <id> only, so a --no-tui session comes back with its conversation but as a TUI.
  • A --no-tui session started behind the tab's agent (from a tool call, say): this was broken. Both reported, and each took the tab's session id back on its next turn. Fixed in 1b992a3: only a session whose stdin is the tab's terminal reports (owns_the_tab now takes on_terminal). 9f6bbe1 gives the existing abandoned-turn test's agent a terminal, since it models a tab's own process.
  • Two sessions that both hold the terminal (one backgrounded with & in the tab's shell): still last-report-wins. I left that alone; telling them apart needs the foreground process group, which means unsafe or a new dependency in a crate that denies unsafe.

catbus-agent: clippy clean, 649 tests pass.


Generated by Claude Code

static SILENT: AtomicBool = AtomicBool::new(false);

/// Whether this process is the agent its tab should resume.
///
/// A tab has one agent: the session a person types into. Everything else that runs there is a
/// passer-by — a `--prompt-file` review started by a git hook, a `--once` child answering one
/// prompt, a sub-agent this agent spawned. Each inherits the tab's environment and mints its own
/// session id, so one that reported would replace the id the app resumes with by one that names a
/// transcript nobody will open again, or none at all.
///
/// `on_terminal` — whether stdin is a terminal — is what tells the tab's own process from one
/// started behind it. A `--no-tui` session a person launched in the tab has the tab's terminal
/// and is its agent; one an agent started from a tool call has a pipe or nothing, and would
/// otherwise trade the tab's session id back and forth with the session in front of it, each
/// taking it on its next turn.
///
/// What this does not settle is two sessions that both hold the terminal (one put in the
/// background with `&`): the last to report wins. And sessions run one after another are simply
/// last-started-wins, which is the right answer — but the app resumes with `--resume <id>` alone,
/// so a `--no-tui` session comes back with its conversation and a TUI.
#[must_use]
pub const fn owns_the_tab(one_shot: bool, once: bool, spawn_depth: u32, on_terminal: bool) -> bool {
!one_shot && !once && spawn_depth == 0 && on_terminal
}

/// Report nothing for the rest of this process. See [`owns_the_tab`].
pub fn stay_silent() {
SILENT.store(true, Ordering::Relaxed);
}

/// How long a status POST may take. Short: this runs while a turn is starting, and the app is on the
/// same machine — anything that takes longer than this is not going to succeed usefully.
const TIMEOUT: Duration = Duration::from_millis(1500);
Expand Down Expand Up @@ -117,6 +149,9 @@ impl Endpoint {
/// be wrong. Even a mistaken one cannot send a session id off this machine.
#[must_use]
pub fn endpoint() -> Option<Endpoint> {
if SILENT.load(Ordering::Relaxed) {
return None;
}
let tab_id = std::env::var("_TAB_ID").ok().filter(|id| !id.is_empty())?;
let api = std::env::var("TAB_ATELIER_API_URL")
.ok()
Expand Down Expand Up @@ -202,6 +237,26 @@ mod tests {
assert!(local_base("http://127.0.0.1:7890").is_some());
}

/// Only the session a person types into speaks for the tab.
///
/// The bug this pins: a commit made from a catbus tab ran the repository's review hook, the
/// hook's one-shot agent reported its own session id, and the tab came back from a restart
/// resuming a review instead of the conversation.
#[test]
fn only_the_interactive_session_owns_the_tab() {
assert!(owns_the_tab(false, false, 0, true));
assert!(
!owns_the_tab(true, false, 0, true),
"a --prompt-file run is a passer-by"
);
assert!(!owns_the_tab(false, true, 0, true), "so is a --once run");
assert!(!owns_the_tab(false, false, 1, true), "and a spawned sub-agent");
assert!(
!owns_the_tab(false, false, 0, false),
"and a session started behind the tab's own, with no terminal"
);
}

/// Only a local address is a candidate, whatever it is called.
///
/// This is the condition that keeps a session id off a remote host. A public relay is the normal
Expand Down
8 changes: 8 additions & 0 deletions crates/catbus-agent/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,14 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {

fetch_prices_in_background(&agent);

let spawn_depth = std::env::var("CATBUS_SPAWN_DEPTH")
.ok()
.and_then(|depth| depth.parse().ok())
.unwrap_or(0);
let on_terminal = std::io::IsTerminal::is_terminal(&std::io::stdin());
if !applink::owns_the_tab(args.prompt_file.is_some(), args.once, spawn_depth, on_terminal) {
applink::stay_silent();
}
announce_to_app(&agent);

apply_launch_gate(&agent, args.gate.as_deref()).await?;
Expand Down
10 changes: 8 additions & 2 deletions crates/catbus-agent/tests/abandoned_turn_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ fn spawn_stalling_model() -> (u16, mpsc::Receiver<()>) {
/// exits cleanly on it (socket.rs installs a handler), and a clean exit is what
/// lets a coverage-instrumented binary flush its profile to disk. SIGKILL only
/// if it has not exited within 5 s.
struct KillOnDrop(Child);
/// The agent, and the terminal it was started on — held so the terminal outlives it.
struct KillOnDrop(Child, #[allow(dead_code)] std::os::fd::OwnedFd);

impl Drop for KillOnDrop {
fn drop(&mut self) {
Expand All @@ -161,7 +162,12 @@ impl Drop for KillOnDrop {
/// removed so the status report goes to `TAB_ATELIER_API_URL` — the direct path,
/// which is the one under test.
fn spawn_agent(dir: &Path, socket: &Path, model_port: u16, app_port: u16) -> KillOnDrop {
// On a terminal, as a tab's own process always is. Only a session holding the tab's terminal
// speaks for the tab (`applink::owns_the_tab`), so one started with whatever stdin the test
// runner has would rightly report nothing.
let pty = nix::pty::openpty(None, None).expect("openpty");
let child = Command::new(env!("CARGO_BIN_EXE_catbus-agent"))
.stdin(std::process::Stdio::from(pty.slave))
.args([
"--no-tui",
"--new-session",
Expand Down Expand Up @@ -201,7 +207,7 @@ fn spawn_agent(dir: &Path, socket: &Path, model_port: u16, app_port: u16) -> Kil
)
.spawn()
.unwrap();
KillOnDrop(child)
KillOnDrop(child, pty.master)
}

/// Poll until the agent's socket accepts, then complete the handshake.
Expand Down
25 changes: 15 additions & 10 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ use serde::Serialize;

use log::{debug, error, info};

mod agent_only;
mod assets;
mod blackboard_route;
#[cfg(feature = "catbus")]
mod catbus;
mod claims_route;
mod claude_only;
// The decision journal, appended to from here and read by the Kiosk — the same crate,
// so the two cannot drift on the format or on what a re-post is allowed to change.
mod decisions_route;
Expand Down Expand Up @@ -782,10 +782,11 @@ pub struct TabSnapshot {
/// which resizes the PTY + grid and persists the pin — so a web viewer of a
/// tab on a large desktop window can be capped to a phone-friendly size.
pub pending_resizes: Vec<(String, Option<(u16, u16)>)>,
/// Forced Claude-only mode toggle queued by `POST /claude-only` (the CLI
/// `claude-only on|off`). `Some(true/false)` sets the mode live; the owner
/// mirrors it onto [`crate::CLAUDE_ONLY`] + its struct field and persists.
pub pending_claude_only: Option<bool>,
/// Forced agent-only mode switch queued by `POST /agent-only` (the CLI
/// `agent-only claude|catbus|off`). `Some(change)` sets the mode live;
/// the owner mirrors it onto
/// [`crate::set_agent_only`] + its struct field and persists.
pub pending_agent_only: Option<crate::AgentOnlyChange>,
/// Relay-mode toggle queued by `POST /relay-mode` (the CLI `relay on|off`).
/// The owner mirrors it onto [`crate::RELAY_MODE`] + its struct field.
pub pending_relay_mode: Option<bool>,
Expand Down Expand Up @@ -1972,8 +1973,8 @@ fn handle_connection<S: Read + Write>(
"POST" => write_reply(stream, limits::set_default(&envelope, state).into()),
_ => method_not_allowed(stream),
},
"/claude-only" => match method.as_str() {
"POST" => write_reply(stream, claude_only::set(&envelope, state).into()),
"/agent-only" => match method.as_str() {
"POST" => write_reply(stream, agent_only::set(&envelope, state).into()),
_ => method_not_allowed(stream),
},
"/relay-mode" => match method.as_str() {
Expand Down Expand Up @@ -3153,7 +3154,7 @@ pub fn test_snapshot(tabs: Vec<SnapshotTab>) -> TabSnapshot {
pending_limit_changes: Vec::new(),
pending_default_limits: None,
pending_resizes: Vec::new(),
pending_claude_only: None,
pending_agent_only: None,
pending_relay_mode: None,
pending_env_changes: Vec::new(),
pending_meta_changes: Vec::new(),
Expand Down Expand Up @@ -5327,7 +5328,7 @@ mod tests {
"no body at all — validated before any lookup",
),
("POST /tabs/by-id/tab-a/resize HTTP/1.1", "", 400, "no body"),
("POST /claude-only HTTP/1.1", "", 400, "no body"),
("POST /agent-only HTTP/1.1", "", 400, "no body"),
("POST /claims HTTP/1.1", "", 400, "no body"),
];
for (line, body_text, want, why) in cases {
Expand Down Expand Up @@ -7451,7 +7452,11 @@ mod tests {
assert!(wipe);
assert_eq!(label, None, "the sentinel is a verb, not text");
assert_eq!(session_id, None);
assert_eq!(kind, None);
assert_eq!(
kind.as_deref(),
Some("claude"),
"who asked survives, so a wrapped agent's wipe can be refused"
);
assert_eq!(state_now, None, "and the indicator comes down");
}
}
43 changes: 43 additions & 0 deletions src/api/agent_only.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: MPL-2.0

//! The forced agent-only mode switch (`POST /agent-only`), queued to the
//! owner which mirrors it onto the process-global and persists.

use std::sync::{Arc, Mutex};

use serde::Serialize;
use tab_atelier_api::schemars::JsonSchema;
use tab_atelier_api::{Doc, Failure, Request};
// The derive emits `schemars::` paths, so the name itself has to be in scope.
use tab_atelier_api::schemars;

use super::TabSnapshot;

/// The acknowledgement a queued toggle answers.
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct Queued {
queued: &'static str,
}

const BODY_HINT: &str = r#"provide {"agent": "claude"|"catbus"|"off"}"#;

pub(super) fn set(request: &Request<'_>, state: &Arc<Mutex<TabSnapshot>>) -> Result<Doc<Queued>, Failure> {
// Switch forced agent-only mode live (the CLI `agent-only …`).
// Body: {"agent": "claude"|"catbus"|"off"}. The owner mirrors it onto the
// global + its struct field and persists, so new tabs launch that agent
// or a shell with no restart.
let parsed: serde_json::Value =
serde_json::from_slice(request.body).map_err(|e| Failure::problem(400, format!("invalid JSON body: {e}")))?;
let agent = match parsed.get("agent").and_then(serde_json::Value::as_str) {
Some("off") => crate::AgentOnlyChange::Off,
Some(word) => match crate::AgentOnly::parse(word) {
Some(agent) => crate::AgentOnlyChange::On(agent),
None => return Err(Failure::problem(400, BODY_HINT)),
},
None => return Err(Failure::problem(400, BODY_HINT)),
};
let mut snap = state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
snap.pending_agent_only = Some(agent);
drop(snap);
Ok(Doc::ok(Queued { queued: "agent-only" }))
}
36 changes: 0 additions & 36 deletions src/api/claude_only.rs

This file was deleted.

14 changes: 8 additions & 6 deletions src/api/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,20 @@ pub(super) fn run(request: &Request<'_>, state: &Arc<Mutex<TabSnapshot>>) -> Res
} else {
None
};
let (session_id, agent_kind, plan_mode, daemon) = if wipe_attachment {
(None, None, None, None)
// Kept on a wipe too: there it names who is asking, so the owner can refuse
// a wrapped agent's `SessionEnd` (see `report_may_touch_attachment`).
let agent_kind = parsed
.get("agentKind")
.and_then(|v| v.as_str())
.map(std::string::ToString::to_string);
let (session_id, plan_mode, daemon) = if wipe_attachment {
(None, None, None)
} else {
(
parsed
.get("sessionId")
.and_then(|v| v.as_str())
.map(std::string::ToString::to_string),
parsed
.get("agentKind")
.and_then(|v| v.as_str())
.map(std::string::ToString::to_string),
parsed.get("planMode").and_then(serde_json::Value::as_bool),
parsed.get("daemon").and_then(serde_json::Value::as_bool),
)
Expand Down
Loading
Loading