Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 220 additions & 0 deletions desktop/ox-host-web/src/client/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use super::*;
use ox_desk_core::host_protocol::{Client as Frame, Server, VERSION};
use std::{
collections::BTreeMap,
env, fs,
io::{BufRead, Write},
os::unix::fs::OpenOptionsExt as _,
Expand Down Expand Up @@ -578,6 +579,225 @@ fn native_continuity_approval() {
credential.discard_key().unwrap();
}

#[test]
#[ignore = "launched by the isolated native continuity stream fixture"]
fn native_continuity_stream() {
let origin = env::var("OX_TEST_ORIGIN").unwrap();
let root = PathBuf::from(env::var_os("OX_TEST_NATIVE_DIR").unwrap());
let supplied: Value =
serde_json::from_str(&fs::read_to_string(root.join("stream.json")).unwrap()).unwrap();
assert_eq!(
supplied.as_object().map(|scope| scope.len()),
Some(2),
"the fixture supplies exactly the project and route"
);
let project = PathBuf::from(
supplied["project"]
.as_str()
.expect("the fixture supplies the project"),
);
assert!(
supplied["route"].is_object(),
"the fixture supplies the route"
);
let scope = json!({"project": project, "route": supplied["route"].clone()});
let invite =
Invitation::parse(&origin, &fs::read_to_string(root.join("code")).unwrap()).unwrap();
let rt = runtime().unwrap();
let credential = rt
.block_on(register(invite, "Native continuity stream"))
.unwrap();
let client = PairedClient::new(&origin, &credential).unwrap();
let host_id = fs::read_to_string(root.join("host-id")).unwrap();
let host_id = host_id.trim();
let socket = rt.block_on(client.session()).unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(75)))
.unwrap();
let mut stream = std::io::BufReader::new(socket);
writeln!(
stream.get_mut(),
"{}",
serde_json::to_string(&Frame::Hello { version: VERSION }).unwrap()
)
.unwrap();
let Server::Hello {
host: Some(host), ..
} = read(&mut stream)
else {
panic!("expected compatible host");
};
assert_eq!(host.id.as_deref(), Some(host_id));
let send = |stream: &mut std::io::BufReader<UnixStream>, frame: Value| {
writeln!(stream.get_mut(), "{frame}").unwrap()
};
send(
&mut stream,
json!({"type":"subscribe","scope":scope,"terminal":false,"after":null}),
);
loop {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
if frame["scopes"].as_array().is_some_and(|scopes| {
scopes.iter().any(|state| {
state["scope"] == scope
&& state["capabilities"]
.as_array()
.is_some_and(|caps| caps.contains(&json!("start")))
})
}) {
break;
}
}
send(
&mut stream,
json!({"type":"act","id":"stream-start","scope":scope,"approval":null,
"action":{"send_text":[null,"Marigold APPROVAL shared"]}}),
);
let witness = |event: &str| {
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(root.join("witness"))
.unwrap();
writeln!(file, "{event}").unwrap();
};
let mut thread: Option<String> = None;
let mut asked = false;
let mut approved = false;
let mut first = false;
let mut texts: BTreeMap<(String, String), String> = BTreeMap::new();
loop {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
if frame["type"] == "opened" && frame["id"] == "stream-start" {
assert_eq!(frame["scope"], scope);
let opened = frame["thread"]
.as_str()
.filter(|thread| !thread.is_empty())
.expect("the host opened the new thread");
if let Some(thread) = &thread {
assert_eq!(thread, opened);
} else {
fs::write(root.join("thread"), format!("{opened}\n")).unwrap();
thread = Some(opened.to_owned());
}
}
for change in frame["changes"].as_array().into_iter().flatten() {
if change["kind"] == "asks" {
for ask in change["asks"].as_array().into_iter().flatten() {
let Some(id) = ask["thread"].as_str() else {
continue;
};
if thread.is_none() {
fs::write(root.join("thread"), format!("{id}\n")).unwrap();
thread = Some(id.to_owned());
}
assert_eq!(thread.as_deref(), Some(id));
let _ = stock_allow(ask);
if !asked {
witness("ask");
asked = true;
}
}
}
if let Some(thread) = &thread {
if !approved
&& change["kind"] == "notification"
&& change["event"] == "finished"
&& change["thread"].as_str() == Some(thread.as_str())
{
assert!(
asked,
"the tool approval must precede the first completed turn"
);
assert_eq!(
fs::read_to_string(project.join("approved.txt"))
.unwrap()
.trim(),
"accepted",
"the desktop-approved tool wrote its marker"
);
approved = true;
witness("approved");
}
collect_stream_text(change, thread, &mut texts);
}
}
if thread.is_some() {
let text = texts.values().map(String::as_str).collect::<String>();
if !first && text.contains("Copperstream") {
assert!(
!text.contains("Sunbeam"),
"the first chunk arrived with the final chunk"
);
first = true;
witness("first");
}
if first && text.contains("Copperstream Sunbeam") {
witness("final");
break;
}
}
}
assert!(
asked,
"the native client witnessed the pending stock approval"
);
assert!(
approved,
"the native client witnessed the approved tool finish"
);
assert!(first, "the native client witnessed the split turn");
rt.block_on(client.revoke_self()).unwrap();
assert!(rt.block_on(client.session()).is_err());
credential.discard_key().unwrap();
}

fn collect_stream_text(
change: &Value,
thread: &str,
texts: &mut BTreeMap<(String, String), String>,
) {
if change["thread"].as_str() != Some(thread) {
return;
}
let insert = |items: &mut BTreeMap<(String, String), String>, item: &Value| {
if let (Some(turn), Some(id)) = (item["turn"].as_str(), item["id"].as_str()) {
items.insert(
(turn.to_owned(), id.to_owned()),
item["text"].as_str().unwrap_or_default().to_owned(),
);
}
};
match change["kind"].as_str() {
Some("transcript") => {
texts.clear();
for item in change["timeline"]["items"].as_array().into_iter().flatten() {
insert(texts, item);
}
}
Some("items") => {
for item in change["items"].as_array().into_iter().flatten() {
insert(texts, item);
}
}
Some("append") => {
if let (Some(turn), Some(id), Some(text)) = (
change["turn"].as_str(),
change["id"].as_str(),
change["text"].as_str(),
) {
texts
.entry((turn.to_owned(), id.to_owned()))
.or_default()
.push_str(text);
}
}
_ => {}
}
}

/// Read the stock Claude tool prompt's own decisions and choose Allow once.
fn stock_allow(ask: &Value) -> (Value, String, usize) {
assert_eq!(
Expand Down
59 changes: 52 additions & 7 deletions desktop/ox-host-web/tests/native_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ def request(frame):
assert row["parent_host"] and row["has_project"] and row["status"] == "online"


def approve_continuity(host_state, root, env, harness, thread, project, route, stack):
"""Allow exactly this thread's pending stock prompt from a signed native client."""
def paired_host(host_state, root, stack):
"""Enable a disposable TLS endpoint and pair one fresh native device."""
state_dir = Path(host_state)
root = Path(root)
if not state_dir.is_dir() or not thread:
raise AssertionError("Expected a running disposable session host and an exact thread")
if not state_dir.is_dir():
raise AssertionError("Expected a running disposable session host")
wait(lambda: (state_dir / "remote-admin.sock").exists())
if admin(state_dir, {"type": "status"})["devices"]:
raise AssertionError("Expected a fresh disposable remote state")
Expand All @@ -90,15 +90,23 @@ def revoke():
invitation = admin(state_dir, {"type": "pair", "login": "[email protected]"})["pairing"]
(root / "code").write_text(invitation["short_code"])
(root / "host-id").write_text((state_dir / "host-id").read_text())
(root / "scope.json").write_text(
json.dumps({"thread": thread, "project": str(project), "route": route})
)
certificate(root)
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
tls.num_tickets = 0
tls.load_cert_chain(root / "server.pem", root / "server.key")
public.socket = tls.wrap_socket(public.socket, server_side=True)
managed_server(stack, public)
return state_dir, root, origin, port


def approve_continuity(host_state, root, env, harness, thread, project, route, stack):
"""Allow exactly this thread's pending stock prompt from a signed native client."""
if not thread:
raise AssertionError("Expected an exact thread")
state_dir, root, origin, port = paired_host(host_state, root, stack)
(root / "scope.json").write_text(
json.dumps({"thread": thread, "project": str(project), "route": route})
)
subprocess.run(
[harness, "--exact", "client::fixture::native_continuity_approval", "--ignored"],
check=True,
Expand All @@ -115,6 +123,43 @@ def revoke():
)


def stream_continuity(host_state, root, env, harness, project, route, stack):
"""Create Beta's first session and witness its split turn from a signed client."""
state_dir, root, origin, port = paired_host(host_state, root, stack)
(root / "stream.json").write_text(
json.dumps({"project": str(project), "route": route})
)
process = subprocess.Popen(
[harness, "--exact", "client::fixture::native_continuity_stream", "--ignored"],
env=dict(
env,
OX_TEST_NATIVE_DIR=str(root),
OX_TEST_LOOPBACK=f"127.0.0.1:{port}",
OX_TEST_ORIGIN=origin,
),
)

def reap(exc_type, _exc_value, _traceback):
if exc_type is not None and process.poll() is None:
process.terminate()
try:
code = process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
if exc_type is None:
raise
return
if exc_type is None:
assert code == 0, f"native stream fixture exited {code}"
assert not admin(state_dir, {"type": "status"})["devices"], (
"native stream fixture did not revoke its device"
)

stack.push(reap)
return process, root / "thread", root / "witness"


def run(host, cli, harness, stock=None):
with tempfile.TemporaryDirectory(prefix="ox-native-") as tmp, ExitStack() as stack:
root = Path(tmp)
Expand Down
Loading
Loading