Files
hermes-agent/tests/gateway/test_signal_format.py
ethernet 890bbbda1f Merge remote-tracking branch 'origin/main' into ethie/pm-clean
# Conflicts:
#	apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts
#	apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts
#	apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts
#	apps/desktop/e2e/bot-mode-roster-localized.spec.ts
#	apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
#	apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
#	apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts
#	apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts
#	apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts
#	apps/desktop/e2e/bot-roster-user-sections.spec.ts
#	apps/desktop/e2e/bot-routines-pane-narrow.spec.ts
#	apps/desktop/e2e/bot-row-open-recent-session.spec.ts
#	apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts
#	apps/desktop/e2e/group-composer-auto-grow.spec.ts
#	apps/desktop/e2e/group-create-gate-remote-roster.spec.ts
#	apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts
#	apps/desktop/e2e/hosted-room-backend-continuity.spec.ts
#	apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts
#	apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts
#	apps/desktop/e2e/worktree-branch-status.spec.ts
#	apps/desktop/electron/backend-probes.test.ts
#	apps/desktop/electron/connection-apply.test.ts
#	apps/desktop/electron/desktop-electron-pin.test.ts
#	apps/desktop/electron/desktop-uninstall.test.ts
#	apps/desktop/electron/gateway-file-download-transport.test.ts
#	apps/desktop/electron/gateway-stop-before-update.test.ts
#	apps/desktop/electron/github-api-auth.test.ts
#	apps/desktop/electron/registry-primary-profile-scope.test.ts
#	apps/desktop/electron/update-api-check.test.ts
#	apps/desktop/electron/update-handoff-marker.test.ts
#	apps/desktop/electron/venv-blocker-scan.test.ts
#	apps/desktop/scripts/after-extract.test.mjs
#	apps/desktop/scripts/local-pack-publish.test.mjs
#	apps/desktop/scripts/tasks-scroll.test.mjs
#	apps/desktop/src/app/settings/model-settings.test.tsx
#	apps/desktop/src/app/updates-overlay.blockers.test.tsx
#	apps/desktop/src/components/desktop-install-overlay.test.tsx
#	apps/desktop/src/lib/update-copy.test.ts
#	scripts/ci/check_os_marker_fakes.py
#	tests-js/desktop-mac-usage-descriptions.test.ts
#	tests-js/node-engine-alignment.test.ts
#	tests/agent/lsp/test_install_and_lint_fixes.py
#	tests/agent/test_command_token_source.py
#	tests/agent/test_compression_boundary_hook.py
#	tests/agent/test_create_openai_client_ssl_verify.py
#	tests/agent/test_custom_provider_ca_probes.py
#	tests/agent/test_endpoint_blackhole.py
#	tests/agent/test_estimator_parity.py
#	tests/agent/test_in_place_compaction.py
#	tests/agent/test_moa_loop_mode.py
#	tests/agent/test_model_metadata.py
#	tests/agent/test_skill_session_platform_gate.py
#	tests/agent/test_skill_utils.py
#	tests/agent/test_ssl_ca_guard.py
#	tests/computer_use/test_doctor.py
#	tests/cron/test_codex_execution_paths.py
#	tests/cron/test_cron_bot_chat_delivery.py
#	tests/cron/test_cron_script.py
#	tests/cron/test_media_delivery_parity.py
#	tests/cron/test_misfire_catchup.py
#	tests/cron/test_parallel_pool.py
#	tests/cron/test_recurring_eagain_redispatch.py
#	tests/gateway/test_choice_picker.py
#	tests/gateway/test_control_socket_windows_live.py
#	tests/gateway/test_dingtalk.py
#	tests/gateway/test_feishu.py
#	tests/gateway/test_feishu_onboard.py
#	tests/gateway/test_gateway_shutdown.py
#	tests/gateway/test_matrix.py
#	tests/gateway/test_model_command_custom_providers.py
#	tests/gateway/test_reasoning_command.py
#	tests/gateway/test_runtime_footer.py
#	tests/gateway/test_session.py
#	tests/gateway/test_session_hygiene.py
#	tests/gateway/test_status.py
#	tests/gateway/test_teams.py
#	tests/gateway/test_turn_lease.py
#	tests/gateway/test_whatsapp_connect.py
#	tests/hermes_cli/test_approvals_command.py
#	tests/hermes_cli/test_auth_store_lock_concurrent.py
#	tests/hermes_cli/test_backup.py
#	tests/hermes_cli/test_banner_git_state.py
#	tests/hermes_cli/test_certifi_repair.py
#	tests/hermes_cli/test_cmd_update.py
#	tests/hermes_cli/test_compat_manifest_targets.py
#	tests/hermes_cli/test_computer_use_cli.py
#	tests/hermes_cli/test_cpr_local_leak.py
#	tests/hermes_cli/test_dashboard_auth_gate.py
#	tests/hermes_cli/test_dashboard_procs_kill_grace.py
#	tests/hermes_cli/test_desktop_lifecycle_windows_live.py
#	tests/hermes_cli/test_doctor.py
#	tests/hermes_cli/test_doctor_command_install.py
#	tests/hermes_cli/test_fleet_config_migration_windows_live.py
#	tests/hermes_cli/test_gateway.py
#	tests/hermes_cli/test_gateway_platform_gating.py
#	tests/hermes_cli/test_gateway_restart_loop.py
#	tests/hermes_cli/test_gateway_task_probe.py
#	tests/hermes_cli/test_gateway_wsl.py
#	tests/hermes_cli/test_gui_command.py
#	tests/hermes_cli/test_install_cua_driver.py
#	tests/hermes_cli/test_kanban_db.py
#	tests/hermes_cli/test_lazy_command_exports.py
#	tests/hermes_cli/test_lazy_refresh_venv_repair.py
#	tests/hermes_cli/test_linux_desktop_entry.py
#	tests/hermes_cli/test_local_runtime.py
#	tests/hermes_cli/test_local_runtime_updates.py
#	tests/hermes_cli/test_managed_uv.py
#	tests/hermes_cli/test_mcp_reload_confirm_gate.py
#	tests/hermes_cli/test_nous_subscription.py
#	tests/hermes_cli/test_npm_engine.py
#	tests/hermes_cli/test_personality_none.py
#	tests/hermes_cli/test_pet_toggle.py
#	tests/hermes_cli/test_plan_reconciliation_windows_live.py
#	tests/hermes_cli/test_plugin_event_bus.py
#	tests/hermes_cli/test_plugin_manifest_v2.py
#	tests/hermes_cli/test_plugin_packs.py
#	tests/hermes_cli/test_plugins_cmd.py
#	tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py
#	tests/hermes_cli/test_process_identity.py
#	tests/hermes_cli/test_profiles.py
#	tests/hermes_cli/test_profiles_sidebar_cache.py
#	tests/hermes_cli/test_pty_bridge.py
#	tests/hermes_cli/test_resolve_turn_limit.py
#	tests/hermes_cli/test_serve_runtime_inventory.py
#	tests/hermes_cli/test_session_vacuum_config.py
#	tests/hermes_cli/test_set_config_value.py
#	tests/hermes_cli/test_signal_handler_kanban_worker.py
#	tests/hermes_cli/test_slash_confirm_windows.py
#	tests/hermes_cli/test_stale_pid_guard.py
#	tests/hermes_cli/test_startup_fast_guards.py
#	tests/hermes_cli/test_status.py
#	tests/hermes_cli/test_telegram_managed_bot.py
#	tests/hermes_cli/test_tools_config.py
#	tests/hermes_cli/test_update_apply_shallow_count.py
#	tests/hermes_cli/test_update_autostash.py
#	tests/hermes_cli/test_update_concurrent_quarantine.py
#	tests/hermes_cli/test_update_fetch_failure_classifier.py
#	tests/hermes_cli/test_update_fleet_probe_resume_token.py
#	tests/hermes_cli/test_update_handoff_backend_reap.py
#	tests/hermes_cli/test_update_handoff_desktop_rebuild.py
#	tests/hermes_cli/test_update_head_moved_gate.py
#	tests/hermes_cli/test_update_host_obligation.py
#	tests/hermes_cli/test_update_import_guard.py
#	tests/hermes_cli/test_update_interrupted_recovery.py
#	tests/hermes_cli/test_update_inventory.py
#	tests/hermes_cli/test_update_launchd_unloaded_gateway.py
#	tests/hermes_cli/test_update_missing_configured_deps.py
#	tests/hermes_cli/test_update_modified_notice.py
#	tests/hermes_cli/test_update_multiplex_migration_hook.py
#	tests/hermes_cli/test_update_no_gateway_restart.py
#	tests/hermes_cli/test_update_orphan_backend_reap.py
#	tests/hermes_cli/test_update_parked_branch_guard.py
#	tests/hermes_cli/test_update_post_pull_syntax_guard.py
#	tests/hermes_cli/test_update_receipt.py
#	tests/hermes_cli/test_update_self_lock.py
#	tests/hermes_cli/test_update_shim_fail_closed.py
#	tests/hermes_cli/test_update_shim_self_lock.py
#	tests/hermes_cli/test_update_sqlite_remediation.py
#	tests/hermes_cli/test_update_stale_dashboard.py
#	tests/hermes_cli/test_update_stale_virtualenv.py
#	tests/hermes_cli/test_update_venv_health.py
#	tests/hermes_cli/test_update_venv_ownership_preflight.py
#	tests/hermes_cli/test_update_wedged_gateway.py
#	tests/hermes_cli/test_update_yes_flag.py
#	tests/hermes_cli/test_update_zip_two_phase.py
#	tests/hermes_cli/test_urllib_security.py
#	tests/hermes_cli/test_ux_messages_auth_config.py
#	tests/hermes_cli/test_ux_messages_startup.py
#	tests/hermes_cli/test_venv_holder_classifier.py
#	tests/hermes_cli/test_verify_console_scripts.py
#	tests/hermes_cli/test_verify_core_dependencies.py
#	tests/hermes_cli/test_web_server.py
#	tests/hermes_cli/test_web_server_console_ws.py
#	tests/hermes_cli/test_web_server_ws_ping.py
#	tests/hermes_cli/test_web_ui_build.py
#	tests/hermes_state/test_fts_rebuild_admission.py
#	tests/hermes_state/test_hermes_state.py
#	tests/plugins/memory/test_memory_lazy_install.py
#	tests/plugins/test_google_meet_plugin.py
#	tests/plugins/test_langfuse_plugin.py
#	tests/plugins/test_security_guidance_plugin.py
#	tests/plugins/test_transform_llm_output_hook.py
#	tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py
#	tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
#	tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
#	tests/scripts/install/test_install_clone_throttle_fallback.py
#	tests/scripts/install/test_install_lockfile_churn.py
#	tests/scripts/install/test_install_no_initial_commit.py
#	tests/scripts/install/test_install_sh_browser_install.py
#	tests/scripts/install/test_install_sh_node_prerelease.py
#	tests/scripts/install/test_install_sh_symlink_stomp.py
#	tests/scripts/install/test_install_sh_uv_lock_config.py
#	tests/scripts/install/test_install_unmerged_index.py
#	tests/scripts/test_contributor_map.py
#	tests/scripts/test_run_tests_parallel.py
#	tests/skills/test_competitor_news_monitor_skill.py
#	tests/skills/test_document_to_action_items_skill.py
#	tests/skills/test_google_workspace_setup.py
#	tests/skills/test_google_workspace_setup_deps.py
#	tests/skills/test_grounded_citations_skill.py
#	tests/skills/test_ip_as_logo_skill.py
#	tests/skills/test_live_dashboard_skill.py
#	tests/skills/test_mcp_oauth_remote_gateway_skill.py
#	tests/skills/test_office_document_skills.py
#	tests/skills/test_openclaw_migration.py
#	tests/skills/test_product_price_monitor_skill.py
#	tests/skills/test_scrollcraft_skill.py
#	tests/skills/test_setup_wizard_generator_skill.py
#	tests/skills/test_weekly_review_planning_skill.py
#	tests/test_engines_satisfiable.py
#	tests/test_fast_safe_load.py
#	tests/test_hermes_bootstrap.py
#	tests/test_hermes_constants.py
#	tests/test_hermes_logging.py
#	tests/test_managed_runtime_resolution.py
#	tests/test_model_tools_async_bridge.py
#	tests/test_packaging_build_guard.py
#	tests/test_packaging_metadata.py
#	tests/test_yaml_indent_consistency.py
#	tests/tools/test_approval_timeout_overflow.py
#	tests/tools/test_base_environment.py
#	tests/tools/test_bot_mode_dm.py
#	tests/tools/test_browser_chromium_check.py
#	tests/tools/test_browser_hardening.py
#	tests/tools/test_browser_homebrew_paths.py
#	tests/tools/test_browser_npx_warmup.py
#	tests/tools/test_browser_orphan_reaper.py
#	tests/tools/test_browser_real_profile.py
#	tests/tools/test_browser_use_cli.py
#	tests/tools/test_clipboard.py
#	tests/tools/test_code_execution.py
#	tests/tools/test_code_execution_modes.py
#	tests/tools/test_code_execution_windows_env.py
#	tests/tools/test_computer_use.py
#	tests/tools/test_delegate_liveness_timeout.py
#	tests/tools/test_execute_code_approval_cluster.py
#	tests/tools/test_execution_flag_detection.py
#	tests/tools/test_fal_common.py
#	tests/tools/test_file_operations.py
#	tests/tools/test_file_tools.py
#	tests/tools/test_file_tools_cwd_resolution.py
#	tests/tools/test_file_tools_live.py
#	tests/tools/test_lazy_deps.py
#	tests/tools/test_lazy_deps_durable_target.py
#	tests/tools/test_lazy_deps_managed.py
#	tests/tools/test_local_env_blocklist.py
#	tests/tools/test_local_tempdir.py
#	tests/tools/test_macos_protected_search.py
#	tests/tools/test_mcp_npx_cached_bin.py
#	tests/tools/test_oneshot_completion_linger.py
#	tests/tools/test_process_registry.py
#	tests/tools/test_read_file_schema_gating.py
#	tests/tools/test_skill_improvements.py
#	tests/tools/test_skills_sync.py
#	tests/tools/test_termux_api_detection.py
#	tests/tools/test_tirith_security.py
#	tests/tools/test_transcription_tools.py
#	tests/tools/test_tts_streaming.py
#	tests/tools/test_wake_word.py
#	tests/tui_gateway/test_compute_host_borrowed_lease.py
#	tests/tui_gateway/test_compute_host_turn_protocol.py
#	tests/tui_gateway/test_isolated_orphan_activity.py
#	tests/tui_gateway/test_protocol.py
#	tests/tui_gateway/test_slash_worker_profile_home.py
#	tests/tui_gateway/test_subprocess_encoding.py
#	tests/tui_gateway/test_tui_gateway_server.py
#	ui-tui/src/__tests__/terminalParity.test.ts
#	ui-tui/src/__tests__/termuxComposerLayout.test.ts
#	ui-tui/src/__tests__/textInputFastEcho.test.ts
2026-09-23 07:02:44 -04:00

250 lines
10 KiB
Python

"""Tests for Signal markdown_to_signal() formatting.
Covers the markdown-to-bodyRanges conversion pipeline: bold, italic,
strikethrough, monospace, code blocks, headings, and — critically — the
false-positive regressions that caused spurious italics in production.
"""
from gateway.platforms.signal_format import markdown_to_signal
# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
def _m2s(text: str):
"""Shorthand: return (plain_text, styles)."""
return markdown_to_signal(text)
def _style_types(styles: list[str]) -> list[str]:
"""Extract just the STYLE part from '0:4:BOLD' strings."""
return [s.rsplit(":", 1)[1] for s in styles]
def _find_style(styles: list[str], style_type: str) -> list[str]:
"""Return only styles matching a given type."""
return [s for s in styles if s.endswith(f":{style_type}")]
# ===========================================================================
# Basic formatting
# ===========================================================================
class TestMarkdownToSignalBasic:
"""Core formatting: bold, italic, strikethrough, monospace."""
def test_bold_double_asterisk(self):
text, styles = _m2s("hello **world**")
assert text == "hello world"
assert len(styles) == 1
assert styles[0].endswith(":BOLD")
def test_italic_single_asterisk(self):
text, styles = _m2s("hello *world*")
assert text == "hello world"
assert len(styles) == 1
assert styles[0].endswith(":ITALIC")
def test_strikethrough(self):
text, styles = _m2s("hello ~~world~~")
assert text == "hello world"
assert len(styles) == 1
assert styles[0].endswith(":STRIKETHROUGH")
def test_inline_monospace(self):
text, styles = _m2s("run `ls -la` now")
assert text == "run ls -la now"
assert len(styles) == 1
assert styles[0].endswith(":MONOSPACE")
# ===========================================================================
# Italic false-positive regressions
# ===========================================================================
class TestItalicFalsePositives:
"""Regressions from signal-italic-false-positive-fix.md and
signal-italic-bullet-list-fix.md."""
# --- snake_case (original fix) ---
def test_snake_case_not_italic(self):
"""snake_case identifiers must NOT be italicized."""
text, styles = _m2s("the config_file is ready")
assert text == "the config_file is ready"
assert _find_style(styles, "ITALIC") == []
# --- Bullet lists (second fix) ---
def test_hyphen_bullet_list_uses_signal_safe_bullets(self):
"""Signal does not render Markdown list markers; normalize them."""
md = "- item one\n- item two"
text, styles = _m2s(md)
assert text == "• item one\n• item two"
assert styles == []
def test_bullet_list_file_paths(self):
"""Real-world case that triggered the bug."""
md = (
"* tools/delegate_tool.py — delegation\n"
"* tools/file_tools.py — file operations\n"
"* tools/web_tools.py — web operations"
)
text, styles = _m2s(md)
assert _find_style(styles, "ITALIC") == []
# --- Cross-line spans (DOTALL removal) ---
def test_underscore_italic_no_cross_line(self):
"""_foo\\nbar_ must NOT match as italic (no DOTALL)."""
text, styles = _m2s("_foo\nbar_")
assert _find_style(styles, "ITALIC") == []
def test_star_italic_multiline_response(self):
"""Multi-paragraph response with * should not false-positive."""
md = (
"I checked the following files:\n\n"
"* tools/delegate_tool.py — sub-agent delegation\n"
"* tools/file_tools.py — file read/write/search\n"
"* tools/web_tools.py — web search/extract\n\n"
"Everything looks good."
)
text, styles = _m2s(md)
assert _find_style(styles, "ITALIC") == []
# --- Legitimate italic still works ---
def test_multiple_italic_same_line(self):
text, styles = _m2s("*foo* and *bar* ok")
assert text == "foo and bar ok"
assert len(_find_style(styles, "ITALIC")) == 2
def test_italic_single_word(self):
text, styles = _m2s("*word*")
assert text == "word"
assert len(_find_style(styles, "ITALIC")) == 1
# ===========================================================================
# Style position accuracy
# ===========================================================================
class TestStylePositions:
"""Verify that start:length positions map to the correct text."""
def _extract(self, text: str, style_str: str) -> str:
"""Given 'start:length:STYLE', extract the substring from text."""
# Positions are UTF-16 code units; for ASCII they match code points
parts = style_str.split(":")
start, length = int(parts[0]), int(parts[1])
# Encode to UTF-16-LE, slice, decode back
encoded = text.encode("utf-16-le")
extracted = encoded[start * 2 : (start + length) * 2]
return extracted.decode("utf-16-le")
def test_bold_position(self):
text, styles = _m2s("hello **world** end")
assert len(styles) == 1
assert self._extract(text, styles[0]) == "world"
# ===========================================================================
# Edge cases
# ===========================================================================
class TestEdgeCases:
"""Tricky inputs that have caused issues or could regress."""
def test_bold_inside_bullet(self):
"""Bold inside a bullet list item."""
md = "* **important** item\n* normal item"
text, styles = _m2s(md)
assert len(_find_style(styles, "BOLD")) == 1
assert _find_style(styles, "ITALIC") == []
def test_lone_asterisk(self):
"""A single * with no pair should not cause issues."""
text, styles = _m2s("5 * 3 = 15")
# Should not crash; any italic match would be a false positive
assert "5" in text and "15" in text
# ===========================================================================
# signal-markdown-strip-patch: core conversion pipeline
# ===========================================================================
class TestMarkdownStripPatch:
"""Tests for the original signal-markdown-strip-patch.
Covers: fenced code blocks with language tags, links preserved,
headings converted to bold, multiple headings, UTF-16 correctness
for multi-byte characters, and marker stripping completeness.
"""
def test_fenced_code_block_multiline(self):
"""Multi-line code blocks preserve all lines."""
md = "```\nline1\nline2\nline3\n```"
text, styles = _m2s(md)
assert "line1" in text
assert "line2" in text
assert "line3" in text
assert "```" not in text
def test_links_preserved(self):
"""[text](url) links are kept as-is — Signal auto-linkifies."""
md = "Check [this link](https://example.com) for details"
text, styles = _m2s(md)
# Links should pass through — either as markdown or just preserved
assert "https://example.com" in text
def test_heading_h1(self):
"""# H1 becomes bold text."""
text, styles = _m2s("# Main Title")
assert text == "Main Title"
assert len(styles) == 1
assert styles[0].endswith(":BOLD")
def test_multiple_headings(self):
"""Multiple headings each become separate bold spans."""
md = "## First\n\nSome text\n\n## Second"
text, styles = _m2s(md)
assert "First" in text
assert "Second" in text
assert "##" not in text
bold_styles = _find_style(styles, "BOLD")
assert len(bold_styles) == 2
# ## at end might remain if not at line start — that's ok
# The important thing is styled markers are stripped
# ===========================================================================
# signal-streaming-patch: SUPPORTS_MESSAGE_EDITING and send() behavior
# ===========================================================================
class TestTableRealignment:
"""GFM pipe tables are re-aligned to a fixed monospace width and wrapped in a
single MONOSPACE style range, per the Signal table-rendering feature request."""
@staticmethod
def _u16_slice(text: str, style: str) -> str:
start, length = (int(p) for p in style.split(":")[:2])
u16 = text.encode("utf-16-le")
return u16[start * 2 : (start + length) * 2].decode("utf-16-le")
def test_wide_char_table_becomes_one_aligned_monospace_block(self):
"""Cells with CJK/emoji (2 display cells, 1-2 UTF-16 units) still produce pipes that line up
by display width, one MONOSPACE range covering exactly the block, and correct UTF-16 offsets
for styles after it."""
from wcwidth import wcswidth
text, styles = _m2s("| 名前 | Score |\n|---|---|\n| 東京 | 🚀 |\n| Bob | 1 |\n\n**tail**")
(mono,) = _find_style(styles, "MONOSPACE")
block = self._u16_slice(text, mono)
assert text == block + "\n\ntail"
rows = block.split("\n")
assert len(rows) == 4 and all(wcswidth(row) == wcswidth(rows[0]) for row in rows)
assert self._u16_slice(text, _find_style(styles, "BOLD")[0]) == "tail"
def test_fenced_pipe_table_is_code_and_later_code_range_survives_realignment(self):
"""A pipe table inside ``` is code and must not be realigned or double-styled; a table's
padding changes its length, and a code block after it still maps to its own text."""
text, styles = _m2s("| Name | Age |\n|---|---|\n| Alice | 30 |\n\n```\n| a | b |\n|---|---|\n| 1 | 22 |\n```")
mono = _find_style(styles, "MONOSPACE")
assert len(mono) == 2
assert self._u16_slice(text, mono[0]) == "| Name | Age |\n|-------|-----|\n| Alice | 30 |"
assert self._u16_slice(text, mono[1]) == "| a | b |\n|---|---|\n| 1 | 22 |"
assert "cost | value" == _m2s("cost | value\nnot a table")[0].split("\n")[0]