use std::fs;
use std::io::ErrorKind;
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Command, Output, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
fn bin() -> &'static str {
env!("CARGO_BIN_EXE_supercode")
}
fn temp_home(label: &str) -> PathBuf {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let home = std::env::temp_dir().join(format!(
"supercode-claude-runtime-resume-{label}-{}-{nonce}",
std::process::id(),
));
fs::create_dir_all(&home).unwrap();
home
}
fn write_lines(path: &PathBuf, lines: &[serde_json::Value]) {
let text = lines
.iter()
.map(serde_json::Value::to_string)
.collect::<Vec<_>>()
.join("\n")
+ "\n";
fs::write(path, text).unwrap();
}
fn write_overdue_wakeup(path: &PathBuf) {
write_lines(
path,
&[
serde_json::json!({
"type": "user",
"sessionId": "runtime-resume",
"cwd": "/tmp",
"timestamp": "2020-01-01T00:00:00Z",
"message": {"role": "user", "content": "initial context"}
}),
serde_json::json!({
"type": "assistant",
"timestamp": "2020-01-01T00:00:01Z",
"message": {"role": "assistant", "content": [{
"type": "tool_use",
"id": "wake-overdue",
"name": "ScheduleWakeup",
"input": {
"delaySeconds": 1,
"reason": "acceptance wakeup",
"prompt": "RUNTIME_WAKEUP_MARKER"
}
}]}
}),
serde_json::json!({
"type": "user",
"timestamp": "2020-01-01T00:00:02Z",
"message": {"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": "wake-overdue",
"content": "Next wakeup scheduled for 00:00:02 (in 1s)."
}]}
}),
],
);
}
fn write_active_cron(path: &PathBuf) {
write_lines(
path,
&[
serde_json::json!({
"type": "user",
"sessionId": "runtime-cron-resume",
"cwd": "/tmp",
"timestamp": "2020-01-01T00:00:00Z",
"message": {"role": "user", "content": "initial context"}
}),
serde_json::json!({
"type": "assistant",
"timestamp": "2020-01-01T00:00:01Z",
"message": {"role": "assistant", "content": [{
"type": "tool_use",
"id": "cron-every-minute",
"name": "CronCreate",
"input": {
"cron": "* * * * *",
"recurring": true,
"prompt": "RUNTIME_CRON_MARKER"
}
}]}
}),
serde_json::json!({
"type": "user",
"timestamp": "2020-01-01T00:00:02Z",
"message": {"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": "cron-every-minute",
"content": "Scheduled recurring job every-minute (* * * * *). Session-only."
}]}
}),
],
);
}
fn write_pending_queue(path: &PathBuf) {
write_lines(
path,
&[
serde_json::json!({
"type": "user",
"sessionId": "runtime-queue-resume",
"cwd": "/tmp",
"timestamp": "2020-01-01T00:00:00Z",
"message": {"role": "user", "content": "initial context"}
}),
serde_json::json!({
"type": "queue-operation",
"operation": "enqueue",
"timestamp": "2020-01-01T00:00:01Z",
"content": "RUNTIME_QUEUE_MARKER"
}),
],
);
}
fn resume_idle(home: &PathBuf, source: &PathBuf) -> (Output, bool) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
listener.set_nonblocking(true).unwrap();
let child = Command::new(bin())
.env("HOME", home)
.env("SUPERCODE_HOME", home.join("supercode-home"))
.env_remove("OPENROUTER_API_KEY")
.args([
"--api-key",
"x",
"--base-url",
&format!("http://{addr}"),
"--max-iterations",
"1",
"resume",
source.to_str().unwrap(),
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let output = child.wait_with_output().unwrap();
let contacted = match listener.accept() {
Ok(_) => true,
Err(error) if error.kind() == ErrorKind::WouldBlock => false,
Err(error) => panic!("unexpected accept error: {error}"),
};
(output, contacted)
}
#[test]
fn an_overdue_wakeup_is_carried_paused_and_never_fires() {
let home = temp_home("wakeup");
let source = home.join("session.jsonl");
write_overdue_wakeup(&source);
let before = fs::read(&source).unwrap();
let (output, contacted) = resume_idle(&home, &source);
assert!(output.status.success(), "{:?}", output.status);
assert!(
!contacted,
"an overdue wakeup must not issue a provider request"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("carried and PAUSED"), "{stderr}");
assert!(stderr.contains("1 scheduled wakeup(s)"), "{stderr}");
assert!(
stderr.contains("None of them will execute here"),
"{stderr}"
);
assert!(
stderr.contains("orchestrator import --from claude-session"),
"{stderr}"
);
assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
fs::remove_dir_all(home).ok();
}
#[test]
fn an_active_cron_is_carried_paused_and_never_fires() {
let home = temp_home("cron");
let source = home.join("cron-session.jsonl");
write_active_cron(&source);
let before = fs::read(&source).unwrap();
let (output, contacted) = resume_idle(&home, &source);
assert!(output.status.success(), "{:?}", output.status);
assert!(!contacted, "a due cron must not issue a provider request");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("carried and PAUSED"), "{stderr}");
assert!(stderr.contains("1 cron job(s)"), "{stderr}");
assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
fs::remove_dir_all(home).ok();
}
#[test]
fn a_pending_queue_is_carried_paused_and_never_replays() {
let home = temp_home("queue");
let source = home.join("queue-session.jsonl");
write_pending_queue(&source);
let before = fs::read(&source).unwrap();
let (output, contacted) = resume_idle(&home, &source);
assert!(output.status.success(), "{:?}", output.status);
assert!(
!contacted,
"a pending queue must not be replayed into a provider request"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("carried and PAUSED"), "{stderr}");
assert!(stderr.contains("1 queued prompt(s)"), "{stderr}");
assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
fs::remove_dir_all(home).ok();
}