mirror of
https://github.com/vercel-labs/agent-browser.git
synced 2026-11-23 02:09:25 +08:00
* fix(daemon): delete <session>.config on daemon exit The CLI writes <session>.config once a daemon is ready, but shutdown never removed it, so one file per session name accumulated in the socket directory. Remove it during run_daemon shutdown, before the .pid file, and only while .pid still holds this daemon's pid so a replacement daemon for the same session keeps its config. Fixes #2098 Co-Authored-By: jomatsu <50577611+jomatsu@users.noreply.github.com> * refactor(cli): declare session sidecar files in one place Daemon shutdown and the CLI's stale cleanup each kept their own list of files to remove, and the lists had drifted (.config was missed on shutdown, .engine/.provider/.extensions on stale cleanup). - Add session_files.rs with a SessionFile enum. Each file declares its extension and whether it only describes a running daemon (.target and .log persist). - Both cleanup paths now call remove_daemon_files, which removes every daemon file. - Shutdown removes them only while .pid still holds our pid, so a replacement daemon keeps all of its files, not just .config. - Build every sidecar path through SessionFile instead of format!. Tested with cargo fmt, clippy -D warnings and cargo test on macOS. Not compiled for Windows locally. * fix(cli): route every sidecar deletion through the owned cleanup Review follow-ups on the shared sidecar list. - Drop the early .port (Windows) and .stream deletions in the socket server. They ran before the ownership check, and the final cleanup already removes both. - Dashboard kill used its own list and left .version, .config, .provider and .port behind. It now uses remove_daemon_files, guarded by the killed pid. - Add integration tests that run a real daemon and shut it down: one checks daemon files go and .target/.log stay, one checks a replacement daemon's files are left alone. Both fail if the cleanup block is removed or made unconditional. - Assert literal survivors in the session_files unit test instead of deriving them from is_daemon_file. Tested with cargo fmt, clippy -D warnings and cargo test on macOS. * fix(daemon): stop accepting connections before replying to close (#2138) The daemon replied to close and kept its listener open for another ~100ms before exiting. A command sent right after close returned could connect to the exiting daemon and fail with "Invalid response: EOF", so `close` followed by `open` lost the page. Close now goes through a small handshake: the connection that handled close asks the accept loop to stop, the loop drops the listener, and only then is the reply written. The next command gets a refused connection, cleans up the old session files, and starts a fresh daemon. The old daemon's exit cleanup leaves those new files alone because it only removes files while .pid still holds its own pid. Fixes #2134 Tested with cargo fmt, clippy -D warnings and cargo test on macOS, plus an integration test that fails without the fix. With real Chrome, `open A; close; open B` failed 20/20 before and 0/20 after. --------- Co-authored-by: jomatsu <50577611+jomatsu@users.noreply.github.com>
152 lines
4.7 KiB
Rust
152 lines
4.7 KiB
Rust
#![cfg(unix)]
|
|
|
|
use std::fs;
|
|
use std::io::{BufRead, BufReader, Write};
|
|
use std::os::unix::net::UnixStream;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Child, Command, Stdio};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant};
|
|
use tempfile::{Builder, TempDir};
|
|
|
|
const BIN: &str = env!("CARGO_BIN_EXE_agent-browser");
|
|
const SESSION: &str = "sf";
|
|
const TIMEOUT: Duration = Duration::from_secs(15);
|
|
|
|
struct Daemon {
|
|
child: Child,
|
|
dir: TempDir,
|
|
}
|
|
|
|
impl Daemon {
|
|
fn start() -> Self {
|
|
// Keep the path short: Unix socket paths are limited to ~104 bytes.
|
|
let dir = Builder::new().prefix("ab-sf").tempdir_in("/tmp").unwrap();
|
|
let child = Command::new(BIN)
|
|
.env("AGENT_BROWSER_DAEMON", "1")
|
|
.env("AGENT_BROWSER_SESSION", SESSION)
|
|
.env("AGENT_BROWSER_SOCKET_DIR", dir.path())
|
|
.env("AGENT_BROWSER_IDLE_TIMEOUT_MS", "0")
|
|
.env_remove("AGENT_BROWSER_CDP")
|
|
.env_remove("AGENT_BROWSER_AUTO_CONNECT")
|
|
.env_remove("AGENT_BROWSER_PROVIDER")
|
|
.env_remove("AGENT_BROWSER_NAMESPACE")
|
|
.env_remove("XDG_RUNTIME_DIR")
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::null())
|
|
.spawn()
|
|
.unwrap();
|
|
let daemon = Self { child, dir };
|
|
daemon.wait_for(|| daemon.path("sock").exists() && daemon.path("pid").exists());
|
|
daemon
|
|
}
|
|
|
|
fn path(&self, ext: &str) -> PathBuf {
|
|
self.dir.path().join(format!("{SESSION}.{ext}"))
|
|
}
|
|
|
|
fn wait_for(&self, cond: impl Fn() -> bool) {
|
|
let start = Instant::now();
|
|
while !cond() {
|
|
assert!(start.elapsed() < TIMEOUT, "timed out waiting for condition");
|
|
thread::sleep(Duration::from_millis(20));
|
|
}
|
|
}
|
|
|
|
fn request_shutdown(&self) {
|
|
let mut stream = UnixStream::connect(self.path("sock")).unwrap();
|
|
stream.set_read_timeout(Some(TIMEOUT)).unwrap();
|
|
stream
|
|
.write_all(b"{\"id\":\"t\",\"action\":\"__agent_browser_internal_shutdown\"}\n")
|
|
.unwrap();
|
|
let mut line = String::new();
|
|
BufReader::new(stream).read_line(&mut line).unwrap();
|
|
assert!(line.contains("\"t\""), "unexpected response: {line}");
|
|
}
|
|
|
|
fn wait_for_exit(&mut self) {
|
|
let start = Instant::now();
|
|
while self.child.try_wait().unwrap().is_none() {
|
|
assert!(start.elapsed() < TIMEOUT, "daemon did not exit");
|
|
thread::sleep(Duration::from_millis(20));
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for Daemon {
|
|
fn drop(&mut self) {
|
|
let _ = self.child.kill();
|
|
let _ = self.child.wait();
|
|
}
|
|
}
|
|
|
|
fn read(path: &Path) -> String {
|
|
fs::read_to_string(path).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn test_daemon_shutdown_removes_daemon_files_and_keeps_persistent_ones() {
|
|
let mut d = Daemon::start();
|
|
for ext in ["config", "engine", "provider", "extensions"] {
|
|
fs::write(d.path(ext), format!("dummy-{ext}")).unwrap();
|
|
}
|
|
fs::write(d.path("target"), "target-content").unwrap();
|
|
fs::write(d.path("log"), "log-content").unwrap();
|
|
|
|
d.request_shutdown();
|
|
d.wait_for_exit();
|
|
|
|
for ext in [
|
|
"sock",
|
|
"pid",
|
|
"version",
|
|
"config",
|
|
"stream",
|
|
"engine",
|
|
"provider",
|
|
"extensions",
|
|
] {
|
|
assert!(!d.path(ext).exists(), "{ext} should be removed");
|
|
}
|
|
assert_eq!(read(&d.path("target")), "target-content");
|
|
assert_eq!(read(&d.path("log")), "log-content");
|
|
}
|
|
|
|
#[test]
|
|
fn test_daemon_shutdown_keeps_files_of_replacement_daemon() {
|
|
let mut d = Daemon::start();
|
|
fs::write(d.path("pid"), "999999").unwrap();
|
|
fs::write(d.path("config"), "replacement-config").unwrap();
|
|
fs::write(d.path("engine"), "replacement-engine").unwrap();
|
|
fs::write(d.path("version"), "replacement-version").unwrap();
|
|
|
|
d.request_shutdown();
|
|
d.wait_for_exit();
|
|
|
|
assert_eq!(read(&d.path("pid")), "999999");
|
|
assert_eq!(read(&d.path("config")), "replacement-config");
|
|
assert_eq!(read(&d.path("engine")), "replacement-engine");
|
|
assert_eq!(read(&d.path("version")), "replacement-version");
|
|
assert!(
|
|
d.path("sock").exists(),
|
|
"replacement socket path should remain"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_daemon_refuses_connections_once_close_replied() {
|
|
let mut d = Daemon::start();
|
|
// Guard against a false pass: the socket must accept connections before close.
|
|
UnixStream::connect(d.path("sock")).expect("socket should accept before close");
|
|
|
|
d.request_shutdown();
|
|
// No sleep: the listener must already be gone once the close reply was read.
|
|
let result = UnixStream::connect(d.path("sock"));
|
|
assert!(
|
|
result.is_err(),
|
|
"socket still accepted a connection after the close reply"
|
|
);
|
|
d.wait_for_exit();
|
|
}
|