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 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