agentmux_launcher/second_instance.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(not(target_os = "windows"))]
5use crate::logging::log;
6
7/// Phase B.6 (post-fix) — forward an `open_new_window` request to
8/// the already-running host and let this launcher exit 0.
9///
10/// The host writes `<data-dir>/ipc-port` after CEF init as
11/// `port:token`, where the token is a forwarding token that opens only the
12/// commands the launcher sends (an older host writes its full token; both
13/// work as the bearer). We open a TCP connection to 127.0.0.1:port, send a
14/// minimal HTTP/1.1 POST to /ipc with the bearer token and a JSON
15/// body, and bail. We deliberately do NOT pull in reqwest: the
16/// launcher binary should stay tiny (~325 KB) and the protocol is
17/// fixed, so a hand-rolled request is the right tool.
18///
19/// Failure classification (codex P2 PR #598):
20/// - `Transient` — port file missing / unreadable / malformed.
21/// The host is alive (pipe held) but mid-startup; caller exits
22/// 0 silently so the user isn't punished for double-clicking
23/// quickly.
24/// - `Fatal` — port file is readable, but the HTTP path failed
25/// (connect refused, write failed, timeout). Either a hung
26/// host or a non-running-instance source of
27/// `ERROR_ACCESS_DENIED` (namespace conflict, security
28/// descriptor failure). Caller surfaces the dialog so the user
29/// sees a real problem rather than a silent no-op.
30pub(crate) enum ForwardError {
31 Transient(String),
32 Fatal(String),
33}
34
35impl ForwardError {
36 pub(crate) fn reason(&self) -> &str {
37 match self {
38 Self::Transient(r) | Self::Fatal(r) => r,
39 }
40 }
41}
42
43/// How long a relaunch keeps at it when the running instance's host didn't
44/// take its `open_new_window`: long enough for an instance that is quitting
45/// to let go of the single-instance socket/pipe (its launcher holds on until
46/// srv has closed every agent, up to `SRV_EXIT_WAIT`, via
47/// `upgrade::quiesce_srv`).
48pub(crate) const QUITTING_INSTANCE_WAIT: std::time::Duration =
49 std::time::Duration::from_secs(agentmux_common::process::SRV_EXIT_WAIT.as_secs() + 5);
50
51/// What [`await_running_instance`] ended with.
52pub(crate) enum Handoff<T> {
53 /// The old instance quit; this launcher holds the socket/pipe now.
54 Claimed(T),
55 /// The host answered and took the request.
56 Forwarded,
57 /// Neither within [`QUITTING_INSTANCE_WAIT`]; the last forward error.
58 GaveUp(ForwardError),
59}
60
61/// A relaunch whose forward failed with `first`: the running instance is
62/// starting (no port file yet) or quitting (its host is gone; a clean exit
63/// deletes the port file). Until [`QUITTING_INSTANCE_WAIT`] passes, take the
64/// socket/pipe as soon as the old launcher lets go of it, or forward as soon
65/// as the host answers. Shared by both supervisors.
66pub(crate) fn await_running_instance<T>(
67 mut try_claim: impl FnMut() -> Option<T>,
68 mut try_forward: impl FnMut() -> Result<(), ForwardError>,
69 first: ForwardError,
70) -> Handoff<T> {
71 let until = std::time::Instant::now() + QUITTING_INSTANCE_WAIT;
72 let mut last = first;
73 loop {
74 if let Some(claimed) = try_claim() {
75 return Handoff::Claimed(claimed);
76 }
77 if std::time::Instant::now() >= until {
78 return Handoff::GaveUp(last);
79 }
80 std::thread::sleep(std::time::Duration::from_millis(250));
81 match try_forward() {
82 Ok(()) => return Handoff::Forwarded,
83 Err(e) => last = e,
84 }
85 }
86}
87
88/// Forward an arbitrary host IPC command over the same authenticated
89/// localhost channel `forward_open_new_window` uses.
90///
91/// Extracted (issue #2977 Workstream 1) so the tray can also send `quit_app`
92/// without a second copy of the port-file read, bearer-token handshake, and
93/// the read-the-response subtlety documented below — all of which are easy to
94/// get subtly wrong and none of which are specific to opening a window.
95/// `forward_open_new_window` is now a thin wrapper, so the long-standing
96/// second-instance path keeps its exact behavior.
97pub(crate) fn forward_host_cmd(
98 data_dir: &std::path::Path,
99 dir_hash: &str,
100 cmd: &str,
101) -> Result<(), ForwardError> {
102 forward_host_cmd_impl(data_dir, dir_hash, cmd)
103}
104
105pub(crate) fn forward_open_new_window(
106 data_dir: &std::path::Path,
107 dir_hash: &str,
108) -> Result<(), ForwardError> {
109 forward_host_cmd_impl(data_dir, dir_hash, "open_new_window")
110}
111
112/// What a launcher that lost the single-instance race hands the running
113/// instance: the deep link the operating system started it with
114/// (`launch_link`, `open_link`), else a request for a new window.
115pub(crate) fn forward_launch(
116 data_dir: &std::path::Path,
117 dir_hash: &str,
118) -> Result<(), ForwardError> {
119 match crate::launch_link::link() {
120 Some(link) => forward_host_cmd_with_args(data_dir, dir_hash, "open_link", serde_json::json!({ "link": link })),
121 None => forward_open_new_window(data_dir, dir_hash),
122 }
123}
124
125/// `forward_host_cmd` with an `args` object — the host's `/ipc` body is
126/// `{"cmd", "args"}` (`crates/cef/src/ipc.rs` `IpcRequest`). Used by the
127/// notification click path (`open_new_window {workspace_id}`,
128/// `focus_window {label}`).
129pub(crate) fn forward_host_cmd_with_args(
130 data_dir: &std::path::Path,
131 dir_hash: &str,
132 cmd: &str,
133 args: serde_json::Value,
134) -> Result<(), ForwardError> {
135 forward_host_body(data_dir, dir_hash, &serde_json::json!({ "cmd": cmd, "args": args }).to_string())
136}
137
138fn forward_host_cmd_impl(
139 data_dir: &std::path::Path,
140 dir_hash: &str,
141 cmd: &str,
142) -> Result<(), ForwardError> {
143 // `cmd` is a fixed internal identifier chosen by call sites in this
144 // crate, never user input, so a plain format is safe here — there is no
145 // untrusted string to escape.
146 forward_host_body(data_dir, dir_hash, &format!(r#"{{"cmd":"{}"}}"#, cmd))
147}
148
149fn forward_host_body(
150 data_dir: &std::path::Path,
151 dir_hash: &str,
152 body: &str,
153) -> Result<(), ForwardError> {
154 // Read the version-scoped port file so we reach THIS version's host,
155 // not a concurrent release's host that may have overwritten "ipc-port".
156 let port_file_name = format!("ipc-port-{}", dir_hash);
157 let port_file = data_dir.join(&port_file_name);
158 let contents = std::fs::read_to_string(&port_file).map_err(|e| {
159 ForwardError::Transient(format!("read {}: {}", port_file.display(), e))
160 })?;
161 let trimmed = contents.trim();
162 let (port_str, token) = trimmed.split_once(':').ok_or_else(|| {
163 ForwardError::Transient(format!(
164 "malformed port file (expected port:token): {}",
165 trimmed
166 ))
167 })?;
168 let port: u16 = port_str
169 .parse()
170 .map_err(|e| ForwardError::Transient(format!("invalid port {:?}: {}", port_str, e)))?;
171
172 // From here on the file was readable: any failure is a fatal
173 // forward (the host got far enough to publish but isn't
174 // serving the IPC port).
175 let addr: std::net::SocketAddr = ([127, 0, 0, 1], port).into();
176 let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(2))
177 .map_err(|e| ForwardError::Fatal(format!("connect 127.0.0.1:{}: {}", port, e)))?;
178 stream
179 .set_write_timeout(Some(std::time::Duration::from_secs(2)))
180 .ok();
181
182 let req = format!(
183 "POST /ipc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nAuthorization: Bearer {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
184 token,
185 body.len(),
186 body
187 );
188 use std::io::{Read, Write};
189 stream
190 .write_all(req.as_bytes())
191 .map_err(|e| ForwardError::Fatal(format!("write request: {}", e)))?;
192 // CRITICAL: read at least the status line. The host's axum
193 // handler is async — if the launcher closes the TCP socket
194 // before axum has finished parsing + dispatching to
195 // `open_new_window`, the request can be dropped (smoke caught
196 // exactly this on v0.33.481: the launcher logged "forwarded"
197 // but no second window appeared because the process exited
198 // before axum ran the handler). We don't care about the body
199 // — `Connection: close` lets the server drop the socket once
200 // the response is written, so a single short read is enough
201 // to keep the connection alive past handler dispatch.
202 stream
203 .set_read_timeout(Some(std::time::Duration::from_secs(2)))
204 .ok();
205 let mut sink = [0u8; 64];
206 let _ = stream.read(&mut sink);
207 Ok(())
208}
209
210/// User-facing message for an actual second-instance collision (not a
211/// bind-failure, not a stale socket — a real running launcher answered our
212/// connect probe). Shared by both call sites in
213/// `bind_socket_with_recovery` (fast-path and post-recovery-lock retry),
214/// which previously duplicated this message and both got it wrong the same
215/// way — see docs/specs/SPEC_DEV_INSTANCE_ISOLATION_DIAGNOSTICS_2026_09_19.md.
216///
217/// For a `dev-` channel, this used to say "Use `task dev:local` to launch a
218/// second isolated session" — plausible-sounding, and wrong for the common
219/// case. `task dev:local`'s version bump only changes the launcher's own
220/// IPC socket key (`hash.rs`'s `data_dir_hash16`, keyed on
221/// `CARGO_PKG_VERSION`/`AGENTMUX_BUILD_LABEL` at compile time) — it does
222/// NOT change the CEF profile/data directory, which for dev mode is keyed
223/// on `(branch, clone_id)` — NOT version — via
224/// `crates/common/src/data_paths.rs`'s `resolve_channel_and_dir`
225/// (`honor_env_channel=false` for dev launches). `clone_id`
226/// (`runtime_mode.rs`'s `derive_clone_id`) is a hash of the CLONE'S OWN
227/// CANONICAL WORKSPACE-ROOT PATH — git-worktree-aware by design, so a
228/// second worktree of the SAME branch already gets a distinct `clone_id`
229/// and therefore a distinct data dir, with no branch switch needed;
230/// `resolve_channel_and_dir` folds both into the one `channel` string this
231/// function receives (`format!("dev-{branch}-{clone_id}")` — confirmed by
232/// reading that call site directly). Two dev instances collide on CEF's
233/// own `SingletonLock` only when BOTH branch and clone/workspace path are
234/// identical — reproduced live: a real rebuild under a bumped version, run
235/// from the unchanged clone path on the unchanged branch, got a new
236/// launcher socket and STILL hit `CEF early exit (process singleton or
237/// similar)` on the unchanged data dir. The fix is a different branch OR a
238/// different clone/worktree path (either one changes `channel`) — named
239/// directly here instead of pointing at a command that cannot solve this
240/// specific problem. (ReAgent P1 on this PR: an earlier revision of this
241/// message claimed branch was the ONLY lever, which is what this revision
242/// corrects — verified against `resolve_channel_and_dir`'s actual source,
243/// not just re-asserted.)
244#[cfg(not(target_os = "windows"))]
245fn print_dev_instance_collision(channel: &str, data_dir: &std::path::Path, socket_path: &str) {
246 eprintln!(
247 "AgentMux dev instance already running for channel \"{channel}\"\n\
248 (dev-<branch>-<clone_id>, where clone_id identifies THIS checkout's\n\
249 own workspace-root path). Data-dir isolation is keyed on branch AND\n\
250 clone/workspace path together, not build version — a `task dev:local`\n\
251 version bump will NOT let a second instance run alongside this one\n\
252 from this same checkout on this same branch (it only changes this\n\
253 launcher's own IPC socket key, not the CEF profile directory below).\n\
254 To run a second dev instance concurrently, either check out a\n\
255 DIFFERENT branch, or run `task dev` from a DIFFERENT clone/worktree\n\
256 path (even on this same branch — clone/worktree path alone is\n\
257 enough to change the channel above).\n\
258 Data dir: {}\n\
259 Socket: {socket_path}",
260 data_dir.display()
261 );
262}
263
264/// Best-effort `open_new_window` forward for the unix second-instance path.
265/// Unlike the Windows path (which pops a dialog on a fatal forward), unix just
266/// logs and lets the caller exit 0: the existing instance is alive (its socket
267/// answered our connect probe), so a transient/fatal forward failure shouldn't
268/// block — at worst the relaunch is a silent no-op instead of a new window.
269/// SPEC_MACOS_LAUNCH_COHERENCE_2026_06_18.md.
270#[cfg(target_os = "macos")]
271pub(crate) fn forward_open_new_window_or_log(data_dir: &std::path::Path, dir_hash: &str) {
272 match forward_open_new_window(data_dir, dir_hash) {
273 Ok(()) => log("forwarded open_new_window to existing instance"),
274 Err(ForwardError::Transient(reason)) => {
275 log(&format!("open_new_window forward transient (host mid-startup?): {}", reason))
276 }
277 Err(ForwardError::Fatal(reason)) => {
278 log(&format!("open_new_window forward failed: {}", reason))
279 }
280 }
281}
282
283/// What a launcher that lost the single-instance race does: open a window in
284/// the running instance, unless it was started by a login entry, which only
285/// asks that AgentMux be running (SPEC_START_WITH_OS_2026_09_25.md §3.6).
286/// Not used by the macOS reopen handler, which is a user asking for a window.
287/// Returns the forward's error, if any, for [`await_running_instance`].
288#[cfg(not(target_os = "windows"))]
289fn forward_for_second_instance(data_dir: &std::path::Path, dir_hash: &str) -> Option<ForwardError> {
290 if !crate::autostart::second_instance_opens_window(&crate::launch_link::own_args()) {
291 log("login start: AgentMux is already running — exiting without opening a window");
292 return None;
293 }
294 match forward_launch(data_dir, dir_hash) {
295 Ok(()) => {
296 log("forwarded the launch (a window, or a deep link) to the existing instance");
297 None
298 }
299 Err(e) => Some(e),
300 }
301}
302
303/// The socket, once the launcher that held it has exited: unlink its file
304/// and bind. `None` while it still answers. Called under the recovery lock.
305#[cfg(not(target_os = "windows"))]
306fn claim_after_quit(socket_path: &str) -> Option<tokio::net::UnixListener> {
307 if std::os::unix::net::UnixStream::connect(socket_path).is_ok() {
308 return None;
309 }
310 let _ = std::fs::remove_file(socket_path);
311 crate::ipc::server::bind_first_unix_socket(socket_path).ok()
312}
313
314/// Bind the launcher's IPC socket with single-instance enforcement +
315/// crash-safe stale-socket recovery, serialized across concurrent
316/// launchers via `flock(2)`.
317///
318/// Returns a bound `UnixListener` on success. Calls `std::process::exit`
319/// on:
320/// * second-instance detection (exit code 0)
321/// * a hard bind failure that isn't `EADDRINUSE` (exit code 2)
322/// * unable to acquire the recovery lock (exit code 2)
323///
324/// Why the lockfile (codex P1 + reagent P1 on PR #1288): see the call-
325/// site comment. Two-launcher concurrent stale-cleanup would otherwise
326/// produce two live launchers for one data dir.
327#[cfg(not(target_os = "windows"))]
328pub(crate) fn bind_socket_with_recovery(
329 socket_path: &str,
330 data_dir: &std::path::Path,
331 dir_hash: &str,
332 channel: &str,
333) -> tokio::net::UnixListener {
334 use std::os::unix::io::AsRawFd as _;
335
336 // Fast path: bind without contention.
337 match crate::ipc::server::bind_first_unix_socket(socket_path) {
338 Ok(l) => return l,
339 Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => { /* slow path below */ }
340 Err(e) => {
341 log(&format!("FATAL: bind {} failed: {}", socket_path, e));
342 eprintln!(
343 "AgentMux failed to start: could not bind IPC socket.\n\nSocket: {}\nError: {}",
344 socket_path, e
345 );
346 std::process::exit(2);
347 }
348 }
349
350 // Slow path: contention. Acquire the recovery lock so only one
351 // launcher at a time does the connect-probe + unlink + rebind.
352 let lock_path = format!("{}.lock", socket_path);
353 let lock_file = match std::fs::OpenOptions::new()
354 .create(true)
355 .read(true)
356 .write(true)
357 .truncate(false)
358 .open(&lock_path)
359 {
360 Ok(f) => f,
361 Err(e) => {
362 log(&format!(
363 "FATAL: could not open recovery lockfile {}: {}",
364 lock_path, e
365 ));
366 eprintln!(
367 "AgentMux failed to start: could not open IPC recovery lockfile.\n\nLockfile: {}\nError: {}",
368 lock_path, e
369 );
370 std::process::exit(2);
371 }
372 };
373 // Block until we have the lock — another launcher's recovery
374 // window is bounded by a single bind + a single connect-probe;
375 // we won't wait long. flock(2) is auto-released on close (when
376 // the OS reaps the launcher process), so a SIGKILL'd holder
377 // doesn't leak the lock.
378 if unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX) } != 0 {
379 let errno = std::io::Error::last_os_error();
380 log(&format!(
381 "FATAL: flock({}, LOCK_EX) failed: {}",
382 lock_path, errno
383 ));
384 eprintln!(
385 "AgentMux failed to start: could not acquire IPC recovery lock.\n\nLockfile: {}\nError: {}",
386 lock_path, errno
387 );
388 std::process::exit(2);
389 }
390
391 // Retry the bind under the lock — another launcher may have
392 // already cleaned up the stale file while we were waiting on
393 // flock, leaving us free to bind directly.
394 match crate::ipc::server::bind_first_unix_socket(socket_path) {
395 Ok(l) => return l,
396 Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => { /* probe below */ }
397 Err(e) => {
398 log(&format!(
399 "FATAL: post-lock bind {} failed: {}",
400 socket_path, e
401 ));
402 eprintln!(
403 "AgentMux failed to start: post-lock IPC bind failed.\n\nSocket: {}\nError: {}",
404 socket_path, e
405 );
406 std::process::exit(2);
407 }
408 }
409
410 // Disambiguate: is the existing socket a real running launcher,
411 // or a stale file?
412 match std::os::unix::net::UnixStream::connect(socket_path) {
413 Ok(_) => {
414 // Real second-instance. Forward an `open_new_window` request to the
415 // already-running launcher's host (Windows-parity: `run_windows`'s
416 // `already_running` branch in supervisor/windows.rs), then exit
417 // cleanly. SPEC_MACOS_LAUNCH_COHERENCE_2026_06_18.md.
418 if channel.starts_with("dev-") {
419 print_dev_instance_collision(channel, data_dir, socket_path);
420 } else {
421 eprintln!(
422 "AgentMux is already running for this data directory.\n\nSocket: {}",
423 socket_path
424 );
425 }
426 if let Some(first) = forward_for_second_instance(data_dir, dir_hash) {
427 log(&format!(
428 "[ipc] open_new_window not taken ({}) — waiting for the instance to start or finish quitting",
429 first.reason()
430 ));
431 match await_running_instance(
432 || claim_after_quit(socket_path),
433 || forward_launch(data_dir, dir_hash),
434 first,
435 ) {
436 Handoff::Claimed(listener) => {
437 log("[ipc] the previous instance has quit — starting");
438 return listener;
439 }
440 Handoff::Forwarded => log("forwarded open_new_window to existing instance"),
441 Handoff::GaveUp(e) => log(&format!("open_new_window forward failed: {}", e.reason())),
442 }
443 }
444 log(&format!(
445 "[ipc] second-instance detected — existing launcher owns {}",
446 socket_path
447 ));
448 std::process::exit(0);
449 }
450 Err(connect_err)
451 if connect_err.kind() == std::io::ErrorKind::ConnectionRefused
452 || connect_err.raw_os_error() == Some(libc::ENOENT) =>
453 {
454 // Stale socket file from a crashed launcher. Unlink and
455 // rebind. The lock serializes us against other launchers
456 // ALSO doing recovery, but it does NOT block a fresh
457 // launcher taking the fast-path bind() above — that
458 // launcher is lock-free and can win the socket in the
459 // microsecond window between our `remove_file` and our
460 // `bind`. If that happens, AddrInUse means a real
461 // launcher just claimed the socket and WE are now the
462 // losing second instance, not a failed start.
463 // (Reagent P2 on PR #1288.)
464 log(&format!(
465 "[ipc] stale socket file at {} — unlinking and rebinding (under recovery lock)",
466 socket_path
467 ));
468 let _ = std::fs::remove_file(socket_path);
469 match crate::ipc::server::bind_first_unix_socket(socket_path) {
470 Ok(l) => l,
471 Err(retry_e) if retry_e.kind() == std::io::ErrorKind::AddrInUse => {
472 if channel.starts_with("dev-") {
473 print_dev_instance_collision(channel, data_dir, socket_path);
474 } else {
475 eprintln!(
476 "AgentMux is already running for this data directory.\n\nSocket: {}",
477 socket_path
478 );
479 }
480 let _ = forward_for_second_instance(data_dir, dir_hash);
481 log(&format!(
482 "[ipc] post-recovery bind lost the race to a fresh launcher on {} — exiting as second instance",
483 socket_path
484 ));
485 std::process::exit(0);
486 }
487 Err(retry_e) => {
488 log(&format!(
489 "FATAL: bind retry after stale-socket unlink failed: {}",
490 retry_e
491 ));
492 eprintln!(
493 "AgentMux failed to start: IPC rebind after stale cleanup failed.\n\nSocket: {}\nError: {}",
494 socket_path, retry_e
495 );
496 std::process::exit(2);
497 }
498 }
499 }
500 Err(other) => {
501 log(&format!(
502 "[ipc] AddrInUse but connect probe failed in an unexpected way: {} — \
503 treating as second instance and exiting cleanly",
504 other
505 ));
506 std::process::exit(0);
507 }
508 }
509 // `lock_file` drops here; flock auto-released on close.
510}
511
512#[cfg(test)]
513mod tests {
514 use super::{await_running_instance, ForwardError, Handoff};
515
516 /// A relaunch during a quit takes the socket/pipe as soon as the old
517 /// instance lets go of it, not after the whole wait.
518 #[test]
519 fn a_relaunch_claims_as_soon_as_the_old_instance_lets_go() {
520 let mut tries = 0;
521 let started = std::time::Instant::now();
522 let out = await_running_instance(
523 || {
524 tries += 1;
525 (tries == 3).then_some("socket")
526 },
527 || Err(ForwardError::Transient("port file gone".into())),
528 ForwardError::Transient("port file gone".into()),
529 );
530 assert!(matches!(out, Handoff::Claimed("socket")));
531 assert!(started.elapsed() < std::time::Duration::from_secs(2));
532 }
533
534 /// A relaunch while the instance is still starting forwards once its
535 /// host answers.
536 #[test]
537 fn a_relaunch_forwards_once_the_host_answers() {
538 let mut forwards = 0;
539 let out = await_running_instance(
540 || None::<()>,
541 || {
542 forwards += 1;
543 if forwards == 2 { Ok(()) } else { Err(ForwardError::Transient("not yet".into())) }
544 },
545 ForwardError::Transient("not yet".into()),
546 );
547 assert!(matches!(out, Handoff::Forwarded));
548 assert_eq!(forwards, 2);
549 }
550}