DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: make deep research resilient to interrupted streams
zhou2030109-glitchbb6b0cd629e9
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.pyindex 9f8b8c5ba..8f7aa3c92 100644--- a/deeptutor/agents/research/pipeline.py+++ b/deeptutor/agents/research/pipeline.py@@ -240,6 +240,7 @@ DEFAULT_REPORT_OUTLINE_MAX_TOKENS = 2000DEFAULT_REPORT_INTRO_MAX_TOKENS = 3000DEFAULT_REPORT_SECTION_MAX_TOKENS = 6000DEFAULT_REPORT_CONCLUSION_MAX_TOKENS = 3000+DEFAULT_REPORT_STEP_MAX_ATTEMPTS = 3DEFAULT_INITIAL_SUBTOPICS = 5DEFAULT_MAX_PARALLEL_TOPICS = 3DEFAULT_QUEUE_MAX_LENGTH = 8@@ -1205,10 +1206,14 @@ class ResearchPipeline:)section_texts.append(title_block)+ # The separator must be on the wire before ``_write_intro`` emits its+ # first heading. Emitting it afterwards produced the literal live+ # stream ``# Report title## 1. Introduction`` even though the final+ # assembled response was normalized correctly.+ if section_texts:+ await self._stream_report_separator(stream)intro = await self._write_intro(topic=topic, outline=outline, stream=stream, client=client)if intro:- if section_texts:- await self._stream_report_separator(stream)section_texts.append(intro)section_bodies: list[str] = []@@ -1711,8 +1716,13 @@ class ResearchPipeline:max_tokens: int,extra_meta: dict[str, Any] | None = None,) -> str:- """Common runner for the four report sub-phases: one labeled step- with body streaming live to the chat bubble + a sub-trace card."""+ """Run and validate one report sub-phase, retrying partial streams.++ Report prose is buffered until the call is known to be complete. This+ prevents a timed-out first attempt from leaking half a section into+ the final bubble before a retry starts. Progress / reasoning traces+ still stream live, so long report calls remain observable.+ """messages = self._build_system_user_messages(system_prompt, user_prompt)trace_extra = dict(extra_meta or {})iter_meta = self._build_simple_trace_meta(@@ -1735,18 +1745,94 @@ class ResearchPipeline:trace_group="stage",**trace_extra,)- step = await self._run_labeled_step(- client=client,- messages=messages,- tool_schemas=None,- protocol=protocol,- stream=stream,- stage="reporting",- iter_meta=iter_meta,- max_tokens=max_tokens,- final_meta=final_meta,+ expected_label = protocol.allowed[0]+ last_reason = "empty response"+ for attempt in range(1, DEFAULT_REPORT_STEP_MAX_ATTEMPTS + 1):+ body = ""+ try:+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=protocol,+ stream=stream,+ stage="reporting",+ iter_meta=iter_meta,+ max_tokens=max_tokens,+ # Buffer body text until validation succeeds. Passing+ # ``final_meta`` here would stream a failed attempt and+ # make a clean retry impossible without duplicated prose.+ final_meta=None,+ )+ body = (step.text or "").strip()+ last_reason = _report_step_incomplete_reason(+ step,+ expected_label=expected_label,+ body=body,+ )+ if not last_reason:+ await stream.content(+ body,+ source=SOURCE,+ stage="reporting",+ metadata=merge_trace_metadata(+ final_meta,+ {"trace_kind": "llm_chunk", "report_attempt": attempt},+ ),+ )+ return body+ except Exception as exc:+ last_reason = f"provider error: {type(exc).__name__}"+ if attempt >= DEFAULT_REPORT_STEP_MAX_ATTEMPTS:+ raise+ logger.warning(+ "Report step %s attempt %d/%d failed: %s",+ call_id_root,+ attempt,+ DEFAULT_REPORT_STEP_MAX_ATTEMPTS,+ exc,+ )++ if attempt < DEFAULT_REPORT_STEP_MAX_ATTEMPTS:+ await stream.progress(+ self._t(+ "labels.report_retry",+ default="Report section was incomplete; retrying.",+ ),+ source=SOURCE,+ stage="reporting",+ metadata={+ "trace_kind": "warning",+ "report_retry": True,+ "report_attempt": attempt,+ "report_retry_reason": last_reason,+ **trace_extra,+ },+ )+ messages.extend(+ [+ {+ "role": "assistant",+ "content": f"``{expected_label}``\n{body}" if body else "",+ },+ {+ "role": "user",+ "content": self._t(+ "report.retry_complete",+ default=(+ "The previous report part was empty or truncated. "+ "Regenerate the complete part from its ## heading, "+ "follow the required label protocol, and finish every sentence."+ ),+ ),+ },+ ]+ )++ raise RuntimeError(+ f"Research report step {call_id_root!r} remained incomplete after "+ f"{DEFAULT_REPORT_STEP_MAX_ATTEMPTS} attempts ({last_reason}).")- return (step.text or "").strip()def _render_section_evidence(self,@@ -2075,6 +2161,37 @@ class ResearchPipeline:# ---------------------------------------------------------------------------_REPORT_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)+_REPORT_SECTION_HEADING_RE = re.compile(r"\A##\s+\d+\.\s*\S")+++def _report_step_incomplete_reason(+ step: LabeledStepResult,+ *,+ expected_label: str,+ body: str,+) -> str:+ """Return why a generated report part is unsafe to persist, or ``""``.++ Deep Research report calls are stricter than ordinary chat: an empty+ formal channel, a token-limit finish, or the labeled-step idle escape+ means the report is incomplete even though the provider call itself did+ not raise. Every report part must also contain its numbered H2 heading.+ """++ if step.label != expected_label:+ return f"expected {expected_label} label, got {step.label or 'none'}"+ if step.stream_idle_timeout:+ return "provider stream went idle before an explicit finish"+ finish_reason = (step.finish_reason or "").strip().lower()+ if finish_reason in {"length", "max_tokens", "max_output_tokens"}:+ return f"provider stopped at its output limit ({finish_reason})"+ if len(body) < 80:+ return f"body is too short ({len(body)} characters)"+ if not _REPORT_SECTION_HEADING_RE.match(body):+ return "numbered report heading is missing"+ return ""++_REPORT_STOPWORDS = {"a","an",diff --git a/deeptutor/agents/research/prompts/en/pipeline.yaml b/deeptutor/agents/research/prompts/en/pipeline.yamlindex 0524c58f7..9b64f0980 100644--- a/deeptutor/agents/research/prompts/en/pipeline.yaml+++ b/deeptutor/agents/research/prompts/en/pipeline.yaml@@ -18,6 +18,7 @@ labels:report_intro: "Write introduction"report_section: "Write section"report_conclusion: "Write conclusion"+ report_retry: "Report section was incomplete; retrying."queue_append: "Sub-topic added"references_heading: "References"addendum_title: "Additional findings"@@ -207,6 +208,8 @@ note:# Phase 4 — Reporting (sequence of one-shot labeled steps)# =======================================================================report:+ retry_complete: |+ The previous report part was empty or truncated. Regenerate the complete part from its ## heading, follow the required label protocol, and finish every sentence. Do not comment on the retry.outline:system: |You are planning the final report's structure from a pile of finished research blocks. Each block has an id, a sub-topic title, and a short knowledge preview.diff --git a/deeptutor/agents/research/prompts/zh/pipeline.yaml b/deeptutor/agents/research/prompts/zh/pipeline.yamlindex 510e68dbf..23e50a4cf 100644--- a/deeptutor/agents/research/prompts/zh/pipeline.yaml+++ b/deeptutor/agents/research/prompts/zh/pipeline.yaml@@ -13,6 +13,7 @@ labels:report_intro: "撰写引言"report_section: "撰写章节"report_conclusion: "撰写结论"+ report_retry: "报告段落不完整,正在重试。"queue_append: "新增子主题"references_heading: "参考资料"addendum_title: "补充发现"@@ -198,6 +199,8 @@ note:# Phase 4 — Reporting# =======================================================================report:+ retry_complete: |+ 上一次报告段落为空或被截断。请从本段的 ## 标题开始重新生成完整内容,严格遵守标签协议,并写完每个句子。不要解释重试过程。outline:system: |根据已完成的研究块规划最终报告的结构。每个块有 id、子主题标题,以及一段简短的知识预览。diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.pyindex 3f8a7cfb1..c58461a56 100644--- a/deeptutor/core/agentic/labeled_step.py+++ b/deeptutor/core/agentic/labeled_step.py@@ -100,6 +100,15 @@ class LabeledStepResult:label: str # one of allowed_labels, or LABEL_UNKNOWN on protocol failuretext: str # post-label content with provider <think> tags cleanedtool_calls: list[dict[str, Any]] = field(default_factory=list)+ # ``finish_reason`` is authoritative when the provider sends it. Report+ # writers use it to reject token-limit truncation instead of persisting a+ # visibly cut-off section as a successful result.+ finish_reason: str | None = None+ # Some OpenAI-compatible gateways stop yielding chunks without closing+ # the SSE response. The generic labeled-step reader keeps its bounded idle+ # escape hatch, but exposes that fact so strict callers can retry rather+ # than treating the partial text as complete.+ stream_idle_timeout: bool = Falseasync def run_labeled_step(@@ -177,6 +186,7 @@ async def run_labeled_step(output_chars_seen = 0finish_reason_seen: str | None = Noneusage_trailer_waited = False+ stream_idle_timeout = Falseasync def _open_sub_trace() -> None:nonlocal sub_trace_opened@@ -446,6 +456,8 @@ async def run_labeled_step(# final-label answer (or an explicit finish_reason), but the# gateway is holding the connection open.if finish_reason_seen or label in final_labels:+ if not finish_reason_seen:+ stream_idle_timeout = Truebreakraiseif getattr(chunk, "usage", None):@@ -552,4 +564,10 @@ async def run_labeled_step(text = clean_thinking_tags(text, binding, model)ordered_tool_calls = tc_acc.ordered()ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]- return LabeledStepResult(label=label, text=text, tool_calls=ordered_tool_calls)+ return LabeledStepResult(+ label=label,+ text=text,+ tool_calls=ordered_tool_calls,+ finish_reason=finish_reason_seen,+ stream_idle_timeout=stream_idle_timeout,+ )diff --git a/tests/agents/research/test_report_stream_formatting.py b/tests/agents/research/test_report_stream_formatting.pynew file mode 100644index 000000000..a25125b62--- /dev/null+++ b/tests/agents/research/test_report_stream_formatting.py@@ -0,0 +1,171 @@+"""Regression coverage for the live deep-research report stream."""++from __future__ import annotations++import types++import pytest++from deeptutor.agents.research.pipeline import (+ _PROTOCOL_REPORT_SECTION,+ LABEL_SECTION,+ ReportOutline,+ ResearchPipeline,+)+from deeptutor.agents.research.utils.citation_manager import CitationManager+from deeptutor.core.agentic import LabeledStepResult+from deeptutor.core.stream_bus import StreamBus++pytestmark = pytest.mark.asyncio+++class _FakeLLM:+ binding = "openai"+ model = "gpt-x"+ api_key = "k"+ base_url = "u"+ api_version = None+ extra_headers: dict = {}+ reasoning_effort = None+++class _FakeRegistry:+ def build_openai_schemas(self, _names):+ return []++ def build_prompt_text(self, _names, **_kwargs):+ return "- none"++ def get(self, _name):+ return None++ def get_enabled(self, _names):+ return []+++def _make_pipeline(monkeypatch: pytest.MonkeyPatch) -> ResearchPipeline:+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM())+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()+ )+ return ResearchPipeline(language="en", runtime_config={})+++async def test_report_title_is_separated_before_the_streamed_introduction(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ """A heading needs a blank line *before* the intro begins streaming.++ The old ordering emitted the separator only after ``_write_intro`` had+ already streamed ``## 1. Introduction``. Markdown then treated it as part+ of the H1: ``# Title## 1. Introduction``.+ """++ pipeline = _make_pipeline(monkeypatch)+ stream = StreamBus()++ async def fake_outline(self, **_kwargs):+ return ReportOutline(title="Report title", sections=())++ async def fake_intro(self, *, stream, **_kwargs):+ await stream.content("## 1. Introduction", stage="reporting")+ return "## 1. Introduction"++ async def fake_conclusion(self, *, stream, **_kwargs):+ await stream.content("## 2. Conclusion", stage="reporting")+ return "## 2. Conclusion"++ pipeline._gen_report_outline = types.MethodType(fake_outline, pipeline)+ pipeline._write_intro = types.MethodType(fake_intro, pipeline)+ pipeline._write_conclusion = types.MethodType(fake_conclusion, pipeline)++ await pipeline._write_report(+ topic="topic",+ blocks=[],+ citations=CitationManager("test-report", cache_dir=tmp_path),+ stream=stream,+ client=None,+ )++ live_content = "".join(+ event.content for event in stream._history if event.type.value == "content"+ )+ assert live_content.startswith("# Report title\n\n## 1. Introduction")+++async def test_report_step_retries_an_idle_truncated_response_before_streaming(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An idle provider stream must not leak a partial section or count as success."""++ pipeline = _make_pipeline(monkeypatch)+ stream = StreamBus()+ attempts = 0++ async def fake_run_labeled_step(self, **_kwargs):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ return LabeledStepResult(+ label=LABEL_SECTION,+ text="## 2. Partial section that stops in the middle",+ stream_idle_timeout=True,+ )+ return LabeledStepResult(+ label=LABEL_SECTION,+ text=(+ "## 2. Complete section\n\n"+ "This replacement is long enough to be a real report section, "+ "and it ends with a complete sentence."+ ),+ finish_reason="stop",+ )++ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)++ result = await pipeline._stream_report_step(+ system_prompt="system",+ user_prompt="user",+ protocol=_PROTOCOL_REPORT_SECTION,+ stream=stream,+ client=None,+ label="Write section",+ call_id_root="test-report-section",+ max_tokens=1000,+ extra_meta={"report_part": "section"},+ )++ live_content = "".join(+ event.content for event in stream._history if event.type.value == "content"+ )+ assert attempts == 2+ assert result == live_content+ assert "Partial section" not in live_content+ assert "Complete section" in live_content+++async def test_report_step_rejects_empty_success_after_all_retries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ stream = StreamBus()++ async def fake_run_labeled_step(self, **_kwargs):+ return LabeledStepResult(label=LABEL_SECTION, text="", finish_reason="stop")++ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)++ with pytest.raises(RuntimeError, match="incomplete"):+ await pipeline._stream_report_step(+ system_prompt="system",+ user_prompt="user",+ protocol=_PROTOCOL_REPORT_SECTION,+ stream=stream,+ client=None,+ label="Write section",+ call_id_root="test-empty-section",+ max_tokens=1000,+ )++ assert not [event for event in stream._history if event.type.value == "content"]diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex bb6ccfc2e..03faeefaa 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -127,6 +127,7 @@ import {normalizeSelectedText,type SelectionTutorContext,} from "@/lib/selection-tutor";+import { shouldReturnToChatAfterResearch } from "@/lib/deep-research-report";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"),@@ -737,6 +738,30 @@ export default function ChatPage() {const isResearchMode = activeCap.value === "deep_research";const isReadingMode = activeCap.value === "immersive_reading";const capabilityNeedsConfig = isQuizMode || isVisualizeMode || isResearchMode;+ const returnedResearchTurnRef = useRef<string | null>(null);++ // Deep Research is a one-shot workflow: once its confirmed-outline turn+ // reaches a terminal event, ordinary composer messages should discuss the+ // report in chat context. Keeping the mode selected caused follow-ups such+ // as "why did this stop?" to become brand-new research outlines. The Retry+ // button still submits the preserved outline explicitly as deep_research.+ useEffect(() => {+ if (state.isStreaming || state.activeCapability !== "deep_research") return;+ const latestAssistant = [...state.messages]+ .reverse()+ .find((message) => message.role === "assistant");+ if (!latestAssistant || !shouldReturnToChatAfterResearch(latestAssistant.events)) {+ return;+ }+ const terminal = [...(latestAssistant.events ?? [])]+ .reverse()+ .find((event) => event.type === "done");+ const turnKey = String(terminal?.turn_id || latestAssistant.id || "");+ if (!turnKey || returnedResearchTurnRef.current === turnKey) return;+ returnedResearchTurnRef.current = turnKey;+ setCapability(null);+ setCapabilityConfigConfirmed(false);+ }, [setCapability, state.activeCapability, state.isStreaming, state.messages]);// Edit-invalidates-confirm wrappers — flipping any field after the user// hit *Confirm* should restore the gate so they re-confirm intentionally.diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex f27b0c811..b6c4c1a35 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -70,6 +70,11 @@ import ContextReferenceTree, {import { AssistantActivity, NestedTraceFlow } from "./TracePanels";import { agentGlyph } from "@/components/agents/agent-icons";import { useConnectedAgentKinds } from "@/hooks/useConnectedAgentKinds";+import {+ authoritativeResearchReport,+ isConfirmedResearchFollowup,+ researchFollowupStatus,+} from "@/lib/deep-research-report";const MathAnimatorViewer = dynamic(() => import("@/components/math-animator/MathAnimatorViewer"),@@ -294,7 +299,7 @@ const AssistantMessage = memo(function AssistantMessage({}: {msg: { content: string; capability?: string; events?: StreamEvent[] };isStreaming?: boolean;- outlineStatus?: "editing" | "researching" | "done";+ outlineStatus?: "editing" | "researching" | "done" | "failed";sessionId?: string | null;language?: string;researchRequestSnapshot?: MessageRequestSnapshot | null;@@ -418,7 +423,9 @@ const AssistantMessage = memo(function AssistantMessage({);const researchInProgress =- outlineStatus === "researching" || outlineStatus === "done";+ outlineStatus === "researching" ||+ outlineStatus === "done" ||+ outlineStatus === "failed";const showResearchBody =Boolean(outlinePreview) && researchInProgress && Boolean(msg.content);@@ -1278,16 +1285,20 @@ export const ChatMessageList = memo(function ChatMessageList({const resultEv = msg.events?.find((e) => e.type === "result");const meta = resultEv?.metadata as Record<string, unknown> | undefined;if (!meta?.outline_preview) continue;- const followupIdx = visibleMessages+ const nextResearchAssistantIdx = visibleMessages.slice(i + 1).findIndex((m) => m.role === "assistant" && m.capability === "deep_research",);- if (followupIdx === -1) continue;- const absoluteFollowupIdx = i + 1 + followupIdx;+ if (nextResearchAssistantIdx === -1) continue;+ const absoluteFollowupIdx = i + 1 + nextResearchAssistantIdx;const followup = visibleMessages[absoluteFollowupIdx];+ if (!isConfirmedResearchFollowup(followup.events)) continue;const mergedEvents = [...(msg.events ?? []), ...(followup.events ?? [])];- const mergedContent = followup.content || msg.content;+ const mergedContent = authoritativeResearchReport(+ followup.events,+ followup.content || msg.content,+ );map.set(i, { mergedEvents, mergedContent });followupIndices.add(absoluteFollowupIdx);}@@ -1295,7 +1306,10 @@ export const ChatMessageList = memo(function ChatMessageList({}, [visibleMessages]);const outlineStatusByIndex = useMemo(() => {- const map = new Map<number, "editing" | "researching" | "done">();+ const map = new Map<+ number,+ "editing" | "researching" | "done" | "failed"+ >();for (let i = 0; i < visibleMessages.length; i++) {const msg = visibleMessages[i];if (msg.role !== "assistant" || msg.capability !== "deep_research")@@ -1308,11 +1322,8 @@ export const ChatMessageList = memo(function ChatMessageList({.find((m) => m.role === "assistant" && m.capability === "deep_research",);- if (followup) {- const followupResult = followup.events?.find(- (e) => e.type === "result",- );- map.set(i, followupResult ? "done" : "researching");+ if (followup && isConfirmedResearchFollowup(followup.events)) {+ map.set(i, researchFollowupStatus(followup.events));} else {// The first deep_research turn only plans/rephrases/decomposes and// returns an outline preview. While that turn is still flushingdiff --git a/web/components/research/ResearchOutlineEditor.tsx b/web/components/research/ResearchOutlineEditor.tsxindex 54fcfa518..50c8ed27a 100644--- a/web/components/research/ResearchOutlineEditor.tsx+++ b/web/components/research/ResearchOutlineEditor.tsx@@ -8,11 +8,12 @@ import {Trash2,Loader2,CheckCircle2,+ AlertCircle,} from "lucide-react";import { useTranslation } from "react-i18next";import type { OutlineItem } from "@/lib/research-types";-type OutlineStatus = "editing" | "researching" | "done";+type OutlineStatus = "editing" | "researching" | "done" | "failed";interface ResearchOutlineEditorProps {outline: OutlineItem[];@@ -38,9 +39,10 @@ export default function ResearchOutlineEditor({const [userToggled, setUserToggled] = useState(false);const locked =- externalStatus === "researching" ||- externalStatus === "done" ||- localConfirmed;+ externalStatus !== "failed" &&+ (externalStatus === "researching" ||+ externalStatus === "done" ||+ localConfirmed);const displayCollapsed = locked && (userToggled ? collapsed : true);@@ -81,13 +83,19 @@ export default function ResearchOutlineEditor({: items;const statusLabel = (() => {- if (externalStatus === "done") return "Research Complete";+ if (externalStatus === "done") return t("Research Complete");+ if (externalStatus === "failed") return t("Research failed. You can retry.");if (externalStatus === "researching" || localConfirmed)- return "Researching…";+ return t("Researching");return null;})();- const StatusIcon = externalStatus === "done" ? CheckCircle2 : Loader2;+ const StatusIcon =+ externalStatus === "failed"+ ? AlertCircle+ : externalStatus === "done"+ ? CheckCircle2+ : Loader2;const headerClickable = locked;@@ -126,7 +134,12 @@ export default function ResearchOutlineEditor({<span className="flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]/60"><StatusIconsize={12}- className={externalStatus === "done" ? "" : "animate-spin"}+ className={+ externalStatus === "researching" ||+ (!externalStatus && localConfirmed)+ ? "animate-spin"+ : ""+ }/>{statusLabel}</span>@@ -134,8 +147,9 @@ export default function ResearchOutlineEditor({</div>{!locked && !collapsed && (<p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]/60">- Review and edit the sub-topics below, then start the research. You- can also type in the chat to regenerate the outline.+ {t(+ "Review and edit the sub-topics below, then start the research. You can also type in the chat to regenerate the outline.",+ )}</p>)}</button>@@ -218,7 +232,7 @@ export default function ResearchOutlineEditor({className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[11px] font-medium text-[var(--primary-foreground)] transition-all hover:opacity-90 disabled:opacity-40"><Play size={11} />- {t("Start Research")}+ {t(externalStatus === "failed" ? "Retry Research" : "Start Research")}</button></div>)}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex d459a9a9b..32063d118 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -41,6 +41,7 @@ import { hasPendingAskUserInMessages } from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";import { forwardReaderAction } from "@/lib/reading-reader-action";import { readingTurnFields } from "@/lib/reading-turn-state";+import { decideIdleTurnRecovery } from "@/lib/chat-idle-recovery";import i18n from "i18next";import {normalizeBookReferences,@@ -222,6 +223,7 @@ type Action =| { type: "POP_LAST_ASSISTANT"; key: string }| { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }| { type: "STREAM_START"; key: string }+ | { type: "STREAM_TOUCH"; key: string }| { type: "STREAM_EVENT"; key: string; event: StreamEvent }| {type: "STREAM_END";@@ -500,6 +502,17 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}+ case "STREAM_TOUCH": {+ const session = state.sessions[action.key];+ if (!session) return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: { ...session, updatedAt: Date.now() },+ },+ };+ }case "STREAM_EVENT": {// If the session entry has been removed (e.g., BIND_SERVER_SESSION// just renamed ``draft_X`` to a real id but a stray event still@@ -1499,9 +1512,11 @@ export function UnifiedChatProvider({dispatch({ type: "ENSURE_DRAFT_SESSION", key: makeDraftKey() });}, []); // eslint-disable-line react-hooks/exhaustive-deps- // Idle timeout: if a streaming session receives no events for the configured- // window (default 180s, set in Settings > Network), auto-fail it. Read per- // tick so a settings change applies without remounting.+ // Idle recovery: if a streaming session receives no events for the+ // configured window (default 180s, set in Settings > Network), re-subscribe+ // from the last sequence. A quiet stream is not terminal: long research+ // calls can emit nothing for minutes, while a dropped browser connection+ // leaves the backend turn alive with replayable events.useEffect(() => {const CHECK_INTERVAL_MS = 10_000;@@ -1510,13 +1525,27 @@ export function UnifiedChatProvider({const idleTimeoutMs = timeoutSeconds * 1000;const current = stateRef.current;for (const [key, session] of Object.entries(current.sessions)) {- if (!session.isStreaming) continue;- if (- hasPendingAskUserInMessages(session.messages, session.activeTurnId)- ) {+ const decision = decideIdleTurnRecovery({+ isStreaming: session.isStreaming,+ hasPendingUserInput: hasPendingAskUserInMessages(+ session.messages,+ session.activeTurnId,+ ),+ activeTurnId: session.activeTurnId,+ lastSeq: session.lastSeq,+ updatedAt: session.updatedAt,+ now: Date.now(),+ idleTimeoutMs,+ });+ if (decision.kind === "none") continue;++ if (decision.kind === "resume") {+ // Avoid retrying on every watchdog tick while the re-subscription is+ // opening. The next event will replace this timestamp naturally.+ dispatch({ type: "STREAM_TOUCH", key });+ sendThroughRunner(key, decision.message);continue;}- if (Date.now() - session.updatedAt <= idleTimeoutMs) continue;dispatch({type: "STREAM_EVENT",@@ -1541,7 +1570,7 @@ export function UnifiedChatProvider({}, CHECK_INTERVAL_MS);return () => clearInterval(timer);- }, []);+ }, [sendThroughRunner]);const sendMessage = useCallback((diff --git a/web/lib/chat-idle-recovery.ts b/web/lib/chat-idle-recovery.tsnew file mode 100644index 000000000..d50e2ca0b--- /dev/null+++ b/web/lib/chat-idle-recovery.ts@@ -0,0 +1,43 @@+import type { ResumeTurnMessage } from "./unified-ws";++interface IdleTurnRecoveryInput {+ isStreaming: boolean;+ hasPendingUserInput: boolean;+ activeTurnId: string | null;+ lastSeq: number;+ updatedAt: number;+ now: number;+ idleTimeoutMs: number;+}++export type IdleTurnRecoveryDecision =+ | { kind: "none" }+ | { kind: "resume"; message: ResumeTurnMessage }+ | { kind: "fail" };++/**+ * Decide what the client-side idle watchdog should do.+ *+ * A quiet WebSocket is not proof that a server turn failed. Long research+ * tool calls can legitimately emit nothing for several minutes, and the+ * backend keeps the turn alive when a browser briefly disconnects. When a+ * server turn id is known, re-subscribe from the last received sequence so+ * buffered events (including a missed terminal event) are replayed.+ */+export function decideIdleTurnRecovery(+ input: IdleTurnRecoveryInput,+): IdleTurnRecoveryDecision {+ if (!input.isStreaming || input.hasPendingUserInput) return { kind: "none" };+ if (input.now - input.updatedAt <= input.idleTimeoutMs) {+ return { kind: "none" };+ }+ if (!input.activeTurnId) return { kind: "fail" };+ return {+ kind: "resume",+ message: {+ type: "resume_from",+ turn_id: input.activeTurnId,+ seq: input.lastSeq,+ },+ };+}diff --git a/web/lib/deep-research-report.ts b/web/lib/deep-research-report.tsnew file mode 100644index 000000000..3be9f9d96--- /dev/null+++ b/web/lib/deep-research-report.ts@@ -0,0 +1,77 @@+import type { StreamEvent } from "./unified-ws";++export type DeepResearchFollowupStatus = "researching" | "done" | "failed";++function eventMetadata(event: StreamEvent): Record<string, unknown> {+ return (event.metadata ?? {}) as Record<string, unknown>;+}++export function isConfirmedResearchFollowup(+ events: StreamEvent[] | undefined,+): boolean {+ if (!events?.length) return false;+ if (+ events.some(+ (event) =>+ event.type === "result" && eventMetadata(event).outline_preview === true,+ )+ ) {+ return false;+ }+ return events.some(+ (event) => event.stage === "researching" || event.stage === "reporting",+ );+}++export function researchFollowupStatus(+ events: StreamEvent[] | undefined,+): DeepResearchFollowupStatus {+ const done = [...(events ?? [])]+ .reverse()+ .find((event) => event.type === "done");+ if (!done) return "researching";+ const status = String(eventMetadata(done).status || "completed");+ if (status !== "completed") return "failed";+ const response = authoritativeResearchReport(events, "");+ return isStructurallyCompleteResearchReport(response) ? "done" : "failed";+}++function isStructurallyCompleteResearchReport(content: string): boolean {+ const normalized = normalizeDeepResearchReportFormatting(content).trim();+ if (!normalized) return false;+ // A confirmed outline always has at least one researched section, so a+ // complete report needs introduction + one body section + conclusion.+ const numberedSections = normalized.match(/^##\s+\d+\.\s*\S/gm) ?? [];+ if (numberedSections.length < 3) return false;+ if (normalized.endsWith("</details>")) return true;+ return /[.!?。!?)\])】]$/.test(normalized);+}++export function normalizeDeepResearchReportFormatting(content: string): string {+ if (!content) return content;+ return content.replace(/^(# [^\r\n]*?)(?=##\s+\d+\.\s*)/, "$1\n\n");+}++export function authoritativeResearchReport(+ events: StreamEvent[] | undefined,+ fallback: string,+): string {+ for (let index = (events?.length ?? 0) - 1; index >= 0; index -= 1) {+ const event = events?.[index];+ if (!event || event.type !== "result") continue;+ const metadata = eventMetadata(event);+ if (metadata.outline_preview === true) continue;+ const response = metadata.response;+ if (typeof response === "string" && response.trim()) {+ return normalizeDeepResearchReportFormatting(response);+ }+ }+ return normalizeDeepResearchReportFormatting(fallback);+}++export function shouldReturnToChatAfterResearch(+ events: StreamEvent[] | undefined,+): boolean {+ if (!isConfirmedResearchFollowup(events)) return false;+ return Boolean(events?.some((event) => event.type === "done"));+}diff --git a/web/lib/unified-ws-recovery.ts b/web/lib/unified-ws-recovery.tsnew file mode 100644index 000000000..85f9021df--- /dev/null+++ b/web/lib/unified-ws-recovery.ts@@ -0,0 +1,20 @@+const MAX_RECONNECT_ATTEMPTS = 5;+const BASE_RECONNECT_DELAY_MS = 200;++export function shouldStopReconnecting({+ attempt,+ activeTurnId,+}: {+ attempt: number;+ activeTurnId: string | null;+}): boolean {+ return !activeTurnId && attempt >= MAX_RECONNECT_ATTEMPTS;+}++export function reconnectDelayMs(attempt: number): number {+ const cappedAttempt = Math.min(+ Math.max(0, attempt),+ MAX_RECONNECT_ATTEMPTS - 1,+ );+ return BASE_RECONNECT_DELAY_MS * Math.pow(2, cappedAttempt);+}diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 87b0e309f..02a8dbf8e 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -6,11 +6,15 @@** Features:* - Client-side heartbeat (30s ping / 45s dead-connection detection)- * - Auto-reconnect with exponential backoff (max 5 attempts)+ * - Auto-reconnect with exponential backoff (active turns keep retrying)* - resume_from after reconnection to continue a streaming turn*/import { wsUrl } from "./api";+import {+ reconnectDelayMs,+ shouldStopReconnecting,+} from "./unified-ws-recovery";// ---- StreamEvent types (mirror Python StreamEventType) ----@@ -162,8 +166,6 @@ export type EventHandler = (event: StreamEvent) => void;const HEARTBEAT_INTERVAL_MS = 30_000;const HEARTBEAT_TIMEOUT_MS = 45_000;-const MAX_RECONNECT_ATTEMPTS = 5;-const BASE_RECONNECT_DELAY_MS = 200;export class UnifiedWSClient {private ws: WebSocket | null = null;@@ -301,13 +303,21 @@ export class UnifiedWSClient {// ---- Reconnect ----private attemptReconnect(): void {- if (this.reconnectAttempt >= MAX_RECONNECT_ATTEMPTS) {+ if (+ shouldStopReconnecting({+ attempt: this.reconnectAttempt,+ activeTurnId: this.activeTurnId,+ })+ ) {this.resetResumeState();this.onClose?.();return;}- const delay = BASE_RECONNECT_DELAY_MS * Math.pow(2, this.reconnectAttempt);+ // A live turn continues on the backend even while the browser is offline.+ // Keep retrying at a capped delay so ``onopen`` can issue ``resume_from``+ // and replay everything after ``lastSeq`` when the network returns.+ const delay = reconnectDelayMs(this.reconnectAttempt);this.reconnectAttempt += 1;this.reconnectTimer = setTimeout(() => {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex bc6f28b3f..0303d0b37 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -120,6 +120,10 @@"Topic Optimization": "Topic Optimization","Topic Assistant": "Topic Assistant","Start Research": "Start Research",+ "Retry Research": "Retry Research",+ "Research Complete": "Research Complete",+ "Research failed. You can retry.": "Research failed. You can retry.",+ "Review and edit the sub-topics below, then start the research. You can also type in the chat to regenerate the outline.": "Review and edit the sub-topics below, then start the research. You can also type in the chat to regenerate the outline.","Research in progress...": "Research in progress...","Co-Writer": "Co-Writer","Intelligent markdown editor with AI-powered writing assistance.": "Intelligent markdown editor with AI-powered writing assistance.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex cca26990d..56902a38d 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -120,6 +120,10 @@"Topic Optimization": "主题优化","Topic Assistant": "主题助手","Start Research": "开始研究",+ "Retry Research": "重试研究",+ "Research Complete": "研究已完成",+ "Research failed. You can retry.": "研究未完成,可重试。",+ "Review and edit the sub-topics below, then start the research. You can also type in the chat to regenerate the outline.": "检查并编辑下方子主题,然后开始研究。也可以在聊天框中输入内容来重新生成大纲。","Research in progress...": "研究进行中…","Co-Writer": "智能写作","Intelligent markdown editor with AI-powered writing assistance.": "带 AI 写作辅助的智能 Markdown 编辑器。",diff --git a/web/tests/chat-idle-recovery.test.ts b/web/tests/chat-idle-recovery.test.tsnew file mode 100644index 000000000..3be90b729--- /dev/null+++ b/web/tests/chat-idle-recovery.test.ts@@ -0,0 +1,54 @@+import test from "node:test";+import assert from "node:assert/strict";+import { decideIdleTurnRecovery } from "../lib/chat-idle-recovery";++test("an idle live turn is resumed instead of being marked failed", () => {+ assert.deepEqual(+ decideIdleTurnRecovery({+ isStreaming: true,+ hasPendingUserInput: false,+ activeTurnId: "turn_research",+ lastSeq: 42,+ updatedAt: 1_000,+ now: 181_001,+ idleTimeoutMs: 180_000,+ }),+ {+ kind: "resume",+ message: {+ type: "resume_from",+ turn_id: "turn_research",+ seq: 42,+ },+ },+ );+});++test("a paused ask-user turn is not touched by the idle watchdog", () => {+ assert.deepEqual(+ decideIdleTurnRecovery({+ isStreaming: true,+ hasPendingUserInput: true,+ activeTurnId: "turn_waiting",+ lastSeq: 7,+ updatedAt: 1_000,+ now: 999_999,+ idleTimeoutMs: 180_000,+ }),+ { kind: "none" },+ );+});++test("a stale stream without a server turn id still fails locally", () => {+ const decision = decideIdleTurnRecovery({+ isStreaming: true,+ hasPendingUserInput: false,+ activeTurnId: null,+ lastSeq: 0,+ updatedAt: 1_000,+ now: 181_001,+ idleTimeoutMs: 180_000,+ });++ assert.equal(decision.kind, "fail");+});diff --git a/web/tests/deep-research-report.test.ts b/web/tests/deep-research-report.test.tsnew file mode 100644index 000000000..27b4d8563--- /dev/null+++ b/web/tests/deep-research-report.test.ts@@ -0,0 +1,95 @@+import test from "node:test";+import assert from "node:assert/strict";+import type { StreamEvent } from "../lib/unified-ws";+import {+ authoritativeResearchReport,+ isConfirmedResearchFollowup,+ normalizeDeepResearchReportFormatting,+ researchFollowupStatus,+ shouldReturnToChatAfterResearch,+} from "../lib/deep-research-report";++function event(+ type: StreamEvent["type"],+ options: Partial<StreamEvent> = {},+): StreamEvent {+ return { type, source: "deep_research", ...options } as StreamEvent;+}++test("repairs a legacy report title joined directly to its first section", () => {+ assert.equal(+ normalizeDeepResearchReportFormatting("# 报告标题## 1. 引言\n\n正文。"),+ "# 报告标题\n\n## 1. 引言\n\n正文。",+ );+ assert.equal(+ normalizeDeepResearchReportFormatting("# 报告标题\n\n## 1. 引言"),+ "# 报告标题\n\n## 1. 引言",+ );+});++test("only a confirmed research run may merge with an outline preview", () => {+ const reportEvents = [+ event("stage_start", { stage: "researching" }),+ event("result", { metadata: { response: "# Full report" } }),+ ];+ const regeneratedOutline = [+ event("stage_start", { stage: "decomposing" }),+ event("result", { metadata: { outline_preview: true } }),+ ];++ assert.equal(isConfirmedResearchFollowup(reportEvents), true);+ assert.equal(isConfirmedResearchFollowup(regeneratedOutline), false);+});++test("the normalized result response wins over malformed streamed content", () => {+ const events = [+ event("result", {+ metadata: { response: "# Report\n\n## 1. Introduction\n\nComplete." },+ }),+ ];+ assert.equal(+ authoritativeResearchReport(events, "# Report## 1. Introduction"),+ "# Report\n\n## 1. Introduction\n\nComplete.",+ );+});++test("a terminal confirmed research run returns the composer to chat", () => {+ const events = [+ event("stage_start", { stage: "reporting", turn_id: "turn_report" }),+ event("done", {+ turn_id: "turn_report",+ metadata: { status: "completed" },+ }),+ ];+ assert.equal(shouldReturnToChatAfterResearch(events), true);+ assert.equal(+ shouldReturnToChatAfterResearch([+ event("result", { metadata: { outline_preview: true } }),+ event("done", { metadata: { status: "completed" } }),+ ]),+ false,+ );+});++test("a completed turn with a structurally truncated report is shown as failed", () => {+ const incomplete = [+ event("stage_start", { stage: "reporting" }),+ event("result", {+ metadata: { response: "# Report\n\n## 1. Introduction\n\nThis cuts off" },+ }),+ event("done", { metadata: { status: "completed" } }),+ ];+ const complete = [+ event("stage_start", { stage: "reporting" }),+ event("result", {+ metadata: {+ response:+ "# Report\n\n## 1. Introduction\n\nIntro.\n\n## 2. Findings\n\nEvidence.\n\n## 3. Conclusion\n\nDone.",+ },+ }),+ event("done", { metadata: { status: "completed" } }),+ ];++ assert.equal(researchFollowupStatus(incomplete), "failed");+ assert.equal(researchFollowupStatus(complete), "done");+});diff --git a/web/tests/unified-ws-recovery.test.ts b/web/tests/unified-ws-recovery.test.tsnew file mode 100644index 000000000..ebb6809cb--- /dev/null+++ b/web/tests/unified-ws-recovery.test.ts@@ -0,0 +1,23 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ reconnectDelayMs,+ shouldStopReconnecting,+} from "../lib/unified-ws-recovery";++test("an active turn keeps reconnecting after the normal attempt budget", () => {+ assert.equal(+ shouldStopReconnecting({ attempt: 99, activeTurnId: "turn_research" }),+ false,+ );+ assert.equal(+ shouldStopReconnecting({ attempt: 5, activeTurnId: null }),+ true,+ );+});++test("active-turn reconnect backoff is capped", () => {+ assert.equal(reconnectDelayMs(0), 200);+ assert.equal(reconnectDelayMs(4), 3200);+ assert.equal(reconnectDelayMs(99), 3200);+});