open-swe/tests/test_plan_mode.py
Adam Moussa b3b0274403
feat: Re-land deferred upstream features on modular webhooks (#80) (#128)
* fix(webhooks): fall back to vision model for Slack/Linear image threads

Re-land upstream #1626 onto the modular webhook structure. When a
Slack mention or Linear issue carries images but the resolved model is
text-only, fall back to a vision-capable model instead of dropping the
images. Re-points default_vision_model_pair at the fork's image-capable
models (Opus 4.8 default, else any supports_images model) rather than
upstream's openai:/anthropic: provider filter.

Refs #80, upstream #1626

* fix(slack): persist trace_message_ts so web-handoff updates the trace reply

Re-land upstream #1630 onto the modular structure. The first-mention
store_slack_run_mapping call did not pass trace_message_ts, so it was
never persisted (nothing to preserve from on first mention) and
_notify_slack_web_handoff always skipped the trace-reply update on web
handoff. Pass it through and cover it with a test.

Refs #80, upstream #1630

* feat(slack): include channel context in Slack prompts

Re-land upstream #1633 onto the modular structure. Fetch cached Slack
channel metadata once per event (_get_slack_channel_context) and thread
it through the docs-plz gate, repo resolution, and process_slack_mention
so prompts carry the channel name and a clearly-marked untrusted
channel description. Avoids duplicate conversations.info calls.

Refs #80, upstream #1633

* feat(tools): add slack_start_new_thread breakout tool

Re-land upstream #1638 onto the modular structure. Adds the
slack_start_new_thread tool (posts a top-level Slack message and
dispatches a fresh agent run for a broken-out task via the durable
dispatch_agent_run contract), wires it into the agent tool list and
tools/__init__, adds prompt guidance, and excludes it from plan mode so
it can't bypass the approval flow. Tool imports only live modules.

Refs #80, upstream #1638

* feat(plan): notify Slack on plan approval

Re-land upstream #1632 onto the modular structure. When a plan is
approved via the dashboard approve endpoint, post a thread reply to the
originating Slack thread noting the comment count and approver, after
the follow-up run is dispatched. Slack post failures never break
approval. Adapted to the fork's approve_plan (no plan_markdown read).

Refs #80, upstream #1632

* feat(plan): publish plans from sandbox files

Re-land upstream #1635 onto the modular structure, completing the
partially-ported change so dev is internally consistent. save_plan now
takes a plan_file_path, reads the agent-authored Markdown file from
/workspace/plans/ (validating extension/location/UTF-8/size) and
publishes it, instead of taking a plan_markdown string. Removes
write_file/edit_file from PLAN_MODE_EXCLUDED_TOOLS so the agent can
author the plan file, updates enter_plan_mode/reject_plan guidance and
the e2e fake LLM. Skips the #1610-only update_plan hunk (not on dev).

Refs #80, upstream #1635

* fix(security): SSRF-harden server-side image fetch + stop logging raw image URLs

INJ-01 (high): fetch_image_block used follow_redirects=True with no per-hop
revalidation and discarded the resolved-IP pin, so an attacker-authored Slack/
Linear image URL could 302-redirect the fetch to an internal host / cloud
metadata endpoint (blind SSRF), and DNS-rebinding could bypass the one-shot
is_url_safe check. Route image fetches through the same per-hop resolve+pin+
revalidate loop the http_request tool uses, lifted into url_safety as the shared
request_with_safe_redirects. Also strip the per-host Slack/Linear bearer token
on redirect so it can't be replayed to a redirect target.

SC-1 (low): linear.py logged full image URLs (which can carry signed tokens) at
DEBUG; multimodal logged them at INFO on every fetch. Log host-only.

Sink lived in multimodal.py (unchanged by the feature work) but PR #128 widened
its reach by no longer dropping images for text-only models. Fixing on the base
branch so #130/#129 inherit it on rebase. Adds fetch_image_block SSRF regression
tests (redirect-to-internal blocked; auth stripped on redirect).
2026-07-08 18:32:43 -04:00

226 lines
7.2 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 (
"task",
"open_pull_request",
"request_pr_review",
"slack_start_new_thread",
"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
# File edit tools stay available so the agent can author the plan file under
# /workspace/plans/ (restricted to that path via prompt guidance).
assert "write_file" not in excluded
assert "edit_file" 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")