Skip to content
Merged
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
267 changes: 267 additions & 0 deletions desktop/ox-host-web/src/client/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,273 @@ fn native_continuity_stop() {
credential.discard_key().unwrap();
}

#[test]
#[ignore = "launched by the isolated native continuity terminal fixture"]
fn native_continuity_terminal() {
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("terminal.json")).unwrap()).unwrap();
assert_eq!(
supplied.as_object().map(|scope| scope.len()),
Some(3),
"the fixture supplies exactly the canonical thread, project and route"
);
let thread = supplied["thread"]
.as_str()
.filter(|thread| !thread.is_empty())
.expect("the fixture supplies the exact canonical thread")
.to_owned();
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: Scope = serde_json::from_value(json!({
"project": &project,
"route": supplied["route"].clone(),
}))
.unwrap();
assert_eq!(scope.project, project);
assert_eq!(scope.route.runtime, ox_desk_core::runtime::Runtime::Claude);
assert_eq!(
scope.route.billing,
ox_desk_core::runtime::Billing::Api("fixture/demo".into()),
"the terminal resumes the stock Claude billing route the fixture named"
);
let wire_scope = serde_json::to_value(&scope).unwrap();
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 terminal"))
.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 witness = |event: &str| {
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(root.join("witness"))
.unwrap();
writeln!(file, "{event}").unwrap();
};
// The same signed session stream the phone keeps open. Subscribe and open
// the exact thread before the terminal, then read it across the handoff.
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":wire_scope,"terminal":false,"after":null}),
);
let mut texts: BTreeMap<(String, String), String> = BTreeMap::new();
let sendable = |frame: &Value| {
session_rows(frame, &wire_scope).into_iter().any(|row| {
row["id"].as_str() == Some(thread.as_str())
&& row["capabilities"].as_array().is_some_and(|caps| {
caps.iter()
.any(|cap| matches!(cap.as_str(), Some("send" | "steer")))
})
})
};
let has_text = |frame: &Value, texts: &BTreeMap<(String, String), String>, expected: &str| {
scope_state(frame, &wire_scope)
.and_then(|state| state["transcripts"].as_object())
.and_then(|transcripts| transcripts.get(&thread))
.and_then(|timeline| timeline["items"].as_array())
.is_some_and(|items| {
items.iter().any(|item| {
item["text"]
.as_str()
.is_some_and(|text| text.contains(expected))
})
})
|| texts
.values()
.map(String::as_str)
.collect::<String>()
.contains(expected)
};
let same_scope = |frame: &Value, label: &str| {
if frame["scope"]
.as_object()
.is_some_and(|scope| !scope.is_empty())
{
assert_eq!(frame["scope"], wire_scope, "{label}");
}
};
let mut original = false;
let mut idle = false;
while !original || !idle {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
same_scope(&frame, "the host kept the exact scope");
for change in frame["changes"].as_array().into_iter().flatten() {
collect_stream_text(change, &thread, &mut texts);
}
original |= has_text(&frame, &texts, "Copperstream Sunbeam");
idle |= sendable(&frame);
}
send(
&mut stream,
json!({"type":"act","id":"select-thread","scope":wire_scope,"approval":null,
"action":{"select_thread":thread}}),
);
loop {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
same_scope(
&frame,
"the signed client opened the thread on the exact scope",
);
for change in frame["changes"].as_array().into_iter().flatten() {
collect_stream_text(change, &thread, &mut texts);
}
if frame["type"] == "ack" && frame["id"] == "select-thread" {
break;
}
}
let operator = rt
.block_on(client.operator(OpenTerminal::NativeSession {
scope: scope.clone(),
thread: thread.clone(),
}))
.unwrap();
let Some(Event::Review { review, cwd }) = rt.block_on(operator.next()) else {
panic!("expected the native session's exact command review");
};
assert_eq!(cwd, project, "the terminal runs in the scope's project");
let native = thread
.split(':')
.nth(2)
.filter(|id| !id.is_empty())
.expect("the canonical thread carries its stock Claude session ID");
assert!(
review.ends_with(&format!("claude --model fixture/demo --resume {native}")),
"the preview names the exact stock argv and route: {review}"
);
assert_eq!(
operator.keys("exit 0\r").unwrap_err().kind(),
io::ErrorKind::InvalidInput,
"no input reaches the terminal before the reviewed Run"
);
witness("review");

operator.run().unwrap();
assert!(matches!(
rt.block_on(operator.next()),
Some(Event::Running { running: true })
));
witness("running");
let mut screen = String::new();
while screen.trim().is_empty() {
match rt.block_on(operator.next()) {
Some(Event::Screen { screen: text, .. }) => screen = text,
Some(Event::Error { error }) => panic!("the terminal failed: {error}"),
Some(Event::Exit { .. }) => panic!("the terminal exited before drawing its screen"),
Some(_) => {}
None => panic!("the operator socket ended before drawing a screen"),
}
}
witness("screen");
// The phone's Disconnect closes the operator socket: the host kills and
// reaps the PTY, then resumes the same thread for the host's own turn.
drop(operator);
// The host's TerminalText releases the stock process: this same stream
// loses the thread's send capability, then regains it only after the
// returned lease has resumed the thread and reloaded its history.
let mut released = false;
loop {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
same_scope(&frame, "the host kept the exact scope across the handoff");
for change in frame["changes"].as_array().into_iter().flatten() {
collect_stream_text(change, &thread, &mut texts);
}
if !released {
released = session_rows(&frame, &wire_scope).into_iter().any(|row| {
row["id"].as_str() == Some(thread.as_str())
&& !row["capabilities"].as_array().is_some_and(|caps| {
caps.iter()
.any(|cap| matches!(cap.as_str(), Some("send" | "steer")))
})
});
} else if sendable(&frame) && has_text(&frame, &texts, "Copperstream Sunbeam") {
break;
}
}
witness("exit");
send(
&mut stream,
json!({"type":"act","id":"terminal-followup","scope":wire_scope,"approval":null,
"action":{"send_text":[thread,"Back from native terminal"]}}),
);
loop {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
if frame["scope"]
.as_object()
.is_some_and(|scope| !scope.is_empty())
{
assert_eq!(
frame["scope"], wire_scope,
"the follow-up turn stayed on the exact scope"
);
}
if frame["type"] == "opened"
&& let Some(id) = frame["thread"].as_str()
{
assert_eq!(id, thread, "the follow-up turn stayed on the same thread");
}
for change in frame["changes"].as_array().into_iter().flatten() {
collect_stream_text(change, &thread, &mut texts);
}
let text = texts.values().map(String::as_str).collect::<String>();
if text.contains("Back from native terminal")
&& text.contains("Fixture completed.")
&& frame["changes"]
.as_array()
.into_iter()
.flatten()
.any(|change| {
change["kind"] == "notification"
&& change["event"] == "finished"
&& change["thread"].as_str() == Some(thread.as_str())
})
{
break;
}
}
witness("followup");
rt.block_on(client.revoke_self()).unwrap();
assert!(rt.block_on(client.session()).is_err());
credential.discard_key().unwrap();
}

fn scope_state<'a>(frame: &'a Value, scope: &Value) -> Option<&'a Value> {
frame["scopes"]
.as_array()?
Expand Down
45 changes: 43 additions & 2 deletions desktop/ox-host-web/tests/native_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def request(frame):
assert row["parent_host"] and row["has_project"] and row["status"] == "online"


def paired_host(host_state, root, stack):
def paired_host(host_state, root, stack, terminal=False):
"""Enable a disposable TLS endpoint and pair one fresh native device."""
state_dir = Path(host_state)
root = Path(root)
Expand All @@ -74,7 +74,9 @@ def revoke():
admin(state_dir, {"type": "revoke", "id": device["id"]})

stack.callback(revoke)
invitation = admin(state_dir, {"type": "pair", "login": "[email protected]"})["pairing"]
invitation = admin(state_dir, {
"type": "pair", "login": "[email protected]", "terminal": terminal,
})["pairing"]
(root / "code").write_text(invitation["short_code"])
(root / "host-id").write_text((state_dir / "host-id").read_text())
certificate(root)
Expand Down Expand Up @@ -186,6 +188,45 @@ def reap(exc_type, _exc_value, _traceback):
return process, root / "witness", root / "default", root / "stop"


def terminal_continuity(host_state, root, env, harness, thread, project, route, stack):
"""Preview, run and disconnect the exact stock thread from a signed client, then continue it."""
if not thread:
raise AssertionError("Expected an exact thread")
state_dir, root, origin, port = paired_host(host_state, root, stack, terminal=True)
(root / "terminal.json").write_text(
json.dumps({"thread": thread, "project": str(project), "route": route})
)
process = subprocess.Popen(
[harness, "--exact", "client::fixture::native_continuity_terminal", "--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 terminal fixture exited {code}"
assert not admin(state_dir, {"type": "status"})["devices"], (
"native terminal fixture did not revoke its device"
)

stack.push(reap)
return process, 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