Files
DeepTutor/web/lib/session-activity.ts
Bingxi Zhao (Frank) 139e060395 feat(chat): collect a session's generated files in the activity panel
Files the tutor produces were only reachable through the one assistant
bubble that made them, so finding a deck or spreadsheet again meant
scrolling the transcript. The activity panel already folded every
message's attachments into one list but ignored the `generated` flag that
distinguishes output from upload, lumping both into "Attachments".

Split them: generated files get their own card, above uploads, since what
a conversation produced is what you come back for. Rows reuse the
existing open-in-viewer path, and show a size plus a hover title with the
file's location under the data root — derived from the artifact URL, so no
absolute server path is persisted or sent to the browser.

Two gaps behind "I can't find the file" are fixed with it:

- A generated .pptx routed to the preview drawer's `office-text` branch,
  which renders `extracted_text` — a field only the upload path filled
  in, so produced decks opened blank. Artifacts now get preview text
  extracted while the file is still on disk, bounded to 20k chars and
  limited to formats the browser cannot render itself. The cancelled-turn
  path deliberately skips it rather than starting blocking work while
  unwinding.
- Path resolution goes through `is_public_output_path`, the same guard
  `/api/outputs` applies, so a crafted URL cannot walk out of the public
  workspace.

The artifact→attachment mapping moves out of `turn_runtime` into its own
module, and the panel's 90-line message fold moves to `lib/session-activity`
— it is pure data reduction with no React in it, which leaves the panel
presentational and the fold directly testable.
2026-07-29 00:35:43 +08:00

165 lines
5.3 KiB
TypeScript

/**
* 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,
};
}