🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: support multiple artifacts rendering in the same message (#13436)
Arvin Xu967302269e28
diff --git a/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsxindex 7968b34bc00..ed16f16c05e 100644--- a/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx+++ b/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx@@ -66,7 +66,7 @@ const Render = memo<ArtifactProps>(({ identifier, title, type, language, childreconst [isGenerating, isArtifactTagClosed, openArtifact, closeArtifact] = useChatStore((s) => {return [messageStateSelectors.isMessageGenerating(id)(s),- chatPortalSelectors.isArtifactTagClosed(id)(s),+ chatPortalSelectors.isArtifactTagClosed(id, identifier)(s),s.openArtifact,s.closeArtifact,];@@ -88,10 +88,10 @@ const Render = memo<ArtifactProps>(({ identifier, title, type, language, childregap={16}width={'100%'}onClick={() => {- const currentArtifactMessageId = chatPortalSelectors.artifactMessageId(- useChatStore.getState(),- );- if (currentArtifactMessageId === id) {+ const state = useChatStore.getState();+ const currentArtifactMessageId = chatPortalSelectors.artifactMessageId(state);+ const currentArtifactIdentifier = chatPortalSelectors.artifactIdentifier(state);+ if (currentArtifactMessageId === id && currentArtifactIdentifier === identifier) {closeArtifact();} else {openArtifactUI();diff --git a/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.tsindex 8bb2c87efe9..7e50e914bf9 100644--- a/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.ts+++ b/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.ts@@ -122,4 +122,97 @@ describe('rehypePlugin', () => {expect(tree).toEqual(expectedTree);});++ it('should transform multiple <lobeArtifact> tags in the same tree', () => {+ const tree = {+ type: 'root',+ children: [+ {+ type: 'element',+ tagName: 'p',+ children: [{ type: 'text', value: 'Here are two artifacts:' }],+ },+ {+ type: 'element',+ tagName: 'p',+ children: [+ {+ type: 'raw',+ value:+ '<lobeArtifact identifier="first" type="text/markdown" title="First Artifact">',+ },+ { type: 'text', value: 'First content' },+ { type: 'raw', value: '</lobeArtifact>' },+ ],+ },+ {+ type: 'element',+ tagName: 'p',+ children: [+ {+ type: 'raw',+ value:+ '<lobeArtifact identifier="second" type="text/markdown" title="Second Artifact">',+ },+ { type: 'text', value: 'Second content' },+ { type: 'raw', value: '</lobeArtifact>' },+ ],+ },+ {+ type: 'element',+ tagName: 'p',+ children: [{ type: 'text', value: 'Done.' }],+ },+ ],+ };++ const plugin = rehypePlugin();+ plugin(tree);++ // Both artifacts should be transformed+ expect(tree.children).toHaveLength(4);+ expect(tree.children[1]).toEqual({+ type: 'element',+ tagName: 'lobeArtifact',+ properties: {+ identifier: 'first',+ type: 'text/markdown',+ title: 'First Artifact',+ },+ children: [{ type: 'text', value: 'First content' }],+ });+ expect(tree.children[2]).toEqual({+ type: 'element',+ tagName: 'lobeArtifact',+ properties: {+ identifier: 'second',+ type: 'text/markdown',+ title: 'Second Artifact',+ },+ children: [{ type: 'text', value: 'Second content' }],+ });+ });++ it('should transform multiple raw <lobeArtifact> nodes (without wrapping <p>)', () => {+ const tree = {+ type: 'root',+ children: [+ {+ type: 'raw',+ value: '<lobeArtifact identifier="raw-1" type="text/html" title="Raw First">',+ },+ {+ type: 'raw',+ value: '<lobeArtifact identifier="raw-2" type="text/html" title="Raw Second">',+ },+ ],+ };++ const plugin = rehypePlugin();+ plugin(tree);++ expect(tree.children).toHaveLength(2);+ expect((tree.children[0] as any).tagName).toBe('lobeArtifact');+ expect((tree.children[1] as any).tagName).toBe('lobeArtifact');+ });});diff --git a/src/features/Conversation/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.tsindex a02d6ee4db8..d179fb65d19 100644--- a/src/features/Conversation/utils/markdown.test.ts+++ b/src/features/Conversation/utils/markdown.test.ts@@ -275,6 +275,53 @@ This code provides a basic calculator that can perform addition, subtraction, muThis code provides a basic calculator that can perform addition, subtraction, multiplication, and division.`);});++ it('should remove line breaks from multiple artifact tags in the same message', () => {+ const input = `Here are two artifacts:++<lobeArtifact identifier="first-artifact" type="text/markdown" title="First">+Line 1+Line 2+</lobeArtifact>++<lobeArtifact identifier="second-artifact" type="text/markdown" title="Second">+Line A+Line B+</lobeArtifact>++Done.`;++ const output = processWithArtifact(input);++ // Both artifacts should have their newlines removed+ expect(output).toEqual(`Here are two artifacts:++<lobeArtifact identifier="first-artifact" type="text/markdown" title="First">Line 1Line 2</lobeArtifact>++<lobeArtifact identifier="second-artifact" type="text/markdown" title="Second">Line ALine B</lobeArtifact>++Done.`);+ });++ it('should handle multiple artifacts where second is still generating (unclosed)', () => {+ const input = `Two artifacts:++<lobeArtifact identifier="done" type="text/markdown" title="Done">+Content 1+</lobeArtifact>++<lobeArtifact identifier="generating" type="text/markdown" title="Generating">+Content 2 still going`;++ const output = processWithArtifact(input);++ // Both artifacts should have newlines removed, even the unclosed one+ expect(output).toEqual(`Two artifacts:++<lobeArtifact identifier="done" type="text/markdown" title="Done">Content 1</lobeArtifact>++<lobeArtifact identifier="generating" type="text/markdown" title="Generating">Content 2 still going`);+ });});describe('outer code block removal', () => {diff --git a/src/features/Conversation/utils/markdown.ts b/src/features/Conversation/utils/markdown.tsindex a834f63628b..2f7d7baceb0 100644--- a/src/features/Conversation/utils/markdown.ts+++ b/src/features/Conversation/utils/markdown.ts@@ -1,4 +1,4 @@-import { ARTIFACT_TAG_REGEX, ARTIFACT_THINKING_TAG_REGEX } from '@lobechat/const';+import { ARTIFACT_THINKING_TAG_REGEX } from '@lobechat/const';/*** Replace all line breaks in the matched `lobeArtifact` tag with an empty string@@ -46,11 +46,13 @@ export const processWithArtifact = (input: string = '') => {},);- const match = ARTIFACT_TAG_REGEX.exec(output);- // If the input contains the `lobeArtifact` tag, replace all line breaks with an empty string- if (match) {- output = output.replace(ARTIFACT_TAG_REGEX, (match) => match.replaceAll(/\r?\n|\r/g, ''));- }+ // If the input contains `lobeArtifact` tags, replace all line breaks with an empty string+ // Use global regex to handle multiple artifacts in the same message+ const ARTIFACT_TAG_REGEX_GLOBAL =+ /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/g;+ output = output.replaceAll(ARTIFACT_TAG_REGEX_GLOBAL, (match) =>+ match.replaceAll(/\r?\n|\r/g, ''),+ );// if not match, check if it's start with <lobeArtifact but not closedconst regex = /<lobeArtifact\b(?:(?!\/?>)[\s\S])*$/;diff --git a/src/features/Portal/Artifacts/Body/index.tsx b/src/features/Portal/Artifacts/Body/index.tsxindex 7e0cf9c6608..50eb6e72f32 100644--- a/src/features/Portal/Artifacts/Body/index.tsx+++ b/src/features/Portal/Artifacts/Body/index.tsx@@ -19,15 +19,16 @@ const ArtifactsUI = memo(() => {isArtifactTagClosed,] = useChatStore((s) => {const messageId = chatPortalSelectors.artifactMessageId(s) || '';+ const identifier = chatPortalSelectors.artifactIdentifier(s);return [messageId,s.portalArtifactDisplayMode,messageStateSelectors.isMessageGenerating(messageId)(s),chatPortalSelectors.artifactType(s),- chatPortalSelectors.artifactCode(messageId)(s),+ chatPortalSelectors.artifactCode(messageId, identifier)(s),chatPortalSelectors.artifactCodeLanguage(s),- chatPortalSelectors.isArtifactTagClosed(messageId)(s),+ chatPortalSelectors.isArtifactTagClosed(messageId, identifier)(s),];});diff --git a/src/features/Portal/Artifacts/Title.tsx b/src/features/Portal/Artifacts/Title.tsxindex c915cb907f8..c334dc7bf8d 100644--- a/src/features/Portal/Artifacts/Title.tsx+++ b/src/features/Portal/Artifacts/Title.tsx@@ -16,12 +16,13 @@ const Title = () => {const [displayMode, artifactType, artifactTitle, isArtifactTagClosed, closeArtifact] =useChatStore((s) => {const messageId = chatPortalSelectors.artifactMessageId(s) || '';+ const identifier = chatPortalSelectors.artifactIdentifier(s);return [s.portalArtifactDisplayMode,chatPortalSelectors.artifactType(s),chatPortalSelectors.artifactTitle(s),- chatPortalSelectors.isArtifactTagClosed(messageId)(s),+ chatPortalSelectors.isArtifactTagClosed(messageId, identifier)(s),s.closeArtifact,];});diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.tsindex 214acf7cc79..9141c9c6941 100644--- a/src/store/chat/slices/portal/action.test.ts+++ b/src/store/chat/slices/portal/action.test.ts@@ -227,6 +227,100 @@ describe('chatDockSlice', () => {});});+ describe('openArtifact', () => {+ it('should push Artifact view and open portal', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openArtifact({+ id: 'msg-1',+ identifier: 'artifact-1',+ title: 'First Artifact',+ type: 'text/markdown',+ });+ });++ expect(result.current.portalStack).toHaveLength(1);+ expect(result.current.portalStack[0]).toEqual({+ type: PortalViewType.Artifact,+ artifact: {+ id: 'msg-1',+ identifier: 'artifact-1',+ title: 'First Artifact',+ type: 'text/markdown',+ },+ });+ expect(result.current.showPortal).toBe(true);+ });++ it('should replace artifact view when switching to different artifact from same message', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openArtifact({+ id: 'msg-1',+ identifier: 'artifact-1',+ title: 'First Artifact',+ type: 'text/markdown',+ });+ });++ act(() => {+ result.current.openArtifact({+ id: 'msg-1',+ identifier: 'artifact-2',+ title: 'Second Artifact',+ type: 'text/html',+ });+ });++ // Should replace, not stack (same view type)+ expect(result.current.portalStack).toHaveLength(1);+ expect(result.current.portalStack[0]).toEqual({+ type: PortalViewType.Artifact,+ artifact: {+ id: 'msg-1',+ identifier: 'artifact-2',+ title: 'Second Artifact',+ type: 'text/html',+ },+ });+ });++ it('should replace artifact view when switching to artifact from different message', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openArtifact({+ id: 'msg-1',+ identifier: 'artifact-1',+ title: 'First',+ type: 'text/markdown',+ });+ });++ act(() => {+ result.current.openArtifact({+ id: 'msg-2',+ identifier: 'artifact-x',+ title: 'Other',+ type: 'text/html',+ });+ });++ expect(result.current.portalStack).toHaveLength(1);+ expect(result.current.portalStack[0]).toEqual({+ type: PortalViewType.Artifact,+ artifact: {+ id: 'msg-2',+ identifier: 'artifact-x',+ title: 'Other',+ type: 'text/html',+ },+ });+ });+ });+describe('openToolUI', () => {it('should push ToolUI view and open portal', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.tsindex 9804d1ad45f..1c4861ff7ec 100644--- a/src/store/chat/slices/portal/selectors.test.ts+++ b/src/store/chat/slices/portal/selectors.test.ts@@ -286,6 +286,104 @@ ${htmlContent}});expect(chatPortalSelectors.artifactCode('test-id')(state)).toBe(htmlContent);});++ it('should extract specific artifact content by identifier', () => {+ const content1 = 'First artifact content';+ const content2 = 'Second artifact content';+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: `<lobeArtifact identifier="first" type="text">${content1}</lobeArtifact>\n\n<lobeArtifact identifier="second" type="text">${content2}</lobeArtifact>`,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.artifactCode('test-id', 'first')(state)).toBe(content1);+ expect(chatPortalSelectors.artifactCode('test-id', 'second')(state)).toBe(content2);+ });++ it('should return empty string for non-existent identifier', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: `<lobeArtifact identifier="real" type="text">Real content</lobeArtifact>`,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.artifactCode('test-id', 'nonexistent')(state)).toBe('');+ });++ it('should extract content from unclosed artifact by identifier', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: `<lobeArtifact identifier="done" type="text">Done</lobeArtifact>\n\n<lobeArtifact identifier="wip" type="text">Still generating...`,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.artifactCode('test-id', 'done')(state)).toBe('Done');+ expect(chatPortalSelectors.artifactCode('test-id', 'wip')(state)).toBe('Still generating...');+ });++ it('should handle identifiers with regex special characters', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: `<lobeArtifact identifier="test+id(1)[2]" type="text">Special content</lobeArtifact>`,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.artifactCode('test-id', 'test+id(1)[2]')(state)).toBe(+ 'Special content',+ );+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'test+id(1)[2]')(state)).toBe(true);+ });++ it('should return first artifact content when no identifier provided (backward compat)', () => {+ const content1 = 'First';+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: `<lobeArtifact identifier="a" type="text">${content1}</lobeArtifact>\n\n<lobeArtifact identifier="b" type="text">Second</lobeArtifact>`,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.artifactCode('test-id')(state)).toBe(content1);+ });});describe('isArtifactTagClosed', () => {@@ -342,5 +440,66 @@ ${htmlContent}});expect(chatPortalSelectors.isArtifactTagClosed('test-id')(state)).toBe(false);});++ it('should check specific artifact by identifier when both artifacts are closed', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content:+ '<lobeArtifact identifier="a" type="text">A</lobeArtifact>\n\n<lobeArtifact identifier="b" type="text">B</lobeArtifact>',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'a')(state)).toBe(true);+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'b')(state)).toBe(true);+ });++ it('should return false for non-existent identifier', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content: '<lobeArtifact identifier="exists" type="text">Content</lobeArtifact>',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'nonexistent')(state)).toBe(false);+ });++ it('should check specific artifact by identifier when first is closed but second is not', () => {+ const state = createState({+ dbMessagesMap: {+ 'test-id_null': [+ {+ id: 'test-id',+ content:+ '<lobeArtifact identifier="done" type="text">Content 1</lobeArtifact>\n\n<lobeArtifact identifier="generating" type="text">Content 2 still going',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'user',+ sessionId: 'test-id',+ } as UIChatMessage,+ ],+ },+ });+ // Without identifier, returns true because first artifact is closed+ expect(chatPortalSelectors.isArtifactTagClosed('test-id')(state)).toBe(true);+ // With identifier, correctly distinguishes between closed and unclosed+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'done')(state)).toBe(true);+ expect(chatPortalSelectors.isArtifactTagClosed('test-id', 'generating')(state)).toBe(false);+ });});});diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex b1724d6165a..d94489c636e 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -63,15 +63,24 @@ const artifactMessageId = (s: ChatStoreState) => currentArtifact(s)?.id;const artifactType = (s: ChatStoreState) => currentArtifact(s)?.type;const artifactCodeLanguage = (s: ChatStoreState) => currentArtifact(s)?.language;+// Escape special regex characters in a string+const escapeRegExp = (str: string) => str.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');+const artifactMessageContent = (id: string) => (s: ChatStoreState) => {const message = dbMessageSelectors.getDbMessageById(id)(s);return message?.content || '';};-const artifactCode = (id: string) => (s: ChatStoreState) => {+const artifactCode = (id: string, identifier?: string) => (s: ChatStoreState) => {const messageContent = artifactMessageContent(id)(s);- const result = messageContent.match(ARTIFACT_TAG_REGEX);+ const regex = identifier+ ? new RegExp(+ `<lobeArtifact\\b[^>]*identifier="${escapeRegExp(identifier)}"[^>]*>(?<content>[\\S\\s]*?)(?:<\\/lobeArtifact>|$)`,+ )+ : ARTIFACT_TAG_REGEX;++ const result = messageContent.match(regex);let content = result?.groups?.content || '';// Remove markdown code block if content is wrapped@@ -80,9 +89,17 @@ const artifactCode = (id: string) => (s: ChatStoreState) => {return content;};-const isArtifactTagClosed = (id: string) => (s: ChatStoreState) => {+const isArtifactTagClosed = (id: string, identifier?: string) => (s: ChatStoreState) => {const content = artifactMessageContent(id)(s);+ if (identifier) {+ // Check if the specific artifact (by identifier) is closed+ const regex = new RegExp(+ `<lobeArtifact\\b[^>]*identifier="${escapeRegExp(identifier)}"[^>]*>[\\S\\s]*?<\\/lobeArtifact>`,+ );+ return regex.test(content || '');+ }+return ARTIFACT_TAG_CLOSED_REGEX.test(content || '');};