open-swe/tests/test_plan_mode.py
Johannes du Plessis 209132d355
refactor: durable interrupt dispatch + completion webhook (#1621)
* wip(rebuild): core reliability spine

- remove PR-babysitting (ci_autofix + ci_monitor graph + webhook wiring)
- dispatch core: agent/dispatch.py with multitask_strategy=interrupt +
  durability=sync + completion webhook; reroute all webhook + plan triggers;
  drop the racy in-process lock + is_thread_active busy-check
- completion webhook: agent/completion.py + /webhooks/run-complete loopback
  route for failure/timeout replies (idempotent)

Co-authored-by: open-swe[bot]

* feat(rebuild): async tools, reconcile, shared http timeouts, assembly tuning

Parallel batch on top of the reliability spine:
- async-ify all 24 tools (drop asyncio.run; requests->httpx); re-implement the
  http_request/fetch_url SSRF + DNS-rebinding defense httpx-natively and harden
  the IP check to 'not is_global' (+ IPv4-mapped unwrap)
- reconcile.py: stale pending-run sweep (threads.search -> per-thread runs.list
  -> cancel_many), wired into the scheduler graph via task='reconcile'
- shared DEFAULT_HTTP_TIMEOUT (agent/utils/http.py) on every bare
  httpx.AsyncClient() across utils/dashboard/webapp/middleware
- run budget: MODEL_CALL_RECURSION_LIMIT 5000->250
- fix stale OpenAI->Anthropic fallback id (claude-opus-4-5 -> 4-8)
- drop redundant custom repair middleware (deepagents auto-adds PatchToolCalls)
- confirm tool-result eviction + summarization auto-wired via backend
- slim system prompt ~8% (full harness-profile rewrite deferred)

Co-authored-by: open-swe[bot]

* feat(rebuild): harness-profile prompt + split webhooks out of webapp

- prompt.py: own the system prompt via a registered harness profile
  (OPEN_SWE_SHARED_BASE, kept neutral so the read-only reviewer/analyzer that
  share it stay safe), registered across all 4 providers; per-thread values
  stay in construct_system_prompt. Assembled main-agent prompt ~6.8k -> ~3.1k
  tokens (~55% smaller); de-duped PR/commit/suite/force-push guidance; dropped
  ALL-CAPS markers.
- webapp.py 3325 -> 1890 LOC: moved 14 per-source handlers into
  agent/webhooks/{linear,slack,github}.py; webapp re-exports them for the
  routes + tests; moved handlers reach shared helpers via the webapp namespace
  to preserve the test suite's monkeypatch targets.

Full suite: 1168 passing, lint clean.

Co-authored-by: open-swe[bot]

* Restore MODEL_CALL_RECURSION_LIMIT to 5000 for long-running tasks

Reverts the 250 cap from the run-budget change — long-running tasks legitimately
need many model calls. The notify_step_limit_reached safety net still fires if a
run does hit the cap, so runs end with a signal either way.

Co-authored-by: open-swe[bot]

* fix: address PR review (auth, SSRF, interrupted status, redirect headers)

- completion.py: drop `interrupted` from failure statuses — with
  multitask_strategy=interrupt a follow-up ends the prior run as interrupted,
  which is healthy, not a failure to report. [open-swe]
- /webhooks/run-complete: shared-secret auth — dispatch appends ?token= when
  RUN_COMPLETE_WEBHOOK_SECRET is set; route verifies via hmac.compare_digest.
  [corridor-security]
- SSRF: extract the URL validator to agent/utils/url_safety.py and apply it
  before server-side image fetches in multimodal.fetch_image_block.
  [corridor-security]
- http_request: preserve caller headers/extensions across redirect hops instead
  of dropping them on the first hop. [open-swe]

Co-authored-by: open-swe[bot]

* chore: remove REBUILD_PLAN.md (planning doc, not needed in the repo)

Co-authored-by: open-swe[bot]

* fix: fail closed on run-complete webhook auth when secret unset

Corridor follow-up: verify_run_complete_token returns False (not True) when
RUN_COMPLETE_WEBHOOK_SECRET is unset, so the public route is never
unauthenticated. Logs a startup warning when the secret is absent, and dispatch
skips registering the webhook when there's no secret (no rejected callbacks).

Co-authored-by: open-swe[bot]

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
2026-06-26 13:48:38 -07:00

223 lines
7 KiB
Python

from __future__ import annotations
import asyncio
from typing import Any
import pytest
from agent import server
from agent.dashboard import thread_api
from agent.prompt import construct_system_prompt
def test_plan_mode_prompt_included_when_enabled() -> None:
prompt = construct_system_prompt(working_dir="/work", plan_mode=True)
assert "Plan Mode (ACTIVE)" in prompt
assert "read-only research-and-planning phase" in prompt
def test_plan_mode_prompt_absent_by_default() -> None:
prompt = construct_system_prompt(working_dir="/work")
assert "Plan Mode (ACTIVE)" not in prompt
def test_plan_mode_excluded_tools_cover_mutating_tools() -> None:
excluded = server.PLAN_MODE_EXCLUDED_TOOLS
for tool in (
"write_file",
"edit_file",
"task",
"open_pull_request",
"request_pr_review",
"linear_create_issue",
"linear_update_issue",
"linear_delete_issue",
):
assert tool in excluded
# Read-only tools must stay available.
assert "read_file" not in excluded
assert "execute" not in excluded
class _FakeThreadsClient:
async def create(
self, *, thread_id: str, metadata: dict[str, Any], if_exists: str
) -> dict[str, Any]:
return {"thread_id": thread_id, "metadata": metadata}
async def update(self, *, thread_id: str, metadata: dict[str, Any]) -> dict[str, Any]:
return {"thread_id": thread_id, "metadata": metadata}
async def get(self, thread_id: str) -> dict[str, Any]:
return {"thread_id": thread_id, "metadata": {}}
class _FakeRunsClient:
def __init__(self) -> None:
self.configurable: dict[str, Any] | None = None
async def create(
self,
thread_id: str,
assistant_id: str,
*,
input: dict[str, Any],
config: dict[str, Any],
if_not_exists: str = "reject",
stream_mode: list[str] | None = None,
stream_resumable: bool = False,
) -> dict[str, str]:
self.configurable = config["configurable"]
return {"run_id": "run-id"}
class _FakeLangGraphClient:
def __init__(self) -> None:
self.threads = _FakeThreadsClient()
self.runs = _FakeRunsClient()
@pytest.fixture
def dashboard_run_client(monkeypatch: pytest.MonkeyPatch) -> _FakeLangGraphClient:
client = _FakeLangGraphClient()
async def fake_get_profile(login: str) -> dict[str, Any]:
return {}
async def fake_ensure_token(login: str) -> None:
return None
async def fake_resolve_email(login: str, profile: dict[str, Any]) -> str:
return "octo@example.com"
monkeypatch.setattr(thread_api, "langgraph_client", lambda: client)
monkeypatch.setattr(thread_api, "get_profile", fake_get_profile)
monkeypatch.setattr(thread_api, "_ensure_dashboard_github_token", fake_ensure_token)
monkeypatch.setattr(thread_api, "_resolve_run_email", fake_resolve_email)
return client
def _run_start_command(plan_mode: bool | None) -> dict[str, Any]:
configurable: dict[str, Any] = {}
if plan_mode is not None:
configurable["plan_mode"] = plan_mode
return {
"method": "run.start",
"params": {
"input": {"messages": [{"role": "user", "content": "do work"}]},
"config": {"configurable": configurable},
},
}
def test_run_start_passes_plan_mode_when_enabled(
dashboard_run_client: _FakeLangGraphClient,
) -> None:
enriched = asyncio.run(
thread_api._enrich_run_start_command(
"thread-id",
"octo",
_run_start_command(True),
metadata={"source": "dashboard", "github_login": "octo"},
creating=False,
)
)
configurable = enriched["params"]["config"]["configurable"]
assert configurable["plan_mode"] is True
def test_run_start_omits_plan_mode_when_disabled(
dashboard_run_client: _FakeLangGraphClient,
) -> None:
enriched = asyncio.run(
thread_api._enrich_run_start_command(
"thread-id",
"octo",
_run_start_command(None),
metadata={"source": "dashboard", "github_login": "octo"},
creating=False,
)
)
configurable = enriched["params"]["config"]["configurable"]
assert "plan_mode" not in configurable
def test_thread_summary_reports_plan_mode() -> None:
summary = thread_api._thread_summary(
{"thread_id": "t1", "metadata": {"source": "dashboard", "plan_mode": True}}
)
assert summary["planMode"] is True
summary_off = thread_api._thread_summary(
{"thread_id": "t2", "metadata": {"source": "dashboard"}}
)
assert summary_off["planMode"] is False
def test_plan_mode_guidance_section_always_present() -> None:
"""The guidance section telling the agent about enter_plan_mode should be in every prompt."""
prompt = construct_system_prompt(working_dir="/work", plan_mode=False)
assert "enter_plan_mode" in prompt
assert "Plan Mode" in prompt
def test_plan_mode_guidance_section_present_when_enabled() -> None:
prompt = construct_system_prompt(working_dir="/work", plan_mode=True)
assert "enter_plan_mode" in prompt
assert "Plan Mode (ACTIVE)" in prompt
async def test_enter_plan_mode_tool_returns_command() -> None:
from langchain_core.messages import ToolMessage
from langchain_core.tools import tool as as_tool
from langgraph.types import Command
from agent.tools.enter_plan_mode import enter_plan_mode
# Wrap as the agent does so the InjectedToolCallId is supplied from the call.
wrapped = as_tool(enter_plan_mode)
result = await wrapped.ainvoke(
{"name": "enter_plan_mode", "args": {}, "id": "call-1", "type": "tool_call"}
)
assert isinstance(result, Command)
assert result.update["plan_mode"] is True
messages = result.update["messages"]
assert len(messages) == 1
assert isinstance(messages[0], ToolMessage)
assert messages[0].tool_call_id == "call-1"
def test_enter_plan_mode_exported() -> None:
from agent.tools import enter_plan_mode
assert callable(enter_plan_mode)
def test_build_plan_approval_blocks_has_three_buttons() -> None:
from agent.tools.slack_thread_reply import _build_plan_approval_blocks
blocks = _build_plan_approval_blocks("Here is my plan")
assert len(blocks) == 2
assert blocks[0]["type"] == "section"
actions = blocks[1]
assert actions["type"] == "actions"
elements = actions["elements"]
assert len(elements) == 3
texts = [e["text"]["text"] for e in elements]
assert "Approve & Implement" in texts
assert "Revise Plan" in texts
assert "Cancel" in texts
def test_build_plan_approval_blocks_values_have_plan_approval_type() -> None:
import json
from agent.tools.slack_thread_reply import _build_plan_approval_blocks
blocks = _build_plan_approval_blocks("plan text")
for element in blocks[1]["elements"]:
value = json.loads(element["value"])
assert value["type"] == "plan_approval"
assert value["action"] in ("approve", "revise", "cancel")