Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ struct ClaudeHookSessionRecord: Codable {
var lastPermissionMode: String?
var isRestorable: Bool?
var agentLifecycle: AgentHibernationLifecycleState?
/// True after a top-level prompt has ended and remains set through later
/// helper notifications until the next accepted UserPromptSubmit.
/// Optional so records written by older builds continue to decode.
var turnSettled: Bool? = nil
/// The hook event that most recently established the persisted lifecycle.
/// Optional so records written by older builds continue to decode.
var hookEventName: String? = nil
Expand Down Expand Up @@ -1176,6 +1180,11 @@ final class ClaudeHookSessionStore {
terminalPromptTurnSet(from: record).contains(normalizedTurnId) {
return (staleTerminalTurn: true, nested: false)
}
// UserPromptSubmit is the lifecycle boundary that starts a new
// parent turn. Clear the settled-turn fence while holding the
// store lock so a concurrent helper PreToolUse cannot reopen the
// old turn between the prompt and its running update.
record.turnSettled = false
update(
&record,
workspaceId: workspaceId,
Expand Down Expand Up @@ -1285,6 +1294,7 @@ final class ClaudeHookSessionStore {
let depthBeforeStop = max(0, record.activePromptDepth ?? 0)
let depthAfterStop = max(0, depthBeforeStop - 1)
let settlesTurn = depthAfterStop == 0
record.turnSettled = settlesTurn
update(
&record,
workspaceId: workspaceId,
Expand Down Expand Up @@ -1413,6 +1423,7 @@ final class ClaudeHookSessionStore {
launchCommand: AgentHookLaunchCommandRecord? = nil,
isRestorable: Bool? = nil,
agentLifecycle: AgentHibernationLifecycleState? = nil,
turnSettled: Bool? = nil,
hookEventName: String? = nil,
lastSubtitle: String? = nil,
lastBody: String? = nil,
Expand Down Expand Up @@ -1472,6 +1483,7 @@ final class ClaudeHookSessionStore {
launchCommand: launchCommand,
isRestorable: isRestorable,
agentLifecycle: agentLifecycle,
turnSettled: turnSettled,
hookEventName: hookEventName,
lastSubtitle: lastSubtitle,
lastBody: lastBody,
Expand Down Expand Up @@ -2028,6 +2040,7 @@ final class ClaudeHookSessionStore {
launchCommand: AgentHookLaunchCommandRecord?,
isRestorable: Bool?,
agentLifecycle: AgentHibernationLifecycleState?,
turnSettled: Bool? = nil,
hookEventName: String? = nil,
lastSubtitle: String?,
lastBody: String?,
Expand Down Expand Up @@ -2124,6 +2137,9 @@ final class ClaudeHookSessionStore {
if let agentLifecycle {
record.agentLifecycle = agentLifecycle
}
if let turnSettled {
record.turnSettled = turnSettled
}
if let hookEventName = normalizeOptional(hookEventName) {
record.hookEventName = hookEventName
}
Expand Down Expand Up @@ -31490,6 +31506,7 @@ struct CMUXCLI {
// hibernatable .idle state so the planner cannot SIGTERM
// a live task (mirrors the antigravity fullyIdle flip).
agentLifecycle: stopFailure != nil ? .needsInput : (hasUnsettledWork ? .backgroundWorkPending : .idle),
turnSettled: true,
hookEventName: reportedHookEventName(from: parsedInput) ?? "Stop",
lastSubtitle: completion?.subtitle,
lastBody: completion?.body,
Expand Down Expand Up @@ -31704,6 +31721,7 @@ struct CMUXCLI {
launchCommand: firstSightingLaunchCommand,
isRestorable: true,
agentLifecycle: .running,
turnSettled: false,
hookEventName: reportedHookEventName(from: parsedInput) ?? "UserPromptSubmit",
updateLastSummary: true,
markActive: true,
Expand Down Expand Up @@ -32269,6 +32287,17 @@ struct CMUXCLI {
let resolvedSurface = resolvedTarget
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let surfaceId = resolvedSurface.surfaceId
sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: surfaceId)
// A helper can invoke PreToolUse after the parent turn's Stop hook.
// That event belongs to the completed turn, so it must not reopen
// the parent session as Running. A new parent turn always passes
// through UserPromptSubmit first, which replaces this settled
// lifecycle and clears the guard.
let parentTurnAlreadyEnded = mappedSession?.turnSettled == true
guard !parentTurnAlreadyEnded else {
telemetry.breadcrumb("claude-hook.pre-tool-use.after-stop")
printClaudeHookAck()
return
}
let claudePid = localClaudePID(mapped: mappedSession)
// One ancestry walk per hook event, shared by the suppression gate
// and the notify payload's subagent tag.
Expand Down
169 changes: 169 additions & 0 deletions cmuxTests/ClaudeBackgroundWorkNotifyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,175 @@ struct ClaudeBackgroundWorkNotifyTests {
#expect(statusLine(result.snapshot, value: "Waiting") == nil)
}

@Test func preToolUseAfterStopDoesNotReopenRunningState() throws {
try assertToolUseAfterBoundary(boundary: "Stop", pendingWork: false, expectRunning: false)
}

@Test func pendingBackgroundWorkPreToolUseDoesNotReopenRunningState() throws {
try assertToolUseAfterBoundary(boundary: "Stop", pendingWork: true, expectRunning: false)
}

@Test func notificationAfterStopKeepsHelperToolFromReopeningTurn() throws {
let session = "helper-after-stop-notification"
let harness = ClaudeHookSurfaceResolutionSwiftTests()
let context = try harness.makeClaudeHookContext(name: "helper-after-stop-notification")
defer { context.cleanup() }
let storeURL = context.root.appendingPathComponent("claude-hook-sessions.json")
let handled = harness.startClaudeSurfaceResolutionServer(
context: context,
surfaces: [(context.surfaceId, "surface:1", true)],
ttyName: "ttys-helper-after-stop-notification",
ttySurfaceId: context.surfaceId
)
let environment = harness.claudeHookEnvironment(
context: context,
surfaceId: context.surfaceId,
ttyName: "ttys-helper-after-stop-notification",
storeURL: storeURL
)
func runHook(_ subcommand: String, _ payload: String) {
let result = harness.runProcess(
executablePath: context.cliPath,
arguments: ["hooks", "claude", subcommand],
environment: environment,
standardInput: payload,
timeout: ClaudeHookLiveDeliveryHarness.processWallBound
)
#expect(handled.wait(timeout: .now() + 5) == .success)
harness.assertSuccessfulHook(result)
}
func lifecycle() throws -> String? {
let object = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: storeURL)) as? [String: Any])
let sessions = try #require(object["sessions"] as? [String: Any])
let record = try #require(sessions[session] as? [String: Any])
return record["agentLifecycle"] as? String
}
func settledTurn() throws -> Bool? {
let object = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: storeURL)) as? [String: Any])
let sessions = try #require(object["sessions"] as? [String: Any])
let record = try #require(sessions[session] as? [String: Any])
return record["turnSettled"] as? Bool
}
let prompt = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"UserPromptSubmit","prompt":"finish this"}"#
let stop = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"Stop","last_assistant_message":"done","background_tasks":[],"session_crons":[]}"#
let notification = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"Notification","notification_type":"permission_prompt","message":"Claude needs your permission"}"#
let tool = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git status"}}"#

runHook("prompt-submit", prompt)
runHook("stop", stop)
#expect(try lifecycle() == "idle")
#expect(try settledTurn() == true)

runHook("notification", notification)
#expect(try lifecycle() == "needsInput")
#expect(try settledTurn() == true)
let commandCountAfterNotification = context.state.snapshot().count

// The notification overwrites hookEventName, so this specifically
// proves the persisted turn boundary—not the event name—owns the guard.
runHook("pre-tool-use", tool)
let afterTool = Array(context.state.snapshot().dropFirst(commandCountAfterNotification))
#expect(try lifecycle() == "needsInput")
#expect(try settledTurn() == true)
#expect(AgentJournalAppendCapture.captures(in: afterTool).contains {
$0.kind == "agent.state.changed" && $0.draft["declared_phase"] as? String == "running"
} == false)
#expect(statusLine(afterTool, value: "Running") == nil)

// The next real prompt clears the fence and allows its own tool call.
runHook("prompt-submit", prompt)
let commandCountAfterPrompt = context.state.snapshot().count
runHook("pre-tool-use", tool)
#expect(try lifecycle() == "running")
#expect(try settledTurn() == false)
#expect(statusLine(Array(context.state.snapshot().dropFirst(commandCountAfterPrompt)), value: "Running") != nil)
}

@Test(arguments: ["SessionStart", "Notification"])
func toolUseWithoutCompletedTurnRemainsRunning(boundary: String) throws {
try assertToolUseAfterBoundary(boundary: boundary, pendingWork: false, expectRunning: true)
}

private func assertToolUseAfterBoundary(
boundary: String,
pendingWork: Bool,
expectRunning: Bool
) throws {
let session = "helper-after-stop"
let harness = ClaudeHookSurfaceResolutionSwiftTests()
let context = try harness.makeClaudeHookContext(name: "helper-after-stop")
defer { context.cleanup() }
let storeURL = context.root.appendingPathComponent("claude-hook-sessions.json")
let handled = harness.startClaudeSurfaceResolutionServer(
context: context,
surfaces: [(context.surfaceId, "surface:1", true)],
ttyName: "ttys-helper-after-stop",
ttySurfaceId: context.surfaceId
)
let environment = harness.claudeHookEnvironment(
context: context,
surfaceId: context.surfaceId,
ttyName: "ttys-helper-after-stop",
storeURL: storeURL
)
func runHook(_ subcommand: String, _ payload: String) {
let result = harness.runProcess(
executablePath: context.cliPath,
arguments: ["hooks", "claude", subcommand],
environment: environment,
standardInput: payload,
timeout: ClaudeHookLiveDeliveryHarness.processWallBound
)
#expect(handled.wait(timeout: .now() + 5) == .success)
harness.assertSuccessfulHook(result)
}
func lifecycle() throws -> String? {
let object = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: storeURL)) as? [String: Any])
let sessions = try #require(object["sessions"] as? [String: Any])
let record = try #require(sessions[session] as? [String: Any])
return record["agentLifecycle"] as? String
}
let prompt = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"UserPromptSubmit","prompt":"finish this"}"#
let tool = #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git status"}}"#
runHook("prompt-submit", prompt)
switch boundary {
case "SessionStart":
runHook("session-start", #"{"session_id":"\#(session)","hook_event_name":"SessionStart","source":"resume"}"#)
case "Notification":
runHook("notification", #"{"session_id":"\#(session)","hook_event_name":"Notification","notification_type":"permission_prompt","message":"Claude needs your permission"}"#)
default:
let tasks = pendingWork ? #"[{"status":"running"}]"# : "[]"
runHook("stop", #"{"session_id":"\#(session)","cwd":"/tmp/x","hook_event_name":"Stop","last_assistant_message":"done","background_tasks":\#(tasks),"session_crons":[]}"#)
#expect(try lifecycle() == (pendingWork ? "backgroundWorkPending" : "idle"))
}
let commandCountAfterBoundary = context.state.snapshot().count

// This helper has no subagent marker or turn id, matching #19781.
runHook("pre-tool-use", tool)
let afterTool = Array(context.state.snapshot().dropFirst(commandCountAfterBoundary))
let expectedLifecycle = expectRunning ? "running" : (pendingWork ? "backgroundWorkPending" : "idle")
#expect(try lifecycle() == expectedLifecycle)
let runningEvents = AgentJournalAppendCapture.captures(in: afterTool).filter {
$0.kind == "agent.state.changed" && $0.draft["declared_phase"] as? String == "running"
}
#expect(!runningEvents.isEmpty == expectRunning)
#expect((statusLine(afterTool, value: "Running") != nil) == expectRunning)
if !expectRunning {
let expectedSettledStatus = pendingWork ? "Waiting" : "Idle"
#expect(lastLine(context.state.snapshot(), prefix: "set_status claude_code ")?.hasPrefix("set_status claude_code \(expectedSettledStatus) ") == true)
if pendingWork {
#expect(try lifecycle() == "backgroundWorkPending")
}

// The completed-turn guard must release on the next user prompt.
runHook("prompt-submit", prompt)
let commandCountAfterPrompt = context.state.snapshot().count
runHook("pre-tool-use", tool)
#expect(try lifecycle() == "running")
#expect(statusLine(Array(context.state.snapshot().dropFirst(commandCountAfterPrompt)), value: "Running") != nil)
}
}

private func statusLine(_ snapshot: [String], value: String) -> String? {
snapshot.first { $0.hasPrefix("set_status claude_code \(value) ") }
}
Expand Down
Loading