Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ public struct OSC133CommandParser {
/// Creates an empty parser.
public init() {}

/// Removes and returns all completed (non-running) blocks, keeping any
/// still-open block so streaming continues uninterrupted.
///
/// A long-lived consumer (e.g. per-tab command-history recording) calls
/// this after ``consume(_:)`` to drain finished commands and bound memory,
/// instead of retaining every block's output for the whole session. The
/// `id` counter keeps advancing, so drained and future blocks never collide.
/// The chat transcript view does not call this (it reads ``blocks``
/// cumulatively), so its own parser instance is unaffected.
public mutating func takeCompletedBlocks() -> [TerminalCommandBlock] {
guard let openIndex else {
let all = blocks
blocks = []
return all
}
// The open block is always the last element; everything before it is
// completed and safe to hand off.
let completed = Array(blocks[..<openIndex])
let open = blocks[openIndex]
blocks = [open]
self.openIndex = 0
return completed
}

/// Feeds a chunk of raw terminal output through the state machine.
///
/// - Parameter text: A slice of the PTY stream, any length.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import Foundation
import Testing

@testable import CmuxAgentChat

/// `takeCompletedBlocks()` lets a long-lived consumer (per-tab command-history
/// recording) drain finished commands and bound memory while a command may
/// still be streaming.
@Suite("OSC133CommandParser.takeCompletedBlocks")
struct OSC133CommandParserDrainTests {
private func esc(_ body: String) -> String { "\u{1b}]\(body)\u{07}" }
private func mark(_ k: String) -> String { esc("133;\(k)") }

@Test("drains finished blocks and empties when nothing is open")
func drainsFinished() {
var parser = OSC133CommandParser()
parser.consume(mark("A") + mark("B") + "ls" + mark("C") + "out\n" + mark("D;0"))
parser.consume(mark("A") + mark("B") + "pwd" + mark("C") + "/tmp\n" + mark("D;0"))

let drained = parser.takeCompletedBlocks()
#expect(drained.map(\.command) == ["ls", "pwd"])
#expect(parser.blocks.isEmpty)
}

@Test("keeps the still-open block and continues streaming into it")
func keepsOpenBlock() {
var parser = OSC133CommandParser()
parser.consume(mark("A") + mark("B") + "ls" + mark("C") + "a\n" + mark("D;0"))
parser.consume(mark("A") + mark("B") + "sleep 5" + mark("C") + "work")

let drained = parser.takeCompletedBlocks()
#expect(drained.map(\.command) == ["ls"])
#expect(parser.blocks.count == 1)
#expect(parser.blocks[0].command == "sleep 5")
#expect(parser.blocks[0].isRunning)

// More output for the kept-open block still lands on it…
parser.consume("ing\n" + mark("D;0"))
#expect(parser.blocks[0].output == "working\n")
#expect(parser.blocks[0].isRunning == false)
}

@Test("ids stay unique across drains")
func idsStayUniqueAcrossDrains() {
var parser = OSC133CommandParser()
parser.consume(mark("A") + mark("B") + "one" + mark("C") + mark("D;0"))
let first = parser.takeCompletedBlocks()

parser.consume(mark("A") + mark("B") + "two" + mark("C") + mark("D;0"))
let second = parser.takeCompletedBlocks()

#expect(first.count == 1)
#expect(second.count == 1)
#expect(first[0].id != second[0].id)
}

@Test("draining an empty parser returns nothing")
func drainEmpty() {
var parser = OSC133CommandParser()
#expect(parser.takeCompletedBlocks().isEmpty)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Foundation

/// Settings for session restore and per-tab shell history, the `session.*`
/// keys. Both are JSON-backed so they can be edited directly in
/// `~/.config/cmux/cmux.json`.
public struct SessionCatalogSection: SettingCatalogSection {
/// How a previously saved session is handled on launch: `always`
/// (restore silently), `ask` (prompt first; the default), or `never`
/// (start fresh, leaving the session reopenable from the File menu).
///
/// ```json
/// { "session": { "restoreMode": "ask" } }
/// ```
public let restoreMode = JSONKey<SessionRestoreMode>(
id: "session.restoreMode",
defaultValue: .ask
)

/// Whether each terminal tab keeps its own shell history (up-arrow /
/// Ctrl-R recall) namespaced by project directory, plus a recorded cmux
/// command history per tab. When off, tabs use the shell's normal global
/// history.
///
/// ```json
/// { "session": { "persistShellHistory": true } }
/// ```
public let persistShellHistory = JSONKey<Bool>(
id: "session.persistShellHistory",
defaultValue: true
)

public init() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public struct SettingCatalog: SettingCatalogSection {
public let shortcuts = KeyboardShortcutsCatalogSection()
public let integrations = IntegrationsCatalogSection()
public let account = AccountCatalogSection()
/// Settings for session restore and per-tab shell history (the `session.*` keys).
public let session = SessionCatalogSection()

public init() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Foundation

/// How cmux handles a previously saved session when it launches.
///
/// Stored under the catalog entry ``SessionCatalogSection/restoreMode``
/// (`session.restoreMode` in `~/.config/cmux/cmux.json`). The raw values are
/// the on-disk strings, so they must not be renamed without a migration.
public enum SessionRestoreMode: String, CaseIterable, Sendable, SettingCodable {
/// Silently restore the previous windows, tabs, and panes on launch
/// (the historical cmux behavior).
case always

/// Prompt before restoring; the user chooses Restore or Start Fresh.
/// This is the default.
case ask

/// Never restore automatically; start with a fresh window. The previous
/// session stays reopenable from File ▸ Reopen Previous Session.
case never
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import Foundation
import Testing
@testable import CmuxSettings

/// Behavior of the `session.*` settings through the real JSON store: the
/// defaults users get out of the box (restore = ask, per-tab shell history
/// on), hand-edited values, unknown fallbacks, and the synchronous
/// ``JSONConfigStore/snapshotValue(for:)`` read used at launch and spawn time.
@Suite("session.*")
struct SessionSettingsTests {
private func makeStore() -> (JSONConfigStore, URL) {
let tempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("cmux-session-tests-\(UUID().uuidString)", isDirectory: true)
try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL = tempDir.appendingPathComponent("cmux.json", isDirectory: false)
return (JSONConfigStore(fileURL: fileURL), fileURL)
}

@Test func restoreModeDefaultsToAsk() async {
#expect(SettingCatalog().session.restoreMode.defaultValue == .ask)
let (store, _) = makeStore()
let value = await store.value(for: SettingCatalog().session.restoreMode)
#expect(value == .ask)
}

@Test func persistShellHistoryDefaultsToTrue() async {
#expect(SettingCatalog().session.persistShellHistory.defaultValue == true)
let (store, _) = makeStore()
let value = await store.value(for: SettingCatalog().session.persistShellHistory)
#expect(value == true)
}

@Test func readsEachRestoreModeFromHandEditedConfigFile() async throws {
for raw in ["always", "ask", "never"] {
let (store, fileURL) = makeStore()
try "{ \"session\": { \"restoreMode\": \"\(raw)\" } }"
.write(to: fileURL, atomically: true, encoding: .utf8)
let value = await store.value(for: SettingCatalog().session.restoreMode)
#expect(value == SessionRestoreMode(rawValue: raw))
}
}

@Test func unknownRestoreModeFallsBackToAsk() async throws {
let (store, fileURL) = makeStore()
try #"{ "session": { "restoreMode": "yolo" } }"#
.write(to: fileURL, atomically: true, encoding: .utf8)
let value = await store.value(for: SettingCatalog().session.restoreMode)
#expect(value == .ask)
}

@Test func persistShellHistoryReadsFalseFromConfigFile() async throws {
let (store, fileURL) = makeStore()
try #"{ "session": { "persistShellHistory": false } }"#
.write(to: fileURL, atomically: true, encoding: .utf8)
let value = await store.value(for: SettingCatalog().session.persistShellHistory)
#expect(value == false)
}

@Test func roundTripsRestoreModeThroughTheStore() async throws {
let (store, fileURL) = makeStore()
try await store.set(.never, for: SettingCatalog().session.restoreMode)
let value = await store.value(for: SettingCatalog().session.restoreMode)
#expect(value == .never)

// The on-disk representation is the raw string, hand-editable.
let parsed = try JSONSerialization.jsonObject(with: Data(contentsOf: fileURL)) as? [String: Any]
let section = parsed?["session"] as? [String: Any]
#expect(section?["restoreMode"] as? String == "never")
}

/// The launch/spawn paths read these keys synchronously off the main
/// actor via ``JSONConfigStore/snapshotValue(for:)``; confirm it observes
/// hand-edited values and the defaults.
@Test func snapshotValueReadsSynchronously() async throws {
let (store, fileURL) = makeStore()
#expect(store.snapshotValue(for: SettingCatalog().session.restoreMode) == .ask)
#expect(store.snapshotValue(for: SettingCatalog().session.persistShellHistory) == true)

try #"{ "session": { "restoreMode": "never", "persistShellHistory": false } }"#
.write(to: fileURL, atomically: true, encoding: .utf8)
#expect(store.snapshotValue(for: SettingCatalog().session.restoreMode) == .never)
#expect(store.snapshotValue(for: SettingCatalog().session.persistShellHistory) == false)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public enum SettingsSectionID: String, CaseIterable, Identifiable, Sendable, Has
case account
case app
case terminal
/// Session restore behavior and per-tab shell history.
case session
case textBox
/// Mobile pairing and sync settings.
case mobile
Expand All @@ -37,6 +39,7 @@ public enum SettingsSectionID: String, CaseIterable, Identifiable, Sendable, Has
case .account: return "Account"
case .app: return "App"
case .terminal: return "Terminal"
case .session: return String(localized: "settings.section.session", defaultValue: "Sessions")
case .textBox: return String(localized: "settings.section.textBox", defaultValue: "TextBox (Beta)")
case .mobile: return String(localized: "settings.section.mobile", defaultValue: "Mobile")
case .sidebarAppearance: return "Sidebar"
Expand All @@ -59,6 +62,7 @@ public enum SettingsSectionID: String, CaseIterable, Identifiable, Sendable, Has
case .account: return "person.crop.circle"
case .app: return "gearshape"
case .terminal: return "terminal"
case .session: return "clock.arrow.circlepath"
case .textBox: return "textformat"
case .mobile: return "iphone"
case .sidebarAppearance: return "sidebar.left"
Expand All @@ -83,6 +87,7 @@ public enum SettingsSectionID: String, CaseIterable, Identifiable, Sendable, Has
case .account: return "sign in team sync user profile"
case .app: return "appearance language workspace notifications menu bar telemetry"
case .terminal: return "scrollbar copy on select agent resume hibernation"
case .session: return "session restore reopen previous launch shell history histfile per tab project command history ask always never"
case .textBox: return "textbox text box rich input prompt default new terminal workspace split tab focus show beta"
case .mobile: return "ios iphone ipad mobile pairing local network sync"
case .sidebarAppearance: return "sidebar details branches material terminal background"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ public struct SettingsWindowRoot: View {
@ViewBuilder
private var sectionStack: some View {
// Order matches the legacy in-app SettingsView scroll order:
// Account, App, Terminal, TextBox, Mobile, Sidebar, Beta Features,
// Automation, Browser (with embedded Import), Global Hotkey,
// Account, App, Terminal, Sessions, TextBox, Mobile, Sidebar, Beta
// Features, Automation, Browser (with embedded Import), Global Hotkey,
// Keyboard Shortcuts, Workspace Colors, cmux.json, Reset.
AccountSection(
defaultsStore: defaultsStore,
Expand All @@ -451,6 +451,13 @@ public struct SettingsWindowRoot: View {
)
.id(anchorID(for: .terminal))

SessionSection(
jsonStore: jsonStore,
catalog: catalog,
errorLog: runtime.errorLog
)
.id(anchorID(for: .session))

TextBoxSection(defaultsStore: defaultsStore, catalog: catalog)
.id(anchorID(for: .textBox))

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import CmuxSettings
import SwiftUI

/// **Sessions** section — controls how cmux restores a previous session on
/// launch and whether each terminal tab keeps its own persistent shell
/// history (grouped by project). Both settings are JSON-backed
/// (`session.*` in `~/.config/cmux/cmux.json`).
@MainActor
public struct SessionSection: View {
@State private var restoreMode: JSONValueModel<SessionRestoreMode>
@State private var persistShellHistory: JSONValueModel<Bool>

public init(
jsonStore: JSONConfigStore,
catalog: SettingCatalog,
errorLog: SettingsErrorLog
) {
_restoreMode = State(initialValue: JSONValueModel(
store: jsonStore,
key: catalog.session.restoreMode,
errorLog: errorLog
))
_persistShellHistory = State(initialValue: JSONValueModel(
store: jsonStore,
key: catalog.session.persistShellHistory,
errorLog: errorLog
))
}

public var body: some View {
Group {
SettingsSectionHeader(String(localized: "settings.section.session", defaultValue: "Sessions"), section: .session)
SettingsCard {
restoreModeRow
SettingsCardDivider()
persistShellHistoryRow
}
}
.task { startObservingSettings() }
}

private func startObservingSettings() {
let models: [any SettingObservationStarting] = [
restoreMode,
persistShellHistory,
]
models.forEach { $0.startObserving() }
}

@ViewBuilder
private var restoreModeRow: some View {
SettingsCardRow(
configurationReview: .json("session.restoreMode"),
String(localized: "settings.session.restoreMode", defaultValue: "Restore Previous Session"),
subtitle: restoreMode.current.modeDescription
) {
Picker("", selection: Binding(get: { restoreMode.current }, set: { restoreMode.set($0) })) {
ForEach(SessionRestoreMode.uiCases, id: \.self) { mode in
Text(mode.displayName).tag(mode)
}
}
.labelsHidden()
.pickerStyle(.menu)
.accessibilityIdentifier("SettingsSessionRestoreModePicker")
}
}

@ViewBuilder
private var persistShellHistoryRow: some View {
SettingsCardRow(
configurationReview: .json("session.persistShellHistory"),
String(localized: "settings.session.persistShellHistory", defaultValue: "Per-Tab Shell History"),
subtitle: persistShellHistory.current
? String(localized: "settings.session.persistShellHistory.subtitleOn", defaultValue: "Each tab keeps its own command history (up-arrow / Ctrl-R), grouped by project, and records a cmux command history.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 User-facing copy misrepresents the history key

The subtitle says "grouped by project" but the implementation keys history by surface UUID (not by working directory). The PR description explicitly states: "Keyed by surface UUID — not working directory — because a tab's cwd is not stable between first open and restore." A user who opens a second tab in the same project directory will find it starts with empty history, directly contradicting the "grouped by project" wording. The same incorrect description appears in web/messages/en.json:960 ("namespaced by project directory") and in the SessionCatalogSection doc-comment. All three occurrences should be corrected to describe the actual behavior: each tab retains its own history across session restores via its stable surface ID.

Rule Used: Flag production user-facing text that is not fully... (source)

: String(localized: "settings.session.persistShellHistory.subtitleOff", defaultValue: "Tabs use your shell's normal global history (e.g. ~/.zsh_history).")
) {
Toggle("", isOn: Binding(get: { persistShellHistory.current }, set: { persistShellHistory.set($0) }))
.labelsHidden()
.controlSize(.small)
.accessibilityIdentifier("SettingsSessionPersistShellHistoryToggle")
}
}
}
Loading