diff --git a/Sources/AgentHibernation/AgentHibernationLifecycleState.swift b/Sources/AgentHibernation/AgentHibernationLifecycleState.swift index bf681db7873f..04dc559ac61d 100644 --- a/Sources/AgentHibernation/AgentHibernationLifecycleState.swift +++ b/Sources/AgentHibernation/AgentHibernationLifecycleState.swift @@ -25,6 +25,38 @@ enum AgentHibernationLifecycleState: String, Codable, Sendable, Equatable, CaseI parse(rawValue) } + static func aggregate( + statusKeyedStates: [String: AgentHibernationLifecycleState], + fallback: AgentHibernationLifecycleState? + ) -> AgentHibernationLifecycleState { + let states = statusKeyedStates + .filter { !AgentHibernationLifecycleStatusKeys.isManualKey($0.key) } + .map(\.value) + guard !states.isEmpty else { + return fallback ?? .unknown + } + if states.contains(.running) { return .running } + if states.contains(.needsInput) { return .needsInput } + if states.contains(.unknown) { return .unknown } + if states.contains(.idle) { return .idle } + return fallback ?? .unknown + } + + /// Aggregates only built-in agent keys for TextBox Escape authorization. + /// Hibernation uses `aggregate` so Feed overlays and registered Vault agents + /// remain part of its safety state; Escape passthrough intentionally fails + /// closed for keys that have not been validated as built-in agents. + static func aggregateForTextBoxEscape( + statusKeyedStates: [String: AgentHibernationLifecycleState] + ) -> AgentHibernationLifecycleState { + aggregate( + statusKeyedStates: statusKeyedStates.filter { + AgentHibernationLifecycleStatusKeys.isAllowed($0.key) + }, + fallback: nil + ) + } + private static func parse(_ rawValue: String) -> AgentHibernationLifecycleState? { let normalized = rawValue .trimmingCharacters(in: .whitespacesAndNewlines) @@ -60,6 +92,7 @@ enum AgentHibernationLifecycleStatusKeys { static let allowedStatusKeys: Set = [ "amp", "antigravity", + "campfire", "claude_code", "codebuddy", "codex", diff --git a/Sources/DockSplitStore+RestoredAgentLifecycle.swift b/Sources/DockSplitStore+RestoredAgentLifecycle.swift index 65914f9c2ebb..73e5b8e75b93 100644 --- a/Sources/DockSplitStore+RestoredAgentLifecycle.swift +++ b/Sources/DockSplitStore+RestoredAgentLifecycle.swift @@ -292,6 +292,22 @@ extension DockSplitStore { } } + func agentHibernationLifecycleState( + panelId: UUID, + fallback: AgentHibernationLifecycleState? + ) -> AgentHibernationLifecycleState { + AgentHibernationLifecycleState.aggregate( + statusKeyedStates: agentRuntimeByPanelId[panelId]?.agentLifecycleStates ?? [:], + fallback: fallback + ) + } + + func agentLifecycleStateForTextBoxEscape(panelId: UUID) -> AgentHibernationLifecycleState { + AgentHibernationLifecycleState.aggregateForTextBoxEscape( + statusKeyedStates: agentRuntimeByPanelId[panelId]?.agentLifecycleStates ?? [:] + ) + } + @discardableResult func clearAgentLifecycle(key: String, panelId: UUID) -> Bool { var didClear = false diff --git a/Sources/Panels/TerminalPanel.swift b/Sources/Panels/TerminalPanel.swift index 14d5a5696b97..a6048690dfaf 100644 --- a/Sources/Panels/TerminalPanel.swift +++ b/Sources/Panels/TerminalPanel.swift @@ -340,6 +340,9 @@ final class TerminalPanel: Panel, ObservableObject { } func handleTextBoxEscape() { + if containerAgentLifecycleStateForTextBoxEscape == .running { + _ = sendNamedKeyResult(TextBoxTerminalKey.escape.rawValue) + } let hadTextBoxView = textBoxInputView != nil let didFocusTerminal = focusTerminalSurface( respectForeignFirstResponder: false, @@ -348,6 +351,14 @@ final class TerminalPanel: Panel, ObservableObject { shouldHideTextBoxOnNextEscape = isTextBoxActive && (hadTextBoxView || didFocusTerminal) } + private var containerAgentLifecycleStateForTextBoxEscape: AgentHibernationLifecycleState { + if let dock = DockSplitStore.liveStore(containingPanel: id) { + return dock.agentLifecycleStateForTextBoxEscape(panelId: id) + } + return surface.owningWorkspace()? + .agentLifecycleStateForTextBoxEscape(panelId: id) ?? .unknown + } + @discardableResult func consumeTextBoxHideEscapeIfArmed(in window: NSWindow?) -> Bool { guard isTextBoxActive, diff --git a/Sources/Workspace+AgentLifecycle.swift b/Sources/Workspace+AgentLifecycle.swift index 06bfb9f8096b..f68bead61802 100644 --- a/Sources/Workspace+AgentLifecycle.swift +++ b/Sources/Workspace+AgentLifecycle.swift @@ -580,17 +580,16 @@ extension Workspace { panelId: UUID, fallback: AgentHibernationLifecycleState? ) -> AgentHibernationLifecycleState { - let states = (agentLifecycleStatesByPanelId[panelId] ?? [:]) - .filter { !AgentHibernationLifecycleStatusKeys.isManualKey($0.key) } - .map(\.value) - guard !states.isEmpty else { - return fallback ?? .unknown - } - if states.contains(.running) { return .running } - if states.contains(.needsInput) { return .needsInput } - if states.contains(.unknown) { return .unknown } - if states.contains(.idle) { return .idle } - return fallback ?? .unknown + AgentHibernationLifecycleState.aggregate( + statusKeyedStates: agentLifecycleStatesByPanelId[panelId] ?? [:], + fallback: fallback + ) + } + + func agentLifecycleStateForTextBoxEscape(panelId: UUID) -> AgentHibernationLifecycleState { + AgentHibernationLifecycleState.aggregateForTextBoxEscape( + statusKeyedStates: agentLifecycleStatesByPanelId[panelId] ?? [:] + ) } private func recordAgentLifecycleChange(panelId: UUID) { diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index f44c92ca3e26..fb854d7e2fc3 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -2509,6 +2509,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B7758A020000000000000001 /* TerminationWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7758A020000000000000002 /* TerminationWatchdogTests.swift */; }; C0DE7B330000000000000001 /* TextBoxAgentDetection.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE7B330000000000000002 /* TextBoxAgentDetection.swift */; }; B8835100000000000000000D /* TextBoxAttachment+PreparedPaste.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8835100000000000000000E /* TextBoxAttachment+PreparedPaste.swift */; }; + 970400000000000000000001 /* TextBoxEscapePassthroughTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 970400000000000000000002 /* TextBoxEscapePassthroughTests.swift */; }; 7898A0020000000000000001 /* TextBoxGitIgnoreProbe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7898A0020000000000000002 /* TextBoxGitIgnoreProbe.swift */; }; C0DE86250000000000000001 /* TextBoxIMECompositionLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE86250000000000000002 /* TextBoxIMECompositionLayoutTests.swift */; }; 5330B0715330B0715330B071 /* TextBoxInlineAttachmentCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5330B0725330B0725330B072 /* TextBoxInlineAttachmentCell.swift */; }; @@ -5313,6 +5314,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef B7758A020000000000000002 /* TerminationWatchdogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminationWatchdogTests.swift; sourceTree = ""; }; C0DE7B330000000000000002 /* TextBoxAgentDetection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBoxAgentDetection.swift; sourceTree = ""; }; B8835100000000000000000E /* TextBoxAttachment+PreparedPaste.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TextBoxAttachment+PreparedPaste.swift"; sourceTree = ""; }; + 970400000000000000000002 /* TextBoxEscapePassthroughTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBoxEscapePassthroughTests.swift; sourceTree = ""; }; 7898A0020000000000000002 /* TextBoxGitIgnoreProbe.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBoxGitIgnoreProbe.swift; sourceTree = ""; }; C0DE86250000000000000002 /* TextBoxIMECompositionLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBoxIMECompositionLayoutTests.swift; sourceTree = ""; }; 5330B0725330B0725330B072 /* TextBoxInlineAttachmentCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBoxInlineAttachmentCell.swift; sourceTree = ""; }; @@ -8023,6 +8025,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef 5330A0025330A0025330A002 /* TextBoxInlineAttachmentRenderingTests.swift */, C0DE7B300000000000000002 /* TextBoxMentionCompletionTests.swift */, C0DE86250000000000000002 /* TextBoxIMECompositionLayoutTests.swift */, + 970400000000000000000002 /* TextBoxEscapePassthroughTests.swift */, 9005A0010000000000000002 /* TextBoxSelectionReplacementTests.swift */, 7898A0010000000000000002 /* TextBoxMentionGitIgnoreProbeTests.swift */, C1713005C1713005C1713005 /* CommandPaletteShortcutCustomizationTests.swift */, @@ -11760,6 +11763,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileRef AA11BB22CC33DD44EE55F002 /* TerminalWindowPortalLayoutPassRefreshTests.swift in Sources */, C95BAC3D37A6111B487582DC /* TerminalWindowPortalLifecycleHiddenRefreshTests.swift in Sources */, B7758A020000000000000001 /* TerminationWatchdogTests.swift in Sources */, + 970400000000000000000001 /* TextBoxEscapePassthroughTests.swift in Sources */, C0DE86250000000000000001 /* TextBoxIMECompositionLayoutTests.swift in Sources */, 5330A0015330A0015330A001 /* TextBoxInlineAttachmentRenderingTests.swift in Sources */, C0DE7B300000000000000001 /* TextBoxMentionCompletionTests.swift in Sources */, diff --git a/cmuxTests/TextBoxEscapePassthroughTests.swift b/cmuxTests/TextBoxEscapePassthroughTests.swift new file mode 100644 index 000000000000..ef24691564e2 --- /dev/null +++ b/cmuxTests/TextBoxEscapePassthroughTests.swift @@ -0,0 +1,276 @@ +import AppKit +import CmuxTerminal +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@MainActor +@Suite("TextBox Escape passthrough", .serialized) +struct TextBoxEscapePassthroughTests { + @Test + func runningAgentReceivesEscapeFromTextBox() throws { + let fixture = try makeWorkspaceFixture() + defer { closeWindow(fixture.windowID) } + + fixture.workspace.setAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id, + lifecycle: .running + ) + defer { + _ = fixture.workspace.clearAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id + ) + } + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents + 1, + "Escape from TextBox must reach the PTY while the focused agent turn is running" + ) + } + + @Test + func runningCampfireAgentReceivesEscapeFromTextBox() throws { + let fixture = try makeWorkspaceFixture() + defer { closeWindow(fixture.windowID) } + + fixture.workspace.setAgentLifecycle( + key: "campfire", + panelId: fixture.panel.id, + lifecycle: .running + ) + defer { + _ = fixture.workspace.clearAgentLifecycle( + key: "campfire", + panelId: fixture.panel.id + ) + } + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents + 1, + "Escape from TextBox must reach a running Campfire agent" + ) + } + + @Test + func focusedTextBoxKeyDownRoutesOneEscapeToRunningAgent() throws { + let fixture = try makeWorkspaceFixture() + defer { closeWindow(fixture.windowID) } + + fixture.workspace.setAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id, + lifecycle: .running + ) + defer { + _ = fixture.workspace.clearAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id + ) + } + + let windowIdentifier = "cmux.main.\(fixture.windowID.uuidString)" + let window = try #require( + NSApp.windows.first { $0.identifier?.rawValue == windowIdentifier } + ) + let contentView = try #require(window.contentView) + let textView = TextBoxInputTextView(frame: NSRect(x: 0, y: 0, width: 240, height: 30)) + let scrollView = NSScrollView(frame: textView.frame) + scrollView.documentView = textView + contentView.addSubview(scrollView) + defer { scrollView.removeFromSuperview() } + + textView.onFocusTextBox = { fixture.panel.textBoxDidBecomeFocused() } + textView.onEscape = { fixture.panel.handleTextBoxEscape() } + fixture.panel.hostedView.setVisibleInUI(true) + fixture.panel.hostedView.setActive(true) + fixture.panel.hostedView.moveFocus() + fixture.panel.registerTextBoxInputView(textView) + window.makeKeyAndOrderFront(nil) + window.displayIfNeeded() + + let sentinelDraft = "unsubmitted sentinel draft" + textView.string = sentinelDraft + #expect(window.makeFirstResponder(textView)) + #expect(window.firstResponder === textView) + + let escapeEvent = try #require( + NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: 0, + windowNumber: window.windowNumber, + context: nil, + characters: "\u{1b}", + charactersIgnoringModifiers: "\u{1b}", + isARepeat: false, + keyCode: 53 + ) + ) + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + textView.keyDown(with: escapeEvent) + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents + 1, + "A physical Escape handled by the focused TextBox must enqueue exactly one PTY key event" + ) + #expect(textView.string == sentinelDraft, "Escape must preserve the unsubmitted TextBox draft") + #expect(fixture.panel.isTextBoxActive, "The first Escape must leave TextBox visible") + // Terminal first-responder transfer is covered by the existing window-routing suite; + // this standalone TextBox fixture focuses on the physical keyDown-to-PTY path. + } + + @Test + func idleAgentDoesNotReceiveEscapeFromTextBox() throws { + let fixture = try makeWorkspaceFixture() + defer { closeWindow(fixture.windowID) } + + fixture.workspace.setAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id, + lifecycle: .idle + ) + defer { + _ = fixture.workspace.clearAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id + ) + } + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents, + "Escape must retain TextBox focus behavior when the agent is not running" + ) + } + + @Test + func unsupportedRunningLifecycleDoesNotReceiveEscapeFromTextBox() throws { + let fixture = try makeWorkspaceFixture() + defer { closeWindow(fixture.windowID) } + + fixture.workspace.setAgentLifecycle( + key: "unsupported-agent", + panelId: fixture.panel.id, + lifecycle: .running + ) + defer { + _ = fixture.workspace.clearAgentLifecycle( + key: "unsupported-agent", + panelId: fixture.panel.id + ) + } + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents, + "Unsupported lifecycle keys must not authorize PTY Escape passthrough" + ) + } + + @Test + func runningDockAgentReceivesEscapeFromTextBox() { + let fixture = makeDockFixture() + defer { fixture.dock.closeAllPanels() } + + fixture.dock.setAgentLifecycle( + key: "claude_code", + panelId: fixture.panel.id, + lifecycle: .running + ) + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents + 1, + "Escape passthrough must follow a running agent into the Dock" + ) + } + + @Test + func manualDockActivityDoesNotReceiveEscapeFromTextBox() { + let fixture = makeDockFixture() + defer { fixture.dock.closeAllPanels() } + + fixture.dock.setAgentLifecycle( + key: "manual:loader", + panelId: fixture.panel.id, + lifecycle: .running + ) + let before = fixture.panel.surface.debugPendingSocketInputForTesting() + + fixture.panel.handleTextBoxEscape() + + let after = fixture.panel.surface.debugPendingSocketInputForTesting() + #expect( + after.keyEvents == before.keyEvents, + "Manual loading activity must not be treated as a running agent turn" + ) + } + + private func makeWorkspaceFixture() throws -> ( + windowID: UUID, + workspace: Workspace, + panel: TerminalPanel + ) { + let appDelegate = try #require(AppDelegate.shared) + let windowID = appDelegate.createMainWindow() + do { + let manager = try #require(appDelegate.tabManagerFor(windowId: windowID)) + let workspace = try #require(manager.selectedWorkspace) + let panelID = try #require(workspace.focusedPanelId) + let panel = try #require(workspace.terminalPanel(for: panelID)) + + panel.showTextBoxInputWhenAvailable() + panel.surface.releaseSurfaceForTesting() + return (windowID, workspace, panel) + } catch { + closeWindow(windowID) + throw error + } + } + + private func makeDockFixture() -> ( + dock: DockSplitStore, + panel: TerminalPanel + ) { + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + let panel = TerminalPanel( + workspaceId: dock.workspaceId, + runtimeSpawnPolicy: .pacedSessionRestore + ) + dock.panels[panel.id] = panel + panel.showTextBoxInputWhenAvailable() + panel.surface.releaseSurfaceForTesting() + return (dock, panel) + } + + private func closeWindow(_ windowID: UUID) { + let identifier = "cmux.main.\(windowID.uuidString)" + NSApp.windows.first { $0.identifier?.rawValue == identifier }?.performClose(nil) + } +} diff --git a/ghostty b/ghostty index 5045df3f2072..b17f1726fc53 160000 --- a/ghostty +++ b/ghostty @@ -1 +1 @@ -Subproject commit 5045df3f2072f0725394c87cebcc854b634e2131 +Subproject commit b17f1726fc53495dd827f7d85c9ec38da3d03814