Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(chat): collect a session's generated files in the activity panel

Bingxi Zhao (Frank)139e060395a1
diff --git a/deeptutor/services/session/artifact_attachments.py b/deeptutor/services/session/artifact_attachments.py
new file mode 100644
index 000000000..c3be4a4a9
--- /dev/null
+++ b/deeptutor/services/session/artifact_attachments.py
@@ -0,0 +1,146 @@
+"""Generated-file attachments carried by a turn's stream events.
+
+The ``exec`` / ``code_execution`` / media tools write files into the turn
+workspace and publish them in two places: each ``tool_result`` event carries
+them in ``metadata.tool_metadata.artifacts`` the moment the tool finishes (the
+source that survives cancelled turns), and the loop's final SOURCES event
+aggregates them as ``type=="artifact"`` sources. Both are read — the caller
+dedupes by URL.
+
+Persisting them as assistant-message attachments is what lets the chat UI
+render openable cards (same Viewer path as user uploads) and list them in the
+session activity panel, instead of relying on the model pasting a raw
+``/api/outputs`` URL into its answer.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote
+
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.services.path_service import get_path_service
+
+logger = logging.getLogger(__name__)
+
+# Artifact URLs are minted as ``"/api/outputs/" + quote(relative_path)`` by
+# ``services.sandbox.artifacts``. The URL is therefore the record's single
+# source of truth for locating the file again — no redundant path field has to
+# be persisted (or leaked to the client).
+_OUTPUTS_URL_PREFIX = "/api/outputs/"
+
+# Extensions whose preview drawer has no in-browser renderer and therefore
+# falls back to the extractor's plain text (mirrors the frontend's
+# ``OFFICE_BINARY_EXTS`` in ``web/components/chat/preview/previewerFor.ts``).
+# Uploads get their ``extracted_text`` from the upload path; generated files
+# never went through it, so a produced .pptx would otherwise open to an empty
+# preview. Formats the browser *can* render (.docx via docx-preview, .xlsx via
+# exceljs, PDF, images, text) are deliberately excluded — extracting them would
+# only cost IO and database size. Legacy binaries the extractor cannot parse
+# (.ppt/.doc/.xls) stay in the set: it is cheaper to let the extractor reject
+# them than to duplicate its format list here.
+_PREVIEW_TEXT_EXTENSIONS = frozenset({".pptx", ".ppt", ".doc", ".xls"})
+
+# Preview text is read by a human in the drawer, not fed to the model, so it
+# needs far less headroom than an uploaded document's index-facing extraction.
+# It is persisted inside the assistant message's ``attachments`` JSON — keeping
+# it tight keeps chat history small.
+_PREVIEW_TEXT_MAX_CHARS = 20_000
+
+
+def artifact_attachments(event: StreamEvent) -> list[dict[str, Any]]:
+ """Return the attachment records for the artifacts *event* carries."""
+ metadata = event.metadata or {}
+ raw: list[Any] = []
+ if event.type == StreamEventType.SOURCES:
+ raw = [
+ entry
+ for entry in metadata.get("sources") or []
+ if isinstance(entry, dict) and entry.get("type") == "artifact"
+ ]
+ elif event.type == StreamEventType.TOOL_RESULT:
+ tool_meta = metadata.get("tool_metadata")
+ if isinstance(tool_meta, dict):
+ raw = [e for e in tool_meta.get("artifacts") or [] if isinstance(e, dict)]
+ attachments: list[dict[str, Any]] = []
+ for entry in raw:
+ url = str(entry.get("url") or "")
+ if not url:
+ continue
+ mime = str(entry.get("mime_type") or "")
+ attachments.append(
+ {
+ "type": "image" if mime.startswith("image/") else "document",
+ "filename": str(entry.get("filename") or "file"),
+ "mime_type": mime,
+ "url": url,
+ "size_bytes": entry.get("size_bytes"),
+ "generated": True,
+ }
+ )
+ return attachments
+
+
+async def fill_preview_text(attachments: list[dict[str, Any]]) -> None:
+ """Populate ``extracted_text`` on artifacts the browser cannot render.
+
+ Mutates *attachments* in place. Reading and parsing files is blocking work,
+ so it runs off the event loop; ``to_thread`` copies contextvars, so the
+ per-user path scope resolves the same as on the loop.
+ """
+ if not any(_needs_preview_text(att) for att in attachments):
+ return
+ await asyncio.to_thread(_fill_preview_text_sync, attachments)
+
+
+def _needs_preview_text(attachment: dict[str, Any]) -> bool:
+ filename = str(attachment.get("filename") or "")
+ return Path(filename).suffix.lower() in _PREVIEW_TEXT_EXTENSIONS
+
+
+def _fill_preview_text_sync(attachments: list[dict[str, Any]]) -> None:
+ from deeptutor.utils.document_extractor import (
+ DocumentExtractionError,
+ extract_text_from_path,
+ )
+
+ for attachment in attachments:
+ if not _needs_preview_text(attachment):
+ continue
+ path = _resolve_artifact_path(str(attachment.get("url") or ""))
+ if path is None:
+ continue
+ try:
+ text = extract_text_from_path(path, max_chars=_PREVIEW_TEXT_MAX_CHARS)
+ except DocumentExtractionError as exc:
+ # Unsupported legacy binary, empty deck, oversized file: the card
+ # still opens and offers a download, it just has no inline text.
+ logger.debug("No preview text for artifact %s: %s", path, exc)
+ continue
+ except OSError as exc:
+ logger.debug("Could not read artifact %s for preview: %s", path, exc)
+ continue
+ if text.strip():
+ attachment["extracted_text"] = text
+
+
+def _resolve_artifact_path(url: str) -> Path | None:
+ """Map an artifact's ``/api/outputs`` URL back to its file on disk.
+
+ Returns ``None`` unless the result is a real file the outputs endpoint
+ would itself serve — the same guard ``/api/outputs`` applies, so a crafted
+ URL cannot walk this out of the public workspace.
+ """
+ if not url.startswith(_OUTPUTS_URL_PREFIX):
+ return None
+ service = get_path_service()
+ candidate = service.get_public_outputs_root() / unquote(url[len(_OUTPUTS_URL_PREFIX) :])
+ if not service.is_public_output_path(candidate):
+ return None
+ return candidate.resolve()
+
+
+__all__ = ["artifact_attachments", "fill_preview_text"]
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 5aee1ffcb..34159f18e 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -16,6 +16,10 @@ from typing import TYPE_CHECKING, Any, Literal
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.services.llm.utils import clean_thinking_tags
from deeptutor.services.path_service import get_path_service
+from deeptutor.services.session.artifact_attachments import (
+ artifact_attachments,
+ fill_preview_text,
+)
from deeptutor.services.session.protocol import SessionStoreProtocol
if TYPE_CHECKING:
@@ -58,50 +62,6 @@ def _narration_marker_call_id(event: StreamEvent) -> str | None:
return None
-def _artifact_attachments(event: StreamEvent) -> list[dict[str, Any]]:
- """Generated-file attachments carried by a stream event.
-
- The ``exec`` / ``code_execution`` tools surface files written to the turn
- workspace ({filename, url, mime_type, size_bytes}) in two places: each
- ``tool_result`` event carries them in ``metadata.tool_metadata.artifacts``
- the moment the tool finishes (the source that survives cancelled turns),
- and the loop's final SOURCES event aggregates them as ``type=="artifact"``
- sources. Both are read — the caller dedupes by URL. Persisting them as
- assistant-message attachments lets the chat UI render openable cards —
- same Viewer path as user uploads — instead of relying on the model
- pasting a raw ``/api/outputs`` URL.
- """
- metadata = event.metadata or {}
- raw: list[Any] = []
- if event.type == StreamEventType.SOURCES:
- raw = [
- entry
- for entry in metadata.get("sources") or []
- if isinstance(entry, dict) and entry.get("type") == "artifact"
- ]
- elif event.type == StreamEventType.TOOL_RESULT:
- tool_meta = metadata.get("tool_metadata")
- if isinstance(tool_meta, dict):
- raw = [e for e in tool_meta.get("artifacts") or [] if isinstance(e, dict)]
- attachments: list[dict[str, Any]] = []
- for entry in raw:
- url = str(entry.get("url") or "")
- if not url:
- continue
- mime = str(entry.get("mime_type") or "")
- attachments.append(
- {
- "type": "image" if mime.startswith("image/") else "document",
- "filename": str(entry.get("filename") or "file"),
- "mime_type": mime,
- "url": url,
- "size_bytes": entry.get("size_bytes"),
- "generated": True,
- }
- )
- return attachments
-
-
def _clip_text(value: str, limit: int = 4000) -> str:
text = str(value or "").strip()
if len(text) <= limit:
@@ -1678,11 +1638,17 @@ class TurnRuntimeManager:
narration_call_id = _narration_marker_call_id(event)
if narration_call_id:
narration_call_ids.add(narration_call_id)
- for attachment in _artifact_attachments(event):
+ for attachment in artifact_attachments(event):
if attachment["url"] not in seen_artifact_urls:
seen_artifact_urls.add(attachment["url"])
generated_attachments.append(attachment)
+ # Office binaries the browser cannot render need their text pulled
+ # out now, while the files are still on disk, or their preview card
+ # opens empty. Skipped on the cancelled path below: that one is
+ # already unwinding and must not start new blocking work.
+ await fill_preview_text(generated_attachments)
+
# The persisted answer is the captured content minus any narration
# rounds (their text stayed in the trace, never the answer).
assistant_content = _persisted_answer()
diff --git a/tests/services/session/test_artifact_attachments.py b/tests/services/session/test_artifact_attachments.py
new file mode 100644
index 000000000..6666affb1
--- /dev/null
+++ b/tests/services/session/test_artifact_attachments.py
@@ -0,0 +1,215 @@
+"""Tests for generated-artifact attachment records."""
+
+from __future__ import annotations
+
+from pathlib import Path
+import zipfile
+
+import pytest
+
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.services.session.artifact_attachments import (
+ _resolve_artifact_path,
+ artifact_attachments,
+ fill_preview_text,
+)
+
+# ---------------------------------------------------------------------------
+# artifact_attachments
+# ---------------------------------------------------------------------------
+
+
+class TestArtifactAttachments:
+ def _sources_event(self, sources: list[dict]) -> StreamEvent:
+ return StreamEvent(type=StreamEventType.SOURCES, metadata={"sources": sources})
+
+ def test_artifact_source_becomes_generated_attachment(self) -> None:
+ event = self._sources_event(
+ [
+ {
+ "type": "artifact",
+ "filename": "report.pdf",
+ "url": "/api/outputs/workspace/chat/chat/t1/exec/report.pdf",
+ "mime_type": "application/pdf",
+ "size_bytes": 2048,
+ }
+ ]
+ )
+ atts = artifact_attachments(event)
+ assert len(atts) == 1
+ a = atts[0]
+ assert a["type"] == "document"
+ assert a["filename"] == "report.pdf"
+ assert a["url"].endswith("report.pdf")
+ assert a["mime_type"] == "application/pdf"
+ assert a["generated"] is True
+
+ def test_image_artifact_typed_as_image(self) -> None:
+ event = self._sources_event(
+ [
+ {
+ "type": "artifact",
+ "filename": "chart.png",
+ "url": "/api/outputs/x/chart.png",
+ "mime_type": "image/png",
+ }
+ ]
+ )
+ assert artifact_attachments(event)[0]["type"] == "image"
+
+ def test_non_artifact_sources_ignored(self) -> None:
+ event = self._sources_event([{"type": "rag", "query": "q", "kb_name": "kb"}])
+ assert artifact_attachments(event) == []
+
+ def test_tool_result_artifacts_extracted(self) -> None:
+ # tool_result events carry artifacts the moment exec finishes — the
+ # durable source for cancelled turns (the aggregate SOURCES event
+ # only fires when the loop completes).
+ event = StreamEvent(
+ type=StreamEventType.TOOL_RESULT,
+ content="Exit code: 0",
+ metadata={
+ "tool_metadata": {
+ "exit_code": 0,
+ "artifacts": [
+ {
+ "filename": "notes.pdf",
+ "url": "/api/outputs/workspace/chat/chat/t2/exec/notes.pdf",
+ "mime_type": "application/pdf",
+ "size_bytes": 1024,
+ }
+ ],
+ }
+ },
+ )
+ atts = artifact_attachments(event)
+ assert len(atts) == 1
+ assert atts[0]["filename"] == "notes.pdf"
+ assert atts[0]["generated"] is True
+
+ def test_tool_result_without_artifacts_ignored(self) -> None:
+ event = StreamEvent(
+ type=StreamEventType.TOOL_RESULT,
+ content="rag result",
+ metadata={"tool_metadata": {"kb_name": "kb"}},
+ )
+ assert artifact_attachments(event) == []
+
+ def test_non_sources_event_ignored(self) -> None:
+ event = StreamEvent(type=StreamEventType.CONTENT, content="hello")
+ assert artifact_attachments(event) == []
+
+ def test_artifact_without_url_skipped(self) -> None:
+ event = self._sources_event([{"type": "artifact", "filename": "x.pdf"}])
+ assert artifact_attachments(event) == []
+
+ def test_no_absolute_path_is_persisted(self) -> None:
+ # The producer rows carry an absolute ``path``; it must not ride along
+ # into the attachment record, which reaches the browser verbatim.
+ event = self._sources_event(
+ [
+ {
+ "type": "artifact",
+ "filename": "deck.pptx",
+ "url": "/api/outputs/x/deck.pptx",
+ "path": "/home/someone/data/users/u1/workspace/x/deck.pptx",
+ "mime_type": "application/vnd.openxmlformats-officedocument"
+ ".presentationml.presentation",
+ }
+ ]
+ )
+ assert "path" not in artifact_attachments(event)[0]
+
+
+# ---------------------------------------------------------------------------
+# _resolve_artifact_path
+# ---------------------------------------------------------------------------
+
+
+class TestResolveArtifactPath:
+ def test_non_outputs_url_rejected(self) -> None:
+ assert _resolve_artifact_path("/api/attachments/abc/deck.pptx") is None
+
+ def test_empty_url_rejected(self) -> None:
+ assert _resolve_artifact_path("") is None
+
+ def test_traversal_outside_public_root_rejected(self) -> None:
+ assert _resolve_artifact_path("/api/outputs/../../../etc/passwd") is None
+
+ def test_missing_file_rejected(self) -> None:
+ # is_public_output_path also requires the target to exist as a file.
+ assert _resolve_artifact_path("/api/outputs/workspace/chat/chat/t/exec/gone.pptx") is None
+
+
+# ---------------------------------------------------------------------------
+# fill_preview_text
+# ---------------------------------------------------------------------------
+
+
+def _write_minimal_pptx(path: Path, text: str) -> None:
+ """A one-slide .pptx the OOXML extractor can read."""
+ slide = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
+ ' xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'
+ f"<p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>{text}</a:t></a:r></a:p>"
+ "</p:txBody></p:sp></p:spTree></p:cSld></p:sld>"
+ )
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(path, "w") as zf:
+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types/>')
+ zf.writestr("ppt/slides/slide1.xml", slide)
+
+
+class TestFillPreviewText:
+ @pytest.mark.asyncio
+ async def test_pptx_gets_preview_text(self, tmp_path, monkeypatch) -> None:
+ from deeptutor.services.session import artifact_attachments as module
+
+ _write_minimal_pptx(tmp_path / "deck.pptx", "Chapter one")
+ monkeypatch.setattr(
+ module, "_resolve_artifact_path", lambda url: tmp_path / "deck.pptx"
+ )
+
+ attachments = [{"filename": "deck.pptx", "url": "/api/outputs/x/deck.pptx"}]
+ await fill_preview_text(attachments)
+
+ assert "Chapter one" in attachments[0]["extracted_text"]
+
+ @pytest.mark.asyncio
+ async def test_browser_renderable_formats_skipped(self, tmp_path, monkeypatch) -> None:
+ # .docx/.xlsx/.pdf render client-side; extracting them would only cost
+ # IO and database size.
+ from deeptutor.services.session import artifact_attachments as module
+
+ calls: list[str] = []
+ monkeypatch.setattr(
+ module, "_resolve_artifact_path", lambda url: calls.append(url) or None
+ )
+
+ attachments = [
+ {"filename": "report.docx", "url": "/api/outputs/x/report.docx"},
+ {"filename": "sheet.xlsx", "url": "/api/outputs/x/sheet.xlsx"},
+ {"filename": "paper.pdf", "url": "/api/outputs/x/paper.pdf"},
+ {"filename": "chart.png", "url": "/api/outputs/x/chart.png"},
+ ]
+ await fill_preview_text(attachments)
+
+ assert calls == []
+ assert all("extracted_text" not in att for att in attachments)
+
+ @pytest.mark.asyncio
+ async def test_unreadable_artifact_leaves_record_intact(self, tmp_path, monkeypatch) -> None:
+ from deeptutor.services.session import artifact_attachments as module
+
+ missing = tmp_path / "gone.pptx"
+ monkeypatch.setattr(module, "_resolve_artifact_path", lambda url: missing)
+
+ attachments = [{"filename": "gone.pptx", "url": "/api/outputs/x/gone.pptx"}]
+ await fill_preview_text(attachments)
+
+ assert "extracted_text" not in attachments[0]
+
+ @pytest.mark.asyncio
+ async def test_empty_list_is_a_noop(self) -> None:
+ await fill_preview_text([])
diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.py
index a6c30280a..9c87c666c 100644
--- a/tests/services/session/test_turn_runtime.py
+++ b/tests/services/session/test_turn_runtime.py
@@ -6,7 +6,6 @@ import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.services.session.turn_runtime import (
- _artifact_attachments,
_clip_text,
_extract_followup_question_context,
_extract_memory_references,
@@ -100,91 +99,6 @@ class TestNarrationMarkerCallId:
assert _narration_marker_call_id(event) is None
-class TestArtifactAttachments:
- def _sources_event(self, sources: list[dict]) -> StreamEvent:
- return StreamEvent(type=StreamEventType.SOURCES, metadata={"sources": sources})
-
- def test_artifact_source_becomes_generated_attachment(self) -> None:
- event = self._sources_event(
- [
- {
- "type": "artifact",
- "filename": "report.pdf",
- "url": "/api/outputs/workspace/chat/chat/t1/exec/report.pdf",
- "mime_type": "application/pdf",
- "size_bytes": 2048,
- }
- ]
- )
- atts = _artifact_attachments(event)
- assert len(atts) == 1
- a = atts[0]
- assert a["type"] == "document"
- assert a["filename"] == "report.pdf"
- assert a["url"].endswith("report.pdf")
- assert a["mime_type"] == "application/pdf"
- assert a["generated"] is True
-
- def test_image_artifact_typed_as_image(self) -> None:
- event = self._sources_event(
- [
- {
- "type": "artifact",
- "filename": "chart.png",
- "url": "/api/outputs/x/chart.png",
- "mime_type": "image/png",
- }
- ]
- )
- assert _artifact_attachments(event)[0]["type"] == "image"
-
- def test_non_artifact_sources_ignored(self) -> None:
- event = self._sources_event([{"type": "rag", "query": "q", "kb_name": "kb"}])
- assert _artifact_attachments(event) == []
-
- def test_tool_result_artifacts_extracted(self) -> None:
- # tool_result events carry artifacts the moment exec finishes — the
- # durable source for cancelled turns (the aggregate SOURCES event
- # only fires when the loop completes).
- event = StreamEvent(
- type=StreamEventType.TOOL_RESULT,
- content="Exit code: 0",
- metadata={
- "tool_metadata": {
- "exit_code": 0,
- "artifacts": [
- {
- "filename": "notes.pdf",
- "url": "/api/outputs/workspace/chat/chat/t2/exec/notes.pdf",
- "mime_type": "application/pdf",
- "size_bytes": 1024,
- }
- ],
- }
- },
- )
- atts = _artifact_attachments(event)
- assert len(atts) == 1
- assert atts[0]["filename"] == "notes.pdf"
- assert atts[0]["generated"] is True
-
- def test_tool_result_without_artifacts_ignored(self) -> None:
- event = StreamEvent(
- type=StreamEventType.TOOL_RESULT,
- content="rag result",
- metadata={"tool_metadata": {"kb_name": "kb"}},
- )
- assert _artifact_attachments(event) == []
-
- def test_non_sources_event_ignored(self) -> None:
- event = StreamEvent(type=StreamEventType.CONTENT, content="hello")
- assert _artifact_attachments(event) == []
-
- def test_artifact_without_url_skipped(self) -> None:
- event = self._sources_event([{"type": "artifact", "filename": "x.pdf"}])
- assert _artifact_attachments(event) == []
-
-
# ---------------------------------------------------------------------------
# _clip_text
# ---------------------------------------------------------------------------
diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsx
index 253aef2c0..447886151 100644
--- a/web/components/chat/home/SessionActivityPanel.tsx
+++ b/web/components/chat/home/SessionActivityPanel.tsx
@@ -27,140 +27,35 @@ import {
History,
NotebookPen,
Paperclip,
+ Sparkles,
UserRound,
Wrench,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
-import { docIconFor, isSvgFilename } from "@/lib/doc-attachments";
-import type {
- MessageAttachment,
- MessageItem,
- MessageRequestSnapshot,
-} from "@/context/UnifiedChatContext";
-import type { StreamEvent } from "@/lib/unified-ws";
+import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";
+import type { MessageAttachment } from "@/context/UnifiedChatContext";
import { listSessions, type SessionSummary } from "@/lib/session-api";
import { listNotebooks, type NotebookSummary } from "@/lib/notebook-api";
import { bookApi } from "@/lib/book-api";
import type { Book } from "@/lib/book-types";
-/* ------------------------------------------------------------------ */
-/* Aggregator */
-/* ------------------------------------------------------------------ */
-
-export interface ToolUsage {
- name: string;
- count: number;
-}
-
-export interface AttachmentWithOrigin {
- messageIndex: number;
- attachment: MessageAttachment;
-}
-
-export interface SpaceReferenceSummary {
- historySessionIds: string[];
- bookPageCount: number;
- bookIds: string[];
- bookPages: Map<string, string[]>;
- notebookRecordCount: number;
- notebookIds: string[];
- questionEntryIds: number[];
- personas: string[];
- memoryKinds: Array<"summary" | "profile">;
-}
-
-export interface SessionActivity {
- tools: ToolUsage[];
- knowledgeBases: string[];
- space: SpaceReferenceSummary;
- attachments: AttachmentWithOrigin[];
- isEmpty: boolean;
-}
-
-export function buildSessionActivity(messages: MessageItem[]): SessionActivity {
- const toolCounts = new Map<string, number>();
- const kbs = new Set<string>();
- const historySessionIds = new Set<string>();
- const bookIds = new Set<string>();
- const bookPages = new Map<string, string[]>();
- let bookPageCount = 0;
- const notebookIds = new Set<string>();
- let notebookRecordCount = 0;
- const questionEntryIds = new Set<number>();
- const personas = new Set<string>();
- const memoryKinds = new Set<"summary" | "profile">();
- const attachments: AttachmentWithOrigin[] = [];
-
- messages.forEach((msg, idx) => {
- msg.events?.forEach((event: StreamEvent) => {
- if (event.type !== "tool_call") return;
- const name =
- String((event.metadata as { tool?: string } | undefined)?.tool || "") ||
- event.content?.trim() ||
- "tool";
- toolCounts.set(name, (toolCounts.get(name) ?? 0) + 1);
- });
-
- msg.attachments?.forEach((a) => {
- attachments.push({ messageIndex: idx, attachment: a });
- });
-
- const snap: MessageRequestSnapshot | undefined = msg.requestSnapshot;
- if (snap) {
- snap.knowledgeBases?.forEach((k) => kbs.add(k));
- snap.historyReferences?.forEach((s) => historySessionIds.add(s));
- snap.bookReferences?.forEach((b) => {
- bookIds.add(b.book_id);
- bookPageCount += b.page_ids?.length ?? 0;
- const existing = bookPages.get(b.book_id) ?? [];
- bookPages.set(b.book_id, [...existing, ...(b.page_ids ?? [])]);
- });
- snap.notebookReferences?.forEach((n) => {
- notebookIds.add(n.notebook_id);
- notebookRecordCount += n.record_ids?.length ?? 0;
- });
- snap.questionNotebookReferences?.forEach((q) => questionEntryIds.add(q));
- if (snap.persona) personas.add(snap.persona);
- snap.memoryReferences?.forEach((k) => memoryKinds.add(k));
- }
- });
-
- const tools = Array.from(toolCounts.entries())
- .map(([name, count]) => ({ name, count }))
- .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
-
- const space: SpaceReferenceSummary = {
- historySessionIds: Array.from(historySessionIds),
- bookPageCount,
- bookIds: Array.from(bookIds),
- bookPages,
- notebookRecordCount,
- notebookIds: Array.from(notebookIds),
- questionEntryIds: Array.from(questionEntryIds),
- personas: Array.from(personas),
- memoryKinds: Array.from(memoryKinds),
- };
-
- const isEmpty =
- tools.length === 0 &&
- kbs.size === 0 &&
- attachments.length === 0 &&
- space.historySessionIds.length === 0 &&
- space.bookIds.length === 0 &&
- space.notebookIds.length === 0 &&
- space.questionEntryIds.length === 0 &&
- space.personas.length === 0 &&
- space.memoryKinds.length === 0;
-
- return {
- tools,
- knowledgeBases: Array.from(kbs),
- space,
- attachments,
- isEmpty,
- };
-}
+import {
+ artifactDiskPath,
+ type AttachmentWithOrigin,
+ type SessionActivity,
+ type SpaceReferenceSummary,
+} from "@/lib/session-activity";
+
+// Re-exported so existing importers (page.tsx, SessionViewerPanel) keep reaching
+// the panel for its own contract while the fold itself lives in lib/.
+export type {
+ AttachmentWithOrigin,
+ SessionActivity,
+ SpaceReferenceSummary,
+ ToolUsage,
+} from "@/lib/session-activity";
+export { buildSessionActivity } from "@/lib/session-activity";
/* ------------------------------------------------------------------ */
/* Title resolver — lazy id -> title for Space items */
@@ -303,7 +198,7 @@ export function ActivityBody({
configSection?: ReactNode;
}) {
const { t } = useTranslation();
- const { tools, knowledgeBases, space, attachments } = activity;
+ const { tools, knowledgeBases, space, attachments, artifacts } = activity;
const { sessions, notebooks, books } = useResolvedTitles(activity, open);
const spaceSubsections: ReactNode[] = [];
@@ -402,7 +297,7 @@ export function ActivityBody({
<SectionCard icon={Wrench} title={t("Session activity")}>
<div className="px-3.5 py-5 text-center text-[12px] italic text-[var(--muted-foreground)]/80">
{t(
- "As you chat, the tools, references and attachments you use will appear here.",
+ "As you chat, the tools and references you use — and the files the tutor generates — will appear here.",
)}
</div>
</SectionCard>
@@ -454,6 +349,26 @@ export function ActivityBody({
</SectionCard>
) : null}
+ {/* Above Attachments: what this conversation produced is what you come
+ back for, more often than a file you uploaded and already have. */}
+ {artifacts.length > 0 ? (
+ <SectionCard
+ icon={Sparkles}
+ title={t("Generated files")}
+ count={artifacts.length}
+ >
+ <ul className="space-y-0.5 p-1.5">
+ {artifacts.map(({ attachment, messageIndex }, i) => (
+ <AttachmentRow
+ key={`${attachment.id ?? attachment.filename ?? i}-${messageIndex}`}
+ attachment={attachment}
+ onOpen={() => onOpenAttachment(attachment)}
+ />
+ ))}
+ </ul>
+ </SectionCard>
+ ) : null}
+
{attachments.length > 0 ? (
<SectionCard
icon={Paperclip}
@@ -584,12 +499,19 @@ function AttachmentRow({
const spec = docIconFor(filename);
const Icon = spec.Icon;
const isImage = attachment.type === "image" || isSvgFilename(filename);
+ // Generated files carry a size; showing it distinguishes a real deliverable
+ // from an empty stub without opening it. The hover title answers "where did
+ // this land on disk?" — the question the transcript cannot.
+ const size = attachment.generated ? formatBytes(attachment.size_bytes ?? -1) : "";
+ const detail = [spec.label, size].filter(Boolean).join(" · ");
+ const diskPath = attachment.generated ? artifactDiskPath(attachment.url) : null;
return (
<li>
<button
type="button"
onClick={onOpen}
+ title={diskPath ?? undefined}
className="flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-[var(--muted)]/35"
>
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/55">
@@ -604,7 +526,7 @@ function AttachmentRow({
{filename}
</span>
<span className="block truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
- {spec.label}
+ {detail}
</span>
</span>
</button>
diff --git a/web/lib/session-activity.ts b/web/lib/session-activity.ts
new file mode 100644
index 000000000..af830fd68
--- /dev/null
+++ b/web/lib/session-activity.ts
@@ -0,0 +1,164 @@
+/**
+ * Session activity — folding a conversation's messages into what it touched.
+ *
+ * Pure data reduction over the message list: which tools ran, which knowledge
+ * bases and Space objects were referenced, which files the user attached, and
+ * which files the assistant produced. No React and no rendering, so the
+ * `SessionActivityPanel` that draws it stays presentational and this fold is
+ * directly testable.
+ */
+
+import type {
+ MessageAttachment,
+ MessageItem,
+ MessageRequestSnapshot,
+} from "@/context/UnifiedChatContext";
+import type { StreamEvent } from "@/lib/unified-ws";
+
+/** Artifact URLs are `/api/outputs/<path under the data root>`. */
+const OUTPUTS_URL_PREFIX = "/api/outputs/";
+
+/**
+ * Where a generated file sits under the data root, for the row's hover title.
+ * Derived from the URL rather than persisted separately, so the backend never
+ * ships an absolute server path to the browser. Returns `null` for anything
+ * that is not an outputs URL.
+ */
+export function artifactDiskPath(url?: string): string | null {
+ if (!url || !url.startsWith(OUTPUTS_URL_PREFIX)) return null;
+ const relative = url.slice(OUTPUTS_URL_PREFIX.length);
+ try {
+ return decodeURIComponent(relative) || null;
+ } catch {
+ // A malformed escape sequence: the raw form is still a usable hint.
+ return relative || null;
+ }
+}
+
+export interface ToolUsage {
+ name: string;
+ count: number;
+}
+
+export interface AttachmentWithOrigin {
+ messageIndex: number;
+ attachment: MessageAttachment;
+}
+
+export interface SpaceReferenceSummary {
+ historySessionIds: string[];
+ bookPageCount: number;
+ bookIds: string[];
+ bookPages: Map<string, string[]>;
+ notebookRecordCount: number;
+ notebookIds: string[];
+ questionEntryIds: number[];
+ personas: string[];
+ memoryKinds: Array<"summary" | "profile">;
+}
+
+export interface SessionActivity {
+ tools: ToolUsage[];
+ knowledgeBases: string[];
+ space: SpaceReferenceSummary;
+ /** Files the user uploaded. */
+ attachments: AttachmentWithOrigin[];
+ /** Files the assistant produced (exec/code_execution/media artifacts).
+ * Split out from uploads so a session's output is one collected list
+ * instead of something you scroll the transcript to find again. */
+ artifacts: AttachmentWithOrigin[];
+ isEmpty: boolean;
+}
+
+export function buildSessionActivity(messages: MessageItem[]): SessionActivity {
+ const toolCounts = new Map<string, number>();
+ const kbs = new Set<string>();
+ const historySessionIds = new Set<string>();
+ const bookIds = new Set<string>();
+ const bookPages = new Map<string, string[]>();
+ let bookPageCount = 0;
+ const notebookIds = new Set<string>();
+ let notebookRecordCount = 0;
+ const questionEntryIds = new Set<number>();
+ const personas = new Set<string>();
+ const memoryKinds = new Set<"summary" | "profile">();
+ const attachments: AttachmentWithOrigin[] = [];
+ const artifacts: AttachmentWithOrigin[] = [];
+
+ messages.forEach((msg, idx) => {
+ msg.events?.forEach((event: StreamEvent) => {
+ if (event.type !== "tool_call") return;
+ const name =
+ String((event.metadata as { tool?: string } | undefined)?.tool || "") ||
+ event.content?.trim() ||
+ "tool";
+ toolCounts.set(name, (toolCounts.get(name) ?? 0) + 1);
+ });
+
+ msg.attachments?.forEach((a) => {
+ // `generated` marks files the assistant produced this turn; everything
+ // else is something the user attached.
+ (a.generated ? artifacts : attachments).push({
+ messageIndex: idx,
+ attachment: a,
+ });
+ });
+
+ const snap: MessageRequestSnapshot | undefined = msg.requestSnapshot;
+ if (snap) {
+ snap.knowledgeBases?.forEach((k) => kbs.add(k));
+ snap.historyReferences?.forEach((s) => historySessionIds.add(s));
+ snap.bookReferences?.forEach((b) => {
+ bookIds.add(b.book_id);
+ bookPageCount += b.page_ids?.length ?? 0;
+ const existing = bookPages.get(b.book_id) ?? [];
+ bookPages.set(b.book_id, [...existing, ...(b.page_ids ?? [])]);
+ });
+ snap.notebookReferences?.forEach((n) => {
+ notebookIds.add(n.notebook_id);
+ notebookRecordCount += n.record_ids?.length ?? 0;
+ });
+ snap.questionNotebookReferences?.forEach((q) => questionEntryIds.add(q));
+ if (snap.persona) personas.add(snap.persona);
+ snap.memoryReferences?.forEach((k) => memoryKinds.add(k));
+ }
+ });
+
+ const tools = Array.from(toolCounts.entries())
+ .map(([name, count]) => ({ name, count }))
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
+
+ const space: SpaceReferenceSummary = {
+ historySessionIds: Array.from(historySessionIds),
+ bookPageCount,
+ bookIds: Array.from(bookIds),
+ bookPages,
+ notebookRecordCount,
+ notebookIds: Array.from(notebookIds),
+ questionEntryIds: Array.from(questionEntryIds),
+ personas: Array.from(personas),
+ memoryKinds: Array.from(memoryKinds),
+ };
+
+ const isEmpty =
+ tools.length === 0 &&
+ kbs.size === 0 &&
+ attachments.length === 0 &&
+ artifacts.length === 0 &&
+ space.historySessionIds.length === 0 &&
+ space.bookIds.length === 0 &&
+ space.notebookIds.length === 0 &&
+ space.questionEntryIds.length === 0 &&
+ space.personas.length === 0 &&
+ space.memoryKinds.length === 0;
+
+ return {
+ tools,
+ knowledgeBases: Array.from(kbs),
+ space,
+ attachments,
+ artifacts,
+ isEmpty,
+ };
+}
+
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index c734ddc2a..1be82b8f9 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2183,7 +2183,8 @@
"Session activity": "Session activity",
"Session title": "Session title",
"Start a conversation to rename": "Start a conversation to rename",
- "As you chat, the tools, references and attachments you use will appear here.": "As you chat, the tools, references and attachments you use will appear here.",
+ "As you chat, the tools and references you use — and the files the tutor generates — will appear here.": "As you chat, the tools and references you use — and the files the tutor generates — will appear here.",
+ "Generated files": "Generated files",
"Question #{{n}}": "Question #{{n}}",
"Tools used": "Tools used",
"{{n}} page(s)": "{{n}} page(s)",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 764cde426..f7ba1238a 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2183,7 +2183,8 @@
"Session activity": "会话活动",
"Session title": "会话标题",
"Start a conversation to rename": "开始对话后即可重命名",
- "As you chat, the tools, references and attachments you use will appear here.": "随着你聊天,使用过的工具、引用和附件会显示在这里。",
+ "As you chat, the tools and references you use — and the files the tutor generates — will appear here.": "随着你聊天,使用过的工具和引用、以及 AI 导师生成的文件会显示在这里。",
+ "Generated files": "生成的文件",
"Question #{{n}}": "第 {{n}} 题",
"Tools used": "使用的工具",
"{{n}} page(s)": "共 {{n}} 页",
diff --git a/web/tests/session-activity.test.ts b/web/tests/session-activity.test.ts
new file mode 100644
index 000000000..8d407d832
--- /dev/null
+++ b/web/tests/session-activity.test.ts
@@ -0,0 +1,190 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ artifactDiskPath,
+ buildSessionActivity,
+} from "../lib/session-activity";
+import type {
+ MessageItem,
+ MessageRequestSnapshot,
+} from "../context/UnifiedChatContext";
+import type { StreamEvent } from "../lib/unified-ws";
+
+/** A StreamEvent with only the fields the fold reads set explicitly. */
+function event(type: string, metadata: Record<string, unknown> = {}): StreamEvent {
+ return {
+ type: type as StreamEvent["type"],
+ source: "",
+ stage: "",
+ content: "",
+ metadata,
+ timestamp: 0,
+ };
+}
+
+/** A request snapshot with only the fields the fold reads set explicitly. */
+function snapshot(
+ fields: Partial<MessageRequestSnapshot> = {},
+): MessageRequestSnapshot {
+ return {
+ content: "",
+ enabledTools: [],
+ knowledgeBases: [],
+ language: "en",
+ ...fields,
+ };
+}
+
+function messages(...items: Partial<MessageItem>[]): MessageItem[] {
+ return items.map(
+ (item, idx) =>
+ ({
+ id: idx + 1,
+ role: idx % 2 === 0 ? "user" : "assistant",
+ content: "",
+ ...item,
+ }) as MessageItem,
+ );
+}
+
+const UPLOAD = {
+ type: "document",
+ filename: "syllabus.pdf",
+ id: "att-1",
+ url: "/api/attachments/att-1/syllabus.pdf",
+};
+
+const ARTIFACT = {
+ type: "document",
+ filename: "summary.pptx",
+ generated: true,
+ size_bytes: 24_576,
+ url: "/api/outputs/workspace/chat/chat/turn_1/exec/summary.pptx",
+};
+
+/* ------------------------------------------------------------------ */
+/* uploads vs generated files */
+/* ------------------------------------------------------------------ */
+
+test("splits generated files out of user uploads", () => {
+ const activity = buildSessionActivity(
+ messages(
+ { role: "user", attachments: [UPLOAD] },
+ { role: "assistant", attachments: [ARTIFACT] },
+ ),
+ );
+
+ assert.equal(activity.attachments.length, 1);
+ assert.equal(activity.attachments[0].attachment.filename, "syllabus.pdf");
+ assert.equal(activity.artifacts.length, 1);
+ assert.equal(activity.artifacts[0].attachment.filename, "summary.pptx");
+});
+
+test("keeps the originating message index on both lists", () => {
+ const activity = buildSessionActivity(
+ messages(
+ { role: "user", attachments: [UPLOAD] },
+ { role: "assistant", attachments: [ARTIFACT] },
+ ),
+ );
+
+ assert.equal(activity.attachments[0].messageIndex, 0);
+ assert.equal(activity.artifacts[0].messageIndex, 1);
+});
+
+test("collects generated files across every turn in order", () => {
+ const second = { ...ARTIFACT, filename: "chart.png", type: "image" };
+ const activity = buildSessionActivity(
+ messages(
+ { role: "user" },
+ { role: "assistant", attachments: [ARTIFACT] },
+ { role: "user" },
+ { role: "assistant", attachments: [second] },
+ ),
+ );
+
+ assert.deepEqual(
+ activity.artifacts.map((a) => a.attachment.filename),
+ ["summary.pptx", "chart.png"],
+ );
+});
+
+test("a session with only generated files is not empty", () => {
+ // Regression guard: isEmpty ignoring artifacts would render the empty-state
+ // card over a session that did produce something.
+ const activity = buildSessionActivity(
+ messages({ role: "assistant", attachments: [ARTIFACT] }),
+ );
+
+ assert.equal(activity.isEmpty, false);
+ assert.equal(activity.attachments.length, 0);
+});
+
+test("a session with nothing at all is empty", () => {
+ const activity = buildSessionActivity(messages({ role: "user" }));
+
+ assert.equal(activity.isEmpty, true);
+ assert.equal(activity.artifacts.length, 0);
+});
+
+/* ------------------------------------------------------------------ */
+/* tools / knowledge bases */
+/* ------------------------------------------------------------------ */
+
+test("counts tool calls and orders them by frequency", () => {
+ const activity = buildSessionActivity(
+ messages({
+ role: "assistant",
+ events: [
+ event("tool_call", { tool: "rag" }),
+ event("tool_call", { tool: "exec" }),
+ event("tool_call", { tool: "rag" }),
+ event("content"),
+ ],
+ }),
+ );
+
+ assert.deepEqual(activity.tools, [
+ { name: "rag", count: 2 },
+ { name: "exec", count: 1 },
+ ]);
+});
+
+test("dedupes knowledge bases across turns", () => {
+ const activity = buildSessionActivity(
+ messages(
+ { role: "user", requestSnapshot: snapshot({ knowledgeBases: ["KB"] }) },
+ { role: "user", requestSnapshot: snapshot({ knowledgeBases: ["KB"] }) },
+ ),
+ );
+
+ assert.deepEqual(activity.knowledgeBases, ["KB"]);
+});
+
+/* ------------------------------------------------------------------ */
+/* artifactDiskPath */
+/* ------------------------------------------------------------------ */
+
+test("derives the data-root-relative path from an outputs URL", () => {
+ assert.equal(
+ artifactDiskPath(ARTIFACT.url),
+ "workspace/chat/chat/turn_1/exec/summary.pptx",
+ );
+});
+
+test("decodes percent-escaped segments", () => {
+ assert.equal(
+ artifactDiskPath("/api/outputs/workspace/chat/chat/t/exec/%E6%8A%A5%E5%91%8A.pptx"),
+ "workspace/chat/chat/t/exec/报告.pptx",
+ );
+});
+
+test("falls back to the raw form on a malformed escape", () => {
+ assert.equal(artifactDiskPath("/api/outputs/bad%zz.pptx"), "bad%zz.pptx");
+});
+
+test("returns null for uploads and for missing URLs", () => {
+ assert.equal(artifactDiskPath(UPLOAD.url), null);
+ assert.equal(artifactDiskPath(undefined), null);
+ assert.equal(artifactDiskPath(""), null);
+});