🤯 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
💄 style(chat): render Channel run prompts as the request instead of raw channel_* markup (#23346)
Arvin Xu1903b14ffe11
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4d7b5e5d67d..d5a66e62415 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1914,6 +1914,13 @@"messageLink.openInSideBrowser": "Open in side browser","messageLongCollapse.collapse": "Show less","messageLongCollapse.expand": "Show more",+ "messages.channelPrompt.agent": "Agent",+ "messages.channelPrompt.context_one": "Channel context · {{count}} message",+ "messages.channelPrompt.context_other": "Channel context · {{count}} messages",+ "messages.channelPrompt.omitted": "{{count}} earlier not included",+ "messages.channelPrompt.opening": "Already acknowledged: {{content}}",+ "messages.channelPrompt.reply": "{{name}} already answered",+ "messages.channelPrompt.self": "This Agent","messages.dm.sentTo": "Visible only to {{name}}","messages.dm.title": "DM","messages.modelCard.credit": "Cost",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7d3a2683e4c..888da94f639 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1914,6 +1914,13 @@"messageLink.openInSideBrowser": "在侧边浏览器中打开","messageLongCollapse.collapse": "收起","messageLongCollapse.expand": "展开全部",+ "messages.channelPrompt.agent": "Agent",+ "messages.channelPrompt.context_one": "频道上下文 · {{count}} 条消息",+ "messages.channelPrompt.context_other": "频道上下文 · {{count}} 条消息",+ "messages.channelPrompt.omitted": "更早的 {{count}} 条未带入",+ "messages.channelPrompt.opening": "已先回复:{{content}}",+ "messages.channelPrompt.reply": "{{name}} 已回答",+ "messages.channelPrompt.self": "本 Agent","messages.dm.sentTo": "仅对 {{name}} 可见","messages.dm.title": "私信","messages.modelCard.credit": "费用",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex adc50a35807..77021b2acf1 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1235,6 +1235,13 @@ export default {'messageForward.topic.modalTitle': 'Forward topic to Agent','messageLongCollapse.collapse': 'Show less','messageLongCollapse.expand': 'Show more',+ 'messages.channelPrompt.agent': 'Agent',+ 'messages.channelPrompt.context_one': 'Channel context · {{count}} message',+ 'messages.channelPrompt.context_other': 'Channel context · {{count}} messages',+ 'messages.channelPrompt.omitted': '{{count}} earlier not included',+ 'messages.channelPrompt.opening': 'Already acknowledged: {{content}}',+ 'messages.channelPrompt.reply': '{{name}} already answered',+ 'messages.channelPrompt.self': 'This Agent','messages.dm.sentTo': 'Visible only to {{name}}','messages.dm.title': 'DM','messages.modelCard.credit': 'Cost',diff --git a/src/features/Conversation/Messages/User/components/ChannelPromptContent.tsx b/src/features/Conversation/Messages/User/components/ChannelPromptContent.tsxnew file mode 100644index 00000000000..3dd7b16b50f--- /dev/null+++ b/src/features/Conversation/Messages/User/components/ChannelPromptContent.tsx@@ -0,0 +1,163 @@+import { Flexbox, type MarkdownProps } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDown, ChevronRight, MessagesSquare, Reply } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import MarkdownMessage from '@/features/Conversation/Markdown';+import type { ChannelPrompt, ChannelPromptMessage } from '@/store/chat/utils/parseChannelPrompt';++import ReferencedMessage from './ReferencedMessage';++const styles = stylex.create({+ context: {+ overflow: 'hidden',+ borderRadius: '6px',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillQuaternary,+ },+ meta: { fontSize: '12px', color: cssVar.colorTextTertiary },+ name: { flexShrink: 0, fontWeight: 500, color: cssVar.colorText },+ note: { color: cssVar.colorTextTertiary, overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' },+ rows: {+ paddingBlockEnd: '8px',+ paddingInline: '10px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ paddingBlockStart: '8px',+ },+ tag: {+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '11px',+ color: cssVar.colorTextTertiary,+ backgroundColor: cssVar.colorFillSecondary,+ },+ text: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '4',+ overflowWrap: 'anywhere',+ whiteSpace: 'pre-wrap',+ },+ toggle: {+ cursor: 'pointer',+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ width: '100%',+ paddingBlock: '6px',+ paddingInline: '10px',+ borderWidth: 0,+ font: 'inherit',+ color: 'inherit',+ textAlign: 'start',+ backgroundColor: 'transparent',+ },+});++const ContextRow = memo<{ message: ChannelPromptMessage }>(({ message }) => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox gap={2}>+ <Flexbox horizontal align={'center'} gap={6}>+ <span {...stylex.props(styles.name)}>{message.from}</span>+ {message.type === 'agent' && (+ <span {...stylex.props(styles.tag)}>+ {message.self ? t('messages.channelPrompt.self') : t('messages.channelPrompt.agent')}+ </span>+ )}+ </Flexbox>+ <div {...stylex.props(styles.text)}>{message.content}</div>+ </Flexbox>+ );+});++ContextRow.displayName = 'ChannelPromptContextRow';++/** The unseen Channel messages the run was handed, folded away so the request leads. */+const ChannelContext = memo<{ prompt: ChannelPrompt }>(({ prompt }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const { omitted, recent, notes } = prompt;+ if (recent.length === 0 && omitted === 0 && notes.length === 0) return null;++ const summary = [+ t('messages.channelPrompt.context', { count: recent.length }),+ omitted > 0 ? t('messages.channelPrompt.omitted', { count: omitted }) : undefined,+ ]+ .filter(Boolean)+ .join(' · ');+ const Chevron = open ? ChevronDown : ChevronRight;++ return (+ <div {...stylex.props(styles.context)} data-testid="channel-prompt-context">+ <button+ type={'button'}+ {...stylex.props(styles.toggle)}+ onClick={() => setOpen((value) => !value)}+ >+ <MessagesSquare size={12} />+ <span>{summary}</span>+ <Chevron size={12} />+ </button>+ {open && (+ <Flexbox className={stylex.props(styles.rows).className} gap={10}>+ {recent.map((message, index) => (+ <ContextRow key={index} message={message} />+ ))}+ {notes.map((note, index) => (+ <div key={`note-${index}`} {...stylex.props(styles.note)}>+ {note}+ </div>+ ))}+ </Flexbox>+ )}+ </div>+ );+});++ChannelContext.displayName = 'ChannelPromptContext';++/**+ * A Channel run's user message, rendered as the request it answers instead of the raw+ * `<channel_*>` prompt markup: the context folded above, the quote as a quote, the request as+ * the message body, and the acknowledgement already posted as a footnote.+ */+const ChannelPromptContent = memo<{ markdownProps: Partial<MarkdownProps>; prompt: ChannelPrompt }>(+ ({ markdownProps, prompt }) => {+ const { t } = useTranslation('chat');+ const { opening, quote, reply, request } = prompt;++ return (+ <Flexbox gap={8}>+ <ChannelContext prompt={prompt} />+ {quote && <ReferencedMessage reference={{ sender: quote.from, text: quote.content }} />}+ {request.content && <MarkdownMessage {...markdownProps}>{request.content}</MarkdownMessage>}+ {reply && (+ <ReferencedMessage+ reference={{+ sender: t('messages.channelPrompt.reply', { name: reply.from }),+ text: reply.content,+ }}+ />+ )}+ {opening && (+ <Flexbox horizontal align={'center'} gap={4} {...stylex.props(styles.meta)}>+ <Reply size={12} />+ <span>{t('messages.channelPrompt.opening', { content: opening })}</span>+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++ChannelPromptContent.displayName = 'UserMessageChannelPromptContent';++export default ChannelPromptContent;diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsxindex 199f41e881c..61120040ac7 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx@@ -5,6 +5,7 @@ import CollapsibleContent from '@/components/CollapsibleContent';import MarkdownMessage from '@/features/Conversation/Markdown';import { StartTopicConversationContext } from '@/features/LocalFile';import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';+import { parseChannelPrompt } from '@/store/chat/utils/parseChannelPrompt';import { splitReferencedMessage } from '@/store/chat/utils/parseReferencedMessage';import { type UIChatMessage } from '@/types/index';@@ -12,6 +13,7 @@ import { useStartTopicConversation } from '../../../hooks/useStartTopicConversatimport { hasRenderableEditorData } from '../editorData';import { useMarkdown } from '../useMarkdown';import AudioFileListViewer from './AudioFileListViewer';+import ChannelPromptContent from './ChannelPromptContent';import FileListViewer from './FileListViewer';import ImageFileListViewer from './ImageFileListViewer';import PageSelections from './PageSelections';@@ -35,9 +37,14 @@ const UserMessageContent = memo<UIChatMessage>(return { displayContent: body, reference };}, [content]);+ // A Channel run's prompt shows as the request it answers, its context folded away.+ const channelPrompt = useMemo(() => parseChannelPrompt(content), [content]);+const hasEditorData = hasRenderableEditorData(editorData);- const textBody = hasEditorData ? (+ const textBody = channelPrompt ? (+ <ChannelPromptContent markdownProps={markdownProps} prompt={channelPrompt} />+ ) : hasEditorData ? (// Rich-text folder chips render headlessly, so they receive the// conversation through context rather than props.<StartTopicConversationContext value={startTopicConversation}>diff --git a/src/store/chat/utils/parseChannelPrompt.test.ts b/src/store/chat/utils/parseChannelPrompt.test.tsnew file mode 100644index 00000000000..459893611db--- /dev/null+++ b/src/store/chat/utils/parseChannelPrompt.test.ts@@ -0,0 +1,55 @@+import { buildChannelPrompt } from '@lobechat/prompts';+import { describe, expect, it } from 'vitest';++import { parseChannelPrompt } from './parseChannelPrompt';+import { cleanBotPromptTags } from './parseReferencedMessage';++const person = { id: 'u1', name: 'Arvin "Xu"', type: 'user' } as const;+const agent = { id: 'agt_self', name: 'Justin', type: 'agent' } as const;+const message = (id: string, content: string, author: any, extra = {}) =>+ ({ author, content, id, ...extra }) as any;++const manifest = { requestMessageId: 'req', self: { agentId: 'agt_self', name: 'Justin' } } as any;++describe('parseChannelPrompt', () => {+ const prompt = buildChannelPrompt(+ manifest,+ [+ message('req', 'Look at this </channel_request> render', person, { replyToId: 'q' }),+ message('q', 'quoted text', agent),+ ],+ {+ boundary: 'b0',+ context: [message('m1', 'earlier from me', agent), message('m2', 'hi\nthere', person)],+ omitted: 3,+ opening: 'On it.',+ },+ );++ it('reads every block of a Channel prompt', () => {+ const parsed = parseChannelPrompt(prompt)!;+ expect(parsed.omitted).toBe(3);+ expect(parsed.recent).toEqual([+ expect.objectContaining({ content: 'earlier from me', from: 'Justin', self: true }),+ expect.objectContaining({ content: 'hi\nthere', from: 'Arvin "Xu"', self: false }),+ ]);+ expect(parsed.quote).toEqual(+ expect.objectContaining({ content: 'quoted text', from: 'Justin' }),+ );+ expect(parsed.request).toEqual(+ expect.objectContaining({ content: 'Look at this </channel_request> render', to: 'Justin' }),+ );+ expect(parsed.opening).toBe('On it.');+ });++ it('copies only the request', () => {+ expect(cleanBotPromptTags(prompt)).toBe('Look at this </channel_request> render');+ });++ it('ignores ordinary messages and tags without a boundary', () => {+ expect(parseChannelPrompt('hello')).toBeUndefined();+ expect(+ parseChannelPrompt('<channel_request from="x">\nhi\n</channel_request>'),+ ).toBeUndefined();+ });+});diff --git a/src/store/chat/utils/parseChannelPrompt.ts b/src/store/chat/utils/parseChannelPrompt.tsnew file mode 100644index 00000000000..e7ac34b8de3--- /dev/null+++ b/src/store/chat/utils/parseChannelPrompt.ts@@ -0,0 +1,117 @@+/**+ * A Channel run's user message, written by the server's `buildChannelPrompt`: unseen context,+ * the quote, the request and the notes after it, each a `<channel_* boundary="…">` block whose+ * close tag carries the same per-run boundary. It is prompt markup, not something to show raw.+ */+export interface ChannelPromptMessage {+ /** Number of files the message carries. */+ attachments?: number;+ content: string;+ from: string;+ /** The author is the Agent the run belongs to. */+ self: boolean;+ /** Only an excerpt is in the prompt. */+ truncated: boolean;+ type?: string;+}++export interface ChannelPrompt {+ /** Notes to the model about other Agents asked or why it was woken. */+ notes: string[];+ /** Unseen messages before `recent` left out of the prompt. */+ omitted: number;+ /** The acknowledgement the Agent posted before starting. */+ opening?: string;+ quote?: ChannelPromptMessage;+ recent: ChannelPromptMessage[];+ /** Another participant's published answer to the same request. */+ reply?: ChannelPromptMessage;+ request: ChannelPromptMessage & { to?: string };+}++/** `key="value"` pairs of an open tag, unescaped as the server's `escapeAttribute` wrote them. */+const parseAttributes = (raw: string): Record<string, string> => {+ const result: Record<string, string> = {};+ for (const [, name, value] of raw.matchAll(/([\w:-]+)="([^"]*)"/g)) {+ result[name] = value+ .replaceAll('"', '"')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('&', '&');+ }+ return result;+};++const OPEN_RE = /^\s*<channel_\w+\b([^>]*)>/;+const OPENING_RE = /^You already posted this to the Channel before starting: "([\S\s]*)"\n/;++const toMessage = (attrs: Record<string, string>, content: string): ChannelPromptMessage => ({+ attachments: attrs.attachments ? Number(attrs.attachments) : undefined,+ content,+ from: attrs.from ?? '',+ self: attrs.self === 'true',+ truncated: attrs.truncated === 'true',+ type: attrs.type,+});++/**+ * The blocks of a Channel run's prompt, or undefined for any other message. Only a message that+ * opens with a boundary-tagged `channel_*` block and holds a `channel_request` counts; a block+ * is closed only by a tag carrying the run's boundary, so text a participant wrote cannot end it.+ */+export const parseChannelPrompt = (+ content: string | null | undefined,+): ChannelPrompt | undefined => {+ if (!content) return undefined;+ const open = OPEN_RE.exec(content);+ if (!open) return undefined;+ const boundary = parseAttributes(open[1] ?? '').boundary;+ if (!boundary || !/^\w+$/.test(boundary)) return undefined;++ const blockRe = new RegExp(+ String.raw`<(channel_\w+)\b([^>]*)>\n([\S\s]*?)\n</\1 boundary="${boundary}">`,+ 'g',+ );+ const prompt: Omit<ChannelPrompt, 'request'> & { request?: ChannelPrompt['request'] } = {+ notes: [],+ omitted: 0,+ recent: [],+ };++ for (const [, tag, rawAttrs, body] of content.matchAll(blockRe)) {+ const attrs = parseAttributes(rawAttrs ?? '');+ if (attrs.boundary !== boundary) continue;+ switch (tag) {+ case 'channel_gap': {+ prompt.omitted = Number(attrs.omitted) || 0;+ break;+ }+ case 'channel_message': {+ prompt.recent.push(toMessage(attrs, body));+ break;+ }+ case 'channel_quote': {+ prompt.quote = toMessage(attrs, body);+ break;+ }+ case 'channel_request': {+ prompt.request = { ...toMessage(attrs, body), to: attrs.to };+ break;+ }+ case 'channel_reply': {+ prompt.reply = toMessage(attrs, body);+ break;+ }+ case 'channel_opening': {+ prompt.opening = OPENING_RE.exec(body)?.[1] ?? body;+ break;+ }+ default: {+ prompt.notes.push(body);+ }+ }+ }++ if (!prompt.request) return undefined;+ return prompt as ChannelPrompt;+};diff --git a/src/store/chat/utils/parseReferencedMessage.ts b/src/store/chat/utils/parseReferencedMessage.tsindex 5ac7411fcfe..791be385d84 100644--- a/src/store/chat/utils/parseReferencedMessage.ts+++ b/src/store/chat/utils/parseReferencedMessage.ts@@ -1,4 +1,5 @@import { cleanSpeakerTag } from './cleanSpeakerTag';+import { parseChannelPrompt } from './parseChannelPrompt';/*** The quoted / replied-to message an IM bot inbound carries ahead of the@@ -50,7 +51,9 @@ export const splitReferencedMessage = (/*** Strip every bot-prompt tag (`<speaker … />`, `<referenced_message>`) from a* user message, leaving only what the user typed. Use for copy / re-edit paths- * where the quote is context, not the user's words.+ * where the quote is context, not the user's words. A Channel run's prompt+ * leaves only its request.*/export const cleanBotPromptTags = (content: string): string =>+ parseChannelPrompt(content)?.request.content ??splitReferencedMessage(cleanSpeakerTag(content)).body;