Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

tooling: [f] to restart Vite in just run_local (#6506)

Peter Chinman1b6c37924762
diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.md
index f16826fc85..1abbab2864 100644
--- a/docs/RUNNING_LOCALLY.md
+++ b/docs/RUNNING_LOCALLY.md
@@ -204,6 +204,8 @@ GenAI content is bounded by `genai_telemetry`; check
While `run_local` is attached:
- Press `r` to rebuild the changed Rust services and reload them.
+- Press `f` to restart Vite with the same frontend port and configuration. This
+ also recovers a stuck frontend reload and leaves backend services and data intact.
- Press `q` to stop the stack and exit.
Use `q`, not the terminal close button. `q` stops and removes the containers at once. The next start does not have to clean up a stale stack.
diff --git a/tooling/xtask/crates/xtask_local/src/local.rs b/tooling/xtask/crates/xtask_local/src/local.rs
index a9e45a2926..372b724fba 100644
--- a/tooling/xtask/crates/xtask_local/src/local.rs
+++ b/tooling/xtask/crates/xtask_local/src/local.rs
@@ -431,7 +431,7 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {
}
// Non-interactive (piped/CI): just hold the dev server until it exits.
Some(mut fe) => {
- let status = fe.child.wait()?;
+ let status = fe.process.child.wait()?;
if !status.success() {
let out = fe.tail_output(40);
if !out.trim().is_empty() {
@@ -447,7 +447,9 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {
/// Print the hotkey legend shown while attached to a running stack.
fn print_hotkeys(stage: &Stage) {
- stage.note(" [r] rebuild & reload services [q] quit (tears the stack down)");
+ stage.note(
+ " [r] rebuild & reload services [f] restart Vite [q] quit (tears the stack down)",
+ );
}
/// Re-build the service binaries on the host and restart only the containers
@@ -557,7 +559,8 @@ fn binary_mtime(
}
/// Stay attached to the running stack, handling hotkeys until the user quits or
-/// the frontend exits. `r` rebuilds + reloads the services; `q`/Esc/Ctrl-C stops
+/// the frontend exits. `r` rebuilds + reloads the services; `f` restarts Vite;
+/// `q`/Esc/Ctrl-C stops
/// the frontend and tears the whole stack down (so the next run starts clean and
/// fast). An unexpected frontend exit just returns, leaving the stack up for
/// inspection — the next run's start-of-run teardown will reclaim it.
@@ -576,7 +579,7 @@ fn interact(
print_hotkeys(stage);
loop {
// Noticed on the next keypress; the frontend running silently is fine.
- if let Some(status) = fe.child.try_wait()? {
+ if let Some(status) = fe.process.child.try_wait()? {
let out = fe.tail_output(40);
if !out.trim().is_empty() {
stage.note("frontend output (last lines):");
@@ -598,6 +601,13 @@ fn interact(
let _ = rebuild_and_reload(stage, mode, instance, env, target, build_aux_services);
print_hotkeys(stage);
}
+ Ok(Key::Char('f' | 'F')) => {
+ let _ = term.clear_last_lines(1);
+ // A failed restart returns with captured output and leaves the
+ // backend containers running, like an unexpected frontend exit.
+ fe.restart(stage)?;
+ print_hotkeys(stage);
+ }
Ok(Key::Char('q' | 'Q') | Key::Escape | Key::CtrlC) | Err(_) => {
// Kill the frontend's whole process group (bun + Vite), not just
// bun — otherwise Vite is orphaned and keeps holding the port.
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
index a3c56aa68f..41e24ba44e 100644
--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
@@ -164,12 +164,39 @@ pub fn wait_backend_ready(stage: &Stage, instance: &Instance) -> Result<()> {
/// A running frontend dev server plus its captured output, so an unexpected
/// exit can be explained (the output is otherwise suppressed).
pub struct Frontend {
+ pub process: FrontendProcess,
+ command: Command,
+ port: u16,
+}
+
+/// One dev-server process and its captured output, replaced on restart.
+pub struct FrontendProcess {
pub child: Child,
captured: Arc<Mutex<Vec<u8>>>,
drains: Vec<JoinHandle<()>>,
}
impl Frontend {
+ /// Restart only Vite, preserving the command, environment, and instance port.
+ /// Killing the old process group also recovers a stuck in-process reload.
+ pub fn restart(&mut self, stage: &Stage) -> Result<()> {
+ self.shutdown();
+ self.process = spawn(stage, &mut self.command, self.port)?;
+ Ok(())
+ }
+
+ /// Stop the current dev-server process group.
+ pub fn shutdown(&mut self) {
+ self.process.shutdown();
+ }
+
+ /// Return the last output from an exited dev server.
+ pub fn tail_output(&mut self, lines: usize) -> String {
+ self.process.tail_output(lines)
+ }
+}
+
+impl FrontendProcess {
/// Stop the dev server and all its children. `bun run dev` spawns Vite (and
/// friends), which we put in their own process group at spawn — so signal the
/// GROUP (negative pid). SIGKILL is enough: the kernel releases the port the
@@ -201,7 +228,7 @@ impl Frontend {
}
}
-impl Drop for Frontend {
+impl Drop for FrontendProcess {
fn drop(&mut self) {
self.shutdown();
}
@@ -275,6 +302,15 @@ pub fn start(
for (k, v) in dev_env(instance, mode, traces_enabled, enable_onboarding) {
cmd.env(k, v);
}
+ let process = spawn(stage, &mut cmd, port)?;
+ Ok(Some(Frontend {
+ process,
+ command: cmd,
+ port,
+ }))
+}
+
+fn spawn(stage: &Stage, cmd: &mut Command, port: u16) -> Result<FrontendProcess> {
let mut child = cmd.spawn().context("launching `bun run dev`")?;
// Drain stdout+stderr into a buffer on their own threads (a full pipe would
@@ -334,11 +370,11 @@ pub fn start(
anyhow::bail!("{error}\nfrontend output (last lines):\n{out}");
}
- Ok(Some(Frontend {
+ Ok(FrontendProcess {
child,
captured,
drains,
- }))
+ })
}
/// Copy a child pipe into the shared capture buffer until EOF.
@@ -353,3 +389,6 @@ fn drain_into(reader: &mut impl Read, buf: &Mutex<Vec<u8>>) {
}
}
}
+
+#[cfg(test)]
+mod test;
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs
new file mode 100644
index 0000000000..fff260daa6
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs
@@ -0,0 +1,86 @@
+use super::*;
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+
+fn test_frontend(stage: &Stage) -> Frontend {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+
+ let mut command = Command::new("python3");
+ command
+ .args([
+ "-u",
+ "-c",
+ include_str!("test_server.py"),
+ &port.to_string(),
+ ])
+ .current_dir(app_dir())
+ .env("VITE_LOCAL_BACKEND_ORIGIN", "http://localhost:18090")
+ .process_group(0)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ let process = spawn(stage, &mut command, port).unwrap();
+ Frontend {
+ process,
+ command,
+ port,
+ }
+}
+
+fn response(frontend: &Frontend) -> String {
+ let mut stream = TcpStream::connect(("127.0.0.1", frontend.port)).unwrap();
+ stream
+ .set_read_timeout(Some(std::time::Duration::from_secs(5)))
+ .unwrap();
+ stream
+ .write_all(b"GET / HTTP/1.0\r\nHost: localhost\r\n\r\n")
+ .unwrap();
+ let mut body = String::new();
+ stream.read_to_string(&mut body).unwrap();
+ body
+}
+
+#[test]
+fn restart_replaces_process_and_preserves_port_environment_and_directory() {
+ let stage = Stage::from_env().quiet();
+ let mut frontend = test_frontend(&stage);
+ // Represents an unrelated backend listener that restarting Vite must not touch.
+ let backend = TcpListener::bind("127.0.0.1:0").unwrap();
+ let original_port = frontend.port;
+
+ for _ in 0..2 {
+ let original_pid = frontend.process.child.id();
+ frontend.restart(&stage).unwrap();
+
+ assert_ne!(frontend.process.child.id(), original_pid);
+ // SAFETY: signal 0 only probes whether the old process still exists.
+ assert_eq!(unsafe { libc::kill(original_pid as i32, 0) }, -1);
+ assert_eq!(frontend.port, original_port);
+ let body = response(&frontend);
+ assert!(body.contains("http://localhost:18090"));
+ assert!(body.contains(&app_dir().display().to_string()));
+ assert!(TcpStream::connect(backend.local_addr().unwrap()).is_ok());
+ }
+
+ frontend.shutdown();
+ assert!(TcpStream::connect(("127.0.0.1", original_port)).is_err());
+}
+
+#[test]
+fn failed_restart_reports_output_and_releases_the_port() {
+ let stage = Stage::from_env().quiet();
+ let mut frontend = test_frontend(&stage);
+ frontend.command = Command::new("sh");
+ frontend
+ .command
+ .args(["-c", "echo vite-startup-failed >&2; exit 1"])
+ .process_group(0)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ let error = frontend.restart(&stage).unwrap_err();
+ assert!(error.to_string().contains("vite-startup-failed"));
+ assert!(TcpStream::connect(("127.0.0.1", frontend.port)).is_err());
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend/test_server.py b/tooling/xtask/crates/xtask_local/src/local/frontend/test_server.py
new file mode 100644
index 0000000000..25debc58dd
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend/test_server.py
@@ -0,0 +1,15 @@
+import http.server
+import os
+import sys
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(
+ (os.environ["VITE_LOCAL_BACKEND_ORIGIN"] + "\n" + os.getcwd()).encode()
+ )
+
+
+http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()