Skip to content
7 changes: 7 additions & 0 deletions crates/dim-app-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<u64>().ok())
{
config.startup_timeout = std::time::Duration::from_millis(timeout);
}
let mut threads = 2usize;
let mut model_config = None;
let mut mock_model = false;
Expand Down
32 changes: 25 additions & 7 deletions crates/dim-app-server/tests/storage_session_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<tokio::sync::oneshot::Sender<()>>>);
impl Drop for Generation {
fn drop(&mut self) {
if let Some(sender) = self.0.lock().unwrap().take() {
let _ = sender.send(());
}
}
}

struct RecordCleanup {
timeline: Key<Timeline>,
_generation: Arc<()>,
_generation: Arc<Generation>,
}
impl RecordCleanup {
fn new(names: &Names<'_>, generation: Arc<()>) -> rutis::Result<Self> {
fn new(names: &Names<'_>, generation: Arc<Generation>) -> rutis::Result<Self> {
Ok(Self {
timeline: names.key()?,
_generation: generation,
Expand Down Expand Up @@ -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)?))
},
Expand Down Expand Up @@ -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!(
Expand Down
88 changes: 39 additions & 49 deletions crates/dim-app-server/tests/transport_flow/branch_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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 = &notice["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
Expand Down Expand Up @@ -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()]
Expand Down Expand Up @@ -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 = &notice["params"];
if params["branchId"] == *branch
&& params["event"]["type"] == "exec"
&& params["event"]["name"] == "started"
&& !receipts.contains(&params["event"]["data"]["task_id"])
{
break params["event"]["data"]["task_id"].clone();
}
})
.await
.unwrap();
};
active.push(task);
}
for (index, branch) in branches.iter().enumerate() {
Expand Down
45 changes: 44 additions & 1 deletion crates/dim-app-server/tests/transport_flow/collaboration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,6 +1266,46 @@ fn agent_results(events: &[Arc<AgentEvent>]) -> Vec<String> {
.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<Value> {
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("<dim-state source=\"dim/environment/clients\"")
})
})
}))
})
.cloned()
.collect()
}

#[test]
fn environment_client_rows_are_ignored_but_collaboration_rows_are_not() {
let events = json!([
{"sequence":1,"type":"input","mode":"append","user":null,"blocks":
[{"type":"raw","text":"<dim-state source=\"dim/environment/clients\">1 client</dim-state>"}]},
{"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.
Expand Down Expand Up @@ -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())
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
8 changes: 8 additions & 0 deletions crates/dimcode/tests/cli_flow/staged_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"))
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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", &registry)
.env("NO_PROXY", "127.0.0.1")
Expand Down
5 changes: 5 additions & 0 deletions crates/dimcode/tests/support/cli_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down