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.

9.1 KB
Raw Blame
import { getBuiltinRender } from '@lobechat/builtin-tools/renders';
import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';
import { Accordion, Divider, Flexbox, Skeleton } from '@lobehub/ui';
import { memo, useState } from 'react';

import SafeBoundary from '@/components/ErrorBoundary';
import { getMcpAppFromState } from '@/libs/mcp/mcpApp';
import dynamic from '@/libs/next/dynamic';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { useDensity } from '@/styles/density';

import { STEP_TRIGGER_STYLES } from '../../../components/stepTriggerStyles';
import { dataSelectors, useConversationStore } from '../../../store';
import { isImageReadTool } from '../toolRenderRules';
import Actions from './Actions';
import Detail from './Detail';
import Inspectors from './Inspector';
import { hasToolResultBody } from './toolResultBody';
import { useArmOnInteraction } from './useArmOnInteraction';
import { useToolExpandState } from './useToolExpandState';

const Debug = dynamic(() => import('./Debug'), {
  loading: () => <Skeleton height={300} width={'100%'} />,
  ssr: false,
});

export interface GroupToolProps {
  assistantMessageId: string;
  disableEditing?: boolean;
  id: string;
}

const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) => {
  const { density } = useDensity();
  // Subscribe directly to this tool's data so a streaming chunk that only
  // updates a sibling tool does not push new props through this subtree.
  // `stabilizeReferences` keeps an unchanged tool's object across snapshots, so
  // identity is enough here β€” a deep compare of every tool's result on every
  // chunk is what made long workflows freeze.
  const tool = useConversationStore(
    dataSelectors.getToolInBlock(assistantMessageId, id),
    Object.is,
  );

  // Stable defaults so downstream hook ordering is preserved even on the brief
  // window where the tool is not yet present in the store snapshot.
  const apiName = tool?.apiName ?? '';
  const identifier = tool?.identifier ?? '';
  const requestArgs = tool?.arguments;
  const intervention = tool?.intervention;
  const result = tool?.result;
  const type = tool?.type;
  const toolMessageId = tool?.result_msg_id;

  // Get renderDisplayControl from manifest. `result.state` lets an API whose
  // output shape varies by target refine it β€” CC `Read` expands once the result
  // turns out to be an image, and stays collapsed for source text.
  const renderDisplayControl = useToolStore(
    toolSelectors.getRenderDisplayControl(identifier, apiName, result?.state),
  );
  // MCP Apps results open by default so their interactive view is visible
  const isMcpApp = useServerConfigStore(
    (s) => serverConfigSelectors.enableMcpApps(s) && !!getMcpAppFromState(result?.state),
  );
  // With `showImageReadPreview` off, a call that only read an image stays
  // collapsed like any other call; the user can still click it open.
  const showImageReads = useUserStore(userGeneralSettingsSelectors.showImageReadPreview);
  const foldImageRead = !showImageReads && !!tool && isImageReadTool(tool);
  const isPending = intervention?.status === 'pending';
  const isReject = intervention?.status === 'rejected';
  const isAbort = intervention?.status === 'aborted';
  const needExpand =
    (renderDisplayControl !== 'collapsed' && !foldImageRead) || isPending || isMcpApp;
  const isAlwaysExpand = renderDisplayControl === 'alwaysExpand' && !foldImageRead;

  const { handleExpand, setShowDebug, showDebug, showToolRender } = useToolExpandState({
    isAlwaysExpand,
    needExpand,
  });
  // Controls switching between custom render and fallback ArgumentRender
  const [showCustomToolRender, setShowCustomToolRender] = useState(true);
  // The row actions only show on hover/focus, yet they are most of a collapsed
  // row's DOM (β‰ˆ28 of β‰ˆ46 nodes). Mount them the first time the row is pointed
  // at or focused, so a list of hundreds of finished calls mounts titles only.
  const { armed: actionsArmed, armProps } = useArmOnInteraction();

  let isArgumentsStreaming = false;
  try {
    JSON.parse(requestArgs || '{}');
  } catch {
    isArgumentsStreaming = true;
  }

  const hasStreamingRenderer = !!getBuiltinStreaming(identifier, apiName);
  const forceShowStreamingRender = isArgumentsStreaming && hasStreamingRenderer;

  // Get precise tool calling state from operation
  const isToolCallingFromOperation = useChatStore(
    operationSelectors.isMessageInToolCalling(assistantMessageId),
  );

  // Only treat "missing/placeholder result" as in-flight while this assistant
  // message still has a running operation. After the run ends, tools may
  // legitimately have no merged `result` β€” do not keep showing "executing".
  const isAssistantMessageBusy = useChatStore(
    operationSelectors.isMessageProcessing(assistantMessageId),
  );

  const hasError = !!result?.error;
  // This tool's own result is the source of truth for completion. The
  // message-level toolCalling flag stays true while sibling tools are still
  // running, so without this guard a finished tool flips back into "loading".
  const hasFinishedResult = hasError || hasToolResultBody(result);
  const looksLikeWaitingForToolResult = !hasError && !isArgumentsStreaming && !hasFinishedResult;
  const isToolCallingFallback = looksLikeWaitingForToolResult && isAssistantMessageBusy;
  const isToolCalling = !hasFinishedResult && (isToolCallingFromOperation || isToolCallingFallback);
  const toolCallStartTime = useConversationStore(
    dataSelectors.getToolMessageCreatedAt(toolMessageId),
  );

  const hasCustomRender = !!getBuiltinRender(identifier, apiName);
  // Only allow toggle when has custom render and not in pending/reject/abort state
  const canToggleCustomToolRender = hasCustomRender && !isPending && !isReject && !isAbort;

  if (!tool) return null;

  const isToolDetailExpand = forceShowStreamingRender || showToolRender || showDebug;
  const mountActions = !disableEditing && (actionsArmed || isToolDetailExpand);

  return (
    <div {...armProps}>
      <Accordion
        hideIndicator={isAlwaysExpand}
        indicatorPlacement="inline"
        styles={STEP_TRIGGER_STYLES[density]}
        value={isToolDetailExpand ? [id] : []}
        items={[
          {
            action: mountActions && (
              <Actions
                assistantMessageId={assistantMessageId}
                canToggleCustomToolRender={canToggleCustomToolRender}
                identifier={identifier}
                setShowCustomToolRender={setShowCustomToolRender}
                setShowDebug={setShowDebug}
                showCustomToolRender={showCustomToolRender}
                showDebug={showDebug}
              />
            ),
            children: (
              <Flexbox gap={8} paddingBlock={8}>
                {showDebug && (
                  <Debug
                    apiName={apiName}
                    identifier={identifier}
                    intervention={intervention}
                    requestArgs={requestArgs}
                    result={result}
                    toolCallId={id}
                    toolMessageId={toolMessageId}
                    type={type}
                  />
                )}
                <SafeBoundary alertTitle={`${identifier} / ${apiName}`} variant="alert">
                  <Detail
                    apiName={apiName}
                    arguments={requestArgs}
                    disableEditing={disableEditing}
                    identifier={identifier}
                    intervention={intervention}
                    isArgumentsStreaming={isArgumentsStreaming}
                    isToolCalling={isToolCalling}
                    messageId={assistantMessageId}
                    result={result}
                    showCustomToolRender={showCustomToolRender}
                    toolCallId={id}
                    toolMessageId={toolMessageId}
                    type={type}
                  />
                </SafeBoundary>
                <Divider dashed style={{ marginBottom: 0, marginTop: 8 }} />
              </Flexbox>
            ),
            key: id,
            title: (
              <Inspectors
                apiName={apiName}
                arguments={requestArgs}
                identifier={identifier}
                intervention={intervention}
                isArgumentsStreaming={isArgumentsStreaming}
                isExpanded={isToolDetailExpand}
                isToolCalling={isToolCalling}
                messageId={assistantMessageId}
                result={result}
                toolCallId={id}
                toolCallStartTime={toolCallStartTime}
              />
            ),
          },
        ]}
        onValueChange={(value) => handleExpand(value.includes(id))}
      />
    </div>
  );
});

Tool.displayName = 'GroupTool';

export default Tool;