DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(attachments): surface PDF processing stages (#1523)
Bingxi Zhao (Frank)9083d5fe3c4b
diff --git a/deeptutor/services/session/attachment_parsing.py b/deeptutor/services/session/attachment_parsing.pyindex 04400e440..8762d1096 100644--- a/deeptutor/services/session/attachment_parsing.py+++ b/deeptutor/services/session/attachment_parsing.py@@ -62,6 +62,8 @@ async def parse_chat_pdf_attachments(on_progress(attachment_id, "parsing", message) if on_progress else None),)+ if on_progress:+ on_progress(attachment_id, "retrieving", "Retrieving parsed document result")text = str(parsed.markdown or "").strip()if not text:error = "configured parser produced no content"diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 7b2362344..4548ea41c 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -355,6 +355,10 @@ class TurnExecutor:for record in attachment_recordsif str(record.get("filename") or "").lower().endswith(".pdf")]+ pdf_names = {+ str(record.get("id") or ""): str(record.get("filename") or "PDF attachment")+ for record in pdf_records+ }from deeptutor.services.session.attachment_parsing import parse_chat_pdf_attachmentsloop = asyncio.get_running_loop()@@ -369,7 +373,11 @@ class TurnExecutor:source="attachment_parsing",stage=phase,content=message,- metadata={"attachment_id": attachment_id, "phase": phase},+ metadata={+ "attachment_id": attachment_id,+ "filename": pdf_names.get(attachment_id, "PDF attachment"),+ "phase": phase,+ },),))@@ -379,7 +387,7 @@ class TurnExecutor:_attachment_progress(str(record.get("id") or ""),"received",- "Received PDF attachment",+ "PDF uploaded to DeepTutor",)attachment_records, document_texts = await parse_chat_pdf_attachments(diff --git a/tests/services/session/test_attachment_parsing.py b/tests/services/session/test_attachment_parsing.pyindex 60283a2e9..5a0a95a64 100644--- a/tests/services/session/test_attachment_parsing.py+++ b/tests/services/session/test_attachment_parsing.py@@ -89,7 +89,12 @@ async def test_scan_pdf_uses_parser_and_reports_structured_progress(assert records[0]["extracted_text"] == ""assert contexts == ["[File: scan.pdf]\n"]- assert [phase for _, phase, _ in progress] == ["submitting", "parsing", "completed"]+ assert [phase for _, phase, _ in progress] == [+ "submitting",+ "parsing",+ "retrieving",+ "completed",+ ]@pytest.mark.asynciodiff --git a/web/components/chat/home/AttachmentProcessingStatus.tsx b/web/components/chat/home/AttachmentProcessingStatus.tsxnew file mode 100644index 000000000..1420772ca--- /dev/null+++ b/web/components/chat/home/AttachmentProcessingStatus.tsx@@ -0,0 +1,98 @@+"use client";++import {+ CheckCircle2,+ FileText,+ LoaderCircle,+ TriangleAlert,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import type {+ AttachmentProcessingItem,+ AttachmentProcessingPhase,+} from "@/features/chat/selectors/attachment-processing";++function phaseLabel(+ phase: AttachmentProcessingPhase,+ t: (key: string) => string,+): string {+ switch (phase) {+ case "received":+ return t("Uploaded to DeepTutor");+ case "submitting":+ return t("Sending to document parser");+ case "parsing":+ return t("Document parser is processing");+ case "retrieving":+ return t("Retrieving parsed result");+ case "completed":+ return t("Ready for this answer");+ case "fallback":+ return t("Using local PDF text");+ case "failed":+ return t("Document parsing failed");+ }+}++function PhaseIcon({ phase }: { phase: AttachmentProcessingPhase }) {+ if (phase === "completed") {+ return <CheckCircle2 className="h-3.5 w-3.5 text-green-600" />;+ }+ if (phase === "failed" || phase === "fallback") {+ return <TriangleAlert className="h-3.5 w-3.5 text-amber-600" />;+ }+ return (+ <LoaderCircle className="h-3.5 w-3.5 animate-spin text-[var(--primary)]" />+ );+}++export default function AttachmentProcessingStatus({+ items,+}: {+ items: AttachmentProcessingItem[];+}) {+ const { t } = useTranslation();+ if (!items.length) return null;++ return (+ <div+ role="status"+ aria-live="polite"+ aria-label={t("Attachment processing")}+ className="mx-3 mb-2 space-y-1 rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3 py-2"+ >+ {items.map((item) => {+ const hasDetails =+ (item.phase === "failed" || item.phase === "fallback") &&+ item.detail;+ return (+ <div key={item.attachmentId} className="text-[11px]">+ <div className="flex min-w-0 items-center gap-2">+ <span className="shrink-0" aria-hidden="true">+ <PhaseIcon phase={item.phase} />+ </span>+ <FileText+ className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]"+ aria-hidden="true"+ />+ <span className="min-w-0 flex-1 truncate font-medium text-[var(--foreground)]">+ {item.filename}+ </span>+ <span className="shrink-0 text-[var(--muted-foreground)]">+ {phaseLabel(item.phase, t)}+ </span>+ </div>+ {hasDetails ? (+ <details className="ml-9 mt-1 text-[var(--muted-foreground)]">+ <summary className="cursor-pointer select-none">+ {t("Failure details")}+ </summary>+ <p className="mt-1 break-words">{item.detail}</p>+ </details>+ ) : null}+ </div>+ );+ })}+ </div>+ );+}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex bbd1645cb..10825911f 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -87,6 +87,8 @@ import { knowledgeBaseRef } from "@/lib/knowledge-helpers";import { ComposerInput, type ComposerInputHandle } from "./ComposerInput";import { useVoiceRecorder } from "@/hooks/useVoiceRecorder";import type { CapabilityDef } from "@/features/capabilities/presentation";+import AttachmentProcessingStatus from "./AttachmentProcessingStatus";+import type { AttachmentProcessingItem } from "@/features/chat/selectors/attachment-processing";interface PendingAttachment {type: string;@@ -202,6 +204,7 @@ export default memo(function ChatComposer({hasMessages,attachments,attachmentError,+ attachmentProcessing = [],activeCap,knowledgeBases,connectedAgents = [],@@ -306,6 +309,7 @@ export default memo(function ChatComposer({hasMessages: boolean;attachments: PendingAttachment[];attachmentError: string | null;+ attachmentProcessing?: AttachmentProcessingItem[];activeCap: CapabilityDef;knowledgeBases: KnowledgeBase[];/** Connected local subagents (Claude Code / Codex) selectable for this turn. */@@ -1007,6 +1011,7 @@ export default memo(function ChatComposer({/><SelectedResources items={contextTreeItems}/>+ <AttachmentProcessingStatus items={attachmentProcessing} /><ComposerInputref={inputHandleRef}textareaRef={textareaRef}diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex cf5aa3914..e0bc7769c 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -50,7 +50,7 @@ import StarterSuggestions from "@/components/chat/home/StarterSuggestions";// render. The heavy renderers inside still load lazily.import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";import { buildSessionActivity } from "@/components/chat/home/SessionActivityPanel";-import Tooltip from "@/components/common/Tooltip";+import Tooltip from "@/shared/ui/Tooltip";import SessionViewerPanel, {type SessionViewerPanelHandle,} from "@/components/chat/home/SessionViewerPanel";@@ -74,6 +74,7 @@ import { useAppShell } from "@/context/AppShellContext";import { WATCHING_ASK_EVENT } from "@/components/watching/WatchingPane";import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";import type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";+import { selectAttachmentProcessing } from "@/features/chat/selectors/attachment-processing";import {extractBase64FromDataUrl,readFileAsDataUrl,@@ -751,6 +752,10 @@ export default function ChatWorkspace({// "done" while nothing visibly changes.useSetupSync(state.messages);const hasMessages = state.messages.length > 0;+ const attachmentProcessing = useMemo(+ () => selectAttachmentProcessing(state.messages, state.isStreaming),+ [state.isStreaming, state.messages],+ );// A line the user might type next, written by the task model against the// conversation's own tail — general prediction, not a question to ask,// unlike the mastery/reading composers' hint. Empty conversations already@@ -2664,6 +2669,7 @@ export default function ChatWorkspace({hasMessages={hasMessages}attachments={attachments}attachmentError={attachmentError}+ attachmentProcessing={attachmentProcessing}activeCap={activeCap}knowledgeBases={kbOptions}connectedAgents={agentOptions}@@ -2926,9 +2932,9 @@ function SubagentTabWatcher({/*** Header action button that auto-collapses to icon-only when the chat* column gets squeezed (Viewer panel open, narrow viewport, etc.). The- * label stays as the button's `title` so hovering an icon still reveals- * what it does. Optional `active` flag paints the button with a primary- * tint, used by the panel-toggle buttons to surface their on/off state.+ * The shared tooltip keeps the full hint available on pointer, keyboard and+ * touch. Optional `active` paints the button with a primary tint, used by the+ * panel-toggle buttons to surface their on/off state.*/// Claude-style icon-only header action: bare 16px glyph, function revealed// by an instant tooltip; active state gets a primary tint.diff --git a/web/features/chat/selectors/attachment-processing.ts b/web/features/chat/selectors/attachment-processing.tsnew file mode 100644index 000000000..bbb623f31--- /dev/null+++ b/web/features/chat/selectors/attachment-processing.ts@@ -0,0 +1,74 @@+import type { StreamEvent } from "@/features/chat/model/protocol";++export type AttachmentProcessingPhase =+ | "received"+ | "submitting"+ | "parsing"+ | "retrieving"+ | "completed"+ | "fallback"+ | "failed";++export interface AttachmentProcessingItem {+ attachmentId: string;+ filename: string;+ phase: AttachmentProcessingPhase;+ detail: string;+}++interface MessageWithEvents {+ role: string;+ events?: StreamEvent[];+}++const PHASES = new Set<AttachmentProcessingPhase>([+ "received",+ "submitting",+ "parsing",+ "retrieving",+ "completed",+ "fallback",+ "failed",+]);++function parsingEvent(event: StreamEvent): AttachmentProcessingItem | null {+ if (event.type !== "progress" || event.source !== "attachment_parsing") {+ return null;+ }+ const phase = String(event.metadata.phase || event.stage || "");+ if (!PHASES.has(phase as AttachmentProcessingPhase)) return null;+ const attachmentId = String(event.metadata.attachment_id || "");+ const filename = String(event.metadata.filename || "PDF attachment");+ return {+ attachmentId: attachmentId || filename,+ filename,+ phase: phase as AttachmentProcessingPhase,+ detail: event.content.trim(),+ };+}++/**+ * Return the latest truthful parser state for every PDF in the latest turn.+ * Successful terminal rows disappear when the turn settles; warnings and+ * failures remain visible so the learner can inspect them after the answer.+ */+export function selectAttachmentProcessing(+ messages: MessageWithEvents[],+ isStreaming: boolean,+): AttachmentProcessingItem[] {+ const latest = [...messages]+ .reverse()+ .find((message) => message.role === "assistant");+ if (!latest) return [];++ const byAttachment = new Map<string, AttachmentProcessingItem>();+ for (const event of latest.events ?? []) {+ const item = parsingEvent(event);+ if (item) byAttachment.set(item.attachmentId, item);+ }+ const items = [...byAttachment.values()];+ if (isStreaming) return items;+ return items.filter(+ (item) => item.phase === "failed" || item.phase === "fallback",+ );+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 93d56e1a3..37d3f4084 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -48,8 +48,17 @@"Too many files, skipped some": "Too many files, skipped some","Attachment preview": "Attachment preview","Attachment": "Attachment",+ "Attachment processing": "Attachment processing","Attach": "Attach","Attach files": "Attach files",+ "Uploaded to DeepTutor": "Uploaded to DeepTutor",+ "Sending to document parser": "Sending to document parser",+ "Document parser is processing": "Document parser is processing",+ "Retrieving parsed result": "Retrieving parsed result",+ "Ready for this answer": "Ready for this answer",+ "Using local PDF text": "Using local PDF text",+ "Document parsing failed": "Document parsing failed",+ "Failure details": "Failure details","Smart Solver": "Smart Solver","Vision Solver": "Vision Solver","Elements": "Elements",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 48aa217f7..daa2cd011 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -48,8 +48,17 @@"Too many files, skipped some": "附件总量超出限制,已跳过部分文件","Attachment preview": "附件预览","Attachment": "附件",+ "Attachment processing": "附件处理中","Attach": "附件","Attach files": "上传附件",+ "Uploaded to DeepTutor": "已上传到 DeepTutor",+ "Sending to document parser": "正在提交到文档解析器",+ "Document parser is processing": "文档解析器正在处理",+ "Retrieving parsed result": "正在获取解析结果",+ "Ready for this answer": "已可用于本次回答",+ "Using local PDF text": "正在使用本地 PDF 文本",+ "Document parsing failed": "文档解析失败",+ "Failure details": "失败详情","Smart Solver": "智能解题","Vision Solver": "视觉解题","Elements": "元素",diff --git a/web/tests/attachment-processing-status.spec.tsx b/web/tests/attachment-processing-status.spec.tsxnew file mode 100644index 000000000..69832f9e2--- /dev/null+++ b/web/tests/attachment-processing-status.spec.tsx@@ -0,0 +1,113 @@+import { render, screen } from "@testing-library/react";+import { expect, it } from "vitest";+import AttachmentProcessingStatus from "@/components/chat/home/AttachmentProcessingStatus";+import type { StreamEvent } from "@/features/chat/model/protocol";+import {+ selectAttachmentProcessing,+ type AttachmentProcessingItem,+} from "@/features/chat/selectors/attachment-processing";+import { initI18n } from "@/i18n/init";++initI18n("en");++function progress(+ attachmentId: string,+ filename: string,+ phase: string,+ content: string,+): StreamEvent {+ return {+ type: "progress",+ source: "attachment_parsing",+ stage: phase,+ content,+ timestamp: 1,+ metadata: {+ attachment_id: attachmentId,+ filename,+ phase,+ },+ } as StreamEvent;+}++it("keeps one latest parser stage per attachment during a live turn", () => {+ const items = selectAttachmentProcessing(+ [+ {+ role: "assistant",+ events: [+ progress("a", "notes.pdf", "received", "Uploaded"),+ progress("b", "scan.pdf", "submitting", "Submitting"),+ progress("a", "notes.pdf", "retrieving", "Retrieving"),+ ],+ },+ ],+ true,+ );++ expect(items).toEqual([+ {+ attachmentId: "a",+ filename: "notes.pdf",+ phase: "retrieving",+ detail: "Retrieving",+ },+ {+ attachmentId: "b",+ filename: "scan.pdf",+ phase: "submitting",+ detail: "Submitting",+ },+ ]);+});++it("hides settled success but preserves parser failure details", () => {+ const items = selectAttachmentProcessing(+ [+ {+ role: "assistant",+ events: [+ progress("a", "notes.pdf", "completed", "Done"),+ progress("b", "scan.pdf", "failed", "Document parsing failed: parser offline"),+ ],+ },+ ],+ false,+ );++ expect(items.map((item) => item.filename)).toEqual(["scan.pdf"]);+ render(<AttachmentProcessingStatus items={items} />);+ expect(screen.getByRole("status", { name: "Attachment processing" })).toBeVisible();+ expect(screen.getByText("scan.pdf")).toBeVisible();+ expect(screen.getByText("Document parsing failed")).toBeVisible();+ expect(screen.getByText("Failure details")).toBeVisible();+});++it("does not carry a previous turn failure into a later answer", () => {+ const items = selectAttachmentProcessing(+ [+ {+ role: "assistant",+ events: [+ progress("a", "notes.pdf", "failed", "Document parsing failed"),+ ],+ },+ { role: "user", events: [] },+ { role: "assistant", events: [] },+ ],+ false,+ );++ expect(items).toEqual([]);+});++it("labels successful completion clearly", () => {+ const item: AttachmentProcessingItem = {+ attachmentId: "a",+ filename: "notes.pdf",+ phase: "completed",+ detail: "Document parsing completed",+ };+ render(<AttachmentProcessingStatus items={[item]} />);+ expect(screen.getByText("Ready for this answer")).toBeVisible();+});