Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,31 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2

- 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
Expand All @@ -317,6 +342,7 @@ jobs:
CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_socket_operation_deadline.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
CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_stop_last_assistant.py
CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_clear_running_status.py
Expand Down
53 changes: 30 additions & 23 deletions Resources/shell-integration/cmux-bash-integration.bash
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +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 &
local bg_pid=$!
disown "$bg_pid" 2>/dev/null || disown 2>/dev/null || true
}

_cmux_send_bg() {
local payload="$1"
_cmux_run_bg _cmux_send "$payload"
}

_cmux_socket_is_unix() {
[[ -n "$CMUX_SOCKET_PATH" && -S "$CMUX_SOCKET_PATH" ]]
}
Expand Down Expand Up @@ -72,10 +92,7 @@ _cmux_relay_rpc_bg() {
local relay_cli=""
_cmux_socket_uses_remote_relay || return 1
relay_cli="$(_cmux_relay_cli_path)" || return 1
{
"$relay_cli" rpc "$method" "$params" >/dev/null 2>&1 || true
} >/dev/null 2>&1 &
disown 2>/dev/null || true
_cmux_run_bg "$relay_cli" rpc "$method" "$params"
}

_cmux_relay_rpc() {
Expand Down Expand Up @@ -380,9 +397,7 @@ _cmux_report_tty_once() {
payload="$(_cmux_report_tty_payload)"
[[ -n "$payload" ]] || return 0
_CMUX_TTY_REPORTED=1
{
_cmux_send "$payload"
} >/dev/null 2>&1 & disown
_cmux_send_bg "$payload"
else
[[ -n "$_CMUX_TTY_NAME" ]] || return 0
# Keep the first relay TTY report synchronous so the server can resolve
Expand All @@ -400,9 +415,7 @@ _cmux_report_shell_activity_state() {
[[ -n "$CMUX_PANEL_ID" ]] || return 0
[[ "$_CMUX_SHELL_ACTIVITY_LAST" == "$state" ]] && return 0
_CMUX_SHELL_ACTIVITY_LAST="$state"
{
_cmux_send "report_shell_state $state --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
} >/dev/null 2>&1 & disown
_cmux_send_bg "report_shell_state $state --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
}

_cmux_reset_terminal_keyboard_protocols() {
Expand All @@ -423,9 +436,7 @@ _cmux_ports_kick() {
fi
_CMUX_PORTS_LAST_RUN="$(_cmux_now)"
if _cmux_socket_is_unix; then
{
_cmux_send "ports_kick --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID --reason=$reason"
} >/dev/null 2>&1 & disown
_cmux_send_bg "ports_kick --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID --reason=$reason"
else
_cmux_ports_kick_via_relay "$reason"
fi
Expand Down Expand Up @@ -521,9 +532,7 @@ _cmux_emit_pr_command_hint() {
local quoted_target="${_CMUX_LAST_PR_TARGET//\"/\\\"}"
payload+=" --target=\"$quoted_target\""
fi
{
_cmux_send "$payload"
} >/dev/null 2>&1 & disown
_cmux_send_bg "$payload"
_CMUX_LAST_PR_ACTION=""
_CMUX_LAST_PR_TARGET=""
}
Expand Down Expand Up @@ -1012,10 +1021,8 @@ _cmux_prompt_command() {
# CWD: keep the app in sync with the actual shell directory.
if [[ "$pwd" != "$_CMUX_PWD_LAST_PWD" ]]; then
_CMUX_PWD_LAST_PWD="$pwd"
{
local qpwd="${pwd//\"/\\\"}"
_cmux_send "report_pwd \"${qpwd}\" --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
} >/dev/null 2>&1 & disown
local qpwd="${pwd//\"/\\\"}"
_cmux_send_bg "report_pwd \"${qpwd}\" --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
fi

# Branch can change via aliases/tools while an older probe is still in flight.
Expand Down Expand Up @@ -1074,7 +1081,7 @@ _cmux_prompt_command() {
fi
} >/dev/null 2>&1 &
_CMUX_GIT_JOB_PID=$!
disown
disown "$_CMUX_GIT_JOB_PID" 2>/dev/null || disown 2>/dev/null || true
_CMUX_GIT_JOB_STARTED_AT=$now
fi

Expand Down Expand Up @@ -1123,9 +1130,9 @@ _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 "$BASH_COMMAND"; }'
builtin readonly _CMUX_BASH_PS0='${ _CMUX_BASH_PS0_INLINE_ACTIVE=1; _cmux_bash_preexec_hook "$BASH_COMMAND"; _CMUX_BASH_PS0_INLINE_ACTIVE=0; }'
Comment thread
austinywang marked this conversation as resolved.
Resolved
else
builtin readonly _CMUX_BASH_PS0='$(_cmux_bash_preexec_hook "$BASH_COMMAND" >/dev/null)'
fi
Expand Down
234 changes: 234 additions & 0 deletions tests/test_shell_bash_background_helpers_disowned.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
#!/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 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 _run_interactive_bash(bash_path: str, tmp: Path) -> tuple[int, str]:
socket_path = tmp / "cmux.sock"
bin_dir = tmp / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)

fake_send_tool = "#!/bin/sh\nsleep 0.05\nexit 0\n"
for tool in ("ncat", "socat", "nc"):
_write_executable(bin_dir / tool, fake_send_tool)

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",
"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"}"',
"echo OK",
"sleep 0.2",
"echo AFTER",
"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
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
else:
with suppress(ProcessLookupError):
os.kill(pid, 15)
Comment thread
austinywang marked this conversation as resolved.
Resolved
with suppress(ChildProcessError):
os.waitpid(pid, 0)
return 124, output.decode(errors="replace")
Comment thread
austinywang marked this conversation as resolved.
Resolved

return exit_status, output.decode(errors="replace")


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
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved

with tempfile.TemporaryDirectory(prefix="cmux-bash-done-noise-") as td:
rc, output = _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

done_lines = [
line
for line in (_clean_line(raw) for raw in output.splitlines())
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())
Loading