codeplain 0.4.2.dev55__py3-none-any.whl → 0.4.2.dev56__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeplain
3
- Version: 0.4.2.dev55
3
+ Version: 0.4.2.dev56
4
4
  Summary: Transform plain language specifications into working code
5
5
  License-File: LICENSE
6
6
  Classifier: Environment :: Console
@@ -12,15 +12,15 @@ metadata_utils.py,sha256=YO17o7IAma5TT1ZN0pTwrLVr_KxFQ8APv02KqKPpI5k,1641
12
12
  module_renderer.py,sha256=OvIgAorSxGwrdTZcKy4hdmNgkdJGh6z6-VzzqrTlRHs,6966
13
13
  partial_rendering.py,sha256=7rQu0EE1H8JND-uePovdKfiQHGfdQncDyepwup7QBSY,15742
14
14
  path_resolution.py,sha256=0tMqU0a1g4DYhTOp7QjLVSEkv_cgasb4NI1mK809dUM,2233
15
- plain2code.py,sha256=_xlTyJ-6k03kwPLtYFvyjBctoFsdbIN1btwVnXiaVK0,23944
16
- plain2code_arguments.py,sha256=2Rgj-FquefqUjLQ4Kld7rc6fwW9SEW7wbb3aKo5H188,20624
15
+ plain2code.py,sha256=FgQNaT12xhyoojJfLcyzigJtwPQfX6PZEOSQWYsAInE,24026
16
+ plain2code_arguments.py,sha256=tP7OQK0JhccZC7d6PWLmIeXctp-FO48e0tGuJUDq8es,21133
17
17
  plain2code_console.py,sha256=YGBONkQtwZUkrjxTKhqcBoRzW0EmSfYHPH8P4_FM60I,6040
18
18
  plain2code_events.py,sha256=QnugBgO1baTe4kj2V3LUnkMDzhmksKwPDFuOKfH9g5o,1738
19
19
  plain2code_exceptions.py,sha256=zlszHIhaPWPN4fvYQibMIDM7f1xsW5J8sEWTOosIUGc,2068
20
20
  plain2code_logger.py,sha256=YQ-ENYBHKXROVv6Q52xh7eXrFkj_3Lex__N9zfxlw9Y,5729
21
21
  plain2code_nodes.py,sha256=QCC9RYBBfHycahvYovcN414sRlGL-dqRV3Baeu7KPkw,140
22
22
  plain2code_read_config.py,sha256=D5CxnmTRjddupecWvstcUm0kIJWWzq5-Zmk6sU0wbIg,2235
23
- plain2code_state.py,sha256=jIo4knKI99C1xkX1E_OaD3pdS9pczI2h9wofDjifMvE,3348
23
+ plain2code_state.py,sha256=Qai9kfsvQ2IYSQ31EyITkqCwlFm_rhO-sO12Y1CCOeA,3615
24
24
  plain2code_telemetry.py,sha256=NO8zw1i3ucM6Z9xQoSCeWqC5Hr-9Oql58YtgEOhBnaQ,4683
25
25
  plain2code_utils.py,sha256=luhiWaE0bXPQvjNDj-VYwxcGBq9vhvuqQCL_xgpq814,2093
26
26
  plain_file.py,sha256=50CevjRihjddXbc3WzKKJF_kaVcMHUJ1FH2HJUZawT8,138
@@ -82,6 +82,7 @@ tests/test_console_log_styles.py,sha256=sxlhynMAP-kmqhBn1-pKvZXdCnlKSyCGJqwYKrh6
82
82
  tests/test_dependency_pins.py,sha256=D_c5sb7ikwuV4zy8trB0DDzwNLkhAX221X67atLA-ec,1864
83
83
  tests/test_distill_conformance_test_memory.py,sha256=Tftw9l-gLVwIU6QttY03h2VedvuFxpIsCmZIzvWfxMA,5481
84
84
  tests/test_dry_run_link_validation.py,sha256=0Ca7v4DHMPBVmmBLWr2AHk4xVHzdOS2PHiPdumgpWkM,2154
85
+ tests/test_exit_when_done.py,sha256=eQeAjZaScqw93liajuYZ1XAIhZX-NpjWMeBXKSazedU,5594
85
86
  tests/test_file_utils.py,sha256=RPab1wBsbE7XAPGync56WveFVnRvafFVRia1a2mMQhk,4490
86
87
  tests/test_fix_unit_tests_action.py,sha256=sNLpg1T586TSPyvhjJcTe-4C9P8iHEkt8zx5z4MJ7po,11446
87
88
  tests/test_fix_unit_tests_conformance_context.py,sha256=G6-_YMhN5BY1sJ7cAx3BDnf_McgFcRpyP0iP6mwJ1eA,13154
@@ -101,14 +102,14 @@ tests/test_plain2code_state.py,sha256=O-sDt4F_lF6XtanWKWfh5IsNmDdfuJP_JoGagujzdf
101
102
  tests/test_plain2code_utils.py,sha256=MXAYsWMY_7Vb4im2ZJK46Gsq1ApIjuGkQAEmUz0ISOY,1665
102
103
  tests/test_plain_modules.py,sha256=fc7__5jSfr6CLh92IQDUdkOS9qkS1XRFmGXPj76v4Xs,33698
103
104
  tests/test_prepare_repositories_layout.py,sha256=PhJQLnHfjfjo6CTWoicyEKgL0_GtjwB2OKYAWSBVHtk,14638
104
- tests/test_render_finished_report.py,sha256=Z7FFQ1uiHkZubr4ElFq2KXEYT9niXVq1fSlehnJJwRE,7735
105
+ tests/test_render_finished_report.py,sha256=aL67ygPglfkOT3sbqlP9wOgG_sKgYdTBMOfVK7is5G8,9283
105
106
  tests/test_render_range.py,sha256=N4XS6zQbQmDlQmUvl6vhqLL7VcczET65GG1DWypP-k0,1832
106
107
  tests/test_render_stop_reason.py,sha256=jBofHzbEQFZlPcczT_7azsCnzh9hnEsLmxbB1IGhGxQ,8602
107
108
  tests/test_resolve_config_file.py,sha256=b87tDOvyzbsnE-QRWbZ97ou7NuyaAgskv-dbYBum31c,2830
108
109
  tests/test_script_path_resolution.py,sha256=tiEqMevQRXr9YpfHN0xldOOQpLAUgnSqTzeZWkKHaUY,4156
109
110
  tests/test_system_config.py,sha256=gH5qs9q4lh5CljAdz28HUrJzuKqCvkZherFuv7enMak,2787
110
111
  tests/test_telemetry.py,sha256=lRm-Z7g2-33CFEkTJHLSUsOpltSnD47gyUoPCRD9SHQ,8153
111
- tests/test_terminal_attachment.py,sha256=AnQzBI3IcxL3f7z_V4XzrzeihVJ1qWKj43Wh7Mue_pk,10503
112
+ tests/test_terminal_attachment.py,sha256=-yssQKLfE-PcOnBIoNJjjXISqjjZvePb74ZwW_TvJJ4,10533
112
113
  tests/test_tests_folders.py,sha256=o_6GMObbqweEDi1cfx6V8UFOGCafbUQcEVu_DSfW1Ns,3249
113
114
  tests/test_traceability_warnings.py,sha256=dqaDrzEaGgYFYdxkcJvdTjaLdP5qkl2YdIgTby7Uq9I,2304
114
115
  tests/test_tui_components.py,sha256=O_PB6z_Xt7YWebsD21b99PVgFtqq5c03lVtYytIT5Ps,6200
@@ -119,16 +120,16 @@ tests/e2e/conftest.py,sha256=5Dm67UTOE-M6hMb-mqZvwa6Ek_wmZgsR7fUv9ZEqCwY,4164
119
120
  tests/e2e/test_hello_world_python.py,sha256=2Cgs3-79dtQh5gVab257tFDHXTznefZeYqbTjlM4Nng,1632
120
121
  tests/e2e/test_hello_world_python_windows.py,sha256=ggynH_Wm4011M500zoPNNgvD-s4vZ3hvlorf1yARgQQ,2019
121
122
  tui/__init__.py,sha256=_fy7FowY0RkWdn4kC7XV2jgvQPCj-2gE8fNUb-Mny0A,60
122
- tui/components.py,sha256=tAgP7paI8bR6XAWOWyiUsKexRurEx1CNz_4z81Ty0G4,27195
123
+ tui/components.py,sha256=w3_MTFRqX_ZSFbFWHZbUQE9yZYcAK2qed0QB5ZH5E7c,27697
123
124
  tui/models.py,sha256=KMjlWubmPD41GA-BjgiqkaV9v7tLJ0fuWKBDPmZj4JA,1493
124
- tui/plain2code_tui.py,sha256=b6FOEXt_dcVhpfOrAHvg-Rvn0bSH18moy5zmUaz3NS4,17552
125
+ tui/plain2code_tui.py,sha256=vRHrB-9MWlttukvMCxv8UwrEjZJPLwD3FBcLMwhdFGY,18537
125
126
  tui/plain_module_render_choice_tui.py,sha256=dWmgpEEKlKijTDK-WQ3ks4EgZqICyQ73_BWDTASzEBk,12116
126
127
  tui/spinner.py,sha256=Ro6Gd9Przf-whuHqPRY6HwI0T57yJjyNPbhDbigZKZE,2471
127
128
  tui/state_handlers.py,sha256=5FkF13mCLYAOgpYnzR932U3tYxSnMkCu5jybMFEBVe4,16264
128
129
  tui/styles.css,sha256=kiC7Og_2G1E7owoiZgV95-3_dSeQnsNj3qzaY04xkDg,6727
129
130
  tui/widget_helpers.py,sha256=jitm2WHiKj-NVFL-hULxWzckPreRbUTl9OIZLN31-ek,6997
130
- codeplain-0.4.2.dev55.dist-info/METADATA,sha256=gPt3JPBUjG9z8ls8esd1nvxLHv9dEOOVSr9VlyeQ9ic,7260
131
- codeplain-0.4.2.dev55.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
132
- codeplain-0.4.2.dev55.dist-info/entry_points.txt,sha256=oDZkBqu9WhtZApb_K6ia8-fn9aojwmAsgnKELceX5T4,46
133
- codeplain-0.4.2.dev55.dist-info/licenses/LICENSE,sha256=pCeKgQ1mXE5OmNUuKOfOZh1T1vqkeCUxghE7N8qgnzc,11345
134
- codeplain-0.4.2.dev55.dist-info/RECORD,,
131
+ codeplain-0.4.2.dev56.dist-info/METADATA,sha256=BnoLF-7J-xvhTMDfm9DIMW7i-7vBQS7MsfmsBg8uQ2A,7260
132
+ codeplain-0.4.2.dev56.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
133
+ codeplain-0.4.2.dev56.dist-info/entry_points.txt,sha256=oDZkBqu9WhtZApb_K6ia8-fn9aojwmAsgnKELceX5T4,46
134
+ codeplain-0.4.2.dev56.dist-info/licenses/LICENSE,sha256=pCeKgQ1mXE5OmNUuKOfOZh1T1vqkeCUxghE7N8qgnzc,11345
135
+ codeplain-0.4.2.dev56.dist-info/RECORD,,
plain2code.py CHANGED
@@ -453,6 +453,7 @@ def render( # noqa: C901
453
453
  enter_pause_event=enter_pause_event,
454
454
  on_cancel=run_state.set_render_cancelled,
455
455
  default_log_level=default_log_level,
456
+ exit_when_done=args.exit_when_done,
456
457
  css_path="styles.css",
457
458
  )
458
459
  app.run()
@@ -591,7 +592,7 @@ def main(): # noqa: C901
591
592
  print_exit_summary(
592
593
  run_state,
593
594
  args.filename,
594
- error_message=error_message,
595
+ error_message=error_message or run_state.render_error_message,
595
596
  )
596
597
  # Remove any scratch extractions created for archive-only ("<module>.module") modules.
597
598
  for module in plain_module.all_required_modules + [plain_module]:
plain2code_arguments.py CHANGED
@@ -511,6 +511,17 @@ def create_parser():
511
511
  "Used automatically when stdin, stdout or stderr is not a terminal.",
512
512
  )
513
513
 
514
+ _add_arg(
515
+ parser,
516
+ "--exit-when-done",
517
+ action=argparse.BooleanOptionalAction,
518
+ default=False,
519
+ help="Close the terminal interface as soon as rendering stops, instead of keeping it open "
520
+ "until you press Enter. The render summary is printed to the terminal as usual. "
521
+ "Use --no-exit-when-done to keep the interface open when config.yaml turns this on. "
522
+ "Headless rendering always ends by itself, so the option changes nothing there.",
523
+ )
524
+
514
525
  parser.add_argument(
515
526
  "--status",
516
527
  action="store_true",
plain2code_state.py CHANGED
@@ -12,6 +12,8 @@ class RunState:
12
12
  self.replay: bool = replay_with is not None
13
13
  self.render_succeeded: bool = False
14
14
  self.render_cancelled: bool = False
15
+ # Why the render failed, as the TUI showed it; printed in the summary after the TUI closes.
16
+ self.render_error_message: Optional[str] = None
15
17
  self.render_generated_code_path: Optional[str] = None
16
18
  self.rendered_functionalities: int = 0
17
19
  if replay_with:
@@ -39,6 +41,9 @@ class RunState:
39
41
  def set_render_succeeded(self, succeeded: bool):
40
42
  self.render_succeeded = succeeded
41
43
 
44
+ def set_render_error_message(self, error_message: str):
45
+ self.render_error_message = error_message
46
+
42
47
  def set_render_cancelled(self):
43
48
  self.render_cancelled = True
44
49
 
@@ -0,0 +1,151 @@
1
+ """Tests for --exit-when-done: the TUI closes by itself once rendering has stopped."""
2
+
3
+ import asyncio
4
+ import threading
5
+
6
+ import pytest
7
+
8
+ from event_bus import EventBus
9
+ from plain2code_arguments import create_parser, parse_arguments
10
+ from plain2code_events import LogMessageEmitted, RenderCompleted, RenderFailed
11
+ from plain2code_state import RunState
12
+ from tui.plain2code_tui import Plain2CodeTUI
13
+
14
+
15
+ def _make_app(run_state: RunState, event_bus: EventBus, exit_when_done: bool, on_ready=lambda: None) -> Plain2CodeTUI:
16
+ return Plain2CodeTUI(
17
+ event_bus=event_bus,
18
+ run_state=run_state,
19
+ on_ready=on_ready,
20
+ render_id="test-render-id",
21
+ unittests_script=None,
22
+ conformance_tests_script=None,
23
+ prepare_environment_script=None,
24
+ state_machine_version="0.0.0",
25
+ exit_when_done=exit_when_done,
26
+ css_path="styles.css",
27
+ )
28
+
29
+
30
+ def _run(exit_when_done: bool, event) -> bool:
31
+ """Publish ``event`` to a mounted TUI and report whether the TUI closed itself."""
32
+
33
+ async def scenario() -> bool:
34
+ event_bus = EventBus()
35
+ run_state = RunState(spec_filename="x.plain")
36
+ app = _make_app(run_state, event_bus, exit_when_done)
37
+ async with app.run_test() as pilot:
38
+ event_bus.publish(event)
39
+ await pilot.pause()
40
+ return app._exit
41
+
42
+ return asyncio.run(scenario())
43
+
44
+
45
+ def test_tui_closes_itself_when_rendering_completes():
46
+ assert _run(True, RenderCompleted(rendered_code_path="plain_modules/x/")) is True
47
+
48
+
49
+ def test_tui_closes_itself_when_rendering_fails():
50
+ assert _run(True, RenderFailed(error_message="Conformance tests failed")) is True
51
+
52
+
53
+ def test_tui_keeps_the_failure_reason_for_the_summary():
54
+ """The TUI closes right away, so the reason it showed must survive on the run state."""
55
+
56
+ async def scenario() -> RunState:
57
+ event_bus = EventBus()
58
+ run_state = RunState(spec_filename="x.plain")
59
+ app = _make_app(run_state, event_bus, True)
60
+ async with app.run_test() as pilot:
61
+ event_bus.publish(RenderFailed(error_message="Conformance tests failed"))
62
+ await pilot.pause()
63
+ return run_state
64
+
65
+ assert asyncio.run(scenario()).render_error_message == "Conformance tests failed"
66
+
67
+
68
+ def test_tui_waits_for_the_user_without_the_option():
69
+ assert _run(False, RenderCompleted(rendered_code_path="plain_modules/x/")) is False
70
+ assert _run(False, RenderFailed(error_message="Conformance tests failed")) is False
71
+
72
+
73
+ def test_tui_closes_itself_when_the_render_thread_reports_completion():
74
+ """The render runs in its own thread, so the completion event reaches the TUI from there."""
75
+
76
+ async def scenario() -> bool:
77
+ event_bus = EventBus()
78
+ run_state = RunState(spec_filename="x.plain")
79
+ app = _make_app(run_state, event_bus, True)
80
+ async with app.run_test() as pilot:
81
+ thread = threading.Thread(
82
+ target=lambda: event_bus.publish(RenderCompleted(rendered_code_path="plain_modules/x/"))
83
+ )
84
+ thread.start()
85
+ thread.join()
86
+ await pilot.pause()
87
+ return app._exit
88
+
89
+ assert asyncio.run(scenario()) is True
90
+
91
+
92
+ def _log(message: str) -> LogMessageEmitted:
93
+ return LogMessageEmitted(logger_name="codeplain", level="INFO", message=message, timestamp="00:00:01")
94
+
95
+
96
+ @pytest.mark.parametrize(
97
+ "event", [RenderCompleted(rendered_code_path="plain_modules/x/"), RenderFailed(error_message="x")]
98
+ )
99
+ def test_tui_closes_cleanly_while_log_lines_are_still_arriving(event):
100
+ """Log lines reach the TUI from the render thread right up to (and past) the final event.
101
+
102
+ Entries still waiting to be drawn when the TUI closes must not crash it: before the fix,
103
+ mounting them into the torn-down log view raised MountError, which run_test re-raises.
104
+ """
105
+
106
+ async def scenario() -> bool:
107
+ event_bus = EventBus()
108
+ run_state = RunState(spec_filename="x.plain")
109
+
110
+ def render():
111
+ for i in range(20):
112
+ event_bus.publish(_log(f"step {i}"))
113
+ event_bus.publish(event)
114
+ for i in range(20):
115
+ event_bus.publish(_log(f"after {i}"))
116
+
117
+ # Started from on_ready, exactly as plain2code.render() starts the render thread.
118
+ render_thread = threading.Thread(target=render, daemon=True)
119
+ app = _make_app(run_state, event_bus, True, on_ready=render_thread.start)
120
+ async with app.run_test() as pilot:
121
+ for _ in range(100):
122
+ if app._exit and not render_thread.is_alive():
123
+ break
124
+ await pilot.pause(0.01)
125
+ return app._exit
126
+
127
+ assert asyncio.run(scenario()) is True
128
+
129
+
130
+ def test_option_is_off_by_default():
131
+ args = create_parser().parse_args(["x.plain"])
132
+ assert args.exit_when_done is False
133
+
134
+
135
+ def test_option_turns_on_from_the_command_line():
136
+ args = create_parser().parse_args(["x.plain", "--exit-when-done"])
137
+ assert args.exit_when_done is True
138
+
139
+
140
+ def test_option_turns_off_from_the_command_line():
141
+ args = create_parser().parse_args(["x.plain", "--no-exit-when-done"])
142
+ assert args.exit_when_done is False
143
+
144
+
145
+ def test_command_line_turns_off_an_exit_configured_in_config_yaml(tmp_path, monkeypatch):
146
+ (tmp_path / "x.plain").write_text("")
147
+ (tmp_path / "config.yaml").write_text("exit-when-done: true\n")
148
+ monkeypatch.chdir(tmp_path)
149
+
150
+ assert parse_arguments([str(tmp_path / "x.plain")]).exit_when_done is True
151
+ assert parse_arguments([str(tmp_path / "x.plain"), "--no-exit-when-done"]).exit_when_done is False
@@ -108,7 +108,7 @@ def make_args(api_key="test-key", headless=False):
108
108
  )
109
109
 
110
110
 
111
- def run_main(render_side_effect=None, api_key="test-key"):
111
+ def run_main(render_side_effect=None, api_key="test-key", print_exit_summary=None):
112
112
  """Drive main() with everything but the reporting path stubbed out.
113
113
 
114
114
  render() is replaced, so the stub is what decides how the render "ended" -
@@ -134,7 +134,7 @@ def run_main(render_side_effect=None, api_key="test-key"):
134
134
  patch("plain2code.setup_logging", return_value="INFO"),
135
135
  patch("plain2code.initialize_telemetry"),
136
136
  patch("plain2code.stop_narrating"),
137
- patch("plain2code.print_exit_summary"),
137
+ patch("plain2code.print_exit_summary", print_exit_summary or MagicMock()),
138
138
  patch("plain2code.dump_crash_logs"),
139
139
  patch("plain2code.capture_crash"),
140
140
  patch("plain2code.codeplain_api.CodeplainAPI", return_value=api),
@@ -204,3 +204,38 @@ class TestMainReportsEveryEnding:
204
204
  api = run_main(api_key=None)
205
205
 
206
206
  api.render_finished.assert_not_called()
207
+
208
+
209
+ class TestSummaryShowsWhyTheRenderFailed:
210
+ """A failure inside the render machine reaches main() only through the run state.
211
+
212
+ The state machine publishes RenderFailed without raising, so render() returns normally
213
+ and main() has no error of its own. The TUI keeps the reason on the run state; with
214
+ --exit-when-done the summary is the only place the user still sees it.
215
+ """
216
+
217
+ def test_the_reason_the_tui_kept_is_printed(self):
218
+ def fail_inside_the_render_machine(run_state):
219
+ run_state.set_render_succeeded(False)
220
+ run_state.set_render_error_message("Conformance tests still fail after 20 attempts.")
221
+
222
+ summary = MagicMock()
223
+ run_main(fail_inside_the_render_machine, print_exit_summary=summary)
224
+
225
+ assert summary.call_args.kwargs["error_message"] == "Conformance tests still fail after 20 attempts."
226
+
227
+ def test_a_raised_error_still_wins(self):
228
+ def fail(run_state):
229
+ run_state.set_render_error_message("reason the TUI kept")
230
+ raise Exception("rendering blew up")
231
+
232
+ summary = MagicMock()
233
+ run_main(fail, print_exit_summary=summary)
234
+
235
+ assert summary.call_args.kwargs["error_message"] == "rendering blew up"
236
+
237
+ def test_a_successful_render_has_no_error_message(self):
238
+ summary = MagicMock()
239
+ run_main(lambda run_state: run_state.set_render_succeeded(True), print_exit_summary=summary)
240
+
241
+ assert summary.call_args.kwargs["error_message"] is None
@@ -84,6 +84,7 @@ def make_args():
84
84
  render_from=None,
85
85
  force_render=False,
86
86
  headless=False,
87
+ exit_when_done=False,
87
88
  replay_with=None,
88
89
  job_tag=None,
89
90
  log_to_file=False,
tui/components.py CHANGED
@@ -624,12 +624,20 @@ class StructuredLogView(VerticalScroll):
624
624
  async def add_log(
625
625
  self, logger_name: str, level: str, message: str, timestamp: str = "", log_color: Optional[str] = None
626
626
  ):
627
- """Add a new log entry."""
627
+ """Add a new log entry.
628
+
629
+ Log entries are scheduled from the render thread, so one can still be pending when the
630
+ TUI closes (e.g. with --exit-when-done). Once the view is detached from the DOM the entry
631
+ is dropped instead of mounted, since mounting into a detached widget raises MountError.
632
+ The check runs right before each mount because the view can detach while awaiting.
633
+ """
628
634
  # Check if this is a success message that should have spacing before it
629
635
  is_success_message = any(keyword in message.lower() for keyword in LogEntry.SUCCESS_KEYWORDS)
630
636
 
631
637
  # Add empty line before success messages
632
638
  if is_success_message:
639
+ if not self.is_attached:
640
+ return
633
641
  spacer = Static("", classes="log-spacer")
634
642
  await self.mount(spacer)
635
643
 
@@ -639,6 +647,8 @@ class StructuredLogView(VerticalScroll):
639
647
  if not self._should_show_log(level):
640
648
  entry.display = False
641
649
 
650
+ if not self.is_attached:
651
+ return
642
652
  await self.mount(entry)
643
653
  # Auto-scroll to bottom to show latest logs
644
654
  self.scroll_end(animate=False)
tui/plain2code_tui.py CHANGED
@@ -84,6 +84,7 @@ class Plain2CodeTUI(App):
84
84
  enter_pause_event: threading.Event | None = None,
85
85
  on_cancel: Callable[[], None] | None = None,
86
86
  default_log_level: str = "INFO",
87
+ exit_when_done: bool = False,
87
88
  **kwargs,
88
89
  ):
89
90
  super().__init__(**kwargs)
@@ -104,6 +105,7 @@ class Plain2CodeTUI(App):
104
105
  self.enter_pause_event = enter_pause_event
105
106
  self._on_cancel = on_cancel
106
107
  self.default_log_level = default_log_level
108
+ self.exit_when_done = exit_when_done
107
109
  self._render_finished = False
108
110
 
109
111
  # Initialize state handlers
@@ -336,10 +338,14 @@ class Plain2CodeTUI(App):
336
338
  footer.update_footer_state("finished")
337
339
  except NoMatches:
338
340
  pass
341
+ self._exit_when_done()
339
342
 
340
343
  def on_render_failed(self, event: RenderFailed):
341
344
  """Handle render failure."""
342
345
  self._render_error_handler.handle(event.error_message)
346
+ # A failure inside the render machine is not raised, so main() has no error message of
347
+ # its own; keep the reason so the summary printed after the TUI closes can show it.
348
+ self.run_state.set_render_error_message(event.error_message)
343
349
  self._render_finished = True
344
350
  self._finalize_usage_summary()
345
351
  try:
@@ -347,6 +353,18 @@ class Plain2CodeTUI(App):
347
353
  footer.update_footer_state("finished")
348
354
  except NoMatches:
349
355
  pass
356
+ self._exit_when_done()
357
+
358
+ def _exit_when_done(self) -> None:
359
+ """Close the TUI once rendering has stopped, when --exit-when-done asked for it.
360
+
361
+ Both render outcomes are reported on the terminal after the TUI closes, so nothing
362
+ the user needs is lost. The events arrive on the render thread. The exit is queued
363
+ behind the log entries the render thread has already scheduled, so those are drawn
364
+ before the TUI starts shutting down; entries scheduled later are dropped by the log view.
365
+ """
366
+ if self.exit_when_done:
367
+ self.call_later(self.exit)
350
368
 
351
369
  async def action_copy_selection(self) -> None:
352
370
  """Handle ctrl+c: copy selected text if any.