Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(run): cancel native session selection on interrupt
Éverton Toffanettoa109c0cf06f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08a74e62..17cebbd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Fixed `Ctrl+C` at the native-session chooser leaving the launcher alive and+ renewing its workstream lease. Cancelling now releases the acquired run and+ exits without waiting for Enter or linking a native session (#795).+## [2.3.2] - 2026-09-20### Changeddiff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 1e649600..1e1edbc2 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -4,8 +4,6 @@ use std::ffi::{OsStr, OsString};use std::io::{self, IsTerminal as _};use std::path::{Path, PathBuf};use std::process::Stdio;-use std::sync::Arc;-use std::sync::atomic::{AtomicBool, Ordering};use std::time::{Duration, SystemTime};use ai_memory_core::{@@ -23,6 +21,7 @@ use ai_memory_workstream::{};use anyhow::{Context as _, Result, anyhow};use tokio::process::Command;+use tokio_util::sync::CancellationToken;use crate::cli::{RunArgs, RunHarnessChoice};use crate::commands::{path_util, resolve_scope};@@ -165,8 +164,8 @@ pub(super) async fn run_from_with_wiring(new_workstream: args.new_workstream,lease_owner: lease_owner(),};- let interrupted_before_spawn = Arc::new(AtomicBool::new(false));- let interrupt_task = tokio::spawn(capture_interrupts(Arc::clone(&interrupted_before_spawn)));+ let interrupted_before_spawn = CancellationToken::new();+ let interrupt_task = tokio::spawn(capture_interrupts(interrupted_before_spawn.clone()));let prepared = prepare_managed_run(&endpoint, &prepare).await.context("opening managed workstream; the agent was not started");@@ -201,7 +200,7 @@ pub(super) async fn run_from_with_wiring(}};}- if interrupted_before_spawn.load(Ordering::SeqCst) {+ if interrupted_before_spawn.is_cancelled() {acquired_try!(Err(anyhow!("managed run interrupted before the agent started")));@@ -319,6 +318,7 @@ pub(super) async fn run_from_with_wiring(candidates,&endpoint,&run_path,+ &interrupted_before_spawn,).await);@@ -417,7 +417,7 @@ pub(super) async fn run_from_with_wiring(plan.args.extend([OsString::from("--rules"), OsString::from(context)]);}- if interrupted_before_spawn.load(Ordering::SeqCst) {+ if interrupted_before_spawn.is_cancelled() {acquired_try!(Err(anyhow!("managed run interrupted before the agent started")));@@ -578,9 +578,9 @@ pub(super) async fn run_from_with_wiring(Ok(exit_code)}-async fn capture_interrupts(interrupted: Arc<AtomicBool>) {+async fn capture_interrupts(interrupted: CancellationToken) {while tokio::signal::ctrl_c().await.is_ok() {- interrupted.store(true, Ordering::SeqCst);+ interrupted.cancel();}}@@ -1081,39 +1081,61 @@ async fn choose_native_session_interactive(candidates: Vec<NativeSessionCandidate>,endpoint: &ServerEndpoint,run_path: &str,+ interrupted: &CancellationToken,) -> Result<io::Result<Option<String>>> {- let mut chooser = tokio::task::spawn_blocking(move || {+ let chooser = tokio::task::spawn_blocking(move || {let stdin = io::stdin();- let stderr = io::stderr();+ let mut stderr = io::stderr();choose_native_session(harness,&workstream_name,&candidates,&mut stdin.lock(),- &mut stderr.lock(),+ // Keep stderr available to report cancellation while stdin is blocked.+ &mut stderr,SystemTime::now(),)});- let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);- heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);- heartbeat.tick().await;- let mut heartbeat_health = HeartbeatHealth::default();- let selection = loop {- tokio::select! {- result = &mut chooser => {- break result.context("waiting for the native session choice")?;- }- _ = heartbeat.tick() => {- let _ = send_managed_heartbeat(endpoint, run_path, &mut heartbeat_health).await;- }+ wait_for_native_session_choice(chooser, endpoint, run_path, interrupted).await+}++async fn wait_for_native_session_choice(+ mut chooser: tokio::task::JoinHandle<io::Result<Option<String>>>,+ endpoint: &ServerEndpoint,+ run_path: &str,+ interrupted: &CancellationToken,+) -> Result<io::Result<Option<String>>> {+ tokio::select! {+ biased;+ _ = interrupted.cancelled() => {+ // A running stdin read cannot be aborted. The CLI runtime's bounded+ // shutdown lets the process exit after the caller cancels the lease.+ chooser.abort();+ Err(anyhow!("managed run interrupted before the agent started"))}- };- send_managed_heartbeat(endpoint, run_path, &mut heartbeat_health)- .await- .context(- "renewing the managed workstream after session selection; the agent was not started",- )?;- Ok(selection)+ result = async {+ let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ heartbeat.tick().await;+ let mut heartbeat_health = HeartbeatHealth::default();+ let selection = loop {+ tokio::select! {+ result = &mut chooser => {+ break result.context("waiting for the native session choice")?;+ }+ _ = heartbeat.tick() => {+ let _ = send_managed_heartbeat(endpoint, run_path, &mut heartbeat_health).await;+ }+ }+ };+ send_managed_heartbeat(endpoint, run_path, &mut heartbeat_health)+ .await+ .context(+ "renewing the managed workstream after session selection; the agent was not started",+ )?;+ Ok(selection)+ } => result,+ }}fn choose_native_session(@@ -1423,7 +1445,8 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>mod tests {use std::ffi::{OsStr, OsString};use std::io::Cursor;- use std::sync::atomic::AtomicUsize;+ use std::sync::Arc;+ use std::sync::atomic::{AtomicUsize, Ordering};use ai_memory_core::{ManagedRunId, WorkstreamId};use axum::Router;@@ -1435,6 +1458,121 @@ mod tests {use super::*;use crate::cli::{Cli, Command as CliCommand};+ #[tokio::test(start_paused = true)]+ async fn native_session_choice_interrupt_does_not_wait_for_input() {+ let interrupted = CancellationToken::new();+ let signal = interrupted.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(50)).await;+ signal.cancel();+ });+ let chooser = tokio::spawn(std::future::pending());+ let abort = chooser.abort_handle();+ let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:1".into()), None);++ let result = tokio::time::timeout(+ Duration::from_secs(1),+ wait_for_native_session_choice(chooser, &endpoint, "/unused", &interrupted),+ )+ .await;+ abort.abort();++ let error = result+ .expect("Ctrl-C must not wait for a line of stdin")+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("interrupted before the agent started")+ );+ }++ #[tokio::test(start_paused = true)]+ async fn native_session_choice_preserves_an_earlier_interrupt() {+ let interrupted = CancellationToken::new();+ interrupted.cancel();+ let chooser = tokio::spawn(std::future::pending());+ let abort = chooser.abort_handle();+ let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:1".into()), None);++ let result = tokio::time::timeout(+ Duration::from_secs(1),+ wait_for_native_session_choice(chooser, &endpoint, "/unused", &interrupted),+ )+ .await;+ abort.abort();++ assert!(+ result+ .expect("an earlier Ctrl-C must remain observable")+ .is_err()+ );+ }++ #[tokio::test]+ async fn native_session_choice_still_renews_before_returning_selection() {+ let heartbeats = Arc::new(AtomicUsize::new(0));+ let observed = heartbeats.clone();+ let app = Router::new().route(+ "/run/heartbeat",+ post(move || {+ observed.fetch_add(1, Ordering::SeqCst);+ async { StatusCode::NO_CONTENT }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let endpoint = ServerEndpoint::from_pair(+ Some(format!("http://{}", listener.local_addr().unwrap())),+ None,+ );+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let chooser = tokio::spawn(async { Ok(Some("selected-session".into())) });+ let selected =+ wait_for_native_session_choice(chooser, &endpoint, "/run", &CancellationToken::new())+ .await+ .unwrap()+ .unwrap();++ assert_eq!(selected.as_deref(), Some("selected-session"));+ assert_eq!(heartbeats.load(Ordering::SeqCst), 1);+ server.abort();+ }++ #[tokio::test]+ async fn native_session_choice_interrupt_cancels_a_stalled_heartbeat() {+ let interrupted = CancellationToken::new();+ let signal = interrupted.clone();+ let app = Router::new().route(+ "/run/heartbeat",+ post(move || {+ signal.cancel();+ std::future::pending::<StatusCode>()+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let endpoint = ServerEndpoint::from_pair(+ Some(format!("http://{}", listener.local_addr().unwrap())),+ None,+ );+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let chooser = tokio::spawn(async { Ok(None) });+ let result = tokio::time::timeout(+ Duration::from_secs(1),+ wait_for_native_session_choice(chooser, &endpoint, "/run", &interrupted),+ )+ .await;+ server.abort();++ let error = result+ .expect("Ctrl-C must also cancel an in-flight heartbeat")+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("interrupted before the agent started")+ );+ }+/// `show` filters its harness menu with this, so a false positive would/// offer an agent that cannot start.#[test]diff --git a/crates/ai-memory-cli/tests/suite/shutdown_signals.rs b/crates/ai-memory-cli/tests/suite/shutdown_signals.rsindex b2931dd9..477571a0 100644--- a/crates/ai-memory-cli/tests/suite/shutdown_signals.rs+++ b/crates/ai-memory-cli/tests/suite/shutdown_signals.rs@@ -82,6 +82,180 @@ const STDIO_STOP_AFTER_HANDSHAKE: &str = "stopping the stdio transport";/// connects. Distinguishing the two is what keeps that test honest.const STDIO_STOP_BEFORE_CLIENT: &str = "shutdown signal received before a client connected";+// `script` supplies a real terminal for both stdin and stderr. Pipes skip the+// native-session chooser entirely, and unit tests cannot catch its stderr lock.+#[cfg(any(target_os = "linux", target_os = "macos"))]+mod native_selector {+ use super::*;+ use axum::{Json, Router, http::StatusCode, routing::post};+ use serde_json::json;+ use std::io::Read;+ use std::path::PathBuf;+ use std::sync::{Arc, Mutex};++ struct Terminal {+ child: Child,+ pid_file: PathBuf,+ output: Receiver<String>,+ seen: String,+ }++ impl Terminal {+ fn wait_for(&mut self, needle: &str) {+ let deadline = Instant::now() + READY_TIMEOUT;+ while !self.seen.contains(needle) {+ let timeout = deadline.saturating_duration_since(Instant::now());+ match self.output.recv_timeout(timeout) {+ Ok(chunk) => self.seen.push_str(&chunk),+ Err(error) => panic!("missing {needle:?}: {error}; output:\n{}", self.seen),+ }+ }+ }+ }++ impl Drop for Terminal {+ fn drop(&mut self) {+ if self.child.try_wait().ok().flatten().is_none() {+ // Reap the launcher too if an assertion fails before it exits.+ if let Ok(pid) = std::fs::read_to_string(&self.pid_file) {+ let _ = Command::new("kill").args(["-KILL", pid.trim()]).status();+ }+ let _ = self.child.kill();+ }+ let _ = self.child.wait();+ }+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn interrupt_releases_native_selector_without_enter() {+ let fixture = tempfile::tempdir().unwrap();+ let root = fixture.path().canonicalize().unwrap();+ let home = root.join("home");+ let native = home.join(".claude/projects/fixture");+ std::fs::create_dir_all(&native).unwrap();+ crate::e2e_support::write_jsonl(+ &native.join("session.jsonl"),+ &[json!({"sessionId": "12345678-1234-4234-9234-123456789abc", "cwd": root})],+ );+ let requests = Arc::new(Mutex::new(Vec::new()));+ let observed = requests.clone();+ let app = Router::new().fallback(post(move |uri: axum::http::Uri| {+ let observed = observed.clone();+ async move {+ observed.lock().unwrap().push(uri.path().to_owned());+ if uri.path() == "/workstream/runs" {+ (+ StatusCode::OK,+ Json(json!({+ "workstream_id": "12345678-1234-4234-9234-123456789abd",+ "workstream_name": "fixture",+ "run_id": "12345678-1234-4234-9234-123456789abe",+ "resolved_agent": "claude-code",+ "sync_after": 0, "sync_through": 0,+ "may_adopt_existing_session": true,+ })),+ )+ } else {+ (StatusCode::NO_CONTENT, Json(json!(null)))+ }+ }+ }));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let runner = root.join("runner.sh");+ let pid_file = root.join("launcher.pid");+ std::fs::write(+ &runner,+ concat!(+ "printf '%s\\n' \"$$\" > \"$PICKER_PID_FILE\"\n",+ "exec \"$PICKER_BINARY\" run --no-autowire --executable /usr/bin/true claude\n",+ ),+ )+ .unwrap();+ let mut command = crate::e2e_support::hermetic("script");+ #[cfg(target_os = "macos")]+ command.args(["-qe", "/dev/null", "/bin/sh"]).arg(&runner);+ #[cfg(target_os = "linux")]+ command.args(["-qec", "exec /bin/sh \"$PICKER_RUNNER\"", "/dev/null"]);+ command+ .current_dir(&root)+ .env("PICKER_RUNNER", &runner)+ .env("PICKER_PID_FILE", &pid_file)+ .env("PICKER_BINARY", bin())+ .env("AI_MEMORY_HOME", &home)+ .env("CLAUDE_CONFIG_DIR", home.join(".claude"))+ .env("AI_MEMORY_DATA_DIR", root.join("data"))+ .env("AI_MEMORY_SERVER_URL", format!("http://{address}"))+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("RUST_LOG", "info")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ let mut child = command+ .spawn()+ .expect("script must provide a pseudo-terminal");+ let mut stdout = child.stdout.take().unwrap();+ let (tx, output) = mpsc::channel();+ std::thread::spawn(move || {+ let mut buffer = [0; 1024];+ while let Ok(count) = stdout.read(&mut buffer) {+ if count == 0+ || tx+ .send(String::from_utf8_lossy(&buffer[..count]).into_owned())+ .is_err()+ {+ break;+ }+ }+ });+ let mut terminal = Terminal {+ child,+ pid_file,+ output,+ seen: String::new(),+ };+ terminal.wait_for("Select [1]: ");+ let pid = std::fs::read_to_string(&terminal.pid_file).unwrap();+ assert!(+ Command::new("kill")+ .args(["-INT", pid.trim()])+ .status()+ .unwrap()+ .success()+ );++ // Keep stdin open and send no newline: only the interrupt may unblock it.+ let deadline = Instant::now() + Duration::from_secs(10);+ let status = loop {+ if let Some(status) = terminal.child.try_wait().unwrap() {+ break status;+ }+ assert!(+ Instant::now() < deadline,+ "selector ignored SIGINT; output:\n{}",+ terminal.seen+ );+ tokio::time::sleep(Duration::from_millis(25)).await;+ };+ terminal.wait_for("managed run interrupted before the agent started");+ assert_eq!(+ status.code(),+ Some(1),+ "must report cancellation, not die from SIGINT"+ );+ assert_eq!(+ *requests.lock().unwrap(),+ vec![+ "/workstream/runs",+ "/workstream/runs/12345678-1234-4234-9234-123456789abe/cancel",+ ],+ "must cancel the acquired lease without linking or starting a session"+ );+ server.abort();+ }+}+fn bin() -> &'static str {env!("CARGO_BIN_EXE_ai-memory")}diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 2e485b97..dae9c09d 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -576,6 +576,13 @@ the conflict remains and concurrent writers are still rejected. Terminalinterrupts continue to reach the child while the parent stays alive to finishor cancel the run.+Before the child starts, `Ctrl+C` at the native-session chooser cancels the+acquired run and exits without requiring Enter or adopting the selected session.+The launcher waits for the server's cancellation response. A request error is+reported and leaves the lease to expire within its normal 90-second window;+a server that accepts the request but never responds can still keep the launcher+waiting. Heartbeats have stopped, so the lease itself still expires.+While the harness or native-session selector is open, a temporary server outageproduces one short notice instead of printing every failed heartbeat. Thelauncher keeps probing every 30 seconds with a 10-second request timeout so the