diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index ea13c6d70701..c7195dde6f8f 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. 33857 CLI/cmux.swift 17914 Sources/AppDelegate.swift -16740 Sources/ContentView.swift +16709 Sources/ContentView.swift 14612 Sources/TerminalController.swift 13595 Sources/Panels/BrowserPanel.swift 12088 Sources/GhosttyTerminalView.swift @@ -13,15 +13,15 @@ 7911 Sources/Panels/BrowserPanelView.swift 7350 cmuxTests/WorkspaceUnitTests.swift 6944 cmuxTests/WorkspaceRemoteConnectionTests.swift +6363 cmuxTests/GhosttyConfigTests.swift 6317 cmuxTests/SessionPersistenceTests.swift -6299 cmuxTests/GhosttyConfigTests.swift 6153 CLI/cmux_open.swift 6074 Sources/TabManager.swift 6074 Sources/TextBoxInput.swift 5925 cmuxTests/TerminalAndGhosttyTests.swift 5522 cmuxTests/BrowserConfigTests.swift -4921 Sources/cmuxApp.swift 5113 Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +4921 Sources/cmuxApp.swift 4460 Sources/Panels/FilePreviewPanel.swift 4400 cmuxTests/BrowserPanelTests.swift 4227 Sources/BrowserWindowPortal.swift @@ -32,7 +32,7 @@ 3664 Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift 3397 Sources/CmuxConfig.swift 3331 cmuxTests/TabManagerSessionSnapshotTests.swift -3204 Sources/Update/UpdateTitlebarAccessory.swift +3200 Sources/Update/UpdateTitlebarAccessory.swift 2878 Sources/SessionIndexView.swift 2871 cmuxTests/CMUXOpenCommandTests.swift 2573 Sources/KeyboardShortcutSettings.swift @@ -59,11 +59,11 @@ 1652 cmuxTests/CMUXCLIErrorOutputRegressionTests.swift 1574 cmuxTests/MarkdownPanelTests.swift 1560 cmuxTests/TextBoxMentionCompletionTests.swift -1498 cmuxTests/OmnibarAndToolsTests.swift +1497 cmuxTests/OmnibarAndToolsTests.swift 1496 cmuxUITests/MultiWindowNotificationsUITests.swift 1446 Sources/FileExplorerStore.swift -1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift 1382 cmuxTests/KeyboardShortcutSettingsFileStoreStartupTests.swift +1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift 1373 cmuxTests/AppDelegateIssue2907RoutingTests.swift 1366 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -92,9 +92,9 @@ 937 Sources/TextBoxMentionIndexStore.swift 934 Sources/App/ShortcutRoutingSupport.swift 926 Sources/DockPanelView.swift +920 Sources/CommandPalette/CommandPaletteSettingsToggle.swift 919 Packages/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift 918 cmuxTests/WorkspaceGroupTests.swift -920 Sources/CommandPalette/CommandPaletteSettingsToggle.swift 905 Sources/CmuxSSHURLRequest.swift 901 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AppSection.swift 893 Sources/WorkspaceContentView.swift @@ -117,13 +117,14 @@ 752 cmuxUITests/CloseWorkspaceCmdDUITests.swift 746 Sources/App/MenuBarExtraController.swift 738 Packages/CMUXProjectModel/Sources/CMUXProjectModel/XcodeProjectAdapter.swift -738 Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +736 Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +726 cmuxTests/CLICodexHookTimeoutRegressionTests.swift 716 Sources/TaskManagerSnapshot.swift 715 Packages/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Input.swift 715 Sources/AppleScriptSupport.swift 710 Sources/TerminalSSHSessionDetector.swift -706 CLI/CMUXCLI+Config.swift 707 CLI/CMUXCLI+AgentHookDefinitions.swift +706 CLI/CMUXCLI+Config.swift 699 Sources/RightSidebarPanelView.swift 699 cmuxTests/TerminalNotificationClearAllTests.swift 698 cmuxTests/RestorableAgentHookProviderResumeTests.swift @@ -187,7 +188,6 @@ 528 cmuxTests/CLINotifyProcessTestSupport.swift 528 cmuxUITests/AutomationSocketUITests.swift 527 CLI/CLISocketPathResolver.swift -726 cmuxTests/CLICodexHookTimeoutRegressionTests.swift 523 Packages/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator+PortScan.swift 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b14ba6b8569..c7d5fa1c4f35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,6 @@ on: permissions: contents: read - actions: write concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -532,6 +531,31 @@ jobs: bun run agent-session-web:test git diff --exit-code -- Resources/agent-session-react Resources/agent-session-solid + - name: Ensure Bash 5.3 for shell integration regression + run: | + set -euo pipefail + + candidates=("/opt/homebrew/bin/bash" "/usr/local/bin/bash" "$(command -v bash || true)") + for candidate in "${candidates[@]}"; do + if [ -x "$candidate" ] && "$candidate" -c '(( BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 3) ))'; then + echo "CMUX_TEST_BASH=$candidate" >> "$GITHUB_ENV" + "$candidate" --version | head -1 + exit 0 + fi + done + + brew install bash + for candidate in /opt/homebrew/bin/bash /usr/local/bin/bash; do + if [ -x "$candidate" ] && "$candidate" -c '(( BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 3) ))'; then + echo "CMUX_TEST_BASH=$candidate" >> "$GITHUB_ENV" + "$candidate" --version | head -1 + exit 0 + fi + done + + echo "Bash >= 5.3 unavailable after brew install" >&2 + exit 1 + - name: Run CLI no-socket regressions run: | set -euo pipefail @@ -554,6 +578,7 @@ jobs: python3 tests/test_stress_cli_socket_api.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_omo_openagent_plugin_migration.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_socket_autodiscovery.py + python3 tests/test_shell_bash_background_helpers_disowned.py python3 tests/test_claude_wrapper_hooks.py python3 tests/test_claude_wrapper_user_binary_resolution.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_claude_teams_fallback_path.py diff --git a/CLAUDE.md b/CLAUDE.md index a920858e22b7..61c6196d98ec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,17 +38,17 @@ App path: **Claude Code** outputs: ```markdown -======================================================= +------------------------------------------------------- [cmux DEV my-tag.app](file:///Users/someone/Library/Developer/Xcode/DerivedData/cmux-my-tag/Build/Products/Debug/cmux%20DEV%20my-tag.app) -======================================================= +------------------------------------------------------- ``` **Codex** outputs: ```markdown -======================================================= +------------------------------------------------------- [my-tag: file:///Users/someone/Library/Developer/Xcode/DerivedData/cmux-my-tag/Build/Products/Debug/cmux%20DEV%20my-tag.app](file:///Users/someone/Library/Developer/Xcode/DerivedData/cmux-my-tag/Build/Products/Debug/cmux%20DEV%20my-tag.app) -======================================================= +------------------------------------------------------- ``` Never use `/tmp/cmux-/...` app links in chat output. diff --git a/Resources/shell-integration/cmux-bash-integration.bash b/Resources/shell-integration/cmux-bash-integration.bash index 2b8983148a3f..111fd8ad35ad 100644 --- a/Resources/shell-integration/cmux-bash-integration.bash +++ b/Resources/shell-integration/cmux-bash-integration.bash @@ -32,20 +32,26 @@ _cmux_send() { esac } +_CMUX_BASH_PS0_INLINE_ACTIVE="${_CMUX_BASH_PS0_INLINE_ACTIVE:-0}" +_cmux_run_bg() { + if [[ "${_CMUX_BASH_PS0_INLINE_ACTIVE:-0}" == "1" ]]; then + # Bash 5.3's inline PS0 expansion leaks background jobs into the + # interactive job table. Start the helper from a command-substitution + # subshell so the user shell never owns the job notification. + : "$("$@" >/dev/null 2>&1 & disown "$!" 2>/dev/null || true)" + return 0 + fi + + ( "$@" >/dev/null 2>&1 & disown "$!" 2>/dev/null || true ) +} + _cmux_detach_bg() { - ( "$@" >/dev/null 2>&1 & ) >/dev/null 2>&1 + _cmux_run_bg "$@" } _cmux_send_bg() { local payload="$1" - if [[ "${_CMUX_IN_PREEXEC:-}" == "1" ]]; then - { - _cmux_send "$payload" - } >/dev/null 2>&1 & - disown - return 0 - fi - _cmux_detach_bg _cmux_send "$payload" + _cmux_run_bg _cmux_send "$payload" } _cmux_start_tracked_bg() { @@ -1364,7 +1370,12 @@ _cmux_command_starts_nested_shell() { } _cmux_preexec_command() { - local cmd="${1:-${BASH_COMMAND:-}}" + local cmd="" + if (( $# > 0 )); then + cmd="$1" + else + cmd="${BASH_COMMAND:-}" + fi _cmux_tmux_sync_cmux_environment local cmux_has_unix_socket=0 @@ -1417,6 +1428,9 @@ _cmux_bash_history_command() { _cmux_bash_preexec_hook() { local cmd="${1:-}" local history_cmd="" + # Bash 5.3's inline `${ ...; }` PS0 updates BASH_COMMAND to cmux's + # own helper command before function arguments are expanded. Interactive + # history is the stable source for the user command on that path. history_cmd="$(_cmux_bash_history_command 2>/dev/null || true)" if [[ -n "$history_cmd" ]]; then cmd="$history_cmd" @@ -1429,6 +1443,14 @@ _cmux_bash_preexec_hook_subshell() { _cmux_bash_preexec_hook "$@" } +_cmux_bash_preexec_inline_ps0() { + _CMUX_BASH_PS0_INLINE_ACTIVE=1 + { + _cmux_bash_preexec_hook + _CMUX_BASH_PS0_INLINE_ACTIVE=0 + } || _CMUX_BASH_PS0_INLINE_ACTIVE=0 +} + _cmux_prompt_command() { local last_status=$? _cmux_tmux_sync_cmux_environment @@ -1601,11 +1623,11 @@ _cmux_install_prompt_command() { esac fi - if (( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )); then + if (( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )); then if (( BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 3) )); then - builtin readonly _CMUX_BASH_PS0='${ _cmux_bash_preexec_hook; }' + builtin readonly _CMUX_BASH_PS0='${ _cmux_bash_preexec_inline_ps0; }' else - builtin readonly _CMUX_BASH_PS0='$(_cmux_bash_preexec_hook_subshell >/dev/null)' + builtin readonly _CMUX_BASH_PS0='$(_cmux_bash_preexec_hook_subshell "$BASH_COMMAND" >/dev/null)' fi if [[ "$PS0" != *"${_CMUX_BASH_PS0}"* ]]; then PS0=$PS0"${_CMUX_BASH_PS0}" diff --git a/tests/test_shell_bash_background_helpers_disowned.py b/tests/test_shell_bash_background_helpers_disowned.py new file mode 100644 index 000000000000..391b52f4b9a6 --- /dev/null +++ b/tests/test_shell_bash_background_helpers_disowned.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +""" +Regression: bash shell integration background helpers must not leak job +completion notices into the user's terminal output. +""" + +from __future__ import annotations + +import os +import re +import select +import shutil +import signal +import socket +import stat +import subprocess +import tempfile +import time +from contextlib import suppress +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SHELL_DIR = ROOT / "Resources" / "shell-integration" +ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +DONE_LINE_RE = re.compile(r"^\[[0-9]+\](?:[+-]|\s)\s+Done\b") + + +def _bash_version(path: str) -> tuple[int, ...] | None: + try: + result = subprocess.run( + [path, "--version"], + capture_output=True, + text=True, + timeout=4, + check=False, + ) + except (OSError, subprocess.TimeoutExpired): + return None + + if result.returncode != 0: + return None + + match = re.search(r"version\s+([0-9]+(?:\.[0-9]+)*)", result.stdout) + if not match: + return None + return tuple(int(part) for part in match.group(1).split(".")) + + +def _find_bash_with_inline_ps0() -> str | None: + candidates = [ + os.environ.get("CMUX_TEST_BASH", ""), + shutil.which("bash") or "", + "/opt/homebrew/bin/bash", + "/usr/local/bin/bash", + "/bin/bash", + ] + seen: set[str] = set() + for candidate in candidates: + if not candidate or candidate in seen: + continue + seen.add(candidate) + version = _bash_version(candidate) + if version is not None and version >= (5, 3): + return candidate + return None + + +class BoundUnixSocket: + def __init__(self, path: Path) -> None: + self.path = path + self.sock: socket.socket | None = None + + def __enter__(self) -> BoundUnixSocket: + self.path.parent.mkdir(parents=True, exist_ok=True) + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.bind(str(self.path)) + self.sock.listen(16) + self.sock.setblocking(False) + return self + + def accept_pending(self) -> None: + if self.sock is None: + return + while True: + try: + conn, _ = self.sock.accept() + except BlockingIOError: + return + conn.close() + + def __exit__(self, exc_type, exc, tb) -> None: + if self.sock is not None: + self.sock.close() + try: + self.path.unlink() + except FileNotFoundError: + pass + + +def _write_executable(path: Path, contents: str) -> None: + path.write_text(contents, encoding="utf-8") + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def _clean_line(raw: str) -> str: + return ANSI_ESCAPE_RE.sub("", raw).replace("\r", "").strip() + + +def _drain_pty(fd: int, output: bytearray, *, quiet_after: float = 0.2) -> None: + deadline = time.time() + quiet_after + while time.time() < deadline: + readable, _, _ = select.select([fd], [], [], 0.05) + if fd not in readable: + continue + try: + chunk = os.read(fd, 4096) + except OSError: + return + if not chunk: + return + output.extend(chunk) + deadline = time.time() + quiet_after + + +def _terminate_child(pid: int, *, grace: float = 0.5) -> None: + with suppress(ProcessLookupError): + os.kill(pid, signal.SIGTERM) + + deadline = time.time() + grace + while time.time() < deadline: + try: + waited_pid, _ = os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + return + if waited_pid == pid: + return + time.sleep(0.05) + + with suppress(ProcessLookupError): + os.kill(pid, signal.SIGKILL) + with suppress(ChildProcessError): + os.waitpid(pid, 0) + + +def _run_interactive_bash(bash_path: str, tmp: Path) -> tuple[int, str, str]: + socket_path = tmp / "cmux.sock" + send_log_path = tmp / "send.log" + bin_dir = tmp / "bin" + bin_dir.mkdir(parents=True, exist_ok=True) + + fake_send_tool = ( + "#!/bin/sh\n" + 'cat >> "$CMUX_TEST_SEND_LOG"\n' + 'printf "\\n" >> "$CMUX_TEST_SEND_LOG"\n' + "sleep 0.05\n" + "exit 0\n" + ) + for tool in ("ncat", "socat", "nc"): + _write_executable(bin_dir / tool, fake_send_tool) + _write_executable(bin_dir / "gh", "#!/bin/sh\nexit 0\n") + + env = dict(os.environ) + env.update( + { + "PATH": f"{bin_dir}:/usr/bin:/bin:/usr/sbin:/sbin", + "CMUX_SOCKET_PATH": str(socket_path), + "CMUX_WORKSPACE_ID": "workspace-bash-done-noise", + "CMUX_TAB_ID": "tab-bash-done-noise", + "CMUX_PANEL_ID": "panel-bash-done-noise", + "CMUX_TEST_SEND_LOG": str(send_log_path), + "PS1": "CMUX_TEST_PROMPT> ", + "PROMPT_COMMAND": "", + } + ) + + with BoundUnixSocket(socket_path) as bound_socket: + pid, fd = os.forkpty() + if pid == 0: + os.chdir(str(ROOT)) + os.execve(bash_path, [bash_path, "--noprofile", "--norc", "-i"], env) + + commands = "\n".join( + [ + f'source "{SHELL_DIR / "cmux-bash-integration.bash"}"', + "sleep 5 & cmux_user_bg_pid=$!", + "echo OK", + "gh pr view 123", + "sleep 0.2", + "echo AFTER", + "cmux_current_bang=$!", + 'echo "CMUX_TEST_USER_BG_PID=$cmux_user_bg_pid"', + 'echo "CMUX_TEST_CURRENT_BANG=$cmux_current_bang"', + ( + 'if [[ "$cmux_current_bang" != "$cmux_user_bg_pid" ]]; then ' + 'echo "CMUX_TEST_BANG_CHANGED"; fi' + ), + 'kill "$cmux_user_bg_pid" 2>/dev/null || true', + 'wait "$cmux_user_bg_pid" 2>/dev/null || true', + "sleep 0.2", + "exit 0", + "", + ] + ) + os.write(fd, commands.encode()) + + output = bytearray() + deadline = time.time() + 8 + exit_status = 1 + while time.time() < deadline: + bound_socket.accept_pending() + readable, _, _ = select.select([fd], [], [], 0.05) + if fd in readable: + try: + chunk = os.read(fd, 4096) + except OSError: + break + if not chunk: + break + output.extend(chunk) + + waited_pid, status = os.waitpid(pid, os.WNOHANG) + if waited_pid == pid: + exit_status = os.waitstatus_to_exitcode(status) + _drain_pty(fd, output) + break + else: + _terminate_child(pid) + _drain_pty(fd, output, quiet_after=0.05) + return 124, output.decode(errors="replace"), "" + + send_log = "" + if send_log_path.exists(): + send_log = send_log_path.read_text(encoding="utf-8", errors="replace") + return exit_status, output.decode(errors="replace"), send_log + + +def main() -> int: + bash_path = _find_bash_with_inline_ps0() + if bash_path is None: + if os.environ.get("CI"): + print("FAIL: CI must provide Bash >= 5.3 for inline PS0 regression coverage") + return 1 + print("SKIP: no Bash >= 5.3 found for inline PS0 regression coverage") + return 0 + + with tempfile.TemporaryDirectory(prefix="cmux-bash-done-noise-") as td: + rc, output, send_log = _run_interactive_bash(bash_path, Path(td)) + + if rc == 124: + print("FAIL: timed out waiting for interactive bash to exit") + print(output) + return 1 + + if "OK" not in output or "AFTER" not in output: + print(f"FAIL: interactive bash did not run the probe commands, rc={rc}") + print(output) + return 1 + + cleaned_lines = [_clean_line(raw) for raw in output.splitlines()] + user_bg_matches = re.findall(r"CMUX_TEST_USER_BG_PID=([0-9]+)", output) + current_bang_matches = re.findall(r"CMUX_TEST_CURRENT_BANG=([0-9]+)", output) + if not user_bg_matches or not current_bang_matches: + print("FAIL: interactive bash did not report $! preservation markers") + print(output) + return 1 + if user_bg_matches[-1] != current_bang_matches[-1] or "CMUX_TEST_BANG_CHANGED" in cleaned_lines: + print("FAIL: cmux bash prompt helpers changed the user's last background PID") + print(output) + return 1 + + expected_pr_action = ( + 'report_pr_action view --tab=tab-bash-done-noise ' + '--panel=panel-bash-done-noise --target="123"' + ) + if expected_pr_action not in send_log: + print("FAIL: Bash 5.3 PS0 preexec did not report the gh pr command") + print(send_log) + return 1 + + done_lines = [ + line + for line in cleaned_lines + if DONE_LINE_RE.match(line) + ] + if done_lines: + print("FAIL: cmux bash integration leaked background job completion notices") + for line in done_lines: + print(line) + return 1 + + print("PASS: bash integration background helpers stay out of the user-visible job table") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())