## Summary epic r04 - begin refactor ## Change Type - [x] Cowork feature - [ ] Bug fix - [ ] Core AI contribution - [ ] Test / hardening - [ ] Performance - [ ] Documentation ## Related Work Cowork Task: Core Repo: http://34.143.229.138/gitea-admin/fsg-ai-core-assets Core AI Issue: Core Task: Related PR: ## Scope What is intentionally included? What is intentionally NOT included? ## Validation - [ ] Unit tests - [ ] Integration tests - [ ] Manual verification - [ ] Regression check Commands / evidence: ## Security Impact Permission / credential / network / customer data impact: ## Compatibility - [ ] No breaking change - [ ] Breaking change documented ## Reviewer Notes Anything Cowork reviewers should pay attention to. --------- Co-authored-by: Anh Tran Nguyen Minh <anhtnm1@fpt.com> Co-authored-by: Huong Le Thi Thien <huongltt35@fpt.com> Co-authored-by: Nam Pham Dinh Thanh <nampdt@fpt.com> Co-authored-by: Vu Dam Tuan <vudt15@fpt.com> Co-authored-by: Hiep Ha Van <hiephv3@fpt.com> Co-authored-by: Lam Hoang Van <lamhv7@fpt.com> Reviewed-on: #7 Co-authored-by: Duy Le Huu <duylh19@fpt.com>
This commit was merged in pull request #7.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Fast, isolated unit tests for the new 4-tier layers (R01/R03/R04, R10-T01).
|
||||
|
||||
Everything in this folder must run offline, without Qt and without touching the
|
||||
real user config directory, so the whole folder stays well under one second.
|
||||
"""
|
||||
@@ -0,0 +1,209 @@
|
||||
"""R04-T02 — unit tests for the typed agent event stream.
|
||||
|
||||
The events replace the untyped ``{"type": ...}`` dicts the runtime emits today,
|
||||
but ``ui/chat_panel.py::_on_event`` still dispatches on those dicts until R08.
|
||||
So the contract under test is two-sided: each event must be a real typed value
|
||||
AND must serialise back to the exact legacy shape the widget already reads —
|
||||
same wire name, same keys, same optional-key behaviour.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
import pytest
|
||||
from cowork_local.domain.agents.agent_event import (
|
||||
AssistantMessageCompletedEvent,
|
||||
ErrorEvent,
|
||||
HistoryReadyEvent,
|
||||
NoticeEvent,
|
||||
OutputsAddedEvent,
|
||||
OutputsRemovedEvent,
|
||||
PlanStep,
|
||||
PlanUpdatedEvent,
|
||||
ReasoningChunkEvent,
|
||||
TextChunkEvent,
|
||||
ToolCallFinishedEvent,
|
||||
ToolCallStartedEvent,
|
||||
ToolOutputChunkEvent,
|
||||
ToolPreview,
|
||||
TurnCompletedEvent,
|
||||
)
|
||||
from cowork_local.domain.agents.agent_event_codec import from_legacy_dict
|
||||
|
||||
|
||||
# -- base contract --------------------------------------------------------- #
|
||||
def test_events_reject_mutation() -> None:
|
||||
event = TextChunkEvent(delta="hello")
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
event.delta = "goodbye"
|
||||
|
||||
|
||||
# -- legacy wire compatibility --------------------------------------------- #
|
||||
def test_text_chunk_serialises_as_the_legacy_text_event() -> None:
|
||||
assert TextChunkEvent(delta="hi").to_legacy_dict() == {"type": "text", "delta": "hi"}
|
||||
|
||||
|
||||
def test_reasoning_chunk_serialises_as_the_legacy_reasoning_event() -> None:
|
||||
assert ReasoningChunkEvent(delta="hmm").to_legacy_dict() == {
|
||||
"type": "reasoning", "delta": "hmm"}
|
||||
|
||||
|
||||
def test_assistant_message_completed_serialises_as_assistant_done() -> None:
|
||||
# Fires once per provider call, so several times in a tool-using turn — it
|
||||
# is NOT the end of the turn (that is TurnCompletedEvent).
|
||||
assert AssistantMessageCompletedEvent(content="done").to_legacy_dict() == {
|
||||
"type": "assistant_done", "content": "done"}
|
||||
|
||||
|
||||
def test_tool_call_started_serialises_with_the_legacy_id_and_args_keys() -> None:
|
||||
event = ToolCallStartedEvent(
|
||||
call_id="call_1", name="write_file", arguments={"path": "a.md"},
|
||||
preview=ToolPreview(kind="diff", title="Create file: a.md", text="+ hi"),
|
||||
)
|
||||
|
||||
assert event.to_legacy_dict() == {
|
||||
"type": "tool_proposed",
|
||||
"id": "call_1",
|
||||
"name": "write_file",
|
||||
"args": {"path": "a.md"},
|
||||
"preview": {"kind": "diff", "title": "Create file: a.md", "text": "+ hi"},
|
||||
}
|
||||
|
||||
|
||||
def test_tool_call_started_omits_the_preview_when_there_is_none() -> None:
|
||||
event = ToolCallStartedEvent(call_id="call_1", name="read_file")
|
||||
|
||||
assert "preview" not in event.to_legacy_dict()
|
||||
|
||||
|
||||
def test_tool_output_chunk_serialises_as_the_legacy_tool_output_event() -> None:
|
||||
event = ToolOutputChunkEvent(call_id="call_1", name="run_command", delta="line\n")
|
||||
|
||||
assert event.to_legacy_dict() == {
|
||||
"type": "tool_output", "id": "call_1", "name": "run_command", "delta": "line\n"}
|
||||
|
||||
|
||||
def test_tool_call_finished_serialises_as_the_legacy_tool_result_event() -> None:
|
||||
event = ToolCallFinishedEvent(
|
||||
call_id="call_1", name="save_file", ok=True, output="saved",
|
||||
path="C:/out/a.md", produced=["C:/out/b.pptx"],
|
||||
)
|
||||
|
||||
assert event.to_legacy_dict() == {
|
||||
"type": "tool_result",
|
||||
"id": "call_1",
|
||||
"name": "save_file",
|
||||
"ok": True,
|
||||
"output": "saved",
|
||||
"path": "C:/out/a.md",
|
||||
"produced": ["C:/out/b.pptx"],
|
||||
}
|
||||
|
||||
|
||||
def test_tool_call_finished_omits_path_and_produced_when_empty() -> None:
|
||||
# chat_agent only sets these keys when they exist; emitting them as None
|
||||
# would make ``ev.get("path")`` truthy checks read differently downstream.
|
||||
legacy = ToolCallFinishedEvent(call_id="c", name="read_file", ok=True).to_legacy_dict()
|
||||
|
||||
assert "path" not in legacy
|
||||
assert "produced" not in legacy
|
||||
|
||||
|
||||
def test_plan_updated_serialises_steps_back_to_title_status_dicts() -> None:
|
||||
event = PlanUpdatedEvent(steps=(PlanStep(title="Read config", status="done"),
|
||||
PlanStep(title="Patch it", status="running")))
|
||||
|
||||
assert event.to_legacy_dict() == {
|
||||
"type": "plan_set",
|
||||
"steps": [{"title": "Read config", "status": "done"},
|
||||
{"title": "Patch it", "status": "running"}],
|
||||
}
|
||||
|
||||
|
||||
def test_notice_serialises_with_its_level() -> None:
|
||||
assert NoticeEvent(text="reading page 2/9", level="progress").to_legacy_dict() == {
|
||||
"type": "notice", "level": "progress", "text": "reading page 2/9"}
|
||||
|
||||
|
||||
def test_notice_defaults_to_the_info_level() -> None:
|
||||
assert NoticeEvent(text="compacted").to_legacy_dict()["level"] == "info"
|
||||
|
||||
|
||||
def test_outputs_added_and_removed_serialise_their_path_lists() -> None:
|
||||
assert OutputsAddedEvent(paths=("a.md",)).to_legacy_dict() == {
|
||||
"type": "outputs_added", "paths": ["a.md"]}
|
||||
assert OutputsRemovedEvent(paths=("tmp.py",)).to_legacy_dict() == {
|
||||
"type": "outputs_removed", "paths": ["tmp.py"]}
|
||||
|
||||
|
||||
def test_history_ready_serialises_its_session_id() -> None:
|
||||
assert HistoryReadyEvent(session_id="s7").to_legacy_dict() == {
|
||||
"type": "history_ready", "session_id": "s7"}
|
||||
|
||||
|
||||
# -- events introduced by R04 (no legacy consumer) ------------------------- #
|
||||
def test_turn_completed_carries_the_final_answer_and_step_count() -> None:
|
||||
event = TurnCompletedEvent(final_text="all done", steps_used=3)
|
||||
|
||||
assert event.to_legacy_dict() == {
|
||||
"type": "turn_completed", "final_text": "all done", "steps_used": 3,
|
||||
"cancelled": False, "budget_exhausted": False}
|
||||
|
||||
|
||||
def test_error_event_is_fatal_unless_marked_recoverable() -> None:
|
||||
assert ErrorEvent(message="boom").recoverable is False
|
||||
assert ErrorEvent(message="rate limited", recoverable=True).recoverable is True
|
||||
|
||||
|
||||
# -- parsing legacy dicts back into events --------------------------------- #
|
||||
_ROUND_TRIP_CASES = [
|
||||
TextChunkEvent(delta="hi"),
|
||||
ReasoningChunkEvent(delta="hmm"),
|
||||
AssistantMessageCompletedEvent(content="done"),
|
||||
ToolCallStartedEvent(call_id="c", name="run_command", arguments={"command": "ls"},
|
||||
preview=ToolPreview(kind="command", title="Run", text="ls")),
|
||||
ToolCallStartedEvent(call_id="c", name="read_file"),
|
||||
ToolOutputChunkEvent(call_id="c", name="run_command", delta="out"),
|
||||
ToolCallFinishedEvent(call_id="c", name="save_file", ok=True, output="ok",
|
||||
path="a.md", produced=["b.md"]),
|
||||
ToolCallFinishedEvent(call_id="c", name="read_file", ok=False, output="missing"),
|
||||
PlanUpdatedEvent(steps=(PlanStep(title="Step", status="pending"),)),
|
||||
NoticeEvent(text="warned", level="warning"),
|
||||
OutputsAddedEvent(paths=("a.md",)),
|
||||
OutputsRemovedEvent(paths=("tmp.py",)),
|
||||
HistoryReadyEvent(session_id="s7"),
|
||||
TurnCompletedEvent(final_text="done", steps_used=2, cancelled=True),
|
||||
ErrorEvent(message="boom", recoverable=True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", _ROUND_TRIP_CASES, ids=lambda e: type(e).__name__)
|
||||
def test_every_event_survives_a_round_trip_through_the_legacy_dict(event) -> None:
|
||||
assert from_legacy_dict(event.to_legacy_dict()) == event
|
||||
|
||||
|
||||
def test_unknown_event_types_parse_to_none_instead_of_raising() -> None:
|
||||
# Co4E emits its own vocabulary (node_status, stage_text, run_done) which R04
|
||||
# deliberately leaves alone; a bridge must be able to pass those through
|
||||
# untouched rather than crash on them.
|
||||
assert from_legacy_dict({"type": "node_status", "node_id": "n1"}) is None
|
||||
assert from_legacy_dict({"type": ""}) is None
|
||||
assert from_legacy_dict("not a dict") is None
|
||||
|
||||
|
||||
def test_missing_payload_keys_parse_to_empty_values() -> None:
|
||||
# Defensive: a truncated event from an older emitter must not kill the turn.
|
||||
assert from_legacy_dict({"type": "text"}) == TextChunkEvent(delta="")
|
||||
assert from_legacy_dict({"type": "tool_result", "id": "c", "name": "x"}) == (
|
||||
ToolCallFinishedEvent(call_id="c", name="x", ok=False, output=""))
|
||||
|
||||
|
||||
def test_plan_steps_from_legacy_drop_entries_without_a_title() -> None:
|
||||
# normalize_plan_steps already clamps upstream; this only guards the parse
|
||||
# path so a hand-written dict cannot produce a titleless step.
|
||||
event = from_legacy_dict({"type": "plan_set",
|
||||
"steps": [{"title": "Real", "status": "done"}, {"status": "done"}]})
|
||||
|
||||
assert event == PlanUpdatedEvent(steps=(PlanStep(title="Real", status="done"),))
|
||||
@@ -0,0 +1,101 @@
|
||||
"""R04-T03 (a) — unit tests for the value a finished turn returns.
|
||||
|
||||
Two callers need different things out of one turn today:
|
||||
``ui/chat_panel.py::_finalize_turn`` wants the message list, while
|
||||
``core/task_executors.py::_run_agent`` returns a
|
||||
``(answer_text, timed_out, incomplete_reason)`` tuple assembled by hand. This
|
||||
type is what both read instead, so "what happened in that turn?" has one answer
|
||||
with names on it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
import pytest
|
||||
from cowork_local.domain.agents.agent_event import PlanStep, TurnCompletedEvent
|
||||
from cowork_local.domain.agents.agent_result import AgentResult
|
||||
|
||||
|
||||
def test_result_rejects_mutation() -> None:
|
||||
result = AgentResult(steps_used=1)
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
result.steps_used = 2
|
||||
|
||||
|
||||
def test_messages_are_frozen_into_a_tuple() -> None:
|
||||
live = [{"role": "user", "content": "hi"}]
|
||||
|
||||
result = AgentResult(messages=live)
|
||||
live.append({"role": "assistant", "content": "later"})
|
||||
|
||||
assert result.messages == ({"role": "user", "content": "hi"},)
|
||||
|
||||
|
||||
def test_final_text_is_the_last_non_empty_assistant_message() -> None:
|
||||
# A turn ends on a tool message often enough (cancelled mid-loop) that the
|
||||
# answer cannot simply be messages[-1].
|
||||
result = AgentResult(messages=[
|
||||
{"role": "assistant", "content": "first pass"},
|
||||
{"role": "assistant", "content": "the answer"},
|
||||
{"role": "tool", "tool_call_id": "c", "name": "read_file", "content": "..."},
|
||||
])
|
||||
|
||||
assert result.final_text == "the answer"
|
||||
|
||||
|
||||
def test_final_text_skips_a_blank_assistant_message() -> None:
|
||||
result = AgentResult(messages=[
|
||||
{"role": "assistant", "content": "the answer"},
|
||||
{"role": "assistant", "content": " "},
|
||||
])
|
||||
|
||||
assert result.final_text == "the answer"
|
||||
|
||||
|
||||
def test_final_text_is_empty_when_the_model_never_answered() -> None:
|
||||
assert AgentResult(messages=[{"role": "user", "content": "hi"}]).final_text == ""
|
||||
|
||||
|
||||
def test_a_plain_finished_turn_is_ok() -> None:
|
||||
assert AgentResult(messages=[{"role": "assistant", "content": "done"}]).ok is True
|
||||
|
||||
|
||||
def test_a_cancelled_turn_is_not_ok() -> None:
|
||||
assert AgentResult(cancelled=True).ok is False
|
||||
|
||||
|
||||
def test_a_failed_turn_is_not_ok_and_keeps_its_message() -> None:
|
||||
result = AgentResult(error="SecurityBlocked: nope")
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error == "SecurityBlocked: nope"
|
||||
|
||||
|
||||
def test_hitting_the_step_ceiling_is_reported_separately_from_cancelling() -> None:
|
||||
# "Stopped because the safety limit was reached" and "the user pressed Stop"
|
||||
# need different wording in the transcript, so they stay separate flags.
|
||||
result = AgentResult(budget_exhausted=True, steps_used=30)
|
||||
|
||||
assert result.budget_exhausted is True
|
||||
assert result.cancelled is False
|
||||
|
||||
|
||||
def test_result_converts_to_the_turn_completed_event() -> None:
|
||||
result = AgentResult(
|
||||
messages=[{"role": "assistant", "content": "done"}],
|
||||
steps_used=3, cancelled=False, budget_exhausted=True,
|
||||
)
|
||||
|
||||
assert result.to_turn_completed_event() == TurnCompletedEvent(
|
||||
final_text="done", steps_used=3, cancelled=False, budget_exhausted=True)
|
||||
|
||||
|
||||
def test_plan_steps_are_frozen_into_a_tuple() -> None:
|
||||
steps = [PlanStep(title="Draft", status="done")]
|
||||
|
||||
result = AgentResult(plan_steps=steps)
|
||||
steps.append(PlanStep(title="Review"))
|
||||
|
||||
assert result.plan_steps == (PlanStep(title="Draft", status="done"),)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""EPIC R06-T02: atomic JSON writes + the WorkspaceRepository/
|
||||
ConversationRepository facades over core/projects.py and core/history.py.
|
||||
|
||||
The motivating bug: ``core/projects.py::save_project`` used to
|
||||
``path.write_text(json.dumps(...))`` — two syscalls, no atomicity. A failure
|
||||
between them must never leave a half-written file on disk; that is the one
|
||||
property these tests exist to pin.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from cowork_local.infrastructure.persistence.json import (
|
||||
ConversationRepository,
|
||||
WorkspaceRepository,
|
||||
write_json,
|
||||
)
|
||||
from cowork_local.infrastructure.persistence.json.atomic_write import write_json as _write_json
|
||||
|
||||
|
||||
def test_write_json_round_trips(tmp_path):
|
||||
path = tmp_path / "a.json"
|
||||
write_json(path, {"hello": "world", "n": 3})
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == {"hello": "world", "n": 3}
|
||||
|
||||
|
||||
def test_write_json_leaves_no_temp_file_behind(tmp_path):
|
||||
write_json(tmp_path / "a.json", {"x": 1})
|
||||
assert list(tmp_path.iterdir()) == [tmp_path / "a.json"]
|
||||
|
||||
|
||||
def test_a_failed_write_never_corrupts_the_existing_file(tmp_path, monkeypatch):
|
||||
"""The whole point of write-temp-then-replace: if the replace step blows
|
||||
up, the ORIGINAL file must still be there and still be readable — not
|
||||
truncated, not half-written."""
|
||||
path = tmp_path / "a.json"
|
||||
write_json(path, {"version": 1})
|
||||
|
||||
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)
|
||||
with pytest.raises(OSError):
|
||||
write_json(path, {"version": 2})
|
||||
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == {"version": 1}
|
||||
# the abandoned temp file was cleaned up, not left orphaned
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_workspace_repository_crud_round_trip(tmp_path):
|
||||
repo = WorkspaceRepository(tmp_path)
|
||||
project = repo.create("My Project", description="d")
|
||||
|
||||
assert [p.project_id for p in repo.list()] == [project.project_id]
|
||||
|
||||
project.description = "updated"
|
||||
repo.save(project)
|
||||
assert repo.get(project.project_id).description == "updated"
|
||||
|
||||
assert repo.delete(project.project_id) is True
|
||||
assert repo.get(project.project_id) is None
|
||||
|
||||
|
||||
def test_conversation_repository_crud_round_trip(tmp_path):
|
||||
repo = ConversationRepository(tmp_path)
|
||||
session_id = repo.new_session_id()
|
||||
path = repo.save("cowork", session_id, [{"role": "user", "content": "hi"}])
|
||||
|
||||
assert [c["session_id"] for c in repo.list()] == [session_id]
|
||||
|
||||
repo.rename(path, "Renamed")
|
||||
repo.set_pinned(path, True)
|
||||
data = repo.load(path)
|
||||
assert data["title"] == "Renamed"
|
||||
assert data["pinned"] is True
|
||||
|
||||
repo.delete(path)
|
||||
assert repo.list() == []
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Unit tests for the Clean Architecture AST Import Guard (check_imports.py)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from scripts.check_imports import FORBIDDEN_MODULE_PREFIXES, scan_file
|
||||
|
||||
|
||||
def test_clean_python_file_passes(tmp_path: Path) -> None:
|
||||
"""Verify that pure Python code without GUI imports produces 0 violations."""
|
||||
clean_code = """
|
||||
import os
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
@dataclass
|
||||
class UserRequest:
|
||||
id: str
|
||||
prompt: str
|
||||
"""
|
||||
clean_file = tmp_path / "clean_service.py"
|
||||
clean_file.write_text(clean_code, encoding="utf-8")
|
||||
|
||||
violations = scan_file(clean_file, FORBIDDEN_MODULE_PREFIXES)
|
||||
assert len(violations) == 0
|
||||
|
||||
|
||||
def test_forbidden_pyside_import_detected(tmp_path: Path) -> None:
|
||||
"""Verify that PySide6 import is caught with correct line number."""
|
||||
dirty_code = """
|
||||
from dataclasses import dataclass
|
||||
from PySide6.QtWidgets import QWidget
|
||||
|
||||
class BadService:
|
||||
pass
|
||||
"""
|
||||
dirty_file = tmp_path / "bad_service.py"
|
||||
dirty_file.write_text(dirty_code, encoding="utf-8")
|
||||
|
||||
violations = scan_file(dirty_file, FORBIDDEN_MODULE_PREFIXES)
|
||||
assert len(violations) == 1
|
||||
assert violations[0].line_number == 3
|
||||
assert "PySide6" in violations[0].imported_module
|
||||
|
||||
|
||||
def test_forbidden_ui_and_app_import_detected(tmp_path: Path) -> None:
|
||||
"""Verify that importing concrete UI or app modules from domain is caught."""
|
||||
dirty_code = """
|
||||
import ui.chat_panel
|
||||
from app import MainWindow
|
||||
"""
|
||||
dirty_file = tmp_path / "cross_layer_leak.py"
|
||||
dirty_file.write_text(dirty_code, encoding="utf-8")
|
||||
|
||||
violations = scan_file(dirty_file, FORBIDDEN_MODULE_PREFIXES)
|
||||
assert len(violations) == 2
|
||||
modules = [v.imported_module for v in violations]
|
||||
assert "ui.chat_panel" in modules
|
||||
assert "app" in modules
|
||||
@@ -0,0 +1,62 @@
|
||||
"""EPIC R05-T03/T04: ``core/code_agent.py::run_code`` used to gate tool calls
|
||||
with ``if name in (WRITE_TOOLS | MS365_WRITE_TOOLS): gate.request(...)``. This
|
||||
pins that the switch to ``ToolPolicyGateway`` still gates exactly the same
|
||||
calls: ``write_file`` (a WRITE tool) consults the gate; ``list_dir``
|
||||
(read-only) never does.
|
||||
|
||||
Runs the REAL engine (``run_code``) via :class:`FakeProvider`, same approach
|
||||
``tests/characterization/test_run_cowork.py`` uses for the Cowork engine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from cowork_local.core.code_agent import run_code
|
||||
from cowork_local.core.tools import ToolContext
|
||||
from tests.fakes import FakeProvider, ScriptedTurn
|
||||
|
||||
|
||||
class _RecordingGate:
|
||||
def __init__(self, approve: bool):
|
||||
self.approve = approve
|
||||
self.calls: List[Dict[str, Any]] = []
|
||||
|
||||
def request(self, payload: Dict[str, Any]) -> bool:
|
||||
self.calls.append(payload)
|
||||
return self.approve
|
||||
|
||||
|
||||
def _run(tmp_path, provider, gate):
|
||||
ctx = ToolContext(tmp_path)
|
||||
events: List[Dict[str, Any]] = []
|
||||
messages: List[Dict[str, Any]] = [{"role": "user", "content": "do it"}]
|
||||
run_code(provider, messages, ctx, gate, events.append)
|
||||
return events
|
||||
|
||||
|
||||
def test_write_file_consults_the_gate_and_honors_rejection(tmp_path):
|
||||
provider = FakeProvider([
|
||||
ScriptedTurn(tool_calls=[("write_file", {"path": "a.txt", "content": "hi"})]),
|
||||
ScriptedTurn(text="done"),
|
||||
])
|
||||
gate = _RecordingGate(approve=False)
|
||||
events = _run(tmp_path, provider, gate)
|
||||
|
||||
assert len(gate.calls) == 1 and gate.calls[0]["name"] == "write_file"
|
||||
results = [e for e in events if e.get("type") == "tool_result"]
|
||||
assert results[0]["ok"] is False
|
||||
assert not (tmp_path / "a.txt").exists() # rejected, never actually written
|
||||
|
||||
|
||||
def test_read_only_tool_never_consults_the_gate(tmp_path):
|
||||
(tmp_path / "existing.txt").write_text("x", encoding="utf-8")
|
||||
provider = FakeProvider([
|
||||
ScriptedTurn(tool_calls=[("list_dir", {})]),
|
||||
ScriptedTurn(text="done"),
|
||||
])
|
||||
gate = _RecordingGate(approve=False) # would reject if ever asked
|
||||
events = _run(tmp_path, provider, gate)
|
||||
|
||||
assert gate.calls == []
|
||||
results = [e for e in events if e.get("type") == "tool_result"]
|
||||
assert results[0]["ok"] is True
|
||||
@@ -0,0 +1,293 @@
|
||||
"""R04-T03 (b) — the turn loop: composition, tool dispatch, budget, cancel.
|
||||
|
||||
Behaviour that used to be reachable only by running the real widget. Every
|
||||
dependency is a fake from ``tests/fakes/turn_runtime_fakes.py``, so the file
|
||||
runs in milliseconds and each test states one rule of the loop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
from cowork_local.application.conversations.conversation_application_service import (
|
||||
ConversationApplicationService,
|
||||
)
|
||||
from cowork_local.domain.agents.agent_event import (
|
||||
AssistantMessageCompletedEvent,
|
||||
PlanStep,
|
||||
PlanUpdatedEvent,
|
||||
TextChunkEvent,
|
||||
ToolCallFinishedEvent,
|
||||
ToolCallStartedEvent,
|
||||
ToolOutputChunkEvent,
|
||||
ToolPreview,
|
||||
TurnCompletedEvent,
|
||||
)
|
||||
from cowork_local.tests.fakes.turn_runtime_fakes import (
|
||||
FakeModelCall,
|
||||
FakeReply,
|
||||
FakeToolRuntime,
|
||||
events_of_type,
|
||||
make_request,
|
||||
run_turn,
|
||||
tool_turn,
|
||||
)
|
||||
|
||||
|
||||
def _service(model, tools, **overrides) -> ConversationApplicationService:
|
||||
return ConversationApplicationService(model, tools, **overrides)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The happy path.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_a_plain_answer_streams_text_then_reports_the_message_and_the_turn() -> None:
|
||||
model = FakeModelCall([FakeReply(content="Hello there", chunks=["Hello ", "there"])])
|
||||
|
||||
result, events = run_turn(_service(model, FakeToolRuntime()))
|
||||
|
||||
assert [e.delta for e in events_of_type(events, TextChunkEvent)] == ["Hello ", "there"]
|
||||
assert events_of_type(events, AssistantMessageCompletedEvent) == [
|
||||
AssistantMessageCompletedEvent(content="Hello there")]
|
||||
assert events_of_type(events, TurnCompletedEvent) == [
|
||||
TurnCompletedEvent(final_text="Hello there", steps_used=1)]
|
||||
assert result.final_text == "Hello there"
|
||||
assert result.ok is True
|
||||
|
||||
|
||||
def test_the_composed_user_message_is_appended_before_the_first_call() -> None:
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
request = make_request(prompt="ship it", instruction_prefix="RULES",
|
||||
session_notes="earlier: a.md",
|
||||
messages=[{"role": "user", "content": "previous"}])
|
||||
|
||||
run_turn(_service(model, FakeToolRuntime()), request)
|
||||
|
||||
sent = model.calls[0]["messages"]
|
||||
assert sent[-1] == {"role": "user",
|
||||
"content": "RULES\n\n---\n\nship it\n\nearlier: a.md"}
|
||||
assert sent[-2] == {"role": "user", "content": "previous"}
|
||||
|
||||
|
||||
def test_attachments_are_read_when_the_turn_runs_not_when_it_was_built() -> None:
|
||||
# Extraction can pip-install a parser or shell out to LibreOffice, so it must
|
||||
# happen here (worker thread), not while the UI was assembling the request.
|
||||
seen: List[Tuple[str, Tuple[str, ...]]] = []
|
||||
|
||||
def reader(prompt: str, attachments: Tuple[str, ...]) -> str:
|
||||
seen.append((prompt, attachments))
|
||||
return f"{prompt}\n\n<contents of {len(attachments)} file(s)>"
|
||||
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
request = make_request(prompt="summarise", attachments=["a.docx", "b.pdf"])
|
||||
|
||||
run_turn(_service(model, FakeToolRuntime(), attachment_reader=reader), request)
|
||||
|
||||
assert seen == [("summarise", ("a.docx", "b.pdf"))]
|
||||
assert "contents of 2 file(s)" in model.calls[0]["messages"][-1]["content"]
|
||||
|
||||
|
||||
def test_the_prompt_preparer_is_told_which_tools_the_turn_advertises() -> None:
|
||||
# The system prompt gains an MS365 paragraph only when ms365__* tools are
|
||||
# present, so the preparer has to see the real list.
|
||||
seen: List[Tuple[str, ...]] = []
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
tools = FakeToolRuntime(specs=("save_file", "ms365__send_mail"))
|
||||
|
||||
run_turn(_service(model, tools,
|
||||
prepare_prompt=lambda messages, names: seen.append(names)))
|
||||
|
||||
assert seen == [("save_file", "ms365__send_mail")]
|
||||
|
||||
|
||||
def test_only_the_allowed_tools_are_advertised() -> None:
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
tools = FakeToolRuntime(specs=("save_file", "run_command", "update_plan"))
|
||||
|
||||
run_turn(_service(model, tools), make_request(allowed_tools=("save_file", "update_plan")))
|
||||
|
||||
assert model.calls[0]["tool_names"] == ["save_file", "update_plan"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Tool dispatch.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def tool_turn(tool_name: str = "save_file", args=None, **tool_kwargs):
|
||||
"""A turn that calls one tool, then answers."""
|
||||
calls = [{"id": "c1", "name": tool_name, "arguments": args or {"filename": "a.md"}}]
|
||||
model = FakeModelCall([FakeReply(content="working", tool_calls=calls),
|
||||
FakeReply(content="done")])
|
||||
return model, FakeToolRuntime(**tool_kwargs)
|
||||
|
||||
|
||||
def test_a_tool_call_is_announced_executed_and_answered_in_the_message_list() -> None:
|
||||
model, tools = tool_turn(results={"save_file": {"ok": True, "output": "saved",
|
||||
"path": "out/a.md"}})
|
||||
|
||||
result, events = run_turn(_service(model, tools))
|
||||
|
||||
assert events_of_type(events, ToolCallStartedEvent) == [ToolCallStartedEvent(
|
||||
call_id="c1", name="save_file", arguments={"filename": "a.md"},
|
||||
preview=ToolPreview(kind="info", title="save_file", text="{'filename': 'a.md'}"))]
|
||||
assert events_of_type(events, ToolCallFinishedEvent) == [ToolCallFinishedEvent(
|
||||
call_id="c1", name="save_file", ok=True, output="saved", path="out/a.md")]
|
||||
assert tools.executed == [("save_file", {"filename": "a.md"})]
|
||||
assert result.messages[-2] == {"role": "tool", "tool_call_id": "c1",
|
||||
"name": "save_file", "content": "saved"}
|
||||
|
||||
|
||||
def test_live_tool_output_is_streamed_while_the_tool_runs() -> None:
|
||||
model, tools = tool_turn("run_command", {"command": "ls"})
|
||||
tools.emit_output = "file-a\n"
|
||||
|
||||
_, events = run_turn(_service(model, tools))
|
||||
|
||||
assert events_of_type(events, ToolOutputChunkEvent) == [ToolOutputChunkEvent(
|
||||
call_id="c1", name="run_command", delta="file-a\n")]
|
||||
|
||||
|
||||
def test_the_loop_ends_as_soon_as_the_model_stops_calling_tools() -> None:
|
||||
model, tools = tool_turn()
|
||||
|
||||
result, _ = run_turn(_service(model, tools))
|
||||
|
||||
assert result.steps_used == 2
|
||||
assert result.budget_exhausted is False
|
||||
|
||||
|
||||
def test_the_plan_tool_reports_a_plan_update_and_no_tool_bubble() -> None:
|
||||
calls = [{"id": "c1", "name": "update_plan",
|
||||
"arguments": {"steps": [{"title": "Draft", "status": "running"}]}}]
|
||||
model = FakeModelCall([FakeReply(content="planning", tool_calls=calls), FakeReply(content="done")])
|
||||
tools = FakeToolRuntime(results={"update_plan": {
|
||||
"ok": True, "output": "Plan updated.",
|
||||
"plan_steps": [PlanStep(title="Draft", status="running")]}})
|
||||
|
||||
result, events = run_turn(_service(model, tools))
|
||||
|
||||
assert events_of_type(events, PlanUpdatedEvent) == [
|
||||
PlanUpdatedEvent(steps=(PlanStep(title="Draft", status="running"),))]
|
||||
assert events_of_type(events, ToolCallStartedEvent) == []
|
||||
assert events_of_type(events, ToolCallFinishedEvent) == []
|
||||
assert result.plan_steps == (PlanStep(title="Draft", status="running"),)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Budget, cancellation.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_running_out_of_steps_is_flagged_and_announced() -> None:
|
||||
# The model keeps calling tools forever; the ceiling must stop it visibly.
|
||||
forever = [FakeReply(content=f"step {i}",
|
||||
tool_calls=[{"id": f"c{i}", "name": "save_file", "arguments": {}}])
|
||||
for i in range(5)]
|
||||
model = FakeModelCall(forever)
|
||||
|
||||
result, events = run_turn(_service(model, FakeToolRuntime()), make_request(max_steps=2))
|
||||
|
||||
assert result.steps_used == 2
|
||||
assert result.budget_exhausted is True
|
||||
assert "2-step safety limit" in events_of_type(events, TextChunkEvent)[-1].delta
|
||||
# The note reaches the transcript but NOT the stored answer: a turn that hits
|
||||
# the ceiling always ends on a tool message, and the existing runtime only
|
||||
# merges the note when the last message is the assistant's. Pinned here so a
|
||||
# future change to that rule is a deliberate decision, not a silent drift.
|
||||
assert result.final_text == "step 1"
|
||||
|
||||
|
||||
def test_run_to_completion_uses_the_higher_ceiling() -> None:
|
||||
forever = [FakeReply(content="x", tool_calls=[{"id": "c", "name": "save_file", "arguments": {}}])
|
||||
for _ in range(6)]
|
||||
model = FakeModelCall(forever)
|
||||
|
||||
result, _ = run_turn(_service(model, FakeToolRuntime()),
|
||||
make_request(max_steps=2, completion_max_steps=5, run_to_completion=True))
|
||||
|
||||
assert result.steps_used == 5
|
||||
|
||||
|
||||
def test_a_turn_cancelled_before_it_starts_never_calls_the_model() -> None:
|
||||
model = FakeModelCall([FakeReply(content="never")])
|
||||
|
||||
result, events = run_turn(_service(model, FakeToolRuntime()), cancel=lambda: True)
|
||||
|
||||
assert model.calls == []
|
||||
assert result.cancelled is True
|
||||
assert result.budget_exhausted is False
|
||||
assert events_of_type(events, TurnCompletedEvent) == [TurnCompletedEvent(cancelled=True)]
|
||||
|
||||
|
||||
def test_cancelling_during_a_turn_stops_dispatching_the_remaining_tool_calls() -> None:
|
||||
calls = [{"id": "c1", "name": "save_file", "arguments": {}},
|
||||
{"id": "c2", "name": "save_file", "arguments": {}}]
|
||||
model = FakeModelCall([FakeReply(content="two tools", tool_calls=calls)])
|
||||
tools = FakeToolRuntime()
|
||||
stop = {"now": False}
|
||||
|
||||
def cancel() -> bool:
|
||||
return stop["now"]
|
||||
|
||||
original_execute = tools.execute
|
||||
|
||||
def execute(name, args, on_output=None, cancel=None):
|
||||
stop["now"] = True # cancel raised while the first tool runs
|
||||
return original_execute(name, args, on_output=on_output, cancel=cancel)
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
result, _ = run_turn(_service(model, tools), cancel=cancel)
|
||||
|
||||
assert len(tools.executed) == 1
|
||||
assert result.cancelled is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Bring-your-own working list.
|
||||
#
|
||||
# ``ui/chat_panel.py`` holds the turn's message list in its own turn context and
|
||||
# reads it WHILE the worker appends (``_reattach_running_turn`` replays the steps
|
||||
# done so far when the user reopens a running conversation; ``_finalize_turn``
|
||||
# slices it by ``snapshot_len``). A service that built its own private list would
|
||||
# silently break both, so a caller can hand its list over instead.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_a_caller_supplied_list_is_appended_to_in_place() -> None:
|
||||
model, tools = tool_turn()
|
||||
live: List[Dict[str, Any]] = [{"role": "user", "content": "already composed"}]
|
||||
|
||||
result = ConversationApplicationService(model, tools).execute(
|
||||
make_request(), lambda event: None, messages=live)
|
||||
|
||||
roles = [m["role"] for m in live]
|
||||
assert roles == ["user", "assistant", "tool", "assistant"]
|
||||
assert result.messages == tuple(live)
|
||||
|
||||
|
||||
def test_a_caller_supplied_list_is_used_as_is_without_recomposing_the_prompt() -> None:
|
||||
# The widget already applied the skill prefix and the session notes when it
|
||||
# built its message; composing again would duplicate them.
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
user = {"role": "user", "content": "already composed"}
|
||||
live = [user]
|
||||
|
||||
ConversationApplicationService(model, FakeToolRuntime()).execute(
|
||||
make_request(prompt="typed text", instruction_prefix="RULES",
|
||||
session_notes="notes"),
|
||||
lambda event: None, messages=live)
|
||||
|
||||
assert live[0] is user
|
||||
assert live[0]["content"] == "already composed"
|
||||
assert [m["role"] for m in live].count("user") == 1
|
||||
|
||||
|
||||
def test_a_caller_supplied_list_skips_the_attachment_reader() -> None:
|
||||
# Reading the attachments is what produced the caller's message in the first
|
||||
# place; doing it again would re-parse every file.
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
calls: List[Any] = []
|
||||
|
||||
ConversationApplicationService(
|
||||
model, FakeToolRuntime(),
|
||||
attachment_reader=lambda prompt, attachments: calls.append(prompt) or prompt,
|
||||
).execute(make_request(attachments=["a.docx"]), lambda event: None,
|
||||
messages=[{"role": "user", "content": "composed"}])
|
||||
|
||||
assert calls == []
|
||||
@@ -0,0 +1,132 @@
|
||||
"""R04-T01 — unit tests for the immutable turn snapshot.
|
||||
|
||||
The snapshot exists so a turn already running cannot be altered by the UI the
|
||||
user keeps clicking on. These tests pin exactly that: the object refuses
|
||||
mutation, it copies the mutable collections handed to it at submit time, and it
|
||||
owns the prompt-composition rules that were inline in
|
||||
``ui/chat_panel.py::_start_turn``'s worker closure (prefix separator, session
|
||||
notes, model-switch review note).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import FrozenInstanceError
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from cowork_local.domain.agents.conversation_execution_request import (
|
||||
ConversationExecutionRequest,
|
||||
)
|
||||
|
||||
|
||||
def _request(**overrides) -> ConversationExecutionRequest:
|
||||
"""A minimal valid request; each test overrides only what it exercises."""
|
||||
base = {"turn_id": "t1", "session_id": "s1"}
|
||||
base.update(overrides)
|
||||
return ConversationExecutionRequest(**base)
|
||||
|
||||
|
||||
# -- immutability ---------------------------------------------------------- #
|
||||
def test_request_rejects_mutation_after_construction() -> None:
|
||||
request = _request(model="gpt-4o-mini")
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
request.model = "claude-sonnet-4-6"
|
||||
|
||||
|
||||
def test_turn_id_is_required() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
ConversationExecutionRequest(turn_id="", session_id="s1")
|
||||
|
||||
|
||||
def test_session_id_is_required() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
ConversationExecutionRequest(turn_id="t1", session_id="")
|
||||
|
||||
|
||||
# -- snapshotting mutable UI state ---------------------------------------- #
|
||||
def test_attachments_are_snapshotted_away_from_the_caller_list() -> None:
|
||||
picked = ["a.docx"]
|
||||
|
||||
request = _request(attachments=picked)
|
||||
picked.append("b.pdf") # the composer clears/refills its own list next turn
|
||||
|
||||
assert request.attachments == ("a.docx",)
|
||||
|
||||
|
||||
def test_messages_are_snapshotted_away_from_the_live_history_list() -> None:
|
||||
history = [{"role": "user", "content": "earlier"}]
|
||||
|
||||
request = _request(messages=history)
|
||||
history.append({"role": "assistant", "content": "later"})
|
||||
|
||||
assert len(request.messages) == 1
|
||||
assert isinstance(request.messages, tuple)
|
||||
|
||||
|
||||
def test_allowed_tools_none_means_every_tool_stays_available() -> None:
|
||||
# None and () must stay distinguishable: None = no restriction, () = deny
|
||||
# every built-in tool. Coercing None to () would silently disarm the agent.
|
||||
assert _request().allowed_tools is None
|
||||
assert _request(allowed_tools=[]).allowed_tools == ()
|
||||
|
||||
|
||||
def test_output_paths_accept_strings_and_normalise_to_path() -> None:
|
||||
request = _request(output_dir="out/t1", home_output_root="out")
|
||||
|
||||
assert request.output_dir == Path("out/t1")
|
||||
assert request.home_output_root == Path("out")
|
||||
|
||||
|
||||
# -- derived turn policy --------------------------------------------------- #
|
||||
def test_effective_max_steps_uses_the_interactive_cap_by_default() -> None:
|
||||
assert _request(max_steps=30, completion_max_steps=200).effective_max_steps == 30
|
||||
|
||||
|
||||
def test_effective_max_steps_lifts_the_cap_when_running_to_completion() -> None:
|
||||
request = _request(max_steps=30, completion_max_steps=200, run_to_completion=True)
|
||||
|
||||
assert request.effective_max_steps == 200
|
||||
|
||||
|
||||
def test_permission_gate_is_required_only_in_confirm_mode() -> None:
|
||||
assert _request(gate_mode="confirm").requires_permission_gate is True
|
||||
assert _request(gate_mode="auto").requires_permission_gate is False
|
||||
|
||||
|
||||
def test_has_prompt_ignores_whitespace_only_input() -> None:
|
||||
assert _request(prompt=" \n ").has_prompt is False
|
||||
assert _request(prompt="do it").has_prompt is True
|
||||
|
||||
|
||||
# -- prompt composition (moved out of the widget's worker closure) --------- #
|
||||
def test_user_content_returns_the_body_unchanged_without_prefix_or_notes() -> None:
|
||||
assert _request().user_content("the body") == "the body"
|
||||
|
||||
|
||||
def test_user_content_separates_the_instruction_prefix_from_the_body() -> None:
|
||||
request = _request(instruction_prefix="SKILL RULES")
|
||||
|
||||
assert request.user_content("the body") == "SKILL RULES\n\n---\n\nthe body"
|
||||
|
||||
|
||||
def test_user_content_appends_session_notes_after_the_body() -> None:
|
||||
request = _request(session_notes="Files produced earlier: a.md")
|
||||
|
||||
assert request.user_content("the body") == "the body\n\nFiles produced earlier: a.md"
|
||||
|
||||
|
||||
def test_user_content_falls_back_to_session_notes_when_the_body_is_empty() -> None:
|
||||
# An attachment-only turn has no typed text, so the notes must not be
|
||||
# prefixed with a stray blank line.
|
||||
request = _request(session_notes="Files produced earlier: a.md")
|
||||
|
||||
assert request.user_content("") == "Files produced earlier: a.md"
|
||||
|
||||
|
||||
def test_user_content_puts_the_review_note_ahead_of_everything_else() -> None:
|
||||
request = _request(instruction_prefix="SKILL RULES", review_note="[Note: switched]")
|
||||
|
||||
content = request.user_content("the body")
|
||||
|
||||
assert content == "[Note: switched]\n\nSKILL RULES\n\n---\n\nthe body"
|
||||
@@ -0,0 +1,210 @@
|
||||
"""R04-T03 (b) — the turn loop: guards, permission gate, compaction, cleanup.
|
||||
|
||||
Split out of ``test_conversation_application_service.py`` to keep each file
|
||||
inside the 400-LOC limit. Same fakes, same service; this half pins the ORDER of
|
||||
the safety steps (guard before model, guard before execute, gate before execute)
|
||||
and the promise that the output sandbox is tidied on the way out.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import pytest
|
||||
from cowork_local.application.conversations.conversation_application_service import (
|
||||
ConversationApplicationService,
|
||||
)
|
||||
from cowork_local.domain.agents.agent_event import (
|
||||
ErrorEvent,
|
||||
OutputsAddedEvent,
|
||||
ReasoningChunkEvent,
|
||||
TextChunkEvent,
|
||||
ToolCallFinishedEvent,
|
||||
)
|
||||
from cowork_local.tests.fakes.turn_runtime_fakes import (
|
||||
FakeModelCall,
|
||||
FakeReply,
|
||||
FakeToolRuntime,
|
||||
events_of_type,
|
||||
make_request,
|
||||
run_turn,
|
||||
tool_turn,
|
||||
)
|
||||
|
||||
|
||||
def _service(model, tools, **overrides) -> ConversationApplicationService:
|
||||
return ConversationApplicationService(model, tools, **overrides)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Guards and the permission gate.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_the_prompt_guard_runs_before_the_model_is_ever_called() -> None:
|
||||
order: List[str] = []
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
model_call = model.call
|
||||
|
||||
def call(*a, **kw):
|
||||
order.append("model")
|
||||
return model_call(*a, **kw)
|
||||
|
||||
model.call = call
|
||||
|
||||
run_turn(_service(model, FakeToolRuntime(), prompt_guard=lambda messages: order.append("guard")))
|
||||
|
||||
assert order == ["guard", "model"]
|
||||
|
||||
|
||||
def test_a_blocked_prompt_propagates_before_the_output_folder_is_touched() -> None:
|
||||
model = FakeModelCall([FakeReply(content="never")])
|
||||
tools = FakeToolRuntime()
|
||||
events: List[Any] = []
|
||||
|
||||
def guard(messages) -> None:
|
||||
raise RuntimeError("SecurityBlocked: nope")
|
||||
|
||||
service = _service(model, tools, prompt_guard=guard)
|
||||
|
||||
with pytest.raises(RuntimeError, match="SecurityBlocked"):
|
||||
service.execute(make_request(), events.append)
|
||||
|
||||
assert model.calls == []
|
||||
assert events_of_type(events, ErrorEvent) == [ErrorEvent(message="SecurityBlocked: nope")]
|
||||
# Cleanup is NOT a read-only operation (it deletes a stale .scratch and every
|
||||
# empty sub-folder), so a turn rejected before it started must not run it.
|
||||
assert tools.finalize_calls == []
|
||||
|
||||
|
||||
def test_output_cleanup_still_runs_when_the_turn_fails_mid_loop() -> None:
|
||||
# Once the turn has started producing files, the sandbox must be tidied on
|
||||
# the way out no matter how the turn ends.
|
||||
model = FakeModelCall([RuntimeError("gateway exploded")])
|
||||
tools = FakeToolRuntime()
|
||||
events: List[Any] = []
|
||||
|
||||
with pytest.raises(RuntimeError, match="gateway exploded"):
|
||||
_service(model, tools).execute(make_request(), events.append)
|
||||
|
||||
assert tools.finalize_calls == [{"before": "before", "cancelled": False}]
|
||||
assert events_of_type(events, ErrorEvent) == [ErrorEvent(message="gateway exploded")]
|
||||
|
||||
|
||||
def test_the_command_guard_runs_before_the_tool_executes() -> None:
|
||||
order: List[str] = []
|
||||
model, tools = tool_turn("run_command", {"command": "ls"})
|
||||
original = tools.execute
|
||||
|
||||
def execute(name, args, on_output=None, cancel=None):
|
||||
order.append("execute")
|
||||
return original(name, args, on_output=on_output, cancel=cancel)
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
run_turn(_service(model, tools,
|
||||
command_guard=lambda name, args: order.append(f"guard:{name}")))
|
||||
|
||||
assert order == ["guard:run_command", "execute"]
|
||||
|
||||
|
||||
def test_disabling_rule_enforcement_skips_both_guards() -> None:
|
||||
# Co4E flow steps run inside the workspace sandbox and opt out on purpose.
|
||||
calls: List[str] = []
|
||||
model, tools = tool_turn("run_command", {"command": "ls"})
|
||||
|
||||
run_turn(_service(model, tools,
|
||||
prompt_guard=lambda messages: calls.append("prompt"),
|
||||
command_guard=lambda name, args: calls.append("command")),
|
||||
make_request(enforce_rules=False))
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_the_permission_gate_is_asked_only_for_command_tools() -> None:
|
||||
asked: List[str] = []
|
||||
model, tools = tool_turn("save_file", {"filename": "a.md"})
|
||||
|
||||
run_turn(_service(model, tools,
|
||||
permission_request=lambda action: asked.append(action["name"]) or True),
|
||||
make_request(gate_mode="confirm"))
|
||||
|
||||
assert asked == [] # save_file writes into the sandbox: never gated
|
||||
|
||||
|
||||
def test_a_command_tool_in_confirm_mode_asks_before_running() -> None:
|
||||
asked: List[Dict[str, Any]] = []
|
||||
model, tools = tool_turn("run_command", {"command": "ls"})
|
||||
|
||||
def approve(action: Dict[str, Any]) -> bool:
|
||||
asked.append(action)
|
||||
return True
|
||||
|
||||
run_turn(_service(model, tools, permission_request=approve), make_request(gate_mode="confirm"))
|
||||
|
||||
assert [a["name"] for a in asked] == ["run_command"]
|
||||
assert tools.executed == [("run_command", {"command": "ls"})]
|
||||
|
||||
|
||||
def test_a_rejected_command_is_reported_as_a_failed_tool_and_never_runs() -> None:
|
||||
model, tools = tool_turn("run_command", {"command": "rm -rf /"})
|
||||
|
||||
result, events = run_turn(_service(model, tools, permission_request=lambda action: False),
|
||||
make_request(gate_mode="confirm"))
|
||||
|
||||
assert tools.executed == []
|
||||
assert events_of_type(events, ToolCallFinishedEvent) == [ToolCallFinishedEvent(
|
||||
call_id="c1", name="run_command", ok=False, output="Rejected by user.")]
|
||||
assert result.messages[-2]["content"] == "Rejected by user."
|
||||
|
||||
|
||||
def test_auto_mode_never_asks_even_for_a_command() -> None:
|
||||
model, tools = tool_turn("run_command", {"command": "ls"})
|
||||
|
||||
def refuse(action): # would block the turn if it were consulted
|
||||
raise AssertionError("the gate must not be consulted in auto mode")
|
||||
|
||||
run_turn(_service(model, tools, permission_request=refuse), make_request(gate_mode="auto"))
|
||||
|
||||
assert tools.executed == [("run_command", {"command": "ls"})]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Context compaction, reasoning, output cleanup.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_the_conversation_is_offered_for_compaction_before_every_call() -> None:
|
||||
compactions: List[int] = []
|
||||
model, tools = tool_turn()
|
||||
|
||||
run_turn(_service(model, tools,
|
||||
compact=lambda messages, cancel: compactions.append(len(messages))))
|
||||
|
||||
assert len(compactions) == 2 # once per provider call
|
||||
|
||||
|
||||
def test_reasoning_is_streamed_as_its_own_event() -> None:
|
||||
model = FakeModelCall([FakeReply(content="42", reasoning="thinking...")])
|
||||
|
||||
_, events = run_turn(_service(model, FakeToolRuntime()))
|
||||
|
||||
assert events_of_type(events, ReasoningChunkEvent) == [ReasoningChunkEvent(delta="thinking...")]
|
||||
|
||||
|
||||
def test_a_reasoning_only_reply_gets_a_visible_note_in_the_transcript() -> None:
|
||||
# Otherwise a Schedule Task run reads back an empty answer and writes
|
||||
# "(no output)" into its report.
|
||||
model = FakeModelCall([FakeReply(content="", reasoning="thought hard")])
|
||||
|
||||
result, events = run_turn(_service(model, FakeToolRuntime()))
|
||||
|
||||
assert "only its reasoning" in events_of_type(events, TextChunkEvent)[-1].delta
|
||||
assert "only its reasoning" in result.final_text
|
||||
|
||||
|
||||
def test_promoted_and_discarded_output_files_are_reported_at_the_end() -> None:
|
||||
model = FakeModelCall([FakeReply(content="ok")])
|
||||
tools = FakeToolRuntime(added=("out/report.pptx",))
|
||||
|
||||
_, events = run_turn(_service(model, tools))
|
||||
|
||||
assert events_of_type(events, OutputsAddedEvent) == [
|
||||
OutputsAddedEvent(paths=("out/report.pptx",))]
|
||||
assert tools.finalize_calls == [{"before": "before", "cancelled": False}]
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Unit tests for the adapters that bridge the routing engine to the app service.
|
||||
|
||||
The integration suite covers the happy path over the real engine; this file pins
|
||||
the translation edge cases that are hard to provoke there — malformed task
|
||||
types, a missing ranking, and the service-caching contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from cowork_local.application.model_routing import (
|
||||
AppContextModeResolver,
|
||||
CoreRoutingEngine,
|
||||
RoutingApplicationService,
|
||||
RoutingMode,
|
||||
RoutingRequest,
|
||||
)
|
||||
from cowork_local.application.model_routing.core_routing_adapter import (
|
||||
build_routing_application_service,
|
||||
)
|
||||
from cowork_local.core.routing.models import SwitchDecision, SwitchMode, TaskType
|
||||
|
||||
|
||||
class FakeRanking:
|
||||
"""Just enough of ``selector.Ranking`` for the adapter's usability check."""
|
||||
|
||||
def __init__(self, scores) -> None:
|
||||
self._scores = dict(scores)
|
||||
|
||||
def score_of(self, key: str) -> float:
|
||||
return self._scores.get(key, 0.0)
|
||||
|
||||
|
||||
class FakeRouteResult:
|
||||
"""Stands in for ``core.routing.service.RouteResult``."""
|
||||
|
||||
def __init__(self, decision, task_type=TaskType.CODING, ranking=None, target=None) -> None:
|
||||
self.decision = decision
|
||||
self.task_type = task_type
|
||||
self.ranking = ranking
|
||||
self._target = target
|
||||
|
||||
@property
|
||||
def should_switch(self) -> bool:
|
||||
return self.decision.should_switch
|
||||
|
||||
def target(self):
|
||||
return self._target
|
||||
|
||||
|
||||
class FakeRoutingService:
|
||||
"""Records the arguments the adapter forwards to the engine."""
|
||||
|
||||
def __init__(self, result: FakeRouteResult) -> None:
|
||||
self.result = result
|
||||
self.calls: list = []
|
||||
|
||||
def route(self, surface, prompt, current_provider, current_model, **kwargs):
|
||||
self.calls.append({"surface": surface, "prompt": prompt,
|
||||
"current_provider": current_provider,
|
||||
"current_model": current_model, **kwargs})
|
||||
return self.result
|
||||
|
||||
|
||||
def make_decision(**overrides) -> SwitchDecision:
|
||||
fields = dict(
|
||||
should_switch=True,
|
||||
from_model="anthropic/weak-model",
|
||||
to_model="anthropic/strong-model",
|
||||
score_gain=0.3,
|
||||
reason="coding fit 0.9 > current 0.6",
|
||||
mode=SwitchMode.AUTO,
|
||||
task_type="coding",
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SwitchDecision(**fields)
|
||||
|
||||
|
||||
def make_request(**overrides) -> RoutingRequest:
|
||||
fields = dict(surface="cowork", prompt="Fix this bug",
|
||||
current_provider="anthropic", current_model="weak-model")
|
||||
fields.update(overrides)
|
||||
return RoutingRequest(**fields)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CoreRoutingEngine translation
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_engine_flattens_the_route_result() -> None:
|
||||
"""No ``core.routing`` type may leak past the adapter — the application
|
||||
service and the widgets only ever see plain fields."""
|
||||
service = FakeRoutingService(FakeRouteResult(
|
||||
make_decision(),
|
||||
ranking=FakeRanking({"anthropic/weak-model": 0.6}),
|
||||
target=("anthropic", "strong-model"),
|
||||
))
|
||||
|
||||
evaluation = CoreRoutingEngine(service).evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert evaluation.task_type == "coding" # str, not TaskType
|
||||
assert evaluation.should_switch is True
|
||||
assert evaluation.target_provider == "anthropic"
|
||||
assert evaluation.target_model == "strong-model"
|
||||
assert evaluation.score_gain == pytest.approx(0.3)
|
||||
assert evaluation.current_is_usable is True
|
||||
|
||||
|
||||
def test_engine_forwards_the_mode_as_a_plain_string() -> None:
|
||||
"""``RoutingService.route`` takes the mode as a string; handing it an enum
|
||||
would silently fall through to its "unknown mode -> off" branch."""
|
||||
service = FakeRoutingService(FakeRouteResult(make_decision(should_switch=False)))
|
||||
|
||||
CoreRoutingEngine(service).evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert service.calls[0]["mode_override"] == "auto"
|
||||
|
||||
|
||||
def test_engine_reports_an_unranked_model_as_unusable() -> None:
|
||||
"""This is the signal Fallback acts on: absent from the ranking means the
|
||||
selector already rejected it (unavailable / no probe / failed probe)."""
|
||||
service = FakeRoutingService(FakeRouteResult(
|
||||
make_decision(),
|
||||
ranking=FakeRanking({"anthropic/strong-model": 0.9}), # current is absent
|
||||
target=("anthropic", "strong-model"),
|
||||
))
|
||||
|
||||
evaluation = CoreRoutingEngine(service).evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert evaluation.current_is_usable is False
|
||||
|
||||
|
||||
def test_engine_assumes_usable_without_a_ranking() -> None:
|
||||
"""No ranking (routing off, or the engine's own error path) is absence of
|
||||
evidence — it must not trigger a surprise Fallback switch."""
|
||||
service = FakeRoutingService(FakeRouteResult(make_decision(), ranking=None))
|
||||
|
||||
evaluation = CoreRoutingEngine(service).evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert evaluation.current_is_usable is True
|
||||
|
||||
|
||||
def test_engine_assumes_usable_when_the_ranking_misbehaves() -> None:
|
||||
"""A broken ranking object must not fail the turn."""
|
||||
class BrokenRanking:
|
||||
def score_of(self, key):
|
||||
raise RuntimeError("corrupt ranking")
|
||||
|
||||
service = FakeRoutingService(FakeRouteResult(make_decision(), ranking=BrokenRanking()))
|
||||
|
||||
evaluation = CoreRoutingEngine(service).evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert evaluation.current_is_usable is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw, expected",
|
||||
[("coding", TaskType.CODING), ("QA", TaskType.QA), (None, None), ("nonsense", None)],
|
||||
)
|
||||
def test_task_type_strings_are_coerced_or_dropped(raw, expected) -> None:
|
||||
"""A pinned task type is honoured; an unknown one falls back to letting the
|
||||
engine classify the prompt rather than raising mid-turn."""
|
||||
service = FakeRoutingService(FakeRouteResult(make_decision(should_switch=False)))
|
||||
|
||||
CoreRoutingEngine(service).evaluate(make_request(task_type=raw), RoutingMode.AUTO)
|
||||
|
||||
assert service.calls[0]["task_type"] == expected
|
||||
|
||||
|
||||
def test_required_capabilities_are_passed_as_a_list_or_none() -> None:
|
||||
"""``rank_models`` filters on a list; an empty tuple must become None so it
|
||||
is treated as "no filter" rather than "require nothing, but filter"."""
|
||||
service = FakeRoutingService(FakeRouteResult(make_decision(should_switch=False)))
|
||||
engine = CoreRoutingEngine(service)
|
||||
|
||||
engine.evaluate(make_request(required_capabilities=("vision",)), RoutingMode.AUTO)
|
||||
engine.evaluate(make_request(), RoutingMode.AUTO)
|
||||
|
||||
assert service.calls[0]["required_capabilities"] == ["vision"]
|
||||
assert service.calls[1]["required_capabilities"] is None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Mode resolver + wiring
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_mode_resolver_reads_the_per_workspace_mode() -> None:
|
||||
"""Per-workspace routing keeps working now that the lookup left the widgets."""
|
||||
class StubCtx:
|
||||
def project_routing_mode(self, surface):
|
||||
return "fallback" if surface == "co4e" else "off"
|
||||
|
||||
resolver = AppContextModeResolver(StubCtx())
|
||||
|
||||
assert resolver.mode_for("co4e") is RoutingMode.FALLBACK
|
||||
assert resolver.mode_for("cowork") is RoutingMode.OFF
|
||||
|
||||
|
||||
def test_service_is_built_once_and_cached_on_the_context() -> None:
|
||||
"""Every surface must share one instance, so future per-surface state (a
|
||||
cool-down, a switch history) is shared rather than duplicated per widget."""
|
||||
class StubCtx:
|
||||
def __init__(self):
|
||||
self.routing_calls = 0
|
||||
self.config = type("Cfg", (), {"routing": {"confirm_timeout_sec": 45}})()
|
||||
|
||||
def routing(self):
|
||||
self.routing_calls += 1
|
||||
return FakeRoutingService(FakeRouteResult(make_decision(should_switch=False)))
|
||||
|
||||
def project_routing_mode(self, surface):
|
||||
return "off"
|
||||
|
||||
ctx = StubCtx()
|
||||
first = build_routing_application_service(ctx)
|
||||
second = build_routing_application_service(ctx)
|
||||
|
||||
assert first is second
|
||||
assert ctx.routing_calls == 1
|
||||
assert isinstance(first, RoutingApplicationService)
|
||||
# The confirm timeout is read from config at call time, not frozen at build.
|
||||
assert first.confirm_timeout() == pytest.approx(45.0)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""EPIC R05-T04: before this change, ``core/chat_agent.py::run_cowork`` called
|
||||
``extra_executor(name, args)`` directly for any MCP/connector tool — no
|
||||
permission check at all, regardless of the "confirm before running commands"
|
||||
setting. This pins the fix: an extra tool now goes through the same
|
||||
``ToolPolicyGateway`` as ``run_command``, using the conservative default
|
||||
capability (``UNKNOWN_SOURCE_CAPABILITIES``) since MCP tools carry no
|
||||
standard risk metadata.
|
||||
|
||||
Runs the real engine via :class:`FakeProvider`, matching
|
||||
``tests/characterization/test_run_cowork.py``'s approach.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from cowork_local.core.chat_agent import run_cowork
|
||||
from cowork_local.providers.base import ToolSpec
|
||||
from tests.fakes import FakeProvider, ScriptedTurn
|
||||
|
||||
|
||||
class _RecordingGate:
|
||||
def __init__(self, approve: bool):
|
||||
self.approve = approve
|
||||
self.calls: List[Dict[str, Any]] = []
|
||||
|
||||
def request(self, payload: Dict[str, Any]) -> bool:
|
||||
self.calls.append(payload)
|
||||
return self.approve
|
||||
|
||||
|
||||
_EXTRA_SPEC = ToolSpec(name="github__delete_repo", description="", parameters={"type": "object"})
|
||||
|
||||
|
||||
def _run(tmp_path, provider, gate, executed: List[str]):
|
||||
events: List[Dict[str, Any]] = []
|
||||
messages: List[Dict[str, Any]] = [{"role": "user", "content": "hi"}]
|
||||
|
||||
def extra_executor(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
|
||||
executed.append(name)
|
||||
return {"ok": True, "output": "done"}
|
||||
|
||||
run_cowork(provider, messages, tmp_path, events.append, gate=gate,
|
||||
extra_tools=[_EXTRA_SPEC], extra_executor=extra_executor)
|
||||
return events
|
||||
|
||||
|
||||
def test_mcp_style_tool_is_rejected_without_ever_calling_the_executor(tmp_path):
|
||||
provider = FakeProvider([
|
||||
ScriptedTurn(tool_calls=[("github__delete_repo", {})]),
|
||||
ScriptedTurn(text="done"),
|
||||
])
|
||||
gate = _RecordingGate(approve=False)
|
||||
executed: List[str] = []
|
||||
events = _run(tmp_path, provider, gate, executed)
|
||||
|
||||
assert len(gate.calls) == 1 and gate.calls[0]["name"] == "github__delete_repo"
|
||||
assert executed == [] # rejected BEFORE the extra_executor ever ran
|
||||
results = [e for e in events if e.get("type") == "tool_result"]
|
||||
assert results[0]["ok"] is False
|
||||
|
||||
|
||||
def test_mcp_style_tool_runs_once_approved(tmp_path):
|
||||
provider = FakeProvider([
|
||||
ScriptedTurn(tool_calls=[("github__delete_repo", {})]),
|
||||
ScriptedTurn(text="done"),
|
||||
])
|
||||
gate = _RecordingGate(approve=True)
|
||||
executed: List[str] = []
|
||||
events = _run(tmp_path, provider, gate, executed)
|
||||
|
||||
assert executed == ["github__delete_repo"]
|
||||
results = [e for e in events if e.get("type") == "tool_result"]
|
||||
assert results[0]["ok"] is True
|
||||
|
||||
|
||||
def test_no_gate_preserves_auto_run_for_extra_tools(tmp_path):
|
||||
"""``gate=None`` is Cowork's existing "no confirmation configured" state —
|
||||
must still auto-run, exactly like before this EPIC."""
|
||||
provider = FakeProvider([
|
||||
ScriptedTurn(tool_calls=[("github__delete_repo", {})]),
|
||||
ScriptedTurn(text="done"),
|
||||
])
|
||||
executed: List[str] = []
|
||||
events = _run(tmp_path, provider, None, executed)
|
||||
|
||||
assert executed == ["github__delete_repo"]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""R04-T04 — unit tests for the UI-state -> request mapping.
|
||||
|
||||
Three small rules used to sit inline in ``ui/cowork_tab.py::build_job``, where no
|
||||
test could reach them: the turn's prompt is the last message in the working list,
|
||||
the history is everything before it, and the confirm-commands flag becomes a gate
|
||||
mode. Getting any of them wrong is silent (a duplicated user message, a command
|
||||
that stops asking for approval), so they are pinned here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from cowork_local.application.conversations.cowork_turn_request import (
|
||||
build_cowork_turn_request,
|
||||
)
|
||||
|
||||
|
||||
def _build(**overrides):
|
||||
base = {
|
||||
"turn_id": "t3",
|
||||
"session_id": "s1",
|
||||
"messages": [{"role": "user", "content": "make me a report"}],
|
||||
}
|
||||
base.update(overrides)
|
||||
return build_cowork_turn_request(**base)
|
||||
|
||||
|
||||
def test_the_last_message_becomes_the_prompt_and_the_rest_the_history() -> None:
|
||||
request = _build(messages=[
|
||||
{"role": "user", "content": "earlier"},
|
||||
{"role": "assistant", "content": "sure"},
|
||||
{"role": "user", "content": "now this"},
|
||||
])
|
||||
|
||||
assert request.prompt == "now this"
|
||||
assert request.messages == ({"role": "user", "content": "earlier"},
|
||||
{"role": "assistant", "content": "sure"})
|
||||
|
||||
|
||||
def test_an_empty_working_list_yields_an_empty_prompt() -> None:
|
||||
# Defensive: a turn with no message at all must not raise on messages[-1].
|
||||
request = _build(messages=[])
|
||||
|
||||
assert request.prompt == ""
|
||||
assert request.messages == ()
|
||||
|
||||
|
||||
def test_confirming_commands_puts_the_turn_in_confirm_gate_mode() -> None:
|
||||
assert _build(confirm_commands=True).gate_mode == "confirm"
|
||||
assert _build(confirm_commands=False).gate_mode == "auto"
|
||||
assert _build().gate_mode == "auto" # auto-run is the default
|
||||
|
||||
|
||||
def test_the_captured_widget_state_is_carried_into_the_request() -> None:
|
||||
request = _build(
|
||||
surface="cowork", project_id="p7", title="Weekly report",
|
||||
provider_id="anthropic", model="claude-sonnet-4-6",
|
||||
instructions="PROJECT RULES", output_dir="out/.turns/t3",
|
||||
home_output_root="out", agent_role="cowork",
|
||||
)
|
||||
|
||||
assert (request.turn_id, request.session_id) == ("t3", "s1")
|
||||
assert (request.surface, request.project_id, request.title) == \
|
||||
("cowork", "p7", "Weekly report")
|
||||
assert (request.provider_id, request.model) == ("anthropic", "claude-sonnet-4-6")
|
||||
assert request.project_context == "PROJECT RULES"
|
||||
assert request.output_dir == Path("out/.turns/t3")
|
||||
assert request.home_output_root == Path("out")
|
||||
assert request.agent_role == "cowork"
|
||||
|
||||
|
||||
def test_the_prompt_survives_a_message_whose_content_is_missing() -> None:
|
||||
request = _build(messages=[{"role": "user"}])
|
||||
|
||||
assert request.prompt == ""
|
||||
@@ -0,0 +1,107 @@
|
||||
"""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):
|
||||
import sys
|
||||
d = tmp_path / "usage"
|
||||
for mod in list(sys.modules.values()):
|
||||
if mod is not None and getattr(mod, "__name__", "").endswith("usage_tracker") and hasattr(mod, "USAGE_DIR"):
|
||||
monkeypatch.setattr(mod, "USAGE_DIR", d)
|
||||
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, directory=usage_dir)
|
||||
start, end = query.period_range("week", 0)
|
||||
assert start <= end
|
||||
|
||||
|
||||
def test_summary_aggregates_events_in_range(usage_dir, ctx):
|
||||
test_day = date(2025, 6, 15)
|
||||
_write_event(usage_dir, test_day, **{"in": 100, "out": 50})
|
||||
_write_event(usage_dir, test_day - timedelta(days=400), **{"in": 999, "out": 999}) # out of range
|
||||
query = DashboardQueryService(ctx, directory=usage_dir)
|
||||
|
||||
summary = query.summary(test_day, test_day)
|
||||
|
||||
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, directory=usage_dir)
|
||||
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, directory=usage_dir)
|
||||
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, directory=usage_dir)
|
||||
|
||||
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, directory=usage_dir)
|
||||
assert query.budget_status() is None
|
||||
|
||||
|
||||
def test_set_budget_then_status_reflects_it(usage_dir, ctx):
|
||||
query = DashboardQueryService(ctx, directory=usage_dir)
|
||||
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,51 @@
|
||||
"""EPIC R06-T03: ExecutionWorkspace names the output-dir/scratch-dir split
|
||||
that already exists in ``core/chat_agent.py`` (``.scratch`` under the
|
||||
workspace root) without changing where anything lands."""
|
||||
from __future__ import annotations
|
||||
|
||||
from cowork_local.domain.workspaces import WorkspaceSession
|
||||
from cowork_local.infrastructure.filesystem.execution_workspace import ExecutionWorkspace
|
||||
|
||||
|
||||
def test_output_dir_is_the_workspace_root_itself(tmp_path):
|
||||
session = WorkspaceSession.unscoped(tmp_path)
|
||||
workspace = ExecutionWorkspace(session, turn_id="turn-1")
|
||||
|
||||
assert workspace.output_dir == tmp_path
|
||||
|
||||
|
||||
def test_scratch_dir_matches_the_existing_flat_convention(tmp_path):
|
||||
"""core/chat_agent.py::_cleanup_cowork_intermediates operates on
|
||||
``output_dir / ".scratch"`` with no per-turn subfolder — this must agree,
|
||||
or cleanup_scratch() would target a directory nothing ever wrote to."""
|
||||
session = WorkspaceSession.unscoped(tmp_path)
|
||||
workspace = ExecutionWorkspace(session, turn_id="turn-1")
|
||||
|
||||
assert workspace.scratch_dir == tmp_path / ".scratch"
|
||||
|
||||
|
||||
def test_ensure_dirs_creates_both_folders(tmp_path):
|
||||
session = WorkspaceSession.unscoped(tmp_path / "root")
|
||||
workspace = ExecutionWorkspace(session, turn_id="t")
|
||||
workspace.ensure_dirs()
|
||||
|
||||
assert workspace.output_dir.is_dir()
|
||||
assert workspace.scratch_dir.is_dir()
|
||||
|
||||
|
||||
def test_cleanup_scratch_removes_it_and_leaves_output_dir_alone(tmp_path):
|
||||
session = WorkspaceSession.unscoped(tmp_path)
|
||||
workspace = ExecutionWorkspace(session, turn_id="t")
|
||||
workspace.ensure_dirs()
|
||||
(workspace.scratch_dir / "helper.py").write_text("print(1)", encoding="utf-8")
|
||||
(workspace.output_dir / "deliverable.txt").write_text("done", encoding="utf-8")
|
||||
|
||||
workspace.cleanup_scratch()
|
||||
|
||||
assert not workspace.scratch_dir.exists()
|
||||
assert (workspace.output_dir / "deliverable.txt").exists()
|
||||
|
||||
|
||||
def test_cleanup_scratch_is_a_no_op_when_never_created(tmp_path):
|
||||
workspace = ExecutionWorkspace(WorkspaceSession.unscoped(tmp_path), turn_id="t")
|
||||
workspace.cleanup_scratch() # must not raise
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Unit tests for FakeProvider and FakeToolExecutor test doubles."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from providers.base import ProviderError
|
||||
from tests.fakes.fake_provider import FakeProvider
|
||||
from tests.fakes.fake_tool_executor import FakeToolExecutor
|
||||
|
||||
|
||||
def test_fake_provider_text_streaming() -> None:
|
||||
"""Verify that FakeProvider streams text chunks to on_text callback."""
|
||||
provider = FakeProvider()
|
||||
provider.queue_response(content="Hello world", chunks=["Hello ", "world"])
|
||||
|
||||
streamed: list[str] = []
|
||||
response = provider.chat(
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
on_text=lambda piece: streamed.append(piece),
|
||||
)
|
||||
|
||||
assert response["role"] == "assistant"
|
||||
assert response["content"] == "Hello world"
|
||||
assert "".join(streamed) == "Hello world"
|
||||
assert provider.call_count == 1
|
||||
|
||||
|
||||
def test_fake_provider_tool_calls_and_reasoning() -> None:
|
||||
"""Verify reasoning streaming and tool_calls payload emission."""
|
||||
provider = FakeProvider()
|
||||
tool_call = {
|
||||
"id": "call_123",
|
||||
"name": "save_file",
|
||||
"arguments": {"filename": "out.txt", "content": "data"},
|
||||
}
|
||||
provider.queue_response(
|
||||
content="Creating file",
|
||||
tool_calls=[tool_call],
|
||||
reasoning="User wants output in a file",
|
||||
)
|
||||
|
||||
reasoning_chunks: list[str] = []
|
||||
response = provider.chat(
|
||||
messages=[{"role": "user", "content": "Save to out.txt"}],
|
||||
on_reasoning=lambda piece: reasoning_chunks.append(piece),
|
||||
)
|
||||
|
||||
assert response["content"] == "Creating file"
|
||||
assert response["tool_calls"] == [tool_call]
|
||||
assert reasoning_chunks == ["User wants output in a file"]
|
||||
|
||||
|
||||
def test_fake_provider_error_injection() -> None:
|
||||
"""Verify that queued exceptions are raised on demand."""
|
||||
provider = FakeProvider()
|
||||
provider.queue_error(ProviderError("Rate limit exceeded (429)"))
|
||||
|
||||
with pytest.raises(ProviderError, match="Rate limit exceeded"):
|
||||
provider.chat(messages=[{"role": "user", "content": "Hi"}])
|
||||
|
||||
|
||||
def test_fake_provider_cancellation() -> None:
|
||||
"""Verify that cancellation stops execution immediately."""
|
||||
provider = FakeProvider()
|
||||
provider.queue_response(content="Long reply", chunks=["Part 1", "Part 2"])
|
||||
|
||||
is_cancelled = False
|
||||
|
||||
def cancel_fn() -> bool:
|
||||
return is_cancelled
|
||||
|
||||
is_cancelled = True
|
||||
with pytest.raises(ProviderError, match="aborted by user cancel"):
|
||||
provider.chat(
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
cancel=cancel_fn,
|
||||
)
|
||||
|
||||
|
||||
def test_fake_tool_executor() -> None:
|
||||
"""Verify that FakeToolExecutor records calls and returns expected mock outputs."""
|
||||
executor = FakeToolExecutor()
|
||||
executor.set_mock_response("read_file", {"ok": True, "content": "file contents"})
|
||||
executor.register_handler("calc", lambda args: {"ok": True, "result": args.get("a", 0) + args.get("b", 0)})
|
||||
|
||||
res1 = executor.execute("read_file", {"path": "test.txt"})
|
||||
assert res1["ok"] is True
|
||||
assert res1["content"] == "file contents"
|
||||
|
||||
res2 = executor.execute("calc", {"a": 5, "b": 10})
|
||||
assert res2["result"] == 15
|
||||
|
||||
assert len(executor.call_log) == 2
|
||||
assert executor.get_calls_for("calc")[0]["args"] == {"a": 5, "b": 10}
|
||||
@@ -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"
|
||||
@@ -0,0 +1,62 @@
|
||||
"""EPIC R06-T05: FileWorkspaceService gives File Explorer / AI Editor the
|
||||
same safe file operations the agent tool loop already has, via the SAME
|
||||
``core/tools.py::execute_tool`` dispatch (not a reimplementation)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from cowork_local.application.workspaces import FileWorkspaceService
|
||||
from cowork_local.domain.workspaces import WorkspaceSession
|
||||
|
||||
|
||||
def _service(tmp_path) -> FileWorkspaceService:
|
||||
return FileWorkspaceService(WorkspaceSession.unscoped(tmp_path))
|
||||
|
||||
|
||||
def test_write_then_read_round_trips(tmp_path):
|
||||
service = _service(tmp_path)
|
||||
written = service.write_file("notes.md", "# Hello")
|
||||
assert written["ok"] is True
|
||||
|
||||
read = service.read_preview("notes.md")
|
||||
assert read == {"ok": True, "output": "# Hello"}
|
||||
|
||||
|
||||
def test_list_tree_reflects_written_files(tmp_path):
|
||||
service = _service(tmp_path)
|
||||
service.write_file("a.txt", "x")
|
||||
listing = service.list_tree()
|
||||
assert listing["ok"] is True and "a.txt" in listing["output"]
|
||||
|
||||
|
||||
def test_apply_edit_uses_the_context_anchored_replace(tmp_path):
|
||||
service = _service(tmp_path)
|
||||
service.write_file("code.py", "value = 1\n")
|
||||
edited = service.apply_edit("code.py", "value = 1", "value = 2")
|
||||
assert edited["ok"] is True
|
||||
assert service.read_preview("code.py")["output"].strip() == "value = 2"
|
||||
|
||||
|
||||
def test_apply_edit_reports_ambiguous_match_like_the_agent_tool_does(tmp_path):
|
||||
service = _service(tmp_path)
|
||||
service.write_file("code.py", "x = 1\nx = 1\n")
|
||||
edited = service.apply_edit("code.py", "x = 1", "x = 2")
|
||||
assert edited["ok"] is False
|
||||
assert "appears" in edited["output"]
|
||||
|
||||
|
||||
def test_path_escape_is_refused_not_a_crash(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(tmp_path / "outside.txt").write_text("secret", encoding="utf-8")
|
||||
service = FileWorkspaceService(WorkspaceSession.unscoped(workspace))
|
||||
|
||||
result = service.read_preview("../outside.txt")
|
||||
assert result["ok"] is False
|
||||
assert "outside the working folder" in result["output"]
|
||||
|
||||
|
||||
def test_write_preserves_subfolders_unlike_cowork_flatten_writes(tmp_path):
|
||||
"""File Explorer must not collapse a write into the workspace root the
|
||||
way Cowork's agent context does (flatten_writes=True there, False here)."""
|
||||
service = _service(tmp_path)
|
||||
service.write_file("sub/dir/file.txt", "content")
|
||||
assert (tmp_path / "sub" / "dir" / "file.txt").read_text(encoding="utf-8") == "content"
|
||||
@@ -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
|
||||
@@ -0,0 +1,106 @@
|
||||
"""EPIC R05-T05: the MCP connection lifecycle extracted out of
|
||||
``state.py::AppContext`` into :class:`McpToolSourceManager`.
|
||||
|
||||
Uses a fake connection (no real subprocess/asyncio loop) so these tests run in
|
||||
milliseconds and don't depend on any actual MCP server being installed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from cowork_local.infrastructure.mcp import McpToolSourceManager
|
||||
|
||||
|
||||
class _FakeConnection:
|
||||
"""Stands in for ``core.mcp_client.McpServerConnection`` — tracks
|
||||
start/stop calls instead of spawning anything."""
|
||||
|
||||
instances: List["_FakeConnection"] = []
|
||||
|
||||
def __init__(self, name: str, command: str, args: Optional[List[str]] = None,
|
||||
env: Optional[Dict[str, str]] = None):
|
||||
self.name = name
|
||||
self.command = command
|
||||
self.args = args
|
||||
self.env = env
|
||||
self.started = False
|
||||
self.stopped = False
|
||||
self._alive = True
|
||||
_FakeConnection.instances.append(self)
|
||||
|
||||
def start(self) -> None:
|
||||
self.started = True
|
||||
|
||||
def stop(self) -> None:
|
||||
self.stopped = True
|
||||
self._alive = False
|
||||
|
||||
def is_alive(self) -> bool:
|
||||
return self._alive
|
||||
|
||||
|
||||
def _manager() -> McpToolSourceManager:
|
||||
_FakeConnection.instances.clear()
|
||||
return McpToolSourceManager(connection_factory=_FakeConnection)
|
||||
|
||||
|
||||
def test_ensure_starts_once_and_caches_the_live_connection():
|
||||
mgr = _manager()
|
||||
first = mgr.ensure("github", "npx", ["-y", "github-mcp"])
|
||||
second = mgr.ensure("github", "npx", ["-y", "github-mcp"])
|
||||
|
||||
assert first is second # same connection reused, not a second subprocess
|
||||
assert len(_FakeConnection.instances) == 1
|
||||
assert first.started is True
|
||||
|
||||
|
||||
def test_two_concurrent_ensures_for_different_servers_dont_collide():
|
||||
mgr = _manager()
|
||||
a = mgr.ensure("server-a", "cmd-a")
|
||||
b = mgr.ensure("server-b", "cmd-b")
|
||||
assert a is not b
|
||||
assert {c.name for c in mgr.active()} == {"server-a", "server-b"}
|
||||
|
||||
|
||||
def test_ensure_restarts_when_the_cached_connection_died():
|
||||
mgr = _manager()
|
||||
first = mgr.ensure("flaky", "cmd")
|
||||
first.stop() # simulate the subprocess crashing
|
||||
assert mgr.is_alive("flaky") is False
|
||||
|
||||
second = mgr.ensure("flaky", "cmd")
|
||||
assert second is not first
|
||||
assert len(_FakeConnection.instances) == 2
|
||||
|
||||
|
||||
def test_a_server_that_fails_to_start_returns_none_and_isnt_cached():
|
||||
class _DyingConnection(_FakeConnection):
|
||||
def start(self) -> None:
|
||||
raise RuntimeError("boom")
|
||||
|
||||
mgr = McpToolSourceManager(connection_factory=_DyingConnection)
|
||||
assert mgr.ensure("broken", "cmd") is None
|
||||
assert mgr.get("broken") is None
|
||||
|
||||
|
||||
def test_stop_removes_one_connection_without_touching_others():
|
||||
mgr = _manager()
|
||||
mgr.ensure("keep", "cmd")
|
||||
doomed = mgr.ensure("drop", "cmd")
|
||||
|
||||
mgr.stop("drop")
|
||||
|
||||
assert doomed.stopped is True
|
||||
assert mgr.get("drop") is None
|
||||
assert mgr.get("keep") is not None
|
||||
|
||||
|
||||
def test_stop_all_stops_every_connection_and_clears_the_cache():
|
||||
mgr = _manager()
|
||||
mgr.ensure("a", "cmd")
|
||||
mgr.ensure("b", "cmd")
|
||||
|
||||
mgr.stop_all()
|
||||
|
||||
assert all(c.stopped for c in _FakeConnection.instances)
|
||||
assert mgr.active() == []
|
||||
@@ -0,0 +1,204 @@
|
||||
"""R03-T02 — unit tests for ProviderDescriptor and the central ProviderRegistry.
|
||||
|
||||
Covers what the rest of the app now relies on the catalogue for: resolving ids
|
||||
and aliases, resolving a bare model id back to its provider, filling in default
|
||||
models, and refusing to let a duplicate registration silently hijack a built-in.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from cowork_local.domain.models.provider_descriptor import (
|
||||
AuthKind,
|
||||
ProviderDescriptor,
|
||||
WireProtocol,
|
||||
)
|
||||
from cowork_local.infrastructure.providers.provider_registry import (
|
||||
BUILTIN_DESCRIPTORS,
|
||||
ProviderNotFoundError,
|
||||
ProviderRegistry,
|
||||
)
|
||||
|
||||
|
||||
def make_descriptor(**overrides) -> ProviderDescriptor:
|
||||
"""A minimal valid descriptor; tests override just the field under test."""
|
||||
fields = dict(
|
||||
provider_id="demo",
|
||||
display_name="Demo provider",
|
||||
wire_protocol=WireProtocol.OPENAI_COMPAT,
|
||||
default_model="demo-small",
|
||||
models=("demo-small", "demo-large"),
|
||||
)
|
||||
fields.update(overrides)
|
||||
return ProviderDescriptor(**fields)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ProviderDescriptor
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_descriptor_rejects_an_empty_id() -> None:
|
||||
"""An id-less descriptor could never be looked up, so it must not exist."""
|
||||
with pytest.raises(ValueError):
|
||||
make_descriptor(provider_id="")
|
||||
|
||||
|
||||
def test_descriptor_rejects_a_non_enum_protocol() -> None:
|
||||
"""The protocol drives adapter selection; a stray string would silently
|
||||
fall through to "no adapter" at build time instead of failing here."""
|
||||
with pytest.raises(TypeError):
|
||||
make_descriptor(wire_protocol="openai_compat")
|
||||
|
||||
|
||||
def test_descriptor_is_immutable() -> None:
|
||||
"""Descriptors are shared process-wide; a mutation would be visible to every
|
||||
other reader mid-iteration."""
|
||||
descriptor = make_descriptor()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
descriptor.default_model = "hacked" # type: ignore[misc]
|
||||
|
||||
|
||||
def test_id_matching_ignores_case_and_honours_aliases() -> None:
|
||||
"""Provider ids come from hand-edited config files and old app versions."""
|
||||
descriptor = make_descriptor(aliases=("legacy-demo",))
|
||||
|
||||
assert descriptor.matches("DEMO")
|
||||
assert descriptor.matches(" legacy-demo ")
|
||||
assert not descriptor.matches("other")
|
||||
|
||||
|
||||
def test_capabilities_use_the_routing_vocabulary() -> None:
|
||||
"""The set must be feedable straight into the routing selector's filter."""
|
||||
descriptor = make_descriptor(supports_vision=True, supports_tools=True,
|
||||
supports_streaming=False)
|
||||
|
||||
assert descriptor.capabilities == frozenset({"vision", "tools"})
|
||||
assert descriptor.has_capability("vision")
|
||||
assert not descriptor.has_capability("streaming")
|
||||
|
||||
|
||||
def test_average_cost_is_none_when_a_price_is_unknown() -> None:
|
||||
"""Unknown prices stay unknown — a guessed number would silently skew the
|
||||
routing scorer's cost term."""
|
||||
assert make_descriptor(cost_per_1k_input=0.5).avg_cost_per_1k is None
|
||||
priced = make_descriptor(cost_per_1k_input=1.0, cost_per_1k_output=3.0)
|
||||
# Same 1:3 input:output weighting as ModelMetadata.avg_cost_per_1k.
|
||||
assert priced.avg_cost_per_1k == pytest.approx((1.0 + 9.0) / 4.0)
|
||||
|
||||
|
||||
def test_resolve_model_prefers_the_caller_then_the_default() -> None:
|
||||
"""One place implements the "picked model or provider default" fallback that
|
||||
every chat surface used to re-implement inline."""
|
||||
descriptor = make_descriptor()
|
||||
|
||||
assert descriptor.resolve_model("demo-large") == "demo-large"
|
||||
assert descriptor.resolve_model("") == "demo-small"
|
||||
assert descriptor.resolve_model(" ") == "demo-small"
|
||||
|
||||
|
||||
def test_with_models_repoints_a_default_that_vanished() -> None:
|
||||
"""After discovery, the default must still name a model that exists."""
|
||||
descriptor = make_descriptor()
|
||||
|
||||
updated = descriptor.with_models(["demo-v2", "demo-v2", "demo-v3"])
|
||||
|
||||
assert updated.models == ("demo-v2", "demo-v3") # de-duplicated, order kept
|
||||
assert updated.default_model == "demo-v2"
|
||||
assert descriptor.models == ("demo-small", "demo-large"), "original was mutated"
|
||||
|
||||
|
||||
def test_with_models_keeps_a_default_that_survived() -> None:
|
||||
"""Discovery must not reshuffle a user's working selection."""
|
||||
updated = make_descriptor().with_models(["demo-large", "demo-small"])
|
||||
|
||||
assert updated.default_model == "demo-small"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ProviderRegistry
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_registry_resolves_ids_aliases_and_reports_unknowns() -> None:
|
||||
"""Lookup must be forgiving about form, but loud about genuinely unknown
|
||||
providers — a typo should fail at the call site, not as a None later."""
|
||||
registry = ProviderRegistry([make_descriptor(aliases=("legacy-demo",))])
|
||||
|
||||
assert registry.get("demo").provider_id == "demo"
|
||||
assert registry.get("legacy-demo").provider_id == "demo"
|
||||
assert registry.find("missing") is None
|
||||
assert "demo" in registry
|
||||
with pytest.raises(ProviderNotFoundError):
|
||||
registry.get("missing")
|
||||
|
||||
|
||||
def test_registry_refuses_to_overwrite_silently_but_replace_works() -> None:
|
||||
"""A second registration of the same id is almost always a bug; updating a
|
||||
descriptor is a deliberate act with its own method."""
|
||||
registry = ProviderRegistry([make_descriptor()])
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
registry.register(make_descriptor(display_name="Impostor"))
|
||||
|
||||
registry.replace(make_descriptor(display_name="Renamed"))
|
||||
assert registry.get("demo").display_name == "Renamed"
|
||||
assert len(registry) == 1
|
||||
|
||||
|
||||
def test_registry_re_registering_an_identical_descriptor_is_a_no_op() -> None:
|
||||
"""Idempotent registration keeps repeated bootstrap calls harmless."""
|
||||
registry = ProviderRegistry([make_descriptor()])
|
||||
|
||||
registry.register(make_descriptor())
|
||||
|
||||
assert len(registry) == 1
|
||||
|
||||
|
||||
def test_find_by_model_resolves_a_bare_model_id() -> None:
|
||||
"""Routing decisions and saved conversations sometimes carry only a model
|
||||
name; the registry is what turns that back into a provider."""
|
||||
registry = ProviderRegistry([make_descriptor()])
|
||||
|
||||
assert registry.find_by_model("demo-large").provider_id == "demo"
|
||||
# A gateway model we cannot enumerate offline is a miss, not an error — the
|
||||
# caller falls back to the configured active provider.
|
||||
assert registry.find_by_model("unknown-model") is None
|
||||
assert registry.find_by_model("") is None
|
||||
|
||||
|
||||
def test_builtin_catalogue_covers_every_configured_provider() -> None:
|
||||
"""The catalogue and DEFAULT_CONFIG must not drift: a provider users can
|
||||
configure but the registry cannot build is a dead Settings entry."""
|
||||
from cowork_local.config import DEFAULT_CONFIG
|
||||
|
||||
registry = ProviderRegistry(BUILTIN_DESCRIPTORS)
|
||||
|
||||
for provider_id in DEFAULT_CONFIG["providers"]:
|
||||
assert registry.find(provider_id) is not None, f"{provider_id} missing from registry"
|
||||
|
||||
|
||||
def test_build_fills_in_the_default_model() -> None:
|
||||
"""A half-written config must still produce a usable provider rather than an
|
||||
empty model id that only fails once the request reaches the gateway."""
|
||||
registry = ProviderRegistry(BUILTIN_DESCRIPTORS)
|
||||
|
||||
provider = registry.build("anthropic", {"api_key": "k"})
|
||||
|
||||
assert provider.model == registry.get("anthropic").default_model
|
||||
|
||||
|
||||
def test_build_respects_an_explicit_model() -> None:
|
||||
"""Per-tab model selection must win over the catalogue default."""
|
||||
registry = ProviderRegistry(BUILTIN_DESCRIPTORS)
|
||||
|
||||
provider = registry.build("anthropic", {"api_key": "k", "model": "claude-opus-4-8"})
|
||||
|
||||
assert provider.model == "claude-opus-4-8"
|
||||
|
||||
|
||||
def test_factory_still_raises_provider_error_for_unknown_ids() -> None:
|
||||
"""Existing call sites catch ProviderError; routing lookups through the
|
||||
registry must not change the exception type they see."""
|
||||
from cowork_local.providers import build_provider
|
||||
from cowork_local.providers.base import ProviderError
|
||||
|
||||
with pytest.raises(ProviderError):
|
||||
build_provider("definitely-not-a-provider", {})
|
||||
@@ -0,0 +1,384 @@
|
||||
"""R03-T03 — unit tests for the unified routing decision rules.
|
||||
|
||||
The point of moving these rules out of the three chat widgets is that they can
|
||||
now be exercised without Qt, without the assessment store and without a network:
|
||||
the service talks to two narrow ports, so every mode is driven here by ~10-line
|
||||
fakes. Each test names the behaviour a chat surface depends on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from cowork_local.application.model_routing import (
|
||||
RouteEvaluation,
|
||||
RoutingApplicationService,
|
||||
RoutingMode,
|
||||
RoutingOutcome,
|
||||
RoutingRequest,
|
||||
)
|
||||
|
||||
|
||||
class FakeDecisionPort:
|
||||
"""A routing engine that returns a canned verdict and records its input."""
|
||||
|
||||
def __init__(self, evaluation: RouteEvaluation) -> None:
|
||||
self.evaluation = evaluation
|
||||
self.calls: list = []
|
||||
|
||||
def evaluate(self, request: RoutingRequest, mode: RoutingMode) -> RouteEvaluation:
|
||||
self.calls.append((request, mode))
|
||||
return self.evaluation
|
||||
|
||||
|
||||
class ExplodingDecisionPort:
|
||||
"""An engine that fails — proves routing degrades instead of breaking a turn."""
|
||||
|
||||
def evaluate(self, request: RoutingRequest, mode: RoutingMode) -> RouteEvaluation:
|
||||
raise RuntimeError("assessment store is corrupt")
|
||||
|
||||
|
||||
class FakeModeResolver:
|
||||
"""Per-surface mode lookup, standing in for the workspace settings."""
|
||||
|
||||
def __init__(self, mode) -> None:
|
||||
self.mode = mode
|
||||
self.surfaces: list = []
|
||||
|
||||
def mode_for(self, surface: str):
|
||||
self.surfaces.append(surface)
|
||||
return self.mode
|
||||
|
||||
|
||||
def make_request(**overrides) -> RoutingRequest:
|
||||
"""A representative turn: Cowork chat, currently on a cheap OpenAI model."""
|
||||
fields = dict(
|
||||
surface="cowork",
|
||||
prompt="Refactor this function",
|
||||
current_provider="codex",
|
||||
current_model="gpt-4o-mini",
|
||||
)
|
||||
fields.update(overrides)
|
||||
return RoutingRequest(**fields)
|
||||
|
||||
|
||||
def switch_evaluation(**overrides) -> RouteEvaluation:
|
||||
"""An engine verdict that proposes a switch to a better coding model."""
|
||||
fields = dict(
|
||||
task_type="coding",
|
||||
should_switch=True,
|
||||
target_provider="anthropic",
|
||||
target_model="claude-sonnet-4-6",
|
||||
score_gain=0.21,
|
||||
reason="coding fit 0.88 > current 0.67",
|
||||
decision=object(),
|
||||
)
|
||||
fields.update(overrides)
|
||||
return RouteEvaluation(**fields)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Off
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_off_mode_never_consults_the_engine() -> None:
|
||||
"""Off must be free: no ranking, no store read, no decision at all."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.OFF))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is False
|
||||
assert outcome.provider is None and outcome.model is None
|
||||
assert port.calls == [], "Off mode must not call the routing engine"
|
||||
|
||||
|
||||
def test_missing_mode_resolver_defaults_to_off() -> None:
|
||||
"""Routing stays opt-in: with no way to read the mode, never switch."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port)
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.mode is RoutingMode.OFF
|
||||
assert outcome.switched is False
|
||||
|
||||
|
||||
def test_empty_prompt_is_not_routed() -> None:
|
||||
"""An empty message carries no signal to classify, so the engine is skipped."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request(prompt=" "))
|
||||
|
||||
assert outcome.switched is False
|
||||
assert port.calls == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Auto
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_auto_mode_switches_silently() -> None:
|
||||
"""Auto applies the engine's verdict without asking the user."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is True
|
||||
assert outcome.provider == "anthropic"
|
||||
assert outcome.model == "claude-sonnet-4-6"
|
||||
assert outcome.task_type == "coding"
|
||||
assert outcome.score_gain == pytest.approx(0.21)
|
||||
assert outcome.should_notify is True
|
||||
|
||||
|
||||
def test_auto_mode_keeps_current_when_nothing_is_better() -> None:
|
||||
"""No proposed switch means the surface's own selection is untouched."""
|
||||
port = FakeDecisionPort(switch_evaluation(
|
||||
should_switch=False, reason="current model is already best-fit"))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is False
|
||||
assert outcome.provider is None
|
||||
assert "already best-fit" in outcome.reason
|
||||
|
||||
|
||||
def test_switch_without_a_target_is_ignored() -> None:
|
||||
"""A verdict that says "switch" but names nothing is not actionable — a
|
||||
surface must never be handed an empty model id."""
|
||||
port = FakeDecisionPort(switch_evaluation(target_provider=None, target_model=None))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is False
|
||||
|
||||
|
||||
def test_same_provider_switch_keeps_the_current_provider() -> None:
|
||||
"""A model-only switch must not blank out the provider the surface uses."""
|
||||
port = FakeDecisionPort(switch_evaluation(target_provider=None, target_model="o3"))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is True
|
||||
assert outcome.provider == "codex" # unchanged, from the request
|
||||
assert outcome.model == "o3"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Manual
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_manual_mode_switches_only_after_approval() -> None:
|
||||
"""Manual's contract: ask first, then apply exactly what was approved."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(
|
||||
port, FakeModeResolver(RoutingMode.MANUAL),
|
||||
confirm_timeout_sec=lambda: 30.0,
|
||||
)
|
||||
asked: list = []
|
||||
|
||||
def confirm(decision, timeout):
|
||||
asked.append((decision, timeout))
|
||||
return True
|
||||
|
||||
outcome = service.resolve(make_request(), confirm=confirm)
|
||||
|
||||
assert outcome.switched is True
|
||||
assert len(asked) == 1
|
||||
# The configured timeout must reach the dialog, not a hard-coded default.
|
||||
assert asked[0][1] == pytest.approx(30.0)
|
||||
|
||||
|
||||
def test_manual_mode_decline_is_reported_distinctly() -> None:
|
||||
""""The user said no" must be distinguishable from "nothing better found",
|
||||
so a surface can stay quiet in one case and explain itself in the other."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.MANUAL))
|
||||
|
||||
outcome = service.resolve(make_request(), confirm=lambda decision, timeout: False)
|
||||
|
||||
assert outcome.switched is False
|
||||
assert outcome.declined is True
|
||||
|
||||
|
||||
def test_manual_mode_without_a_callback_never_switches() -> None:
|
||||
"""Silently switching in Manual mode would violate the mode's promise."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.MANUAL))
|
||||
|
||||
outcome = service.resolve(make_request(), confirm=None)
|
||||
|
||||
assert outcome.switched is False
|
||||
|
||||
|
||||
def test_manual_mode_treats_a_broken_dialog_as_a_decline() -> None:
|
||||
"""A crashing confirm dialog must not auto-approve a model change."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.MANUAL))
|
||||
|
||||
def confirm(decision, timeout):
|
||||
raise RuntimeError("dialog blew up")
|
||||
|
||||
outcome = service.resolve(make_request(), confirm=confirm)
|
||||
|
||||
assert outcome.switched is False
|
||||
assert outcome.declined is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Fallback
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_fallback_keeps_a_healthy_model_even_when_a_better_one_exists() -> None:
|
||||
"""Fallback is a resilience mode, not an optimiser: a usable pinned model
|
||||
wins over a higher-scoring candidate."""
|
||||
port = FakeDecisionPort(switch_evaluation(current_is_usable=True))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.FALLBACK))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is False
|
||||
assert "healthy" in outcome.reason
|
||||
|
||||
|
||||
def test_fallback_switches_when_the_current_model_cannot_serve_the_turn() -> None:
|
||||
"""The one case Fallback exists for: rescue an unusable selection."""
|
||||
port = FakeDecisionPort(switch_evaluation(current_is_usable=False))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.FALLBACK))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is True
|
||||
assert outcome.model == "claude-sonnet-4-6"
|
||||
|
||||
|
||||
def test_fallback_asks_the_engine_with_auto_semantics() -> None:
|
||||
"""The engine only understands off/auto/manual, so Fallback must reach it as
|
||||
Auto — otherwise the engine would reject the unknown mode and rank nothing."""
|
||||
port = FakeDecisionPort(switch_evaluation(current_is_usable=False))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.FALLBACK))
|
||||
|
||||
service.resolve(make_request())
|
||||
|
||||
assert port.calls[0][1] is RoutingMode.AUTO
|
||||
|
||||
|
||||
def test_fallback_never_confirms_with_the_user() -> None:
|
||||
"""Rescuing an unusable model is not a proposal — it happens silently."""
|
||||
port = FakeDecisionPort(switch_evaluation(current_is_usable=False))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.FALLBACK))
|
||||
asked: list = []
|
||||
|
||||
outcome = service.resolve(
|
||||
make_request(), confirm=lambda decision, timeout: asked.append(1) or True)
|
||||
|
||||
assert outcome.switched is True
|
||||
assert asked == []
|
||||
|
||||
|
||||
def test_fallback_with_no_replacement_keeps_current() -> None:
|
||||
"""Nothing to fall back to means keep going with what we have and let the
|
||||
provider surface the real error, rather than blanking the model."""
|
||||
port = FakeDecisionPort(switch_evaluation(
|
||||
current_is_usable=False, target_provider=None, target_model=None))
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.FALLBACK))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.switched is False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Robustness & plumbing
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_engine_failure_degrades_to_keep_current() -> None:
|
||||
"""A broken assessment store must never stop a user sending a message."""
|
||||
service = RoutingApplicationService(
|
||||
ExplodingDecisionPort(), FakeModeResolver(RoutingMode.AUTO))
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert isinstance(outcome, RoutingOutcome)
|
||||
assert outcome.switched is False
|
||||
assert "error" in outcome.reason
|
||||
|
||||
|
||||
def test_mode_resolver_failure_degrades_to_off() -> None:
|
||||
"""An unreadable workspace config must not enable routing by accident."""
|
||||
class BrokenResolver:
|
||||
def mode_for(self, surface):
|
||||
raise OSError("workspace file unreadable")
|
||||
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, BrokenResolver())
|
||||
|
||||
outcome = service.resolve(make_request())
|
||||
|
||||
assert outcome.mode is RoutingMode.OFF
|
||||
assert port.calls == []
|
||||
|
||||
|
||||
def test_explicit_request_mode_overrides_the_resolver() -> None:
|
||||
"""A surface may pin the mode for one turn (tests, replay, admin actions)."""
|
||||
resolver = FakeModeResolver(RoutingMode.OFF)
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, resolver)
|
||||
|
||||
outcome = service.resolve(make_request(mode=RoutingMode.AUTO))
|
||||
|
||||
assert outcome.switched is True
|
||||
assert resolver.surfaces == [], "an explicit mode must skip the resolver"
|
||||
|
||||
|
||||
def test_request_is_forwarded_to_the_engine_unchanged() -> None:
|
||||
"""Surface, prompt and pinned task type must survive the hand-off — AI-Edit
|
||||
relies on its "coding" pin reaching the engine."""
|
||||
port = FakeDecisionPort(switch_evaluation())
|
||||
service = RoutingApplicationService(port, FakeModeResolver(RoutingMode.AUTO))
|
||||
request = make_request(surface="ai_edit", task_type="coding",
|
||||
required_capabilities=("vision",))
|
||||
|
||||
service.resolve(request)
|
||||
|
||||
forwarded = port.calls[0][0]
|
||||
assert forwarded is request
|
||||
assert forwarded.surface == "ai_edit"
|
||||
assert forwarded.task_type == "coding"
|
||||
assert forwarded.required_capabilities == ("vision",)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw, expected",
|
||||
[
|
||||
("auto", RoutingMode.AUTO),
|
||||
("MANUAL", RoutingMode.MANUAL),
|
||||
(" fallback ", RoutingMode.FALLBACK),
|
||||
("nonsense", RoutingMode.OFF),
|
||||
("", RoutingMode.OFF),
|
||||
(None, RoutingMode.OFF),
|
||||
],
|
||||
)
|
||||
def test_mode_parsing_is_forgiving(raw, expected) -> None:
|
||||
"""Config values are hand-edited; an unknown one must degrade, not raise."""
|
||||
assert RoutingMode.parse(raw) is expected
|
||||
|
||||
|
||||
def test_confirm_timeout_falls_back_to_the_default_when_unusable() -> None:
|
||||
"""A corrupted timeout must not produce a zero-second dialog that declines
|
||||
every switch before the user can read it."""
|
||||
service = RoutingApplicationService(
|
||||
FakeDecisionPort(switch_evaluation()),
|
||||
FakeModeResolver(RoutingMode.MANUAL),
|
||||
confirm_timeout_sec=lambda: 0.0,
|
||||
)
|
||||
|
||||
assert service.confirm_timeout() == RoutingApplicationService.DEFAULT_CONFIRM_TIMEOUT_SEC
|
||||
|
||||
|
||||
def test_routing_request_is_immutable() -> None:
|
||||
"""The snapshot must not change under a turn that is already in flight."""
|
||||
request = make_request()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
request.prompt = "something else" # type: ignore[misc]
|
||||
@@ -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)) == []
|
||||
@@ -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
|
||||
@@ -0,0 +1,34 @@
|
||||
"""R04-T05 — unit tests for the unattended-run prompt assembly.
|
||||
|
||||
``_run_agent`` used to build this by rebinding ``prompt`` three times, each with
|
||||
its own ``f"{block}\n\n{prompt}"``. The ORDER that produced is load-bearing (the
|
||||
plan reminder has to lead, the task's own words have to trail) and it was
|
||||
readable only by replaying the rebindings in your head.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cowork_local.core.task_executors import _unattended_prompt
|
||||
|
||||
|
||||
def test_the_plan_reminder_leads_and_the_task_prompt_trails() -> None:
|
||||
built = _unattended_prompt("write the report")
|
||||
|
||||
assert built.startswith("This runs unattended (Schedule Task)")
|
||||
assert built.endswith("write the report")
|
||||
|
||||
|
||||
def test_a_skill_block_sits_between_the_reminder_and_the_agent_persona() -> None:
|
||||
built = _unattended_prompt("write the report", skill_text="SKILL",
|
||||
agent_instructions="PERSONA")
|
||||
|
||||
assert built.index("This runs unattended") < built.index("SKILL")
|
||||
assert built.index("SKILL") < built.index("PERSONA")
|
||||
assert built.index("PERSONA") < built.index("write the report")
|
||||
|
||||
|
||||
def test_absent_blocks_leave_no_extra_blank_lines() -> None:
|
||||
built = _unattended_prompt("do it", skill_text="", agent_instructions=None)
|
||||
|
||||
assert "\n\n\n" not in built
|
||||
assert built.count("do it") == 1
|
||||
@@ -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
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Unit tests for EPIC R05: the tool descriptor/registry (R05-T01), the split
|
||||
built-in handlers (R05-T02), and the policy gateway (R05-T03).
|
||||
|
||||
The gateway tests assert the SAME capability set each engine used to hard-code
|
||||
as a name tuple still gets gated after the switch to capability lookup — that
|
||||
equivalence is the whole point of R05-T03, not an incidental detail.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from cowork_local.application.conversations import ToolPolicyGateway
|
||||
from cowork_local.core.tools import TOOL_SPECS, ToolContext, execute_tool
|
||||
from cowork_local.domain.tools import ToolCapability, ToolDescriptor, default_registry
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# R05-T01 - ToolDescriptor / ToolRegistry
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_capability_flags_compose():
|
||||
install = ToolDescriptor("install_package", "", {}, ToolCapability.WRITE | ToolCapability.EXECUTE)
|
||||
assert install.has(ToolCapability.WRITE)
|
||||
assert install.has(ToolCapability.EXECUTE)
|
||||
assert not install.has(ToolCapability.NETWORK)
|
||||
|
||||
|
||||
def test_default_registry_matches_todays_hardcoded_gating_sets():
|
||||
"""The two literal sets this EPIC replaces:
|
||||
``core/tools.py::WRITE_TOOLS`` and ``core/chat_agent.py``'s
|
||||
``("run_command", "install_package")`` tuple. The registry must agree
|
||||
with both, or the capability switch silently changes who gets gated."""
|
||||
registry = default_registry(TOOL_SPECS)
|
||||
|
||||
execute_gated = {d.name for d in registry.all() if d.has(ToolCapability.EXECUTE)}
|
||||
assert execute_gated == {"run_command", "install_package"}
|
||||
|
||||
write_gated = {d.name for d in registry.all() if d.has(ToolCapability.WRITE)}
|
||||
assert write_gated == {"write_file", "edit_file", "install_package"}
|
||||
|
||||
|
||||
def test_unregistered_tool_has_no_capabilities():
|
||||
registry = default_registry(TOOL_SPECS)
|
||||
assert registry.capabilities_for("no_such_tool") is ToolCapability.NONE
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# R05-T02 - core/tools.py dispatch, now built from the split infra modules
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_execute_tool_still_dispatches_every_built_in(tmp_path):
|
||||
ctx = ToolContext(tmp_path)
|
||||
written = execute_tool(ctx, "write_file", {"path": "a.txt", "content": "hi"})
|
||||
assert written["ok"] is True
|
||||
read = execute_tool(ctx, "read_file", {"path": "a.txt"})
|
||||
assert read == {"ok": True, "output": "hi"}
|
||||
edited = execute_tool(ctx, "edit_file", {"path": "a.txt", "old_string": "hi", "new_string": "bye"})
|
||||
assert edited["ok"] is True
|
||||
assert execute_tool(ctx, "read_file", {"path": "a.txt"})["output"] == "bye"
|
||||
listing = execute_tool(ctx, "list_dir", {})
|
||||
assert listing["ok"] is True and "a.txt" in listing["output"]
|
||||
|
||||
|
||||
def test_execute_tool_reports_unknown_name(tmp_path):
|
||||
ctx = ToolContext(tmp_path)
|
||||
result = execute_tool(ctx, "not_a_real_tool", {})
|
||||
assert result == {"ok": False, "output": "Tool not found: not_a_real_tool"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# R05-T03 - ToolPolicyGateway
|
||||
# --------------------------------------------------------------------------- #
|
||||
class _RecordingGate:
|
||||
def __init__(self, approve: bool):
|
||||
self.approve = approve
|
||||
self.calls: list = []
|
||||
|
||||
def request(self, payload: Dict[str, Any]) -> bool:
|
||||
self.calls.append(payload)
|
||||
return self.approve
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cowork_policy() -> ToolPolicyGateway:
|
||||
"""Same construction as ``core/chat_agent.py``'s module-level
|
||||
``_COWORK_TOOL_POLICY`` - EXECUTE is exactly what Cowork used to gate via
|
||||
the literal ``("run_command", "install_package")`` tuple."""
|
||||
return ToolPolicyGateway(default_registry(TOOL_SPECS), ToolCapability.EXECUTE)
|
||||
|
||||
|
||||
def test_no_gate_means_auto_run(cowork_policy):
|
||||
assert cowork_policy.allow("run_command", None, {}) is True
|
||||
|
||||
|
||||
def test_read_only_tool_never_asks_the_gate(cowork_policy):
|
||||
gate = _RecordingGate(approve=False) # would reject if asked
|
||||
assert cowork_policy.allow("write_file", gate, {}) is True
|
||||
assert gate.calls == [] # never consulted - write_file isn't EXECUTE
|
||||
|
||||
|
||||
def test_gated_capability_consults_the_gate_and_honors_its_answer(cowork_policy):
|
||||
approving = _RecordingGate(approve=True)
|
||||
assert cowork_policy.allow("run_command", approving, {"name": "run_command"}) is True
|
||||
assert approving.calls == [{"name": "run_command"}]
|
||||
|
||||
rejecting = _RecordingGate(approve=False)
|
||||
assert cowork_policy.allow("install_package", rejecting, {}) is False
|
||||
@@ -0,0 +1,36 @@
|
||||
"""R04-T04 — unit tests for the shared turn-runtime helpers.
|
||||
|
||||
``combine_instructions`` is the small rule the UI applied inline: a turn's
|
||||
standing instructions are several independent blocks (project context, an Admin
|
||||
agent's persona, a skill's rules, an unattended-run reminder) that must be joined
|
||||
with one blank line, skipping whatever is absent. Two call sites need it (T04's
|
||||
widget and T05's task runner), which is exactly when a rule stops being an inline
|
||||
expression.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cowork_local.application.conversations.turn_runtime import combine_instructions
|
||||
|
||||
|
||||
def test_two_blocks_are_joined_by_a_blank_line() -> None:
|
||||
assert combine_instructions("PROJECT", "AGENT") == "PROJECT\n\nAGENT"
|
||||
|
||||
|
||||
def test_an_absent_block_leaves_no_blank_line_behind() -> None:
|
||||
assert combine_instructions("", "AGENT") == "AGENT"
|
||||
assert combine_instructions("PROJECT", "") == "PROJECT"
|
||||
assert combine_instructions("PROJECT", None) == "PROJECT"
|
||||
|
||||
|
||||
def test_whitespace_only_blocks_do_not_count_as_instructions() -> None:
|
||||
assert combine_instructions(" \n ", "AGENT") == "AGENT"
|
||||
|
||||
|
||||
def test_nothing_to_say_produces_an_empty_string() -> None:
|
||||
assert combine_instructions() == ""
|
||||
assert combine_instructions("", None, " ") == ""
|
||||
|
||||
|
||||
def test_more_than_two_blocks_keep_their_order() -> None:
|
||||
assert combine_instructions("A", "B", "C") == "A\n\nB\n\nC"
|
||||
@@ -0,0 +1,184 @@
|
||||
"""R03-T06 — unit tests for the token-usage telemetry seam.
|
||||
|
||||
The seam exists so provider adapters stop owning telemetry policy. These tests
|
||||
pin the two properties that makes that safe: events reach every subscriber, and
|
||||
no telemetry failure can ever propagate back into the turn that produced it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from cowork_local.infrastructure.telemetry import usage_sink
|
||||
from cowork_local.infrastructure.telemetry.usage_sink import (
|
||||
CompositeUsageSink,
|
||||
InMemoryUsageSink,
|
||||
UsageEvent,
|
||||
UsageTrackerSink,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_sink(monkeypatch):
|
||||
"""Give every test its own process-wide sink.
|
||||
|
||||
Autouse because a leaked sink would let one test's subscriber observe the
|
||||
next test's events — and, worse, let a test write to the developer's real
|
||||
usage files through the default tracker sink.
|
||||
"""
|
||||
monkeypatch.setattr(usage_sink, "_sink", None)
|
||||
yield
|
||||
monkeypatch.setattr(usage_sink, "_sink", None)
|
||||
|
||||
|
||||
def make_event(**overrides) -> UsageEvent:
|
||||
fields = dict(provider="anthropic", model="claude-sonnet-4-6",
|
||||
input_tokens=100, output_tokens=40, cached_tokens=10)
|
||||
fields.update(overrides)
|
||||
return UsageEvent(**fields)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# UsageEvent
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_event_is_immutable() -> None:
|
||||
"""A subscriber must not be able to edit the event the next one receives."""
|
||||
event = make_event()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
event.input_tokens = 0 # type: ignore[misc]
|
||||
|
||||
|
||||
def test_total_tokens_does_not_double_count_cache_reads() -> None:
|
||||
"""Every gateway we support already reports cached tokens inside the input
|
||||
count, so adding them again would inflate the dashboard."""
|
||||
assert make_event().total_tokens == 140
|
||||
|
||||
|
||||
def test_to_dict_uses_the_stored_row_keys() -> None:
|
||||
"""Matching the tracker's short keys lets a caller diff an event against a
|
||||
persisted row without a translation table."""
|
||||
row = make_event(source="cowork", label="Refactor chat").to_dict()
|
||||
|
||||
assert row["in"] == 100 and row["out"] == 40 and row["cache"] == 10
|
||||
assert row["source"] == "cowork" and row["label"] == "Refactor chat"
|
||||
assert row["estimated"] is False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Fan-out
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_publish_reaches_every_subscriber() -> None:
|
||||
"""The whole point of the seam: extra consumers attach without patching
|
||||
provider code."""
|
||||
first, second = InMemoryUsageSink(), InMemoryUsageSink()
|
||||
usage_sink.set_usage_sink(CompositeUsageSink([first, second]))
|
||||
|
||||
usage_sink.publish(make_event())
|
||||
|
||||
assert len(first.snapshot()) == 1
|
||||
assert len(second.snapshot()) == 1
|
||||
|
||||
|
||||
def test_one_failing_subscriber_does_not_starve_the_others() -> None:
|
||||
"""A buggy consumer must not silently disable the Dashboard."""
|
||||
class Exploding:
|
||||
def emit(self, event):
|
||||
raise RuntimeError("subscriber is broken")
|
||||
|
||||
healthy = InMemoryUsageSink()
|
||||
usage_sink.set_usage_sink(CompositeUsageSink([Exploding(), healthy]))
|
||||
|
||||
usage_sink.publish(make_event())
|
||||
|
||||
assert len(healthy.snapshot()) == 1
|
||||
|
||||
|
||||
def test_subscribe_and_unsubscribe_round_trip() -> None:
|
||||
"""Teardown code calls unsubscribe unconditionally, so removing a sink that
|
||||
was never added must be harmless."""
|
||||
extra = InMemoryUsageSink()
|
||||
|
||||
usage_sink.subscribe(extra)
|
||||
usage_sink.publish(make_event())
|
||||
usage_sink.unsubscribe(extra)
|
||||
usage_sink.unsubscribe(extra) # second removal is a no-op
|
||||
usage_sink.publish(make_event(model="claude-opus-4-8"))
|
||||
|
||||
assert [e.model for e in extra.snapshot()] == ["claude-sonnet-4-6"]
|
||||
|
||||
|
||||
def test_default_sink_is_the_usage_tracker() -> None:
|
||||
"""Out of the box the seam must preserve the existing Dashboard pipeline."""
|
||||
sinks = usage_sink.get_usage_sink().sinks()
|
||||
|
||||
assert any(isinstance(s, UsageTrackerSink) for s in sinks)
|
||||
|
||||
|
||||
def test_in_memory_sink_totals_and_clears() -> None:
|
||||
"""Test-double conveniences the contract suite relies on."""
|
||||
sink = InMemoryUsageSink()
|
||||
sink.emit(make_event())
|
||||
sink.emit(make_event(input_tokens=1, output_tokens=1, cached_tokens=0))
|
||||
|
||||
assert sink.total_tokens == 142
|
||||
sink.clear()
|
||||
assert sink.snapshot() == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# UsageTrackerSink forwarding
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_tracker_sink_forwards_the_counts() -> None:
|
||||
"""The adapter must hand the tracker exactly what the provider measured."""
|
||||
recorded: list = []
|
||||
|
||||
def fake_record(provider, model, tokens_in, tokens_out, cached, estimated=False):
|
||||
recorded.append((provider, model, tokens_in, tokens_out, cached, estimated))
|
||||
|
||||
UsageTrackerSink(recorder=fake_record).emit(make_event(estimated=True))
|
||||
|
||||
assert recorded == [("anthropic", "claude-sonnet-4-6", 100, 40, 10, True)]
|
||||
|
||||
|
||||
def test_tracker_sink_restores_the_thread_context_it_borrowed() -> None:
|
||||
"""An event carrying its own attribution must relabel ONE row, not every
|
||||
later turn that happens to run on the same worker thread."""
|
||||
from cowork_local.core import usage_tracker as tracker
|
||||
|
||||
tracker.set_context("cowork", "original chat")
|
||||
seen: list = []
|
||||
UsageTrackerSink(recorder=lambda *a, **k: seen.append(tracker.current_context())).emit(
|
||||
make_event(source="co4e", label="flow run"))
|
||||
|
||||
assert seen == [("co4e", "flow run")], "event attribution was not applied"
|
||||
assert tracker.current_context() == ("cowork", "original chat")
|
||||
|
||||
|
||||
def test_tracker_sink_swallows_recorder_failures() -> None:
|
||||
"""Telemetry is never allowed to abort an otherwise successful turn."""
|
||||
def boom(*_args, **_kwargs):
|
||||
raise OSError("usage directory is read-only")
|
||||
|
||||
UsageTrackerSink(recorder=boom).emit(make_event()) # must not raise
|
||||
|
||||
|
||||
def test_publish_never_raises_even_with_a_broken_sink() -> None:
|
||||
"""Last line of defence: providers call publish() inside their stream loop."""
|
||||
class Hostile:
|
||||
def emit(self, event):
|
||||
raise RuntimeError("nope")
|
||||
|
||||
def sinks(self):
|
||||
raise RuntimeError("nope")
|
||||
|
||||
usage_sink.set_usage_sink(Hostile())
|
||||
|
||||
usage_sink.publish(make_event()) # must not raise
|
||||
|
||||
|
||||
def test_estimate_tokens_matches_the_tracker_heuristic() -> None:
|
||||
"""Re-exported so adapters need one telemetry import; it must not drift."""
|
||||
from cowork_local.core import usage_tracker as tracker
|
||||
|
||||
for text in ("", "a", "hello world", "x" * 4001):
|
||||
assert usage_sink.estimate_tokens(text) == tracker.estimate_tokens(text)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""EPIC R06-T01: WorkspaceSession is a frozen snapshot, captured once, that a
|
||||
turn keeps using regardless of what the UI does to the live project
|
||||
selection afterwards - see the module docstring for the race this replaces.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cowork_local.domain.workspaces import WorkspaceSession
|
||||
|
||||
|
||||
class _FakeProject:
|
||||
def __init__(self, project_id: str, root: Path):
|
||||
self.project_id = project_id
|
||||
self._root = root
|
||||
|
||||
def workspace_dir(self) -> Path:
|
||||
return self._root
|
||||
|
||||
|
||||
def test_from_project_derives_sandbox_dir_under_the_workspace_root(tmp_path):
|
||||
project = _FakeProject("proj-a", tmp_path)
|
||||
session = WorkspaceSession.from_project(project)
|
||||
|
||||
assert session.project_id == "proj-a"
|
||||
assert session.workspace_root == tmp_path
|
||||
assert session.sandbox_dir == tmp_path / ".scratch"
|
||||
assert session.allowed_paths == (tmp_path,)
|
||||
|
||||
|
||||
def test_is_allowed_true_for_the_root_and_descendants(tmp_path):
|
||||
session = WorkspaceSession.from_project(_FakeProject("p", tmp_path))
|
||||
nested = tmp_path / "sub" / "file.txt"
|
||||
nested.parent.mkdir(parents=True)
|
||||
nested.write_text("x", encoding="utf-8")
|
||||
|
||||
assert session.is_allowed(tmp_path) is True
|
||||
assert session.is_allowed(nested) is True
|
||||
|
||||
|
||||
def test_is_allowed_false_outside_the_workspace(tmp_path):
|
||||
session = WorkspaceSession.from_project(_FakeProject("p", tmp_path / "a"))
|
||||
outside = tmp_path / "b" / "secret.txt"
|
||||
|
||||
assert session.is_allowed(outside) is False
|
||||
|
||||
|
||||
def test_two_sessions_from_different_projects_stay_independent(tmp_path):
|
||||
"""The exact race this snapshot exists to prevent: a turn holding session
|
||||
A must never start accepting paths that belong to session B, no matter
|
||||
what the (mutable, shared) AppContext does after the snapshot was taken."""
|
||||
session_a = WorkspaceSession.from_project(_FakeProject("a", tmp_path / "a"))
|
||||
session_b = WorkspaceSession.from_project(_FakeProject("b", tmp_path / "b"))
|
||||
|
||||
assert session_a.is_allowed(tmp_path / "b" / "file.txt") is False
|
||||
assert session_b.is_allowed(tmp_path / "a" / "file.txt") is False
|
||||
|
||||
|
||||
def test_unscoped_session_has_no_project_id(tmp_path):
|
||||
session = WorkspaceSession.unscoped(tmp_path)
|
||||
assert session.project_id == ""
|
||||
assert session.is_allowed(tmp_path / "code.py") is True
|
||||
Reference in New Issue
Block a user