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.

💄 style: AnalyzeVisualMedia inspector, Portal HTML preview refactor & CE trace dedup (#14777)

Arvin Xud00770a956a3
diff --git a/.agents/skills/builtin-tool/references/ui.md b/.agents/skills/builtin-tool/references/ui.md
index 7b6e597eb49..da6220a7d43 100644
--- a/.agents/skills/builtin-tool/references/ui.md
+++ b/.agents/skills/builtin-tool/references/ui.md
@@ -18,6 +18,27 @@ The two reference tools to read end-to-end:
---
+## Tool Render 设计原则(中文草案)
+
+这些原则用于判断一个 builtin tool 的 Inspector / Render / Placeholder / Streaming / Intervention / Portal 应该做什么,以及做到什么程度。
+
+1. **先保证折叠态可读。** 每个 API 都必须有 Inspector;用户不展开也应该能看懂 “正在做什么 / 对什么做 / 当前结果是什么”。Inspector 不应该只展示函数名和原始参数。
+2. **Inspector 是一句话,不是详情页。** 优先表达动作、关键对象、数量、状态,例如 “分析图片 3 张”“搜索 12 个结果”“读取 config.json”。长文本、列表和结构化结果放到 Render 或 Portal。
+3. **Inspector 要覆盖执行生命周期。** `args` 还在 streaming、工具执行中、执行完成、执行失败时都应该有稳定展示;必要时同时读取 `args`、`partialArgs` 和 `pluginState`,避免出现空白、跳变或只显示半截参数。
+4. **只有结构化结果才需要 Render。** 如果工具结果只是自然语言总结,通常不需要 Render;如果结果包含列表、媒体、文件、表格、代码、diff、地图、时间线、权限请求等结构,就应该提供 Render。
+5. **Render 要帮助用户检查结果,而不是复述参数。** Render 的主体应该围绕工具产物组织:可预览、可比较、可筛选、可定位。参数只作为上下文辅助出现,不要把 Render 做成一块更大的 args dump。
+6. **参数和结果要一起参与渲染。** 好的 Tool UI 通常同时用 `args` 解释意图,用 `pluginState` 展示真实执行结果;但 `pluginState` 只放结果域数据,不要反向塞入可以从 `args` 推导出的内容。
+7. **慢操作要有 Placeholder。** 如果工具通常需要等待网络、文件系统、模型或外部进程,Placeholder 应该先占住最终 Render 的版式,让用户知道即将看到什么,而不是只显示一个泛化 loading。
+8. **Streaming 只用于连续产物。** 搜索列表、日志、长文本、文件分析、分阶段计划适合 Streaming;一次性小结果不需要强行做 Streaming。Streaming UI 要能渐进追加,并且完成后自然过渡到最终 Render。
+9. **有风险的动作必须 Intervention。** 写文件、删除、发送、安装、执行命令、外部可见操作、权限敏感操作,都应该在执行前给出可理解的确认界面;确认文案要说明影响范围,而不是只问 “是否继续”。
+10. **错误、空态和截断都是正式状态。** Render 不能在失败、无结果、超长结果时退化成空白。错误要说明发生在哪一步;空态要告诉用户没有产物;超长内容要明确 “展示前 N 项 / 还有 N 项”。
+11. **信息密度要克制。** 默认展示最有判断价值的部分:标题、来源、状态、摘要、少量关键字段。大对象、长列表、原文、调试数据放进可展开区域或 Portal,避免把聊天流撑成后台管理页。
+12. **视觉上融入聊天流。** Tool UI 应该使用 `@lobehub/ui` / base-ui、`Flexbox`、`createStaticStyles` 和 `cssVar.*`,遵循现有间距、圆角、颜色、字号;不要为单个工具发明一套独立视觉语言。
+13. **Devtools fixture 是验收入口。** 新增或修改 Tool UI 时,应在 `/devtools` 里准备覆盖典型态、loading/streaming、空态、错误态、长内容态的 fixture;一个 API 如果在真实聊天里会出现,就不应该在 devtools 中缺席。
+14. **先做用户会看的 UI,再做调试 UI。** Raw JSON、trace、schema、内部 id 可以存在,但应默认收起或放到调试区;主界面先回答用户最关心的问题:工具做了什么,结果值不值得信任,下一步能做什么。
+
+---
+
## 0. Shared Style Rules
These apply across every surface.
diff --git a/packages/agent-tracing/src/cli/inspect.ts b/packages/agent-tracing/src/cli/inspect.ts
index 3fad7e2062f..3919f7c4a9f 100644
--- a/packages/agent-tracing/src/cli/inspect.ts
+++ b/packages/agent-tracing/src/cli/inspect.ts
@@ -19,6 +19,7 @@ import {
renderSnapshot,
renderStepDetail,
renderSystemRole,
+ resolveCeSnapshot,
} from '../viewer';
async function fetchSnapshotFromUrl(url: string): Promise<ExecutionSnapshot> {
@@ -44,8 +45,8 @@ function findStep(snapshot: ExecutionSnapshot, stepIndex: number): StepSnapshot
return step;
}
-function getSystemRole(step: StepSnapshot): string | undefined {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+function getSystemRole(step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
const inputRole = ceEvent?.input?.systemRole;
if (inputRole) return inputRole;
const outputMsgs = ceEvent?.output as any[] | undefined;
@@ -56,8 +57,8 @@ function getSystemRole(step: StepSnapshot): string | undefined {
: JSON.stringify(systemMsg.content, null, 2);
}
-function getEnvContent(step: StepSnapshot): string | undefined {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+function getEnvContent(step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
const outputMsgs = ceEvent?.output as any[] | undefined;
const envMsg = outputMsgs?.find((m: any) => m.role === 'user');
if (!envMsg) return undefined;
@@ -195,8 +196,12 @@ export function registerInspectCommand(program: Command) {
const stepA = findStep(snapshot, effectiveStepIndex);
const stepB = findStep(snapshot, diffStepIndex);
const label = opts.systemRole ? 'System Role' : 'Environment Context';
- const contentA = opts.systemRole ? getSystemRole(stepA) : getEnvContent(stepA);
- const contentB = opts.systemRole ? getSystemRole(stepB) : getEnvContent(stepB);
+ const contentA = opts.systemRole
+ ? getSystemRole(stepA, snapshot.steps)
+ : getEnvContent(stepA, snapshot.steps);
+ const contentB = opts.systemRole
+ ? getSystemRole(stepB, snapshot.steps)
+ : getEnvContent(stepB, snapshot.steps);
console.log(
renderDiff(contentA ?? '', contentB ?? '', {
labelA: `Step ${effectiveStepIndex}`,
@@ -212,14 +217,18 @@ export function registerInspectCommand(program: Command) {
const step = findStep(snapshot, effectiveStepIndex);
if (opts.json) {
if (opts.systemRole) {
- console.log(JSON.stringify(getSystemRole(step) ?? null, null, 2));
+ console.log(JSON.stringify(getSystemRole(step, snapshot.steps) ?? null, null, 2));
} else {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;
const envMsg = (ceEvent?.output as any[])?.find((m: any) => m.role === 'user');
console.log(JSON.stringify(envMsg ?? null, null, 2));
}
} else {
- console.log(opts.systemRole ? renderSystemRole(step) : renderEnvContext(step));
+ console.log(
+ opts.systemRole
+ ? renderSystemRole(step, snapshot.steps)
+ : renderEnvContext(step, snapshot.steps),
+ );
}
return;
}
@@ -228,12 +237,12 @@ export function registerInspectCommand(program: Command) {
if (opts.payloadTools && effectiveStepIndex !== undefined) {
const step = findStep(snapshot, effectiveStepIndex);
if (opts.json) {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;
const toolsConfig = ceEvent?.input?.toolsConfig;
const payloadTools = (step.context?.payload as any)?.tools;
console.log(JSON.stringify({ payloadTools, toolsConfig }, null, 2));
} else {
- console.log(renderPayloadTools(step));
+ console.log(renderPayloadTools(step, snapshot.steps));
}
return;
}
@@ -242,10 +251,10 @@ export function registerInspectCommand(program: Command) {
if (opts.payload && effectiveStepIndex !== undefined) {
const step = findStep(snapshot, effectiveStepIndex);
if (opts.json) {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;
console.log(JSON.stringify(ceEvent?.input ?? null, null, 2));
} else {
- console.log(renderPayload(step));
+ console.log(renderPayload(step, snapshot.steps));
}
return;
}
@@ -254,10 +263,10 @@ export function registerInspectCommand(program: Command) {
if (opts.memory && effectiveStepIndex !== undefined) {
const step = findStep(snapshot, effectiveStepIndex);
if (opts.json) {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;
console.log(JSON.stringify(ceEvent?.input?.userMemory ?? null, null, 2));
} else {
- console.log(renderMemory(step));
+ console.log(renderMemory(step, snapshot.steps));
}
return;
}
diff --git a/packages/agent-tracing/src/types.ts b/packages/agent-tracing/src/types.ts
index aaa134ce9c2..042f16e8abd 100644
--- a/packages/agent-tracing/src/types.ts
+++ b/packages/agent-tracing/src/types.ts
@@ -38,6 +38,22 @@ export interface StepSnapshot {
payload?: unknown;
stepContext?: unknown;
};
+ /**
+ * Context Engine result snapshot for this step. Only present on steps where the CE ran
+ * (typically `call_llm`). Uses a delta format: only `input`/`output` fields that changed
+ * from the previous step are stored — resolve the full snapshot by walking backward
+ * through steps (same pattern as `messagesBaseline`/`messagesDelta`).
+ *
+ * - `undefined` → CE did not run for this step (e.g., `call_tool` steps)
+ * - `{}` → CE ran but both `input` and `output` are unchanged from before
+ * - `{ input }` → input changed; `output` unchanged
+ * - `{ output }` → output changed; `input` unchanged
+ * - `{ input, output}` → both changed (full snapshot, typical of the first CE event)
+ */
+ contextEngine?: {
+ input?: unknown;
+ output?: unknown;
+ };
events?: Array<{ type: string; [key: string]: unknown }>;
executionTimeMs: number;
diff --git a/packages/agent-tracing/src/viewer/index.ts b/packages/agent-tracing/src/viewer/index.ts
index 7a90fde8be3..129e8415cf0 100644
--- a/packages/agent-tracing/src/viewer/index.ts
+++ b/packages/agent-tracing/src/viewer/index.ts
@@ -5,6 +5,64 @@ import { reconstructMessages } from '../utils/reconstruct';
export { analyzeAgentSignal, renderAgentSignal } from './agentSignal';
+/**
+ * Resolve the Context Engine snapshot for a step, reconstructing missing `input`/`output`
+ * fields by walking back through previous steps (delta format).
+ * Returns undefined if CE did not run for this step.
+ *
+ * Supports both the new `contextEngine` field format and the legacy `context_engine_result`
+ * event format for backward compatibility with older snapshots.
+ */
+export function resolveCeSnapshot(
+ step: StepSnapshot,
+ allSteps?: StepSnapshot[],
+): Record<string, unknown> | undefined {
+ // New format: contextEngine typed field
+ if (step.contextEngine !== undefined) {
+ let resolvedInput = step.contextEngine.input;
+ let resolvedOutput = step.contextEngine.output;
+
+ if (allSteps && (resolvedInput === undefined || resolvedOutput === undefined)) {
+ for (let i = step.stepIndex - 1; i >= 0; i--) {
+ const prevStep = allSteps.find((s) => s.stepIndex === i);
+ if (!prevStep?.contextEngine) continue;
+ if (resolvedInput === undefined && prevStep.contextEngine.input !== undefined) {
+ resolvedInput = prevStep.contextEngine.input;
+ }
+ if (resolvedOutput === undefined && prevStep.contextEngine.output !== undefined) {
+ resolvedOutput = prevStep.contextEngine.output;
+ }
+ if (resolvedInput !== undefined && resolvedOutput !== undefined) break;
+ }
+ }
+
+ return { input: resolvedInput, output: resolvedOutput };
+ }
+
+ // Legacy format: context_engine_result stored in events array
+ const localCe = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ if (!localCe) return undefined;
+ if (!allSteps || (localCe.input !== undefined && localCe.output !== undefined)) return localCe;
+
+ let resolvedInput = localCe.input;
+ let resolvedOutput = localCe.output;
+
+ for (let i = step.stepIndex - 1; i >= 0; i--) {
+ const prevStep = allSteps.find((s) => s.stepIndex === i);
+ if (!prevStep) continue;
+ const prevCe = prevStep.events?.find((e) => e.type === 'context_engine_result') as any;
+ if (!prevCe) continue;
+ if (resolvedInput === undefined && prevCe.input !== undefined) resolvedInput = prevCe.input;
+ if (resolvedOutput === undefined && prevCe.output !== undefined) resolvedOutput = prevCe.output;
+ if (resolvedInput !== undefined && resolvedOutput !== undefined) break;
+ }
+
+ return { ...localCe, input: resolvedInput, output: resolvedOutput };
+}
+
+/** @deprecated Use resolveCeSnapshot instead. */
+export const resolveCeEvent = resolveCeSnapshot;
+
/**
* Resolve messages for a step, supporting both legacy (full) and incremental (delta) formats.
*/
@@ -353,7 +411,7 @@ export function renderMessageDetail(
source: 'input' | 'output' = 'output',
allSteps?: StepSnapshot[],
): string {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
let messages: any[] | undefined;
let label: string;
@@ -405,8 +463,8 @@ export function renderMessageDetail(
return lines.join('\n');
}
-export function renderSystemRole(step: StepSnapshot): string {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+export function renderSystemRole(step: StepSnapshot, allSteps?: StepSnapshot[]): string {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
// Try input.systemRole first (user-configured agent prompt)
const inputSystemRole = ceEvent?.input?.systemRole;
@@ -437,8 +495,8 @@ export function renderSystemRole(step: StepSnapshot): string {
return lines.join('\n');
}
-export function renderEnvContext(step: StepSnapshot): string {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+export function renderEnvContext(step: StepSnapshot, allSteps?: StepSnapshot[]): string {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
const outputMsgs: any[] | undefined = ceEvent?.output;
if (!outputMsgs || outputMsgs.length === 0) {
@@ -463,9 +521,9 @@ export function renderEnvContext(step: StepSnapshot): string {
return lines.join('\n');
}
-export function renderPayloadTools(step: StepSnapshot): string {
+export function renderPayloadTools(step: StepSnapshot, allSteps?: StepSnapshot[]): string {
const lines: string[] = [];
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
// Section 1: Plugin manifests from context engine input
const toolsConfig = ceEvent?.input?.toolsConfig;
@@ -519,8 +577,8 @@ export function renderPayloadTools(step: StepSnapshot): string {
return lines.join('\n');
}
-export function renderPayload(step: StepSnapshot): string {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+export function renderPayload(step: StepSnapshot, allSteps?: StepSnapshot[]): string {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
if (!ceEvent?.input) {
return red('No context engine data found in this step.');
}
@@ -654,8 +712,8 @@ export function renderPayload(step: StepSnapshot): string {
return lines.join('\n');
}
-export function renderMemory(step: StepSnapshot): string {
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+export function renderMemory(step: StepSnapshot, allSteps?: StepSnapshot[]): string {
+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;
const userMemory = ceEvent?.input?.userMemory;
if (!userMemory) {
@@ -865,7 +923,7 @@ export function renderStepDetail(
if (options?.messages) {
// Show context engine input/output from events if available
- const ceEvent = step.events?.find((e) => e.type === 'context_engine_result') as any;
+ const ceEvent = resolveCeSnapshot(step, options?.allSteps) as any;
if (ceEvent) {
// Context engine input messages (DB messages passed to engine)
diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/AnalyzeVisualMedia/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/AnalyzeVisualMedia/index.tsx
new file mode 100644
index 00000000000..0af075f0651
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/AnalyzeVisualMedia/index.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { AnalyzeVisualMediaParams, AnalyzeVisualMediaState } from '../../../types';
+
+const getArrayLength = (value?: string[]) => (Array.isArray(value) ? value.length : 0);
+
+export const AnalyzeVisualMediaInspector = memo<
+ BuiltinInspectorProps<AnalyzeVisualMediaParams, AnalyzeVisualMediaState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const question = args?.question || partialArgs?.question;
+ const mediaCount =
+ pluginState?.files?.length ??
+ getArrayLength(args?.refs || partialArgs?.refs) +
+ getArrayLength(args?.urls || partialArgs?.urls);
+
+ if (isArgumentsStreaming && !question) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent.apiName.analyzeVisualMedia')}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ {question ? (
+ <Trans
+ components={{ question: <span className={highlightTextStyles.primary} /> }}
+ i18nKey="builtins.lobe-agent.apiName.analyzeVisualMedia.result"
+ ns="plugin"
+ values={{ question }}
+ />
+ ) : (
+ <span>{t('builtins.lobe-agent.apiName.analyzeVisualMedia')}</span>
+ )}
+ {!isArgumentsStreaming && !isLoading && mediaCount > 0 && (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 6 }}
+ >
+ · {t('builtins.lobe-agent.apiName.analyzeVisualMedia.mediaCount', { count: mediaCount })}
+ </Text>
+ )}
+ </div>
+ );
+});
+
+AnalyzeVisualMediaInspector.displayName = 'AnalyzeVisualMediaInspector';
+
+export default AnalyzeVisualMediaInspector;
diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/index.ts b/packages/builtin-tool-lobe-agent/src/client/Inspector/index.ts
index adf7f1a6976..c99cc04c7b1 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/index.ts
@@ -1,6 +1,7 @@
import type { BuiltinInspector } from '@lobechat/types';
import { LobeAgentApiName } from '../../types';
+import { AnalyzeVisualMediaInspector } from './AnalyzeVisualMedia';
import { CallSubAgentInspector } from './CallSubAgent';
import { CallSubAgentsInspector } from './CallSubAgents';
import { ClearTodosInspector } from './ClearTodos';
@@ -16,6 +17,7 @@ import { UpdateTodosInspector } from './UpdateTodos';
* of tool calls in the conversation UI.
*/
export const LobeAgentInspectors: Record<string, BuiltinInspector> = {
+ [LobeAgentApiName.analyzeVisualMedia]: AnalyzeVisualMediaInspector as BuiltinInspector,
[LobeAgentApiName.callSubAgent]: CallSubAgentInspector as BuiltinInspector,
[LobeAgentApiName.callSubAgents]: CallSubAgentsInspector as BuiltinInspector,
[LobeAgentApiName.clearTodos]: ClearTodosInspector as BuiltinInspector,
diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.ts
index f542af40ff0..417dbb3b167 100644
--- a/packages/builtin-tool-lobe-agent/src/types.ts
+++ b/packages/builtin-tool-lobe-agent/src/types.ts
@@ -19,6 +19,21 @@ export interface AnalyzeVisualMediaParams {
urls?: string[];
}
+export interface AnalyzeVisualMediaFileSummary {
+ id?: string;
+ name: string;
+ ref: string;
+ type: 'image' | 'video';
+}
+
+export interface AnalyzeVisualMediaState {
+ files?: AnalyzeVisualMediaFileSummary[];
+ model?: string;
+ provider?: string;
+ trigger?: string;
+ usage?: unknown;
+}
+
// ==================== Sub-Agent Tasks ====================
/**
diff --git a/src/components/HtmlPreview/PreviewDrawer.tsx b/src/components/HtmlPreview/PreviewDrawer.tsx
index 5b9ad1854e8..1fc106c417d 100644
--- a/src/components/HtmlPreview/PreviewDrawer.tsx
+++ b/src/components/HtmlPreview/PreviewDrawer.tsx
@@ -1,6 +1,6 @@
import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { exportFile } from '@lobechat/utils/client';
-import { Block, Button, Flexbox, Highlighter, Segmented } from '@lobehub/ui';
+import { Block, Button, Flexbox, Highlighter, HtmlPreview, Segmented } from '@lobehub/ui';
import { Drawer } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Code2, Download, Eye } from 'lucide-react';
@@ -13,13 +13,10 @@ const styles = createStaticStyles(({ css }) => ({
container: css`
height: 100%;
`,
- iframe: css`
- width: 100%;
- height: 100%;
- border: none;
- `,
}));
+const hideHtmlPreviewActions = () => null;
+
interface HtmlPreviewDrawerProps {
content: string;
onClose: () => void;
@@ -104,12 +101,17 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose
>
{mode === 'preview' ? (
<Block className={styles.container}>
- <iframe
- className={styles.iframe}
- sandbox="allow-scripts allow-same-origin"
- srcDoc={content}
+ <HtmlPreview
+ actionsRender={hideHtmlPreviewActions}
+ copyable={false}
+ downloadable={false}
+ style={{ height: '100%' }}
+ styles={{ iframe: { height: '100%' } }}
title={t('HtmlPreview.iframeTitle')}
- />
+ variant={'borderless'}
+ >
+ {content}
+ </HtmlPreview>
</Block>
) : (
<Block className={styles.container}>
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index 2b8344dbed1..f5d4647a0c4 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -171,9 +171,10 @@ export const useErrorContent = (error: any) => {
interface ErrorExtraProps {
data: ErrorMessageData;
error?: AlertProps;
+ onRegenerate?: () => void;
}
-const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) => {
+const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRegenerate }) => {
const error = data.error;
const navigate = useNavigate();
const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);
@@ -181,8 +182,6 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>
const sessionErrorBody = error?.body;
const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;
- if (enableBusinessFeatures && businessChatErrorMessageExtra) return businessChatErrorMessageExtra;
-
if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {
return (
<HeterogeneousAgentStatusGuide
@@ -193,6 +192,8 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>
);
}
+ if (enableBusinessFeatures && businessChatErrorMessageExtra) return businessChatErrorMessageExtra;
+
switch (error?.type) {
case AgentRuntimeErrorType.OllamaServiceUnavailable: {
return <OllamaSetupGuide id={data.id} />;
@@ -234,6 +235,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>
</Highlighter>
) : undefined,
}}
+ onRegenerate={onRegenerate}
/>
);
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
new file mode 100644
index 00000000000..d5fd707e641
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
@@ -0,0 +1,147 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ContentBlock from './ContentBlock';
+
+const continueGenerationMock = vi.fn();
+const deleteDBMessageMock = vi.fn();
+const navigateMock = vi.fn();
+
+vi.mock('@lobehub/ui', () => ({
+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Highlighter: ({ children }: { children?: ReactNode }) => <pre>{children}</pre>,
+ Skeleton: {
+ Button: () => <div>loading</div>,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: {
+ language: 'en-US',
+ resolvedLanguage: 'en-US',
+ },
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => navigateMock,
+}));
+
+vi.mock('@/business/client/hooks/useBusinessErrorAlertConfig', () => ({
+ default: () => undefined,
+}));
+
+vi.mock('@/business/client/hooks/useBusinessErrorContent', () => ({
+ default: () => ({ errorType: undefined, hideMessage: false }),
+}));
+
+vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () => ({
+ default: () => undefined,
+}));
+
+vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({
+ default: ({ agentType, error }: { agentType?: string; error?: { code?: string } }) => (
+ <div>{`guide:${agentType}:${error?.code}`}</div>
+ ),
+}));
+
+vi.mock('@/hooks/useProviderName', () => ({
+ useProviderName: () => 'Mock Provider',
+}));
+
+vi.mock('@/libs/next/dynamic', () => ({
+ default: () => () => <div>dynamic</div>,
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: {
+ enableBusinessFeatures: () => false,
+ },
+ useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/components/ErrorBoundary', () => ({
+ default: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('../../../ChatItem/components/ErrorContent', () => ({
+ default: ({
+ customErrorRender,
+ error,
+ }: {
+ customErrorRender?: (error: Record<string, unknown>) => ReactNode;
+ error?: Record<string, unknown>;
+ }) => <>{customErrorRender ? customErrorRender(error || {}) : error?.message}</>,
+}));
+
+vi.mock('../../components/ImageFileListViewer', () => ({
+ default: () => <div>images</div>,
+}));
+
+vi.mock('../../components/Reasoning', () => ({
+ default: () => <div>reasoning</div>,
+}));
+
+vi.mock('../Tools', () => ({
+ Tools: () => <div>tools</div>,
+}));
+
+vi.mock('./MessageContent', () => ({
+ default: () => <div>message content</div>,
+}));
+
+vi.mock('../../../store', () => ({
+ messageStateSelectors: {
+ isMessageInReasoning: () => () => false,
+ },
+ useConversationStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ continueGeneration: continueGenerationMock,
+ deleteDBMessage: deleteDBMessageMock,
+ }),
+}));
+
+describe('AssistantGroup ContentBlock', () => {
+ beforeEach(() => {
+ continueGenerationMock.mockClear();
+ deleteDBMessageMock.mockClear();
+ navigateMock.mockClear();
+ });
+
+ it('uses the shared message error renderer for heterogeneous agent errors', () => {
+ render(
+ <ContentBlock
+ assistantId="assistant-1"
+ content=""
+ id="block-1"
+ error={
+ {
+ body: {
+ agentType: 'claude-code',
+ code: HeterogeneousAgentSessionErrorCode.RateLimit,
+ message: "You've hit your limit · resets 2:50pm (Asia/Shanghai)",
+ rateLimitInfo: {
+ rateLimitType: 'five_hour',
+ resetsAt: 1_778_741_400,
+ status: 'rejected',
+ },
+ stderr: "You've hit your limit · resets 2:50pm (Asia/Shanghai)",
+ },
+ message: "You've hit your limit · resets 2:50pm (Asia/Shanghai)",
+ type: 'AgentRuntimeError',
+ } as any
+ }
+ />,
+ );
+
+ expect(screen.getByText('guide:claude-code:rate_limit')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
index f2590d47143..31a0cdadab2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
@@ -1,9 +1,9 @@
-import { Flexbox, Highlighter } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { memo, useCallback } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
import { LOADING_FLAT } from '@/const/message';
-import { useErrorContent } from '@/features/Conversation/Error';
+import ErrorMessageExtra, { useErrorContent } from '@/features/Conversation/Error';
import ErrorContent from '../../../ChatItem/components/ErrorContent';
import { messageStateSelectors, useConversationStore } from '../../../store';
@@ -54,21 +54,16 @@ const ContentBlock = memo<ContentBlockProps>(
return (
<ErrorContent
id={id}
+ customErrorRender={(alertError) => (
+ <ErrorMessageExtra
+ data={{ error, id }}
+ error={alertError}
+ onRegenerate={handleRegenerate}
+ />
+ )}
error={
errorContent && error && (content === LOADING_FLAT || !content)
- ? {
- ...errorContent,
- extra: error?.body && (
- <Highlighter
- actionIconSize={'small'}
- language={'json'}
- padding={8}
- variant={'borderless'}
- >
- {JSON.stringify(error?.body, null, 2)}
- </Highlighter>
- ),
- }
+ ? errorContent
: undefined
}
onRegenerate={handleRegenerate}
diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsx
index d00c0dea7ef..578eb45289b 100644
--- a/src/features/Conversation/Messages/components/ContentLoading.tsx
+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx
@@ -8,7 +8,7 @@ import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { type OperationType } from '@/store/chat/slices/operation/types';
-import { shinyTextStyles } from '@/styles/loading';
+import { elapsedTimeStyles, shinyTextStyles } from '@/styles/loading';
const ELAPSED_TIME_THRESHOLD = 2100; // Show elapsed time after 2 seconds
@@ -82,7 +82,9 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
return (
<Flexbox horizontal align={'center'} gap={4}>
<span className={shinyTextStyles.shinyText}>{operationLabel}...</span>
- {showElapsedTime && <span>({elapsedSeconds}s)</span>}
+ {showElapsedTime && (
+ <span className={elapsedTimeStyles.elapsedTime}>({elapsedSeconds}s)</span>
+ )}
</Flexbox>
);
}
diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent.ts
index 156e88bffb8..9d43010b951 100644
--- a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent.ts
+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent.ts
@@ -5,6 +5,24 @@ import { defineFixtures, single, variants } from './_helpers';
export default defineFixtures({
identifier: 'lobe-agent',
fixtures: {
+ analyzeVisualMedia: single({
+ args: {
+ question: 'Describe the primary controls and layout in this interface.',
+ refs: ['msg_devtools.image_1'],
+ },
+ pluginState: {
+ files: [
+ {
+ id: 'image_devtools_interface',
+ name: 'interface-preview.png',
+ ref: 'msg_devtools.image_1',
+ type: 'image',
+ },
+ ],
+ model: 'gpt-5.4',
+ provider: 'openai',
+ },
+ }),
callSubAgent: single({
pluginState: {
task: {
diff --git a/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts b/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts
deleted file mode 100644
index 7da5e01af1e..00000000000
--- a/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { injectSandboxStorageShim } from './HTML';
-
-describe('injectSandboxStorageShim', () => {
- it('should inject the storage shim before user scripts in head', () => {
- const html = `<!DOCTYPE html>
-<html>
-<head>
- <script>localStorage.getItem('snakeHighScore');</script>
-</head>
-<body></body>
-</html>`;
-
- const result = injectSandboxStorageShim(html);
-
- expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeGreaterThan(-1);
- expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeLessThan(
- result.indexOf("localStorage.getItem('snakeHighScore')"),
- );
- });
-
- it('should not inject the storage shim twice', () => {
- const html = '<html><head></head><body></body></html>';
- const result = injectSandboxStorageShim(injectSandboxStorageShim(html));
-
- expect(result.match(/data-lobe-artifact-storage-shim/g)).toHaveLength(1);
- });
-
- it('should not inject into head-like strings inside scripts', () => {
- const html = `<!DOCTYPE html>
-<html>
-<body>
- <script>
- const template = "<head><title>Preview</title></head>";
- </script>
-</body>
-</html>`;
-
- const result = injectSandboxStorageShim(html);
-
- expect(result).toContain('const template = "<head><title>Preview</title></head>";');
- expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeLessThan(
- result.indexOf('const template'),
- );
- });
-});
diff --git a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
index 85c794f591a..5df7510a493 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
@@ -1,127 +1,35 @@
+import { HtmlPreview } from '@lobehub/ui';
import { memo } from 'react';
interface HTMLRendererProps {
+ animated?: boolean;
height?: string;
htmlContent: string;
width?: string;
}
-const SANDBOX_STORAGE_SHIM = `<script data-lobe-artifact-storage-shim>
-(() => {
- if (window.__lobeArtifactStorageShim) return;
- Object.defineProperty(window, '__lobeArtifactStorageShim', { value: true });
-
- const createStorage = () => {
- const data = Object.create(null);
-
- return {
- clear() {
- for (const key of Object.keys(data)) delete data[key];
- },
- getItem(key) {
- const normalizedKey = String(key);
- return Object.prototype.hasOwnProperty.call(data, normalizedKey) ? data[normalizedKey] : null;
- },
- key(index) {
- return Object.keys(data)[index] ?? null;
- },
- get length() {
- return Object.keys(data).length;
- },
- removeItem(key) {
- delete data[String(key)];
- },
- setItem(key, value) {
- data[String(key)] = String(value);
- },
- };
- };
-
- const defineStorage = (name) => {
- try {
- void window[name];
- return;
- } catch {
- Object.defineProperty(window, name, {
- configurable: true,
- value: createStorage(),
- });
- }
- };
-
- defineStorage('localStorage');
- defineStorage('sessionStorage');
-})();
-</script>`;
-
-const SCRIPT_TAG_REGEX = /<script\b/i;
-const HEAD_TAG_REGEX = /<head(?:\s[^>]*)?>/i;
-const HTML_TAG_REGEX = /<html(?:\s[^>]*)?>/i;
-
-const findTagBeforeFirstScript = (htmlContent: string, tagRegex: RegExp) => {
- const firstScriptIndex = htmlContent.search(SCRIPT_TAG_REGEX);
- const searchableContent =
- firstScriptIndex === -1 ? htmlContent : htmlContent.slice(0, firstScriptIndex);
- const match = searchableContent.match(tagRegex);
-
- if (!match?.[0] || match.index === undefined) return;
-
- return {
- index: match.index,
- value: match[0],
- };
-};
-
-const insertAfterTag = (htmlContent: string, tag: { index: number; value: string }) => {
- const insertIndex = tag.index + tag.value.length;
- return `${htmlContent.slice(0, insertIndex)}\n${SANDBOX_STORAGE_SHIM}${htmlContent.slice(
- insertIndex,
- )}`;
-};
-
-export const injectSandboxStorageShim = (htmlContent: string) => {
- if (htmlContent.includes('data-lobe-artifact-storage-shim')) return htmlContent;
-
- const headTag = findTagBeforeFirstScript(htmlContent, HEAD_TAG_REGEX);
- if (headTag) return insertAfterTag(htmlContent, headTag);
-
- const htmlTag = findTagBeforeFirstScript(htmlContent, HTML_TAG_REGEX);
- if (htmlTag) {
- const insertIndex = htmlTag.index + htmlTag.value.length;
- return `${htmlContent.slice(0, insertIndex)}\n<head>${SANDBOX_STORAGE_SHIM}</head>${htmlContent.slice(
- insertIndex,
- )}`;
- }
-
- return `${SANDBOX_STORAGE_SHIM}\n${htmlContent}`;
-};
-
-// Security boundary: the iframe runs in a unique opaque origin because the
-// sandbox attribute does NOT include `allow-same-origin`. This blocks
-// `window.parent.*` access (the GHSA-xq4x-622m-q8fq XSS-to-RCE path on
-// Electron), denies access to the app's cookies / storage, and prevents
-// top-level navigation, while still allowing scripts and styles to run so
-// that LLM-generated single-file HTML demos (Tailwind CDN, p5.js, three.js,
-// vanilla JS, etc.) actually work.
-//
-// IMPORTANT — do NOT add the following capabilities:
-// - `allow-same-origin`: combined with `allow-scripts` it lets the iframe
-// remove its own sandbox and reintroduces the original XSS-to-RCE.
-// - `allow-popups`: in the Electron desktop app `setWindowOpenHandler`
-// unconditionally forwards `window.open(url)` to `shell.openExternal`,
-// which means untrusted artifact scripts could launch arbitrary
-// protocol handlers / external URLs with zero user interaction.
-// - `allow-top-navigation` (any flavor): would let the artifact hijack
-// the host window.
-const HTMLRenderer = memo<HTMLRendererProps>(({ htmlContent, width = '100%', height = '100%' }) => {
- return (
- <iframe
- sandbox="allow-scripts allow-forms allow-modals"
- srcDoc={injectSandboxStorageShim(htmlContent)}
- style={{ border: 'none', height, width }}
- title="html-renderer"
- />
- );
-});
+const hideHtmlPreviewActions = () => null;
+
+const HTMLRenderer = memo<HTMLRendererProps>(
+ ({ animated, htmlContent, width = '100%', height = '100%' }) => {
+ return (
+ <HtmlPreview
+ actionsRender={hideHtmlPreviewActions}
+ animated={animated}
+ copyable={false}
+ downloadable={false}
+ shadow={false}
+ style={{ height, minHeight: 0, overflow: 'hidden', width }}
+ variant={'borderless'}
+ styles={{
+ content: { height: '100%' },
+ iframe: { height: '100%' },
+ }}
+ >
+ {htmlContent}
+ </HtmlPreview>
+ );
+ },
+);
export default HTMLRenderer;
diff --git a/src/features/Portal/Artifacts/Body/Renderer/index.tsx b/src/features/Portal/Artifacts/Body/Renderer/index.tsx
index 0f63b55d26d..f92b5a60bc4 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/index.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/index.tsx
@@ -8,28 +8,30 @@ import SVGRender from './SVG';
const ReactRenderer = dynamic(() => import('./React'), { ssr: false });
-const Renderer = memo<{ content: string; type?: string }>(({ content, type }) => {
- switch (type) {
- case 'application/lobe.artifacts.react': {
- return <ReactRenderer code={content} />;
+const Renderer = memo<{ animated?: boolean; content: string; type?: string }>(
+ ({ animated, content, type }) => {
+ switch (type) {
+ case 'application/lobe.artifacts.react': {
+ return <ReactRenderer code={content} />;
+ }
+
+ case 'image/svg+xml': {
+ return <SVGRender content={content} />;
+ }
+
+ case 'application/lobe.artifacts.mermaid': {
+ return <Mermaid variant={'borderless'}>{content}</Mermaid>;
+ }
+
+ case 'text/markdown': {
+ return <Markdown style={{ overflow: 'auto' }}>{content}</Markdown>;
+ }
+
+ default: {
+ return <HTMLRenderer animated={animated} htmlContent={content} />;
+ }
}
-
- case 'image/svg+xml': {
- return <SVGRender content={content} />;
- }
-
- case 'application/lobe.artifacts.mermaid': {
- return <Mermaid variant={'borderless'}>{content}</Mermaid>;
- }
-
- case 'text/markdown': {
- return <Markdown style={{ overflow: 'auto' }}>{content}</Markdown>;
- }
-
- default: {
- return <HTMLRenderer htmlContent={content} />;
- }
- }
-});
+ },
+);
export default Renderer;
diff --git a/src/features/Portal/Artifacts/Body/index.tsx b/src/features/Portal/Artifacts/Body/index.tsx
index 50eb6e72f32..d957b9e805f 100644
--- a/src/features/Portal/Artifacts/Body/index.tsx
+++ b/src/features/Portal/Artifacts/Body/index.tsx
@@ -8,6 +8,8 @@ import { ArtifactType } from '@/types/artifact';
import Renderer from './Renderer';
+const TEXT_HTML_ARTIFACT_TYPE = 'text/html';
+
const ArtifactsUI = memo(() => {
const [
messageId,
@@ -32,13 +34,21 @@ const ArtifactsUI = memo(() => {
];
});
+ const isHtmlArtifact =
+ !artifactType ||
+ artifactType === ArtifactType.Default ||
+ artifactType === TEXT_HTML_ARTIFACT_TYPE;
+
useEffect(() => {
- // when message generating , check whether the artifact is closed
- // if close, move the display mode to preview
- if (isMessageGenerating && isArtifactTagClosed && displayMode === ArtifactDisplayMode.Code) {
+ // Prefer live preview while HTML artifacts stream; reset stale code mode from previous artifacts.
+ if (
+ isMessageGenerating &&
+ displayMode === ArtifactDisplayMode.Code &&
+ (isArtifactTagClosed || (isHtmlArtifact && !isArtifactTagClosed))
+ ) {
useChatStore.setState({ portalArtifactDisplayMode: ArtifactDisplayMode.Preview });
}
- }, [isMessageGenerating, displayMode, isArtifactTagClosed]);
+ }, [isMessageGenerating, displayMode, isArtifactTagClosed, isHtmlArtifact]);
const language = useMemo(() => {
switch (artifactType) {
@@ -60,12 +70,13 @@ const ArtifactsUI = memo(() => {
}
}, [artifactType, artifactCodeLanguage]);
- // show code when the artifact is not closed or the display mode is code or the artifact type is code
+ // Keep incomplete non-HTML artifacts in code mode, but let HTML stream into the preview.
const showCode =
- !isArtifactTagClosed ||
- displayMode === ArtifactDisplayMode.Code ||
- artifactType === ArtifactType.Code;
- const isStreamingCode = isMessageGenerating && !isArtifactTagClosed;
+ artifactType === ArtifactType.Code ||
+ (!isArtifactTagClosed && !isHtmlArtifact) ||
+ (displayMode === ArtifactDisplayMode.Code && !(isHtmlArtifact && !isArtifactTagClosed));
+ const isStreamingCode = isMessageGenerating && showCode && !isArtifactTagClosed;
+ const isStreamingArtifact = isMessageGenerating && !isArtifactTagClosed;
// make sure the message and id is valid
if (!messageId) return;
@@ -90,7 +101,7 @@ const ArtifactsUI = memo(() => {
</Highlighter>
</Flexbox>
) : (
- <Renderer content={artifactContent} type={artifactType} />
+ <Renderer animated={isStreamingArtifact} content={artifactContent} type={artifactType} />
)}
</Flexbox>
);
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 688467ea079..947f24b4011 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -51,6 +51,10 @@ export default {
'builtins.lobe-agent-management.render.installPlugin.plugin': 'Plugin',
'builtins.lobe-agent-management.render.installPlugin.success': 'Installed successfully',
'builtins.lobe-agent-management.title': 'Agent Manager',
+ 'builtins.lobe-agent.apiName.analyzeVisualMedia': 'Analyze visual media',
+ 'builtins.lobe-agent.apiName.analyzeVisualMedia.mediaCount': '{{count}} media',
+ 'builtins.lobe-agent.apiName.analyzeVisualMedia.result':
+ 'Analyze visual media: <question>{{question}}</question>',
'builtins.lobe-agent.apiName.callSubAgent': 'Call sub-agent',
'builtins.lobe-agent.apiName.callSubAgent.completed': 'Sub-agent dispatched: ',
'builtins.lobe-agent.apiName.callSubAgent.loading': 'Dispatching sub-agent: ',
diff --git a/src/server/services/agentRuntime/OperationTraceRecorder.ts b/src/server/services/agentRuntime/OperationTraceRecorder.ts
index ed4dabf2c3f..deb95dc66db 100644
--- a/src/server/services/agentRuntime/OperationTraceRecorder.ts
+++ b/src/server/services/agentRuntime/OperationTraceRecorder.ts
@@ -74,7 +74,9 @@ export class OperationTraceRecorder {
this.initPartialHeader(partial, params.agentState);
if (!partial.steps) partial.steps = [];
- partial.steps.push(this.buildStepSnapshot(params));
+ const newStep = this.buildStepSnapshot(params);
+ this.deduplicateCeSnapshot(newStep, partial.steps);
+ partial.steps.push(newStep);
await this.store.savePartial(operationId, partial);
} catch (e) {
@@ -108,15 +110,10 @@ export class OperationTraceRecorder {
// existing record instead of pushing a duplicate stepIndex —
// duplicates corrupt ordering and per-step metrics in trace
// reconstruction.
- const existing = partial.steps.find(
- (s) => s.stepIndex === params.failedStep!.stepIndex,
- );
+ const existing = partial.steps.find((s) => s.stepIndex === params.failedStep!.stepIndex);
if (existing) {
if (params.error) {
- existing.events = [
- ...(existing.events ?? []),
- { error: params.error, type: 'error' },
- ];
+ existing.events = [...(existing.events ?? []), { error: params.error, type: 'error' }];
}
} else {
const now = Date.now();
@@ -174,6 +171,40 @@ export class OperationTraceRecorder {
}
}
+ /**
+ * Strip `contextEngine` input/output fields that are identical to the most-recently
+ * stored values in previous steps. The viewer reconstructs the full snapshot by
+ * walking back through the step list (same pattern as messagesBaseline + messagesDelta).
+ */
+ private deduplicateCeSnapshot(step: StepSnapshot, prevSteps: StepSnapshot[]): void {
+ if (!step.contextEngine) return;
+
+ let lastInputJson: string | undefined;
+ let lastOutputJson: string | undefined;
+
+ for (let i = prevSteps.length - 1; i >= 0; i--) {
+ const prev = prevSteps[i];
+ if (!prev.contextEngine) continue;
+ if (lastInputJson === undefined && prev.contextEngine.input !== undefined) {
+ lastInputJson = JSON.stringify(prev.contextEngine.input);
+ }
+ if (lastOutputJson === undefined && prev.contextEngine.output !== undefined) {
+ lastOutputJson = JSON.stringify(prev.contextEngine.output);
+ }
+ if (lastInputJson !== undefined && lastOutputJson !== undefined) break;
+ }
+
+ const storeInput =
+ lastInputJson === undefined || JSON.stringify(step.contextEngine.input) !== lastInputJson;
+ const storeOutput =
+ lastOutputJson === undefined || JSON.stringify(step.contextEngine.output) !== lastOutputJson;
+
+ step.contextEngine = {
+ ...(storeInput ? { input: step.contextEngine.input } : {}),
+ ...(storeOutput ? { output: step.contextEngine.output } : {}),
+ };
+ }
+
private initPartialHeader(partial: any, agentState: any): void {
if (partial.startedAt) return;
partial.startedAt = Date.now();
@@ -206,11 +237,21 @@ export class OperationTraceRecorder {
const isBaseline = stepIndex === 0 || isCompression;
const messagesDelta = afterMessages.slice(prevMessages.length);
+ // Extract context_engine_result into contextEngine (dedicated typed field).
+ // CE data is structural state, not a streaming event — it lives separately
+ // from events and uses the same delta pattern as messagesBaseline/messagesDelta.
+ const rawEvents = (stepResult.events as any[]) ?? [];
+ const ceEvent = rawEvents.find((e: any) => e.type === 'context_engine_result') as any;
+ const contextEngine: StepSnapshot['contextEngine'] = ceEvent
+ ? { input: ceEvent.input, output: ceEvent.output }
+ : undefined;
+
// Strip heavy/redundant data from events before persisting to snapshot.
+ // context_engine_result is excluded — stored in contextEngine instead.
const snapshotEvents = [
...beforeStepSignalEvents,
- ...((stepResult.events as any[])
- ?.filter((e) => e.type !== 'llm_stream')
+ ...rawEvents
+ .filter((e) => e.type !== 'llm_stream' && e.type !== 'context_engine_result')
.map((e) => {
if (e.type === 'done' && e.finalState) {
// Remove reconstructible fields from finalState:
@@ -229,7 +270,7 @@ export class OperationTraceRecorder {
return { ...e, finalState: restState };
}
return e;
- }) ?? []),
+ }),
...afterStepSignalEvents,
];
@@ -254,6 +295,7 @@ export class OperationTraceRecorder {
return {
activatedStepToolsDelta,
+ contextEngine,
completedAt: Date.now(),
content: presentation.content,
context: {
diff --git a/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
index 263e5d61c2d..47048e81350 100644
--- a/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
+++ b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
@@ -349,6 +349,189 @@ describe('OperationTraceRecorder', () => {
});
});
+ describe('contextEngine dedup (via appendStep)', () => {
+ let store: ReturnType<typeof buildStore>;
+ let recorder: OperationTraceRecorder;
+
+ beforeEach(() => {
+ store = buildStore();
+ recorder = new OperationTraceRecorder(store as any);
+ });
+
+ const buildCeEvent = (overrides: Record<string, unknown> = {}) => ({
+ input: { messages: ['hello'] },
+ output: { tokens: 42 },
+ type: 'context_engine_result',
+ ...overrides,
+ });
+
+ const appendStepWithCe = (ceEvent: Record<string, unknown>, prevStepsInStore: any[]) => {
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: prevStepsInStore });
+ return recorder.appendStep('op-ce', {
+ afterStepSignalEvents: [],
+ agentState: { messages: [] },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'user_input' },
+ externalRetryCount: 0,
+ presentation: buildPresentation(),
+ startedAt: 1000,
+ stepIndex: prevStepsInStore.length,
+ stepResult: {
+ events: [ceEvent],
+ newState: { activatedStepTools: [], messages: [] },
+ },
+ });
+ };
+
+ const getSavedStep = (newStepIndex: number) => {
+ const saved = store.savePartial.mock.calls[0][1];
+ return saved.steps.find((s: any) => s.stepIndex === newStepIndex);
+ };
+
+ it('extracts CE event into contextEngine, not in events', async () => {
+ await appendStepWithCe(buildCeEvent(), []);
+
+ const step = getSavedStep(0);
+ // CE data lives in contextEngine, not events
+ expect(step.contextEngine).toBeDefined();
+ expect(step.events.some((e: any) => e.type === 'context_engine_result')).toBe(false);
+ });
+
+ it('keeps both input and output on the first step (no previous CE to compare against)', async () => {
+ await appendStepWithCe(buildCeEvent(), []);
+
+ const step = getSavedStep(0);
+ expect(step.contextEngine.input).toEqual({ messages: ['hello'] });
+ expect(step.contextEngine.output).toEqual({ tokens: 42 });
+ });
+
+ it('strips both input and output when both are identical to the previous step', async () => {
+ const prevStep = {
+ contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ };
+ await appendStepWithCe(buildCeEvent(), [prevStep]);
+
+ const step = getSavedStep(1);
+ expect(step.contextEngine.input).toBeUndefined();
+ expect(step.contextEngine.output).toBeUndefined();
+ });
+
+ it('strips only input when input matches previous but output differs', async () => {
+ const prevStep = {
+ contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ };
+ await appendStepWithCe(
+ buildCeEvent({ input: { messages: ['hello'] }, output: { tokens: 99 } }),
+ [prevStep],
+ );
+
+ const step = getSavedStep(1);
+ expect(step.contextEngine.input).toBeUndefined();
+ expect(step.contextEngine.output).toEqual({ tokens: 99 });
+ });
+
+ it('strips only output when output matches previous but input differs', async () => {
+ const prevStep = {
+ contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ };
+ await appendStepWithCe(
+ buildCeEvent({ input: { messages: ['world'] }, output: { tokens: 42 } }),
+ [prevStep],
+ );
+
+ const step = getSavedStep(1);
+ expect(step.contextEngine.input).toEqual({ messages: ['world'] });
+ expect(step.contextEngine.output).toBeUndefined();
+ });
+
+ it('keeps both when both input and output differ from previous', async () => {
+ const prevStep = {
+ contextEngine: { input: { messages: ['old'] }, output: { tokens: 10 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ };
+ await appendStepWithCe(
+ buildCeEvent({ input: { messages: ['new'] }, output: { tokens: 20 } }),
+ [prevStep],
+ );
+
+ const step = getSavedStep(1);
+ expect(step.contextEngine.input).toEqual({ messages: ['new'] });
+ expect(step.contextEngine.output).toEqual({ tokens: 20 });
+ });
+
+ it('walks back past intermediate steps without CE to find last stored values', async () => {
+ const prevSteps = [
+ {
+ contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ // step 1 has no contextEngine — dedup must skip it and walk back to step 0
+ { stepIndex: 1, stepType: 'call_tool' },
+ ];
+ await appendStepWithCe(buildCeEvent(), prevSteps);
+
+ const step = getSavedStep(2);
+ expect(step.contextEngine.input).toBeUndefined();
+ expect(step.contextEngine.output).toBeUndefined();
+ });
+
+ it('resolves input and output independently from different previous steps', async () => {
+ // step 0 stored only input (output was stripped vs its own predecessor)
+ // step 1 stored only output (input was stripped vs step 0)
+ // New step 2 has the same input as step 0 and same output as step 1 → both deduped
+ const prevSteps = [
+ { contextEngine: { input: { messages: ['hello'] } }, stepIndex: 0, stepType: 'call_llm' },
+ { contextEngine: { output: { tokens: 42 } }, stepIndex: 1, stepType: 'call_llm' },
+ ];
+ await appendStepWithCe(
+ buildCeEvent({ input: { messages: ['hello'] }, output: { tokens: 42 } }),
+ prevSteps,
+ );
+
+ const step = getSavedStep(2);
+ expect(step.contextEngine.input).toBeUndefined();
+ expect(step.contextEngine.output).toBeUndefined();
+ });
+
+ it('sets contextEngine to undefined when the step has no context_engine_result event', async () => {
+ const prevStep = {
+ contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ };
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [prevStep] });
+
+ await recorder.appendStep('op-ce', {
+ afterStepSignalEvents: [],
+ agentState: { messages: [] },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'tool_result' },
+ externalRetryCount: 0,
+ presentation: buildPresentation({ stepType: 'call_tool' }),
+ startedAt: 1000,
+ stepIndex: 1,
+ stepResult: {
+ events: [{ type: 'tool_result', id: 'tc-1' }],
+ newState: { activatedStepTools: [], messages: [] },
+ },
+ });
+
+ const saved = store.savePartial.mock.calls[0][1];
+ const newStep = saved.steps.find((s: any) => s.stepIndex === 1);
+ expect(newStep.contextEngine).toBeUndefined();
+ expect(newStep.events.some((e: any) => e.type === 'context_engine_result')).toBe(false);
+ expect(newStep.events.some((e: any) => e.type === 'tool_result')).toBe(true);
+ });
+ });
+
describe('store=null (snapshot tracing disabled)', () => {
it('appendStep is a no-op', async () => {
const recorder = new OperationTraceRecorder(null);
diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.ts
index e14dc28e8f6..839ea32b5e0 100644
--- a/src/store/chat/slices/portal/selectors.test.ts
+++ b/src/store/chat/slices/portal/selectors.test.ts
@@ -387,6 +387,30 @@ ${htmlContent}
expect(chatPortalSelectors.artifactCode('test-id')(state)).toBe(htmlContent);
});
+ it('should remove an opening markdown code fence while the artifact streams', () => {
+ const htmlContent = `<!DOCTYPE html>
+<html>
+<body>
+ <div>Streaming content</div>`;
+ const state = createState({
+ dbMessagesMap: {
+ 'test-id_null': [
+ {
+ id: 'test-id',
+ content: `<lobeArtifact type="text/html">
+\`\`\`html
+${htmlContent}`,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ role: 'user',
+ sessionId: 'test-id',
+ } as UIChatMessage,
+ ],
+ },
+ });
+ 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';
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index a8d02a01e61..a697a51ac94 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -66,6 +66,14 @@ const artifactCodeLanguage = (s: ChatStoreState) => currentArtifact(s)?.language
// Escape special regex characters in a string
const escapeRegExp = (str: string) => str.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+const CODE_FENCE_START_REGEX = /^\s*```[^\n]*(?:\n|$)/;
+const CODE_FENCE_END_REGEX = /\n```\s*$/;
+
+const unwrapArtifactCodeBlock = (content: string) => {
+ if (!CODE_FENCE_START_REGEX.test(content)) return content;
+
+ return content.replace(CODE_FENCE_START_REGEX, '').replace(CODE_FENCE_END_REGEX, '');
+};
const artifactMessageContent = (id: string) => (s: ChatStoreState) => {
const message = dbMessageSelectors.getDbMessageById(id)(s);
@@ -84,8 +92,7 @@ const artifactCode = (id: string, identifier?: string) => (s: ChatStoreState) =>
const result = messageContent.match(regex);
let content = result?.groups?.content || '';
- // Remove markdown code block if content is wrapped
- content = content.replace(/^\s*```[^\n]*\n([\S\s]*?)\n```\s*$/, '$1');
+ content = unwrapArtifactCodeBlock(content);
return content;
};
diff --git a/src/styles/loading.ts b/src/styles/loading.ts
index 2f2c7c60bd9..8ded54b0aae 100644
--- a/src/styles/loading.ts
+++ b/src/styles/loading.ts
@@ -37,6 +37,12 @@ const shine = keyframes`
}
`;
+export const elapsedTimeStyles = createStaticStyles(({ css, cssVar }) => ({
+ elapsedTime: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
export const shinyTextStyles = createStaticStyles(({ css, cssVar }) => ({
shinyText: css`
color: color-mix(in srgb, ${cssVar.colorText} 45%, transparent);