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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
10 changes: 10 additions & 0 deletions apps/macos/Config/TokenBar-Debug.entitlements
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- Debug only: the agent prototype selects a Terminal tab with an Apple Event ("Go to Session").
The hardened runtime blocks Apple Events without this entitlement. -->
<key>com.apple.security.automation.apple-events</key>
<true/>
</dict>
</plist>
5 changes: 5 additions & 0 deletions apps/macos/Config/TokenBar.xcconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
<EnvironmentVariable
key = "TOKENBAR_AGENT_HOOKS"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
Expand Down
25 changes: 25 additions & 0 deletions apps/macos/TokenBar/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import AppKit
import OSLog
import TokenBarCore
import TokenBarProviders
import TokenBarUI

/// Owns long-lived objects and starts background refreshing at launch.
Expand All @@ -9,6 +10,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let settings: AppSettings
let store: UsageStore
let launchAtLogin = LaunchAtLogin()
/// Sessions waiting for the user. `nil` unless agent monitoring runs (Debug prototype).
let agents: AgentActivityStore?
/// Brings a waiting session's window to the front. `nil` with ``agents``.
let navigator: AgentSessionNavigator?
private let agentSource: (any AgentActivitySource)?
private let logger = Logger(subsystem: Log.subsystem, category: "app")

override init() {
let registry = ProviderRegistry.make()
Expand All @@ -18,18 +25,36 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
.notice("Registered providers: \(providers.joined(separator: ", "), privacy: .public)")
settings = AppSettings(defaults: registry.defaults, initiallyEnabled: registry.initiallyEnabled)
store = UsageStore(providers: registry.providers, enabledProviders: [])
agentSource = registry.agentSource
agents = registry.agentSource == nil ? nil : AgentActivityStore()
navigator =
registry.agentSource == nil ? nil : AgentSessionNavigator(environment: MacAgentNavigationEnvironment())
super.init()
store.follow(settings)
}

func applicationDidFinishLaunching(_ notification: Notification) {
store.startScheduledRefreshes()
startAgentSource()
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(systemDidWake), name: NSWorkspace.didWakeNotification, object: nil)
}

func applicationWillTerminate(_ notification: Notification) {
store.stopScheduledRefreshes()
agentSource?.stop()
}

private func startAgentSource() {
guard let agentSource, let agents else { return }
do {
let events = try agentSource.start()
Task {
for await event in events { agents.apply(event) }
}
} catch {
logger.error("Agent hooks could not start: \(String(describing: error), privacy: .public)")
}
}

/// The scheduled refresh due during sleep runs at wake, usually before the network is back, so
Expand Down
8 changes: 8 additions & 0 deletions apps/macos/TokenBar/InfoPlist.xcstrings
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
{
"sourceLanguage" : "en",
"strings" : {
"NSAppleEventsUsageDescription" : {
"comment" : "Debug builds only: shown when the agent prototype first asks to control Terminal (Go to Session).",
"extractionState" : "manual",
"localizations" : {
"en" : { "stringUnit" : { "state" : "translated", "value" : "TokenBar brings the Terminal tab with a waiting Claude Code question to the front. It never types into the session." } },
"pt-BR" : { "stringUnit" : { "state" : "translated", "value" : "O TokenBar traz para a frente a aba do Terminal com uma pergunta pendente do Claude Code. Ele nunca digita na sessão." } }
}
},
"NSHumanReadableCopyright" : {
"comment" : "Also declares the app's supported languages: macOS only uses a translation in TokenBarKit if the app bundle itself has that language.",
"extractionState" : "manual",
Expand Down
28 changes: 26 additions & 2 deletions apps/macos/TokenBar/ProviderRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ enum ProviderRegistry {
let defaults: UserDefaults
/// Enabled until the user changes the selection. Real providers always start disabled.
let initiallyEnabled: Set<ProviderID>
/// 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 {
Expand All @@ -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)
)
}
}
4 changes: 2 additions & 2 deletions apps/macos/TokenBar/TokenBarApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
@@ -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<AgentEvent>
func stop()
}
Original file line number Diff line number Diff line change
@@ -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 }
}
}
Loading
Loading