Lutra/crates/control/tests/events.rs
danny d097558ba5 M4.10: remotes: fetch, pull, push, clone and manage remotes
Owner decision D23: Lutra runs fetch, pull (merge or rebase per the new
git.pull.mode setting), push (upstream set on the first push) and clone
through the user's git. Any HTTPS or SSH server works; sign-in stays with
git's credential helper (its own window is allowed for network calls only)
and the ssh agent. Terminal prompts stay off, ext:: is refused, and URL
userinfo is redacted in every message, progress line and remote listing.

- vcs: Call::network with a 30 min timeout, a stderr progress sink and a
  Cancel flag that kills git's process group; remote.rs with clone_repo,
  fetch, pull, push (--porcelain rejections), remotes and add/set-url/
  remove; explained refusals (rejected push, sign-in, host key, not found,
  unreachable, no upstream, local changes, conflicts).
- engine: git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/
  remoteRemove, one network call at a time, gitProgress events,
  gitChanged after changes.
- ui: status-bar progress with Cancel and ahead/behind, vcs.fetch/pull/
  push/clone/manageRemotes (Git menu, no default shortcuts), Clone
  Repository and Manage Remotes dialogs; desktop pick_dir IPC.
- Tests against local bare repositories only (vcs 8, engine 3, Vitest 11)
  plus unit and property tests; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:50:26 +01:00

247 lines
8.6 KiB
Rust

//! `events.subscribe` over a real TCP socket: engine events from commands and
//! from changes on disk arrive as `{"event": ...}` lines.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Arc;
use std::time::{Duration, Instant};
use lutra_testkit::EngineBackend;
use serde_json::{Value, json};
/// A client that keeps responses and event lines apart.
struct Client {
reader: BufReader<TcpStream>,
writer: TcpStream,
events: Vec<Value>,
}
impl Client {
fn connect(addr: std::net::SocketAddr) -> Self {
let stream = TcpStream::connect(addr).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
Self {
writer: stream.try_clone().unwrap(),
reader: BufReader::new(stream),
events: Vec::new(),
}
}
fn line(&mut self) -> Value {
let mut line = String::new();
self.reader.read_line(&mut line).expect("line within 5 s");
serde_json::from_str(&line).unwrap()
}
/// Sends a request and returns its response, collecting event lines that
/// arrive before it.
fn call(&mut self, request: Value) -> Value {
self.writer
.write_all(format!("{request}\n").as_bytes())
.unwrap();
loop {
let line = self.line();
if line.get("event").is_some() {
self.events.push(line["event"].clone());
} else {
return line;
}
}
}
/// Waits until an event of `kind` has arrived and returns it.
fn event(&mut self, kind: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(at) = self.events.iter().position(|e| e["kind"] == kind) {
return self.events.remove(at);
}
assert!(
Instant::now() < deadline,
"no {kind} event; got {:?}",
self.events
);
let line = self.line();
if line.get("event").is_some() {
self.events.push(line["event"].clone());
}
}
}
}
fn execute(command: &str, params: Value) -> Value {
json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}})
}
#[test]
fn streams_command_and_disk_events() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.php"), "<?php\n").unwrap();
let backend = Arc::new(EngineBackend::new());
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
let r = client.call(json!({"id": 1, "method": "events.subscribe"}));
assert_eq!(r["result"]["subscribed"], true);
let again = client.call(json!({"id": 2, "method": "events.subscribe"}));
assert_eq!(again["result"]["subscribed"], true);
assert_eq!(
backend.subscribers.len(),
1,
"subscribing twice is idempotent"
);
let r = client.call(execute("project.open", json!({"path": dir.path()})));
assert!(r["result"]["root"].is_string(), "{r}");
client.event("projectOpened");
let r = client.call(execute("file.open", json!({"path": "a.php"})));
let id = r["result"]["id"].as_u64().unwrap();
assert_eq!(client.event("bufferOpened")["id"], id);
let r = client.call(execute("file.open", json!({"path": "a.php"})));
assert_eq!(r["result"]["id"], id);
assert_eq!(client.event("bufferFocused")["id"], id);
let r = client.call(execute(
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 6, "insert": "echo 1;\n"}]}),
));
assert_eq!(r["result"]["version"], 2);
assert_eq!(client.event("bufferChanged")["version"], 2);
assert_eq!(client.event("dirtyChanged")["dirty"], true);
let r = client.call(execute(
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": []}),
));
assert_eq!(r["error"]["code"], "stale_version");
client.call(execute("file.save", json!({"id": id})));
assert_eq!(client.event("dirtyChanged")["dirty"], false);
assert_eq!(
std::fs::read_to_string(dir.path().join("a.php")).unwrap(),
"<?php\necho 1;\n"
);
std::fs::write(dir.path().join("b.php"), "b").unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
backend.pump();
client.call(json!({"id": "ping", "method": "app.ping"}));
if client.events.iter().any(|e| e["kind"] == "treeChanged") {
break;
}
assert!(
Instant::now() < deadline,
"no treeChanged; got {:?}",
client.events
);
std::thread::sleep(Duration::from_millis(50));
}
assert_eq!(client.event("treeChanged")["dir"], "");
}
#[test]
fn settings_changes_stream_and_persist() {
let dir = tempfile::tempdir().unwrap();
let config = lutra_testkit::engine_config(dir.path());
{
let backend = Arc::new(EngineBackend::with_config(config.clone()));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 1, "method": "events.subscribe"}));
let r = client.call(execute(
"settings.set",
json!({"key": "editor.fontSize", "value": 16}),
));
assert_eq!(r["result"]["value"], 16, "{r}");
assert_eq!(
client.event("settingsChanged")["keys"],
json!(["editor.fontSize"])
);
let r = client.call(execute(
"settings.set",
json!({"key": "editor.fontSize", "value": 4}),
));
assert_eq!(r["error"]["code"], "invalid_params");
}
{
let backend = Arc::new(EngineBackend::with_config(config.clone()));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
let r = client.call(execute(
"settings.get",
json!({"keys": ["editor.fontSize"]}),
));
assert_eq!(r["result"]["values"]["editor.fontSize"], 16, "{r}");
}
let file = config.config_dir.join("settings.json");
std::fs::write(&file, "{\"editor.fontSize\": 16,,").unwrap();
let backend = Arc::new(EngineBackend::with_config(config.clone()));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 1, "method": "events.subscribe"}));
let r = client.call(execute("settings.get", Value::Null));
assert_eq!(
r["result"]["values"],
json!({
"appearance.theme": "system",
"editor.fontSize": 14,
"ui.language": "en",
"php.executable": "",
"phpactor.path": "",
"phpactor.autoDownload": true,
"editor.autosave.onBlur": true,
"editor.autosave.onTabSwitch": true,
"editor.autosave.idleSeconds": 15,
"editor.completion.autoPopup": true,
"editor.completion.delayMs": 0,
"editor.hover.delayMs": 350,
"git.executable": "",
"git.pull.mode": "merge"
}),
"{r}"
);
let notice = client.event("notification");
assert_eq!(notice["level"], "warning");
assert_eq!(notice["messageKey"], "notification.settings.corrupt");
let backup = notice["params"]["backup"].as_str().unwrap();
assert!(backup.starts_with("settings.json.bad-"), "{backup}");
assert_eq!(
std::fs::read_to_string(config.config_dir.join(backup)).unwrap(),
"{\"editor.fontSize\": 16,,"
);
assert!(!file.exists());
}
#[test]
fn a_closed_connection_stops_receiving() {
let backend = Arc::new(EngineBackend::new());
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 1, "method": "events.subscribe"}));
assert_eq!(backend.subscribers.len(), 1);
drop(client);
let dir = tempfile::tempdir().unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !backend.subscribers.is_empty() {
assert!(Instant::now() < deadline, "subscriber was not dropped");
lutra_control::Backend::execute(
backend.as_ref(),
"project.open",
json!({"path": dir.path()}),
)
.unwrap();
std::thread::sleep(Duration::from_millis(100));
}
}