Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(deepresearch): raise final report output limits

oyk43b0cbc81b65
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
index 29dc93bd6f..971956434d 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
@@ -86,7 +86,10 @@ MAX_SECTION_COUNT = 256
MAX_STATE_ENTRIES = 256
MAX_IDENTIFIER_CHARS = 1024
MAX_CHUNK_TEXT_CHARS = 1_048_576
-MAX_TERMINAL_RESULT_TEXT_CHARS = 16 * 1024 * 1024
+# Complete reports include citations, charts and metadata. Keep this budget
+# separate from process-display limits; depth and identifier bounds still apply.
+MAX_TERMINAL_RESULT_TEXT_CHARS = 64 * 1024 * 1024
+MAX_TERMINAL_RESULT_JSON_NODES = 100_000
MAX_ACCUMULATED_TEXT_CHARS = 1_048_576
MAX_JSON_DEPTH = 64
MAX_JSON_NODES = 16_384
@@ -191,20 +194,24 @@ def _validate_identifier(value: Any) -> str:
def _validate_json_shape(
- value: Any, *, max_text_chars: int = MAX_CHUNK_TEXT_CHARS
+ value: Any,
+ *,
+ max_text_chars: int = MAX_CHUNK_TEXT_CHARS,
+ max_nodes: int | None = None,
) -> int:
"""Bound container traversal without recursion or copying caller data."""
stack: list[tuple[Any, int, bool]] = [(value, 0, False)]
active: set[int] = set()
nodes = 0
text_chars = 0
+ node_limit = MAX_JSON_NODES if max_nodes is None else max_nodes
while stack:
current, depth, leaving = stack.pop()
if leaving:
active.discard(id(current))
continue
nodes += 1
- if nodes > MAX_JSON_NODES or depth > MAX_JSON_DEPTH:
+ if nodes > node_limit or depth > MAX_JSON_DEPTH:
raise ValueError(ROUTER_LIMIT_ERROR)
if isinstance(current, str):
if len(current) > max_text_chars:
@@ -372,9 +379,15 @@ def _validate_router_input(
incoming_text_chars = 0
for key in ("content", "reasoning_content"):
value = chunk.get(key)
- if value is not None and not (
- terminal_result_content and key == "content"
- ):
+ if value is None:
+ continue
+ if terminal_result_content and key == "content":
+ _validate_json_shape(
+ value,
+ max_text_chars=MAX_TERMINAL_RESULT_TEXT_CHARS,
+ max_nodes=MAX_TERMINAL_RESULT_JSON_NODES,
+ )
+ else:
incoming_text_chars += _validate_json_shape(value)
if len(state.active_nodes) > MAX_STATE_ENTRIES:
raise ValueError(ROUTER_LIMIT_ERROR)
@@ -791,6 +804,20 @@ def _can_start_final_report(state: RouterState, agent: str) -> bool:
return agent in BRIEF_FINAL_REPORT_NODES or _all_sections_completed(state)
+def is_terminal_result_chunk(value: Any) -> bool:
+ """Identify result envelopes without parsing or trusting their contents."""
+ if not isinstance(value, dict):
+ return False
+ if (value.get("__deepsearch_status__") or value.get("status")) == "completed":
+ return isinstance(value.get("final_result"), dict)
+ return (
+ value.get("agent") == "end"
+ and str(value.get("section_idx", "0")).strip() in {"", "0"}
+ and value.get("event") in ("summary_response", "error")
+ and isinstance(value.get("content"), (str, dict))
+ )
+
+
def _is_successful_workflow_end(chunk: dict, agent: str, event: str) -> bool:
"""Recognize the SDK EndNode result emitted after the workflow has finished."""
if (
@@ -803,12 +830,14 @@ def _is_successful_workflow_end(chunk: dict, agent: str, event: str) -> bool:
_validate_json_shape(
content,
max_text_chars=MAX_TERMINAL_RESULT_TEXT_CHARS,
+ max_nodes=MAX_TERMINAL_RESULT_JSON_NODES,
)
result = _as_json_object(content)
if result is not None:
_validate_json_shape(
result,
max_text_chars=MAX_TERMINAL_RESULT_TEXT_CHARS,
+ max_nodes=MAX_TERMINAL_RESULT_JSON_NODES,
)
return bool(
result
@@ -927,14 +956,11 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
section_idx = _validate_identifier(chunk.get("section_idx", "0")) or "0"
# The EndNode embeds the complete final result in ``content`` (1+ MiB).
# It is a workflow boundary, not process text for the frontend, so keep it
- # under the terminal 16 MiB protocol bound without applying the 1 MiB
+ # under the terminal result budget without applying the 1 MiB
# process-display accumulator limit — even when the result carries
# non-fatal exception_info (the SDK then emits event=error). Delivery is
# still gated by _is_successful_workflow_end below.
- is_end_node = (
- agent == "end"
- and section_idx in {"", "0"}
- )
+ is_end_node = agent == "end" and is_terminal_result_chunk(chunk)
successful_workflow_end = _is_successful_workflow_end(chunk, agent, event)
_validate_router_input(
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index 02433cbe6f..37e31baa56 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -44,6 +44,8 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (
)
from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
FINAL_REPORT_NODES,
+ MAX_TERMINAL_RESULT_JSON_NODES,
+ MAX_TERMINAL_RESULT_TEXT_CHARS,
ROUTER_LIMIT_ERROR,
RouterState,
_format_outline_card_markdown,
@@ -52,6 +54,7 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
collected_questions,
complete_final_report_processing,
is_outline_status_placeholder,
+ is_terminal_result_chunk,
route_chunk,
stage_for_resume_node,
start_final_report_processing,
@@ -100,12 +103,15 @@ DEEPRESEARCH_RACE_DELIVERY_TIMEOUT_SECONDS = 60.0
# 真实管道在子进程退出后毫秒级 EOF;窗口只防异常管道/测试桩永久不 EOF。
DEEPRESEARCH_DRAIN_EOF_GRACE_SECONDS = 2.0
DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES = 16 * 1024 * 1024
+# A UTF-8 result can require four bytes per character. This is a per-frame
+# wire bound; ordinary frames still retain their original 16 MiB limit.
+DEEPRESEARCH_STDOUT_TERMINAL_MAX_BYTES = 4 * MAX_TERMINAL_RESULT_TEXT_CHARS
DEEPRESEARCH_STDERR_TAIL_MAX_BYTES = 20_000
DEEPRESEARCH_ERROR_TEXT_MAX_CHARS = 2048
DEEPRESEARCH_STDERR_OUTCOME_MAX_CHARS = 2048
_HUAWEI_MAAS_PLACEHOLDER_API_KEY = "huawei-maas-session"
DEEPRESEARCH_STREAM_JSON_MAX_DEPTH = 64
-DEEPRESEARCH_STREAM_JSON_MAX_NODES = 100_000
+DEEPRESEARCH_STREAM_JSON_MAX_NODES = MAX_TERMINAL_RESULT_JSON_NODES
DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS = 16 * 1024 * 1024
DEEPRESEARCH_FINAL_REPORT_PROGRESS_INTERVAL_SECONDS = 60.0
DEEPRESEARCH_OUTLINE_CACHE_TENANTS = 256
@@ -820,6 +826,10 @@ def _redact_json_value(value: Any, secrets: tuple[str, ...]) -> Any:
stack: list[tuple[Any, Any, int]] = [(value, root, 0)]
nodes = 0
text_chars = 0
+ text_limit = (
+ MAX_TERMINAL_RESULT_TEXT_CHARS if is_terminal_result_chunk(value)
+ else DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS
+ )
while stack:
source, target, depth = stack.pop()
if depth > DEEPRESEARCH_STREAM_JSON_MAX_DEPTH:
@@ -866,7 +876,7 @@ def _redact_json_value(value: Any, secrets: tuple[str, ...]) -> Any:
target[key] = child
else:
target.append(child)
- if text_chars > DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS:
+ if text_chars > text_limit:
raise _StreamProtocolInvalid("JSON text limit exceeded")
return root
@@ -922,6 +932,10 @@ def _validate_stream_json_shape(value: Any) -> bool:
stack: list[tuple[Any, int]] = [(value, 0)]
nodes = 0
text_chars = 0
+ text_limit = (
+ MAX_TERMINAL_RESULT_TEXT_CHARS if is_terminal_result_chunk(value)
+ else DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS
+ )
while stack:
item, depth = stack.pop()
nodes += 1
@@ -942,7 +956,7 @@ def _validate_stream_json_shape(value: Any) -> bool:
text_chars += len(item)
elif item is not None and not isinstance(item, (bool, int, float)):
return False
- if text_chars > DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS:
+ if text_chars > text_limit:
return False
return True
@@ -1017,6 +1031,8 @@ def _capture_completed_frame(line: bytes, captured: dict[str, Any]) -> None:
return
if not isinstance(chunk, dict):
return
+ if not _validate_stream_json_shape(chunk):
+ return
status_value = chunk.get("__deepsearch_status__") or chunk.get("status")
if status_value != "completed":
return
@@ -1044,28 +1060,19 @@ async def _drain_stream_while_stopping(
read = getattr(stream, "read", None)
if not callable(read):
return
- pending = bytearray()
- while True:
+ if captured is not None:
try:
- chunk = await read(64 * 1024)
- except (OSError, ValueError):
- return
- if not chunk:
+ async for line in _iter_ndjson_lines(stream):
+ _capture_completed_frame(line, captured)
return
- if captured is None:
- continue
- pending.extend(chunk)
- if len(pending) > DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES:
- # 无换行的异常输出:丢弃已有内容防止无界膨胀,继续排空。
- pending.clear()
- continue
- while True:
- newline = pending.find(b"\n")
- if newline < 0:
- break
- line = bytes(pending[:newline])
- del pending[: newline + 1]
- _capture_completed_frame(line, captured)
+ except (OSError, ValueError):
+ # Keep draining malformed output so the stopping child can exit.
+ pass
+ try:
+ while await read(64 * 1024):
+ pass
+ except (OSError, ValueError):
+ return
async def _request_graceful_stop(
@@ -1151,9 +1158,31 @@ async def _iter_ndjson_lines(
_safe_log_correlation_id(conversation_id),
)
+ def check_limit(size: int, limit: int) -> None:
+ if size > limit:
+ logger.error(
+ "[deepresearch_stream] stdout frame limit exceeded "
+ "pending_bytes=%s limit_bytes=%s request_id=%s session_id=%s "
+ "conversation_id=%s",
+ size, limit, *correlation_ids,
+ )
+ raise ValueError("deepresearch_stdout_limit_exceeded")
+
+ def validate_frame(line: bytes) -> None:
+ check_limit(len(line), DEEPRESEARCH_STDOUT_TERMINAL_MAX_BYTES)
+ if len(line) <= DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES:
+ return
+ try:
+ value = json.loads(line)
+ except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):
+ value = None
+ if not is_terminal_result_chunk(value):
+ check_limit(len(line), DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES)
+
read = getattr(stream, "read", None)
if not callable(read):
async for line in stream:
+ validate_frame(line)
yield line
return
pending = bytearray()
@@ -1161,25 +1190,23 @@ async def _iter_ndjson_lines(
chunk = await read(read_size)
if not chunk:
break
+ search_from = len(pending)
pending.extend(chunk)
- if len(pending) > DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES:
- logger.error(
- "[deepresearch_stream] stdout frame limit exceeded "
- "pending_bytes=%s limit_bytes=%s request_id=%s session_id=%s "
- "conversation_id=%s",
- len(pending),
- DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES,
- *correlation_ids,
- )
- raise ValueError("deepresearch_stdout_limit_exceeded")
while True:
- newline = pending.find(b"\n")
+ newline = pending.find(b"\n", search_from)
if newline < 0:
break
- yield bytes(pending[:newline])
+ check_limit(newline, DEEPRESEARCH_STDOUT_TERMINAL_MAX_BYTES)
+ line = bytes(pending[:newline])
del pending[: newline + 1]
+ validate_frame(line)
+ yield line
+ search_from = 0
+ check_limit(len(pending), DEEPRESEARCH_STDOUT_TERMINAL_MAX_BYTES)
if pending:
- yield bytes(pending)
+ line = bytes(pending)
+ validate_frame(line)
+ yield line
async def _await_with_periodic_progress(
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py
index c9b522781a..1bd76c4682 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py
@@ -24,7 +24,9 @@ SAFE_BUNDLE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")
RESPONSE_CONTENT_MAX_BYTES = 10 * 1024 * 1024
INFER_MESSAGE_MAX = 20
-CHART_MESSAGE_MAX = 20
+# Multi-section SDK reports can contain dozens of charts. Bound their count
+# separately from the per-image and aggregate decoded-byte limits below.
+CHART_MESSAGE_MAX = 512
BASE64_FIELD_MAX_BYTES = 5 * 1024 * 1024
DECODED_BINARY_TOTAL_MAX_BYTES = 100 * 1024 * 1024
CITATION_COUNT_MAX = 10_000
diff --git a/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py b/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py
index 838b9eb075..6e61df15d5 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py
@@ -46,6 +46,40 @@ def _chart(resource_id: str, payload: bytes = b"png-bytes") -> dict:
}
[email protected]("chart_count", [32, 104, 512])
+def test_build_report_bundle_preserves_large_chart_sets(tmp_path, chart_count):
+ charts = [_chart(f"chart-{index}") for index in range(chart_count)]
+ bundle = build_report_bundle(
+ _payload(
+ response_content="\n".join(
+ f"(#insertChart:{chart['chart_id']})" for chart in charts
+ ),
+ chart_messages=charts,
+ ),
+ tmp_path / "report-v1",
+ )
+
+ assert len(bundle.chart_manifest) == chart_count
+ snapshot = json.loads(serialize_final_result_snapshot(bundle.final_result_snapshot))
+ assert len(snapshot["chart_messages"]) == chart_count
+ for message in snapshot["chart_messages"]:
+ path = tmp_path / message["artifact_path"]
+ assert path.read_bytes() == b"png-bytes"
+ assert message["artifact_path"] in bundle.markdown_text
+ assert "base64" not in message
+ assert "(#insertChart:" not in bundle.markdown_text
+
+
+def test_build_report_bundle_rejects_more_than_512_charts_before_writing(tmp_path):
+ with pytest.raises(ValueError, match="chart_messages exceeds the message count limit"):
+ build_report_bundle(
+ _payload(chart_messages=[_chart(f"chart-{index}") for index in range(513)]),
+ tmp_path / "report-v1",
+ )
+
+ assert not list(tmp_path.iterdir())
+
+
@pytest.mark.parametrize(
"occupied_kind",
["directory", "directory_symlink", "file_symlink", "file_hardlink"],
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
index ef4ec6941c..7082a263d4 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
@@ -1290,7 +1290,7 @@ def test_successful_end_result_bypasses_process_display_text_limit():
def test_successful_end_result_keeps_json_shape_limit(monkeypatch):
- monkeypatch.setattr(stream_router_module, "MAX_JSON_NODES", 4)
+ monkeypatch.setattr(stream_router_module, "MAX_TERMINAL_RESULT_JSON_NODES", 4)
content = json.dumps({
"response_content": "# Final",
"metadata": [1, 2, 3],
@@ -1308,6 +1308,42 @@ def test_successful_end_result_keeps_json_shape_limit(monkeypatch):
)
[email protected]("event", [[], {}, None])
+def test_terminal_classifier_rejects_non_text_event(event):
+ assert stream_router_module.is_terminal_result_chunk({
+ "agent": "end", "event": event, "content": "# Report",
+ }) is False
+
+
+def test_terminal_citations_use_separate_node_budget():
+ result = {
+ "response_content": "# Final report",
+ "citations": [{"title": "source", "url": "https://example.org"}] * 6000,
+ }
+ state = RouterState()
+ route_chunk({
+ "agent": "end", "section_idx": "0", "event": "summary_response",
+ "content": json.dumps(result),
+ }, state)
+ assert state.final_report_started is True
+ assert state.report_parts == []
+ with pytest.raises(ValueError, match="deepresearch_router_limit_exceeded"):
+ route_chunk({
+ "agent": "plan_reasoning", "section_idx": "1", "content": result,
+ }, RouterState())
+
+
[email protected]("event", ["summary_response", "error"])
+def test_terminal_result_keeps_depth_and_text_bounds(monkeypatch, event):
+ monkeypatch.setattr(stream_router_module, "MAX_TERMINAL_RESULT_TEXT_CHARS", 256)
+ for content in ("x" * 257, _deep_json(65)):
+ with pytest.raises(ValueError, match="deepresearch_router_limit_exceeded"):
+ route_chunk({
+ "agent": "end", "section_idx": "0", "event": event,
+ "content": content,
+ }, RouterState())
+
+
def test_end_result_with_error_event_does_not_crash():
"""EndNode event=error (exception_info present) must not crash, but delivery is gated."""
state = RouterState()
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index 5d2f4430ab..8346364b43 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -867,6 +867,108 @@ async def test_stdout_pending_buffer_is_bounded_and_logs_dimensions():
)
+async def test_stdout_limits_apply_per_frame_not_per_read(monkeypatch):
+ monkeypatch.setattr(dt, "DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES", 32)
+ payload = b'{"status":"started"}\n' * 8
+ assert [line async for line in dt._iter_ndjson_lines(_Reader(payload))] == [
+ b'{"status":"started"}'
+ ] * 8
+
+
+async def test_terminal_stdout_has_a_hard_wire_limit(monkeypatch):
+ monkeypatch.setattr(dt, "DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES", 32)
+ monkeypatch.setattr(dt, "DEEPRESEARCH_STDOUT_TERMINAL_MAX_BYTES", 128)
+ payload = json.dumps({
+ "__deepsearch_status__": "completed",
+ "final_result": {"response_content": "x" * 129},
+ }).encode()
+ for value in (payload, payload + b"\n"):
+ with pytest.raises(ValueError, match="deepresearch_stdout_limit_exceeded"):
+ async for _ in dt._iter_ndjson_lines(_Reader(value)):
+ pass
+
+
+ {"agent": "reporter", "content": "x" * 100},
+ {"agent": "end", "section_idx": "1", "event": "summary_response",
+ "content": "x" * 100},
+ {"agent": "end", "section_idx": "0", "event": "message",
+ "content": "x" * 100},
+ {"__deepsearch_status__": "completed", "final_result": "x" * 100},
+])
+async def test_ordinary_stdout_frames_keep_their_wire_limit(monkeypatch, frame):
+ monkeypatch.setattr(dt, "DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES", 32)
+ with pytest.raises(ValueError, match="deepresearch_stdout_limit_exceeded"):
+ async for _ in dt._iter_ndjson_lines(_Reader(json.dumps(frame).encode() + b"\n")):
+ pass
+
+
+async def test_fragmented_unicode_terminal_frame_exceeds_legacy_wire_limit():
+ content = "银发" * (3 * 1024 * 1024)
+ frame = {"__deepsearch_status__": "completed",
+ "final_result": {"response_content": content}}
+ payload = json.dumps(frame, ensure_ascii=False).encode() + b"\n"
+ assert len(payload) > 16 * 1024 * 1024
+ assert len(content) < 16 * 1024 * 1024
+
+ class Reader:
+ def __init__(self):
+ self.offset = 0
+
+ async def read(self, size):
+ chunk = payload[self.offset:self.offset + size]
+ self.offset += len(chunk)
+ return chunk
+
+ lines = [line async for line in dt._iter_ndjson_lines(Reader(), read_size=65537)]
+ assert len(lines) == 1
+ parsed = json.loads(lines[0])
+ assert dt._validate_stream_json_shape(parsed)
+ assert dt._redact_json_value(parsed, ())["final_result"]["response_content"] == content
+
+
[email protected]("operation", [dt._validate_stream_json_shape, dt._redact_json_value])
+def test_terminal_text_budget_remains_bounded(monkeypatch, operation):
+ monkeypatch.setattr(dt, "MAX_TERMINAL_RESULT_TEXT_CHARS", 256)
+ frame = {"__deepsearch_status__": "completed",
+ "final_result": {"response_content": "x" * 257}}
+ if operation is dt._validate_stream_json_shape:
+ assert operation(frame) is False
+ else:
+ with pytest.raises(dt._StreamProtocolInvalid):
+ operation(frame, ())
+
+
+async def test_stop_drain_preserves_large_completed_report():
+ content = "x" * (16 * 1024 * 1024 + 1)
+ frame = json.dumps({
+ "__deepsearch_status__": "completed",
+ "final_result": {"response_content": content},
+ }).encode() + b"\n"
+ captured = {}
+ await dt._drain_stream_while_stopping(_Reader(frame), captured)
+ assert captured["final_result"]["response_content"] == content
+
+
+def test_terminal_redaction_and_validation_share_text_budget(monkeypatch):
+ monkeypatch.setattr(dt, "DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS", 256)
+ frame = {
+ "__deepsearch_status__": "completed",
+ "final_result": {"response_content": "secret " * 100},
+ }
+ assert dt._validate_stream_json_shape(frame)
+ redacted = dt._redact_json_value(frame, ("secret",))
+ assert "secret" not in redacted["final_result"]["response_content"]
+ assert not dt._validate_stream_json_shape({"content": "x" * 257})
+ with pytest.raises(dt._StreamProtocolInvalid):
+ dt._redact_json_value({"content": "x" * 257}, ())
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("exception_message", "expected_reason", "expected_exc_info"),
@@ -2162,6 +2264,43 @@ async def test_completed_marker_delivers_large_sdk_end_result(tmp_path: Path):
write_artifacts.assert_awaited_once()
+async def test_completed_marker_delivers_report_above_legacy_limits(tmp_path: Path):
+ content = "x" * (16 * 1024 * 1024 + 1) + " REPORT_SECRET"
+ final_result = {
+ "response_content": content,
+ "citations": [{"title": "source", "url": "https://example.org"}] * 6000,
+ }
+ proc = _Proc([
+ json.dumps({"agent": "end", "section_idx": "0",
+ "event": "summary_response", "content": json.dumps(final_result)}),
+ json.dumps({"__deepsearch_status__": "completed", "conversation_id": "C1",
+ "final_result": final_result}),
+ ])
+ route = {"request_id": "R1", "channel_id": "CH1", "session_id": "S1",
+ "service_id": "default", "agent_id": "default"}
+ push = AsyncMock()
+ with ExitStack() as stack:
+ for item in _stream_patches(proc, route=route):
+ stack.enter_context(item)
+ stack.enter_context(patch.object(dt, "_build_deepresearch_request_config",
+ return_value=_valid_config(LLM_API_KEY="REPORT_SECRET")))
+ stack.enter_context(patch.object(dt, "WebSocketGatewayPushTransport", return_value=push))
+ write = stack.enter_context(patch.object(
+ dt, "_write_report_artifacts_stream",
+ new=AsyncMock(return_value={"md": str(tmp_path / "report.md")}),
+ ))
+ outcome = json.loads(await dt.deepresearch_stream._func(action="start", query="q"))
+ assert outcome["status"] == "completed"
+ assert outcome["report_delivered"] is True
+ delivered = write.await_args.args[0]
+ assert delivered["response_content"].startswith(content[:100])
+ assert "REPORT_SECRET" not in delivered["response_content"]
+ assert len(delivered["citations"]) == 6000
+ assert any(call.args[0]["payload"].get("event_type") == "chat.file"
+ for call in push.send_push.await_args_list)
+
+
@pytest.mark.asyncio
async def test_completed_marker_rejects_sdk_end_result_with_exception() -> None:
final_result = {
@@ -4359,6 +4498,75 @@ async def test_ordered_stage_gateway_updates_reach_completed_todo_snapshot(tmp_p
assert persist.called
+async def test_completed_report_with_32_charts_publishes_real_files(tmp_path: Path):
+ image_bytes = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jV1EAAAAASUVORK5CYII="
+ )
+ charts = [
+ {
+ "chart_id": f"chart-{index}",
+ "chart_title": f"Chart {index}",
+ "base64": base64.b64encode(image_bytes).decode("ascii"),
+ }
+ for index in range(32)
+ ]
+ proc = _Proc([
+ json.dumps({
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ }),
+ json.dumps({
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": {
+ "response_content": "# Report\n\n" + "\n".join(
+ f"(#insertChart:{chart['chart_id']})" for chart in charts
+ ),
+ "chart_messages": charts,
+ },
+ }),
+ ])
+ route = {
+ "request_id": "R", "channel_id": "CH", "session_id": "S",
+ "service_id": "default", "agent_id": "default",
+ }
+ push = AsyncMock()
+ with ExitStack() as stack:
+ for item in _stream_patches(proc, route=route):
+ stack.enter_context(item)
+ stack.enter_context(patch.object(dt, "get_cwd", return_value=str(tmp_path)))
+ stack.enter_context(patch.object(dt, "WebSocketGatewayPushTransport", return_value=push))
+ stack.enter_context(patch.object(dt, "deepresearch_todo_path", return_value=tmp_path / "todo.json"))
+ # Avoid model calls while exercising real Markdown/HTML publication.
+ stack.enter_context(patch.object(
+ dt, "stylize_report_archive",
+ side_effect=DeepResearchRuntimeError("offline_test"),
+ ))
+ outcome = json.loads(await dt.deepresearch_stream._func(action="start", query="q"))
+
+ assert outcome["status"] == "completed", outcome
+ deliveries = [
+ call.args[0]["payload"] for call in push.send_push.await_args_list
+ if call.args[0]["payload"].get("event_type") == "chat.file"
+ ]
+ assert len(deliveries) == 1
+ files = {item["mime_type"]: Path(item["path"]) for item in deliveries[0]["files"]}
+ markdown = files["text/markdown"]
+ html = files["text/html"]
+ snapshot = json.loads(markdown.with_suffix(".final-result.json").read_text(encoding="utf-8"))
+ assert len(snapshot["chart_messages"]) == 32
+ rendered = html.read_text(encoding="utf-8")
+ for message in snapshot["chart_messages"]:
+ asset = markdown.parent / message["artifact_path"]
+ assert asset.read_bytes() == image_bytes
+ assert message["artifact_path"] in rendered
+ assert markdown.with_suffix(".provenance.json").is_file()
+
+
def test_windows_path_publication_backend_avoids_directory_descriptors(
tmp_path: Path,
):
diff --git a/uv.lock b/uv.lock
index e7faf46e20..27d000c28e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3510,7 +3510,7 @@ wheels = [
[[package]]
name = "openjiuwen"
version = "0.1.16"
-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#e0ab3d500a9b3b2c9a974b8760009bed524c27d6" }
+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#b100371567d48ea807f53d530249cf1564a9be6e" }
dependencies = [
{ name = "aiofiles" },
{ name = "aiohttp" },
@@ -3572,8 +3572,8 @@ zmq = [
[[package]]
name = "openjiuwen-deepsearch"
-version = "0.1.10"
-source = { git = "https://gitcode.com/openJiuwen/deepsearch.git?subdirectory=deepsearch&rev=dev-stable#05d846214487c603a31022c3d46782675d34d4f9" }
+version = "0.1.11"
+source = { git = "https://gitcode.com/openJiuwen/deepsearch.git?subdirectory=deepsearch&rev=dev-stable#09cf56a20254206ba7afa62a74998f05fc3501ad" }
dependencies = [
{ name = "aiolimiter" },
{ name = "beautifulsoup4" },