From 9a1e1c43981324917c81727da2e8be280683c807 Mon Sep 17 00:00:00 2001 From: ZephyrWang <152375907+Wang-Zephyr@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:05:09 +0800 Subject: [PATCH] fix(input-polish): preserve Unicode separators in fenced drafts (#8644) Co-authored-by: Willem Jiang Co-authored-by: AochenShen99 --- .../harness/deerflow/utils/llm_text.py | 6 +-- backend/tests/test_input_polish_router.py | 51 +++++++++++++++++++ backend/tests/test_utils_llm_text.py | 6 ++- docs/guide/knowledge-retrieval.md | 2 + 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/backend/packages/harness/deerflow/utils/llm_text.py b/backend/packages/harness/deerflow/utils/llm_text.py index cafc0c74a9..88cb360d95 100644 --- a/backend/packages/harness/deerflow/utils/llm_text.py +++ b/backend/packages/harness/deerflow/utils/llm_text.py @@ -126,13 +126,13 @@ def strip_leading_think_blocks(text: str) -> str: def strip_markdown_code_fence(text: str) -> str: - """Remove a single wrapping markdown code fence when present.""" + """Remove a single wrapping markdown code fence without rewriting its body.""" stripped = text.strip() if not stripped.startswith("```"): return stripped - lines = stripped.splitlines() + lines = stripped.splitlines(keepends=True) if len(lines) >= 3 and lines[0].startswith("```") and lines[-1].startswith("```"): - return "\n".join(lines[1:-1]).strip() + return "".join(lines[1:-1]).strip() return stripped diff --git a/backend/tests/test_input_polish_router.py b/backend/tests/test_input_polish_router.py index b9223b8d10..f82236ec97 100644 --- a/backend/tests/test_input_polish_router.py +++ b/backend/tests/test_input_polish_router.py @@ -1,13 +1,18 @@ import asyncio +import json from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock +import httpx import pytest from fastapi import HTTPException from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel from langchain_core.messages import AIMessage from app.gateway.routers import input_polish +from deerflow.config.app_config import AppConfig +from deerflow.config.model_config import ModelConfig +from deerflow.config.sandbox_config import SandboxConfig from deerflow.utils import oneshot_llm @@ -92,6 +97,52 @@ def test_polish_input_uses_default_model_when_config_model_is_missing(monkeypatc assert create_chat_model.call_args.kwargs["name"] is None +def test_polish_input_preserves_unicode_separators_in_fenced_json(): + draft = json.dumps({"text": "first\u0085second\u2028third\u2029last"}, ensure_ascii=False) + content = f"```json\n{draft}\n```" + requests = [] + + def respond(request): + requests.append(json.loads(request.content)) + return httpx.Response( + 200, + json={ + "id": "chatcmpl-polish", + "object": "chat.completion", + "created": 0, + "model": "offline-model", + "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}], + }, + ) + + async def polish(): + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + config = AppConfig( + models=[ + ModelConfig( + name="offline-model", + use="langchain_openai:ChatOpenAI", + model="offline-model", + base_url="https://model.invalid/v1", + api_key="test-key", + http_async_client=client, + use_responses_api=False, + ) + ], + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + ) + return await input_polish.polish_input.__wrapped__(input_polish.InputPolishRequest(text=draft), request=None, config=config) + + result = asyncio.run(polish()) + + assert len(requests) == 1 + assert requests[0]["model"] == "offline-model" + assert draft in requests[0]["messages"][-1]["content"] + assert result.rewritten_text == draft + assert json.loads(result.rewritten_text) == json.loads(draft) + assert result.changed is False + + def test_polish_input_returns_404_when_disabled(monkeypatch): request = input_polish.InputPolishRequest(text="hello") fake_model = MagicMock() diff --git a/backend/tests/test_utils_llm_text.py b/backend/tests/test_utils_llm_text.py index e44846ea81..b6e1c99335 100644 --- a/backend/tests/test_utils_llm_text.py +++ b/backend/tests/test_utils_llm_text.py @@ -116,8 +116,10 @@ def test_strip_think_blocks_handles_many_unclosed_tags_in_bounded_time(tag: str, # --------------------------------------------------------------------------- -def test_strip_markdown_code_fence_unwraps_language_fence() -> None: - assert strip_markdown_code_fence('```json\n{"a": 1}\n```') == '{"a": 1}' +@pytest.mark.parametrize("line_ending", ["\n", "\r\n", "\r"]) +def test_strip_markdown_code_fence_unwraps_language_fence(line_ending: str) -> None: + payload = '{"a": 1, "text": "first\u0085second\u2028third\u2029last"}' + assert strip_markdown_code_fence(f"```json{line_ending}{payload}{line_ending}```") == payload def test_strip_markdown_code_fence_unwraps_bare_fence() -> None: diff --git a/docs/guide/knowledge-retrieval.md b/docs/guide/knowledge-retrieval.md index 45ed35fdef..ba2a3a8d94 100644 --- a/docs/guide/knowledge-retrieval.md +++ b/docs/guide/knowledge-retrieval.md @@ -337,6 +337,8 @@ Backend response cleanup preserves unrelated tag names such as `` an The Web UI composer can polish draft input before sending. The rewrite runs as a short Gateway LLM request using the `input_polish` model configuration, keeps slash skill prefixes such as `/data-analysis`, and only replaces the local draft after the user clicks the polish button; it does not create a thread run or persist a message. +Removing a code-fence wrapper from a polished draft preserves Unicode separators inside the draft, including JSON string values. + Input polishing, follow-up suggestions, background project-file summaries, the LLM skill scanner, thread title generation, the `/goal` evaluator, and manual context compaction (`/compact`) construct their model providers off the