import os import subprocess from tamq import tmux import pytest def test_tmux_manager_builds_tap_windows(tmp_path, monkeypatch): calls = [] manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") repo_a = tmp_path / "a" repo_b = tmp_path / "b" repo_a.mkdir() repo_b.mkdir() monkeypatch.setattr(tmux, "validate_targets", lambda repos: None) monkeypatch.setattr(tmux, "repository_paths", lambda: {"a": str(repo_a), "b": str(repo_b)}) monkeypatch.setattr(tmux.shutil, "which", lambda command: f"/bin/{command}") def run(*args, check=True): calls.append(args) if args[:2] == ("list-windows", "-t"): return "__tamq_boot" if args[:2] == ("display-message", "-p"): return "42" return "" monkeypatch.setattr(manager, "_run", run) monkeypatch.setattr(tmux.subprocess, "run", lambda *args, **kwargs: type("R", (), {"returncode": 1})()) plan = manager.preflight(["a", "b"], "codex --quiet") endpoint = manager.ensure_plan(plan, tap=True) assert endpoint.endpoint_id == "tmux-amq-42" assert endpoint.instance_id.startswith("tmux-amq-42-") assert endpoint.repos == ["a", "b"] new_session = next(call for call in calls if call and call[0] == "new-session") assert new_session[-2:] == ("-c", str(repo_a)) assert "sleep" not in new_session new_window = next(call for call in calls if call and call[0] == "new-window") assert new_window[-2:] == ("-c", str(repo_b)) tap_calls = [call for call in calls if call and call[0] == "send-keys"] assert len(tap_calls) == 2 assert all("tamq tap" in " ".join(call) for call in tap_calls) assert all(endpoint.instance_id in " ".join(call) for call in tap_calls) assert all("codex --quiet" in " ".join(call) for call in tap_calls) assert ("select-window", "-t", "tamq-test:a") in calls assert any(call and call[0] == "set-option" for call in calls) def test_tmux_manager_reuses_session_instance_id(tmp_path, monkeypatch): repo = tmp_path / "a" repo.mkdir() manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") options = {"@tamq_managed": "1"} monkeypatch.setattr(tmux, "validate_targets", lambda repos: None) monkeypatch.setattr(tmux, "repository_paths", lambda: {"a": str(repo)}) monkeypatch.setattr(tmux.shutil, "which", lambda command: f"/bin/{command}") def run(*args, check=True): if args[:2] == ("display-message", "-p"): return "42" if args and args[0] == "show-options": return options.get(args[-1], "") if args and args[0] == "set-option": options[args[-2]] = args[-1] if args[:2] == ("list-windows", "-t"): return "a" return "" monkeypatch.setattr(manager, "_run", run) monkeypatch.setattr( tmux.subprocess, "run", lambda *args, **kwargs: type("R", (), {"returncode": 0})(), ) first = manager.ensure(["a"]) second = manager.ensure(["a"]) assert first.instance_id == second.instance_id def test_preflight_rejects_foreign_session(tmp_path, monkeypatch): repo = tmp_path / "a" repo.mkdir() manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") monkeypatch.setattr(tmux, "validate_targets", lambda repos: None) monkeypatch.setattr(tmux, "repository_paths", lambda: {"a": str(repo)}) monkeypatch.setattr(tmux.shutil, "which", lambda command: f"/bin/{command}") monkeypatch.setattr( tmux.subprocess, "run", lambda *args, **kwargs: type("R", (), {"returncode": 0})(), ) def run(*args, check=True): if args[:2] == ("display-message", "-p"): return "42" return "" monkeypatch.setattr(manager, "_run", run) with pytest.raises(tmux.TmuxError, match="not managed by tamq"): manager.preflight(["a"]) def test_tap_refuses_managed_session_without_duplex_protocol(tmp_path, monkeypatch): manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") plan = tmux.LaunchPlan(("a",), {"a": str(tmp_path)}, ("sh",)) monkeypatch.setattr(manager, "_existing_session_identity", lambda: (42, "tmux-amq-42-old")) monkeypatch.setattr(manager, "_run", lambda *args, **kwargs: "") with pytest.raises(tmux.TmuxError, match="predates worker message blocks"): manager.ensure_plan(plan, tap=True) def test_tmux_only_plan_starts_agent_without_tap(tmp_path, monkeypatch): manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") calls = [] plan = tmux.LaunchPlan(("a",), {"a": str(tmp_path)}, ("codex", "--quiet")) def run(*args, check=True): calls.append(args) if args[:2] == ("display-message", "-p"): return "42" if args[:2] == ("list-windows", "-t"): return "__tamq_boot" return "" monkeypatch.setattr(manager, "_run", run) monkeypatch.setattr( tmux.subprocess, "run", lambda *args, **kwargs: type("R", (), {"returncode": 1})(), ) manager.ensure_plan(plan, tap=False) send = next(call for call in calls if call and call[0] == "send-keys") assert "codex --quiet" in send assert "tamq tap" not in send def test_neutral_plan_starts_shell_without_sending_keystrokes(tmp_path, monkeypatch): command_dir = tmp_path / "commands" manager = tmux.TmuxManager("tamq-test", command_dir=command_dir) calls = [] plan = tmux.LaunchPlan(("a", "b"), {"a": str(tmp_path), "b": str(tmp_path)}, ()) def run(*args, check=True): calls.append(args) if args[:2] == ("display-message", "-p"): return "42" if args[:2] == ("list-windows", "-t"): return "__tamq_boot" return "" monkeypatch.setattr(manager, "_run", run) monkeypatch.setattr( tmux.subprocess, "run", lambda *args, **kwargs: type("R", (), {"returncode": 1})(), ) manager.ensure_plan(plan) assert not any(call and call[0] == "send-keys" for call in calls) new_session = next(call for call in calls if call and call[0] == "new-session") new_window = next(call for call in calls if call and call[0] == "new-window") assert "TAMQ_REPO=a" in new_session assert "TAMQ_REPO=b" in new_window assert f"PATH={command_dir}{os.pathsep}" in " ".join(new_session) assert f"PATH={command_dir}{os.pathsep}" in " ".join(new_window) for keyword in ("To", "to", "TO", "tO"): assert (command_dir / f"{keyword}:a:").is_file() assert (command_dir / f"{keyword}:b:").is_file() for keyword in ("Cmd", "cmd", "CMD", "cMd"): assert (command_dir / f"{keyword}:").is_file() assert not any(path.name.startswith("@") for path in command_dir.iterdir()) def test_protocol_commands_absorb_forwarded_shell_lines(tmp_path): command_dir = tmp_path / "commands" manager = tmux.TmuxManager( "tamq-test", tamq_command=("echo",), command_dir=command_dir, ) manager._install_address_commands(["audit-core"]) for name in ( "To:audit-core:", "to:audit-core:", "TO:audit-core:", "tO:audit-core:", "Cmd:", "cmd:", "CMD:", "cMd:", ): result = subprocess.run( [str(command_dir / name), "Some message!", "$value"], text=True, capture_output=True, check=True, ) assert result.stdout == "" def test_protocol_reconciliation_skips_unrelated_binary_executables(tmp_path): command_dir = tmp_path / "commands" command_dir.mkdir() binary = command_dir / "other-tool" binary.write_bytes(b"\x7fELF\x8e\xff\x00") legacy = command_dir / "@audit-core" legacy.write_text( "#!/bin/sh\n# tamq-address-command v1\nexit 0\n", encoding="utf-8", ) manager = tmux.TmuxManager("tamq-test", command_dir=command_dir) manager._install_address_commands(["audit-core"]) assert binary.read_bytes() == b"\x7fELF\x8e\xff\x00" assert not legacy.exists() assert (command_dir / "To:audit-core:").is_file() def test_protocol_reconciliation_refuses_undecodable_command_collision(tmp_path): command_dir = tmp_path / "commands" command_dir.mkdir() collision = command_dir / "To:audit-core:" collision.write_bytes(b"\x8e\xff") manager = tmux.TmuxManager("tamq-test", command_dir=command_dir) with pytest.raises(tmux.TmuxError, match="cannot inspect existing command"): manager._install_address_commands(["audit-core"]) assert collision.read_bytes() == b"\x8e\xff" def test_address_commands_reject_unsafe_repository_names(tmp_path): manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") with pytest.raises(tmux.TmuxError, match="cannot be exposed"): manager._install_address_commands(["../outside"]) def test_address_commands_do_not_replace_unowned_commands(tmp_path): command_dir = tmp_path / "commands" command_dir.mkdir() existing = command_dir / "To:audit-core:" existing.write_text("#!/bin/sh\necho mine\n", encoding="utf-8") manager = tmux.TmuxManager("tamq-test", command_dir=command_dir) with pytest.raises(tmux.TmuxError, match="refusing to replace"): manager._install_address_commands(["audit-core"]) assert existing.read_text(encoding="utf-8") == "#!/bin/sh\necho mine\n" def test_address_commands_do_not_replace_unowned_command_lane(tmp_path): command_dir = tmp_path / "commands" command_dir.mkdir() existing = command_dir / "Cmd:" existing.write_text("#!/bin/sh\necho mine\n", encoding="utf-8") manager = tmux.TmuxManager("tamq-test", command_dir=command_dir) with pytest.raises(tmux.TmuxError, match="refusing to replace"): manager._install_address_commands(["audit-core"]) assert existing.read_text(encoding="utf-8") == "#!/bin/sh\necho mine\n" def test_preflight_rejects_missing_agent(tmp_path, monkeypatch): repo = tmp_path / "a" repo.mkdir() manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") monkeypatch.setattr(tmux, "validate_targets", lambda repos: None) monkeypatch.setattr(tmux, "repository_paths", lambda: {"a": str(repo)}) monkeypatch.setattr(tmux.shutil, "which", lambda command: None if command == "missing-agent" else f"/bin/{command}") with pytest.raises(tmux.TmuxError, match="initial command not found"): manager.preflight(["a"], "missing-agent") def test_preflight_deduplicates_repositories(tmp_path, monkeypatch): repo = tmp_path / "a" repo.mkdir() manager = tmux.TmuxManager("tamq-test", command_dir=tmp_path / "commands") monkeypatch.setattr(tmux, "validate_targets", lambda repos: None) monkeypatch.setattr(tmux, "repository_paths", lambda: {"a": str(repo)}) monkeypatch.setattr(tmux.shutil, "which", lambda command: f"/bin/{command}") plan = manager.preflight(["a", "a"], "codex") assert plan.repos == ("a",)