import shutil import logging import zipfile import subprocess from pathlib import Path, PurePosixPath import pytest import reachy_mini_conversation_app.config as config_mod import reachy_mini_conversation_app.prompts as prompts_mod import reachy_mini_conversation_app.personality as headless_mod import reachy_mini_conversation_app.profile_store as profile_store_mod from reachy_mini_conversation_app.config import DEFAULT_PROFILES_DIRECTORY, config from reachy_mini_conversation_app.personality import ( list_personalities, ) from reachy_mini_conversation_app.profile_store import read_profile, write_profile, read_profile_from_directory # Path characters budget computation # ───────────────── # Windows MAX_PATH limit: 259 usable characters (failures start at 260) # # Project files (WINDOWS_PATH_BUDGET = 130): # C:\Users\ # \.cache\huggingface\hub # \spaces--pollen-robotics--reachy_mini_conversation_app # \snapshots\\ # = 158 characters => 101 remaining to 259. # The project root folder is not cloned in the snapshot, so we add it # back to the budget: 101 + len("reachy_mini_conversation_app\") (29) = 130. # # Wheel files (WINDOWS_WHEEL_PATH_BUDGET = 71): # C:\Users\ # \.cache\huggingface\hub # \spaces--pollen-robotics--reachy_mini_conversation_app # \snapshots\ # \build\bdist.win-amd64\wheel\ # = 186 characters => 73 remaining to 259. # In practice the copy fails at 257 because of an intermediate \.\ # folder, bringing the real budget down to 71. WINDOWS_PATH_BUDGET = 130 WINDOWS_WHEEL_PATH_BUDGET = 71 def _git_tracked_files(project_root: Path) -> list[Path]: """Return git-tracked files that still exist in the working tree.""" try: result = subprocess.run( ["git", "ls-files", "--cached"], cwd=project_root, check=True, capture_output=True, text=True, ) except (OSError, subprocess.CalledProcessError) as exc: pytest.skip(f"git-tracked file listing unavailable: {exc}") tracked_files = [project_root / relative_path for relative_path in result.stdout.splitlines() if relative_path] return [path for path in tracked_files if path.is_file()] def test_profile_name_resolves_directly_to_storage_dir() -> None: """Built-in profile names should map directly to their on-disk directory.""" profile_dir = config.resolve_profile_dir("mad_scientist_assistant") assert profile_dir.name == "mad_scientist_assistant" assert (profile_dir / "profile.md").is_file() def test_prompts_load_from_compact_builtin_profile(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """Prompt loading should read compact built-in profile instructions directly.""" monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "mad_scientist_assistant") monkeypatch.setattr(config, "PROFILES_DIRECTORY", DEFAULT_PROFILES_DIRECTORY) expected = read_profile_from_directory( "mad_scientist_assistant", DEFAULT_PROFILES_DIRECTORY / "mad_scientist_assistant", ).instructions assert prompts_mod.get_session_instructions(instance_path=tmp_path) == expected def test_default_session_instructions_load_from_default_profile( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """The no-profile session prompt should come from the built-in default profile.""" monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", None) expected = read_profile_from_directory("default", DEFAULT_PROFILES_DIRECTORY / "default").instructions assert prompts_mod.get_session_instructions(instance_path=tmp_path) == expected def test_bracketed_prompt_line_stays_plain_text( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Bracketed prompt text should not be treated as an include.""" profile_dir = tmp_path / "literal_prompt" write_profile("literal_prompt", profile_dir, "[custom_prompt]\n\nStay extra brief.", []) monkeypatch.setattr(config, "PROFILES_DIRECTORY", tmp_path) monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "literal_prompt") assert prompts_mod.get_session_instructions(instance_path=tmp_path) == "[custom_prompt]\n\nStay extra brief." def test_session_instructions_fall_back_to_default_for_incomplete_profile( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Incomplete selected profiles should not stop session startup.""" profile_dir = tmp_path / "incomplete_prompt" profile_dir.mkdir() monkeypatch.setattr(config, "PROFILES_DIRECTORY", tmp_path) monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "incomplete_prompt") expected = read_profile_from_directory("default", DEFAULT_PROFILES_DIRECTORY / "default").instructions assert prompts_mod.get_session_instructions(instance_path=tmp_path) == expected def test_explicit_default_profile_does_not_fall_back_to_itself( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: """A broken explicit default profile should fail without a self-fallback log.""" default_dir = tmp_path / "default" default_dir.mkdir() monkeypatch.setattr(config, "PROFILES_DIRECTORY", tmp_path) monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "default") monkeypatch.setattr(profile_store_mod, "DEFAULT_PROFILES_DIRECTORY", tmp_path) with caplog.at_level(logging.WARNING, logger="reachy_mini_conversation_app.prompts"): with pytest.raises(RuntimeError, match="Default profile has no usable instructions"): prompts_mod.get_session_instructions(instance_path=tmp_path) assert "Using default profile instructions" not in caplog.text def test_session_voice_defaults_to_hf_voice(monkeypatch: pytest.MonkeyPatch) -> None: """Session voice should fall back to the Hugging Face default voice.""" monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", None) assert prompts_mod.get_session_voice() == "Aiden" def test_session_greeting_prompt_loads_from_selected_profile( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Profile metadata should steer the startup greeting prompt.""" profile_dir = tmp_path / "friendly" write_profile( "friendly", profile_dir, "test instructions", [], greeting="Greet me like a tiny stage host.", ) monkeypatch.setattr(config, "PROFILES_DIRECTORY", tmp_path) monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "friendly") assert prompts_mod.get_session_greeting_prompt() == "Greet me like a tiny stage host." def test_session_greeting_prompt_uses_builtin_default_without_profile( monkeypatch: pytest.MonkeyPatch, ) -> None: """The no-profile greeting should come from the built-in constant only.""" monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", None) assert prompts_mod.get_session_greeting_prompt() == prompts_mod.DEFAULT_GREETING_PROMPT def test_headless_profile_write_can_store_greeting( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """New headless profiles can persist a greeting in one profile document.""" monkeypatch.setattr(config, "INSTANCE_PATH", tmp_path) headless_mod.save_user_personality( "with_greeting", "test instructions", greeting="Open with a quick astronomy joke.", ) profile_path = tmp_path / "user_personalities" / "with_greeting" / "profile.md" assert 'greeting = "Open with a quick astronomy joke."' in profile_path.read_text(encoding="utf-8") assert read_profile("user_personalities/with_greeting").greeting == "Open with a quick astronomy joke." def test_headless_profile_write_skips_empty_greeting( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Empty custom greetings should be omitted from the profile metadata.""" monkeypatch.setattr(config, "INSTANCE_PATH", tmp_path) headless_mod.save_user_personality("without_greeting", "test instructions", greeting="") profile_text = (tmp_path / "user_personalities" / "without_greeting" / "profile.md").read_text(encoding="utf-8") assert "greeting =" not in profile_text def test_headless_profile_write_defaults_voice_at_call_time( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """New headless profiles should use the Hugging Face default voice.""" monkeypatch.setattr(config, "INSTANCE_PATH", tmp_path) headless_mod.save_user_personality("runtime_voice_default", "test instructions") profile = read_profile_from_directory( "runtime_voice_default", tmp_path / "user_personalities" / "runtime_voice_default", ) assert profile.voice == "Aiden" def test_headless_profile_write_uses_terminal_storage_without_instance( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Standalone creation should write to terminal runtime storage, not packaged profiles.""" monkeypatch.chdir(tmp_path) monkeypatch.setattr(config, "INSTANCE_PATH", None) selection = headless_mod.save_user_personality("terminal_guide", "Be concise.") assert selection == "user_personalities/terminal_guide" assert (tmp_path / "external_content" / "user_personalities" / "terminal_guide" / "profile.md").is_file() assert read_profile(selection).instructions == "Be concise." def test_headless_profile_write_rejects_unsafe_name( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Headless callers must not escape the user-personality storage root.""" monkeypatch.setattr(config, "INSTANCE_PATH", tmp_path) with pytest.raises(ValueError, match="letters, numbers, dashes"): headless_mod.save_user_personality("../outside", "Unsafe.") assert not (tmp_path / "outside").exists() def test_user_profile_round_trips_through_instance_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """UI-created profiles persist in the writable instance dir and load back from it.""" monkeypatch.setattr(config, "INSTANCE_PATH", tmp_path) monkeypatch.setattr(config, "REACHY_MINI_CUSTOM_PROFILE", "user_personalities/zen_master") headless_mod.save_user_personality("zen_master", "Be calm.") assert (tmp_path / "user_personalities" / "zen_master" / "profile.md").is_file() assert "user_personalities/zen_master" in list_personalities() assert prompts_mod.get_session_instructions(instance_path=tmp_path) == "Be calm." def test_packaged_profiles_win_outside_source_checkout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """Installed builds should use packaged profiles, not an unrelated sibling folder.""" unrelated_profiles = tmp_path / "profiles" unrelated_profiles.mkdir() packaged_profiles = tmp_path / "package_data" / "profiles" packaged_profiles.mkdir(parents=True) monkeypatch.setattr(config_mod, "PROJECT_ROOT", tmp_path) monkeypatch.setattr(config_mod, "_packaged_profiles_directory", lambda: packaged_profiles) assert config_mod._resolve_default_profiles_directory() == packaged_profiles def test_project_file_paths_stay_within_windows_budget() -> None: """Git-tracked project file paths should stay below the agreed Windows budget.""" project_root = Path(__file__).parents[1].resolve() project_files = _git_tracked_files(project_root) violations = [] for path in project_files: relative = str(Path(project_root.name) / path.relative_to(project_root)) length = len(relative) if length > WINDOWS_PATH_BUDGET: violations.append( f"Windows path budget exceeded ({WINDOWS_PATH_BUDGET}): {relative} is {length} characters long" ) assert not violations, "\n".join(violations) def test_wheel_file_paths_stay_within_windows_budget(tmp_path: Path) -> None: """Built wheel paths should stay below the agreed Windows budget.""" project_root = Path(__file__).parents[1].resolve() source_checkout = tmp_path / "checkout" dist_dir = tmp_path / "dist" for source_file in _git_tracked_files(project_root): target_file = source_checkout / source_file.relative_to(project_root) target_file.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source_file, target_file) try: subprocess.run( ["uv", "build", "--wheel", "--out-dir", str(dist_dir)], cwd=source_checkout, check=True, capture_output=True, text=True, ) except (OSError, subprocess.CalledProcessError) as exc: details = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc) pytest.fail(f"Wheel build failed while checking Windows path budget: {details}") wheel_files = list(dist_dir.glob("*.whl")) assert len(wheel_files) == 1, f"Expected exactly one built wheel in {dist_dir}, found: {wheel_files}" with zipfile.ZipFile(wheel_files[0]) as archive: archived_paths = [PurePosixPath(info.filename) for info in archive.infolist() if not info.is_dir()] violations = [] for path in archived_paths: length = len(path.as_posix()) if length > WINDOWS_WHEEL_PATH_BUDGET: violations.append( f"Windows wheel path budget exceeded ({WINDOWS_WHEEL_PATH_BUDGET}): " f"{path.as_posix()} is {length} characters long" ) assert not violations, "\n".join(violations)