deer-flow/backend/tests/test_github_prompts.py
Zheng Feng dcb2e687d5
feat(channels): add GitHub as a webhook-driven channel (#3754)
* feat(channels): add GitHub event-driven agents (#3754)

Add a webhook-driven GitHub channel with fail-closed webhook routing, deterministic per-agent PR/issue threads, mention-gated trigger fan-out, GitHub App token injection for sandboxed gh/git commands, and backend/AGENTS.md documentation.

* fix(llm-middleware): classify bare IndexError as transient

Upstream chat providers occasionally return 200 OK with an empty
generations list (observed against Volces "coding" on
ark.cn-beijing.volces.com). When that happens,
langchain_core.language_models.chat_models.ainvoke raises
``IndexError: list index out of range`` at
``llm_result.generations[0][0].message`` and kills the run.

Treat a bare IndexError reaching the middleware as a transient
upstream-payload glitch and route it through the existing
retry/backoff path instead of failing the whole agent run. The
retry budget and backoff schedule are unchanged.

Adds three regression tests covering the classifier and both the
recover-on-retry and exhausted-retries paths.

* fix(runtime): ignore stale LLM fallback markers from prior runs

When a run on a thread ends with the LLM-error-handling middleware emitting
a `deerflow_error_fallback`-marked AIMessage (e.g. after the IndexError
empty-generations classification fix lands), that message is persisted to
the thread's checkpoint as part of the messages channel. LangGraph replays
the full message history in `stream_mode="values"` chunks, so every
subsequent run on the same thread re-streams the stale fallback marker —
and the worker's chunk scanner faithfully picks it up, flipping
`RunStatus.success` to `RunStatus.error` for runs that themselves had
no LLM failure at all.

Snapshot the set of pre-existing message ids from the pre-run checkpoint
and thread it through `_extract_llm_error_fallback_message` /
`_try_extract_from_message` as a filter. Markers on history messages are
ignored; markers on fresh messages produced during this run still trip
the error path. Falls back to an empty set when the checkpointer is
absent or the snapshot can't be captured, preserving the prior behavior
on first-run / no-state paths.

Adds unit tests for the new filter (helper-level and `_collect_pre_existing_message_ids`)
plus an integration test exercising the full `run_agent` path with a stale
history checkpointer.

* fix(channels): make github channel fire-and-forget to avoid httpx.ReadTimeout on long runs

GitHub agent runs (clone -> edit -> test -> push -> PR) routinely exceed
the langgraph_sdk default 300s read deadline. The manager's runs.wait
call kept an HTTP stream open for the entire run lifetime, so the long
run blew up with httpx.ReadTimeout and the outer except branch then
released the dedupe key and emitted a false 'internal error' outbound.

The GitHub channel's outbound send is log-only by design: agents post to
the issue/PR via the gh CLI in the sandbox when they choose to comment
or create a PR. There is nothing for the manager to ferry back, so the
long-poll was pure overhead.

This change adds ChannelRunPolicy.fire_and_forget (default False) and
sets it True for the github channel. When fire_and_forget is True,
_handle_chat dispatches via client.runs.create (short POST, returns
once the run is pending) instead of client.runs.wait, and skips the
response-extraction + outbound-publish block. ConflictError on a busy
thread still trips the standard THREAD_BUSY_MESSAGE path so behavior on
the busy case is preserved for any future non-github fire-and-forget
channel.

Other (non-github) channels are unchanged: their policy defaults
fire_and_forget=False and they continue to dispatch via runs.wait.

Adds 6 regression tests in tests/test_channels.py::TestGithubFireAndForget:
- Default ChannelRunPolicy.fire_and_forget is False.
- The github policy registers fire_and_forget=True.
- github inbound calls runs.create, not runs.wait, with the right kwargs.
- github inbound publishes no outbound on success.
- ConflictError from runs.create still emits THREAD_BUSY_MESSAGE.
- Non-github channels (slack) still dispatch via runs.wait.

* test(lead-agent): accept user_id kwarg in skill-policy test stubs

The two GitHub-channel tests added in #3754 stubbed
_load_enabled_skills_for_tool_policy with a lambda that only accepted
`available_skills` and `app_config`, but the real function (and its call
site in agent.py) also passes `user_id`. This raised TypeError on every
run, failing backend-unit-tests.

Add `user_id=None` to match the three sibling stubs in the same file.

* refactor(gateway): disambiguate context-key set names

The two frozensets _INTERNAL_ONLY_CONTEXT_KEYS and _CONTEXT_ONLY_KEYS
shared a confusable "CONTEXT_ONLY" token in different orders, and the
first broke the _CONTEXT_<X>_KEYS pattern of its sibling
_CONTEXT_CONFIGURABLE_KEYS. Rename to make the distinct axes explicit:

  _CONTEXT_INTERNAL_CALLER_KEYS  - WHO: internal callers (scheduler) only
  _CONTEXT_RUNTIME_ONLY_KEYS     - WHERE: runtime context only, never configurable

Pure rename, no behavior change.
2026-07-04 22:56:24 +08:00

216 lines
6.9 KiB
Python

"""Tests for the GitHub webhook → prompt translator."""
from __future__ import annotations
from app.gateway.github.prompts import build_prompt
def test_pull_request_prompt_contains_core_fields() -> None:
payload = {
"action": "opened",
"pull_request": {
"number": 7,
"title": "Add webhook receiver",
"user": {"login": "zhfeng"},
"html_url": "https://github.com/a/b/pull/7",
"body": "This adds X and fixes Y.",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request", payload)
assert "pull request" in prompt.lower()
assert "#7" in prompt
assert "Add webhook receiver" in prompt
assert "zhfeng" in prompt
assert "https://github.com/a/b/pull/7" in prompt
assert "This adds X and fixes Y." in prompt
def test_pull_request_prompt_handles_missing_body() -> None:
payload = {
"action": "opened",
"pull_request": {"number": 1, "title": "x", "user": {}, "body": None},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request", payload)
assert "(no description)" in prompt
def test_pull_request_prompt_truncates_huge_body() -> None:
huge = "X" * 50000
payload = {
"action": "opened",
"pull_request": {"number": 1, "title": "x", "user": {}, "body": huge},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request", payload)
assert "truncated" in prompt
assert len(prompt) < 10000
def test_issue_comment_prompt_includes_body_verbatim() -> None:
payload = {
"action": "created",
"issue": {"number": 11, "pull_request": {"url": "..."}},
"comment": {
"body": "Hey @coding-llm-gateway please look at this",
"user": {"login": "zhfeng"},
"html_url": "https://github.com/a/b/issues/11#issuecomment-1",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("issue_comment", payload)
assert "pull request #11" in prompt # is_pr True
assert "@coding-llm-gateway please look at this" in prompt
assert "zhfeng" in prompt
def test_issue_comment_plain_issue_says_issue() -> None:
payload = {
"action": "created",
"issue": {"number": 12},
"comment": {"body": "x", "user": {"login": "u"}},
"repository": {"full_name": "a/b"},
}
assert "issue #12" in build_prompt("issue_comment", payload)
def test_issue_comment_prompt_includes_issue_title_and_body() -> None:
"""The comment alone isn't enough — the agent needs the issue context too.
The webhook payload already includes the parent issue/PR's title and body
on the ``issue`` object; we just have to render them.
"""
payload = {
"action": "created",
"issue": {
"number": 42,
"title": "Login button is broken",
"body": "Clicking login throws a 500. Repro: open /login, click submit.",
"user": {"login": "reporter"},
},
"comment": {
"body": "@bot what do you think?",
"user": {"login": "asker"},
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("issue_comment", payload)
assert "Login button is broken" in prompt
assert "Clicking login throws a 500" in prompt
assert "reporter" in prompt # issue author, distinct from comment author
assert "@bot what do you think?" in prompt
def test_pull_request_review_comment_includes_pr_title_and_body() -> None:
payload = {
"action": "created",
"pull_request": {
"number": 9,
"title": "Refactor auth flow",
"body": "Splits AuthService into AuthN/AuthZ.",
"user": {"login": "author"},
},
"comment": {
"user": {"login": "alice"},
"path": "src/foo.py",
"line": 42,
"diff_hunk": "@@ -1 +1 @@\n-a\n+b",
"body": "consider renaming",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request_review_comment", payload)
assert "Refactor auth flow" in prompt
assert "Splits AuthService into AuthN/AuthZ." in prompt
assert "consider renaming" in prompt
def test_pull_request_review_prompt_includes_pr_title_and_body() -> None:
payload = {
"action": "submitted",
"pull_request": {
"number": 5,
"title": "Bump deps",
"body": "Updates everything to latest.",
"user": {"login": "author"},
},
"review": {
"state": "changes_requested",
"user": {"login": "alice"},
"body": "Looks risky",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request_review", payload)
assert "Bump deps" in prompt
assert "Updates everything to latest." in prompt
assert "changes_requested" in prompt
assert "Looks risky" in prompt
def test_pull_request_review_comment_includes_file_and_diff() -> None:
payload = {
"action": "created",
"pull_request": {"number": 9},
"comment": {
"user": {"login": "alice"},
"path": "src/foo.py",
"line": 42,
"diff_hunk": "@@ -1,3 +1,4 @@\n a\n+b\n c",
"body": "consider renaming",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request_review_comment", payload)
assert "src/foo.py:42" in prompt
assert "+b" in prompt
assert "consider renaming" in prompt
def test_pull_request_review_prompt_includes_state() -> None:
payload = {
"action": "submitted",
"pull_request": {"number": 5},
"review": {
"state": "changes_requested",
"user": {"login": "alice"},
"body": "Looks risky",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("pull_request_review", payload)
assert "changes_requested" in prompt
assert "Looks risky" in prompt
assert "alice" in prompt
def test_issues_prompt() -> None:
payload = {
"action": "opened",
"issue": {
"number": 3,
"title": "bug",
"user": {"login": "u"},
"html_url": "https://github.com/a/b/issues/3",
"body": "things broken",
},
"repository": {"full_name": "a/b"},
}
prompt = build_prompt("issues", payload)
assert "#3" in prompt
assert "bug" in prompt
assert "things broken" in prompt
def test_ping_prompt() -> None:
payload = {"zen": "Practicality beats purity.", "hook": {"id": 42}}
prompt = build_prompt("ping", payload)
assert "ping" in prompt.lower()
assert "42" in prompt
def test_unknown_event_returns_generic_stub() -> None:
prompt = build_prompt("workflow_run", {"action": "completed", "repository": {"full_name": "a/b"}})
assert "workflow_run" in prompt
assert "a/b" in prompt