Merge pull request #25 from LofiSu/feat/citations

feat(citations): add shared citation components and optimize code
This commit is contained in:
LofiSu
2026-02-07 12:13:32 +08:00
committed by GitHub
15 changed files with 583 additions and 504 deletions

View File

@@ -249,35 +249,30 @@ You have access to skills that provide optimized workflows for specific tasks. E
</response_style>
<citations_format>
**FORMAT** - After web_search, ALWAYS include citations in your output:
**For chat responses:**
Your visible response MUST start with citations block, then content with inline links:
<citations>
{{"id": "cite-1", "title": "Page Title", "url": "https://example.com/page", "snippet": "Brief description"}}
</citations>
Content with inline links...
After web_search, ALWAYS include citations in your output:
**For files (write_file):**
File content MUST start with citations block, then content with inline links:
<citations>
{{"id": "cite-1", "title": "Page Title", "url": "https://example.com/page", "snippet": "Brief description"}}
</citations>
# Document Title
Content with inline [Source Name](full_url) links...
1. Start with a `<citations>` block in JSONL format listing all sources
2. In content, use FULL markdown link format: [Short Title](full_url)
**RULES:**
- `<citations>` block MUST be FIRST (in both chat response AND file content)
- Write full content naturally, add [Source Name](full_url) at end of sentence/paragraph
- NEVER use "According to [Source]" format - write content first, then add citation link at end
- Example: "AI agents will transform digital work ([Microsoft](url))" NOT "According to [Microsoft](url), AI agents will..."
**CRITICAL - Citation Link Format:**
- CORRECT: `[TechCrunch](https://techcrunch.com/ai-trends)` - full markdown link with URL
- WRONG: `[arXiv:2502.19166]` - missing URL, will NOT render as link
- WRONG: `[Source]` - missing URL, will NOT render as link
**Rules:**
- Every citation MUST be a complete markdown link with URL: `[Title](https://...)`
- Write content naturally, add citation link at end of sentence/paragraph
- NEVER use bare brackets like `[arXiv:xxx]` or `[Source]` without URL
**Example:**
<citations>
{{"id": "cite-1", "title": "AI Trends 2026", "url": "https://techcrunch.com/ai-trends", "snippet": "Tech industry predictions"}}
{{"id": "cite-2", "title": "OpenAI Research", "url": "https://openai.com/research", "snippet": "Latest AI research developments"}}
</citations>
The key AI trends for 2026 include enhanced reasoning capabilities, multimodal integration, and improved efficiency [TechCrunch](https://techcrunch.com/ai-trends).
The key AI trends for 2026 include enhanced reasoning capabilities and multimodal integration [TechCrunch](https://techcrunch.com/ai-trends). Recent breakthroughs in language models have also accelerated progress [OpenAI](https://openai.com/research).
</citations_format>
<critical_reminders>
- **Clarification First**: ALWAYS clarify unclear/missing/ambiguous requirements BEFORE starting work - never assume or guess
{subagent_reminder}- Skill First: Always load the relevant skill before starting **complex** tasks.

View File

@@ -1,5 +1,6 @@
import mimetypes
import os
import re
import zipfile
from pathlib import Path
from urllib.parse import quote
@@ -61,6 +62,68 @@ def is_text_file_by_content(path: Path, sample_size: int = 8192) -> bool:
return False
def remove_citations_block(content: str) -> str:
"""Remove ALL citations from markdown content.
Removes:
- <citations>...</citations> blocks (complete and incomplete)
- [cite-N] references
- Citation markdown links that were converted from [cite-N]
This is used for downloads to provide clean markdown without any citation references.
Args:
content: The markdown content that may contain citations blocks.
Returns:
Clean content with all citations completely removed.
"""
if not content:
return content
result = content
# Step 1: Parse and extract citation URLs before removing blocks
citation_urls = set()
citations_pattern = r'<citations>([\s\S]*?)</citations>'
for match in re.finditer(citations_pattern, content):
citations_block = match.group(1)
# Extract URLs from JSON lines
import json
for line in citations_block.split('\n'):
line = line.strip()
if line.startswith('{'):
try:
citation = json.loads(line)
if 'url' in citation:
citation_urls.add(citation['url'])
except (json.JSONDecodeError, ValueError):
pass
# Step 2: Remove complete citations blocks
result = re.sub(r'<citations>[\s\S]*?</citations>', '', result)
# Step 3: Remove incomplete citations blocks (at end of content during streaming)
if "<citations>" in result:
result = re.sub(r'<citations>[\s\S]*$', '', result)
# Step 4: Remove all [cite-N] references
result = re.sub(r'\[cite-\d+\]', '', result)
# Step 5: Remove markdown links that point to citation URLs
# Pattern: [text](url)
if citation_urls:
for url in citation_urls:
# Escape special regex characters in URL
escaped_url = re.escape(url)
result = re.sub(rf'\[[^\]]+\]\({escaped_url}\)', '', result)
# Step 6: Clean up extra whitespace and newlines
result = re.sub(r'\n{3,}', '\n\n', result) # Replace 3+ newlines with 2
return result.strip()
def _extract_file_from_skill_archive(zip_path: Path, internal_path: str) -> bytes | None:
"""Extract a file from a .skill ZIP archive.
@@ -175,9 +238,24 @@ async def get_artifact(thread_id: str, path: str, request: Request) -> FileRespo
# Encode filename for Content-Disposition header (RFC 5987)
encoded_filename = quote(actual_path.name)
# Check if this is a markdown file that might contain citations
is_markdown = mime_type == "text/markdown" or actual_path.suffix.lower() in [".md", ".markdown"]
# if `download` query parameter is true, return the file as a download
if request.query_params.get("download"):
# For markdown files, remove citations block before download
if is_markdown:
content = actual_path.read_text()
clean_content = remove_citations_block(content)
return Response(
content=clean_content.encode("utf-8"),
media_type="text/markdown",
headers={
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}",
"Content-Type": "text/markdown; charset=utf-8"
}
)
return FileResponse(path=actual_path, filename=actual_path.name, media_type=mime_type, headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"})
if mime_type and mime_type == "text/html":

View File

@@ -13,7 +13,7 @@ import {
HoverCardTrigger,
} from "@/components/ui/hover-card";
import { cn } from "@/lib/utils";
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
import { ExternalLinkIcon, ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
import {
type ComponentProps,
createContext,
@@ -22,6 +22,10 @@ import {
useEffect,
useState,
} from "react";
import type { Citation } from "@/core/citations";
import { extractDomainFromUrl } from "@/core/citations";
import { Shimmer } from "./shimmer";
import { useI18n } from "@/core/i18n/hooks";
export type InlineCitationProps = ComponentProps<"span">;
@@ -285,3 +289,114 @@ export const InlineCitationQuote = ({
{children}
</blockquote>
);
/**
* Shared CitationLink component that renders a citation as a hover card badge
* Used across message-list-item, artifact-file-detail, and message-group
*
* When citation is provided, displays title and snippet from the citation.
* When citation is omitted, falls back to displaying the domain name extracted from href.
*/
export type CitationLinkProps = {
citation?: Citation;
href: string;
children: React.ReactNode;
};
export const CitationLink = ({
citation,
href,
children,
}: CitationLinkProps) => {
const domain = extractDomainFromUrl(href);
// Priority: citation.title > children (if meaningful) > domain
// - citation.title: from parsed <citations> block, most accurate
// - children: from markdown link text [Text](url), used when no citation data
// - domain: fallback when both above are unavailable
// Skip children if it's a generic placeholder like "Source"
const childrenText = typeof children === "string" ? children : null;
const isGenericText = childrenText === "Source" || childrenText === "来源";
const displayText = citation?.title || (!isGenericText && childrenText) || domain;
return (
<InlineCitationCard>
<HoverCardTrigger asChild>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center"
onClick={(e) => e.stopPropagation()}
>
<Badge
variant="secondary"
className="hover:bg-secondary/80 mx-0.5 cursor-pointer gap-1 rounded-full px-2 py-0.5 text-xs font-normal"
>
{displayText}
<ExternalLinkIcon className="size-3" />
</Badge>
</a>
</HoverCardTrigger>
<InlineCitationCardBody>
<div className="p-3">
<InlineCitationSource
title={citation?.title || domain}
url={href}
description={citation?.snippet}
/>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
>
Visit source
<ExternalLinkIcon className="size-3" />
</a>
</div>
</InlineCitationCardBody>
</InlineCitationCard>
);
};
/**
* Shared CitationsLoadingIndicator component
* Used across message-list-item and message-group to show loading citations
*/
export type CitationsLoadingIndicatorProps = {
citations: Citation[];
className?: string;
};
export const CitationsLoadingIndicator = ({
citations,
className,
}: CitationsLoadingIndicatorProps) => {
const { t } = useI18n();
return (
<div className={cn("flex flex-col gap-2", className)}>
<Shimmer duration={2.5} className="text-sm">
{citations.length > 0
? t.citations.loadingCitationsWithCount(citations.length)
: t.citations.loadingCitations}
</Shimmer>
{citations.length > 0 && (
<div className="flex flex-wrap gap-2">
{citations.map((citation) => (
<Badge
key={citation.id}
variant="secondary"
className="animate-fade-in gap-1 rounded-full px-2.5 py-1 text-xs font-normal"
>
<Shimmer duration={2} as="span">
{citation.title || extractDomainFromUrl(citation.url)}
</Shimmer>
</Badge>
))}
</div>
)}
</div>
);
};

View File

@@ -2,7 +2,6 @@ import {
Code2Icon,
CopyIcon,
DownloadIcon,
ExternalLinkIcon,
EyeIcon,
LoaderIcon,
PackageIcon,
@@ -22,13 +21,7 @@ import {
ArtifactHeader,
ArtifactTitle,
} from "@/components/ai-elements/artifact";
import {
InlineCitationCard,
InlineCitationCardBody,
InlineCitationSource,
} from "@/components/ai-elements/inline-citation";
import { Badge } from "@/components/ui/badge";
import { HoverCardTrigger } from "@/components/ui/hover-card";
import { CitationLink } from "@/components/ai-elements/inline-citation";
import { Select, SelectItem } from "@/components/ui/select";
import {
SelectContent,
@@ -42,9 +35,8 @@ import { useArtifactContent } from "@/core/artifacts/hooks";
import { urlOfArtifact } from "@/core/artifacts/utils";
import {
buildCitationMap,
extractDomainFromUrl,
parseCitations,
type Citation,
removeAllCitations,
} from "@/core/citations";
import { useI18n } from "@/core/i18n/hooks";
import { installSkill } from "@/core/skills/api";
@@ -110,6 +102,14 @@ export function ArtifactFileDetail({
return content;
}, [content, language]);
// Get content without ANY citations for copy/download
const contentWithoutCitations = useMemo(() => {
if (language === "markdown" && content) {
return removeAllCitations(content);
}
return content;
}, [content, language]);
const [viewMode, setViewMode] = useState<"code" | "preview">("code");
const [isInstalling, setIsInstalling] = useState(false);
@@ -220,7 +220,7 @@ export function ArtifactFileDetail({
disabled={!content}
onClick={async () => {
try {
await navigator.clipboard.writeText(content ?? "");
await navigator.clipboard.writeText(contentWithoutCitations ?? "");
toast.success(t.clipboard.copiedToClipboard);
} catch (error) {
toast.error("Failed to copy to clipboard");
@@ -293,7 +293,6 @@ export function ArtifactFilePreview({
const parsed = parseCitations(content ?? "");
const map = buildCitationMap(parsed.citations);
return {
citations: parsed.citations,
cleanContent: parsed.cleanContent,
citationMap: map,
};
@@ -314,29 +313,24 @@ export function ArtifactFilePreview({
return <span>{children}</span>;
}
// Check if it's a citation link
// Only render as CitationLink badge if it's a citation (in citationMap)
const citation = citationMap.get(href);
if (citation) {
return (
<ArtifactCitationLink citation={citation} href={href}>
<CitationLink citation={citation} href={href}>
{children}
</ArtifactCitationLink>
</CitationLink>
);
}
// Check if it's an external link (http/https)
const isExternalLink =
href.startsWith("http://") || href.startsWith("https://");
if (isExternalLink) {
return (
<ExternalLinkBadge href={href}>{children}</ExternalLinkBadge>
);
}
// Internal/anchor link
// All other links (including project URLs) render as plain links
return (
<a href={href} className="text-primary hover:underline">
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline underline-offset-2 hover:no-underline"
>
{children}
</a>
);
@@ -359,105 +353,3 @@ export function ArtifactFilePreview({
return null;
}
/**
* Citation link component for artifact preview (with full citation data)
*/
function ArtifactCitationLink({
citation,
href,
children,
}: {
citation: Citation;
href: string;
children: React.ReactNode;
}) {
const domain = extractDomainFromUrl(href);
return (
<InlineCitationCard>
<HoverCardTrigger asChild>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center"
onClick={(e) => e.stopPropagation()}
>
<Badge
variant="secondary"
className="hover:bg-secondary/80 mx-0.5 cursor-pointer gap-1 rounded-full px-2 py-0.5 text-xs font-normal"
>
{children ?? domain}
<ExternalLinkIcon className="size-3" />
</Badge>
</a>
</HoverCardTrigger>
<InlineCitationCardBody>
<div className="p-3">
<InlineCitationSource
title={citation.title}
url={href}
description={citation.snippet}
/>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
>
Visit source
<ExternalLinkIcon className="size-3" />
</a>
</div>
</InlineCitationCardBody>
</InlineCitationCard>
);
}
/**
* External link badge component for artifact preview
*/
function ExternalLinkBadge({
href,
children,
}: {
href: string;
children: React.ReactNode;
}) {
const domain = extractDomainFromUrl(href);
return (
<InlineCitationCard>
<HoverCardTrigger asChild>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center"
>
<Badge
variant="secondary"
className="hover:bg-secondary/80 mx-0.5 cursor-pointer gap-1 rounded-full px-2 py-0.5 text-xs font-normal"
>
{children ?? domain}
<ExternalLinkIcon className="size-3" />
</Badge>
</a>
</HoverCardTrigger>
<InlineCitationCardBody>
<div className="p-3">
<InlineCitationSource title={domain} url={href} />
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
>
Visit source
<ExternalLinkIcon className="size-3" />
</a>
</div>
</InlineCitationCardBody>
</InlineCitationCard>
);
}

View File

@@ -22,14 +22,17 @@ import {
ChainOfThoughtStep,
} from "@/components/ai-elements/chain-of-thought";
import { CodeBlock } from "@/components/ai-elements/code-block";
import { CitationsLoadingIndicator } from "@/components/ai-elements/inline-citation";
import { MessageResponse } from "@/components/ai-elements/message";
import { Button } from "@/components/ui/button";
import { parseCitations } from "@/core/citations";
import { useI18n } from "@/core/i18n/hooks";
import {
extractReasoningContentFromMessage,
findToolCallResult,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { streamdownPlugins } from "@/core/streamdown";
import { extractTitleFromMarkdown } from "@/core/utils/markdown";
import { env } from "@/env";
import { cn } from "@/lib/utils";
@@ -38,6 +41,8 @@ import { useArtifacts } from "../artifacts";
import { FlipDisplay } from "../flip-display";
import { Tooltip } from "../tooltip";
import { useThread } from "./context";
export function MessageGroup({
className,
messages,
@@ -115,8 +120,8 @@ export function MessageGroup({
<ChainOfThoughtStep
key={step.id}
label={
<MessageResponse rehypePlugins={rehypePlugins}>
{step.reasoning ?? ""}
<MessageResponse remarkPlugins={streamdownPlugins.remarkPlugins} rehypePlugins={rehypePlugins}>
{parseCitations(step.reasoning ?? "").cleanContent}
</MessageResponse>
}
></ChainOfThoughtStep>
@@ -165,8 +170,8 @@ export function MessageGroup({
<ChainOfThoughtStep
key={lastReasoningStep.id}
label={
<MessageResponse rehypePlugins={rehypePlugins}>
{lastReasoningStep.reasoning ?? ""}
<MessageResponse remarkPlugins={streamdownPlugins.remarkPlugins} rehypePlugins={rehypePlugins}>
{parseCitations(lastReasoningStep.reasoning ?? "").cleanContent}
</MessageResponse>
}
></ChainOfThoughtStep>
@@ -198,6 +203,13 @@ function ToolCall({
const { t } = useI18n();
const { setOpen, autoOpen, autoSelect, selectedArtifact, select } =
useArtifacts();
const { thread } = useThread();
const threadIsLoading = thread.isLoading;
// Move useMemo to top level to comply with React Hooks rules
const fileContent = typeof args.content === "string" ? args.content : "";
const { citations } = useMemo(() => parseCitations(fileContent), [fileContent]);
if (name === "web_search") {
let label: React.ReactNode = t.toolCalls.searchForRelatedInfo;
if (typeof args.query === "string") {
@@ -355,29 +367,42 @@ function ToolCall({
setOpen(true);
}, 100);
}
// Check if this is a markdown file with citations
const isMarkdown = path?.toLowerCase().endsWith(".md") || path?.toLowerCase().endsWith(".markdown");
const hasCitationsBlock = fileContent.includes("<citations>");
const showCitationsLoading = isMarkdown && threadIsLoading && hasCitationsBlock && isLast;
return (
<ChainOfThoughtStep
key={id}
className="cursor-pointer"
label={description}
icon={NotebookPenIcon}
onClick={() => {
select(
new URL(
`write-file:${path}?message_id=${messageId}&tool_call_id=${id}`,
).toString(),
);
setOpen(true);
}}
>
{path && (
<Tooltip content={t.toolCalls.clickToViewContent}>
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
</Tooltip>
<>
<ChainOfThoughtStep
key={id}
className="cursor-pointer"
label={description}
icon={NotebookPenIcon}
onClick={() => {
select(
new URL(
`write-file:${path}?message_id=${messageId}&tool_call_id=${id}`,
).toString(),
);
setOpen(true);
}}
>
{path && (
<Tooltip content={t.toolCalls.clickToViewContent}>
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
</Tooltip>
)}
</ChainOfThoughtStep>
{showCitationsLoading && (
<div className="ml-8 mt-2">
<CitationsLoadingIndicator citations={citations} />
</div>
)}
</ChainOfThoughtStep>
</>
);
} else if (name === "bash") {
const description: string | undefined = (args as { description: string })

View File

@@ -1,12 +1,12 @@
import type { Message } from "@langchain/langgraph-sdk";
import { ExternalLinkIcon, FileIcon } from "lucide-react";
import { FileIcon } from "lucide-react";
import { useParams } from "next/navigation";
import { memo, useMemo } from "react";
import rehypeKatex from "rehype-katex";
import {
InlineCitationCard,
InlineCitationCardBody,
InlineCitationSource,
CitationLink,
CitationsLoadingIndicator,
} from "@/components/ai-elements/inline-citation";
import {
Message as AIElementMessage,
@@ -15,13 +15,13 @@ import {
MessageToolbar,
} from "@/components/ai-elements/message";
import { Badge } from "@/components/ui/badge";
import { HoverCardTrigger } from "@/components/ui/hover-card";
import { resolveArtifactURL } from "@/core/artifacts/utils";
import {
type Citation,
buildCitationMap,
extractDomainFromUrl,
isCitationsBlockIncomplete,
parseCitations,
removeAllCitations,
} from "@/core/citations";
import {
extractContentFromMessage,
@@ -29,7 +29,8 @@ import {
parseUploadedFiles,
type UploadedFile,
} from "@/core/messages/utils";
import { streamdownPlugins } from "@/core/streamdown";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { humanMessagePlugins, streamdownPlugins } from "@/core/streamdown";
import { cn } from "@/lib/utils";
import { CopyButton } from "../copy-button";
@@ -43,30 +44,30 @@ export function MessageListItem({
message: Message;
isLoading?: boolean;
}) {
const isHuman = message.type === "human";
return (
<AIElementMessage
className={cn("group/conversation-message relative w-full", className)}
from={message.type === "human" ? "user" : "assistant"}
from={isHuman ? "user" : "assistant"}
>
<MessageContent
className={message.type === "human" ? "w-fit" : "w-full"}
className={isHuman ? "w-fit" : "w-full"}
message={message}
isLoading={isLoading}
/>
<MessageToolbar
className={cn(
message.type === "human" && "justify-end",
message.type === "human" ? "-bottom-9" : "-bottom-8",
isHuman ? "justify-end -bottom-9" : "-bottom-8",
"absolute right-0 left-0 z-20 opacity-0 transition-opacity delay-200 duration-300 group-hover/conversation-message:opacity-100",
)}
>
<div className="flex gap-1">
<CopyButton
clipboardData={
extractContentFromMessage(message)
? extractContentFromMessage(message)
: (extractReasoningContentFromMessage(message) ?? "")
}
clipboardData={removeAllCitations(
extractContentFromMessage(message) ??
extractReasoningContentFromMessage(message) ??
""
)}
/>
</div>
</MessageToolbar>
@@ -74,6 +75,76 @@ export function MessageListItem({
);
}
/**
* Custom link component that handles citations and external links
* Only links in citationMap are rendered as CitationLink badges
* Other links (project URLs, regular links) are rendered as plain links
*/
function MessageLink({
href,
children,
citationMap,
isHuman,
}: React.AnchorHTMLAttributes<HTMLAnchorElement> & {
citationMap: Map<string, Citation>;
isHuman: boolean;
}) {
if (!href) return <span>{children}</span>;
const citation = citationMap.get(href);
// Only render as CitationLink badge if it's a citation (in citationMap) and not human message
if (citation && !isHuman) {
return (
<CitationLink citation={citation} href={href}>
{children}
</CitationLink>
);
}
// All other links render as plain links
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline underline-offset-2 hover:no-underline"
>
{children}
</a>
);
}
/**
* Custom image component that handles artifact URLs
*/
function MessageImage({
src,
alt,
threadId,
maxWidth = "90%",
...props
}: React.ImgHTMLAttributes<HTMLImageElement> & {
threadId: string;
maxWidth?: string;
}) {
if (!src) return null;
const imgClassName = cn("overflow-hidden rounded-lg", `max-w-[${maxWidth}]`);
if (typeof src !== "string") {
return <img className={imgClassName} src={src} alt={alt} {...props} />;
}
const url = src.startsWith("/mnt/") ? resolveArtifactURL(src, threadId) : src;
return (
<a href={url} target="_blank" rel="noopener noreferrer">
<img className={imgClassName} src={url} alt={alt} {...props} />
</a>
);
}
function MessageContent_({
className,
message,
@@ -83,295 +154,164 @@ function MessageContent_({
message: Message;
isLoading?: boolean;
}) {
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
const isHuman = message.type === "human";
// Extract and parse citations and uploaded files from message content
const { citations, cleanContent, uploadedFiles } = useMemo(() => {
const reasoningContent = extractReasoningContentFromMessage(message);
const rawContent = extractContentFromMessage(message);
if (!isLoading && reasoningContent && !rawContent) {
return {
citations: [],
cleanContent: reasoningContent,
uploadedFiles: [],
};
}
// For human messages, first parse uploaded files
if (isHuman && rawContent) {
const { files, cleanContent: contentWithoutFiles } =
parseUploadedFiles(rawContent);
const { citations, cleanContent: finalContent } =
parseCitations(contentWithoutFiles);
return { citations, cleanContent: finalContent, uploadedFiles: files };
}
const { citations, cleanContent } = parseCitations(rawContent ?? "");
return { citations, cleanContent, uploadedFiles: [] };
}, [isLoading, message, isHuman]);
// Build citation map for quick URL lookup
const citationMap = useMemo(() => buildCitationMap(citations), [citations]);
const { thread_id } = useParams<{ thread_id: string }>();
// For human messages with uploaded files, render files outside the bubble
// Extract and parse citations and uploaded files from message content
const { citations, cleanContent, uploadedFiles, isLoadingCitations } =
useMemo(() => {
const reasoningContent = extractReasoningContentFromMessage(message);
const rawContent = extractContentFromMessage(message);
// When only reasoning content exists (no main content), also parse citations
if (!isLoading && reasoningContent && !rawContent) {
const { citations, cleanContent } = parseCitations(reasoningContent);
return {
citations,
cleanContent,
uploadedFiles: [],
isLoadingCitations: false,
};
}
// For human messages, parse uploaded files first
if (isHuman && rawContent) {
const { files, cleanContent: contentWithoutFiles } =
parseUploadedFiles(rawContent);
const { citations, cleanContent: finalContent } =
parseCitations(contentWithoutFiles);
return {
citations,
cleanContent: finalContent,
uploadedFiles: files,
isLoadingCitations: false,
};
}
const { citations, cleanContent } = parseCitations(rawContent ?? "");
const isLoadingCitations =
isLoading && isCitationsBlockIncomplete(rawContent ?? "");
return { citations, cleanContent, uploadedFiles: [], isLoadingCitations };
}, [isLoading, message, isHuman]);
const citationMap = useMemo(() => buildCitationMap(citations), [citations]);
// Shared markdown components
const markdownComponents = useMemo(() => ({
a: (props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
<MessageLink {...props} citationMap={citationMap} isHuman={isHuman} />
),
img: (props: React.ImgHTMLAttributes<HTMLImageElement>) => (
<MessageImage {...props} threadId={thread_id} maxWidth={isHuman ? "full" : "90%"} />
),
}), [citationMap, thread_id, isHuman]);
// Render message response
// Human messages use humanMessagePlugins (no autolink) to prevent URL bleeding into adjacent text
const messageResponse = cleanContent ? (
<AIElementMessageResponse
remarkPlugins={isHuman ? humanMessagePlugins.remarkPlugins : streamdownPlugins.remarkPlugins}
rehypePlugins={isHuman ? humanMessagePlugins.rehypePlugins : [...rehypePlugins, [rehypeKatex, { output: "html" }]]}
components={markdownComponents}
>
{cleanContent}
</AIElementMessageResponse>
) : null;
// Uploaded files list
const filesList = uploadedFiles.length > 0 && thread_id ? (
<UploadedFilesList files={uploadedFiles} threadId={thread_id} />
) : null;
// Citations loading indicator
const citationsLoadingIndicator = isLoadingCitations ? (
<CitationsLoadingIndicator citations={citations} className="my-3" />
) : null;
// Human messages with uploaded files: render outside bubble
if (isHuman && uploadedFiles.length > 0) {
return (
<div className={cn("ml-auto flex flex-col gap-2", className)}>
{/* Uploaded files outside the message bubble */}
<UploadedFilesList files={uploadedFiles} threadId={thread_id} />
{/* Message content inside the bubble (only if there's text) */}
{cleanContent && (
{filesList}
{messageResponse && (
<AIElementMessageContent className="w-fit">
<AIElementMessageResponse
{...streamdownPlugins}
components={{
a: ({
href,
children,
}: React.AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (!href) {
return <span>{children}</span>;
}
// Check if this link matches a citation
const citation = citationMap.get(href);
if (citation) {
return (
<CitationLink citation={citation} href={href}>
{children}
</CitationLink>
);
}
// Regular external link
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline underline-offset-2 hover:no-underline"
>
{children}
</a>
);
},
img: ({
src,
alt,
}: React.ImgHTMLAttributes<HTMLImageElement>) => {
if (!src) return null;
if (typeof src !== "string") {
return (
<img
className="max-w-full overflow-hidden rounded-lg"
src={src}
alt={alt}
/>
);
}
let url = src;
if (src.startsWith("/mnt/")) {
url = resolveArtifactURL(src, thread_id);
}
return (
<a href={url} target="_blank" rel="noopener noreferrer">
<img
className="max-w-full overflow-hidden rounded-lg"
src={url}
alt={alt}
/>
</a>
);
},
}}
>
{cleanContent}
</AIElementMessageResponse>
{messageResponse}
</AIElementMessageContent>
)}
</div>
);
}
// Default rendering for non-human messages or human messages without files
// Default rendering
return (
<AIElementMessageContent className={className}>
{/* Uploaded files for human messages - show first */}
{uploadedFiles.length > 0 && thread_id && (
<UploadedFilesList files={uploadedFiles} threadId={thread_id} />
)}
{/* Message content - always show if present */}
{cleanContent && (
<AIElementMessageResponse
{...streamdownPlugins}
components={{
a: ({
href,
children,
}: React.AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (!href) {
return <span>{children}</span>;
}
// Check if this link matches a citation
const citation = citationMap.get(href);
if (citation) {
return (
<CitationLink citation={citation} href={href}>
{children}
</CitationLink>
);
}
// Regular external link
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline underline-offset-2 hover:no-underline"
>
{children}
</a>
);
},
img: ({ src, alt }: React.ImgHTMLAttributes<HTMLImageElement>) => {
if (!src) return null;
if (typeof src !== "string") {
return (
<img
className="max-w-[90%] overflow-hidden rounded-lg"
src={src}
alt={alt}
/>
);
}
let url = src;
if (src.startsWith("/mnt/")) {
url = resolveArtifactURL(src, thread_id);
}
return (
<a href={url} target="_blank" rel="noopener noreferrer">
<img
className="max-w-[90%] overflow-hidden rounded-lg"
src={url}
alt={alt}
/>
</a>
);
},
}}
>
{cleanContent}
</AIElementMessageResponse>
)}
{filesList}
{messageResponse}
{citationsLoadingIndicator}
</AIElementMessageContent>
);
}
/**
* Get file type label from filename extension
* Get file extension and check helpers
*/
const getFileExt = (filename: string) => filename.split(".").pop()?.toLowerCase() ?? "";
const FILE_TYPE_MAP: Record<string, string> = {
json: "JSON", csv: "CSV", txt: "TXT", md: "Markdown",
py: "Python", js: "JavaScript", ts: "TypeScript", tsx: "TSX", jsx: "JSX",
html: "HTML", css: "CSS", xml: "XML", yaml: "YAML", yml: "YAML",
pdf: "PDF", png: "PNG", jpg: "JPG", jpeg: "JPEG", gif: "GIF",
svg: "SVG", zip: "ZIP", tar: "TAR", gz: "GZ",
};
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"];
function getFileTypeLabel(filename: string): string {
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
const typeMap: Record<string, string> = {
json: "JSON",
csv: "CSV",
txt: "TXT",
md: "Markdown",
py: "Python",
js: "JavaScript",
ts: "TypeScript",
tsx: "TSX",
jsx: "JSX",
html: "HTML",
css: "CSS",
xml: "XML",
yaml: "YAML",
yml: "YAML",
pdf: "PDF",
png: "PNG",
jpg: "JPG",
jpeg: "JPEG",
gif: "GIF",
svg: "SVG",
zip: "ZIP",
tar: "TAR",
gz: "GZ",
};
return (typeMap[ext] ?? ext.toUpperCase()) || "FILE";
const ext = getFileExt(filename);
return FILE_TYPE_MAP[ext] ?? (ext.toUpperCase() || "FILE");
}
/**
* Check if a file is an image based on extension
*/
function isImageFile(filename: string): boolean {
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
return ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"].includes(ext);
return IMAGE_EXTENSIONS.includes(getFileExt(filename));
}
/**
* Uploaded files list component that displays files as cards or image thumbnails (Claude-style)
* Uploaded files list component
*/
function UploadedFilesList({
files,
threadId,
}: {
files: UploadedFile[];
threadId: string;
}) {
function UploadedFilesList({ files, threadId }: { files: UploadedFile[]; threadId: string }) {
if (files.length === 0) return null;
return (
<div className="mb-2 flex flex-wrap justify-end gap-2">
{files.map((file, index) => (
<UploadedFileCard
key={`${file.path}-${index}`}
file={file}
threadId={threadId}
/>
<UploadedFileCard key={`${file.path}-${index}`} file={file} threadId={threadId} />
))}
</div>
);
}
/**
* Single uploaded file card component (Claude-style)
* Shows image thumbnail for image files, file card for others
* Single uploaded file card component
*/
function UploadedFileCard({
file,
threadId,
}: {
file: UploadedFile;
threadId: string;
}) {
const typeLabel = getFileTypeLabel(file.filename);
function UploadedFileCard({ file, threadId }: { file: UploadedFile; threadId: string }) {
if (!threadId) return null;
const isImage = isImageFile(file.filename);
const fileUrl = resolveArtifactURL(file.path, threadId);
// Don't render if threadId is invalid
if (!threadId) {
return null;
}
// Build URL - browser will handle encoding automatically
const imageUrl = resolveArtifactURL(file.path, threadId);
// For image files, show thumbnail
if (isImage) {
return (
<a
href={imageUrl}
href={fileUrl}
target="_blank"
rel="noopener noreferrer"
className="group border-border/40 relative block overflow-hidden rounded-lg border"
>
<img
src={imageUrl}
src={fileUrl}
alt={file.filename}
className="h-32 w-auto max-w-[240px] object-cover transition-transform group-hover:scale-105"
/>
@@ -379,24 +319,17 @@ function UploadedFileCard({
);
}
// For non-image files, show file card
return (
<div className="bg-background border-border/40 flex max-w-[200px] min-w-[120px] flex-col gap-1 rounded-lg border p-3 shadow-sm">
<div className="flex items-start gap-2">
<FileIcon className="text-muted-foreground mt-0.5 size-4 shrink-0" />
<span
className="text-foreground truncate text-sm font-medium"
title={file.filename}
>
<span className="text-foreground truncate text-sm font-medium" title={file.filename}>
{file.filename}
</span>
</div>
<div className="flex items-center justify-between gap-2">
<Badge
variant="secondary"
className="rounded px-1.5 py-0.5 text-[10px] font-normal"
>
{typeLabel}
<Badge variant="secondary" className="rounded px-1.5 py-0.5 text-[10px] font-normal">
{getFileTypeLabel(file.filename)}
</Badge>
<span className="text-muted-foreground text-[10px]">{file.size}</span>
</div>
@@ -404,58 +337,4 @@ function UploadedFileCard({
);
}
/**
* Citation link component that renders as a hover card badge
*/
function CitationLink({
citation,
href,
children,
}: {
citation: Citation;
href: string;
children: React.ReactNode;
}) {
const domain = extractDomainFromUrl(href);
return (
<InlineCitationCard>
<HoverCardTrigger asChild>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center"
onClick={(e) => e.stopPropagation()}
>
<Badge
variant="secondary"
className="hover:bg-secondary/80 mx-0.5 cursor-pointer gap-1 rounded-full px-2 py-0.5 text-xs font-normal"
>
{children ?? domain}
<ExternalLinkIcon className="size-3" />
</Badge>
</a>
</HoverCardTrigger>
<InlineCitationCardBody>
<div className="p-3">
<InlineCitationSource
title={citation.title}
url={href}
description={citation.snippet}
/>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
>
Visit source
<ExternalLinkIcon className="size-3" />
</a>
</div>
</InlineCitationCardBody>
</InlineCitationCard>
);
}
const MessageContent = memo(MessageContent_);

View File

@@ -37,8 +37,6 @@ function memoryToMarkdown(
) {
const parts: string[] = [];
console.info(memory);
parts.push(`## ${t.settings.memory.markdown.overview}`);
parts.push(
`- **${t.common.lastUpdated}**: \`${formatTimeAgo(memory.lastUpdated)}\``,

View File

@@ -3,6 +3,7 @@ export {
buildCitationMap,
extractDomainFromUrl,
isCitationsBlockIncomplete,
removeAllCitations,
} from "./utils";
export type { Citation, ParseCitationsResult } from "./utils";

View File

@@ -76,6 +76,29 @@ export function parseCitations(content: string): ParseCitationsResult {
cleanContent = cleanContent.replace(/<citations>[\s\S]*$/g, "").trim();
}
// Convert [cite-N] references to markdown links
// Example: [cite-1] -> [Title](url)
if (citations.length > 0) {
// Build a map from citation id to citation object
const idMap = new Map<string, Citation>();
for (const citation of citations) {
idMap.set(citation.id, citation);
}
// Replace all [cite-N] patterns with markdown links
cleanContent = cleanContent.replace(/\[cite-(\d+)\]/g, (match, num) => {
const citeId = `cite-${num}`;
const citation = idMap.get(citeId);
if (citation) {
// Use title if available, otherwise use domain
const linkText = citation.title || extractDomainFromUrl(citation.url);
return `[${linkText}](${citation.url})`;
}
// If citation not found, keep the original text
return match;
});
}
return { citations, cleanContent };
}
@@ -129,3 +152,51 @@ export function isCitationsBlockIncomplete(content: string): boolean {
return hasOpenTag && !hasCloseTag;
}
/**
* Remove ALL citations from content, including:
* - <citations> blocks
* - [cite-N] references
* - Citation markdown links that were converted from [cite-N]
*
* This is used for copy/download operations where we want clean content without any references.
*
* @param content - The raw content that may contain citations
* @returns Content with all citations completely removed
*/
export function removeAllCitations(content: string): string {
if (!content) {
return content;
}
let result = content;
// Step 1: Remove all <citations> blocks (complete and incomplete)
result = result.replace(/<citations>[\s\S]*?<\/citations>/g, "");
result = result.replace(/<citations>[\s\S]*$/g, "");
// Step 2: Remove all [cite-N] references
result = result.replace(/\[cite-\d+\]/g, "");
// Step 3: Parse to find citation URLs and remove those specific links
const parsed = parseCitations(content);
const citationUrls = new Set(parsed.citations.map(c => c.url));
// Remove markdown links that point to citation URLs
// Pattern: [text](url)
result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
// If this URL is a citation, remove the entire link
if (citationUrls.has(url)) {
return "";
}
// Keep non-citation links
return match;
});
// Step 4: Clean up extra whitespace and newlines
result = result
.replace(/\n{3,}/g, "\n\n") // Replace 3+ newlines with 2
.trim();
return result;
}

View File

@@ -167,6 +167,13 @@ export const enUS: Translations = {
startConversation: "Start a conversation to see messages here",
},
// Citations
citations: {
loadingCitations: "Organizing citations...",
loadingCitationsWithCount: (count: number) =>
`Organizing ${count} citation${count === 1 ? "" : "s"}...`,
},
// Chats
chats: {
searchChats: "Search chats",

View File

@@ -115,6 +115,12 @@ export interface Translations {
startConversation: string;
};
// Citations
citations: {
loadingCitations: string;
loadingCitationsWithCount: (count: number) => string;
};
// Chats
chats: {
searchChats: string;

View File

@@ -163,6 +163,12 @@ export const zhCN: Translations = {
startConversation: "开始新的对话以查看消息",
},
// Citations
citations: {
loadingCitations: "正在整理引用...",
loadingCitationsWithCount: (count: number) => `正在整理 ${count} 个引用...`,
},
// Chats
chats: {
searchChats: "搜索对话",

View File

@@ -78,7 +78,6 @@ export function useNotification(): UseNotificationReturn {
// Optional: Add event listeners
notification.onclick = () => {
console.log("Notification clicked");
window.focus();
notification.close();
};

View File

@@ -5,7 +5,20 @@ import type { StreamdownProps } from "streamdown";
export const streamdownPlugins = {
remarkPlugins: [
[remarkGfm, [remarkMath, { singleDollarTextMath: true }]],
remarkGfm,
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],
] as StreamdownProps["rehypePlugins"],
};
// Plugins for human messages - no autolink to prevent URL bleeding into adjacent text
export const humanMessagePlugins = {
remarkPlugins: [
// Use remark-gfm without autolink literals by not including it
// Only include math support for human messages
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],

View File

@@ -207,12 +207,6 @@ export function useRenameThread() {
});
},
onSuccess(_, { threadId, title }) {
queryClient.setQueryData(
["thread", "state", threadId],
(oldData: Array<AgentThread>) => {
console.info("oldData", oldData);
},
);
queryClient.setQueriesData(
{
queryKey: ["threads", "search"],