From a14bdcca875ac3c5826759add347c0206f17f3cb Mon Sep 17 00:00:00 2001 From: Rafael Sordi <68669818+DerRafDev@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:31:19 -0400 Subject: [PATCH] feat(agents): add debug agent alerts and Terminal session navigation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Debug builds launched with TOKENBAR_AGENT_HOOKS=1 show Claude Code sessions waiting for an answer to a structured question (AskUserQuestion): an amber "Claude · N" in the menu bar and an Agents page in the popover. Answering, the next prompt, or the end of the session removes the entry; Esc sends no event, so Dismiss removes it. Claude Code command hooks post each payload with /usr/bin/curl to a listener bound to 127.0.0.1 and always exit 0, so Claude Code shows no error or delay while TokenBar is closed. Approvals are not counted: Claude Code sends no event when the user approves or denies. Go to Session brings the Terminal.app tab with the question to the front. The hook reports the Claude Code process and its TTY; TokenBar confirms both with the kernel and checks them again on click, so a closed tab whose TTY was reused never comes to the front. Other apps get Open . The Apple Events entitlement is Debug only. Not yet: listener authentication, installing hooks from the app, Codex, and exact targets outside Terminal.app. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 + apps/macos/Config/TokenBar-Debug.entitlements | 10 + apps/macos/Config/TokenBar.xcconfig | 5 + .../xcshareddata/xcschemes/TokenBar.xcscheme | 5 + apps/macos/TokenBar/AppDelegate.swift | 25 ++ apps/macos/TokenBar/InfoPlist.xcstrings | 8 + apps/macos/TokenBar/ProviderRegistry.swift | 28 +- apps/macos/TokenBar/TokenBarApp.swift | 4 +- .../TokenBarCore/Agents/AgentActivity.swift | 95 +++++++ .../Agents/AgentActivityStore.swift | 46 ++++ .../TokenBarCore/Agents/AgentNavigation.swift | 117 +++++++++ .../Claude/Hooks/ClaudeHookMapper.swift | 91 +++++++ .../Claude/Hooks/ClaudeHookSource.swift | 36 +++ .../Claude/Hooks/HookHTTPRequest.swift | 41 +++ .../Claude/Hooks/LocalHookServer.swift | 84 ++++++ .../MacAgentNavigationEnvironment.swift | 78 ++++++ .../Navigation/SystemProcess.swift | 34 +++ .../Sources/TokenBarUI/MenuBarLabel.swift | 48 +++- .../TokenBarUI/Popover/AgentsSection.swift | 216 ++++++++++++++++ .../Resources/pt-BR.lproj/Localizable.strings | 17 ++ .../Sources/TokenBarUI/UsagePopover.swift | 58 ++++- .../AgentActivityStoreTests.swift | 97 +++++++ .../AgentSessionNavigatorTests.swift | 127 +++++++++ .../TokenBarCoreTests/DemoModeTests.swift | 2 + .../ClaudeHookTests.swift | 243 ++++++++++++++++++ .../TokenBarUITests/AgentIndicatorTests.swift | 54 ++++ docs/agents.md | 119 +++++++++ docs/architecture.md | 37 ++- docs/roadmap.md | 4 + docs/testing-agent-alerts.md | 187 ++++++++++++++ 30 files changed, 1912 insertions(+), 14 deletions(-) create mode 100644 apps/macos/Config/TokenBar-Debug.entitlements create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivity.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivityStore.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentNavigation.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookMapper.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookSource.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/HookHTTPRequest.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/LocalHookServer.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/MacAgentNavigationEnvironment.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/SystemProcess.swift create mode 100644 apps/macos/TokenBarKit/Sources/TokenBarUI/Popover/AgentsSection.swift create mode 100644 apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentActivityStoreTests.swift create mode 100644 apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentSessionNavigatorTests.swift create mode 100644 apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeHookTests.swift create mode 100644 apps/macos/TokenBarKit/Tests/TokenBarUITests/AgentIndicatorTests.swift create mode 100644 docs/agents.md create mode 100644 docs/testing-agent-alerts.md diff --git a/README.md b/README.md index f3c8447..85b2541 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,16 @@ Every build runs the real providers. To work on the UI without accounts, launch build with `TOKENBAR_DEMO=1` (listed, unchecked, in the scheme's environment variables). Demo data is labeled "Demo" and does not exist in Release builds. +### Experimental: Claude Code question alerts + +Debug builds include a prototype that shows when a Claude Code session is waiting for your answer +to a question: `● Claude · 2` in the menu bar, an **Agents** page in the popover, and +**Go to Session** to bring the Terminal.app tab with the question to the front. It is off unless +you launch with `TOKENBAR_AGENT_HOOKS=1` (listed, unchecked, in the scheme) and set up Claude Code +hooks in a test folder by hand. It is not part of Release builds. To try it, follow +[docs/testing-agent-alerts.md](docs/testing-agent-alerts.md); design and limits are in +[docs/agents.md](docs/agents.md). + The repository also holds the TokenBar website in `apps/web`, a separate static site with its own [README](apps/web/README.md). The app never needs it to build. diff --git a/apps/macos/Config/TokenBar-Debug.entitlements b/apps/macos/Config/TokenBar-Debug.entitlements new file mode 100644 index 0000000..96f7cde --- /dev/null +++ b/apps/macos/Config/TokenBar-Debug.entitlements @@ -0,0 +1,10 @@ + + + + + + com.apple.security.automation.apple-events + + + diff --git a/apps/macos/Config/TokenBar.xcconfig b/apps/macos/Config/TokenBar.xcconfig index 6aaa6bb..293ea62 100644 --- a/apps/macos/Config/TokenBar.xcconfig +++ b/apps/macos/Config/TokenBar.xcconfig @@ -32,3 +32,8 @@ DEVELOPMENT_TEAM = ENABLE_USER_SCRIPT_SANDBOXING = YES DEAD_CODE_STRIPPING = YES COMBINE_HIDPI_IMAGES = YES + +// Debug only: the agent prototype ("Go to Session") selects a Terminal tab with an Apple Event. +// Release builds send no Apple Events and carry neither the entitlement nor the prompt text. +CODE_SIGN_ENTITLEMENTS[config=Debug] = Config/TokenBar-Debug.entitlements +INFOPLIST_KEY_NSAppleEventsUsageDescription[config=Debug] = TokenBar brings the Terminal tab with a waiting Claude Code question to the front. It never types into the session. diff --git a/apps/macos/TokenBar.xcodeproj/xcshareddata/xcschemes/TokenBar.xcscheme b/apps/macos/TokenBar.xcodeproj/xcshareddata/xcschemes/TokenBar.xcscheme index b71ef27..b8edea5 100644 --- a/apps/macos/TokenBar.xcodeproj/xcshareddata/xcschemes/TokenBar.xcscheme +++ b/apps/macos/TokenBar.xcodeproj/xcshareddata/xcschemes/TokenBar.xcscheme @@ -66,6 +66,11 @@ value = "1" isEnabled = "NO"> + + + /// Reports agent sessions waiting for the user. Debug-only prototype, `nil` unless requested. + var agentSource: (any AgentActivitySource)? + } + + /// Debug builds listen for Claude Code hooks when launched with `TOKENBAR_AGENT_HOOKS=1`. + /// Off in the shared scheme, absent from Release builds. See docs/agents.md. + static let agentHooksKey = "TOKENBAR_AGENT_HOOKS" + /// Optional port, so a second Debug build can listen next to one already running. + static let agentHooksPortKey = "TOKENBAR_AGENT_HOOKS_PORT" + + static func agentSource(environment: [String: String]) -> (any AgentActivitySource)? { + #if DEBUG + if environment[agentHooksKey] == "1" { + let port = environment[agentHooksPortKey].flatMap(UInt16.init) ?? ClaudeHookSource.defaultPort + return ClaudeHookSource(port: port) + } + #endif + return nil } static func make(environment: [String: String] = ProcessInfo.processInfo.environment) -> Configuration { @@ -22,11 +40,17 @@ enum ProviderRegistry { return Configuration( providers: providers, defaults: defaults, - initiallyEnabled: Set(providers.map(\.descriptor.id)) + initiallyEnabled: Set(providers.map(\.descriptor.id)), + agentSource: agentSource(environment: environment) ) } #endif // Every real provider starts disabled; the user enables it in Settings (see docs/roadmap.md). - return Configuration(providers: [ClaudeProvider(), CodexProvider()], defaults: .standard, initiallyEnabled: []) + return Configuration( + providers: [ClaudeProvider(), CodexProvider()], + defaults: .standard, + initiallyEnabled: [], + agentSource: agentSource(environment: environment) + ) } } diff --git a/apps/macos/TokenBar/TokenBarApp.swift b/apps/macos/TokenBar/TokenBarApp.swift index b98bb12..7192f0e 100644 --- a/apps/macos/TokenBar/TokenBarApp.swift +++ b/apps/macos/TokenBar/TokenBarApp.swift @@ -8,9 +8,9 @@ struct TokenBarApp: App { var body: some Scene { MenuBarExtra { - UsagePopover(store: appDelegate.store) + UsagePopover(store: appDelegate.store, agents: appDelegate.agents, navigator: appDelegate.navigator) } label: { - MenuBarLabel(store: appDelegate.store, settings: appDelegate.settings) + MenuBarLabel(store: appDelegate.store, settings: appDelegate.settings, agents: appDelegate.agents) } .menuBarExtraStyle(.window) diff --git a/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivity.swift b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivity.swift new file mode 100644 index 0000000..b67be39 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivity.swift @@ -0,0 +1,95 @@ +import Foundation + +/// Identifies one agent session, such as a Claude Code session. The same session ID from two +/// providers is two different sessions. +public struct AgentSessionKey: Hashable, Sendable { + public let provider: ProviderID + public let sessionID: String + + public init(provider: ProviderID, sessionID: String) { + self.provider = provider + self.sessionID = sessionID + } +} + +/// Why a session is waiting for the user. +public enum AgentWaitReason: Hashable, Sendable { + /// The agent asked a structured question (Claude Code's `AskUserQuestion`). + case answer +} + +/// A normalized change in a session's waiting state, translated from a provider's own signals. +public struct AgentEvent: Hashable, Sendable { + public enum Kind: Hashable, Sendable { + /// The session started waiting for the user. + case waiting(AgentWaitReason) + /// The session is no longer waiting: the user answered, or the session moved on. + case resolved + /// The session ended. + case ended + } + + public let key: AgentSessionKey + public let kind: Kind + /// Name of the tool the session runs in, such as "Claude Code". `nil` to use the provider's name. + public let agentName: String? + /// Folder name of the session's project, when known. Never a full path. + public let project: String? + /// Where the session is open. Read from "waiting" events. + public let origin: AgentOrigin? + public let date: Date + + public init( + key: AgentSessionKey, + kind: Kind, + agentName: String? = nil, + project: String?, + origin: AgentOrigin? = nil, + date: Date + ) { + self.key = key + self.kind = kind + self.agentName = agentName + self.project = project + self.origin = origin + self.date = date + } +} + +/// A session that is waiting for the user right now. +public struct PendingAgentSession: Identifiable, Hashable, Sendable { + public let key: AgentSessionKey + public let reason: AgentWaitReason + public let agentName: String? + public let project: String? + public let origin: AgentOrigin? + /// When the session started waiting. + public let since: Date + + public var id: AgentSessionKey { key } + + public init( + key: AgentSessionKey, + reason: AgentWaitReason, + agentName: String?, + project: String?, + origin: AgentOrigin? = nil, + since: Date + ) { + self.key = key + self.reason = reason + self.agentName = agentName + self.project = project + self.origin = origin + self.since = since + } +} + +/// A source of agent events, such as Claude Code hooks. +public protocol AgentActivitySource: Sendable { + var provider: ProviderID { get } + + /// Starts listening. Events arrive on the returned stream until ``stop()``. + func start() throws -> AsyncStream + func stop() +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivityStore.swift b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivityStore.swift new file mode 100644 index 0000000..a185ed5 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentActivityStore.swift @@ -0,0 +1,46 @@ +import Foundation +import Observation + +/// Sessions waiting for the user, one entry per session. +/// +/// Holds only what is waiting now. A resolved or ended session is removed, so a repeated or late +/// "resolved" event can never bring it back; only a new "waiting" event can. A repeated "waiting" +/// event keeps the original start time, so the counter never counts a session twice. +@MainActor +@Observable +public final class AgentActivityStore { + public private(set) var waiting: [AgentSessionKey: PendingAgentSession] = [:] + + public init() {} + + /// Sessions waiting for the user, longest-waiting first. + public var pending: [PendingAgentSession] { + waiting.values.sorted { ($0.since, $0.key.sessionID) < ($1.since, $1.key.sessionID) } + } + + /// Number of sessions that need the user, counted once per session. + public var pendingCount: Int { waiting.count } + + public func apply(_ event: AgentEvent) { + switch event.kind { + case .waiting(let reason): + guard waiting[event.key] == nil else { return } + waiting[event.key] = PendingAgentSession( + key: event.key, reason: reason, agentName: event.agentName, project: event.project, + origin: event.origin, + since: event.date) + case .resolved, .ended: + if waiting[event.key] != nil { waiting[event.key] = nil } + } + } + + /// Removes a session the user knows is no longer waiting, such as a question they dismissed + /// with Esc. A later question from the same session shows up again. + public func dismiss(_ key: AgentSessionKey) { + waiting[key] = nil + } + + public func removeAll(provider: ProviderID) { + waiting = waiting.filter { $0.key.provider != provider } + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentNavigation.swift b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentNavigation.swift new file mode 100644 index 0000000..767ce56 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarCore/Agents/AgentNavigation.swift @@ -0,0 +1,117 @@ +import Foundation + +/// Where an agent session is open: the app that runs it and, when it can be told apart from other +/// sessions, the exact place inside that app. +/// +/// Separate from ``AgentSessionKey``: the session ID names the conversation, the origin names the +/// window it lives in, which depends on the user's environment. +public struct AgentOrigin: Hashable, Sendable { + /// Bundle identifier of the app the session runs in, such as `com.apple.Terminal`. + public let appBundleID: String? + public let target: Target? + + public enum Target: Hashable, Sendable { + /// A terminal tab, found by its TTY. The TTY of a closed tab is soon reused by a new one, + /// so the agent process that owns it is part of the target and checked before every use. + case terminalTab(tty: String, process: AgentProcess) + } + + public init(appBundleID: String?, target: Target? = nil) { + self.appBundleID = appBundleID + self.target = target + } +} + +/// A process, identified by its ID and start time, so a reused process ID never matches. +public struct AgentProcess: Hashable, Sendable { + public let id: Int32 + public let startedAt: Date + + public init(id: Int32, startedAt: Date) { + self.id = id + self.startedAt = startedAt + } +} + +/// What the popover offers for a waiting session. +public enum AgentSessionAction: Hashable, Sendable { + /// Bring the exact window and tab with the question to the front. + case goToSession + /// Only the app is known: bring it to the front. + case openApp(name: String) +} + +public enum AgentNavigationResult: Hashable, Sendable { + case openedSession + case openedApp + /// The session's tab or process is gone. Nothing was brought to the front. + case sessionClosed + case failed +} + +/// The system calls navigation needs. Implemented with AppKit and Apple Events in the app, +/// and by a fake in tests. +@MainActor +public protocol AgentNavigationEnvironment { + /// Display name of an installed app, such as "Terminal". `nil` when it is not installed. + func appName(bundleID: String) -> String? + /// Whether the app can bring one of its own sessions to the front for this kind of target. + func supportsExactTarget(_ target: AgentOrigin.Target, bundleID: String) -> Bool + /// Whether the process is still running, is the same process (start time), and owns the TTY. + func isRunning(_ process: AgentProcess, tty: String) -> Bool + /// Selects the tab that owns `tty` and brings its window to the front. `false` when the app + /// has no such tab. + func showTerminalTab(tty: String, bundleID: String) -> Bool + func activateApp(bundleID: String) -> Bool +} + +/// Decides what a waiting session's button does, and does it. +/// +/// "Go to session" is offered only when the exact target is known and still alive, and is checked +/// again on click: a closed tab never leads to a different one that happens to reuse its TTY. +@MainActor +public final class AgentSessionNavigator { + private let environment: any AgentNavigationEnvironment + + public init(environment: any AgentNavigationEnvironment) { + self.environment = environment + } + + /// Name of the app the session runs in, for display. + public func appName(for origin: AgentOrigin?) -> String? { + origin?.appBundleID.flatMap(environment.appName(bundleID:)) + } + + public func action(for origin: AgentOrigin?) -> AgentSessionAction? { + guard let origin, let bundleID = origin.appBundleID, let name = environment.appName(bundleID: bundleID) + else { return nil } + if let target = origin.target, isAlive(target, bundleID: bundleID) { + return .goToSession + } + return .openApp(name: name) + } + + public func open(_ origin: AgentOrigin?) -> AgentNavigationResult { + guard let origin, let bundleID = origin.appBundleID, environment.appName(bundleID: bundleID) != nil + else { return .failed } + if let target = origin.target { + // Checked again: the session may have closed since the popover was drawn. + guard isAlive(target, bundleID: bundleID) else { return .sessionClosed } + switch target { + case .terminalTab(let tty, _): + if environment.showTerminalTab(tty: tty, bundleID: bundleID) { return .openedSession } + } + // The process lives but has no tab of its own (for example inside tmux): the app is + // the closest place that is certain. + } + return environment.activateApp(bundleID: bundleID) ? .openedApp : .failed + } + + private func isAlive(_ target: AgentOrigin.Target, bundleID: String) -> Bool { + guard environment.supportsExactTarget(target, bundleID: bundleID) else { return false } + switch target { + case .terminalTab(let tty, let process): + return environment.isRunning(process, tty: tty) + } + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookMapper.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookMapper.swift new file mode 100644 index 0000000..c8b617e --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookMapper.swift @@ -0,0 +1,91 @@ +import Foundation +import TokenBarCore + +/// Translates a Claude Code hook payload into an ``AgentEvent``. +/// +/// Only structured questions (`AskUserQuestion`) count as waiting. Approvals are left out: Claude +/// Code sends no event when the user approves (only when the command finishes) or denies, so +/// TokenBar cannot tell when the user has decided. See docs/agents.md. +/// +/// Reads only the event name, session ID, tool name, and the project folder name. Everything else +/// in the payload, including the question and the tool input, is never decoded. +public enum ClaudeHookMapper { + static let questionTool = "AskUserQuestion" + + struct Payload: Decodable { + let sessionID: String? + let hookEventName: String? + let toolName: String? + let cwd: String? + + enum CodingKeys: String, CodingKey { + case sessionID = "session_id" + case hookEventName = "hook_event_name" + case toolName = "tool_name" + case cwd + } + } + + /// - Parameters: + /// - headers: Request headers, lowercased. The hook adds where Claude Code runs (see + /// ``origin(from:process:)``). + /// - process: Looks up a running process, to confirm the hook's claim about its terminal. + public static func event( + from body: Data, + headers: [String: String] = [:], + date: Date, + process: (Int32) -> ProcessSnapshot? = { _ in nil } + ) -> AgentEvent? { + guard let payload = try? JSONDecoder().decode(Payload.self, from: body), + let sessionID = payload.sessionID, !sessionID.isEmpty, + let name = payload.hookEventName, + let kind = kind(event: name, tool: payload.toolName) + else { return nil } + let project = payload.cwd.map { URL(filePath: $0).lastPathComponent }.flatMap { $0.isEmpty ? nil : $0 } + return AgentEvent( + key: AgentSessionKey(provider: "claude", sessionID: sessionID), + kind: kind, + agentName: "Claude Code", + project: project, + origin: kind == .waiting(.answer) ? origin(from: headers, process: process) : nil, + date: date + ) + } + + /// Where the session runs, from headers the hook command fills in from its environment: + /// `x-origin-app` (`$__CFBundleIdentifier`), `x-origin-pid` (`$PPID`, the Claude Code process) + /// and `x-origin-tty` (that process's terminal). + /// + /// The terminal is trusted only when the process is running and the kernel reports the same + /// TTY; the process start time is kept so a reused process ID never matches later. Values that + /// do not look exactly like a bundle ID, a process ID, or a TTY name are dropped. + static func origin(from headers: [String: String], process: (Int32) -> ProcessSnapshot?) -> AgentOrigin? { + guard let app = headers["x-origin-app"], app.wholeMatch(of: /[A-Za-z0-9][A-Za-z0-9.\-]{0,154}/) != nil + else { return nil } + guard let tty = headers["x-origin-tty"], tty.wholeMatch(of: /ttys?[0-9]{1,4}/) != nil, + let pid = headers["x-origin-pid"].flatMap(Int32.init), pid > 1, + let snapshot = process(pid), snapshot.tty == tty + else { return AgentOrigin(appBundleID: app) } + return AgentOrigin( + appBundleID: app, + target: .terminalTab(tty: tty, process: AgentProcess(id: pid, startedAt: snapshot.startedAt)) + ) + } + + static func kind(event: String, tool: String?) -> AgentEvent.Kind? { + switch event { + case "PreToolUse": + tool == questionTool ? .waiting(.answer) : nil + case "PostToolUse", "PostToolUseFailure": + tool == questionTool ? .resolved : nil + // A new prompt or the end of a turn means the question is no longer open, including one + // dismissed with Esc (which sends no event of its own). + case "UserPromptSubmit", "Stop", "StopFailure": + .resolved + case "SessionEnd": + .ended + default: + nil + } + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookSource.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookSource.swift new file mode 100644 index 0000000..56ba20b --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/ClaudeHookSource.swift @@ -0,0 +1,36 @@ +import Foundation +import TokenBarCore + +/// Claude Code sessions waiting for an answer, reported by Claude Code hooks. +/// +/// The hooks run `/usr/bin/curl` to post each payload to this listener and always exit 0, so +/// Claude Code shows no error and no delay while TokenBar is closed. This prototype does not +/// install hooks: they are configured by hand in a test folder (see docs/agents.md). +public final class ClaudeHookSource: AgentActivitySource, @unchecked Sendable { + public static let defaultPort: UInt16 = 47811 + public static let path = "/hooks/claude" + + public let provider: ProviderID = "claude" + private let server: LocalHookServer + + public init(port: UInt16 = ClaudeHookSource.defaultPort) { + server = LocalHookServer(port: port, path: Self.path) + } + + public func start() throws -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream(of: AgentEvent.self) + try server.start { headers, body in + if let event = ClaudeHookMapper.event( + from: body, headers: headers, date: Date(), process: SystemProcess.snapshot(of:)) + { + continuation.yield(event) + } + } + continuation.onTermination = { [server] _ in server.stop() } + return stream + } + + public func stop() { + server.stop() + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/HookHTTPRequest.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/HookHTTPRequest.swift new file mode 100644 index 0000000..9a52a0f --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/HookHTTPRequest.swift @@ -0,0 +1,41 @@ +import Foundation + +/// The small part of HTTP/1.1 the hook listener needs: one `POST` with a `Content-Length` body. +enum HookHTTPRequest: Equatable { + /// More bytes are needed. + case incomplete + /// Not a request the listener accepts. The connection is closed. + case rejected + /// Header names are lowercased. + case post(path: String, headers: [String: String], body: Data) + + /// Largest accepted request, headers included. Hook payloads are a few kilobytes. + static let maxSize = 256 * 1024 + + static func parse(_ data: Data) -> HookHTTPRequest { + guard data.count <= maxSize else { return .rejected } + guard let headerEnd = data.firstRange(of: Data("\r\n\r\n".utf8)) else { + return .incomplete + } + guard let head = String(data: data[data.startIndex..= 0 else { return .rejected } + + let bodyStart = headerEnd.upperBound + let available = data.endIndex - bodyStart + if available < length { return .incomplete } + return .post( + path: String(requestLine[1]), headers: headers, body: Data(data[bodyStart..<(bodyStart + length)])) + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/LocalHookServer.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/LocalHookServer.swift new file mode 100644 index 0000000..dffb553 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/Hooks/LocalHookServer.swift @@ -0,0 +1,84 @@ +import Foundation +import Network +import OSLog +import TokenBarCore + +/// Receives hook payloads over HTTP on the loopback interface only. +/// +/// Always answers `200` with an empty body, so a hook never makes a decision for Claude Code. +/// Requests are handed to `onRequest` and never stored or logged. +final class LocalHookServer: @unchecked Sendable { + let port: UInt16 + let path: String + private let queue = DispatchQueue(label: "io.github.derrafdev.TokenBar.hooks") + private let logger = Logger(subsystem: Log.subsystem, category: "agents") + // Accessed on `queue` only. + private var listener: NWListener? + + init(port: UInt16, path: String) { + self.port = port + self.path = path + } + + func start(onRequest: @escaping @Sendable ([String: String], Data) -> Void) throws { + guard port != 0, let endpointPort = NWEndpoint.Port(rawValue: port) else { throw NWError.posix(.EINVAL) } + let parameters = NWParameters.tcp + parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: endpointPort) + parameters.allowLocalEndpointReuse = true + let listener = try NWListener(using: parameters) + listener.newConnectionHandler = { [weak self] connection in + self?.handle(connection, onRequest: onRequest) + } + listener.stateUpdateHandler = { [logger, port] state in + switch state { + case .ready: logger.notice("Listening for agent hooks on 127.0.0.1:\(port, privacy: .public)") + case .failed(let error): + logger.error("Hook listener failed: \(String(describing: error), privacy: .public)") + default: break + } + } + queue.sync { self.listener = listener } + listener.start(queue: queue) + } + + func stop() { + queue.sync { + listener?.cancel() + listener = nil + } + } + + private func handle(_ connection: NWConnection, onRequest: @escaping @Sendable ([String: String], Data) -> Void) { + connection.start(queue: queue) + receive(connection, buffer: Data(), onRequest: onRequest) + // A client that never finishes its request is dropped. + queue.asyncAfter(deadline: .now() + 5) { connection.cancel() } + } + + private func receive( + _ connection: NWConnection, buffer: Data, onRequest: @escaping @Sendable ([String: String], Data) -> Void + ) { + connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { + [weak self] data, _, isComplete, error in + guard let self else { return connection.cancel() } + var buffer = buffer + if let data { buffer.append(data) } + switch HookHTTPRequest.parse(buffer) { + case .incomplete where !isComplete && error == nil: + self.receive(connection, buffer: buffer, onRequest: onRequest) + case .post(let path, let headers, let body) where path == self.path: + onRequest(headers, body) + self.respond(connection, status: "200 OK") + case .post: + self.respond(connection, status: "404 Not Found") + default: + self.respond(connection, status: "400 Bad Request") + } + } + } + + private func respond(_ connection: NWConnection, status: String) { + let response = Data("HTTP/1.1 \(status)\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".utf8) + connection.send(content: response, completion: .contentProcessed { _ in connection.cancel() }) + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/MacAgentNavigationEnvironment.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/MacAgentNavigationEnvironment.swift new file mode 100644 index 0000000..a7a64ee --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/MacAgentNavigationEnvironment.swift @@ -0,0 +1,78 @@ +import AppKit +import OSLog +import TokenBarCore + +/// ``AgentNavigationEnvironment`` for macOS. +/// +/// Exact targets are supported in Terminal.app only, where AppleScript can select a tab by its +/// TTY. Other apps (iTerm2, VS Code, tmux) get "Open " until their own integration is +/// verified; see docs/agents.md. +/// +/// Selecting a tab sends one Apple Event to Terminal, so macOS asks the user once to allow +/// TokenBar to control Terminal. Nothing is typed into the session. +@MainActor +public struct MacAgentNavigationEnvironment: AgentNavigationEnvironment { + static let terminalBundleID = "com.apple.Terminal" + private let logger = Logger(subsystem: Log.subsystem, category: "agents") + + public init() {} + + public func appName(bundleID: String) -> String? { + guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else { return nil } + return FileManager.default.displayName(atPath: url.path).replacing(/\.app$/, with: "") + } + + public func supportsExactTarget(_ target: AgentOrigin.Target, bundleID: String) -> Bool { + switch target { + case .terminalTab: bundleID == Self.terminalBundleID + } + } + + public func isRunning(_ process: AgentProcess, tty: String) -> Bool { + guard let snapshot = SystemProcess.snapshot(of: process.id) else { return false } + // Start times come from the same kernel field, so they match exactly for the same process. + return abs(snapshot.startedAt.timeIntervalSince(process.startedAt)) < 0.001 && snapshot.tty == tty + } + + public func showTerminalTab(tty: String, bundleID: String) -> Bool { + // Never launches Terminal: a tab can only exist while it runs. + guard bundleID == Self.terminalBundleID, + !NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).isEmpty, + tty.wholeMatch(of: /ttys?[0-9]{1,4}/) != nil + else { return false } + let source = """ + tell application id "\(Self.terminalBundleID)" + repeat with w in windows + repeat with t in tabs of w + if tty of t is "/dev/\(tty)" then + -- Activate first: activation brings Terminal's last key window to the + -- front, which would cover the window chosen below. + activate + set index of w to 1 + set selected of t to true + return true + end if + end repeat + end repeat + return false + end tell + """ + var error: NSDictionary? + let result = NSAppleScript(source: source)?.executeAndReturnError(&error) + if let error { + let code = error[NSAppleScript.errorNumber] as? Int ?? 0 + logger.error("Could not select the Terminal tab (Apple Event error \(code, privacy: .public))") + return false + } + return result?.booleanValue ?? false + } + + public func activateApp(bundleID: String) -> Bool { + if let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first { + return running.activate() + } + guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else { return false } + NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration()) + return true + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/SystemProcess.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/SystemProcess.swift new file mode 100644 index 0000000..14bccb2 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Navigation/SystemProcess.swift @@ -0,0 +1,34 @@ +import Darwin +import Foundation + +/// What the kernel reports about a running process: when it started and its controlling terminal. +public struct ProcessSnapshot: Hashable, Sendable { + public let startedAt: Date + /// Device name of the controlling terminal, such as "ttys005". `nil` without one. + public let tty: String? + + public init(startedAt: Date, tty: String?) { + self.startedAt = startedAt + self.tty = tty + } +} + +/// Reads ``ProcessSnapshot``s with `sysctl`, without launching any tool. +public enum SystemProcess { + public static func snapshot(of id: Int32) -> ProcessSnapshot? { + guard id > 0 else { return nil } + var info = kinfo_proc() + var size = MemoryLayout.stride + var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, id] + guard sysctl(&mib, u_int(mib.count), &info, &size, nil, 0) == 0, size > 0, info.kp_proc.p_pid == id else { + return nil + } + let start = info.kp_proc.p_un.__p_starttime + let startedAt = Date( + timeIntervalSince1970: TimeInterval(start.tv_sec) + TimeInterval(start.tv_usec) / 1_000_000) + let device = info.kp_eproc.e_tdev + // NODEV (-1) means no controlling terminal. + let tty = device == -1 ? nil : devname(device, S_IFCHR).map { String(cString: $0) } + return ProcessSnapshot(startedAt: startedAt, tty: tty) + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/MenuBarLabel.swift b/apps/macos/TokenBarKit/Sources/TokenBarUI/MenuBarLabel.swift index d4f8108..6028095 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarUI/MenuBarLabel.swift +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/MenuBarLabel.swift @@ -14,11 +14,21 @@ import TokenBarCore public struct MenuBarLabel: View { let store: UsageStore let settings: AppSettings + let agents: AgentActivityStore? let formatter: UsageFormatter + /// Follows the menu bar's appearance, which the agent indicator needs because it is not a + /// template image. + @Environment(\.colorScheme) private var colorScheme - public init(store: UsageStore, settings: AppSettings, formatter: UsageFormatter = UsageFormatter()) { + public init( + store: UsageStore, + settings: AppSettings, + agents: AgentActivityStore? = nil, + formatter: UsageFormatter = UsageFormatter() + ) { self.store = store self.settings = settings + self.agents = agents self.formatter = formatter } @@ -27,7 +37,11 @@ public struct MenuBarLabel: View { public var body: some View { let snapshots = settings.showsUsageInMenuBar ? self.snapshots : [] - if let image = Self.image(for: snapshots, mode: settings.menuBarDisplay, formatter: formatter) { + // Sessions waiting for an answer take over the menu bar until none is left. + if let indicator = agentIndicator { + Image(nsImage: Self.renderIndicator(indicator.text, colorScheme: colorScheme)) + .accessibilityLabel(indicator.spoken) + } else if let image = Self.image(for: snapshots, mode: settings.menuBarDisplay, formatter: formatter) { Image(nsImage: image) .accessibilityLabel( snapshots.map { @@ -42,6 +56,13 @@ public struct MenuBarLabel: View { } } + private var agentIndicator: AgentIndicator.Label? { + guard let agents else { return nil } + let names = Dictionary( + store.descriptors.map { ($0.id, $0.displayName) }, uniquingKeysWith: { first, _ in first }) + return AgentIndicator.label(for: agents.pending, names: names, compact: settings.menuBarDisplay == .minimal) + } + /// Enabled providers shown in the menu bar that have data, in display order. private var snapshots: [(descriptor: ProviderDescriptor, snapshot: UsageSnapshot)] { store.enabledDescriptors.compactMap { descriptor in @@ -128,6 +149,29 @@ public struct MenuBarLabel: View { return image } + /// Amber, so a waiting question stands out from usage numbers in light and dark menu bars. + static let attentionColor = Color(red: 1.0, green: 0.72, blue: 0.0) + + /// "● Claude · 2" with an amber dot. Not a template image, since macOS would drop the color; + /// the text takes the menu bar's own text color instead. + static func renderIndicator(_ text: String, colorScheme: ColorScheme) -> NSImage { + let content = HStack(spacing: 5) { + Circle() + .fill(attentionColor) + .frame(width: 7, height: 7) + Text(verbatim: text) + .font(.system(size: 12, weight: .semibold)) + .monospacedDigit() + .foregroundStyle(colorScheme == .dark ? Color.white : Color.black.opacity(0.85)) + } + .padding(.vertical, 1) + let renderer = ImageRenderer(content: content) + renderer.scale = NSScreen.main?.backingScaleFactor ?? 2 + let image = renderer.nsImage ?? NSImage() + image.isTemplate = false + return image + } + /// Quiet while usage is normal, heavier as a limit gets close. private static func weight(for level: UsageLevel) -> Font.Weight { switch level { diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/Popover/AgentsSection.swift b/apps/macos/TokenBarKit/Sources/TokenBarUI/Popover/AgentsSection.swift new file mode 100644 index 0000000..6fdad18 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/Popover/AgentsSection.swift @@ -0,0 +1,216 @@ +import SwiftUI +import TokenBarCore + +/// Which page the popover shows. +enum PopoverTab: String, Hashable { + case usage + case agents + + /// The page shown when the popover opens: Agents while a session waits for the user, so one + /// click goes from the menu bar alert to its details; Usage otherwise. + static func initial(pendingCount: Int) -> PopoverTab { + pendingCount > 0 ? .agents : .usage + } +} + +/// What the menu bar shows while agent sessions wait for an answer. +/// +/// Named ("Claude · 2") when every waiting session belongs to one provider, so the menu bar says +/// who is asking. Compact ("2") when several providers are waiting or the user chose the Minimal +/// display. The amber dot in front is drawn by ``MenuBarLabel``. +enum AgentIndicator { + struct Label: Equatable { + /// Text after the dot, such as "Claude · 2" or "2". + let text: String + /// What VoiceOver reads, such as "Claude: 2 questions waiting for an answer". + let spoken: String + } + + /// `nil` when nothing is waiting, so the menu bar shows usage. + static func label(for pending: [PendingAgentSession], names: [ProviderID: String], compact: Bool) -> Label? { + guard !pending.isEmpty else { return nil } + let count = pending.count + let providers = Set(pending.map(\.key.provider)) + let name = providers.count == 1 ? providers.first.flatMap { names[$0] } : nil + let questions = + count == 1 + ? String(localized: "1 question waiting for an answer", bundle: .module) + : String(localized: "\(count) questions waiting for an answer", bundle: .module) + guard let name, !compact else { + return Label(text: "\(count)", spoken: questions) + } + return Label(text: "\(name) · \(count)", spoken: "\(name): \(questions)") + } +} + +/// The Agents page: sessions waiting for the user, one row per session. +struct AgentsSection: View { + let store: AgentActivityStore + let navigator: AgentSessionNavigator? + let descriptors: [ProviderDescriptor] + let now: Date + let formatter: UsageFormatter + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text("Waiting for you", bundle: .module) + .font(.headline) + .padding(.horizontal, Spacing.small) + .padding(.top, Spacing.tight) + .padding(.bottom, Spacing.small) + .accessibilityAddTraits(.isHeader) + let pending = store.pending + if pending.isEmpty { + emptyState + } + ForEach(Array(pending.enumerated()), id: \.element.id) { index, session in + if index > 0 { + Divider().padding(.leading, PendingAgentRow.contentInset + Spacing.small) + } + PendingAgentRow( + session: session, + descriptor: descriptor(for: session.key.provider), + navigator: navigator, + now: now, + formatter: formatter, + onDismiss: { store.dismiss(session.key) } + ) + } + } + } + + private func descriptor(for id: ProviderID) -> ProviderDescriptor { + descriptors.first { $0.id == id } ?? ProviderDescriptor(id: id, displayName: id.rawValue) + } + + private var emptyState: some View { + Text("No agent is waiting for you.", bundle: .module) + .font(.callout) + .foregroundStyle(.secondary) + .padding(.horizontal, Spacing.small) + .padding(.vertical, Spacing.small) + } +} + +/// "Claude Code · TokenBar" over "Terminal · Waiting for an answer · 2m", with the session's +/// action and Dismiss on the trailing edge. +/// +/// The button says what TokenBar can actually do (``AgentSessionNavigator``): "Go to Session" when +/// the exact tab is known and alive, "Open " when only the app is, and nothing otherwise. +/// It never reopens the conversation or types into it; the user answers where the question is. +struct PendingAgentRow: View { + let session: PendingAgentSession + let descriptor: ProviderDescriptor + let navigator: AgentSessionNavigator? + let now: Date + let formatter: UsageFormatter + let onDismiss: () -> Void + + @State private var isHovered = false + /// Set when "Go to Session" found the session closed, until the popover is drawn again. + @State private var sessionClosed = false + + /// Leading inset that lines the text up with the title, past the icon. + static let contentInset = ProviderIcon.slotWidth + Spacing.small + + var body: some View { + // Actions sit under the text, so both lines keep the popover's full width. + HStack(alignment: .top, spacing: Spacing.small) { + ProviderIcon(descriptor: descriptor, size: 20) + .font(.title3) + VStack(alignment: .leading, spacing: 2) { + VStack(alignment: .leading, spacing: 2) { + title + Text(verbatim: detail) + .font(.callout) + .foregroundStyle(.secondary) + .monospacedDigit() + .lineLimit(1) + if sessionClosed { + Text("This session is no longer open.", bundle: .module) + .font(.callout) + .foregroundStyle(.orange) + } + } + .accessibilityElement(children: .combine) + HStack(spacing: Spacing.small) { + if let action = navigator?.action(for: session.origin) { + actionButton(action) + } + Button(String(localized: "Dismiss", bundle: .module), action: onDismiss) + .buttonStyle(.borderless) + .controlSize(.small) + .foregroundStyle(.secondary) + .help( + String( + localized: "Already answered or cancelled? Remove it from the list.", bundle: .module)) + } + .padding(.top, Spacing.tight) + } + Spacer(minLength: 0) + } + .padding(.horizontal, Spacing.small) + .padding(.vertical, Spacing.small + 2) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(.primary.opacity(isHovered ? 0.035 : 0)) + ) + .onHover { isHovered = $0 } + } + + @ViewBuilder + private func actionButton(_ action: AgentSessionAction) -> some View { + switch action { + case .goToSession: + Button(String(localized: "Go to Session", bundle: .module), action: open) + .buttonStyle(.borderedProminent) + .controlSize(.small) + .help(String(localized: "Shows the window and tab where the question is open.", bundle: .module)) + case .openApp(let name): + Button(String(localized: "Open \(name)", bundle: .module), action: open) + .buttonStyle(.bordered) + .controlSize(.small) + .help(String(localized: "TokenBar can't find the exact window, so it opens the app.", bundle: .module)) + } + } + + private func open() { + guard let navigator else { return } + sessionClosed = navigator.open(session.origin) == .sessionClosed + } + + /// "Terminal · Waiting for an answer · now". The app is left out when it is unknown. + private var detail: String { + let parts = [navigator?.appName(for: session.origin), Self.reason(session.reason), elapsed] + return parts.compactMap(\.self).joined(separator: " · ") + } + + /// The agent's name stays whole; a long project name is shortened in the middle, so both its + /// start and end stay recognizable. + private var title: some View { + HStack(spacing: 0) { + Text(verbatim: session.agentName ?? descriptor.displayName) + .layoutPriority(1) + if let project = session.project { + Text(verbatim: " · ") + .layoutPriority(1) + Text(verbatim: project) + .truncationMode(.middle) + } + } + .font(.body.weight(.semibold)) + .lineLimit(1) + } + + /// "now" in the first minute, then "2m", "1h 5m". + private var elapsed: String { + let interval = now.timeIntervalSince(session.since) + return interval < 60 ? String(localized: "now", bundle: .module) : formatter.countdown(interval) + } + + static func reason(_ reason: AgentWaitReason) -> String { + switch reason { + case .answer: String(localized: "Waiting for an answer", bundle: .module) + } + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings index 4636ab3..04f88d8 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings @@ -1,8 +1,13 @@ /* Portuguese (Brazil). Keys are the English source strings used in code. */ "%@ used" = "%@ usado"; +"%lld questions waiting for an answer" = "%lld perguntas aguardando resposta"; +"1 question waiting for an answer" = "1 pergunta aguardando resposta"; "Access was not allowed. Refresh to be asked again." = "Acesso não permitido. Atualize para ser perguntado de novo."; +"Agents (%lld)" = "Agentes (%lld)"; +"Agents" = "Agentes"; "Allow TokenBar in Login Items to open it at login." = "Permita o TokenBar em Itens de Início para abri-lo ao iniciar sessão."; +"Already answered or cancelled? Remove it from the list." = "Já respondeu ou cancelou? Remova da lista."; "Cancel" = "Cancelar"; "Checking…" = "Verificando…"; "Configure Providers…" = "Configurar provedores…"; @@ -10,6 +15,7 @@ "Current session" = "Sessão atual"; "Demo" = "Demo"; "Detailed" = "Detalhado"; +"Dismiss" = "Dispensar"; "Display" = "Exibição"; "Each provider's current session. Switches to Minimal when there are too many providers to fit." = "A sessão atual de cada provedor. Muda para Mínimo quando há provedores demais para caber."; "Enable %@" = "Ativar %@"; @@ -18,22 +24,27 @@ "Enabled" = "Ativado"; "Experimental" = "Experimental"; "General" = "Geral"; +"Go to Session" = "Ir para a sessão"; "Hides details" = "Oculta os detalhes"; "Loading…" = "Carregando…"; "Menu Bar" = "Barra de menus"; "Minimal" = "Mínimo"; "Month" = "Mês"; "Monthly" = "Uso mensal"; +"No agent is waiting for you." = "Nenhum agente está esperando por você."; "No providers are available in this version yet." = "Ainda não há provedores disponíveis nesta versão."; "No providers enabled" = "Nenhum provedor ativado"; "No usage limits reported." = "Nenhum limite de uso informado."; "Not connected" = "Não conectado"; "Not connected. See Settings › Providers for what's needed." = "Não conectado. Veja em Ajustes › Provedores o que é necessário."; "Not updated yet" = "Ainda não atualizado"; +"now" = "agora"; "Off" = "Desativado"; "Only the provider whose current session is most used." = "Apenas o provedor com a sessão atual mais usada."; +"Open %@" = "Abrir %@"; "Open at login" = "Abrir ao iniciar sessão"; "Open Login Items…" = "Abrir Itens de Início…"; +"Page" = "Página"; "Providers" = "Provedores"; "Quit TokenBar" = "Encerrar TokenBar"; "Refresh every" = "Atualizar a cada"; @@ -48,12 +59,15 @@ "Show in menu bar" = "Mostrar na barra de menus"; "Show usage in menu bar" = "Mostrar uso na barra de menus"; "Shows details" = "Mostra os detalhes"; +"Shows the window and tab where the question is open." = "Mostra a janela e a aba onde a pergunta está aberta."; "Sign-in expired. Sign in again to resume updates." = "Login expirado. Entre novamente para retomar as atualizações."; "Something went wrong." = "Algo deu errado."; "The service returned an error (%lld)." = "O serviço retornou um erro (%lld)."; "The service took too long to respond." = "O serviço demorou demais para responder."; "The two main limits of each provider, such as 15/12 for session and week." = "Os dois limites principais de cada provedor, como 15/12 para sessão e semana."; +"This session is no longer open." = "Esta sessão não está mais aberta."; "Today" = "Hoje"; +"TokenBar can't find the exact window, so it opens the app." = "O TokenBar não encontra a janela exata, então abre o app."; "Too many requests. Trying again at %@." = "Muitas solicitações. Nova tentativa às %@."; "Too many requests. Will retry later." = "Muitas solicitações. Tentaremos novamente mais tarde."; "Turn on a provider to see its usage limits here." = "Ative um provedor para ver os limites de uso aqui."; @@ -61,6 +75,9 @@ "Updated %@ ago" = "Atualizado há %@"; "Updated just now" = "Atualizado agora"; "Updating…" = "Atualizando…"; +"Usage" = "Uso"; +"Waiting for an answer" = "Aguardando resposta"; +"Waiting for you" = "Esperando por você"; "Week" = "Semana"; "Weekly" = "Uso semanal"; "When off, the menu bar shows only the TokenBar icon." = "Quando desativado, a barra de menus mostra apenas o ícone do TokenBar."; diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift b/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift index 386a12f..c7fd2cb 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift @@ -5,9 +5,12 @@ import TokenBarCore /// provider at a time can be expanded to show its details. public struct UsagePopover: View { let store: UsageStore + let agents: AgentActivityStore? + let navigator: AgentSessionNavigator? let formatter: UsageFormatter @State private var isVisible = false + @State private var tab = PopoverTab.usage /// The provider the user expanded, or `nil` when they collapsed it. Only read once /// ``hasChosenExpansion`` is true; until then a lone provider starts expanded. @State private var expandedID: ProviderID? @@ -15,9 +18,17 @@ public struct UsagePopover: View { @Environment(\.openSettings) private var openSettings @Environment(\.accessibilityReduceMotion) private var reduceMotion - public init(store: UsageStore, formatter: UsageFormatter = UsageFormatter()) { + public init( + store: UsageStore, + agents: AgentActivityStore? = nil, + navigator: AgentSessionNavigator? = nil, + formatter: UsageFormatter = UsageFormatter() + ) { self.store = store + self.agents = agents + self.navigator = navigator self.formatter = formatter + _tab = State(initialValue: PopoverTab.initial(pendingCount: agents?.pendingCount ?? 0)) } public var body: some View { @@ -40,6 +51,7 @@ public struct UsagePopover: View { WindowVisibilityObserver { visible in isVisible = visible if visible { + tab = PopoverTab.initial(pendingCount: agents?.pendingCount ?? 0) Task { await store.refreshAll(.popoverOpened) } } } @@ -47,6 +59,28 @@ public struct UsagePopover: View { } private func content(now: Date) -> some View { + VStack(alignment: .leading, spacing: 0) { + if let agents { + tabPicker(waiting: agents.pendingCount) + .padding(.horizontal, Spacing.small) + .padding(.bottom, Spacing.small) + } + if let agents, tab == .agents { + AgentsSection( + store: agents, navigator: navigator, descriptors: store.descriptors, now: now, formatter: formatter) + } else { + usage(now: now) + } + Divider() + .padding(.horizontal, Spacing.small) + .padding(.top, Spacing.small) + .padding(.bottom, Spacing.small) + footer(now: now) + .padding(.horizontal, Spacing.small) + } + } + + private func usage(now: Date) -> some View { VStack(alignment: .leading, spacing: 0) { if store.enabledDescriptors.isEmpty { emptyState @@ -64,15 +98,25 @@ public struct UsagePopover: View { ) } } - Divider() - .padding(.horizontal, Spacing.small) - .padding(.top, Spacing.small) - .padding(.bottom, Spacing.small) - footer(now: now) - .padding(.horizontal, Spacing.small) } } + private func tabPicker(waiting: Int) -> some View { + Picker(String(localized: "Page", bundle: .module), selection: $tab) { + Text("Usage", bundle: .module).tag(PopoverTab.usage) + Group { + if waiting > 0 { + Text("Agents (\(waiting))", bundle: .module) + } else { + Text("Agents", bundle: .module) + } + } + .tag(PopoverTab.agents) + } + .pickerStyle(.segmented) + .labelsHidden() + } + private var expanded: ProviderID? { if hasChosenExpansion { return expandedID } let descriptors = store.enabledDescriptors diff --git a/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentActivityStoreTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentActivityStoreTests.swift new file mode 100644 index 0000000..e2b63de --- /dev/null +++ b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentActivityStoreTests.swift @@ -0,0 +1,97 @@ +import Foundation +import Testing + +@testable import TokenBarCore + +@MainActor +struct AgentActivityStoreTests { + let start = Date(timeIntervalSince1970: 1_000_000) + let session = AgentSessionKey(provider: "claude", sessionID: "session-1") + + private func event(_ kind: AgentEvent.Kind, _ key: AgentSessionKey? = nil, after seconds: TimeInterval = 0) + -> AgentEvent + { + AgentEvent(key: key ?? session, kind: kind, project: "tokenbar", date: start.addingTimeInterval(seconds)) + } + + @Test func questionMakesSessionPending() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + #expect(store.pendingCount == 1) + #expect(store.pending.first?.project == "tokenbar") + #expect(store.pending.first?.reason == .answer) + } + + @Test func repeatedQuestionCountsOnceAndKeepsStartTime() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.apply(event(.waiting(.answer), after: 30)) + #expect(store.pendingCount == 1) + #expect(store.pending.first?.since == start) + } + + @Test func resolvedQuestionDoesNotComeBackOnRepeatedResolve() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.apply(event(.resolved, after: 5)) + store.apply(event(.resolved, after: 6)) + #expect(store.pendingCount == 0) + } + + @Test func newQuestionAfterResolveIsPendingAgain() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.apply(event(.resolved, after: 5)) + store.apply(event(.waiting(.answer), after: 60)) + #expect(store.pending.first?.since == start.addingTimeInterval(60)) + } + + @Test func endedSessionIsRemoved() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.apply(event(.ended, after: 1)) + #expect(store.pendingCount == 0) + } + + @Test func sameSessionIDFromTwoProvidersCountsTwice() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.apply(event(.waiting(.answer), AgentSessionKey(provider: "codex", sessionID: "session-1"))) + #expect(store.pendingCount == 2) + } + + @Test func resolvingOneSessionKeepsTheOther() { + let store = AgentActivityStore() + let other = AgentSessionKey(provider: "claude", sessionID: "session-2") + store.apply(event(.waiting(.answer))) + store.apply(event(.waiting(.answer), other, after: 10)) + store.apply(event(.resolved, after: 20)) + #expect(store.pending.map(\.key) == [other]) + } + + @Test func pendingIsLongestWaitingFirst() { + let store = AgentActivityStore() + let other = AgentSessionKey(provider: "claude", sessionID: "session-2") + store.apply(event(.waiting(.answer), other, after: 10)) + store.apply(event(.waiting(.answer))) + #expect(store.pending.map(\.key) == [session, other]) + } + + @Test func dismissRemovesUntilNextQuestion() { + let store = AgentActivityStore() + store.apply(event(.waiting(.answer))) + store.dismiss(session) + #expect(store.pendingCount == 0) + store.apply(event(.waiting(.answer), after: 30)) + #expect(store.pendingCount == 1) + } + + @Test func removeAllForProviderKeepsOthers() { + let store = AgentActivityStore() + let codex = AgentSessionKey(provider: "codex", sessionID: "x") + store.apply(event(.waiting(.answer))) + store.apply(event(.waiting(.answer), codex)) + store.removeAll(provider: "claude") + #expect(store.pending.map(\.key) == [codex]) + } +} diff --git a/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentSessionNavigatorTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentSessionNavigatorTests.swift new file mode 100644 index 0000000..ee0471f --- /dev/null +++ b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/AgentSessionNavigatorTests.swift @@ -0,0 +1,127 @@ +import Foundation +import Testing + +@testable import TokenBarCore + +/// Simulates the system: installed apps, running processes, and Terminal tabs. +@MainActor +final class FakeNavigationEnvironment: AgentNavigationEnvironment { + var apps = ["com.apple.Terminal": "Terminal", "com.microsoft.VSCode": "Visual Studio Code"] + var exactTargetApps: Set = ["com.apple.Terminal"] + /// Running processes and the TTY each owns. + var processes: [AgentProcess: String] = [:] + /// TTYs of open Terminal tabs. + var tabs: Set = [] + private(set) var shownTabs: [String] = [] + private(set) var activatedApps: [String] = [] + + func appName(bundleID: String) -> String? { apps[bundleID] } + + func supportsExactTarget(_ target: AgentOrigin.Target, bundleID: String) -> Bool { + exactTargetApps.contains(bundleID) + } + + func isRunning(_ process: AgentProcess, tty: String) -> Bool { processes[process] == tty } + + func showTerminalTab(tty: String, bundleID: String) -> Bool { + guard tabs.contains(tty) else { return false } + shownTabs.append(tty) + return true + } + + func activateApp(bundleID: String) -> Bool { + activatedApps.append(bundleID) + return true + } +} + +@MainActor +struct AgentSessionNavigatorTests { + let environment = FakeNavigationEnvironment() + let processA = AgentProcess(id: 100, startedAt: Date(timeIntervalSince1970: 1_000)) + let processB = AgentProcess(id: 200, startedAt: Date(timeIntervalSince1970: 2_000)) + + private func terminal(_ tty: String, _ process: AgentProcess) -> AgentOrigin { + AgentOrigin(appBundleID: "com.apple.Terminal", target: .terminalTab(tty: tty, process: process)) + } + + private var navigator: AgentSessionNavigator { AgentSessionNavigator(environment: environment) } + + @Test func liveTerminalTabOffersGoToSession() { + environment.processes = [processA: "ttys005"] + environment.tabs = ["ttys005"] + #expect(navigator.action(for: terminal("ttys005", processA)) == .goToSession) + #expect(navigator.appName(for: terminal("ttys005", processA)) == "Terminal") + } + + @Test func goToSessionShowsTheRightTabAmongTwoInTheSameFolder() { + environment.processes = [processA: "ttys005", processB: "ttys007"] + environment.tabs = ["ttys005", "ttys007"] + let navigator = navigator + #expect(navigator.open(terminal("ttys007", processB)) == .openedSession) + #expect(navigator.open(terminal("ttys005", processA)) == .openedSession) + #expect(environment.shownTabs == ["ttys007", "ttys005"]) + #expect(environment.activatedApps.isEmpty) + } + + @Test func appOnlyOriginOffersOpenApp() { + let origin = AgentOrigin(appBundleID: "com.microsoft.VSCode") + #expect(navigator.action(for: origin) == .openApp(name: "Visual Studio Code")) + #expect(navigator.open(origin) == .openedApp) + #expect(environment.activatedApps == ["com.microsoft.VSCode"]) + } + + @Test func unknownOrUninstalledAppOffersNothing() { + #expect(navigator.action(for: nil) == nil) + #expect(navigator.action(for: AgentOrigin(appBundleID: nil)) == nil) + #expect(navigator.action(for: AgentOrigin(appBundleID: "com.example.Missing")) == nil) + #expect(navigator.open(AgentOrigin(appBundleID: "com.example.Missing")) == .failed) + } + + @Test func exactTargetInAnAppWithoutSupportOffersOpenApp() { + environment.processes = [processA: "ttys005"] + let origin = AgentOrigin( + appBundleID: "com.microsoft.VSCode", target: .terminalTab(tty: "ttys005", process: processA)) + #expect(navigator.action(for: origin) == .openApp(name: "Visual Studio Code")) + } + + /// A closed session falls back to its app in the label, and a click never lands on a tab that + /// reuses its TTY. + @Test func closedSessionIsNotOpenedEvenIfItsTTYWasReused() { + environment.tabs = ["ttys005"] + environment.processes = [processB: "ttys005"] // A new tab reused the TTY. + let origin = terminal("ttys005", processA) + #expect(navigator.action(for: origin) == .openApp(name: "Terminal")) + #expect(navigator.open(origin) == .sessionClosed) + #expect(environment.shownTabs.isEmpty) + #expect(environment.activatedApps.isEmpty) + } + + @Test func sessionClosedBetweenDrawingAndClickIsCaught() { + environment.processes = [processA: "ttys005"] + environment.tabs = ["ttys005"] + let origin = terminal("ttys005", processA) + let navigator = navigator + #expect(navigator.action(for: origin) == .goToSession) + environment.processes = [:] + environment.tabs = [] + #expect(navigator.open(origin) == .sessionClosed) + #expect(environment.shownTabs.isEmpty) + } + + /// Inside tmux the process lives but owns no Terminal tab: the app is the closest certain place. + @Test func liveProcessWithoutTabOpensTheApp() { + environment.processes = [processA: "ttys009"] + environment.tabs = ["ttys005"] + #expect(navigator.open(terminal("ttys009", processA)) == .openedApp) + #expect(environment.activatedApps == ["com.apple.Terminal"]) + } + + @Test func storeKeepsTheOriginOfTheWaitingEvent() { + let store = AgentActivityStore() + let key = AgentSessionKey(provider: "claude", sessionID: "s") + let origin = terminal("ttys005", processA) + store.apply(AgentEvent(key: key, kind: .waiting(.answer), project: "p", origin: origin, date: .now)) + #expect(store.pending.first?.origin == origin) + } +} diff --git a/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/DemoModeTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/DemoModeTests.swift index 3e1e659..9f57577 100644 --- a/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/DemoModeTests.swift +++ b/apps/macos/TokenBarKit/Tests/TokenBarCoreTests/DemoModeTests.swift @@ -26,6 +26,8 @@ struct DemoModeTests { let launchArguments = try xml.nodes(forXPath: "//LaunchAction//CommandLineArgument[@isEnabled='YES']/@argument") #expect(!launchVariables.contains { $0.stringValue == DemoMode.environmentKey }) + // The agent hooks prototype opens a local port, so it must be opted into as well. + #expect(!launchVariables.contains { $0.stringValue == "TOKENBAR_AGENT_HOOKS" }) #expect(!launchArguments.contains { $0.stringValue?.contains("Mock") == true }) } } diff --git a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeHookTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeHookTests.swift new file mode 100644 index 0000000..06bcabd --- /dev/null +++ b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeHookTests.swift @@ -0,0 +1,243 @@ +import Foundation +import Testing +import TokenBarCore + +@testable import TokenBarProviders + +struct ClaudeHookMapperTests { + let date = Date(timeIntervalSince1970: 1_000_000) + + /// A sanitized payload with the fields Claude Code sends; only some are read. + private func payload(_ event: String, tool: String? = nil, session: String = "session-1") -> Data { + var json: [String: Any] = [ + "session_id": session, + "hook_event_name": event, + "cwd": "/Users/someone/projects/tokenbar", + "transcript_path": "/Users/someone/.claude/projects/x/session-1.jsonl", + "permission_mode": "default", + ] + if let tool { + json["tool_name"] = tool + json["tool_input"] = ["questions": [["question": "Which color?", "options": [["label": "Red"]]]]] + json["tool_use_id"] = "call-1" + } + return try! JSONSerialization.data(withJSONObject: json) + } + + private func kind(_ event: String, tool: String? = nil) -> AgentEvent.Kind? { + ClaudeHookMapper.event(from: payload(event, tool: tool), date: date)?.kind + } + + @Test func questionWaitsForAnAnswer() throws { + let event = try #require( + ClaudeHookMapper.event(from: payload("PreToolUse", tool: "AskUserQuestion"), date: date)) + #expect(event.kind == .waiting(.answer)) + #expect(event.key == AgentSessionKey(provider: "claude", sessionID: "session-1")) + #expect(event.project == "tokenbar") + #expect(event.agentName == "Claude Code") + #expect(event.date == date) + } + + private let started = Date(timeIntervalSince1970: 5_000) + private let originHeaders = [ + "x-origin-app": "com.apple.Terminal", "x-origin-pid": "4242", "x-origin-tty": "ttys005", + ] + + @Test func questionKeepsTerminalTabWhenTheProcessOwnsIt() throws { + let event = try #require( + ClaudeHookMapper.event( + from: payload("PreToolUse", tool: "AskUserQuestion"), headers: originHeaders, date: date, + process: { $0 == 4242 ? ProcessSnapshot(startedAt: started, tty: "ttys005") : nil })) + #expect( + event.origin + == AgentOrigin( + appBundleID: "com.apple.Terminal", + target: .terminalTab(tty: "ttys005", process: AgentProcess(id: 4242, startedAt: started)))) + } + + @Test func terminalClaimNotConfirmedByTheKernelKeepsOnlyTheApp() { + let otherTTY: (Int32) -> ProcessSnapshot? = { _ in ProcessSnapshot(startedAt: started, tty: "ttys009") } + let gone: (Int32) -> ProcessSnapshot? = { _ in nil } + for process in [otherTTY, gone] { + let event = ClaudeHookMapper.event( + from: payload("PreToolUse", tool: "AskUserQuestion"), headers: originHeaders, date: date, + process: process) + #expect(event?.origin == AgentOrigin(appBundleID: "com.apple.Terminal")) + } + } + + /// Header values end up in an AppleScript and a process lookup, so anything unexpected is dropped. + @Test func malformedOriginHeadersAreDropped() { + let process: (Int32) -> ProcessSnapshot? = { _ in ProcessSnapshot(startedAt: started, tty: "ttys005") } + let bad: [[String: String]] = [ + ["x-origin-app": "com.apple.Terminal\" end tell", "x-origin-pid": "4242", "x-origin-tty": "ttys005"], + ["x-origin-app": ""], + [:], + ] + for headers in bad { + let event = ClaudeHookMapper.event( + from: payload("PreToolUse", tool: "AskUserQuestion"), headers: headers, date: date, process: process) + #expect(event?.origin == nil) + } + let badTTY = ClaudeHookMapper.event( + from: payload("PreToolUse", tool: "AskUserQuestion"), + headers: ["x-origin-app": "com.apple.Terminal", "x-origin-pid": "4242", "x-origin-tty": "ttys005\" & x"], + date: date, process: process) + #expect(badTTY?.origin == AgentOrigin(appBundleID: "com.apple.Terminal")) + } + + @Test func onlyWaitingEventsCarryAnOrigin() { + let event = ClaudeHookMapper.event( + from: payload("PostToolUse", tool: "AskUserQuestion"), headers: originHeaders, date: date) + #expect(event?.origin == nil) + } + + @Test func answerResolvesTheQuestion() { + #expect(kind("PostToolUse", tool: "AskUserQuestion") == .resolved) + #expect(kind("PostToolUseFailure", tool: "AskUserQuestion") == .resolved) + } + + /// Approvals are left out: Claude Code reports no event when the user approves or denies. + @Test func otherToolsAndApprovalsAreIgnored() { + #expect(kind("PreToolUse", tool: "Bash") == nil) + #expect(kind("PostToolUse", tool: "Bash") == nil) + #expect(kind("PermissionRequest", tool: "Bash") == nil) + #expect(kind("PermissionRequest", tool: "AskUserQuestion") == nil) + #expect(kind("Notification") == nil) + #expect(kind("SubagentStop") == nil) + #expect(kind("SessionStart") == nil) + } + + @Test func newPromptOrEndOfTurnResolves() { + #expect(kind("UserPromptSubmit") == .resolved) + #expect(kind("Stop") == .resolved) + #expect(kind("StopFailure") == .resolved) + } + + @Test func sessionEndEnds() { + #expect(kind("SessionEnd") == .ended) + } + + @Test func invalidPayloadsAreIgnored() { + #expect(ClaudeHookMapper.event(from: Data("not json".utf8), date: date) == nil) + #expect(ClaudeHookMapper.event(from: Data(#"{"hook_event_name":"Stop"}"#.utf8), date: date) == nil) + #expect( + ClaudeHookMapper.event(from: Data(#"{"hook_event_name":"Stop","session_id":""}"#.utf8), date: date) == nil) + } + + /// Sequences captured from Claude Code 2.1.319 (docs/agents.md), replayed through the store. + @MainActor + @Test(arguments: [ + // Question answered. + (["UserPromptSubmit", "PreToolUse:AskUserQuestion", "PermissionRequest:AskUserQuestion"], 1), + ( + [ + "UserPromptSubmit", "PreToolUse:AskUserQuestion", "PermissionRequest:AskUserQuestion", + "Notification", "PostToolUse:AskUserQuestion", "Stop", + ], 0 + ), + // Question dismissed with Esc: nothing is sent until the next prompt. + ( + [ + "UserPromptSubmit", "PreToolUse:AskUserQuestion", "PermissionRequest:AskUserQuestion", + "Notification", + ], 1 + ), + ( + [ + "UserPromptSubmit", "PreToolUse:AskUserQuestion", "PermissionRequest:AskUserQuestion", + "Notification", "UserPromptSubmit", + ], 0 + ), + // A Bash approval never counts. + (["UserPromptSubmit", "PreToolUse:Bash", "PermissionRequest:Bash", "Notification"], 0), + // Session closed while asking. + (["PreToolUse:AskUserQuestion", "SessionEnd"], 0), + ]) + func capturedSequences(steps: [String], expected: Int) { + let store = AgentActivityStore() + for step in steps { + let parts = step.split(separator: ":").map(String.init) + if let event = ClaudeHookMapper.event( + from: payload(parts[0], tool: parts.count > 1 ? parts[1] : nil), date: date) + { + store.apply(event) + } + } + #expect(store.pendingCount == expected) + } +} + +struct HookHTTPRequestTests { + private func request(_ head: String, body: String = "") -> Data { + Data((head + "\r\n\r\n" + body).utf8) + } + + @Test func parsesPostWithBody() { + let data = request("POST /hooks/claude HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 2", body: "{}") + #expect( + HookHTTPRequest.parse(data) + == .post( + path: "/hooks/claude", headers: ["host": "127.0.0.1", "content-length": "2"], body: Data("{}".utf8)) + ) + } + + @Test func headerNamesAreCaseInsensitive() { + let data = request("POST /x HTTP/1.1\r\ncontent-length: 1", body: "a") + #expect( + HookHTTPRequest.parse(data) == .post(path: "/x", headers: ["content-length": "1"], body: Data("a".utf8))) + } + + @Test func waitsForTheWholeRequest() { + #expect(HookHTTPRequest.parse(Data("POST /x HTTP/1.1\r\nContent-Le".utf8)) == .incomplete) + #expect(HookHTTPRequest.parse(request("POST /x HTTP/1.1\r\nContent-Length: 10", body: "{}")) == .incomplete) + } + + @Test func rejectsOtherMethodsAndMissingLength() { + #expect(HookHTTPRequest.parse(request("GET /x HTTP/1.1")) == .rejected) + #expect(HookHTTPRequest.parse(request("POST /x HTTP/1.1")) == .rejected) + #expect(HookHTTPRequest.parse(request("garbage")) == .rejected) + } + + @Test func rejectsOversizedRequests() { + let body = String(repeating: "a", count: HookHTTPRequest.maxSize) + #expect( + HookHTTPRequest.parse(request("POST /x HTTP/1.1\r\nContent-Length: \(body.count)", body: body)) == .rejected + ) + } +} + +/// End to end over the loopback interface, as Claude Code's `curl` hook sends it. +struct ClaudeHookSourceTests { + @Test func deliversQuestionPostedOverHTTP() async throws { + let port = UInt16.random(in: 49_152...60_000) + let source = ClaudeHookSource(port: port) + let events = try source.start() + defer { source.stop() } + + let body = Data( + #"{"session_id":"session-1","hook_event_name":"PreToolUse","tool_name":"AskUserQuestion","cwd":"/tmp/demo"}"# + .utf8) + var request = URLRequest(url: URL(string: "http://127.0.0.1:\(port)\(ClaudeHookSource.path)")!) + request.httpMethod = "POST" + request.httpBody = body + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + + // The listener may need a moment to become ready. + var response: URLResponse? + for _ in 0..<20 { + if let (_, sent) = try? await URLSession.shared.data(for: request) { + response = sent + break + } + try await Task.sleep(for: .milliseconds(50)) + } + let http = try #require(response as? HTTPURLResponse) + #expect(http.statusCode == 200) + + var iterator = events.makeAsyncIterator() + let event = await iterator.next() + #expect(event?.kind == .waiting(.answer)) + #expect(event?.project == "demo") + } +} diff --git a/apps/macos/TokenBarKit/Tests/TokenBarUITests/AgentIndicatorTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarUITests/AgentIndicatorTests.swift new file mode 100644 index 0000000..940c0b2 --- /dev/null +++ b/apps/macos/TokenBarKit/Tests/TokenBarUITests/AgentIndicatorTests.swift @@ -0,0 +1,54 @@ +import Foundation +import Testing +import TokenBarCore + +@testable import TokenBarUI + +struct AgentIndicatorTests { + let names: [ProviderID: String] = ["claude": "Claude", "codex": "Codex"] + + private func pending(_ provider: ProviderID, _ id: String) -> PendingAgentSession { + PendingAgentSession( + key: AgentSessionKey(provider: provider, sessionID: id), + reason: .answer, + agentName: nil, + project: nil, + since: Date(timeIntervalSince1970: 0) + ) + } + + @Test func showsNothingWhileNothingWaits() { + #expect(AgentIndicator.label(for: [], names: names, compact: false) == nil) + } + + @Test func namesTheProviderWhenOnlyOneIsWaiting() { + let label = AgentIndicator.label( + for: [pending("claude", "a"), pending("claude", "b")], names: names, compact: false) + #expect(label?.text == "Claude · 2") + #expect(label?.spoken == "Claude: 2 questions waiting for an answer") + } + + @Test func singleQuestionIsSpokenInSingular() { + let label = AgentIndicator.label(for: [pending("claude", "a")], names: names, compact: false) + #expect(label?.text == "Claude · 1") + #expect(label?.spoken == "Claude: 1 question waiting for an answer") + } + + @Test func compactShowsOnlyTheCount() { + let label = AgentIndicator.label( + for: [pending("claude", "a"), pending("claude", "b")], names: names, compact: true) + #expect(label?.text == "2") + #expect(label?.spoken == "2 questions waiting for an answer") + } + + @Test func severalProvidersShowOnlyTheCount() { + let label = AgentIndicator.label( + for: [pending("claude", "a"), pending("codex", "b")], names: names, compact: false) + #expect(label?.text == "2") + } + + @Test func popoverOpensOnAgentsOnlyWhileSomethingWaits() { + #expect(PopoverTab.initial(pendingCount: 0) == .usage) + #expect(PopoverTab.initial(pendingCount: 1) == .agents) + } +} diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..7bff093 --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,119 @@ +# Agent alerts (experimental, Debug only) + +TokenBar can show when a Claude Code session is waiting for an answer from you. While one is, +the menu bar shows an amber dot and `Claude · N` instead of usage (`N` alone in Minimal mode or +when several providers wait), and the popover opens on **Agents › Waiting for you**, one row per +session ("Claude Code · project", "Terminal · Waiting for an answer · now"). When the last +question is answered, the menu bar returns to the usage mode you chose. + +**Status:** prototype. It exists only in Debug builds and only runs when the app is launched with +`TOKENBAR_AGENT_HOOKS=1`. Release builds contain no listener, no Apple Events entitlement, and +install no hooks. To try it, follow [testing-agent-alerts.md](testing-agent-alerts.md). + +## Validated and missing + +| | Status | +|---|---| +| Structured questions from Claude Code (`AskUserQuestion`) | **Validated** with real sessions (Claude Code 2.1.116 and 2.1.319) | +| Counter, one per session; `2 → 1 → usage` as questions are answered | **Validated** live in the menu bar | +| Question removed when the session ends (`/exit` or tab closed) | **Validated** | +| **Go to Session** in Terminal.app, including two sessions in the same folder and a closed session whose TTY was reused | **Validated** live | +| Hook transport with TokenBar closed: no errors, no noticeable delay in Claude Code | **Validated** | +| **Open ** for apps without an exact target (VS Code, iTerm2) | Implemented and unit tested; brings the app to the front only | +| Approvals (permission prompts) | **Not counted**: see below | +| iTerm2, VS Code terminal and extension, tmux panes, other terminals | Missing: app activation only, or nothing | +| Listener authentication (shared secret) | Missing: any local process can post a fake question | +| Installing hooks from TokenBar (Settings, consent, safe edit of `~/.claude/settings.json`) | Missing: hooks are configured by hand per folder | +| Codex | Missing: no verified signal for a question | + +## What counts as waiting + +Only **structured questions**, Claude Code's `AskUserQuestion` tool. One entry per session +(provider + session ID): repeated events never count twice, and a resolved question never comes +back unless a new one is asked. + +| Hook event | Effect | +|---|---| +| `PreToolUse` with `tool_name: AskUserQuestion` | The session waits for an answer | +| `PostToolUse` / `PostToolUseFailure` with `tool_name: AskUserQuestion` | Answered: removed (about 35 ms after the answer) | +| `UserPromptSubmit`, `Stop`, `StopFailure` | The session moved on: removed | +| `SessionEnd` | The session is gone: removed | +| **Dismiss** in the popover | Removed by hand | + +**Esc on a question.** Claude Code sends no event when a question is cancelled with Esc. The +entry stays until you send the next prompt in that session (`UserPromptSubmit`), the session +ends, or you click **Dismiss**. A dismissed question does not come back; a new question from the +same session shows up again. + +**Approvals are left out.** Captured with real sessions: `PermissionRequest` arrives before the +dialog, but approving sends nothing until the command **finishes** (20 s for `sleep 20`), and +denying or pressing Esc sends nothing at all until the next prompt. TokenBar cannot tell when you +have decided, so it would keep showing an approval that is no longer waiting. + +## Transport + +Claude Code `command` hooks pipe each payload to TokenBar with `/usr/bin/curl` over the loopback +interface and always exit 0: + +```text +/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0 +``` + +- `type: "http"` hooks were tried first and rejected: while TokenBar is closed, Claude Code prints + `hook error … ECONNREFUSED` on every prompt and tool call. The `curl` hook shows nothing. +- Cost: about 20–50 ms per event, the same with TokenBar open or closed. `--max-time 1` caps a + listener that accepts a connection but never answers. +- `PreToolUse` and `PostToolUse` hooks use `matcher: "AskUserQuestion"`, so other tool calls run + no hook at all. +- Events sent while TokenBar is closed are lost: a question asked before TokenBar starts does not + appear. + +The listener (`LocalHookServer`) binds to 127.0.0.1 only, accepts one small `POST` (256 KB at +most), and always answers `200` with an empty body, so a hook never makes a decision for Claude +Code. It reads `session_id`, `hook_event_name`, `tool_name`, the last component of `cwd`, and the +origin headers below. Nothing is stored or logged. + +## Going back to the session + +The session ID names the conversation. Where it is open (`AgentOrigin`) is separate and depends +on the environment. The hook that reports a question adds it as headers: + +```text +-H "X-Origin-App: $__CFBundleIdentifier" -H "X-Origin-PID: $PPID" -H "X-Origin-TTY: $(/bin/ps -o tty= -p $PPID)" +``` + +`$PPID` is the Claude Code process. When the question arrives, TokenBar asks the kernel for that +process's terminal and start time and trusts the tab only if the kernel reports the same TTY. +Values that do not look exactly like a bundle ID, a process ID, or a TTY name are dropped (the TTY +ends up in an AppleScript). + +| What is known | Button | Click | +|---|---|---| +| A Terminal.app tab whose Claude Code process is still running (same PID, start time, and TTY) | **Go to Session** | Selects that tab and brings its window to the front | +| Only the app (VS Code, iTerm2, or a session that ended) | **Open ** | Brings the app to the front | +| Nothing | — | Only **Dismiss** | + +- The target is checked again on click. A closed tab's TTY is reused by the next tab within + seconds (seen while testing), so a closed session shows "This session is no longer open." and + never brings another tab to the front. +- A process that runs without its own tab (inside tmux) opens the app instead. +- Selecting a tab sends one Apple Event to Terminal. macOS asks once to allow TokenBar to control + Terminal (System Settings › Privacy & Security › Automation). Debug builds carry the + `com.apple.security.automation.apple-events` entitlement for this; Release builds do not. +- TokenBar never reopens the conversation (`claude --resume`) and never types into the session. +- `$__CFBundleIdentifier` comes from the environment and can be inherited: a tmux server started + in one app and attached from another reports the first app. + +Adding an environment (iTerm2 via `ITERM_SESSION_ID`, VS Code, tmux) means a new +`AgentOrigin.Target` case and its support in `MacAgentNavigationEnvironment`. The popover and the +decision logic (`AgentSessionNavigator`) stay the same. + +## Code + +| Piece | Where | +|---|---| +| Sessions, events, store, origin, navigation decisions | `TokenBarCore/Agents` | +| Hook payload and origin parsing, loopback listener | `TokenBarProviders/Claude/Hooks` | +| Process lookup (`sysctl`), Terminal tab selection, app activation | `TokenBarProviders/Navigation` | +| Menu bar indicator, Agents page | `TokenBarUI/MenuBarLabel.swift`, `TokenBarUI/Popover/AgentsSection.swift` | +| Debug-only wiring (`TOKENBAR_AGENT_HOOKS`, `TOKENBAR_AGENT_HOOKS_PORT`) | `TokenBar/ProviderRegistry.swift`, `TokenBar/AppDelegate.swift` | diff --git a/docs/architecture.md b/docs/architecture.md index 1a3e9b4..1720976 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -178,6 +178,34 @@ scheme enables it, so ⌘R never silently runs on mock data. Demo mode keeps its separate defaults suite, so it never changes real preferences. Mock code is wrapped in `#if DEBUG` and absent from Release builds, and the popover labels demo data with a "Demo" badge. +## Agent alerts (Debug prototype) + +Debug builds launched with `TOKENBAR_AGENT_HOOKS=1` show Claude Code sessions waiting for an +answer to a structured question (`AskUserQuestion`). Details, validation status and limits: +[agents.md](agents.md); how to try it: [testing-agent-alerts.md](testing-agent-alerts.md). + +```text +Claude Code hook ──curl──▶ LocalHookServer (127.0.0.1) ──▶ ClaudeHookMapper ──▶ AgentActivityStore ──▶ MenuBarLabel / Agents page + (command, exit 0) TokenBarProviders origin check TokenBarCore TokenBarUI + │ + AgentSessionNavigator ◀── "Go to Session" / "Open " + + MacAgentNavigationEnvironment (sysctl, Apple Events to Terminal) +``` + +- **Transport:** Claude Code `command` hooks post each payload with `/usr/bin/curl` to a listener + bound to the loopback interface, and always exit 0, so Claude Code shows no error or delay while + TokenBar is closed. `http` hooks were rejected because they print an error on every event then. +- **State:** one entry per session (provider + session ID). A question is resolved by its + `PostToolUse`, the next prompt, the end of the turn, the end of the session, or **Dismiss** + (Esc on a question sends no event). +- **Conversation vs. place:** the session ID names the conversation; `AgentOrigin` names where it + is open (app, and for Terminal.app the tab's TTY plus the Claude Code process ID and start + time). Navigation decisions live in `AgentSessionNavigator` (Core, tested with a fake + environment); system calls live in `MacAgentNavigationEnvironment` (Providers). The UI only + shows the action the navigator offers. +- **Not yet:** listener authentication, installing hooks from the app, Codex, and exact targets + outside Terminal.app. + ## Security boundaries - Third-party credentials (Claude Code, Codex) are read from their owner's storage and never @@ -191,9 +219,16 @@ builds, and the popover labels demo data with a "Demo" badge. authenticated URLs, and response bodies are never logged. - No TokenBar backend. The app talks only to provider endpoints. *Usage data stays on your Mac.* +- The agent alerts prototype exists only in Debug builds and only when launched with + `TOKENBAR_AGENT_HOOKS=1`. Its listener binds to 127.0.0.1, accepts small `POST`s, answers `200` + with an empty body (so a hook never makes a decision for Claude Code), and stores and logs + nothing from the payload. It has no authentication yet: any local process can post a fake + question. Debug builds carry the Apple Events entitlement so **Go to Session** can select a + Terminal tab after the user allows it in System Settings › Privacy & Security › Automation; + Release builds do not. TokenBar never types into a session or reopens a conversation. ## Dependencies None. Foundation, SwiftUI, AppKit, Security, ServiceManagement, and OSLog cover -networking, JSON, Keychain, dates, and UI. Lint and formatting use `swift format`, +networking, JSON, Keychain, dates, and UI. The Debug-only agent listener uses Network. Lint and formatting use `swift format`, which ships with Xcode. diff --git a/docs/roadmap.md b/docs/roadmap.md index 47e7e38..7e08ef6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,6 +29,10 @@ Candidates, not commitments. Each needs evidence that it works reliably before i | **Automatic updates** | Would add the first network request not made for a provider. Needs a privacy-preserving design. | | **More providers** (Gemini, Cursor, Copilot, …) | Only with a reliable, documented-enough source. Start with a section in [providers.md](providers.md). | | **Menu bar customization** | Driven by dogfooding feedback. | +| **Agent alerts: Claude Code questions** | Debug-only prototype ([agents.md](agents.md)). Validated with real sessions: structured questions (`AskUserQuestion`) in the menu bar and popover, `2 → 1 → usage` as they are answered, and **Go to Session** in Terminal.app. Before a release: listener authentication, installing and removing hooks from Settings with consent, and a safe edit of `~/.claude/settings.json`. | +| **Agent alerts: more environments** | Exact targets for iTerm2, VS Code, and tmux (today: open the app, or nothing). Each needs a verified way to find and show the session. | +| **Agent alerts: Codex** | Needs a verified signal for when a Codex session asks the user something and when it is answered. | +| **Agent alerts: approvals** | Not counted: Claude Code sends no event when the user approves (only when the command finishes) or denies. Needs a reliable signal that the user has decided. | ## Not planned diff --git a/docs/testing-agent-alerts.md b/docs/testing-agent-alerts.md new file mode 100644 index 0000000..5760e66 --- /dev/null +++ b/docs/testing-agent-alerts.md @@ -0,0 +1,187 @@ +# Testing agent alerts (Debug) + +How to try the experimental Claude Code alerts on your own Mac: a question from Claude Code shows +`● Claude · 1` in the menu bar, the popover opens on **Agents**, **Go to Session** brings the +Terminal tab with the question to the front, and answering returns the menu bar to usage. +Background and limits: [agents.md](agents.md). + +Nothing here touches your global Claude Code settings. The hooks live in one test folder. + +## Requirements + +- macOS 14+, Xcode 26+, this repository. +- Claude Code signed in (`claude --version`). Tested with 2.1.116 and 2.1.319. +- Terminal.app for **Go to Session**. Other terminals and VS Code get **Open ** only. + +## 1. Turn the prototype on in Xcode + +1. Open `apps/macos/TokenBar.xcodeproj`. +2. **Product › Scheme › Edit Scheme… › Run › Arguments › Environment Variables**. +3. Check **`TOKENBAR_AGENT_HOOKS`** (value `1`). Optionally also check `TOKENBAR_DEMO` to see + demo usage numbers instead of enabling real providers. +4. Run with **⌘R** (Debug). TokenBar now listens on `127.0.0.1:47811`. + +Both flags are listed in the shared scheme, unchecked. Uncheck them again before committing: +`scripts/test.sh` fails while `TOKENBAR_AGENT_HOOKS` is checked in the shared scheme. + +To confirm the listener runs: + +```sh +lsof -nP -iTCP:47811 -sTCP:LISTEN # shows TokenBar +``` + +## 2. Create a test folder with the hooks + +The hooks go in `.claude/settings.local.json` of a test folder, so only Claude Code sessions +started there report to TokenBar. Paste this in a terminal: + +```sh +TEST_DIR="$HOME/tokenbar-agent-test" +mkdir -p "$TEST_DIR/.claude" +cat > "$TEST_DIR/.claude/settings.local.json" <<'EOF' +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "AskUserQuestion", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' -H \"X-Origin-App: $__CFBundleIdentifier\" -H \"X-Origin-PID: $PPID\" -H \"X-Origin-TTY: $(/bin/ps -o tty= -p $PPID)\" --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", + "timeout": 3 + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "AskUserQuestion", + "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] + } + ], + "PostToolUseFailure": [ + { + "matcher": "AskUserQuestion", + "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] + } + ], + "UserPromptSubmit": [ + { "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] } + ], + "Stop": [ + { "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] } + ], + "StopFailure": [ + { "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] } + ], + "SessionEnd": [ + { "hooks": [{ "type": "command", "command": "/usr/bin/curl -s -o /dev/null --connect-timeout 0.3 --max-time 1 -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:47811/hooks/claude; exit 0", "timeout": 3 }] } + ] + } +} +EOF +``` + +What the hooks do: + +- Each one posts the hook's JSON to TokenBar with `/usr/bin/curl` and always exits 0. With + TokenBar closed, Claude Code shows no error and no noticeable delay. +- `PreToolUse` and `PostToolUse` only run for `AskUserQuestion`; other tool calls run no hook. +- The question hook also sends where the session runs: the app (`$__CFBundleIdentifier`), the + Claude Code process (`$PPID`), and its terminal (`ps -o tty=`). TokenBar uses them for + **Go to Session**. + +## 3. Start Claude Code in Terminal.app + +In **Terminal.app**: + +```sh +cd "$HOME/tokenbar-agent-test" +claude +``` + +The first time, Claude Code asks whether you trust the folder. With command hooks present, +**"No, exit" is preselected**: choose **Yes, I trust this folder**. Hooks load when a session +starts, so restart any session opened before you created the file. + +## 4. Test the flow + +Ask for a structured question: + +```text +Use the AskUserQuestion tool to ask me which color I prefer, Red or Blue. +``` + +| Step | Expected | +|---|---| +| The question appears in Terminal | The menu bar shows an amber dot and **Claude · 1** | +| Click the menu bar | The popover opens on **Agents (1)** › **Waiting for you**: "Claude Code · tokenbar-agent-test", "Terminal · Waiting for an answer · now", **Go to Session** and **Dismiss** | +| Switch to another app, open the popover, click **Go to Session** | The first time, macOS asks: *"TokenBar" wants access to control "Terminal"*. Click **Allow**. Terminal comes to the front with the tab that holds the question | +| Answer the question in Terminal | The entry disappears and the menu bar returns to your usage display | + +### Two sessions + +1. In Terminal, open a second window (**⌘N**), `cd "$HOME/tokenbar-agent-test"`, run `claude`, + and ask the same question. Keep the first question open too. +2. The menu bar shows **Claude · 2**; the popover lists both sessions, longest-waiting first. +3. Click **Go to Session** on each row, switching to another app in between. Each click brings + its own window and tab to the front, even though both sessions are in the same folder. +4. Answer one question: **Claude · 1**. Answer the other: the menu bar returns to usage. + +### Cancel with Esc + +Press **Esc** on a question instead of answering. Claude Code sends no event for this, so the +entry **stays**. It goes away when you send the next prompt in that session, when the session +ends, or when you click **Dismiss**. + +### Closed session + +Ask a question, then close that Terminal window (confirm **Terminate**). Claude Code reports the +end of the session and the entry disappears. A target that went stale while still listed shows +"This session is no longer open." and brings no other tab to the front; this case is covered by +`AgentSessionNavigatorTests`. + +### Other checks + +- **Minimal display** (Settings › General › Display): the menu bar shows only the count, `● 2`. +- **Other apps:** a question asked from VS Code's terminal shows **Open Visual Studio Code**, + which brings the app to the front (not the exact terminal). +- **TokenBar closed:** quit TokenBar and keep using Claude Code in the test folder. No hook + errors appear. + +## Troubleshooting + +- **Nothing appears.** Check that `TOKENBAR_AGENT_HOOKS` is checked and the listener runs + (`lsof` above), that the session started in the test folder after you created the hooks, and + that the folder is trusted. Watch TokenBar's log: + + ```sh + log stream --predicate 'subsystem == "io.github.derrafdev.TokenBar" AND category == "agents"' + ``` + +- **Port 47811 is taken** (another TokenBar build is running). Add `TOKENBAR_AGENT_HOOKS_PORT` + with another port, such as `47813`, to the scheme's environment variables and point the hooks + at it: + + ```sh + sed -i '' 's/127.0.0.1:47811/127.0.0.1:47813/g' "$HOME/tokenbar-agent-test/.claude/settings.local.json" + ``` + +- **Go to Session does nothing.** You may have denied the Automation prompt. Turn **Terminal** + on for TokenBar in **System Settings › Privacy & Security › Automation**, or reset the answer + and click again: + + ```sh + tccutil reset AppleEvents io.github.derrafdev.TokenBar + ``` + + Debug builds are signed ad hoc, so macOS may ask again after a rebuild. + +## Clean up + +```sh +rm -r "$HOME/tokenbar-agent-test" +tccutil reset AppleEvents io.github.derrafdev.TokenBar +``` + +Uncheck `TOKENBAR_AGENT_HOOKS` in the scheme.