merge: hoàn tất merge origin/feature/teamhoa/r05-r06 vào feature/delta-team/epic-R04

Resolve 3 file conflict:
- docs/refactor/Refactoring_Checklist.md: giữ nội dung incoming (phía HEAD
  trống ở đoạn conflict).
- tests/integration/test_routing_surfaces.py: khôi phục từ incoming (bị mất
  ở merge trước đó), điều chỉnh lại cho khớp API hiện tại của
  RoutingApplicationService (resolve()/RouteEvaluation/mode_resolver thay vì
  route_turn()/mode_reader cũ), bỏ 2 test pin một lớp RoutingDecision không
  còn tồn tại trên nhánh này.
- ui/folder_tab.py: chấp nhận xoá (deleted by them) — đã được thay thế hoàn
  toàn bởi presentation/folder/* (R08-T12), không còn nơi nào import module
  cũ.

Sửa thêm 2 chỗ lệch API bị auto-merge không báo conflict (phát hiện khi chạy
lại test):
- presentation/folder/ai_edit_model_resolver.py + ai_file_editor_dialog.py:
  AiEditModelResolver.apply_routing() gọi route_turn() đã bị xoá khỏi
  RoutingApplicationService — chuyển sang build_routing_application_service()
  .resolve(RoutingRequest(...)) giống chat_panel.py/co4e_chat.py; sửa luôn
  chữ ký _confirm_routing_switch nhận thêm timeout cho khớp contract confirm
  mới.
- config.py: import JsonConfigRepository ở đầu file gây circular import với
  core/tasks.py (cần CONFIG_DIR) qua chuỗi mới
  infrastructure/persistence/json/task_repository_impl.py (R07). Dời import
  xuống ngay trước chỗ dùng đầu tiên.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-28 11:40:44 +09:00
co-authored by Claude Sonnet 5
73 changed files with 7674 additions and 4174 deletions
+142
View File
@@ -0,0 +1,142 @@
"""EPIC R08-T13: TokenUsageCardWidget / UsageChartWidget / HabitsWidget /
DashboardTab shell, real Qt offscreen.
``DashboardQueryService``'s own logic is unit tested (R08-T13, no Qt) in
``tests/unit/test_dashboard_query_service.py``; this file proves the three
widgets and the shell are actually wired to it and to each other (the period
selector living on ``UsageChartWidget`` driving all three).
"""
from __future__ import annotations
import json
import os
from datetime import date
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.core import usage_tracker as ut # noqa: E402
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def usage_dir(tmp_path, monkeypatch):
d = tmp_path / "usage"
monkeypatch.setattr(ut, "USAGE_DIR", d)
return d
@pytest.fixture
def ctx(qt_app, tmp_path):
return AppContext(AppConfig.load(tmp_path / "config.json"))
def _write_event(usage_dir, day: date, **overrides):
usage_dir.mkdir(parents=True, exist_ok=True)
event = {
"ts": f"{day.isoformat()}T10:00:00", "source": "cowork", "label": "Test chat",
"provider": "anthropic", "model": "claude-sonnet-4-6",
"in": 100, "out": 50, "cache": 0, "estimated": False,
"account": "", "machine": "",
}
event.update(overrides)
path = usage_dir / f"{day.isoformat()}.jsonl"
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(event) + "\n")
def test_dashboard_tab_builds_and_populates_cards(usage_dir, ctx):
from cowork_local.presentation.dashboard.dashboard_tab import DashboardTab
_write_event(usage_dir, date.today())
tab = DashboardTab(ctx) # refresh() runs once at construction
assert "100" in tab.token_cards.card_in.value_lbl.text() \
or tab.token_cards.card_in.value_lbl.text() # non-crashing, has SOME text
assert tab.token_cards.card_total.value_lbl.text() != ""
def test_period_navigation_on_chart_refreshes_the_whole_shell(usage_dir, ctx):
from cowork_local.presentation.dashboard.dashboard_tab import DashboardTab
_write_event(usage_dir, date.today())
tab = DashboardTab(ctx)
calls = []
tab.refresh = lambda *a, orig=tab.refresh: (calls.append(1), orig(*a))[-1]
tab.chart._chart_prev()
assert calls == [1]
def test_granularity_change_resets_offset_to_current(usage_dir, ctx):
from cowork_local.presentation.dashboard.dashboard_tab import DashboardTab
from cowork_local.presentation.dashboard.usage_chart_widget import UsageChartWidget
tab = DashboardTab(ctx)
tab.chart._chart_offset = -3
idx = tab.chart.gran_combo.findData("month")
tab.chart.gran_combo.setCurrentIndex(idx)
assert tab.chart.chart_offset == 0
def test_currency_change_persists_and_triggers_refresh(usage_dir, ctx):
from cowork_local.presentation.dashboard.dashboard_tab import DashboardTab
tab = DashboardTab(ctx)
idx = tab.chart.currency_combo.findData("EUR") \
if tab.chart.currency_combo.findData("EUR") >= 0 else 0
seen = []
tab.chart.currency_changed.connect(lambda: seen.append(1))
tab.chart.currency_combo.setCurrentIndex(idx)
if tab.chart.currency_combo.currentData() != "USD":
assert seen == [1]
assert ctx.config.data["usage"]["currency"] == tab.chart.currency_combo.currentData()
def test_habits_widget_ai_analyze_noop_without_data(usage_dir, ctx):
"""No events in range -> emits a status message instead of starting a
background worker (matches the original _ai_analyze guard)."""
from cowork_local.presentation.dashboard.habits_widget import HabitsWidget
from cowork_local.application.monitoring import DashboardQueryService
query = DashboardQueryService(ctx)
widget = HabitsWidget(ctx, query)
widget.refresh(date(2020, 1, 1), date(2020, 1, 1))
messages = []
widget.status_message.connect(messages.append)
widget._ai_analyze()
assert messages # "no data" status, no worker started
assert widget._ai_worker is None
def test_budget_apply_updates_budget_card(usage_dir, ctx):
from cowork_local.application.monitoring import DashboardQueryService
from cowork_local.presentation.dashboard.token_usage_card_widget import TokenUsageCardWidget
query = DashboardQueryService(ctx)
widget = TokenUsageCardWidget(ctx, query)
widget.budget_card.budget_spin.setValue(50.0)
widget._apply_budget()
status = query.budget_status()
assert status is not None
assert status["amount_usd"] == pytest.approx(50.0)
+193
View File
@@ -0,0 +1,193 @@
"""EPIC R08-T12: WorkspaceFileTree / DocumentPreviewManager / FolderTab,
real Qt offscreen.
Scope note: the AI-Edit panel's send -> plan -> edit -> apply pipeline
(``ai_edit_pipeline.py``) runs on a real ``core.worker.AgentWorker`` QThread
and had ZERO existing tests before this task (confirmed by grep — nothing
under tests/ exercised ``ui/folder_tab.py``'s AI methods except the routing
surface test, fixed alongside this task in
``tests/integration/test_routing_surfaces.py``). Driving that full async
pipeline end to end is out of scope here; what's covered is everything that
doesn't need a live QThread: navigation, preview rendering, and — the
concrete R08-T12 deliverable — that saves/creates actually go through
``FileWorkspaceService`` (containment enforced, not just "writes a file").
"""
from __future__ import annotations
import os
from pathlib import Path
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def ctx(qt_app, tmp_path: Path):
return AppContext(AppConfig.load(tmp_path / "config.json"))
@pytest.fixture
def root(tmp_path: Path) -> Path:
d = tmp_path / "workspace"
d.mkdir()
return d
# ---- WorkspaceFileTree ----------------------------------------------------- #
def test_workspace_file_tree_set_root_updates_label_and_model(qt_app, root):
from cowork_local.presentation.folder.workspace_file_tree import WorkspaceFileTree
tree = WorkspaceFileTree(str(root))
other = root.parent / "other-root"
other.mkdir()
tree.set_root(str(other))
assert tree.root == str(other)
assert tree.path_lbl.text() == str(other)
def test_workspace_file_tree_ignores_an_invalid_root(qt_app, root):
from cowork_local.presentation.folder.workspace_file_tree import WorkspaceFileTree
tree = WorkspaceFileTree(str(root))
tree.set_root(str(root / "does-not-exist"))
assert tree.root == str(root) # unchanged
def test_workspace_file_tree_click_emits_file_selected(qt_app, root):
from cowork_local.presentation.folder.workspace_file_tree import WorkspaceFileTree
f = root / "a.txt"
f.write_text("hello", encoding="utf-8")
tree = WorkspaceFileTree(str(root))
seen = []
tree.file_selected.connect(seen.append)
index = tree.model.index(str(f))
tree._on_tree_clicked(index)
assert seen and os.path.normpath(seen[0]) == os.path.normpath(str(f))
# ---- DocumentPreviewManager ------------------------------------------------- #
def test_open_file_renders_code_into_the_editor(qt_app, root):
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
f = root / "script.py"
f.write_text("print('hi')\n", encoding="utf-8")
preview = DocumentPreviewManager(str(root))
preview.open_file(str(f))
assert preview.stack.currentWidget() is preview.editor
assert preview.editor.toPlainText() == "print('hi')\n"
assert preview.current_file == str(f)
def test_open_file_on_a_binary_file_shows_the_placeholder(qt_app, root):
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
f = root / "data.bin"
f.write_bytes(b"\x00\x01\x02binary")
preview = DocumentPreviewManager(str(root))
preview.open_file(str(f))
assert preview.stack.currentWidget() is preview._placeholder
def test_save_writes_through_file_workspace_service(qt_app, root):
"""The concrete R08-T12/R06-T05 deliverable: FileWorkspaceService (built
at R06, unused until this task) is now the actual write path."""
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
f = root / "note.txt"
f.write_text("old", encoding="utf-8")
preview = DocumentPreviewManager(str(root))
preview.open_file(str(f))
preview.editor.setPlainText("new content")
preview.save()
assert f.read_text(encoding="utf-8") == "new content"
def test_create_new_file_writes_inside_root_via_file_workspace_service(qt_app, root):
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
preview = DocumentPreviewManager(str(root))
dest = preview.create_new_file("sub/new.md", "# hello")
assert dest == str(root / "sub" / "new.md")
assert (root / "sub" / "new.md").read_text(encoding="utf-8") == "# hello"
assert preview.current_file == dest # opened it, kept the AI chat (reset_ai=False)
def test_create_new_file_rejects_a_path_escaping_the_root(qt_app, root):
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
preview = DocumentPreviewManager(str(root))
messages = []
preview.status_message.connect(messages.append)
dest = preview.create_new_file("../escaped.txt", "nope")
assert dest is None
assert not (root.parent / "escaped.txt").exists()
assert messages # a save_error status was emitted
def test_write_content_persists_and_refreshes_html_preview(qt_app, root):
from cowork_local.presentation.folder.document_preview_manager import DocumentPreviewManager
f = root / "page.html"
f.write_text("<p>old</p>", encoding="utf-8")
preview = DocumentPreviewManager(str(root))
preview.open_file(str(f)) # HTML opens in preview mode by default
preview.write_content("<p>new</p>")
assert f.read_text(encoding="utf-8") == "<p>new</p>"
# ---- FolderTab shell -------------------------------------------------------- #
def test_folder_tab_builds_and_wires_tree_to_preview(ctx, root):
from cowork_local.presentation.folder.folder_tab import FolderTab
tab = FolderTab(ctx)
tab.set_root(str(root))
f = root / "hello.py"
f.write_text("x = 1\n", encoding="utf-8")
tab.tree.file_selected.emit(str(f)) # simulate a tree click
assert tab.preview.current_file == str(f)
assert tab.preview.editor.toPlainText() == "x = 1\n"
def test_folder_tab_ai_panel_toggle_updates_button_badge(ctx, root):
from cowork_local.presentation.folder.folder_tab import FolderTab
tab = FolderTab(ctx)
assert tab.ai_panel.isHidden()
tab.ai_btn.setChecked(True)
tab._toggle_ai_panel()
assert not tab.ai_panel.isHidden()
@@ -0,0 +1,53 @@
"""EPIC R07-T03: QtSchedulerClock against a REAL QTimer/event loop.
``tests/unit/test_task_scheduler_dispatch.py`` covers ``TaskScheduler``'s
dispatch logic entirely through ``tests/fakes/fake_clock.py::FakeClock`` (no
Qt at all — that's the whole point of the extraction). This file is the
complement: it proves the adapter itself actually drives a real ``QTimer``
and pumps a real event loop, offscreen, the way ``test_history_dir_race.py``
proves ``ui/chat_panel.py``'s fix against real Qt rather than a double.
"""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest # noqa: E402
from PySide6.QtTest import QTest # noqa: E402
from PySide6.QtWidgets import QApplication # noqa: E402
from cowork_local.infrastructure.qt.qt_scheduler_clock import QtSchedulerClock # noqa: E402
@pytest.fixture(scope="module")
def qapp():
return QApplication.instance() or QApplication([])
def test_start_fires_callback_on_the_real_qt_event_loop(qapp):
clock = QtSchedulerClock()
ticks = []
clock.start(interval_ms=10, callback=lambda: ticks.append(1))
try:
QTest.qWait(200) # let the real QTimer fire a few times
finally:
clock.stop()
assert len(ticks) >= 1
def test_stop_prevents_further_callbacks(qapp):
clock = QtSchedulerClock()
ticks = []
clock.start(interval_ms=10, callback=lambda: ticks.append(1))
QTest.qWait(50)
clock.stop()
count_after_stop = len(ticks)
QTest.qWait(100)
assert len(ticks) == count_after_stop # no more callbacks after stop()
def test_pump_processes_pending_events_without_raising(qapp):
clock = QtSchedulerClock()
clock.pump() # must not raise even with nothing pending
+254
View File
@@ -0,0 +1,254 @@
"""The three chat surfaces really route through the shared service (R03-T04/T05).
The unit suite proves ``RoutingApplicationService`` decides correctly against a
fake router. This file proves the three widgets that used to own a private copy
of that algorithm now call it, on real (offscreen) widgets:
* ``ui/chat_panel.py::_apply_routing`` (Cowork)
* ``ui/co4e_tab.py::_apply_co4e_routing`` (Co4E)
* ``presentation/folder/ai_edit_model_resolver.py::AiEditModelResolver.apply_routing`` (AI-Edit)
On this branch the Manual-mode confirm dialog (``ui/routing_toggle.py::
confirm_switch``) still reads its decision straight off the engine's own
``core/routing/models.py::SwitchDecision`` - ``RoutingOutcome.decision`` passes
it through unwrapped rather than translating it into an application-layer
type, so there is no separate field contract to pin here.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any, List, Optional, Tuple
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.application.model_routing import ( # noqa: E402
RoutingApplicationService,
RoutingMode,
)
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def ctx(qt_app, tmp_path: Path) -> AppContext:
return AppContext(AppConfig.load(tmp_path / "config.json"))
class _FakeDecisionPort:
"""A :class:`RoutingDecisionPort` that always proposes the same switch and
records the surface (and task type) it was asked to evaluate."""
def __init__(self, provider="anthropic", model="claude-sonnet-4-6",
gain: float = 0.4) -> None:
self.provider = provider
self.model = model
self.gain = gain
self.surfaces: List[str] = []
def evaluate(self, request, mode):
from cowork_local.application.model_routing import RouteEvaluation
self.surfaces.append(request.surface)
return RouteEvaluation(
task_type=request.task_type or "coding",
should_switch=True,
target_provider=self.provider,
target_model=self.model,
score_gain=self.gain,
reason="better fit",
)
class _FixedModeResolver:
"""A :class:`ModeResolver` that reports the same mode for every surface."""
def __init__(self, mode: str) -> None:
self._mode = mode
def mode_for(self, surface: str) -> str:
return self._mode
def _install(ctx: AppContext, mode: str) -> _FakeDecisionPort:
"""Wire a fake decision port into the context and force ``mode`` on every
surface.
Every surface reaches the service through
``build_routing_application_service(ctx)``, which memoises its instance on
``ctx._routing_app_service`` (see ``core_routing_adapter.py``) — pre-seeding
that exact attribute is what makes the surfaces under test see this fake
instead of building a real one against ``ctx.routing()``.
"""
router = _FakeDecisionPort()
service = RoutingApplicationService(router, mode_resolver=_FixedModeResolver(mode))
ctx._routing_app_service = service # already-built instance; accessor returns it
return router
# --------------------------------------------------------------------------- #
# Cowork chat
# --------------------------------------------------------------------------- #
def test_cowork_applies_an_auto_switch_to_the_next_turn(ctx):
from cowork_local.ui.cowork_tab import CoworkTab
router = _install(ctx, "auto")
tab = CoworkTab(ctx)
turn: dict = {"bubbles": []}
tab._apply_routing("write a function", turn)
assert router.surfaces == [tab.kind]
# build_provider() honours these for THIS turn only.
assert (tab._routed_provider, tab._routed_model) == ("anthropic", "claude-sonnet-4-6")
assert turn["bubbles"], "the user must be told the model was switched"
def test_cowork_leaves_the_model_alone_when_routing_is_off(ctx):
from cowork_local.ui.cowork_tab import CoworkTab
router = _install(ctx, "off")
tab = CoworkTab(ctx)
turn: dict = {"bubbles": []}
tab._apply_routing("write a function", turn)
assert router.surfaces == []
assert (tab._routed_provider, tab._routed_model) == (None, None)
assert turn["bubbles"] == []
def test_cowork_manual_mode_switches_only_after_the_dialog_approves(ctx, monkeypatch):
"""Manual mode's confirm dialog is ``ui/routing_toggle.py::confirm_switch``,
imported locally inside ``_apply_routing`` at call time — patching the
source module's attribute is what a local import actually re-reads."""
from cowork_local.ui.cowork_tab import CoworkTab
_install(ctx, "manual")
tab = CoworkTab(ctx)
asked: List[Any] = []
def fake_confirm(parent, decision, timeout):
asked.append(decision)
return True
monkeypatch.setattr("cowork_local.ui.routing_toggle.confirm_switch", fake_confirm)
turn: dict = {"bubbles": []}
tab._apply_routing("write a function", turn)
assert len(asked) == 1
assert (tab._routed_provider, tab._routed_model) == ("anthropic", "claude-sonnet-4-6")
def test_cowork_manual_mode_keeps_the_model_when_the_dialog_is_declined(ctx, monkeypatch):
from cowork_local.ui.cowork_tab import CoworkTab
_install(ctx, "manual")
tab = CoworkTab(ctx)
monkeypatch.setattr("cowork_local.ui.routing_toggle.confirm_switch",
lambda parent, decision, timeout: False)
turn: dict = {"bubbles": []}
tab._apply_routing("write a function", turn)
assert (tab._routed_provider, tab._routed_model) == (None, None)
assert turn["bubbles"] == []
def test_a_pinned_admin_agent_still_wins_over_routing(ctx):
"""An explicitly chosen Admin agent pins its own provider/model; routing must
not override a deliberate user choice."""
from cowork_local.ui.cowork_tab import CoworkTab
router = _install(ctx, "auto")
tab = CoworkTab(ctx)
tab._admin_agent = object()
turn: dict = {"bubbles": []}
tab._apply_routing("write a function", turn)
assert router.surfaces == []
assert (tab._routed_provider, tab._routed_model) == (None, None)
# --------------------------------------------------------------------------- #
# Co4E
# --------------------------------------------------------------------------- #
def test_co4e_routes_on_its_own_surface_key_and_returns_the_model(ctx):
from cowork_local.ui.co4e_tab import Co4ETab
router = _install(ctx, "auto")
tab = Co4ETab(ctx)
model = tab._apply_co4e_routing("build me a flow")
assert router.surfaces == ["co4e"]
assert model == "claude-sonnet-4-6"
assert tab._co4e_routed_provider == "anthropic"
def test_co4e_returns_an_empty_model_when_routing_is_off(ctx):
"""'' means "use the provider default" - the contract _run_chat_turn expects."""
from cowork_local.ui.co4e_tab import Co4ETab
_install(ctx, "off")
tab = Co4ETab(ctx)
assert tab._apply_co4e_routing("build me a flow") == ""
assert tab._co4e_routed_provider is None
# --------------------------------------------------------------------------- #
# AI-Edit
# --------------------------------------------------------------------------- #
def test_ai_edit_routes_on_its_own_surface_key(ctx):
"""R08-T12: the routing call this test pins moved from
``ui/folder_tab.py::FolderTab._ai_apply_routing`` to
``presentation/folder/ai_edit_model_resolver.py::AiEditModelResolver.
apply_routing`` - same RoutingApplicationService call, same surface key,
now independently testable without the whole FolderTab widget tree."""
from cowork_local.presentation.folder.folder_tab import FolderTab
router = _install(ctx, "auto")
tab = FolderTab(ctx)
tab.ai_panel.resolver.apply_routing("rename this variable")
assert router.surfaces == ["ai_edit"]
assert (tab.ai_panel.resolver.routed_provider, tab.ai_panel.resolver.routed_model) == (
"anthropic", "claude-sonnet-4-6")
def test_ai_edit_pins_the_coding_task_type(ctx):
"""An edit instruction is never a QA question, so AI-Edit skips
classification entirely - the constraint has to survive the move into the
shared service or it is silently dropped."""
from cowork_local.core.routing.models import TaskType
from cowork_local.presentation.folder.folder_tab import FolderTab
seen: List[Any] = []
class _Recorder(_FakeDecisionPort):
def evaluate(self, request, mode):
seen.append(request.task_type)
return super().evaluate(request, mode)
ctx._routing_app_service = RoutingApplicationService(
_Recorder(), mode_resolver=_FixedModeResolver("auto"))
tab = FolderTab(ctx)
tab.ai_panel.resolver.apply_routing("rename this variable")
assert seen == [TaskType.CODING]
+125
View File
@@ -0,0 +1,125 @@
"""EPIC R08-T11: ScheduleTaskTab shell + KanbanBoardWidget, real Qt offscreen.
Drives the real widgets end to end (build -> refresh -> drag-drop rule via
TaskApplicationService -> refresh) against a tmp_path task repository, the
way ``test_history_dir_race.py`` proves R06-T04 against real Qt rather than
a double. ``TaskApplicationService``'s own business rules are already unit
tested (R07-T04); this file exists to prove the WIDGET is actually wired to
that service, not to re-test the rules themselves.
"""
from __future__ import annotations
import os
from pathlib import Path
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.infrastructure.persistence.json.task_repository_impl import ( # noqa: E402
TaskRepository,
)
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def ctx(qt_app, tmp_path: Path):
return AppContext(AppConfig.load(tmp_path / "config.json"))
@pytest.fixture
def tasks_dir(tmp_path: Path) -> Path:
d = tmp_path / "tasks"
d.mkdir()
return d
def test_schedule_task_tab_builds_and_refreshes_with_no_tasks(ctx, tasks_dir):
from cowork_local.presentation.scheduling.schedule_task_tab import ScheduleTaskTab
tab = ScheduleTaskTab(ctx, scheduler=None, tasks_dir=tasks_dir)
tab.refresh() # must not raise against an empty repo
assert tab.kanban.columns.keys() # 7 lanes were built
def test_kanban_renders_a_task_into_its_status_lane(ctx, tasks_dir):
from cowork_local.presentation.scheduling.kanban_board_widget import KanbanBoardWidget
repo = TaskRepository(tasks_dir)
task = repo.create("My Task", task_type="cowork")
task["status"] = "backlog"
repo.save(task)
board = KanbanBoardWidget(ctx, tasks_dir=tasks_dir)
board.refresh()
from PySide6.QtCore import Qt
backlog_ids = [board.columns["backlog"].item(i).data(Qt.UserRole)
for i in range(board.columns["backlog"].count())]
assert task["task_id"] in backlog_ids
def test_dropping_a_card_on_done_disables_its_schedule_through_the_real_widget(ctx, tasks_dir):
"""Same rule TaskApplicationService.move_to_status covers at the unit
level (R07-T04) — this proves the Kanban widget's drop handler actually
calls it, end to end, with a real TaskRepository on disk."""
from cowork_local.presentation.scheduling.kanban_board_widget import KanbanBoardWidget
repo = TaskRepository(tasks_dir)
task = repo.create("Recurring", task_type="cowork")
task["schedule"]["enabled"] = True
task["schedule"]["run_at"] = "2026-08-28 09:00"
task["schedule"]["repeat_type"] = "daily"
task["status"] = "scheduled"
repo.save(task)
board = KanbanBoardWidget(ctx, tasks_dir=tasks_dir)
board.refresh()
board._on_task_dropped(task["task_id"], "done")
on_disk = repo.get(task["task_id"])
assert on_disk["status"] == "done"
assert on_disk["schedule"]["enabled"] is False
def test_kanban_edit_requested_is_wired_to_the_shells_edit_task(ctx, tasks_dir, monkeypatch):
"""Proves ScheduleTaskTab actually connects
``kanban.edit_requested -> self._edit_task`` (not just that the Kanban
widget emits the signal in isolation) by monkeypatching the dialog class
``_edit_task`` opens and checking it was constructed for the right task."""
import cowork_local.ui.task_editor_dialog as task_editor_dialog_module
from cowork_local.presentation.scheduling.schedule_task_tab import ScheduleTaskTab
repo = TaskRepository(tasks_dir)
task = repo.create("Editable")
repo.save(task)
seen_task_ids = []
class _FakeDialog:
def __init__(self, task, all_tasks, parent, ctx):
seen_task_ids.append(task["task_id"] if task else None)
self.edited_task = None
def exec(self):
return False # Cancel — nothing further should happen
monkeypatch.setattr(task_editor_dialog_module, "TaskEditorDialog", _FakeDialog)
tab = ScheduleTaskTab(ctx, scheduler=None, tasks_dir=tasks_dir)
tab.kanban.edit_requested.emit(task["task_id"])
assert seen_task_ids == [task["task_id"]]
@@ -0,0 +1,162 @@
"""EPIC R08-T14: GraphRenderer / GraphQaWidget / StructureGraphView shell,
real Qt offscreen.
Scope note: a real directory SCAN (``GraphRenderer._scan``) runs on a
``core.worker.AgentWorker`` QThread and had no existing test before this
task either (grep confirms nothing under tests/ exercised
``ui/structure_graph_view.py``). These tests drive ``_render()`` directly
with a hand-built ``StructureGraph`` instead of a live scan — enough to
prove the renderer <-> Q&A wiring (the actual R08-T14 deliverable) without
needing a real codebase to walk.
"""
from __future__ import annotations
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.core.structure_graph import GEdge, GNode, StructureGraph # noqa: E402
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def ctx(qt_app, tmp_path):
return AppContext(AppConfig.load(tmp_path / "config.json"))
def _fake_graph(tmp_path):
f = tmp_path / "mod.py"
f.write_text("def hello():\n pass\n", encoding="utf-8")
nodes = [
GNode(id="n1", label="mod.py", kind="file", detail="a module", path=str(f)),
GNode(id="n2", label="hello", kind="function", detail="says hi", path=str(f)),
]
edges = [GEdge(source="n1", target="n2", type="defines")]
return StructureGraph(nodes=nodes, edges=edges)
def test_structure_graph_view_builds(ctx):
from cowork_local.presentation.graph.structure_graph_view import StructureGraphView
view = StructureGraphView(ctx)
assert view.renderer is not None
assert view.qa is not None
def test_render_populates_the_scene_and_emits_graph_rendered(ctx, tmp_path):
from cowork_local.presentation.graph.graph_renderer import GraphRenderer
renderer = GraphRenderer(ctx)
graph = _fake_graph(tmp_path)
seen = []
renderer.graph_rendered.connect(lambda: seen.append(1))
renderer._render({"graph": graph, "pos": {"n1": (0, 0), "n2": (100, 0)}, "seq": renderer._scan_seq})
assert renderer.graph is graph
assert len(renderer._node_items) == 2
assert seen == [1]
def test_render_ignores_a_stale_scan_result(ctx, tmp_path):
"""Only the LATEST scan's result is ever rendered (no stale overwrite)."""
from cowork_local.presentation.graph.graph_renderer import GraphRenderer
renderer = GraphRenderer(ctx)
first = _fake_graph(tmp_path)
renderer._render({"graph": first, "pos": {}, "seq": renderer._scan_seq})
renderer._scan_seq += 1 # a second scan started
stale = StructureGraph(nodes=[], edges=[])
renderer._render({"graph": stale, "pos": {}, "seq": renderer._scan_seq - 1})
assert renderer.graph is first # stale result was dropped
def test_node_selection_updates_the_qa_detail_panel(ctx, tmp_path):
from cowork_local.presentation.graph.graph_qa_widget import GraphQaWidget
from cowork_local.presentation.graph.graph_renderer import GraphRenderer
renderer = GraphRenderer(ctx)
graph = _fake_graph(tmp_path)
renderer._render({"graph": graph, "pos": {"n1": (0, 0), "n2": (100, 0)}, "seq": renderer._scan_seq})
qa = GraphQaWidget(ctx, renderer)
node = graph.nodes[1]
renderer.node_selected.emit(node)
assert "hello" in qa.detail.toPlainText()
assert "says hi" in qa.detail.toPlainText()
def test_candidate_file_paths_uses_selected_nodes_when_present(ctx, tmp_path):
from cowork_local.presentation.graph.graph_qa_widget import GraphQaWidget
from cowork_local.presentation.graph.graph_renderer import GraphRenderer
renderer = GraphRenderer(ctx)
graph = _fake_graph(tmp_path)
renderer._render({"graph": graph, "pos": {"n1": (0, 0), "n2": (100, 0)}, "seq": renderer._scan_seq})
qa = GraphQaWidget(ctx, renderer)
# No selection -> every file node in the graph (both nodes share one
# file here, so this also proves the path-dedup in _candidate_file_paths).
assert qa._candidate_file_paths() == [graph.nodes[0].path]
renderer._node_items[0].setSelected(True)
assert qa._candidate_file_paths() == [graph.nodes[0].path]
def test_project_change_clears_the_qa_extraction_cache(ctx, tmp_path):
from cowork_local.presentation.graph.graph_qa_widget import GraphQaWidget
from cowork_local.presentation.graph.graph_renderer import GraphRenderer
renderer = GraphRenderer(ctx)
qa = GraphQaWidget(ctx, renderer)
qa._extract_cache = {"some/path.py": "cached text"}
renderer.project_changed.emit()
assert qa._extract_cache == {}
def test_qa_collapse_resizes_the_shells_splitter(ctx):
"""Exact pixel width is Qt's splitter-layout arithmetic, not this code's
concern - what matters is that collapsing narrows the QA pane a lot
(down near the strip's width) while the strip itself becomes visible and
the total splitter width is conserved."""
from cowork_local.presentation.graph.structure_graph_view import StructureGraphView
from cowork_local.ui.widgets import CollapseStrip
view = StructureGraphView(ctx)
before = view._split.sizes()
view.qa._set_collapsed(True)
after = view._split.sizes()
assert after[1] <= CollapseStrip.WIDTH + 2
assert view.qa.maximumWidth() == CollapseStrip.WIDTH + 2
assert sum(after) == sum(before) # total width conserved, just redistributed
def test_hide_event_clears_extracts(ctx):
from cowork_local.presentation.graph.structure_graph_view import StructureGraphView
view = StructureGraphView(ctx)
view.qa._extract_cache = {"x": "y"}
from PySide6.QtGui import QHideEvent
view.hideEvent(QHideEvent())
assert view.qa._extract_cache == {}