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:
@@ -46,6 +46,7 @@ final class HookServer: @unchecked Sendable {
|
||||
private var focusBeforeQuestion: String? = nil // saved focus to restore after question
|
||||
private var activeSessionId: String? = nil // current Claude Code session
|
||||
private var focusBeforeApproval: String? = nil // saved focus to restore after approval
|
||||
private var sessions = PillSessionRegistry() // live sessions behind each pill (upstream #562)
|
||||
|
||||
private init() {}
|
||||
|
||||
@@ -376,6 +377,13 @@ 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)
|
||||
|
||||
#if PHONE_LINK
|
||||
// The iPhone's "last turn" (prompt, actions, diffs, answer).
|
||||
@@ -432,7 +440,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) }
|
||||
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)))")
|
||||
if state.isPresent { expandIfNeeded(to: .overview) }
|
||||
@@ -440,7 +449,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) }
|
||||
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 {
|
||||
@@ -455,7 +465,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) }
|
||||
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 = frenchStep(tool: tool, input: input)
|
||||
@@ -463,6 +474,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 / Write
|
||||
let diffTool = payload["tool_name"] as? String ?? ""
|
||||
@@ -474,10 +486,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: "⚠ ошибка")
|
||||
|
||||
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") {
|
||||
@@ -489,15 +503,21 @@ 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) }
|
||||
// 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 {
|
||||
@@ -506,6 +526,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 {
|
||||
@@ -515,6 +537,7 @@ final class HookServer: @unchecked Sendable {
|
||||
}
|
||||
|
||||
case "StopFailure":
|
||||
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
|
||||
state.updateTask(id: agentId, state: .error)
|
||||
SoundEngine.shared.play("error")
|
||||
if focused {
|
||||
@@ -525,11 +548,18 @@ final class HookServer: @unchecked Sendable {
|
||||
|
||||
case "Interrupt":
|
||||
// Codex: user stopped the turn
|
||||
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
|
||||
activeSessionId = nil
|
||||
state.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 {
|
||||
nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")
|
||||
applyDisplayOwner(pill: agentId)
|
||||
break
|
||||
}
|
||||
activeSessionId = nil
|
||||
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
||||
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.
|
||||
/// ID format: "agent_<name>" — never collides with "integration_*" pills.
|
||||
/// 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
|
||||
private func upsertExternalAgent(id: String, name: String) {
|
||||
let state = AppState.shared
|
||||
@@ -704,7 +760,9 @@ final class HookServer: @unchecked Sendable {
|
||||
pendingApprovalFD = fd
|
||||
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.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,
|
||||
command: command, inputKey: inputKey, pillId: pillId,
|
||||
@@ -851,7 +909,9 @@ final class HookServer: @unchecked Sendable {
|
||||
activeSessionId = sessionId
|
||||
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.pendingQuestion = parsed
|
||||
state.isPinned = true
|
||||
@@ -890,9 +950,12 @@ 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 = "") {
|
||||
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", session: String) {
|
||||
let state = AppState.shared
|
||||
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
|
||||
if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user