A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Claude plan usage in the notch: 5-hour and weekly limits (#159)
Louisad44a2f55014
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 48185b78..01f5d21a 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -27,6 +27,9 @@ jobs:- name: Test chat parsingrun: bash scripts/test-chat-parsing.sh+ - name: Test plan gauge+ run: bash scripts/test-plan-gauge.sh+- name: Buildrun: |xcodebuild \diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 866c65c0..94fd3635 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -19,6 +19,7 @@1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */; };160EDB9D06275E2607DA5151 /* N8nPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = B89DA1A0C21AE3535A1760BB /* N8nPoller.swift */; };186AB8904029767DAA5277CF /* IslandScreenGeometry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78BC1357785CA1B099A33969 /* IslandScreenGeometry.swift */; };+ 18D47AE663EB96BE5638D5F7 /* ClaudePlanCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */; };1969590AFEE6CB21404346F1 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };1F11EC4E6F604C612A1ADAD1 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E4F18AA940EFF7E047B9F7 /* AppState.swift */; };2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3232F258523DD8D09B670363 /* FileDropView.swift */; };@@ -53,6 +54,7 @@8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };8D1C01F283FA7806119A1C85 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */; };8FC5907E9506DC79EB1DDC3C /* ChatMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */; };+ 94E0849D13762C6EC8548FEF /* ClaudePlanCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */; };967B525F7D3837F31D740D18 /* ResendPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */; };9C653B8291EFFA414565E8A8 /* MusicController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F142FB3952B5F0639383047 /* MusicController.swift */; };9DD56C95ECABDDCE23652D50 /* HookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */; };@@ -69,12 +71,14 @@CD8DECA66B9E09C97E469DB9 /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };D58B1E93AF65DE404C40E21E /* PillCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B6A38B5686C4A1F15AB5D29 /* PillCatalog.swift */; };D82E93014C8087AE81511E40 /* IslandTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */; };+ D861479F6E7EAD07A6AC2105 /* ClaudePlanGauge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */; };DCAC390FF9EC65B945A15B24 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 506824380E9C80B9BC6DCE72 /* Assets.xcassets */; };DE05D09A32117582AC93A24A /* NotchBuddyApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */; };E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */; };E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3232F258523DD8D09B670363 /* FileDropView.swift */; };E7A5D23F455565FE1E210398 /* PillCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B6A38B5686C4A1F15AB5D29 /* PillCatalog.swift */; };E81575CE4433C6F88E424A8F /* LocalChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8790ACE9F73BD74640A0F20C /* LocalChat.swift */; };+ E9C21D11BCB72C392436D19E /* ClaudePlanGauge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */; };EB23ED9F1C12EA8B54A76A91 /* ResendPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */; };ECECA2F225E82B7C951658D7 /* UploadSequenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */; };F06EE0A97CB77096A337AA8B /* sounds in Resources */ = {isa = PBXBuildFile; fileRef = C066E2B991AA4F56B2724263 /* sounds */; };@@ -101,6 +105,7 @@79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HookServer.swift; sourceTree = "<group>"; };7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };8790ACE9F73BD74640A0F20C /* LocalChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalChat.swift; sourceTree = "<group>"; };+ 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanGauge.swift; sourceTree = "<group>"; };8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GithubPoller.swift; sourceTree = "<group>"; };8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandTypes.swift; sourceTree = "<group>"; };9F6D7015D6A77AA59323C0E7 /* AppLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLog.swift; sourceTree = "<group>"; };@@ -121,6 +126,7 @@D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandStateMachine.swift; sourceTree = "<group>"; };E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowContextCapture.swift; sourceTree = "<group>"; };F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchBuddyApp.swift; sourceTree = "<group>"; };+ F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanCardView.swift; sourceTree = "<group>"; };F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIdentity.swift; sourceTree = "<group>"; };FA02B08886939FF6FE0475DD /* IslandViewContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandViewContent.swift; sourceTree = "<group>"; };/* End PBXFileReference section */@@ -137,6 +143,8 @@3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */,D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */,BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */,+ F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */,+ 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */,A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,3232F258523DD8D09B670363 /* FileDropView.swift */,8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */,@@ -314,6 +322,8 @@4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */,8FC5907E9506DC79EB1DDC3C /* ChatMarkdown.swift in Sources */,4976F8BF814D6F817370F1D8 /* ChatMarkdownView.swift in Sources */,+ 94E0849D13762C6EC8548FEF /* ClaudePlanCardView.swift in Sources */,+ D861479F6E7EAD07A6AC2105 /* ClaudePlanGauge.swift in Sources */,2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,@@ -356,6 +366,8 @@1969590AFEE6CB21404346F1 /* CalcomPoller.swift in Sources */,B2D86BE268D6F4C86BD0C446 /* ChatMarkdown.swift in Sources */,733FCC6A45DE963EF2024B4E /* ChatMarkdownView.swift in Sources */,+ 18D47AE663EB96BE5638D5F7 /* ClaudePlanCardView.swift in Sources */,+ E9C21D11BCB72C392436D19E /* ClaudePlanGauge.swift in Sources */,0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */,C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */,diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swiftindex 82bc6946..751ee930 100644--- a/NotchBuddy/Sources/App/AppState.swift+++ b/NotchBuddy/Sources/App/AppState.swift@@ -293,6 +293,31 @@ final class AppState: ObservableObject {@Published var musicAutomationDenied: Bool = false#endif+ // Claude plan gauge (from statusline hook)+ @Published var claudePlanUsage: PlanUsage? = nil {+ didSet {+ if let u = claudePlanUsage,+ let data = try? JSONEncoder().encode(u) {+ UserDefaults.standard.set(data, forKey: "claudePlanUsage")+ }+ }+ }++ // Plan gauge: show pill in notch header — persisted+ #if !APPSTORE+ @Published var showPlanInNotch: Bool = false {+ didSet { UserDefaults.standard.set(showPlanInNotch, forKey: "showPlanInNotch") }+ }+ // Cached relay-installed state — updated at launch, after install/uninstall, on Settings open+ @Published var planRelayInstalled: Bool = false+ // Transient — reset when island closes or view changes+ @Published var showingPlanDetail: Bool = false++ func refreshPlanRelayState() {+ planRelayInstalled = HookServer.statusLineInstalled()+ }+ #endif+// MARK: - Init (loads persisted settings)private init() {@@ -328,6 +353,12 @@ final class AppState: ObservableObject {PillCatalog.available.contains(where: { $0.id == v && $0.category == .workspace && !$0.comingSoon }) {mainPillId = v}+ if let d = ud.data(forKey: "claudePlanUsage"),+ let u = try? JSONDecoder().decode(PlanUsage.self, from: d) { claudePlanUsage = u }+ #if !APPSTORE+ if let v = ud.object(forKey: "showPlanInNotch") as? Bool { showPlanInNotch = v }+ planRelayInstalled = HookServer.statusLineInstalled()+ #endif// Sync SoundEngine volume on launchSoundEngine.shared.volume = Float(soundVolume)diff --git a/NotchBuddy/Sources/App/BotCanvasView.swift b/NotchBuddy/Sources/App/BotCanvasView.swiftindex 050d47af..23b1edde 100644--- a/NotchBuddy/Sources/App/BotCanvasView.swift+++ b/NotchBuddy/Sources/App/BotCanvasView.swift@@ -28,9 +28,20 @@ struct BotCanvasView: View {}// Integration pills have a fixed brand color → use it as bodyColor.// Claude Code tasks use state-based gradient (working=blue, thinking=purple, etc.).+ #if !APPSTORE+ if state.showingPlanDetail {+ let hex = ClaudePlanGauge.color(for: state.claudePlanUsage.flatMap { ClaudePlanGauge.dominantPct($0) })+ engine.bodyColor = cgColorFromHex(hex)+ } else {+ engine.bodyColor = (state.focusTask?.isIntegration == true)+ ? cgColorFromHex(state.focusTask!.color)+ : nil+ }+ #elseengine.bodyColor = (state.focusTask?.isIntegration == true)? cgColorFromHex(state.focusTask!.color): nil+ #endif// Compute shouldDance per-frame (no observer lag)let dancing: Bool = {diff --git a/NotchBuddy/Sources/App/ClaudePlanCardView.swift b/NotchBuddy/Sources/App/ClaudePlanCardView.swiftnew file mode 100644index 00000000..e17bbce4--- /dev/null+++ b/NotchBuddy/Sources/App/ClaudePlanCardView.swift@@ -0,0 +1,128 @@+import SwiftUI++// MARK: - Claude Plan Card View++struct ClaudePlanCardView: View {+ let usage: PlanUsage? // nil = installed, no data yet++ @State private var now = Date()++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header+ HStack(spacing: 6) {+ let dominant = usage.flatMap { ClaudePlanGauge.dominantPct($0) }+ Circle()+ .fill(Color(hex: ClaudePlanGauge.color(for: dominant)))+ .frame(width: 7, height: 7)+ Text("Claude plan")+ .font(.system(size: 12, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ Text(subtitleText)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ .lineLimit(1)+ .fixedSize()+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 36)++ // Gauge rows+ VStack(alignment: .leading, spacing: 5) {+ GaugeRowView(label: "5 hours", window: usage?.fiveHour, now: now)+ GaugeRowView(label: "Week", window: usage?.sevenDay, now: now, weekly: true)+ }+ .padding(.top, 8)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ }+ .frame(maxWidth: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ // Update countdown every 30s, only while visible+ .background(+ TimelineView(.periodic(from: .now, by: 30)) { ctx in+ Color.clear.onChange(of: ctx.date) { _, d in now = d }+ }+ )+ }++ private var subtitleText: String {+ guard let usage else { return "Waiting for a Claude Code reply" }+ let diff = now.timeIntervalSince(usage.updatedAt)+ if diff < 60 { return "just now" }+ let mins = Int(diff / 60)+ if mins < 60 { return "\(mins) min ago" }+ return "\(mins / 60) h ago"+ }+}++// MARK: - Gauge Row++// DateFormatter created once, in English, for the weekly reset label+private let weeklyResetFormatter: DateFormatter = {+ let fmt = DateFormatter()+ fmt.locale = Locale(identifier: "en_US_POSIX")+ fmt.dateFormat = "EEE H:mm"+ return fmt+}()++private struct GaugeRowView: View {+ let label: String+ let window: PlanWindow?+ let now: Date+ var weekly: Bool = false++ var body: some View {+ HStack(spacing: 5) {+ Text(label)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#6B7079"))+ .frame(width: 40, alignment: .leading)+ if let w = window {+ let pct = ClaudePlanGauge.effectivePct(w)+ let accent = Color(hex: ClaudePlanGauge.color(for: pct))+ // Fixed-width bar (~50pt)+ ZStack(alignment: .leading) {+ Capsule()+ .fill(Color.white.opacity(0.08))+ .frame(width: 50, height: 4)+ Capsule()+ .fill(accent)+ .frame(width: max(0, 50 * CGFloat(pct / 100)), height: 4)+ }+ .frame(width: 50, height: 4)+ Text("\(Int(pct.rounded()))%")+ .font(.system(size: 11, weight: .semibold))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .monospacedDigit()+ .frame(width: 30, alignment: .trailing)+ Image(systemName: "arrow.clockwise")+ .font(.system(size: 8))+ .foregroundColor(Color(hex: "#6B7079"))+ Text(resetLabel(w))+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ .fixedSize()+ } else {+ Text("—")+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#6B7079"))+ Spacer()+ }+ }+ }++ private func resetLabel(_ w: PlanWindow) -> String {+ let secs = w.resetsAt.timeIntervalSince(now)+ guard secs > 0 else { return "Resetting…" }+ if weekly {+ return weeklyResetFormatter.string(from: w.resetsAt)+ } else {+ let h = Int(secs / 3600)+ let m = Int((secs.truncatingRemainder(dividingBy: 3600)) / 60)+ if h > 0 { return "in \(h) h \(m)" }+ return "in \(m) min"+ }+ }+}diff --git a/NotchBuddy/Sources/App/ClaudePlanGauge.swift b/NotchBuddy/Sources/App/ClaudePlanGauge.swiftnew file mode 100644index 00000000..e9258adc--- /dev/null+++ b/NotchBuddy/Sources/App/ClaudePlanGauge.swift@@ -0,0 +1,80 @@+import Foundation++// MARK: - Plan window++struct PlanWindow: Codable {+ let usedPct: Double // 0–100, clamped+ let resetsAt: Date+}++// MARK: - Plan usage++struct PlanUsage: Codable {+ var fiveHour: PlanWindow?+ var sevenDay: PlanWindow?+ var updatedAt: Date+}++// MARK: - Parsing + helpers (Foundation-only, no AppKit/SwiftUI)++enum ClaudePlanGauge {++ /// Parses rate_limits from a statusline payload dict. Returns nil if absent/malformed.+ static func parse(payload: [String: Any]) -> PlanUsage? {+ guard let limits = payload["rate_limits"] as? [String: Any] else { return nil }+ let fh = parseWindow(limits["five_hour"])+ let sd = parseWindow(limits["seven_day"])+ guard fh != nil || sd != nil else { return nil }+ return PlanUsage(fiveHour: fh, sevenDay: sd, updatedAt: Date())+ }++ private static func parseWindow(_ raw: Any?) -> PlanWindow? {+ guard let d = raw as? [String: Any] else { return nil }+ let rawPct: Double+ if let v = d["used_percentage"] as? Double { rawPct = v }+ else if let v = d["used_percentage"] as? Int { rawPct = Double(v) }+ else { return nil }+ guard rawPct >= 0, rawPct <= 200 else { return nil }+ let pct = min(100, rawPct) // clamp 100–200 down to 100+ let rawEpoch: Double+ if let v = d["resets_at"] as? Double { rawEpoch = v }+ else if let v = d["resets_at"] as? Int { rawEpoch = Double(v) }+ else { return nil }+ guard rawEpoch > 0 else { return nil }+ // Reject if more than 400 days in the future (likely milliseconds, not seconds)+ let maxEpoch = Date().timeIntervalSince1970 + 400 * 86400+ guard rawEpoch <= maxEpoch else { return nil }+ return PlanWindow(usedPct: pct, resetsAt: Date(timeIntervalSince1970: rawEpoch))+ }++ /// Effective % for display: 0 if the reset time is in the past.+ static func effectivePct(_ w: PlanWindow) -> Double {+ w.resetsAt <= Date() ? 0 : w.usedPct+ }++ /// The higher of the two effective percentages. nil if both windows absent.+ static func dominantPct(_ usage: PlanUsage) -> Double? {+ let p1 = usage.fiveHour.map { effectivePct($0) }+ let p2 = usage.sevenDay.map { effectivePct($0) }+ switch (p1, p2) {+ case (.none, .none): return nil+ case (let x?, .none): return x+ case (.none, let y?): return y+ case (let x?, let y?): return max(x, y)+ }+ }++ /// Hex color for a given percentage (nil → grey).+ static func color(for pct: Double?) -> String {+ guard let p = pct else { return "#6B7079" }+ if p < 50 { return "#22C55E" }+ if p < 80 { return "#F59E0B" }+ return "#F4505E"+ }++ /// Label shown in the island pill chip.+ static func pillLabel(_ usage: PlanUsage?) -> String {+ guard let usage, let pct = dominantPct(usage) else { return "Claude plan" }+ return "Claude \(Int(pct.rounded()))%"+ }+}diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swiftindex 06687662..7ba0d652 100644--- a/NotchBuddy/Sources/App/HookServer.swift+++ b/NotchBuddy/Sources/App/HookServer.swift@@ -187,6 +187,14 @@ final class HookServer: @unchecked Sendable {return}+ // statusline payloads are handled separately — no session, no reveal, no sound+ if let kind = payload["coucou_kind"] as? String, kind == "statusline" {+ Task { @MainActor in self.processStatusLine(payload: payload) }+ sendLine(fd: fd, text: #"{"ok":true}"#)+ close(fd)+ return+ }+let eventName = payload["hook_event_name"] as? String ?? ""if eventName == "PermissionRequest" {@@ -452,6 +460,15 @@ final class HookServer: @unchecked Sendable {// Already compact and non-alert: Mochi state update is enough, no expand}+ // MARK: - Status line (plan gauge)++ @MainActor+ private func processStatusLine(payload: [String: Any]) {+ if let usage = ClaudePlanGauge.parse(payload: payload) {+ AppState.shared.claudePlanUsage = usage+ }+ }+// MARK: - Permission request (blocking — Claude Code waits for decision)@MainActor@@ -915,6 +932,142 @@ final class HookServer: @unchecked Sendable {try newData.write(to: settingsURL, options: .atomic)}+ // MARK: - Claude plan status line installer++ private var statusLinePreviousURL: URL {+ Self.supportDir.appendingPathComponent("statusline-previous.json")+ }++ /// Returns true if our statusLine command is installed in ~/.claude/settings.json.+ static func statusLineInstalled() -> Bool {+ let url = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent(".claude/settings.json")+ guard let data = try? Data(contentsOf: url),+ let settings = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let sl = settings["statusLine"] as? [String: Any],+ let cmd = sl["command"] as? String else { return false }+ return cmd.contains("nb-hook")+ }++ private var _pendingStatusLineData: Data?+ private var _pendingPreviousData: Data?+ private var _pendingDeletePrevious: Bool = false++ /// Returns a diff string (only the statusLine key: before → after) without writing anything.+ func previewStatusLine(install: Bool) throws -> String {+ let settingsURL = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent(".claude/settings.json")+ var settings: [String: Any] = [:]+ if let d = try? Data(contentsOf: settingsURL),+ let parsed = (try? JSONSerialization.jsonObject(with: d)) as? [String: Any] {+ settings = parsed+ }+ let hookPath = Self.hookScriptPath+ let quotedPath = hookPath.replacingOccurrences(of: "\"", with: "\\\"")+ let quotedCmd = "\"\(quotedPath)\" --statusline"++ // Reset pending side-effects+ _pendingPreviousData = nil+ _pendingDeletePrevious = false++ let oldSL = settings["statusLine"] as? [String: Any]+ let newSL: [String: Any]?++ if install {+ // Check that Python 3 is available (requires Command Line Tools)+ let clCheck = Process()+ clCheck.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")+ clCheck.arguments = ["-p"]+ clCheck.standardOutput = FileHandle.nullDevice+ clCheck.standardError = FileHandle.nullDevice+ try? clCheck.run()+ clCheck.waitUntilExit()+ if clCheck.terminationStatus != 0 {+ throw NSError(domain: "Coucou", code: 1,+ userInfo: [NSLocalizedDescriptionKey:+ "Command Line Tools are required but not installed. Run: xcode-select --install"])+ }++ if let existing = oldSL,+ let cmd = existing["command"] as? String, !cmd.contains("nb-hook") {+ // Keep existing object but swap command; save old for later restoration+ var updated = existing+ updated["command"] = quotedCmd+ newSL = updated+ _pendingPreviousData = try? JSONSerialization.data(withJSONObject: existing,+ options: [.prettyPrinted, .sortedKeys])+ } else if let existing = oldSL,+ let cmd = existing["command"] as? String, cmd.contains("nb-hook") {+ // Already installed — rebuild to update path if needed, keep other fields+ var updated = existing+ updated["command"] = quotedCmd+ newSL = updated+ } else {+ newSL = ["type": "command", "command": quotedCmd]+ }+ } else {+ // Uninstall: only if it's ours+ if let cur = oldSL, let cmd = cur["command"] as? String, cmd.contains("nb-hook") {+ if let prevData = try? Data(contentsOf: statusLinePreviousURL),+ let prevObj = (try? JSONSerialization.jsonObject(with: prevData)) as? [String: Any] {+ newSL = prevObj+ _pendingDeletePrevious = true+ } else {+ newSL = nil+ }+ } else {+ newSL = oldSL // not ours — leave unchanged+ }+ }++ // Build the full settings.json with the new statusLine+ var newSettings = settings+ if let sl = newSL {+ newSettings["statusLine"] = sl+ } else {+ newSettings.removeValue(forKey: "statusLine")+ }+ let data = try JSONSerialization.data(withJSONObject: newSettings,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ _pendingStatusLineData = data++ // Build a compact diff: show only the statusLine key before → after+ func slJSON(_ val: [String: Any]?) throws -> String {+ guard let v = val else { return "(none)" }+ let d = try JSONSerialization.data(withJSONObject: v, options: [.prettyPrinted, .sortedKeys])+ return String(data: d, encoding: .utf8) ?? "(none)"+ }+ let before = try slJSON(oldSL)+ let after = try slJSON(newSL)+ return "statusLine\nBefore:\n\(before)\n\nAfter:\n\(after)"+ }++ /// Writes settings.json and commits side effects (call after user confirms).+ func writeStatusLine() throws {+ guard let data = _pendingStatusLineData else { return }+ let settingsURL = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent(".claude/settings.json")+ let formatter = DateFormatter()+ formatter.dateFormat = "yyyyMMdd-HHmm"+ let stamp = formatter.string(from: Date())+ let backupURL = settingsURL.deletingLastPathComponent()+ .appendingPathComponent("settings.json.bak-\(stamp)")+ try? FileManager.default.copyItem(at: settingsURL, to: backupURL)+ try? FileManager.default.createDirectory(at: settingsURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ try data.write(to: settingsURL, options: .atomic)+ // Commit side effects only after successful write+ if let prevData = _pendingPreviousData {+ try? prevData.write(to: statusLinePreviousURL, options: .atomic)+ }+ if _pendingDeletePrevious {+ try? FileManager.default.removeItem(at: statusLinePreviousURL)+ }+ _pendingStatusLineData = nil+ _pendingPreviousData = nil+ _pendingDeletePrevious = false+ }+// MARK: - App Store: hooks via security-scoped bookmark#if APPSTORE@@ -1472,12 +1625,53 @@ def normalize_tool_fields(payload):payload['session_id'] = siddef main():+ raw = b''+ payload = {}try:raw = sys.stdin.buffer.read()if not raw:- return- payload = json.loads(raw)+ if '--statusline' not in sys.argv[1:]:+ return+ else:+ payload = json.loads(raw)except Exception:+ if '--statusline' not in sys.argv[1:]:+ return++ socket_path = os.path.expanduser(+ '~/Library/Application Support/NotchBuddy/nb.sock'+ )++ # --statusline mode: relay rate_limits to Coucou, then delegate to saved previous+ if '--statusline' in sys.argv[1:]:+ relay = {+ 'coucou_kind': 'statusline',+ 'session_id': payload.get('session_id', ''),+ 'rate_limits': payload.get('rate_limits', {}),+ }+ try:+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ s.settimeout(0.3)+ s.connect(socket_path)+ s.sendall((json.dumps(relay) + '\\n').encode())+ s.close()+ except Exception:+ pass+ prev_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statusline-previous.json')+ if os.path.exists(prev_file):+ try:+ import subprocess+ with open(prev_file) as f:+ prev = json.load(f)+ cmd = prev.get('command', '')+ if cmd:+ result = subprocess.run(['/bin/sh', '-c', cmd], input=raw,+ capture_output=True, timeout=10)+ if result.stdout:+ sys.stdout.buffer.write(result.stdout)+ sys.stdout.buffer.flush()+ except Exception:+ passreturn# Parse --agent <name> and optional positional event from argv.@@ -1521,9 +1715,7 @@ def main():passevent = payload.get('hook_event_name', '')- socket_path = os.path.expanduser(- '~/Library/Application Support/NotchBuddy/nb.sock'- )+ # socket_path is already defined aboveif event == 'PermissionRequest':# Block and wait for Coucou's decision (Claude Code allows up to 120s)@@ -1642,12 +1834,53 @@ def normalize_tool_fields(payload):payload['session_id'] = siddef main():+ raw = b''+ payload = {}try:raw = sys.stdin.buffer.read()if not raw:- return- payload = json.loads(raw)+ if '--statusline' not in sys.argv[1:]:+ return+ else:+ payload = json.loads(raw)except Exception:+ if '--statusline' not in sys.argv[1:]:+ return++ socket_path = os.path.expanduser(+ '~/Library/Containers/fr.louisraille.Coucou/Data/nb.sock'+ )++ # --statusline mode: relay rate_limits to Coucou, then delegate to saved previous+ if '--statusline' in sys.argv[1:]:+ relay = {+ 'coucou_kind': 'statusline',+ 'session_id': payload.get('session_id', ''),+ 'rate_limits': payload.get('rate_limits', {}),+ }+ try:+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ s.settimeout(0.3)+ s.connect(socket_path)+ s.sendall((json.dumps(relay) + '\\n').encode())+ s.close()+ except Exception:+ pass+ prev_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statusline-previous.json')+ if os.path.exists(prev_file):+ try:+ import subprocess+ with open(prev_file) as f:+ prev = json.load(f)+ cmd = prev.get('command', '')+ if cmd:+ result = subprocess.run(['/bin/sh', '-c', cmd], input=raw,+ capture_output=True, timeout=10)+ if result.stdout:+ sys.stdout.buffer.write(result.stdout)+ sys.stdout.buffer.flush()+ except Exception:+ passreturn# Parse --agent <name> and optional positional event from argv.@@ -1690,9 +1923,7 @@ def main():passevent = payload.get('hook_event_name', '')- socket_path = os.path.expanduser(- '~/Library/Containers/fr.louisraille.Coucou/Data/nb.sock'- )+ # socket_path is already defined aboveif event == 'PermissionRequest':# Block and wait for Coucou's decision (Claude Code allows up to 120s)diff --git a/NotchBuddy/Sources/App/IslandRootView.swift b/NotchBuddy/Sources/App/IslandRootView.swiftindex 9eb8b69b..aa809e84 100644--- a/NotchBuddy/Sources/App/IslandRootView.swift+++ b/NotchBuddy/Sources/App/IslandRootView.swift@@ -483,25 +483,32 @@ struct IslandHeader: View {Spacer()- // Right: action icons- HStack(spacing: 14) {- Button(action: {- withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {- state.view = .settings- }- }) {- Image(systemName: state.view == .settings ? "gearshape.fill" : "gearshape")- .font(.system(size: 14))- .foregroundColor(state.view == .settings ? Color(hex: "#F5F6F8") : Color(hex: "#8E939C"))+ // Right: plan pill (GitHub build, home view only) + action icons+ HStack(spacing: 8) {+ #if !APPSTORE+ if state.view == .overview && state.showPlanInNotch && state.planRelayInstalled {+ ClaudePlanHeaderPill(state: state)}- .buttonStyle(.plain)+ #endif+ HStack(spacing: 14) {+ Button(action: {+ withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {+ state.view = .settings+ }+ }) {+ Image(systemName: state.view == .settings ? "gearshape.fill" : "gearshape")+ .font(.system(size: 14))+ .foregroundColor(state.view == .settings ? Color(hex: "#F5F6F8") : Color(hex: "#8E939C"))+ }+ .buttonStyle(.plain)- Button(action: { state.soundEnabled.toggle() }) {- Image(systemName: state.soundEnabled ? "speaker.wave.2" : "speaker.slash")- .font(.system(size: 14))- .foregroundColor(Color(hex: "#8E939C"))+ Button(action: { state.soundEnabled.toggle() }) {+ Image(systemName: state.soundEnabled ? "speaker.wave.2" : "speaker.slash")+ .font(.system(size: 14))+ .foregroundColor(Color(hex: "#8E939C"))+ }+ .buttonStyle(.plain)}- .buttonStyle(.plain)}.padding(.trailing, 16)}@@ -543,6 +550,64 @@ struct TabButton: View {}}+// MARK: - Claude Plan header pill (GitHub build only)++#if !APPSTORE+struct ClaudePlanHeaderPill: View {+ @ObservedObject var state: AppState+ @State private var isHovered = false++ private var effectiveColor: String {+ ClaudePlanGauge.color(for: state.claudePlanUsage.flatMap { ClaudePlanGauge.dominantPct($0) })+ }++ private var label: String {+ guard let usage = state.claudePlanUsage,+ let pct = ClaudePlanGauge.dominantPct(usage) else { return "Claude —" }+ return "Claude \(Int(pct.rounded()))%"+ }++ private var isActive: Bool { state.showingPlanDetail || isHovered }++ var body: some View {+ Button(action: {+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) {+ state.showingPlanDetail.toggle()+ }+ }) {+ HStack(spacing: 4) {+ Circle()+ .fill(Color(hex: effectiveColor))+ .frame(width: 6, height: 6)+ Text(label)+ .font(.system(size: 10, weight: .semibold))+ .foregroundColor(isActive+ ? Color(hex: effectiveColor).lighter(by: 0.3)+ : Color(hex: "#6B7079"))+ .lineLimit(1)+ .fixedSize()+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(+ Capsule()+ .fill(isActive+ ? Color(hex: effectiveColor).opacity(0.18)+ : Color(hex: "#0E0F11"))+ )+ .overlay(+ Capsule()+ .stroke(Color(hex: effectiveColor).opacity(isActive ? 0.55 : 0.14), lineWidth: 1)+ )+ }+ .buttonStyle(.plain)+ .onHover { h in+ withAnimation(.spring(response: 0.2, dampingFraction: 0.7)) { isHovered = h }+ }+ }+}+#endif+// MARK: - Compact mini mochi grid (2×2 to the right of the notch)struct CompactMiniGrid: View {diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex 3b2ab506..7eb12456 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -93,8 +93,22 @@ struct OverviewView: View {}}+ // Plan detail overlays on top of normal content (GitHub build, home view only)+ #if !APPSTORE+ if state.showingPlanDetail {+ CardBackground(wash: nil)+ ClaudePlanCardView(usage: state.claudePlanUsage)+ .transition(.opacity)+ }+ #endif+// ↗ jump button — last in ZStack so it renders on top; hidden while any detail is open- if !showingN8nDetail {+ #if !APPSTORE+ let hideJumpButton = showingN8nDetail || state.showingPlanDetail+ #else+ let hideJumpButton = showingN8nDetail+ #endif+ if !hideJumpButton {Button(action: { openAgentTarget(agent) }) {Image(systemName: "arrow.up.right").font(.system(size: 8, weight: .medium))@@ -116,7 +130,20 @@ struct OverviewView: View {AgentPillsView(state: state)}}- .onChange(of: state.focusId) { _, _ in showingN8nDetail = false }+ .onChange(of: state.focusId) { _, _ in+ showingN8nDetail = false+ #if !APPSTORE+ withAnimation(.easeIn(duration: 0.16)) { state.showingPlanDetail = false }+ #endif+ }+ #if !APPSTORE+ .onChange(of: state.view) { _, v in+ if v != .overview { state.showingPlanDetail = false }+ }+ .onChange(of: state.mode) { _, m in+ if m != .expanded { state.showingPlanDetail = false }+ }+ #endif}private func openAgentTarget(_ task: AgentTask?) {@@ -2696,6 +2723,8 @@ struct AgentPill: View {let onTap: () -> Void@State private var isHovered = false+ private var effectiveColor: String { task.color }+// VS Code pill always shows "VS Code" label regardless of active project nameprivate var displayName: String {task.id == "integration_claude" ? "VS Code" : task.name@@ -2707,10 +2736,10 @@ struct AgentPill: View {ZStack {Capsule().fill(isHovered- ? Color(hex: task.color).opacity(0.18)+ ? Color(hex: effectiveColor).opacity(0.18): Color(hex: "#0E0F11"))Capsule()- .stroke(Color(hex: task.color).opacity(isHovered ? 0.55 : 0.14), lineWidth: 1)+ .stroke(Color(hex: effectiveColor).opacity(isHovered ? 0.55 : 0.14), lineWidth: 1)HStack(spacing: 0) {MiniBotCanvasView(task: task).frame(width: 22 / 0.6, height: 22 / 0.6)@@ -2721,7 +2750,7 @@ struct AgentPill: View {Text(displayName).font(.system(size: 10, weight: .semibold)).foregroundColor(isHovered- ? Color(hex: task.color).lighter(by: 0.3)+ ? Color(hex: effectiveColor).lighter(by: 0.3): Color(hex: "#6B7079")).lineLimit(1).truncationMode(.tail)@@ -2729,11 +2758,11 @@ struct AgentPill: View {}.frame(maxWidth: .infinity).frame(height: 28)- .shadow(color: Color(hex: task.color).opacity(isHovered ? 0.35 : 0), radius: 10, x: 0, y: 2)+ .shadow(color: Color(hex: effectiveColor).opacity(isHovered ? 0.35 : 0), radius: 10, x: 0, y: 2)// Alert badge (approval / finished / error)if let badge = task.pillBadge {- PillBadgeView(badge: badge, taskColor: task.color)+ PillBadgeView(badge: badge, taskColor: effectiveColor).offset(x: 3, y: -3)}}diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex 26c4775e..21f0ff45 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -33,6 +33,11 @@ struct SettingsView: View {@State private var hookNeedsUpdate: Bool = HookServer.hooksNeedUpdate()#if !APPSTORE+ @State private var showStatusLineDiff: Bool = false+ @State private var pendingStatusLineJSON: String = ""+ @State private var statusLinePendingInstall: Bool = true+ @State private var planTogglePending: Bool = false+@State private var geminiHooksInstalled: Bool = HookServer.geminiHooksInstalled()@State private var showGeminiDiff: Bool = false@State private var pendingGeminiJSON: String = ""@@ -164,6 +169,9 @@ struct SettingsView: View {}}.onAppear {+ #if !APPSTORE+ state.refreshPlanRelayState()+ #endifguard fetchedModels.isEmpty,let key = KeychainStore.shared.get("anthropic-api-key"), !key.isEmpty else { return }Task {@@ -476,6 +484,67 @@ struct SettingsView: View {}.padding(6)}++ GroupBox("Plan usage") {+ VStack(alignment: .leading, spacing: 10) {+ Text("Shows your Claude plan usage (5-hour and weekly limits) in the notch header. Coucou adds a status line relay to ~/.claude/settings.json. If you already have a status line, it keeps working as before. Pro and Max plans only.")+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ Toggle("Show in the notch", isOn: Binding(+ get: { state.showPlanInNotch || planTogglePending },+ set: { on in+ if on {+ if state.planRelayInstalled {+ state.showPlanInNotch = true+ } else {+ planTogglePending = true+ installStatusLine()+ }+ } else {+ state.showPlanInNotch = false+ planTogglePending = false+ }+ }+ ))+ HStack(spacing: 10) {+ if state.planRelayInstalled {+ Text("Relay: installed")+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ Button("Uninstall relay") { uninstallStatusLine() }+ .buttonStyle(.bordered)+ } else {+ Text("Relay: not installed")+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ Button("Install relay") { installStatusLine() }+ .buttonStyle(.borderedProminent)+ }+ }+ if showStatusLineDiff {+ ScrollView {+ Text(pendingStatusLineJSON)+ .font(.system(size: 10, design: .monospaced))+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .frame(height: 100)+ .background(Color(NSColor.textBackgroundColor))+ .cornerRadius(6)+ HStack {+ Button("Confirm & write") { confirmStatusLine() }+ .buttonStyle(.borderedProminent)+ Button("Cancel") {+ showStatusLineDiff = false+ pendingStatusLineJSON = ""+ planTogglePending = false+ }+ .buttonStyle(.bordered)+ }+ }+ }+ .padding(6)+ }#endif}@@ -951,6 +1020,50 @@ struct SettingsView: View {statusMessage = "❌ \(error.localizedDescription)"}}++ private func installStatusLine() {+ do {+ pendingStatusLineJSON = try HookServer.shared.previewStatusLine(install: true)+ showStatusLineDiff = true+ statusLinePendingInstall = true+ statusMessage = "Review the JSON below before confirming."+ } catch {+ statusMessage = "❌ \(error.localizedDescription)"+ }+ }++ private func uninstallStatusLine() {+ do {+ pendingStatusLineJSON = try HookServer.shared.previewStatusLine(install: false)+ showStatusLineDiff = true+ statusLinePendingInstall = false+ statusMessage = "Review the JSON below before confirming."+ } catch {+ statusMessage = "❌ \(error.localizedDescription)"+ }+ }++ private func confirmStatusLine() {+ do {+ try HookServer.shared.writeStatusLine()+ showStatusLineDiff = false+ pendingStatusLineJSON = ""+ state.refreshPlanRelayState()+ if planTogglePending {+ state.showPlanInNotch = true+ planTogglePending = false+ }+ if !statusLinePendingInstall {+ state.showPlanInNotch = false+ }+ statusMessage = statusLinePendingInstall+ ? "✓ Status line installed."+ : "✓ Status line removed."+ } catch {+ planTogglePending = false+ statusMessage = "❌ \(error.localizedDescription)"+ }+ }#endifprivate func saveIntegrations() {diff --git a/README.md b/README.mdindex 9951e17b..d2e14637 100644--- a/README.md+++ b/README.md@@ -36,6 +36,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch- ✅ **Approve from the notch** — Claude Code and Codex permission requests show up with **Allow / Deny** (and **Always** for Claude Code), in VS Code, Cursor's terminal, or Codex. One click, back to work.- 🧑💻 **Jump to the right terminal** — open the exact terminal window of a session *(macOS)*.- 💬 **Chat with Claude, Gemini, OpenAI, or a local model (Ollama / LM Studio)** — click the model name above the chat box to switch provider and pick a model. Cloud providers use your own API key; local providers connect to a server running on your Mac. *(Gemini, OpenAI and local models: macOS)*+- 📊 **Claude plan usage** *(macOS, GitHub build)* — a small pill in the notch header shows your 5-hour and weekly Claude plan limits. Enable it from Settings → Agents → Plan usage. Pro and Max plans only.- 📋 **Declare the tools you use** — open Settings → Active pills and pick your main workspace tool (VS Code, Cursor, Codex or Antigravity), then toggle up to 4 more: Gemini CLI, Anthropic, Google AI, OpenAI, Ollama, LM Studio and service integrations *(macOS)*.- 📎 **Drop a file on the notch** — Mochi turns into a box and swallows it, then ask a question about it or send it by email *(email: macOS, Mail.app)*.- 🪟 **Drag Mochi onto any window** — attach that window as context for Claude *(macOS)*.@@ -132,6 +133,7 @@ Click the Coucou icon in the menu bar (macOS) or in the system tray (Windows, Li| What | Why | Where the key goes ||---|---|---|| **Claude Code hooks** | live sessions and approvals | **Install hooks** — Coucou backs up `~/.claude/settings.json`, merges its hooks and shows you the diff before writing anything |+| **Claude plan** *(macOS, GitHub build)* | Plan usage gauge in the notch header | **Install relay** in Settings → Agents → Plan usage, then enable "Show in the notch" || **Gemini CLI hooks** *(macOS)* | Gemini CLI sessions in the island | **Install hooks** in Settings → Gemini CLI — backs up `~/.gemini/settings.json` || **Antigravity (agy) hooks** *(macOS)* | agy sessions in the island | **Install hooks** in Settings → Antigravity — backs up `~/.gemini/config/hooks.json` || **Anthropic API key** | chat and questions about files | Settings → Anthropic API · Keychain / Windows Credential Manager / Secret Service |diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex b5448e9e..edbec867 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -68,6 +68,44 @@ Demande l'autorisation Automatisation la première fois (normal).---+## 1bis. Jauge de forfait Claude (statusLine)++**Affichage** : petit pill dans l'en-tête de l'île (vue home uniquement) — plus de pastille dans le catalogue Active pills.+**Plateforme** : macOS uniquement (build GitHub)+**Plans** : Pro et Max uniquement (le champ `rate_limits` n'est présent que pour ces plans)++Affiche la consommation du forfait Claude via un pill coloré dans l'en-tête de l'île. Couleur dynamique : vert `#22C55E` < 50 %, orange `#F59E0B` 50–80 %, rouge `#F4505E` ≥ 80 %, gris `#6B7079` sans données. Cliquer sur le pill bascule `showingPlanDetail`, ce qui remplace la carte en cours par `ClaudePlanCardView`. `showingPlanDetail` se remet à false au changement de focusId, de vue ou de mode.++### Données++Claude Code envoie, à chaque réponse et avec un debounce de 300 ms, un JSON à la commande `statusLine` configurée dans `~/.claude/settings.json`. Ce JSON contient :++```json+{+ "session_id": "…",+ "rate_limits": {+ "five_hour": { "used_percentage": 23.5, "resets_at": 1738425600 },+ "seven_day": { "used_percentage": 67.0, "resets_at": 1738598400 }+ }+}+```++`used_percentage` va de 0 à 100. `resets_at` est un epoch UNIX en secondes. Le champ `rate_limits` peut être absent (plan Free, ou première réponse de la session). Chaque fenêtre peut être absente indépendamment. Les valeurs absurdes (< 0 ou > 100) sont ignorées. Une fenêtre dont `resets_at` est passé s'affiche à 0 % jusqu'à la prochaine mise à jour.++### Relais++nb-hook.py, en mode `--statusline`, lit le JSON de stdin, en extrait `rate_limits` et `session_id`, et envoie `{"coucou_kind": "statusline", …}` au socket en fire-and-forget (timeout 0,3 s). Si une `statusLine` précédente existait (sauvegardée dans `statusline-previous.json` à côté de nb-hook), elle est appelée via `/bin/sh -c` avec le même stdin et sa sortie est réécrite telle quelle (timeout 10 s, couleurs ANSI comprises).++### Installation et activation++Réglages → Agents → Plan usage → **Install relay**. Coucou montre le diff de `~/.claude/settings.json` avant d'écrire quoi que ce soit. Si une `statusLine` existait, seul le champ `command` est remplacé ; les autres champs (`padding`, `refreshInterval`, etc.) sont conservés. Une fois le relais installé, activer le toggle **Show in the notch** pour faire apparaître le pill dans l'en-tête. Si le toggle est activé avant l'installation du relais, l'installation est lancée automatiquement ; le toggle s'active après confirmation.++### Désinstallation++Réglages → Agents → Plan usage → **Uninstall relay**. Remet l'objet `statusLine` d'origine à l'identique, ou retire la clé si elle n'existait pas. Si la `statusLine` actuelle n'est plus celle de Coucou (l'utilisateur l'a changée), elle n'est pas touchée.++---+## 2. n8n (workflows de Louis)- Réglages : URL de l'instance (probablement `https://n8nlouis.dcsys.tech`, **à confirmer avec Louis**) et clé API n8n (Trousseau). La clé se crée dans n8n : Settings → n8n API.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex ab619113..c9bd6aed 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -212,6 +212,7 @@ Fenêtre Réglages (SwiftUI, simple), sections dans l'ordre d'affichage :- **Chat — other providers** : clé Google AI (Trousseau) ; clé OpenAI (Trousseau). Les modèles se choisissent dans le chat (voir INTEGRATIONS §5bis).- **Local models** : URL du serveur Ollama (défaut `http://127.0.0.1:11434`) et/ou LM Studio (défaut `http://127.0.0.1:1234`). Bouton **Connect** : vérifie la joignabilité et sauvegarde l'URL. Bouton **Disconnect** : efface l'URL et le cache. Aucune clé requise (voir INTEGRATIONS §5ter).- **Claude Code Hooks** : état des hooks, bouton Installer / Désinstaller.+- **Plan usage** : toggle **Show in the notch** + bouton **Install relay** / **Uninstall relay**. Voir INTEGRATIONS §1bis. **Jauge de forfait Claude** *(GitHub only)* : petit pill dans l'en-tête de l'île (vue home uniquement). Activé via `showPlanInNotch` (UserDefaults) + `HookServer.statusLineInstalled()`. Couleur = `ClaudePlanGauge.color(for: dominantPct)`. Clic → `showingPlanDetail` bascule et `ClaudePlanCardView` s'affiche à la place de la carte en cours. `showingPlanDetail` se remet à false au changement de focusId, de vue ou de mode. Grand Mochi prend la couleur de l'usage quand `showingPlanDetail == true`.- **Gemini CLI Hooks** *(build GitHub)* : état des hooks, bouton Installer / Désinstaller.- **Antigravity Hooks** *(build GitHub)* : état des hooks, bouton Installer / Désinstaller.- **Integrations** : clé ou token (Trousseau) pour chaque service (n8n, Stripe, GitHub, Vercel, Resend, Notion, Cal.com).diff --git a/docs/privacy.html b/docs/privacy.htmlindex 6b182c7b..980b37fd 100644--- a/docs/privacy.html+++ b/docs/privacy.html@@ -37,7 +37,7 @@<p>We have no access to these requests or their responses.</p><h2>5. Claude Code, Gemini CLI, Antigravity and Codex hooks</h2>-<p>If you install the Claude Code hooks, Claude Code sends session events to Coucou through a local connection on your computer. If you install the Gemini CLI, Antigravity or Codex hooks, those agents send their session events the same way. These events never leave your computer through Coucou. Before changing any settings file (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou makes a dated backup and shows you the changes.</p>+<p>If you install the Claude Code hooks, Claude Code sends session events to Coucou through a local connection on your computer. If you install the Gemini CLI, Antigravity or Codex hooks, those agents send their session events the same way. These events never leave your computer through Coucou. If you install the Plan usage status line, Claude Code also passes the percentage used and the reset times of your plan windows to Coucou through the same local connection; nothing leaves your computer. Before changing any settings file (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou makes a dated backup and shows you the changes.</p><h2>6. Apple Music</h2><p>If you activate the Apple Music pill <i>(macOS, GitHub build)</i>, Coucou reads the current track (title, artist, album) from Music on your Mac to display it in the notch, and only sends play, pause or skip commands to Music when you click. Nothing leaves your computer.</p>@@ -93,7 +93,7 @@<p>Le développeur n’a accès ni à ces requêtes ni à leurs réponses.</p><h2>5. Claude Code, Gemini CLI, Antigravity et Codex</h2>-<p>Si tu installes les hooks Claude Code, Claude Code envoie les événements de session à Coucou par une connexion locale sur ton ordinateur. Si tu installes les hooks Gemini CLI, Antigravity ou Codex, ces agents envoient leurs événements de la même façon. Coucou ne les fait jamais sortir de ton ordinateur. Avant de modifier un fichier de configuration (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou en fait une sauvegarde datée et te montre les changements.</p>+<p>Si tu installes les hooks Claude Code, Claude Code envoie les événements de session à Coucou par une connexion locale sur ton ordinateur. Si tu installes les hooks Gemini CLI, Antigravity ou Codex, ces agents envoient leurs événements de la même façon. Coucou ne les fait jamais sortir de ton ordinateur. Si tu installes le relais de jauge de forfait (Plan usage), Claude Code transmet aussi à Coucou, par la même connexion locale, les pourcentages utilisés et les heures de remise à zéro de tes fenêtres de forfait ; rien ne quitte ton ordinateur. Avant de modifier un fichier de configuration (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou en fait une sauvegarde datée et te montre les changements.</p><h2>6. Apple Music</h2><p>Si tu actives la pastille Apple Music <i>(macOS, version GitHub)</i>, Coucou lit le morceau en cours (titre, artiste, album) depuis l’app Musique de ton Mac pour l’afficher dans le notch, et n’envoie lecture, pause ou morceau suivant à Musique que quand tu cliques. Rien ne quitte ton ordinateur.</p>diff --git a/docs/support.html b/docs/support.htmlindex d9fa00c9..0be53c5e 100644--- a/docs/support.html+++ b/docs/support.html@@ -46,7 +46,7 @@<h3>Does it work without a notch?</h3><p>Yes. On an iMac, a Mac mini, or a MacBook with its lid closed on an external display, Mochi sits in a small bar at the top of the main screen. With the lid open, it stays in the notch.</p><h3>How do I uninstall?</h3>-<p>Remove hooks first: <b>Settings → Claude Code → Uninstall</b>, and if you installed them, also <b>Settings → Gemini CLI → Uninstall</b> and <b>Settings → Antigravity → Uninstall</b>. Then quit the app and move it to the Trash. Optionally delete <code>~/Library/Application Support/NotchBuddy</code>.</p>+<p>Remove hooks first: <b>Settings → Claude Code → Uninstall</b>, and if you installed them, also <b>Settings → Gemini CLI → Uninstall</b> and <b>Settings → Antigravity → Uninstall</b>. If you installed the Plan usage status line (Settings → Agents → Plan usage), click Uninstall there first to restore your previous status line. Then quit the app and move it to the Trash. Optionally delete <code>~/Library/Application Support/NotchBuddy</code>.</p><p>On Windows: same <b>Uninstall</b> button for the hooks, then Windows Settings → Apps → <b>Coucou</b> → Uninstall. Optionally delete <code>%LOCALAPPDATA%\Coucou</code>.</p><p>On Linux: same <b>Uninstall</b> button for the hooks, then <code>sudo apt remove coucou</code> or <code>sudo dnf remove coucou</code>, or delete the AppImage. Optionally delete <code>~/.config/coucou</code>, <code>~/.local/share/coucou</code>, <code>~/.local/share/fr.louisraille.coucou</code> and <code>~/.cache/coucou</code>.</p></section>@@ -93,7 +93,7 @@<h3>Ça marche sans notch ?</h3><p>Oui. Sur un iMac, un Mac mini ou un MacBook capot fermé branché à un écran externe, Mochi s’affiche dans une petite barre en haut de l’écran principal. Capot ouvert, il reste dans le notch.</p><h3>Comment désinstaller ?</h3>-<p>Retire d’abord les hooks : <b>Réglages → Claude Code → Uninstall</b>, et si tu les as installés, aussi <b>Réglages → Gemini CLI → Uninstall</b> et <b>Réglages → Antigravity → Uninstall</b>. Puis quitte l’app et mets-la à la corbeille. Tu peux aussi supprimer <code>~/Library/Application Support/NotchBuddy</code>.</p>+<p>Retire d’abord les hooks : <b>Réglages → Claude Code → Uninstall</b>, et si tu les as installés, aussi <b>Réglages → Gemini CLI → Uninstall</b> et <b>Réglages → Antigravity → Uninstall</b>. Si tu as installé le relais Plan usage (Réglages → Agents → Plan usage), clique sur Uninstall d’abord pour retrouver ta status line d’avant. Puis quitte l’app et mets-la à la corbeille. Tu peux aussi supprimer <code>~/Library/Application Support/NotchBuddy</code>.</p><p>Sous Windows : le même bouton <b>Uninstall</b> pour les hooks, puis Paramètres Windows → Applications → <b>Coucou</b> → Désinstaller. Tu peux aussi supprimer <code>%LOCALAPPDATA%\Coucou</code>.</p><p>Sous Linux : le même bouton <b>Uninstall</b> pour les hooks, puis <code>sudo apt remove coucou</code> ou <code>sudo dnf remove coucou</code>, ou supprime l’AppImage. Tu peux aussi supprimer <code>~/.config/coucou</code>, <code>~/.local/share/coucou</code>, <code>~/.local/share/fr.louisraille.coucou</code> et <code>~/.cache/coucou</code>.</p></section>diff --git a/scripts/test-plan-gauge.sh b/scripts/test-plan-gauge.shnew file mode 100755index 00000000..9133fad5--- /dev/null+++ b/scripts/test-plan-gauge.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-plan-gauge.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/ClaudePlanGauge.swift \+ tests/ClaudePlanGaugeTests.swift -o "$TEST_DIR/plan-gauge-tests"+"$TEST_DIR/plan-gauge-tests"diff --git a/tests/ClaudePlanGaugeTests.swift b/tests/ClaudePlanGaugeTests.swiftnew file mode 100644index 00000000..91fa1ce0--- /dev/null+++ b/tests/ClaudePlanGaugeTests.swift@@ -0,0 +1,133 @@+import Foundation++@main+enum ClaudePlanGaugeTests {++ static var failures = 0++ static func check(_ label: String, _ got: String, _ expected: String) {+ if got == expected {+ print(" ✓ \(label)")+ } else {+ print(" ✗ \(label)")+ print(" got: \(got.debugDescription)")+ print(" expected: \(expected.debugDescription)")+ failures += 1+ }+ }++ static func checkTrue(_ label: String, _ value: Bool) {+ if value { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ static func main() {+ let futureEpoch: Double = Date().timeIntervalSince1970 + 7200 // 2 hours from now+ let pastEpoch: Double = Date().timeIntervalSince1970 - 100 // already passed++ // ── parse ──────────────────────────────────────────────────────────────+ print("ClaudePlanGauge.parse")++ let full: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 23.5, "resets_at": futureEpoch],+ "seven_day": ["used_percentage": 67.0, "resets_at": futureEpoch],+ ]]+ let usage = ClaudePlanGauge.parse(payload: full)+ checkTrue("parse full payload → non-nil", usage != nil)+ checkTrue("five_hour usedPct 23.5", usage?.fiveHour?.usedPct == 23.5)+ checkTrue("seven_day usedPct 67.0", usage?.sevenDay?.usedPct == 67.0)++ // Missing rate_limits → nil+ checkTrue("missing rate_limits → nil", ClaudePlanGauge.parse(payload: [:]) == nil)++ // Absurd pct (>200) → nil window (150 is now clamped to 100)+ let badPct: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 250.0, "resets_at": futureEpoch],+ ]]+ let badUsage = ClaudePlanGauge.parse(payload: badPct)+ checkTrue("absurd pct (250) → nil window", badUsage?.fiveHour == nil)++ // pct 150 → clamped to 100 (not rejected)+ let clampPct: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 150.0, "resets_at": futureEpoch],+ ]]+ let clampUsage = ClaudePlanGauge.parse(payload: clampPct)+ checkTrue("pct 150 → clamped to 100", clampUsage?.fiveHour?.usedPct == 100.0)++ // pct 201 → rejected+ let tooBig: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 201.0, "resets_at": futureEpoch],+ ]]+ checkTrue("pct 201 → nil window", ClaudePlanGauge.parse(payload: tooBig)?.fiveHour == nil)++ // resets_at > 400 days → rejected+ let farFuture = Date().timeIntervalSince1970 + 401 * 86400+ let msEpoch: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 50.0, "resets_at": farFuture],+ ]]+ checkTrue("resets_at > 400d → nil window", ClaudePlanGauge.parse(payload: msEpoch)?.fiveHour == nil)++ // Negative pct → nil window+ let negPct: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": -5.0, "resets_at": futureEpoch],+ ]]+ checkTrue("negative pct → nil window", ClaudePlanGauge.parse(payload: negPct)?.fiveHour == nil)++ // Int pct accepted+ let intPct: [String: Any] = ["rate_limits": [+ "five_hour": ["used_percentage": 42, "resets_at": Int(futureEpoch)],+ ]]+ let intUsage = ClaudePlanGauge.parse(payload: intPct)+ checkTrue("Int pct parsed", intUsage?.fiveHour?.usedPct == 42.0)++ // ── effectivePct (expired window) ─────────────────────────────────────+ print("ClaudePlanGauge.effectivePct")++ let expiredWindow = PlanWindow(usedPct: 80, resetsAt: Date(timeIntervalSince1970: pastEpoch))+ let futureWindow = PlanWindow(usedPct: 80, resetsAt: Date(timeIntervalSince1970: futureEpoch))+ checkTrue("expired window → 0", ClaudePlanGauge.effectivePct(expiredWindow) == 0)+ checkTrue("future window → original pct", ClaudePlanGauge.effectivePct(futureWindow) == 80)++ // ── dominantPct ────────────────────────────────────────────────────────+ print("ClaudePlanGauge.dominantPct")++ let both = PlanUsage(fiveHour: PlanWindow(usedPct: 30, resetsAt: Date(timeIntervalSince1970: futureEpoch)),+ sevenDay: PlanWindow(usedPct: 70, resetsAt: Date(timeIntervalSince1970: futureEpoch)),+ updatedAt: Date())+ let fhOnly = PlanUsage(fiveHour: PlanWindow(usedPct: 55, resetsAt: Date(timeIntervalSince1970: futureEpoch)),+ sevenDay: nil, updatedAt: Date())+ let empty = PlanUsage(fiveHour: nil, sevenDay: nil, updatedAt: Date())++ checkTrue("dominant picks higher (70)", ClaudePlanGauge.dominantPct(both) == 70)+ checkTrue("dominant with one window (55)", ClaudePlanGauge.dominantPct(fhOnly) == 55)+ checkTrue("dominant with no windows → nil", ClaudePlanGauge.dominantPct(empty) == nil)++ // ── color ──────────────────────────────────────────────────────────────+ print("ClaudePlanGauge.color")++ check("nil → grey", ClaudePlanGauge.color(for: nil), "#6B7079")+ check("0 → green", ClaudePlanGauge.color(for: 0), "#22C55E")+ check("49 → green", ClaudePlanGauge.color(for: 49), "#22C55E")+ check("50 → orange", ClaudePlanGauge.color(for: 50), "#F59E0B")+ check("79 → orange", ClaudePlanGauge.color(for: 79), "#F59E0B")+ check("80 → red", ClaudePlanGauge.color(for: 80), "#F4505E")+ check("100 → red", ClaudePlanGauge.color(for: 100), "#F4505E")++ // ── pillLabel ──────────────────────────────────────────────────────────+ print("ClaudePlanGauge.pillLabel")++ check("nil usage → 'Claude plan'", ClaudePlanGauge.pillLabel(nil), "Claude plan")+ check("no windows → 'Claude plan'", ClaudePlanGauge.pillLabel(empty), "Claude plan")+ check("70 pct → 'Claude 70%'", ClaudePlanGauge.pillLabel(both), "Claude 70%")+ check("55 pct → 'Claude 55%'", ClaudePlanGauge.pillLabel(fhOnly), "Claude 55%")++ // ── finish ─────────────────────────────────────────────────────────────+ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}