diff --git a/web/components/common/InlineFileCard.tsx b/web/components/common/InlineFileCard.tsx index d551642ec..65189b050 100644 --- a/web/components/common/InlineFileCard.tsx +++ b/web/components/common/InlineFileCard.tsx @@ -1,11 +1,11 @@ "use client"; -import { createContext, useContext, useMemo, type ReactNode } from "react"; +import { createContext, useContext, useMemo, useSyncExternalStore, type ReactNode } from "react"; import { fromMarkdown } from "mdast-util-from-markdown"; import type { MessageAttachment } from "@/features/chat/ChatStateAdapter"; import { docIconFor } from "@/lib/doc-attachments"; -import { isChatFileLink } from "@/lib/chat-file-link"; +import { chatFilePath } from "@/lib/chat-file-link"; import { ChatFileLink } from "./ChatFileLink"; import { langForFilename } from "@/lib/code-languages"; import type { StreamEvent } from "@/features/chat/model/protocol"; @@ -430,12 +430,15 @@ export function unlinkedGeneratedFiles( interface InlineFileCardValue { files: MessageAttachment[]; + origin?: string; resolve: (name: string) => MessageAttachment | undefined; onOpen?: (attachment: MessageAttachment) => void; unresolvedRelativeLinksAsText: boolean; } const InlineFileCardContext = createContext(null); +// The page origin is constant for the document and becomes known after hydration. +const subscribeToOrigin = () => () => {}; export function useInlineFileCardContext(): InlineFileCardValue | null { return useContext(InlineFileCardContext); @@ -464,6 +467,7 @@ export function InlineFileCardProvider({ unresolvedRelativeLinksAsText?: boolean; children: ReactNode; }) { + const origin = useSyncExternalStore(subscribeToOrigin, () => window.location.origin, () => undefined); const files = useMemo( () => mergeGeneratedFiles(attachments, events), [attachments, events], @@ -487,8 +491,8 @@ export function InlineFileCardProvider({ if (direct) return direct; return base.get(norm(basename(name))); }; - return { files, resolve, onOpen, unresolvedRelativeLinksAsText }; - }, [files, onOpen, unresolvedRelativeLinksAsText]); + return { files, origin, resolve, onOpen, unresolvedRelativeLinksAsText }; + }, [files, origin, onOpen, unresolvedRelativeLinksAsText]); return ( {children} @@ -507,10 +511,10 @@ export function ChatFileReference({ }) { const context = useInlineFileCardContext(); if (!context?.onOpen || !href) return fallback; - const serveFile = isChatFileLink(href); + const filePath = chatFilePath(href, context.origin); const filename = decode(href.split(/[?#]/, 1)[0].split("/").pop() ?? ""); if ( - !serveFile && + !filePath && (/^(?:[a-z][a-z\d+.-]*:|\/|[?#])/i.test(href) || (!/\.[a-z\d][a-z\d_-]*$/i.test(filename) && !langForFilename(filename))) ) { @@ -518,14 +522,14 @@ export function ChatFileReference({ } return ( file.url === href)) || { - filename: serveFile && href.startsWith("/files/workspace-items/") ? undefined : filename, + attachment={(filePath && context.files.find((file) => file.url === filePath)) || { + filename: filePath?.startsWith("/files/workspace-items/") ? undefined : filename, type: "file", - url: serveFile ? href : undefined, - id: serveFile ? undefined : `unavailable:${href}`, + url: filePath, + id: filePath ? undefined : `unavailable:${href}`, }} onOpen={context.onOpen} - unavailableReference={serveFile ? undefined : href} + unavailableReference={filePath ? undefined : href} className="text-[var(--primary)] underline decoration-[var(--primary)]/40 underline-offset-2" > {label} diff --git a/web/lib/chat-file-link.ts b/web/lib/chat-file-link.ts index eccafbfb5..87fb353b2 100644 --- a/web/lib/chat-file-link.ts +++ b/web/lib/chat-file-link.ts @@ -7,6 +7,21 @@ export function isChatFileLink(href: string): boolean { ) } +/** Map a pasted same-origin file URL back to the route used by the chat viewer. */ +export function chatFilePath(href: string, origin?: string): string | undefined { + if (isChatFileLink(href)) return href + if (!origin || !/^https?:\/\//i.test(href) || /[\\\r\n\t]/.test(href)) return + + try { + const url = new URL(href) + if (url.origin !== origin || url.username || url.password) return + const path = url.pathname + url.search + url.hash + return isChatFileLink(path) ? path : undefined + } catch { + return undefined + } +} + /** Published lesson pages render model-written scripts in the lesson sandbox. */ export function isChatVideoLessonLink(href: string): boolean { if (!isChatFileLink(href)) return false diff --git a/web/tests/session-viewer-panel.spec.tsx b/web/tests/session-viewer-panel.spec.tsx index e348c12c3..a8a61232e 100644 --- a/web/tests/session-viewer-panel.spec.tsx +++ b/web/tests/session-viewer-panel.spec.tsx @@ -70,8 +70,10 @@ it("keeps an explicit return to the conversation inside the Activity view", asyn expect(onClose).toHaveBeenCalledTimes(1); }); -it("opens a stale file link inside the chat and returns to the same conversation", async () => { - const url = "/files/outputs/workspace/chat/session/turn/missing.md"; +it.each(["relative path", "absolute URL"])("opens a stale file from a %s and returns to the same conversation", async (form) => { + const url = "/files/outputs/workspace/chat/session/turn/missing.md?dt_workspace=course"; + const href = form === "absolute URL" ? new URL(url, window.location.origin).href : url; + const external = new URL(url, "https://example.org").href; let completeProbe!: (response: Response) => void; const probe = new Promise((resolve) => { completeProbe = resolve; }); const fetch = vi.fn(() => probe); @@ -79,10 +81,16 @@ it("opens a stale file link inside the chat and returns to the same conversation vi.stubGlobal("fetch", fetch); try { - render(); + render(); const file = screen.getByRole("link", { name: "Meeting notes" }); - expect(file.getAttribute("href")).toContain(url); expect(file).toHaveAttribute("data-chat-file-link"); + expect(file).toHaveAttribute("href", url); + const externalLink = screen.getByRole("link", { name: "External" }); + expect(externalLink).toHaveAttribute("href", external); + expect(externalLink).not.toHaveAttribute("data-chat-file-link"); expect(fireEvent.click(file)).toBe(false); expect(await screen.findByRole("status", { name: /^Loading/ })).toBeVisible(); expect(screen.queryByRole("link", { name: "Download" })).not.toBeInTheDocument(); @@ -199,7 +207,8 @@ it("distinguishes unsupported snapshots from unavailable files with the same nam fireEvent.click(screen.getByRole("link", { name: "Generated archive" })); expect(await screen.findByText("Preview is not available for this file type.")).toBeVisible(); - expect(screen.getAllByRole("link", { name: "Download" }).some((link) => + const downloads = await screen.findAllByRole("link", { name: "Download" }); + expect(downloads.some((link) => link.getAttribute("href")?.includes(outputUrl), )).toBe(true);