diff --git a/libs/code/deepagents_code/_env_vars.py b/libs/code/deepagents_code/_env_vars.py index dc73f4028d4..359cf1c8147 100644 --- a/libs/code/deepagents_code/_env_vars.py +++ b/libs/code/deepagents_code/_env_vars.py @@ -80,6 +80,21 @@ as enabled, and `0`, `false`, `no`, `off`, empty string, or unset as disabled. """ +DEBUG_CONSOLE_CLICK_TO_COPY = "DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY" +r"""Enable click-to-copy in the `Ctrl+\` Debug Console when enabled. + +Off by default; toggle the "Click to copy" checkbox in the console or set +`[ui].debug_console_click_to_copy` in config.toml. A recognized value is parsed +by `classify_env_bool`; an unrecognized value falls through to the config value. +An empty/whitespace value is ignored before parsing (rather than being treated +as falsy) and also falls through, so it never masks the saved preference. + +When set, this env var takes precedence over the persisted +`[ui].debug_console_click_to_copy` config value on launch, so toggling the +checkbox will not appear to "stick" across restarts while the env var remains +set. +""" + DEBUG_FILE = "DEEPAGENTS_CODE_DEBUG_FILE" """Path for the debug log file (default: `DEFAULT_DEBUG_FILE`).""" diff --git a/libs/code/deepagents_code/app.py b/libs/code/deepagents_code/app.py index 4a18b446204..9f76d486376 100644 --- a/libs/code/deepagents_code/app.py +++ b/libs/code/deepagents_code/app.py @@ -960,6 +960,63 @@ def _load_show_scrollbar() -> bool: return False +def _load_debug_console_click_to_copy() -> bool: + r"""Load the `Ctrl+\` Debug Console click-to-copy preference. + + Reads `DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY` env var, falling back to + `[ui].debug_console_click_to_copy` from `~/.deepagents/config.toml`, and + finally `False` (click-to-copy off; Enter-to-copy is always available). + + Returns: + The resolved preference. + """ + from deepagents_code._env_vars import ( + DEBUG_CONSOLE_CLICK_TO_COPY, + classify_env_bool, + ) + + raw = os.environ.get(DEBUG_CONSOLE_CLICK_TO_COPY) + if raw is not None and raw.strip(): + env = classify_env_bool(raw) + if env is not None: + return env + + import tomllib + + from deepagents_code.model_config import DEFAULT_CONFIG_PATH + + if not DEFAULT_CONFIG_PATH.exists(): + return False + try: + with DEFAULT_CONFIG_PATH.open("rb") as f: + data = tomllib.load(f) + except (tomllib.TOMLDecodeError, PermissionError, OSError) as exc: + logger.warning( + "Could not read config for debug console click-to-copy preference: %s", + exc, + ) + return False + + ui = data.get("ui", {}) + if not isinstance(ui, dict): + logger.warning( + "[ui] should be a table; got %s while loading debug console " + "click-to-copy preference", + type(ui).__name__, + ) + return False + + value = ui.get("debug_console_click_to_copy") + if isinstance(value, bool): + return value + if value is not None: + logger.warning( + "[ui].debug_console_click_to_copy should be a boolean; got %s", + type(value).__name__, + ) + return False + + def _replace_malformed_ui( data: dict[str, object], ) -> tuple[dict[str, object], str | None]: @@ -1401,6 +1458,68 @@ def _save_show_scrollbar_result(visible: bool) -> _ConfigWriteResult: return _ConfigWriteResult(True, repair_message) +def _save_debug_console_click_to_copy_result(enabled: bool) -> _ConfigWriteResult: + r"""Persist the `Ctrl+\` Debug Console click-to-copy preference. + + Writes `[ui].debug_console_click_to_copy` atomically (temp file + + `Path.replace`). Mirrors `_save_show_scrollbar_result`. + + Returns: + Write status and a message suitable for a toast when the user needs to + know about a repair or failure. + """ + import contextlib + import tempfile + import tomllib + + try: + import tomli_w + + from deepagents_code.model_config import ( + DEFAULT_CONFIG_PATH, + _config_write_lock, + ) + + DEFAULT_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + with _config_write_lock: + if DEFAULT_CONFIG_PATH.exists(): + with DEFAULT_CONFIG_PATH.open("rb") as f: + data = tomllib.load(f) + else: + data = {} + + ui, repair_message = _replace_malformed_ui(data) + ui["debug_console_click_to_copy"] = enabled + + fd, tmp_path = tempfile.mkstemp( + dir=DEFAULT_CONFIG_PATH.parent, + suffix=".tmp", + ) + try: + with os.fdopen(fd, "wb") as f: + tomli_w.dump(data, f) + Path(tmp_path).replace(DEFAULT_CONFIG_PATH) + except BaseException: + with contextlib.suppress(OSError): + Path(tmp_path).unlink() + raise + except ( + OSError, + tomllib.TOMLDecodeError, + ImportError, + TypeError, + ValueError, + ) as exc: + logger.exception("Could not save debug console click-to-copy preference") + return _ConfigWriteResult( + False, + f"Click-to-copy toggled for this session but could not be saved " + f"({type(exc).__name__}).", + "error", + ) + return _ConfigWriteResult(True, repair_message) + + def _extract_model_params_flag(raw_arg: str) -> tuple[str, dict[str, Any] | None]: """Extract `--model-params` and its JSON value from a `/model` arg string. @@ -2984,6 +3103,15 @@ def __init__( `[ui].show_scrollbar` and re-persisted on toggle. Off by default. """ + self._debug_console_click_to_copy = _load_debug_console_click_to_copy() + r"""Whether the `Ctrl+\` Debug Console copies on click. + + Restored from `DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY` env var or + `[ui].debug_console_click_to_copy` and re-persisted when the console's + "Click to copy" checkbox is toggled. Off by default; Enter-to-copy is + always available. + """ + # Widget refs (populated in compose/on_mount) self._status_bar: StatusBar | None = None """Status bar widget; populated in `on_mount`.""" @@ -17203,10 +17331,52 @@ def persist_clear(cursor: int) -> None: self._build_debug_snapshot(), cleared_upto=self._debug_console_cleared_upto, on_clear=persist_clear, + click_to_copy=self._debug_console_click_to_copy, + on_click_to_copy_change=self._persist_debug_console_click_to_copy, ), handle_result, ) + def _persist_debug_console_click_to_copy(self, enabled: bool) -> None: + r"""Persist the Debug Console click-to-copy toggle off the UI thread. + + Keeps the in-memory preference in sync so a reopened console reflects + the latest choice, and writes `[ui].debug_console_click_to_copy` off the + UI thread via `asyncio.to_thread` so a slow disk never blocks the toggle. + A write failure degrades to a toast rather than losing the session-level + change. + + Args: + enabled: The new click-to-copy state to persist. + """ + self._debug_console_click_to_copy = enabled + + async def _persist() -> None: + try: + result = await asyncio.to_thread( + _save_debug_console_click_to_copy_result, enabled + ) + if result.message is not None: + self.notify( + result.message, + severity=result.severity, + timeout=6, + markup=False, + ) + except Exception: + logger.warning( + "Failed to persist debug console click-to-copy preference", + exc_info=True, + ) + self.notify( + "Click-to-copy toggled for this session but could not be saved.", + severity="error", + timeout=6, + markup=False, + ) + + self.call_later(_persist) + def _build_debug_snapshot(self) -> list[SnapshotField]: """Capture a point-in-time session/runtime snapshot for the console. diff --git a/libs/code/deepagents_code/config_manifest.py b/libs/code/deepagents_code/config_manifest.py index 478393b0eb5..6597eb1b9e0 100644 --- a/libs/code/deepagents_code/config_manifest.py +++ b/libs/code/deepagents_code/config_manifest.py @@ -917,6 +917,15 @@ def _credential_options() -> tuple[ConfigOption, ...]: env_var=_env_vars.SHOW_SCROLLBAR, toml_keys=("ui", "show_scrollbar"), ), + ConfigOption( + key="display.debug_console_click_to_copy", + group="Display", + summary="Copy on click in the Ctrl+\\ Debug Console (off by default).", + kind=OptionKind.BOOL, + default=False, + env_var=_env_vars.DEBUG_CONSOLE_CLICK_TO_COPY, + toml_keys=("ui", "debug_console_click_to_copy"), + ), ConfigOption( key="display.collapse_pastes", group="Display", diff --git a/libs/code/deepagents_code/tui/widgets/debug_console.py b/libs/code/deepagents_code/tui/widgets/debug_console.py index a144d061caa..1a2540c3181 100644 --- a/libs/code/deepagents_code/tui/widgets/debug_console.py +++ b/libs/code/deepagents_code/tui/widgets/debug_console.py @@ -24,7 +24,7 @@ from textual.scroll_view import ScrollView from textual.strip import Strip from textual.style import Style as TStyle -from textual.widgets import Select, Static +from textual.widgets import Checkbox, Select, Static from textual.widgets._select import ( # noqa: PLC2701 # needed to keep Tab navigation inside the open Select overlay SelectCurrent, SelectOverlay, @@ -85,6 +85,12 @@ class SnapshotField(NamedTuple): level-partitioned retention instead of re-flattening it into a single window.""" _FILTER_SELECT_ID = "debug-level-filter" +_CLICK_TO_COPY_ID = "debug-click-to-copy" +"""Id of the checkbox that opts click-to-copy in for the console.""" +_CLICK_TO_COPY_DEFAULT = False +"""Whether click-to-copy is enabled before the user toggles the checkbox.""" +_FOCUS_CYCLE = f"#{_FILTER_SELECT_ID}, #{_CLICK_TO_COPY_ID}, #debug-log" +"""Tab-cycle selector spanning the toolbar controls and the log view.""" FilterValue = Literal[ "all", "min:DEBUG", @@ -245,9 +251,12 @@ def __init__( *, widget_id: str | None = None, classes: str | None = None, + click_to_copy: bool = _CLICK_TO_COPY_DEFAULT, ) -> None: super().__init__(id=widget_id, classes=classes) self._on_copy_record = on_copy_record + self.click_to_copy = click_to_copy + """Whether clicking a log line copies it. Enter always copies.""" self._records: list[InMemoryLogRecord] = [] self._notice: Content | None = None self._contents: list[Content] = [] @@ -543,19 +552,19 @@ def key_enter(self, event: events.Key) -> None: self._copy_selected_record() def key_tab(self, event: events.Key) -> None: - """Move focus from the log to the level filter.""" + """Move focus from the log to the next toolbar control.""" event.prevent_default() event.stop() - self.screen.focus_next("#debug-level-filter, #debug-log") + self.screen.focus_next(_FOCUS_CYCLE) def key_shift_tab(self, event: events.Key) -> None: - """Move focus from the log to the level filter.""" + """Move focus from the log to the previous toolbar control.""" event.prevent_default() event.stop() - self.screen.focus_previous("#debug-level-filter, #debug-log") + self.screen.focus_previous(_FOCUS_CYCLE) def on_click(self, event: events.Click) -> None: - """Copy the clicked logical log record.""" + """Select the clicked log record, copying it when click-to-copy is on.""" _scroll_x, scroll_y = self.scroll_offset record = self._record_at_visual_y(scroll_y + event.y) if record is None: @@ -564,7 +573,8 @@ def on_click(self, event: events.Click) -> None: if index is not None: self._select_record(index) event.stop() - self._on_copy_record(record) + if self.click_to_copy: + self._on_copy_record(record) def _snapshot_copy_text(style: object) -> str | None: @@ -591,22 +601,32 @@ class _SnapshotView(Static): auto_links = False def __init__( - self, on_copy: Callable[[str], None], *, classes: str | None = None + self, + on_copy: Callable[[str], None], + *, + classes: str | None = None, + click_to_copy: bool = _CLICK_TO_COPY_DEFAULT, ) -> None: """Initialize with a callback used to copy a clicked span's text. Args: on_copy: Called with the span text when a copyable span is clicked. classes: Optional space-separated CSS classes. + click_to_copy: Whether copyable spans respond to clicks. Links + always open regardless of this setting. """ super().__init__(classes=classes) self._on_copy = on_copy + self.click_to_copy = click_to_copy + """Whether clicking a copyable span copies its value.""" def on_click(self, event: events.Click) -> None: """Copy a marked span or open a link span under the click.""" if getattr(event.style, "link", None): open_style_link(event) return + if not self.click_to_copy: + return text = _snapshot_copy_text(event.style) if text is not None: event.stop() @@ -615,7 +635,7 @@ def on_click(self, event: events.Click) -> None: def on_mouse_move(self, event: events.MouseMove) -> None: """Show a hand pointer over clickable spans and reset it elsewhere.""" clickable = bool(getattr(event.style, "link", None)) or ( - _snapshot_copy_text(event.style) is not None + self.click_to_copy and _snapshot_copy_text(event.style) is not None ) self.styles.pointer = "pointer" if clickable else "default" @@ -683,6 +703,11 @@ class DebugConsoleScreen(ModalScreen[None]): width: 18; } + DebugConsoleScreen .debug-console-click-to-copy { + margin-left: 2; + color: $text-muted; + } + DebugConsoleScreen .debug-console-log { height: 1fr; min-height: 5; @@ -712,6 +737,8 @@ def __init__( *, cleared_upto: int = 0, on_clear: Callable[[int], None] | None = None, + click_to_copy: bool = _CLICK_TO_COPY_DEFAULT, + on_click_to_copy_change: Callable[[bool], None] | None = None, ) -> None: """Initialize with a captured *snapshot* of session/runtime fields. @@ -722,6 +749,10 @@ def __init__( close/reopen; records emitted after it still appear. on_clear: Invoked with the new clear cursor whenever `Ctrl+L` clears the view, letting the owner persist it for the next open. + click_to_copy: Initial state of the "Click to copy" checkbox, + restored from the persisted preference. + on_click_to_copy_change: Called with the new value whenever the + checkbox is toggled, so the host can persist the preference. """ super().__init__() self._snapshot = list(snapshot) @@ -733,6 +764,8 @@ def __init__( # One-shot guard so the "buffer unavailable" notice is written only once. self._missing_notice_shown = False self._level_filter: FilterValue = "all" + self._click_to_copy = click_to_copy + self._on_click_to_copy_change = on_click_to_copy_change # Seed links resolved elsewhere in this process (normally the welcome # banner) so reopening the console does not briefly render without one. self._langsmith_urls = self._cached_langsmith_urls() @@ -766,7 +799,9 @@ def compose(self) -> ComposeResult: with Vertical(): yield Static("Debug Console", classes="debug-console-title") snapshot_view = _SnapshotView( - self._copy_snapshot_value, classes="debug-console-snapshot" + self._copy_snapshot_value, + classes="debug-console-snapshot", + click_to_copy=self._click_to_copy, ) snapshot_view.update(self._render_snapshot()) yield snapshot_view @@ -779,10 +814,18 @@ def compose(self) -> ComposeResult: id=_FILTER_SELECT_ID, compact=True, ) + yield Checkbox( + "Click to copy", + value=self._click_to_copy, + id=_CLICK_TO_COPY_ID, + compact=True, + classes="debug-console-click-to-copy", + ) yield _DebugLogView( self._copy_record, widget_id="debug-log", classes="debug-console-log", + click_to_copy=self._click_to_copy, ) yield Static(self._render_help(), classes="debug-console-help") @@ -860,20 +903,20 @@ def _refresh_snapshot(self) -> None: logger.debug("Debug console snapshot refresh skipped (widget unavailable)") def key_tab(self, event: events.Key) -> None: - """Cycle focus between the level filter and log lines.""" + """Cycle focus between the toolbar controls and log lines.""" if self._level_select().expanded: return event.prevent_default() event.stop() - self.focus_next("#debug-level-filter, #debug-log") + self.focus_next(_FOCUS_CYCLE) def key_shift_tab(self, event: events.Key) -> None: - """Cycle focus between the log lines and level filter.""" + """Cycle focus between the log lines and toolbar controls.""" if self._level_select().expanded: return event.prevent_default() event.stop() - self.focus_previous("#debug-level-filter, #debug-log") + self.focus_previous(_FOCUS_CYCLE) def on_select_changed(self, event: Select.Changed) -> None: """Refresh visible records when the log-level filter changes.""" @@ -891,6 +934,18 @@ def on_select_changed(self, event: Select.Changed) -> None: self._level_filter = cast("FilterValue", value) self._refresh_log_view(scroll_end=True) + def on_checkbox_changed(self, event: Checkbox.Changed) -> None: + """Toggle click-to-copy for the log lines and snapshot spans.""" + if event.checkbox.id != _CLICK_TO_COPY_ID: + return + self._click_to_copy = event.value + self.query_one("#debug-log", _DebugLogView).click_to_copy = event.value + self.query_one( + ".debug-console-snapshot", _SnapshotView + ).click_to_copy = event.value + if self._on_click_to_copy_change is not None: + self._on_click_to_copy_change(event.value) + def _render_snapshot(self) -> Content: """Build the right-aligned `label: value` snapshot block. @@ -936,7 +991,7 @@ def _render_help() -> Content: """ return Content.styled( "Esc close · Ctrl+L clear view · c copy visible logs · " - "click copy line/thread", + "Enter copy line · check 'Click to copy' to copy on click", "dim italic", ) diff --git a/libs/code/tests/unit_tests/test_app.py b/libs/code/tests/unit_tests/test_app.py index f5d9822238d..fed5b615e74 100644 --- a/libs/code/tests/unit_tests/test_app.py +++ b/libs/code/tests/unit_tests/test_app.py @@ -14,7 +14,7 @@ import webbrowser from pathlib import Path from types import SimpleNamespace -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast from unittest.mock import AsyncMock, MagicMock, call, patch if TYPE_CHECKING: @@ -12121,6 +12121,211 @@ def test_save_failure_reports_error( assert result.message is not None +class TestDebugConsoleClickToCopyPreference: + """Tests for the persisted Debug Console click-to-copy preference.""" + + @pytest.mark.parametrize( + ("ok", "message", "severity"), + [ + (True, "Replaced malformed [ui] configuration.", "warning"), + (False, "Click-to-copy preference could not be saved.", "error"), + ], + ) + async def test_persist_notifies_with_result_severity( + self, + ok: bool, + message: str, + severity: Literal["warning", "error"], + ) -> None: + """Repairs and failures are surfaced with their reported severity.""" + from deepagents_code.app import _ConfigWriteResult + + app = DeepAgentsApp() + result = _ConfigWriteResult(ok, message, severity) + + with ( + patch.object(app, "call_later") as call_later_mock, + patch.object(app, "notify") as notify_mock, + patch( + "deepagents_code.app.asyncio.to_thread", + new=AsyncMock(return_value=result), + ), + ): + app._persist_debug_console_click_to_copy(True) + persist = call_later_mock.call_args.args[0] + await persist() + + assert app._debug_console_click_to_copy is True + notify_mock.assert_called_once_with( + message, + severity=severity, + timeout=6, + markup=False, + ) + + def test_load_defaults_false_when_config_missing( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A missing config yields the off default.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + monkeypatch.setattr( + "deepagents_code.model_config.DEFAULT_CONFIG_PATH", + tmp_path / "config.toml", + ) + assert _load_debug_console_click_to_copy() is False + + def test_load_reads_saved_true( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An explicit `true` preference is read back.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text("[ui]\ndebug_console_click_to_copy = true\n") + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + assert _load_debug_console_click_to_copy() is True + + def test_load_ignores_non_boolean( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """A non-boolean preference is ignored with a warning.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text('[ui]\ndebug_console_click_to_copy = "yes"\n') + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + with caplog.at_level("WARNING", logger="deepagents_code.app"): + assert _load_debug_console_click_to_copy() is False + assert any( + "debug_console_click_to_copy" in record.getMessage() + for record in caplog.records + ) + + def test_env_var_overrides_config( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The env var takes priority over the config.toml value.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text("[ui]\ndebug_console_click_to_copy = false\n") + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + monkeypatch.setenv("DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY", "1") + assert _load_debug_console_click_to_copy() is True + + def test_invalid_env_var_falls_back_to_config( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An unrecognized env var value does not mask the saved preference.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text("[ui]\ndebug_console_click_to_copy = true\n") + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + monkeypatch.setenv("DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY", "maybe") + assert _load_debug_console_click_to_copy() is True + + def test_empty_env_var_falls_back_to_config( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An empty/whitespace env var is ignored, not treated as falsy.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text("[ui]\ndebug_console_click_to_copy = true\n") + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + monkeypatch.setenv("DEEPAGENTS_CODE_DEBUG_CONSOLE_CLICK_TO_COPY", " ") + assert _load_debug_console_click_to_copy() is True + + def test_load_ignores_non_table_ui( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """A `[ui]` value that is not a table degrades to the off default.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text('ui = "not-a-table"\n') + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + with caplog.at_level("WARNING", logger="deepagents_code.app"): + assert _load_debug_console_click_to_copy() is False + assert any("[ui]" in record.getMessage() for record in caplog.records) + + def test_load_handles_unreadable_config( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """Malformed TOML degrades to the off default with a warning.""" + from deepagents_code.app import _load_debug_console_click_to_copy + + config = tmp_path / "config.toml" + config.write_text("[ui]\ndebug_console_click_to_copy = tru\n") # invalid TOML + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + with caplog.at_level("WARNING", logger="deepagents_code.app"): + assert _load_debug_console_click_to_copy() is False + assert any("click-to-copy" in record.getMessage() for record in caplog.records) + + def test_save_round_trips( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Saving then loading returns the saved value, both directions.""" + from deepagents_code.app import ( + _load_debug_console_click_to_copy, + _save_debug_console_click_to_copy_result, + ) + + monkeypatch.setattr( + "deepagents_code.model_config.DEFAULT_CONFIG_PATH", + tmp_path / "config.toml", + ) + assert _save_debug_console_click_to_copy_result(True).ok is True + assert _load_debug_console_click_to_copy() is True + assert _save_debug_console_click_to_copy_result(False).ok is True + assert _load_debug_console_click_to_copy() is False + + def test_save_preserves_other_ui_keys( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Persisting the toggle leaves unrelated `[ui]` keys intact.""" + import tomllib + + from deepagents_code.app import _save_debug_console_click_to_copy_result + + config = tmp_path / "config.toml" + config.write_text('[ui]\ntheme = "langchain"\n') + monkeypatch.setattr("deepagents_code.model_config.DEFAULT_CONFIG_PATH", config) + assert _save_debug_console_click_to_copy_result(True).ok is True + data = tomllib.loads(config.read_text()) + assert data["ui"]["theme"] == "langchain" + assert data["ui"]["debug_console_click_to_copy"] is True + + def test_save_failure_reports_error( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An unwritable target yields an error result instead of raising.""" + from deepagents_code.app import _save_debug_console_click_to_copy_result + + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + monkeypatch.setattr( + "deepagents_code.model_config.DEFAULT_CONFIG_PATH", + blocker / "config.toml", + ) + + result = _save_debug_console_click_to_copy_result(True) + assert result.ok is False + assert result.severity == "error" + assert result.message is not None + + class TestAppBlurPausesCursorBlink: """Test `on_app_blur` pauses cursor blink without changing widget focus.""" diff --git a/libs/code/tests/unit_tests/test_debug_console.py b/libs/code/tests/unit_tests/test_debug_console.py index 8d44fc92ee6..b688666dc05 100644 --- a/libs/code/tests/unit_tests/test_debug_console.py +++ b/libs/code/tests/unit_tests/test_debug_console.py @@ -9,7 +9,7 @@ from textual.app import App, ComposeResult from textual.screen import ModalScreen -from textual.widgets import Select, Static +from textual.widgets import Checkbox, Select, Static from textual.widgets._select import SelectOverlay import deepagents_code.tui.widgets.debug_console as debug_console_mod @@ -711,7 +711,7 @@ def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: assert "debug-console-enter-copy-marker" in captured["text"] - async def test_tab_cycles_between_level_filter_and_log_lines(self) -> None: + async def test_tab_cycles_through_toolbar_controls_and_log_lines(self) -> None: app = _Harness() async with app.run_test() as pilot: screen = DebugConsoleScreen(_snapshot()) @@ -719,16 +719,31 @@ async def test_tab_cycles_between_level_filter_and_log_lines(self) -> None: await pilot.pause() log = screen.query_one("#debug-log", _DebugLogView) select = screen.query_one("#debug-level-filter", Select) + checkbox = screen.query_one("#debug-click-to-copy", Checkbox) log.focus() + # Forward: log -> filter -> checkbox -> log. await pilot.press("tab") await pilot.pause() assert screen.focused is select - await pilot.press("shift+tab") + await pilot.press("tab") + await pilot.pause() + assert screen.focused is checkbox + + await pilot.press("tab") await pilot.pause() assert screen.focused is log + # Reverse walks back through the checkbox. + await pilot.press("shift+tab") + await pilot.pause() + assert screen.focused is checkbox + + await pilot.press("shift+tab") + await pilot.pause() + assert screen.focused is select + async def test_tab_moves_open_level_dropdown_highlight(self) -> None: app = _Harness() async with app.run_test() as pilot: @@ -888,6 +903,9 @@ def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: app.push_screen(screen) await pilot.pause() + screen.query_one("#debug-click-to-copy", Checkbox).value = True + await pilot.pause() + snapshot_widget = screen.query_one(".debug-console-snapshot", Static) # Single "Thread" field: label (6 chars) + 2-space gutter puts the # value at column 8, so an x offset of 10 lands inside the copyable @@ -897,6 +915,125 @@ def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: assert captured["text"] == "thread-abc" + async def test_click_to_copy_defaults_off_and_ignores_snapshot_click( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + captured: dict[str, str] = {} + + def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: + captured["text"] = text + return True, None + + monkeypatch.setattr(debug_console_mod, "copy_text_to_clipboard", fake_copy) + + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen( + [SnapshotField("Thread", "thread-abc", copyable=True)] + ) + app.push_screen(screen) + await pilot.pause() + + assert screen.query_one("#debug-click-to-copy", Checkbox).value is False + + snapshot_widget = screen.query_one(".debug-console-snapshot", Static) + await pilot.click(snapshot_widget, offset=(10, 0)) + await pilot.pause() + + assert "text" not in captured + + async def test_click_line_ignored_when_click_to_copy_off_but_enter_copies( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + captured: dict[str, str] = {} + + def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: + captured["text"] = text + return True, None + + monkeypatch.setattr(debug_console_mod, "copy_text_to_clipboard", fake_copy) + + logger.info("debug-console-click-off-marker") + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen(_snapshot()) + app.push_screen(screen) + await pilot.pause() + log = screen.query_one("#debug-log", _DebugLogView) + index = next( + index + for index, record in enumerate(log.records) + if "debug-console-click-off-marker" in record.message + ) + log._select_record(index) + + # A click selects but does not copy while the checkbox is unchecked. + await pilot.click(log) + await pilot.pause() + assert "text" not in captured + + # Enter still copies the selected record regardless of the checkbox. + log.focus() + log._select_record(index) + await pilot.press("enter") + await pilot.pause() + + assert "debug-console-click-off-marker" in captured["text"] + + async def test_toggling_checkbox_propagates_to_child_widgets(self) -> None: + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen( + [SnapshotField("Thread", "thread-abc", copyable=True)] + ) + app.push_screen(screen) + await pilot.pause() + + log = screen.query_one("#debug-log", _DebugLogView) + snapshot_view = screen.query_one( + ".debug-console-snapshot", debug_console_mod._SnapshotView + ) + assert log.click_to_copy is False + assert snapshot_view.click_to_copy is False + + screen.query_one("#debug-click-to-copy", Checkbox).value = True + await pilot.pause() + assert screen._click_to_copy is True + assert log.click_to_copy is True + assert snapshot_view.click_to_copy is True + + screen.query_one("#debug-click-to-copy", Checkbox).value = False + await pilot.pause() + assert log.click_to_copy is False + assert snapshot_view.click_to_copy is False + + async def test_initial_click_to_copy_restores_checkbox_and_children(self) -> None: + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen(_snapshot(), click_to_copy=True) + app.push_screen(screen) + await pilot.pause() + + assert screen.query_one("#debug-click-to-copy", Checkbox).value is True + assert screen.query_one("#debug-log", _DebugLogView).click_to_copy is True + + async def test_toggling_checkbox_invokes_persist_callback(self) -> None: + changes: list[bool] = [] + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen( + _snapshot(), on_click_to_copy_change=changes.append + ) + app.push_screen(screen) + await pilot.pause() + + screen.query_one("#debug-click-to-copy", Checkbox).value = True + await pilot.pause() + screen.query_one("#debug-click-to-copy", Checkbox).value = False + await pilot.pause() + + assert changes == [True, False] + async def test_copyable_value_carries_copy_meta_span(self) -> None: app = _Harness() async with app.run_test() as pilot: @@ -1085,6 +1222,49 @@ def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: assert len(opened) == 1 assert copied == [] + async def test_clicking_langsmith_link_opens_it_even_with_click_to_copy_on( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + opened: list[object] = [] + monkeypatch.setattr( + debug_console_mod, "open_style_link", lambda event: opened.append(event) + ) + copied: list[str] = [] + + def fake_copy(_app: App, text: str) -> tuple[bool, str | None]: + copied.append(text) + return True, None + + monkeypatch.setattr(debug_console_mod, "copy_text_to_clipboard", fake_copy) + + url = "https://smith.langchain.com/o/org/projects/p/proj/t/thread-abc" + app = _Harness() + async with app.run_test() as pilot: + screen = DebugConsoleScreen( + [ + SnapshotField( + "Thread", "thread-abc", copyable=True, thread_id="thread-abc" + ) + ], + click_to_copy=True, + ) + app.push_screen(screen) + await pilot.pause() + + screen._langsmith_urls["thread-abc"] = url + screen._refresh_snapshot() + await pilot.pause() + + snapshot_widget = screen.query_one(".debug-console-snapshot", Static) + # "(langsmith)" starts at col 20 (see the toggle-off test); x=22 is + # inside it. + await pilot.click(snapshot_widget, offset=(22, 0)) + await pilot.pause() + + # The link branch still returns early even though click-to-copy is on. + assert len(opened) == 1 + assert copied == [] + async def test_copy_failure_notifies_warning( self, monkeypatch: pytest.MonkeyPatch ) -> None: