Skip to content
Merged
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
9 changes: 6 additions & 3 deletions Resources/shell-integration/cmux-bash-integration.bash
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ _cmux_report_tty_once() {
_CMUX_TTY_REPORTED=1
{
_cmux_send "report_tty $_CMUX_TTY_NAME --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
} >/dev/null 2>&1 &
} >/dev/null 2>&1 & disown
}

_cmux_ports_kick() {
Expand All @@ -74,7 +74,7 @@ _cmux_ports_kick() {
_CMUX_PORTS_LAST_RUN=$SECONDS
{
_cmux_send "ports_kick --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
} >/dev/null 2>&1 &
} >/dev/null 2>&1 & disown
}

_cmux_prompt_command() {
Expand Down Expand Up @@ -123,7 +123,7 @@ _cmux_prompt_command() {
{
local qpwd="${pwd//\"/\\\"}"
_cmux_send "report_pwd \"${qpwd}\" --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID"
} >/dev/null 2>&1 &
} >/dev/null 2>&1 & disown
fi

# Git branch/dirty can change without a directory change (e.g. `git checkout`),
Expand Down Expand Up @@ -154,6 +154,7 @@ _cmux_prompt_command() {
fi
} >/dev/null 2>&1 &
_CMUX_GIT_JOB_PID=$!
disown
_CMUX_GIT_JOB_STARTED_AT=$now
fi

Expand Down Expand Up @@ -197,6 +198,7 @@ _cmux_prompt_command() {
fi
} >/dev/null 2>&1 &
_CMUX_PR_JOB_PID=$!
disown
_CMUX_PR_JOB_STARTED_AT=$now
fi
fi
Expand All @@ -205,6 +207,7 @@ _cmux_prompt_command() {
if (( now - _CMUX_PORTS_LAST_RUN >= 10 )); then
_cmux_ports_kick
fi

}

_cmux_install_prompt_command() {
Expand Down
10 changes: 10 additions & 0 deletions Sources/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1956,11 +1956,21 @@ final class Workspace: Identifiable, ObservableObject {
guard let paneId = sourcePaneId else { return nil }
let inheritedConfig = inheritedTerminalConfig(preferredPanelId: panelId, inPane: paneId)

// Inherit working directory: prefer the source panel's reported cwd,
// fall back to the workspace's current directory.
let splitWorkingDirectory: String? = panelDirectories[panelId]
?? (currentDirectory.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? nil : currentDirectory)
#if DEBUG
dlog("split.cwd panelId=\(panelId.uuidString.prefix(5)) panelDir=\(panelDirectories[panelId] ?? "nil") currentDir=\(currentDirectory) resolved=\(splitWorkingDirectory ?? "nil")")
#endif

// Create the new terminal panel.
let newPanel = TerminalPanel(
workspaceId: id,
context: GHOSTTY_SURFACE_CONTEXT_SPLIT,
configTemplate: inheritedConfig,
workingDirectory: splitWorkingDirectory,
portOrdinal: portOrdinal
)
panels[newPanel.id] = newPanel
Expand Down
199 changes: 199 additions & 0 deletions tests/test_split_cwd_inheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""
End-to-end test for split CWD inheritance.

Verifies that new split panes and new workspace tabs inherit the current
working directory from the source terminal.

Requires:
- cmux running with allowAll socket mode
- bash shell integration sourced (cmux-bash-integration.bash)

Run with a tagged instance:
CMUX_TAG=<tag> python3 tests/test_split_cwd_inheritance.py
"""

from __future__ import annotations

import os
import sys
import time
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from cmux import cmux, cmuxError # noqa: E402


def _parse_sidebar_state(text: str) -> dict[str, str]:
data: dict[str, str] = {}
for raw in (text or "").splitlines():
line = raw.rstrip("\n")
if not line or line.startswith(" "):
continue
if "=" not in line:
continue
k, v = line.split("=", 1)
data[k.strip()] = v.strip()
return data


def _wait_for(predicate, timeout: float, interval: float, label: str):
start = time.time()
last_error: Exception | None = None
while time.time() - start < timeout:
try:
value = predicate()
if value:
return value
except Exception as e:
last_error = e
time.sleep(interval)
extra = ""
if last_error is not None:
extra = f" Last error: {last_error}"
raise AssertionError(f"Timed out waiting for {label}.{extra}")


def _wait_for_focused_cwd(
client: cmux,
expected: str,
timeout: float = 12.0,
exclude_panel: str | None = None,
) -> dict[str, str]:
"""Wait for focused_cwd to match expected.

If exclude_panel is given, also require that focused_panel differs from
that value — ensuring we're checking the *new* pane, not the original.
"""
def pred():
state = _parse_sidebar_state(client.sidebar_state())
cwd = state.get("focused_cwd", "")
if cwd != expected:
return None
if exclude_panel and state.get("focused_panel", "") == exclude_panel:
return None
return state
label = f"focused_cwd={expected!r}"
if exclude_panel:
label += f" (panel != {exclude_panel})"
return _wait_for(pred, timeout=timeout, interval=0.3, label=label)


def _send_cd_and_wait(
client: cmux,
target: str,
timeout: float = 12.0,
) -> dict[str, str]:
"""cd to target and wait for sidebar focused_cwd to reflect it."""
client.send(f"cd {target}\n")
return _wait_for_focused_cwd(client, target, timeout=timeout)


def main() -> int:
tag = os.environ.get("CMUX_TAG", "")

socket_path = None
if tag:
socket_path = f"/tmp/cmux-debug-{tag}.sock"
client = cmux(socket_path=socket_path)
client.connect()

# Use resolved paths to avoid /tmp -> /private/tmp symlink mismatch on macOS
test_dir_a = str(Path("/tmp/cmux_split_cwd_test_a").resolve())
test_dir_b = str(Path("/tmp/cmux_split_cwd_test_b").resolve())
os.makedirs(test_dir_a, exist_ok=True)
os.makedirs(test_dir_b, exist_ok=True)
Comment on lines +96 to +106

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -name "test_split_cwd_inheritance.py" -type f

Repository: jleechanorg/cmux

Length of output: 97


🏁 Script executed:

wc -l tests/test_split_cwd_inheritance.py

Repository: jleechanorg/cmux

Length of output: 99


🏁 Script executed:

cat -n tests/test_split_cwd_inheritance.py | sed -n '80,170p'

Repository: jleechanorg/cmux

Length of output: 3967


Use isolated temp dirs and guaranteed teardown for test reliability.

Lines 90–91 use hardcoded /tmp paths that collide across concurrent test runs. More critically, if any operation before line 157 fails (e.g., in _send_cd_and_wait, _wait_for_focused_cwd, or client.new_split()), both client.close() and directory cleanup are skipped, leaking resources. Wrap the entire test logic in try/finally to guarantee teardown, and use tempfile.TemporaryDirectory for isolation. Also remove the unused exception variables at lines 131 and 150.

Proposed fix
 import os
 import sys
 import time
+import tempfile
 from pathlib import Path
@@
-    # Use resolved paths to avoid /tmp -> /private/tmp symlink mismatch on macOS
-    test_dir_a = str(Path("/tmp/cmux_split_cwd_test_a").resolve())
-    test_dir_b = str(Path("/tmp/cmux_split_cwd_test_b").resolve())
-    os.makedirs(test_dir_a, exist_ok=True)
-    os.makedirs(test_dir_b, exist_ok=True)
+    temp_root = tempfile.TemporaryDirectory(prefix="cmux_split_cwd_")
+    try:
+        root = Path(temp_root.name).resolve()
+        test_dir_a = str((root / "a").resolve())
+        test_dir_b = str((root / "b").resolve())
+        os.makedirs(test_dir_a, exist_ok=True)
+        os.makedirs(test_dir_b, exist_ok=True)
@@
-    try:
-        state = _wait_for_focused_cwd(client, test_dir_a, timeout=15.0)
-        check("test1: split inherited test_dir_a", True)
-    except AssertionError as e:
+        # ... test logic ...
+        try:
+            state = _wait_for_focused_cwd(client, test_dir_a, timeout=15.0)
+            check("test1: split inherited test_dir_a", True)
+        except AssertionError:
@@
-    try:
-        state = _wait_for_focused_cwd(client, test_dir_b, timeout=15.0)
-        check("test2: new workspace inherited test_dir_b", True)
-    except AssertionError as e:
+        try:
+            state = _wait_for_focused_cwd(client, test_dir_b, timeout=15.0)
+            check("test2: new workspace inherited test_dir_b", True)
+        except AssertionError:
@@
-    print(f"\n{passed} passed, {failed} failed")
-
-    client.close()
-
-    # Cleanup
-    for d in [test_dir_a, test_dir_b]:
-        try:
-            os.rmdir(d)
-        except OSError:
-            pass
+        print(f"\n{passed} passed, {failed} failed")
+    finally:
+        client.close()
+        temp_root.cleanup()
🧰 Tools
🪛 Ruff (0.15.2)

[error] 85-85: Probable insecure usage of temporary file or directory: "/tmp/cmux-debug-"

(S108)


[error] 90-90: Probable insecure usage of temporary file or directory: "/tmp/cmux_split_cwd_test_a"

(S108)


[error] 91-91: Probable insecure usage of temporary file or directory: "/tmp/cmux_split_cwd_test_b"

(S108)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_split_cwd_inheritance.py` around lines 83 - 93, Replace the
hardcoded /tmp dirs with isolated TemporaryDirectory instances (use
tempfile.TemporaryDirectory() to create test_dir_a and test_dir_b and get
resolved paths) and wrap the test logic that runs after client.connect() in a
try/finally so client.close() is always called and directories are always
cleaned up (or rely on the TemporaryDirectory context to tear down). Ensure
calls that may raise (e.g., _send_cd_and_wait, _wait_for_focused_cwd,
client.new_split()) are inside the try block and that the finally calls
client.close() (and any explicit cleanup if not using TemporaryDirectory). Also
remove unused exception variables from the test’s except clauses so no unused
names remain.


passed = 0
failed = 0

def check(name: str, condition: bool, detail: str = ""):
nonlocal passed, failed
if condition:
print(f" PASS {name}")
passed += 1
else:
print(f" FAIL {name}{': ' + detail if detail else ''}")
failed += 1

print("=== Split CWD Inheritance Tests ===")

# --- Setup: cd to test_dir_a in workspace 1 ---
print(" [setup] cd to test_dir_a and wait for shell integration...")
_send_cd_and_wait(client, test_dir_a)
state = _parse_sidebar_state(client.sidebar_state())
check("setup: focused_cwd is test_dir_a", state.get("focused_cwd") == test_dir_a,
f"got {state.get('focused_cwd')!r}")

# --- Test 1: New split inherits test_dir_a ---
print(" [test1] creating right split from test_dir_a...")
# Record the original panel so we can verify focus moves to the NEW pane.
original_panel = state.get("focused_panel", "")
split_result = client.new_split("right")
check("split created", bool(split_result))

# Wait for the NEW pane (different panel ID) to report test_dir_a.
time.sleep(4) # wait for new bash to start + run PROMPT_COMMAND
Comment on lines +130 to +137

Copilot AI Mar 5, 2026

Copy link

Choose a reason for hiding this comment

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

This test doesn’t currently guarantee it’s asserting the new split pane’s working directory. It waits for focused_cwd == test_dir_a, but that will also be true if focus never moved off the original pane (which is already in test_dir_a), so the test can pass even when the split starts in the wrong directory. Consider capturing focused_panel before the split and asserting it changes, or use new_split()’s returned panel id / list_pane_surfaces + focus_surface to explicitly focus the new surface before checking focused_cwd.

Copilot uses AI. Check for mistakes.
try:
state = _wait_for_focused_cwd(
client, test_dir_a, timeout=15.0, exclude_panel=original_panel,
)
new_panel = state.get("focused_panel", "")
check("test1: focus moved to new pane", new_panel != original_panel,
f"original={original_panel!r}, current={new_panel!r}")
check("test1: split inherited test_dir_a", True)
except AssertionError:
state = _parse_sidebar_state(client.sidebar_state())
check("test1: split inherited test_dir_a", False,
f"focused_cwd={state.get('focused_cwd')!r}, focused_panel={state.get('focused_panel')!r}")

# --- Test 2: New workspace tab inherits CWD ---
# First cd to test_dir_b so we have a different dir to inherit
print(" [test2] cd to test_dir_b, then creating new workspace tab...")
_send_cd_and_wait(client, test_dir_b)
state = _parse_sidebar_state(client.sidebar_state())
original_tab = state.get("tab", "")

tab_result = client.new_tab()
check("new tab created", bool(tab_result))

# New workspace should be a different tab AND inherit test_dir_b
time.sleep(4)
try:
def _new_tab_with_cwd():
s = _parse_sidebar_state(client.sidebar_state())
tab_id = s.get("tab", "")
cwd = s.get("focused_cwd", "")
if tab_id != original_tab and cwd == test_dir_b:
return s
return None

state = _wait_for(
_new_tab_with_cwd, timeout=15.0, interval=0.3,
label=f"new tab with focused_cwd={test_dir_b!r}",
)
check("test2: focus moved to new tab", state.get("tab") != original_tab,
f"original={original_tab!r}, current={state.get('tab')!r}")
check("test2: new workspace inherited test_dir_b", True)
Comment on lines +153 to +178

Copilot AI Mar 5, 2026

Copy link

Choose a reason for hiding this comment

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

Similar to test1, this check can pass without validating the new workspace tab’s inherited CWD: focused_cwd == test_dir_b is already true in the current workspace right after _send_cd_and_wait, even if new_tab() doesn’t select the new tab (or if selection is delayed). To make the test sound, assert that the current tab/workspace id changes (e.g., via current_tab()/current_workspace()), or explicitly select_tab(tab_result) before waiting on focused_cwd.

Copilot uses AI. Check for mistakes.
except AssertionError:
state = _parse_sidebar_state(client.sidebar_state())
check("test2: new workspace inherited test_dir_b", False,
f"focused_cwd={state.get('focused_cwd')!r}, tab={state.get('tab')!r}")

print(f"\n{passed} passed, {failed} failed")

client.close()

# Cleanup
for d in [test_dir_a, test_dir_b]:
try:
os.rmdir(d)
except OSError:
pass

return 1 if failed else 0


if __name__ == "__main__":
sys.exit(main())