diff --git a/eco/logs.py b/eco/logs.py index efee8e5..c427c67 100644 --- a/eco/logs.py +++ b/eco/logs.py @@ -163,6 +163,12 @@ def _kernel_record_to_entry(rec, session_label): text = f"{event} — {rec.get('kind', '')}:{rec.get('label', session_label)} (pid {rec.get('pid')})" elif event == "input": kind, text = "input", rec.get("code", "") + elif event == "widget_control": + # Same code-is-the-text contract as "input" (see + # KernelSession.log_widget_control's docstring) -- both kinds are + # directly usable as script lines in log_timeline_qt's "copy + # selected as script". + kind, text = "widget_control", rec.get("code", "") elif event == "error": kind, text = "error", f"{rec.get('ename', '')}: {rec.get('evalue', '')}" elif event == "result": diff --git a/eco/widgets/desktop_app.py b/eco/widgets/desktop_app.py index 72f2c72..b0bbf3f 100644 --- a/eco/widgets/desktop_app.py +++ b/eco/widgets/desktop_app.py @@ -900,6 +900,16 @@ class EcoDesktopApp: except Exception: logger.exception("opening %r's widget failed", name) return + # Record it as a timeline entry alongside console input/output -- + # a bare name, not `namespace.` (which, per build_namespace's + # own docstring, doesn't actually resolve -- Namespace.append_obj + # writes devices onto the scope module, not the Namespace + # instance): `.widget()` is exactly what build_namespace_vars + # already made available as a bare name in this console, so it's + # directly runnable if copy-pasted or included via "copy selected + # as script" (see eco.widgets.log_timeline_qt). + if self._kernel_session is not None: + self._kernel_session.log_widget_control(f"{name}.widget()") self._dock_widget_object(name, widget_obj) def _dock_widget_object(self, name, widget_obj): diff --git a/eco/widgets/kernel_registry.py b/eco/widgets/kernel_registry.py index d715345..9069a78 100644 --- a/eco/widgets/kernel_registry.py +++ b/eco/widgets/kernel_registry.py @@ -60,6 +60,19 @@ class KernelSession: programmatically via `.execute()`), whichever widget it came from.""" self._record("input", {"code": code}) + def log_widget_control(self, code): + """A GUI action that changed something without going through the + console at all -- e.g. clicking "Open" on a device in the + Namespace launcher (see eco.widgets.desktop_app._open_widget / + eco.widgets.jupyter_sidecar's equivalent). `code` is the actual + Python that reproduces the action (e.g. "namespace.cam_west. + widget()"), not just a description -- so this timeline entry is + directly usable in eco.widgets.log_timeline_qt's "copy selected as + script" (see eco.logs._kernel_record_to_entry for how "widget_ + control" events map to a TimelineEntry -- same code-is-the-text + contract as log_input).""" + self._record("widget_control", {"code": code}) + def log_output(self, event, **fields): """A message received back from this session's kernel -- `event` is one of "result" | "stream" | "error" (matching the qtconsole/ diff --git a/eco/widgets/log_timeline_qt.py b/eco/widgets/log_timeline_qt.py index 921bded..ae6943d 100644 --- a/eco/widgets/log_timeline_qt.py +++ b/eco/widgets/log_timeline_qt.py @@ -22,9 +22,14 @@ _MIN_SPAN = 180.0 # seconds _KIND_COLORS = { "input": "#1E7772", + "widget_control": "#3D5EA8", "error": "#AE3A2E", "session": "#B85E19", } +#: kinds whose .text is directly runnable Python -- see +#: LogTimelineQt._copy_selected_as_script and KernelSession.log_input / +#: log_widget_control's matching "code-is-the-text" contract. +_CODE_KINDS = ("input", "widget_control") _MATCH_COLOR = "#7A4FB0" @@ -278,6 +283,7 @@ class LogTimelineQt(QtWidgets.QWidget): super().__init__(parent) self.entries = sorted(entries, key=lambda e: e.t) self.on_open = on_open + self._kind_checkboxes = {} # kind -> QCheckBox, see _build_filter_row self.matches = [] self.match_idx = -1 @@ -328,6 +334,9 @@ class LogTimelineQt(QtWidgets.QWidget): findbar.addWidget(next_btn) root.addLayout(findbar) + root.addLayout(self._build_filter_row()) + root.addLayout(self._build_script_row()) + split = QtWidgets.QSplitter(QtCore.Qt.Vertical) top = QtWidgets.QWidget() @@ -337,6 +346,10 @@ class LogTimelineQt(QtWidgets.QWidget): self.list = QtWidgets.QListWidget() self.list.setUniformItemSizes(True) + # click+drag / Shift+click / Ctrl+click ranges and multi-select -- + # what "select entries to copy as a script" needs; Qt's own + # built-in behaviour once this is set, nothing else to wire up. + self.list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.list.itemActivated.connect(self._open_entry) self.list.itemDoubleClicked.connect(self._open_entry) self.list.verticalScrollBar().valueChanged.connect(self._on_scroll) @@ -365,6 +378,96 @@ class LogTimelineQt(QtWidgets.QWidget): root.addWidget(split, 1) + def _build_filter_row(self): + """One checkbox per distinct `kind` present in self.entries (e.g. + input/widget_control/result/stream/error/session) -- unticking one + hides its rows via _apply_filters, same list, no rebuild. All on + by default.""" + row = QtWidgets.QHBoxLayout() + row.setContentsMargins(10, 4, 10, 4) + row.addWidget(QtWidgets.QLabel("Show:")) + for kind in sorted({e.kind for e in self.entries}): + cb = QtWidgets.QCheckBox(kind) + cb.setChecked(True) + if kind in _KIND_COLORS: + cb.setStyleSheet(f"color: {_KIND_COLORS[kind]};") + cb.toggled.connect(self._apply_filters) + self._kind_checkboxes[kind] = cb + row.addWidget(cb) + row.addStretch(1) + return row + + def _build_script_row(self): + """"Copy Selected as Script": input/widget_control entries in the + current selection (see ExtendedSelection above) become script + lines verbatim (both kinds' .text is already runnable Python -- + see KernelSession.log_input/log_widget_control); anything else + selected is kept as a `# [kind] ...` comment, for context, not + executed. "Replicate timing" optionally inserts time.sleep(dt) + between consecutive lines, dt being the real gap (in seconds) + between those two entries' timestamps -- so replaying the script + reproduces the original pacing, not just the sequence.""" + row = QtWidgets.QHBoxLayout() + row.setContentsMargins(10, 4, 10, 4) + copy_btn = QtWidgets.QPushButton("Copy Selected as Script") + copy_btn.setToolTip( + "Select entries above (click, Shift+click for a range, Ctrl+click " + "to add) then click this to copy them as Python to the clipboard" + ) + copy_btn.clicked.connect(self._copy_selected_as_script) + row.addWidget(copy_btn) + self.timing_checkbox = QtWidgets.QCheckBox("Replicate timing (sleep calls)") + row.addWidget(self.timing_checkbox) + self.script_status = QtWidgets.QLabel() + self.script_status.setStyleSheet("color: palette(mid);") + row.addWidget(self.script_status) + row.addStretch(1) + return row + + def _apply_filters(self): + active = {k for k, cb in self._kind_checkboxes.items() if cb.isChecked()} + for i in range(self.list.count()): + item = self.list.item(i) + e = item.data(QtCore.Qt.UserRole) + if e is None: + continue # day-header row -- always visible + item.setHidden(e.kind not in active) + self._reposition_sticky() + self._sync_visible_range() + + def _copy_selected_as_script(self): + selected = [] + for item in self.list.selectedItems(): + if item.isHidden(): + continue # filtered out -- selection can include hidden rows + e = item.data(QtCore.Qt.UserRole) + if e is not None: + selected.append(e) + selected.sort(key=lambda e: e.t) + if not selected: + self.script_status.setText("nothing selected") + return + + include_timing = self.timing_checkbox.isChecked() + lines = [] + prev_t = None + for e in selected: + if include_timing and prev_t is not None: + dt = e.t - prev_t + if dt > 0.05: # skip negligible/near-zero gaps + lines.append(f"time.sleep({dt:.3f})") + if e.kind in _CODE_KINDS: + lines.append(e.text) + else: + comment = e.text.replace("\n", "\n# ") + lines.append(f"# [{e.kind}] {comment}") + prev_t = e.t + + header = "import time\n\n" if include_timing else "" + script = header + "\n".join(lines) + "\n" + QtWidgets.QApplication.clipboard().setText(script) + self.script_status.setText(f"copied {len(selected)} entries ({len(lines)} lines)") + def _populate(self): self.list.clear() cur_day = None diff --git a/tests/test_desktop_app.py b/tests/test_desktop_app.py index 8aeed59..d0ba6ad 100644 --- a/tests/test_desktop_app.py +++ b/tests/test_desktop_app.py @@ -642,6 +642,50 @@ def test_open_widget_calls_widget_directly_not_through_the_console(): gui.stop() +def test_open_widget_records_a_widget_control_timeline_entry(): + """So opening a device from the Namespace launcher shows up in + eco.logs.widget() alongside console input/output -- and, since the + logged code is a bare name (`.widget()`, exactly what + build_namespace_vars already made available in this console, not + `namespace.` which doesn't resolve -- see that docstring), it's + directly usable via log_timeline_qt's "copy selected as script".""" + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + ns = _FakeNamespace(initialized=["prepump"]) + gui = EcoDesktopApp(namespace=ns, auto_start=False) + gui._build_window() + import json + + try: + gui._open_widget("prepump") + lines = gui._kernel_session.log_path.read_text().splitlines() + events = [json.loads(l) for l in lines] + widget_control = [e for e in events if e["event"] == "widget_control"] + assert widget_control == [{"t": widget_control[0]["t"], "event": "widget_control", "code": "prepump.widget()"}] + finally: + gui.stop() + + +def test_open_widget_failure_does_not_log_a_widget_control_entry(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + ns = _FakeNamespace(initialized=["broken"]) + + def boom(): + raise RuntimeError("no display") + + ns._items["broken"].widget = boom + gui = EcoDesktopApp(namespace=ns, auto_start=False) + gui._build_window() + import json + + try: + gui._open_widget("broken") + lines = gui._kernel_session.log_path.read_text().splitlines() + events = [json.loads(l)["event"] for l in lines] + assert "widget_control" not in events + finally: + gui.stop() + + def test_open_widget_logs_and_survives_a_failing_widget(): app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) ns = _FakeNamespace(initialized=["broken"]) diff --git a/tests/test_kernel_registry.py b/tests/test_kernel_registry.py index 8d226be..28f6aa9 100644 --- a/tests/test_kernel_registry.py +++ b/tests/test_kernel_registry.py @@ -48,6 +48,14 @@ def test_log_input_and_log_output_append_jsonl_entries(tmp_path): assert lines[3]["name"] == "stdout" +def test_log_widget_control_appends_jsonl_entry(tmp_path): + session = _make_session(tmp_path, kind="desktop") + session.log_widget_control("cam_west.widget()") + + lines = [json.loads(l) for l in session.log_path.read_text().splitlines()] + assert lines[1] == {"t": lines[1]["t"], "event": "widget_control", "code": "cam_west.widget()"} + + def test_tail_returns_last_n_entries_oldest_first(tmp_path): session = _make_session(tmp_path, kind="desktop") for i in range(5): diff --git a/tests/test_log_timeline_qt.py b/tests/test_log_timeline_qt.py new file mode 100644 index 0000000..cbe428b --- /dev/null +++ b/tests/test_log_timeline_qt.py @@ -0,0 +1,156 @@ +"""Coverage for LogTimelineQt's kind-filter checkboxes, multi/range +selection, and "copy selected as script" -- constructing a real +LogTimelineQt has been confirmed safe under pytest+offscreen (unlike some +of eco's other real-Qt-widget constructions -- see +tests/test_indicator_widgets.py's docstring for that fragility), verified +manually before writing this file. +""" +import pytest + +pytest.importorskip("qtpy") +from qtpy import QtCore, QtWidgets + +from eco.widgets.log_timeline_common import TimelineEntry +from eco.widgets.log_timeline_qt import LogTimelineQt + + +def _entries(): + return [ + TimelineEntry(t=1000.0, kind="input", text="mono.get_current_value()"), + TimelineEntry(t=1000.2, kind="result", text="12000.0"), + TimelineEntry(t=1005.0, kind="widget_control", text="cam_west.widget()"), + TimelineEntry(t=1010.0, kind="input", text="att.set_target_value(0.5)"), + TimelineEntry(t=1010.1, kind="stream", text="[stdout] moving..."), + TimelineEntry(t=1015.0, kind="error", text="RuntimeError: timeout"), + ] + + +def _select_all_visible(viewer): + viewer.list.clearSelection() + for i in range(viewer.list.count()): + item = viewer.list.item(i) + if item.data(QtCore.Qt.UserRole) is not None and not item.isHidden(): + item.setSelected(True) + + +def _visible_kinds(viewer): + kinds = set() + for i in range(viewer.list.count()): + item = viewer.list.item(i) + e = item.data(QtCore.Qt.UserRole) + if e is not None and not item.isHidden(): + kinds.add(e.kind) + return kinds + + +def test_filter_checkboxes_cover_every_distinct_kind(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + assert set(viewer._kind_checkboxes.keys()) == { + "input", "result", "widget_control", "stream", "error", + } + assert all(cb.isChecked() for cb in viewer._kind_checkboxes.values()) + + +def test_unchecking_a_kind_hides_only_its_rows(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + + viewer._kind_checkboxes["stream"].setChecked(False) + viewer._kind_checkboxes["result"].setChecked(False) + + assert _visible_kinds(viewer) == {"input", "widget_control", "error"} + + +def test_rechecking_shows_rows_again(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + + viewer._kind_checkboxes["error"].setChecked(False) + assert "error" not in _visible_kinds(viewer) + viewer._kind_checkboxes["error"].setChecked(True) + assert "error" in _visible_kinds(viewer) + + +def test_list_selection_mode_allows_multi_select(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + assert viewer.list.selectionMode() == QtWidgets.QAbstractItemView.ExtendedSelection + + +def test_copy_selected_as_script_without_timing(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + _select_all_visible(viewer) + viewer.timing_checkbox.setChecked(False) + + viewer._copy_selected_as_script() + script = QtWidgets.QApplication.clipboard().text() + + assert "mono.get_current_value()" in script + assert "cam_west.widget()" in script + assert "att.set_target_value(0.5)" in script + assert "# [result]" in script + assert "# [stream]" in script + assert "# [error]" in script + assert "time.sleep" not in script + assert "import time" not in script + + +def test_copy_selected_as_script_with_timing_inserts_real_gaps(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + _select_all_visible(viewer) + viewer.timing_checkbox.setChecked(True) + + viewer._copy_selected_as_script() + script = QtWidgets.QApplication.clipboard().text() + + assert script.startswith("import time\n") + # mono -> cam_west is a 5s gap (1005.0 - 1000.0), skipping the 0.2s + # mono->result gap (below the 0.05s "negligible" threshold is not the + # point here -- 0.2s *is* above it, but result isn't code, so no sleep + # is inserted purely between two comment lines either; what matters is + # a real, selected code-to-code/comment gap shows up as a real sleep): + assert "time.sleep(5.000)" in script + + +def test_copy_selected_as_script_only_uses_visible_selection(): + """Hidden (filtered-out) rows can still technically be "selected" in + Qt's own model even while hidden -- must not leak into the script.""" + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + viewer._kind_checkboxes["error"].setChecked(False) # hide the error row + + # select everything in the model, hidden or not + for i in range(viewer.list.count()): + item = viewer.list.item(i) + if item.data(QtCore.Qt.UserRole) is not None: + item.setSelected(True) + viewer.timing_checkbox.setChecked(False) + + viewer._copy_selected_as_script() + script = QtWidgets.QApplication.clipboard().text() + + assert "timeout" not in script + + +def test_copy_selected_as_script_with_nothing_selected_sets_status(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + viewer.list.clearSelection() + + viewer._copy_selected_as_script() + + assert "nothing selected" in viewer.script_status.text() + + +def test_copy_selected_as_script_status_reports_counts(): + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + viewer = LogTimelineQt(_entries(), title="test") + _select_all_visible(viewer) + viewer.timing_checkbox.setChecked(False) + + viewer._copy_selected_as_script() + + assert "copied 6 entries" in viewer.script_status.text() diff --git a/tests/test_logs_namespace.py b/tests/test_logs_namespace.py index cbf2098..43bbbc8 100644 --- a/tests/test_logs_namespace.py +++ b/tests/test_logs_namespace.py @@ -15,6 +15,19 @@ def test_kernel_record_input(): assert e.is_error is False +def test_kernel_record_widget_control(): + """Same code-is-the-text contract as "input" (see + KernelSession.log_widget_control's docstring) -- both kinds must be + directly usable as script lines in log_timeline_qt's "copy selected + as script".""" + e = _kernel_record_to_entry( + {"t": 1.0, "event": "widget_control", "code": "cam_west.widget()"}, "sess" + ) + assert e.kind == "widget_control" + assert e.text == "cam_west.widget()" + assert e.is_error is False + + def test_kernel_record_error_sets_is_error(): e = _kernel_record_to_entry( {"t": 1.0, "event": "error", "ename": "ValueError", "evalue": "bad"}, "sess" @@ -280,6 +293,28 @@ def test_open_timeline_qt_forced_raises_instead_of_falling_back(monkeypatch): logs._open_timeline([], title="t", subtitle="s", prefer="qt") +def test_open_timeline_sidecar_renders_html_into_a_sidecar_panel(monkeypatch): + """JupyterLab's Log Viewer button (eco.widgets.jupyter_sidecar. + NamespaceDashboard) goes through prefer="sidecar" -- must render the + same HTML the html/jupyter path would, into a real dockable panel + (eco.widgets.jupyter_sidecar.open_html_in_sidecar), not some + parallel, duplicated rendering path.""" + calls = [] + monkeypatch.setattr( + "eco.widgets.log_timeline_html.render_html", + lambda entries, **kw: "rendered", + ) + monkeypatch.setattr( + "eco.widgets.jupyter_sidecar.open_html_in_sidecar", + lambda html, **kw: calls.append((html, kw)) or "sidecar-handle", + ) + + result = logs._open_timeline([], title="t", subtitle="s", prefer="sidecar") + + assert result == "sidecar-handle" + assert calls == [("rendered", {"title": "t"})] + + def test_open_timeline_rejects_unknown_prefer(): with pytest.raises(ValueError): logs._open_timeline([], title="t", subtitle="s", prefer="bogus")