diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index fa65d6dcf094..66cce97bf58c 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -3,7 +3,7 @@ # Reduce counts as files shrink. CI fails if tracked files exceed this budget. 34499 CLI/cmux.swift 17954 Sources/AppDelegate.swift -16427 Sources/ContentView.swift +16431 Sources/ContentView.swift 14270 Sources/TerminalController.swift 13172 Sources/Workspace.swift 12348 cmuxTests/AppDelegateShortcutRoutingTests.swift @@ -24,13 +24,13 @@ 4483 Sources/cmuxApp.swift 4482 Sources/Panels/FilePreviewPanel.swift 4367 cmuxTests/BrowserPanelTests.swift -4283 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 4121 Sources/BrowserWindowPortal.swift +3964 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3934 Sources/Feed/FeedPanelView.swift 3926 cmuxTests/TabManagerUnitTests.swift 3896 cmuxTests/WindowAndDragTests.swift 3668 cmuxTests/CLIGenericHookPersistenceTests.swift -3397 Sources/CmuxConfig.swift +3469 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3058 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift @@ -213,6 +213,7 @@ 553 Sources/RightSidebarPanelView.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 @@ -237,7 +238,6 @@ 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 518 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift 518 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift 516 Sources/TerminalImageTransfer.swift 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 4028a5ebc9f9..604ea4540235 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -14189,6 +14189,12 @@ "value": "キャンセル" } }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បោះបង់" + } + }, "ko": { "stringUnit": { "state": "translated", @@ -73646,6 +73652,381 @@ } } }, + "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": "Виконати" + } + } + } + }, + "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.confirmCommand.cancel": { "extractionState": "manual", "localizations": { diff --git a/Sources/CmuxCommandTemplate.swift b/Sources/CmuxCommandTemplate.swift new file mode 100644 index 000000000000..8ac72af032cc --- /dev/null +++ b/Sources/CmuxCommandTemplate.swift @@ -0,0 +1,338 @@ +import Foundation + +/// 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/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 +/// 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. +/// - 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. +/// - 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 + + 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 match in Self.variableMatches(in: Array(rawValue)) + where seen.insert(match.variable.name).inserted { + result.append(match.variable) + } + return result + } + + /// Whether the command contains at least one recognized variable placeholder. + var containsVariables: Bool { + guard rawValue.contains("{{") else { return false } + return !Self.variableMatches(in: Array(rawValue)).isEmpty + } + + /// 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, 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 + /// 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.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.. [(variable: CmuxCommandVariable, range: Range)] { + templateMatches(in: chars).compactMap { match in + guard let variable = match.variable, !match.stripEscape else { return nil } + return (variable, match.range) + } + } + + private static func templateMatches( + in chars: [Character] + ) -> [(variable: CmuxCommandVariable?, range: Range, stripEscape: Bool)] { + var matches: [(variable: CmuxCommandVariable?, range: Range, stripEscape: Bool)] = [] + let count = chars.count + 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)] = [] + + while index < count { + let character = chars[index] + + if inSingleQuote { + // Inside single quotes nothing is special except the closing + // quote — not even backslash. + if character == "'" { inSingleQuote = false } + index += 1 + 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 / `;` / `&` / `|` + /// / `(`). + private static func isCommentStart(_ chars: [Character], at i: Int) -> 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[.. 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/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 new file mode 100644 index 000000000000..833a91f8244d --- /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 +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. + /// + /// - 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 + func present( + in 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() + 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(captured, 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 func makeFields() -> [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 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)) * Self.rowGap + let container = NSView( + frame: NSRect(x: 0, y: 0, width: Self.fieldWidth, height: totalHeight) + ) + + // 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: rowBottom + Self.inputHeight + Self.labelToInputGap, + width: Self.fieldWidth, + height: Self.labelHeight + ) + container.addSubview(label) + + 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. + for index in fields.indices { + fields[index].nextKeyView = fields[(index + 1) % fields.count] + } + + return container + } +} diff --git a/Sources/CmuxConfig.swift b/Sources/CmuxConfig.swift index b72416ab9da3..ef84a86dc698 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? = nil var terminalCommand: String? { action.terminalCommand @@ -1617,9 +1620,54 @@ 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) + // 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. 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]) + .map { $0.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? $0 } + .joined(separator: "/") + 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 [] } + 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( @@ -1629,7 +1677,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 +1687,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 +1699,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( @@ -2144,7 +2195,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? @@ -2198,9 +2252,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 } @@ -2233,9 +2287,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 } } @@ -2474,26 +2528,38 @@ 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"), 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, - iconSourcePath: nil + iconSourcePath: nil, + folder: folderBreadcrumb ) } @@ -2729,7 +2795,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, @@ -2991,7 +3060,9 @@ 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 = CmuxCommandDefinition.command(matching: commandName, in: commands) else { return newWorkspaceResolutionIssue( kind: .newWorkspaceCommandNotFound, settingName: settingName, @@ -3047,7 +3118,8 @@ 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 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 de34b48dbfcd..029a8706ce6a 100644 --- a/Sources/CmuxConfigExecutor.swift +++ b/Sources/CmuxConfigExecutor.swift @@ -76,8 +76,8 @@ 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, + let command = CmuxCommandDefinition.command(matching: commandReference, in: commands) { guard command.workspace != nil else { return false } return execute( command: command, @@ -121,6 +121,22 @@ struct CmuxConfigExecutor { } } + /// 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 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 action is authorized and the user fills in the + /// prompt, and is never called if the user cancels. @discardableResult static func prepareShellInputIfAuthorized( _ rawCommand: String, @@ -135,11 +151,13 @@ struct CmuxConfigExecutor { presentingWindow: NSWindow? = nil, onAuthorized: @escaping (String) -> Void ) -> Bool { - let shellCommand = sanitizeForDisplay(rawCommand) - guard !shellCommand.isEmpty else { return false } + let template = CmuxCommandTemplate(rawValue: rawCommand) + let variables = template.variables + let displayCommand = sanitizeForDisplay(rawCommand) + guard !displayCommand.isEmpty else { return false } let descriptor = terminalTrustDescriptor( - command: shellCommand, + command: displayCommand, actionID: actionID, target: target, configSourcePath: configSourcePath, @@ -147,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/Sources/ContentView.swift b/Sources/ContentView.swift index 5378a63140e3..5a62fb3ebd3b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -6015,7 +6015,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, @@ -7407,11 +7407,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 1a0f2bf013e5..b5d7850fce88 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -344,6 +344,10 @@ 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 */; }; + 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 */; }; @@ -1698,6 +1702,10 @@ C0DE64950000000000000006 /* CMUXCLISessionsListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISessionsListTests.swift; sourceTree = ""; }; C0DE6495000000000000000C /* CMUXCLISessionsListTranscriptPidTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXCLISessionsListTranscriptPidTests.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 = ""; }; + 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 = ""; }; @@ -3529,6 +3537,9 @@ A5001642 /* RemoteInteractiveShellBootstrapBuilder.swift */, A5001641 /* RemoteRelayZshBootstrap.swift */, A5001651 /* CmuxConfig.swift */, + C1A2B3C4D5E6F7080000655A /* CmuxCommandTemplate.swift */, + C1A2B3C4D5E6F7080000655E /* CmuxCommandVariable.swift */, + C1A2B3C4D5E6F7080000655C /* CmuxCommandVariablePrompt.swift */, C10D00040000000000000004 /* CmuxSurfaceTabBarBuiltInAction.swift */, C57B00030000000000000002 /* Workspace+CustomSidebarPane.swift */, C0DEF0A10000000000000002 /* CmuxConfigUI.swift */, @@ -4014,6 +4025,7 @@ A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */, 10D684CFFB8CDEF89CE2D9E1 /* TabManagerSessionSnapshotTests.swift */, C1A2B3C4D5E6F70800000002 /* CmuxConfigTests.swift */, + C1A2B3C4D5E6F70800006558 /* CmuxCommandVariableTests.swift */, C0DEF0A40000000000000002 /* CmuxConfigContextMenuTests.swift */, E30750000000000000000005 /* CmuxConfigNamedColorTests.swift */, FE002012 /* FileExplorerGitStatusProviderTests.swift */, @@ -4629,6 +4641,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 */, A5001650 /* CmuxConfig.swift in Sources */, A5001652 /* CmuxConfigExecutor.swift in Sources */, C5D0DEC0CF00000000000A1 /* CmuxConfigStore+ConfigStoreReloading.swift in Sources */, @@ -5450,6 +5465,7 @@ C0DE64950000000000000005 /* CMUXCLISessionsListTests.swift in Sources */, C0DE6495000000000000000B /* CMUXCLISessionsListTranscriptPidTests.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..54af75ead6ea --- /dev/null +++ b/cmuxTests/CmuxCommandVariableTests.swift @@ -0,0 +1,417 @@ +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +// MARK: - Variable parsing + +@Suite struct CmuxCommandTemplateTests { + + private func variables(_ command: String) -> [CmuxCommandVariable] { + CmuxCommandTemplate(rawValue: command).variables + } + + private func substitute(_ command: String, _ values: [String: String]) -> String { + CmuxCommandTemplate(rawValue: command).substituting(values) + } + + @Test func noPlaceholdersReturnsEmpty() { + #expect(variables("npm test").isEmpty) + #expect(!CmuxCommandTemplate(rawValue: "npm test").containsVariables) + } + + @Test func singlePlaceholder() { + #expect(variables("bin/deploy --env {{environment}}") + == [CmuxCommandVariable(name: "environment", defaultValue: nil)]) + #expect(CmuxCommandTemplate(rawValue: "bin/deploy --env {{environment}}").containsVariables) + } + + @Test func placeholderWithDefault() { + #expect(variables("bin/deploy --env {{environment=staging}}") + == [CmuxCommandVariable(name: "environment", defaultValue: "staging")]) + } + + @Test func whitespaceIsTrimmed() { + #expect( + variables("echo {{ name }} {{ env = prod }}") + == [ + CmuxCommandVariable(name: "name", defaultValue: nil), + CmuxCommandVariable(name: "env", defaultValue: "prod"), + ] + ) + } + + @Test func multipleDistinctPlaceholdersPreserveOrder() { + #expect(variables("bin/deploy --env {{environment}} --branch {{branch}}").map(\.name) + == ["environment", "branch"]) + } + + @Test func duplicatePlaceholdersAreDeduplicatedKeepingFirstDefault() { + #expect(variables("echo {{env=a}} && deploy {{env=b}}") + == [CmuxCommandVariable(name: "env", defaultValue: "a")]) + } + + @Test func nameAllowsBareIdentifiers() { + #expect(variables("x {{branch_name}} {{RAILS_ENV}} {{my-var}}").map(\.name) + == ["branch_name", "RAILS_ENV", "my-var"]) + } + + @Test func emptyPlaceholderIsIgnored() { + #expect(variables("echo {{}} {{ }}").isEmpty) + } + + @Test func unquotedNonIdentifierIsRejected() { + // At an unquoted position, only bare identifiers are variables; shell + // snippets and template expressions keep the braces literal. + #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) + } + + @Test func quotedPlaceholdersAreLeftLiteral() { + // A placeholder inside single or double quotes is template text, not a + // cmux variable, so existing quoted template commands run unchanged. + #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). + #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}}'") + } + + @Test func mixedQuotedAndUnquotedOccurrences() { + // Only the unquoted occurrence is a variable; the quoted one stays literal. + let command = "deploy {{env}} --label '{{env}}'" + #expect(variables(command).map(\.name) == ["env"]) + #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. + let command = "echo \"prefix \\\" {{branch}} suffix\"" + #expect(variables(command).isEmpty) + #expect(substitute(command, ["branch": "$(touch /tmp/pwn)"]) == command) + // After the double-quoted span closes, an unquoted placeholder is a variable. + #expect(variables("echo \"a \\\" b\" {{env}}").map(\.name) == ["env"]) + } + + @Test func newlineInsidePlaceholderIsIgnored() { + #expect(variables("echo {{na\nme}}").isEmpty) + } + + @Test func heredocBodiesAreLeftLiteral() { + // Template text inside a here-doc body is not a shell word, so existing + // commands that embed templates via heredocs run unchanged. + #expect(variables("cat >t <<'EOF'\n{{name}}\nEOF").isEmpty) + #expect(substitute("cat < CmuxConfigFile { + let data = json.data(using: .utf8)! + return try JSONDecoder().decode(CmuxConfigFile.self, from: data) + } + + @Test func decodeFolderField() throws { + let config = try decode(""" + { + "commands": [{ + "name": "Lint modified files", + "folder": "Project/Linting", + "command": "bash lint.sh" + }] + } + """) + #expect(config.commands[0].folder == "Project/Linting") + #expect(config.commands[0].folderComponents == ["Project", "Linting"]) + #expect(config.commands[0].folderBreadcrumb == "Project / Linting") + } + + @Test func folderComponentsTrimAndDropEmptySegments() { + let command = CmuxCommandDefinition( + name: "x", + command: "echo", + folder: " /Project// Linting /" + ) + #expect(command.folderComponents == ["Project", "Linting"]) + #expect(command.folderBreadcrumb == "Project / Linting") + } + + @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: " // ") + #expect(blank.folderComponents.isEmpty) + #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") + // 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 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 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)", + 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)", + 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 #require( + store.paletteCustomActions().first { $0.title.contains("Lint modified files") } + ) + #expect(action.folder == "Project / Linting") + #expect(action.keywords.contains("Project")) + #expect(action.keywords.contains("Linting")) + #expect(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 6bae7cec0286..1b20094e62e4 100644 --- a/web/app/[locale]/docs/custom-commands/page.tsx +++ b/web/app/[locale]/docs/custom-commands/page.tsx @@ -335,10 +335,25 @@ 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("commandVariablesTemplateNote")}

    + {t("workspaceCommands")}

    {t("workspaceCommandsDesc")}

    {`{ diff --git a/web/data/cmux.schema.json b/web/data/cmux.schema.json index 145b8c003027..80540e255177 100644 --- a/web/data/cmux.schema.json +++ b/web/data/cmux.schema.json @@ -48,7 +48,51 @@ "type": "array", "items": { "type": "object", - "additionalProperties": true + "additionalProperties": true, + "required": ["name"], + "oneOf": [ + { + "required": ["command"], + "not": { "required": ["workspace"] } + }, + { + "required": ["workspace"], + "not": { "required": ["command"] } + } + ], + "properties": { + "name": { + "type": "string", + "pattern": "\\S", + "description": "Display name shown in the Command Palette. Must not be blank." + }, + "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 {{name}} placeholders (optionally {{name=default}}) at unquoted positions 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_-]*) at unquoted positions are treated as variables; a placeholder inside single or double quotes (e.g. '{{tag}}') and other template expressions such as {{ .Env.FOO }} run unchanged." + }, + "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 49fd5ba4e416..5ce645d12b9b 100644 --- a/web/messages/ar.json +++ b/web/messages/ar.json @@ -966,7 +966,12 @@ "absolutePath": "مسار مطلق", "cwdAbsolute": "يُستخدم كما هو", "fullExample": "مثال كامل", - "restartNew": "إنشاء مساحة عمل جديدة (الافتراضي)" + "restartNew": "إنشاء مساحة عمل جديدة (الافتراضي)", + "fieldFolder": "مسار مجلد اختياري مفصول بـ / (مثل Project/Linting) لتجميع الأمر في لوحة الأوامر", + "commandVariables": "متغيرات الأمر", + "commandVariablesDesc": "أضِف عناصر نائبة إلى الأمر، وسيطلب cmux إدخال كل قيمة قبل التشغيل. أعِد استخدام اسم العنصر النائب نفسه لتعبئته في عدة أماكن دفعة واحدة.", + "commandVariablesDefaultNote": "أضِف قيمة افتراضية بعد علامة المساواة داخل العنصر النائب لملء المطالبة مسبقًا.", + "commandVariablesTemplateNote": "تتحوّل إلى متغيّرات فقط العناصر النائبة ذات المعرّف البسيط غير المحاطة بعلامات اقتباس؛ أما العناصر النائبة داخل علامات الاقتباس (وأي نص قالب آخر) فتعمل دون تغيير." }, "keyboardShortcuts": { "title": "اختصارات لوحة المفاتيح", diff --git a/web/messages/bs.json b/web/messages/bs.json index 42854cfbceb0..099ddb15addd 100644 --- a/web/messages/bs.json +++ b/web/messages/bs.json @@ -966,7 +966,12 @@ "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 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": "Varijable postaju samo rezervirana mjesta s običnim identifikatorom koja nisu pod navodnicima; rezervirana mjesta unutar navodnika (i ostali tekst predloška) izvršavaju se nepromijenjeni." }, "keyboardShortcuts": { "title": "Prečice na tastaturi", diff --git a/web/messages/da.json b/web/messages/da.json index 7099fcecd776..7e8803c93e39 100644 --- a/web/messages/da.json +++ b/web/messages/da.json @@ -966,7 +966,12 @@ "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 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 pladsholdere med simple identifikatorer uden anførselstegn bliver variabler; pladsholdere inde i anførselstegn (og anden skabelontekst) køres uændret." }, "keyboardShortcuts": { "title": "Tastaturgenveje", diff --git a/web/messages/de.json b/web/messages/de.json index 378ca2d07ec1..3e3979f23fd2 100644 --- a/web/messages/de.json +++ b/web/messages/de.json @@ -966,7 +966,12 @@ "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 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 Platzhalter mit einfachem Bezeichner ohne Anführungszeichen werden zu Variablen; Platzhalter innerhalb von Anführungszeichen (und anderer Vorlagentext) werden unverändert ausgeführt." }, "keyboardShortcuts": { "title": "Tastaturkürzel", diff --git a/web/messages/en.json b/web/messages/en.json index b19ef75f8723..09bebe1679ae 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -1263,7 +1263,12 @@ "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 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 unquoted bare-identifier placeholders become variables; placeholders inside quotes (and other template text) run unchanged." }, "keyboardShortcuts": { "title": "Keyboard Shortcuts", diff --git a/web/messages/es.json b/web/messages/es.json index 5dbcfba2e4c2..8a2f2ccac3ca 100644 --- a/web/messages/es.json +++ b/web/messages/es.json @@ -966,7 +966,12 @@ "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 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 marcadores con identificador simple y sin comillas se convierten en variables; los marcadores entre comillas (y otro texto de plantilla) se ejecutan sin cambios." }, "keyboardShortcuts": { "title": "Atajos de teclado", diff --git a/web/messages/fr.json b/web/messages/fr.json index 8181f3a87644..b507e95417bf 100644 --- a/web/messages/fr.json +++ b/web/messages/fr.json @@ -966,7 +966,12 @@ "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 à 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 espaces réservés à identifiant simple et sans guillemets deviennent des variables ; les espaces réservés entre guillemets (et tout autre texte de modèle) s'exécutent sans changement." }, "keyboardShortcuts": { "title": "Raccourcis clavier", diff --git a/web/messages/it.json b/web/messages/it.json index bc8230ce127f..8461e51e679a 100644 --- a/web/messages/it.json +++ b/web/messages/it.json @@ -966,7 +966,12 @@ "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 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": "Diventano variabili solo i segnaposto con identificatore semplice e senza virgolette; i segnaposto tra virgolette (e altro testo di template) vengono eseguiti senza modifiche." }, "keyboardShortcuts": { "title": "Scorciatoie da tastiera", diff --git a/web/messages/ja.json b/web/messages/ja.json index 261185592d09..05d58552d1e2 100644 --- a/web/messages/ja.json +++ b/web/messages/ja.json @@ -1233,7 +1233,12 @@ "absolutePath": "絶対パス", "cwdAbsolute": "そのまま使用", "fullExample": "完全な例", - "restartNew": "新しいワークスペースを作成する (デフォルト)" + "restartNew": "新しいワークスペースを作成する (デフォルト)", + "fieldFolder": "コマンドパレットでコマンドをグループ化する任意の / 区切りフォルダーパス(例: Project/Linting)", + "commandVariables": "コマンド変数", + "commandVariablesDesc": "コマンドにプレースホルダーを追加すると、実行前に cmux が各値の入力を求めます。同じプレースホルダー名を再利用すると、複数箇所を一度に入力できます。", + "commandVariablesDefaultNote": "プレースホルダー内のイコール記号の後に既定値を指定すると、プロンプトにあらかじめ入力できます。", + "commandVariablesTemplateNote": "変数になるのは引用符で囲まれていない単純な識別子のプレースホルダーだけです。引用符の中のプレースホルダー(その他のテンプレートテキストを含む)はそのまま実行されます。" }, "keyboardShortcuts": { "title": "キーボードショートカット", diff --git a/web/messages/km.json b/web/messages/km.json index d9fb77e7d6b6..becff158e1b3 100644 --- a/web/messages/km.json +++ b/web/messages/km.json @@ -966,7 +966,12 @@ "absolutePath": "ផ្លូវដាច់ខាត", "cwdAbsolute": "ប្រើដូចដែលមាន", "fullExample": "ឧទាហរណ៍ពេញលេញ", - "restartNew": "បង្កើត workspace ថ្មី (លំនាំដើម)" + "restartNew": "បង្កើត workspace ថ្មី (លំនាំដើម)", + "fieldFolder": "ផ្លូវថតឯកសារស្រេចចិត្តបំបែកដោយ / (ឧ. Project/Linting) ដែលដាក់ជាក្រុមពាក្យបញ្ជាក្នុង Command Palette", + "commandVariables": "អថេរពាក្យបញ្ជា", + "commandVariablesDesc": "បន្ថែមកន្លែងដាក់ទៅពាក្យបញ្ជា ហើយ cmux នឹងសួរតម្លៃនីមួយៗមុនពេលដំណើរការ។ ប្រើឈ្មោះដដែលឡើងវិញ ដើម្បីបំពេញវានៅកន្លែងជាច្រើនក្នុងពេលតែមួយ។", + "commandVariablesDefaultNote": "បន្ថែមតម្លៃលំនាំដើមបន្ទាប់ពីសញ្ញាស្មើនៅក្នុងកន្លែងដាក់ ដើម្បីបំពេញប្រអប់សួរជាមុន។", + "commandVariablesTemplateNote": "មានតែកន្លែងដាក់ដែលជាឈ្មោះសម្គាល់ធម្មតា និងគ្មានសញ្ញាសម្រង់ប៉ុណ្ណោះដែលក្លាយជាអថេរ។ កន្លែងដាក់នៅក្នុងសញ្ញាសម្រង់ (និងអត្ថបទគំរូផ្សេងទៀត) ដំណើរការដោយមិនផ្លាស់ប្ដូរ។" }, "keyboardShortcuts": { "title": "ផ្លូវកាត់ក្ដារចុច", diff --git a/web/messages/ko.json b/web/messages/ko.json index ea3ed14f8744..ed960655b26e 100644 --- a/web/messages/ko.json +++ b/web/messages/ko.json @@ -966,7 +966,12 @@ "absolutePath": "절대 경로", "cwdAbsolute": "있는 그대로 사용", "fullExample": "전체 예시", - "restartNew": "새 워크스페이스 만들기 (기본값)" + "restartNew": "새 워크스페이스 만들기 (기본값)", + "fieldFolder": "명령 팔레트에서 명령을 그룹화하는 선택적 / 구분 폴더 경로(예: Project/Linting)", + "commandVariables": "명령 변수", + "commandVariablesDesc": "명령에 자리표시자를 추가하면 cmux가 실행 전에 각 값을 입력하도록 요청합니다. 같은 이름을 재사용하면 여러 위치를 한 번에 채울 수 있습니다.", + "commandVariablesDefaultNote": "자리표시자 안의 등호 뒤에 기본값을 추가하면 프롬프트를 미리 채울 수 있습니다.", + "commandVariablesTemplateNote": "따옴표로 감싸지 않은 단순 식별자 자리표시자만 변수가 됩니다. 따옴표 안의 자리표시자(및 기타 템플릿 텍스트)는 그대로 실행됩니다." }, "keyboardShortcuts": { "title": "키보드 단축키", diff --git a/web/messages/no.json b/web/messages/no.json index d9bd759aece1..98cace45e911 100644 --- a/web/messages/no.json +++ b/web/messages/no.json @@ -966,7 +966,12 @@ "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 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 plassholdere med enkel identifikator uten anførselstegn blir variabler; plassholdere inne i anførselstegn (og annen maltekst) kjøres uendret." }, "keyboardShortcuts": { "title": "Tastatursnarveier", diff --git a/web/messages/pl.json b/web/messages/pl.json index cda279f25e64..314ad62e74a6 100644 --- a/web/messages/pl.json +++ b/web/messages/pl.json @@ -966,7 +966,12 @@ "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 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": "Zmiennymi stają się tylko symbole zastępcze z prostym identyfikatorem bez cudzysłowów; symbole w cudzysłowach (i inny tekst szablonu) są uruchamiane bez zmian." }, "keyboardShortcuts": { "title": "Skróty klawiszowe", diff --git a/web/messages/pt-BR.json b/web/messages/pt-BR.json index 91aa528928f1..3a7fe1bbbbdc 100644 --- a/web/messages/pt-BR.json +++ b/web/messages/pt-BR.json @@ -966,7 +966,12 @@ "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 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 marcadores com identificador simples e sem aspas viram variáveis; marcadores dentro de aspas (e outro texto de template) são executados sem alteração." }, "keyboardShortcuts": { "title": "Atalhos de Teclado", diff --git a/web/messages/ru.json b/web/messages/ru.json index 5e87385515cd..3a90bb6f9d5a 100644 --- a/web/messages/ru.json +++ b/web/messages/ru.json @@ -966,7 +966,12 @@ "absolutePath": "Абсолютный путь", "cwdAbsolute": "используется как есть", "fullExample": "Полный пример", - "restartNew": "Создать новый workspace (по умолчанию)" + "restartNew": "Создать новый workspace (по умолчанию)", + "fieldFolder": "Необязательный путь к папке через / (например, Project/Linting), группирующий команду в палитре команд", + "commandVariables": "Переменные команды", + "commandVariablesDesc": "Добавьте в команду заполнители, и cmux запросит каждое значение перед запуском. Используйте одно и то же имя повторно, чтобы заполнить его сразу в нескольких местах.", + "commandVariablesDefaultNote": "Добавьте значение по умолчанию после знака равенства внутри заполнителя, чтобы заранее заполнить запрос.", + "commandVariablesTemplateNote": "Переменными становятся только заполнители с простым идентификатором без кавычек; заполнители в кавычках (и прочий текст шаблона) выполняются без изменений." }, "keyboardShortcuts": { "title": "Горячие клавиши", diff --git a/web/messages/th.json b/web/messages/th.json index 3e365973e924..1e9699febb50 100644 --- a/web/messages/th.json +++ b/web/messages/th.json @@ -966,7 +966,12 @@ "absolutePath": "พาธสัมบูรณ์", "cwdAbsolute": "ใช้ตามที่เป็น", "fullExample": "ตัวอย่างเต็ม", - "restartNew": "สร้าง workspace ใหม่ (ค่าเริ่มต้น)" + "restartNew": "สร้าง workspace ใหม่ (ค่าเริ่มต้น)", + "fieldFolder": "เส้นทางโฟลเดอร์เสริมที่คั่นด้วย / (เช่น Project/Linting) สำหรับจัดกลุ่มคำสั่งในคอมมานด์พาเลตต์", + "commandVariables": "ตัวแปรของคำสั่ง", + "commandVariablesDesc": "เพิ่มตัวยึดลงในคำสั่ง แล้ว cmux จะถามค่าแต่ละค่าก่อนเรียกใช้ ใช้ชื่อเดิมซ้ำเพื่อกรอกค่าในหลายตำแหน่งพร้อมกัน", + "commandVariablesDefaultNote": "เพิ่มค่าเริ่มต้นหลังเครื่องหมายเท่ากับภายในตัวยึดเพื่อกรอกกล่องข้อความล่วงหน้า", + "commandVariablesTemplateNote": "เฉพาะตัวยึดที่เป็นตัวระบุแบบธรรมดาและไม่อยู่ในเครื่องหมายคำพูดเท่านั้นที่จะกลายเป็นตัวแปร ส่วนตัวยึดที่อยู่ในเครื่องหมายคำพูด (และข้อความเทมเพลตอื่น ๆ) จะทำงานโดยไม่เปลี่ยนแปลง" }, "keyboardShortcuts": { "title": "คีย์ลัด", diff --git a/web/messages/tr.json b/web/messages/tr.json index 7f0dd773d5e0..865028d0f9a2 100644 --- a/web/messages/tr.json +++ b/web/messages/tr.json @@ -966,7 +966,12 @@ "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 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 tırnak içinde olmayan düz tanımlayıcı yer tutucular değişken olur; tırnak içindeki yer tutucular (ve diğer şablon metni) değişmeden çalışır." }, "keyboardShortcuts": { "title": "Klavye Kısayolları", diff --git a/web/messages/uk.json b/web/messages/uk.json index 1b232c14a8b6..6c9037579cca 100644 --- a/web/messages/uk.json +++ b/web/messages/uk.json @@ -966,7 +966,12 @@ "absolutePath": "Абсолютний шлях", "cwdAbsolute": "використовується як є", "fullExample": "Повний приклад", - "restartNew": "Створити новий workspace (за замовчуванням)" + "restartNew": "Створити новий workspace (за замовчуванням)", + "fieldFolder": "Необов'язковий шлях до теки, розділений / (напр., Project/Linting), що групує команду в палітрі команд", + "commandVariables": "Змінні команди", + "commandVariablesDesc": "Додайте до команди заповнювачі, і cmux запитає кожне значення перед запуском. Повторно використовуйте те саме ім'я, щоб заповнити його одразу в кількох місцях.", + "commandVariablesDefaultNote": "Додайте значення за замовчуванням після знака рівності всередині заповнювача, щоб заздалегідь заповнити запит.", + "commandVariablesTemplateNote": "Змінними стають лише заповнювачі з простим ідентифікатором без лапок; заповнювачі в лапках (та інший текст шаблону) виконуються без змін." }, "keyboardShortcuts": { "title": "Клавіатурні скорочення", diff --git a/web/messages/zh-CN.json b/web/messages/zh-CN.json index 63d7e76eba50..22092627cf06 100644 --- a/web/messages/zh-CN.json +++ b/web/messages/zh-CN.json @@ -966,7 +966,12 @@ "absolutePath": "绝对路径", "cwdAbsolute": "按原样使用", "fullExample": "完整示例", - "restartNew": "创建新的 workspace(默认)" + "restartNew": "创建新的 workspace(默认)", + "fieldFolder": "可选的以 / 分隔的文件夹路径(例如 Project/Linting),用于在命令面板中对命令进行分组", + "commandVariables": "命令变量", + "commandVariablesDesc": "在命令中添加占位符,cmux 会在运行前提示输入每个值。重复使用相同的名称即可一次性填充多个位置。", + "commandVariablesDefaultNote": "在占位符内的等号后添加默认值,可为提示预填内容。", + "commandVariablesTemplateNote": "只有不在引号内的简单标识符占位符才会成为变量;引号内的占位符(及其他模板文本)会原样运行。" }, "keyboardShortcuts": { "title": "快捷键", diff --git a/web/messages/zh-TW.json b/web/messages/zh-TW.json index 23a22483d1d8..0587689f901d 100644 --- a/web/messages/zh-TW.json +++ b/web/messages/zh-TW.json @@ -966,7 +966,12 @@ "absolutePath": "絕對路徑", "cwdAbsolute": "按原樣使用", "fullExample": "完整範例", - "restartNew": "建立新的 workspace(預設)" + "restartNew": "建立新的 workspace(預設)", + "fieldFolder": "選用的以 / 分隔的資料夾路徑(例如 Project/Linting),用於在命令選擇區中將命令分組", + "commandVariables": "命令變數", + "commandVariablesDesc": "在命令中加入佔位符,cmux 會在執行前提示輸入每個值。重複使用相同的名稱即可一次填入多個位置。", + "commandVariablesDefaultNote": "在佔位符內的等號後加入預設值,即可為提示預先填入內容。", + "commandVariablesTemplateNote": "只有不在引號內的簡單識別碼佔位符才會成為變數;引號內的佔位符(及其他範本文字)會原樣執行。" }, "keyboardShortcuts": { "title": "鍵盤快捷鍵",