From c12ac9164357b72dd998f30560de0a9b3dd615ee Mon Sep 17 00:00:00 2001 From: Jonathan Slenders Date: Fri, 4 Oct 2024 16:25:31 +0200 Subject: [PATCH] Handle InvalidStateError during termination when using `run_in_terminal`/`patch_stdout`. (#1926) In some edge cases, during cancellation, probably when using anyio, we can get this `InvalidStateError` during termination. This patch fixes that bug. ``` Traceback (most recent call last): File "/home/jonathan/git/python-prompt-toolkit/src/prompt_toolkit/application/run_in_terminal.py", line 49, in run async with in_terminal(render_cli_done=render_cli_done): File "/home/jonathan/.local/share/uv/python/cpython-3.11.10-linux-aarch64-gnu/lib/python3.11/contextlib.py", line 217, in __aexit__ await anext(self.gen) File "/home/jonathan/git/python-prompt-toolkit/src/prompt_toolkit/application/run_in_terminal.py", line 114, in in_terminal new_run_in_terminal_f.set_result(None) asyncio.exceptions.InvalidStateError: invalid state ``` --- src/prompt_toolkit/application/run_in_terminal.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/prompt_toolkit/application/run_in_terminal.py b/src/prompt_toolkit/application/run_in_terminal.py index 18a3dadeb..1f5e18ea7 100644 --- a/src/prompt_toolkit/application/run_in_terminal.py +++ b/src/prompt_toolkit/application/run_in_terminal.py @@ -111,4 +111,7 @@ async def f(): app._request_absolute_cursor_position() app._redraw() finally: - new_run_in_terminal_f.set_result(None) + # (Check for `.done()`, because it can be that this future was + # cancelled.) + if not new_run_in_terminal_f.done(): + new_run_in_terminal_f.set_result(None)