fix(input-polish): preserve Unicode separators in fenced drafts (#8644)

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: AochenShen99 <sac1063467113@hotmail.com>
This commit is contained in:
ZephyrWang 2026-11-26 16:05:09 +08:00 committed by GitHub
parent d3aad45fc6
commit 9a1e1c4398
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 60 additions and 5 deletions

View File

@ -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

View File

@ -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()

View File

@ -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:

View File

@ -337,6 +337,8 @@ Backend response cleanup preserves unrelated tag names such as `<think-tank>` 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