Spaces:
Paused
Paused
File size: 8,329 Bytes
4e7644b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | /**
* ToolCardShell — universal wrapper for tool cards.
*
* Renders the compact `<details>/<summary>` layout used by ChatV2 tool
* blocks: icon + label on a single line, expandable body underneath.
*
* When a tool is actively running (status === "calling"), a gear button
* appears in the header. The gear button toggles an offload banner
* below the card that lets users control background execution.
*
* During execution, clicking the card expands a metadata panel showing
* tool name, call ID, and parameters.
*/
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Settings } from "lucide-react";
import type { ToolCallContent } from "./types";
import DefaultBlock from "./DefaultBlock";
import { stringifyResult } from "./utils";
import { useToolCallSessionId } from "./ToolCallSessionContext";
import { useToolCallControl } from "../../../../hooks/useToolCallControl";
import { OffloadBanner } from "./ToolCallControlPopover";
import styles from "./toolCards.module.less";
import bannerStyles from "./offloadBanner.module.less";
export interface ToolCardShellProps {
/** Full ToolCallContent (name, params, result, status). */
content: ToolCallContent;
/** Whether the parent message is still streaming. */
isStreaming?: boolean;
/** Icon element (antd icon). */
icon: React.ReactNode;
/** Human-readable title to show in the summary line. */
title: string;
/** Optional inline result shown after the title when status === done. */
inlineResult?: string | null;
/** Optional badge elements (line counts, diff counts). */
badges?: React.ReactNode;
/** Optional compact action rendered immediately after the title. */
summaryAction?: React.ReactNode;
/** Expandable body content. */
children?: React.ReactNode;
/** Open the tool details when its user-facing result should be visible. */
defaultExpanded?: boolean;
}
const AUTO_POPUP_TOTAL_SECS = 30;
const ToolCardShell: React.FC<ToolCardShellProps> = ({
content,
isStreaming = false,
icon,
title,
inlineResult,
badges,
summaryAction,
children,
defaultExpanded = false,
}) => {
const { t } = useTranslation();
const sessionId = useToolCallSessionId();
// Lazy-mount the expandable body: children stay unmounted until the
// <details> is first opened, so collapsed cards never pay the render
// cost of heavy result blocks.
const [expanded, setExpanded] = useState(defaultExpanded);
const [bodyMounted, setBodyMounted] = useState(defaultExpanded);
const handleToggle = useCallback(
(e: React.SyntheticEvent<HTMLDetailsElement>) => {
setExpanded(e.currentTarget.open);
if (e.currentTarget.open) setBodyMounted(true);
},
[],
);
const isLoading = content.status === "calling" && isStreaming;
const isError = content.status === "error";
const inputProgress = content.inputProgress;
const inputPreview = inputProgress
? `${inputProgress.truncated ? "…\n" : ""}${inputProgress.preview}`
: "";
useEffect(() => {
if (defaultExpanded) {
setExpanded(true);
setBodyMounted(true);
}
}, [defaultExpanded]);
const isExecuting = content.status === "calling" && !inputProgress;
const showGear = isExecuting && !!sessionId;
const control = useToolCallControl(
sessionId,
content.id,
isExecuting,
content.name || title,
);
const gearDotClass = useMemo(() => {
if (!control.bannerVisible) return "";
return `${bannerStyles.show}`;
}, [control.bannerVisible]);
const staticMetadata = useMemo(() => {
if (!content.params || Object.keys(content.params).length === 0)
return null;
const lines: string[] = [];
if (content.id) lines.push(`tool_call_id: ${content.id}`);
if (content.name) lines.push(`tool: ${content.name}`);
for (const [k, v] of Object.entries(content.params)) {
if (k === "timeout" && control.killRemaining !== null) continue;
const val = typeof v === "string" ? v : JSON.stringify(v, null, 2);
lines.push(`${k}: ${val}`);
}
return lines.join("\n");
// control.killRemaining only gates whether to hide static "timeout" param;
// coerce to boolean so the memo doesn't rerun every second.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
content.id,
content.name,
content.params,
control.killRemaining !== null,
]);
const dynamicMetadata = useMemo(() => {
const lines: string[] = [];
if (control.offloadRemaining !== null) {
lines.push(`offload_remaining: ${Math.ceil(control.offloadRemaining)}s`);
}
if (control.killRemaining !== null) {
lines.push(`timeout: ${Math.ceil(control.killRemaining)}s`);
}
return lines.length > 0 ? lines.join("\n") : null;
}, [control.offloadRemaining, control.killRemaining]);
return (
<div className={styles.toolCallContainer}>
<details
open={expanded}
className={`${styles.toolCallCompact} ${
isLoading ? styles.toolCallCompactLoading : ""
} ${isError ? styles.toolCallCompactError : ""}`}
onToggle={handleToggle}
>
<summary className={styles.toolCallCompactSummary}>
{isLoading ? (
<span key="spinner" className={styles.toolCallSpinner} />
) : (
<span
key="icon"
className={`${styles.toolCallIcon} ${
isError ? styles.toolCallIconError : styles.toolCallIconSuccess
}`}
>
{icon}
</span>
)}
<span className={styles.toolCallLabel} title={title}>
{title}
{isLoading && ` ${t("tool.loading")}`}
</span>
{summaryAction}
{!isLoading && !isError && badges}
{inlineResult && (
<span className={styles.toolCallInlineResult} title={inlineResult}>
{inlineResult}
</span>
)}
{showGear && (
<button
className={`${bannerStyles.gearBtn} ${
control.bannerVisible ? bannerStyles.active : ""
}`}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
control.toggleBanner();
}}
title={t("tool.control.manage")}
>
<Settings size={14} aria-hidden />
<div className={`${bannerStyles.gearDot} ${gearDotClass}`} />
</button>
)}
</summary>
{bodyMounted &&
(isError ? (
<>
<DefaultBlock
title="Input"
content={JSON.stringify(content.params, null, 2)}
/>
<DefaultBlock
title="Error"
content={stringifyResult(content.result)}
/>
</>
) : (
<>
{isLoading && inputPreview && (
<DefaultBlock
title={t("tool.rawInputPreview")}
content={inputPreview}
/>
)}
{isLoading && (staticMetadata || dynamicMetadata) && (
<div className={styles.toolCallMetadata}>
{staticMetadata && (
<DefaultBlock title="Parameters" content={staticMetadata} />
)}
{dynamicMetadata && (
<DefaultBlock title="Runtime" content={dynamicMetadata} />
)}
</div>
)}
{children}
</>
))}
</details>
{control.bannerVisible && showGear && (
<OffloadBanner
sessionId={sessionId}
toolCallId={content.id}
toolName={content.name || title}
offloadRemaining={control.offloadRemaining}
killRemaining={control.killRemaining}
totalSeconds={AUTO_POPUP_TOTAL_SECS}
defaultPolicy={control.defaultPolicy}
maxInternalTimeoutSecs={control.maxInternalTimeoutSecs}
elapsed={control.elapsed}
onClose={control.closeBanner}
onUpdateRemaining={control.updateRemaining}
/>
)}
</div>
);
};
export default ToolCardShell;
|