Skip to content

Commit 06f325a

Browse files
Flush window title updates on the prompt event loop
1 parent 07495f8 commit 06f325a

4 files changed

Lines changed: 115 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
- Bug Fixes
44
- Fixed `@with_annotated` command `--help` output bypassing the application's output stream,
55
leaving redirected help files empty and preventing help from being captured by embedded apps.
6+
- Fixed `set_window_title()` leaving title changes buffered until the next prompt render.
7+
Updates during a running prompt are sent through its event loop to avoid concurrent writes
8+
from background threads.
69

710
## 4.3.0 (October 13, 2026)
811

‎cmd2/cmd2.py‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171
filters,
7272
print_formatted_text,
7373
)
74-
from prompt_toolkit.application import create_app_session, get_app
74+
from prompt_toolkit.application import create_app_session, get_app, get_app_or_none, get_app_session
7575
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
7676
from prompt_toolkit.completion import Completer, DummyCompleter
7777
from prompt_toolkit.formatted_text import ANSI, AnyFormattedText
@@ -84,7 +84,7 @@
8484
from prompt_toolkit.layout.containers import ConditionalContainer, FloatContainer
8585
from prompt_toolkit.output import DummyOutput, create_output
8686
from prompt_toolkit.patch_stdout import patch_stdout
87-
from prompt_toolkit.shortcuts import CompleteStyle, PromptSession, choice, set_title
87+
from prompt_toolkit.shortcuts import CompleteStyle, PromptSession, choice
8888
from prompt_toolkit.styles import DynamicStyle
8989
from rich.console import (
9090
Group,
@@ -5862,12 +5862,35 @@ def add_alert(
58625862
self._alert_condition.notify_all()
58635863

58645864
@staticmethod
5865-
def set_window_title(title: str) -> None: # pragma: no cover
5865+
def set_window_title(title: str) -> None:
58665866
"""Set the terminal window title.
58675867
5868+
When a prompt-toolkit application is running, update the title on its event loop
5869+
to avoid writing to its output buffer from a background thread.
5870+
Calls use the current prompt-toolkit app session. Worker threads serving a custom
5871+
app session must inherit that session's context.
5872+
58685873
:param title: the new window title
58695874
"""
5870-
set_title(title)
5875+
output = get_app_session().output
5876+
5877+
def set_title_and_flush() -> None:
5878+
output.set_title(title)
5879+
output.flush()
5880+
5881+
app = get_app_or_none()
5882+
loop = app.loop if app is not None else None
5883+
if loop is not None and loop.is_running():
5884+
try:
5885+
loop.call_soon_threadsafe(set_title_and_flush)
5886+
except RuntimeError:
5887+
# The application can finish and close its loop between the check and scheduling.
5888+
if not loop.is_closed():
5889+
raise
5890+
else:
5891+
return
5892+
5893+
set_title_and_flush()
58715894

58725895
def enable_command(self, command: str) -> None:
58735896
"""Enable a command by restoring its functions.

‎docs/features/prompt.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ Alerts can interact with the CLI in two ways:
5454

5555
- [cmd2.Cmd.set_window_title][]
5656

57+
Title changes are flushed without waiting for the next prompt. When a prompt-toolkit application is
58+
running, the update is scheduled on its event loop so background threads can change the title
59+
without writing to the prompt's output buffer directly.
60+
61+
Calls use the current prompt-toolkit app session. If you create a custom session, pass its context
62+
to worker threads, for example with `contextvars.copy_context().run`.
63+
5764
The easiest way to understand these functions is to see the
5865
[async_printing.py](https://github.com/python-cmd2/cmd2/blob/main/examples/async_printing.py)
5966
example for a demonstration.

‎tests/test_cmd2.py‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Cmd2 unit/functional testing"""
22

33
import contextlib
4+
import contextvars
45
import io
56
import os
67
import signal
@@ -17,11 +18,13 @@
1718
from unittest import mock
1819

1920
import pytest
20-
from prompt_toolkit.application import create_app_session, get_app
21+
from prompt_toolkit.application import Application, create_app_session, get_app
2122
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
2223
from prompt_toolkit.completion import DummyCompleter
24+
from prompt_toolkit.data_structures import Size
2325
from prompt_toolkit.input import DummyInput, create_pipe_input
2426
from prompt_toolkit.output import DummyOutput
27+
from prompt_toolkit.output.vt100 import Vt100_Output
2528
from prompt_toolkit.shortcuts import CompleteStyle, PromptSession
2629
from rich.style import Style
2730
from rich.text import Text
@@ -4965,6 +4968,80 @@ def get_rprompt(self):
49654968
assert True not in drawn_while_done, "the right prompt was drawn into the committed final frame"
49664969

49674970

4971+
def test_set_window_title_is_flushed_during_a_command() -> None:
4972+
stream = io.StringIO()
4973+
output = Vt100_Output(stream, lambda: Size(rows=24, columns=80), enable_cpr=False)
4974+
observed = []
4975+
4976+
class TitleApp(cmd2.Cmd):
4977+
def do_work(self, _statement):
4978+
self.set_window_title("Working…")
4979+
observed.append(stream.getvalue())
4980+
4981+
with create_app_session(input=DummyInput(), output=output):
4982+
app = TitleApp(allow_cli_args=False)
4983+
app.onecmd_plus_hooks("work")
4984+
4985+
assert observed == ["\x1b]2;Working…\x07"]
4986+
4987+
4988+
@pytest.mark.parametrize("from_worker", [False, True])
4989+
def test_set_window_title_while_a_prompt_is_running(from_worker) -> None:
4990+
stream = io.StringIO()
4991+
title_threads = []
4992+
observed = []
4993+
workers = []
4994+
loop_thread = threading.get_ident()
4995+
4996+
class TitleOutput(Vt100_Output):
4997+
def set_title(self, title):
4998+
title_threads.append(threading.get_ident())
4999+
super().set_title(title)
5000+
5001+
output = TitleOutput(stream, lambda: Size(rows=24, columns=80), enable_cpr=False)
5002+
with create_pipe_input() as pipe_input, create_app_session(input=pipe_input, output=output):
5003+
app = Application(input=pipe_input, output=output)
5004+
sent = False
5005+
5006+
def check_title():
5007+
# Observe before exiting, because the final render also flushes output.
5008+
observed.append("\x1b]2;Working…\x07" in stream.getvalue())
5009+
app.exit()
5010+
5011+
def update_title():
5012+
cmd2.Cmd.set_window_title("Working…")
5013+
app.loop.call_soon_threadsafe(check_title)
5014+
5015+
def after_render(_sender):
5016+
nonlocal sent
5017+
if sent:
5018+
return
5019+
sent = True
5020+
# Start after the first frame, so its flush cannot hide a buffered title.
5021+
if from_worker:
5022+
context = contextvars.copy_context()
5023+
worker = threading.Thread(target=context.run, args=(update_title,), daemon=True)
5024+
workers.append(worker)
5025+
worker.start()
5026+
else:
5027+
update_title()
5028+
5029+
app.after_render += after_render
5030+
app.run(pre_run=lambda: app.loop.call_later(5, app.exit), set_exception_handler=False)
5031+
5032+
for worker in workers:
5033+
worker.join(timeout=5)
5034+
assert not worker.is_alive()
5035+
5036+
assert observed == [True]
5037+
assert title_threads == [loop_thread]
5038+
5039+
5040+
def test_set_window_title_without_a_terminal() -> None:
5041+
with create_app_session(input=DummyInput(), output=DummyOutput()):
5042+
cmd2.Cmd.set_window_title("Working…")
5043+
5044+
49685045
def test_get_bottom_toolbar(base_app: cmd2.Cmd) -> None:
49695046
assert base_app.get_bottom_toolbar() is None
49705047

0 commit comments

Comments
 (0)