diff --git a/backend/docs/TUI.md b/backend/docs/TUI.md index 0fb33dbda9..3b35fc46f4 100644 --- a/backend/docs/TUI.md +++ b/backend/docs/TUI.md @@ -39,6 +39,9 @@ a bare flag (`deerflow summarize this repo --print`) are the message, as with both sides of the flag are rejected with exit 2, since their order cannot be recovered. `--print` and `--json` cannot be combined; pick one output mode. +If the program reading a `--print` pipe closes it before the answer is written, +DeerFlow exits quietly with status `1`. + If no TTY is available and no headless flag is given, `deerflow` prints guidance instead of hanging. diff --git a/backend/packages/harness/deerflow/tui/cli.py b/backend/packages/harness/deerflow/tui/cli.py index 0eccbbbb69..f3755b017a 100644 --- a/backend/packages/harness/deerflow/tui/cli.py +++ b/backend/packages/harness/deerflow/tui/cli.py @@ -290,8 +290,9 @@ def _silence_closed_stdout() -> None: the descriptor is pointed somewhere harmless first. """ try: - devnull = os.open(os.devnull, os.O_WRONLY) - os.dup2(devnull, sys.stdout.fileno()) + stdout_fd = sys.stdout.fileno() + with open(os.devnull, "wb") as devnull: + os.dup2(devnull.fileno(), stdout_fd) except (OSError, ValueError): pass @@ -358,7 +359,7 @@ def _run_print(plan: LaunchPlan) -> int: print(f"Error: {_error_text(exc)}", file=sys.stderr) return 1 try: - print(outcome.answer()) + print(outcome.answer(), flush=True) except BrokenPipeError: _silence_closed_stdout() return 1 diff --git a/backend/tests/test_tui_cli_main.py b/backend/tests/test_tui_cli_main.py index ff7336f08f..ca3b44102a 100644 --- a/backend/tests/test_tui_cli_main.py +++ b/backend/tests/test_tui_cli_main.py @@ -1,6 +1,8 @@ """Integration tests for ``main`` dispatch (headless paths), with a fake session.""" import json +import os +from contextlib import suppress from types import SimpleNamespace import pytest @@ -186,11 +188,21 @@ class _BrokenStdout: raise OSError # forces the devnull dup2 to take its best-effort path -def test_main_print_broken_pipe_exits_without_traceback(monkeypatch): +def test_main_print_broken_pipe_exits_without_traceback(monkeypatch, capsys): monkeypatch.setattr(cli, "_make_session", _FakeSession) - monkeypatch.setattr(cli.sys, "stdout", _BrokenStdout()) - rc = cli.main(["--print", "hello"]) - assert rc == 1 + read_fd, write_fd = os.pipe() + os.close(read_fd) + stdout = os.fdopen(write_fd, "w", encoding="utf-8") + try: + monkeypatch.setattr(cli.sys, "stdout", stdout) + rc = cli.main(["--print", "hello"]) + assert rc == 1 + stdout.flush() # Repeat the flush Python performs at shutdown. + finally: + # A close-time flush must not mask a failed assertion above. + with suppress(BrokenPipeError): + stdout.close() + assert capsys.readouterr().err == "" def test_main_json_broken_pipe_error_record_fails_silently(monkeypatch):