use std::fs;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use serde_json::json;
use supercode::server::{run_http, RpcEngine};
use supercode::{
register_live_runtime, Agent, ChatMessage, ChatRequest, Config, FrontendRuntime,
FrontendRuntimeMetadata, HarnessSessionService, LiveRuntimeSource, Provider, Usage,
};
struct SaysProvider;
#[async_trait]
impl Provider for SaysProvider {
async fn complete(
&self,
_request: &ChatRequest,
_on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
) -> supercode::Result<(ChatMessage, Usage)> {
Ok((
ChatMessage::assistant("ONE SHARED RUNTIME"),
Usage::default(),
))
}
}
#[tokio::test]
async fn discovery_attaches_drives_detaches_and_reattaches_one_runtime() {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!(
"supercode-live-attach-{}-{nonce}",
std::process::id()
));
let workspace = root.join("project");
let codex_home = root.join("codex-sessions");
let supercode_home = root.join("supercode-home");
fs::create_dir_all(&workspace).unwrap();
fs::create_dir_all(&codex_home).unwrap();
std::env::set_var("SUPERCODE_HOME", &supercode_home);
fs::write(
codex_home.join("source-1.jsonl"),
json!({
"timestamp": "2026-01-01T00:00:00Z",
"type": "session_meta",
"payload": {"id": "source-1", "cwd": workspace, "model": "test"}
})
.to_string()
+ "\n",
)
.unwrap();
let agent = Agent::with_provider(
Config::builder().cwd(workspace.clone()).build(),
Box::new(SaysProvider),
);
let runtime = RpcEngine::new_named_with_frontend_metadata(
agent,
"runtime-1",
FrontendRuntimeMetadata {
source_harness: Some("codex".into()),
emulation_profile: None,
},
None,
);
let token: Arc<str> = "private-live-token".into();
let address = run_http(runtime.clone(), "127.0.0.1:0", token.clone())
.await
.unwrap();
let registration = register_live_runtime(
runtime.session_id(),
LiveRuntimeSource {
harness: "codex".into(),
session_id: "source-1".into(),
workspace: workspace.clone(),
},
format!("http://{address}"),
token.to_string(),
)
.unwrap();
let mut service = HarnessSessionService::new();
let discovered = service.handle(json!({
"jsonrpc": "2.0",
"id": 1,
"method": "harness.v1.sessions.discover",
"params": {
"workspace": workspace,
"harnesses": ["codex"],
"homes": {"codex": codex_home}
}
}));
let endpoint = discovered["result"]["sessions"][0]["live_endpoint"]
.as_str()
.expect("trusted discovery should expose an opaque live endpoint")
.to_string();
assert_eq!(endpoint, registration.endpoint().as_str());
assert!(!discovered.to_string().contains(token.as_ref()));
assert!(!discovered.to_string().contains(&address.to_string()));
let attached = service
.handle_async(json!({
"jsonrpc": "2.0",
"id": 2,
"method": "harness.v1.runtimes.attach_existing",
"params": {
"harness": "codex",
"runtime_id": "source-1",
"cwd": workspace,
"base_url": endpoint,
}
}))
.await;
assert!(attached.get("error").is_none(), "{attached}");
assert_eq!(attached["result"]["handle"]["runtime_id"], "runtime-1");
let connection = attached["result"]["connection"].as_str().unwrap();
let sent = service
.handle_async(json!({
"jsonrpc": "2.0",
"id": 3,
"method": "harness.v1.runtimes.send_input",
"params": {"connection": connection, "text": "DRIVE FROM EDITOR"}
}))
.await;
assert!(sent.get("error").is_none(), "{sent}");
let (saw_reply, saw_completion) = tokio::time::timeout(Duration::from_secs(3), async {
let mut saw_reply = false;
let mut saw_completion = false;
while !saw_reply || !saw_completion {
for notification in service.poll_runtimes().await {
let event = ¬ification["params"]["event"];
saw_reply |= event["kind"] == "turn_succeeded"
&& event["payload"]["reply"] == "ONE SHARED RUNTIME";
saw_completion |= event["kind"] == "turn_succeeded";
}
tokio::task::yield_now().await;
}
(saw_reply, saw_completion)
})
.await
.expect("shared runtime should stream a complete turn");
assert!(saw_reply && saw_completion);
let closed = service
.handle_async(json!({
"jsonrpc": "2.0",
"id": 4,
"method": "harness.v1.runtimes.close",
"params": {"connection": connection}
}))
.await;
assert_eq!(closed["result"]["closed"], true);
assert!(
FrontendRuntime::describe(runtime.as_ref()).await.is_ok(),
"editor detach must not stop the terminal-owned runtime"
);
let reattached = service
.handle_async(json!({
"jsonrpc": "2.0",
"id": 5,
"method": "harness.v1.runtimes.attach_existing",
"params": {
"harness": "codex",
"runtime_id": "source-1",
"cwd": workspace,
"base_url": registration.endpoint().as_str(),
}
}))
.await;
assert!(reattached.get("error").is_none(), "{reattached}");
assert_eq!(reattached["result"]["handle"]["runtime_id"], "runtime-1");
runtime.shutdown().await;
drop(registration);
std::env::remove_var("SUPERCODE_HOME");
fs::remove_dir_all(root).ok();
}