logbar 0.4.2__tar.gz → 0.4.4__tar.gz

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.
Files changed (44) hide show
  1. {logbar-0.4.2 → logbar-0.4.4}/LogBar.egg-info/PKG-INFO +1 -1
  2. {logbar-0.4.2 → logbar-0.4.4}/LogBar.egg-info/SOURCES.txt +1 -0
  3. {logbar-0.4.2 → logbar-0.4.4}/PKG-INFO +1 -1
  4. {logbar-0.4.2 → logbar-0.4.4}/logbar/logbar.py +65 -0
  5. {logbar-0.4.2 → logbar-0.4.4}/logbar/progress.py +21 -0
  6. {logbar-0.4.2 → logbar-0.4.4}/logbar/terminal.py +133 -7
  7. {logbar-0.4.2 → logbar-0.4.4}/pyproject.toml +1 -1
  8. logbar-0.4.4/tests/test_headless.py +212 -0
  9. {logbar-0.4.2 → logbar-0.4.4}/LICENSE +0 -0
  10. {logbar-0.4.2 → logbar-0.4.4}/LogBar.egg-info/dependency_links.txt +0 -0
  11. {logbar-0.4.2 → logbar-0.4.4}/LogBar.egg-info/top_level.txt +0 -0
  12. {logbar-0.4.2 → logbar-0.4.4}/README.md +0 -0
  13. {logbar-0.4.2 → logbar-0.4.4}/logbar/__init__.py +0 -0
  14. {logbar-0.4.2 → logbar-0.4.4}/logbar/buffer.py +0 -0
  15. {logbar-0.4.2 → logbar-0.4.4}/logbar/columns.py +0 -0
  16. {logbar-0.4.2 → logbar-0.4.4}/logbar/coordinator.py +0 -0
  17. {logbar-0.4.2 → logbar-0.4.4}/logbar/drawing.py +0 -0
  18. {logbar-0.4.2 → logbar-0.4.4}/logbar/frame.py +0 -0
  19. {logbar-0.4.2 → logbar-0.4.4}/logbar/layout.py +0 -0
  20. {logbar-0.4.2 → logbar-0.4.4}/logbar/region.py +0 -0
  21. {logbar-0.4.2 → logbar-0.4.4}/logbar/region_logger.py +0 -0
  22. {logbar-0.4.2 → logbar-0.4.4}/logbar/region_progress.py +0 -0
  23. {logbar-0.4.2 → logbar-0.4.4}/logbar/screen.py +0 -0
  24. {logbar-0.4.2 → logbar-0.4.4}/logbar/screen_backend.py +0 -0
  25. {logbar-0.4.2 → logbar-0.4.4}/logbar/session.py +0 -0
  26. {logbar-0.4.2 → logbar-0.4.4}/logbar/util.py +0 -0
  27. {logbar-0.4.2 → logbar-0.4.4}/setup.cfg +0 -0
  28. {logbar-0.4.2 → logbar-0.4.4}/tests/test_columns.py +0 -0
  29. {logbar-0.4.2 → logbar-0.4.4}/tests/test_coordinator.py +0 -0
  30. {logbar-0.4.2 → logbar-0.4.4}/tests/test_drawing.py +0 -0
  31. {logbar-0.4.2 → logbar-0.4.4}/tests/test_example.py +0 -0
  32. {logbar-0.4.2 → logbar-0.4.4}/tests/test_frame.py +0 -0
  33. {logbar-0.4.2 → logbar-0.4.4}/tests/test_layout.py +0 -0
  34. {logbar-0.4.2 → logbar-0.4.4}/tests/test_log.py +0 -0
  35. {logbar-0.4.2 → logbar-0.4.4}/tests/test_progress.py +0 -0
  36. {logbar-0.4.2 → logbar-0.4.4}/tests/test_progress_stack.py +0 -0
  37. {logbar-0.4.2 → logbar-0.4.4}/tests/test_region.py +0 -0
  38. {logbar-0.4.2 → logbar-0.4.4}/tests/test_region_logger.py +0 -0
  39. {logbar-0.4.2 → logbar-0.4.4}/tests/test_region_progress.py +0 -0
  40. {logbar-0.4.2 → logbar-0.4.4}/tests/test_screen.py +0 -0
  41. {logbar-0.4.2 → logbar-0.4.4}/tests/test_session.py +0 -0
  42. {logbar-0.4.2 → logbar-0.4.4}/tests/test_snake_render.py +0 -0
  43. {logbar-0.4.2 → logbar-0.4.4}/tests/test_terminal.py +0 -0
  44. {logbar-0.4.2 → logbar-0.4.4}/tests/test_thread_safety.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: LogBar
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: A unified Logger and ProgressBar util with zero dependencies.
5
5
  Author-email: ModelCloud <qubitium@modelcloud.ai>
6
6
  License-Expression: Apache-2.0
@@ -27,6 +27,7 @@ tests/test_coordinator.py
27
27
  tests/test_drawing.py
28
28
  tests/test_example.py
29
29
  tests/test_frame.py
30
+ tests/test_headless.py
30
31
  tests/test_layout.py
31
32
  tests/test_log.py
32
33
  tests/test_progress.py
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: LogBar
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: A unified Logger and ProgressBar util with zero dependencies.
5
5
  Author-email: ModelCloud <qubitium@modelcloud.ai>
6
6
  License-Expression: Apache-2.0
@@ -28,6 +28,8 @@ last_rendered_length = 0
28
28
  _STATE_LOCK = threading.RLock()
29
29
  _RENDER_LOCK = threading.RLock()
30
30
  _EXTERNAL_TERMINAL_HANDOFF_HOOKS_INSTALLED = False
31
+ _HEADLESS_LOG_EMITTED = False
32
+ _HEADLESS_LOG_LOCK = threading.RLock()
31
33
 
32
34
  def _stdout_stream():
33
35
  """Return the stdout stream wrapper used by all renderer writes."""
@@ -115,6 +117,38 @@ def _running_in_notebook_environment() -> bool:
115
117
  return shell_name == "ZMQInteractiveShell"
116
118
 
117
119
 
120
+ def _log_headless_state_once(backend_state: Optional[RenderBackendState] = None) -> None:
121
+ """Emit a single INFO log when LogBar is running in a headless environment."""
122
+
123
+ global _HEADLESS_LOG_EMITTED, logger
124
+
125
+ with _HEADLESS_LOG_LOCK:
126
+ if _HEADLESS_LOG_EMITTED:
127
+ return
128
+ _HEADLESS_LOG_EMITTED = True
129
+
130
+ if backend_state is None:
131
+ try:
132
+ backend_state = _current_render_backend_state()
133
+ except Exception:
134
+ return
135
+
136
+ if not backend_state.headless:
137
+ return
138
+
139
+ log = logger
140
+ if log is None:
141
+ try:
142
+ log = LogBar.shared()
143
+ except Exception:
144
+ return
145
+
146
+ log.info(
147
+ "LogBar: headless/AI-agent/notebook/CI environment detected; "
148
+ "high-frequency progress bars and animations are disabled."
149
+ )
150
+
151
+
118
152
  def _stdout_supports_cursor_movement() -> bool:
119
153
  """Best-effort check for cursor positioning support on stdout."""
120
154
 
@@ -489,6 +523,18 @@ def _clear_progress_stack_locked(
489
523
  coordinator_state = _coordinator_state()
490
524
  count = coordinator_state._last_drawn_progress_count
491
525
  state = backend_state or _current_render_backend_state()
526
+
527
+ if state.headless:
528
+ coordinator_state._last_drawn_progress_count = 0
529
+ coordinator_state._last_rendered_terminal_size = None
530
+ coordinator_state._last_rendered_progress_lines = []
531
+ coordinator_state._cursor_positioned_above_stack = False
532
+ coordinator_state._cursor_positioned_on_stack_top = False
533
+ coordinator_state._stack_redraw_invalidated = False
534
+ if flush_deferred_logs and not for_log_output:
535
+ _flush_deferred_logs_locked()
536
+ return
537
+
492
538
  supports_cursor = state.supports_cursor
493
539
 
494
540
  if not supports_cursor:
@@ -844,6 +890,14 @@ def _render_progress_stack_locked(
844
890
 
845
891
  coordinator_state = _coordinator_state()
846
892
  state = backend_state or _current_render_backend_state(columns_hint)
893
+
894
+ if state.headless:
895
+ bars = _active_progress_bars()
896
+ with _STATE_LOCK:
897
+ coordinator_state._dirty_progress_bars.difference_update(bars)
898
+ _record_progress_activity_locked()
899
+ return
900
+
847
901
  columns = state.columns
848
902
  rows = state.lines
849
903
 
@@ -1089,6 +1143,9 @@ def _record_progress_activity() -> None:
1089
1143
  def _should_refresh_in_background(state: RenderBackendState, bars: Sequence["ProgressBar"]) -> bool:
1090
1144
  """Return whether the background worker should wake for current bars."""
1091
1145
 
1146
+ if state.headless:
1147
+ return False
1148
+
1092
1149
  if state.supports_cursor or state.notebook:
1093
1150
  return True
1094
1151
 
@@ -1168,6 +1225,12 @@ def _progress_refresh_worker() -> None:
1168
1225
  def _ensure_background_refresh_thread() -> None:
1169
1226
  """Start the shared renderer refresh worker exactly once."""
1170
1227
 
1228
+ try:
1229
+ if _current_render_backend_state().headless:
1230
+ return
1231
+ except Exception:
1232
+ pass
1233
+
1171
1234
  with _STATE_LOCK:
1172
1235
  state = _coordinator_state()
1173
1236
  if state._refresh_thread is not None and state._refresh_thread.is_alive():
@@ -1287,6 +1350,8 @@ class LogBar(logging.Logger):
1287
1350
 
1288
1351
  _ensure_background_refresh_thread()
1289
1352
 
1353
+ _log_headless_state_once()
1354
+
1290
1355
  return shared_logger
1291
1356
 
1292
1357
 
@@ -25,6 +25,7 @@ from .logbar import (
25
25
  mark_progress_bar_dirty,
26
26
  render_lock,
27
27
  render_progress_stack,
28
+ _log_headless_state_once,
28
29
  )
29
30
  if TYPE_CHECKING: # pragma: no cover - type hints without runtime import cycle
30
31
  from .logbar import LogBar as LogBarType
@@ -496,6 +497,18 @@ class ProgressBar:
496
497
  )
497
498
  self._last_output_step: Optional[int] = None
498
499
 
500
+ # Auto-detect headless/AI-agent/notebook/CI environments and suppress
501
+ # high-frequency redraws so logs do not get polluted with terminal
502
+ # control sequences in remote or non-interactive shells.
503
+ _backend_state = render_backend_state(
504
+ stream=sys.stdout,
505
+ size_provider=terminal_size,
506
+ notebook=_running_in_notebook_environment(),
507
+ )
508
+ self._headless = _backend_state.headless
509
+ if self._headless:
510
+ _log_headless_state_once(_backend_state)
511
+
499
512
  self.ui_show_left_steps = True # show [1 of 100] on left side
500
513
  self.ui_show_left_steps_offset = 0
501
514
 
@@ -808,6 +821,9 @@ class ProgressBar:
808
821
  if self._attached:
809
822
  return self
810
823
 
824
+ if self._headless:
825
+ return self
826
+
811
827
  target_logger = logger or self._owner_logger or LogBar.shared()
812
828
  self._attached_logger = target_logger
813
829
  self._owner_logger = target_logger
@@ -934,6 +950,9 @@ class ProgressBar:
934
950
  def draw(self, force: bool = False):
935
951
  """Render the current progress state either inline or in the stack."""
936
952
 
953
+ if self._headless:
954
+ return
955
+
937
956
  # Even skipped draws count as activity. This prevents the background
938
957
  # refresher from redrawing the same bar immediately and undoing the
939
958
  # throttle when progress is advancing quickly.
@@ -1209,6 +1228,8 @@ class ProgressBar:
1209
1228
  state = self._render_backend_state(backend_state)
1210
1229
  except Exception:
1211
1230
  return False
1231
+ if state.headless:
1232
+ return False
1212
1233
  if style_enabled is None:
1213
1234
  style_enabled = state.supports_styling
1214
1235
  return bool(style_enabled) and (state.supports_cursor or state.notebook)
@@ -25,6 +25,7 @@ class RenderBackendState:
25
25
  supports_cursor: bool
26
26
  supports_ansi: bool
27
27
  supports_styling: bool
28
+ headless: bool = False
28
29
 
29
30
 
30
31
  def _stream_terminal_size(stream: Optional[object], fallback: tuple[int, int]) -> Optional[tuple[int, int]]:
@@ -91,6 +92,127 @@ def terminal_size(fallback=(80, 24), stream: Optional[object] = None):
91
92
  return (columns, lines)
92
93
 
93
94
 
95
+ # Environment markers used by AI-agent, remote, or non-interactive runtimes.
96
+ # A match on its own is enough to disable animated/redrawing UI in LogBar.
97
+ _HEADLESS_ENV_VARS = frozenset(
98
+ [
99
+ "CI",
100
+ "CI_NAME",
101
+ "BUILD_ID",
102
+ "BUILDKITE",
103
+ "TEAMCITY_VERSION",
104
+ "TF_BUILD",
105
+ "JENKINS_URL",
106
+ "CIRCLECI",
107
+ "TRAVIS",
108
+ "GITHUB_ACTIONS",
109
+ "GITLAB_CI",
110
+ "AGENT",
111
+ "AI_AGENT",
112
+ "AGENT_ID",
113
+ "SMITHERY",
114
+ "AIDER",
115
+ "CODEX_HOME",
116
+ "CODEX_SQLITE_HOME",
117
+ "CODEX_API_KEY",
118
+ "CODEX_ACCESS_TOKEN",
119
+ "CODEX_NON_INTERACTIVE",
120
+ "DEVIN_OUTPOST_SESSION_ID",
121
+ "DEVIN_OUTPOST_CONNECT_TOKEN",
122
+ "DEVIN_OUTPOST_GATEWAY_URL",
123
+ "DEVIN_REMOTE_AUTH_TOKEN",
124
+ "DEVIN_REMOTE_STATE_DIR",
125
+ "DEVIN_PTY_BRIDGE_PORT",
126
+ "JPY_PARENT_PID",
127
+ "IPYKERNEL_PARENT_PID",
128
+ "JUPYTER_SERVER_URI",
129
+ "KAGGLE_KERNEL_RUN_TYPE",
130
+ "COLAB_GPU",
131
+ "COLAB_BACKEND_VERSION",
132
+ ]
133
+ )
134
+
135
+ # Environment variable name prefixes that strongly indicate an AI-agent shell.
136
+ _HEADLESS_ENV_PREFIXES = (
137
+ "DEVIN_",
138
+ "CODEX_",
139
+ "SMITHERY_",
140
+ "AIDER_",
141
+ "CLAUDE_",
142
+ "ANTHROPIC_",
143
+ "COPILOT_",
144
+ "__COG_",
145
+ )
146
+
147
+
148
+ def _is_stream_tty(stream: Optional[object]) -> bool:
149
+ """Best-effort check whether ``stream`` is connected to a real terminal."""
150
+
151
+ target = stream if stream is not None else sys.stdout
152
+ isatty = getattr(target, "isatty", None)
153
+ if not callable(isatty):
154
+ return False
155
+ try:
156
+ return bool(isatty())
157
+ except Exception:
158
+ return False
159
+
160
+
161
+ def _env_flag_enabled(name: str) -> bool:
162
+ """Return True when ``name`` is set to a non-empty, non-disabling value."""
163
+
164
+ value = str(os.environ.get(name, "")).strip().lower()
165
+ return value not in {"", "0", "false", "off", "no"}
166
+
167
+
168
+ # xdist worker markers are set before test modules are imported; cache the flag
169
+ # at import time so tests that patch ``os.environ`` still detect pytest correctly.
170
+ _PYTEST_XDIST_WORKER = bool(os.environ.get("PYTEST_XDIST_WORKER"))
171
+
172
+
173
+ def _running_under_pytest() -> bool:
174
+ """Best-effort detection for pytest-driven terminal sessions."""
175
+
176
+ if _PYTEST_XDIST_WORKER:
177
+ return True
178
+
179
+ argv0 = str(sys.argv[0]).lower() if sys.argv else ""
180
+ return "PYTEST_CURRENT_TEST" in os.environ or "pytest" in argv0
181
+
182
+
183
+ def _is_headless_environment(*, notebook: bool = False) -> bool:
184
+ """Detect non-interactive, AI-agent, notebook, or CI environments.
185
+
186
+ Headless detection is intentionally disabled while LogBar is running under
187
+ pytest so that the test suite can continue to assert against rendered
188
+ output. Callers can force redrawing with ``LOGBAR_FORCE_PROGRESS=1`` or
189
+ disable this heuristic with ``LOGBAR_DISABLE_HEADLESS_DETECTION=1``.
190
+ """
191
+
192
+ if _env_flag_enabled("LOGBAR_FORCE_PROGRESS"):
193
+ return False
194
+
195
+ if _env_flag_enabled("LOGBAR_DISABLE_HEADLESS_DETECTION"):
196
+ return False
197
+
198
+ # Do not disable the UI while the test suite is driving it.
199
+ if _running_under_pytest():
200
+ return False
201
+
202
+ if notebook:
203
+ return True
204
+
205
+ env_vars = os.environ
206
+ for key in env_vars:
207
+ if key in _HEADLESS_ENV_VARS or key.startswith(_HEADLESS_ENV_PREFIXES):
208
+ return True
209
+
210
+ if os.environ.get("TERM", "").strip().lower() == "dumb":
211
+ return True
212
+
213
+ return False
214
+
215
+
94
216
  def render_backend_state(
95
217
  *,
96
218
  stream: Optional[object] = None,
@@ -104,13 +226,7 @@ def render_backend_state(
104
226
  provider = size_provider or (lambda: terminal_size(fallback=fallback, stream=target))
105
227
  columns, lines = provider()
106
228
 
107
- is_tty = False
108
- isatty = getattr(target, "isatty", None)
109
- if callable(isatty):
110
- try:
111
- is_tty = bool(isatty())
112
- except Exception:
113
- is_tty = False
229
+ is_tty = _is_stream_tty(target)
114
230
 
115
231
  term_value = str(os.environ.get("TERM", "")).strip().lower()
116
232
  force_cursor = bool(os.environ.get("LOGBAR_FORCE_TERMINAL_CURSOR", "").strip())
@@ -138,6 +254,15 @@ def render_backend_state(
138
254
  if not disable_styling:
139
255
  supports_styling = notebook or force_ansi or is_tty
140
256
 
257
+ headless = _is_headless_environment(notebook=notebook)
258
+
259
+ # A headless backend should never claim cursor/ANSI support; the flag is
260
+ # the canonical signal used by the rest of the renderer to suppress draws.
261
+ if headless:
262
+ supports_cursor = False
263
+ supports_ansi = False
264
+ supports_styling = False
265
+
141
266
  return RenderBackendState(
142
267
  columns=max(0, int(columns)),
143
268
  lines=max(0, int(lines)),
@@ -146,4 +271,5 @@ def render_backend_state(
146
271
  supports_cursor=supports_cursor,
147
272
  supports_ansi=supports_ansi,
148
273
  supports_styling=supports_styling,
274
+ headless=headless,
149
275
  )
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "LogBar"
7
- version = "0.4.2"
7
+ version = "0.4.4"
8
8
  description = "A unified Logger and ProgressBar util with zero dependencies."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3"
@@ -0,0 +1,212 @@
1
+ # SPDX-FileCopyrightText: 2024-2025 ModelCloud.ai
2
+ # SPDX-FileCopyrightText: 2024-2025 qubitium@modelcloud.ai
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ # Contact: qubitium@modelcloud.ai, x.com/qubitium
5
+
6
+ """Tests for headless / AI-agent / notebook auto-detection."""
7
+
8
+ import os
9
+ import subprocess
10
+ import sys
11
+ import unittest
12
+ from pathlib import Path
13
+ from unittest.mock import patch
14
+
15
+ from logbar.terminal import (
16
+ _is_headless_environment,
17
+ render_backend_state,
18
+ )
19
+
20
+ REPO_ROOT = Path(__file__).resolve().parents[1]
21
+
22
+
23
+ class TestHeadlessDetection(unittest.TestCase):
24
+ """Unit coverage for the environment-based headless detector."""
25
+
26
+ def setUp(self):
27
+ """Expose the detector to the test process by faking non-pytest mode."""
28
+
29
+ self._headless_patch = patch("logbar.terminal._running_under_pytest", return_value=False)
30
+ self._headless_patch.start()
31
+
32
+ def tearDown(self):
33
+ """Restore the pytest-detection patch."""
34
+
35
+ self._headless_patch.stop()
36
+
37
+ def test_force_progress_disables_headless_detection(self):
38
+ """``LOGBAR_FORCE_PROGRESS=1`` keeps the UI enabled."""
39
+
40
+ with patch.dict(
41
+ "logbar.terminal.os.environ",
42
+ {"CI": "1", "LOGBAR_FORCE_PROGRESS": "1"},
43
+ clear=True,
44
+ ):
45
+ self.assertFalse(_is_headless_environment())
46
+
47
+ def test_disable_headless_detection_flag(self):
48
+ """``LOGBAR_DISABLE_HEADLESS_DETECTION=1`` keeps the UI enabled."""
49
+
50
+ with patch.dict(
51
+ "logbar.terminal.os.environ",
52
+ {"CI": "1", "LOGBAR_DISABLE_HEADLESS_DETECTION": "1"},
53
+ clear=True,
54
+ ):
55
+ self.assertFalse(_is_headless_environment())
56
+
57
+ def test_ci_env_is_headless(self):
58
+ """CI variables are treated as non-interactive headless backends."""
59
+
60
+ with patch.dict("logbar.terminal.os.environ", {"CI": "true"}, clear=True):
61
+ self.assertTrue(_is_headless_environment())
62
+
63
+ def test_devin_env_is_headless(self):
64
+ """Devin session variables disable progress redrawing."""
65
+
66
+ with patch.dict(
67
+ "logbar.terminal.os.environ",
68
+ {"DEVIN_OUTPOST_SESSION_ID": "devin-123"},
69
+ clear=True,
70
+ ):
71
+ self.assertTrue(_is_headless_environment())
72
+
73
+ def test_codex_env_is_headless(self):
74
+ """Codex session variables disable progress redrawing."""
75
+
76
+ with patch.dict(
77
+ "logbar.terminal.os.environ",
78
+ {"CODEX_HOME": "/tmp/codex"},
79
+ clear=True,
80
+ ):
81
+ self.assertTrue(_is_headless_environment())
82
+
83
+ def test_jupyter_kernel_env_is_headless(self):
84
+ """Jupyter kernel parent markers disable progress redrawing."""
85
+
86
+ with patch.dict(
87
+ "logbar.terminal.os.environ",
88
+ {"JPY_PARENT_PID": "12345"},
89
+ clear=True,
90
+ ):
91
+ self.assertTrue(_is_headless_environment())
92
+
93
+ def test_dumb_term_is_headless(self):
94
+ """A ``TERM=dumb`` terminal disables progress redrawing."""
95
+
96
+ with patch.dict("logbar.terminal.os.environ", {"TERM": "dumb"}, clear=True):
97
+ self.assertTrue(_is_headless_environment())
98
+
99
+ def test_notebook_backend_is_headless(self):
100
+ """The backend state reports ``headless=True`` for notebook targets."""
101
+
102
+ state = render_backend_state(notebook=True)
103
+ self.assertTrue(state.headless)
104
+ self.assertFalse(state.supports_cursor)
105
+ self.assertFalse(state.supports_ansi)
106
+ self.assertFalse(state.supports_styling)
107
+
108
+ def test_plain_terminal_is_not_headless(self):
109
+ """A clean, non-CI, non-agent environment is not headless."""
110
+
111
+ with patch.dict("logbar.terminal.os.environ", {}, clear=True):
112
+ self.assertFalse(_is_headless_environment())
113
+
114
+
115
+ class TestHeadlessProgressBehavior(unittest.TestCase):
116
+ """End-to-end checks that headless mode suppresses progress output."""
117
+
118
+ _PROGRESS_SCRIPT = """
119
+ import sys
120
+ from io import StringIO
121
+ sys.stdout = StringIO()
122
+ # Import after replacing stdout so any import-time log lands in the buffer.
123
+ from logbar.progress import ProgressBar
124
+
125
+ for _ in ProgressBar(range(5)):
126
+ pass
127
+ out = sys.stdout.getvalue()
128
+ print("HAS_LOG", "LogBar: headless" in out, file=sys.stderr)
129
+ print("HAS_PROGRESS", "[1 of 5]" in out or "100.0%" in out, file=sys.stderr)
130
+ """
131
+
132
+ @staticmethod
133
+ def _run_progress_in_subprocess(env: dict) -> subprocess.CompletedProcess:
134
+ """Run the progress script with the supplied environment."""
135
+
136
+ return subprocess.run(
137
+ [sys.executable, "-c", TestHeadlessProgressBehavior._PROGRESS_SCRIPT],
138
+ cwd=str(REPO_ROOT),
139
+ env=env,
140
+ capture_output=True,
141
+ text=True,
142
+ check=True,
143
+ )
144
+
145
+ def test_devin_terminal_suppresses_progress_and_logs_state(self):
146
+ """A Devin-marked subprocess logs the headless state and skips redraws."""
147
+
148
+ env = {
149
+ "PATH": os.environ.get("PATH", ""),
150
+ "PYTHONPATH": str(REPO_ROOT),
151
+ "DEVIN_OUTPOST_SESSION_ID": "devin-test-123",
152
+ }
153
+ result = self._run_progress_in_subprocess(env)
154
+ self.assertIn("HAS_LOG True", result.stderr)
155
+ self.assertIn("HAS_PROGRESS False", result.stderr)
156
+
157
+ def test_codex_terminal_suppresses_progress_and_logs_state(self):
158
+ """A Codex-marked subprocess logs the headless state and skips redraws."""
159
+
160
+ env = {
161
+ "PATH": os.environ.get("PATH", ""),
162
+ "PYTHONPATH": str(REPO_ROOT),
163
+ "CODEX_HOME": "/tmp/codex-test",
164
+ }
165
+ result = self._run_progress_in_subprocess(env)
166
+ self.assertIn("HAS_LOG True", result.stderr)
167
+ self.assertIn("HAS_PROGRESS False", result.stderr)
168
+
169
+ def test_plain_terminal_renders_progress_and_no_headless_log(self):
170
+ """A clean subprocess renders progress and does not emit the headless log."""
171
+
172
+ env = {
173
+ "PATH": os.environ.get("PATH", ""),
174
+ "PYTHONPATH": str(REPO_ROOT),
175
+ }
176
+ result = self._run_progress_in_subprocess(env)
177
+ self.assertIn("HAS_LOG False", result.stderr)
178
+ self.assertIn("HAS_PROGRESS True", result.stderr)
179
+
180
+ def test_logbar_shared_emits_single_headless_log(self):
181
+ """``LogBar.shared()`` emits the headless state once in a headless shell."""
182
+
183
+ script = """
184
+ import sys
185
+ from io import StringIO
186
+ sys.stdout = StringIO()
187
+ from logbar import LogBar
188
+
189
+ log = LogBar.shared()
190
+ log = LogBar.shared() # second call should be idempotent
191
+ out = sys.stdout.getvalue()
192
+ # The single log line should appear exactly once.
193
+ print("COUNT", out.count("high-frequency progress bars"), file=sys.stderr)
194
+ """
195
+ env = {
196
+ "PATH": os.environ.get("PATH", ""),
197
+ "PYTHONPATH": str(REPO_ROOT),
198
+ "DEVIN_OUTPOST_SESSION_ID": "devin-test-123",
199
+ }
200
+ result = subprocess.run(
201
+ [sys.executable, "-c", script],
202
+ cwd=str(REPO_ROOT),
203
+ env=env,
204
+ capture_output=True,
205
+ text=True,
206
+ check=True,
207
+ )
208
+ self.assertIn("COUNT 1", result.stderr)
209
+
210
+
211
+ if __name__ == "__main__":
212
+ unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes