diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/MicroHarnessManagerApp.java b/app/src/main/java/io/github/ghosthack/microhm/app/MicroHarnessManagerApp.java index 420feb8..d7be90f 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/MicroHarnessManagerApp.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/MicroHarnessManagerApp.java @@ -56,6 +56,10 @@ public static void main(String[] args) throws Exception { PackageSmoke.run(); return; } + if (args.length == 1 && args[0].equals(McpHost.TRAY_PROBE_FLAG)) { + McpHost.probeTray(); + return; + } if (args.length >= 1 && args[0].equals(McpHost.FLAG)) { McpHost.run(args); return; @@ -102,7 +106,7 @@ public static void main(String[] args) throws Exception { startMcpServer(mcpService); startPhoneServer(stack.phone()); // However the app ends, agents keep their MCP tools while sessions live: a - // headless host takes over the server (and the registry) until the app is back. + // background host takes over the server (and the registry) until the app is back. // Bounded: it asks the daemon for its sessions, and the JVM waits on its hooks, so a // daemon that has stopped answering would otherwise hold the exit. No answer in // time still starts the host, which checks for itself. @@ -179,7 +183,7 @@ private static void startPhoneServer(io.github.ghosthack.microhm.app.phone.Phone } /** - * Takes the registry's instance lock. A headless MCP host holding it (the app was + * Takes the registry's instance lock. The background host holding it (the app was * closed while sessions ran) is stopped and the lock taken over; anything else holding * it is another app. A lock that cannot even be attempted runs unguarded. */ diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostLauncher.java b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostLauncher.java index 1952633..696260a 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostLauncher.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostLauncher.java @@ -45,7 +45,7 @@ public static boolean launchIfNeeded(SessionRegistry registry, SessionServerHost if (!anyLive(() -> McpHost.liveRegistered(registry, host), wait)) { return false; } - return start(withState(launcher(), McpHost.FLAG), "mcp-host.log", "the background host"); + return start(withState(launcher(), McpHost.FLAG), "mcp-host.log", "the background host") != null; } /** @@ -72,24 +72,69 @@ static boolean anyLive(IntSupplier liveCount, Duration wait) { } } - /** Opens the app (from the tray menu); it stops this host as it starts. */ - static boolean openApp() { - return start(withState(launcher()), "app.log", "the app"); + /** The app this host last started from its tray menu, while it may still be starting. */ + private static Process openedApp; + + /** + * Opens the app (from the tray menu); it stops this host as it starts. A second Open + * while the app started by the first is still running does nothing: that app is about + * to take over, and another would only find the registry taken and say so. + */ + static synchronized boolean openApp() { + if (openedApp != null && openedApp.isAlive()) { + LOG.info("the app is already starting; not opening another"); + return false; + } + openedApp = start(withState(launcher()), "app.log", "the app"); + return openedApp != null; } - private static boolean start(List command, String logName, String what) { + /** How long the tray probe may take; a JVM start, so seconds, not milliseconds. */ + static final Duration TRAY_PROBE_WAIT = Duration.ofSeconds(15); + + /** + * Whether the desktop has a tray, asked by a throwaway process ({@link McpHost#probeTray}) + * so this one never connects to the display. No answer in time counts as no tray: the + * host then runs headless, which keeps MCP and the phone page safe from a logout. + */ + static boolean trayAvailable() { + List command = new ArrayList<>(launcher()); + command.add(McpHost.TRAY_PROBE_FLAG); + try { + Process probe = new ProcessBuilder(command) + .directory(new File(System.getProperty("user.home"))) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start(); + if (!probe.waitFor(TRAY_PROBE_WAIT.toMillis(), TimeUnit.MILLISECONDS)) { + probe.destroyForcibly(); + LOG.info("the tray probe did not answer within {} s; no tray icon", TRAY_PROBE_WAIT.toSeconds()); + return false; + } + return probe.exitValue() == McpHost.TRAY_PRESENT; + } catch (IOException e) { + LOG.warn("could not run the tray probe: {}", e.toString()); + return false; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + /** The started process, or null when it could not be started. */ + private static Process start(List command, String logName, String what) { Path log = RegistryPaths.resolve().toAbsolutePath().resolveSibling(logName); try { - new ProcessBuilder(command) + Process process = new ProcessBuilder(command) .directory(new File(System.getProperty("user.home"))) .redirectErrorStream(true) .redirectOutput(ProcessBuilder.Redirect.appendTo(log.toFile())) .start(); LOG.info("started {}", what); - return true; + return process; } catch (IOException e) { LOG.warn("could not start {} ({}): {}", what, String.join(" ", command), e.toString()); - return false; + return null; } } diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostOwner.java b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostOwner.java index 7f2e617..57ddf70 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostOwner.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/HostOwner.java @@ -11,9 +11,14 @@ import java.util.function.LongFunction; /** - * Who the headless MCP host is: an {@code mcp-host.pid} file beside the registry holding + * Who the background host is: an {@code mcp-host.pid} file beside the registry holding * the host's pid and its start instant. The pair, not the pid alone, identifies the * process, so the app never signals an unrelated process that reused the number. + * + *

The app stops the host with a stop request ({@code mcp-host.stop}, naming the host's + * record) as well as a signal: on Windows the only signal Java can send ends the process + * outright, so the host would never run its shutdown hook or take its tray icon down. The + * host watches for the request ({@link #stopRequested}) and exits cleanly. */ public final class HostOwner { @@ -45,6 +50,21 @@ public static Path file(Path registryFile) { return registryFile.toAbsolutePath().resolveSibling("mcp-host.pid"); } + public static Path stopFile(Path registryFile) { + return registryFile.toAbsolutePath().resolveSibling("mcp-host.stop"); + } + + /** Whether the app has asked the host named by {@code record} to stop. A request for + * another host (a stale file left by one that ended first) does not count. */ + public static boolean stopRequested(Path registryFile, Record record) { + try { + return Record.decode(Files.readString(stopFile(registryFile), StandardCharsets.UTF_8)) + .filter(record::equals).isPresent(); + } catch (IOException e) { + return false; + } + } + /** This process's record, or empty when the platform does not report a start time. */ public static Optional current() { ProcessHandle self = ProcessHandle.current(); @@ -106,7 +126,10 @@ public static boolean stop(Path registryFile, Duration timeout) throws Interrupt clear(registryFile, record.get()); return true; } - host.get().destroy(); // SIGTERM: its shutdown hook stops the server and clears the file + requestStop(registryFile, record.get()); + if (!WINDOWS) { + host.get().destroy(); // SIGTERM: its shutdown hook stops the server and clears the file + } // On Windows destroy() is TerminateProcess: no hook would run, the tray icon would stay. long deadline = System.nanoTime() + timeout.toNanos(); while (host.get().isAlive() && System.nanoTime() - deadline < 0) { Thread.sleep(50); @@ -116,9 +139,27 @@ public static boolean stop(Path registryFile, Duration timeout) throws Interrupt Thread.sleep(200); } clear(registryFile, record.get()); + try { + Files.deleteIfExists(stopFile(registryFile)); + } catch (IOException ignored) { + // A stale request names a host that is gone, so no later host acts on it. + } return !host.get().isAlive(); } + private static void requestStop(Path registryFile, Record record) { + Path target = stopFile(registryFile); + Path tmp = target.resolveSibling(target.getFileName() + ".tmp"); + try { + Files.writeString(tmp, record.encode(), StandardCharsets.UTF_8); + Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException ignored) { + // The signal (or, on Windows, the forcible end after the wait) still stops it. + } + } + + private static final boolean WINDOWS = System.getProperty("os.name", "").toLowerCase().startsWith("windows"); + /** For log lines. */ static String describe(Record record) { return "pid " + record.pid() + ", started " + Instant.ofEpochMilli(record.startEpochMillis()); diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/McpHost.java b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/McpHost.java index 7931db1..5f738a7 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/McpHost.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/McpHost.java @@ -43,6 +43,13 @@ public final class McpHost { /** The command-line flag that selects this mode. */ public static final String FLAG = "--mcp-host"; + /** The flag for a throwaway process that only answers whether the desktop has a tray + * (see {@link #probeTray}). */ + public static final String TRAY_PROBE_FLAG = "--tray-probe"; + /** Exit status of a tray probe that found a tray. */ + static final int TRAY_PRESENT = 0; + /** Exit status of a tray probe that found none. */ + static final int TRAY_ABSENT = 3; /** The app's registry file, so the host finds the same settings, MCP configs and lock. */ public static final String REGISTRY_OPTION = "--registry="; /** The app's daemon home, so the host talks to the same daemon. */ @@ -55,16 +62,23 @@ public final class McpHost { /** Consecutive checks that must find nothing live before exiting: one daemon hiccup * must not end the host. */ static final int EMPTY_CHECKS_TO_EXIT = 2; + /** How often the host looks for the app's stop request ({@link HostOwner#stopRequested}). */ + static final Duration STOP_POLL = Duration.ofMillis(250); + /** How long exit waits for the tray icon to be taken down. */ + static final Duration ICON_REMOVE_WAIT = Duration.ofSeconds(1); /** The macOS glyph follows a dark/light switch about once a minute (every 4th check). */ static final int APPEARANCE_CHECK_TICKS = 4; public static void run(String[] args) throws InterruptedException { applyStateOptions(args); boolean mcp = AppSettings.mcpServerEnabled(); - boolean wantIcon = AppSettings.trayIconEnabled(); boolean phone = AppSettings.phoneServerEnabled(); + // On Linux, asking for a tray connects this process to the X/Wayland display, and + // that connection ends the process when the user logs out of the desktop, taking MCP + // with it. So a throwaway process asks, and this one stays headless when it finds none. + boolean wantIcon = AppSettings.trayIconEnabled() && (!isLinux() || HostLauncher.trayAvailable()); if (!mcp && !wantIcon && !phone) { - LOG.info("neither the MCP server, the phone page nor the tray icon is on; nothing to host"); + LOG.info("neither the MCP server, the phone page nor a tray icon is on (or the desktop has no tray); nothing to host"); return; } // Before anything touches AWT: headless when there is no icon to show, else a @@ -143,9 +157,21 @@ public void hide() { Runtime.getRuntime().addShutdownHook(Thread.ofPlatform().unstarted(() -> { stack.service().stop(); stack.phone().stop(); - icon.ifPresent(StatusIcon::remove); + icon.ifPresent(i -> i.removeAndWait(ICON_REMOVE_WAIT)); self.ifPresent(record -> HostOwner.clear(registryFile, record)); })); + // The app's way to stop this host cleanly where a signal cannot (Windows). + self.ifPresent(record -> Thread.ofPlatform().daemon().name("mhm-host-stop-watch").start(() -> { + try { + while (!HostOwner.stopRequested(registryFile, record)) { + Thread.sleep(STOP_POLL); + } + } catch (InterruptedException e) { + return; + } + LOG.info("the app asked the background host to stop; exiting"); + System.exit(0); + })); LOG.info("background host running while the app is closed: {}, {} ({})", (servingPort > 0 ? "MCP on 127.0.0.1:" + servingPort : "no MCP") + (phoneServing ? ", phone page on port " + AppSettings.phonePort() : ""), @@ -154,10 +180,12 @@ public void hide() { int empty = 0; long ticks = 0; + boolean iconRemoved = false; while (empty < EMPTY_CHECKS_TO_EXIT) { - if (icon.isPresent()) { + if (icon.isPresent() && !iconRemoved) { if (iconHidden.get()) { icon.get().remove(); + iconRemoved = true; } else { icon.get().update(live, servingPort, ticks % APPEARANCE_CHECK_TICKS == 0 && ticks > 0); } @@ -171,6 +199,24 @@ public void hide() { System.exit(0); } + /** + * The {@link #TRAY_PROBE_FLAG} process: exits {@link #TRAY_PRESENT} when the desktop has + * a tray, else {@link #TRAY_ABSENT}. Its display connection ends with it. + */ + public static void probeTray() { + boolean present; + try { + present = !java.awt.GraphicsEnvironment.isHeadless() && java.awt.SystemTray.isSupported(); + } catch (RuntimeException | Error e) { + present = false; + } + System.exit(present ? TRAY_PRESENT : TRAY_ABSENT); + } + + private static boolean isLinux() { + return System.getProperty("os.name", "").toLowerCase().startsWith("linux"); + } + /** Applies {@link #REGISTRY_OPTION} and {@link #MUX_HOME_OPTION} as the overrides every * path resolution reads, for the app and the host alike. */ public static void applyStateOptions(String[] args) { diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/StatusIcon.java b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/StatusIcon.java index 18bb630..8511e36 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/StatusIcon.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/mcphost/StatusIcon.java @@ -50,7 +50,9 @@ interface Actions { private final MenuItem sessionsItem; private final MenuItem mcpItem; private final boolean mac; + /** Touched only on the AWT event thread. */ private boolean dark; + private boolean removed; private int sessions = -1; private int mcpPort = -1; @@ -99,7 +101,11 @@ private static StatusIcon create(Actions actions) { TrayIcon icon = new TrayIcon(image(mac, dark, tray.getTrayIconSize().height), APP_NAME, menu); icon.setImageAutoSize(true); - icon.addActionListener(e -> actions.open()); // double-click on Windows + if (!mac) { + // A double-click on Windows. macOS fires this on the single click that opens the + // menu, so there it would launch the app (and end this host) at every glance. + icon.addActionListener(e -> actions.open()); + } try { tray.add(icon); } catch (AWTException e) { @@ -110,9 +116,12 @@ private static StatusIcon create(Actions actions) { /** Refreshes the menu, the tooltip and (on macOS, after an appearance change) the glyph. */ void update(int liveSessions, int servingPort, boolean recheckAppearance) { - boolean nowDark = mac && recheckAppearance ? macDarkMenuBar() : dark; + Boolean nowDark = mac && recheckAppearance ? macDarkMenuBar() : null; EventQueue.invokeLater(() -> { - if (nowDark != dark) { + if (removed) { + return; + } + if (nowDark != null && nowDark != dark) { dark = nowDark; icon.setImage(image(true, dark, tray.getTrayIconSize().height)); } @@ -126,8 +135,27 @@ void update(int liveSessions, int servingPort, boolean recheckAppearance) { }); } + /** Takes the icon out of the tray; later calls (and updates) do nothing. */ void remove() { - EventQueue.invokeLater(() -> tray.remove(icon)); + EventQueue.invokeLater(() -> { + if (!removed) { + removed = true; + tray.remove(icon); + } + }); + } + + /** {@link #remove} for a shutdown hook: waits (at most {@code wait}) for the icon to be + * gone, since the JVM may halt before a queued removal runs. */ + void removeAndWait(java.time.Duration wait) { + java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); + remove(); + EventQueue.invokeLater(done::countDown); + try { + done.await(wait.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } } static String sessionsLabel(int sessions) { @@ -223,12 +251,13 @@ static boolean macDarkMenuBar() { try { Process p = new ProcessBuilder("defaults", "read", "-g", "AppleInterfaceStyle") .redirectErrorStream(true).start(); - String out = new String(p.getInputStream().readAllBytes()).trim(); + // Wait first: reading blocks until the process ends, so a hung `defaults` would + // hang the host's main loop. The output ("Dark", or a short error) fits the pipe. if (!p.waitFor(2, TimeUnit.SECONDS)) { p.destroyForcibly(); return true; } - return out.equalsIgnoreCase("Dark"); + return new String(p.getInputStream().readAllBytes()).trim().equalsIgnoreCase("Dark"); } catch (IOException e) { return true; } catch (InterruptedException e) { diff --git a/app/src/test/java/io/github/ghosthack/microhm/app/mcphost/HostOwnerTest.java b/app/src/test/java/io/github/ghosthack/microhm/app/mcphost/HostOwnerTest.java index 0284a6e..4fee68f 100644 --- a/app/src/test/java/io/github/ghosthack/microhm/app/mcphost/HostOwnerTest.java +++ b/app/src/test/java/io/github/ghosthack/microhm/app/mcphost/HostOwnerTest.java @@ -69,4 +69,15 @@ void stoppingWithNoLiveHostClearsAStaleRecord() throws Exception { assertTrue(HostOwner.stop(registry, java.time.Duration.ofSeconds(1))); assertTrue(HostOwner.read(registry).isEmpty()); } + + @Test + void aStopRequestCountsOnlyForTheHostItNames() throws Exception { + Path registry = dir.resolve("sessions.json"); + HostOwner.Record host = new HostOwner.Record(4242, 1_000_000); + assertFalse(HostOwner.stopRequested(registry, host), "no request yet"); + java.nio.file.Files.writeString(HostOwner.stopFile(registry), host.encode()); + assertTrue(HostOwner.stopRequested(registry, host)); + assertFalse(HostOwner.stopRequested(registry, new HostOwner.Record(4242, 9_000_000)), + "a stale request for an earlier host with the same pid"); + } }