Skip to content

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

fix: resolve generated files in partner archives

Frankisfrankfc13e0f998fb
diff --git a/web/components/common/InlineFileCard.tsx b/web/components/common/InlineFileCard.tsx
index 5487b537d..fff2d748f 100644
--- a/web/components/common/InlineFileCard.tsx
+++ b/web/components/common/InlineFileCard.tsx
@@ -168,9 +168,12 @@ function boundaryOk(text: string, start: number, len: number): boolean {
* Build a remark plugin that wraps every plain-text occurrence of a known
* generated filename in an ``attachment:`` link. Matches the exact filename
* and a separator-normalized variant (``_``/``-`` ⇄ space), longest first.
- * Returns null when there are no filenames to match.
+ * Returns null when there are no filenames and relative-link fallback is off.
*/
-export function makeFileLinkRemarkPlugin(files: MessageAttachment[]) {
+export function makeFileLinkRemarkPlugin(
+ files: MessageAttachment[],
+ unresolvedRelativeLinksAsText = false,
+) {
const entries: Array<{ needle: string; name: string }> = [];
const seen = new Set<string>();
for (const file of files) {
@@ -189,7 +192,7 @@ export function makeFileLinkRemarkPlugin(files: MessageAttachment[]) {
}
}
}
- if (!entries.length) return null;
+ if (!entries.length && !unresolvedRelativeLinksAsText) return null;
// Prefer the most specific (longest) needle when several could match.
entries.sort((a, b) => b.needle.length - a.needle.length);
@@ -307,13 +310,30 @@ export function makeFileLinkRemarkPlugin(files: MessageAttachment[]) {
return nodes;
};
- const visit = (node: Record<string, unknown>): void => {
+ const visit = (
+ node: Record<string, unknown>,
+ definitions: Map<string, Record<string, unknown>>,
+ ): void => {
const children = node.children as
| Array<Record<string, unknown>>
| undefined;
if (!Array.isArray(children)) return;
const out: Array<Record<string, unknown>> = [];
- for (const child of children) {
+ for (let child of children) {
+ if (
+ unresolvedRelativeLinksAsText &&
+ (child.type === "linkReference" || child.type === "imageReference")
+ ) {
+ const definition = definitions.get(String(child.identifier).toUpperCase());
+ if (definition) {
+ child = {
+ ...child,
+ type: child.type === "linkReference" ? "link" : "image",
+ url: definition.url,
+ title: definition.title,
+ };
+ }
+ }
if (child.type === "text" && typeof child.value === "string") {
out.push(...splitText(child.value));
} else if (child.type === "link" || child.type === "image") {
@@ -324,17 +344,40 @@ export function makeFileLinkRemarkPlugin(files: MessageAttachment[]) {
const real = linkTargetFile(child);
if (real) {
child.url = `${ATTACHMENT_HREF_PREFIX}${encodeURIComponent(real)}`;
+ } else if (
+ unresolvedRelativeLinksAsText &&
+ !/^(?:[a-z][a-z\d+.-]*:|\/|#|\?)/i.test(String(child.url ?? ""))
+ ) {
+ // Archive file paths without a published snapshot must not navigate.
+ out.push(
+ ...(child.type === "image"
+ ? [{ type: "text", value: String(child.alt ?? "") }]
+ : ((child.children as Record<string, unknown>[] | undefined) ?? [])),
+ );
+ continue;
}
out.push(child);
} else {
- if (!SKIP_NODE_TYPES.has(child.type as string)) visit(child);
+ if (!SKIP_NODE_TYPES.has(child.type as string)) visit(child, definitions);
out.push(child);
}
}
node.children = out;
};
- return () => (tree: Record<string, unknown>) => visit(tree);
+ return () => (tree: Record<string, unknown>) => {
+ const definitions = new Map<string, Record<string, unknown>>();
+ const collectDefinitions = (node: Record<string, unknown>): void => {
+ // mdast already normalizes identifiers; match mdast-to-hast's case fold.
+ const id = String(node.identifier).toUpperCase();
+ if (node.type === "definition" && !definitions.has(id)) definitions.set(id, node);
+ for (const child of (node.children as Record<string, unknown>[] | undefined) ?? []) {
+ collectDefinitions(child);
+ }
+ };
+ if (unresolvedRelativeLinksAsText) collectDefinitions(tree);
+ visit(tree, definitions);
+ };
}
/** Files with no visible inline link in the rendered Markdown. Reuse the
@@ -378,6 +421,7 @@ interface InlineFileCardValue {
files: MessageAttachment[];
resolve: (name: string) => MessageAttachment | undefined;
onOpen?: (attachment: MessageAttachment) => void;
+ unresolvedRelativeLinksAsText: boolean;
}
const InlineFileCardContext = createContext<InlineFileCardValue | null>(null);
@@ -400,11 +444,13 @@ export function InlineFileCardProvider({
attachments,
events,
onOpen,
+ unresolvedRelativeLinksAsText = false,
children,
}: {
attachments: MessageAttachment[];
events?: StreamEvent[];
onOpen?: (attachment: MessageAttachment) => void;
+ unresolvedRelativeLinksAsText?: boolean;
children: ReactNode;
}) {
const files = useMemo(
@@ -430,8 +476,8 @@ export function InlineFileCardProvider({
if (direct) return direct;
return base.get(norm(basename(name)));
};
- return { files, resolve, onOpen };
- }, [files, onOpen]);
+ return { files, resolve, onOpen, unresolvedRelativeLinksAsText };
+ }, [files, onOpen, unresolvedRelativeLinksAsText]);
return (
<InlineFileCardContext.Provider value={value}>
{children}
diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx
index 0fd1f711c..37b4077fa 100644
--- a/web/components/common/RichMarkdownRenderer.tsx
+++ b/web/components/common/RichMarkdownRenderer.tsx
@@ -697,8 +697,11 @@ export default function RichMarkdownRenderer({
// clickable file links (no-op outside a chat message — fileCtx is null).
const fileCtx = useInlineFileCardContext();
const fileLinkPlugin = useMemo(
- () => makeFileLinkRemarkPlugin(fileCtx?.files ?? []),
- [fileCtx?.files],
+ () => makeFileLinkRemarkPlugin(
+ fileCtx?.files ?? [],
+ fileCtx?.unresolvedRelativeLinksAsText,
+ ),
+ [fileCtx?.files, fileCtx?.unresolvedRelativeLinksAsText],
);
const remarkPlugins = useMemo(() => {
const p: Array<any> = [remarkGfm];
diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsx
index ac898601c..546376e3d 100644
--- a/web/components/common/SimpleMarkdownRenderer.tsx
+++ b/web/components/common/SimpleMarkdownRenderer.tsx
@@ -454,8 +454,11 @@ export default function SimpleMarkdownRenderer({
// clickable file links (no-op outside a chat message — fileCtx is null).
const fileCtx = useInlineFileCardContext();
const fileLinkPlugin = useMemo(
- () => makeFileLinkRemarkPlugin(fileCtx?.files ?? []),
- [fileCtx?.files],
+ () => makeFileLinkRemarkPlugin(
+ fileCtx?.files ?? [],
+ fileCtx?.unresolvedRelativeLinksAsText,
+ ),
+ [fileCtx?.files, fileCtx?.unresolvedRelativeLinksAsText],
);
const remarkPlugins = useMemo(
() => (fileLinkPlugin ? [remarkGfm, fileLinkPlugin] : [remarkGfm]),
diff --git a/web/components/partners/PartnerArchives.tsx b/web/components/partners/PartnerArchives.tsx
index ded8fd1de..4db136aff 100644
--- a/web/components/partners/PartnerArchives.tsx
+++ b/web/components/partners/PartnerArchives.tsx
@@ -24,6 +24,8 @@ import type { ExportableMessage } from "@/lib/chat-export";
import { plainTextPreview } from "@/lib/chat-outline";
import { displaySessionTitle } from "@/lib/session-title";
import AssistantResponse from "@/components/common/AssistantResponse";
+import { InlineFileCardProvider } from "@/components/common/InlineFileCard";
+import type { MessageAttachment } from "@/features/chat/ChatStateAdapter";
import Tooltip from "@/shared/ui/Tooltip";
interface HistoryMessage {
@@ -31,6 +33,27 @@ interface HistoryMessage {
content: string;
timestamp?: string;
channel?: string;
+ attachments?: Record<string, unknown>[];
+}
+
+function historyAttachments(attachments?: Record<string, unknown>[]): MessageAttachment[] {
+ return (attachments ?? []).flatMap((attachment): MessageAttachment[] => {
+ if (
+ typeof attachment.type !== "string" ||
+ typeof attachment.filename !== "string" ||
+ typeof attachment.url !== "string" ||
+ (attachment.generated !== true && attachment.origin !== "workspace")
+ ) return [];
+ return [{
+ type: attachment.type,
+ filename: attachment.filename,
+ url: attachment.url,
+ generated: attachment.generated === true,
+ origin: attachment.origin === "workspace" ? "workspace" : undefined,
+ relative_path: typeof attachment.relative_path === "string" ? attachment.relative_path : undefined,
+ title: typeof attachment.title === "string" ? attachment.title : undefined,
+ }];
+ });
}
function conversationPreview(content: string): string {
@@ -147,6 +170,16 @@ export default function PartnerArchives({
const selectedKeyRef = useRef(selectedKey);
selectedKeyRef.current = selectedKey;
+ const downloadGeneratedAttachment = useCallback((attachment: MessageAttachment) => {
+ if (!attachment.url) return;
+ const link = document.createElement("a");
+ link.href = attachment.url;
+ link.download = attachment.filename || "download";
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ }, []);
+
const selected = useMemo(
() =>
sessions.find((session) => session.session_key === selectedKey) ?? null,
@@ -460,7 +493,13 @@ export default function PartnerArchives({
}`}
>
{message.role === "assistant" ? (
- <AssistantResponse content={message.content} />
+ <InlineFileCardProvider
+ attachments={historyAttachments(message.attachments)}
+ onOpen={downloadGeneratedAttachment}
+ unresolvedRelativeLinksAsText
+ >
+ <AssistantResponse content={message.content} />
+ </InlineFileCardProvider>
) : message.content}
</div>
</div>
diff --git a/web/tests/partner-archives-markdown.spec.tsx b/web/tests/partner-archives-markdown.spec.tsx
index 9434762fd..eb70a5c13 100644
--- a/web/tests/partner-archives-markdown.spec.tsx
+++ b/web/tests/partner-archives-markdown.spec.tsx
@@ -1,7 +1,9 @@
-import { cleanup, render, screen, within } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { fromMarkdown } from "mdast-util-from-markdown";
import PartnerArchives from "@/components/partners/PartnerArchives";
+import { makeFileLinkRemarkPlugin } from "@/components/common/InlineFileCard";
const api = vi.hoisted(() => ({ sessions: vi.fn(), historyPage: vi.fn() }));
const translate = vi.hoisted(() => (key: string) => key);
@@ -41,6 +43,108 @@ beforeEach(() => {
});
afterEach(cleanup);
+const savedFile = {
+ type: "document",
+ filename: "report.md",
+ mime_type: "text/markdown",
+ url: "/files/workspace-items/ws_test/wsi_report",
+ generated: true,
+ origin: "workspace",
+ relative_path: "outputs/chat/turn/report.md",
+};
+const rendererCases = ["", "<div>Archive context</div>\n\n"].flatMap((prefix) =>
+ ["inline", "reference"].map((style) => ({ prefix, style })),
+);
+
+it("keeps reference handling opt-in for other file-provider consumers", () => {
+ const tree = fromMarkdown("[Download][report] ![Chart][chart]\n\n[report]: outputs/chat/turn/report.md\n[chart]: outputs/chart.png");
+ makeFileLinkRemarkPlugin([{ ...savedFile, origin: "workspace" }])?.()(
+ tree as unknown as Record<string, unknown>,
+ );
+ expect(tree.children[0]).toMatchObject({
+ type: "paragraph",
+ children: [{ type: "linkReference" }, { type: "text" }, { type: "imageReference" }],
+ });
+ expect(tree.children[1]).toMatchObject({ type: "definition", url: savedFile.relative_path });
+});
+
+it.each(rendererCases)(
+ "downloads a saved workspace file using $style Markdown with prefix $prefix",
+ async ({ prefix, style }) => {
+ api.historyPage.mockResolvedValue({
+ messages: [{
+ role: "assistant",
+ content: prefix + (style === "reference"
+ ? "[Download][RePoRt FiLe]\n\n[ report file ]: outputs/chat/turn/report.md\n[REPORT FILE]: outputs/missing.md"
+ : "[Download](outputs/chat/turn/report.md)"),
+ attachments: [savedFile],
+ }],
+ next_before: null,
+ });
+ const downloads: { href: string | null; filename: string }[] = [];
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {
+ downloads.push({ href: this.getAttribute("href"), filename: this.download });
+ });
+ render(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
+
+ const article = await screen.findByRole("article");
+ const card = await within(article).findByRole("button", { name: "report.md" });
+ expect(article.querySelector("a[href='outputs/chat/turn/report.md']")).toBeNull();
+ fireEvent.click(card);
+ expect(downloads).toEqual([{ href: savedFile.url, filename: savedFile.filename }]);
+ },
+);
+
+it.each(rendererCases)(
+ "keeps unresolved $style file paths as text with prefix $prefix",
+ async ({ prefix, style }) => {
+ api.historyPage.mockResolvedValue({
+ messages: [{
+ role: "assistant",
+ content: prefix + (style === "reference"
+ ? "[Unpublished report][missing] ![Unavailable chart][chart] [External][external] [Section][section] [Query][query] [App][app] [Undefined][no-definition]\n\n[missing]: outputs/missing.md\n[chart]: outputs/missing.png\n[external]: https://example.com/docs\n[section]: #section\n[query]: ?view=archive\n[app]: /settings"
+ : "[Unpublished report](outputs/missing.md) ![Unavailable chart](outputs/missing.png) [External](https://example.com/docs) [Section](#section) [Query](?view=archive) [App](/settings)"),
+ }],
+ next_before: null,
+ });
+ render(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
+
+ const article = await screen.findByRole("article");
+ await within(article).findByText("Unpublished report", { exact: false });
+ expect(article.querySelector("a[href='outputs/missing.md']")).toBeNull();
+ expect(article.querySelector("img[src='outputs/missing.png']")).toBeNull();
+ expect(article).toHaveTextContent("Unavailable chart");
+ expect(within(article).getByRole("link", { name: "External" })).toHaveAttribute("href", "https://example.com/docs");
+ expect(within(article).getByRole("link", { name: "Section" })).toHaveAttribute("href", "#section");
+ expect(within(article).getByRole("link", { name: "Query" })).toHaveAttribute("href", "?view=archive");
+ expect(within(article).getByRole("link", { name: "App" })).toHaveAttribute("href", "/settings");
+ if (style === "reference") expect(article).toHaveTextContent("[Undefined][no-definition]");
+ },
+);
+
+it.each(rendererCases)("resolves a saved $style workspace image with prefix $prefix", async ({ prefix, style }) => {
+ api.historyPage.mockResolvedValue({
+ messages: [{
+ role: "assistant",
+ content: prefix + (style === "reference"
+ ? "![Published chart][chart]\n\n[chart]: outputs/chart.png"
+ : "![Published chart](outputs/chart.png)"),
+ attachments: [{
+ ...savedFile,
+ type: "image",
+ filename: "chart.png",
+ mime_type: "image/png",
+ relative_path: "outputs/chart.png",
+ }],
+ }],
+ next_before: null,
+ });
+ render(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
+
+ const article = await screen.findByRole("article");
+ expect(await within(article).findByRole("img", { name: "Published chart" })).toHaveAttribute("src", savedFile.url);
+});
+
it("renders assistant Markdown with the real chat renderer and keeps user text literal", async () => {
const onMessagesChange = vi.fn();
const { container } = render(