fix(tui): handle closed pipes when flushing short --print answers (#8388)

* fix(tui): flush short headless answers before exiting

* test(tui): expose the broken-pipe exit status on regression
This commit is contained in:
paer 2026-11-21 10:34:47 +08:00 committed by GitHub
parent 477c8e04ec
commit ec2c881c6b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 23 additions and 7 deletions

View File

@ -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.

View File

@ -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

View File

@ -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):