From 11f450a0e2b9fa8e4be0907a0dcab12a7eff6f3c Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 04:19:39 -0700 Subject: [PATCH 01/24] Add command variables and folder organization to custom commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the two improvements requested in #6557 for cmux.json `commands`: 1. Variables — `{{variable}}` (and `{{variable=default}}`) placeholders in a command's `command` string. cmux prompts for each value before running and substitutes them back in. Wired into the single `CmuxConfigExecutor.prepareShellInputIfAuthorized` choke point so every entrypoint (Command Palette, surface tab-bar buttons, dock) gets prompting without per-surface duplication. New `CmuxCommandVariableParser` does the shell-safe parsing/substitution; `CmuxCommandVariablePrompt` shows the inline NSAlert prompt. 2. Folder organization — a `folder` key (e.g. "Project/Linting") groups a command in the Command Palette. The breadcrumb shows as the row's trailing badge and feeds the search corpus/keywords so you can filter by folder. Also updates the JSON schema, the custom-commands docs page (all web locales), and adds Localizable.xcstrings entries for the prompt across all locales. Tests: CmuxCommandVariableTests covers parsing, de-duplication, shell-safety, substitution, folder normalization, and palette resolution. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 4 +- .../CommandPaletteCommandContribution.swift | 5 + Resources/Localizable.xcstrings | 375 ++++++++++++++++++ Sources/CmuxCommandVariablePrompt.swift | 140 +++++++ Sources/CmuxCommandVariables.swift | 132 ++++++ Sources/CmuxConfig.swift | 48 ++- Sources/CmuxConfigExecutor.swift | 58 +++ Sources/ContentView.swift | 6 +- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/CmuxCommandVariableTests.swift | 189 +++++++++ .../[locale]/docs/custom-commands/page.tsx | 14 + web/data/cmux.schema.json | 34 +- web/messages/ar.json | 6 +- web/messages/bs.json | 6 +- web/messages/da.json | 6 +- web/messages/de.json | 6 +- web/messages/en.json | 6 +- web/messages/es.json | 6 +- web/messages/fr.json | 6 +- web/messages/it.json | 6 +- web/messages/ja.json | 6 +- web/messages/km.json | 6 +- web/messages/ko.json | 6 +- web/messages/no.json | 6 +- web/messages/pl.json | 6 +- web/messages/pt-BR.json | 6 +- web/messages/ru.json | 6 +- web/messages/th.json | 6 +- web/messages/tr.json | 6 +- web/messages/uk.json | 6 +- web/messages/zh-CN.json | 6 +- web/messages/zh-TW.json | 6 +- 32 files changed, 1100 insertions(+), 29 deletions(-) create mode 100644 Sources/CmuxCommandVariablePrompt.swift create mode 100644 Sources/CmuxCommandVariables.swift create mode 100644 cmuxTests/CmuxCommandVariableTests.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 7b3ae3f3ab43..bea9f0dca844 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3397 Sources/CmuxConfig.swift +3435 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift @@ -214,7 +214,7 @@ 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift -519 Sources/CmuxConfigExecutor.swift +577 Sources/CmuxConfigExecutor.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 diff --git a/Packages/macOS/CmuxCommandPalette/Sources/CmuxCommandPalette/Handling/CommandPaletteCommandContribution.swift b/Packages/macOS/CmuxCommandPalette/Sources/CmuxCommandPalette/Handling/CommandPaletteCommandContribution.swift index f2bfc7a28296..5177b6526d0e 100644 --- a/Packages/macOS/CmuxCommandPalette/Sources/CmuxCommandPalette/Handling/CommandPaletteCommandContribution.swift +++ b/Packages/macOS/CmuxCommandPalette/Sources/CmuxCommandPalette/Handling/CommandPaletteCommandContribution.swift @@ -12,6 +12,9 @@ public struct CommandPaletteCommandContribution { public let subtitle: (CommandPaletteContextSnapshot) -> String /// Optional keyboard-shortcut hint. public let shortcutHint: String? + /// Optional trailing "kind" badge (e.g. a custom command's folder + /// breadcrumb). Only shown when there is no `shortcutHint`. + public let kindLabel: String? /// Additional search keywords. public let keywords: [String] /// Whether activating the command dismisses the palette. @@ -27,6 +30,7 @@ public struct CommandPaletteCommandContribution { title: @escaping (CommandPaletteContextSnapshot) -> String, subtitle: @escaping (CommandPaletteContextSnapshot) -> String, shortcutHint: String? = nil, + kindLabel: String? = nil, keywords: [String] = [], dismissOnRun: Bool = true, when: @escaping (CommandPaletteContextSnapshot) -> Bool = { _ in true }, @@ -36,6 +40,7 @@ public struct CommandPaletteCommandContribution { self.title = title self.subtitle = subtitle self.shortcutHint = shortcutHint + self.kindLabel = kindLabel self.keywords = keywords self.dismissOnRun = dismissOnRun self.when = when diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 2fc5cd11de10..d0671812f1b2 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -212710,6 +212710,381 @@ } } } + }, + "dialog.cmuxConfig.commandVariables.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "إدخال متغيرات الأمر" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Unesite varijable komande" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Indtast kommandovariabler" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Befehlsvariablen eingeben" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter Command Variables" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Introducir variables del comando" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Saisir les variables de la commande" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Inserisci le variabili del comando" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "コマンド変数を入力" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បញ្ចូលអថេរពាក្យបញ្ជា" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "명령 변수 입력" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Skriv inn kommandovariabler" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Wprowadź zmienne polecenia" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Inserir variáveis do comando" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Введите переменные команды" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ป้อนตัวแปรของคำสั่ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Komut değişkenlerini girin" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "输入命令变量" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "輸入命令變數" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Введіть змінні команди" + } + } + } + }, + "dialog.cmuxConfig.commandVariables.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "أدخل قيم هذا الأمر قبل التشغيل." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Popunite vrijednosti za ovu komandu prije pokretanja." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udfyld værdierne for denne kommando, før du kører den." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Geben Sie die Werte für diesen Befehl vor der Ausführung ein." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Fill in the values for this command before running." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Completa los valores de este comando antes de ejecutarlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Renseignez les valeurs de cette commande avant de l'exécuter." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Inserisci i valori per questo comando prima di eseguirlo." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "実行する前に、このコマンドの値を入力してください。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បំពេញតម្លៃសម្រាប់ពាក្យបញ្ជានេះមុនពេលដំណើរការ។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "실행하기 전에 이 명령의 값을 입력하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fyll inn verdiene for denne kommandoen før du kjører den." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Wprowadź wartości dla tego polecenia przed uruchomieniem." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Preencha os valores deste comando antes de executá-lo." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Введите значения для этой команды перед запуском." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "กรอกค่าสำหรับคำสั่งนี้ก่อนเรียกใช้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Çalıştırmadan önce bu komutun değerlerini girin." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "运行前请填写此命令的值。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "執行前請填入此命令的值。" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Введіть значення для цієї команди перед запуском." + } + } + } + }, + "dialog.cmuxConfig.commandVariables.run": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تشغيل" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Pokreni" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Kør" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Ausführen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Run" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ejecutar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Exécuter" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Esegui" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "実行" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ដំណើរការ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "실행" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Kjør" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Uruchom" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Executar" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Выполнить" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "รัน" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Çalıştır" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "运行" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "執行" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Виконати" + } + } + } } } } diff --git a/Sources/CmuxCommandVariablePrompt.swift b/Sources/CmuxCommandVariablePrompt.swift new file mode 100644 index 000000000000..dadbf2811f04 --- /dev/null +++ b/Sources/CmuxCommandVariablePrompt.swift @@ -0,0 +1,140 @@ +import AppKit +import Foundation + +/// Presents an inline prompt asking the user to fill in the `{{variable}}` +/// placeholders of a custom command before it runs. +/// +/// The prompt is an `NSAlert` with an accessory view of labeled text fields — +/// one per variable — matching the look of the existing project-action confirm +/// dialog in ``CmuxConfigExecutor``. Because every command entrypoint (Command +/// Palette, surface tab-bar buttons, dock, …) funnels shell commands through +/// ``CmuxConfigExecutor/prepareShellInputIfAuthorized(_:confirm:actionID:target:configSourcePath:globalConfigPath:displayTitle:icon:iconSourcePath:presentingWindow:onAuthorized:)``, +/// wiring the prompt there gives variable support to all of them at once. +@MainActor +enum CmuxCommandVariablePrompt { + /// Presents the variable prompt and invokes `completion` with the collected + /// `[name: value]` map when the user confirms. Cancelling does nothing. + /// + /// - Returns: `true` once the prompt has been presented (always, given a + /// non-empty `variables`). When `variables` is empty the completion runs + /// immediately with an empty map. + @discardableResult + static func present( + variables: [CmuxCommandVariable], + displayTitle: String?, + presentingWindow: NSWindow?, + completion: @escaping ([String: String]) -> Void + ) -> Bool { + guard !variables.isEmpty else { + completion([:]) + return true + } + + let alert = NSAlert() + let trimmedTitle = displayTitle?.trimmingCharacters(in: .whitespacesAndNewlines) + alert.messageText = (trimmedTitle?.isEmpty == false) + ? trimmedTitle! + : String( + localized: "dialog.cmuxConfig.commandVariables.title", + defaultValue: "Enter Command Variables" + ) + alert.informativeText = String( + localized: "dialog.cmuxConfig.commandVariables.message", + defaultValue: "Fill in the values for this command before running." + ) + alert.addButton(withTitle: String( + localized: "dialog.cmuxConfig.commandVariables.run", + defaultValue: "Run" + )) + alert.addButton(withTitle: String( + localized: "common.cancel", + defaultValue: "Cancel" + )) + + let fields = makeFields(for: variables) + alert.accessoryView = makeAccessoryView(variables: variables, fields: fields) + alert.layout() + if let firstField = fields.first { + alert.window.initialFirstResponder = firstField + } + + let handler: (NSApplication.ModalResponse) -> Void = { response in + guard response == .alertFirstButtonReturn else { return } + var values: [String: String] = [:] + for (variable, field) in zip(variables, fields) { + values[variable.name] = field.stringValue + } + completion(values) + } + + if let presentingWindow { + alert.beginSheetModal(for: presentingWindow, completionHandler: handler) + } else { + handler(alert.runModal()) + } + return true + } + + // MARK: - Accessory layout + + private static let fieldWidth: CGFloat = 320 + private static let labelHeight: CGFloat = 15 + private static let inputHeight: CGFloat = 22 + private static let labelToInputGap: CGFloat = 3 + private static let rowGap: CGFloat = 10 + + private static func makeFields(for variables: [CmuxCommandVariable]) -> [NSTextField] { + variables.map { variable in + let field = NSTextField(string: variable.defaultValue ?? "") + field.placeholderString = variable.name + field.translatesAutoresizingMaskIntoConstraints = true + field.lineBreakMode = .byTruncatingTail + field.isEditable = true + field.isSelectable = true + return field + } + } + + private static func makeAccessoryView( + variables: [CmuxCommandVariable], + fields: [NSTextField] + ) -> NSView { + let rowHeight = labelHeight + labelToInputGap + inputHeight + let totalHeight = CGFloat(variables.count) * rowHeight + + CGFloat(max(0, variables.count - 1)) * rowGap + let container = FlippedView( + frame: NSRect(x: 0, y: 0, width: fieldWidth, height: totalHeight) + ) + + var y: CGFloat = 0 + for (variable, field) in zip(variables, fields) { + let label = NSTextField(labelWithString: variable.name) + label.font = NSFont.systemFont(ofSize: 11, weight: .semibold) + label.textColor = .secondaryLabelColor + label.lineBreakMode = .byTruncatingTail + label.frame = NSRect(x: 0, y: y, width: fieldWidth, height: labelHeight) + container.addSubview(label) + + field.frame = NSRect( + x: 0, + y: y + labelHeight + labelToInputGap, + width: fieldWidth, + height: inputHeight + ) + container.addSubview(field) + + y += rowHeight + rowGap + } + + // Tab order: walk the fields top-to-bottom, then loop back to the first. + for index in fields.indices { + fields[index].nextKeyView = fields[(index + 1) % fields.count] + } + + return container + } + + private final class FlippedView: NSView { + override var isFlipped: Bool { true } + } +} diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift new file mode 100644 index 000000000000..d0a017f5e54c --- /dev/null +++ b/Sources/CmuxCommandVariables.swift @@ -0,0 +1,132 @@ +import Foundation + +/// A `{{name}}` (or `{{name=default}}`) placeholder discovered in a custom +/// command's `command` string. +/// +/// Variables let a single `commands` entry be reused with different values: +/// cmux prompts for each variable before running the command and substitutes +/// the entered values back into the shell string. The syntax intentionally +/// matches the existing `{{…}}` convention already used by Vault agent +/// templates so users only have to learn one placeholder form. +struct CmuxCommandVariable: Equatable, Sendable { + /// The placeholder name, e.g. `environment` for `{{environment}}`. + let name: String + /// The optional default value parsed from `{{name=default}}`, used to + /// pre-fill the prompt field. `nil` when the placeholder has no default. + let defaultValue: String? +} + +/// Parses and substitutes `{{variable}}` placeholders inside custom command +/// strings. +/// +/// Grammar (kept deliberately small and shell-safe): +/// - A placeholder is `{{` … `}}` whose inner text contains no `{`, `}`, or +/// newline. +/// - The name is the text before the first `=`; an optional default value is +/// the text after it. Both are trimmed of surrounding whitespace. +/// - A name must be non-empty and contain only letters, digits, spaces, or +/// `_ - .`. Anything else (`$`, `(`, `/`, `|`, …) makes the braces literal so +/// ordinary shell snippets that happen to use `{{` are never mistaken for a +/// variable. +enum CmuxCommandVariableParser { + /// Returns the ordered, de-duplicated variables found in `command`, + /// preserving first-occurrence order. When the same name appears more than + /// once, the first occurrence's default value wins. + static func variables(in command: String) -> [CmuxCommandVariable] { + var seen = Set() + var result: [CmuxCommandVariable] = [] + for match in matches(in: command) where seen.insert(match.name).inserted { + result.append(CmuxCommandVariable(name: match.name, defaultValue: match.defaultValue)) + } + return result + } + + /// Whether `command` contains at least one recognized variable placeholder. + static func containsVariables(_ command: String) -> Bool { + for _ in matches(in: command) { return true } + return false + } + + /// Replaces every recognized placeholder whose name is present in `values` + /// with the corresponding value. Placeholders whose name is missing from + /// `values` are left untouched so partial maps never corrupt the command. + static func substitute(_ command: String, values: [String: String]) -> String { + let found = matches(in: command) + guard !found.isEmpty else { return command } + var result = "" + result.reserveCapacity(command.count) + var cursor = command.startIndex + for match in found { + result.append(contentsOf: command[cursor.. + let name: String + let defaultValue: String? + } + + private static let allowedNameCharacters: CharacterSet = CharacterSet.alphanumerics + .union(CharacterSet(charactersIn: "_-. ")) + + private static func matches(in command: String) -> [Match] { + var matches: [Match] = [] + var index = command.startIndex + let end = command.endIndex + while index < end { + guard let open = command.range(of: "{{", range: index.. (name: String, defaultValue: String?)? { + if let equals = inner.firstIndex(of: "=") { + let name = inner[.. Bool { + guard !name.isEmpty else { return false } + return name.unicodeScalars.allSatisfy { allowedNameCharacters.contains($0) } + } +} diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index b72416ab9da3..895c0ffecc7c 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -1486,6 +1486,9 @@ struct CmuxResolvedConfigAction: Identifiable, Sendable, Hashable { var terminalCommandTarget: CmuxConfigTerminalCommandTarget? var actionSourcePath: String? var iconSourcePath: String? + /// Optional Command Palette folder breadcrumb (e.g. `Project / Linting`), + /// shown as the row's trailing badge for folder-organized custom commands. + var folder: String? var terminalCommand: String? { action.terminalCommand @@ -1617,11 +1620,31 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { var workspace: CmuxWorkspaceDefinition? var command: String? var confirm: Bool? + /// Optional `/`-separated folder path used to group the command in the + /// Command Palette (e.g. `"Project/Linting"`). Purely organizational. + var folder: String? var id: String { "cmux.config.command." + (name.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? name) } + /// The trimmed, non-empty components of ``folder`` split on `/`. + var folderComponents: [String] { + guard let folder else { return [] } + return folder + .split(separator: "/", omittingEmptySubsequences: true) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } + + /// A human-readable breadcrumb for ``folderComponents`` (e.g. `Project / Linting`), + /// or `nil` when the command has no usable folder. + var folderBreadcrumb: String? { + let components = folderComponents + guard !components.isEmpty else { return nil } + return components.joined(separator: " / ") + } + init( name: String, description: String? = nil, @@ -1629,7 +1652,8 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { restart: CmuxRestartBehavior? = nil, workspace: CmuxWorkspaceDefinition? = nil, command: String? = nil, - confirm: Bool? = nil + confirm: Bool? = nil, + folder: String? = nil ) { self.name = name self.description = description @@ -1638,6 +1662,7 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { self.workspace = workspace self.command = command self.confirm = confirm + self.folder = folder } init(from decoder: Decoder) throws { @@ -1649,6 +1674,7 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { workspace = try container.decodeIfPresent(CmuxWorkspaceDefinition.self, forKey: .workspace) command = try container.decodeIfPresent(String.self, forKey: .command) confirm = try container.decodeIfPresent(Bool.self, forKey: .confirm) + folder = try container.decodeIfPresent(String.self, forKey: .folder) if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { throw DecodingError.dataCorrupted( @@ -2474,15 +2500,26 @@ final class CmuxConfigStore: ObservableObject { for command in commands where registry[command.id] == nil { let sourcePath = commandSourcePaths[command.id] + let folderBreadcrumb = command.folderBreadcrumb.map { sanitizeConfigText($0) } + let sanitizedDescription = command.description.map { sanitizeConfigText($0) } + let subtitle: String + if let folderBreadcrumb { + // Fold the breadcrumb into the subtitle so the folder path is + // searchable and discoverable alongside any description. + subtitle = sanitizedDescription.map { "\(folderBreadcrumb) · \($0)" } ?? folderBreadcrumb + } else { + subtitle = sanitizedDescription + ?? String(localized: "command.cmuxConfig.subtitle", defaultValue: "cmux.json") + } + let folderKeywords = command.folderComponents.map { sanitizeConfigText($0) } registry[command.id] = CmuxResolvedConfigAction( id: command.id, title: String( localized: "command.cmuxConfig.customTitle", defaultValue: "Custom: \(sanitizeConfigText(command.name))" ), - subtitle: command.description.map { sanitizeConfigText($0) } - ?? String(localized: "command.cmuxConfig.subtitle", defaultValue: "cmux.json"), - keywords: command.keywords ?? [], + subtitle: subtitle, + keywords: (command.keywords ?? []) + folderKeywords, palette: true, shortcut: nil, icon: .symbol(command.workspace == nil ? "terminal" : "rectangle.stack.badge.plus"), @@ -2493,7 +2530,8 @@ final class CmuxConfigStore: ObservableObject { confirm: command.confirm, terminalCommandTarget: command.workspace == nil ? .currentTerminal : nil, actionSourcePath: sourcePath, - iconSourcePath: nil + iconSourcePath: nil, + folder: folderBreadcrumb ) } diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index de34b48dbfcd..9bc8563e608a 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -134,6 +134,64 @@ struct CmuxConfigExecutor { iconSourcePath: String? = nil, presentingWindow: NSWindow? = nil, onAuthorized: @escaping (String) -> Void + ) -> Bool { + // Resolve any `{{variable}}` placeholders before authorizing/dispatching. + // This single choke point feeds every command entrypoint (palette, + // surface tab-bar buttons, dock, …), so the prompt applies to all of + // them without per-surface duplication. + let variables = CmuxCommandVariableParser.variables(in: rawCommand) + guard !variables.isEmpty else { + return authorizeSanitizedShellCommand( + rawCommand, + confirm: confirm, + actionID: actionID, + target: target, + configSourcePath: configSourcePath, + globalConfigPath: globalConfigPath, + displayTitle: displayTitle, + icon: icon, + iconSourcePath: iconSourcePath, + presentingWindow: presentingWindow, + onAuthorized: onAuthorized + ) + } + + let resolvedWindow = presentingWindow ?? NSApp.keyWindow ?? NSApp.mainWindow + return CmuxCommandVariablePrompt.present( + variables: variables, + displayTitle: displayTitle, + presentingWindow: resolvedWindow + ) { values in + let substituted = CmuxCommandVariableParser.substitute(rawCommand, values: values) + _ = authorizeSanitizedShellCommand( + substituted, + confirm: confirm, + actionID: actionID, + target: target, + configSourcePath: configSourcePath, + globalConfigPath: globalConfigPath, + displayTitle: displayTitle, + icon: icon, + iconSourcePath: iconSourcePath, + presentingWindow: resolvedWindow, + onAuthorized: onAuthorized + ) + } + } + + @discardableResult + private static func authorizeSanitizedShellCommand( + _ rawCommand: String, + confirm: Bool, + actionID: String, + target: CmuxConfigTerminalCommandTarget, + configSourcePath: String?, + globalConfigPath: String, + displayTitle: String?, + icon: CmuxButtonIcon?, + iconSourcePath: String?, + presentingWindow: NSWindow?, + onAuthorized: @escaping (String) -> Void ) -> Bool { let shellCommand = sanitizeForDisplay(rawCommand) guard !shellCommand.isEmpty else { return false } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index ac3cff00d88b..7cd477fb5c1c 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -6037,7 +6037,7 @@ struct ContentView: View { title: configuredPaletteAction?.title ?? contribution.title(context), subtitle: configuredPaletteAction?.subtitle ?? contribution.subtitle(context), shortcutHint: commandPaletteShortcutHint(for: contribution, context: context), - kindLabel: nil, + kindLabel: contribution.kindLabel, keywords: configuredPaletteAction?.keywords.isEmpty == false ? configuredPaletteAction?.keywords ?? contribution.keywords : contribution.keywords, @@ -7451,11 +7451,15 @@ struct ContentView: View { .map { sanitizeCmuxConfigPaletteText($0) } .flatMap { $0.isEmpty ? nil : $0 } ?? cmuxConfigDefaultSubtitle + let folderLabel = action.folder + .map { sanitizeCmuxConfigPaletteText($0) } + .flatMap { $0.isEmpty ? nil : $0 } contributions.append( CommandPaletteCommandContribution( commandId: action.id, title: constant(actionTitle), subtitle: constant(subtitleText), + kindLabel: folderLabel, keywords: action.keywords ) ) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 8da4291ed351..a296dc0df884 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -272,6 +272,7 @@ C0DE64950000000000000003 /* CMUXCLITestAssertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */; }; 5E55500000000000000000E3 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; 5E55500000000000000000E4 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; + C1A2B3C4D5E6F70800006557 /* CmuxCommandVariableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */; }; A5001650 /* CmuxConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001651 /* CmuxConfig.swift */; }; C0DEF0A40000000000000001 /* CmuxConfigContextMenuTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */; }; A5001652 /* CmuxConfigExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001653 /* CmuxConfigExecutor.swift */; }; @@ -1430,6 +1431,7 @@ C12985000000000000000003 /* CMUXCLISentryTelemetryRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISentryTelemetryRegressionTests.swift; sourceTree = ""; }; C0DE64950000000000000006 /* CMUXCLISessionsListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISessionsListTests.swift; sourceTree = ""; }; C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLITestAssertions.swift; sourceTree = ""; }; + C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariableTests.swift; sourceTree = ""; }; A5001651 /* CmuxConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfig.swift; sourceTree = ""; }; C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigContextMenuTests.swift; sourceTree = ""; }; A5001653 /* CmuxConfigExecutor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigExecutor.swift; sourceTree = ""; }; @@ -3425,6 +3427,7 @@ A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */, 10D684CFFB8CDEF89CE2D9E1 /* TabManagerSessionSnapshotTests.swift */, C1A2B3C4D5E6F70800000002 /* CmuxConfigTests.swift */, + C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */, C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */, E30750000000000000000005 /* CmuxConfigNamedColorTests.swift */, FE002001 /* FileExplorerRootResolverTests.swift */, @@ -4688,6 +4691,7 @@ C12985000000000000000004 /* CMUXCLISentryTelemetryRegressionTests.swift in Sources */, C0DE64950000000000000005 /* CMUXCLISessionsListTests.swift in Sources */, C0DE64950000000000000003 /* CMUXCLITestAssertions.swift in Sources */, + C1A2B3C4D5E6F70800006557 /* CmuxCommandVariableTests.swift in Sources */, C0DEF0A40000000000000001 /* CmuxConfigContextMenuTests.swift in Sources */, E30750000000000000000006 /* CmuxConfigNamedColorTests.swift in Sources */, C1A2B3C4D5E6F70800000001 /* CmuxConfigTests.swift in Sources */, diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift new file mode 100644 index 000000000000..8d42d9f041a8 --- /dev/null +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -0,0 +1,189 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +// MARK: - Variable parsing + +final class CmuxCommandVariableParserTests: XCTestCase { + + func testNoPlaceholdersReturnsEmpty() { + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "npm test"), []) + XCTAssertFalse(CmuxCommandVariableParser.containsVariables("npm test")) + } + + func testSinglePlaceholder() { + let vars = CmuxCommandVariableParser.variables(in: "bin/deploy --env {{environment}}") + XCTAssertEqual(vars, [CmuxCommandVariable(name: "environment", defaultValue: nil)]) + XCTAssertTrue(CmuxCommandVariableParser.containsVariables("bin/deploy --env {{environment}}")) + } + + func testPlaceholderWithDefault() { + let vars = CmuxCommandVariableParser.variables(in: "bin/deploy --env {{environment=staging}}") + XCTAssertEqual(vars, [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) + } + + func testWhitespaceIsTrimmed() { + let vars = CmuxCommandVariableParser.variables(in: "echo {{ name }} {{ env = prod }}") + XCTAssertEqual( + vars, + [ + CmuxCommandVariable(name: "name", defaultValue: nil), + CmuxCommandVariable(name: "env", defaultValue: "prod"), + ] + ) + } + + func testMultipleDistinctPlaceholdersPreserveOrder() { + let command = "bin/deploy --env {{environment}} --branch {{branch}}" + let vars = CmuxCommandVariableParser.variables(in: command) + XCTAssertEqual(vars.map(\.name), ["environment", "branch"]) + } + + func testDuplicatePlaceholdersAreDeduplicatedKeepingFirstDefault() { + let command = "echo {{env=a}} && deploy {{env=b}}" + let vars = CmuxCommandVariableParser.variables(in: command) + XCTAssertEqual(vars, [CmuxCommandVariable(name: "env", defaultValue: "a")]) + } + + func testNameAllowsSpacesLettersDigitsAndPunctuation() { + let vars = CmuxCommandVariableParser.variables(in: "x {{branch name}} {{RAILS_ENV}} {{my.var}}") + XCTAssertEqual(vars.map(\.name), ["branch name", "RAILS_ENV", "my.var"]) + } + + func testEmptyPlaceholderIsIgnored() { + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{}} {{ }}"), []) + } + + func testShellSyntaxIsNotMistakenForVariables() { + // Names with shell-special characters keep the braces literal so + // ordinary shell snippets are never treated as variables. + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{ $(date) }}"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "awk '{{ print $1 | sort }}'"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{1+1}}"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{a/b}}"), []) + } + + func testNewlineInsidePlaceholderIsIgnored() { + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{na\nme}}"), []) + } + + // MARK: Substitution + + func testSubstituteReplacesEveryOccurrence() { + let result = CmuxCommandVariableParser.substitute( + "echo {{x}} and {{x}}", + values: ["x": "hi"] + ) + XCTAssertEqual(result, "echo hi and hi") + } + + func testSubstituteReplacesPlaceholderIncludingDefault() { + let result = CmuxCommandVariableParser.substitute( + "bin/deploy --env {{environment=staging}}", + values: ["environment": "production"] + ) + XCTAssertEqual(result, "bin/deploy --env production") + } + + func testSubstituteLeavesUnknownPlaceholdersIntact() { + let result = CmuxCommandVariableParser.substitute( + "{{a}}-{{b}}", + values: ["a": "x"] + ) + XCTAssertEqual(result, "x-{{b}}") + } + + func testSubstituteWithNoPlaceholdersReturnsInput() { + XCTAssertEqual( + CmuxCommandVariableParser.substitute("npm test", values: ["x": "y"]), + "npm test" + ) + } + + func testSubstitutePreservesValuesWithSpecialCharacters() { + let result = CmuxCommandVariableParser.substitute( + "git checkout {{branch}}", + values: ["branch": "feature/new-thing"] + ) + XCTAssertEqual(result, "git checkout feature/new-thing") + } +} + +// MARK: - Folder organization + +final class CmuxCommandFolderTests: XCTestCase { + + private func decode(_ json: String) throws -> CmuxConfigFile { + let data = json.data(using: .utf8)! + return try JSONDecoder().decode(CmuxConfigFile.self, from: data) + } + + func testDecodeFolderField() throws { + let config = try decode(""" + { + "commands": [{ + "name": "Lint modified files", + "folder": "Project/Linting", + "command": "bash lint.sh" + }] + } + """) + XCTAssertEqual(config.commands[0].folder, "Project/Linting") + XCTAssertEqual(config.commands[0].folderComponents, ["Project", "Linting"]) + XCTAssertEqual(config.commands[0].folderBreadcrumb, "Project / Linting") + } + + func testFolderComponentsTrimAndDropEmptySegments() { + let command = CmuxCommandDefinition( + name: "x", + command: "echo", + folder: " /Project// Linting /" + ) + XCTAssertEqual(command.folderComponents, ["Project", "Linting"]) + XCTAssertEqual(command.folderBreadcrumb, "Project / Linting") + } + + func testNilOrBlankFolderHasNoComponents() { + XCTAssertEqual(CmuxCommandDefinition(name: "x", command: "echo").folderComponents, []) + XCTAssertNil(CmuxCommandDefinition(name: "x", command: "echo").folderBreadcrumb) + let blank = CmuxCommandDefinition(name: "x", command: "echo", folder: " // ") + XCTAssertEqual(blank.folderComponents, []) + XCTAssertNil(blank.folderBreadcrumb) + } + + @MainActor + func testFolderSurfacesInResolvedPaletteAction() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-folder-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + let configURL = root.appendingPathComponent("cmux.json") + try """ + { + "commands": [{ + "name": "Lint modified files", + "folder": "Project/Linting", + "command": "bash lint.sh" + }] + } + """.write(to: configURL, atomically: true, encoding: .utf8) + + let store = CmuxConfigStore(globalConfigPath: configURL.path, startFileWatchers: false) + store.loadAll() + + let action = try XCTUnwrap( + store.paletteCustomActions().first { $0.title.contains("Lint modified files") } + ) + XCTAssertEqual(action.folder, "Project / Linting") + XCTAssertTrue(action.keywords.contains("Project")) + XCTAssertTrue(action.keywords.contains("Linting")) + XCTAssertEqual(action.subtitle, "Project / Linting") + } +} diff --git a/web/app/[locale]/docs/custom-commands/page.tsx b/web/app/[locale]/docs/custom-commands/page.tsx index 183c2fd4ec11..afc48651fbbb 100644 --- a/web/app/[locale]/docs/custom-commands/page.tsx +++ b/web/app/[locale]/docs/custom-commands/page.tsx @@ -335,10 +335,24 @@ export default function CustomCommandsPage() {
  • description: {t("fieldDescription")}
  • keywords: {t("fieldKeywords")}
  • command: {t("fieldCommand")}
  • +
  • folder: {t("fieldFolder")}
  • confirm: {t("fieldConfirm")}
  • {t("simpleCommandCwdNote")} {"cd \"$(git rev-parse --show-toplevel)\" &&"} {t("simpleCommandCwdRepoRoot")} {"cd /your/path &&"} {t("simpleCommandCwdCustomPath")}

    + {t("commandVariables")} +

    {t("commandVariablesDesc")}

    + {`{ + "commands": [ + { + "name": "Deploy", + "folder": "Project/Deploy", + "command": "bin/deploy --env {{environment}} --branch {{branch}}" + } + ] +}`} +

    {t("commandVariablesDefaultNote")}

    + {t("workspaceCommands")}

    {t("workspaceCommandsDesc")}

    {`{ diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 4e640706037b..021fcfd59893 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -36,7 +36,39 @@ "type": "array", "items": { "type": "object", - "additionalProperties": true + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Display name shown in the Command Palette." + }, + "description": { + "type": "string", + "description": "Optional subtitle shown beneath the name." + }, + "keywords": { + "type": "array", + "items": { "type": "string" }, + "description": "Extra search terms for the Command Palette." + }, + "command": { + "type": "string", + "description": "Shell command to run. Use {{variable}} placeholders (optionally {{variable=default}}) to prompt for values before running, for example \"bin/deploy --env {{environment}}\"." + }, + "folder": { + "type": "string", + "description": "Optional /-separated folder path used to group the command in the Command Palette, for example \"Project/Linting\"." + }, + "confirm": { + "type": "boolean", + "description": "Ask for confirmation before running the command." + }, + "workspace": { + "type": "object", + "additionalProperties": true, + "description": "Workspace layout to open instead of running a shell command. Mutually exclusive with command." + } + } } }, "vault": { diff --git a/web/messages/ar.json b/web/messages/ar.json index 589784af5be5..5f53bf115bfc 100644 --- a/web/messages/ar.json +++ b/web/messages/ar.json @@ -961,7 +961,11 @@ "absolutePath": "مسار مطلق", "cwdAbsolute": "يُستخدم كما هو", "fullExample": "مثال كامل", - "restartNew": "إنشاء مساحة عمل جديدة (الافتراضي)" + "restartNew": "إنشاء مساحة عمل جديدة (الافتراضي)", + "fieldFolder": "مسار مجلد اختياري مفصول بـ / (مثل Project/Linting) لتجميع الأمر في لوحة الأوامر", + "commandVariables": "متغيرات الأمر", + "commandVariablesDesc": "أضِف عناصر نائبة {{variable}} إلى الأمر، وسيطلب cmux إدخال كل قيمة قبل التشغيل. أعِد استخدام الاسم نفسه لتعبئته في عدة أماكن دفعة واحدة.", + "commandVariablesDefaultNote": "استخدم {{variable=default}} لملء المطالبة بقيمة افتراضية مسبقًا." }, "keyboardShortcuts": { "title": "اختصارات لوحة المفاتيح", diff --git a/web/messages/bs.json b/web/messages/bs.json index 24775c1e19f6..0edf9cd16971 100644 --- a/web/messages/bs.json +++ b/web/messages/bs.json @@ -961,7 +961,11 @@ "absolutePath": "Apsolutna putanja", "cwdAbsolute": "koristi se kao takvo", "fullExample": "Potpuni primjer", - "restartNew": "Kreiraj novi radni prostor (zadano)" + "restartNew": "Kreiraj novi radni prostor (zadano)", + "fieldFolder": "Opcionalna putanja foldera odvojena znakom / (npr. Project/Linting) koja grupira komandu u Komandnoj paleti", + "commandVariables": "Varijable komande", + "commandVariablesDesc": "Dodajte {{variable}} rezervirana mjesta u komandu i cmux će zatražiti svaku vrijednost prije pokretanja. Ponovo upotrijebite isti naziv da ga popunite na više mjesta odjednom.", + "commandVariablesDefaultNote": "Koristite {{variable=default}} da unaprijed popunite upit zadanom vrijednošću." }, "keyboardShortcuts": { "title": "Prečice na tastaturi", diff --git a/web/messages/da.json b/web/messages/da.json index 7d15a6bf7ff1..fbb93fd7ab5d 100644 --- a/web/messages/da.json +++ b/web/messages/da.json @@ -961,7 +961,11 @@ "absolutePath": "Absolut sti", "cwdAbsolute": "bruges som den er", "fullExample": "Fuldt eksempel", - "restartNew": "Opret et nyt workspace (standard)" + "restartNew": "Opret et nyt workspace (standard)", + "fieldFolder": "Valgfri /-adskilt mappesti (f.eks. Project/Linting), der grupperer kommandoen i kommandopaletten", + "commandVariables": "Kommandovariabler", + "commandVariablesDesc": "Tilføj {{variable}}-pladsholdere til en kommando, og cmux beder om hver værdi, før den køres. Genbrug det samme navn for at udfylde det flere steder på én gang.", + "commandVariablesDefaultNote": "Brug {{variable=default}} til at udfylde prompten med en standardværdi på forhånd." }, "keyboardShortcuts": { "title": "Tastaturgenveje", diff --git a/web/messages/de.json b/web/messages/de.json index af6789f6dc07..9ba4ba04fe99 100644 --- a/web/messages/de.json +++ b/web/messages/de.json @@ -961,7 +961,11 @@ "absolutePath": "Absoluter Pfad", "cwdAbsolute": "wird unverändert verwendet", "fullExample": "Vollständiges Beispiel", - "restartNew": "Neuen Workspace erstellen (Standard)" + "restartNew": "Neuen Workspace erstellen (Standard)", + "fieldFolder": "Optionaler, durch / getrennter Ordnerpfad (z. B. Project/Linting), der den Befehl in der Befehlspalette gruppiert", + "commandVariables": "Befehlsvariablen", + "commandVariablesDesc": "Füge einem Befehl {{variable}}-Platzhalter hinzu; cmux fragt vor der Ausführung nach jedem Wert. Verwende denselben Namen erneut, um ihn an mehreren Stellen gleichzeitig auszufüllen.", + "commandVariablesDefaultNote": "Verwende {{variable=default}}, um die Eingabeaufforderung mit einem Standardwert vorzubelegen." }, "keyboardShortcuts": { "title": "Tastaturkürzel", diff --git a/web/messages/en.json b/web/messages/en.json index e94c5d562537..47041728340b 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -1154,7 +1154,11 @@ "absolutePath": "Absolute path", "cwdAbsolute": "used as-is", "fullExample": "Full example", - "restartNew": "Create a new workspace (default)" + "restartNew": "Create a new workspace (default)", + "fieldFolder": "Optional /-separated folder path (e.g. Project/Linting) that groups the command in the Command Palette", + "commandVariables": "Command variables", + "commandVariablesDesc": "Add {{variable}} placeholders to a command and cmux prompts for each value before running it. Reuse the same placeholder name to fill it in several places at once.", + "commandVariablesDefaultNote": "Use {{variable=default}} to pre-fill the prompt with a default value." }, "keyboardShortcuts": { "title": "Keyboard Shortcuts", diff --git a/web/messages/es.json b/web/messages/es.json index 1c445c0db15b..f4d4e69e736e 100644 --- a/web/messages/es.json +++ b/web/messages/es.json @@ -961,7 +961,11 @@ "absolutePath": "Ruta absoluta", "cwdAbsolute": "se usa tal cual", "fullExample": "Ejemplo completo", - "restartNew": "Crear un workspace nuevo (por defecto)" + "restartNew": "Crear un workspace nuevo (por defecto)", + "fieldFolder": "Ruta de carpeta opcional separada por / (p. ej. Project/Linting) que agrupa el comando en la paleta de comandos", + "commandVariables": "Variables del comando", + "commandVariablesDesc": "Añade marcadores {{variable}} a un comando y cmux pedirá cada valor antes de ejecutarlo. Reutiliza el mismo nombre para rellenarlo en varios lugares a la vez.", + "commandVariablesDefaultNote": "Usa {{variable=default}} para rellenar previamente el campo con un valor predeterminado." }, "keyboardShortcuts": { "title": "Atajos de teclado", diff --git a/web/messages/fr.json b/web/messages/fr.json index 853e96c5f414..b0b588ba53cd 100644 --- a/web/messages/fr.json +++ b/web/messages/fr.json @@ -961,7 +961,11 @@ "absolutePath": "Chemin absolu", "cwdAbsolute": "utilisé tel quel", "fullExample": "Exemple complet", - "restartNew": "Créer un nouveau workspace (par défaut)" + "restartNew": "Créer un nouveau workspace (par défaut)", + "fieldFolder": "Chemin de dossier facultatif séparé par / (par ex. Project/Linting) qui regroupe la commande dans la palette de commandes", + "commandVariables": "Variables de commande", + "commandVariablesDesc": "Ajoutez des espaces réservés {{variable}} à une commande et cmux demande chaque valeur avant de l'exécuter. Réutilisez le même nom pour le renseigner à plusieurs endroits à la fois.", + "commandVariablesDefaultNote": "Utilisez {{variable=default}} pour préremplir l'invite avec une valeur par défaut." }, "keyboardShortcuts": { "title": "Raccourcis clavier", diff --git a/web/messages/it.json b/web/messages/it.json index 7d061dc0700d..77ed52c5643d 100644 --- a/web/messages/it.json +++ b/web/messages/it.json @@ -961,7 +961,11 @@ "absolutePath": "Percorso assoluto", "cwdAbsolute": "usato così com'è", "fullExample": "Esempio completo", - "restartNew": "Crea un nuovo workspace (predefinito)" + "restartNew": "Crea un nuovo workspace (predefinito)", + "fieldFolder": "Percorso di cartella facoltativo separato da / (es. Project/Linting) che raggruppa il comando nella palette dei comandi", + "commandVariables": "Variabili del comando", + "commandVariablesDesc": "Aggiungi segnaposto {{variable}} a un comando e cmux chiederà ogni valore prima di eseguirlo. Riutilizza lo stesso nome per compilarlo in più punti contemporaneamente.", + "commandVariablesDefaultNote": "Usa {{variable=default}} per precompilare il prompt con un valore predefinito." }, "keyboardShortcuts": { "title": "Scorciatoie da tastiera", diff --git a/web/messages/ja.json b/web/messages/ja.json index 5cd13ce871a3..d6a8f8c61463 100644 --- a/web/messages/ja.json +++ b/web/messages/ja.json @@ -1113,7 +1113,11 @@ "absolutePath": "絶対パス", "cwdAbsolute": "そのまま使用", "fullExample": "完全な例", - "restartNew": "新しいワークスペースを作成する (デフォルト)" + "restartNew": "新しいワークスペースを作成する (デフォルト)", + "fieldFolder": "コマンドパレットでコマンドをグループ化する任意の / 区切りフォルダーパス(例: Project/Linting)", + "commandVariables": "コマンド変数", + "commandVariablesDesc": "コマンドに {{variable}} プレースホルダーを追加すると、実行前に cmux が各値の入力を求めます。同じプレースホルダー名を再利用すると、複数箇所を一度に入力できます。", + "commandVariablesDefaultNote": "{{variable=default}} を使うと、プロンプトに既定値をあらかじめ入力できます。" }, "keyboardShortcuts": { "title": "キーボードショートカット", diff --git a/web/messages/km.json b/web/messages/km.json index 1f854bc3c50f..99a6187d1994 100644 --- a/web/messages/km.json +++ b/web/messages/km.json @@ -961,7 +961,11 @@ "absolutePath": "ផ្លូវដាច់ខាត", "cwdAbsolute": "ប្រើដូចដែលមាន", "fullExample": "ឧទាហរណ៍ពេញលេញ", - "restartNew": "បង្កើត workspace ថ្មី (លំនាំដើម)" + "restartNew": "បង្កើត workspace ថ្មី (លំនាំដើម)", + "fieldFolder": "ផ្លូវថតឯកសារស្រេចចិត្តបំបែកដោយ / (ឧ. Project/Linting) ដែលដាក់ជាក្រុមពាក្យបញ្ជាក្នុង Command Palette", + "commandVariables": "អថេរពាក្យបញ្ជា", + "commandVariablesDesc": "បន្ថែម {{variable}} ទៅពាក្យបញ្ជា ហើយ cmux នឹងសួរតម្លៃនីមួយៗមុនពេលដំណើរការ។ ប្រើឈ្មោះដដែលឡើងវិញ ដើម្បីបំពេញវានៅកន្លែងជាច្រើនក្នុងពេលតែមួយ។", + "commandVariablesDefaultNote": "ប្រើ {{variable=default}} ដើម្បីបំពេញតម្លៃលំនាំដើមជាមុនក្នុងប្រអប់សួរ។" }, "keyboardShortcuts": { "title": "ផ្លូវកាត់ក្ដារចុច", diff --git a/web/messages/ko.json b/web/messages/ko.json index 2d9c7bbeb581..713a88c6c1f0 100644 --- a/web/messages/ko.json +++ b/web/messages/ko.json @@ -961,7 +961,11 @@ "absolutePath": "절대 경로", "cwdAbsolute": "있는 그대로 사용", "fullExample": "전체 예시", - "restartNew": "새 워크스페이스 만들기 (기본값)" + "restartNew": "새 워크스페이스 만들기 (기본값)", + "fieldFolder": "명령 팔레트에서 명령을 그룹화하는 선택적 / 구분 폴더 경로(예: Project/Linting)", + "commandVariables": "명령 변수", + "commandVariablesDesc": "명령에 {{variable}} 자리표시자를 추가하면 cmux가 실행 전에 각 값을 입력하도록 요청합니다. 같은 이름을 재사용하면 여러 위치를 한 번에 채울 수 있습니다.", + "commandVariablesDefaultNote": "{{variable=default}}를 사용하면 프롬프트에 기본값을 미리 채울 수 있습니다." }, "keyboardShortcuts": { "title": "키보드 단축키", diff --git a/web/messages/no.json b/web/messages/no.json index e440e62049cd..81a3e3d91aba 100644 --- a/web/messages/no.json +++ b/web/messages/no.json @@ -961,7 +961,11 @@ "absolutePath": "Absolutt sti", "cwdAbsolute": "brukes som den er", "fullExample": "Fullstendig eksempel", - "restartNew": "Opprett et nytt workspace (standard)" + "restartNew": "Opprett et nytt workspace (standard)", + "fieldFolder": "Valgfri /-separert mappebane (f.eks. Project/Linting) som grupperer kommandoen i kommandopaletten", + "commandVariables": "Kommandovariabler", + "commandVariablesDesc": "Legg til {{variable}}-plassholdere i en kommando, så ber cmux om hver verdi før den kjøres. Bruk det samme navnet på nytt for å fylle det inn flere steder samtidig.", + "commandVariablesDefaultNote": "Bruk {{variable=default}} for å forhåndsutfylle ledeteksten med en standardverdi." }, "keyboardShortcuts": { "title": "Tastatursnarveier", diff --git a/web/messages/pl.json b/web/messages/pl.json index 7b9db613c7b9..c6eb45e97bb8 100644 --- a/web/messages/pl.json +++ b/web/messages/pl.json @@ -961,7 +961,11 @@ "absolutePath": "Ścieżka bezwzględna", "cwdAbsolute": "używana bez zmian", "fullExample": "Pełny przykład", - "restartNew": "Utwórz nowy workspace (domyślnie)" + "restartNew": "Utwórz nowy workspace (domyślnie)", + "fieldFolder": "Opcjonalna ścieżka folderu rozdzielona znakiem / (np. Project/Linting), która grupuje polecenie w palecie poleceń", + "commandVariables": "Zmienne polecenia", + "commandVariablesDesc": "Dodaj symbole {{variable}} do polecenia, a cmux poprosi o każdą wartość przed jego uruchomieniem. Użyj tej samej nazwy ponownie, aby wypełnić ją w wielu miejscach naraz.", + "commandVariablesDefaultNote": "Użyj {{variable=default}}, aby wstępnie wypełnić monit wartością domyślną." }, "keyboardShortcuts": { "title": "Skróty klawiszowe", diff --git a/web/messages/pt-BR.json b/web/messages/pt-BR.json index 13247ecfaf50..792d51cc8464 100644 --- a/web/messages/pt-BR.json +++ b/web/messages/pt-BR.json @@ -961,7 +961,11 @@ "absolutePath": "Caminho absoluto", "cwdAbsolute": "usado como está", "fullExample": "Exemplo completo", - "restartNew": "Criar um novo workspace (padrão)" + "restartNew": "Criar um novo workspace (padrão)", + "fieldFolder": "Caminho de pasta opcional separado por / (ex.: Project/Linting) que agrupa o comando na paleta de comandos", + "commandVariables": "Variáveis do comando", + "commandVariablesDesc": "Adicione marcadores {{variable}} a um comando e o cmux solicitará cada valor antes de executá-lo. Reutilize o mesmo nome para preenchê-lo em vários lugares de uma vez.", + "commandVariablesDefaultNote": "Use {{variable=default}} para preencher o prompt previamente com um valor padrão." }, "keyboardShortcuts": { "title": "Atalhos de Teclado", diff --git a/web/messages/ru.json b/web/messages/ru.json index 800e1792a20d..5eabc42003fb 100644 --- a/web/messages/ru.json +++ b/web/messages/ru.json @@ -961,7 +961,11 @@ "absolutePath": "Абсолютный путь", "cwdAbsolute": "используется как есть", "fullExample": "Полный пример", - "restartNew": "Создать новый workspace (по умолчанию)" + "restartNew": "Создать новый workspace (по умолчанию)", + "fieldFolder": "Необязательный путь к папке через / (например, Project/Linting), группирующий команду в палитре команд", + "commandVariables": "Переменные команды", + "commandVariablesDesc": "Добавьте в команду подстановки {{variable}}, и cmux запросит каждое значение перед запуском. Используйте одно и то же имя повторно, чтобы заполнить его сразу в нескольких местах.", + "commandVariablesDefaultNote": "Используйте {{variable=default}}, чтобы заранее подставить в запрос значение по умолчанию." }, "keyboardShortcuts": { "title": "Горячие клавиши", diff --git a/web/messages/th.json b/web/messages/th.json index c9a0629d52fd..2cbd397b8d7e 100644 --- a/web/messages/th.json +++ b/web/messages/th.json @@ -961,7 +961,11 @@ "absolutePath": "พาธสัมบูรณ์", "cwdAbsolute": "ใช้ตามที่เป็น", "fullExample": "ตัวอย่างเต็ม", - "restartNew": "สร้าง workspace ใหม่ (ค่าเริ่มต้น)" + "restartNew": "สร้าง workspace ใหม่ (ค่าเริ่มต้น)", + "fieldFolder": "เส้นทางโฟลเดอร์เสริมที่คั่นด้วย / (เช่น Project/Linting) สำหรับจัดกลุ่มคำสั่งในคอมมานด์พาเลตต์", + "commandVariables": "ตัวแปรของคำสั่ง", + "commandVariablesDesc": "เพิ่มตัวยึด {{variable}} ลงในคำสั่ง แล้ว cmux จะถามค่าแต่ละค่าก่อนเรียกใช้ ใช้ชื่อเดิมซ้ำเพื่อกรอกค่าในหลายตำแหน่งพร้อมกัน", + "commandVariablesDefaultNote": "ใช้ {{variable=default}} เพื่อกรอกค่าเริ่มต้นในกล่องข้อความล่วงหน้า" }, "keyboardShortcuts": { "title": "คีย์ลัด", diff --git a/web/messages/tr.json b/web/messages/tr.json index 1b082069eace..63fc2d086110 100644 --- a/web/messages/tr.json +++ b/web/messages/tr.json @@ -961,7 +961,11 @@ "absolutePath": "Mutlak yol", "cwdAbsolute": "olduğu gibi kullanılır", "fullExample": "Tam örnek", - "restartNew": "Yeni bir workspace oluştur (varsayılan)" + "restartNew": "Yeni bir workspace oluştur (varsayılan)", + "fieldFolder": "Komutu komut paletinde gruplayan, / ile ayrılmış isteğe bağlı klasör yolu (ör. Project/Linting)", + "commandVariables": "Komut değişkenleri", + "commandVariablesDesc": "Bir komuta {{variable}} yer tutucuları ekleyin; cmux çalıştırmadan önce her değeri sorar. Aynı adı yeniden kullanarak birden çok yeri tek seferde doldurun.", + "commandVariablesDefaultNote": "İstemi varsayılan bir değerle önceden doldurmak için {{variable=default}} kullanın." }, "keyboardShortcuts": { "title": "Klavye Kısayolları", diff --git a/web/messages/uk.json b/web/messages/uk.json index 36d918db5eba..d0e49d38c3cc 100644 --- a/web/messages/uk.json +++ b/web/messages/uk.json @@ -961,7 +961,11 @@ "absolutePath": "Абсолютний шлях", "cwdAbsolute": "використовується як є", "fullExample": "Повний приклад", - "restartNew": "Створити новий workspace (за замовчуванням)" + "restartNew": "Створити новий workspace (за замовчуванням)", + "fieldFolder": "Необов'язковий шлях до теки, розділений / (напр., Project/Linting), що групує команду в палітрі команд", + "commandVariables": "Змінні команди", + "commandVariablesDesc": "Додайте до команди заповнювачі {{variable}}, і cmux запитає кожне значення перед запуском. Повторно використовуйте те саме ім'я, щоб заповнити його одразу в кількох місцях.", + "commandVariablesDefaultNote": "Використовуйте {{variable=default}}, щоб заздалегідь підставити в запит значення за замовчуванням." }, "keyboardShortcuts": { "title": "Клавіатурні скорочення", diff --git a/web/messages/zh-CN.json b/web/messages/zh-CN.json index a763291d3908..03cbad88c6fa 100644 --- a/web/messages/zh-CN.json +++ b/web/messages/zh-CN.json @@ -961,7 +961,11 @@ "absolutePath": "绝对路径", "cwdAbsolute": "按原样使用", "fullExample": "完整示例", - "restartNew": "创建新的 workspace(默认)" + "restartNew": "创建新的 workspace(默认)", + "fieldFolder": "可选的以 / 分隔的文件夹路径(例如 Project/Linting),用于在命令面板中对命令进行分组", + "commandVariables": "命令变量", + "commandVariablesDesc": "在命令中添加 {{variable}} 占位符,cmux 会在运行前提示输入每个值。重复使用相同的名称即可一次性填充多个位置。", + "commandVariablesDefaultNote": "使用 {{variable=default}} 可为提示预填默认值。" }, "keyboardShortcuts": { "title": "快捷键", diff --git a/web/messages/zh-TW.json b/web/messages/zh-TW.json index 1d3940181965..27438208a4e2 100644 --- a/web/messages/zh-TW.json +++ b/web/messages/zh-TW.json @@ -961,7 +961,11 @@ "absolutePath": "絕對路徑", "cwdAbsolute": "按原樣使用", "fullExample": "完整範例", - "restartNew": "建立新的 workspace(預設)" + "restartNew": "建立新的 workspace(預設)", + "fieldFolder": "選用的以 / 分隔的資料夾路徑(例如 Project/Linting),用於在命令選擇區中將命令分組", + "commandVariables": "命令變數", + "commandVariablesDesc": "在命令中加入 {{variable}} 佔位符,cmux 會在執行前提示輸入每個值。重複使用相同的名稱即可一次填入多個位置。", + "commandVariablesDefaultNote": "使用 {{variable=default}} 可為提示預先填入預設值。" }, "keyboardShortcuts": { "title": "鍵盤快捷鍵", From 9a574b75fe201de8ec96c3784d3e36b60b458431 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 04:36:04 -0700 Subject: [PATCH 02/24] Wire new command-variable source files into the app target CmuxCommandVariables.swift and CmuxCommandVariablePrompt.swift were added to the worktree but not registered in project.pbxproj, so the app target failed to compile with "Cannot find 'CmuxCommandVariableParser'/'CmuxCommandVariablePrompt' in scope". Add the four pbxproj entries for each file (build file, file reference, group child, Sources build phase). Co-Authored-By: Claude Opus 4.8 (1M context) --- cmux.xcodeproj/project.pbxproj | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index a296dc0df884..8e977e88da93 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -272,6 +272,8 @@ C0DE64950000000000000003 /* CMUXCLITestAssertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */; }; 5E55500000000000000000E3 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; 5E55500000000000000000E4 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; + C1A2B3C4D5E6F7080000655B /* CmuxCommandVariablePrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */; }; + C1A2B3C4D5E6F70800006559 /* CmuxCommandVariables.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */; }; C1A2B3C4D5E6F70800006557 /* CmuxCommandVariableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */; }; A5001650 /* CmuxConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001651 /* CmuxConfig.swift */; }; C0DEF0A40000000000000001 /* CmuxConfigContextMenuTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */; }; @@ -1431,6 +1433,8 @@ C12985000000000000000003 /* CMUXCLISentryTelemetryRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISentryTelemetryRegressionTests.swift; sourceTree = ""; }; C0DE64950000000000000006 /* CMUXCLISessionsListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISessionsListTests.swift; sourceTree = ""; }; C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLITestAssertions.swift; sourceTree = ""; }; + C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariablePrompt.swift; sourceTree = ""; }; + C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariables.swift; sourceTree = ""; }; C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariableTests.swift; sourceTree = ""; }; A5001651 /* CmuxConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfig.swift; sourceTree = ""; }; C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigContextMenuTests.swift; sourceTree = ""; }; @@ -3016,6 +3020,8 @@ A5001642 /* RemoteInteractiveShellBootstrapBuilder.swift */, A5001641 /* RemoteRelayZshBootstrap.swift */, A5001651 /* CmuxConfig.swift */, + C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */, + C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */, C10D00040000000000000004 /* CmuxSurfaceTabBarBuiltInAction.swift */, C57B00030000000000000002 /* Workspace+CustomSidebarPane.swift */, C0DEF0A10000000000000002 /* CmuxConfigUI.swift */, @@ -4000,6 +4006,8 @@ C4160A010000000000000001 /* cmuxApp+HistoryMenu.swift in Sources */, A5001001 /* cmuxApp.swift in Sources */, A72C9F4179B54DF38E99A021 /* CmuxCLIPathInstaller.swift in Sources */, + C1A2B3C4D5E6F7080000655B /* CmuxCommandVariablePrompt.swift in Sources */, + C1A2B3C4D5E6F70800006559 /* CmuxCommandVariables.swift in Sources */, A5001650 /* CmuxConfig.swift in Sources */, A5001652 /* CmuxConfigExecutor.swift in Sources */, C5D0DEC0CF00000000000A1 /* CmuxConfigStore+ConfigStoreReloading.swift in Sources */, From e8c7938a40ebef9c7a8ee0e38a3d88c4ca2ccab2 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 05:02:33 -0700 Subject: [PATCH 03/24] Narrow variable grammar, add escape, keep ICU-safe docs Address review: the initial parser treated any {{...}} with letters/dots/spaces as a cmux variable, which would hijack existing custom commands that embed Go/Handlebars-style templates such as {{ .Env.FOO }}. - Narrow the grammar to bare identifiers ([A-Za-z_][A-Za-z0-9_-]*): template expressions with leading dots, internal spaces, pipes, or functions are now left completely untouched and run as-is. - Add a backslash escape: \{{name}} forces a literal {{name}} (the backslash is stripped at run time, no prompt). The executor's no-variable path now strips escapes too. - Document the identifier rule and escape in the JSON schema. - Docs messages rendered via plain next-intl t() must be ICU-safe, so the command-variable doc strings are brace-free prose (the {{...}} syntax is shown in the adjacent CodeBlock, which is raw JSX); add a template/escape note across all web locales. - Expand tests: template expressions stay literal, backslash escape, mixed escaped/unescaped occurrences. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandVariables.swift | 138 +++++++++++------- Sources/CmuxConfigExecutor.swift | 5 +- cmuxTests/CmuxCommandVariableTests.swift | 33 ++++- .../[locale]/docs/custom-commands/page.tsx | 1 + web/data/cmux.schema.json | 2 +- web/messages/ar.json | 5 +- web/messages/bs.json | 5 +- web/messages/da.json | 5 +- web/messages/de.json | 5 +- web/messages/en.json | 5 +- web/messages/es.json | 5 +- web/messages/fr.json | 5 +- web/messages/it.json | 5 +- web/messages/ja.json | 5 +- web/messages/km.json | 5 +- web/messages/ko.json | 5 +- web/messages/no.json | 5 +- web/messages/pl.json | 5 +- web/messages/pt-BR.json | 5 +- web/messages/ru.json | 5 +- web/messages/th.json | 5 +- web/messages/tr.json | 5 +- web/messages/uk.json | 5 +- web/messages/zh-CN.json | 5 +- web/messages/zh-TW.json | 5 +- 25 files changed, 185 insertions(+), 94 deletions(-) diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift index d0a017f5e54c..17791cac09a8 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandVariables.swift @@ -19,97 +19,130 @@ struct CmuxCommandVariable: Equatable, Sendable { /// Parses and substitutes `{{variable}}` placeholders inside custom command /// strings. /// -/// Grammar (kept deliberately small and shell-safe): +/// Grammar (deliberately narrow so it does not regress shell commands that +/// embed Go/Handlebars-style `{{…}}` templates): /// - A placeholder is `{{` … `}}` whose inner text contains no `{`, `}`, or /// newline. -/// - The name is the text before the first `=`; an optional default value is -/// the text after it. Both are trimmed of surrounding whitespace. -/// - A name must be non-empty and contain only letters, digits, spaces, or -/// `_ - .`. Anything else (`$`, `(`, `/`, `|`, …) makes the braces literal so -/// ordinary shell snippets that happen to use `{{` are never mistaken for a -/// variable. +/// - The name is the text before an optional `=`; the text after `=` is a +/// default value. Both are trimmed of surrounding whitespace. +/// - The name must be a *bare identifier*: a letter or `_` followed by letters, +/// digits, `_`, or `-`. Anything else — a leading `.` (`{{ .Env.FOO }}`), +/// internal spaces (`{{ range .Items }}`), pipes, or function calls — is left +/// completely untouched and runs as-is. +/// - Prefix the placeholder with a backslash (`\{{name}}`) to force a literal +/// `{{name}}`; cmux strips the backslash and never prompts for it. enum CmuxCommandVariableParser { /// Returns the ordered, de-duplicated variables found in `command`, /// preserving first-occurrence order. When the same name appears more than /// once, the first occurrence's default value wins. static func variables(in command: String) -> [CmuxCommandVariable] { + guard command.contains("{{") else { return [] } var seen = Set() var result: [CmuxCommandVariable] = [] - for match in matches(in: command) where seen.insert(match.name).inserted { - result.append(CmuxCommandVariable(name: match.name, defaultValue: match.defaultValue)) + for case let .variable(variable, _) in scan(command) where seen.insert(variable.name).inserted { + result.append(variable) } return result } /// Whether `command` contains at least one recognized variable placeholder. static func containsVariables(_ command: String) -> Bool { - for _ in matches(in: command) { return true } + guard command.contains("{{") else { return false } + for case .variable in scan(command) { return true } return false } - /// Replaces every recognized placeholder whose name is present in `values` - /// with the corresponding value. Placeholders whose name is missing from - /// `values` are left untouched so partial maps never corrupt the command. + /// Resolves `command` for execution: replaces every recognized placeholder + /// whose name is present in `values` with its value, leaves placeholders + /// whose name is missing from `values` untouched, leaves non-identifier + /// `{{…}}` template expressions untouched, and strips the escaping + /// backslash from any `\{{…}}` so it becomes a literal `{{…}}`. static func substitute(_ command: String, values: [String: String]) -> String { - let found = matches(in: command) - guard !found.isEmpty else { return command } + guard command.contains("{{") else { return command } var result = "" result.reserveCapacity(command.count) - var cursor = command.startIndex - for match in found { - result.append(contentsOf: command[cursor.. - let name: String - let defaultValue: String? + private enum Token { + /// Text emitted verbatim (plain text, escaped placeholders with the + /// backslash removed, and unrecognized `{{…}}` template expressions). + case literal(String) + /// A recognized variable placeholder; `raw` is the original `{{…}}` + /// text used when no value is supplied. + case variable(CmuxCommandVariable, raw: String) } - private static let allowedNameCharacters: CharacterSet = CharacterSet.alphanumerics - .union(CharacterSet(charactersIn: "_-. ")) - - private static func matches(in command: String) -> [Match] { - var matches: [Match] = [] + private static func scan(_ command: String) -> [Token] { + var tokens: [Token] = [] + var literalStart = command.startIndex var index = command.startIndex let end = command.endIndex + + func flushLiteral(upTo upperBound: String.Index) { + if literalStart < upperBound { + tokens.append(.literal(String(command[literalStart.. command.startIndex + && command[command.index(before: open.lowerBound)] == "\\" + if isEscaped { + // Drop the escaping backslash and emit a literal "{{…}}". + let backslash = command.index(before: open.lowerBound) + flushLiteral(upTo: backslash) + tokens.append(.literal(String(command[open.lowerBound.. (name: String, defaultValue: String?)? { @@ -117,16 +150,23 @@ enum CmuxCommandVariableParser { let name = inner[.. Bool { - guard !name.isEmpty else { return false } - return name.unicodeScalars.allSatisfy { allowedNameCharacters.contains($0) } + private static let trailingNameCharacters: CharacterSet = CharacterSet.letters + .union(.decimalDigits) + .union(CharacterSet(charactersIn: "_-")) + + /// A bare identifier: a leading letter or `_`, then letters, digits, `_`, or + /// `-`. Rejects dots, spaces, and everything used by template engines. + private static func isValidIdentifier(_ name: String) -> Bool { + guard let first = name.unicodeScalars.first else { return false } + guard CharacterSet.letters.contains(first) || first == "_" else { return false } + return name.unicodeScalars.allSatisfy { trailingNameCharacters.contains($0) } } } diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index 9bc8563e608a..136e2c6b5baa 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -141,8 +141,11 @@ struct CmuxConfigExecutor { // them without per-surface duplication. let variables = CmuxCommandVariableParser.variables(in: rawCommand) guard !variables.isEmpty else { + // No variables to prompt for, but still strip any escaped + // `\{{…}}` placeholders so they run as literal `{{…}}`. + let resolvedCommand = CmuxCommandVariableParser.substitute(rawCommand, values: [:]) return authorizeSanitizedShellCommand( - rawCommand, + resolvedCommand, confirm: confirm, actionID: actionID, target: target, diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index 8d42d9f041a8..885286142d02 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -49,9 +49,9 @@ final class CmuxCommandVariableParserTests: XCTestCase { XCTAssertEqual(vars, [CmuxCommandVariable(name: "env", defaultValue: "a")]) } - func testNameAllowsSpacesLettersDigitsAndPunctuation() { - let vars = CmuxCommandVariableParser.variables(in: "x {{branch name}} {{RAILS_ENV}} {{my.var}}") - XCTAssertEqual(vars.map(\.name), ["branch name", "RAILS_ENV", "my.var"]) + func testNameAllowsBareIdentifiers() { + let vars = CmuxCommandVariableParser.variables(in: "x {{branch_name}} {{RAILS_ENV}} {{my-var}}") + XCTAssertEqual(vars.map(\.name), ["branch_name", "RAILS_ENV", "my-var"]) } func testEmptyPlaceholderIsIgnored() { @@ -67,6 +67,33 @@ final class CmuxCommandVariableParserTests: XCTestCase { XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{a/b}}"), []) } + func testTemplateExpressionsAreLeftUntouched() { + // Go/Handlebars-style templates (leading dot, internal spaces, pipes, + // functions) must not be mistaken for cmux variables, so existing + // templated shell commands keep running unchanged. + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "gomplate -i '{{ .Env.FOO }}'"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{ range .Items }}'"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{ name | upper }}'"), []) + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{.value}}'"), []) + XCTAssertEqual( + CmuxCommandVariableParser.substitute("gomplate -i '{{ .Env.FOO }}'", values: ["FOO": "x"]), + "gomplate -i '{{ .Env.FOO }}'" + ) + } + + func testBackslashEscapeProducesLiteralBraces() { + // `\{{name}}` is not a variable and the backslash is stripped on run. + XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo \\{{name}}"), []) + XCTAssertEqual(CmuxCommandVariableParser.substitute("echo \\{{name}}", values: [:]), "echo {{name}}") + // An escaped and an unescaped occurrence can coexist. + let mixed = "echo \\{{env}} {{env}}" + XCTAssertEqual(CmuxCommandVariableParser.variables(in: mixed).map(\.name), ["env"]) + XCTAssertEqual( + CmuxCommandVariableParser.substitute(mixed, values: ["env": "prod"]), + "echo {{env}} prod" + ) + } + func testNewlineInsidePlaceholderIsIgnored() { XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{na\nme}}"), []) } diff --git a/web/app/[locale]/docs/custom-commands/page.tsx b/web/app/[locale]/docs/custom-commands/page.tsx index afc48651fbbb..4fb99ef60a24 100644 --- a/web/app/[locale]/docs/custom-commands/page.tsx +++ b/web/app/[locale]/docs/custom-commands/page.tsx @@ -352,6 +352,7 @@ export default function CustomCommandsPage() { ] }`}

    {t("commandVariablesDefaultNote")}

    +

    {t("commandVariablesTemplateNote")}

    {t("workspaceCommands")}

    {t("workspaceCommandsDesc")}

    diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 021fcfd59893..009f23e57dcc 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -53,7 +53,7 @@ }, "command": { "type": "string", - "description": "Shell command to run. Use {{variable}} placeholders (optionally {{variable=default}}) to prompt for values before running, for example \"bin/deploy --env {{environment}}\"." + "description": "Shell command to run. Use {{name}} placeholders (optionally {{name=default}}) to prompt for values before running, for example \"bin/deploy --env {{environment}}\". Only bare identifiers ([A-Za-z_][A-Za-z0-9_-]*) are treated as variables, so Go/Handlebars-style templates such as {{ .Env.FOO }} run unchanged; prefix a placeholder with a backslash (\\{{name}}) to keep a literal {{name}}." }, "folder": { "type": "string", diff --git a/web/messages/ar.json b/web/messages/ar.json index 5f53bf115bfc..397d400addf5 100644 --- a/web/messages/ar.json +++ b/web/messages/ar.json @@ -964,8 +964,9 @@ "restartNew": "إنشاء مساحة عمل جديدة (الافتراضي)", "fieldFolder": "مسار مجلد اختياري مفصول بـ / (مثل Project/Linting) لتجميع الأمر في لوحة الأوامر", "commandVariables": "متغيرات الأمر", - "commandVariablesDesc": "أضِف عناصر نائبة {{variable}} إلى الأمر، وسيطلب cmux إدخال كل قيمة قبل التشغيل. أعِد استخدام الاسم نفسه لتعبئته في عدة أماكن دفعة واحدة.", - "commandVariablesDefaultNote": "استخدم {{variable=default}} لملء المطالبة بقيمة افتراضية مسبقًا." + "commandVariablesDesc": "أضِف عناصر نائبة إلى الأمر، وسيطلب cmux إدخال كل قيمة قبل التشغيل. أعِد استخدام اسم العنصر النائب نفسه لتعبئته في عدة أماكن دفعة واحدة.", + "commandVariablesDefaultNote": "أضِف قيمة افتراضية بعد علامة المساواة داخل العنصر النائب لملء المطالبة مسبقًا.", + "commandVariablesTemplateNote": "تتحوّل المعرّفات البسيطة فقط إلى متغيّرات، لذا تعمل القوالب التي تستخدم نقاطًا في البداية أو مسافات أو أنابيب دون تغيير. ضَع شرطة مائلة عكسية قبل العنصر النائب للإبقاء عليه حرفيًا." }, "keyboardShortcuts": { "title": "اختصارات لوحة المفاتيح", diff --git a/web/messages/bs.json b/web/messages/bs.json index 0edf9cd16971..58aa52183a5a 100644 --- a/web/messages/bs.json +++ b/web/messages/bs.json @@ -964,8 +964,9 @@ "restartNew": "Kreiraj novi radni prostor (zadano)", "fieldFolder": "Opcionalna putanja foldera odvojena znakom / (npr. Project/Linting) koja grupira komandu u Komandnoj paleti", "commandVariables": "Varijable komande", - "commandVariablesDesc": "Dodajte {{variable}} rezervirana mjesta u komandu i cmux će zatražiti svaku vrijednost prije pokretanja. Ponovo upotrijebite isti naziv da ga popunite na više mjesta odjednom.", - "commandVariablesDefaultNote": "Koristite {{variable=default}} da unaprijed popunite upit zadanom vrijednošću." + "commandVariablesDesc": "Dodajte rezervirana mjesta u komandu i cmux će zatražiti svaku vrijednost prije pokretanja. Ponovo upotrijebite isti naziv da ga popunite na više mjesta odjednom.", + "commandVariablesDefaultNote": "Dodajte zadanu vrijednost iza znaka jednakosti unutar rezerviranog mjesta da unaprijed popunite upit.", + "commandVariablesTemplateNote": "Samo obični identifikatori postaju varijable, pa se predlošci koji koriste vodeće tačke, razmake ili cijevi izvršavaju nepromijenjeni. Stavite obrnutu kosu crtu ispred rezerviranog mjesta da ostane doslovno." }, "keyboardShortcuts": { "title": "Prečice na tastaturi", diff --git a/web/messages/da.json b/web/messages/da.json index fbb93fd7ab5d..71cc95f00eae 100644 --- a/web/messages/da.json +++ b/web/messages/da.json @@ -964,8 +964,9 @@ "restartNew": "Opret et nyt workspace (standard)", "fieldFolder": "Valgfri /-adskilt mappesti (f.eks. Project/Linting), der grupperer kommandoen i kommandopaletten", "commandVariables": "Kommandovariabler", - "commandVariablesDesc": "Tilføj {{variable}}-pladsholdere til en kommando, og cmux beder om hver værdi, før den køres. Genbrug det samme navn for at udfylde det flere steder på én gang.", - "commandVariablesDefaultNote": "Brug {{variable=default}} til at udfylde prompten med en standardværdi på forhånd." + "commandVariablesDesc": "Tilføj pladsholdere til en kommando, og cmux beder om hver værdi, før den køres. Genbrug det samme navn for at udfylde det flere steder på én gang.", + "commandVariablesDefaultNote": "Tilføj en standardværdi efter et lighedstegn inde i en pladsholder for at udfylde prompten på forhånd.", + "commandVariablesTemplateNote": "Kun simple identifikatorer bliver variabler, så skabeloner med indledende punktummer, mellemrum eller pipes køres uændret. Sæt en omvendt skråstreg foran en pladsholder for at bevare den bogstaveligt." }, "keyboardShortcuts": { "title": "Tastaturgenveje", diff --git a/web/messages/de.json b/web/messages/de.json index 9ba4ba04fe99..850fc67eb0ac 100644 --- a/web/messages/de.json +++ b/web/messages/de.json @@ -964,8 +964,9 @@ "restartNew": "Neuen Workspace erstellen (Standard)", "fieldFolder": "Optionaler, durch / getrennter Ordnerpfad (z. B. Project/Linting), der den Befehl in der Befehlspalette gruppiert", "commandVariables": "Befehlsvariablen", - "commandVariablesDesc": "Füge einem Befehl {{variable}}-Platzhalter hinzu; cmux fragt vor der Ausführung nach jedem Wert. Verwende denselben Namen erneut, um ihn an mehreren Stellen gleichzeitig auszufüllen.", - "commandVariablesDefaultNote": "Verwende {{variable=default}}, um die Eingabeaufforderung mit einem Standardwert vorzubelegen." + "commandVariablesDesc": "Füge einem Befehl Platzhalter hinzu; cmux fragt vor der Ausführung nach jedem Wert. Verwende denselben Namen erneut, um ihn an mehreren Stellen gleichzeitig auszufüllen.", + "commandVariablesDefaultNote": "Füge nach einem Gleichheitszeichen innerhalb eines Platzhalters einen Standardwert hinzu, um die Eingabeaufforderung vorzubelegen.", + "commandVariablesTemplateNote": "Nur einfache Bezeichner werden zu Variablen, daher werden Vorlagen mit führenden Punkten, Leerzeichen oder Pipes unverändert ausgeführt. Stelle einem Platzhalter einen Backslash voran, um ihn wörtlich zu behalten." }, "keyboardShortcuts": { "title": "Tastaturkürzel", diff --git a/web/messages/en.json b/web/messages/en.json index 47041728340b..913e9c7d2dfc 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -1157,8 +1157,9 @@ "restartNew": "Create a new workspace (default)", "fieldFolder": "Optional /-separated folder path (e.g. Project/Linting) that groups the command in the Command Palette", "commandVariables": "Command variables", - "commandVariablesDesc": "Add {{variable}} placeholders to a command and cmux prompts for each value before running it. Reuse the same placeholder name to fill it in several places at once.", - "commandVariablesDefaultNote": "Use {{variable=default}} to pre-fill the prompt with a default value." + "commandVariablesDesc": "Add placeholders to a command and cmux prompts for each value before running it. Reuse the same placeholder name to fill it in several places at once.", + "commandVariablesDefaultNote": "Add a default value after an equals sign inside a placeholder to pre-fill the prompt.", + "commandVariablesTemplateNote": "Only bare identifiers become variables, so templates that use leading dots, spaces, or pipes run unchanged. Prefix a placeholder with a backslash to keep it literal." }, "keyboardShortcuts": { "title": "Keyboard Shortcuts", diff --git a/web/messages/es.json b/web/messages/es.json index f4d4e69e736e..42eba5a78af0 100644 --- a/web/messages/es.json +++ b/web/messages/es.json @@ -964,8 +964,9 @@ "restartNew": "Crear un workspace nuevo (por defecto)", "fieldFolder": "Ruta de carpeta opcional separada por / (p. ej. Project/Linting) que agrupa el comando en la paleta de comandos", "commandVariables": "Variables del comando", - "commandVariablesDesc": "Añade marcadores {{variable}} a un comando y cmux pedirá cada valor antes de ejecutarlo. Reutiliza el mismo nombre para rellenarlo en varios lugares a la vez.", - "commandVariablesDefaultNote": "Usa {{variable=default}} para rellenar previamente el campo con un valor predeterminado." + "commandVariablesDesc": "Añade marcadores a un comando y cmux pedirá cada valor antes de ejecutarlo. Reutiliza el mismo nombre para rellenarlo en varios lugares a la vez.", + "commandVariablesDefaultNote": "Añade un valor predeterminado después de un signo igual dentro de un marcador para rellenar el campo previamente.", + "commandVariablesTemplateNote": "Solo los identificadores simples se convierten en variables, así que las plantillas con puntos iniciales, espacios o tuberías se ejecutan sin cambios. Antepón una barra invertida a un marcador para mantenerlo literal." }, "keyboardShortcuts": { "title": "Atajos de teclado", diff --git a/web/messages/fr.json b/web/messages/fr.json index b0b588ba53cd..23300f7010e8 100644 --- a/web/messages/fr.json +++ b/web/messages/fr.json @@ -964,8 +964,9 @@ "restartNew": "Créer un nouveau workspace (par défaut)", "fieldFolder": "Chemin de dossier facultatif séparé par / (par ex. Project/Linting) qui regroupe la commande dans la palette de commandes", "commandVariables": "Variables de commande", - "commandVariablesDesc": "Ajoutez des espaces réservés {{variable}} à une commande et cmux demande chaque valeur avant de l'exécuter. Réutilisez le même nom pour le renseigner à plusieurs endroits à la fois.", - "commandVariablesDefaultNote": "Utilisez {{variable=default}} pour préremplir l'invite avec une valeur par défaut." + "commandVariablesDesc": "Ajoutez des espaces réservés à une commande et cmux demande chaque valeur avant de l'exécuter. Réutilisez le même nom pour le renseigner à plusieurs endroits à la fois.", + "commandVariablesDefaultNote": "Ajoutez une valeur par défaut après un signe égal à l'intérieur d'un espace réservé pour préremplir l'invite.", + "commandVariablesTemplateNote": "Seuls les identifiants simples deviennent des variables ; les modèles utilisant des points en tête, des espaces ou des barres verticales s'exécutent sans changement. Faites précéder un espace réservé d'une barre oblique inverse pour le garder littéral." }, "keyboardShortcuts": { "title": "Raccourcis clavier", diff --git a/web/messages/it.json b/web/messages/it.json index 77ed52c5643d..ad3634555bd8 100644 --- a/web/messages/it.json +++ b/web/messages/it.json @@ -964,8 +964,9 @@ "restartNew": "Crea un nuovo workspace (predefinito)", "fieldFolder": "Percorso di cartella facoltativo separato da / (es. Project/Linting) che raggruppa il comando nella palette dei comandi", "commandVariables": "Variabili del comando", - "commandVariablesDesc": "Aggiungi segnaposto {{variable}} a un comando e cmux chiederà ogni valore prima di eseguirlo. Riutilizza lo stesso nome per compilarlo in più punti contemporaneamente.", - "commandVariablesDefaultNote": "Usa {{variable=default}} per precompilare il prompt con un valore predefinito." + "commandVariablesDesc": "Aggiungi segnaposto a un comando e cmux chiederà ogni valore prima di eseguirlo. Riutilizza lo stesso nome per compilarlo in più punti contemporaneamente.", + "commandVariablesDefaultNote": "Aggiungi un valore predefinito dopo un segno di uguale all'interno di un segnaposto per precompilare il prompt.", + "commandVariablesTemplateNote": "Solo gli identificatori semplici diventano variabili, quindi i template che usano punti iniziali, spazi o pipe vengono eseguiti senza modifiche. Anteponi una barra rovesciata a un segnaposto per mantenerlo letterale." }, "keyboardShortcuts": { "title": "Scorciatoie da tastiera", diff --git a/web/messages/ja.json b/web/messages/ja.json index d6a8f8c61463..7d4b239b1fa9 100644 --- a/web/messages/ja.json +++ b/web/messages/ja.json @@ -1116,8 +1116,9 @@ "restartNew": "新しいワークスペースを作成する (デフォルト)", "fieldFolder": "コマンドパレットでコマンドをグループ化する任意の / 区切りフォルダーパス(例: Project/Linting)", "commandVariables": "コマンド変数", - "commandVariablesDesc": "コマンドに {{variable}} プレースホルダーを追加すると、実行前に cmux が各値の入力を求めます。同じプレースホルダー名を再利用すると、複数箇所を一度に入力できます。", - "commandVariablesDefaultNote": "{{variable=default}} を使うと、プロンプトに既定値をあらかじめ入力できます。" + "commandVariablesDesc": "コマンドにプレースホルダーを追加すると、実行前に cmux が各値の入力を求めます。同じプレースホルダー名を再利用すると、複数箇所を一度に入力できます。", + "commandVariablesDefaultNote": "プレースホルダー内のイコール記号の後に既定値を指定すると、プロンプトにあらかじめ入力できます。", + "commandVariablesTemplateNote": "変数として扱われるのは単純な識別子のみです。先頭のドット、スペース、パイプを使うテンプレートはそのまま実行されます。プレースホルダーの前にバックスラッシュを付けると、そのまま残せます。" }, "keyboardShortcuts": { "title": "キーボードショートカット", diff --git a/web/messages/km.json b/web/messages/km.json index 99a6187d1994..ae78e4813add 100644 --- a/web/messages/km.json +++ b/web/messages/km.json @@ -964,8 +964,9 @@ "restartNew": "បង្កើត workspace ថ្មី (លំនាំដើម)", "fieldFolder": "ផ្លូវថតឯកសារស្រេចចិត្តបំបែកដោយ / (ឧ. Project/Linting) ដែលដាក់ជាក្រុមពាក្យបញ្ជាក្នុង Command Palette", "commandVariables": "អថេរពាក្យបញ្ជា", - "commandVariablesDesc": "បន្ថែម {{variable}} ទៅពាក្យបញ្ជា ហើយ cmux នឹងសួរតម្លៃនីមួយៗមុនពេលដំណើរការ។ ប្រើឈ្មោះដដែលឡើងវិញ ដើម្បីបំពេញវានៅកន្លែងជាច្រើនក្នុងពេលតែមួយ។", - "commandVariablesDefaultNote": "ប្រើ {{variable=default}} ដើម្បីបំពេញតម្លៃលំនាំដើមជាមុនក្នុងប្រអប់សួរ។" + "commandVariablesDesc": "បន្ថែមកន្លែងដាក់ទៅពាក្យបញ្ជា ហើយ cmux នឹងសួរតម្លៃនីមួយៗមុនពេលដំណើរការ។ ប្រើឈ្មោះដដែលឡើងវិញ ដើម្បីបំពេញវានៅកន្លែងជាច្រើនក្នុងពេលតែមួយ។", + "commandVariablesDefaultNote": "បន្ថែមតម្លៃលំនាំដើមបន្ទាប់ពីសញ្ញាស្មើនៅក្នុងកន្លែងដាក់ ដើម្បីបំពេញប្រអប់សួរជាមុន។", + "commandVariablesTemplateNote": "មានតែឈ្មោះសម្គាល់ធម្មតាប៉ុណ្ណោះដែលក្លាយជាអថេរ ដូច្នេះគំរូដែលប្រើសញ្ញាចុចនៅដើម ដកឃ្លា ឬបន្ទាត់បញ្ឈរ ដំណើរការដោយមិនផ្លាស់ប្ដូរ។ ដាក់សញ្ញា backslash នៅពីមុខកន្លែងដាក់ ដើម្បីរក្សាវាជាអក្សរ។" }, "keyboardShortcuts": { "title": "ផ្លូវកាត់ក្ដារចុច", diff --git a/web/messages/ko.json b/web/messages/ko.json index 713a88c6c1f0..c57c64e21513 100644 --- a/web/messages/ko.json +++ b/web/messages/ko.json @@ -964,8 +964,9 @@ "restartNew": "새 워크스페이스 만들기 (기본값)", "fieldFolder": "명령 팔레트에서 명령을 그룹화하는 선택적 / 구분 폴더 경로(예: Project/Linting)", "commandVariables": "명령 변수", - "commandVariablesDesc": "명령에 {{variable}} 자리표시자를 추가하면 cmux가 실행 전에 각 값을 입력하도록 요청합니다. 같은 이름을 재사용하면 여러 위치를 한 번에 채울 수 있습니다.", - "commandVariablesDefaultNote": "{{variable=default}}를 사용하면 프롬프트에 기본값을 미리 채울 수 있습니다." + "commandVariablesDesc": "명령에 자리표시자를 추가하면 cmux가 실행 전에 각 값을 입력하도록 요청합니다. 같은 이름을 재사용하면 여러 위치를 한 번에 채울 수 있습니다.", + "commandVariablesDefaultNote": "자리표시자 안의 등호 뒤에 기본값을 추가하면 프롬프트를 미리 채울 수 있습니다.", + "commandVariablesTemplateNote": "단순 식별자만 변수가 되므로 선행 점, 공백, 파이프를 사용하는 템플릿은 그대로 실행됩니다. 자리표시자 앞에 백슬래시를 붙이면 문자 그대로 유지됩니다." }, "keyboardShortcuts": { "title": "키보드 단축키", diff --git a/web/messages/no.json b/web/messages/no.json index 81a3e3d91aba..386690420434 100644 --- a/web/messages/no.json +++ b/web/messages/no.json @@ -964,8 +964,9 @@ "restartNew": "Opprett et nytt workspace (standard)", "fieldFolder": "Valgfri /-separert mappebane (f.eks. Project/Linting) som grupperer kommandoen i kommandopaletten", "commandVariables": "Kommandovariabler", - "commandVariablesDesc": "Legg til {{variable}}-plassholdere i en kommando, så ber cmux om hver verdi før den kjøres. Bruk det samme navnet på nytt for å fylle det inn flere steder samtidig.", - "commandVariablesDefaultNote": "Bruk {{variable=default}} for å forhåndsutfylle ledeteksten med en standardverdi." + "commandVariablesDesc": "Legg til plassholdere i en kommando, så ber cmux om hver verdi før den kjøres. Bruk det samme navnet på nytt for å fylle det inn flere steder samtidig.", + "commandVariablesDefaultNote": "Legg til en standardverdi etter et likhetstegn inne i en plassholder for å forhåndsutfylle ledeteksten.", + "commandVariablesTemplateNote": "Bare enkle identifikatorer blir variabler, så maler som bruker innledende punktum, mellomrom eller rør kjøres uendret. Sett en omvendt skråstrek foran en plassholder for å beholde den bokstavelig." }, "keyboardShortcuts": { "title": "Tastatursnarveier", diff --git a/web/messages/pl.json b/web/messages/pl.json index c6eb45e97bb8..9589a0b00325 100644 --- a/web/messages/pl.json +++ b/web/messages/pl.json @@ -964,8 +964,9 @@ "restartNew": "Utwórz nowy workspace (domyślnie)", "fieldFolder": "Opcjonalna ścieżka folderu rozdzielona znakiem / (np. Project/Linting), która grupuje polecenie w palecie poleceń", "commandVariables": "Zmienne polecenia", - "commandVariablesDesc": "Dodaj symbole {{variable}} do polecenia, a cmux poprosi o każdą wartość przed jego uruchomieniem. Użyj tej samej nazwy ponownie, aby wypełnić ją w wielu miejscach naraz.", - "commandVariablesDefaultNote": "Użyj {{variable=default}}, aby wstępnie wypełnić monit wartością domyślną." + "commandVariablesDesc": "Dodaj symbole zastępcze do polecenia, a cmux poprosi o każdą wartość przed jego uruchomieniem. Użyj tej samej nazwy ponownie, aby wypełnić ją w wielu miejscach naraz.", + "commandVariablesDefaultNote": "Dodaj wartość domyślną po znaku równości wewnątrz symbolu zastępczego, aby wstępnie wypełnić monit.", + "commandVariablesTemplateNote": "Tylko proste identyfikatory stają się zmiennymi, więc szablony używające początkowych kropek, spacji lub potoków są uruchamiane bez zmian. Poprzedź symbol zastępczy ukośnikiem wstecznym, aby zachować go dosłownie." }, "keyboardShortcuts": { "title": "Skróty klawiszowe", diff --git a/web/messages/pt-BR.json b/web/messages/pt-BR.json index 792d51cc8464..ce3c245bfd3f 100644 --- a/web/messages/pt-BR.json +++ b/web/messages/pt-BR.json @@ -964,8 +964,9 @@ "restartNew": "Criar um novo workspace (padrão)", "fieldFolder": "Caminho de pasta opcional separado por / (ex.: Project/Linting) que agrupa o comando na paleta de comandos", "commandVariables": "Variáveis do comando", - "commandVariablesDesc": "Adicione marcadores {{variable}} a um comando e o cmux solicitará cada valor antes de executá-lo. Reutilize o mesmo nome para preenchê-lo em vários lugares de uma vez.", - "commandVariablesDefaultNote": "Use {{variable=default}} para preencher o prompt previamente com um valor padrão." + "commandVariablesDesc": "Adicione marcadores a um comando e o cmux solicitará cada valor antes de executá-lo. Reutilize o mesmo nome para preenchê-lo em vários lugares de uma vez.", + "commandVariablesDefaultNote": "Adicione um valor padrão após um sinal de igual dentro de um marcador para preencher o prompt previamente.", + "commandVariablesTemplateNote": "Apenas identificadores simples viram variáveis, então templates que usam pontos iniciais, espaços ou pipes são executados sem alteração. Coloque uma barra invertida antes de um marcador para mantê-lo literal." }, "keyboardShortcuts": { "title": "Atalhos de Teclado", diff --git a/web/messages/ru.json b/web/messages/ru.json index 5eabc42003fb..aab2e0c836ad 100644 --- a/web/messages/ru.json +++ b/web/messages/ru.json @@ -964,8 +964,9 @@ "restartNew": "Создать новый workspace (по умолчанию)", "fieldFolder": "Необязательный путь к папке через / (например, Project/Linting), группирующий команду в палитре команд", "commandVariables": "Переменные команды", - "commandVariablesDesc": "Добавьте в команду подстановки {{variable}}, и cmux запросит каждое значение перед запуском. Используйте одно и то же имя повторно, чтобы заполнить его сразу в нескольких местах.", - "commandVariablesDefaultNote": "Используйте {{variable=default}}, чтобы заранее подставить в запрос значение по умолчанию." + "commandVariablesDesc": "Добавьте в команду заполнители, и cmux запросит каждое значение перед запуском. Используйте одно и то же имя повторно, чтобы заполнить его сразу в нескольких местах.", + "commandVariablesDefaultNote": "Добавьте значение по умолчанию после знака равенства внутри заполнителя, чтобы заранее заполнить запрос.", + "commandVariablesTemplateNote": "Переменными становятся только простые идентификаторы, поэтому шаблоны с начальными точками, пробелами или конвейерами выполняются без изменений. Поставьте обратную косую черту перед заполнителем, чтобы сохранить его буквально." }, "keyboardShortcuts": { "title": "Горячие клавиши", diff --git a/web/messages/th.json b/web/messages/th.json index 2cbd397b8d7e..e31aa36d9951 100644 --- a/web/messages/th.json +++ b/web/messages/th.json @@ -964,8 +964,9 @@ "restartNew": "สร้าง workspace ใหม่ (ค่าเริ่มต้น)", "fieldFolder": "เส้นทางโฟลเดอร์เสริมที่คั่นด้วย / (เช่น Project/Linting) สำหรับจัดกลุ่มคำสั่งในคอมมานด์พาเลตต์", "commandVariables": "ตัวแปรของคำสั่ง", - "commandVariablesDesc": "เพิ่มตัวยึด {{variable}} ลงในคำสั่ง แล้ว cmux จะถามค่าแต่ละค่าก่อนเรียกใช้ ใช้ชื่อเดิมซ้ำเพื่อกรอกค่าในหลายตำแหน่งพร้อมกัน", - "commandVariablesDefaultNote": "ใช้ {{variable=default}} เพื่อกรอกค่าเริ่มต้นในกล่องข้อความล่วงหน้า" + "commandVariablesDesc": "เพิ่มตัวยึดลงในคำสั่ง แล้ว cmux จะถามค่าแต่ละค่าก่อนเรียกใช้ ใช้ชื่อเดิมซ้ำเพื่อกรอกค่าในหลายตำแหน่งพร้อมกัน", + "commandVariablesDefaultNote": "เพิ่มค่าเริ่มต้นหลังเครื่องหมายเท่ากับภายในตัวยึดเพื่อกรอกกล่องข้อความล่วงหน้า", + "commandVariablesTemplateNote": "เฉพาะตัวระบุแบบธรรมดาเท่านั้นที่จะกลายเป็นตัวแปร ดังนั้นเทมเพลตที่ใช้จุดนำหน้า ช่องว่าง หรือไปป์จะทำงานโดยไม่เปลี่ยนแปลง ใส่แบ็กสแลชไว้หน้าตัวยึดเพื่อคงไว้ตามตัวอักษร" }, "keyboardShortcuts": { "title": "คีย์ลัด", diff --git a/web/messages/tr.json b/web/messages/tr.json index 63fc2d086110..86ace8e136a4 100644 --- a/web/messages/tr.json +++ b/web/messages/tr.json @@ -964,8 +964,9 @@ "restartNew": "Yeni bir workspace oluştur (varsayılan)", "fieldFolder": "Komutu komut paletinde gruplayan, / ile ayrılmış isteğe bağlı klasör yolu (ör. Project/Linting)", "commandVariables": "Komut değişkenleri", - "commandVariablesDesc": "Bir komuta {{variable}} yer tutucuları ekleyin; cmux çalıştırmadan önce her değeri sorar. Aynı adı yeniden kullanarak birden çok yeri tek seferde doldurun.", - "commandVariablesDefaultNote": "İstemi varsayılan bir değerle önceden doldurmak için {{variable=default}} kullanın." + "commandVariablesDesc": "Bir komuta yer tutucular ekleyin; cmux çalıştırmadan önce her değeri sorar. Aynı adı yeniden kullanarak birden çok yeri tek seferde doldurun.", + "commandVariablesDefaultNote": "İstemi önceden doldurmak için bir yer tutucu içindeki eşittir işaretinden sonra bir varsayılan değer ekleyin.", + "commandVariablesTemplateNote": "Yalnızca düz tanımlayıcılar değişken olur; bu nedenle baştaki noktalar, boşluklar veya borular kullanan şablonlar değişmeden çalışır. Bir yer tutucuyu olduğu gibi bırakmak için önüne ters eğik çizgi koyun." }, "keyboardShortcuts": { "title": "Klavye Kısayolları", diff --git a/web/messages/uk.json b/web/messages/uk.json index d0e49d38c3cc..708d00cf3d47 100644 --- a/web/messages/uk.json +++ b/web/messages/uk.json @@ -964,8 +964,9 @@ "restartNew": "Створити новий workspace (за замовчуванням)", "fieldFolder": "Необов'язковий шлях до теки, розділений / (напр., Project/Linting), що групує команду в палітрі команд", "commandVariables": "Змінні команди", - "commandVariablesDesc": "Додайте до команди заповнювачі {{variable}}, і cmux запитає кожне значення перед запуском. Повторно використовуйте те саме ім'я, щоб заповнити його одразу в кількох місцях.", - "commandVariablesDefaultNote": "Використовуйте {{variable=default}}, щоб заздалегідь підставити в запит значення за замовчуванням." + "commandVariablesDesc": "Додайте до команди заповнювачі, і cmux запитає кожне значення перед запуском. Повторно використовуйте те саме ім'я, щоб заповнити його одразу в кількох місцях.", + "commandVariablesDefaultNote": "Додайте значення за замовчуванням після знака рівності всередині заповнювача, щоб заздалегідь заповнити запит.", + "commandVariablesTemplateNote": "Змінними стають лише прості ідентифікатори, тож шаблони, що використовують початкові крапки, пробіли або канали, виконуються без змін. Поставте зворотну косу риску перед заповнювачем, щоб зберегти його буквально." }, "keyboardShortcuts": { "title": "Клавіатурні скорочення", diff --git a/web/messages/zh-CN.json b/web/messages/zh-CN.json index 03cbad88c6fa..dc9475cca855 100644 --- a/web/messages/zh-CN.json +++ b/web/messages/zh-CN.json @@ -964,8 +964,9 @@ "restartNew": "创建新的 workspace(默认)", "fieldFolder": "可选的以 / 分隔的文件夹路径(例如 Project/Linting),用于在命令面板中对命令进行分组", "commandVariables": "命令变量", - "commandVariablesDesc": "在命令中添加 {{variable}} 占位符,cmux 会在运行前提示输入每个值。重复使用相同的名称即可一次性填充多个位置。", - "commandVariablesDefaultNote": "使用 {{variable=default}} 可为提示预填默认值。" + "commandVariablesDesc": "在命令中添加占位符,cmux 会在运行前提示输入每个值。重复使用相同的名称即可一次性填充多个位置。", + "commandVariablesDefaultNote": "在占位符内的等号后添加默认值,可为提示预填内容。", + "commandVariablesTemplateNote": "只有简单标识符才会成为变量,因此使用前导点、空格或竖线的模板会原样运行。在占位符前加反斜杠可保留其字面形式。" }, "keyboardShortcuts": { "title": "快捷键", diff --git a/web/messages/zh-TW.json b/web/messages/zh-TW.json index 27438208a4e2..1bdd2bb7bd84 100644 --- a/web/messages/zh-TW.json +++ b/web/messages/zh-TW.json @@ -964,8 +964,9 @@ "restartNew": "建立新的 workspace(預設)", "fieldFolder": "選用的以 / 分隔的資料夾路徑(例如 Project/Linting),用於在命令選擇區中將命令分組", "commandVariables": "命令變數", - "commandVariablesDesc": "在命令中加入 {{variable}} 佔位符,cmux 會在執行前提示輸入每個值。重複使用相同的名稱即可一次填入多個位置。", - "commandVariablesDefaultNote": "使用 {{variable=default}} 可為提示預先填入預設值。" + "commandVariablesDesc": "在命令中加入佔位符,cmux 會在執行前提示輸入每個值。重複使用相同的名稱即可一次填入多個位置。", + "commandVariablesDefaultNote": "在佔位符內的等號後加入預設值,即可為提示預先填入內容。", + "commandVariablesTemplateNote": "只有簡單識別碼才會成為變數,因此使用前導點、空格或管線的範本會原樣執行。在佔位符前加上反斜線即可保留其字面形式。" }, "keyboardShortcuts": { "title": "鍵盤快捷鍵", From af53f453ced76093e7d478227c5d878bcc4ccbcb Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 05:14:32 -0700 Subject: [PATCH 04/24] Bump CmuxConfigExecutor length budget for escape-stripping change The backslash-escape handling added three lines (577 -> 580). Refresh just that file's entry in the length budget. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index bea9f0dca844..41d290c02cd4 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -214,7 +214,7 @@ 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift -577 Sources/CmuxConfigExecutor.swift +580 Sources/CmuxConfigExecutor.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 From c188d16ba8daf9aeeb17da3ecd0aab205e0df8bc Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 05:19:06 -0700 Subject: [PATCH 05/24] Shell-quote substituted variable values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review (P1): substitution inserted the entered value directly into the shell command, so a value containing shell metacharacters (e.g. a pasted branch/label like "main; rm -rf /") could break out of the intended command. Each substituted value is now wrapped as a single POSIX-quoted shell argument (single quotes with embedded `'` escaped as `'\''`), so whatever the user types is passed literally. This covers every documented example (`--env {{environment}}` -> `--env 'staging'`, `git checkout {{branch}}` -> `git checkout 'main'`). Escaped `\{{…}}` literals and unrecognized template expressions are left unquoted. Document the quoting in the JSON schema and add tests for metacharacter neutralization and single-quote escaping. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandVariables.swift | 25 +++++++++++++++---- cmuxTests/CmuxCommandVariableTests.swift | 31 ++++++++++++++++++------ web/data/cmux.schema.json | 2 +- 3 files changed, 45 insertions(+), 13 deletions(-) diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift index 17791cac09a8..527705c21b4f 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandVariables.swift @@ -53,10 +53,15 @@ enum CmuxCommandVariableParser { } /// Resolves `command` for execution: replaces every recognized placeholder - /// whose name is present in `values` with its value, leaves placeholders - /// whose name is missing from `values` untouched, leaves non-identifier - /// `{{…}}` template expressions untouched, and strips the escaping - /// backslash from any `\{{…}}` so it becomes a literal `{{…}}`. + /// whose name is present in `values` with its value as a single + /// POSIX-quoted shell argument, leaves placeholders whose name is missing + /// from `values` untouched, leaves non-identifier `{{…}}` template + /// expressions untouched, and strips the escaping backslash from any + /// `\{{…}}` so it becomes a literal `{{…}}`. + /// + /// Values are shell-quoted so that whatever the user types is passed as one + /// literal argument — a value like `main; rm -rf /` cannot break out of the + /// command and run as separate shell words. static func substitute(_ command: String, values: [String: String]) -> String { guard command.contains("{{") else { return command } var result = "" @@ -66,12 +71,22 @@ enum CmuxCommandVariableParser { case .literal(let text): result.append(text) case .variable(let variable, let raw): - result.append(values[variable.name] ?? raw) + if let value = values[variable.name] { + result.append(shellQuote(value)) + } else { + result.append(raw) + } } } return result } + /// Wraps `value` in POSIX single quotes so it is a single literal shell + /// argument, escaping any embedded single quotes as `'\''`. + static func shellQuote(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" + } + // MARK: - Scanning private enum Token { diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index 885286142d02..f87c25832c37 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -85,12 +85,13 @@ final class CmuxCommandVariableParserTests: XCTestCase { // `\{{name}}` is not a variable and the backslash is stripped on run. XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo \\{{name}}"), []) XCTAssertEqual(CmuxCommandVariableParser.substitute("echo \\{{name}}", values: [:]), "echo {{name}}") - // An escaped and an unescaped occurrence can coexist. + // An escaped and an unescaped occurrence can coexist; only the real + // variable is substituted (and shell-quoted). let mixed = "echo \\{{env}} {{env}}" XCTAssertEqual(CmuxCommandVariableParser.variables(in: mixed).map(\.name), ["env"]) XCTAssertEqual( CmuxCommandVariableParser.substitute(mixed, values: ["env": "prod"]), - "echo {{env}} prod" + "echo {{env}} 'prod'" ) } @@ -100,12 +101,12 @@ final class CmuxCommandVariableParserTests: XCTestCase { // MARK: Substitution - func testSubstituteReplacesEveryOccurrence() { + func testSubstituteShellQuotesEveryOccurrence() { let result = CmuxCommandVariableParser.substitute( "echo {{x}} and {{x}}", values: ["x": "hi"] ) - XCTAssertEqual(result, "echo hi and hi") + XCTAssertEqual(result, "echo 'hi' and 'hi'") } func testSubstituteReplacesPlaceholderIncludingDefault() { @@ -113,7 +114,7 @@ final class CmuxCommandVariableParserTests: XCTestCase { "bin/deploy --env {{environment=staging}}", values: ["environment": "production"] ) - XCTAssertEqual(result, "bin/deploy --env production") + XCTAssertEqual(result, "bin/deploy --env 'production'") } func testSubstituteLeavesUnknownPlaceholdersIntact() { @@ -121,7 +122,7 @@ final class CmuxCommandVariableParserTests: XCTestCase { "{{a}}-{{b}}", values: ["a": "x"] ) - XCTAssertEqual(result, "x-{{b}}") + XCTAssertEqual(result, "'x'-{{b}}") } func testSubstituteWithNoPlaceholdersReturnsInput() { @@ -136,7 +137,23 @@ final class CmuxCommandVariableParserTests: XCTestCase { "git checkout {{branch}}", values: ["branch": "feature/new-thing"] ) - XCTAssertEqual(result, "git checkout feature/new-thing") + XCTAssertEqual(result, "git checkout 'feature/new-thing'") + } + + func testSubstituteNeutralizesShellMetacharacters() { + // A value with shell metacharacters is passed as one literal argument, + // never as separate shell words. + let result = CmuxCommandVariableParser.substitute( + "git checkout {{branch}}", + values: ["branch": "main; rm -rf /"] + ) + XCTAssertEqual(result, "git checkout 'main; rm -rf /'") + } + + func testShellQuoteEscapesEmbeddedSingleQuotes() { + XCTAssertEqual(CmuxCommandVariableParser.shellQuote("it's"), "'it'\\''s'") + XCTAssertEqual(CmuxCommandVariableParser.shellQuote(""), "''") + XCTAssertEqual(CmuxCommandVariableParser.shellQuote("plain"), "'plain'") } } diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 009f23e57dcc..92e05d51f067 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -53,7 +53,7 @@ }, "command": { "type": "string", - "description": "Shell command to run. Use {{name}} placeholders (optionally {{name=default}}) to prompt for values before running, for example \"bin/deploy --env {{environment}}\". Only bare identifiers ([A-Za-z_][A-Za-z0-9_-]*) are treated as variables, so Go/Handlebars-style templates such as {{ .Env.FOO }} run unchanged; prefix a placeholder with a backslash (\\{{name}}) to keep a literal {{name}}." + "description": "Shell command to run. Use {{name}} placeholders (optionally {{name=default}}) to prompt for values before running, for example \"bin/deploy --env {{environment}}\". Each entered value is inserted as a single POSIX-quoted shell argument. Only bare identifiers ([A-Za-z_][A-Za-z0-9_-]*) are treated as variables, so Go/Handlebars-style templates such as {{ .Env.FOO }} run unchanged; prefix a placeholder with a backslash (\\{{name}}) to keep a literal {{name}}." }, "folder": { "type": "string", From 505009d66cb9dac347248dd24ed7a29a6bbe0899 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 05:28:58 -0700 Subject: [PATCH 06/24] Address review: value types, schema exclusivity, km cancel, return docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Refactor the static `CmuxCommandVariableParser` enum and `CmuxCommandVariablePrompt` static enum into constructable value types (`CmuxCommandTemplate(rawValue:)` with instance members, and a `CmuxCommandVariablePrompt` struct with an instance `present(in:)`), per the no-ambient-global-state guidance — no static-only namespaces. - Enforce command/workspace exclusivity in the JSON schema with `oneOf`, matching the runtime decoder which requires exactly one. - Add the missing Khmer (`km`) translation for the reused `common.cancel` key. - Document the `prepareShellInputIfAuthorized` return contract: `true` means the request was accepted/presented, not that it executed (consistent with the existing async confirm-dialog path). Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Resources/Localizable.xcstrings | 6 ++ Sources/CmuxCommandVariablePrompt.swift | 43 ++++---- Sources/CmuxCommandVariables.swift | 55 ++++++---- Sources/CmuxConfigExecutor.swift | 57 ++++++----- cmuxTests/CmuxCommandVariableTests.swift | 122 ++++++++++------------- web/data/cmux.schema.json | 10 ++ 7 files changed, 153 insertions(+), 142 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 41d290c02cd4..a86c1d24103b 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -214,7 +214,7 @@ 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift -580 Sources/CmuxConfigExecutor.swift +583 Sources/CmuxConfigExecutor.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 diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index d0671812f1b2..64f2e46199fe 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -66695,6 +66695,12 @@ "state": "translated", "value": "Скасувати" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បោះបង់" + } } } }, diff --git a/Sources/CmuxCommandVariablePrompt.swift b/Sources/CmuxCommandVariablePrompt.swift index dadbf2811f04..e2ad4bf20f10 100644 --- a/Sources/CmuxCommandVariablePrompt.swift +++ b/Sources/CmuxCommandVariablePrompt.swift @@ -11,7 +11,12 @@ import Foundation /// ``CmuxConfigExecutor/prepareShellInputIfAuthorized(_:confirm:actionID:target:configSourcePath:globalConfigPath:displayTitle:icon:iconSourcePath:presentingWindow:onAuthorized:)``, /// wiring the prompt there gives variable support to all of them at once. @MainActor -enum CmuxCommandVariablePrompt { +struct CmuxCommandVariablePrompt { + /// The variables to prompt for, in display order. + let variables: [CmuxCommandVariable] + /// Optional dialog title (typically the command's display name). + let displayTitle: String? + /// Presents the variable prompt and invokes `completion` with the collected /// `[name: value]` map when the user confirms. Cancelling does nothing. /// @@ -19,10 +24,8 @@ enum CmuxCommandVariablePrompt { /// non-empty `variables`). When `variables` is empty the completion runs /// immediately with an empty map. @discardableResult - static func present( - variables: [CmuxCommandVariable], - displayTitle: String?, - presentingWindow: NSWindow?, + func present( + in presentingWindow: NSWindow?, completion: @escaping ([String: String]) -> Void ) -> Bool { guard !variables.isEmpty else { @@ -51,17 +54,18 @@ enum CmuxCommandVariablePrompt { defaultValue: "Cancel" )) - let fields = makeFields(for: variables) - alert.accessoryView = makeAccessoryView(variables: variables, fields: fields) + let fields = makeFields() + alert.accessoryView = makeAccessoryView(fields: fields) alert.layout() if let firstField = fields.first { alert.window.initialFirstResponder = firstField } + let captured = variables let handler: (NSApplication.ModalResponse) -> Void = { response in guard response == .alertFirstButtonReturn else { return } var values: [String: String] = [:] - for (variable, field) in zip(variables, fields) { + for (variable, field) in zip(captured, fields) { values[variable.name] = field.stringValue } completion(values) @@ -83,7 +87,7 @@ enum CmuxCommandVariablePrompt { private static let labelToInputGap: CGFloat = 3 private static let rowGap: CGFloat = 10 - private static func makeFields(for variables: [CmuxCommandVariable]) -> [NSTextField] { + private func makeFields() -> [NSTextField] { variables.map { variable in let field = NSTextField(string: variable.defaultValue ?? "") field.placeholderString = variable.name @@ -95,15 +99,12 @@ enum CmuxCommandVariablePrompt { } } - private static func makeAccessoryView( - variables: [CmuxCommandVariable], - fields: [NSTextField] - ) -> NSView { - let rowHeight = labelHeight + labelToInputGap + inputHeight + private func makeAccessoryView(fields: [NSTextField]) -> NSView { + let rowHeight = Self.labelHeight + Self.labelToInputGap + Self.inputHeight let totalHeight = CGFloat(variables.count) * rowHeight - + CGFloat(max(0, variables.count - 1)) * rowGap + + CGFloat(max(0, variables.count - 1)) * Self.rowGap let container = FlippedView( - frame: NSRect(x: 0, y: 0, width: fieldWidth, height: totalHeight) + frame: NSRect(x: 0, y: 0, width: Self.fieldWidth, height: totalHeight) ) var y: CGFloat = 0 @@ -112,18 +113,18 @@ enum CmuxCommandVariablePrompt { label.font = NSFont.systemFont(ofSize: 11, weight: .semibold) label.textColor = .secondaryLabelColor label.lineBreakMode = .byTruncatingTail - label.frame = NSRect(x: 0, y: y, width: fieldWidth, height: labelHeight) + label.frame = NSRect(x: 0, y: y, width: Self.fieldWidth, height: Self.labelHeight) container.addSubview(label) field.frame = NSRect( x: 0, - y: y + labelHeight + labelToInputGap, - width: fieldWidth, - height: inputHeight + y: y + Self.labelHeight + Self.labelToInputGap, + width: Self.fieldWidth, + height: Self.inputHeight ) container.addSubview(field) - y += rowHeight + rowGap + y += rowHeight + Self.rowGap } // Tab order: walk the fields top-to-bottom, then loop back to the first. diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift index 527705c21b4f..2d743f88e6c3 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandVariables.swift @@ -16,8 +16,11 @@ struct CmuxCommandVariable: Equatable, Sendable { let defaultValue: String? } -/// Parses and substitutes `{{variable}}` placeholders inside custom command -/// strings. +/// A custom command string that may contain `{{variable}}` placeholders. +/// +/// Wrapping the command in a value type keeps the placeholder logic on a +/// constructable type (`CmuxCommandTemplate(rawValue:)`) rather than a static +/// namespace. /// /// Grammar (deliberately narrow so it does not regress shell commands that /// embed Go/Handlebars-style `{{…}}` templates): @@ -31,29 +34,36 @@ struct CmuxCommandVariable: Equatable, Sendable { /// completely untouched and runs as-is. /// - Prefix the placeholder with a backslash (`\{{name}}`) to force a literal /// `{{name}}`; cmux strips the backslash and never prompts for it. -enum CmuxCommandVariableParser { - /// Returns the ordered, de-duplicated variables found in `command`, - /// preserving first-occurrence order. When the same name appears more than - /// once, the first occurrence's default value wins. - static func variables(in command: String) -> [CmuxCommandVariable] { - guard command.contains("{{") else { return [] } +struct CmuxCommandTemplate { + /// The raw command string, exactly as written in `cmux.json`. + let rawValue: String + + init(rawValue: String) { + self.rawValue = rawValue + } + + /// The ordered, de-duplicated variables in the command, preserving + /// first-occurrence order. When the same name appears more than once, the + /// first occurrence's default value wins. + var variables: [CmuxCommandVariable] { + guard rawValue.contains("{{") else { return [] } var seen = Set() var result: [CmuxCommandVariable] = [] - for case let .variable(variable, _) in scan(command) where seen.insert(variable.name).inserted { + for case let .variable(variable, _) in scan() where seen.insert(variable.name).inserted { result.append(variable) } return result } - /// Whether `command` contains at least one recognized variable placeholder. - static func containsVariables(_ command: String) -> Bool { - guard command.contains("{{") else { return false } - for case .variable in scan(command) { return true } + /// Whether the command contains at least one recognized variable placeholder. + var containsVariables: Bool { + guard rawValue.contains("{{") else { return false } + for case .variable in scan() { return true } return false } - /// Resolves `command` for execution: replaces every recognized placeholder - /// whose name is present in `values` with its value as a single + /// Resolves the command for execution: replaces every recognized + /// placeholder whose name is present in `values` with its value as a single /// POSIX-quoted shell argument, leaves placeholders whose name is missing /// from `values` untouched, leaves non-identifier `{{…}}` template /// expressions untouched, and strips the escaping backslash from any @@ -62,17 +72,17 @@ enum CmuxCommandVariableParser { /// Values are shell-quoted so that whatever the user types is passed as one /// literal argument — a value like `main; rm -rf /` cannot break out of the /// command and run as separate shell words. - static func substitute(_ command: String, values: [String: String]) -> String { - guard command.contains("{{") else { return command } + func substituting(_ values: [String: String]) -> String { + guard rawValue.contains("{{") else { return rawValue } var result = "" - result.reserveCapacity(command.count) - for token in scan(command) { + result.reserveCapacity(rawValue.count) + for token in scan() { switch token { case .literal(let text): result.append(text) case .variable(let variable, let raw): if let value = values[variable.name] { - result.append(shellQuote(value)) + result.append(Self.shellQuote(value)) } else { result.append(raw) } @@ -98,7 +108,8 @@ enum CmuxCommandVariableParser { case variable(CmuxCommandVariable, raw: String) } - private static func scan(_ command: String) -> [Token] { + private func scan() -> [Token] { + let command = rawValue var tokens: [Token] = [] var literalStart = command.startIndex var index = command.startIndex @@ -139,7 +150,7 @@ enum CmuxCommandVariableParser { continue } - if let parsed = parse(inner: String(inner)) { + if let parsed = Self.parse(inner: String(inner)) { flushLiteral(upTo: open.lowerBound) tokens.append( .variable( diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index 136e2c6b5baa..b30fb53ccf96 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -121,6 +121,17 @@ struct CmuxConfigExecutor { } } + /// Resolves any `{{variable}}` placeholders, then authorizes and dispatches + /// the command. This single choke point feeds every command entrypoint + /// (palette, surface tab-bar buttons, dock, …), so variable prompting and + /// trust handling apply to all of them without per-surface duplication. + /// + /// - Returns: `true` when the request was accepted for handling — either it + /// was authorized and dispatched, or an asynchronous variable/confirm + /// sheet was presented. As with the existing confirm-dialog path, a + /// `true` result does not guarantee execution: `onAuthorized` is invoked + /// later only if the user fills in the prompt and the action is + /// authorized, and is never called if the user cancels. @discardableResult static func prepareShellInputIfAuthorized( _ rawCommand: String, @@ -135,17 +146,13 @@ struct CmuxConfigExecutor { presentingWindow: NSWindow? = nil, onAuthorized: @escaping (String) -> Void ) -> Bool { - // Resolve any `{{variable}}` placeholders before authorizing/dispatching. - // This single choke point feeds every command entrypoint (palette, - // surface tab-bar buttons, dock, …), so the prompt applies to all of - // them without per-surface duplication. - let variables = CmuxCommandVariableParser.variables(in: rawCommand) + let template = CmuxCommandTemplate(rawValue: rawCommand) + let variables = template.variables guard !variables.isEmpty else { // No variables to prompt for, but still strip any escaped // `\{{…}}` placeholders so they run as literal `{{…}}`. - let resolvedCommand = CmuxCommandVariableParser.substitute(rawCommand, values: [:]) return authorizeSanitizedShellCommand( - resolvedCommand, + template.substituting([:]), confirm: confirm, actionID: actionID, target: target, @@ -160,26 +167,22 @@ struct CmuxConfigExecutor { } let resolvedWindow = presentingWindow ?? NSApp.keyWindow ?? NSApp.mainWindow - return CmuxCommandVariablePrompt.present( - variables: variables, - displayTitle: displayTitle, - presentingWindow: resolvedWindow - ) { values in - let substituted = CmuxCommandVariableParser.substitute(rawCommand, values: values) - _ = authorizeSanitizedShellCommand( - substituted, - confirm: confirm, - actionID: actionID, - target: target, - configSourcePath: configSourcePath, - globalConfigPath: globalConfigPath, - displayTitle: displayTitle, - icon: icon, - iconSourcePath: iconSourcePath, - presentingWindow: resolvedWindow, - onAuthorized: onAuthorized - ) - } + return CmuxCommandVariablePrompt(variables: variables, displayTitle: displayTitle) + .present(in: resolvedWindow) { values in + _ = authorizeSanitizedShellCommand( + template.substituting(values), + confirm: confirm, + actionID: actionID, + target: target, + configSourcePath: configSourcePath, + globalConfigPath: globalConfigPath, + displayTitle: displayTitle, + icon: icon, + iconSourcePath: iconSourcePath, + presentingWindow: resolvedWindow, + onAuthorized: onAuthorized + ) + } } @discardableResult diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index f87c25832c37..6e140e13aeb8 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -8,28 +8,35 @@ import XCTest // MARK: - Variable parsing -final class CmuxCommandVariableParserTests: XCTestCase { +final class CmuxCommandTemplateTests: XCTestCase { + + private func variables(_ command: String) -> [CmuxCommandVariable] { + CmuxCommandTemplate(rawValue: command).variables + } + + private func substitute(_ command: String, _ values: [String: String]) -> String { + CmuxCommandTemplate(rawValue: command).substituting(values) + } func testNoPlaceholdersReturnsEmpty() { - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "npm test"), []) - XCTAssertFalse(CmuxCommandVariableParser.containsVariables("npm test")) + XCTAssertEqual(variables("npm test"), []) + XCTAssertFalse(CmuxCommandTemplate(rawValue: "npm test").containsVariables) } func testSinglePlaceholder() { - let vars = CmuxCommandVariableParser.variables(in: "bin/deploy --env {{environment}}") - XCTAssertEqual(vars, [CmuxCommandVariable(name: "environment", defaultValue: nil)]) - XCTAssertTrue(CmuxCommandVariableParser.containsVariables("bin/deploy --env {{environment}}")) + XCTAssertEqual(variables("bin/deploy --env {{environment}}"), + [CmuxCommandVariable(name: "environment", defaultValue: nil)]) + XCTAssertTrue(CmuxCommandTemplate(rawValue: "bin/deploy --env {{environment}}").containsVariables) } func testPlaceholderWithDefault() { - let vars = CmuxCommandVariableParser.variables(in: "bin/deploy --env {{environment=staging}}") - XCTAssertEqual(vars, [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) + XCTAssertEqual(variables("bin/deploy --env {{environment=staging}}"), + [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) } func testWhitespaceIsTrimmed() { - let vars = CmuxCommandVariableParser.variables(in: "echo {{ name }} {{ env = prod }}") XCTAssertEqual( - vars, + variables("echo {{ name }} {{ env = prod }}"), [ CmuxCommandVariable(name: "name", defaultValue: nil), CmuxCommandVariable(name: "env", defaultValue: "prod"), @@ -38,122 +45,95 @@ final class CmuxCommandVariableParserTests: XCTestCase { } func testMultipleDistinctPlaceholdersPreserveOrder() { - let command = "bin/deploy --env {{environment}} --branch {{branch}}" - let vars = CmuxCommandVariableParser.variables(in: command) - XCTAssertEqual(vars.map(\.name), ["environment", "branch"]) + XCTAssertEqual(variables("bin/deploy --env {{environment}} --branch {{branch}}").map(\.name), + ["environment", "branch"]) } func testDuplicatePlaceholdersAreDeduplicatedKeepingFirstDefault() { - let command = "echo {{env=a}} && deploy {{env=b}}" - let vars = CmuxCommandVariableParser.variables(in: command) - XCTAssertEqual(vars, [CmuxCommandVariable(name: "env", defaultValue: "a")]) + XCTAssertEqual(variables("echo {{env=a}} && deploy {{env=b}}"), + [CmuxCommandVariable(name: "env", defaultValue: "a")]) } func testNameAllowsBareIdentifiers() { - let vars = CmuxCommandVariableParser.variables(in: "x {{branch_name}} {{RAILS_ENV}} {{my-var}}") - XCTAssertEqual(vars.map(\.name), ["branch_name", "RAILS_ENV", "my-var"]) + XCTAssertEqual(variables("x {{branch_name}} {{RAILS_ENV}} {{my-var}}").map(\.name), + ["branch_name", "RAILS_ENV", "my-var"]) } func testEmptyPlaceholderIsIgnored() { - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{}} {{ }}"), []) + XCTAssertEqual(variables("echo {{}} {{ }}"), []) } func testShellSyntaxIsNotMistakenForVariables() { // Names with shell-special characters keep the braces literal so // ordinary shell snippets are never treated as variables. - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{ $(date) }}"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "awk '{{ print $1 | sort }}'"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{1+1}}"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{a/b}}"), []) + XCTAssertEqual(variables("echo {{ $(date) }}"), []) + XCTAssertEqual(variables("awk '{{ print $1 | sort }}'"), []) + XCTAssertEqual(variables("echo {{1+1}}"), []) + XCTAssertEqual(variables("echo {{a/b}}"), []) } func testTemplateExpressionsAreLeftUntouched() { // Go/Handlebars-style templates (leading dot, internal spaces, pipes, // functions) must not be mistaken for cmux variables, so existing // templated shell commands keep running unchanged. - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "gomplate -i '{{ .Env.FOO }}'"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{ range .Items }}'"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{ name | upper }}'"), []) - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo '{{.value}}'"), []) - XCTAssertEqual( - CmuxCommandVariableParser.substitute("gomplate -i '{{ .Env.FOO }}'", values: ["FOO": "x"]), - "gomplate -i '{{ .Env.FOO }}'" - ) + XCTAssertEqual(variables("gomplate -i '{{ .Env.FOO }}'"), []) + XCTAssertEqual(variables("echo '{{ range .Items }}'"), []) + XCTAssertEqual(variables("echo '{{ name | upper }}'"), []) + XCTAssertEqual(variables("echo '{{.value}}'"), []) + XCTAssertEqual(substitute("gomplate -i '{{ .Env.FOO }}'", ["FOO": "x"]), + "gomplate -i '{{ .Env.FOO }}'") } func testBackslashEscapeProducesLiteralBraces() { // `\{{name}}` is not a variable and the backslash is stripped on run. - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo \\{{name}}"), []) - XCTAssertEqual(CmuxCommandVariableParser.substitute("echo \\{{name}}", values: [:]), "echo {{name}}") + XCTAssertEqual(variables("echo \\{{name}}"), []) + XCTAssertEqual(substitute("echo \\{{name}}", [:]), "echo {{name}}") // An escaped and an unescaped occurrence can coexist; only the real // variable is substituted (and shell-quoted). let mixed = "echo \\{{env}} {{env}}" - XCTAssertEqual(CmuxCommandVariableParser.variables(in: mixed).map(\.name), ["env"]) - XCTAssertEqual( - CmuxCommandVariableParser.substitute(mixed, values: ["env": "prod"]), - "echo {{env}} 'prod'" - ) + XCTAssertEqual(variables(mixed).map(\.name), ["env"]) + XCTAssertEqual(substitute(mixed, ["env": "prod"]), "echo {{env}} 'prod'") } func testNewlineInsidePlaceholderIsIgnored() { - XCTAssertEqual(CmuxCommandVariableParser.variables(in: "echo {{na\nme}}"), []) + XCTAssertEqual(variables("echo {{na\nme}}"), []) } // MARK: Substitution func testSubstituteShellQuotesEveryOccurrence() { - let result = CmuxCommandVariableParser.substitute( - "echo {{x}} and {{x}}", - values: ["x": "hi"] - ) - XCTAssertEqual(result, "echo 'hi' and 'hi'") + XCTAssertEqual(substitute("echo {{x}} and {{x}}", ["x": "hi"]), "echo 'hi' and 'hi'") } func testSubstituteReplacesPlaceholderIncludingDefault() { - let result = CmuxCommandVariableParser.substitute( - "bin/deploy --env {{environment=staging}}", - values: ["environment": "production"] - ) - XCTAssertEqual(result, "bin/deploy --env 'production'") + XCTAssertEqual(substitute("bin/deploy --env {{environment=staging}}", ["environment": "production"]), + "bin/deploy --env 'production'") } func testSubstituteLeavesUnknownPlaceholdersIntact() { - let result = CmuxCommandVariableParser.substitute( - "{{a}}-{{b}}", - values: ["a": "x"] - ) - XCTAssertEqual(result, "'x'-{{b}}") + XCTAssertEqual(substitute("{{a}}-{{b}}", ["a": "x"]), "'x'-{{b}}") } func testSubstituteWithNoPlaceholdersReturnsInput() { - XCTAssertEqual( - CmuxCommandVariableParser.substitute("npm test", values: ["x": "y"]), - "npm test" - ) + XCTAssertEqual(substitute("npm test", ["x": "y"]), "npm test") } func testSubstitutePreservesValuesWithSpecialCharacters() { - let result = CmuxCommandVariableParser.substitute( - "git checkout {{branch}}", - values: ["branch": "feature/new-thing"] - ) - XCTAssertEqual(result, "git checkout 'feature/new-thing'") + XCTAssertEqual(substitute("git checkout {{branch}}", ["branch": "feature/new-thing"]), + "git checkout 'feature/new-thing'") } func testSubstituteNeutralizesShellMetacharacters() { // A value with shell metacharacters is passed as one literal argument, // never as separate shell words. - let result = CmuxCommandVariableParser.substitute( - "git checkout {{branch}}", - values: ["branch": "main; rm -rf /"] - ) - XCTAssertEqual(result, "git checkout 'main; rm -rf /'") + XCTAssertEqual(substitute("git checkout {{branch}}", ["branch": "main; rm -rf /"]), + "git checkout 'main; rm -rf /'") } func testShellQuoteEscapesEmbeddedSingleQuotes() { - XCTAssertEqual(CmuxCommandVariableParser.shellQuote("it's"), "'it'\\''s'") - XCTAssertEqual(CmuxCommandVariableParser.shellQuote(""), "''") - XCTAssertEqual(CmuxCommandVariableParser.shellQuote("plain"), "'plain'") + XCTAssertEqual(CmuxCommandTemplate.shellQuote("it's"), "'it'\\''s'") + XCTAssertEqual(CmuxCommandTemplate.shellQuote(""), "''") + XCTAssertEqual(CmuxCommandTemplate.shellQuote("plain"), "'plain'") } } diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 92e05d51f067..91130ea71623 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -37,6 +37,16 @@ "items": { "type": "object", "additionalProperties": true, + "oneOf": [ + { + "required": ["command"], + "not": { "required": ["workspace"] } + }, + { + "required": ["workspace"], + "not": { "required": ["command"] } + } + ], "properties": { "name": { "type": "string", From 56cf338b3c2cb4eadce5e33abfceb14143ce1d38 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 06:06:13 -0700 Subject: [PATCH 07/24] Only treat unquoted {{name}} as variables (quote-aware scanning) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review (P1 + P2): the previous approach shell-quoted substituted values but could still be unsafe when the author wrapped a placeholder in quotes (`deploy '{{branch}}'` -> the value could break out), and it intercepted bare template placeholders like `helm ... '{{tag}}'`. Scan the command tracking single/double shell-quote state and treat a `{{identifier}}` as a cmux variable only when it appears at an unquoted position. One rule fixes both: - Quoted placeholders (`'{{tag}}'`, `"{{x}}"`, `'{{ .Env.FOO }}'`) are template text and run unchanged — existing template commands are not intercepted. - Variables only ever substitute at unquoted positions, where the value is POSIX-quoted as one argument and cannot break out of the command. Drops the backslash escape (quoting a placeholder is now the way to keep it literal). Updates schema/docs and replaces the escape tests with quote-position and mixed quoted/unquoted coverage. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandVariables.swift | 94 ++++++++++++------------ Sources/CmuxConfigExecutor.swift | 5 +- cmuxTests/CmuxCommandVariableTests.swift | 49 ++++++------ web/data/cmux.schema.json | 2 +- web/messages/ar.json | 2 +- web/messages/bs.json | 2 +- web/messages/da.json | 2 +- web/messages/de.json | 2 +- web/messages/en.json | 2 +- web/messages/es.json | 2 +- web/messages/fr.json | 2 +- web/messages/it.json | 2 +- web/messages/ja.json | 2 +- web/messages/km.json | 2 +- web/messages/ko.json | 2 +- web/messages/no.json | 2 +- web/messages/pl.json | 2 +- web/messages/pt-BR.json | 2 +- web/messages/ru.json | 2 +- web/messages/th.json | 2 +- web/messages/tr.json | 2 +- web/messages/uk.json | 2 +- web/messages/zh-CN.json | 2 +- web/messages/zh-TW.json | 2 +- 24 files changed, 96 insertions(+), 94 deletions(-) diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift index 2d743f88e6c3..7321953121bf 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandVariables.swift @@ -23,7 +23,7 @@ struct CmuxCommandVariable: Equatable, Sendable { /// namespace. /// /// Grammar (deliberately narrow so it does not regress shell commands that -/// embed Go/Handlebars-style `{{…}}` templates): +/// embed Go/Handlebars/Mustache-style `{{…}}` templates): /// - A placeholder is `{{` … `}}` whose inner text contains no `{`, `}`, or /// newline. /// - The name is the text before an optional `=`; the text after `=` is a @@ -31,9 +31,13 @@ struct CmuxCommandVariable: Equatable, Sendable { /// - The name must be a *bare identifier*: a letter or `_` followed by letters, /// digits, `_`, or `-`. Anything else — a leading `.` (`{{ .Env.FOO }}`), /// internal spaces (`{{ range .Items }}`), pipes, or function calls — is left -/// completely untouched and runs as-is. -/// - Prefix the placeholder with a backslash (`\{{name}}`) to force a literal -/// `{{name}}`; cmux strips the backslash and never prompts for it. +/// completely untouched. +/// - A placeholder is only treated as a cmux variable when it appears at an +/// **unquoted** shell position. A `{{name}}` inside single or double quotes +/// (e.g. `gomplate -i '{{tag}}'`) is left literal and runs unchanged, so +/// existing template commands are not intercepted. This also means the +/// substituted value is always inserted at an unquoted position, where it can +/// be safely POSIX-quoted as a single argument. struct CmuxCommandTemplate { /// The raw command string, exactly as written in `cmux.json`. let rawValue: String @@ -100,20 +104,24 @@ struct CmuxCommandTemplate { // MARK: - Scanning private enum Token { - /// Text emitted verbatim (plain text, escaped placeholders with the - /// backslash removed, and unrecognized `{{…}}` template expressions). + /// Text emitted verbatim (plain text, quoted text, and unrecognized + /// `{{…}}` template expressions). case literal(String) /// A recognized variable placeholder; `raw` is the original `{{…}}` /// text used when no value is supplied. case variable(CmuxCommandVariable, raw: String) } + /// Walks the command tracking single/double shell-quote state, recognizing a + /// `{{identifier}}` placeholder only when it appears at an unquoted position. private func scan() -> [Token] { let command = rawValue var tokens: [Token] = [] var literalStart = command.startIndex var index = command.startIndex let end = command.endIndex + var inSingleQuote = false + var inDoubleQuote = false func flushLiteral(upTo upperBound: String.Index) { if literalStart < upperBound { @@ -122,49 +130,43 @@ struct CmuxCommandTemplate { } while index < end { - guard let open = command.range(of: "{{", range: index.. command.startIndex - && command[command.index(before: open.lowerBound)] == "\\" - if isEscaped { - // Drop the escaping backslash and emit a literal "{{…}}". - let backslash = command.index(before: open.lowerBound) - flushLiteral(upTo: backslash) - tokens.append(.literal(String(command[open.lowerBound.. Date: Fri, 26 Jun 2026 06:24:01 -0700 Subject: [PATCH 08/24] Honor shell escapes in quote scan; authorize before prompting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review: - [P1] The quote scanner toggled state on every quote, so a backslash-escaped quote (`echo "... \" {{x}} ..."`) made a still-quoted placeholder look unquoted and get substituted, defeating the quoting safety. The scanner now models shell escaping: backslash escapes the next character outside single quotes (so `\"` does not close a double-quoted span), and single quotes are literal-only. A placeholder after an escaped quote stays quoted and is not a variable. - [P2] The variable prompt ran before the project-action trust/confirm dialog, letting an untrusted .cmux/cmux.json solicit values first. Authorization now happens first, keyed on the command template (with its {{…}} placeholders) and shown before any values are collected; only after the user approves does cmux prompt for variables, substitute, and dispatch. Trust now also persists across values since it is keyed on the template. Adds an escaped-quote regression test. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandVariables.swift | 38 +++++++++-- Sources/CmuxConfigExecutor.swift | 87 +++++++----------------- cmuxTests/CmuxCommandVariableTests.swift | 10 +++ 3 files changed, 67 insertions(+), 68 deletions(-) diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandVariables.swift index 7321953121bf..76cb21e73f81 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandVariables.swift @@ -112,8 +112,9 @@ struct CmuxCommandTemplate { case variable(CmuxCommandVariable, raw: String) } - /// Walks the command tracking single/double shell-quote state, recognizing a - /// `{{identifier}}` placeholder only when it appears at an unquoted position. + /// Walks the command tracking single/double shell-quote state (honouring + /// backslash escapes outside single quotes), recognizing a `{{identifier}}` + /// placeholder only when it appears at an unquoted position. private func scan() -> [Token] { let command = rawValue var tokens: [Token] = [] @@ -132,7 +133,30 @@ struct CmuxCommandTemplate { while index < end { let character = command[index] - if !inSingleQuote, !inDoubleQuote, character == "{" { + if inSingleQuote { + // Inside single quotes nothing is special except the closing + // quote — not even backslash. + if character == "'" { inSingleQuote = false } + index = command.index(after: index) + continue + } + + if character == "\\" { + // A backslash escapes the next character in unquoted and + // double-quoted text, so e.g. `\"` does not change quote state. + let next = command.index(after: index) + index = next < end ? command.index(after: next) : end + continue + } + + if inDoubleQuote { + if character == "\"" { inDoubleQuote = false } + index = command.index(after: index) + continue + } + + // Unquoted context: a `{{identifier}}` here is a cmux variable. + if character == "{" { let afterFirstBrace = command.index(after: index) if afterFirstBrace < end, command[afterFirstBrace] == "{" { let innerStart = command.index(after: afterFirstBrace) @@ -161,10 +185,10 @@ struct CmuxCommandTemplate { } } - if character == "'", !inDoubleQuote { - inSingleQuote.toggle() - } else if character == "\"", !inSingleQuote { - inDoubleQuote.toggle() + if character == "'" { + inSingleQuote = true + } else if character == "\"" { + inDoubleQuote = true } index = command.index(after: index) } diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index d45cadfdd58e..0d782958049b 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -121,17 +121,22 @@ struct CmuxConfigExecutor { } } - /// Resolves any `{{variable}}` placeholders, then authorizes and dispatches - /// the command. This single choke point feeds every command entrypoint + /// Authorizes a command, then resolves any `{{variable}}` placeholders and + /// dispatches it. This single choke point feeds every command entrypoint /// (palette, surface tab-bar buttons, dock, …), so variable prompting and /// trust handling apply to all of them without per-surface duplication. /// + /// The trust/confirm prompt is keyed on the command *template* (with its + /// `{{…}}` placeholders) and shown **before** any variable values are + /// collected, so an untrusted project config cannot solicit input ahead of + /// the provenance warning, and trusting the action persists across values. + /// /// - Returns: `true` when the request was accepted for handling — either it - /// was authorized and dispatched, or an asynchronous variable/confirm + /// was authorized and dispatched, or an asynchronous confirm/variable /// sheet was presented. As with the existing confirm-dialog path, a /// `true` result does not guarantee execution: `onAuthorized` is invoked - /// later only if the user fills in the prompt and the action is - /// authorized, and is never called if the user cancels. + /// later only if the action is authorized and the user fills in the + /// prompt, and is never called if the user cancels. @discardableResult static func prepareShellInputIfAuthorized( _ rawCommand: String, @@ -148,61 +153,11 @@ struct CmuxConfigExecutor { ) -> Bool { let template = CmuxCommandTemplate(rawValue: rawCommand) let variables = template.variables - guard !variables.isEmpty else { - // No unquoted `{{variable}}` placeholders; run the command as-is. - return authorizeSanitizedShellCommand( - rawCommand, - confirm: confirm, - actionID: actionID, - target: target, - configSourcePath: configSourcePath, - globalConfigPath: globalConfigPath, - displayTitle: displayTitle, - icon: icon, - iconSourcePath: iconSourcePath, - presentingWindow: presentingWindow, - onAuthorized: onAuthorized - ) - } - - let resolvedWindow = presentingWindow ?? NSApp.keyWindow ?? NSApp.mainWindow - return CmuxCommandVariablePrompt(variables: variables, displayTitle: displayTitle) - .present(in: resolvedWindow) { values in - _ = authorizeSanitizedShellCommand( - template.substituting(values), - confirm: confirm, - actionID: actionID, - target: target, - configSourcePath: configSourcePath, - globalConfigPath: globalConfigPath, - displayTitle: displayTitle, - icon: icon, - iconSourcePath: iconSourcePath, - presentingWindow: resolvedWindow, - onAuthorized: onAuthorized - ) - } - } - - @discardableResult - private static func authorizeSanitizedShellCommand( - _ rawCommand: String, - confirm: Bool, - actionID: String, - target: CmuxConfigTerminalCommandTarget, - configSourcePath: String?, - globalConfigPath: String, - displayTitle: String?, - icon: CmuxButtonIcon?, - iconSourcePath: String?, - presentingWindow: NSWindow?, - onAuthorized: @escaping (String) -> Void - ) -> Bool { - let shellCommand = sanitizeForDisplay(rawCommand) - guard !shellCommand.isEmpty else { return false } + let displayCommand = sanitizeForDisplay(rawCommand) + guard !displayCommand.isEmpty else { return false } let descriptor = terminalTrustDescriptor( - command: shellCommand, + command: displayCommand, actionID: actionID, target: target, configSourcePath: configSourcePath, @@ -210,16 +165,26 @@ struct CmuxConfigExecutor { iconSourcePath: iconSourcePath, globalConfigPath: globalConfigPath ) + let resolvedWindow = presentingWindow ?? NSApp.keyWindow ?? NSApp.mainWindow return authorizeProjectActionIfNeeded( descriptor: descriptor, confirm: confirm, configSourcePath: configSourcePath, globalConfigPath: globalConfigPath, - displayCommand: shellCommand, + displayCommand: displayCommand, displayTitle: displayTitle, - presentingWindow: presentingWindow + presentingWindow: resolvedWindow ) { - onAuthorized(shellCommand + "\n") + guard !variables.isEmpty else { + onAuthorized(displayCommand + "\n") + return + } + CmuxCommandVariablePrompt(variables: variables, displayTitle: displayTitle) + .present(in: resolvedWindow) { values in + let resolved = sanitizeForDisplay(template.substituting(values)) + guard !resolved.isEmpty else { return } + onAuthorized(resolved + "\n") + } } } diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index ab398111614a..30b2fe841755 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -96,6 +96,16 @@ final class CmuxCommandTemplateTests: XCTestCase { "deploy 'prod' --label '{{env}}'") } + func testEscapedQuoteKeepsPlaceholderQuoted() { + // A backslash-escaped quote does not close the surrounding quote, so a + // placeholder after it is still quoted and must not be substituted. + let command = "echo \"prefix \\\" {{branch}} suffix\"" + XCTAssertEqual(variables(command), []) + XCTAssertEqual(substitute(command, ["branch": "$(touch /tmp/pwn)"]), command) + // After the double-quoted span closes, an unquoted placeholder is a variable. + XCTAssertEqual(variables("echo \"a \\\" b\" {{env}}").map(\.name), ["env"]) + } + func testNewlineInsidePlaceholderIsIgnored() { XCTAssertEqual(variables("echo {{na\nme}}"), []) } From a774605d88b0baff1ac148636e7420acbaff78c2 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 06:35:35 -0700 Subject: [PATCH 09/24] Make CmuxResolvedConfigAction.folder default explicit The optional already defaults to nil in Swift's synthesized memberwise initializer (the app target compiles and CI's test build succeeded with it), but spell the `= nil` out so the source-compatibility of the existing call sites is obvious to readers and reviewers. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxConfig.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index 895c0ffecc7c..f7b6c32a6edd 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -1488,7 +1488,7 @@ struct CmuxResolvedConfigAction: Identifiable, Sendable, Hashable { var iconSourcePath: String? /// Optional Command Palette folder breadcrumb (e.g. `Project / Linting`), /// shown as the row's trailing badge for folder-organized custom commands. - var folder: String? + var folder: String? = nil var terminalCommand: String? { action.terminalCommand From 88c46f2503fa7fcc74e169c373daf4c3452ad3c5 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 06:57:16 -0700 Subject: [PATCH 10/24] Require non-blank name on command schema entries The new oneOf left command/workspace entries valid without a name, but CmuxCommandDefinition.init(from:) requires a non-blank name. Add required: ["name"] and a \S pattern so editor validation matches what the app actually accepts. Co-Authored-By: Claude Opus 4.8 (1M context) --- web/data/cmux.schema.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 3b903c913e98..215b39b452a6 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -37,6 +37,7 @@ "items": { "type": "object", "additionalProperties": true, + "required": ["name"], "oneOf": [ { "required": ["command"], @@ -50,7 +51,8 @@ "properties": { "name": { "type": "string", - "description": "Display name shown in the Command Palette." + "pattern": "\\S", + "description": "Display name shown in the Command Palette. Must not be blank." }, "description": { "type": "string", From 01084eea4c87b788da302d9a970ed838bae93405 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 07:06:54 -0700 Subject: [PATCH 11/24] Convert command-variable tests to Swift Testing Per the repo testing policy, new non-UI test suites use Swift Testing rather than XCTest. Convert CmuxCommandVariableTests to `@Suite`/`@Test`/`#expect`/ `#require` (the folder suite stays `@MainActor` for the CmuxConfigStore case). No behavior change; same coverage. Co-Authored-By: Claude Opus 4.8 (1M context) --- cmuxTests/CmuxCommandVariableTests.swift | 188 +++++++++++------------ 1 file changed, 94 insertions(+), 94 deletions(-) diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index 30b2fe841755..acc0752881f4 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -1,4 +1,5 @@ -import XCTest +import Foundation +import Testing #if canImport(cmux_DEV) @testable import cmux_DEV @@ -8,7 +9,7 @@ import XCTest // MARK: - Variable parsing -final class CmuxCommandTemplateTests: XCTestCase { +@Suite struct CmuxCommandTemplateTests { private func variables(_ command: String) -> [CmuxCommandVariable] { CmuxCommandTemplate(rawValue: command).variables @@ -18,146 +19,146 @@ final class CmuxCommandTemplateTests: XCTestCase { CmuxCommandTemplate(rawValue: command).substituting(values) } - func testNoPlaceholdersReturnsEmpty() { - XCTAssertEqual(variables("npm test"), []) - XCTAssertFalse(CmuxCommandTemplate(rawValue: "npm test").containsVariables) + @Test func noPlaceholdersReturnsEmpty() { + #expect(variables("npm test").isEmpty) + #expect(!CmuxCommandTemplate(rawValue: "npm test").containsVariables) } - func testSinglePlaceholder() { - XCTAssertEqual(variables("bin/deploy --env {{environment}}"), - [CmuxCommandVariable(name: "environment", defaultValue: nil)]) - XCTAssertTrue(CmuxCommandTemplate(rawValue: "bin/deploy --env {{environment}}").containsVariables) + @Test func singlePlaceholder() { + #expect(variables("bin/deploy --env {{environment}}") + == [CmuxCommandVariable(name: "environment", defaultValue: nil)]) + #expect(CmuxCommandTemplate(rawValue: "bin/deploy --env {{environment}}").containsVariables) } - func testPlaceholderWithDefault() { - XCTAssertEqual(variables("bin/deploy --env {{environment=staging}}"), - [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) + @Test func placeholderWithDefault() { + #expect(variables("bin/deploy --env {{environment=staging}}") + == [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) } - func testWhitespaceIsTrimmed() { - XCTAssertEqual( - variables("echo {{ name }} {{ env = prod }}"), - [ - CmuxCommandVariable(name: "name", defaultValue: nil), - CmuxCommandVariable(name: "env", defaultValue: "prod"), - ] + @Test func whitespaceIsTrimmed() { + #expect( + variables("echo {{ name }} {{ env = prod }}") + == [ + CmuxCommandVariable(name: "name", defaultValue: nil), + CmuxCommandVariable(name: "env", defaultValue: "prod"), + ] ) } - func testMultipleDistinctPlaceholdersPreserveOrder() { - XCTAssertEqual(variables("bin/deploy --env {{environment}} --branch {{branch}}").map(\.name), - ["environment", "branch"]) + @Test func multipleDistinctPlaceholdersPreserveOrder() { + #expect(variables("bin/deploy --env {{environment}} --branch {{branch}}").map(\.name) + == ["environment", "branch"]) } - func testDuplicatePlaceholdersAreDeduplicatedKeepingFirstDefault() { - XCTAssertEqual(variables("echo {{env=a}} && deploy {{env=b}}"), - [CmuxCommandVariable(name: "env", defaultValue: "a")]) + @Test func duplicatePlaceholdersAreDeduplicatedKeepingFirstDefault() { + #expect(variables("echo {{env=a}} && deploy {{env=b}}") + == [CmuxCommandVariable(name: "env", defaultValue: "a")]) } - func testNameAllowsBareIdentifiers() { - XCTAssertEqual(variables("x {{branch_name}} {{RAILS_ENV}} {{my-var}}").map(\.name), - ["branch_name", "RAILS_ENV", "my-var"]) + @Test func nameAllowsBareIdentifiers() { + #expect(variables("x {{branch_name}} {{RAILS_ENV}} {{my-var}}").map(\.name) + == ["branch_name", "RAILS_ENV", "my-var"]) } - func testEmptyPlaceholderIsIgnored() { - XCTAssertEqual(variables("echo {{}} {{ }}"), []) + @Test func emptyPlaceholderIsIgnored() { + #expect(variables("echo {{}} {{ }}").isEmpty) } - func testUnquotedNonIdentifierIsRejected() { + @Test func unquotedNonIdentifierIsRejected() { // At an unquoted position, only bare identifiers are variables; shell // snippets and template expressions keep the braces literal. - XCTAssertEqual(variables("echo {{ $(date) }}"), []) - XCTAssertEqual(variables("echo {{1+1}}"), []) - XCTAssertEqual(variables("echo {{a/b}}"), []) - XCTAssertEqual(variables("gomplate -i {{ .Env.FOO }}"), []) - XCTAssertEqual(variables("echo {{ name | upper }}"), []) + #expect(variables("echo {{ $(date) }}").isEmpty) + #expect(variables("echo {{1+1}}").isEmpty) + #expect(variables("echo {{a/b}}").isEmpty) + #expect(variables("gomplate -i {{ .Env.FOO }}").isEmpty) + #expect(variables("echo {{ name | upper }}").isEmpty) } - func testQuotedPlaceholdersAreLeftLiteral() { + @Test func quotedPlaceholdersAreLeftLiteral() { // A placeholder inside single or double quotes is template text, not a // cmux variable, so existing quoted template commands run unchanged. - XCTAssertEqual(variables("helm --set-template '{{tag}}'"), []) - XCTAssertEqual(variables("echo \"{{x}}\""), []) - XCTAssertEqual(variables("gomplate -i '{{ .Env.FOO }}'"), []) + #expect(variables("helm --set-template '{{tag}}'").isEmpty) + #expect(variables("echo \"{{x}}\"").isEmpty) + #expect(variables("gomplate -i '{{ .Env.FOO }}'").isEmpty) // Even when the author wraps a bare identifier in quotes it is not // intercepted (and therefore cannot be unsafely re-quoted). - XCTAssertEqual(variables("deploy '{{branch}}'"), []) - XCTAssertEqual(substitute("helm --set-template '{{tag}}'", ["tag": "v1"]), - "helm --set-template '{{tag}}'") - XCTAssertEqual(substitute("deploy '{{branch}}'", ["branch": "main; rm -rf /"]), - "deploy '{{branch}}'") + #expect(variables("deploy '{{branch}}'").isEmpty) + #expect(substitute("helm --set-template '{{tag}}'", ["tag": "v1"]) + == "helm --set-template '{{tag}}'") + #expect(substitute("deploy '{{branch}}'", ["branch": "main; rm -rf /"]) + == "deploy '{{branch}}'") } - func testMixedQuotedAndUnquotedOccurrences() { + @Test func mixedQuotedAndUnquotedOccurrences() { // Only the unquoted occurrence is a variable; the quoted one stays literal. let command = "deploy {{env}} --label '{{env}}'" - XCTAssertEqual(variables(command).map(\.name), ["env"]) - XCTAssertEqual(substitute(command, ["env": "prod"]), - "deploy 'prod' --label '{{env}}'") + #expect(variables(command).map(\.name) == ["env"]) + #expect(substitute(command, ["env": "prod"]) == "deploy 'prod' --label '{{env}}'") } - func testEscapedQuoteKeepsPlaceholderQuoted() { + @Test func escapedQuoteKeepsPlaceholderQuoted() { // A backslash-escaped quote does not close the surrounding quote, so a // placeholder after it is still quoted and must not be substituted. let command = "echo \"prefix \\\" {{branch}} suffix\"" - XCTAssertEqual(variables(command), []) - XCTAssertEqual(substitute(command, ["branch": "$(touch /tmp/pwn)"]), command) + #expect(variables(command).isEmpty) + #expect(substitute(command, ["branch": "$(touch /tmp/pwn)"]) == command) // After the double-quoted span closes, an unquoted placeholder is a variable. - XCTAssertEqual(variables("echo \"a \\\" b\" {{env}}").map(\.name), ["env"]) + #expect(variables("echo \"a \\\" b\" {{env}}").map(\.name) == ["env"]) } - func testNewlineInsidePlaceholderIsIgnored() { - XCTAssertEqual(variables("echo {{na\nme}}"), []) + @Test func newlineInsidePlaceholderIsIgnored() { + #expect(variables("echo {{na\nme}}").isEmpty) } // MARK: Substitution - func testSubstituteShellQuotesEveryOccurrence() { - XCTAssertEqual(substitute("echo {{x}} and {{x}}", ["x": "hi"]), "echo 'hi' and 'hi'") + @Test func substituteShellQuotesEveryOccurrence() { + #expect(substitute("echo {{x}} and {{x}}", ["x": "hi"]) == "echo 'hi' and 'hi'") } - func testSubstituteReplacesPlaceholderIncludingDefault() { - XCTAssertEqual(substitute("bin/deploy --env {{environment=staging}}", ["environment": "production"]), - "bin/deploy --env 'production'") + @Test func substituteReplacesPlaceholderIncludingDefault() { + #expect(substitute("bin/deploy --env {{environment=staging}}", ["environment": "production"]) + == "bin/deploy --env 'production'") } - func testSubstituteLeavesUnknownPlaceholdersIntact() { - XCTAssertEqual(substitute("{{a}}-{{b}}", ["a": "x"]), "'x'-{{b}}") + @Test func substituteLeavesUnknownPlaceholdersIntact() { + #expect(substitute("{{a}}-{{b}}", ["a": "x"]) == "'x'-{{b}}") } - func testSubstituteWithNoPlaceholdersReturnsInput() { - XCTAssertEqual(substitute("npm test", ["x": "y"]), "npm test") + @Test func substituteWithNoPlaceholdersReturnsInput() { + #expect(substitute("npm test", ["x": "y"]) == "npm test") } - func testSubstitutePreservesValuesWithSpecialCharacters() { - XCTAssertEqual(substitute("git checkout {{branch}}", ["branch": "feature/new-thing"]), - "git checkout 'feature/new-thing'") + @Test func substitutePreservesValuesWithSpecialCharacters() { + #expect(substitute("git checkout {{branch}}", ["branch": "feature/new-thing"]) + == "git checkout 'feature/new-thing'") } - func testSubstituteNeutralizesShellMetacharacters() { + @Test func substituteNeutralizesShellMetacharacters() { // A value with shell metacharacters is passed as one literal argument, // never as separate shell words. - XCTAssertEqual(substitute("git checkout {{branch}}", ["branch": "main; rm -rf /"]), - "git checkout 'main; rm -rf /'") + #expect(substitute("git checkout {{branch}}", ["branch": "main; rm -rf /"]) + == "git checkout 'main; rm -rf /'") } - func testShellQuoteEscapesEmbeddedSingleQuotes() { - XCTAssertEqual(CmuxCommandTemplate.shellQuote("it's"), "'it'\\''s'") - XCTAssertEqual(CmuxCommandTemplate.shellQuote(""), "''") - XCTAssertEqual(CmuxCommandTemplate.shellQuote("plain"), "'plain'") + @Test func shellQuoteEscapesEmbeddedSingleQuotes() { + #expect(CmuxCommandTemplate.shellQuote("it's") == "'it'\\''s'") + #expect(CmuxCommandTemplate.shellQuote("") == "''") + #expect(CmuxCommandTemplate.shellQuote("plain") == "'plain'") } } // MARK: - Folder organization -final class CmuxCommandFolderTests: XCTestCase { +@MainActor +@Suite struct CmuxCommandFolderTests { private func decode(_ json: String) throws -> CmuxConfigFile { let data = json.data(using: .utf8)! return try JSONDecoder().decode(CmuxConfigFile.self, from: data) } - func testDecodeFolderField() throws { + @Test func decodeFolderField() throws { let config = try decode(""" { "commands": [{ @@ -167,31 +168,30 @@ final class CmuxCommandFolderTests: XCTestCase { }] } """) - XCTAssertEqual(config.commands[0].folder, "Project/Linting") - XCTAssertEqual(config.commands[0].folderComponents, ["Project", "Linting"]) - XCTAssertEqual(config.commands[0].folderBreadcrumb, "Project / Linting") + #expect(config.commands[0].folder == "Project/Linting") + #expect(config.commands[0].folderComponents == ["Project", "Linting"]) + #expect(config.commands[0].folderBreadcrumb == "Project / Linting") } - func testFolderComponentsTrimAndDropEmptySegments() { + @Test func folderComponentsTrimAndDropEmptySegments() { let command = CmuxCommandDefinition( name: "x", command: "echo", folder: " /Project// Linting /" ) - XCTAssertEqual(command.folderComponents, ["Project", "Linting"]) - XCTAssertEqual(command.folderBreadcrumb, "Project / Linting") + #expect(command.folderComponents == ["Project", "Linting"]) + #expect(command.folderBreadcrumb == "Project / Linting") } - func testNilOrBlankFolderHasNoComponents() { - XCTAssertEqual(CmuxCommandDefinition(name: "x", command: "echo").folderComponents, []) - XCTAssertNil(CmuxCommandDefinition(name: "x", command: "echo").folderBreadcrumb) + @Test func nilOrBlankFolderHasNoComponents() { + #expect(CmuxCommandDefinition(name: "x", command: "echo").folderComponents.isEmpty) + #expect(CmuxCommandDefinition(name: "x", command: "echo").folderBreadcrumb == nil) let blank = CmuxCommandDefinition(name: "x", command: "echo", folder: " // ") - XCTAssertEqual(blank.folderComponents, []) - XCTAssertNil(blank.folderBreadcrumb) + #expect(blank.folderComponents.isEmpty) + #expect(blank.folderBreadcrumb == nil) } - @MainActor - func testFolderSurfacesInResolvedPaletteAction() throws { + @Test func folderSurfacesInResolvedPaletteAction() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "cmux-folder-\(UUID().uuidString)", isDirectory: true @@ -213,12 +213,12 @@ final class CmuxCommandFolderTests: XCTestCase { let store = CmuxConfigStore(globalConfigPath: configURL.path, startFileWatchers: false) store.loadAll() - let action = try XCTUnwrap( + let action = try #require( store.paletteCustomActions().first { $0.title.contains("Lint modified files") } ) - XCTAssertEqual(action.folder, "Project / Linting") - XCTAssertTrue(action.keywords.contains("Project")) - XCTAssertTrue(action.keywords.contains("Linting")) - XCTAssertEqual(action.subtitle, "Project / Linting") + #expect(action.folder == "Project / Linting") + #expect(action.keywords.contains("Project")) + #expect(action.keywords.contains("Linting")) + #expect(action.subtitle == "Project / Linting") } } From 7c95bf1d6f8f2d8d27029e36b93c5d4bf3811b15 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 07:21:06 -0700 Subject: [PATCH 12/24] One major type per new file (Aziz file-organization policy) - Split the CmuxCommandVariable DTO into its own file and rename CmuxCommandVariables.swift -> CmuxCommandTemplate.swift so each new source file declares a single major type. - Drop the nested FlippedView helper from CmuxCommandVariablePrompt by laying the accessory rows out in AppKit's native bottom-left coordinate space. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) --- ...iables.swift => CmuxCommandTemplate.swift} | 16 ---------- Sources/CmuxCommandVariable.swift | 19 ++++++++++++ Sources/CmuxCommandVariablePrompt.swift | 29 +++++++++---------- cmux.xcodeproj/project.pbxproj | 12 +++++--- 4 files changed, 41 insertions(+), 35 deletions(-) rename Sources/{CmuxCommandVariables.swift => CmuxCommandTemplate.swift} (91%) create mode 100644 Sources/CmuxCommandVariable.swift diff --git a/Sources/CmuxCommandVariables.swift b/Sources/CmuxCommandTemplate.swift similarity index 91% rename from Sources/CmuxCommandVariables.swift rename to Sources/CmuxCommandTemplate.swift index 76cb21e73f81..cecdbe2b5e05 100644 --- a/Sources/CmuxCommandVariables.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -1,21 +1,5 @@ import Foundation -/// A `{{name}}` (or `{{name=default}}`) placeholder discovered in a custom -/// command's `command` string. -/// -/// Variables let a single `commands` entry be reused with different values: -/// cmux prompts for each variable before running the command and substitutes -/// the entered values back into the shell string. The syntax intentionally -/// matches the existing `{{…}}` convention already used by Vault agent -/// templates so users only have to learn one placeholder form. -struct CmuxCommandVariable: Equatable, Sendable { - /// The placeholder name, e.g. `environment` for `{{environment}}`. - let name: String - /// The optional default value parsed from `{{name=default}}`, used to - /// pre-fill the prompt field. `nil` when the placeholder has no default. - let defaultValue: String? -} - /// A custom command string that may contain `{{variable}}` placeholders. /// /// Wrapping the command in a value type keeps the placeholder logic on a diff --git a/Sources/CmuxCommandVariable.swift b/Sources/CmuxCommandVariable.swift new file mode 100644 index 000000000000..3bf145713968 --- /dev/null +++ b/Sources/CmuxCommandVariable.swift @@ -0,0 +1,19 @@ +import Foundation + +/// A `{{name}}` (or `{{name=default}}`) placeholder discovered in a custom +/// command's `command` string. +/// +/// Variables let a single `commands` entry be reused with different values: +/// cmux prompts for each variable before running the command and substitutes +/// the entered values back into the shell string. The syntax intentionally +/// matches the existing `{{…}}` convention already used by Vault agent +/// templates so users only have to learn one placeholder form. +/// +/// See ``CmuxCommandTemplate`` for the parsing and substitution logic. +struct CmuxCommandVariable: Equatable, Sendable { + /// The placeholder name, e.g. `environment` for `{{environment}}`. + let name: String + /// The optional default value parsed from `{{name=default}}`, used to + /// pre-fill the prompt field. `nil` when the placeholder has no default. + let defaultValue: String? +} diff --git a/Sources/CmuxCommandVariablePrompt.swift b/Sources/CmuxCommandVariablePrompt.swift index e2ad4bf20f10..833a91f8244d 100644 --- a/Sources/CmuxCommandVariablePrompt.swift +++ b/Sources/CmuxCommandVariablePrompt.swift @@ -103,28 +103,31 @@ struct CmuxCommandVariablePrompt { let rowHeight = Self.labelHeight + Self.labelToInputGap + Self.inputHeight let totalHeight = CGFloat(variables.count) * rowHeight + CGFloat(max(0, variables.count - 1)) * Self.rowGap - let container = FlippedView( + let container = NSView( frame: NSRect(x: 0, y: 0, width: Self.fieldWidth, height: totalHeight) ) - var y: CGFloat = 0 - for (variable, field) in zip(variables, fields) { + // Lay the rows out top-to-bottom in AppKit's default bottom-left origin + // coordinate space (no flipped-view subclass needed). + for (offset, pair) in zip(variables, fields).enumerated() { + let (variable, field) = pair + let rowTop = totalHeight - CGFloat(offset) * (rowHeight + Self.rowGap) + let rowBottom = rowTop - rowHeight + let label = NSTextField(labelWithString: variable.name) label.font = NSFont.systemFont(ofSize: 11, weight: .semibold) label.textColor = .secondaryLabelColor label.lineBreakMode = .byTruncatingTail - label.frame = NSRect(x: 0, y: y, width: Self.fieldWidth, height: Self.labelHeight) - container.addSubview(label) - - field.frame = NSRect( + label.frame = NSRect( x: 0, - y: y + Self.labelHeight + Self.labelToInputGap, + y: rowBottom + Self.inputHeight + Self.labelToInputGap, width: Self.fieldWidth, - height: Self.inputHeight + height: Self.labelHeight ) - container.addSubview(field) + container.addSubview(label) - y += rowHeight + Self.rowGap + field.frame = NSRect(x: 0, y: rowBottom, width: Self.fieldWidth, height: Self.inputHeight) + container.addSubview(field) } // Tab order: walk the fields top-to-bottom, then loop back to the first. @@ -134,8 +137,4 @@ struct CmuxCommandVariablePrompt { return container } - - private final class FlippedView: NSView { - override var isFlipped: Bool { true } - } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 8e977e88da93..93cd24fdf6b4 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -272,8 +272,9 @@ C0DE64950000000000000003 /* CMUXCLITestAssertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */; }; 5E55500000000000000000E3 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; 5E55500000000000000000E4 /* CmuxCommandPalette in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55500000000000000000E2 /* CmuxCommandPalette */; }; + C1A2B3C4D5E6F70800006559 /* CmuxCommandTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655A /* CmuxCommandTemplate.swift */; }; + C1A2B3C4D5E6F7080000655D /* CmuxCommandVariable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655E /* CmuxCommandVariable.swift */; }; C1A2B3C4D5E6F7080000655B /* CmuxCommandVariablePrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */; }; - C1A2B3C4D5E6F70800006559 /* CmuxCommandVariables.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */; }; C1A2B3C4D5E6F70800006557 /* CmuxCommandVariableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */; }; A5001650 /* CmuxConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001651 /* CmuxConfig.swift */; }; C0DEF0A40000000000000001 /* CmuxConfigContextMenuTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */; }; @@ -1433,8 +1434,9 @@ C12985000000000000000003 /* CMUXCLISentryTelemetryRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISentryTelemetryRegressionTests.swift; sourceTree = ""; }; C0DE64950000000000000006 /* CMUXCLISessionsListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISessionsListTests.swift; sourceTree = ""; }; C0DE64950000000000000004 /* CMUXCLITestAssertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLITestAssertions.swift; sourceTree = ""; }; + C1A2B3C4D5E6F7080000655A /* CmuxCommandTemplate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandTemplate.swift; sourceTree = ""; }; + C1A2B3C4D5E6F7080000655E /* CmuxCommandVariable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariable.swift; sourceTree = ""; }; C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariablePrompt.swift; sourceTree = ""; }; - C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariables.swift; sourceTree = ""; }; C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxCommandVariableTests.swift; sourceTree = ""; }; A5001651 /* CmuxConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfig.swift; sourceTree = ""; }; C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigContextMenuTests.swift; sourceTree = ""; }; @@ -3020,7 +3022,8 @@ A5001642 /* RemoteInteractiveShellBootstrapBuilder.swift */, A5001641 /* RemoteRelayZshBootstrap.swift */, A5001651 /* CmuxConfig.swift */, - C1A2B3C4D5E6F7080000655A /* CmuxCommandVariables.swift */, + C1A2B3C4D5E6F7080000655A /* CmuxCommandTemplate.swift */, + C1A2B3C4D5E6F7080000655E /* CmuxCommandVariable.swift */, C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */, C10D00040000000000000004 /* CmuxSurfaceTabBarBuiltInAction.swift */, C57B00030000000000000002 /* Workspace+CustomSidebarPane.swift */, @@ -4006,8 +4009,9 @@ C4160A010000000000000001 /* cmuxApp+HistoryMenu.swift in Sources */, A5001001 /* cmuxApp.swift in Sources */, A72C9F4179B54DF38E99A021 /* CmuxCLIPathInstaller.swift in Sources */, + C1A2B3C4D5E6F70800006559 /* CmuxCommandTemplate.swift in Sources */, + C1A2B3C4D5E6F7080000655D /* CmuxCommandVariable.swift in Sources */, C1A2B3C4D5E6F7080000655B /* CmuxCommandVariablePrompt.swift in Sources */, - C1A2B3C4D5E6F70800006559 /* CmuxCommandVariables.swift in Sources */, A5001650 /* CmuxConfig.swift in Sources */, A5001652 /* CmuxConfigExecutor.swift in Sources */, C5D0DEC0CF00000000000A1 /* CmuxConfigStore+ConfigStoreReloading.swift in Sources */, From af33147c12106a1f5ec245fcb49fe475590c1c64 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 07:27:48 -0700 Subject: [PATCH 13/24] Strip terminal control characters from substituted variable values Address review (P1): the resolved command is delivered as interactive terminal input, so line-editor control bytes (Ctrl-U, newline, ESC, DEL, C1) are interpreted by readline/zle before the shell parses the quotes. A value like "\u{15}rm -rf ~ #" could clear the quoted prefix and run as its own command despite the single-quoting. shellQuote now drops C0/C1 control characters and DEL from the value before quoting, so quoting is actually sufficient. Legitimate argument values never need control bytes. Adds a regression test for the Ctrl-U clear-line vector. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandTemplate.swift | 16 +++++++++++++++- cmuxTests/CmuxCommandVariableTests.swift | 13 +++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index cecdbe2b5e05..332e95fdf248 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -81,8 +81,22 @@ struct CmuxCommandTemplate { /// Wraps `value` in POSIX single quotes so it is a single literal shell /// argument, escaping any embedded single quotes as `'\''`. + /// + /// The resolved command is delivered as interactive terminal input, so the + /// line editor (readline/zle) interprets control bytes — Ctrl-U, ESC, an + /// embedded newline — *before* the shell parses the quotes. A value such as + /// `\u{15}rm -rf ~ #` could otherwise clear the quoted prefix and run as its + /// own command. Drop C0/C1 control characters and DEL from the value first + /// so quoting is actually sufficient; legitimate argument values never need + /// them. static func shellQuote(_ value: String) -> String { - "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" + let stripped = value.unicodeScalars.filter { scalar in + !(scalar.value <= 0x1F || scalar.value == 0x7F + || (scalar.value >= 0x80 && scalar.value <= 0x9F)) + } + let escaped = String(String.UnicodeScalarView(stripped)) + .replacingOccurrences(of: "'", with: "'\\''") + return "'" + escaped + "'" } // MARK: - Scanning diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index acc0752881f4..b1ce4a80181f 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -146,6 +146,19 @@ import Testing #expect(CmuxCommandTemplate.shellQuote("") == "''") #expect(CmuxCommandTemplate.shellQuote("plain") == "'plain'") } + + @Test func shellQuoteStripsTerminalControlCharacters() { + // The resolved command is sent as interactive terminal input, so + // line-editor control bytes (Ctrl-U, newline, ESC, DEL) must be removed + // from values — quoting alone does not stop the line editor. + #expect(CmuxCommandTemplate.shellQuote("a\u{15}b") == "'ab'") + #expect(CmuxCommandTemplate.shellQuote("x\ny") == "'xy'") + #expect(CmuxCommandTemplate.shellQuote("e\u{1B}[31m") == "'e[31m'") + #expect(CmuxCommandTemplate.shellQuote("\u{7F}del") == "'del'") + // The Ctrl-U "clear line" injection is neutralized end-to-end. + #expect(substitute("git checkout {{branch}}", ["branch": "\u{15}rm -rf ~ #"]) + == "git checkout 'rm -rf ~ #'") + } } // MARK: - Folder organization From fc172dea0524a2f18645034c521461a5d52d06b1 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 07:36:36 -0700 Subject: [PATCH 14/24] Skip here-doc bodies and comments when scanning for variables Address review (P2): the scanner recognized `{{name}}` anywhere unquoted, including inside here-doc bodies, so a command embedding a template via a heredoc (`cat <<'EOF'\n{{name}}\nEOF`) would prompt and rewrite the template body. Complete the "unquoted shell-word position" rule by also skipping: - here-doc bodies (`< --- Sources/CmuxCommandTemplate.swift | 193 ++++++++++++++++++----- cmuxTests/CmuxCommandVariableTests.swift | 21 +++ 2 files changed, 172 insertions(+), 42 deletions(-) diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index 332e95fdf248..e1d080add042 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -110,77 +110,106 @@ struct CmuxCommandTemplate { case variable(CmuxCommandVariable, raw: String) } - /// Walks the command tracking single/double shell-quote state (honouring - /// backslash escapes outside single quotes), recognizing a `{{identifier}}` - /// placeholder only when it appears at an unquoted position. + /// Walks the command tracking shell-quote state (honouring backslash escapes + /// outside single quotes), here-doc bodies, and comments, recognizing a + /// `{{identifier}}` placeholder only when it appears at an unquoted + /// shell-word position. Quoted text, here-doc bodies (`< [Token] { - let command = rawValue + let chars = Array(rawValue) + let count = chars.count var tokens: [Token] = [] - var literalStart = command.startIndex - var index = command.startIndex - let end = command.endIndex + var literalStart = 0 + var index = 0 var inSingleQuote = false var inDoubleQuote = false + // FIFO of here-doc delimiters opened on the current line whose bodies + // are skipped once the line's newline is reached. + var pendingHeredocs: [(delimiter: String, stripTabs: Bool)] = [] - func flushLiteral(upTo upperBound: String.Index) { + func flushLiteral(upTo upperBound: Int) { if literalStart < upperBound { - tokens.append(.literal(String(command[literalStart.. Bool { + guard i > 0 else { return true } + switch chars[i - 1] { + case " ", "\t", "\n", ";", "&", "|", "(": return true + default: return false + } + } + + /// Parses a `<<`/`<<-` here-doc operator and its delimiter starting at `i` + /// (the first `<`), appending the delimiter to `pending`. Returns the index + /// just past the delimiter word. + private static func consumeHeredocOperator( + _ chars: [Character], + from i: Int, + into pending: inout [(delimiter: String, stripTabs: Bool)] + ) -> Int { + let count = chars.count + var j = i + 2 + var stripTabs = false + if j < count, chars[j] == "-" { stripTabs = true; j += 1 } + while j < count, chars[j] == " " || chars[j] == "\t" { j += 1 } + + var delimiter = "" + loop: while j < count { + let c = chars[j] + switch c { + case "'", "\"": + let quote = c + j += 1 + while j < count, chars[j] != quote { delimiter.append(chars[j]); j += 1 } + if j < count { j += 1 } + case "\\": + j += 1 + if j < count { delimiter.append(chars[j]); j += 1 } + case " ", "\t", "\n", ";", "&", "|", "<", ">", "(", ")": + break loop + default: + delimiter.append(c) + j += 1 + } + } + if !delimiter.isEmpty { pending.append((delimiter, stripTabs)) } + return j + } + + /// Skips here-doc bodies starting at `start`, one per queued delimiter, and + /// returns the index just past the final terminator line. + private static func skipHeredocBodies( + _ chars: [Character], + from start: Int, + delimiters: [(delimiter: String, stripTabs: Bool)] + ) -> Int { + let count = chars.count + var index = start + for (delimiter, stripTabs) in delimiters { + while index < count { + let lineStart = index + while index < count, chars[index] != "\n" { index += 1 } + var line = String(chars[lineStart.. Int? { + var i = start + while i + 1 < chars.count { + if chars[i] == "}", chars[i + 1] == "}" { return i } + i += 1 + } + return nil + } + private static func parse(inner: String) -> (name: String, defaultValue: String?)? { if let equals = inner.firstIndex(of: "=") { let name = inner[..t <<'EOF'\n{{name}}\nEOF").isEmpty) + #expect(substitute("cat < Date: Fri, 26 Jun 2026 07:39:58 -0700 Subject: [PATCH 15/24] Return variable matches instead of a Token enum The scanner emitted a private `Token` enum (the file's second type, flagged by the file-organization policy). Replace it with a scan that returns the variable placeholders and their character ranges; `substituting` reconstructs the literal gaps from those ranges. One major type per file, no behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandTemplate.swift | 92 +++++++++++++------------------ 1 file changed, 38 insertions(+), 54 deletions(-) diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index e1d080add042..dad4eb085f7a 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -37,8 +37,9 @@ struct CmuxCommandTemplate { guard rawValue.contains("{{") else { return [] } var seen = Set() var result: [CmuxCommandVariable] = [] - for case let .variable(variable, _) in scan() where seen.insert(variable.name).inserted { - result.append(variable) + for match in Self.variableMatches(in: Array(rawValue)) + where seen.insert(match.variable.name).inserted { + result.append(match.variable) } return result } @@ -46,8 +47,7 @@ struct CmuxCommandTemplate { /// Whether the command contains at least one recognized variable placeholder. var containsVariables: Bool { guard rawValue.contains("{{") else { return false } - for case .variable in scan() { return true } - return false + return !Self.variableMatches(in: Array(rawValue)).isEmpty } /// Resolves the command for execution: replaces every recognized @@ -62,20 +62,22 @@ struct CmuxCommandTemplate { /// command and run as separate shell words. func substituting(_ values: [String: String]) -> String { guard rawValue.contains("{{") else { return rawValue } + let chars = Array(rawValue) + let matches = Self.variableMatches(in: chars) + guard !matches.isEmpty else { return rawValue } var result = "" - result.reserveCapacity(rawValue.count) - for token in scan() { - switch token { - case .literal(let text): - result.append(text) - case .variable(let variable, let raw): - if let value = values[variable.name] { - result.append(Self.shellQuote(value)) - } else { - result.append(raw) - } + result.reserveCapacity(chars.count) + var cursor = 0 + for match in matches { + result.append(String(chars[cursor.. [Token] { - let chars = Array(rawValue) + /// Finds the `{{identifier}}` placeholders that sit at unquoted shell-word + /// positions, returning each variable with its character range in `chars`. + /// + /// The scan tracks single/double shell-quote state (honouring backslash + /// escapes outside single quotes), here-doc bodies (`< [(variable: CmuxCommandVariable, range: Range)] { + var matches: [(variable: CmuxCommandVariable, range: Range)] = [] let count = chars.count - var tokens: [Token] = [] - var literalStart = 0 var index = 0 var inSingleQuote = false var inDoubleQuote = false @@ -127,12 +122,6 @@ struct CmuxCommandTemplate { // are skipped once the line's newline is reached. var pendingHeredocs: [(delimiter: String, stripTabs: Bool)] = [] - func flushLiteral(upTo upperBound: Int) { - if literalStart < upperBound { - tokens.append(.literal(String(chars[literalStart.. Date: Fri, 26 Jun 2026 07:44:28 -0700 Subject: [PATCH 16/24] Include folder path in custom command identity Address review (P2): command ids were derived from name only, so two foldered commands with the same leaf name (e.g. Frontend/Build and Backend/Build) shared an id and the registration loop silently dropped the second from the Command Palette. Fold the normalized folder path into the id so they stay distinct; folderless commands keep their historical cmux.config.command. id. Adds identity + end-to-end "same leaf name, different folders" tests. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Sources/CmuxConfig.swift | 7 ++++- cmuxTests/CmuxCommandVariableTests.swift | 39 ++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index a86c1d24103b..b017763e27d0 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3435 Sources/CmuxConfig.swift +3440 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index f7b6c32a6edd..799abca70bd9 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -1625,7 +1625,12 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { var folder: String? var id: String { - "cmux.config.command." + (name.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? name) + // Fold the folder path into the identity so same-named commands in + // different folders (e.g. `Frontend/Build` and `Backend/Build`) stay + // distinct rather than colliding. Folderless commands keep their + // historical `cmux.config.command.` id. + let key = (folderComponents + [name]).joined(separator: "/") + return "cmux.config.command." + (key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? key) } /// The trimmed, non-empty components of ``folder`` split on `/`. diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index f8cd83ad66c3..ea3a40addf19 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -225,6 +225,45 @@ import Testing #expect(blank.folderBreadcrumb == nil) } + @Test func folderIsPartOfCommandIdentity() { + // Same leaf name in different folders must produce distinct ids so one + // does not silently hide the other in the Command Palette. + let frontend = CmuxCommandDefinition(name: "Build", command: "x", folder: "Frontend") + let backend = CmuxCommandDefinition(name: "Build", command: "x", folder: "Backend") + let plain = CmuxCommandDefinition(name: "Build", command: "x") + #expect(frontend.id != backend.id) + #expect(frontend.id != plain.id) + // Folderless commands keep their historical id. + #expect(plain.id == "cmux.config.command.Build") + } + + @Test func sameLeafNameInDifferentFoldersBothResolve() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-folder-collide-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + let configURL = root.appendingPathComponent("cmux.json") + try """ + { + "commands": [ + { "name": "Build", "folder": "Frontend", "command": "yarn build" }, + { "name": "Build", "folder": "Backend", "command": "make build" } + ] + } + """.write(to: configURL, atomically: true, encoding: .utf8) + + let store = CmuxConfigStore(globalConfigPath: configURL.path, startFileWatchers: false) + store.loadAll() + + let builds = store.paletteCustomActions().filter { $0.title.contains("Build") } + #expect(builds.count == 2) + #expect(Set(builds.map(\.id)).count == 2) + #expect(Set(builds.compactMap(\.folder)) == ["Frontend", "Backend"]) + } + @Test func folderSurfacesInResolvedPaletteAction() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "cmux-folder-\(UUID().uuidString)", From fa21ef26c75de3167eb62c4259ba2bd503221998 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 08:34:51 -0700 Subject: [PATCH 17/24] De-duplicate loaded commands by identity, not name Follow-up to the folder-identity fix: CmuxConfigStore.loadAll() still de-duped commands by name, so foldered same-leaf-name commands (Frontend/Build, Backend/Build) were dropped at load time before the folder-aware ids were ever used. Key the dedup set by command.id (folder + name) so both load while local config still overrides the matching global command. This is the path the sameLeafNameInDifferentFolders regression test exercises. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Sources/CmuxConfig.swift | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index b017763e27d0..133999e2d917 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3440 Sources/CmuxConfig.swift +3443 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index 799abca70bd9..ce22ffa6bb61 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -2175,7 +2175,10 @@ final class CmuxConfigStore: ObservableObject { func loadAll() { var commands: [CmuxCommandDefinition] = [] - var seenNames = Set() + // Keyed by command identity (folder + name) so local overrides the + // matching global command, while same-named commands in different + // folders both load. + var seenCommandIDs = Set() var sourcePaths: [String: String] = [:] var configuredNewWorkspaceCommandName: String? var configuredNewWorkspaceCommandSourcePath: String? @@ -2229,9 +2232,9 @@ final class CmuxConfigStore: ObservableObject { configuredSurfaceTabBarButtonSourcePath = localPath } for command in localConfig.commands { - if !seenNames.contains(command.name) { + if !seenCommandIDs.contains(command.id) { commands.append(command) - seenNames.insert(command.name) + seenCommandIDs.insert(command.id) if let localPath { sourcePaths[command.id] = localPath } @@ -2264,9 +2267,9 @@ final class CmuxConfigStore: ObservableObject { configuredSurfaceTabBarButtonSourcePath = globalConfigPath } for command in globalConfig.commands { - if !seenNames.contains(command.name) { + if !seenCommandIDs.contains(command.id) { commands.append(command) - seenNames.insert(command.name) + seenCommandIDs.insert(command.id) sourcePaths[command.id] = globalConfigPath } } From b4160233b2ad26456958eb44ed89a05b7b452ad3 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 08:46:22 -0700 Subject: [PATCH 18/24] Fix workspace command resolution and id encoding for folders Address review: - [P1] Custom workspace-command palette actions stored only the command name, so two foldered workspace commands with the same name dispatched whichever loaded first. The custom action now carries the folder-aware command id, and the executor resolves `.workspaceCommand` by id first, falling back to name (user config still references commands by name). - [P2] The identity key joined folder components and name with `/` before encoding, so `folder:"A/B", name:"C"` and `folder:"A", name:"B/C"` collided. Percent-encode each component before joining so distinct (folder, name) pairs always produce distinct ids; folderless commands keep their historical id. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Sources/CmuxConfig.swift | 12 ++++++++---- Sources/CmuxConfigExecutor.swift | 8 ++++++-- cmuxTests/CmuxCommandVariableTests.swift | 5 +++++ 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 133999e2d917..7b9fcdd91c27 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3443 Sources/CmuxConfig.swift +3447 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index ce22ffa6bb61..b14478e21481 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -1627,10 +1627,14 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { var id: String { // Fold the folder path into the identity so same-named commands in // different folders (e.g. `Frontend/Build` and `Backend/Build`) stay - // distinct rather than colliding. Folderless commands keep their + // distinct rather than colliding. Each component is percent-encoded + // *before* joining so a `/` inside a folder or name cannot make two + // different (folder, name) pairs collide. Folderless commands keep their // historical `cmux.config.command.` id. - let key = (folderComponents + [name]).joined(separator: "/") - return "cmux.config.command." + (key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? key) + let key = (folderComponents + [name]) + .map { $0.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? $0 } + .joined(separator: "/") + return "cmux.config.command." + key } /// The trimmed, non-empty components of ``folder`` split on `/`. @@ -2534,7 +2538,7 @@ final class CmuxConfigStore: ObservableObject { tooltip: command.description, action: command.workspace == nil ? .command(command.command ?? "") - : .workspaceCommand(command.name), + : .workspaceCommand(command.id), confirm: command.confirm, terminalCommandTarget: command.workspace == nil ? .currentTerminal : nil, actionSourcePath: sourcePath, diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index 0d782958049b..5dc1c36e543a 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -76,8 +76,12 @@ struct CmuxConfigExecutor { presentingWindow: NSWindow? = nil, onExecuted: (() -> Void)? = nil ) -> Bool { - if let commandName = action.workspaceCommandName, - let command = commands.first(where: { $0.name == commandName }) { + if let commandReference = action.workspaceCommandName, + // Resolve by the folder-aware id first (self-generated custom-command + // actions store it) and fall back to the display name (user config + // references commands by name). + let command = commands.first(where: { $0.id == commandReference }) + ?? commands.first(where: { $0.name == commandReference }) { guard command.workspace != nil else { return false } return execute( command: command, diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index ea3a40addf19..f10fa0372f65 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -235,6 +235,11 @@ import Testing #expect(frontend.id != plain.id) // Folderless commands keep their historical id. #expect(plain.id == "cmux.config.command.Build") + // A `/` inside a folder or name must not make two distinct (folder, + // name) pairs collide on the same id. + let a = CmuxCommandDefinition(name: "C", command: "x", folder: "A/B") + let b = CmuxCommandDefinition(name: "B/C", command: "x", folder: "A") + #expect(a.id != b.id) } @Test func sameLeafNameInDifferentFoldersBothResolve() throws { From 5bc46f0e0812452ccb53d5337ff32779172c68b0 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 08:50:38 -0700 Subject: [PATCH 19/24] Resolve workspace command references by id-then-name everywhere MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up: generated workspace custom actions now carry the folder-aware command id, but the shared new-workspace and surface-button resolvers (resolvedConfiguredNewWorkspaceCommand / resolvedWorkspaceCommand) still matched by name only, so action-reference entrypoints (ui.newWorkspace.action, context menu, tab-bar buttons) would drop those actions. Both resolvers now match the command id first and fall back to the display name, matching the executor — covering every workspace-command resolution path. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Sources/CmuxConfig.swift | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 7b9fcdd91c27..f1a92a2316c0 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3447 Sources/CmuxConfig.swift +3452 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index b14478e21481..29e4138880a6 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -3041,7 +3041,10 @@ final class CmuxConfigStore: ObservableObject { commands: [CmuxCommandDefinition], sourcePaths: [String: String] ) -> NewWorkspaceCommandResolution { - guard let command = commands.first(where: { $0.name == commandName }) else { + // The reference may be a folder-aware command id (from a generated + // action) or a display name (from user config); match id first. + guard let command = commands.first(where: { $0.id == commandName }) + ?? commands.first(where: { $0.name == commandName }) else { return newWorkspaceResolutionIssue( kind: .newWorkspaceCommandNotFound, settingName: settingName, @@ -3097,7 +3100,9 @@ final class CmuxConfigStore: ObservableObject { commands: [CmuxCommandDefinition], sourcePaths: [String: String] ) -> CmuxResolvedCommand? { - guard let command = commands.first(where: { $0.name == commandName }) else { + // Accept a folder-aware command id or a display name (id first). + guard let command = commands.first(where: { $0.id == commandName }) + ?? commands.first(where: { $0.name == commandName }) else { NSLog("[CmuxConfig] %@ '%@' does not match any loaded command", settingName, commandName) return nil } From 03f758035d4620e74a01be9d71450af71419a035 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 08:53:44 -0700 Subject: [PATCH 20/24] Carry folder-aware id in new-workspace action rebuild Final piece of the folder-aware workspace identity: the configured new-workspace action rebuild stored .workspaceCommand(command.command.name), so even after the resolver selected the right same-named command, execution looked it up by name and could open the wrong one. Store command.command.id, matching the generated palette action and the id-then-name resolvers. Self-generated actions now consistently carry ids; user config references stay name-based. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/swift-file-length-budget.tsv | 2 +- Sources/CmuxConfig.swift | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index f1a92a2316c0..b7688e242afa 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3896 cmuxTests/WindowAndDragTests.swift 3745 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3699 cmuxTests/CLIGenericHookPersistenceTests.swift -3452 Sources/CmuxConfig.swift +3455 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index 29e4138880a6..3771d71de251 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -2779,7 +2779,10 @@ final class CmuxConfigStore: ObservableObject { shortcut: nil, icon: .symbol("rectangle.stack.badge.plus"), tooltip: command.command.description, - action: .workspaceCommand(command.command.name), + // Carry the folder-aware id (not the display name) so execution + // resolves the exact command even when same-named commands exist + // in other folders. + action: .workspaceCommand(command.command.id), confirm: command.command.confirm, terminalCommandTarget: nil, actionSourcePath: command.sourcePath, From 6849901365dd03bf02170d846b90a276eaaefc70 Mon Sep 17 00:00:00 2001 From: cmux Date: Fri, 26 Jun 2026 09:00:24 -0700 Subject: [PATCH 21/24] Fix stale substituting() docstring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The quote-position rewrite dropped the backslash-escape mechanism, but the substituting() docstring still claimed it "strips the escaping backslash from any \{{…}}". Describe the actual behavior: recognized placeholders are substituted (POSIX-quoted) and everything else — unknown placeholders, non-identifier template expressions, and {{…}} inside quotes/here-docs/comments — is left untouched. (Greptile.) Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/CmuxCommandTemplate.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index dad4eb085f7a..5db2ac3da456 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -52,10 +52,10 @@ struct CmuxCommandTemplate { /// Resolves the command for execution: replaces every recognized /// placeholder whose name is present in `values` with its value as a single - /// POSIX-quoted shell argument, leaves placeholders whose name is missing - /// from `values` untouched, leaves non-identifier `{{…}}` template - /// expressions untouched, and strips the escaping backslash from any - /// `\{{…}}` so it becomes a literal `{{…}}`. + /// POSIX-quoted shell argument, and leaves everything else untouched — + /// placeholders whose name is missing from `values`, non-identifier `{{…}}` + /// template expressions, and any `{{…}}` inside quotes, here-doc bodies, or + /// comments. /// /// Values are shell-quoted so that whatever the user types is passed as one /// literal argument — a value like `main; rm -rf /` cannot break out of the From 50f822038a25c0402d73bc032bfda013a19441dd Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 3 Jul 2026 14:00:52 -0700 Subject: [PATCH 22/24] Address command variable review findings --- .github/swift-file-length-budget.tsv | 6 +- Sources/CmuxCommandTemplate.swift | 103 +++++++++++++++-------- Sources/CmuxConfig.swift | 24 ++++-- Sources/CmuxConfigExecutor.swift | 6 +- cmuxTests/CmuxCommandVariableTests.swift | 29 +++++++ cmuxTests/CmuxConfigTests.swift | 87 +++++++++++++++++++ 6 files changed, 209 insertions(+), 46 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 3d6f9ce4912b..d5e440c7bf33 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -30,7 +30,7 @@ 3926 cmuxTests/TabManagerUnitTests.swift 3896 cmuxTests/WindowAndDragTests.swift 3668 cmuxTests/CLIGenericHookPersistenceTests.swift -3455 Sources/CmuxConfig.swift +3469 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift @@ -43,7 +43,7 @@ 2328 cmuxTests/CJKIMEInputTests.swift 2242 Sources/TerminalNotificationStore.swift 2229 Sources/TerminalWindowPortal.swift -2126 cmuxTests/CmuxConfigTests.swift +2213 cmuxTests/CmuxConfigTests.swift 2085 cmuxTests/ShortcutAndCommandPaletteTests.swift 2078 Sources/SessionPersistence.swift 2011 Sources/KeyboardShortcutSettingsFileStore.swift @@ -210,9 +210,9 @@ 560 cmuxTests/CLISSHPTYResizeInputTests.swift 558 Packages/macOS/CmuxGit/Sources/CmuxGit/Parsing/GitMetadataService+Config.swift 553 Sources/RightSidebarPanelView.swift -551 Sources/CmuxConfigExecutor.swift 549 Sources/Panels/BrowserAutomation.swift 547 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore.swift +547 Sources/CmuxConfigExecutor.swift 546 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AutomationSection.swift 544 cmuxUITests/DisplayResolutionRegressionUITests.swift 540 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index 5db2ac3da456..f4eb8975d456 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -22,6 +22,8 @@ import Foundation /// existing template commands are not intercepted. This also means the /// substituted value is always inserted at an unquoted position, where it can /// be safely POSIX-quoted as a single argument. +/// - Prefix an unquoted placeholder with `\` (`\{{name}}`) to pass a literal +/// `{{name}}` through to the shell without prompting. struct CmuxCommandTemplate { /// The raw command string, exactly as written in `cmux.json`. let rawValue: String @@ -63,17 +65,22 @@ struct CmuxCommandTemplate { func substituting(_ values: [String: String]) -> String { guard rawValue.contains("{{") else { return rawValue } let chars = Array(rawValue) - let matches = Self.variableMatches(in: chars) + let matches = Self.templateMatches(in: chars) guard !matches.isEmpty else { return rawValue } var result = "" result.reserveCapacity(chars.count) var cursor = 0 for match in matches { result.append(String(chars[cursor.. String { - let stripped = value.unicodeScalars.filter { scalar in - !(scalar.value <= 0x1F || scalar.value == 0x7F - || (scalar.value >= 0x80 && scalar.value <= 0x9F)) + private enum TemplateMatch { + case variable(CmuxCommandVariable, Range) + case escapedPlaceholder(Range) + + var range: Range { + switch self { + case .variable(_, let range), .escapedPlaceholder(let range): + return range + } } - let escaped = String(String.UnicodeScalarView(stripped)) - .replacingOccurrences(of: "'", with: "'\\''") - return "'" + escaped + "'" } - // MARK: - Scanning - - /// Finds the `{{identifier}}` placeholders that sit at unquoted shell-word - /// positions, returning each variable with its character range in `chars`. - /// - /// The scan tracks single/double shell-quote state (honouring backslash - /// escapes outside single quotes), here-doc bodies (`< [(variable: CmuxCommandVariable, range: Range)] { - var matches: [(variable: CmuxCommandVariable, range: Range)] = [] + templateMatches(in: chars).compactMap { match in + guard case .variable(let variable, let range) = match else { return nil } + return (variable, range) + } + } + + private static func templateMatches( + in chars: [Character] + ) -> [TemplateMatch] { + var matches: [TemplateMatch] = [] let count = chars.count var index = 0 var inSingleQuote = false @@ -133,6 +132,24 @@ struct CmuxCommandTemplate { continue } + if character == "\\", !inDoubleQuote, + index + 2 < count, + chars[index + 1] == "{", + chars[index + 2] == "{" { + let innerStart = index + 3 + if let close = indexOfCloseBraces(chars, from: innerStart) { + let inner = chars[innerStart.. String { + let stripped = value.unicodeScalars.filter { scalar in + !(scalar.value <= 0x1F || scalar.value == 0x7F + || (scalar.value >= 0x80 && scalar.value <= 0x9F)) + } + let escaped = String(String.UnicodeScalarView(stripped)) + .replacingOccurrences(of: "'", with: "'\\''") + return "'" + escaped + "'" + } + /// Whether `chars[i]` (a `#`) begins a shell comment: it must sit at a word /// boundary (start of input or after unquoted whitespace / `;` / `&` / `|` /// / `(`). diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index 3771d71de251..ef84a86dc698 100644 --- a/Sources/CmuxConfig.swift +++ b/Sources/CmuxConfig.swift @@ -1637,6 +1637,22 @@ struct CmuxCommandDefinition: Codable, Sendable, Identifiable { return "cmux.config.command." + key } + static func command( + matching reference: String, + in commands: [CmuxCommandDefinition] + ) -> CmuxCommandDefinition? { + if let byID = commands.first(where: { $0.id == reference }) { + return byID + } + + var nameMatch: CmuxCommandDefinition? + for command in commands where command.name == reference { + guard nameMatch == nil else { return nil } + nameMatch = command + } + return nameMatch + } + /// The trimmed, non-empty components of ``folder`` split on `/`. var folderComponents: [String] { guard let folder else { return [] } @@ -3046,8 +3062,7 @@ final class CmuxConfigStore: ObservableObject { ) -> NewWorkspaceCommandResolution { // The reference may be a folder-aware command id (from a generated // action) or a display name (from user config); match id first. - guard let command = commands.first(where: { $0.id == commandName }) - ?? commands.first(where: { $0.name == commandName }) else { + guard let command = CmuxCommandDefinition.command(matching: commandName, in: commands) else { return newWorkspaceResolutionIssue( kind: .newWorkspaceCommandNotFound, settingName: settingName, @@ -3103,9 +3118,8 @@ final class CmuxConfigStore: ObservableObject { commands: [CmuxCommandDefinition], sourcePaths: [String: String] ) -> CmuxResolvedCommand? { - // Accept a folder-aware command id or a display name (id first). - guard let command = commands.first(where: { $0.id == commandName }) - ?? commands.first(where: { $0.name == commandName }) else { + // Accept a folder-aware command id or a unique display name (id first). + guard let command = CmuxCommandDefinition.command(matching: commandName, in: commands) else { NSLog("[CmuxConfig] %@ '%@' does not match any loaded command", settingName, commandName) return nil } diff --git a/Sources/CmuxConfigExecutor.swift b/Sources/CmuxConfigExecutor.swift index 5dc1c36e543a..029a8706ce6a 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -77,11 +77,7 @@ struct CmuxConfigExecutor { onExecuted: (() -> Void)? = nil ) -> Bool { if let commandReference = action.workspaceCommandName, - // Resolve by the folder-aware id first (self-generated custom-command - // actions store it) and fall back to the display name (user config - // references commands by name). - let command = commands.first(where: { $0.id == commandReference }) - ?? commands.first(where: { $0.name == commandReference }) { + let command = CmuxCommandDefinition.command(matching: commandReference, in: commands) { guard command.workspace != nil else { return false } return execute( command: command, diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index f10fa0372f65..61f82bd31e37 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -96,6 +96,13 @@ import Testing #expect(substitute(command, ["env": "prod"]) == "deploy 'prod' --label '{{env}}'") } + @Test func escapedUnquotedPlaceholderIsLiteral() { + let command = "deploy \\{{template_var}} {{real}}" + #expect(variables(command).map(\.name) == ["real"]) + #expect(substitute(command, ["template_var": "wrong", "real": "prod"]) + == "deploy {{template_var}} 'prod'") + } + @Test func escapedQuoteKeepsPlaceholderQuoted() { // A backslash-escaped quote does not close the surrounding quote, so a // placeholder after it is still quoted and must not be substituted. @@ -242,6 +249,28 @@ import Testing #expect(a.id != b.id) } + @Test func commandReferenceMatchesIDOrUniqueNameOnly() { + let frontend = CmuxCommandDefinition( + name: "Build", + workspace: CmuxWorkspaceDefinition(name: "Frontend"), + folder: "Frontend" + ) + let backend = CmuxCommandDefinition( + name: "Build", + workspace: CmuxWorkspaceDefinition(name: "Backend"), + folder: "Backend" + ) + let deploy = CmuxCommandDefinition( + name: "Deploy", + workspace: CmuxWorkspaceDefinition(name: "Deploy") + ) + let commands = [frontend, backend, deploy] + + #expect(CmuxCommandDefinition.command(matching: backend.id, in: commands)?.id == backend.id) + #expect(CmuxCommandDefinition.command(matching: "Deploy", in: commands)?.id == deploy.id) + #expect(CmuxCommandDefinition.command(matching: "Build", in: commands)?.id == nil) + } + @Test func sameLeafNameInDifferentFoldersBothResolve() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "cmux-folder-collide-\(UUID().uuidString)", diff --git a/cmuxTests/CmuxConfigTests.swift b/cmuxTests/CmuxConfigTests.swift index 56f92a3fd118..96750646f4bd 100644 --- a/cmuxTests/CmuxConfigTests.swift +++ b/cmuxTests/CmuxConfigTests.swift @@ -1334,6 +1334,52 @@ final class CmuxConfigDecodingTests: XCTestCase { XCTAssertEqual(store.surfaceTabBarButtons.last?.workspaceCommandName, "Dev Environment") } + @MainActor + func testSurfaceTabBarDropsAmbiguousWorkspaceCommandNameFallback() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-config-store-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + let configURL = root.appendingPathComponent("cmux.json") + let json = """ + { + "ui": { + "surfaceTabBar": { + "buttons": [ + { "action": "newTerminal" }, + { "id": "dev", "type": "workspaceCommand", "commandName": "Dev Environment" } + ] + } + }, + "commands": [ + { + "name": "Dev Environment", + "folder": "Frontend", + "workspace": { "name": "Frontend Dev" } + }, + { + "name": "Dev Environment", + "folder": "Backend", + "workspace": { "name": "Backend Dev" } + } + ] + } + """ + try json.write(to: configURL, atomically: true, encoding: .utf8) + + let store = CmuxConfigStore( + globalConfigPath: root.appendingPathComponent("missing-global.json").path, + localConfigPath: configURL.path, + startFileWatchers: false + ) + store.loadAll() + + XCTAssertEqual(store.surfaceTabBarButtons.map(\.id), ["newTerminal"]) + } + func testDecodeEmptySurfaceTabBarButtons() throws { let json = """ { @@ -1876,6 +1922,47 @@ final class CmuxCommandIdentityTests: XCTestCase { @MainActor final class CmuxConfigWorkspaceCommandExecutionTests: XCTestCase { + func testWorkspaceCommandActionNameFallbackFailsClosedWhenAmbiguous() { + let manager = TabManager() + let action = CmuxResolvedConfigAction( + id: "open-dev", + title: "Open Dev", + subtitle: nil, + keywords: [], + palette: true, + shortcut: nil, + icon: nil, + tooltip: nil, + action: .workspaceCommand("Dev command"), + confirm: nil, + terminalCommandTarget: nil, + actionSourcePath: nil, + iconSourcePath: nil + ) + let commands = [ + CmuxCommandDefinition( + name: "Dev command", + workspace: CmuxWorkspaceDefinition(name: "Frontend Dev"), + folder: "Frontend" + ), + CmuxCommandDefinition( + name: "Dev command", + workspace: CmuxWorkspaceDefinition(name: "Backend Dev"), + folder: "Backend" + ), + ] + + XCTAssertFalse(CmuxConfigExecutor.execute( + action: action, + commands: commands, + commandSourcePaths: [:], + tabManager: manager, + baseCwd: NSTemporaryDirectory(), + globalConfigPath: "/tmp/cmux-test-global-config.json" + )) + XCTAssertEqual(manager.tabs.count, 1) + } + func testWorkspaceCommandCreatesNewWorkspaceByDefaultWhenNameAlreadyExists() { let manager = TabManager() let existingWorkspace = manager.tabs[0] From 8359c29ddafe50f6df60b1e50c752f87fe452e56 Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 3 Jul 2026 15:00:21 -0700 Subject: [PATCH 23/24] Satisfy command template file policy --- Sources/CmuxCommandTemplate.swift | 42 +++++++++++-------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift index f4eb8975d456..8ac72af032cc 100644 --- a/Sources/CmuxCommandTemplate.swift +++ b/Sources/CmuxCommandTemplate.swift @@ -72,15 +72,12 @@ struct CmuxCommandTemplate { var cursor = 0 for match in matches { result.append(String(chars[cursor..) - case escapedPlaceholder(Range) - - var range: Range { - switch self { - case .variable(_, let range), .escapedPlaceholder(let range): - return range - } - } - } - private static func variableMatches( in chars: [Character] ) -> [(variable: CmuxCommandVariable, range: Range)] { templateMatches(in: chars).compactMap { match in - guard case .variable(let variable, let range) = match else { return nil } - return (variable, range) + guard let variable = match.variable, !match.stripEscape else { return nil } + return (variable, match.range) } } private static func templateMatches( in chars: [Character] - ) -> [TemplateMatch] { - var matches: [TemplateMatch] = [] + ) -> [(variable: CmuxCommandVariable?, range: Range, stripEscape: Bool)] { + var matches: [(variable: CmuxCommandVariable?, range: Range, stripEscape: Bool)] = [] let count = chars.count var index = 0 var inSingleQuote = false @@ -143,7 +128,7 @@ struct CmuxCommandTemplate { c == "{" || c == "}" || c == "\n" || c == "\r" } if !innerHasIllegalCharacter, parse(inner: String(inner)) != nil { - matches.append(.escapedPlaceholder(index..<(close + 2))) + matches.append((nil, index..<(close + 2), true)) index = close + 2 continue } @@ -201,9 +186,10 @@ struct CmuxCommandTemplate { c == "{" || c == "}" || c == "\n" || c == "\r" } if !innerHasIllegalCharacter, let parsed = parse(inner: String(inner)) { - matches.append(.variable( + matches.append(( CmuxCommandVariable(name: parsed.name, defaultValue: parsed.defaultValue), - index..<(close + 2) + index..<(close + 2), + false )) index = close + 2 continue From ba6054ef4019d4375885f4654b21efab2a1b69a0 Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 3 Jul 2026 15:28:27 -0700 Subject: [PATCH 24/24] Move command regression tests to Swift Testing --- .github/swift-file-length-budget.tsv | 2 +- cmuxTests/CmuxCommandVariableTests.swift | 86 +++++++++++++++++++++++ cmuxTests/CmuxConfigTests.swift | 87 ------------------------ 3 files changed, 87 insertions(+), 88 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index d5e440c7bf33..b1077ce245cc 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -43,7 +43,7 @@ 2328 cmuxTests/CJKIMEInputTests.swift 2242 Sources/TerminalNotificationStore.swift 2229 Sources/TerminalWindowPortal.swift -2213 cmuxTests/CmuxConfigTests.swift +2126 cmuxTests/CmuxConfigTests.swift 2085 cmuxTests/ShortcutAndCommandPaletteTests.swift 2078 Sources/SessionPersistence.swift 2011 Sources/KeyboardShortcutSettingsFileStore.swift diff --git a/cmuxTests/CmuxCommandVariableTests.swift b/cmuxTests/CmuxCommandVariableTests.swift index 61f82bd31e37..54af75ead6ea 100644 --- a/cmuxTests/CmuxCommandVariableTests.swift +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -271,6 +271,92 @@ import Testing #expect(CmuxCommandDefinition.command(matching: "Build", in: commands)?.id == nil) } + @Test func surfaceTabBarDropsAmbiguousWorkspaceCommandNameFallback() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-config-store-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + let configURL = root.appendingPathComponent("cmux.json") + let json = """ + { + "ui": { + "surfaceTabBar": { + "buttons": [ + { "action": "newTerminal" }, + { "id": "dev", "type": "workspaceCommand", "commandName": "Dev Environment" } + ] + } + }, + "commands": [ + { + "name": "Dev Environment", + "folder": "Frontend", + "workspace": { "name": "Frontend Dev" } + }, + { + "name": "Dev Environment", + "folder": "Backend", + "workspace": { "name": "Backend Dev" } + } + ] + } + """ + try json.write(to: configURL, atomically: true, encoding: .utf8) + + let store = CmuxConfigStore( + globalConfigPath: root.appendingPathComponent("missing-global.json").path, + localConfigPath: configURL.path, + startFileWatchers: false + ) + store.loadAll() + + #expect(store.surfaceTabBarButtons.map(\.id) == ["newTerminal"]) + } + + @Test func workspaceCommandActionNameFallbackFailsClosedWhenAmbiguous() { + let manager = TabManager() + let action = CmuxResolvedConfigAction( + id: "open-dev", + title: "Open Dev", + subtitle: nil, + keywords: [], + palette: true, + shortcut: nil, + icon: nil, + tooltip: nil, + action: .workspaceCommand("Dev command"), + confirm: nil, + terminalCommandTarget: nil, + actionSourcePath: nil, + iconSourcePath: nil + ) + let commands = [ + CmuxCommandDefinition( + name: "Dev command", + workspace: CmuxWorkspaceDefinition(name: "Frontend Dev"), + folder: "Frontend" + ), + CmuxCommandDefinition( + name: "Dev command", + workspace: CmuxWorkspaceDefinition(name: "Backend Dev"), + folder: "Backend" + ), + ] + + #expect(!CmuxConfigExecutor.execute( + action: action, + commands: commands, + commandSourcePaths: [:], + tabManager: manager, + baseCwd: NSTemporaryDirectory(), + globalConfigPath: "/tmp/cmux-test-global-config.json" + )) + #expect(manager.tabs.count == 1) + } + @Test func sameLeafNameInDifferentFoldersBothResolve() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "cmux-folder-collide-\(UUID().uuidString)", diff --git a/cmuxTests/CmuxConfigTests.swift b/cmuxTests/CmuxConfigTests.swift index 96750646f4bd..56f92a3fd118 100644 --- a/cmuxTests/CmuxConfigTests.swift +++ b/cmuxTests/CmuxConfigTests.swift @@ -1334,52 +1334,6 @@ final class CmuxConfigDecodingTests: XCTestCase { XCTAssertEqual(store.surfaceTabBarButtons.last?.workspaceCommandName, "Dev Environment") } - @MainActor - func testSurfaceTabBarDropsAmbiguousWorkspaceCommandNameFallback() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent( - "cmux-config-store-\(UUID().uuidString)", - isDirectory: true - ) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } - - let configURL = root.appendingPathComponent("cmux.json") - let json = """ - { - "ui": { - "surfaceTabBar": { - "buttons": [ - { "action": "newTerminal" }, - { "id": "dev", "type": "workspaceCommand", "commandName": "Dev Environment" } - ] - } - }, - "commands": [ - { - "name": "Dev Environment", - "folder": "Frontend", - "workspace": { "name": "Frontend Dev" } - }, - { - "name": "Dev Environment", - "folder": "Backend", - "workspace": { "name": "Backend Dev" } - } - ] - } - """ - try json.write(to: configURL, atomically: true, encoding: .utf8) - - let store = CmuxConfigStore( - globalConfigPath: root.appendingPathComponent("missing-global.json").path, - localConfigPath: configURL.path, - startFileWatchers: false - ) - store.loadAll() - - XCTAssertEqual(store.surfaceTabBarButtons.map(\.id), ["newTerminal"]) - } - func testDecodeEmptySurfaceTabBarButtons() throws { let json = """ { @@ -1922,47 +1876,6 @@ final class CmuxCommandIdentityTests: XCTestCase { @MainActor final class CmuxConfigWorkspaceCommandExecutionTests: XCTestCase { - func testWorkspaceCommandActionNameFallbackFailsClosedWhenAmbiguous() { - let manager = TabManager() - let action = CmuxResolvedConfigAction( - id: "open-dev", - title: "Open Dev", - subtitle: nil, - keywords: [], - palette: true, - shortcut: nil, - icon: nil, - tooltip: nil, - action: .workspaceCommand("Dev command"), - confirm: nil, - terminalCommandTarget: nil, - actionSourcePath: nil, - iconSourcePath: nil - ) - let commands = [ - CmuxCommandDefinition( - name: "Dev command", - workspace: CmuxWorkspaceDefinition(name: "Frontend Dev"), - folder: "Frontend" - ), - CmuxCommandDefinition( - name: "Dev command", - workspace: CmuxWorkspaceDefinition(name: "Backend Dev"), - folder: "Backend" - ), - ] - - XCTAssertFalse(CmuxConfigExecutor.execute( - action: action, - commands: commands, - commandSourcePaths: [:], - tabManager: manager, - baseCwd: NSTemporaryDirectory(), - globalConfigPath: "/tmp/cmux-test-global-config.json" - )) - XCTAssertEqual(manager.tabs.count, 1) - } - func testWorkspaceCommandCreatesNewWorkspaceByDefaultWhenNameAlreadyExists() { let manager = TabManager() let existingWorkspace = manager.tabs[0]