diff --git a/crates/dim-app-server/src/cli.rs b/crates/dim-app-server/src/cli.rs index 174d7f16de..a69547337b 100644 --- a/crates/dim-app-server/src/cli.rs +++ b/crates/dim-app-server/src/cli.rs @@ -350,6 +350,13 @@ pub fn run_with( websocket_address: Some(([127, 0, 0, 1], 8787).into()), ..Default::default() }; + #[cfg(debug_assertions)] + if let Some(timeout) = std::env::var("DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS") + .ok() + .and_then(|value| value.parse::().ok()) + { + config.startup_timeout = std::time::Duration::from_millis(timeout); + } let mut threads = 2usize; let mut model_config = None; let mut mock_model = false; diff --git a/crates/dim-app-server/tests/storage_session_flow.rs b/crates/dim-app-server/tests/storage_session_flow.rs index afd280cbb1..e18d0a956d 100644 --- a/crates/dim-app-server/tests/storage_session_flow.rs +++ b/crates/dim-app-server/tests/storage_session_flow.rs @@ -252,12 +252,21 @@ async fn sqlite_session_failure_rejects_writes_on_an_idle_sibling_timeline() { }).await.expect("SQLite sibling failure and cleanup completed"); } +struct Generation(Mutex>>); +impl Drop for Generation { + fn drop(&mut self) { + if let Some(sender) = self.0.lock().unwrap().take() { + let _ = sender.send(()); + } + } +} + struct RecordCleanup { timeline: Key, - _generation: Arc<()>, + _generation: Arc, } impl RecordCleanup { - fn new(names: &Names<'_>, generation: Arc<()>) -> rutis::Result { + fn new(names: &Names<'_>, generation: Arc) -> rutis::Result { Ok(Self { timeline: names.key()?, _generation: generation, @@ -306,12 +315,16 @@ async fn session_close_and_idle_unload_persist_finalizers_and_release_branch_par defaults::install(&mut builder); let generation = Arc::new(Mutex::new(Weak::new())); let mounted_generation = generation.clone(); + let released = Arc::new(Mutex::new(None)); + let mounted_released = released.clone(); builder .timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())) .require_feature(Feature::new("storage-session.record-cleanup").branch( "storage-session.record-cleanup", move |names| { - let marker = Arc::new(()); + let (sender, receiver) = tokio::sync::oneshot::channel(); + *mounted_released.lock().unwrap() = Some(receiver); + let marker = Arc::new(Generation(Mutex::new(Some(sender)))); *mounted_generation.lock().unwrap() = Arc::downgrade(&marker); Ok(Box::new(RecordCleanup::new(names, marker)?)) }, @@ -339,10 +352,15 @@ async fn session_close_and_idle_unload_persist_finalizers_and_release_branch_par session.close().await.unwrap(); } drop(session); - assert!( - generation.upgrade().is_none(), - "branch part must be dropped after Session teardown (idle unload: {unloading})" - ); + let released = released.lock().unwrap().take().expect("branch part built"); + tokio::time::timeout(Duration::from_secs(10), released) + .await + .unwrap_or_else(|_| { + panic!( + "branch part must be dropped after Session teardown (idle unload: {unloading})" + ) + }) + .expect("branch part drop signalled"); let head = store.head(&key).await.unwrap(); let records = store.read(&key, 1..=head).await.unwrap(); assert_eq!( diff --git a/crates/dim-app-server/tests/transport_flow/branch_events.rs b/crates/dim-app-server/tests/transport_flow/branch_events.rs index 61768d8f69..6323b1d5c9 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_events.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_events.rs @@ -104,6 +104,11 @@ async fn restored_task_branches_are_discovered_locally_and_named_stops_preserve_ .await; assert_ok(&created); let session = created["result"]["sessionId"].as_str().unwrap().to_owned(); + assert_ok( + &client + .rpc("session.attach", json!({"sessionId":session})) + .await, + ); let mut branches = Vec::new(); let mut receipts = Vec::new(); let mut parent = "main".to_owned(); @@ -126,32 +131,26 @@ async fn restored_task_branches_are_discovered_locally_and_named_stops_preserve_ .as_str() .unwrap() .to_owned(); - let history = tokio::time::timeout(Duration::from_secs(10), async { - loop { - let history = page(&mut client, &session, &branch).await; - if history["events"] - .as_array() - .unwrap() - .iter() - .any(|event| event["type"] == "exec" && event["name"] == "ended") - { - break history; - } - tokio::time::sleep(Duration::from_millis(10)).await; + let task = loop { + let notice = client.notice("session.event").await; + let params = ¬ice["params"]; + if params["sessionId"] == session + && params["branchId"] == branch + && params["event"]["type"] == "exec" + && params["event"]["name"] == "ended" + && params["event"]["data"]["status"] == "completed" + { + break params["event"]["data"]["task_id"].clone(); } - }) - .await - .unwrap(); + }; + let history = page(&mut client, &session, &branch).await; let events = history["events"].as_array().unwrap(); - let started = events - .iter() - .find(|event| event["type"] == "exec" && event["name"] == "started") - .unwrap(); - let task = started["data"]["task_id"].clone(); - assert!(events.iter().any(|event| event["type"] == "exec" - && event["name"] == "ended" - && event["data"]["task_id"] == task - && event["data"]["status"] == "completed")); + assert!( + events.iter().any(|event| event["type"] == "exec" + && event["name"] == "started" + && event["data"]["task_id"] == task), + "the history carries the started fact of the ended command" + ); receipts.push(task); assert_ok( &client @@ -188,17 +187,12 @@ async fn restored_task_branches_are_discovered_locally_and_named_stops_preserve_ .rpc("session.attach", json!({"sessionId":session})) .await, ); - let discovered = tokio::time::timeout(Duration::from_secs(10), async { - let mut discovered = std::collections::HashSet::new(); - while discovered.len() != 3 { - let state = client.notice("session.state").await; - assert_eq!(state["params"]["sessionId"], session); - discovered.insert(state["params"]["branchId"].as_str().unwrap().to_owned()); - } - discovered - }) - .await - .unwrap(); + let mut discovered = std::collections::HashSet::new(); + while discovered.len() != 3 { + let state = client.notice("session.state").await; + assert_eq!(state["params"]["sessionId"], session); + discovered.insert(state["params"]["branchId"].as_str().unwrap().to_owned()); + } assert_eq!( discovered, ["main".to_owned(), branches[0].clone(), branches[1].clone()] @@ -245,21 +239,17 @@ async fn restored_task_branches_are_discovered_locally_and_named_stops_preserve_ ) .await, ); - let task = tokio::time::timeout(Duration::from_secs(10), async { - loop { - let history = page(&mut client, &session, branch).await; - if let Some(event) = history["events"].as_array().unwrap().iter().find(|event| { - event["type"] == "exec" - && event["name"] == "started" - && !receipts.contains(&event["data"]["task_id"]) - }) { - break event["data"]["task_id"].clone(); - } - tokio::time::sleep(Duration::from_millis(10)).await; + let task = loop { + let notice = client.notice("session.event").await; + let params = ¬ice["params"]; + if params["branchId"] == *branch + && params["event"]["type"] == "exec" + && params["event"]["name"] == "started" + && !receipts.contains(¶ms["event"]["data"]["task_id"]) + { + break params["event"]["data"]["task_id"].clone(); } - }) - .await - .unwrap(); + }; active.push(task); } for (index, branch) in branches.iter().enumerate() { diff --git a/crates/dim-app-server/tests/transport_flow/collaboration.rs b/crates/dim-app-server/tests/transport_flow/collaboration.rs index d675844a12..4d7ba3c392 100644 --- a/crates/dim-app-server/tests/transport_flow/collaboration.rs +++ b/crates/dim-app-server/tests/transport_flow/collaboration.rs @@ -1266,6 +1266,46 @@ fn agent_results(events: &[Arc]) -> Vec { .collect() } +/// The page's business events, without the environment state inputs that can +/// land between two reads when a client attaches, detaches or unloads. +fn business_events(events: &Value) -> Vec { + events + .as_array() + .unwrap() + .iter() + .filter(|event| { + !(event["type"] == "input" + && event["mode"] == "append" + && event["user"].is_null() + && event["blocks"].as_array().is_some_and(|blocks| { + !blocks.is_empty() + && blocks.iter().all(|block| { + block["text"].as_str().is_some_and(|text| { + text.starts_with("1 client"}]}, + {"sequence":2,"type":"input","mode":"queue","user":{"content":[{"type":"text","text":"follow-up"}]},"blocks":[]}, + {"sequence":3,"type":"tool_call","callId":"same","name":"hold"}, + {"sequence":4,"type":"tool_call","callId":"same","name":"hold"} + ]); + assert_eq!( + business_events(&events), + events.as_array().unwrap()[1..].to_vec(), + "only the client-presence row is removed; order and duplicates stay" + ); +} + /// Each operation event has exactly one later `delivered`; each delivered /// request exactly one later `result`. Collaboration facts stay out of the /// model context. @@ -3179,7 +3219,10 @@ async fn member_work(mut config: ServerConfig) { .get_session(&member) .expect("the authorized read acquires its peer"); let read = last_ok(&events(&lead_session).await); - assert_eq!(read["events"], full["events"]); + assert_eq!( + business_events(&read["events"]), + business_events(&full["events"]) + ); assert!( (full["nextCursor"].as_u64().unwrap()..=restored.sequence("main").unwrap()) .contains(&read["nextCursor"].as_u64().unwrap()) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 5b7c1d77b2..5f5acb2b25 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1769,7 +1769,7 @@ cargo test --locked -p dimcode --test cli_flow --test cli_tui_flow --test cli_se cargo clippy --locked -p dim-cli --all-targets -- -D warnings ``` -Two debug-only variables shorten the daemon startup waits for the flow tests: `DIM_TEST_DAEMON_START_TIMEOUT_MS` replaces the 10 s bound of the wait before spawning and of the spawn wait and `DIM_TEST_START_LOCK_TIMEOUT_MS` the start-lock wait's derived bound, so a test reaches an inactivity bound without waiting the production time. Two more inject build identity without recompiling: `DIM_TEST_BUILD_ID` replaces this build's artifact stamp (so a flow or a tmux scenario can stand a client and a daemon of different builds beside each other; an empty value means no stamp), and `DIM_TEST_RELEASE_BUILD` overrides the release mark (so flows can test release-gated startup recovery and `Update now` against the already-compiled debug binary; an empty value or `"0"` means a source build). `DIM_TEST_UPDATE_TIMEOUT_MS` replaces the update check's 4 s registry deadline, so a flow on a loaded runner still sees the offer. Only a debug build reads them, a release build ignores them, and the tests that set them compile only in debug builds. +Two debug-only variables shorten the daemon startup waits for the flow tests: `DIM_TEST_DAEMON_START_TIMEOUT_MS` replaces the 10 s bound of the wait before spawning and of the spawn wait and `DIM_TEST_START_LOCK_TIMEOUT_MS` the start-lock wait's derived bound, so a test reaches an inactivity bound without waiting the production time. Two more inject build identity without recompiling: `DIM_TEST_BUILD_ID` replaces this build's artifact stamp (so a flow or a tmux scenario can stand a client and a daemon of different builds beside each other; an empty value means no stamp), and `DIM_TEST_RELEASE_BUILD` overrides the release mark (so flows can test release-gated startup recovery and `Update now` against the already-compiled debug binary; an empty value or `"0"` means a source build). `DIM_TEST_UPDATE_TIMEOUT_MS` replaces the update check's 4 s registry deadline, so a flow on a loaded runner still sees the offer. `DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS` replaces the embedded App Server's 10 s startup inactivity bound, so its plugin assembly may take longer on a loaded runner. Only a debug build reads them, a release build ignores them, and the tests that set them compile only in debug builds. The production-model flow uses the actual App Server, an API-key environment reference and a local OpenAI-compatible HTTP stream fixture. It checks the production tool list, a real file read reaching the model, and continued input on the same persisted session: diff --git a/crates/dimcode/tests/cli_flow/staged_update.rs b/crates/dimcode/tests/cli_flow/staged_update.rs index b5d07152ff..c677c8214d 100644 --- a/crates/dimcode/tests/cli_flow/staged_update.rs +++ b/crates/dimcode/tests/cli_flow/staged_update.rs @@ -944,6 +944,8 @@ mod recovery { .env_remove("DIMCODE_STARTUP_RETRY") .env("DIM_TEST_RELEASE_BUILD", "1") .env("DIM_TEST_UPDATE_TIMEOUT_MS", "60000") + .env("DIM_TEST_DAEMON_START_TIMEOUT_MS", "60000") + .env("DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS", "60000") .env("DIMCODE_NPM_PACKAGE", "dimcode-alpha") .env("DIMCODE_NPM_REGISTRY", registry) .env("NO_PROXY", "127.0.0.1") @@ -1089,6 +1091,8 @@ mod recovery { .env_remove("DIMCODE_STARTUP_RETRY") .env("DIM_TEST_RELEASE_BUILD", "1") .env("DIM_TEST_UPDATE_TIMEOUT_MS", "60000") + .env("DIM_TEST_DAEMON_START_TIMEOUT_MS", "60000") + .env("DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS", "60000") .env("DIMCODE_NPM_PACKAGE", "dimcode-alpha") .env("DIMCODE_NPM_REGISTRY", "http://127.0.0.1:1") .env("UPDATE_ARGS", installed.home.0.join("install-args")) @@ -1178,6 +1182,8 @@ mod recovery { .env_remove("DIMCODE_STARTUP_RETRY") .env("DIM_TEST_RELEASE_BUILD", "1") .env("DIM_TEST_UPDATE_TIMEOUT_MS", "60000") + .env("DIM_TEST_DAEMON_START_TIMEOUT_MS", "60000") + .env("DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS", "60000") .env("DIMCODE_NPM_PACKAGE", "dimcode-alpha") .env("DIMCODE_NPM_REGISTRY", registry) .env("NO_PROXY", "127.0.0.1") @@ -1499,6 +1505,8 @@ printf 'Updated launcher started\n' .env_remove("DIMCODE_UPDATE_CHECK") .env("DIM_TEST_RELEASE_BUILD", "1") .env("DIM_TEST_UPDATE_TIMEOUT_MS", "60000") + .env("DIM_TEST_DAEMON_START_TIMEOUT_MS", "60000") + .env("DIM_TEST_APP_SERVER_STARTUP_TIMEOUT_MS", "60000") .env("DIMCODE_NPM_PACKAGE", "dimcode-alpha") .env("DIMCODE_NPM_REGISTRY", ®istry) .env("NO_PROXY", "127.0.0.1") diff --git a/crates/dimcode/tests/support/cli_harness.rs b/crates/dimcode/tests/support/cli_harness.rs index 545995c5e7..4d9d0d21ef 100644 --- a/crates/dimcode/tests/support/cli_harness.rs +++ b/crates/dimcode/tests/support/cli_harness.rs @@ -906,6 +906,11 @@ impl Terminal { let mut bytes = [0u8; 4096]; let size = match self.master.as_mut().unwrap().read(&mut bytes) { Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => continue, + Err(error) + if cfg!(target_os = "linux") && error.raw_os_error() == Some(libc::EIO) => + { + 0 + } result => result.unwrap(), }; assert!(