diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/daemon/SessionServerHost.java b/app/src/main/java/io/github/ghosthack/microhm/app/daemon/SessionServerHost.java index 10c7653..cf0f61f 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/daemon/SessionServerHost.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/daemon/SessionServerHost.java @@ -10,6 +10,7 @@ import io.github.ghosthack.microhm.mux.client.AttachedSession; import io.github.ghosthack.microhm.mux.client.SessionServerClient; import io.github.ghosthack.microhm.mux.client.SessionServerException; +import io.github.ghosthack.microhm.mux.protocol.Protocol; import io.github.ghosthack.microhm.mux.session.Session; import java.nio.file.Path; @@ -17,6 +18,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.BiConsumer; import java.util.function.Supplier; /** @@ -149,6 +151,31 @@ public SessionConnection attach(String session, int columns, int rows) { return new SessionServerConnection(attached); } + /** The daemon's event stream for every session (later ones too), filtered to its + * {@code title} events. The quiet period only paces {@code quiet} events, which this + * ignores, so it is set long to keep them rare. */ + @Override + public Optional watchTitles(BiConsumer onTitle) { + SessionServerClient.Watch watch = call(() -> client.watch(null, TITLE_WATCH_QUIET_MS, event -> { + if (Protocol.EVENT_TITLE.equals(event.type())) { + onTitle.accept(event.name(), event.title() == null ? "" : event.title()); + } + })); + return Optional.of(new TitleWatch() { + @Override + public boolean isOpen() { + return watch.isOpen(); + } + + @Override + public void close() { + watch.close(); + } + }); + } + + private static final long TITLE_WATCH_QUIET_MS = 60_000; + /** One daemon request, with its failure translated for the seam: same message, the * daemon's exception kept as the cause so a log still shows which side failed. */ private static T call(Supplier request) { diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/host/SessionHost.java b/app/src/main/java/io/github/ghosthack/microhm/app/host/SessionHost.java index aaabfcc..a56e07d 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/host/SessionHost.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/host/SessionHost.java @@ -4,6 +4,8 @@ import java.nio.file.Path; import java.util.List; +import java.util.Optional; +import java.util.function.BiConsumer; /** * The substrate that hosts named sessions — the app's session daemon. This is the seam @@ -49,4 +51,25 @@ public interface SessionHost { * therefore never called on the EDT. */ SessionConnection attach(String session, int columns, int rows); + + /** An open title stream from {@link #watchTitles}. */ + interface TitleWatch extends AutoCloseable { + /** False once the stream has ended (the daemon went away or dropped it). */ + boolean isOpen(); + + @Override + void close(); + } + + /** + * Streams every session's OSC title as the program in it sets it, frame by frame: a + * spinner a harness animates in its title arrives as each frame it writes. {@code + * onTitle} gets {@code (sessionName, title)} on a background thread. Empty when this + * host cannot stream titles (callers fall back to {@link #capture}'s title); throws + * {@link SessionHostException} when it could but the stream would not open now (no + * server, or one too old to watch). + */ + default Optional watchTitles(BiConsumer onTitle) { + return Optional.empty(); + } } diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/ui/LiveTitles.java b/app/src/main/java/io/github/ghosthack/microhm/app/ui/LiveTitles.java new file mode 100644 index 0000000..adf238a --- /dev/null +++ b/app/src/main/java/io/github/ghosthack/microhm/app/ui/LiveTitles.java @@ -0,0 +1,133 @@ +package io.github.ghosthack.microhm.app.ui; + +import io.github.ghosthack.microhm.app.host.SessionHost; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** + * Keeps the host's title stream ({@link SessionHost#watchTitles}) open and hands each + * session's newest title to the UI, so the sidebar shows the frames a harness writes into + * its title as it writes them rather than whatever frame the next status poll samples. + * + *

Titles are coalesced per session between deliveries: a burst of spinner frames + * arriving faster than the EDT drains becomes one delivery carrying the latest frame of + * each session, so a busy harness can never queue up stale frames. Nothing is invented + * or interpolated; at worst a frame is skipped. A stream that ends (daemon restarted, no + * daemon yet, one too old to watch) is reopened with backoff, and the status poll's title + * covers the gap. + */ +final class LiveTitles { + + private static final Logger LOG = LoggerFactory.getLogger(LiveTitles.class); + + static final Duration BACKOFF_MIN = Duration.ofSeconds(1); + static final Duration BACKOFF_MAX = Duration.ofSeconds(30); + /** How often the loop checks that an open stream is still open. */ + private static final Duration CHECK = Duration.ofSeconds(1); + + private final SessionHost host; + private final Consumer edt; + private final Consumer> onTitles; + private final Map latest = new ConcurrentHashMap<>(); + private final AtomicBoolean drainQueued = new AtomicBoolean(); + private volatile boolean running; + private Thread loop; + + /** + * @param edt runs a task on the UI thread ({@code SwingUtilities::invokeLater}) + * @param onTitles gets {@code sessionName -> newest title} on the UI thread + */ + LiveTitles(SessionHost host, Consumer edt, Consumer> onTitles) { + this.host = host; + this.edt = edt; + this.onTitles = onTitles; + } + + synchronized void start() { + if (loop != null) { + return; + } + running = true; + loop = Thread.ofVirtual().name("mhm-live-titles").start(this::run); + } + + synchronized void stop() { + running = false; + if (loop != null) { + loop.interrupt(); + loop = null; + } + } + + /** Called on the stream's reader thread for every title change. */ + void titleChanged(String session, String title) { + latest.put(session, title); + if (drainQueued.compareAndSet(false, true)) { + edt.accept(this::drain); + } + } + + private void drain() { + drainQueued.set(false); + Map batch = new HashMap<>(); + for (String session : latest.keySet()) { + String title = latest.remove(session); + if (title != null) { + batch.put(session, title); + } + } + if (!batch.isEmpty() && running) { + onTitles.accept(batch); + } + } + + private void run() { + Duration backoff = BACKOFF_MIN; + SessionHost.TitleWatch watch = null; + try { + while (running) { + if (watch == null || !watch.isOpen()) { + closeQuietly(watch); + watch = null; + try { + Optional opened = host.watchTitles(this::titleChanged); + if (opened.isEmpty()) { + return; // this host has no title stream: the poll is all there is + } + watch = opened.get(); + backoff = BACKOFF_MIN; + } catch (RuntimeException e) { + LOG.debug("title stream unavailable, retrying in {}: {}", backoff, e.toString()); + Thread.sleep(backoff.toMillis()); + Duration doubled = backoff.multipliedBy(2); + backoff = doubled.compareTo(BACKOFF_MAX) > 0 ? BACKOFF_MAX : doubled; + continue; + } + } + Thread.sleep(CHECK.toMillis()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + closeQuietly(watch); + } + } + + private static void closeQuietly(SessionHost.TitleWatch watch) { + if (watch != null) { + try { + watch.close(); + } catch (RuntimeException ignored) { + // already gone + } + } + } +} diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/ui/MainWindow.java b/app/src/main/java/io/github/ghosthack/microhm/app/ui/MainWindow.java index a4b74c9..642691e 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/ui/MainWindow.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/ui/MainWindow.java @@ -232,6 +232,16 @@ public String getToolTipText(MouseEvent event) { * stopping: a tick that finds nothing pulsing stops the timer, and * {@link #ensurePulsing()} restarts it wherever states or attachment change. */ private final Timer pulseTimer = new Timer(PULSE_FRAME_MS, e -> repaintPulsingDots()); + + /** Each session's title as its harness writes it, frame by frame (see + * {@link #onLiveTitles}); the status poll's sampled title is the fallback. */ + private final LiveTitles liveTitles; + + /** The window title follows the selected session's live status mark, but no faster + * than this: a native title-bar update per spinner frame costs more than it shows. */ + static final int WINDOW_TITLE_MARK_MIN_MS = 250; + private final Timer windowTitleTimer = new Timer(WINDOW_TITLE_MARK_MIN_MS, + e -> updateWindowTitle(sidebarList.getSelectedValue())); private final KeyEventDispatcher keyEventDispatcher = this::handleGlobalKeyEvent; private final JButton sidebarButton = new JButton(); private final JButton openButton = new JButton("Open…"); @@ -586,6 +596,8 @@ public void doLayout() { this.gracefulCloser = new GracefulCloser(host, Duration.ofMillis(250), Duration.ofSeconds(10), Duration.ofSeconds(5)); this.statusPollTimer = new Timer(statusPollIntervalMs, e -> pollLiveSessions()); + this.liveTitles = new LiveTitles(host, SwingUtilities::invokeLater, this::onLiveTitles); + windowTitleTimer.setRepeats(false); statusPollTimer.setInitialDelay(500); if (statusPollingEnabled) { statusPollTimer.start(); @@ -606,6 +618,7 @@ public void doLayout() { sessionEvents.addSessionRunEndedListener(sessionRunEndedListener); refreshSidebar(null); + liveTitles.start(); } /** @@ -681,6 +694,8 @@ void shutdown() { statusPollTimer.stop(); activeTabPollTimer.stop(); pulseTimer.stop(); + liveTitles.stop(); + windowTitleTimer.stop(); KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keyEventDispatcher); backgroundExecutor.shutdownNow(); settingsExecutor.shutdown(); @@ -1079,7 +1094,7 @@ private void applySidebar(ReconciliationResult result, String reselect) { if (previous.state() != null) { sidebarEntry.setState(previous.state(), previous.stateReason()); } - sidebarEntry.setPaneTitle(previous.paneTitle()); + sidebarEntry.carryTitleFrom(previous); } allSidebarEntries.add(sidebarEntry); } @@ -1240,6 +1255,9 @@ private void updateWindowTitle(SidebarEntry entry) { } String path = entry.abbreviatedPath(); String sessionName = ellipsizeRight(entry.displayName(), WINDOW_TITLE_SESSION_MAX_CHARS); + if (!entry.titleMark().isEmpty()) { + sessionName = entry.titleMark() + " " + sessionName; + } setTitle(sessionName + (path.isEmpty() ? "" : " — " + path) + " — " + APP_NAME); } @@ -1519,6 +1537,7 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r SessionState oldState = entry.state(); String oldReason = entry.stateReason(); String oldPaneTitle = entry.paneTitle(); + String oldTitleMark = entry.titleMark(); if (result.stateConfirmed()) { entry.setState(result.classification().state(), result.classification().reason()); } @@ -1527,7 +1546,8 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r // tooltip can show differently afterwards boolean changed = oldState != entry.state() || !Objects.equals(oldReason, entry.stateReason()) - || !Objects.equals(oldPaneTitle, entry.paneTitle()); + || !Objects.equals(oldPaneTitle, entry.paneTitle()) + || !oldTitleMark.equals(entry.titleMark()); SidebarView.FilterStatus newStatus = SidebarView.filterStatus(entry); boolean filterMembershipMayChange = oldStatus != newStatus && visibleStatuses.size() != SidebarView.FilterStatus.values().length; @@ -1557,6 +1577,48 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r // landing — nothing to update, and the next refreshSidebar() already dropped it } + /** + * Titles just written by harnesses (on the EDT, newest per session). A new status + * mark repaints only its row; a new name may also re-sort the sidebar, as a polled + * rename does. The selected session's window title follows at most every + * {@link #WINDOW_TITLE_MARK_MIN_MS}. + */ + private void onLiveTitles(Map titles) { + if (disposed) { + return; + } + boolean resort = false; + boolean selectedChanged = false; + SidebarEntry selected = sidebarList.getSelectedValue(); + for (SidebarEntry entry : allSidebarEntries) { + String title = titles.get(entry.sessionName()); + if (title == null || entry.status() != SidebarEntry.Status.LIVE) { + continue; + } + String oldDisplayName = entry.displayName(); + String oldMark = entry.titleMark(); + entry.setLiveTitle(title); + if (oldMark.equals(entry.titleMark()) && oldDisplayName.equals(entry.displayName())) { + continue; + } + if (sidebarSort == SidebarView.SortMode.SESSION_NAME && !oldDisplayName.equals(entry.displayName())) { + resort = true; + } else { + int index = indexOfSessionName(entry.sessionName()); + if (index >= 0) { + sidebarList.repaint(sidebarList.getCellBounds(index, index)); + } + } + selectedChanged |= entry.equals(selected); + } + if (resort) { + rebuildVisibleSidebar(lastSelectedSessionName, false); + } + if (selectedChanged && !windowTitleTimer.isRunning()) { + windowTitleTimer.start(); + } + } + /** Moves the sidebar's hover highlight to {@code index} (-1 for none), repainting * only the two rows involved. */ private void setSidebarHover(int index) { diff --git a/app/src/main/java/io/github/ghosthack/microhm/app/ui/SidebarEntry.java b/app/src/main/java/io/github/ghosthack/microhm/app/ui/SidebarEntry.java index e9df165..a6ed097 100644 --- a/app/src/main/java/io/github/ghosthack/microhm/app/ui/SidebarEntry.java +++ b/app/src/main/java/io/github/ghosthack/microhm/app/ui/SidebarEntry.java @@ -27,6 +27,16 @@ enum Status { LIVE, DEAD } * mid-redraw must not make the name flicker off. */ private String paneTitle = ""; + /** The live status mark the harness leads its title with ({@code ✳}, a braille or + * half-circle spinner frame, …), exactly as last written; empty when it writes none. + * Shown before the name but never part of it, so a new frame repaints the row + * without renaming it or moving it in a name sort. */ + private String titleMark = ""; + + /** Whether a title has arrived from the live stream: from then on the stream owns + * the mark, and the poll (a sample a few seconds old) only keeps the name fresh. */ + private boolean liveTitleSeen; + private SidebarEntry(Status status, SessionEntry sessionEntry, String sessionName) { this.status = status; this.sessionEntry = sessionEntry; @@ -84,23 +94,89 @@ String paneTitle() { return paneTitle; } - void setPaneTitle(String paneTitle) { - String name = paneTitle == null ? "" : withoutStatusGlyph(paneTitle); - if (!name.isBlank()) { - this.paneTitle = name; + String titleMark() { + return titleMark; + } + + /** A title the status poll sampled. Updates the name; updates the mark only until + * the live stream has delivered one, since its frames are newer than any sample. */ + void setPaneTitle(String polledTitle) { + if (polledTitle == null || polledTitle.isBlank()) { + return; + } + TitleParts parts = TitleParts.of(polledTitle); + if (!parts.name().isBlank()) { + this.paneTitle = parts.name(); + } + if (!liveTitleSeen) { + this.titleMark = parts.mark(); } } - /** Harnesses prefix their terminal title with a live status mark: Claude Code's - * {@code ✳} when idle, a braille spinner frame while working. The row already shows - * status in its badge, and a mark that changes every frame would make the name (and - * a name sort) flicker, so it is dropped from the name. */ - static String withoutStatusGlyph(String title) { - return STATUS_GLYPH.matcher(title).replaceFirst("").strip(); + /** + * A title as the harness just wrote it (the live stream). The mark follows it frame + * for frame, cleared when the harness stops writing one. The name follows too, + * except for Codex, whose name is its saved chat name (the poll resolves it) rather + * than its title. A title with no name in it keeps the previous name. + */ + void setLiveTitle(String title) { + liveTitleSeen = true; + TitleParts parts = TitleParts.of(title == null ? "" : title); + this.titleMark = parts.mark(); + if (!parts.name().isBlank() && harnessType() != HarnessType.CODEX) { + this.paneTitle = parts.name(); + } } - private static final java.util.regex.Pattern STATUS_GLYPH = - java.util.regex.Pattern.compile("^\\s*[\\u2800-\\u28FF\\u2722-\\u273D\\u00B7\\u2022\\u25CF]+(\\s+|$)"); + /** Takes over {@code previous}'s title state when the sidebar is rebuilt. */ + void carryTitleFrom(SidebarEntry previous) { + this.paneTitle = previous.paneTitle; + this.titleMark = previous.titleMark; + this.liveTitleSeen = previous.liveTitleSeen; + } + + /** + * A harness title split into its leading status mark and the name after it. The + * mark is a run of non-ASCII symbols (Unicode {@code So}/{@code Sm}, plus {@code ·} + * and {@code •}, which Claude Code cycles through) ending at a space or the end of + * the title; joiners and variation selectors may sit inside it so an emoji stays + * whole. Whatever the harness's spinner glyphs are, they need no listing here. + * Anything else (no mark, or symbols glued to a word) is all name. + */ + record TitleParts(String mark, String name) { + + static TitleParts of(String title) { + String t = title.strip(); + int i = 0; + int marks = 0; + while (i < t.length()) { + int cp = t.codePointAt(i); + if (isMarkSymbol(cp)) { + marks++; + } else if (marks == 0 || !isMarkJoiner(cp)) { + break; + } + i += Character.charCount(cp); + } + if (marks == 0 || (i < t.length() && !Character.isWhitespace(t.codePointAt(i)))) { + return new TitleParts("", t); + } + return new TitleParts(t.substring(0, i), t.substring(i).strip()); + } + + private static boolean isMarkSymbol(int cp) { + if (cp == 0x00B7 || cp == 0x2022) { + return true; + } + int type = Character.getType(cp); + return cp > 0x7F && (type == Character.OTHER_SYMBOL || type == Character.MATH_SYMBOL); + } + + private static boolean isMarkJoiner(int cp) { + int type = Character.getType(cp); + return cp == 0x200D || type == Character.NON_SPACING_MARK || type == Character.ENCLOSING_MARK; + } + } /** The session's name as shown to the user: an explicit persisted rename, then the * harness-set OSC title (e.g. Claude Code's /rename), then the session name. */ @@ -127,12 +203,19 @@ String abbreviatedPath() { } /** - * The row's top line: the session's name (a persisted rename, then the harness-set - * OSC title, then the session name). The harness isn't named + * The row's top line: the harness's live status mark, if any, then the session's + * name (a persisted rename, then the harness-set OSC title, then the session + * name). The harness isn't named * here — the renderer badges the row with {@link #harnessType()}'s glyph instead. */ String nameText() { - return displayName(); + return markedName(); + } + + /** {@link #displayName()} led by the harness's current status mark, if any: the name + * as every title-showing surface presents it. */ + String markedName() { + return titleMark.isEmpty() ? displayName() : titleMark + " " + displayName(); } /** The row's muted second line: the project dir. The renderer clips this from the @@ -152,7 +235,7 @@ private static String escapeHtml(String s) { String tooltipText() { String fullDisplayName = displayName(); StringBuilder html = new StringBuilder("") - .append(escapeHtml(fullDisplayName)).append(""); + .append(escapeHtml(markedName())).append(""); if (!fullDisplayName.equals(sessionName)) { html.append("
").append(escapeHtml(sessionName)); } diff --git a/app/src/test/java/io/github/ghosthack/microhm/app/daemon/SessionServerHostTest.java b/app/src/test/java/io/github/ghosthack/microhm/app/daemon/SessionServerHostTest.java index 1df1274..2c76ee8 100644 --- a/app/src/test/java/io/github/ghosthack/microhm/app/daemon/SessionServerHostTest.java +++ b/app/src/test/java/io/github/ghosthack/microhm/app/daemon/SessionServerHostTest.java @@ -255,6 +255,28 @@ void newSendKeysCaptureAttachInputOutputDetachKill() throws Exception { assertDoesNotThrow(() -> host.killSession(name)); } + /** Every OSC title a program writes reaches {@code watchTitles} as written, frame by + * frame, with no capture in between; a dead home has no stream to open. */ + @Test + void watchTitlesStreamsEachTitleFrameAsWritten() throws Exception { + String name = "mhm-title"; + host.newSession(name, workdir, 100, 30); + List titles = new java.util.concurrent.CopyOnWriteArrayList<>(); + try (var watch = host.watchTitles((session, title) -> { + if (session.equals(name)) { + titles.add(title); + } + }).orElseThrow()) { + assertTrue(watch.isOpen()); + host.sendKeys(name, "printf '\\033]0;\\342\\227\\220 build\\007'; sleep 0.2; " + + "printf '\\033]0;\\342\\227\\221 build\\007'"); + awaitUntil("both frames to arrive", () -> titles.contains("◑ build"), titles::toString); + assertEquals(List.of("◐ build", "◑ build"), titles); + } + SessionServerHost dead = new SessionServerHost(new SessionServerClient(deadHome, false)); + assertThrows(SessionHostException.class, () -> dead.watchTitles((session, title) -> { })); + } + /** Hermeticity pin: the session's cwd is the requested workdir and its foreground * process is {@code sh}, whatever {@code $SHELL} and its login files say — so no * developer dotfile can move the cwd or replace the foreground process under the diff --git a/app/src/test/java/io/github/ghosthack/microhm/app/host/FakeSessionHost.java b/app/src/test/java/io/github/ghosthack/microhm/app/host/FakeSessionHost.java index c3e602d..e83b395 100644 --- a/app/src/test/java/io/github/ghosthack/microhm/app/host/FakeSessionHost.java +++ b/app/src/test/java/io/github/ghosthack/microhm/app/host/FakeSessionHost.java @@ -11,7 +11,11 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; /** * In-memory session host: the test sets up live sessions and screens directly; no @@ -208,4 +212,55 @@ public void close() { } }; } + + // ------------------------------------------------------------------ title stream + + private volatile boolean titleStream; + private final AtomicInteger titleWatchFailures = new AtomicInteger(); + private final List> titleWatchers = new CopyOnWriteArrayList<>(); + /** How many title streams {@link #watchTitles} opened. */ + public final AtomicInteger titleWatchOpens = new AtomicInteger(); + + /** Makes {@link #watchTitles} stream titles (it reports no stream until called). */ + public void enableTitleStream() { + titleStream = true; + } + + /** The next {@code count} {@link #watchTitles} calls throw, like a missing daemon. */ + public void failTitleWatches(int count) { + titleWatchFailures.set(count); + } + + /** Delivers a title change to every open title stream. */ + public void emitTitle(String session, String title) { + titleWatchers.forEach(w -> w.accept(session, title)); + } + + /** Ends every open title stream, like a daemon going away. */ + public void endTitleStreams() { + titleWatchers.clear(); + } + + @Override + public Optional watchTitles(BiConsumer onTitle) { + if (!titleStream) { + return Optional.empty(); + } + if (titleWatchFailures.getAndUpdate(n -> Math.max(0, n - 1)) > 0) { + throw new SessionHostException("no session server is running", null); + } + titleWatchers.add(onTitle); + titleWatchOpens.incrementAndGet(); + return Optional.of(new TitleWatch() { + @Override + public boolean isOpen() { + return titleWatchers.contains(onTitle); + } + + @Override + public void close() { + titleWatchers.remove(onTitle); + } + }); + } } diff --git a/app/src/test/java/io/github/ghosthack/microhm/app/ui/LiveTitlesTest.java b/app/src/test/java/io/github/ghosthack/microhm/app/ui/LiveTitlesTest.java new file mode 100644 index 0000000..d89b04b --- /dev/null +++ b/app/src/test/java/io/github/ghosthack/microhm/app/ui/LiveTitlesTest.java @@ -0,0 +1,80 @@ +package io.github.ghosthack.microhm.app.ui; + +import io.github.ghosthack.microhm.app.host.FakeSessionHost; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BooleanSupplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LiveTitlesTest { + + @Test + void framesArrivingFasterThanTheUiDrainsCoalesceToTheNewestPerSession() { + List edtQueue = new ArrayList<>(); + List> delivered = new ArrayList<>(); + LiveTitles titles = new LiveTitles(new FakeSessionHost(), edtQueue::add, delivered::add); + titles.start(); + try { + titles.titleChanged("a", "◐ build"); + titles.titleChanged("a", "◓ build"); + titles.titleChanged("b", "✳ docs"); + titles.titleChanged("a", "◑ build"); + + assertEquals(1, edtQueue.size(), "one drain queued for the whole burst"); + edtQueue.remove(0).run(); + assertEquals(List.of(Map.of("a", "◑ build", "b", "✳ docs")), delivered); + + titles.titleChanged("a", "◒ build"); + assertEquals(1, edtQueue.size(), "a frame after the drain queues the next one"); + edtQueue.remove(0).run(); + assertEquals(Map.of("a", "◒ build"), delivered.get(1)); + } finally { + titles.stop(); + } + } + + @Test + void streamsTitlesFromTheHostAndReopensAStreamThatEnds() throws Exception { + FakeSessionHost host = new FakeSessionHost(); + host.enableTitleStream(); + host.failTitleWatches(1); // no daemon yet: the first open fails and is retried + List> delivered = new CopyOnWriteArrayList<>(); + LiveTitles titles = new LiveTitles(host, Runnable::run, delivered::add); + titles.start(); + try { + await(() -> host.titleWatchOpens.get() == 1); + host.emitTitle("mhm-a", "⠋ working"); + assertEquals(List.of(Map.of("mhm-a", "⠋ working")), delivered); + + host.endTitleStreams(); + await(() -> host.titleWatchOpens.get() == 2); + host.emitTitle("mhm-a", "⠙ working"); + assertEquals(Map.of("mhm-a", "⠙ working"), delivered.get(1)); + } finally { + titles.stop(); + } + } + + @Test + void stopsQuietlyWhenTheHostHasNoTitleStream() throws Exception { + FakeSessionHost host = new FakeSessionHost(); + LiveTitles titles = new LiveTitles(host, Runnable::run, batch -> { }); + titles.start(); + titles.stop(); + assertEquals(0, host.titleWatchOpens.get()); + } + + private static void await(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + 10_000_000_000L; + while (!condition.getAsBoolean()) { + assertTrue(System.nanoTime() < deadline, "timed out"); + Thread.sleep(20); + } + } +} diff --git a/app/src/test/java/io/github/ghosthack/microhm/app/ui/SidebarViewTest.java b/app/src/test/java/io/github/ghosthack/microhm/app/ui/SidebarViewTest.java index 3beee61..88cd5f9 100644 --- a/app/src/test/java/io/github/ghosthack/microhm/app/ui/SidebarViewTest.java +++ b/app/src/test/java/io/github/ghosthack/microhm/app/ui/SidebarViewTest.java @@ -209,18 +209,73 @@ void tooltipOfANeverRenamedSessionDoesNotRepeatItsName() { } @Test - void harnessStatusGlyphsAreDroppedFromPaneTitleNames() { + void harnessStatusMarksAreKeptApartFromPaneTitleNames() { SidebarEntry entry = live("mhm-glyph", "/work/project"); entry.setPaneTitle("✳ Refactor auth middleware"); assertEquals("Refactor auth middleware", entry.displayName()); + assertEquals("✳", entry.titleMark()); + assertEquals("✳ Refactor auth middleware", entry.nameText()); entry.setPaneTitle("⠼ Refactor auth middleware"); assertEquals("Refactor auth middleware", entry.displayName()); + assertEquals("⠼", entry.titleMark()); // a bare mark carries no name: the previous one stays rather than blanking entry.setPaneTitle("✳"); assertEquals("Refactor auth middleware", entry.displayName()); + assertEquals("✳", entry.titleMark()); // only a leading mark followed by a space is a status mark entry.setPaneTitle("v2 · draft"); assertEquals("v2 · draft", entry.displayName()); + assertEquals("", entry.titleMark()); + assertEquals("v2 · draft", entry.nameText()); + } + + @Test + void anyLeadingSymbolRunIsAMarkWithoutListingSpinnerGlyphs() { + for (String frame : List.of("◐", "◓", "◑", "◒", "◴", "⠋", "·", "•", "●", "✻", "🤖", "❤️")) { + SidebarEntry.TitleParts parts = SidebarEntry.TitleParts.of(frame + " Architecture html page server"); + assertEquals(frame, parts.mark(), frame); + assertEquals("Architecture html page server", parts.name(), frame); + } + // ASCII punctuation, symbols glued to a word, and plain names are all name + for (String title : List.of("~/Projects", "+ add tests", "◑draft", "#12 fix", "Plain name")) { + SidebarEntry.TitleParts parts = SidebarEntry.TitleParts.of(title); + assertEquals("", parts.mark(), title); + assertEquals(title, parts.name(), title); + } + } + + @Test + void liveTitlesDriveTheMarkFrameByFrameAndOutrankPolledSamples() { + SidebarEntry entry = live("mhm-live", "/work/project"); + entry.setLiveTitle("◐ Architecture html page server"); + assertEquals("◐ Architecture html page server", entry.nameText()); + entry.setLiveTitle("◓ Architecture html page server"); + assertEquals("◓", entry.titleMark()); + // a poll sample (older than the stream) keeps the name fresh but not the mark + entry.setPaneTitle("◐ Architecture html page server"); + assertEquals("◓", entry.titleMark()); + // the harness stops writing a mark: so does the row + entry.setLiveTitle("Architecture html page server"); + assertEquals("", entry.titleMark()); + assertEquals("Architecture html page server", entry.nameText()); + // a persisted rename keeps showing the harness's live mark + SidebarEntry renamed = SidebarEntry.live(session("mhm-live", "/work/project", HarnessType.CLAUDE_CODE) + .withDisplayName("Mine")); + renamed.setLiveTitle("⠼ Harness name"); + assertEquals("⠼ Mine", renamed.nameText()); + // a rebuilt row takes the whole title state over + SidebarEntry rebuilt = live("mhm-live", "/work/project"); + rebuilt.carryTitleFrom(entry); + rebuilt.setPaneTitle("✳ Architecture html page server"); + assertEquals("", rebuilt.titleMark()); + } + + @Test + void codexLiveTitlesMoveTheMarkButNotTheSavedChatName() { + SidebarEntry entry = SidebarEntry.live(session("mhm-codex", "/work/project", HarnessType.CODEX)); + entry.setPaneTitle("saved Codex name"); + entry.setLiveTitle("⠼ project-directory"); + assertEquals("⠼ saved Codex name", entry.nameText()); } @Test