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
3 changes: 2 additions & 1 deletion .github/workflows/desktop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,9 @@ jobs:
env:
FIXTURE: ${{ steps.window-tests.outputs.dir }}
run: |
harness=$(desktop/ci/test-bin.sh ox_host_web --profile release -p ox-host-web --features server,client --lib)
xvfb-run -a -s '-screen 0 1280x900x24' python3 desktop/tests/host_continuity_window.py \
"$FIXTURE/ox-desktop/ox-desktop" "$FIXTURE/node_modules/.bin/claude"
"$FIXTURE/ox-desktop/ox-desktop" "$FIXTURE/node_modules/.bin/claude" --harness "$harness"
- name: Exercise concurrent stock sessions in the packaged Linux window
if: runner.os == 'Linux' && !cancelled() && steps.window-tests.outcome == 'success'
env:
Expand Down
180 changes: 180 additions & 0 deletions desktop/ox-host-web/src/client/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,186 @@ fn native_desktop() {
credential.discard_key().unwrap();
}

#[test]
#[ignore = "launched by the isolated native continuity fixture"]
fn native_continuity_approval() {
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("scope.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();
assert!(
supplied["project"].is_string(),
"the fixture supplies the project"
);
assert!(
supplied["route"].is_object(),
"the fixture supplies the route"
);
let scope = json!({
"project": supplied["project"].clone(),
"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")).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 handshake = || {
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),
version: VERSION,
..
} = read(&mut stream)
else {
panic!("expected compatible host");
};
assert_eq!(host.id.as_deref(), Some(host_id));
stream
};
let subscribe = |stream: &mut std::io::BufReader<UnixStream>| {
writeln!(
stream.get_mut(),
"{}",
serde_json::to_string(&json!({
"type": "subscribe", "scope": scope, "terminal": false, "after": null
}))
.unwrap()
)
.unwrap();
};
let mut stream = handshake();
subscribe(&mut stream);
let mut allow: Option<(Value, String, usize)> = None;
let mut finished = false;
while allow.is_none() || !finished {
let frame = serde_json::to_value(read(&mut stream)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
let asks = match frame["type"].as_str() {
Some("snapshot") => {
let state = frame["scopes"]
.as_array()
.and_then(|scopes| scopes.iter().find(|state| state["scope"] == scope))
.unwrap_or_else(|| {
panic!("host did not subscribe the supplied project and route: {scope}")
});
state["asks"].as_array().cloned().unwrap_or_default()
}
Some("delta") => {
assert_eq!(frame["scope"], scope, "the host scoped the change exactly");
let changes = frame["changes"].as_array().cloned().unwrap_or_default();
finished = allow.is_some()
&& changes.iter().any(|change| {
change["kind"] == "notification"
&& change["event"] == "finished"
&& change["thread"].as_str() == Some(thread.as_str())
});
changes
.iter()
.filter(|change| change["kind"] == "asks")
.flat_map(|change| change["asks"].as_array().cloned().unwrap_or_default())
.collect()
}
_ => continue,
};
if allow.is_none()
&& let Some(ask) = asks
.iter()
.find(|ask| ask["thread"].as_str() == Some(thread.as_str()))
{
let (id, token, choice) = stock_allow(ask);
writeln!(
stream.get_mut(),
"{}",
serde_json::to_string(&json!({
"type": "act",
"id": "continuity-allow",
"scope": scope,
"approval": &token,
"action": {"answer_ask": [&id, choice]},
}))
.unwrap()
)
.unwrap();
allow = Some((id, token, choice));
}
}
let (ask_id, _, _) = allow.expect("the exact thread had a pending stock approval");
// A fresh subscription proves the host no longer lists the approval, rather
// than only that the allowed tool happened to finish.
drop(stream);
let mut check = handshake();
subscribe(&mut check);
loop {
let frame = serde_json::to_value(read(&mut check)).unwrap();
assert_ne!(frame["type"], "error", "{}", frame["message"]);
if frame["type"] != "snapshot" {
continue;
}
let state = frame["scopes"]
.as_array()
.and_then(|scopes| scopes.iter().find(|state| state["scope"] == scope))
.unwrap_or_else(|| {
panic!("host did not resubscribe the supplied project and route: {scope}")
});
assert!(
state["asks"]
.as_array()
.into_iter()
.flatten()
.all(|ask| ask["id"] != ask_id),
"the allowed approval must clear"
);
break;
}
drop(check);
rt.block_on(client.revoke_self()).unwrap();
assert!(rt.block_on(client.session()).is_err());
credential.discard_key().unwrap();
}

/// Read the stock Claude tool prompt's own decisions and choose Allow once.
fn stock_allow(ask: &Value) -> (Value, String, usize) {
assert_eq!(
ask["title"], "Allow Claude tool call",
"the pending approval must be the stock Claude tool prompt"
);
let choice = ask["choices"]
.as_array()
.expect("the stock prompt lists its decisions")
.iter()
.position(|choice| choice.as_str() == Some("Allow once"))
.expect("the stock prompt offers Allow once");
let token = ask["token"]
.as_str()
.filter(|token| !token.is_empty())
.expect("the pending approval has its token")
.to_owned();
(ask["id"].clone(), token, choice)
}

fn stock_turn(
connect: impl Fn() -> std::io::BufReader<UnixStream>,
scope: Value,
Expand Down
49 changes: 49 additions & 0 deletions desktop/ox-host-web/tests/native_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,55 @@ 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."""
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")
wait(lambda: (state_dir / "remote-admin.sock").exists())
if admin(state_dir, {"type": "status"})["devices"]:
raise AssertionError("Expected a fresh disposable remote state")
root.mkdir(parents=True, exist_ok=True)
public = ThreadedTCP(("127.0.0.1", 0), Forward)
port = public.server_address[1]
origin = f"https://studio.fixture.ts.net:{port}"
public.backend = admin(state_dir, {"type": "enable", "origin": origin, "port": 0})["port"]
stack.callback(admin, state_dir, {"type": "disable"})

def revoke():
for device in admin(state_dir, {"type": "status"})["devices"]:
admin(state_dir, {"type": "revoke", "id": device["id"]})

stack.callback(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)
subprocess.run(
[harness, "--exact", "client::fixture::native_continuity_approval", "--ignored"],
check=True,
timeout=180,
env=dict(
env,
OX_TEST_NATIVE_DIR=str(root),
OX_TEST_LOOPBACK=f"127.0.0.1:{port}",
OX_TEST_ORIGIN=origin,
),
)
assert not admin(state_dir, {"type": "status"})["devices"], (
"native approval fixture did not revoke its device"
)


def run(host, cli, harness, stock=None):
with tempfile.TemporaryDirectory(prefix="ox-native-") as tmp, ExitStack() as stack:
root = Path(tmp)
Expand Down
22 changes: 16 additions & 6 deletions desktop/tests/host_continuity_window.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Close the actual desktop during a stock tool approval, approve from a paired PWA and reopen."""
"""Close the actual desktop during a stock tool approval, approve from a signed native client and reopen."""
import argparse
from contextlib import contextmanager, ExitStack
import json
Expand All @@ -16,9 +16,12 @@
from mixed_runtime_window import Window

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "ox-host-web/tests"))
from browser import answer_from_phone, paired_browser
from browser import paired_browser
from native_client import approve_continuity
from tailnet_fixture import admin, wait

ROUTE = {"runtime": "claude", "billing": {"api": "fixture/demo"}}


@contextmanager
def desktop_window(gui, root, env, project, name):
Expand Down Expand Up @@ -192,7 +195,7 @@ def live_session(window, provider, env, root):
print("PASS cross-project session appears live, bidirectional prompt and stream, approval, confirmed YOLO/restore, and phone Stop.",flush=True)


def run(gui, claude, root, capture=None):
def run(gui, claude, root, harness, capture=None):
with ExitStack() as stack:
provider, env = setup(root, claude, stack)
project = root / "Alpha"
Expand Down Expand Up @@ -221,7 +224,11 @@ def run(gui, claude, root, capture=None):
window.command("import","-window",window.id,str(capture))
marker = project / "approved.txt"
assert not marker.exists()
answer_from_phone(Path(env["OX_HOST_SOCKET"]), Path(env["OX_HOST_STATE_DIR"]), thread, env)
with ExitStack() as native:
approve_continuity(
Path(env["OX_HOST_STATE_DIR"]), root / "native-approval", env, harness,
thread, project.resolve(), ROUTE, native,
)
deadline = time.monotonic() + 15
while not marker.exists() and time.monotonic() < deadline:
time.sleep(.05)
Expand All @@ -235,14 +242,17 @@ def run(gui, claude, root, capture=None):
local_tool_terminal(restored,provider,root,project)
live_session(restored,provider,env,root)
assert not provider.errors, provider.errors
print("PASS stock Claude, desktop exit, paired browser approval, original-project write, and desktop reopen.")
print("PASS stock Claude, desktop exit, signed native approval, original-project write, and desktop reopen.")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("gui", type=Path)
parser.add_argument("claude", type=Path)
parser.add_argument("--harness", type=Path, required=True)
parser.add_argument("--capture", type=Path)
args = parser.parse_args()
harness = args.harness.resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="ox-phone-") as tmp:
run(args.gui.resolve(strict=True), args.claude.resolve(strict=True), Path(tmp),args.capture)
run(args.gui.resolve(strict=True), args.claude.resolve(strict=True), Path(tmp), harness,
args.capture)
Loading