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(conversation): improve workflow display when user intervention is pending (#13847)

Inneibc7b798dbbd0
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 50a465436e3..660e44ab8ad 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -465,6 +465,7 @@
"viewMode.fullWidth": "Full Width",
"viewMode.normal": "Standard",
"viewMode.wideScreen": "Widescreen",
+ "workflow.awaitingConfirmation": "Awaiting your confirmation",
"workflow.failedSuffix": "(failed)",
"workflow.thoughtForDuration": "Thought for {{duration}}",
"workflow.toolDisplayName.activateDevice": "Activated device",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 6237f185fc9..1b9bf7e8eae 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -465,6 +465,7 @@
"viewMode.fullWidth": "全宽显示",
"viewMode.normal": "普通",
"viewMode.wideScreen": "宽屏",
+ "workflow.awaitingConfirmation": "需要你确认",
"workflow.failedSuffix": "(失败)",
"workflow.thoughtForDuration": "思考了 {{duration}}",
"workflow.toolDisplayName.activateDevice": "激活了设备",
diff --git a/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx b/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
index 26cdf495a9a..c85e884e1a7 100644
--- a/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
+++ b/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
@@ -9,7 +9,7 @@ import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '@/styles';
-import type { ActivateToolsParams, ActivateToolsState } from '../../../types';
+import type { ActivatedToolInfo, ActivateToolsParams, ActivateToolsState } from '../../../types';
const styles = createStaticStyles(({ css }) => ({
notFoundHint: css`
@@ -45,6 +45,10 @@ export const ActivateToolsInspector = memo<
const identifiers = args?.identifiers || partialArgs?.identifiers;
const activatedTools = pluginState?.activatedTools;
const notFoundList = pluginState?.notFound ?? [];
+ const requestedTools: ActivatedToolInfo[] =
+ identifiers?.map((id) => ({ apiCount: 0, identifier: id, name: id })) ?? [];
+ const visibleTools =
+ activatedTools && activatedTools.length > 0 ? activatedTools : requestedTools;
// Streaming / Loading: show identifiers from arguments
if (isArgumentsStreaming || isLoading) {
@@ -89,9 +93,9 @@ export const ActivateToolsInspector = memo<
</Flexbox>
</Tooltip>
)}
- {activatedTools && activatedTools.length > 0 && (
+ {visibleTools.length > 0 && (
<span className={styles.tools}>
- {activatedTools.map((tool) => (
+ {visibleTools.map((tool) => (
<span className={styles.tool} key={tool.identifier}>
{tool.avatar && <Avatar avatar={tool.avatar} size={18} title={tool.name} />}
<span>{tool.name}</span>
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
new file mode 100644
index 00000000000..be45ed5e1e8
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
@@ -0,0 +1,100 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import FallbackIntervention from './Fallback';
+
+const metaMap: Record<string, { avatar?: string; title?: string }> = {
+ 'calculator': { title: 'Calculator' },
+ 'lobe-activator': { avatar: '🛠', title: 'Tools & Skills Activator' },
+ 'search': { title: 'Web Search' },
+};
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button {...props}>{children}</button>
+ ),
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ Icon: () => <span>icon</span>,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { count?: number; defaultValue?: string }) =>
+ (
+ ({
+ 'builtins.lobe-activator.apiName.activateTools': 'Activate Tools',
+ 'builtins.lobe-activator.title': 'Tools & Skills Activator',
+ 'edit': 'Edit',
+ }) as Record<string, string>
+ )[key] ||
+ (key === 'tool.intervention.viewParameters'
+ ? `View parameters (${options?.count ?? 0})`
+ : options?.defaultValue || key),
+ }),
+}));
+
+vi.mock('@/store/tool/selectors', () => ({
+ toolSelectors: {
+ getMetaById: (id: string) => () => metaMap[id],
+ },
+}));
+
+vi.mock('@/store/tool', () => ({
+ pluginHelpers: {
+ getPluginTitle: (meta?: { title?: string }) => meta?.title,
+ },
+ useToolStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ toolInterventionSelectors: {
+ approvalMode: () => 'manual',
+ },
+}));
+
+vi.mock('../../../../../store', () => ({
+ useConversationStore: (
+ selector: (state: { updatePluginArguments: ReturnType<typeof vi.fn> }) => unknown,
+ ) => selector({ updatePluginArguments: vi.fn() }),
+}));
+
+vi.mock('../Arguments', () => ({
+ default: ({ arguments: args }: { arguments?: string }) => <pre>{args}</pre>,
+}));
+
+vi.mock('./ApprovalActions', () => ({
+ default: () => <div>approval-actions</div>,
+}));
+
+vi.mock('./KeyValueEditor', () => ({
+ default: () => <div>editor</div>,
+}));
+
+describe('FallbackIntervention', () => {
+ it('shows requested tool names for activateTools interventions', () => {
+ render(
+ <FallbackIntervention
+ apiName="activateTools"
+ assistantGroupId="assistant-group-1"
+ id="message-1"
+ identifier="lobe-activator"
+ requestArgs='{"identifiers":["search","calculator"]}'
+ toolCallId="tool-call-1"
+ />,
+ );
+
+ expect(
+ screen.getByText('Tools & Skills Activator → Activate Tools (Web Search, Calculator)'),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx
index 8c68a80b9fa..0785af5a73f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx
@@ -1,7 +1,13 @@
+import {
+ type ActivateToolsParams,
+ ActivatorApiName,
+ LobeActivatorIdentifier,
+} from '@lobechat/builtin-tool-activator';
import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';
import { safeParseJSON } from '@lobechat/utils';
import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronRight, Edit3Icon } from 'lucide-react';
import { memo, Suspense, useCallback, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
@@ -75,6 +81,28 @@ const FallbackIntervention = memo<FallbackInterventionProps>(
const parsedArgs = useMemo(() => safeParseJSON(requestArgs || '') ?? {}, [requestArgs]);
const argCount = typeof parsedArgs === 'object' ? Object.keys(parsedArgs).length : 0;
+ const requestedToolIdentifiers = useMemo(() => {
+ if (identifier !== LobeActivatorIdentifier || apiName !== ActivatorApiName.activateTools) {
+ return [];
+ }
+
+ const identifiers = (parsedArgs as ActivateToolsParams | undefined)?.identifiers;
+ if (!Array.isArray(identifiers)) return [];
+
+ return identifiers.filter(
+ (item): item is string => typeof item === 'string' && !!item.trim(),
+ );
+ }, [apiName, identifier, parsedArgs]);
+ const requestedToolNames = useToolStore(
+ (s) =>
+ requestedToolIdentifiers.map((toolIdentifier) => {
+ const meta = toolSelectors.getMetaById(toolIdentifier)(s);
+ return pluginHelpers.getPluginTitle(meta) ?? meta?.title ?? toolIdentifier;
+ }),
+ isEqual,
+ );
+ const actionTitleSuffix =
+ requestedToolNames.length > 0 ? ` (${requestedToolNames.join(', ')})` : '';
const handleCancel = useCallback(() => {
setIsEditing(false);
@@ -128,6 +156,7 @@ const FallbackIntervention = memo<FallbackInterventionProps>(
{pluginMeta?.avatar && <span className={styles.avatar}>{pluginMeta.avatar}</span>}
<span>
{toolTitle} → {actionTitle}
+ {actionTitleSuffix}
</span>
</Flexbox>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
index e1659b41a14..1c8bcbeae62 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
@@ -27,6 +27,7 @@ interface GroupChildrenProps {
blocks: AssistantContentBlock[];
content?: string;
contentId?: string;
+ defaultWorkflowExpanded?: boolean;
disableEditing?: boolean;
id: string;
messageIndex: number;
@@ -160,7 +161,7 @@ const partitionBlocks = (
};
const Group = memo<GroupChildrenProps>(
- ({ blocks, contentId, disableEditing, messageIndex, id, content }) => {
+ ({ blocks, contentId, defaultWorkflowExpanded, disableEditing, messageIndex, id, content }) => {
const [isCollapsed, isGenerating] = useConversationStore((s) => [
messageStateSelectors.isMessageCollapsed(id)(s),
messageStateSelectors.isMessageGenerating(id)(s),
@@ -197,6 +198,7 @@ const Group = memo<GroupChildrenProps>(
<WorkflowCollapse
assistantMessageId={id}
blocks={workingBlocks}
+ defaultStreamingExpanded={defaultWorkflowExpanded}
disableEditing={disableEditing}
workflowChromeComplete={workflowChromeComplete}
/>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
new file mode 100644
index 00000000000..e5f71eea6fd
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
@@ -0,0 +1,181 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { ComponentType, ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { AssistantContentBlock } from '@/types/index';
+
+import WorkflowCollapse from './WorkflowCollapse';
+
+let mockIsGenerating = true;
+
+vi.mock('@lobehub/ui', () => ({
+ Accordion: ({ children, expandedKeys }: { children?: ReactNode; expandedKeys?: string[] }) => (
+ <div data-expanded-keys={JSON.stringify(expandedKeys ?? [])} data-testid="workflow-accordion">
+ {children}
+ </div>
+ ),
+ AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) => (
+ <div>
+ <div>{title}</div>
+ <div>{children}</div>
+ </div>
+ ),
+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Icon: ({ icon: IconComponent }: { icon?: ComponentType }) =>
+ IconComponent ? <IconComponent /> : <div />,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('motion/react', () => ({
+ AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ m: {
+ div: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { defaultValue?: string }) =>
+ (
+ ({
+ 'workflow.awaitingConfirmation': 'Awaiting your confirmation',
+ 'workflow.working': 'Working...',
+ }) as Record<string, string>
+ )[key] ||
+ options?.defaultValue ||
+ key,
+ }),
+}));
+
+vi.mock('@/components/NeuralNetworkLoading', () => ({
+ default: () => <div>loading</div>,
+}));
+
+vi.mock('@/hooks/useAutoScroll', () => ({
+ useAutoScroll: () => ({
+ handleScroll: vi.fn(),
+ ref: { current: null },
+ }),
+}));
+
+vi.mock('@/styles', () => ({
+ shinyTextStyles: {
+ shinyText: 'shiny-text',
+ },
+}));
+
+vi.mock('../../../store', () => ({
+ messageStateSelectors: {
+ isMessageGenerating: () => () => mockIsGenerating,
+ },
+ useConversationStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('./WorkflowExpandedList', () => ({
+ default: () => <div>workflow-expanded-list</div>,
+}));
+
+const makeBlocks = (toolOverrides: Record<string, unknown> = {}): AssistantContentBlock[] => [
+ {
+ content: '',
+ id: 'block-1',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"workflow"}',
+ id: 'tool-1',
+ identifier: 'search',
+ type: 'builtin',
+ ...toolOverrides,
+ } as any,
+ ],
+ } as AssistantContentBlock,
+];
+
+const getExpandedKeys = () =>
+ screen.getByTestId('workflow-accordion').getAttribute('data-expanded-keys');
+
+describe('WorkflowCollapse', () => {
+ afterEach(() => {
+ cleanup();
+ mockIsGenerating = true;
+ vi.useRealTimers();
+ });
+
+ it('defaults to expanded while streaming', () => {
+ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />);
+
+ expect(getExpandedKeys()).toBe('["workflow"]');
+ });
+
+ it('respects defaultStreamingExpanded={false} while streaming', () => {
+ render(
+ <WorkflowCollapse
+ assistantMessageId="msg-1"
+ blocks={makeBlocks()}
+ defaultStreamingExpanded={false}
+ />,
+ );
+
+ expect(getExpandedKeys()).toBe('[]');
+ });
+
+ it('auto expands and switches the header when confirmation is pending', async () => {
+ render(
+ <WorkflowCollapse
+ assistantMessageId="msg-1"
+ blocks={makeBlocks({ intervention: { status: 'pending' } })}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(getExpandedKeys()).toBe('["workflow"]');
+ });
+
+ expect(screen.getByText('Awaiting your confirmation')).toBeInTheDocument();
+ expect(screen.queryByText('Working...')).not.toBeInTheDocument();
+ });
+
+ it('pauses and hides elapsed time while confirmation is pending', () => {
+ vi.useFakeTimers();
+
+ const { rerender } = render(
+ <WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />,
+ );
+
+ act(() => {
+ vi.advanceTimersByTime(3000);
+ });
+
+ expect(screen.getByText('(3s)')).toBeInTheDocument();
+
+ rerender(
+ <WorkflowCollapse
+ assistantMessageId="msg-1"
+ blocks={makeBlocks({ intervention: { status: 'pending' } })}
+ />,
+ );
+
+ expect(screen.queryByText('(3s)')).not.toBeInTheDocument();
+
+ act(() => {
+ vi.advanceTimersByTime(5000);
+ });
+
+ expect(screen.queryByText('(8s)')).not.toBeInTheDocument();
+
+ rerender(<WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />);
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ expect(screen.getByText('(4s)')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
index d1fdbf7c442..3fe2512337e 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
@@ -1,7 +1,7 @@
import { type ChatToolPayloadWithResult } from '@lobechat/types';
import { Accordion, AccordionItem, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { Check, X } from 'lucide-react';
+import { Check, HandIcon, X } from 'lucide-react';
import { AnimatePresence, m as motion } from 'motion/react';
import { type Key, memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -35,6 +35,8 @@ interface WorkflowCollapseProps {
/** Assistant group message id (for generation state) */
assistantMessageId: string;
blocks: AssistantContentBlock[];
+ /** Default expansion state while the workflow is still streaming. Pending intervention always expands. */
+ defaultStreamingExpanded?: boolean;
disableEditing?: boolean;
workflowChromeComplete?: boolean;
}
@@ -43,6 +45,10 @@ const collectTools = (blocks: AssistantContentBlock[]): ChatToolPayloadWithResul
return blocks.flatMap((b) => b.tools ?? []);
};
+const hasPendingIntervention = (tools: ChatToolPayloadWithResult[]) => {
+ return tools.some((tool) => tool.intervention?.status === 'pending');
+};
+
const useDebouncedHeadline = (raw: string, allComplete: boolean, immediate = false) => {
const [out, setOut] = useState(raw);
const prevCompleteRef = useRef(allComplete);
@@ -98,10 +104,17 @@ const useCommittedProseHeadline = (proseSource: string, streaming: boolean) => {
};
const WorkflowCollapse = memo<WorkflowCollapseProps>(
- ({ assistantMessageId, blocks, disableEditing, workflowChromeComplete = false }) => {
+ ({
+ assistantMessageId,
+ blocks,
+ defaultStreamingExpanded = true,
+ disableEditing,
+ workflowChromeComplete = false,
+ }) => {
const { t } = useTranslation('chat');
const allTools = useMemo(() => collectTools(blocks), [blocks]);
const toolsPhaseComplete = areWorkflowToolsComplete(allTools);
+ const pendingInterventionPresent = useMemo(() => hasPendingIntervention(allTools), [allTools]);
const isGenerating = useConversationStore(
messageStateSelectors.isMessageGenerating(assistantMessageId),
);
@@ -116,8 +129,9 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
[blocks],
);
const durationText = totalWorkflowMs > 0 ? formatReasoningDuration(totalWorkflowMs) : undefined;
+ const streamingDefaultExpanded = defaultStreamingExpanded || pendingInterventionPresent;
- const [expanded, setExpanded] = useState(false);
+ const [expanded, setExpanded] = useState(() => !allComplete && streamingDefaultExpanded);
const userOpenedRef = useRef(false);
const prevCompleteRef = useRef(allComplete);
@@ -127,15 +141,24 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
if (!allComplete && wasComplete) {
userOpenedRef.current = false;
+ setExpanded(streamingDefaultExpanded);
+ return;
}
if (allComplete && !wasComplete && !userOpenedRef.current && allTools.length > 0) {
setExpanded(false);
}
- }, [allComplete, allTools.length]);
+ }, [allComplete, allTools.length, streamingDefaultExpanded]);
const streaming = !allComplete;
- const isExpanded = expanded;
+ const forceExpanded = streaming && pendingInterventionPresent;
+ const isExpanded = forceExpanded || expanded;
+
+ useEffect(() => {
+ if (streaming && pendingInterventionPresent) {
+ setExpanded(true);
+ }
+ }, [pendingInterventionPresent, streaming]);
const headlineState = useMemo(() => getWorkflowStreamingHeadlineState(blocks), [blocks]);
const committedProse = useCommittedProseHeadline(
@@ -143,9 +166,13 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
streaming,
);
- const showExpandedWorkingLabel = streaming && isExpanded;
+ const showExpandedWorkingLabel = streaming && isExpanded && !pendingInterventionPresent;
+ const pendingInterventionLabel = t('workflow.awaitingConfirmation', {
+ defaultValue: 'Awaiting your confirmation',
+ });
const workingLabel = t('workflow.working', { defaultValue: 'Working...' });
const streamingHeadlineRaw = useMemo(() => {
+ if (pendingInterventionPresent) return pendingInterventionLabel;
if (showExpandedWorkingLabel) return workingLabel;
switch (headlineState.kind) {
case 'thinking': {
@@ -161,41 +188,72 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
return '';
}
}
- }, [committedProse, headlineState, showExpandedWorkingLabel, workingLabel]);
+ }, [
+ committedProse,
+ headlineState,
+ pendingInterventionLabel,
+ pendingInterventionPresent,
+ showExpandedWorkingLabel,
+ workingLabel,
+ ]);
const streamingHeadline = useDebouncedHeadline(
streamingHeadlineRaw,
allComplete,
- showExpandedWorkingLabel,
+ showExpandedWorkingLabel || pendingInterventionPresent,
);
const [workingElapsedSeconds, setWorkingElapsedSeconds] = useState(0);
+ const accumulatedWorkingMsRef = useRef(0);
+ const activeWorkingStartedAtRef = useRef<number | null>(null);
useEffect(() => {
if (!streaming) {
+ accumulatedWorkingMsRef.current = 0;
+ activeWorkingStartedAtRef.current = null;
setWorkingElapsedSeconds(0);
return;
}
- const start = Date.now();
+ if (pendingInterventionPresent) {
+ if (activeWorkingStartedAtRef.current !== null) {
+ accumulatedWorkingMsRef.current += Date.now() - activeWorkingStartedAtRef.current;
+ activeWorkingStartedAtRef.current = null;
+ }
+ setWorkingElapsedSeconds(Math.floor(accumulatedWorkingMsRef.current / TIME_MS_PER_SECOND));
+ return;
+ }
+
+ if (activeWorkingStartedAtRef.current === null) {
+ activeWorkingStartedAtRef.current = Date.now();
+ }
+
const tick = () => {
- setWorkingElapsedSeconds(Math.floor((Date.now() - start) / 1000));
+ const activeMs =
+ activeWorkingStartedAtRef.current === null
+ ? 0
+ : Date.now() - activeWorkingStartedAtRef.current;
+ const totalMs = accumulatedWorkingMsRef.current + activeMs;
+ setWorkingElapsedSeconds(Math.floor(totalMs / TIME_MS_PER_SECOND));
};
tick();
const interval = setInterval(tick, 1000);
return () => clearInterval(interval);
- }, [streaming]);
+ }, [pendingInterventionPresent, streaming]);
const showWorkingElapsed =
+ !pendingInterventionPresent &&
workingElapsedSeconds >= WORKFLOW_WORKING_ELAPSED_SHOW_AFTER_MS / TIME_MS_PER_SECOND;
const handleExpandedChange = (keys: Key[]) => {
const nowExpanded = keys.includes('workflow');
+ if (forceExpanded && !nowExpanded) return;
+
setExpanded(nowExpanded);
if (nowExpanded) userOpenedRef.current = true;
};
- const constrained = streaming && expanded;
+ const constrained = streaming && isExpanded;
const { ref: scrollRef, handleScroll: handleAutoScroll } = useAutoScroll<HTMLDivElement>({
deps: [allTools.length],
@@ -204,7 +262,11 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
});
const statusIcon = streaming ? (
- <NeuralNetworkLoading size={16} />
+ pendingInterventionPresent ? (
+ <Icon color={cssVar.colorInfo} icon={HandIcon} />
+ ) : (
+ <NeuralNetworkLoading size={16} />
+ )
) : errorPresent ? (
<Icon color={cssVar.colorError} icon={X} />
) : (
@@ -248,14 +310,16 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
}}
>
<span
- className={shinyTextStyles.shinyText}
+ className={pendingInterventionPresent ? undefined : shinyTextStyles.shinyText}
style={{
+ color: pendingInterventionPresent ? cssVar.colorInfo : undefined,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
- {streamingHeadline || workingLabel}
+ {streamingHeadline ||
+ (pendingInterventionPresent ? pendingInterventionLabel : workingLabel)}
</span>
</motion.div>
</AnimatePresence>
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 352be0f78c4..27b12107a54 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -39,155 +39,161 @@ const actionBarHolder = (
/>
);
interface GroupMessageProps {
+ defaultWorkflowExpanded?: boolean;
disableEditing?: boolean;
id: string;
index: number;
isLatestItem?: boolean;
}
-const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing }) => {
- // Get message and actionsConfig from ConversationStore
- const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
-
- const { agentId, usage, createdAt, children, performance, model, provider, branch, metadata } =
- item;
- const avatar = useAgentMeta(agentId);
-
- // Collect fileList from all children blocks
- const aggregatedFileList = useMemo(() => {
- if (!children || children.length === 0) return [];
- return children.flatMap((child: AssistantContentBlock) => child.fileList || []);
- }, [children]);
-
- const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
- const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
- const openChatSettings = useOpenChatSettings();
-
- // Get the latest message block from the group that doesn't contain tools
- const lastAssistantMsg = useConversationStore(
- dataSelectors.getGroupLatestMessageWithoutTools(id),
- );
-
- const contentId = lastAssistantMsg?.id;
-
- // Get editing and interrupted state from ConversationStore
- const editing = useConversationStore(messageStateSelectors.isMessageEditing(contentId || ''));
- // Check interrupted on both the group root and the active block, because
- // continuation runs attach their operations to lastBlockId (contentId),
- // not the group root.
- const groupInterrupted = useConversationStore(messageStateSelectors.isMessageInterrupted(id));
- const blockInterrupted = useConversationStore(
- messageStateSelectors.isMessageInterrupted(contentId || ''),
- );
- const interrupted = groupInterrupted || blockInterrupted;
-
- const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
- const addReaction = useConversationStore((s) => s.addReaction);
- const removeReaction = useConversationStore((s) => s.removeReaction);
- const userId = useUserStore(userProfileSelectors.userId)!;
- const reactions: EmojiReaction[] = metadata?.reactions || [];
-
- const handleReactionClick = useCallback(
- (emoji: string) => {
- const existing = reactions.find((r) => r.emoji === emoji);
- if (existing && existing.users.includes(userId)) {
- removeReaction(id, emoji);
+const GroupMessage = memo<GroupMessageProps>(
+ ({ defaultWorkflowExpanded, id, index, disableEditing }) => {
+ // Get message and actionsConfig from ConversationStore
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+
+ const { agentId, usage, createdAt, children, performance, model, provider, branch, metadata } =
+ item;
+ const avatar = useAgentMeta(agentId);
+
+ // Collect fileList from all children blocks
+ const aggregatedFileList = useMemo(() => {
+ if (!children || children.length === 0) return [];
+ return children.flatMap((child: AssistantContentBlock) => child.fileList || []);
+ }, [children]);
+
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
+ const openChatSettings = useOpenChatSettings();
+
+ // Get the latest message block from the group that doesn't contain tools
+ const lastAssistantMsg = useConversationStore(
+ dataSelectors.getGroupLatestMessageWithoutTools(id),
+ );
+
+ const contentId = lastAssistantMsg?.id;
+
+ // Get editing and interrupted state from ConversationStore
+ const editing = useConversationStore(messageStateSelectors.isMessageEditing(contentId || ''));
+ // Check interrupted on both the group root and the active block, because
+ // continuation runs attach their operations to lastBlockId (contentId),
+ // not the group root.
+ const groupInterrupted = useConversationStore(messageStateSelectors.isMessageInterrupted(id));
+ const blockInterrupted = useConversationStore(
+ messageStateSelectors.isMessageInterrupted(contentId || ''),
+ );
+ const interrupted = groupInterrupted || blockInterrupted;
+
+ const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
+ const addReaction = useConversationStore((s) => s.addReaction);
+ const removeReaction = useConversationStore((s) => s.removeReaction);
+ const userId = useUserStore(userProfileSelectors.userId)!;
+ const reactions: EmojiReaction[] = metadata?.reactions || [];
+
+ const handleReactionClick = useCallback(
+ (emoji: string) => {
+ const existing = reactions.find((r) => r.emoji === emoji);
+ if (existing && existing.users.includes(userId)) {
+ removeReaction(id, emoji);
+ } else {
+ addReaction(id, emoji);
+ }
+ },
+ [id, reactions, addReaction, removeReaction],
+ );
+
+ const isReactionActive = useCallback(
+ (emoji: string) => {
+ const reaction = reactions.find((r) => r.emoji === emoji);
+ return !!reaction && reaction.users.includes(userId);
+ },
+ [reactions],
+ );
+
+ const setMessageItemActionElementPortialContext =
+ useSetMessageItemActionElementPortialContext();
+ const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
+
+ const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
+ (e) => {
+ if (disableEditing) return;
+ setMessageItemActionElementPortialContext(e.currentTarget);
+ setMessageItemActionTypeContext({ id, index, type: 'assistantGroup' });
+ },
+ [
+ disableEditing,
+ id,
+ index,
+ setMessageItemActionElementPortialContext,
+ setMessageItemActionTypeContext,
+ ],
+ );
+
+ const onAvatarClick = useCallback(() => {
+ if (!isInbox) {
+ toggleSystemRole(true);
} else {
- addReaction(id, emoji);
+ openChatSettings();
}
- },
- [id, reactions, addReaction, removeReaction],
- );
-
- const isReactionActive = useCallback(
- (emoji: string) => {
- const reaction = reactions.find((r) => r.emoji === emoji);
- return !!reaction && reaction.users.includes(userId);
- },
- [reactions],
- );
-
- const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
- const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
-
- const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
- (e) => {
- if (disableEditing) return;
- setMessageItemActionElementPortialContext(e.currentTarget);
- setMessageItemActionTypeContext({ id, index, type: 'assistantGroup' });
- },
- [
- disableEditing,
- id,
- index,
- setMessageItemActionElementPortialContext,
- setMessageItemActionTypeContext,
- ],
- );
-
- const onAvatarClick = useCallback(() => {
- if (!isInbox) {
- toggleSystemRole(true);
- } else {
- openChatSettings();
- }
- }, [isInbox]);
-
- return (
- <ChatItem
- showTitle
- avatar={avatar}
- placement={'left'}
- time={createdAt}
- actions={
- !disableEditing && (
- <>
- {isDevMode && branch && (
- <MessageBranch
- activeBranchIndex={branch.activeBranchIndex}
- count={branch.count}
- messageId={id}
- />
- )}
- {actionBarHolder}
- </>
- )
- }
- onAvatarClick={onAvatarClick}
- onMouseEnter={onMouseEnter}
- >
- {children && children.length > 0 && (
- <Group
- blocks={children}
- content={lastAssistantMsg?.content}
- contentId={contentId}
- disableEditing={disableEditing}
- id={id}
- messageIndex={index}
- />
- )}
- {aggregatedFileList.length > 0 && (
- <div style={{ marginTop: 8 }}>
- <FileListViewer items={aggregatedFileList} />
- </div>
- )}
- {interrupted && <InterruptedHint />}
- {isDevMode && model && (
- <Usage model={model} performance={performance} provider={provider!} usage={usage} />
- )}
- {reactions.length > 0 && (
- <ReactionDisplay
- isActive={isReactionActive}
- messageId={id}
- reactions={reactions}
- onReactionClick={handleReactionClick}
- />
- )}
- <Suspense fallback={null}>
- {editing && contentId && <EditState content={lastAssistantMsg?.content} id={contentId} />}
- </Suspense>
- </ChatItem>
- );
-}, isEqual);
+ }, [isInbox]);
+
+ return (
+ <ChatItem
+ showTitle
+ avatar={avatar}
+ placement={'left'}
+ time={createdAt}
+ actions={
+ !disableEditing && (
+ <>
+ {isDevMode && branch && (
+ <MessageBranch
+ activeBranchIndex={branch.activeBranchIndex}
+ count={branch.count}
+ messageId={id}
+ />
+ )}
+ {actionBarHolder}
+ </>
+ )
+ }
+ onAvatarClick={onAvatarClick}
+ onMouseEnter={onMouseEnter}
+ >
+ {children && children.length > 0 && (
+ <Group
+ blocks={children}
+ content={lastAssistantMsg?.content}
+ contentId={contentId}
+ defaultWorkflowExpanded={defaultWorkflowExpanded}
+ disableEditing={disableEditing}
+ id={id}
+ messageIndex={index}
+ />
+ )}
+ {aggregatedFileList.length > 0 && (
+ <div style={{ marginTop: 8 }}>
+ <FileListViewer items={aggregatedFileList} />
+ </div>
+ )}
+ {interrupted && <InterruptedHint />}
+ {isDevMode && model && (
+ <Usage model={model} performance={performance} provider={provider!} usage={usage} />
+ )}
+ {reactions.length > 0 && (
+ <ReactionDisplay
+ isActive={isReactionActive}
+ messageId={id}
+ reactions={reactions}
+ onReactionClick={handleReactionClick}
+ />
+ )}
+ <Suspense fallback={null}>
+ {editing && contentId && <EditState content={lastAssistantMsg?.content} id={contentId} />}
+ </Suspense>
+ </ChatItem>
+ );
+ },
+ isEqual,
+);
export default GroupMessage;
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index ff9373997d0..0eceb70ba44 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -41,6 +41,7 @@ const styles = createStaticStyles(({ css }) => ({
export interface MessageItemProps {
className?: string;
+ defaultWorkflowExpanded?: boolean;
disableEditing?: boolean;
enableHistoryDivider?: boolean;
endRender?: ReactNode;
@@ -53,6 +54,7 @@ export interface MessageItemProps {
const MessageItem = memo<MessageItemProps>(
({
className,
+ defaultWorkflowExpanded,
enableHistoryDivider,
id,
endRender,
@@ -129,6 +131,7 @@ const MessageItem = memo<MessageItemProps>(
case 'assistantGroup': {
return (
<AssistantGroupMessage
+ defaultWorkflowExpanded={defaultWorkflowExpanded}
disableEditing={disableEditing}
id={id}
index={index}
@@ -180,7 +183,7 @@ const MessageItem = memo<MessageItemProps>(
}
return null;
- }, [role, disableEditing, id, index, isLatestItem]);
+ }, [role, defaultWorkflowExpanded, disableEditing, id, index, isLatestItem]);
if (!role) return;
diff --git a/src/features/Onboarding/Agent/Conversation.test.tsx b/src/features/Onboarding/Agent/Conversation.test.tsx
index dc347788ae4..1729f8bf2ef 100644
--- a/src/features/Onboarding/Agent/Conversation.test.tsx
+++ b/src/features/Onboarding/Agent/Conversation.test.tsx
@@ -12,8 +12,9 @@ vi.mock('@lobehub/ui/brand', () => ({
LogoThree: () => null,
}));
-const { chatInputSpy, mockState } = vi.hoisted(() => ({
+const { chatInputSpy, messageItemSpy, mockState } = vi.hoisted(() => ({
chatInputSpy: vi.fn(),
+ messageItemSpy: vi.fn(),
mockState: {
displayMessages: [] as Array<{ content?: string; id: string; role: string }>,
},
@@ -50,7 +51,11 @@ vi.mock('@/features/Conversation', () => ({
))}
</div>
),
- MessageItem: ({ id }: { id: string }) => <div data-testid={`message-item-${id}`}>{id}</div>,
+ MessageItem: (props: { defaultWorkflowExpanded?: boolean; id: string }) => {
+ messageItemSpy(props);
+
+ return <div data-testid={`message-item-${props.id}`}>{props.id}</div>;
+ },
conversationSelectors: {
displayMessages: (state: typeof mockState) => state.displayMessages,
},
@@ -80,6 +85,7 @@ vi.mock('./Welcome', () => ({
describe('AgentOnboardingConversation', () => {
beforeEach(() => {
chatInputSpy.mockClear();
+ messageItemSpy.mockClear();
mockState.displayMessages = [];
});
@@ -128,4 +134,19 @@ describe('AgentOnboardingConversation', () => {
expect(screen.getByTestId('message-item-assistant-2')).toBeInTheDocument();
expect(screen.queryByText('finish')).not.toBeInTheDocument();
});
+
+ it('passes collapsed workflow default to onboarding message items', () => {
+ mockState.displayMessages = [
+ { id: 'assistant-1', role: 'assistant' },
+ { id: 'user-1', role: 'user' },
+ ];
+
+ render(<AgentOnboardingConversation />);
+
+ expect(messageItemSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ defaultWorkflowExpanded: false,
+ }),
+ );
+ });
});
diff --git a/src/features/Onboarding/Agent/Conversation.tsx b/src/features/Onboarding/Agent/Conversation.tsx
index 53a2cb6d7e0..30ddb029cc5 100644
--- a/src/features/Onboarding/Agent/Conversation.tsx
+++ b/src/features/Onboarding/Agent/Conversation.tsx
@@ -74,7 +74,14 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
const itemContent = (index: number, id: string) => {
const isLatestItem = displayMessages.length === index + 1;
- return <MessageItem id={id} index={index} isLatestItem={isLatestItem} />;
+ return (
+ <MessageItem
+ defaultWorkflowExpanded={false}
+ id={id}
+ index={index}
+ isLatestItem={isLatestItem}
+ />
+ );
};
return (
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 1e098a67f2f..c4b23af7751 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -580,6 +580,7 @@ export default {
'workflow.toolDisplayName.updateTodos': 'Updated todos',
'workflow.toolDisplayName.upsertDocumentByFilename': 'Updated a document',
'workflow.toolDisplayName.writeLocalFile': 'Wrote a file',
+ 'workflow.awaitingConfirmation': 'Awaiting your confirmation',
'workflow.working': 'Working...',
'workingPanel.agentDocuments': 'Agent Documents',
'workingPanel.progress': 'Progress',