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
+4
View File
@@ -14,6 +14,9 @@ def __getattr__(name: str) -> Any:
if name == "FakeToolExecutor":
from .fake_tool_executor import FakeToolExecutor
return FakeToolExecutor
if name == "FakeClock":
from .fake_clock import FakeClock
return FakeClock
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -22,4 +25,5 @@ __all__ = [
"FakeToolExecutor",
"RecordedCall",
"ScriptedTurn",
"FakeClock",
]
+54
View File
@@ -0,0 +1,54 @@
"""FakeClock - offline stand-in for ``platform/qt/qt_scheduler_clock.py::
QtSchedulerClock`` (R07-T03).
``TaskScheduler`` (``core/task_scheduler.py``) needs a clock that can
``start(interval_ms, callback)`` / ``stop()`` / ``pump()``. In production
that's a real ``QTimer``, which means testing dispatch logic (what runs, in
what order, what gets re-armed) would otherwise require a live Qt event loop
ticking every 30 seconds. This double satisfies the same duck-typed
interface with manual control: ``fire()`` calls the scripted callback once,
synchronously, on whichever thread the test is running on - no timers, no
event loop, no waiting.
"""
from __future__ import annotations
from typing import Callable, Optional
class FakeClock:
"""Scriptable stand-in for :class:`QtSchedulerClock`.
Args:
running: whether ``start()`` has been called and ``stop()`` hasn't
since - a test can assert on this to check lifecycle wiring.
pump_count: how many times ``pump()`` was called - lets a test on
``TaskScheduler.stop()``'s drain loop assert the event loop was
actually pumped while waiting for workers.
"""
def __init__(self) -> None:
self._callback: Optional[Callable[[], None]] = None
self.interval_ms: Optional[int] = None
self.running: bool = False
self.pump_count: int = 0
def start(self, interval_ms: int, callback: Callable[[], None]) -> None:
self.interval_ms = interval_ms
self._callback = callback
self.running = True
def stop(self) -> None:
self.running = False
def pump(self) -> None:
self.pump_count += 1
def fire(self) -> None:
"""Test helper: manually trigger one tick, as if the interval had
elapsed. A no-op when the clock isn't running (matches a real
``QTimer`` never firing after ``stop()``)."""
if self.running and self._callback is not None:
self._callback()
__all__ = ["FakeClock"]
+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 == {}
@@ -0,0 +1,87 @@
"""EPIC R07-T05: AiTaskPlannerService — AI-generate + import, no Qt, no network.
``core/ai_task_planner.py::plan_tasks`` and ``core/task_import.py::
import_tasks`` are exercised through a FakeProvider / real tmp files rather
than reimplemented — this service is a seam, not a new planner.
"""
from __future__ import annotations
import json
import pytest
from cowork_local.application.scheduling.ai_task_planner_service import (
AiTaskPlannerService,
)
from tests.fakes import FakeProvider, ScriptedTurn
_PLAN_REPLY = json.dumps({
"tasks": [
{"title": "Draft report", "description": "d", "task_type": "cowork",
"priority": "medium", "schedule": {"enabled": False}}
]
})
def test_plan_uses_the_constructor_injected_provider_factory():
provider = FakeProvider([ScriptedTurn(text=_PLAN_REPLY)])
service = AiTaskPlannerService(provider_factory=lambda: provider)
tasks = service.plan("Write a weekly report")
assert len(tasks) == 1
assert tasks[0]["title"] == "Draft report"
assert provider.call_count == 1
def test_plan_prefers_an_explicit_provider_over_the_factory():
factory_provider = FakeProvider([ScriptedTurn(text=_PLAN_REPLY)], strict=False)
explicit_provider = FakeProvider([ScriptedTurn(text=_PLAN_REPLY)])
service = AiTaskPlannerService(provider_factory=lambda: factory_provider)
service.plan("Write a weekly report", provider=explicit_provider)
assert explicit_provider.call_count == 1
assert factory_provider.call_count == 0
def test_plan_without_any_provider_raises_runtime_error():
service = AiTaskPlannerService(provider_factory=None)
with pytest.raises(RuntimeError):
service.plan("Write a weekly report")
def test_plan_stamps_attachments_onto_every_generated_task():
two_tasks_reply = json.dumps({"tasks": [
{"title": "A", "task_type": "cowork"},
{"title": "B", "task_type": "cowork"},
]})
provider = FakeProvider([ScriptedTurn(text=two_tasks_reply)])
service = AiTaskPlannerService(provider_factory=lambda: provider)
tasks = service.plan("do two things", file_paths=["a.txt"], links=["https://x"])
assert len(tasks) == 2
for t in tasks:
assert t["input"]["file_paths"] == ["a.txt"]
assert t["input"]["links"] == ["https://x"]
def test_import_file_delegates_to_core_task_import(tmp_path):
csv_path = tmp_path / "tasks.csv"
csv_path.write_text("title,task_type,priority\nMy Task,cowork,medium\n", encoding="utf-8")
service = AiTaskPlannerService()
tasks = service.import_file(csv_path)
assert len(tasks) == 1
assert tasks[0]["title"] == "My Task"
def test_import_file_raises_value_error_on_unsupported_extension(tmp_path):
bogus = tmp_path / "tasks.txt"
bogus.write_text("nope", encoding="utf-8")
service = AiTaskPlannerService()
with pytest.raises(ValueError):
service.import_file(bogus)
+103
View File
@@ -0,0 +1,103 @@
"""EPIC R08-T13: DashboardQueryService — no Qt.
``core/usage_tracker.py::USAGE_DIR`` is a module-level constant (not
injectable per-call except through an explicit ``directory=`` kwarg
``load_events`` alone accepts) — this is a pre-existing testability gap the
original ``ui/dashboard_tab.py`` also had (it had zero tests before this
task). Monkeypatching the module attribute is what lets these tests write
usage events without touching the real ``~/.cowork_local/usage/``.
"""
from __future__ import annotations
import json
from datetime import date, timedelta
import pytest
from cowork_local.application.monitoring import DashboardQueryService
from cowork_local.config import AppConfig
from cowork_local.core import usage_tracker as ut
from cowork_local.state import AppContext
@pytest.fixture
def usage_dir(tmp_path, monkeypatch):
d = tmp_path / "usage"
monkeypatch.setattr(ut, "USAGE_DIR", d)
return d
@pytest.fixture
def ctx(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_period_range_is_inclusive_end(usage_dir, ctx):
query = DashboardQueryService(ctx)
start, end = query.period_range("week", 0)
assert start <= end
def test_summary_aggregates_events_in_range(usage_dir, ctx):
today = date.today()
_write_event(usage_dir, today, **{"in": 100, "out": 50})
_write_event(usage_dir, today - timedelta(days=400), **{"in": 999, "out": 999}) # out of range
query = DashboardQueryService(ctx)
summary = query.summary(today, today)
assert len(summary["events"]) == 1
assert summary["stats"]["in"] == 100
assert summary["stats"]["out"] == 50
assert summary["total_cost"] >= 0
def test_summary_empty_range_has_no_events(usage_dir, ctx):
query = DashboardQueryService(ctx)
summary = query.summary(date(2020, 1, 1), date(2020, 1, 1))
assert summary["events"] == []
assert summary["stats"]["total"] == 0
def test_pricing_returns_a_dict_with_currency(usage_dir, ctx):
query = DashboardQueryService(ctx)
pricing = query.pricing()
assert "currency" in pricing
def test_chart_series_returns_points_for_the_granularity(usage_dir, ctx):
today = date.today()
_write_event(usage_dir, today)
query = DashboardQueryService(ctx)
pts = query.chart_series("week", 0, "tokens")
assert len(pts) == 7 # week view = 7 days
assert all(isinstance(p, tuple) and len(p) == 2 for p in pts)
def test_budget_status_none_when_no_budget_set(usage_dir, ctx):
query = DashboardQueryService(ctx)
assert query.budget_status() is None
def test_set_budget_then_status_reflects_it(usage_dir, ctx):
query = DashboardQueryService(ctx)
query.set_budget(100.0, "USD")
status = query.budget_status()
assert status is not None
assert status["amount_usd"] == pytest.approx(100.0)
@@ -0,0 +1,76 @@
"""EPIC R08-T12: pure helpers moved out of ui/folder_tab.py into
application/workspaces/ (file_preview_helpers.py, ai_edit_output.py) — no Qt,
directly unit-testable, unlike when they lived as private module functions
inside the Qt widget file.
"""
from __future__ import annotations
from cowork_local.application.workspaces.ai_edit_output import (
parse_ai_output,
split_code_block,
)
from cowork_local.application.workspaces.file_preview_helpers import (
is_probably_text,
read_text,
)
def test_read_text_returns_file_contents(tmp_path):
f = tmp_path / "a.txt"
f.write_text("hello", encoding="utf-8")
assert read_text(str(f)) == "hello"
def test_read_text_on_missing_file_returns_a_note_not_raise(tmp_path):
result = read_text(str(tmp_path / "missing.txt"))
assert "could not read file" in result
def test_is_probably_text_true_for_utf8(tmp_path):
f = tmp_path / "a.txt"
f.write_text("hello world", encoding="utf-8")
assert is_probably_text(str(f)) is True
def test_is_probably_text_false_for_null_bytes(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"\x00\x01\x02")
assert is_probably_text(str(f)) is False
def test_split_code_block_extracts_fenced_block_and_summary():
text = "Here is the change:\n\n```python\nprint('hi')\n```"
content, summary = split_code_block(text)
assert content == "print('hi')\n"
assert summary == "Here is the change:"
def test_split_code_block_no_fence_returns_none_and_full_text():
content, summary = split_code_block("just prose, no code")
assert content is None
assert summary == "just prose, no code"
def test_parse_ai_output_extracts_file_target():
text = "FILE: new/thing.py\n```python\nx = 1\n```"
target, content, summary, image_gens = parse_ai_output(text)
assert target == "new/thing.py"
assert content == "x = 1\n"
assert image_gens == []
def test_parse_ai_output_extracts_image_gen_directives():
text = ("Adding an illustration.\n"
"IMAGE_GEN: a red fox in a forest => assets/fox.png\n"
"```html\n<img src='assets/fox.png'>\n```")
target, content, summary, image_gens = parse_ai_output(text)
assert image_gens == [("a red fox in a forest", "assets/fox.png")]
assert "IMAGE_GEN" not in summary
def test_parse_ai_output_no_directives_or_code_block():
target, content, summary, image_gens = parse_ai_output("just an answer")
assert target is None
assert content is None
assert image_gens == []
assert summary == "just an answer"
+44
View File
@@ -0,0 +1,44 @@
"""EPIC R08-T14: graph_index_service.py — pure helpers moved out of
ui/structure_graph_view.py, no Qt.
"""
from __future__ import annotations
from cowork_local.application.workspaces.graph_index_service import extract_file_contents
def test_extract_file_contents_reads_text_files(tmp_path):
f = tmp_path / "a.py"
f.write_text("print('hello')\n", encoding="utf-8")
block, cache = extract_file_contents([str(f)], {}, str(tmp_path))
assert "print('hello')" in block
assert str(f) in cache
assert cache[str(f)]
def test_extract_file_contents_reuses_the_cache(tmp_path):
f = tmp_path / "a.txt"
f.write_text("original", encoding="utf-8")
seed_cache = {str(f): "cached content, not re-read"}
block, cache = extract_file_contents([str(f)], seed_cache, str(tmp_path))
assert "cached content, not re-read" in block
def test_extract_file_contents_skips_unreadable_paths_without_raising(tmp_path):
missing = tmp_path / "does-not-exist.txt"
block, cache = extract_file_contents([str(missing)], {}, str(tmp_path))
assert block == ""
def test_extract_file_contents_respects_max_total_budget(tmp_path):
f1 = tmp_path / "a.txt"
f1.write_text("x" * 100, encoding="utf-8")
f2 = tmp_path / "b.txt"
f2.write_text("y" * 100, encoding="utf-8")
block, cache = extract_file_contents([str(f1), str(f2)], {}, str(tmp_path), max_total=50)
assert len(block) < 250 # bounded, not both files in full
+164
View File
@@ -0,0 +1,164 @@
"""EPIC R07-T02: ScheduleCalculator — pure due-time/cron math.
This is the one piece of scheduling logic core/tasks.py's own docstring
claimed was "Qt-free so it can be unit-tested headlessly" but had NO unit
test at all before this task (confirmed by grepping tests/ for
"schedule_calculator"/"compute_next_run"/"cron" — nothing matched). These
tests exercise domain/tasks/schedule_calculator.py directly, with no Qt, no
filesystem, and fake holiday/cron callables so the module stays provably
zero-I/O.
"""
from __future__ import annotations
from datetime import datetime
import pytest
from cowork_local.domain.tasks.schedule_calculator import ScheduleCalculator
def _sched(**overrides):
base = {
"enabled": True,
"run_at": "2026-08-24 09:00", # a Monday
"repeat_type": "none",
"cron_expression": None,
"working_days_only": False,
"skip_holidays": False,
"holiday_country": "VN",
}
base.update(overrides)
return base
def _task(**sched_overrides):
return {"status": "scheduled", "schedule": _sched(**sched_overrides)}
class _FakeCron:
"""A cron stub that fires every day at a fixed hour:minute — enough to
exercise the cron branch without depending on core/cron.py::Cron."""
def __init__(self, expression: str):
if expression == "bad":
raise ValueError("bad cron expression")
self.hour, self.minute = 10, 0
def next_after(self, after: datetime) -> datetime:
candidate = after.replace(hour=self.hour, minute=self.minute, second=0, microsecond=0)
if candidate <= after:
from datetime import timedelta
candidate += timedelta(days=1)
return candidate
def _is_weekend_holiday(date_, country):
# A deterministic fake: only 2026-08-29 (a Saturday) counts as a holiday.
return date_.isoformat() == "2026-08-29"
def test_daily_advances_by_one_day():
calc = ScheduleCalculator()
task = _task(repeat_type="daily")
nxt = calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0))
assert nxt == datetime(2026, 8, 25, 9, 0)
def test_weekly_advances_by_seven_days():
calc = ScheduleCalculator()
task = _task(repeat_type="weekly")
nxt = calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0))
assert nxt == datetime(2026, 8, 31, 9, 0)
def test_monthly_clamps_day_to_shorter_month():
calc = ScheduleCalculator()
task = _task(run_at="2026-01-31 09:00", repeat_type="monthly")
nxt = calc.compute_next_run(task, datetime(2026, 1, 31, 9, 0))
assert nxt == datetime(2026, 2, 28, 9, 0) # Feb 2026 has 28 days
def test_one_shot_repeat_type_none_has_no_next_run():
calc = ScheduleCalculator()
task = _task(repeat_type="none")
assert calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0)) is None
def test_cron_without_injected_factory_returns_none():
"""No make_cron wired in -> a cron schedule simply never produces a next
run, instead of crashing the caller."""
calc = ScheduleCalculator()
task = _task(repeat_type="cron", cron_expression="0 10 * * *")
assert calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0)) is None
def test_cron_uses_injected_factory():
calc = ScheduleCalculator(make_cron=_FakeCron)
task = _task(repeat_type="cron", cron_expression="0 10 * * *")
nxt = calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0))
assert nxt == datetime(2026, 8, 24, 10, 0)
def test_malformed_cron_expression_returns_none_not_raise():
calc = ScheduleCalculator(make_cron=_FakeCron)
task = _task(repeat_type="cron", cron_expression="bad")
assert calc.compute_next_run(task, datetime(2026, 8, 24, 9, 0)) is None
def test_working_days_only_skips_weekend():
calc = ScheduleCalculator()
# 2026-08-28 is a Friday; +1 day (daily) would land on Saturday 08-29.
task = _task(run_at="2026-08-28 09:00", repeat_type="daily", working_days_only=True)
nxt = calc.compute_next_run(task, datetime(2026, 8, 28, 9, 0))
assert nxt.weekday() < 5 # Monday 08-31, not the weekend
def test_skip_holidays_uses_injected_is_holiday():
calc = ScheduleCalculator(is_holiday=_is_weekend_holiday)
# 2026-08-28 (Fri) + 1 day = 2026-08-29, which the fake marks a holiday.
task = _task(run_at="2026-08-28 09:00", repeat_type="daily", skip_holidays=True)
nxt = calc.compute_next_run(task, datetime(2026, 8, 28, 9, 0))
assert nxt == datetime(2026, 8, 30, 9, 0) # skipped past the holiday
def test_skip_holidays_without_injected_is_holiday_degrades_gracefully():
calc = ScheduleCalculator() # no is_holiday wired in
task = _task(run_at="2026-08-28 09:00", repeat_type="daily", skip_holidays=True)
nxt = calc.compute_next_run(task, datetime(2026, 8, 28, 9, 0))
assert nxt == datetime(2026, 8, 29, 9, 0) # no holiday check applied at all
def test_shift_off_excluded_days_moves_weekend_forward():
calc = ScheduleCalculator()
sched = _sched(working_days_only=True)
saturday = datetime(2026, 8, 29, 9, 0)
shifted = calc.shift_off_excluded_days(saturday, sched)
assert shifted.weekday() < 5
assert shifted >= saturday
def test_add_month_end_of_year_rolls_to_january():
calc = ScheduleCalculator()
assert calc.add_month(datetime(2026, 12, 15, 9, 0)) == datetime(2027, 1, 15, 9, 0)
def test_due_tasks_filters_by_status_enabled_and_run_at():
calc = ScheduleCalculator()
now = datetime(2026, 8, 27, 12, 0)
due_now = _task(run_at="2026-08-27 09:00")
due_now["title"] = "due"
future = _task(run_at="2026-08-28 09:00")
future["title"] = "future"
disabled = _task(run_at="2026-08-27 09:00", enabled=False)
disabled["title"] = "disabled"
not_scheduled = _task(run_at="2026-08-27 09:00")
not_scheduled["title"] = "backlog"
not_scheduled["status"] = "backlog"
result = calc.due_tasks([due_now, future, disabled, not_scheduled], now)
assert [t["title"] for t in result] == ["due"]
def test_due_tasks_empty_when_no_tasks():
calc = ScheduleCalculator()
assert calc.due_tasks([], datetime(2026, 8, 27, 12, 0)) == []
+191
View File
@@ -0,0 +1,191 @@
"""EPIC R07-T04: TaskApplicationService — CRUD + dispatch rules, no Qt.
Everything here used to be exercised only by driving the real
``ui/schedule_task_tab.py`` widget (a QListWidget drag gesture, a QMenu
click). These tests drive the same rules directly through the service.
"""
from __future__ import annotations
from cowork_local.application.scheduling.task_application_service import (
TaskApplicationService,
)
from cowork_local.infrastructure.persistence.json import TaskRepository
def _service(tmp_path, run_now=None):
return TaskApplicationService(TaskRepository(tmp_path), run_now=run_now)
def _new_saved_task(repo: TaskRepository, **overrides):
task = repo.create("T", **overrides)
repo.save(task)
return task
def test_run_now_rejects_manual_task_type(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo, task_type="manual")
service = TaskApplicationService(repo, run_now=lambda tid: True)
result = service.run_now(task["task_id"])
assert result.ok is False
assert result.reason == "manual_task"
def test_run_now_without_scheduler_wired_reports_no_scheduler(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo, task_type="cowork")
service = TaskApplicationService(repo, run_now=None)
result = service.run_now(task["task_id"])
assert result.ok is False
assert result.reason == "no_scheduler"
def test_run_now_delegates_to_injected_scheduler(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo, task_type="cowork")
seen = []
service = TaskApplicationService(repo, run_now=lambda tid: seen.append(tid) or True)
result = service.run_now(task["task_id"])
assert result.ok is True
assert seen == [task["task_id"]]
def test_run_now_missing_task_reports_not_found(tmp_path):
service = _service(tmp_path, run_now=lambda tid: True)
result = service.run_now("does-not-exist")
assert result.ok is False
assert result.reason == "not_found"
def test_duplicate_saves_a_copy_with_fresh_identity(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo, description="d")
service = TaskApplicationService(repo)
dup = service.duplicate(task["task_id"])
assert dup is not None
assert dup["task_id"] != task["task_id"]
assert dup["description"] == "d"
assert repo.get(dup["task_id"]) is not None # actually persisted, not just returned
def test_toggle_pause_then_resume_goes_to_backlog(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
service = TaskApplicationService(repo)
paused = service.toggle_pause(task["task_id"])
assert paused["status"] == "paused"
resumed = service.toggle_pause(task["task_id"])
assert resumed["status"] == "backlog"
def test_delete_reports_whether_the_task_existed(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
service = TaskApplicationService(repo)
assert service.delete(task["task_id"]) is True
assert repo.get(task["task_id"]) is None
assert service.delete(task["task_id"]) is False # already gone
def test_bulk_delete_counts_only_tasks_that_existed(tmp_path):
repo = TaskRepository(tmp_path)
a = _new_saved_task(repo)
b = _new_saved_task(repo)
service = TaskApplicationService(repo)
count = service.bulk_delete([a["task_id"], b["task_id"], "ghost-id"])
assert count == 2
assert repo.list() == []
def test_move_to_status_running_task_is_blocked(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
task["status"] = "running"
repo.save(task)
service = TaskApplicationService(repo)
result = service.move_to_status(task["task_id"], "backlog")
assert result.blocked is True
assert repo.get(task["task_id"])["status"] == "running" # untouched
def test_move_to_status_running_lane_dispatches_run_now(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo, task_type="cowork")
seen = []
service = TaskApplicationService(repo, run_now=lambda tid: seen.append(tid) or True)
result = service.move_to_status(task["task_id"], "running")
assert result.ran_now is True
assert result.run_now_result.ok is True
assert seen == [task["task_id"]]
def test_move_to_status_done_disables_the_schedule(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
task["schedule"]["enabled"] = True
task["schedule"]["run_at"] = "2026-08-28 09:00"
repo.save(task)
service = TaskApplicationService(repo)
result = service.move_to_status(task["task_id"], "done")
assert result.task["status"] == "done"
assert result.task["schedule"]["enabled"] is False
assert repo.get(task["task_id"])["schedule"]["enabled"] is False
def test_move_to_status_scheduled_without_run_at_needs_schedule(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo) # fresh task has schedule.run_at = None
service = TaskApplicationService(repo)
result = service.move_to_status(task["task_id"], "scheduled")
assert result.needs_schedule is True
assert repo.get(task["task_id"])["status"] == "scheduled"
assert repo.get(task["task_id"])["schedule"]["enabled"] is False
def test_move_to_status_scheduled_with_run_at_enables_it(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
task["schedule"]["run_at"] = "2026-08-28 09:00"
repo.save(task)
service = TaskApplicationService(repo)
result = service.move_to_status(task["task_id"], "scheduled")
assert result.needs_schedule is False
assert repo.get(task["task_id"])["schedule"]["enabled"] is True
def test_move_to_status_plain_change(tmp_path):
repo = TaskRepository(tmp_path)
task = _new_saved_task(repo)
service = TaskApplicationService(repo)
result = service.move_to_status(task["task_id"], "backlog")
assert result.task["status"] == "backlog"
def test_move_to_status_missing_task_returns_none(tmp_path):
service = _service(tmp_path)
assert service.move_to_status("does-not-exist", "backlog") is None
+70
View File
@@ -0,0 +1,70 @@
"""EPIC R07-T01: TaskRepository + core/tasks.py::save_task atomic write.
The motivating bug: ``core/tasks.py::save_task`` used to
``path.write_text(json.dumps(...))`` — two syscalls, no atomicity, same class
of bug already fixed for projects/conversations at R06-T02. A failure between
the write and the replace must never leave a half-written task JSON file on
disk; that is the one property the crash-injection test exists to pin.
"""
from __future__ import annotations
import json
import pytest
from cowork_local.core.tasks import new_task
from cowork_local.infrastructure.persistence.json import TaskRepository
def test_task_repository_crud_round_trip(tmp_path):
repo = TaskRepository(tmp_path)
task = repo.create("My Task")
repo.save(task)
assert [t["task_id"] for t in repo.list()] == [task["task_id"]]
assert repo.get(task["task_id"])["title"] == "My Task"
task["title"] = "Renamed"
repo.save(task)
assert repo.get(task["task_id"])["title"] == "Renamed"
repo.delete(task["task_id"])
assert repo.get(task["task_id"]) is None
assert repo.list() == []
def test_task_repository_duplicate_keeps_config_resets_identity(tmp_path):
repo = TaskRepository(tmp_path)
task = repo.create("Original", description="d")
repo.save(task)
dup = repo.duplicate(task)
repo.save(dup)
assert dup["task_id"] != task["task_id"]
assert dup["description"] == "d"
assert {t["task_id"] for t in repo.list()} == {task["task_id"], dup["task_id"]}
def test_save_task_never_corrupts_existing_file_on_crash(tmp_path, monkeypatch):
"""Same guarantee as ``test_atomic_write_and_repositories.py``'s crash
test, exercised through ``core/tasks.py::save_task`` directly (not just
through the repository) since that is the function every existing
scheduler/executor call site still uses."""
from cowork_local.core.tasks import save_task, task_path
task = new_task("Stable")
save_task(task, tmp_path)
import cowork_local.infrastructure.persistence.json.atomic_write as mod
def boom(*_a, **_k):
raise OSError("simulated crash between write and replace")
monkeypatch.setattr(mod.os, "replace", boom)
task["title"] = "Corrupted?"
with pytest.raises(OSError):
save_task(task, tmp_path)
on_disk = json.loads(task_path(task["task_id"], tmp_path).read_text(encoding="utf-8"))
assert on_disk["title"] == "Stable"
@@ -0,0 +1,66 @@
"""EPIC R07-T03: TaskScheduler <-> clock wiring, entirely through
tests/fakes/fake_clock.py::FakeClock — no real QTimer, no Qt event loop.
Scope note: this only exercises the clock injection seam (start arms+starts
the clock with `tick`, stop stops it), not the full dispatch/execution
pipeline (`_start` -> `AgentWorker` -> `execute_task`), which needs a real
``ctx``/provider and is exactly the kind of Qt-adjacent, thread-heavy path
better left to an offscreen integration test if/when R08 touches this file
again — recorded here rather than silently left untested.
"""
from __future__ import annotations
from cowork_local.core.task_scheduler import TICK_MS, TaskScheduler
from tests.fakes import FakeClock
def test_start_arms_and_starts_the_injected_clock(tmp_path):
clock = FakeClock()
scheduler = TaskScheduler(ctx=None, tasks_dir=tmp_path, clock=clock)
ticks = []
# Instance-attribute override, set BEFORE start(): TaskScheduler.start()
# reads `self.tick`, which Python resolves to this override rather than
# the class method, so we can count calls without a real due task/ctx.
scheduler.tick = lambda: ticks.append(1)
scheduler.start()
assert clock.running is True
assert clock.interval_ms == TICK_MS
assert ticks == [1] # the catch-up tick() call at startup
def test_clock_fire_drives_another_tick(tmp_path):
clock = FakeClock()
scheduler = TaskScheduler(ctx=None, tasks_dir=tmp_path, clock=clock)
ticks = []
scheduler.tick = lambda: ticks.append(1)
scheduler.start()
clock.fire()
assert ticks == [1, 1]
def test_stop_stops_the_clock(tmp_path):
clock = FakeClock()
scheduler = TaskScheduler(ctx=None, tasks_dir=tmp_path, clock=clock)
scheduler.tick = lambda: None
scheduler.start()
scheduler.stop()
assert clock.running is False
def test_fire_after_stop_does_not_call_tick(tmp_path):
clock = FakeClock()
scheduler = TaskScheduler(ctx=None, tasks_dir=tmp_path, clock=clock)
ticks = []
scheduler.tick = lambda: ticks.append(1)
scheduler.start()
scheduler.stop()
clock.fire()
assert ticks == [1] # only the startup catch-up tick, nothing after stop