From ca1e383254db931e15dfe1df76ad5a8ec2a8fe4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:46:37 +0000 Subject: [PATCH 1/3] feat(focus): open an event's own Herdr pane Herdr runs agents under its own server, so the terminal the hook finds (Ghostty) is shared by every Herdr pane, and Open raised it on whatever pane Herdr last showed. Open now reads HERDR_PANE_ID and HERDR_SOCKET_PATH from the agent's environment (or its shell's, once the agent has exited) and asks Herdr to focus that pane's workspace, tab and pane, before the terminal is raised and any approval keystroke is sent. Co-Authored-By: Claude Opus 5.5 --- .../HerdrFocusTests.swift | 32 +++++++ panel/HerdrFocus.swift | 93 +++++++++++++++++++ panel/Panel.swift | 13 +++ 3 files changed, 138 insertions(+) create mode 100644 Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift create mode 100644 panel/HerdrFocus.swift diff --git a/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift new file mode 100644 index 00000000..c2fc7fc5 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift @@ -0,0 +1,32 @@ +import XCTest + +@testable import StackNudgePanelCore + +final class HerdrFocusTests: XCTestCase { + + func testReadsThePaneAndSocketFromTheAgentsEnvironment() { + let ps = "4242 claude --resume HERDR_PANE_ID=w5C:p1 TERM=xterm HERDR_SOCKET_PATH=/Users/a/.config/herdr/herdr.sock\n" + XCTAssertEqual(HerdrFocus.parse(psOutput: ps, pid: 4242), + HerdrFocus.Target(pane: "w5C:p1", socket: "/Users/a/.config/herdr/herdr.sock")) + } + + func testOutsideHerdrThereIsNoTarget() { + XCTAssertNil(HerdrFocus.parse(psOutput: "4242 claude TERM_SESSION_ID=abc\n", pid: 4242)) + XCTAssertNil(HerdrFocus.parse(psOutput: "4242 claude HERDR_PANE_ID=w5C:p1\n", pid: 4242), + "a pane without a socket can't be focused") + } + + func testFocusesTheWorkspaceAndTabBeforeThePane() { + let reply = Data(#"{"id":"x","result":{"pane":{"pane_id":"w5C:p1","tab_id":"w5C:t1","workspace_id":"w5C"},"type":"pane_info"}}"#.utf8) + let place = HerdrFocus.location(fromReply: reply) + let calls = HerdrFocus.requests(pane: "w5C:p1", workspace: place.workspace, tab: place.tab) + XCTAssertEqual(calls.map(\.0), ["workspace.focus", "tab.focus", "pane.focus"]) + XCTAssertEqual(calls.map(\.1), [["workspace_id": "w5C"], ["tab_id": "w5C:t1"], ["pane_id": "w5C:p1"]]) + } + + func testAnUnreadableReplyStillFocusesThePane() { + let place = HerdrFocus.location(fromReply: Data("not json".utf8)) + XCTAssertEqual(HerdrFocus.requests(pane: "w5C:p1", workspace: place.workspace, tab: place.tab).map(\.0), + ["pane.focus"]) + } +} diff --git a/panel/HerdrFocus.swift b/panel/HerdrFocus.swift new file mode 100644 index 00000000..05218672 --- /dev/null +++ b/panel/HerdrFocus.swift @@ -0,0 +1,93 @@ +import Darwin +import Foundation + +// Herdr (a terminal workspace manager) runs agents under its own server, so the +// hook's process walk ends at the emulator around it, whose session id every +// Herdr pane shares. Raising that emulator leaves Herdr on whatever pane it last +// showed; the agent's environment names its pane, and Herdr's socket focuses it. +enum HerdrFocus { + + struct Target: Equatable { + let pane: String // HERDR_PANE_ID, e.g. "w5C:p1" + let socket: String // HERDR_SOCKET_PATH + } + + static func parse(psOutput raw: String, pid: Int) -> Target? { + guard let pane = EnvVarTerminalIntegration.parseEnvValues(raw, envVar: "HERDR_PANE_ID")[pid], + let socket = EnvVarTerminalIntegration.parseEnvValues(raw, envVar: "HERDR_SOCKET_PATH")[pid] + else { return nil } + return Target(pane: pane, socket: socket) + } + + // Reads the live env, as TmuxFocus does. Off the main thread. + static func target(pid: Int) -> Target? { + guard let raw = ProcessOutput.read( + "/bin/ps", ["eww", "-o", "pid=,command=", "-p", String(pid)], timeout: 3) + else { return nil } + return parse(psOutput: raw, pid: pid) + } + + // The pane's workspace and tab go first: pane.focus alone may not leave + // the workspace on screen. + static func requests(pane: String, workspace: String?, tab: String?) -> [(String, [String: String])] { + var out: [(String, [String: String])] = [] + if let workspace { out.append(("workspace.focus", ["workspace_id": workspace])) } + if let tab { out.append(("tab.focus", ["tab_id": tab])) } + out.append(("pane.focus", ["pane_id": pane])) + return out + } + + // pane.get's reply: {"result":{"pane":{"workspace_id":…,"tab_id":…}}}. + static func location(fromReply reply: Data) -> (workspace: String?, tab: String?) { + guard let obj = try? JSONSerialization.jsonObject(with: reply) as? [String: Any], + let pane = (obj["result"] as? [String: Any])?["pane"] as? [String: Any] + else { return (nil, nil) } + return (pane["workspace_id"] as? String, pane["tab_id"] as? String) + } + + static func focus(_ target: Target) { + let place: (workspace: String?, tab: String?) = + call(target.socket, method: "pane.get", params: ["pane_id": target.pane]) + .map(location(fromReply:)) ?? (nil, nil) + for (method, params) in requests(pane: target.pane, workspace: place.workspace, tab: place.tab) { + _ = call(target.socket, method: method, params: params) + } + } + + // One newline-delimited JSON request per connection; returns the reply line. + private static func call(_ socketPath: String, method: String, params: [String: String]) -> Data? { + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { return nil } + defer { close(fd) } + var timeout = timeval(tv_sec: 1, tv_usec: 0) + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size)) + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size)) + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + let pathBytes = Array(socketPath.utf8) + guard pathBytes.count < MemoryLayout.size(ofValue: addr.sun_path) else { return nil } + withUnsafeMutableBytes(of: &addr.sun_path) { raw in + raw.copyBytes(from: pathBytes) + raw[pathBytes.count] = 0 + } + let connected = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + guard connected == 0 else { return nil } + let request: [String: Any] = ["id": "stack-nudge:\(method)", "method": method, "params": params] + guard var line = try? JSONSerialization.data(withJSONObject: request) else { return nil } + line.append(0x0A) + let sent = line.withUnsafeBytes { send(fd, $0.baseAddress, line.count, 0) } + guard sent == line.count else { return nil } + var reply = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while !reply.contains(0x0A) { + let n = recv(fd, &buffer, buffer.count, 0) + guard n > 0 else { break } + reply.append(contentsOf: buffer[0.. Date: Wed, 2 Dec 2026 18:22:36 +0000 Subject: [PATCH 2/3] fix: address review feedback - Only read Herdr's env when a process named herdr is among the agent's ancestors, so agents that merely inherited HERDR_PANE_ID (e.g. from `code .`) no longer switch Herdr's view. The walk uses proc_pidinfo (no fork), is capped at 32 hops, and runs before the `ps eww` read. - Set SO_NOSIGPIPE on the socket so a Herdr that closes before the write cannot raise SIGPIPE. - Test the socket path against a fake Herdr server (request order and ids, refused socket, hang-up) and the ancestry rule through an injectable lookup. Co-Authored-By: Claude Opus 5.5 --- .../HerdrFocusTests.swift | 140 ++++++++++++++++++ panel/HerdrFocus.swift | 31 +++- 2 files changed, 170 insertions(+), 1 deletion(-) diff --git a/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift index c2fc7fc5..00277b59 100644 --- a/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift +++ b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift @@ -29,4 +29,144 @@ final class HerdrFocusTests: XCTestCase { XCTAssertEqual(HerdrFocus.requests(pane: "w5C:p1", workspace: place.workspace, tab: place.tab).map(\.0), ["pane.focus"]) } + + private func chain(_ entries: [Int: HerdrFocus.ProcessEntry]) -> (Int) -> HerdrFocus.ProcessEntry? { + { entries[$0] } + } + + func testAnAgentUnderHerdrCounts() { + let lookup = chain([ + 500: (ppid: 400, name: "claude"), 400: (ppid: 300, name: "zsh"), + 300: (ppid: 200, name: "herdr"), 200: (ppid: 100, name: "herdr"), + 100: (ppid: 1, name: "ghostty"), + ]) + XCTAssertTrue(HerdrFocus.isUnderHerdr(pid: 500, lookup: lookup)) + XCTAssertTrue(HerdrFocus.isUnderHerdr(pid: 400, lookup: lookup), "the pane's shell is under herdr too") + } + + func testAnAgentOutsideHerdrDoesNotCount() { + let lookup = chain([ + 500: (ppid: 400, name: "claude"), 400: (ppid: 300, name: "zsh"), + 300: (ppid: 200, name: "Code Helper"), 200: (ppid: 100, name: "Code"), + 100: (ppid: 1, name: "launchd"), + ]) + XCTAssertFalse(HerdrFocus.isUnderHerdr(pid: 500, lookup: lookup)) + } + + func testACycleOrAnUnknownProcessStopsTheWalk() { + let cycle = chain([5: (ppid: 6, name: "a"), 6: (ppid: 5, name: "b")]) + XCTAssertFalse(HerdrFocus.isUnderHerdr(pid: 5, lookup: cycle)) + XCTAssertFalse(HerdrFocus.isUnderHerdr(pid: 99, lookup: chain([:]))) + } + + func testHerdrBeyondTheHopLimitDoesNotCount() { + var entries: [Int: HerdrFocus.ProcessEntry] = [:] + for pid in 10..<60 { entries[pid] = (ppid: pid + 1, name: "zsh") } + entries[60] = (ppid: 1, name: "herdr") + XCTAssertFalse(HerdrFocus.isUnderHerdr(pid: 10, lookup: chain(entries))) + XCTAssertTrue(HerdrFocus.isUnderHerdr(pid: 10, maxHops: 64, lookup: chain(entries))) + } + + // MARK: - Socket + + private final class FakeHerdr { + let path: String + private let listener: Int32 + private let lock = NSLock() + private var seen: [(method: String, params: [String: String])] = [] + private let done = DispatchSemaphore(value: 0) + + var requests: [(method: String, params: [String: String])] { + lock.lock(); defer { lock.unlock() } + return seen + } + + init() { + path = "/tmp/hf-\(getpid())-\(UInt32.random(in: 0...size)) + } + } + listen(listener, 8) + } + + // closeAtOnce: accept and hang up without reading, as a Herdr that is going away would. + func start(connections count: Int, closeAtOnce: Bool = false) { + let listener = self.listener + Thread.detachNewThread { [self] in + for _ in 0..= 0 else { break } + if !closeAtOnce { serve(fd) } + close(fd) + } + done.signal() + } + } + + private func serve(_ fd: Int32) { + var data = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while !data.contains(0x0A) { + let n = recv(fd, &buffer, buffer.count, 0) + guard n > 0 else { return } + data.append(contentsOf: buffer[0.. ProcessEntry? = liveProcess(_:)) -> Bool { + var current = lookup(pid)?.ppid ?? 0 + for _ in 0.. 1, let entry = lookup(current) else { return false } + if entry.name == "herdr" { return true } + current = entry.ppid + } + return false + } + + // In-process, no fork: the process's parent pid and its own name. + static func liveProcess(_ pid: Int) -> ProcessEntry? { + var info = proc_bsdinfo() + let size = Int32(MemoryLayout.size) + guard proc_pidinfo(pid_t(pid), PROC_PIDTBSDINFO, 0, &info, size) == size else { return nil } + let name = withUnsafeBytes(of: info.pbi_comm) { raw in + String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self) + } + return (Int(info.pbi_ppid), name) + } + // Reads the live env, as TmuxFocus does. Off the main thread. static func target(pid: Int) -> Target? { + guard isUnderHerdr(pid: pid) else { return nil } guard let raw = ProcessOutput.read( "/bin/ps", ["eww", "-o", "pid=,command=", "-p", String(pid)], timeout: 3) else { return nil } @@ -55,13 +82,15 @@ enum HerdrFocus { } // One newline-delimited JSON request per connection; returns the reply line. - private static func call(_ socketPath: String, method: String, params: [String: String]) -> Data? { + static func call(_ socketPath: String, method: String, params: [String: String]) -> Data? { let fd = socket(AF_UNIX, SOCK_STREAM, 0) guard fd >= 0 else { return nil } defer { close(fd) } var timeout = timeval(tv_sec: 1, tv_usec: 0) setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size)) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size)) + var noSigPipe: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout.size)) var addr = sockaddr_un() addr.sun_family = sa_family_t(AF_UNIX) let pathBytes = Array(socketPath.utf8) From d40d4c3bfc83634697039d9263d6d3bdeeb3c542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:21:47 +0000 Subject: [PATCH 3/3] test(focus): call the socket functions through Darwin CI's compiler resolved bind to an instance method in the test class. Co-Authored-By: Claude Opus 5.5 --- Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift index 00277b59..f57c69c3 100644 --- a/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift +++ b/Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift @@ -94,10 +94,10 @@ final class HerdrFocusTests: XCTestCase { } _ = withUnsafePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - bind(listener, $0, socklen_t(MemoryLayout.size)) + Darwin.bind(listener, $0, socklen_t(MemoryLayout.size)) } } - listen(listener, 8) + Darwin.listen(listener, 8) } // closeAtOnce: accept and hang up without reading, as a Herdr that is going away would. @@ -105,7 +105,7 @@ final class HerdrFocusTests: XCTestCase { let listener = self.listener Thread.detachNewThread { [self] in for _ in 0..= 0 else { break } if !closeAtOnce { serve(fd) } close(fd)