Several Claude Code sessions on one pill no longer clobber each other (upstream #562)

PillSessionRegistry (upstream 5652ea8, after #245 by @TheodoreRiant) tracks the live
sessions behind each pill: only the last session takes the card and its diffs down, a
Stop finishes the pill only when no sibling is mid-turn, the 5.2 s idle reset is skipped
when a new turn started, and the oldest live session owns the name and folder (passed on
when it ends). Upstream tests pass on our copy: bash scripts/test-session-registry.sh.

Co-Authored-By: TheodoreRiant <57949703+TheodoreRiant@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-14 00:16:01 +03:00
parent 08949d136c
commit c0447ca327
4 changed files with 452 additions and 12 deletions
+75 -12
View File
@@ -46,6 +46,7 @@ final class HookServer: @unchecked Sendable {
private var focusBeforeQuestion: String? = nil // saved focus to restore after question private var focusBeforeQuestion: String? = nil // saved focus to restore after question
private var activeSessionId: String? = nil // current Claude Code session private var activeSessionId: String? = nil // current Claude Code session
private var focusBeforeApproval: String? = nil // saved focus to restore after approval private var focusBeforeApproval: String? = nil // saved focus to restore after approval
private var sessions = PillSessionRegistry() // live sessions behind each pill (upstream #562)
private init() {} private init() {}
@@ -376,6 +377,13 @@ final class HookServer: @unchecked Sendable {
} }
let focused = state.focusId == agentId 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)
#if PHONE_LINK #if PHONE_LINK
// The iPhone's "last turn" (prompt, actions, diffs, answer). // The iPhone's "last turn" (prompt, actions, diffs, answer).
@@ -432,7 +440,8 @@ final class HookServer: @unchecked Sendable {
case "SessionStart": case "SessionStart":
activeSessionId = sessionId activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) } 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 } if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))") nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
if state.isPresent { expandIfNeeded(to: .overview) } if state.isPresent { expandIfNeeded(to: .overview) }
@@ -440,7 +449,8 @@ final class HookServer: @unchecked Sendable {
case "UserPromptSubmit": case "UserPromptSubmit":
activeSessionId = sessionId activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) } 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 } if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
state.updateTask(id: agentId, state: .thinking) state.updateTask(id: agentId, state: .thinking)
if let prompt = payload["prompt"] as? String, !prompt.isEmpty { if let prompt = payload["prompt"] as? String, !prompt.isEmpty {
@@ -455,7 +465,8 @@ final class HookServer: @unchecked Sendable {
// AskUserQuestion is handled via the dedicated --ask hook. // AskUserQuestion is handled via the dedicated --ask hook.
// Skip state/step update here to avoid flickering over the question card. // Skip state/step update here to avoid flickering over the question card.
guard tool != "AskUserQuestion" else { break } guard tool != "AskUserQuestion" else { break }
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) } upsertTask(pill: agentId, display: display, working: true,
externalAgent: isExternalAgent ? validAgent : nil)
state.updateTask(id: agentId, state: .working) state.updateTask(id: agentId, state: .working)
let input = payload["tool_input"] as? [String: Any] ?? [:] let input = payload["tool_input"] as? [String: Any] ?? [:]
let step = frenchStep(tool: tool, input: input) let step = frenchStep(tool: tool, input: input)
@@ -463,6 +474,7 @@ final class HookServer: @unchecked Sendable {
nbLog("PreToolUse \(tool)") nbLog("PreToolUse \(tool)")
case "PostToolUse": case "PostToolUse":
sessions.note(pill: agentId, display: display, working: true)
state.updateTask(id: agentId, state: .working) state.updateTask(id: agentId, state: .working)
// Live diff for Edit / MultiEdit / Write // Live diff for Edit / MultiEdit / Write
let diffTool = payload["tool_name"] as? String ?? "" let diffTool = payload["tool_name"] as? String ?? ""
@@ -474,10 +486,12 @@ final class HookServer: @unchecked Sendable {
} }
case "PostToolUseFailure": case "PostToolUseFailure":
sessions.note(pill: agentId, display: display, working: true)
state.updateTask(id: agentId, state: .working) state.updateTask(id: agentId, state: .working)
appendStep(id: agentId, step: "⚠ ошибка") appendStep(id: agentId, step: "⚠ ошибка")
case "Notification": case "Notification":
sessions.note(pill: agentId, display: display, working: false)
let message = payload["message"] as? String ?? "" let message = payload["message"] as? String ?? ""
let lower = message.lowercased() let lower = message.lowercased()
if lower.contains("rate limit") || lower.contains("limite d") { if lower.contains("rate limit") || lower.contains("limite d") {
@@ -489,15 +503,21 @@ final class HookServer: @unchecked Sendable {
} }
case "Stop": case "Stop":
state.updateTask(id: agentId, state: .finished) let scope = sessions.endTurn(pill: agentId, session: sessionId)
let rawFinal = (payload["last_assistant_message"] as? String) let rawFinal = (payload["last_assistant_message"] as? String)
?? (payload["message"] as? String) ?? "" ?? (payload["message"] as? String) ?? ""
let finalText = DiffEngine.toOneLine(rawFinal) let finalText = DiffEngine.toOneLine(rawFinal)
if !finalText.isEmpty { // The step log is shared, so the conclusion is worth showing either way.
appendStep(id: agentId, step: finalText) if !finalText.isEmpty { appendStep(id: agentId, step: finalText) }
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { // Another session is still mid-turn behind this pill: the finished state, the
state.tasks[idx].finalLine = finalText // 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") SoundEngine.shared.play("finish")
if focused { if focused {
@@ -506,6 +526,8 @@ final class HookServer: @unchecked Sendable {
setPillBadge(id: agentId, badge: .finished) setPillBadge(id: agentId, badge: .finished)
} }
DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) { 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 { if isExternalAgent {
AppState.shared.removeTask(id: agentId) AppState.shared.removeTask(id: agentId)
} else { } else {
@@ -515,6 +537,7 @@ final class HookServer: @unchecked Sendable {
} }
case "StopFailure": case "StopFailure":
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
state.updateTask(id: agentId, state: .error) state.updateTask(id: agentId, state: .error)
SoundEngine.shared.play("error") SoundEngine.shared.play("error")
if focused { if focused {
@@ -525,11 +548,18 @@ final class HookServer: @unchecked Sendable {
case "Interrupt": case "Interrupt":
// Codex: user stopped the turn // Codex: user stopped the turn
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
activeSessionId = nil activeSessionId = nil
state.updateTask(id: agentId, state: .idle) state.updateTask(id: agentId, state: .idle)
clearPillBadge(id: agentId) clearPillBadge(id: agentId)
case "SessionEnd": 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 {
nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")
applyDisplayOwner(pill: agentId)
break
}
activeSessionId = nil activeSessionId = nil
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil } if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
state.clearSessionDiffs(for: agentId) state.clearSessionDiffs(for: agentId)
@@ -566,6 +596,32 @@ final class HookServer: @unchecked Sendable {
/// Creates a dynamic pill for a third-party agent on first event, then no-ops. /// Creates a dynamic pill for a third-party agent on first event, then no-ops.
/// ID format: "agent_<name>" — never collides with "integration_*" pills. /// ID format: "agent_<name>" — never collides with "integration_*" pills.
/// Inserted right after integration_claude so it appears in the visible prefix(4). /// Inserted right after integration_claude so it appears in the visible prefix(4).
/// 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,
session: display.session)
}
}
/// Writes the pill's name and cwd 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 }
AppState.shared.tasks[idx].name = owner.projectName
if !owner.cwd.isEmpty { AppState.shared.tasks[idx].sessionCwd = owner.cwd }
}
@MainActor @MainActor
private func upsertExternalAgent(id: String, name: String) { private func upsertExternalAgent(id: String, name: String) {
let state = AppState.shared let state = AppState.shared
@@ -704,7 +760,9 @@ final class HookServer: @unchecked Sendable {
pendingApprovalFD = fd pendingApprovalFD = fd
activeSessionId = sessionId activeSessionId = sessionId
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd) upsertTask(pill: pillId,
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
working: true, externalAgent: nil)
state.updateTask(id: pillId, state: .approval) state.updateTask(id: pillId, state: .approval)
state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool, state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,
command: command, inputKey: inputKey, pillId: pillId, command: command, inputKey: inputKey, pillId: pillId,
@@ -851,7 +909,9 @@ final class HookServer: @unchecked Sendable {
activeSessionId = sessionId activeSessionId = sessionId
questionPillId = pillId questionPillId = pillId
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd) upsertTask(pill: pillId,
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
working: true, externalAgent: nil)
state.updateTask(id: pillId, state: .question) state.updateTask(id: pillId, state: .question)
state.pendingQuestion = parsed state.pendingQuestion = parsed
state.isPinned = true state.isPinned = true
@@ -890,9 +950,12 @@ final class HookServer: @unchecked Sendable {
/// If the task already exists (persistent), just updates name/cwd. /// If the task already exists (persistent), just updates name/cwd.
/// If missing (transient), creates it and inserts after the main pill. /// If missing (transient), creates it and inserts after the main pill.
@MainActor @MainActor
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "") { private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", session: String) {
let state = AppState.shared let state = AppState.shared
if let idx = state.tasks.firstIndex(where: { $0.id == id }) { if let idx = state.tasks.firstIndex(where: { $0.id == id }) {
// Name and cwd belong to the session that owns the pill (the oldest one still
// running): a second session under the same client can't rename the card.
guard sessions.ownsDisplay(pill: id, session: session) else { return }
state.tasks[idx].name = projectName state.tasks[idx].name = projectName
if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd } if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
return return
@@ -0,0 +1,162 @@
import Foundation
// MARK: - PillSessionRegistry
//
// From upstream Coucou 5652ea8 (#562, after #245 by @TheodoreRiant), MIT. Unchanged.
/// 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
}
}
}
}
+8
View File
@@ -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"
+207
View File
@@ -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)
}
}
}