Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion scripts/agent_gan_repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ def write(self, text: str) -> int:
return 0
with self._lock:
self.terminal.write(text)
if self.log.closed:
return len(text)
for part in text.splitlines(keepends=True):
if self._line_start:
self.log.write(f"[{self.timestamp_fn()}] ")
Expand All @@ -71,10 +73,13 @@ def write(self, text: str) -> int:
def flush(self) -> None:
with self._lock:
self.terminal.flush()
self.log.flush()
if not self.log.closed:
self.log.flush()

def log_only(self, event: str) -> None:
with self._lock:
if self.log.closed:
return
if not self._line_start:
self.log.write("\n")
self.log.write(f"[{self.timestamp_fn()}] {event.rstrip()}\n")
Expand All @@ -83,6 +88,10 @@ def log_only(self, event: str) -> None:

def close_log(self) -> None:
with self._lock:
if sys.stdout is self:
sys.stdout = self.terminal
if sys.stderr is self:
sys.stderr = self.terminal
if not self.log.closed:
self.log.flush()
self.log.close()
Expand Down
17 changes: 17 additions & 0 deletions tests/inference_engine/bridge/test_agent_gan_repl.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import io
import json
import signal
import sys
import time
from pathlib import Path

Expand Down Expand Up @@ -63,6 +64,22 @@ def test_timestamped_tee_preserves_terminal_and_flushes_log(tmp_path):
)


def test_timestamped_tee_shutdown_restores_streams_and_flush_is_safe(
tmp_path,
monkeypatch,
):
terminal = io.StringIO()
tee = TimestampedTee(terminal, tmp_path / "agent.log")
monkeypatch.setattr(sys, "stdout", tee)
monkeypatch.setattr(sys, "stderr", tee)
tee.close_log()
assert sys.stdout is terminal
assert sys.stderr is terminal
tee.flush()
tee.write("after-close")
assert terminal.getvalue() == "after-close"


def test_token_printer_streams_only_new_suffix(capsys):
printer = TokenPrinter(Tokenizer(), "generator")
printer([1])
Expand Down
Loading