Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
25 changes: 12 additions & 13 deletions .github/swift-file-length-budget.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
# Format: max_lines<TAB>relative path
# Reduce counts as files shrink. CI fails if tracked files exceed this budget.
34590 CLI/cmux.swift
17841 Sources/AppDelegate.swift
16132 Sources/ContentView.swift
17827 Sources/AppDelegate.swift
16128 Sources/ContentView.swift
13832 Sources/TerminalController.swift
12894 Sources/Workspace.swift
12863 Sources/Workspace.swift
12237 Sources/GhosttyTerminalView.swift
12144 cmuxTests/AppDelegateShortcutRoutingTests.swift
11929 Sources/Panels/BrowserPanel.swift
11920 Sources/Panels/BrowserPanel.swift
9497 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift
8017 CLI/cmux_open.swift
8016 CLI/cmux_open.swift
7986 Sources/Panels/BrowserPanelView.swift
7366 cmuxTests/WorkspaceUnitTests.swift
7218 cmuxTests/WorkspaceRemoteConnectionTests.swift
Expand All @@ -23,7 +23,7 @@
5573 cmuxTests/BrowserConfigTests.swift
4487 Sources/Panels/FilePreviewPanel.swift
4478 Sources/cmuxApp.swift
4401 cmuxTests/BrowserPanelTests.swift
4367 cmuxTests/BrowserPanelTests.swift
4187 Sources/BrowserWindowPortal.swift
3934 Sources/Feed/FeedPanelView.swift
3926 cmuxTests/TabManagerUnitTests.swift
Expand All @@ -35,7 +35,7 @@
3058 Sources/Update/UpdateTitlebarAccessory.swift
2876 cmuxTests/CMUXOpenCommandTests.swift
2875 Sources/SessionIndexView.swift
2608 Sources/KeyboardShortcutSettings.swift
2606 Sources/KeyboardShortcutSettings.swift
2565 Sources/Panels/CmuxWebView.swift
2546 cmuxTests/WorkspaceManualUnreadTests.swift
2524 cmuxTests/CommandPaletteSearchEngineTests.swift
Expand All @@ -46,7 +46,7 @@
2126 cmuxTests/CmuxConfigTests.swift
2091 cmuxTests/ShortcutAndCommandPaletteTests.swift
2078 Sources/SessionPersistence.swift
1952 Sources/KeyboardShortcutSettingsFileStore.swift
1963 Sources/KeyboardShortcutSettingsFileStore.swift
1949 Sources/Panels/BrowserWebAuthnSupport.swift
1945 Sources/RestorableAgentSession.swift
1900 cmuxTests/NotificationAndMenuBarTests.swift
Expand Down Expand Up @@ -101,7 +101,7 @@
905 Sources/CmuxSSHURLRequest.swift
899 Sources/Panels/MarkdownWebRenderer.swift
885 Sources/Panels/TerminalPanel.swift
881 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift
878 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift
877 Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatConversationStoreTests.swift
871 cmuxTests/ClaudeHookSurfaceResolutionSwiftTests.swift
868 Sources/Panels/BrowserScreenshotSnapshotter.swift
Expand Down Expand Up @@ -159,13 +159,13 @@
636 Sources/TerminalController+ControlPaneContext.swift
632 cmuxTests/AgentSessionAutoResumeSwiftTests.swift
630 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift
629 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift
627 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift
621 cmuxUITests/RightSidebarChromeHeightUITests.swift
620 cmuxTests/FinderFileDropRegressionTests.swift
620 cmuxTests/TerminalNotificationQueueTests.swift
612 cmuxUITests/FeedSidebarUITests.swift
608 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Coordinators/WorkspaceGroupCoordinator.swift
606 Sources/SettingsNavigation.swift
608 Sources/SettingsNavigation.swift
604 Packages/macOS/CmuxCommandPalette/Tests/CmuxCommandPaletteTests/CommandPaletteNucleoFFITests.swift
601 Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerPrimaryPolicies.swift
599 Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift
Expand Down Expand Up @@ -214,19 +214,18 @@
520 cmuxTests/MainWindowVisibilityControllerTests.swift
519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift
519 Sources/CmuxConfigExecutor.swift
518 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift
518 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift
516 Sources/TerminalImageTransfer.swift
514 Packages/macOS/CmuxSwiftRender/Sources/CmuxSwiftRender/ExpressionEvaluator.swift
514 cmuxUITests/UpdatePillUITests.swift
509 Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerAdditionalPolicies.swift
507 Sources/TerminalControllerTopSupport.swift
506 Sources/App/MainWindowVisibilityController.swift
505 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift
505 cmuxUITests/DisplayResolutionRegressionUITests.swift
504 cmuxTests/TerminalNotificationSocketActionTests.swift
503 Sources/Settings/ConfigSource.swift
502 Sources/CmuxEventPublishing.swift
502 Sources/KeyboardShortcutContext.swift
502 Sources/RemoteTmuxSessionMirror.swift
501 Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift
500 Sources/KeyboardShortcutRecorder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ public struct TerminalCatalogSection: SettingCatalogSection {
userDefaultsKey: "terminal.autoResumeAgentSessions"
)

/// How cmux answers Claude Code's compacted-session resume prompt when it
/// auto-resumes a Claude agent on restore. Default `.ask` leaves the prompt
/// for the user; `.full`/`.summary` auto-select that option.
public let claudeResumeMode = DefaultsKey<ClaudeResumeMode>(
id: "terminal.claudeResumeMode",
defaultValue: .ask,
userDefaultsKey: "terminal.claudeResumeMode"
)

public let agentHibernationEnabled = DefaultsKey<Bool>(
id: "terminal.agentHibernation.enabled",
defaultValue: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Foundation

/// How cmux answers Claude Code's compacted-session resume prompt when it
/// auto-resumes a Claude agent on session restore. Claude shows an interactive
/// menu ("Resume from summary" / "Resume full session as-is" / "Don't ask me
/// again") that has no CLI flag or config to skip, so cmux drives it for you.
/// - ``ask`` — leave the prompt for you to answer (current behavior, default).
/// - ``full`` — auto-select "Resume full session as-is".
/// - ``summary`` — auto-select "Resume from summary".
public enum ClaudeResumeMode: String, CaseIterable, Sendable, Identifiable, SettingCodable {
case ask
case full
case summary

public var id: String { rawValue }

/// Parse shared by every configuration surface (`cmux.json`, `settings.json`,
/// the control socket): trims whitespace and accepts only the exact schema
/// enum values (`ask`/`full`/`summary`) case-insensitively; anything else is
/// rejected so out-of-schema config is reported invalid.
public init?(rawString: String?) {
guard let raw = rawString?.trimmingCharacters(in: .whitespacesAndNewlines),
!raw.isEmpty else { return nil }
// Accept only the exact schema enum values (case-insensitive + trimmed);
// anything else is rejected so out-of-schema config is reported invalid
// rather than silently accepted. Keep in sync with
// web/data/cmux.schema.json (`terminal.claudeResumeMode` enum).
switch raw.lowercased() {
case "ask":
self = .ask
case "full":
self = .full
case "summary":
self = .summary
default:
return nil
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

public static func decodeFromUserDefaults(_ raw: Any?) -> ClaudeResumeMode? {
guard let string = raw as? String else { return nil }
return ClaudeResumeMode(rawString: string)
}

public func encodeForUserDefaults() -> Any { rawValue }

public static func decodeFromJSON(_ raw: Any?) -> ClaudeResumeMode? {
guard let string = raw as? String else { return nil }
return ClaudeResumeMode(rawString: string)
}

public func encodeForJSON() -> Any { rawValue }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import Foundation

/// A single key cmux synthesizes into a Claude agent pane to drive its
/// compacted-session resume menu. Maps to cmux's named-key sender so libghostty
/// encodes the correct escape sequence for the pane's cursor mode.
public enum ClaudeResumeKey: String, Sendable {
case up
case down
case enter

/// Name understood by `TerminalSurface.sendNamedKey` / `TerminalPanel.sendNamedKeyResult`.
public var namedKey: String { rawValue }
}

/// Pure, UI-free detection and keystroke planning for Claude Code's
/// compacted-session resume menu. Kept free of AppKit/ghostty so it is fully
/// unit-testable; the app-side controller supplies the rendered screen text and
/// performs the side effects (reading the pane, sending keys).
public enum ClaudeResumePrompt {
/// Distinctive option labels Claude Code prints for the resume menu. Matching
/// the two "Resume …" labels together is specific enough not to fire on
/// ordinary conversation. The apostrophe in "Don't ask me again" is avoided
/// on purpose (straight-vs-curly quote ambiguity across renderers).
public static let summaryLabel = "Resume from summary"
public static let fullLabel = "Resume full session as-is"
public static let dontAskLabel = "ask me again"

/// Selection-pointer glyphs Ink-style menus render next to the active row.
private static let pointerGlyphs: Set<Character> = ["❯", "›", "▶", "▸", "➤"]

/// True when the resume menu is currently on screen. Requires all three
/// option labels together — a deliberately strict signal so the responder
/// never synthesizes keys just because one phrase appears in ordinary
/// terminal output.
public static func isVisible(in screen: String) -> Bool {
screen.contains(summaryLabel) && screen.contains(fullLabel) && screen.contains(dontAskLabel)
}

/// The keys needed to land on `mode`'s option and confirm it, given the
/// rendered screen. Returns nil when the menu isn't present, the mode is
/// `.ask` (no automation), or the target option can't be located.
///
/// Selection model: the menu's option rows are detected by their labels, in
/// display order. The currently highlighted row is found by its pointer
/// glyph; if no glyph is rendered we assume the first (recommended) row is
/// highlighted, which matches Claude's default. We then move up/down to the
/// target row and press Enter. Detecting the row order (rather than
/// hard-coding "press Down once") keeps this working if Claude reorders the
/// options.
public static func keystrokes(for mode: ClaudeResumeMode, in screen: String) -> [ClaudeResumeKey]? {
guard mode != .ask, isVisible(in: screen) else { return nil }

let targetLabel: String
switch mode {
case .full: targetLabel = fullLabel
case .summary: targetLabel = summaryLabel
case .ask: return nil
}

// Single pass over the screen: collect the menu's option rows (in display
// order) and note which row currently carries the selection pointer.
var optionLines: [String] = []
var pointerPosition: Int?
for rawLine in screen.split(separator: "\n", omittingEmptySubsequences: false) {
let line = String(rawLine)
guard line.contains(summaryLabel) || line.contains(fullLabel) || line.contains(dontAskLabel) else {
continue
}
if line.contains(where: { pointerGlyphs.contains($0) }) {
pointerPosition = optionLines.count
}
optionLines.append(line)
}

guard let targetPosition = optionLines.firstIndex(where: { $0.contains(targetLabel) }) else {
return nil
}
// Claude highlights the recommended (first) row by default; if no pointer
// glyph rendered, assume the first option is selected.
let currentPosition = pointerPosition ?? 0

var keys: [ClaudeResumeKey] = []
let delta = targetPosition - currentPosition
if delta > 0 {
keys.append(contentsOf: Array(repeating: .down, count: delta))
} else if delta < 0 {
keys.append(contentsOf: Array(repeating: .up, count: -delta))
}
keys.append(.enter)
return keys
}
}

/// One-shot responder armed for a single resumed Claude pane. The controller
/// feeds it the pane's rendered screen on each poll; it returns the keys to send
/// exactly once — when the menu first appears — then reports having responded so
/// the controller can disarm it.
public final class ClaudeResumeAutoResponder {
public let mode: ClaudeResumeMode
public private(set) var hasResponded = false

public init(mode: ClaudeResumeMode) {
self.mode = mode
}

/// Returns the keys to send if the menu is now visible and we haven't already
/// responded; nil otherwise. Marks itself responded when it returns keys so a
/// later call never double-fires.
public func evaluate(screen: String) -> [ClaudeResumeKey]? {
guard !hasResponded, mode != .ask else { return nil }
guard let keys = ClaudeResumePrompt.keystrokes(for: mode, in: screen) else { return nil }
hasResponded = true
return keys
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import Foundation
import Testing
@testable import CmuxSettings

@Suite("ClaudeResumeMode")
struct ClaudeResumeModeTests {
@Test func strictRawStringParse() {
#expect(ClaudeResumeMode(rawString: "ask") == .ask)
#expect(ClaudeResumeMode(rawString: "full") == .full)
#expect(ClaudeResumeMode(rawString: "summary") == .summary)
#expect(ClaudeResumeMode(rawString: "FULL") == .full) // case-insensitive
#expect(ClaudeResumeMode(rawString: " summary ") == .summary) // trimmed
// Non-schema aliases must be rejected so invalid config is reported.
#expect(ClaudeResumeMode(rawString: "manual") == nil)
#expect(ClaudeResumeMode(rawString: "full-session") == nil)
#expect(ClaudeResumeMode(rawString: "garbage") == nil)
#expect(ClaudeResumeMode(rawString: "") == nil)
#expect(ClaudeResumeMode(rawString: nil) == nil)
}

@Test func roundTripsThroughUserDefaultsAndJSON() {
for mode in ClaudeResumeMode.allCases {
#expect(ClaudeResumeMode.decodeFromUserDefaults(mode.encodeForUserDefaults()) == mode)
#expect(ClaudeResumeMode.decodeFromJSON(mode.encodeForJSON()) == mode)
}
#expect(ClaudeResumeMode.decodeFromUserDefaults(42) == nil)
}
}

@Suite("ClaudeResumePrompt")
struct ClaudeResumePromptTests {
/// Default rendering: pointer (❯) on the recommended first option (summary).
private let menu = """
Resuming the full session will consume a substantial portion of your usage limits. We recommend resuming from a summary.
❯ 1. Resume from summary (recommended)
2. Resume full session as-is
3. Don't ask me again
"""

@Test func detectsPromptOnlyWhenAllOptionLabelsPresent() {
#expect(ClaudeResumePrompt.isVisible(in: menu))
#expect(!ClaudeResumePrompt.isVisible(in: "just some normal claude output\nnothing to see"))
#expect(!ClaudeResumePrompt.isVisible(in: "Resume from summary mentioned alone"))
// Two of three labels appearing in prose must NOT count as the menu.
#expect(!ClaudeResumePrompt.isVisible(in: "We support Resume from summary and Resume full session as-is here."))
}

@Test func fullModeMovesDownToSecondOptionThenEnter() {
#expect(ClaudeResumePrompt.keystrokes(for: .full, in: menu) == [.down, .enter])
}

@Test func summaryModeConfirmsDefaultWithEnter() {
#expect(ClaudeResumePrompt.keystrokes(for: .summary, in: menu) == [.enter])
}

@Test func askModeNeverActs() {
#expect(ClaudeResumePrompt.keystrokes(for: .ask, in: menu) == nil)
}

@Test func returnsNilWhenMenuAbsent() {
#expect(ClaudeResumePrompt.keystrokes(for: .full, in: "no menu here") == nil)
}

/// Order-independence: if Claude lists "full" first with the pointer on it,
/// full needs only Enter and summary needs one Down.
@Test func adaptsToReorderedOptions() {
let reordered = """
❯ 1. Resume full session as-is
2. Resume from summary (recommended)
3. Don't ask me again
"""
#expect(ClaudeResumePrompt.keystrokes(for: .full, in: reordered) == [.enter])
#expect(ClaudeResumePrompt.keystrokes(for: .summary, in: reordered) == [.down, .enter])
}

/// With no pointer glyph rendered we assume the first option is highlighted.
@Test func assumesFirstOptionHighlightedWithoutPointer() {
let noPointer = """
1. Resume from summary (recommended)
2. Resume full session as-is
3. Don't ask me again
"""
#expect(ClaudeResumePrompt.keystrokes(for: .full, in: noPointer) == [.down, .enter])
}
}

@Suite("ClaudeResumeAutoResponder")
struct ClaudeResumeAutoResponderTests {
private let menu = """
❯ 1. Resume from summary (recommended)
2. Resume full session as-is
3. Don't ask me again
"""

@Test func firesExactlyOnce() {
let responder = ClaudeResumeAutoResponder(mode: .full)
#expect(responder.hasResponded == false)
#expect(responder.evaluate(screen: menu) == [.down, .enter])
#expect(responder.hasResponded == true)
// Subsequent polls (menu still on screen) must not re-send.
#expect(responder.evaluate(screen: menu) == nil)
}

@Test func waitsForMenuBeforeFiring() {
let responder = ClaudeResumeAutoResponder(mode: .full)
#expect(responder.evaluate(screen: "claude is starting up…") == nil)
#expect(responder.hasResponded == false)
#expect(responder.evaluate(screen: menu) == [.down, .enter])
}

@Test func askModeIsAlwaysInert() {
let responder = ClaudeResumeAutoResponder(mode: .ask)
#expect(responder.evaluate(screen: menu) == nil)
#expect(responder.hasResponded == false)
}
}
Loading
Loading