codeburn/mac/Sources/CodeBurnMenubar/Data/DataClient.swift
Resham Joshi ee5cf7c38f
Some checks are pending
CI / semgrep (push) Waiting to run
macOS Menubar CI / test (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / vscode (push) Waiting to run
Windows Menubar CI / check (ubuntu-latest) (push) Waiting to run
Windows Menubar CI / check (windows-latest) (push) Waiting to run
fix(menubar): find the desktop app's bundled CLI when no CLI is on PATH (#1871)
With only the desktop app installed from the Homebrew cask, the menu bar
failed to load Today with "nonZeroExit (code: 127, stderr: env: codeburn:
No such file or directory)". The menu bar looked for a codeburn in the
path recorded for it and in package-manager folders, then fell back to the
bare name. A desktop-only machine has nothing in those folders, so when the
record was missing or no longer ran, nothing was found and the error named
nothing.

The packaged desktop app now carries a plain launcher at
CodeBurn.app/Contents/Resources/cli/codeburn that runs its bundled CLI
through its own executable and finds its own bundle. The menu bar checks
it, in /Applications and ~/Applications, after the recorded path and the
package-manager folders. When none of them runs, Today says which paths
were tried. The CLI's menubar installer records the same launcher instead
of refusing the install when nothing named codeburn is on PATH.
2026-11-05 05:59:42 +01:00

423 lines
17 KiB
Swift

import Foundation
/// Upper bound on payload + stderr bytes read from the CLI. Real payloads top out near 500 KB
/// (365 days of history with dozens of models); anything larger is pathological and truncating
/// prevents unbounded memory growth. Hard timeout guards against a hung CLI keeping Process and
/// Pipe file descriptors pinned forever.
private let maxPayloadBytes = 20 * 1024 * 1024
private let maxStderrBytes = 256 * 1024
private let maxConcurrentSpawns = 6
/// Whether this app run has ever completed a payload fetch. Until it has, the
/// on-disk cache may be cold and a spawn gets the long floor; afterwards the
/// ordinary silence window applies. Mirrors the resident client's `warmed`.
actor SpawnWarmth {
private(set) var warm = false
func markWarm() { warm = true }
}
enum DataClientError: Error {
case spawn(String)
case nonZeroExit(code: Int32, stderr: String)
case decode(Error)
case timeout
case outputTooLarge
}
/// Wraps a `MenubarPayload` decode failure with a bounded snippet of what the CLI
/// actually wrote to stdout (plus stderr), so a malformed-output failure — for
/// example a stray Node banner landing on stdout ahead of the JSON (see #515) —
/// is self-diagnosing in logs and the UI instead of an opaque "not valid JSON".
struct CLIDecodeFailure: Error, CustomStringConvertible {
let underlying: Error
let stdoutByteCount: Int
let stdoutSnippet: String
let stderr: String
var description: String {
var parts = [
"decode failed: \(underlying)",
"stdout (\(stdoutByteCount) bytes): \(stdoutSnippet.isEmpty ? "<empty>" : stdoutSnippet)",
]
if !stderr.isEmpty { parts.append("stderr: \(stderr)") }
return parts.joined(separator: " | ")
}
}
/// Runs the CLI via argv (no shell interpretation). See `CodeburnCLI` for why we never route
/// commands through `/bin/zsh -c` anymore.
struct DataClient {
#if DEBUG
/// Test seam. The in-flight slot and the all-provider acceptance ordering
/// are only observable when two REAL fetches overlap, which needs a fetch
/// whose completion the test controls rather than a spawned CLI.
@MainActor
static var fetchHookForTesting: (@Sendable (ProviderFilter, Bool) async throws -> MenubarPayload)?
#endif
static func fetch(period: Period,
day: String? = nil,
days: Set<String> = [],
provider: ProviderFilter,
includeOptimize: Bool,
scope: MenubarScope = .local,
claudeConfigSourceId: String? = nil,
bypassResident: Bool = false,
qualityOfService: QualityOfService = .userInitiated) async throws -> MenubarPayload {
#if DEBUG
if let hook = await MainActor.run(body: { fetchHookForTesting }) {
return try await hook(provider, bypassResident)
}
#endif
let subcommand = statusSubcommand(
period: period,
day: day,
days: days,
provider: provider,
includeOptimize: includeOptimize,
scope: scope,
claudeConfigSourceId: claudeConfigSourceId
)
let result = try await runCLI(
subcommand: subcommand,
bypassResident: bypassResident,
qualityOfService: qualityOfService
)
guard result.exitCode == 0 else {
throw DataClientError.nonZeroExit(
code: result.exitCode,
stderr: CodeburnCLI.explainedFailure(code: result.exitCode, stderr: result.stderr)
)
}
do {
let payload = try JSONDecoder().decode(MenubarPayload.self, from: result.stdout)
await warmth.markWarm()
return payload
} catch {
let snippet = String(decoding: result.stdout.prefix(2048), as: UTF8.self)
throw DataClientError.decode(CLIDecodeFailure(
underlying: error,
stdoutByteCount: result.stdout.count,
stdoutSnippet: snippet,
stderr: result.stderr
))
}
}
static func statusSubcommand(period: Period,
day: String? = nil,
days: Set<String> = [],
provider: ProviderFilter,
includeOptimize: Bool,
scope: MenubarScope = .local,
claudeConfigSourceId: String? = nil) -> [String] {
let effectiveScope: MenubarScope = days.count > 1 ? .local : scope
let effectiveProvider: ProviderFilter = effectiveScope == .combined ? .all : provider
var subcommand = [
"status",
"--format", "menubar-json",
"--provider", effectiveProvider.cliArg,
]
if effectiveScope == .combined {
subcommand.append(contentsOf: ["--scope", effectiveScope.cliArg])
}
if effectiveScope == .local, let claudeConfigSourceId, !claudeConfigSourceId.isEmpty {
subcommand.append(contentsOf: ["--claude-config-source", claudeConfigSourceId])
}
if days.count > 1 {
subcommand.append(contentsOf: ["--days", days.sorted().joined(separator: ",")])
} else if let day {
subcommand.append(contentsOf: ["--day", day])
} else if let d = days.first {
subcommand.append(contentsOf: ["--day", d])
} else {
subcommand.append(contentsOf: ["--period", period.cliArg])
}
if !includeOptimize {
subcommand.append("--no-optimize")
}
return subcommand
}
struct ProcessResult {
let stdout: Data
let stderr: String
let exitCode: Int32
}
/// Caps concurrent CLI spawns so a wake-burst of refreshes can't fan out into
/// dozens of node processes at once.
private static let spawnLimiter = AsyncSemaphore(maxConcurrentSpawns)
/// Cold floor gate for the one-shot path. See `SpawnWarmth`.
static let warmth = SpawnWarmth()
private static func runCLI(
subcommand: [String],
bypassResident: Bool = false,
qualityOfService: QualityOfService = .userInitiated
) async throws -> ProcessResult {
try await runCLI(
subcommand: subcommand,
bypassResident: bypassResident,
serveRequest: { args in
try await ServeConnection.shared.request(args: args)
},
spawnFallback: {
await spawnLimiter.acquire()
defer { Task { await spawnLimiter.release() } }
let process = CodeburnCLI.makeProcess(
subcommand: subcommand,
qualityOfService: qualityOfService
)
// Heartbeats for the no-output watchdog: a multi-minute parse
// writes progress lines to stderr instead of going silent.
process.environment = CLIWatchdog.withProgressHeartbeat(process.environment)
let silenceSeconds = CLIWatchdog.silenceWindow(warm: await warmth.warm)
return try await runProcess(
process,
timeoutSeconds: silenceSeconds,
label: subcommand.joined(separator: " ")
)
}
)
}
/// Internal seam for behavior-shaped lifecycle tests. Production supplies
/// the shared resident and globally limited one-shot closures above.
static func runCLI(
subcommand: [String],
bypassResident: Bool = false,
serveRequest: ([String]) async throws -> Data,
spawnFallback: () async throws -> ProcessResult
) async throws -> ProcessResult {
// Serve path: the first real status payload warms the resident child,
// then later payloads reuse it (no node boot or session-cache reload).
// Transport/protocol failures fall back to the spawn path below, so
// the resident remains an optimization. Resource-policy failures stay
// terminal and cannot bypass the resident output ceiling.
if !bypassResident, ServeConnection.isEligible(subcommand) {
do {
let stdout = try await serveRequest(subcommand)
return ProcessResult(stdout: stdout, stderr: "", exitCode: 0)
} catch let error as CancellationError {
// Cancellation is control flow from the refresh owner. Starting
// a fallback process here would turn cancelled work into a new
// expensive cold parse and delay task teardown.
throw error
} catch {
if let terminalError = terminalServeError(error) {
throw terminalError
}
// Resident serve is only an optimization. Protocol, child, and
// timeout failures retain the established one-shot fallback,
// unless a sibling teardown raced this task's cancellation.
try Task.checkCancellation()
}
}
return try await spawnFallback()
}
/// Some resident failures are terminal resource-policy decisions, not
/// transport failures. Retrying those through the one-shot path would redo
/// the cold scan and could bypass the resident's stricter output ceiling.
static func terminalServeError(_ error: Error) -> DataClientError? {
guard let failure = error as? ServeConnection.ServeRequestFailed,
failure.reason == .outputTooLarge else { return nil }
return .outputTooLarge
}
/// Runs an already-configured process to completion, draining its output and
/// enforcing the no-output watchdog: `timeoutSeconds` bounds SILENCE, not
/// total runtime, and restarts on every byte the child produces. See
/// `CLIWatchdog` for why (and for the absolute ceiling that still bounds a
/// child which chatters forever).
///
/// CRITICAL: nothing here may block a worker thread waiting for the process.
/// `process.waitUntilExit()` is a blocking syscall. An earlier fix moved it
/// onto a global(qos:.utility) queue with the timeout on that SAME queue — but
/// under sustained load every utility worker ended up blocked in waitUntilExit,
/// so the timeout could never be scheduled to kill them and the menubar wedged
/// on "Loading…" forever (confirmed via sample: threads parked in
/// waitUntilExit, timeout never firing). Instead we await
/// `process.terminationHandler`, which fires on a Foundation-managed queue and
/// blocks nothing, so the timeout always has a free thread to fire on.
static func runProcess(_ process: Process,
timeoutSeconds: Double,
label: String) async throws -> ProcessResult {
let outPipe = Pipe()
let errPipe = Pipe()
process.standardOutput = outPipe
process.standardError = errPipe
// Bridge the process exit to an async signal set up BEFORE run(), so the
// exit can never be missed and the wait never blocks a worker thread.
let exitSignal = ProcessExitSignal()
process.terminationHandler = { _ in exitSignal.fulfill() }
do {
try process.run()
} catch {
throw DataClientError.spawn(error.localizedDescription)
}
// Silence watchdog, not a runtime cap: `activity` is touched by both
// drains, so the window restarts on every byte (progress keepalives
// included) and only a genuinely mute child is killed.
let activity = OutputActivity()
let startedAt = OutputActivity.now()
let timeoutTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility))
timeoutTimer.schedule(deadline: .now() + .seconds(1), repeating: .seconds(1))
timeoutTimer.setEventHandler {
guard process.isRunning else { return }
let verdict = CLIWatchdog.verdict(
now: OutputActivity.now(),
startedAt: startedAt,
lastOutputAt: activity.lastOutputAt,
silenceSeconds: timeoutSeconds
)
switch verdict {
case .wait:
return
case .silent:
NSLog("CodeBurn: CLI subprocess produced no output for %.0fs for %@ — terminating",
timeoutSeconds, label)
case .ceiling:
NSLog("CodeBurn: CLI subprocess exceeded %.0fs for %@ — terminating",
CLIWatchdog.ceilingSeconds, label)
}
// One verdict per process: the escalation owns the kill from here,
// and a repeating tick would re-send SIGTERM every second for the
// whole grace. Cancelling from inside the handler is supported.
timeoutTimer.cancel()
terminateWithEscalation(process)
}
timeoutTimer.resume()
defer { timeoutTimer.cancel() }
let outHandle = outPipe.fileHandleForReading
let errHandle = errPipe.fileHandleForReading
let (out, err) = await withTaskCancellationHandler {
async let stdoutData = drain(outHandle, limit: maxPayloadBytes, activity: activity)
async let stderrData = drain(errHandle, limit: maxStderrBytes, activity: activity)
return await (stdoutData, stderrData)
} onCancel: {
terminateWithEscalation(process)
}
try? outHandle.close()
try? errHandle.close()
// Wait for exit via terminationHandler, never by parking a worker thread
// in waitUntilExit (see the doc comment above for why that wedged).
await exitSignal.wait()
if out.count >= maxPayloadBytes {
throw DataClientError.outputTooLarge
}
let stderrString = CLIWatchdog.withoutProgressLines(String(data: err, encoding: .utf8) ?? "")
return ProcessResult(stdout: out, stderr: stderrString, exitCode: process.terminationStatus)
}
/// Ask a child to exit, then insist. The grace exists so the CLI's signal
/// cleanup can unlink the cache refresh lock it may be holding before it
/// dies; only a child that ignores SIGTERM is SIGKILLed.
private static func terminateWithEscalation(_ process: Process) {
guard process.isRunning else { return }
process.terminate()
let pid = process.processIdentifier
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + CLIWatchdog.killGraceSeconds) {
if process.isRunning { kill(pid, SIGKILL) }
}
}
private static func drain(_ handle: FileHandle, limit: Int, activity: OutputActivity) async -> Data {
let fd = handle.fileDescriptor
let flags = Darwin.fcntl(fd, F_GETFL)
if flags >= 0 {
_ = Darwin.fcntl(fd, F_SETFL, flags | O_NONBLOCK)
} else {
NSLog("CodeBurn: fcntl F_GETFL failed on fd %d, drain may block", fd)
}
var buffer = Data()
var chunk = [UInt8](repeating: 0, count: 65_536)
while buffer.count < limit && !Task.isCancelled {
let toRead = min(chunk.count, limit - buffer.count)
let n = chunk.withUnsafeMutableBufferPointer { ptr in
Darwin.read(fd, ptr.baseAddress!, toRead)
}
if n > 0 {
activity.touch()
buffer.append(contentsOf: chunk.prefix(n))
} else if n == 0 {
break
} else if errno == EAGAIN || errno == EWOULDBLOCK {
try? await Task.sleep(nanoseconds: 5_000_000)
} else if errno == EINTR {
continue
} else {
NSLog("CodeBurn: drain read() failed on fd %d: errno %d", fd, errno)
break
}
}
return buffer
}
}
/// One-shot async signal that bridges `Process.terminationHandler` (invoked on a
/// Foundation-internal queue) to an awaiting task without blocking a worker
/// thread. Safe against fulfill-before-wait.
final class ProcessExitSignal: @unchecked Sendable {
private let lock = NSLock()
private var fulfilled = false
private var continuation: CheckedContinuation<Void, Never>?
func fulfill() {
lock.lock()
if fulfilled { lock.unlock(); return }
fulfilled = true
let cont = continuation
continuation = nil
lock.unlock()
cont?.resume()
}
func wait() async {
await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
lock.lock()
if fulfilled {
lock.unlock()
cont.resume()
} else {
continuation = cont
lock.unlock()
}
}
}
}
/// Minimal actor-based async semaphore. Caps concurrency without blocking a
/// thread (unlike DispatchSemaphore.wait()).
actor AsyncSemaphore {
private var available: Int
private var waiters: [CheckedContinuation<Void, Never>] = []
init(_ count: Int) { available = count }
func acquire() async {
if available > 0 {
available -= 1
return
}
await withCheckedContinuation { waiters.append($0) }
}
func release() {
if waiters.isEmpty {
available += 1
} else {
waiters.removeFirst().resume()
}
}
}