From 4bae72230470d0a4864071e6d98cbc3ece4a9cc0 Mon Sep 17 00:00:00 2001 From: aamj Date: Mon, 23 Nov 2026 11:40:00 -0300 Subject: [PATCH 1/5] Non Blocking prompt handling --- tests/test_run/test_websocket_connect.py | 162 +++++++++++++++++++++++ th_cli/test_run/websocket.py | 69 ++++++++-- 2 files changed, 221 insertions(+), 10 deletions(-) diff --git a/tests/test_run/test_websocket_connect.py b/tests/test_run/test_websocket_connect.py index 4a1a8b3..c59faeb 100644 --- a/tests/test_run/test_websocket_connect.py +++ b/tests/test_run/test_websocket_connect.py @@ -235,3 +235,165 @@ async def test_older_backend_drains_trailing_log_records(self): mock_logger.log.assert_any_call("INFO", "trailing") assert fake_socket.recv.await_count == 3 fake_socket.close.assert_called_once() + + +# --------------------------------------------------------------------------- +# connect_websocket — prompts are answered without blocking the read loop +# --------------------------------------------------------------------------- + +_PROMPT_ID = 7 + +_OPTIONS_PROMPT = json.dumps( + { + "type": "options_request", + "payload": {"prompt": "Make sure the DUT is in Commissioning Mode", "timeout": 60, "message_id": _PROMPT_ID, + "options": {"DONE": 1, "FAILED": 2}}, + } +) +_PROMPT_TIMED_OUT = json.dumps({"type": "time_out_notification", "payload": {"message_id": _PROMPT_ID}}) +_LOG_RECORDS = json.dumps( + {"type": "test_log_records", "payload": [{"level": "INFO", "timestamp": 1.0, "message": "pairing logs"}]} +) + + +def _yielding_recv(messages): + """recv() stand-in that hands over the messages in order, yielding to the loop before each one.""" + pending = list(messages) + + async def recv(): + await asyncio.sleep(0) + return pending.pop(0) + + return recv + + +class _BlockedPrompt: + """handle_prompt stand-in that stays open until released, recording how it ended.""" + + def __init__(self): + self.started = asyncio.Event() + self.release = asyncio.Event() + self.cancelled = False + + async def __call__(self, **_kwargs): + self.started.set() + try: + await self.release.wait() + except asyncio.CancelledError: + self.cancelled = True + raise + + +@pytest.mark.unit +class TestConnectWebsocketPrompts: + @pytest.mark.asyncio + async def test_log_records_are_processed_while_prompt_is_open(self): + """The prompt only returns after a log record was handled: the read loop must not wait for it.""" + s = _make_socket() + prompt = _BlockedPrompt() + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv([_OPTIONS_PROMPT, _LOG_RECORDS, _terminal_run_update(logs_complete=True)]) + ) + + with ( + _patch_connect(fake_socket), + patch("th_cli.test_run.websocket.handle_prompt", new=prompt), + patch("th_cli.test_run.websocket.logger") as mock_logger, + ): + mock_logger.log.side_effect = lambda *_: prompt.release.set() + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + mock_logger.log.assert_any_call("INFO", "pairing logs") + assert prompt.started.is_set() + assert not prompt.cancelled + + @pytest.mark.asyncio + async def test_timeout_notification_cancels_open_prompt(self, capsys): + s = _make_socket() + prompt = _BlockedPrompt() + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv( + [_OPTIONS_PROMPT, _PROMPT_TIMED_OUT, _terminal_run_update(logs_complete=True)] + ) + ) + + with _patch_connect(fake_socket), patch("th_cli.test_run.websocket.handle_prompt", new=prompt): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert prompt.cancelled + assert capsys.readouterr().err.count("Prompt timed out") == 1 + + @pytest.mark.asyncio + async def test_timeout_notification_for_unknown_prompt_is_ignored(self, capsys): + s = _make_socket() + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv([_PROMPT_TIMED_OUT, _terminal_run_update(logs_complete=True)]) + ) + + with _patch_connect(fake_socket): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert "Prompt timed out" not in capsys.readouterr().err + + @pytest.mark.asyncio + async def test_open_prompt_is_cancelled_when_run_finishes(self): + s = _make_socket() + prompt = _BlockedPrompt() + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv([_OPTIONS_PROMPT, _terminal_run_update(logs_complete=True)]) + ) + + with _patch_connect(fake_socket), patch("th_cli.test_run.websocket.handle_prompt", new=prompt): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert prompt.started.is_set() + assert prompt.cancelled + + @pytest.mark.asyncio + async def test_prompt_failure_is_reported_and_raised(self, capsys): + s = _make_socket() + messages = [_OPTIONS_PROMPT] + [_LOG_RECORDS] * 5 + [_terminal_run_update(logs_complete=True)] + fake_socket = _FakeWSSocket(recv_side_effect=_yielding_recv(messages)) + + with ( + _patch_connect(fake_socket), + patch("th_cli.test_run.websocket.handle_prompt", new=AsyncMock(side_effect=EOFError("stdin closed"))), + patch("th_cli.test_run.websocket.logger"), + ): + with pytest.raises(EOFError): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert "Prompt handling failed" in capsys.readouterr().err + + @pytest.mark.asyncio + async def test_prompts_are_answered_one_at_a_time(self): + s = _make_socket() + second_prompt = _OPTIONS_PROMPT.replace(f'"message_id": {_PROMPT_ID}', f'"message_id": {_PROMPT_ID + 1}') + running = 0 + max_running = 0 + + async def prompt(**_kwargs): + nonlocal running, max_running + running += 1 + max_running = max(max_running, running) + await asyncio.sleep(0.05) + running -= 1 + + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv([_OPTIONS_PROMPT, second_prompt, _terminal_run_update(logs_complete=True)]) + ) + # The run finishing cancels what is still open, so keep the loop alive until both prompts are done. + original = s._TestRunSocket__cancel_pending_prompts + + async def wait_then_cancel(): + await asyncio.gather(*s._prompt_tasks.values(), return_exceptions=True) + await original() + + with ( + _patch_connect(fake_socket), + patch("th_cli.test_run.websocket.handle_prompt", new=prompt), + patch.object(s, "_TestRunSocket__cancel_pending_prompts", wait_then_cancel), + ): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert max_running == 1 diff --git a/th_cli/test_run/websocket.py b/th_cli/test_run/websocket.py index 2976b9a..9d5df9a 100644 --- a/th_cli/test_run/websocket.py +++ b/th_cli/test_run/websocket.py @@ -139,6 +139,13 @@ def __init__( self._run_finished = False # From the terminal TestRunUpdate (see TestRunUpdate.logs_complete). self._logs_complete: bool | None = None + # Prompts are answered in background tasks (keyed by message_id) so the + # read loop keeps handling updates and log records while the user types. + self._prompt_tasks: dict[int, asyncio.Task] = {} + # Every prompt reads from the same stdin, so only one is shown at a time. + self._prompt_lock = asyncio.Lock() + # First exception raised by a prompt task, re-raised by the read loop. + self._prompt_error: BaseException | None = None # Track test step errors for logging # Key: (suite_index, case_index), Value: list of error strings from all steps self.test_case_step_errors: dict[tuple[int, int], list[str]] = {} @@ -192,6 +199,8 @@ async def connect_websocket(self) -> None: ) as socket: try: while True: + if self._prompt_error is not None: + raise self._prompt_error if self._run_finished and self._logs_complete is not None: # The backend sent the terminal update after the # run's last log records: nothing left to drain. @@ -249,6 +258,10 @@ async def connect_websocket(self) -> None: finally: if self._chip_server_watcher: self._chip_server_watcher.cancel() + await self.__cancel_pending_prompts() + + if self._prompt_error is not None: + raise self._prompt_error if incomplete_closure: raise IncompleteTestRunError( @@ -262,7 +275,27 @@ async def __handle_incoming_socket_message(self, socket: WebSocketClientProtocol elif isinstance(message.payload, PromptRequest): # Debug: log the message type logger.debug(f"Received prompt with type: {message.type}") + self.__start_prompt_task(socket=socket, message=message) + elif message.type == MessageTypeEnum.TEST_LOG_RECORDS and isinstance(message.payload, list): + await self.__handle_log_record(message.payload) + elif isinstance(message.payload, TimeOutNotification): + # The backend stopped waiting for this prompt: drop it if it is still open. + self.__cancel_prompt(message.payload.message_id) + else: + click.echo( + colorize_error(f"Unknown socket message type: {message.type} | payload: {message.payload}."), + err=True, + ) + + def __start_prompt_task(self, socket: WebSocketClientProtocol, message: SocketMessage) -> None: + """Answer the prompt in the background so the read loop is not blocked while waiting for input.""" + message_id = message.payload.message_id + task = asyncio.create_task(self.__answer_prompt(socket=socket, message=message)) + self._prompt_tasks[message_id] = task + task.add_done_callback(lambda done: self.__prompt_task_done(message_id=message_id, task=done)) + async def __answer_prompt(self, socket: WebSocketClientProtocol, message: SocketMessage) -> None: + async with self._prompt_lock: # Check message type to route to appropriate handler if message.type == MessageTypeEnum.FILE_UPLOAD_REQUEST: await handle_file_upload_request(socket=socket, request=message.payload) @@ -274,16 +307,32 @@ async def __handle_incoming_socket_message(self, socket: WebSocketClientProtocol message_type=message.type, two_way_talk_handler=self.two_way_talk_handler, ) - elif message.type == MessageTypeEnum.TEST_LOG_RECORDS and isinstance(message.payload, list): - await self.__handle_log_record(message.payload) - elif isinstance(message.payload, TimeOutNotification): - # ignore time_out_notification as we handle timeout our selves - pass - else: - click.echo( - colorize_error(f"Unknown socket message type: {message.type} | payload: {message.payload}."), - err=True, - ) + + def __prompt_task_done(self, message_id: int, task: asyncio.Task) -> None: + if self._prompt_tasks.get(message_id) is task: + del self._prompt_tasks[message_id] + if task.cancelled(): + return + error = task.exception() + if error is not None: + # Show it right away; the read loop re-raises it once it gets control back. + click.echo(colorize_error(f"Prompt handling failed: {error}"), err=True) + if self._prompt_error is None: + self._prompt_error = error + + def __cancel_prompt(self, message_id: int) -> None: + task = self._prompt_tasks.get(message_id) + if task is None or task.done(): + return + task.cancel() + click.echo(colorize_error("Prompt timed out"), err=True) + + async def __cancel_pending_prompts(self) -> None: + tasks = list(self._prompt_tasks.values()) + for task in tasks: + task.cancel() + if tasks: + await asyncio.gather(*tasks, return_exceptions=True) async def __handle_test_update(self, update: TestUpdate) -> None: if isinstance(update.body, TestStepUpdate): From 92a6d9f60ef3b225542072e1b15d711d6723545d Mon Sep 17 00:00:00 2001 From: aamj Date: Tue, 24 Nov 2026 12:32:06 -0300 Subject: [PATCH 2/5] Order and color of the prompt --- tests/test_colorize.py | 41 +++++++++++ tests/test_run/test_websocket_connect.py | 93 +++++++++++++++++++++++- th_cli/colorize.py | 33 +++++++++ th_cli/test_run/prompt_manager.py | 4 +- th_cli/test_run/websocket.py | 25 +++++++ 5 files changed, 191 insertions(+), 5 deletions(-) diff --git a/tests/test_colorize.py b/tests/test_colorize.py index 56f1ef0..baa68c7 100644 --- a/tests/test_colorize.py +++ b/tests/test_colorize.py @@ -34,6 +34,7 @@ colorize_state, colorize_success, colorize_warning, + colorize_prompt, italic, set_colors_enabled, ) @@ -440,6 +441,46 @@ def test_non_empty_with_colors_enabled(self): assert "hello" in result +# --------------------------------------------------------------------------- +# colorize_prompt +# --------------------------------------------------------------------------- + +_DUT_PROMPT = "Make sure the DUT is in Commissioning Mode (looking for discriminator 3437, setup code 9198814)" + + +@pytest.mark.unit +class TestColorizePrompt: + def test_plain_when_colors_disabled(self): + set_colors_enabled(False) + assert colorize_prompt(_DUT_PROMPT) == _DUT_PROMPT + + def test_text_is_unchanged_once_styles_are_removed(self): + set_colors_enabled(True) + assert click.unstyle(colorize_prompt(_DUT_PROMPT)) == _DUT_PROMPT + + def test_highlights_discriminator_and_setup_code_values(self): + set_colors_enabled(True) + result = colorize_prompt(_DUT_PROMPT) + for value in ("3437", "9198814"): + assert click.style(value, fg="bright_yellow", bold=True, italic=True) in result + + def test_highlights_values_in_retry_prompt(self): + set_colors_enabled(True) + prompt = ( + "Commissioning failed.\n" + "The Test Harness was looking for discriminator 3840, setup code 20202021.\n" + "Retry?" + ) + result = colorize_prompt(prompt) + assert click.unstyle(result) == prompt + assert click.style("20202021", fg="bright_yellow", bold=True, italic=True) in result + + def test_other_numbers_are_not_highlighted(self): + set_colors_enabled(True) + prompt = "Press 1 within 60 seconds" + assert colorize_prompt(prompt) == italic(prompt) + + # --------------------------------------------------------------------------- # colorize_change # --------------------------------------------------------------------------- diff --git a/tests/test_run/test_websocket_connect.py b/tests/test_run/test_websocket_connect.py index c59faeb..4b845ab 100644 --- a/tests/test_run/test_websocket_connect.py +++ b/tests/test_run/test_websocket_connect.py @@ -22,7 +22,7 @@ import asyncio import json -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest import websockets.exceptions as ws_exceptions @@ -256,12 +256,12 @@ async def test_older_backend_drains_trailing_log_records(self): ) -def _yielding_recv(messages): +def _yielding_recv(messages, delay=0): """recv() stand-in that hands over the messages in order, yielding to the loop before each one.""" pending = list(messages) async def recv(): - await asyncio.sleep(0) + await asyncio.sleep(delay) return pending.pop(0) return recv @@ -397,3 +397,90 @@ async def wait_then_cancel(): await asyncio.wait_for(s.connect_websocket(), timeout=5) assert max_running == 1 + + +# --------------------------------------------------------------------------- +# CHIP server info is shown before the prompt, not between the prompt and its answer +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +class TestChipServerInfoBeforePrompt: + @staticmethod + async def _run(s, show, prompt, messages, delay=0): + fake_socket = _FakeWSSocket(recv_side_effect=_yielding_recv(messages, delay=delay)) + with ( + _patch_connect(fake_socket), + patch.object(s, "_TestRunSocket__display_manual_pairing_code", new=show), + patch("th_cli.test_run.websocket.handle_prompt", new=prompt), + patch("th_cli.test_run.websocket.logger"), + ): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + @pytest.mark.asyncio + async def test_info_is_shown_before_the_prompt(self): + s = _make_socket() + s._chip_server_watcher = MagicMock() # the run is executing + order = [] + + async def show(): + order.append("info") + + async def prompt(**_kwargs): + order.append("prompt") + + messages = [_OPTIONS_PROMPT] + [_LOG_RECORDS] * 5 + [_terminal_run_update(logs_complete=True)] + await self._run(s, show, prompt, messages) + + assert order == ["info", "prompt"] + + @pytest.mark.asyncio + async def test_no_info_before_the_prompt_when_run_is_not_executing(self): + s = _make_socket() + show = AsyncMock() + prompt = AsyncMock() + + messages = [_OPTIONS_PROMPT] + [_LOG_RECORDS] * 5 + [_terminal_run_update(logs_complete=True)] + await self._run(s, show, prompt, messages) + + show.assert_not_called() + prompt.assert_awaited_once() + + @pytest.mark.asyncio + async def test_slow_info_does_not_hold_the_prompt_back(self): + s = _make_socket() + s._chip_server_watcher = MagicMock() + shown = [] + + async def show(): + await asyncio.Event().wait() # never answers + + async def prompt(**_kwargs): + shown.append("prompt") + + with patch("th_cli.test_run.websocket.CHIP_SERVER_INFO_BEFORE_PROMPT_TIMEOUT_S", 0.01): + await self._run(s, show, prompt, [_OPTIONS_PROMPT, _terminal_run_update(logs_complete=True)], delay=0.05) + + assert shown == ["prompt"] + + @pytest.mark.asyncio + async def test_info_is_fetched_one_caller_at_a_time(self): + """The watcher and a prompt can ask at once; only one may fetch, so the banner shows once.""" + s = _make_socket() + running = 0 + peak = 0 + + async def fetch(): + nonlocal running, peak + running += 1 + peak = max(peak, running) + await asyncio.sleep(0.01) + running -= 1 + + with patch.object(s, "_TestRunSocket__fetch_and_display_chip_server_info", new=fetch): + await asyncio.gather( + s._TestRunSocket__display_manual_pairing_code(), + s._TestRunSocket__display_manual_pairing_code(), + ) + + assert peak == 1 diff --git a/th_cli/colorize.py b/th_cli/colorize.py index c4ed773..ae8f365 100644 --- a/th_cli/colorize.py +++ b/th_cli/colorize.py @@ -15,6 +15,7 @@ # import os +import re from enum import Enum import click @@ -32,6 +33,7 @@ class TextTypeEnum(str, Enum): SUCCESS = "success" ERROR = "error" WARNING = "warning" + HIGHLIGHT = "highlight" class HierarchyEnum(str, Enum): @@ -89,6 +91,7 @@ class ColorConfig: TextTypeEnum.SUCCESS.value: "green", TextTypeEnum.ERROR.value: "red", TextTypeEnum.WARNING.value: "yellow", + TextTypeEnum.HIGHLIGHT.value: "bright_yellow", } def __init__(self): @@ -349,6 +352,36 @@ def italic(text: str) -> str: return click.style(text, italic=True) +# The values the backend names when it asks about the DUT's commissioning mode, e.g. +# "(looking for discriminator 3840, setup code 20202021)". +_DUT_VALUE_PATTERN = re.compile(r"(?<=discriminator )\d+|(?<=setup code )\d+") + + +def colorize_prompt(prompt: str) -> str: + """ + Italicize a prompt, emphasizing the DUT discriminator and setup code it mentions. + + Args: + prompt: The prompt text, as sent by the backend + Returns: + Styled string if colors are enabled, plain string otherwise + """ + if not color_config.colors_enabled: + return prompt + + highlight_color = color_config.get_text_color(TextTypeEnum.HIGHLIGHT.value) + parts = [] + position = 0 + for match in _DUT_VALUE_PATTERN.finditer(prompt): + if match.start() > position: + parts.append(click.style(prompt[position : match.start()], italic=True)) + parts.append(click.style(match.group(), fg=highlight_color, bold=True, italic=True)) + position = match.end() + if position < len(prompt): + parts.append(click.style(prompt[position:], italic=True)) + return "".join(parts) + + def set_colors_enabled(enabled: bool) -> None: """ Programmatically enable or disable colors. diff --git a/th_cli/test_run/prompt_manager.py b/th_cli/test_run/prompt_manager.py index 1e28540..cb957a8 100644 --- a/th_cli/test_run/prompt_manager.py +++ b/th_cli/test_run/prompt_manager.py @@ -27,7 +27,7 @@ import httpx from websockets.client import WebSocketClientProtocol -from th_cli.colorize import colorize_error, colorize_key_value, italic +from th_cli.colorize import colorize_error, colorize_key_value, colorize_prompt, italic from th_cli.config import config from th_cli.shared_constants import MessageKeysEnum, MessageTypeEnum @@ -392,7 +392,7 @@ async def __handle_message_prompt(socket: WebSocketClientProtocol, prompt: Promp async def _prompt_user_for_option(prompt: OptionsSelectPromptRequest) -> int: # Print Prompt - click.echo(italic(prompt.prompt)) + click.echo(colorize_prompt(prompt.prompt)) for key in prompt.options.keys(): id = prompt.options[key] click.echo(f" {colorize_key_value(str(id), key)}") diff --git a/th_cli/test_run/websocket.py b/th_cli/test_run/websocket.py index 9d5df9a..1630d42 100644 --- a/th_cli/test_run/websocket.py +++ b/th_cli/test_run/websocket.py @@ -96,6 +96,9 @@ # How often to check whether the CHIP server (re)started, so its Node ID is shown. CHIP_SERVER_POLL_INTERVAL_S = 2.0 +# Longest a prompt waits for the CHIP server info to be shown ahead of it. +CHIP_SERVER_INFO_BEFORE_PROMPT_TIMEOUT_S = 5.0 + # Yield to the event loop every N log records while processing one batch, so # a very large batch doesn't block the websocket read loop for its entire # duration. The backend sends up to LOG_RECORDS_BROADCAST_CHUNK_SIZE=200 @@ -136,6 +139,9 @@ def __init__( self._chip_server_info_displayed = False self._displayed_node_id: int | None = None self._chip_server_watcher: asyncio.Task | None = None + # The watcher and the prompts both show the CHIP server info: one at a time, + # so it is only shown once per server start. + self._chip_info_lock = asyncio.Lock() self._run_finished = False # From the terminal TestRunUpdate (see TestRunUpdate.logs_complete). self._logs_complete: bool | None = None @@ -296,6 +302,8 @@ def __start_prompt_task(self, socket: WebSocketClientProtocol, message: SocketMe async def __answer_prompt(self, socket: WebSocketClientProtocol, message: SocketMessage) -> None: async with self._prompt_lock: + await self.__show_chip_server_info_before_prompt() + # Check message type to route to appropriate handler if message.type == MessageTypeEnum.FILE_UPLOAD_REQUEST: await handle_file_upload_request(socket=socket, request=message.payload) @@ -382,7 +390,24 @@ async def __watch_chip_server_info(self) -> None: await self.__display_manual_pairing_code() await asyncio.sleep(CHIP_SERVER_POLL_INTERVAL_S) + async def __show_chip_server_info_before_prompt(self) -> None: + """Show the CHIP server info before a prompt, instead of between it and its answer. + + The CHIP server starts right before the commissioning prompt is sent, but the + watcher only notices it up to a poll interval later. + """ + if self._chip_server_watcher is None: + return # The run is not executing yet, so there is no CHIP server + try: + await asyncio.wait_for(self.__display_manual_pairing_code(), CHIP_SERVER_INFO_BEFORE_PROMPT_TIMEOUT_S) + except asyncio.TimeoutError: + logger.debug("Timed out fetching the CHIP server info before a prompt") + async def __display_manual_pairing_code(self) -> None: + async with self._chip_info_lock: + await self.__fetch_and_display_chip_server_info() + + async def __fetch_and_display_chip_server_info(self) -> None: """Display the Node ID and manual pairing code once the CHIP server is up. The Node ID is regenerated every time the CHIP server starts, so it is only From e0ee4b57bc65b21d7315612e9fc851bb0b209f5f Mon Sep 17 00:00:00 2001 From: aamj Date: Tue, 24 Nov 2026 13:59:46 -0300 Subject: [PATCH 3/5] Changing to a blue color highlight --- tests/test_colorize.py | 4 ++-- th_cli/colorize.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_colorize.py b/tests/test_colorize.py index baa68c7..53710e5 100644 --- a/tests/test_colorize.py +++ b/tests/test_colorize.py @@ -462,7 +462,7 @@ def test_highlights_discriminator_and_setup_code_values(self): set_colors_enabled(True) result = colorize_prompt(_DUT_PROMPT) for value in ("3437", "9198814"): - assert click.style(value, fg="bright_yellow", bold=True, italic=True) in result + assert click.style(value, fg="bright_blue", bold=True, italic=True) in result def test_highlights_values_in_retry_prompt(self): set_colors_enabled(True) @@ -473,7 +473,7 @@ def test_highlights_values_in_retry_prompt(self): ) result = colorize_prompt(prompt) assert click.unstyle(result) == prompt - assert click.style("20202021", fg="bright_yellow", bold=True, italic=True) in result + assert click.style("20202021", fg="bright_blue", bold=True, italic=True) in result def test_other_numbers_are_not_highlighted(self): set_colors_enabled(True) diff --git a/th_cli/colorize.py b/th_cli/colorize.py index ae8f365..2b469b7 100644 --- a/th_cli/colorize.py +++ b/th_cli/colorize.py @@ -91,7 +91,7 @@ class ColorConfig: TextTypeEnum.SUCCESS.value: "green", TextTypeEnum.ERROR.value: "red", TextTypeEnum.WARNING.value: "yellow", - TextTypeEnum.HIGHLIGHT.value: "bright_yellow", + TextTypeEnum.HIGHLIGHT.value: "bright_blue", } def __init__(self): From 293e5b93d2ae242de281579d95673766c287e4ff Mon Sep 17 00:00:00 2001 From: aamj Date: Wed, 25 Nov 2026 15:11:37 -0300 Subject: [PATCH 4/5] Prompt failure raises while idle now --- tests/test_run/test_websocket_connect.py | 55 ++++++++++++++++++++++++ th_cli/test_run/websocket.py | 46 +++++++++++++++++--- 2 files changed, 96 insertions(+), 5 deletions(-) diff --git a/tests/test_run/test_websocket_connect.py b/tests/test_run/test_websocket_connect.py index 4b845ab..c210ff2 100644 --- a/tests/test_run/test_websocket_connect.py +++ b/tests/test_run/test_websocket_connect.py @@ -484,3 +484,58 @@ async def fetch(): ) assert peak == 1 + + +# --------------------------------------------------------------------------- +# A failed prompt is raised even if the backend sends nothing more +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +class TestConnectWebsocketPromptFailureWhileIdle: + @pytest.mark.asyncio + async def test_prompt_failure_is_raised_while_waiting_for_a_message(self, capsys): + """The backend waits for the prompt's answer, so no further message will come.""" + s = _make_socket() + to_send = [_OPTIONS_PROMPT] + receive_cancelled = [] + + async def recv(): + if to_send: + await asyncio.sleep(0) + return to_send.pop(0) + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + receive_cancelled.append(True) + raise + + fake_socket = _FakeWSSocket(recv_side_effect=recv) + + with ( + _patch_connect(fake_socket), + patch("th_cli.test_run.websocket.handle_prompt", new=AsyncMock(side_effect=EOFError("stdin closed"))), + ): + with pytest.raises(EOFError): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + assert receive_cancelled == [True] + assert "Prompt handling failed" in capsys.readouterr().err + + @pytest.mark.asyncio + async def test_healthy_prompt_does_not_interrupt_receiving(self): + """No failure: messages keep being received and the run ends normally.""" + s = _make_socket() + fake_socket = _FakeWSSocket( + recv_side_effect=_yielding_recv([_OPTIONS_PROMPT, _LOG_RECORDS, _terminal_run_update(logs_complete=True)]) + ) + + with ( + _patch_connect(fake_socket), + patch("th_cli.test_run.websocket.handle_prompt", new=AsyncMock()), + patch("th_cli.test_run.websocket.logger") as mock_logger, + ): + await asyncio.wait_for(s.connect_websocket(), timeout=5) + + mock_logger.log.assert_any_call("INFO", "pairing logs") + assert fake_socket.recv.await_count == 3 diff --git a/th_cli/test_run/websocket.py b/th_cli/test_run/websocket.py index 1630d42..6e60c87 100644 --- a/th_cli/test_run/websocket.py +++ b/th_cli/test_run/websocket.py @@ -150,8 +150,10 @@ def __init__( self._prompt_tasks: dict[int, asyncio.Task] = {} # Every prompt reads from the same stdin, so only one is shown at a time. self._prompt_lock = asyncio.Lock() - # First exception raised by a prompt task, re-raised by the read loop. + # First exception raised by a prompt task, re-raised by the read loop. The + # event wakes the loop up even while it is waiting for the next message. self._prompt_error: BaseException | None = None + self._prompt_failed = asyncio.Event() # Track test step errors for logging # Key: (suite_index, case_index), Value: list of error strings from all steps self.test_case_step_errors: dict[tuple[int, int], list[str]] = {} @@ -194,6 +196,7 @@ async def connect_websocket(self) -> None: # once at the end so we still run the existing cleanup (socket.close(), # ConnectionClosed suppression) unchanged before deciding whether to raise. incomplete_closure = False + prompt_failure_waiter: asyncio.Task | None = None try: async with websocket_connect( WEBSOCKET_URL, @@ -203,10 +206,9 @@ async def connect_websocket(self) -> None: read_limit=WEBSOCKET_MAX_MESSAGE_SIZE, write_limit=WEBSOCKET_MAX_MESSAGE_SIZE, ) as socket: + prompt_failure_waiter = asyncio.ensure_future(self._prompt_failed.wait()) try: while True: - if self._prompt_error is not None: - raise self._prompt_error if self._run_finished and self._logs_complete is not None: # The backend sent the terminal update after the # run's last log records: nothing left to drain. @@ -216,9 +218,9 @@ async def connect_websocket(self) -> None: # Drain any trailing messages for a short grace # period instead of closing the instant the # terminal state update arrives. - message = await asyncio.wait_for(socket.recv(), timeout=DRAIN_TIMEOUT_S) + message = await self.__receive(socket, prompt_failure_waiter, timeout=DRAIN_TIMEOUT_S) else: - message = await socket.recv() + message = await self.__receive(socket, prompt_failure_waiter) except websockets.exceptions.ConnectionClosedOK: if not self._run_finished: # Connection closed cleanly, but before the run @@ -262,6 +264,8 @@ async def connect_websocket(self) -> None: if not self._run_finished: incomplete_closure = True finally: + if prompt_failure_waiter: + prompt_failure_waiter.cancel() if self._chip_server_watcher: self._chip_server_watcher.cancel() await self.__cancel_pending_prompts() @@ -275,6 +279,37 @@ async def connect_websocket(self) -> None: "results may be incomplete." ) + async def __receive( + self, socket: WebSocketClientProtocol, prompt_failure_waiter: asyncio.Future, timeout: float | None = None + ) -> str | bytes: + """Receive the next message, giving up as soon as a prompt task fails. + + Without this a failed prompt would only be raised once the backend sends + another message, which may never happen while it waits for the prompt's answer. + Cancelling recv() is safe: a message is never lost to it. + + Raises: + asyncio.TimeoutError: no message arrived within the timeout. + """ + if self._prompt_error is not None: + raise self._prompt_error + + receive_task = asyncio.ensure_future(socket.recv()) + try: + done, _ = await asyncio.wait( + {receive_task, prompt_failure_waiter}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED + ) + if prompt_failure_waiter in done and self._prompt_error is not None: + raise self._prompt_error + if receive_task not in done: + raise asyncio.TimeoutError() + return receive_task.result() + finally: + if not receive_task.done(): + receive_task.cancel() + elif not receive_task.cancelled(): + receive_task.exception() # Retrieved, so a dropped result is not reported as an error + async def __handle_incoming_socket_message(self, socket: WebSocketClientProtocol, message: SocketMessage) -> None: if isinstance(message.payload, TestUpdate): await self.__handle_test_update(update=message.payload) @@ -327,6 +362,7 @@ def __prompt_task_done(self, message_id: int, task: asyncio.Task) -> None: click.echo(colorize_error(f"Prompt handling failed: {error}"), err=True) if self._prompt_error is None: self._prompt_error = error + self._prompt_failed.set() def __cancel_prompt(self, message_id: int) -> None: task = self._prompt_tasks.get(message_id) From 6ba8cf27dc8b00bfd38acd4d6625462ad69dffe4 Mon Sep 17 00:00:00 2001 From: aamj Date: Wed, 25 Nov 2026 15:30:30 -0300 Subject: [PATCH 5/5] Wait for cancelled tasks to finish --- th_cli/test_run/websocket.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/th_cli/test_run/websocket.py b/th_cli/test_run/websocket.py index 6e60c87..2605f82 100644 --- a/th_cli/test_run/websocket.py +++ b/th_cli/test_run/websocket.py @@ -307,6 +307,8 @@ async def __receive( finally: if not receive_task.done(): receive_task.cancel() + # Let the cancelled receive unwind, so none is left running on the socket + await asyncio.gather(receive_task, return_exceptions=True) elif not receive_task.cancelled(): receive_task.exception() # Retrieved, so a dropped result is not reported as an error