Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(search): drop citations with empty url to avoid Invalid URL crash (#15954)

Arvin Xude207a65c290
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.ts
index b1bb2085264..19391d0776e 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts
@@ -3374,6 +3374,52 @@ describe('OpenAIStream', () => {
]);
});
+ it('should filter out empty url_citation annotations (OpenRouter built-in search)', async () => {
+ // OpenRouter's built-in web search may emit empty citation objects like `{}`,
+ // which previously crashed rendering (`new URL(undefined)`) and message persistence.
+ // See https://github.com/lobehub/lobehub/issues/15043
+ const mockOpenAIStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ id: 'openrouter-search',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ annotations: [
+ { type: 'url_citation', url_citation: {} },
+ {
+ type: 'url_citation',
+ url_citation: { url: 'https://example.com', title: 'Example' },
+ },
+ ],
+ },
+ finish_reason: 'stop',
+ },
+ ],
+ });
+
+ controller.close();
+ },
+ });
+
+ const protocolStream = OpenAIStream(mockOpenAIStream);
+
+ const decoder = new TextDecoder();
+ const chunks = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual([
+ 'id: openrouter-search\n',
+ 'event: grounding\n',
+ `data: {"citations":[{"title":"Example","url":"https://example.com"}]}\n\n`,
+ ]);
+ });
+
it('should handle XiaomiMiMo annotations', async () => {
const mockOpenAIStream = new ReadableStream({
start(controller) {
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.ts
index d5bd35b2c1f..fb59e036f37 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.ts
@@ -40,6 +40,15 @@ const hasThoughtSignature = (
return 'thoughtSignature' in toolCall && typeof toolCall.thoughtSignature === 'string';
};
+/**
+ * Drop citations without a valid url. Some providers (e.g. OpenRouter's built-in
+ * web search) emit empty citation objects like `{}`, which would otherwise break
+ * downstream rendering (`new URL(undefined)`) and message persistence (Zod requires
+ * `url` to be a string). See https://github.com/lobehub/lobehub/issues/15043
+ */
+const filterValidCitations = (citations: ChatCitationItem[]): ChatCitationItem[] =>
+ citations.filter((citation) => !!citation?.url);
+
// Process markdown base64 images: extract URLs and clean text in one pass
const processMarkdownBase64Images = (text: string): { cleanedText: string; urls: string[] } => {
if (!text) return { cleanedText: text, urls: [] };
@@ -301,12 +310,14 @@ const transformOpenAIStream = (
return [
{
data: {
- citations: citations.map(
- (item: any) =>
- ({
- title: item.url_citation.title,
- url: item.url_citation.url,
- }) as ChatCitationItem,
+ citations: filterValidCitations(
+ citations.map(
+ (item: any) =>
+ ({
+ title: item.url_citation?.title,
+ url: item.url_citation?.url,
+ }) as ChatCitationItem,
+ ),
),
},
id: chunk.id,
@@ -323,12 +334,14 @@ const transformOpenAIStream = (
return [
{
data: {
- citations: citations.map(
- (item: any) =>
- ({
- title: item.url,
- url: item.url,
- }) as ChatCitationItem,
+ citations: filterValidCitations(
+ citations.map(
+ (item: any) =>
+ ({
+ title: item.url,
+ url: item.url,
+ }) as ChatCitationItem,
+ ),
),
},
id: chunk.id,
@@ -350,12 +363,14 @@ const transformOpenAIStream = (
return [
{
data: {
- citations: citations.map(
- (item: any) =>
- ({
- title: item,
- url: item,
- }) as ChatCitationItem,
+ citations: filterValidCitations(
+ citations.map(
+ (item: any) =>
+ ({
+ title: item,
+ url: item,
+ }) as ChatCitationItem,
+ ),
),
},
id: chunk.id,
@@ -380,12 +395,14 @@ const transformOpenAIStream = (
return [
{
data: {
- citations: citations.map(
- (item: any) =>
- ({
- title: item.title,
- url: item.url,
- }) as ChatCitationItem,
+ citations: filterValidCitations(
+ citations.map(
+ (item: any) =>
+ ({
+ title: item.title,
+ url: item.url,
+ }) as ChatCitationItem,
+ ),
),
},
id: chunk.id,
@@ -517,12 +534,13 @@ const transformOpenAIStream = (
const baseChunks: StreamProtocolChunk[] = [
{
data: {
- citations: (citations as any[])
- .map((item) => ({
+ // Zhipu built-in search tool sometimes returns empty link causing crashes
+ citations: filterValidCitations(
+ (citations as any[]).map((item) => ({
title: typeof item === 'string' ? item : item.title,
url: typeof item === 'string' ? item : item.url || item.link,
- }))
- .filter((c) => c.title && c.url), // Zhipu built-in search tool sometimes returns empty link causing crashes
+ })),
+ ),
},
id: chunk.id,
type: 'grounding',
diff --git a/src/features/Conversation/Messages/components/SearchGrounding.tsx b/src/features/Conversation/Messages/components/SearchGrounding.tsx
index f5f609e7495..edfae784475 100644
--- a/src/features/Conversation/Messages/components/SearchGrounding.tsx
+++ b/src/features/Conversation/Messages/components/SearchGrounding.tsx
@@ -9,6 +9,20 @@ import { useIsDark } from '@/hooks/useIsDark';
import Image from '@/libs/next/Image';
import { type GroundingSearch } from '@/types/search';
+// Resolve the favicon host defensively: some providers (e.g. OpenRouter built-in
+// web search) may emit citations with an empty/invalid url, and `new URL(undefined)`
+// would throw and crash the whole message render.
+// See https://github.com/lobehub/lobehub/issues/15043
+const getFaviconHost = (favicon?: string, url?: string): string => {
+ if (favicon) return favicon;
+ if (!url) return '';
+ try {
+ return new URL(url).host;
+ } catch {
+ return '';
+ }
+};
+
const stripHtml = (html: string) =>
html
.replaceAll(/<[^>]*>/g, '')
@@ -114,11 +128,14 @@ const SearchGrounding = memo<GroundingSearch>(
const [showDetail, setShowDetail] = useState(false);
- const hasWebResults = !!citations?.length;
+ // Drop citations without a valid url so a malformed entry can't crash the render
+ const validCitations = citations?.filter((item) => !!item.url);
+
+ const hasWebResults = !!validCitations?.length;
const hasImageResults = !!imageResults?.length;
const titleIcon = !hasWebResults && hasImageResults ? Images : Globe;
const titleText = hasWebResults
- ? t('search.grounding.title', { count: citations?.length })
+ ? t('search.grounding.title', { count: validCitations?.length })
: t('search.grounding.imageTitle', { count: imageResults?.length });
return (
@@ -146,13 +163,13 @@ const SearchGrounding = memo<GroundingSearch>(
<Flexbox horizontal>{titleText}</Flexbox>
{!showDetail && hasWebResults && (
<Flexbox horizontal>
- {citations?.slice(0, 8).map((item, index) => (
+ {validCitations?.slice(0, 8).map((item, index) => (
<Image
unoptimized
alt={item.title || item.url}
height={16}
key={`${item.url}-${index}`}
- src={`https://icons.duckduckgo.com/ip3/${item.favicon || new URL(item.url).host}.ico`}
+ src={`https://icons.duckduckgo.com/ip3/${getFaviconHost(item.favicon, item.url)}.ico`}
width={16}
style={{
background: cssVar.colorBgContainer,
@@ -220,9 +237,9 @@ const SearchGrounding = memo<GroundingSearch>(
</Flexbox>
</Flexbox>
)}
- {citations && (
+ {validCitations && (
<SearchResultCards
- dataSource={citations.map((c) => ({
+ dataSource={validCitations.map((c) => ({
...c,
// Pass the original redirect URL as href to preserve the actual link
href: c.url,