From b9e70bedcbdbe031d6d294c3b5691b81dd466eb8 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 14 Sep 2026 01:38:01 -0700 Subject: [PATCH] Raise a live session's terminal from the Capacity Dock card MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clicking a session row finds the row's process — Claude Code writes its pid into ~/.claude/sessions/.json, Kimi Code is found by the one `kimi` working in the directory its state.json records — walks the process tree to the application that owns it, selects the tab by tty in Terminal.app and iTerm2, and raises the app everywhere else. The AppleScript runs off the main actor with a 3s cap. A row whose process cannot be found keeps its layout and stays inert: no pointer change, no tooltip. --- CHANGELOG.md | 1 + .../Data/UsageDataChangeGuard.swift | 2 +- .../Resources/en.lproj/Localizable.strings | 5 + .../zh-Hans.lproj/Localizable.strings | 3 + .../Security/SessionFocus.swift | 336 ++++++++++++++++++ .../Views/CapacityDockView.swift | 36 ++ .../SessionFocusTests.swift | 168 +++++++++ 7 files changed, 550 insertions(+), 1 deletion(-) create mode 100644 mac/Sources/CodeBurnMenubar/Security/SessionFocus.swift create mode 100644 mac/Tests/CodeBurnMenubarTests/SessionFocusTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d0ab290..a63788d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - **Kimi Code sessions now show up in the live-sessions block.** A Kimi session whose `agents/*/wire.jsonl` was written inside the liveness window is reported as `kimicode`, with its project, the model of its last request and the activity of its sub-agents folded in. ### Added (macOS) +- **Clicking a live session in the Capacity Dock card raises the terminal it is running in.** The row's process is found from Claude Code's own `~/.claude/sessions/.json` or, for Kimi Code, from the one `kimi` working in the session's directory, and the process tree is walked up to the application that owns it: Terminal.app and iTerm2 get the exact tab selected by tty, every other terminal is brought to the front. A row whose process cannot be found stays inert, with no pointer change and no tooltip. - **Launching the menubar app replaces the copy already running instead of stacking a second Capacity Dock on the screen edge.** At launch it terminates only *strictly older* instances of its own bundle identifier, so two simultaneous launches cannot quit each other and leave none, and an older copy that ignores the polite quit is forced out a few seconds later. - **The menubar tells you when a quota window crosses 80% and again when it hits its limit.** Every connected provider's windows — the same list the menu-bar flame and the popover warning row are built from — are checked on the quota refresh that already runs, with no new polling: crossing 80% posts `Claude · Weekly at 80%`, reaching the limit posts `Claude · Weekly limit reached`. Each fires once per window per cycle, a window that hits its limit without ever having been seen at 80% posts only the limit notice, and the cycle's reset instant is part of the identity, so the next cycle re-arms both while an absent or failed fetch keeps what was already announced. The fired set is persisted, so a relaunch does not repeat a crossing. Notification authorization is requested on the first real crossing and never at launch. Settings → Notifications gains a switch, on by default. - **The macOS menubar app speaks Simplified Chinese, and follows your system language to decide.** Every user-facing string in the popover, the Capacity Dock, the status-item menu, the update alerts and all of Settings now resolves through a `Localizable.strings` catalog shipped for `en` and `zh-Hans` with no third-party library: 628 keys, whose key *is* the English copy, so an untranslated string degrades to correct English rather than a visible identifier. AppKit picks the table from the user's preferred languages; Settings > General > Language overrides it for CodeBurn alone by writing `AppleLanguages` into the app's own preferences domain, which is the same key `CFBundleLocalizations` makes System Settings > Language & Region > Applications write, so the two surfaces are one setting rather than two. Enum raw values that double as persistence or cache keys (`Period`, `MenubarScope`, `InsightMode`, `AccentPreset`, `ProviderFilter`) keep their raw value and gained a separate display label, so nothing a user has saved changes meaning. Three display-only date formatters that were pinned to `en_US_POSIX` with fixed patterns now follow the locale, and the calendar popover's weekday row comes from the locale's own short symbols clipped to two units, so a Chinese UI reads `2026年9月` and `周一 周二` while English keeps `Mo Tu We`. That locale move is the one place English output changes: `EEE MMM d` reads `Sat, Sep 12` in en_US and `Sat 12 Sep` in en_GB, and `MMM d` reads `12 Sep` in en_GB. Provider, model and plan names, units, currency codes, shell commands and anything the `codeburn` CLI itself produces stay verbatim in every locale. Adding a language is now one more `.lproj`; a test fails the build if the two tables disagree on keys, leave a value blank, or disagree on format specifiers, and a second test reads `mac/Sources` itself and fails when a user-facing literal never reaches the catalog at all — the drift a catalog-versus-catalog diff cannot see, because both tables stay in perfect agreement while a bare `Text("…")` ships English to a zh-Hans user. This covers the menubar half of #1219 only, not the CLI output or the web dashboard. (#1219) diff --git a/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift b/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift index f037556f..236bac03 100644 --- a/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift +++ b/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift @@ -157,7 +157,7 @@ enum UsageDataChangeGuard { return attributes[.modificationDate] as? Date } - private static func claudeConfigDirectories(environment: [String: String], homeDirectory: String) -> [String] { + static func claudeConfigDirectories(environment: [String: String], homeDirectory: String) -> [String] { if let multi = environment["CLAUDE_CONFIG_DIRS"], !multi.isEmpty { return multi.split(separator: ":").map { expand(String($0), homeDirectory: homeDirectory) } } diff --git a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings index 04df040b..0c7f2ae5 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings @@ -433,6 +433,11 @@ "1 running" = "1 running"; "%lld running" = "%lld running"; "%@ left" = "%@ left"; +/* Tooltip on a live-session row. %@ is the terminal application's own name, + left verbatim. The second form is used where the terminal cannot select the + session's tab, only come forward. */ +"Open in %@" = "Open in %@"; +"Bring %@ to front" = "Bring %@ to front"; "burned" = "burned"; "today %@ of %@" = "today %@ of %@"; "no budget set" = "no budget set"; diff --git a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings index 10d785ff..cef5b8b7 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings @@ -426,6 +426,9 @@ "1 running" = "1 个运行中"; "%lld running" = "%lld 个运行中"; "%@ left" = "剩余 %@"; +/* 运行中会话行的提示。%@ 为终端应用自身的名称,保持原样。 */ +"Open in %@" = "在 %@ 中打开"; +"Bring %@ to front" = "将 %@ 切换到前台"; "burned" = "已消耗"; "today %@ of %@" = "今天 %@ / %@"; "no budget set" = "未设置预算"; diff --git a/mac/Sources/CodeBurnMenubar/Security/SessionFocus.swift b/mac/Sources/CodeBurnMenubar/Security/SessionFocus.swift new file mode 100644 index 00000000..5cf5a56a --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Security/SessionFocus.swift @@ -0,0 +1,336 @@ +import AppKit +import Darwin +import Foundation + +/// Where a live-session row points: the application that owns the agent's +/// process, plus the tty of the shell it runs in when the terminal can name a +/// tab by it. +struct SessionFocusTarget: Equatable, Sendable { + let appPID: pid_t + let bundleID: String + let appName: String + let tty: String? + + /// Terminal.app and iTerm2 can raise the exact tab; every other terminal + /// only gets the app, and the tooltip promises no more than that. + var selectsTab: Bool { SessionTabScript.script(bundleID: bundleID, tty: tty) != nil } + + var tooltip: String { + selectsTab ? L("Open in %@", appName) : L("Bring %@ to front", appName) + } +} + +/// One process as the ancestry walk sees it. +struct SessionProcess: Equatable, Sendable { + let ppid: pid_t + let tty: String? + /// Set only when macOS knows this pid as a running application, which is + /// what makes an ancestor the terminal rather than another shell. + let bundleID: String? + let appName: String? +} + +/// Raises the terminal a live session is running in. +/// +/// A session row knows a session id, not a window: neither Claude Code nor Kimi +/// publishes one. What it can be given is a pid — Claude writes its own into +/// `~/.claude/sessions/.json`, Kimi is found by the working directory its +/// state file records — and a pid has a parent, and somewhere up that chain is +/// the terminal application. So the app is found by walking the process tree, +/// and the tab inside it by the tty the shell holds. +enum SessionFocus { + /// A pid whose start time disagrees with the session file by more than this + /// has been recycled and belongs to something else. Wide enough to absorb + /// the gap between the process starting and the file being written. + static let pidReuseTolerance: TimeInterval = 5 * 60 + + // MARK: - Pure core + + /// Walks from the agent's process up to the application that owns it, + /// keeping the first tty seen on the way — the shell the agent talks to. + /// + /// Bounded rather than looped to pid 1: a `kinfo_proc` naming itself as its + /// own parent would otherwise spin, and no real agent-to-terminal chain is + /// more than a handful deep. launchd ends the walk with nothing, which is + /// the honest answer for an agent started outside a terminal. + static func owner( + of pid: pid_t, + hops: Int = 8, + lookup: (pid_t) -> SessionProcess? + ) -> SessionFocusTarget? { + var current = pid + var tty: String? + for _ in 0.. 1, let process = lookup(current) else { return nil } + if tty == nil { tty = process.tty } + if let bundleID = process.bundleID { + return SessionFocusTarget( + appPID: current, + bundleID: bundleID, + appName: process.appName ?? bundleID, + tty: tty + ) + } + guard process.ppid != current else { return nil } + current = process.ppid + } + return nil + } + + /// The pid running `sessionID`, or nil when no file claims it, the process + /// is gone, or the pid has since been handed to something unrelated. + static func pid( + forSessionID sessionID: String, + files: [ClaudeSessionFile], + startTime: (pid_t) -> Date? + ) -> pid_t? { + guard let file = files.first(where: { $0.sessionId == sessionID }), + let started = startTime(file.pid), + abs(started.timeIntervalSince1970 - file.startedAt / 1000) < pidReuseTolerance + else { return nil } + return file.pid + } + + /// The one candidate working in `cwd`. Two agents in the same directory are + /// treated as not found: raising the wrong window is worse than doing nothing. + static func pid(forWorkingDirectory cwd: String, candidates: [(pid: pid_t, cwd: String)]) -> pid_t? { + let matches = candidates.filter { $0.cwd == cwd } + return matches.count == 1 ? matches[0].pid : nil + } + + // MARK: - Resolving a row + + /// Where this row points, or nil when its process cannot be found — which + /// leaves the row inert rather than promising a window that is not there. + /// Reads files and walks the process tree, so callers keep it off the main + /// actor. + static func target(for session: LiveSession) -> SessionFocusTarget? { + guard let pid = sessionPID(for: session) else { return nil } + return owner(of: pid, lookup: process(of:)) + } + + /// Selects the session's tab where the terminal allows it, then raises the + /// owning application either way. The script is a subprocess, so it runs off + /// the main actor with a hard cap on how long it may take. + @MainActor + static func raise(_ target: SessionFocusTarget) { + let app = NSRunningApplication(processIdentifier: target.appPID) + let script = SessionTabScript.script(bundleID: target.bundleID, tty: target.tty) + DispatchQueue.global(qos: .userInitiated).async { + if let script { runScript(script) } + DispatchQueue.main.async { app?.activate() } + } + } + + private static func sessionPID(for session: LiveSession) -> pid_t? { + switch session.provider { + case "claude": + return pid(forSessionID: session.id, files: claudeSessionFiles(), startTime: startTime(of:)) + case "kimicode": + guard let cwd = kimiWorkingDirectory(sessionID: session.id) else { return nil } + return pid(forWorkingDirectory: resolved(cwd), candidates: kimiProcesses()) + default: + return nil + } + } + + // MARK: - Claude + + /// Every `/sessions/.json` Claude Code has written. The + /// directory also holds `.key` files, which are not sessions. + private static func claudeSessionFiles() -> [ClaudeSessionFile] { + let decoder = JSONDecoder() + let directories = UsageDataChangeGuard.claudeConfigDirectories( + environment: ProcessInfo.processInfo.environment, + homeDirectory: NSHomeDirectory() + ) + return directories.flatMap { configDir -> [ClaudeSessionFile] in + let directory = URL(fileURLWithPath: configDir).appendingPathComponent("sessions") + let entries = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? [] + return entries.filter { $0.hasSuffix(".json") }.compactMap { entry in + guard let data = try? Data(contentsOf: directory.appendingPathComponent(entry)) else { return nil } + return try? decoder.decode(ClaudeSessionFile.self, from: data) + } + } + } + + // MARK: - Kimi Code + + /// Kimi keeps `/sessions//session_/state.json`, and the row's + /// id is that directory's suffix. Nothing on disk names the pid, so this only + /// recovers the directory the agent is working in. + static func kimiWorkingDirectory( + sessionID: String, + home: String = ProcessInfo.processInfo.environment["KIMI_CODE_HOME"] + ?? NSHomeDirectory() + "/.kimi-code" + ) -> String? { + let sessions = URL(fileURLWithPath: home).appendingPathComponent("sessions") + let workDirs = (try? FileManager.default.contentsOfDirectory(atPath: sessions.path)) ?? [] + for workDir in workDirs { + let state = sessions + .appendingPathComponent(workDir) + .appendingPathComponent("session_" + sessionID) + .appendingPathComponent("state.json") + guard let data = try? Data(contentsOf: state), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + else { continue } + if let cwd = object["cwd"] as? String, !cwd.isEmpty { return cwd } + if let workDir = object["workDir"] as? String, !workDir.isEmpty { return workDir } + } + return nil + } + + /// Running `kimi` processes with the directory each is working in. The name + /// comes from `p_comm`, which is the executable's, so a shell function or an + /// alias named `kimi` is not mistaken for one. + private static func kimiProcesses() -> [(pid: pid_t, cwd: String)] { + var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0] + var size = 0 + guard sysctl(&mib, u_int(mib.count), nil, &size, nil, 0) == 0, size > 0 else { return [] } + var table = [kinfo_proc](repeating: kinfo_proc(), count: size / MemoryLayout.stride) + guard sysctl(&mib, u_int(mib.count), &table, &size, nil, 0) == 0 else { return [] } + return table.prefix(size / MemoryLayout.stride).compactMap { entry in + var proc = entry + let width = MemoryLayout.size(ofValue: proc.kp_proc.p_comm) + let name = withUnsafePointer(to: &proc.kp_proc.p_comm) { pointer in + pointer.withMemoryRebound(to: CChar.self, capacity: width) { String(cString: $0) } + } + guard name == "kimi", let cwd = workingDirectory(of: proc.kp_proc.p_pid) else { return nil } + return (proc.kp_proc.p_pid, resolved(cwd)) + } + } + + /// The kernel reports `/private/var/…` where the user's path says `/var/…`, + /// and either side can carry a symlink, so both are compared resolved. + private static func resolved(_ path: String) -> String { + URL(fileURLWithPath: path).resolvingSymlinksInPath().path + } + + // MARK: - Reading the process table + + private static func process(of pid: pid_t) -> SessionProcess? { + guard let info = kernelProcess(pid) else { return nil } + var tty: String? + // NODEV (-1) means no controlling terminal; devname would read it as a + // real device number and answer garbage. + if info.kp_eproc.e_tdev != -1, let name = devname(info.kp_eproc.e_tdev, S_IFCHR) { + tty = String(cString: name) + } + let app = NSRunningApplication(processIdentifier: pid) + return SessionProcess( + ppid: info.kp_eproc.e_ppid, + tty: tty, + bundleID: app?.bundleIdentifier, + appName: app?.localizedName + ) + } + + static func startTime(of pid: pid_t) -> Date? { + guard let info = kernelProcess(pid) else { return nil } + let started = info.kp_proc.p_starttime + return Date(timeIntervalSince1970: Double(started.tv_sec) + Double(started.tv_usec) / 1_000_000) + } + + private static func kernelProcess(_ pid: pid_t) -> kinfo_proc? { + var info = kinfo_proc() + var size = MemoryLayout.stride + var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid] + guard sysctl(&mib, u_int(mib.count), &info, &size, nil, 0) == 0, size > 0 else { return nil } + return info + } + + private static func workingDirectory(of pid: pid_t) -> String? { + var info = proc_vnodepathinfo() + let read = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, Int32(MemoryLayout.size)) + guard read == Int32(MemoryLayout.size) else { return nil } + return withUnsafePointer(to: &info.pvi_cdir.vip_path) { pointer in + pointer.withMemoryRebound(to: CChar.self, capacity: Int(MAXPATHLEN)) { String(cString: $0) } + } + } + + // MARK: - Running the script + + /// Detached with a hard cap: a terminal wedged on its own AppleScript must + /// not keep a worker alive, and the caller has already returned either way. + private static func runScript(_ script: String) { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript") + process.arguments = ["-e", script] + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + let finished = DispatchSemaphore(value: 0) + process.terminationHandler = { _ in finished.signal() } + do { + try process.run() + } catch { + NSLog("CodeBurn: could not spawn osascript to focus a session: \(error.localizedDescription)") + return + } + if finished.wait(timeout: .now() + 3) == .timedOut { + NSLog("CodeBurn: osascript did not select the session's tab in 3s; terminating it") + process.terminate() + } + } +} + +/// One `~/.claude/sessions/.json`. Claude Code writes far more than this; +/// only the three fields that identify the running process are read. +struct ClaudeSessionFile: Decodable, Equatable, Sendable { + let pid: pid_t + let sessionId: String + /// Epoch milliseconds, used only to notice a recycled pid. + let startedAt: Double +} + +/// AppleScript that selects the tab holding a tty. +/// +/// There is no general mechanism: Terminal.app and iTerm2 both expose a tty per +/// tab, and everything else (Warp, Ghostty, WezTerm, kitty) publishes nothing to +/// match on, so those fall back to raising the application. +enum SessionTabScript { + static func script(bundleID: String, tty: String?) -> String? { + // The tty comes from the kernel, but it is interpolated into a script, + // so it is held to the shape `devname` produces rather than trusted. + guard let tty, !tty.isEmpty, + tty.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }) + else { return nil } + switch bundleID { + case "com.apple.Terminal": + return """ + tell application "Terminal" + repeat with w in windows + repeat with t in tabs of w + if tty of t is "/dev/\(tty)" then + set selected of t to true + set index of w to 1 + return + end if + end repeat + end repeat + end tell + """ + case "com.googlecode.iterm2": + // "iTerm", not "iTerm2", for the reason PreferredTerminal records: + // the bundle is iTerm.app, and that name resolves whether or not + // the app's terminology has loaded. + return """ + tell application "iTerm" + repeat with w in windows + repeat with t in tabs of w + repeat with s in sessions of t + if tty of s is "/dev/\(tty)" then + select s + select t + select w + return + end if + end repeat + end repeat + end repeat + end tell + """ + default: + return nil + } + } +} diff --git a/mac/Sources/CodeBurnMenubar/Views/CapacityDockView.swift b/mac/Sources/CodeBurnMenubar/Views/CapacityDockView.swift index b77f1e3c..dfbb311a 100644 --- a/mac/Sources/CodeBurnMenubar/Views/CapacityDockView.swift +++ b/mac/Sources/CodeBurnMenubar/Views/CapacityDockView.swift @@ -737,6 +737,10 @@ struct CapacityDockDetailView: View { let quota: (CapacityDockProvider) -> QuotaSummary? let onConnect: (CapacityDockProvider) -> Void @Environment(AppStore.self) private var store + /// Session id -> the terminal its process was found in. A row missing from + /// here stays inert; resolution reads files and the process table, so it + /// happens once per session list rather than per render. + @State private var sessionFocusTargets: [String: SessionFocusTarget] = [:] var body: some View { let bubbleShape = CapacityDockBubbleShape( @@ -940,6 +944,13 @@ struct CapacityDockDetailView: View { .padding(.top, CapacityDockGlance.sectionPadTop * s) .padding(.bottom, CapacityDockGlance.sectionPadBottom * s) .padding(.horizontal, CapacityDockGlance.contentInset * s) + .task(id: sessions.map(\.id)) { + sessionFocusTargets = await Task.detached(priority: .utility) { + sessions.reduce(into: [String: SessionFocusTarget]()) { targets, session in + targets[session.id] = SessionFocus.target(for: session) + } + }.value + } } private func sessionsTrailing(_ count: Int) -> String { @@ -1008,6 +1019,7 @@ struct CapacityDockDetailView: View { ) // A session waiting on the user recedes; one that is generating does not. .opacity(session.isIdle ? 0.55 : 1) + .modifier(SessionFocusAffordance(target: sessionFocusTargets[session.id])) } /// The pill itself is the context gauge: a tinted band over the first N% of @@ -1318,6 +1330,30 @@ struct CapacityDockDetailView: View { } } +/// Click-to-raise on a session row whose process was found. A row that resolved +/// to nothing keeps exactly the layout, the cursor and the inertness it had, so +/// the affordance never promises a window that is not there. +private struct SessionFocusAffordance: ViewModifier { + let target: SessionFocusTarget? + + @ViewBuilder + func body(content: Content) -> some View { + if let target { + content + .contentShape(Rectangle()) + .help(target.tooltip) + .accessibilityAddTraits(.isButton) + .accessibilityHint(target.tooltip) + .onHover { hovering in + if hovering { NSCursor.pointingHand.push() } else { NSCursor.pop() } + } + .onTapGesture { SessionFocus.raise(target) } + } else { + content + } + } +} + /// A percentage drawn as its own gauge: the glyphs sit dim, and the value's own /// severity colour fills them left to right up to the value, wiped off on a /// slant. One band colour, so the fill says how bad it is and the wipe says how diff --git a/mac/Tests/CodeBurnMenubarTests/SessionFocusTests.swift b/mac/Tests/CodeBurnMenubarTests/SessionFocusTests.swift new file mode 100644 index 00000000..51f60b36 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/SessionFocusTests.swift @@ -0,0 +1,168 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +/// The parts of "raise the terminal this session runs in" that can be decided +/// without a process table: the ancestry walk, the tab script, and the two +/// matchers that turn a session row into a pid. +@Suite("Session focus") +struct SessionFocusTests { + + /// A table of processes standing in for the kernel's. + static func lookup(_ table: [pid_t: SessionProcess]) -> (pid_t) -> SessionProcess? { + { table[$0] } + } + + static func shell(ppid: pid_t, tty: String? = nil) -> SessionProcess { + SessionProcess(ppid: ppid, tty: tty, bundleID: nil, appName: nil) + } + + static func app(_ bundleID: String, _ name: String) -> SessionProcess { + SessionProcess(ppid: 1, tty: nil, bundleID: bundleID, appName: name) + } + + // MARK: - Walking to the owning app + + @Test("the first ancestor macOS knows as an application is the owner") + func findsOwningApp() { + let target = SessionFocus.owner(of: 500, lookup: Self.lookup([ + 500: Self.shell(ppid: 400, tty: "ttys004"), + 400: Self.shell(ppid: 300), + 300: Self.app("com.apple.Terminal", "Terminal"), + ])) + #expect(target?.appPID == 300) + #expect(target?.bundleID == "com.apple.Terminal") + #expect(target?.appName == "Terminal") + // The tty belongs to the shell, not to the app above it. + #expect(target?.tty == "ttys004") + } + + @Test("a chain that reaches launchd owns nothing") + func stopsAtLaunchd() { + let target = SessionFocus.owner(of: 500, lookup: Self.lookup([ + 500: Self.shell(ppid: 1, tty: "ttys004"), + 1: Self.shell(ppid: 0), + ])) + #expect(target == nil) + } + + @Test("the walk gives up after eight hops rather than following a long chain") + func stopsAfterEightHops() { + var table: [pid_t: SessionProcess] = [:] + for pid in pid_t(100)...pid_t(120) { table[pid] = Self.shell(ppid: pid + 1) } + table[121] = Self.app("com.apple.Terminal", "Terminal") + #expect(SessionFocus.owner(of: 100, lookup: Self.lookup(table)) == nil) + #expect(SessionFocus.owner(of: 100, hops: 30, lookup: Self.lookup(table))?.appPID == 121) + } + + @Test("a process that names itself as its own parent does not loop") + func survivesSelfParent() { + let target = SessionFocus.owner(of: 500, lookup: Self.lookup([500: Self.shell(ppid: 500)])) + #expect(target == nil) + } + + @Test("an app that is not a known terminal still owns the session") + func ownsAnyAppBundle() { + let target = SessionFocus.owner(of: 500, lookup: Self.lookup([ + 500: Self.shell(ppid: 300, tty: "ttys004"), + 300: Self.app("dev.warp.Warp-Stable", "Warp"), + ])) + #expect(target?.appName == "Warp") + // Warp publishes no tab to select, so the row promises only a raise. + #expect(target?.selectsTab == false) + #expect(target?.tooltip == "Bring Warp to front") + } + + // MARK: - The tab script + + @Test("Terminal.app and iTerm2 select the tab holding the tty") + func buildsTabScripts() throws { + let terminal = try #require(SessionTabScript.script(bundleID: "com.apple.Terminal", tty: "ttys004")) + #expect(terminal.contains("tell application \"Terminal\"")) + #expect(terminal.contains("if tty of t is \"/dev/ttys004\"")) + + let iterm = try #require(SessionTabScript.script(bundleID: "com.googlecode.iterm2", tty: "ttys012")) + #expect(iterm.contains("tell application \"iTerm\"")) + #expect(iterm.contains("if tty of s is \"/dev/ttys012\"")) + #expect(iterm.contains("sessions of t")) + } + + @Test("a terminal with no tab to name, or a session with no tty, gets no script") + func refusesWhatItCannotSelect() { + #expect(SessionTabScript.script(bundleID: "dev.warp.Warp-Stable", tty: "ttys004") == nil) + #expect(SessionTabScript.script(bundleID: "com.apple.Terminal", tty: nil) == nil) + #expect(SessionTabScript.script(bundleID: "com.apple.Terminal", tty: "") == nil) + } + + @Test("a tty that is not the shape devname produces never reaches the script") + func refusesUnshapedTTY() { + for tty in ["ttys004\" or true or \"", "../../evil", "ttys 004"] { + #expect(SessionTabScript.script(bundleID: "com.apple.Terminal", tty: tty) == nil) + } + } + + // MARK: - Claude: session id to pid + + static func file(pid: pid_t, id: String, startedAt: Date) -> ClaudeSessionFile { + ClaudeSessionFile(pid: pid, sessionId: id, startedAt: startedAt.timeIntervalSince1970 * 1000) + } + + @Test("the session file naming this id gives up its pid") + func matchesSessionFile() { + let started = Date(timeIntervalSince1970: 1_780_000_000) + let files = [ + Self.file(pid: 111, id: "other", startedAt: started), + Self.file(pid: 222, id: "wanted", startedAt: started), + ] + let pid = SessionFocus.pid(forSessionID: "wanted", files: files) { _ in started.addingTimeInterval(2) } + #expect(pid == 222) + } + + @Test("a pid the kernel no longer knows is not a session") + func rejectsDeadPID() { + let files = [Self.file(pid: 222, id: "wanted", startedAt: Date(timeIntervalSince1970: 1_780_000_000))] + #expect(SessionFocus.pid(forSessionID: "wanted", files: files) { _ in nil } == nil) + } + + @Test("a pid handed to an unrelated process since the file was written is not a session") + func rejectsRecycledPID() { + let started = Date(timeIntervalSince1970: 1_780_000_000) + let files = [Self.file(pid: 222, id: "wanted", startedAt: started)] + let recycled = started.addingTimeInterval(SessionFocus.pidReuseTolerance + 1) + #expect(SessionFocus.pid(forSessionID: "wanted", files: files) { _ in recycled } == nil) + } + + @Test("a session no file claims is not found") + func rejectsUnknownSession() { + let files = [Self.file(pid: 222, id: "wanted", startedAt: Date())] + #expect(SessionFocus.pid(forSessionID: "missing", files: files) { _ in Date() } == nil) + } + + // MARK: - Kimi: working directory to pid + + @Test("the one kimi working in this directory is the session's") + func matchesKimiByWorkingDirectory() { + let pid = SessionFocus.pid(forWorkingDirectory: "/Users/x/Projects/app", candidates: [ + (pid: 10, cwd: "/Users/x/Projects/other"), + (pid: 20, cwd: "/Users/x/Projects/app"), + ]) + #expect(pid == 20) + } + + @Test("two kimis in the same directory are an ambiguity, not a guess") + func refusesAmbiguousKimi() { + let pid = SessionFocus.pid(forWorkingDirectory: "/Users/x/Projects/app", candidates: [ + (pid: 10, cwd: "/Users/x/Projects/app"), + (pid: 20, cwd: "/Users/x/Projects/app"), + ]) + #expect(pid == nil) + } + + @Test("no kimi in that directory is not found") + func refusesMissingKimi() { + let pid = SessionFocus.pid(forWorkingDirectory: "/Users/x/Projects/app", candidates: [ + (pid: 10, cwd: "/Users/x/Projects/other"), + ]) + #expect(pid == nil) + } +}