Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions Tests/StackNudgePanelCoreTests/HerdrFocusTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
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"])
}

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..<UInt32.max)).sock"
unlink(path)
listener = socket(AF_UNIX, SOCK_STREAM, 0)
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
let bytes = Array(path.utf8)
withUnsafeMutableBytes(of: &addr.sun_path) { raw in
raw.copyBytes(from: bytes)
raw[bytes.count] = 0
}
_ = withUnsafePointer(to: &addr) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.bind(listener, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
Darwin.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..<count {
let fd = Darwin.accept(listener, nil, nil)
guard fd >= 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..<n])
}
guard let obj = try? JSONSerialization.jsonObject(with: data.split(separator: 0x0A)[0]) as? [String: Any],
let method = obj["method"] as? String
else { return }
lock.lock()
seen.append((method, obj["params"] as? [String: String] ?? [:]))
lock.unlock()
let reply = Array((#"{"id":"x","result":{"pane":{"pane_id":"w5C:p1","tab_id":"w5C:t1","workspace_id":"w5C"},"type":"pane_info"}}"# + "\n").utf8)
let mid = reply.count / 2
_ = send(fd, reply, mid, 0)
Thread.sleep(forTimeInterval: 0.05)
_ = send(fd, Array(reply[mid...]), reply.count - mid, 0)
}

func finish() {
_ = done.wait(timeout: .now() + 5)
close(listener)
unlink(path)
}
}

func testFocusSendsTheFourRequestsInOrderOverTheSocket() {
let server = FakeHerdr()
server.start(connections: 4)
HerdrFocus.focus(HerdrFocus.Target(pane: "w5C:p1", socket: server.path))
server.finish()
XCTAssertEqual(server.requests.map(\.method),
["pane.get", "workspace.focus", "tab.focus", "pane.focus"])
XCTAssertEqual(server.requests.map(\.params), [
["pane_id": "w5C:p1"], ["workspace_id": "w5C"], ["tab_id": "w5C:t1"], ["pane_id": "w5C:p1"],
])
}

func testARefusedSocketReturnsQuickly() {
let start = Date()
XCTAssertNil(HerdrFocus.call("/tmp/hf-no-such-\(getpid()).sock", method: "pane.get", params: [:]))
HerdrFocus.focus(HerdrFocus.Target(pane: "w5C:p1", socket: "/tmp/hf-no-such-\(getpid()).sock"))
XCTAssertLessThan(Date().timeIntervalSince(start), 1.0)
}

func testAServerThatHangsUpDoesNotKillUs() {
let server = FakeHerdr()
server.start(connections: 20, closeAtOnce: true)
for _ in 0..<20 {
_ = HerdrFocus.call(server.path, method: "pane.get", params: ["pane_id": String(repeating: "x", count: 100_000)])
}
server.finish()
}
}
122 changes: 122 additions & 0 deletions panel/HerdrFocus.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
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)
}

typealias ProcessEntry = (ppid: Int, name: String)

// The env vars leak into anything started from a Herdr pane (`code .`), so
// they only count when a process named herdr is among the ancestors.
static func isUnderHerdr(pid: Int, maxHops: Int = 32,
lookup: (Int) -> ProcessEntry? = liveProcess(_:)) -> Bool {
var current = lookup(pid)?.ppid ?? 0
for _ in 0..<maxHops {
guard current > 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<proc_bsdinfo>.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 }
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.
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<timeval>.size))
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
var noSigPipe: Int32 = 1
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout<Int32>.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<sockaddr_un>.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) }
Comment thread
adefreitas marked this conversation as resolved.
Resolved
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..<n])
}
return reply.split(separator: 0x0A).first.map { Data($0) }
}
}
13 changes: 13 additions & 0 deletions panel/Panel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3729,6 +3729,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
}
if config.activateImmediately, let bundleID = event.bundleID {
DispatchQueue.global(qos: .userInitiated).async {
Self.focusHerdrPane(pids: [event.agentPID, event.shellPID])
AppActivator.activate(bundleID: bundleID,
windowTitle: event.windowTitle,
ipcHook: event.ipcHook,
Expand Down Expand Up @@ -4468,6 +4469,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,

DispatchQueue.global(qos: .userInitiated).async {
Thread.sleep(forTimeInterval: 0.15)
Self.focusHerdrPane(pids: [event.agentPID, event.shellPID])
AppActivator.activate(bundleID: bundleID,
windowTitle: event.windowTitle,
ipcHook: event.ipcHook,
Expand Down Expand Up @@ -6025,6 +6027,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
hidePanel()
DispatchQueue.global(qos: .userInitiated).async {
Thread.sleep(forTimeInterval: 0.15)
Self.focusHerdrPane(pids: [event.agentPID, event.shellPID])
AppActivator.activate(
bundleID: bundleID,
windowTitle: event.windowTitle,
Expand Down Expand Up @@ -6305,6 +6308,15 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
}
}

// Inside Herdr the raised terminal shows whichever pane Herdr last had up,
// so ask Herdr for the agent's own pane, before any approval keystroke is
// sent. The shell outlives a finished agent. Background queue only.
static func focusHerdrPane(pids: [Int?]) {
guard let target = pids.lazy.compactMap({ $0 }).compactMap(HerdrFocus.target(pid:)).first
Comment thread
adefreitas marked this conversation as resolved.
Resolved
else { return }
HerdrFocus.focus(target)
}

private func focusSelectedSession() {
guard let pid = sessions.selectedPID,
let session = sessions.sessions.first(where: { $0.pid == pid })
Expand Down Expand Up @@ -6343,6 +6355,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
// frontmost before we raise the target — mirrors actOnSelected
// and the banner-click path.
Thread.sleep(forTimeInterval: 0.15)
Self.focusHerdrPane(pids: [session.pid])
AppActivator.activate(
bundleID: bundleID,
windowTitle: session.projectName,
Expand Down
Loading