mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-09 16:08:31 +00:00
* 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.
163 lines
5.6 KiB
Python
163 lines
5.6 KiB
Python
"""Tests for the GitHubChannel.
|
|
|
|
The channel is log-only on the outbound path: GitHub agents have ``gh`` in
|
|
their sandbox and post comments themselves mid-run, so the channel does NOT
|
|
auto-deliver the agent's final assistant message to GitHub. These tests pin
|
|
that contract — any regression that re-introduces an HTTP call during
|
|
``send`` will fail the httpx tripwire.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from unittest.mock import AsyncMock
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
import app.channels.github as github_channel_module
|
|
from app.channels.github import GitHubChannel
|
|
from app.channels.manager import CHANNEL_CAPABILITIES
|
|
from app.channels.message_bus import MessageBus, OutboundMessage
|
|
from app.channels.service import _CHANNEL_REGISTRY
|
|
|
|
|
|
def test_github_channel_registered() -> None:
|
|
assert _CHANNEL_REGISTRY["github"] == "app.channels.github:GitHubChannel"
|
|
|
|
|
|
def test_github_channel_capabilities_non_streaming() -> None:
|
|
# GitHub comments are single-shot; no in-place editing (yet).
|
|
assert CHANNEL_CAPABILITIES["github"]["supports_streaming"] is False
|
|
|
|
|
|
def test_github_channel_does_not_import_writeback() -> None:
|
|
"""The ``writeback`` module has been deleted — confirm the channel does
|
|
not re-import it under any name."""
|
|
# Check both the old module path and any httpx usage inside the channel
|
|
assert "app.gateway.github.writeback" not in dir(github_channel_module)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_subscribes_outbound_and_stop_unsubscribes() -> None:
|
|
bus = MessageBus()
|
|
channel = GitHubChannel(bus=bus, config={"enabled": True})
|
|
|
|
assert channel.is_running is False
|
|
assert bus._outbound_listeners == []
|
|
|
|
await channel.start()
|
|
assert channel.is_running is True
|
|
assert bus._outbound_listeners == [channel._on_outbound]
|
|
|
|
await channel.stop()
|
|
assert channel.is_running is False
|
|
assert bus._outbound_listeners == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_never_posts_to_github(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
|
"""The contract: ``send`` logs but never makes an HTTP call.
|
|
|
|
We patch ``httpx.AsyncClient.request`` as the tripwire — the channel
|
|
(unlike the old ``writeback`` module) has no business talking to GitHub
|
|
over HTTP. If a future refactor wires it back, the mock will be awaited
|
|
and the test fails.
|
|
"""
|
|
bus = MessageBus()
|
|
channel = GitHubChannel(bus=bus, config={})
|
|
|
|
tripwire = AsyncMock()
|
|
monkeypatch.setattr(httpx.AsyncClient, "request", tripwire)
|
|
|
|
out = OutboundMessage(
|
|
channel_name="github",
|
|
chat_id="zhfeng/llm-gateway",
|
|
thread_id="t-1",
|
|
text="Hello from the agent.",
|
|
metadata={
|
|
"github": {
|
|
"repo": "zhfeng/llm-gateway",
|
|
"number": 7,
|
|
"installation_id": 1234,
|
|
}
|
|
},
|
|
)
|
|
with caplog.at_level(logging.INFO, logger="app.channels.github"):
|
|
await channel.send(out)
|
|
|
|
tripwire.assert_not_awaited()
|
|
assert any("final message from agent for zhfeng/llm-gateway#7" in rec.message and "not posted" in rec.message for rec in caplog.records)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_logs_empty_body_at_info(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
|
"""An empty final message still gets the info log (text_len=0). The body
|
|
debug line is skipped when there's nothing to mirror."""
|
|
bus = MessageBus()
|
|
channel = GitHubChannel(bus=bus, config={})
|
|
|
|
tripwire = AsyncMock()
|
|
monkeypatch.setattr(httpx.AsyncClient, "request", tripwire)
|
|
|
|
out = OutboundMessage(
|
|
channel_name="github",
|
|
chat_id="a/b",
|
|
thread_id="t",
|
|
text="",
|
|
metadata={"github": {"repo": "a/b", "number": 1, "installation_id": 1}},
|
|
)
|
|
with caplog.at_level(logging.DEBUG, logger="app.channels.github"):
|
|
await channel.send(out)
|
|
|
|
tripwire.assert_not_awaited()
|
|
assert any("text_len=0" in rec.message for rec in caplog.records)
|
|
assert not any("final body" in rec.message for rec in caplog.records)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_tolerates_missing_metadata(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
|
"""No github metadata block: log line falls back to ``chat_id`` as the
|
|
repo and ``None`` for the number. Still no HTTP call."""
|
|
bus = MessageBus()
|
|
channel = GitHubChannel(bus=bus, config={})
|
|
|
|
tripwire = AsyncMock()
|
|
monkeypatch.setattr(httpx.AsyncClient, "request", tripwire)
|
|
|
|
out = OutboundMessage(
|
|
channel_name="github",
|
|
chat_id="a/b",
|
|
thread_id="t",
|
|
text="hi",
|
|
metadata={}, # no github block at all
|
|
)
|
|
with caplog.at_level(logging.INFO, logger="app.channels.github"):
|
|
await channel.send(out)
|
|
|
|
tripwire.assert_not_awaited()
|
|
# ``chat_id`` falls in as the repo when metadata is absent.
|
|
assert any("a/b" in rec.message for rec in caplog.records)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_handles_non_dict_github_metadata(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
|
"""Defensive: a stringly-typed ``metadata["github"]`` must not raise."""
|
|
bus = MessageBus()
|
|
channel = GitHubChannel(bus=bus, config={})
|
|
|
|
tripwire = AsyncMock()
|
|
monkeypatch.setattr(httpx.AsyncClient, "request", tripwire)
|
|
|
|
out = OutboundMessage(
|
|
channel_name="github",
|
|
chat_id="a/b",
|
|
thread_id="t",
|
|
text="hi",
|
|
metadata={"github": "not-a-dict"},
|
|
)
|
|
with caplog.at_level(logging.INFO, logger="app.channels.github"):
|
|
await channel.send(out)
|
|
|
|
tripwire.assert_not_awaited()
|
|
assert any("a/b" in rec.message for rec in caplog.records)
|