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
Several Claude Code sessions on one pill no longer clobber each other
Claude5652ea8f9e62
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 78822f15..0211f171 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -27,6 +27,9 @@ jobs:- name: Test display choicerun: bash scripts/test-display-choice.sh+ - name: Test parallel Claude Code sessions+ run: bash scripts/test-session-registry.sh+- name: Desktop Mochi and gaze testsrun: bash scripts/test-desktop-mochi.shdiff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex ef367c43..9e51bce8 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -46,6 +46,7 @@1C2BB61FA83015C42B321E0E /* PillColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37564F5F041B38C976DF3DEF /* PillColors.swift */; };1D23613B270FE8B11C5E27A7 /* IslandDisplayChoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A09E73F1E58019EF6EA2A62 /* IslandDisplayChoice.swift */; };1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };+ 9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };1DAB0704A136FF8E6FB34191 /* ClaudeResponseText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 444604C7E2C530B664849EF9 /* ClaudeResponseText.swift */; };1DCF28998358810CDBC93F91 /* ClaudeHookDetection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EA7D927F6BB2667D37AA963 /* ClaudeHookDetection.swift */; };1E55440B97C640993E93D04D /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = B32FB972D02162720E566674 /* DiffEngine.swift */; };@@ -125,6 +126,7 @@65CB53E20B2289CA3AC3E8FE /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };6613EB914852E6EEB1FF37BF /* IntentParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = F39753CFF90B494D449CCD95 /* IntentParser.swift */; };6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };+ 11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };68C3ACC708B69035FD0CB8C4 /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };694AB4504CD65662E1681E5C /* ServicePublisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F0C229BD085D76EB3DD94DF /* ServicePublisher.swift */; };@@ -436,6 +438,7 @@871CA2BADC67D97C97C7009D /* error.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = error.wav; sourceTree = "<group>"; };8790ACE9F73BD74640A0F20C /* LocalChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalChat.swift; sourceTree = "<group>"; };87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalTarget.swift; sourceTree = "<group>"; };+ 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PillSessionRegistry.swift; sourceTree = "<group>"; };888B3E1420BCB6292BDC8117 /* WeeklyRecapView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeeklyRecapView.swift; sourceTree = "<group>"; };8ACB4350729C6513824D1ADF /* ColorHex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorHex.swift; sourceTree = "<group>"; };8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanGauge.swift; sourceTree = "<group>"; };@@ -579,6 +582,7 @@914A792788D403F836BEB570 /* SpotifyViews.swift */,2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */,+ 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */,244A7909EEDA4BFF4C2EA9B5 /* TerminalTarget+AppKit.swift */,B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */,6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */,@@ -1051,6 +1055,7 @@1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */,1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */,+ 9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */,8551E592C5FFC6A0A7458A26 /* TurnEndPolicy.swift in Sources */,0408FE7F86EBEE61CAED32DA /* TurnRecorder.swift in Sources */,68C3ACC708B69035FD0CB8C4 /* TurnSnapshot.swift in Sources */,@@ -1243,6 +1248,7 @@E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,11F14DB97C93CF84DF9D5C43 /* TerminalTarget+AppKit.swift in Sources */,6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */,+ 11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */,ABE0CEF17018F1BAD8F7DBFA /* TurnEndPolicy.swift in Sources */,CE0A1BD64DF3E08D200691A6 /* TurnRecorder.swift in Sources */,4D34FF10654B19B69FE1964C /* TurnSnapshot.swift in Sources */,diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swiftindex 6ff4b70b..fa5157ff 100644--- a/NotchBuddy/Sources/App/HookServer.swift+++ b/NotchBuddy/Sources/App/HookServer.swift@@ -52,6 +52,7 @@ final class HookServer: @unchecked Sendable {private var focusBeforeQuestion: String? = nil // saved focus to restore after questionprivate var activeSessionId: String? = nil // current Claude Code sessionprivate var focusBeforeApproval: String? = nil // saved focus to restore after approval+ private var sessions = PillSessionRegistry() // live sessions behind each pillprivate init() {}@@ -399,6 +400,14 @@ final class HookServer: @unchecked Sendable {}let focused = state.focusId == agentId+ // Several sessions can share one pill (it is chosen from the client, not from the+ // session). The registry tells a turn-ending event whether it may touch the pill,+ // and which session owns the project name shown on it.+ let display = PillSessionRegistry.Display(+ session: sessionId,+ projectName: isExternalAgent ? (validAgent ?? projectName) : projectName,+ cwd: isExternalAgent ? "" : cwd,+ hostApp: hostApp, bundleId: bundleId)// For sessions that carry no id, derive a unique key from pill + cwd so that// concurrent anonymous sessions are tracked independently in RecapStore.let recapSessionId = (sessionId == "unknown" || sessionId.isEmpty)@@ -450,7 +459,8 @@ final class HookServer: @unchecked Sendable {case "SessionStart":activeSessionId = sessionId- if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd, hostApp: hostApp, bundleId: bundleId) }+ upsertTask(pill: agentId, display: display, working: false,+ externalAgent: isExternalAgent ? validAgent : nil)if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")NotificationCenter.default.post(name: .checkMondayRecap, object: nil)@@ -464,7 +474,8 @@ final class HookServer: @unchecked Sendable {case "UserPromptSubmit":activeSessionId = sessionId- if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd, hostApp: hostApp, bundleId: bundleId) }+ upsertTask(pill: agentId, display: display, working: true,+ externalAgent: isExternalAgent ? validAgent : nil)if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }state.updateTask(id: agentId, state: .thinking)if let prompt = payload["prompt"] as? String, !prompt.isEmpty {@@ -482,7 +493,8 @@ final class HookServer: @unchecked Sendable {// AskUserQuestion is handled via the dedicated --ask hook.// Skip state/step update here to avoid flickering over the question card.guard tool != "AskUserQuestion" else { break }- if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd, hostApp: hostApp, bundleId: bundleId) }+ upsertTask(pill: agentId, display: display, working: true,+ externalAgent: isExternalAgent ? validAgent : nil)state.updateTask(id: agentId, state: .working)let input = payload["tool_input"] as? [String: Any] ?? [:]let step = localizedStep(tool: tool, input: input)@@ -490,6 +502,7 @@ final class HookServer: @unchecked Sendable {nbLog("PreToolUse \(tool)")case "PostToolUse":+ sessions.note(pill: agentId, display: display, working: true)state.updateTask(id: agentId, state: .working)// Live diff for Edit / MultiEdit / Writelet diffTool = payload["tool_name"] as? String ?? ""@@ -502,10 +515,12 @@ final class HookServer: @unchecked Sendable {}case "PostToolUseFailure":+ sessions.note(pill: agentId, display: display, working: true)state.updateTask(id: agentId, state: .working)appendStep(id: agentId, step: "⚠ failed")case "Notification":+ sessions.note(pill: agentId, display: display, working: false)let message = payload["message"] as? String ?? ""let lower = message.lowercased()if lower.contains("rate limit") || lower.contains("limite d") {@@ -517,17 +532,23 @@ final class HookServer: @unchecked Sendable {}case "Stop":- state.updateTask(id: agentId, state: .finished)+ let scope = sessions.endTurn(pill: agentId, session: sessionId)let rawFinal = (payload["last_assistant_message"] as? String)?? (payload["message"] as? String) ?? ""let finalText = DiffEngine.toOneLine(rawFinal)- if !finalText.isEmpty {- appendStep(id: agentId, step: finalText)- if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {- state.tasks[idx].finalLine = finalText- }- }+ // The step log is shared, so the conclusion is worth showing either way.+ if !finalText.isEmpty { appendStep(id: agentId, step: finalText) }RecapStore.shared.stop(sessionId: recapSessionId)+ // Another session is still mid-turn behind this pill: the finished state, the+ // sound and the idle reset below would land on its work. Its own Stop comes later.+ guard scope == .pill else {+ nbLog("Stop \(sessionId.prefix(8)) — \(sessions.workingCount(pill: agentId)) session(s) still working on \(agentId)")+ break+ }+ state.updateTask(id: agentId, state: .finished)+ if !finalText.isEmpty, let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {+ state.tasks[idx].finalLine = finalText+ }SoundEngine.shared.play("finish")if focused {expandIfNeeded(to: .finished)@@ -535,6 +556,8 @@ final class HookServer: @unchecked Sendable {setPillBadge(id: agentId, badge: .finished)}DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {+ // A session (this one or a sibling) may have started a new turn meanwhile.+ guard self.sessions.workingCount(pill: agentId) == 0 else { return }if isExternalAgent {AppState.shared.removeTask(id: agentId)} else {@@ -545,6 +568,7 @@ final class HookServer: @unchecked Sendable {case "StopFailure":RecapStore.shared.stop(sessionId: recapSessionId)+ guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }state.updateTask(id: agentId, state: .error)SoundEngine.shared.play("error")if focused {@@ -556,11 +580,19 @@ final class HookServer: @unchecked Sendable {case "Interrupt":// Codex: user stopped the turnRecapStore.shared.stop(sessionId: recapSessionId)+ guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }activeSessionId = nilstate.updateTask(id: agentId, state: .idle)clearPillBadge(id: agentId)case "SessionEnd":+ // Only the last session behind the pill may take the card and its diffs down.+ guard sessions.endSession(pill: agentId, session: sessionId) == .pill else {+ RecapStore.shared.sessionEnd(sessionId: recapSessionId)+ nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")+ applyDisplayOwner(pill: agentId)+ break+ }activeSessionId = nilif let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }state.clearSessionDiffs(for: agentId)@@ -765,7 +797,11 @@ final class HookServer: @unchecked Sendable {pendingApprovalFD = fdactiveSessionId = sessionId- upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd, hostApp: terminalHost?.bundleId, bundleId: bundleId)+ upsertTask(pill: pillId,+ display: PillSessionRegistry.Display(session: sessionId, projectName: projectName,+ cwd: cwd, hostApp: terminalHost?.bundleId,+ bundleId: bundleId),+ working: true, externalAgent: nil)state.updateTask(id: pillId, state: .approval)state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,command: command, inputKey: inputKey, pillId: pillId)@@ -936,7 +972,11 @@ final class HookServer: @unchecked Sendable {? "\(pillId)+\(cwd)": sessionId- upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd, hostApp: terminalHost?.bundleId, bundleId: bundleId)+ upsertTask(pill: pillId,+ display: PillSessionRegistry.Display(session: sessionId, projectName: projectName,+ cwd: cwd, hostApp: terminalHost?.bundleId,+ bundleId: bundleId),+ working: true, externalAgent: nil)state.updateTask(id: pillId, state: .question)state.pendingQuestion = parsedstate.isPinned = true@@ -981,9 +1021,44 @@ final class HookServer: @unchecked Sendable {/// If the task already exists (persistent), just updates name/cwd./// If missing (transient), creates it and inserts after the main pill.@MainActor- private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", hostApp: String? = nil, bundleId: String = "") {+ /// Records the session an event came from, then refreshes its card.+ /// `externalAgent` is the validated `coucou_agent` name for a third-party agent pill,+ /// nil for a workspace pill.+ @MainActor+ private func upsertTask(pill: String, display: PillSessionRegistry.Display,+ working: Bool, externalAgent: String?) {+ sessions.note(pill: pill, display: display, working: working)+ if let externalAgent {+ upsertExternalAgent(id: pill, name: externalAgent)+ } else {+ upsertWorkspaceTask(id: pill, projectName: display.projectName, cwd: display.cwd,+ hostApp: display.hostApp, bundleId: display.bundleId,+ session: display.session)+ }+ }++ /// Writes the pill's name, cwd and terminal from the session that owns it: used when+ /// the owner ends and a sibling session inherits the card.+ @MainActor+ private func applyDisplayOwner(pill: String) {+ guard let owner = sessions.displayOwner(of: pill),+ let idx = AppState.shared.tasks.firstIndex(where: { $0.id == pill }),+ !owner.projectName.isEmpty else { return }+ let state = AppState.shared+ state.tasks[idx].name = owner.projectName+ if !owner.cwd.isEmpty { state.tasks[idx].sessionCwd = owner.cwd }+ if pill == "integration_claude" { state.tasks[idx].hostApp = owner.hostApp }+ if !owner.bundleId.isEmpty { state.tasks[idx].sessionBundleId = owner.bundleId }+ }++ /// Name, cwd and terminal belong to the session that owns the pill (the oldest one+ /// still running), so a second session under the same client cannot rename the card,+ /// or send "Open terminal" elsewhere, out from under the first.+ @MainActor+ private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", hostApp: String? = nil, bundleId: String = "", session: String) {let state = AppState.sharedif let idx = state.tasks.firstIndex(where: { $0.id == id }) {+ guard sessions.ownsDisplay(pill: id, session: session) else { return }state.tasks[idx].name = projectNameif !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }if id == "integration_claude" { state.tasks[idx].hostApp = hostApp }diff --git a/NotchBuddy/Sources/App/PillSessionRegistry.swift b/NotchBuddy/Sources/App/PillSessionRegistry.swiftnew file mode 100644index 00000000..bccebc26--- /dev/null+++ b/NotchBuddy/Sources/App/PillSessionRegistry.swift@@ -0,0 +1,160 @@+import Foundation++// MARK: - PillSessionRegistry++/// Keeps track of the agent sessions living behind each pill.+///+/// A pill is picked from the client that sent the event — bundle ID,+/// `term_program`, `coucou_agent` — never from the session. Two `claude`+/// started in two projects under VS Code therefore land on the same+/// `integration_claude`, while `AppState.tasks` holds one entry per pill.+/// Without a session set, the first session to end wipes the card and the+/// diffs the second one is still filling.+///+/// A value type on purpose: the hook server owns one copy and every change+/// goes through a `mutating` call, so no other object can alias the state.+struct PillSessionRegistry {++ /// A session unheard of for this long counts as gone. A `SessionEnd` that+ /// never arrives — a killed terminal, a crash — would otherwise pin a card+ /// to a session nobody is running any more.+ static let maxSilence: TimeInterval = 12 * 3600++ /// A session mid-turn emits a hook event every few seconds, so this long+ /// without one means its `Stop` went missing. Stops counting it as working,+ /// which is what keeps a sibling session from staying stuck out of its+ /// finished state. Longer than any tool call Claude Code will wait on.+ static let maxTurnSilence: TimeInterval = 30 * 60++ /// How far a terminal event is allowed to reach.+ enum TerminalScope: Equatable {+ /// No other session is mid-turn behind this pill, so the pill may+ /// follow: finished state, sound, badge, card removal.+ case pill+ /// Another session is still working — leave the pill as it is.+ case sessionOnly+ }++ /// What a pill shows while a session owns it.+ struct Display: Equatable {+ var session: String+ var projectName: String+ var cwd: String+ /// Terminal the session runs in (bundle id), for "Open terminal".+ var hostApp: String? = nil+ /// Bundle id of the client (VS Code, Cursor…) that sent the event.+ var bundleId: String = ""+ }++ private struct Session {+ var projectName: String+ var cwd: String+ var hostApp: String?+ var bundleId: String+ var isWorking: Bool+ var lastSeen: Date+ }++ private struct Pill {+ /// Live sessions, oldest first. The first one owns name and cwd.+ var order: [String] = []+ var sessions: [String: Session] = [:]+ }++ private var pills: [String: Pill] = [:]++ // MARK: - Recording activity++ /// Records the session that sent an event as live behind `pill`.+ /// `working` says whether the event means the session is mid-turn: a+ /// `PreToolUse` does, a `SessionStart` or a stray notification does not.+ mutating func note(pill: String, display: Display, working: Bool, now: Date = Date()) {+ var p = pills[pill] ?? Pill()+ sweep(&p, now: now)+ if p.sessions[display.session] == nil {+ p.order.append(display.session)+ }+ var session = p.sessions[display.session]+ ?? Session(projectName: display.projectName, cwd: display.cwd,+ hostApp: display.hostApp, bundleId: display.bundleId,+ isWorking: false, lastSeen: now)+ session.projectName = display.projectName+ if !display.cwd.isEmpty { session.cwd = display.cwd }+ if display.hostApp != nil { session.hostApp = display.hostApp }+ if !display.bundleId.isEmpty { session.bundleId = display.bundleId }+ if working { session.isWorking = true }+ session.lastSeen = now+ p.sessions[display.session] = session+ pills[pill] = p+ }++ // MARK: - Terminal events++ /// Ends a session's turn without ending the session: a `Stop` closes a+ /// turn, and the user can send another prompt right after.+ ///+ /// A session we have never seen stays untracked — Coucou can start in the+ /// middle of one, and a session we only ever heard stop owns nothing.+ mutating func endTurn(pill: String, session: String, now: Date = Date()) -> TerminalScope {+ var p = pills[pill] ?? Pill()+ sweep(&p, now: now)+ p.sessions[session]?.isWorking = false+ p.sessions[session]?.lastSeen = now+ if p.order.isEmpty { pills.removeValue(forKey: pill) } else { pills[pill] = p }+ return p.sessions.values.contains(where: \.isWorking) ? .sessionOnly : .pill+ }++ /// Drops a session for good. `.pill` only when it was the last one live,+ /// so the card and the diffs survive a sibling session ending.+ mutating func endSession(pill: String, session: String, now: Date = Date()) -> TerminalScope {+ var p = pills[pill] ?? Pill()+ sweep(&p, now: now)+ p.order.removeAll { $0 == session }+ p.sessions.removeValue(forKey: session)+ guard !p.order.isEmpty else {+ pills.removeValue(forKey: pill)+ return .pill+ }+ pills[pill] = p+ return .sessionOnly+ }++ // MARK: - Reading++ /// The session whose project name and cwd the pill shows. Ownership goes+ /// to the oldest live session and only moves on when that one ends, so a+ /// single name field stops flipping between two parallel sessions.+ func displayOwner(of pill: String) -> Display? {+ guard let p = pills[pill], let id = p.order.first,+ let session = p.sessions[id] else { return nil }+ return Display(session: id, projectName: session.projectName, cwd: session.cwd,+ hostApp: session.hostApp, bundleId: session.bundleId)+ }++ /// Whether this session may write the pill's name and cwd. True when the+ /// pill has no live session yet, so a first event is never dropped.+ func ownsDisplay(pill: String, session: String) -> Bool {+ guard let owner = displayOwner(of: pill) else { return true }+ return owner.session == session+ }++ func liveCount(pill: String) -> Int { pills[pill]?.order.count ?? 0 }++ func workingCount(pill: String) -> Int {+ pills[pill]?.sessions.values.filter(\.isWorking).count ?? 0+ }++ // MARK: - Silence sweep++ private func sweep(_ pill: inout Pill, now: Date) {+ for (id, session) in pill.sessions.map({ ($0.key, $0.value) }) {+ let silence = now.timeIntervalSince(session.lastSeen)+ if silence > Self.maxSilence {+ pill.sessions.removeValue(forKey: id)+ pill.order.removeAll { $0 == id }+ } else if session.isWorking, silence > Self.maxTurnSilence {+ pill.sessions[id]?.isWorking = false+ }+ }+ }+}diff --git a/scripts/test-session-registry.sh b/scripts/test-session-registry.shnew file mode 100755index 00000000..e92e15bd--- /dev/null+++ b/scripts/test-session-registry.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-session-registry.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/PillSessionRegistry.swift \+ tests/PillSessionRegistryTests.swift -o "$TEST_DIR/session-registry-tests"+"$TEST_DIR/session-registry-tests"diff --git a/tests/PillSessionRegistryTests.swift b/tests/PillSessionRegistryTests.swiftnew file mode 100644index 00000000..a2d4e7ef--- /dev/null+++ b/tests/PillSessionRegistryTests.swift@@ -0,0 +1,207 @@+import Foundation++@main+enum PillSessionRegistryTests {++ static var failures = 0++ static func check(_ label: String, _ got: Bool) {+ if got { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ static let claude = "integration_claude"++ static func display(_ session: String, _ project: String, _ cwd: String = "")+ -> PillSessionRegistry.Display {+ PillSessionRegistry.Display(session: session, projectName: project, cwd: cwd)+ }++ static func main() {++ // ── one session alone: the pill follows it all the way ──────────────────+ print("\nSingle session")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: false)+ check("one live session", reg.liveCount(pill: claude) == 1)+ check("not working after SessionStart", reg.workingCount(pill: claude) == 0)++ reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: true)+ check("working after a tool call", reg.workingCount(pill: claude) == 1)++ check("Stop reaches the pill", reg.endTurn(pill: claude, session: "a") == .pill)+ check("still live between turns", reg.liveCount(pill: claude) == 1)+ check("SessionEnd reaches the pill",+ reg.endSession(pill: claude, session: "a") == .pill)+ check("pill is empty", reg.liveCount(pill: claude) == 0)+ }++ // ── two sessions on one pill: this is the defect ────────────────────────+ // Negative cases: an implementation that always answers .pill fails here.+ print("\nTwo sessions behind one pill")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)+ reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)+ check("both live", reg.liveCount(pill: claude) == 2)+ check("both working", reg.workingCount(pill: claude) == 2)++ check("A's Stop must not touch the pill while B works",+ reg.endTurn(pill: claude, session: "a") == .sessionOnly)+ check("B still working", reg.workingCount(pill: claude) == 1)+ check("A's SessionEnd must not remove the card",+ reg.endSession(pill: claude, session: "a") == .sessionOnly)+ check("B alone now", reg.liveCount(pill: claude) == 1)++ check("B's Stop reaches the pill", reg.endTurn(pill: claude, session: "b") == .pill)+ check("B's SessionEnd reaches the pill",+ reg.endSession(pill: claude, session: "b") == .pill)+ }++ // ── a resting sibling does not hold the pill back ───────────────────────+ print("\nResting sibling")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou"), working: true)+ reg.note(pill: claude, display: display("b", "lokil"), working: true)+ _ = reg.endTurn(pill: claude, session: "b")+ check("A's Stop reaches the pill once B rests",+ reg.endTurn(pill: claude, session: "a") == .pill)+ check("A's SessionEnd still spares B's card",+ reg.endSession(pill: claude, session: "a") == .sessionOnly)+ }++ // ── name and cwd: owned by one session, handed over when it leaves ──────+ print("\nDisplay ownership")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)+ reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)+ check("oldest session owns the name", reg.displayOwner(of: claude)?.session == "a")+ check("name is A's", reg.displayOwner(of: claude)?.projectName == "coucou")+ check("A may write the card", reg.ownsDisplay(pill: claude, session: "a"))+ check("B may not rename the card under A",+ !reg.ownsDisplay(pill: claude, session: "b"))++ // B keeps working; the name must not flip.+ reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)+ check("name still A's after more B events",+ reg.displayOwner(of: claude)?.projectName == "coucou")++ _ = reg.endSession(pill: claude, session: "a")+ check("B inherits the display", reg.displayOwner(of: claude)?.session == "b")+ check("name is now B's", reg.displayOwner(of: claude)?.projectName == "lokil")+ check("cwd is now B's", reg.displayOwner(of: claude)?.cwd == "/b")+ check("B may write the card now", reg.ownsDisplay(pill: claude, session: "b"))+ }++ // ── empty cwd must not erase a known one ────────────────────────────────+ print("\nPartial payloads")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)+ reg.note(pill: claude, display: display("a", "coucou", ""), working: false)+ check("cwd kept when the event carries none",+ reg.displayOwner(of: claude)?.cwd == "/a")+ check("working flag is sticky inside a turn", reg.workingCount(pill: claude) == 1)+ }++ // ── pills are independent ──────────────────────────────────────────────+ print("\nSeparate pills")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude, display: display("a", "coucou"), working: true)+ reg.note(pill: "agent_cursor", display: display("b", "lokil"), working: true)+ check("Cursor's Stop reaches its own pill",+ reg.endTurn(pill: "agent_cursor", session: "b") == .pill)+ check("Claude untouched", reg.workingCount(pill: claude) == 1)+ check("an unknown pill is empty", reg.liveCount(pill: "agent_codex") == 0)+ }++ // ── sessions we never saw start ─────────────────────────────────────────+ print("\nUntracked sessions")+ do {+ var reg = PillSessionRegistry()+ check("a Stop from nowhere reaches the pill",+ reg.endTurn(pill: claude, session: "ghost") == .pill)+ check("it owns nothing", reg.liveCount(pill: claude) == 0)+ check("a SessionEnd from nowhere reaches the pill",+ reg.endSession(pill: claude, session: "ghost") == .pill)++ reg.note(pill: claude, display: display("a", "coucou"), working: true)+ check("a Stop from nowhere spares a working session",+ reg.endTurn(pill: claude, session: "ghost") == .sessionOnly)+ check("a SessionEnd from nowhere spares a live session",+ reg.endSession(pill: claude, session: "ghost") == .sessionOnly)+ }++ // ── a Stop that never arrives must not hold the other session back ─────+ print("\nTurn silence")+ do {+ var reg = PillSessionRegistry()+ let start = Date(timeIntervalSince1970: 1_000_000)+ reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)+ reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)++ let soon = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence - 60)+ reg.note(pill: claude, display: display("b", "lokil"), working: true, now: soon)+ check("A still working just under the limit",+ reg.endTurn(pill: claude, session: "b", now: soon) == .sessionOnly)++ let late = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence + 60)+ reg.note(pill: claude, display: display("b", "lokil"), working: true, now: late)+ check("silent A no longer counts as working",+ reg.workingCount(pill: claude) == 1)+ check("B's Stop reaches the pill again",+ reg.endTurn(pill: claude, session: "b", now: late) == .pill)+ check("A is still live", reg.liveCount(pill: claude) == 2)+ check("A still owns the display", reg.displayOwner(of: claude)?.session == "a")+ }++ // ── a SessionEnd that never arrives must not pin the card forever ──────+ print("\nSilence sweep")+ do {+ var reg = PillSessionRegistry()+ let start = Date(timeIntervalSince1970: 1_000_000)+ reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)+ reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)++ let later = start.addingTimeInterval(PillSessionRegistry.maxSilence + 60)+ reg.note(pill: claude, display: display("b", "lokil"), working: true, now: later)+ check("silent A swept", reg.liveCount(pill: claude) == 1)+ check("B owns the display", reg.displayOwner(of: claude)?.session == "b")+ check("B's SessionEnd clears the pill",+ reg.endSession(pill: claude, session: "b", now: later) == .pill)+ }++ // ── the terminal ("Open terminal") follows the display owner ────────────+ print("\nTerminal of the owner")+ do {+ var reg = PillSessionRegistry()+ reg.note(pill: claude,+ display: PillSessionRegistry.Display(session: "a", projectName: "coucou",+ cwd: "/tmp/coucou",+ hostApp: "com.googlecode.iterm2"),+ working: true)+ reg.note(pill: claude,+ display: PillSessionRegistry.Display(session: "b", projectName: "lokil",+ cwd: "/tmp/lokil",+ hostApp: "com.apple.Terminal"),+ working: true)+ check("A's terminal shown", reg.displayOwner(of: claude)?.hostApp == "com.googlecode.iterm2")+ _ = reg.endSession(pill: claude, session: "a")+ check("B's terminal once A ends", reg.displayOwner(of: claude)?.hostApp == "com.apple.Terminal")+ check("B's folder once A ends", reg.displayOwner(of: claude)?.cwd == "/tmp/lokil")+ }++ // ── finish ─────────────────────────────────────────────────────────────+ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}