源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
+153
@@ -0,0 +1,153 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import type {
|
||||
AgentToolCallVM,
|
||||
AgentToolRendererKind
|
||||
} from "../../contracts/agentToolCallVM";
|
||||
import { AgentEditContent } from "./AgentEditContent";
|
||||
import { AgentWebFetchContent } from "./AgentWebFetchContent";
|
||||
import { AgentWebSearchContent } from "./AgentWebSearchContent";
|
||||
import {
|
||||
arrayValue,
|
||||
objectValue,
|
||||
stringValue,
|
||||
ToolSection,
|
||||
ToolMarkdownBlock,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { formatToolDetails } from "../interactivePromptPresentation";
|
||||
|
||||
export function AgentApprovalContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const previewCall = approvalPreviewCall(call);
|
||||
const detailText = approvalDetailText(call.input);
|
||||
if (!previewCall && !call.summary.trim() && !detailText) {
|
||||
return null;
|
||||
}
|
||||
if (previewCall) {
|
||||
switch (previewCall.rendererKind) {
|
||||
case "web-fetch":
|
||||
return (
|
||||
<AgentWebFetchContent call={previewCall} onLinkClick={onLinkClick} />
|
||||
);
|
||||
case "web-search":
|
||||
return (
|
||||
<AgentWebSearchContent call={previewCall} onLinkClick={onLinkClick} />
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<AgentEditContent call={previewCall} onLinkClick={onLinkClick} />
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{call.summary.trim() ? (
|
||||
<ToolMarkdownBlock content={call.summary} />
|
||||
) : null}
|
||||
{detailText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.input")}>
|
||||
<ToolMarkdownBlock content={detailText} />
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function approvalDetailText(
|
||||
input: Record<string, unknown> | null
|
||||
): string | null {
|
||||
const details = formatToolDetails(input);
|
||||
if (details.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return details
|
||||
.map((detail) =>
|
||||
[detail.label, detail.value, detail.meta]
|
||||
.filter((value): value is string => Boolean(value?.trim()))
|
||||
.join("\n")
|
||||
)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
interface ApprovalPreviewKind {
|
||||
rendererKind: AgentToolRendererKind;
|
||||
toolName: string;
|
||||
}
|
||||
|
||||
// The nested tool-call's `kind` follows the ACP vocabulary (edit/move/fetch/...)
|
||||
// when the provider sends it (e.g. Codex); Claude Code omits `kind` and only
|
||||
// sets `title`/`toolName` to the canonical tool name (e.g. "WebFetch"), so
|
||||
// both vocabularies are matched here.
|
||||
function approvalPreviewKindFor(
|
||||
normalizedKind: string
|
||||
): ApprovalPreviewKind | null {
|
||||
switch (normalizedKind) {
|
||||
case "edit":
|
||||
case "move":
|
||||
return { rendererKind: "edit", toolName: "Edit" };
|
||||
case "fetch":
|
||||
case "webfetch":
|
||||
case "web_fetch":
|
||||
case "web-fetch":
|
||||
return { rendererKind: "web-fetch", toolName: "WebFetch" };
|
||||
case "websearch":
|
||||
case "web_search":
|
||||
case "web-search":
|
||||
return { rendererKind: "web-search", toolName: "WebSearch" };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function approvalPreviewCall(call: AgentToolCallVM): AgentToolCallVM | null {
|
||||
const toolCall = objectValue(call.input?.toolCall);
|
||||
if (!toolCall) {
|
||||
return null;
|
||||
}
|
||||
const normalizedKind = normalizeToolKind(
|
||||
stringValue(toolCall.kind) ??
|
||||
stringValue(toolCall.title) ??
|
||||
stringValue(toolCall.toolName)
|
||||
);
|
||||
const preview = approvalPreviewKindFor(normalizedKind);
|
||||
if (!preview) {
|
||||
return null;
|
||||
}
|
||||
const input = objectValue(toolCall.input) ?? call.input;
|
||||
const locations = arrayValue(toolCall.locations);
|
||||
return {
|
||||
kind: "tool-call",
|
||||
id: `${call.id}:approval-preview`,
|
||||
turnId: call.turnId,
|
||||
name: stringValue(toolCall.title) ?? call.name,
|
||||
toolName: preview.toolName,
|
||||
callType: "tool",
|
||||
status: stringValue(toolCall.status) ?? call.status,
|
||||
statusKind: call.statusKind,
|
||||
summary: "",
|
||||
compactSummary: null,
|
||||
payload: {
|
||||
input,
|
||||
locations
|
||||
},
|
||||
input,
|
||||
output: null,
|
||||
error: null,
|
||||
metadata: null,
|
||||
locations,
|
||||
rendererKind: preview.rendererKind,
|
||||
approval: null,
|
||||
planMode: null,
|
||||
askUserQuestion: null,
|
||||
task: null,
|
||||
occurredAtUnixMs: call.occurredAtUnixMs
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeToolKind(value: string | null): string {
|
||||
return (value ?? "").trim().toLowerCase();
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import type { JSX } from "react";
|
||||
import { MessageSquareMoreIcon } from "../../../../app/renderer/components/icons/MessageSquareMoreIcon";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
|
||||
export function AgentAskUserQuestionContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const questions = call.askUserQuestion?.questions ?? [];
|
||||
const outputText = stringValue(call.output?.text);
|
||||
if (questions.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
<ToolSection title={translate("agentHost.agentTool.details.questions")}>
|
||||
<div className="workspace-agents-status-panel__detail-tool-stack">
|
||||
{questions.map((question) => {
|
||||
const body =
|
||||
question.question ||
|
||||
question.header ||
|
||||
translate("agentHost.agentTool.details.questionFallback");
|
||||
const answer = formatAnswer(question.answer);
|
||||
const questionKey =
|
||||
question.id.trim() ||
|
||||
`${question.header}:${question.question}:${question.options.map((option) => option.label).join("|")}`;
|
||||
return (
|
||||
<div
|
||||
key={questionKey}
|
||||
className="workspace-agents-status-panel__detail-tool-stack-item"
|
||||
>
|
||||
<div className="workspace-agents-status-panel__detail-tool-question">
|
||||
{body}
|
||||
</div>
|
||||
{question.options.length > 0 ? (
|
||||
<div className="workspace-agents-status-panel__detail-tool-stack">
|
||||
{question.options.map((option) => (
|
||||
<div
|
||||
key={`${questionKey}-option-${option.label}:${option.description}`}
|
||||
className="workspace-agents-status-panel__detail-tool-stack-item"
|
||||
>
|
||||
<div className="workspace-agents-status-panel__detail-tool-summary">
|
||||
{option.label}
|
||||
</div>
|
||||
{option.description ? (
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer workspace-agents-status-panel__detail-tool-answer--muted">
|
||||
{option.description}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{answer ? (
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer">
|
||||
{translate("agentHost.agentTool.details.answerPrefix", {
|
||||
answer
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer workspace-agents-status-panel__detail-tool-answer--muted inline-flex items-center gap-1.5">
|
||||
<MessageSquareMoreIcon
|
||||
size={14}
|
||||
active
|
||||
aria-hidden="true"
|
||||
className="shrink-0"
|
||||
/>
|
||||
{translate("agentHost.agentTool.details.waitingForAnswer")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ToolSection>
|
||||
{outputText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<ToolMarkdownBlock
|
||||
content={outputText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatAnswer(
|
||||
answer: string | string[] | null | undefined
|
||||
): string | null {
|
||||
if (Array.isArray(answer)) {
|
||||
return answer.filter((value) => value.trim()).join(", ") || null;
|
||||
}
|
||||
return typeof answer === "string" && answer.trim() ? answer.trim() : null;
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import type { JSX } from "react";
|
||||
import { AgentTerminalBlock } from "./terminal/AgentTerminalBlock";
|
||||
import type { AgentToolRendererProps } from "./agentToolContentShared";
|
||||
import {
|
||||
getCommandRenderData,
|
||||
getToolCallFailureText
|
||||
} from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentBashContent({
|
||||
call
|
||||
}: AgentToolRendererProps): JSX.Element {
|
||||
"use memo";
|
||||
const commandData = getCommandRenderData(call);
|
||||
const structuredFailureText =
|
||||
commandData.status === "failed" &&
|
||||
!commandData.stdout &&
|
||||
!commandData.stderr
|
||||
? getToolCallFailureText(call)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body workspace-agents-status-panel__detail-tool-body--plain">
|
||||
<AgentTerminalBlock
|
||||
command={commandData.command}
|
||||
stdout={commandData.stdout}
|
||||
stderr={commandData.stderr || structuredFailureText || ""}
|
||||
exitCode={commandData.exitCode}
|
||||
durationMs={commandData.durationMs}
|
||||
status={commandData.status}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import { AgentCodeBlock } from "./code/AgentCodeBlock";
|
||||
import { AgentMonacoDiffViewer } from "./file-diff/AgentMonacoDiffViewer";
|
||||
import { AgentUnifiedPatchViewer } from "./file-diff/AgentUnifiedPatchViewer";
|
||||
import {
|
||||
stringValue,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import {
|
||||
getFileChangeRenderData,
|
||||
getToolCallFailureText
|
||||
} from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentEditContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const files = getFileChangeRenderData(call);
|
||||
const [file] = files;
|
||||
const path =
|
||||
file?.path ??
|
||||
stringValue(call.input?.path) ??
|
||||
stringValue(call.input?.file_path) ??
|
||||
stringValue(call.input?.filePath) ??
|
||||
null;
|
||||
const patchFiles = files.filter(
|
||||
(candidate) => candidate.unifiedDiff !== null
|
||||
);
|
||||
const diffFiles = files.filter(
|
||||
(candidate) =>
|
||||
candidate.unifiedDiff === null &&
|
||||
candidate.oldString !== null &&
|
||||
candidate.newString !== null
|
||||
);
|
||||
const contentFiles = files.filter(
|
||||
(candidate) =>
|
||||
candidate.unifiedDiff === null &&
|
||||
!(candidate.oldString !== null && candidate.newString !== null) &&
|
||||
candidate.content !== null
|
||||
);
|
||||
const failureText = getToolCallFailureText(call);
|
||||
const hasRenderableContent =
|
||||
Boolean(failureText) ||
|
||||
Boolean(path && files.length === 0) ||
|
||||
patchFiles.length > 0 ||
|
||||
diffFiles.length > 0 ||
|
||||
contentFiles.length > 0;
|
||||
|
||||
if (!hasRenderableContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body workspace-agents-status-panel__detail-tool-body--flat">
|
||||
{failureText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={failureText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{path && files.length === 0 ? (
|
||||
<ToolMarkdownBlock content={path} onLinkClick={onLinkClick} />
|
||||
) : null}
|
||||
{patchFiles.map((candidate) => (
|
||||
<AgentUnifiedPatchViewer
|
||||
key={`patch:${candidate.path}`}
|
||||
path={candidate.path}
|
||||
diffText={candidate.unifiedDiff!}
|
||||
compact
|
||||
flat
|
||||
/>
|
||||
))}
|
||||
{diffFiles.map((candidate) => (
|
||||
<AgentMonacoDiffViewer
|
||||
key={`diff:${candidate.path}`}
|
||||
path={candidate.path}
|
||||
oldValue={candidate.oldString!}
|
||||
newValue={candidate.newString!}
|
||||
flat
|
||||
/>
|
||||
))}
|
||||
{contentFiles.map((candidate) => (
|
||||
<AgentCodeBlock
|
||||
key={`content:${candidate.path}`}
|
||||
path={candidate.path}
|
||||
content={candidate.content!}
|
||||
language={candidate.language}
|
||||
showHeader={false}
|
||||
flat
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+1518
File diff suppressed because it is too large.
Load diff
+88
@@ -0,0 +1,88 @@
|
||||
import type { JSX } from "react";
|
||||
import type { AgentToolCallVM } from "../../contracts/agentToolCallVM";
|
||||
import { AgentApprovalContent } from "./AgentApprovalContent";
|
||||
import { AgentAskUserQuestionContent } from "./AgentAskUserQuestionContent";
|
||||
import { AgentBashContent } from "./AgentBashContent";
|
||||
import { AgentEditContent } from "./AgentEditContent";
|
||||
import { AgentImageGenerationContent } from "./AgentImageGenerationContent";
|
||||
import { AgentMcpToolContent } from "./AgentMcpToolContent";
|
||||
import { AgentPlanModeContent } from "./AgentPlanModeContent";
|
||||
import { AgentReadContent } from "./AgentReadContent";
|
||||
import { AgentSearchContent } from "./AgentSearchContent";
|
||||
import { AgentSkillContent } from "./AgentSkillContent";
|
||||
import { AgentTaskContent } from "./AgentTaskContent";
|
||||
import { AgentTodoWriteContent } from "./AgentTodoWriteContent";
|
||||
import { AgentToolSearchContent } from "./AgentToolSearchContent";
|
||||
import { AgentDefaultToolContent } from "./agentToolContentShared";
|
||||
import { AgentWebFetchContent } from "./AgentWebFetchContent";
|
||||
import { AgentWebSearchContent } from "./AgentWebSearchContent";
|
||||
import { AgentWriteContent } from "./AgentWriteContent";
|
||||
|
||||
export function AgentExpandedToolContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: {
|
||||
call: AgentToolCallVM;
|
||||
onLinkClick?: (href: string) => void;
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
const props = { call, onLinkClick };
|
||||
let content: JSX.Element | null;
|
||||
switch (call.rendererKind) {
|
||||
case "approval":
|
||||
content = <AgentApprovalContent {...props} />;
|
||||
break;
|
||||
case "plan-enter":
|
||||
case "plan-exit":
|
||||
content = <AgentPlanModeContent {...props} />;
|
||||
break;
|
||||
case "ask-user":
|
||||
content = <AgentAskUserQuestionContent {...props} />;
|
||||
break;
|
||||
case "task":
|
||||
content = <AgentTaskContent {...props} />;
|
||||
break;
|
||||
case "read":
|
||||
content = <AgentReadContent {...props} />;
|
||||
break;
|
||||
case "write":
|
||||
content = <AgentWriteContent {...props} />;
|
||||
break;
|
||||
case "edit":
|
||||
content = <AgentEditContent {...props} />;
|
||||
break;
|
||||
case "bash":
|
||||
content = <AgentBashContent {...props} />;
|
||||
break;
|
||||
case "search":
|
||||
content = <AgentSearchContent {...props} />;
|
||||
break;
|
||||
case "web-search":
|
||||
content = <AgentWebSearchContent {...props} />;
|
||||
break;
|
||||
case "web-fetch":
|
||||
content = <AgentWebFetchContent {...props} />;
|
||||
break;
|
||||
case "image-generation":
|
||||
content = <AgentImageGenerationContent {...props} />;
|
||||
break;
|
||||
case "todo-write":
|
||||
content = <AgentTodoWriteContent {...props} />;
|
||||
break;
|
||||
case "tool-search":
|
||||
content = <AgentToolSearchContent {...props} />;
|
||||
break;
|
||||
case "skill":
|
||||
content = <AgentSkillContent {...props} />;
|
||||
break;
|
||||
case "mcp":
|
||||
content = <AgentMcpToolContent {...props} />;
|
||||
break;
|
||||
default:
|
||||
content = <AgentDefaultToolContent {...props} />;
|
||||
}
|
||||
if (!content) {
|
||||
return null;
|
||||
}
|
||||
return content;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import type { AgentToolRendererProps } from "./agentToolContentShared";
|
||||
import { ToolMarkdownBlock, ToolSection } from "./agentToolContentShared";
|
||||
import { getImageGenerationRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentImageGenerationContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const image = getImageGenerationRenderData(call);
|
||||
if (!image.prompt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
<ToolSection title={translate("agentHost.agentTool.details.input")}>
|
||||
<ToolMarkdownBlock
|
||||
content={image.prompt}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
dedupeToolSectionContent,
|
||||
RawPayloadSection,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { renderRegisteredMcp } from "./mcp-renderers/agentMcpRendererRegistry";
|
||||
import { normalizeMcpPayload } from "./mcp-renderers/agentMcpShared";
|
||||
|
||||
export function AgentMcpToolContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element {
|
||||
"use memo";
|
||||
const payload = normalizeMcpPayload(call);
|
||||
const specialized = renderRegisteredMcp(payload);
|
||||
const visibleText = dedupeToolSectionContent(
|
||||
payload.text,
|
||||
payload.inputSummary
|
||||
);
|
||||
const errorText = dedupeToolSectionContent(payload.errorText);
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{payload.server || payload.tool ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.mcp")}>
|
||||
<ToolMarkdownBlock
|
||||
content={[
|
||||
payload.server
|
||||
? `${translate("agentHost.agentTool.details.mcpServer")}: ${payload.server}`
|
||||
: null,
|
||||
payload.tool
|
||||
? `${translate("agentHost.agentTool.details.mcpTool")}: ${payload.tool}`
|
||||
: null
|
||||
]
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.join("\n\n")}
|
||||
onLinkClick={onLinkClick}
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{payload.inputSummary ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.input")}>
|
||||
<ToolMarkdownBlock
|
||||
content={payload.inputSummary}
|
||||
onLinkClick={onLinkClick}
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{specialized ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
{specialized}
|
||||
</ToolSection>
|
||||
) : visibleText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<ToolMarkdownBlock
|
||||
content={visibleText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{errorText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={errorText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
<RawPayloadSection payload={call.payload ?? payload.structured} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import type { JSX } from "react";
|
||||
|
||||
interface AgentPathTailLabelProps {
|
||||
path?: string | null;
|
||||
fallback: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function AgentPathTailLabel({
|
||||
path,
|
||||
fallback,
|
||||
className
|
||||
}: AgentPathTailLabelProps): JSX.Element {
|
||||
"use memo";
|
||||
const label = path?.trim() || fallback;
|
||||
const parts = splitPathTail(label);
|
||||
|
||||
if (!parts) {
|
||||
return (
|
||||
<span
|
||||
className={`agent-path-tail-label ${className ?? ""}`}
|
||||
title={path ?? undefined}
|
||||
>
|
||||
<span className="agent-path-tail-label__file">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`agent-path-tail-label ${className ?? ""}`}
|
||||
title={path ?? undefined}
|
||||
>
|
||||
<span className="agent-path-tail-label__directory">
|
||||
{parts.directory}
|
||||
</span>
|
||||
<span className="agent-path-tail-label__file">{parts.fileName}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function splitPathTail(
|
||||
value: string
|
||||
): { directory: string; fileName: string } | null {
|
||||
const lastForwardSlash = value.lastIndexOf("/");
|
||||
const lastBackwardSlash = value.lastIndexOf("\\");
|
||||
const lastSeparator = Math.max(lastForwardSlash, lastBackwardSlash);
|
||||
if (lastSeparator <= 0 || lastSeparator === value.length - 1) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
directory: value.slice(0, lastSeparator + 1),
|
||||
fileName: value.slice(lastSeparator + 1)
|
||||
};
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import type { JSX } from "react";
|
||||
import {
|
||||
ToolMarkdownBlock,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { getPlanModeRenderData } from "./render-data/agentToolRenderData";
|
||||
import { AgentPlanCard } from "../AgentPlanCard";
|
||||
|
||||
export function AgentPlanModeContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const planMode = getPlanModeRenderData(call);
|
||||
if (call.rendererKind === "plan-enter") {
|
||||
if (!planMode.enterText) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="rounded-[8px] bg-[var(--transparency-block)] px-3 py-2 text-[11px] text-[var(--text-secondary)]">
|
||||
<ToolMarkdownBlock
|
||||
content={planMode.enterText}
|
||||
onLinkClick={onLinkClick}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!planMode.plan) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<AgentPlanCard
|
||||
title={planMode.fileName ?? undefined}
|
||||
copyText={planMode.plan}
|
||||
>
|
||||
<ToolMarkdownBlock content={planMode.plan} onLinkClick={onLinkClick} />
|
||||
</AgentPlanCard>
|
||||
);
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import type { JSX } from "react";
|
||||
import { AgentCodeBlock } from "./code/AgentCodeBlock";
|
||||
import {
|
||||
objectValue,
|
||||
stringValue,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { AgentPathTailLabel } from "./AgentPathTailLabel";
|
||||
|
||||
export function AgentReadContent({
|
||||
call
|
||||
}: AgentToolRendererProps): JSX.Element {
|
||||
"use memo";
|
||||
const path =
|
||||
stringValue(call.input?.path) ??
|
||||
stringValue(call.input?.file_path) ??
|
||||
stringValue(call.input?.filePath) ??
|
||||
stringValue(call.input?.file) ??
|
||||
null;
|
||||
const file = objectValue(call.output?.file);
|
||||
const outputText =
|
||||
stringValue(call.output?.text) ??
|
||||
stringValue(call.output?.stdout) ??
|
||||
(!file ? call.summary.trim() || null : null);
|
||||
const fileLineRange = fileRange(file);
|
||||
const fileTotalLines = numericValue(file?.totalLines);
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body workspace-agents-status-panel__detail-tool-body--plain">
|
||||
{outputText ? (
|
||||
<AgentCodeBlock
|
||||
path={path}
|
||||
content={outputText}
|
||||
language={languageForPath(path)}
|
||||
/>
|
||||
) : path || fileLineRange || fileTotalLines !== null ? (
|
||||
<div className="rounded-[8px] border border-[var(--line-2)] bg-[var(--background-panel)] px-3 py-2">
|
||||
{path ? (
|
||||
<AgentPathTailLabel
|
||||
path={path}
|
||||
fallback="File"
|
||||
className="font-[var(--tsh-font-mono)] text-[11px] text-[var(--text-secondary)]"
|
||||
/>
|
||||
) : null}
|
||||
{fileLineRange || fileTotalLines !== null ? (
|
||||
<div className="mt-1 text-[11px] text-[var(--text-secondary)]">
|
||||
{[
|
||||
fileLineRange,
|
||||
fileTotalLines !== null ? `${fileTotalLines} lines` : null
|
||||
]
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.join(" · ")}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function fileRange(file: Record<string, unknown> | null): string | null {
|
||||
const startLine = numericValue(file?.startLine);
|
||||
const numLines = numericValue(file?.numLines);
|
||||
if (startLine === null || numLines === null || numLines <= 0) {
|
||||
return null;
|
||||
}
|
||||
const endLine = startLine + numLines - 1;
|
||||
return startLine === endLine ? `L${startLine}` : `L${startLine}-${endLine}`;
|
||||
}
|
||||
|
||||
function numericValue(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function languageForPath(path: string | null): string | null {
|
||||
const extension = path?.split(".").pop()?.toLowerCase();
|
||||
switch (extension) {
|
||||
case "ts":
|
||||
case "tsx":
|
||||
return "typescript";
|
||||
case "js":
|
||||
case "jsx":
|
||||
return "javascript";
|
||||
case "go":
|
||||
return "go";
|
||||
case "md":
|
||||
return "markdown";
|
||||
case "json":
|
||||
return "json";
|
||||
default:
|
||||
return extension || null;
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
dedupeToolSectionContent,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { getSearchRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentSearchContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element {
|
||||
"use memo";
|
||||
const search = getSearchRenderData(call);
|
||||
const queryText = search.scope
|
||||
? `${search.query ?? ""}\n\n${translate("agentHost.agentTool.details.scope")}: ${search.scope}`.trim()
|
||||
: search.query;
|
||||
const resultFiles = withStableOccurrenceKeys(search.files, "file");
|
||||
const visibleOutput = dedupeToolSectionContent(search.output, queryText);
|
||||
const outputLines = withStableOccurrenceKeys(
|
||||
visibleOutput.split("\n").filter(Boolean),
|
||||
"line"
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{queryText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.query")}>
|
||||
<ToolMarkdownBlock content={queryText} onLinkClick={onLinkClick} />
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{(search.mode === "files_with_matches" || search.mode === "list_files") &&
|
||||
search.files.length > 0 ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.results")}>
|
||||
<div className="workspace-agents-status-panel__detail-tool-result-list overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)]">
|
||||
{resultFiles.map(({ key, value: file, isFirst }) => (
|
||||
<div
|
||||
key={key}
|
||||
className={`px-3 py-2 font-[var(--tsh-font-mono)] text-[11px] text-[var(--text-primary)] ${
|
||||
isFirst ? "" : "border-t border-[var(--line-2)]"
|
||||
}`}
|
||||
>
|
||||
{file}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{search.mode === "content" && visibleOutput ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<pre className="max-h-[320px] overflow-auto rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-2 text-[11px] leading-5 text-[var(--text-primary)]">
|
||||
{outputLines.map(({ key, value: line }) => (
|
||||
<div
|
||||
key={key}
|
||||
className={
|
||||
line.includes(":")
|
||||
? "text-[var(--text-primary)]"
|
||||
: "text-[var(--text-tertiary)]"
|
||||
}
|
||||
>
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
</pre>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{search.mode === "count" ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.results")}>
|
||||
<div className="inline-flex rounded-full border border-[var(--line-2)] bg-[var(--transparency-block)] px-2.5 py-1 text-[11px] text-[var(--text-tertiary)]">
|
||||
{search.output || "0"}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{(search.mode === "files_with_matches" ||
|
||||
search.mode === "list_files" ||
|
||||
search.mode === "count") &&
|
||||
search.files.length === 0 &&
|
||||
!visibleOutput &&
|
||||
!search.error ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.results")}>
|
||||
<div className="text-[11px] italic text-[var(--text-tertiary)]">
|
||||
{translate("agentHost.agentTool.details.noMatches")}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{search.mode === "unknown" && visibleOutput ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<ToolMarkdownBlock
|
||||
content={visibleOutput}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{search.error ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={search.error}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function withStableOccurrenceKeys(
|
||||
values: readonly string[],
|
||||
prefix: string
|
||||
): Array<{ key: string; value: string; isFirst: boolean }> {
|
||||
const seen = new Map<string, number>();
|
||||
const keyedValues: Array<{ key: string; value: string; isFirst: boolean }> =
|
||||
[];
|
||||
let isFirst = true;
|
||||
for (const value of values) {
|
||||
const occurrence = seen.get(value) ?? 0;
|
||||
seen.set(value, occurrence + 1);
|
||||
keyedValues.push({
|
||||
key: `${prefix}:${value}:${occurrence}`,
|
||||
value,
|
||||
isFirst
|
||||
});
|
||||
isFirst = false;
|
||||
}
|
||||
return keyedValues;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { ToolMarkdownBlock } from "./agentToolContentShared";
|
||||
import { getSkillRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentSkillContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const skill = getSkillRenderData(call);
|
||||
|
||||
if (!skill.skill && !skill.statusText) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{skill.skill ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.skill")}>
|
||||
<ToolMarkdownBlock
|
||||
content={
|
||||
skill.args ? `${skill.skill}\n\n${skill.args}` : skill.skill
|
||||
}
|
||||
onLinkClick={onLinkClick}
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{skill.statusText ? (
|
||||
<div className="text-[10px] text-[var(--text-tertiary)]">
|
||||
{skill.statusText}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { AgentTaskStepList } from "../AgentTaskStepList";
|
||||
import { getTaskRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentTaskContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element {
|
||||
"use memo";
|
||||
const task = getTaskRenderData(call);
|
||||
const failureMarkdown =
|
||||
task.errorMarkdown ??
|
||||
(isFailedTaskStatus(call.statusKind, task.status, call.status)
|
||||
? translate("agentHost.agentTool.details.missingFailureDetails")
|
||||
: null);
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer">
|
||||
<strong>{task.title}</strong>
|
||||
{task.status ? (
|
||||
<span className="workspace-agents-status-panel__detail-tool-answer--muted">
|
||||
{" · "}
|
||||
{task.status}
|
||||
</span>
|
||||
) : null}
|
||||
{task.durationText ? (
|
||||
<span className="workspace-agents-status-panel__detail-tool-answer--muted">
|
||||
{" · "}
|
||||
{task.durationText}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{task.status === "running" && task.latestStepSummary ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.summary")}>
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer workspace-agents-status-panel__detail-tool-answer--muted">
|
||||
{task.latestStepSummary}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{task.prompt ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.prompt")}>
|
||||
<ToolMarkdownBlock content={task.prompt} onLinkClick={onLinkClick} />
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{task.childSessionId ? (
|
||||
<ToolSection
|
||||
title={translate("agentHost.agentTool.details.delegateSession")}
|
||||
>
|
||||
<div className="workspace-agents-status-panel__detail-tool-answer">
|
||||
{task.childSessionId}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{task.steps.length > 0 ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.steps")}>
|
||||
<AgentTaskStepList steps={task.steps} onLinkClick={onLinkClick} />
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{task.resultMarkdown ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<ToolMarkdownBlock
|
||||
content={task.resultMarkdown}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{failureMarkdown ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={failureMarkdown}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function isFailedTaskStatus(
|
||||
...values: Array<string | null | undefined>
|
||||
): boolean {
|
||||
return values.some((value) => {
|
||||
const normalized = (value ?? "").trim().toLowerCase();
|
||||
return normalized === "failed" || normalized === "error";
|
||||
});
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import type { JSX } from "react";
|
||||
import { CheckCircle2, Circle } from "lucide-react";
|
||||
import { AtomIcon } from "../../../../app/renderer/components/icons/AtomIcon";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { getTodoRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentTodoWriteContent({
|
||||
call
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const todos = getTodoRenderData(call);
|
||||
if (todos.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
<ToolSection title={translate("agentHost.agentTool.details.todos")}>
|
||||
<div className="space-y-1">
|
||||
{todos.map((todo) => (
|
||||
<div
|
||||
key={`${todo.content}:${todo.status ?? "pending"}`}
|
||||
className="flex items-start gap-2 rounded-[8px] px-1 py-0.5 text-[11px]"
|
||||
>
|
||||
<div className="mt-[1px] shrink-0">
|
||||
{iconForStatus(todo.status)}
|
||||
</div>
|
||||
<span className={contentClassName(todo.status)}>
|
||||
{todo.content}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToolSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function iconForStatus(status: string | null): JSX.Element {
|
||||
switch (status) {
|
||||
case "completed":
|
||||
return (
|
||||
<CheckCircle2
|
||||
size={14}
|
||||
className="text-[var(--state-success)]"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
case "in_progress":
|
||||
return (
|
||||
<AtomIcon
|
||||
size={14}
|
||||
active
|
||||
className="text-[var(--tutti-purple)]"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Circle
|
||||
size={14}
|
||||
className="text-[var(--text-tertiary)]"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function contentClassName(status: string | null): string {
|
||||
switch (status) {
|
||||
case "completed":
|
||||
return "text-[var(--text-tertiary)] line-through";
|
||||
case "in_progress":
|
||||
return "text-[var(--text-primary)]";
|
||||
default:
|
||||
return "text-[var(--text-secondary)]";
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import type { HTMLAttributes, JSX, ReactNode } from "react";
|
||||
import { CustomScrollArea } from "../../../../app/renderer/components/ui/custom-scroll-area";
|
||||
import { cn } from "../../../../app/renderer/lib/utils";
|
||||
|
||||
interface AgentToolScrollAreaProps extends HTMLAttributes<HTMLDivElement> {
|
||||
children: ReactNode;
|
||||
viewportClassName?: string;
|
||||
maxHeightClassName?: string;
|
||||
}
|
||||
|
||||
export function AgentToolScrollArea({
|
||||
children,
|
||||
className,
|
||||
viewportClassName,
|
||||
maxHeightClassName = "max-h-[240px]",
|
||||
...props
|
||||
}: AgentToolScrollAreaProps): JSX.Element {
|
||||
"use memo";
|
||||
return (
|
||||
<CustomScrollArea
|
||||
className={cn(
|
||||
"agent-tool-scroll-area group/agent-tool-scroll",
|
||||
className
|
||||
)}
|
||||
viewportClassName={cn(
|
||||
"workspace-agents-status-panel__detail-scroll-region",
|
||||
maxHeightClassName,
|
||||
viewportClassName
|
||||
)}
|
||||
scrollbarClassName="agent-tool-scroll-area__scrollbar"
|
||||
scrollbarThumbClassName="workspace-agents-status-panel__scrollbar-thumb"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CustomScrollArea>
|
||||
);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { getToolSearchRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentToolSearchContent({
|
||||
call
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const toolSearch = getToolSearchRenderData(call);
|
||||
if (!toolSearch.query && toolSearch.matches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{toolSearch.displayQuery ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.query")}>
|
||||
<ToolMarkdownBlock
|
||||
content={`${toolSearch.displayQuery}\n\n${toolSearch.mode}`}
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{toolSearch.matches.length > 0 ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.results")}>
|
||||
<div className="workspace-agents-status-panel__detail-tool-result-list overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)]">
|
||||
{toolSearch.matches.map((match, index) => (
|
||||
<div
|
||||
key={match}
|
||||
className={`px-3 py-2 font-[var(--tsh-font-mono)] text-[11px] text-[var(--text-primary)] ${
|
||||
index > 0 ? "border-t border-[var(--line-2)]" : ""
|
||||
}`}
|
||||
>
|
||||
{match}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{toolSearch.matches.length === 0 ? (
|
||||
<div className="text-[11px] italic text-[var(--text-tertiary)]">
|
||||
{translate("agentHost.agentTool.details.noMatchingTools")}
|
||||
</div>
|
||||
) : null}
|
||||
{typeof toolSearch.totalDeferredTools === "number" ? (
|
||||
<div className="text-[10px] text-[var(--text-tertiary)]">
|
||||
{translate("agentHost.agentTool.details.loadedAvailable", {
|
||||
loaded: toolSearch.matches.length,
|
||||
available: toolSearch.totalDeferredTools
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
dedupeToolSectionContent,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import {
|
||||
getToolFallbackText,
|
||||
getWebFetchRenderData
|
||||
} from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentWebFetchContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const web = getWebFetchRenderData(call);
|
||||
const urlText =
|
||||
web.url && web.domain && web.domain !== web.url
|
||||
? `${web.domain}\n\n${web.url}`
|
||||
: web.url;
|
||||
const visibleContent = dedupeToolSectionContent(
|
||||
web.visibleContent,
|
||||
web.url,
|
||||
web.domain,
|
||||
urlText
|
||||
);
|
||||
const fallbackText = getToolFallbackText(call);
|
||||
const errorText = dedupeToolSectionContent(
|
||||
fallbackText.error,
|
||||
urlText,
|
||||
visibleContent
|
||||
);
|
||||
if (!web.url && !visibleContent && !errorText) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{web.url ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.url")}>
|
||||
<ToolMarkdownBlock
|
||||
content={urlText ?? ""}
|
||||
onLinkClick={onLinkClick}
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{visibleContent ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.content")}>
|
||||
<ToolMarkdownBlock
|
||||
content={visibleContent}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{web.isTruncated ? (
|
||||
<div className="text-[10px] italic text-[var(--text-tertiary)]">
|
||||
{translate("agentHost.agentTool.details.contentTruncated")}
|
||||
</div>
|
||||
) : null}
|
||||
{errorText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={errorText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import {
|
||||
arrayValue,
|
||||
dedupeToolSectionContent,
|
||||
optionRecord,
|
||||
stringValue,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import { getWebSearchRenderData } from "./render-data/agentToolRenderData";
|
||||
|
||||
const MAX_SUMMARY_LENGTH = 3000;
|
||||
|
||||
export function AgentWebSearchContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const web = getWebSearchRenderData(call);
|
||||
const queries = web.queries;
|
||||
const outputText = web.output;
|
||||
const links = normalizeLinks(call.output?.links, outputText);
|
||||
const queryText = webSearchQueryText(web.query, queries);
|
||||
const summary = extractSummary(outputText);
|
||||
const visibleSummary = dedupeToolSectionContent(
|
||||
summary ? summary.slice(0, MAX_SUMMARY_LENGTH) : null,
|
||||
queryText,
|
||||
links.map((link) => `${link.domain} ${link.title}`).join("\n")
|
||||
);
|
||||
|
||||
const hasRenderableContent = Boolean(
|
||||
queryText || links.length > 0 || visibleSummary || web.error
|
||||
);
|
||||
if (!hasRenderableContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{queryText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.query")}>
|
||||
<ToolMarkdownBlock content={queryText} onLinkClick={onLinkClick} />
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{links.length > 0 ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.results")}>
|
||||
<div className="workspace-agents-status-panel__detail-tool-result-list overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)]">
|
||||
{links.map((link, index) => (
|
||||
<a
|
||||
key={`${link.url}:${link.title}`}
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={`flex items-center gap-3 px-3 py-2 text-[11px] ${
|
||||
index > 0 ? "border-t border-[var(--line-2)]" : ""
|
||||
}`}
|
||||
>
|
||||
<span className="w-[120px] shrink-0 truncate text-[11px] text-[var(--text-tertiary)]">
|
||||
{link.domain}
|
||||
</span>
|
||||
<span className="truncate text-[var(--text-primary)]">
|
||||
{link.title}
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{visibleSummary ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.output")}>
|
||||
<ToolMarkdownBlock
|
||||
content={visibleSummary}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{summary && summary.length > MAX_SUMMARY_LENGTH ? (
|
||||
<div className="text-[10px] italic text-[var(--text-tertiary)]">
|
||||
{translate("agentHost.agentTool.details.summaryTruncated")}
|
||||
</div>
|
||||
) : null}
|
||||
{web.error ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={web.error}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function webSearchQueryText(
|
||||
query: string | null,
|
||||
queries: readonly string[]
|
||||
): string | null {
|
||||
const candidates = queries.length > 0 ? queries : query ? [query] : [];
|
||||
const deduped = [
|
||||
...new Set(candidates.map((value) => value.trim()).filter(Boolean))
|
||||
];
|
||||
return deduped.length > 0 ? deduped.join("\n") : null;
|
||||
}
|
||||
|
||||
function normalizeLinks(
|
||||
value: unknown,
|
||||
output: string
|
||||
): Array<{ title: string; url: string; domain: string }> {
|
||||
const explicitLinks =
|
||||
arrayValue(value)
|
||||
?.map(optionRecord)
|
||||
.filter(
|
||||
(candidate): candidate is Record<string, unknown> => candidate !== null
|
||||
)
|
||||
.flatMap((link) => {
|
||||
const url = stringValue(link.url);
|
||||
if (!url) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
title: stringValue(link.title) ?? url,
|
||||
url,
|
||||
domain: domainForUrl(url)
|
||||
}
|
||||
];
|
||||
}) ?? [];
|
||||
if (explicitLinks.length > 0) {
|
||||
return explicitLinks;
|
||||
}
|
||||
|
||||
const match = output.match(/^Links:\s*(\[[\s\S]*?\])(?:\n\n|\n|$)/);
|
||||
if (!match) {
|
||||
return extractQuotedLinks(output);
|
||||
}
|
||||
try {
|
||||
const linksJson = match[1];
|
||||
if (!linksJson) {
|
||||
return extractQuotedLinks(output);
|
||||
}
|
||||
const parsed = JSON.parse(linksJson) as unknown[];
|
||||
return parsed.flatMap((entry) => {
|
||||
const link = optionRecord(entry);
|
||||
const url = stringValue(link?.url);
|
||||
if (!url) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
title: stringValue(link?.title) ?? url,
|
||||
url,
|
||||
domain: domainForUrl(url)
|
||||
}
|
||||
];
|
||||
});
|
||||
} catch {
|
||||
return extractQuotedLinks(output);
|
||||
}
|
||||
}
|
||||
|
||||
function extractQuotedLinks(
|
||||
output: string
|
||||
): Array<{ title: string; url: string; domain: string }> {
|
||||
return Array.from(
|
||||
output.matchAll(/"title":"([^"]+)"\s*,\s*"url":"([^"]+)"/g)
|
||||
).flatMap((entry) => {
|
||||
const title = entry[1];
|
||||
const url = entry[2];
|
||||
if (!title || !url) {
|
||||
return [];
|
||||
}
|
||||
return [{ title, url, domain: domainForUrl(url) }];
|
||||
});
|
||||
}
|
||||
|
||||
function extractSummary(output: string): string | null {
|
||||
const trimmed = output.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
const withLinksRemoved = trimmed
|
||||
.replace(/^Links:\s*\[[\s\S]*?\](?:\n\n|\n)?/, "")
|
||||
.trim();
|
||||
return withLinksRemoved || (!trimmed.startsWith("Links:") ? trimmed : null);
|
||||
}
|
||||
|
||||
function domainForUrl(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import { AgentCodeBlock } from "./code/AgentCodeBlock";
|
||||
import { AgentUnifiedPatchViewer } from "./file-diff/AgentUnifiedPatchViewer";
|
||||
import {
|
||||
stringValue,
|
||||
ToolMarkdownBlock,
|
||||
ToolSection,
|
||||
type AgentToolRendererProps
|
||||
} from "./agentToolContentShared";
|
||||
import {
|
||||
getFileChangeRenderData,
|
||||
getToolCallFailureText
|
||||
} from "./render-data/agentToolRenderData";
|
||||
|
||||
export function AgentWriteContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const files = getFileChangeRenderData(call);
|
||||
const [file] = files;
|
||||
const path =
|
||||
file?.path ??
|
||||
stringValue(call.input?.path) ??
|
||||
stringValue(call.input?.file_path) ??
|
||||
stringValue(call.input?.filePath) ??
|
||||
null;
|
||||
const contentFiles = files.filter((candidate) => candidate.content !== null);
|
||||
const contentPaths = new Set(contentFiles.map((candidate) => candidate.path));
|
||||
const patchFiles = files.filter(
|
||||
(candidate) =>
|
||||
candidate.unifiedDiff !== null && !contentPaths.has(candidate.path)
|
||||
);
|
||||
const fallbackContent =
|
||||
files.length === 0 ? call.summary.trim() || null : null;
|
||||
const failureText = getToolCallFailureText(call);
|
||||
const showFileHeaders = files.length > 1;
|
||||
const hasRenderableContent =
|
||||
Boolean(failureText) ||
|
||||
Boolean(path && files.length === 0) ||
|
||||
patchFiles.length > 0 ||
|
||||
contentFiles.length > 0 ||
|
||||
Boolean(fallbackContent);
|
||||
|
||||
if (!hasRenderableContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body workspace-agents-status-panel__detail-tool-body--flat">
|
||||
{failureText ? (
|
||||
<ToolSection title={translate("agentHost.agentTool.details.error")}>
|
||||
<ToolMarkdownBlock
|
||||
content={failureText}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible
|
||||
/>
|
||||
</ToolSection>
|
||||
) : null}
|
||||
{path && files.length === 0 ? (
|
||||
<ToolMarkdownBlock content={path} onLinkClick={onLinkClick} />
|
||||
) : null}
|
||||
{patchFiles.map((candidate) => (
|
||||
<AgentUnifiedPatchViewer
|
||||
key={`patch:${candidate.path}`}
|
||||
path={candidate.path}
|
||||
diffText={candidate.unifiedDiff!}
|
||||
showHeader={showFileHeaders}
|
||||
compact
|
||||
flat
|
||||
/>
|
||||
))}
|
||||
{contentFiles.map((candidate) => (
|
||||
<AgentCodeBlock
|
||||
key={`content:${candidate.path}`}
|
||||
path={candidate.path}
|
||||
content={candidate.content!}
|
||||
language={candidate.language}
|
||||
showHeader={showFileHeaders}
|
||||
flat
|
||||
/>
|
||||
))}
|
||||
{fallbackContent ? (
|
||||
<AgentCodeBlock
|
||||
path={path}
|
||||
content={fallbackContent}
|
||||
language={file?.language ?? null}
|
||||
showHeader={false}
|
||||
flat
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+619
@@ -0,0 +1,619 @@
|
||||
import { useState, type JSX, type ReactNode } from "react";
|
||||
import { ChevronDown, ChevronRight } from "lucide-react";
|
||||
import { translate } from "../../../../i18n/index";
|
||||
import { AgentMessageMarkdown } from "../../../AgentMessageMarkdown";
|
||||
import { stripImagePayloadData } from "../../../imageGenerationTool";
|
||||
import type { AgentToolCallVM } from "../../contracts/agentToolCallVM";
|
||||
import {
|
||||
getCommandRenderData,
|
||||
getFileChangeRenderData,
|
||||
getImageGenerationRenderData,
|
||||
getToolCallFailureText,
|
||||
getToolFallbackText,
|
||||
getWebFetchRenderData,
|
||||
getWebSearchRenderData
|
||||
} from "./render-data/agentToolRenderData";
|
||||
import { CollapsibleReveal } from "../CollapsibleReveal";
|
||||
import { fileRange } from "./AgentReadContent";
|
||||
import { structuredToolText } from "./render-data/structuredToolText";
|
||||
import { getPromptToolDetails } from "../../promptToolDetails";
|
||||
|
||||
export interface AgentToolRendererProps {
|
||||
call: AgentToolCallVM;
|
||||
onLinkClick?: (href: string) => void;
|
||||
}
|
||||
|
||||
export interface TaskStepView {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string | null;
|
||||
summary: string;
|
||||
toolName: string | null;
|
||||
payload: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export function ToolSection({
|
||||
title,
|
||||
children
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
if (!children) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<section className="workspace-agents-status-panel__detail-tool-section-block">
|
||||
<div className="workspace-agents-status-panel__detail-tool-section-title">
|
||||
{title}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ToolMarkdownBlock({
|
||||
content,
|
||||
onLinkClick,
|
||||
collapsible = false
|
||||
}: {
|
||||
content: string;
|
||||
onLinkClick?: (href: string) => void;
|
||||
collapsible?: boolean;
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
const normalized = content.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<AgentMessageMarkdown
|
||||
content={normalized}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible={collapsible}
|
||||
enableImageZoom
|
||||
className="workspace-agents-status-panel__detail-tool-markdown [&_ol]:text-[var(--text-secondary)] [&_ul]:text-[var(--text-secondary)]"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentDefaultToolContent({
|
||||
call,
|
||||
onLinkClick
|
||||
}: AgentToolRendererProps): JSX.Element | null {
|
||||
"use memo";
|
||||
const fallbackText = getToolFallbackText(call);
|
||||
const inputText = dedupeToolSectionContent(fallbackText.input);
|
||||
const outputText = dedupeToolSectionContent(fallbackText.output, inputText);
|
||||
const errorText = dedupeToolSectionContent(
|
||||
fallbackText.error,
|
||||
inputText,
|
||||
outputText
|
||||
);
|
||||
const detail = dedupeToolSummary(
|
||||
call.summary.trim(),
|
||||
inputText,
|
||||
outputText,
|
||||
errorText
|
||||
);
|
||||
const sections = [
|
||||
detail
|
||||
? {
|
||||
key: "summary",
|
||||
title: translate("agentHost.agentTool.details.summary"),
|
||||
content: detail,
|
||||
collapsible: true
|
||||
}
|
||||
: null,
|
||||
inputText
|
||||
? {
|
||||
key: "input",
|
||||
title: translate("agentHost.agentTool.details.input"),
|
||||
content: inputText,
|
||||
collapsible: true
|
||||
}
|
||||
: null,
|
||||
outputText
|
||||
? {
|
||||
key: "output",
|
||||
title: translate("agentHost.agentTool.details.output"),
|
||||
content: outputText,
|
||||
collapsible: true
|
||||
}
|
||||
: null,
|
||||
errorText
|
||||
? {
|
||||
key: "error",
|
||||
title: translate("agentHost.agentTool.details.error"),
|
||||
content: errorText,
|
||||
collapsible: true
|
||||
}
|
||||
: null
|
||||
].filter(
|
||||
(
|
||||
section
|
||||
): section is {
|
||||
key: string;
|
||||
title: string;
|
||||
content: string;
|
||||
collapsible: boolean;
|
||||
} => section !== null
|
||||
);
|
||||
const rawPayload = call.payload ?? rawPayloadFromCall(call);
|
||||
|
||||
if (sections.length === 0 && !rawPayload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-body">
|
||||
{sections.map((section) => (
|
||||
<ToolSection key={section.key} title={section.title}>
|
||||
<ToolMarkdownBlock
|
||||
content={section.content}
|
||||
onLinkClick={onLinkClick}
|
||||
collapsible={section.collapsible}
|
||||
/>
|
||||
</ToolSection>
|
||||
))}
|
||||
<RawPayloadSection payload={rawPayload} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function hasAgentToolContent(call: AgentToolCallVM): boolean {
|
||||
if (call.rendererKind === "approval") {
|
||||
return Boolean(
|
||||
call.input?.toolCall ||
|
||||
call.summary.trim() ||
|
||||
getPromptToolDetails(call.input).length > 0
|
||||
);
|
||||
}
|
||||
|
||||
switch (call.rendererKind) {
|
||||
case "plan-enter":
|
||||
case "plan-exit":
|
||||
return Boolean(call.planMode || hasGenericStructuredContent(call));
|
||||
case "ask-user":
|
||||
return Boolean(call.askUserQuestion || hasGenericStructuredContent(call));
|
||||
case "task":
|
||||
return Boolean(call.task || hasGenericStructuredContent(call));
|
||||
case "read":
|
||||
return hasReadContent(call);
|
||||
case "write":
|
||||
return hasWriteContent(call);
|
||||
case "edit":
|
||||
return hasEditContent(call);
|
||||
case "bash": {
|
||||
const command = getCommandRenderData(call);
|
||||
// toolName-only Claude Bash starts must not claim expandable detail —
|
||||
// that paints an empty terminal shell with no data-agent-terminal-command.
|
||||
return Boolean(
|
||||
command.command ||
|
||||
command.stdout ||
|
||||
command.stderr ||
|
||||
call.error ||
|
||||
stringValue(call.summary)
|
||||
);
|
||||
}
|
||||
case "search":
|
||||
return hasGenericStructuredContent(call);
|
||||
case "web-search":
|
||||
return hasWebSearchContent(call);
|
||||
case "web-fetch":
|
||||
return hasWebFetchContent(call) || hasGenericStructuredContent(call);
|
||||
case "image-generation": {
|
||||
const image = getImageGenerationRenderData(call);
|
||||
return Boolean(image.prompt || image.imageUri);
|
||||
}
|
||||
case "todo-write":
|
||||
case "tool-search":
|
||||
case "skill":
|
||||
case "mcp":
|
||||
return true;
|
||||
default:
|
||||
return Boolean(
|
||||
call.summary.trim() || call.input || call.output || call.error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function hasGenericStructuredContent(call: AgentToolCallVM): boolean {
|
||||
return Boolean(
|
||||
call.summary.trim() ||
|
||||
call.compactSummary?.trim() ||
|
||||
call.input ||
|
||||
call.output ||
|
||||
call.error ||
|
||||
call.payload ||
|
||||
call.metadata ||
|
||||
call.locations?.length
|
||||
);
|
||||
}
|
||||
|
||||
function hasWebFetchContent(call: AgentToolCallVM): boolean {
|
||||
const web = getWebFetchRenderData(call);
|
||||
return Boolean(web.url || web.visibleContent);
|
||||
}
|
||||
|
||||
function hasWebSearchContent(call: AgentToolCallVM): boolean {
|
||||
// Mirror what AgentWebSearchContent can actually render. Web search payloads
|
||||
// (notably the Codex path) often carry only a query and no results, so guard
|
||||
// against treating an empty payload as renderable detail.
|
||||
const web = getWebSearchRenderData(call);
|
||||
return Boolean(
|
||||
web.query ||
|
||||
web.queries.length > 0 ||
|
||||
web.output.trim() ||
|
||||
web.error ||
|
||||
arrayValue(call.output?.links)?.length
|
||||
);
|
||||
}
|
||||
|
||||
function hasReadContent(call: AgentToolCallVM): boolean {
|
||||
const file = objectValue(call.output?.file);
|
||||
return Boolean(
|
||||
stringValue(call.output?.text) ||
|
||||
stringValue(call.output?.stdout) ||
|
||||
(!file && call.summary.trim()) ||
|
||||
stringValue(call.input?.path) ||
|
||||
stringValue(call.input?.file_path) ||
|
||||
stringValue(call.input?.filePath) ||
|
||||
stringValue(call.input?.file) ||
|
||||
fileRange(file) ||
|
||||
numericValue(file?.totalLines) !== null
|
||||
);
|
||||
}
|
||||
|
||||
function hasWriteContent(call: AgentToolCallVM): boolean {
|
||||
const files = getFileChangeRenderData(call);
|
||||
return Boolean(
|
||||
getToolCallFailureText(call) ||
|
||||
files.some((file) => file.content !== null || file.unifiedDiff !== null) ||
|
||||
(files.length === 0 &&
|
||||
(call.summary.trim() ||
|
||||
stringValue(call.input?.path) ||
|
||||
stringValue(call.input?.file_path) ||
|
||||
stringValue(call.input?.filePath)))
|
||||
);
|
||||
}
|
||||
|
||||
function hasEditContent(call: AgentToolCallVM): boolean {
|
||||
const files = getFileChangeRenderData(call);
|
||||
return Boolean(
|
||||
getToolCallFailureText(call) ||
|
||||
files.some(
|
||||
(file) =>
|
||||
file.unifiedDiff !== null ||
|
||||
(file.oldString !== null && file.newString !== null) ||
|
||||
file.content !== null
|
||||
) ||
|
||||
(files.length === 0 &&
|
||||
(stringValue(call.input?.path) ||
|
||||
stringValue(call.input?.file_path) ||
|
||||
stringValue(call.input?.filePath)))
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeTaskSteps(call: AgentToolCallVM): TaskStepView[] {
|
||||
const steps =
|
||||
arrayValue(call.metadata?.steps) ??
|
||||
arrayValue(call.output?.steps) ??
|
||||
arrayValue(call.payload?.steps) ??
|
||||
[];
|
||||
return steps.flatMap((value, index) => {
|
||||
const step = optionRecord(value);
|
||||
if (!step) {
|
||||
return [];
|
||||
}
|
||||
const toolName =
|
||||
stringValue(step.toolName) ??
|
||||
stringValue(step.tool_name) ??
|
||||
stringValue(step.name) ??
|
||||
null;
|
||||
const name = toolName
|
||||
? humanizeToolLabel(toolName)
|
||||
: translate("agentHost.agentTool.details.stepLabel", {
|
||||
index: index + 1
|
||||
});
|
||||
const status =
|
||||
stringValue(step.status) ??
|
||||
stringValue(optionRecord(step.toolResult)?.status) ??
|
||||
stringValue(optionRecord(step.tool_result)?.status) ??
|
||||
null;
|
||||
const summary =
|
||||
firstNonEmptyText(
|
||||
optionRecord(step.toolResult),
|
||||
optionRecord(step.tool_result),
|
||||
optionRecord(step.toolInput),
|
||||
optionRecord(step.tool_input)
|
||||
) ?? "";
|
||||
return [
|
||||
{
|
||||
id:
|
||||
stringValue(step.toolUseId) ??
|
||||
stringValue(step.id) ??
|
||||
`step-${index + 1}`,
|
||||
name,
|
||||
status,
|
||||
summary,
|
||||
toolName,
|
||||
payload: {
|
||||
input: optionRecord(step.toolInput) ?? optionRecord(step.tool_input),
|
||||
output:
|
||||
optionRecord(step.toolResult) ?? optionRecord(step.tool_result),
|
||||
error: optionRecord(step.toolError) ?? optionRecord(step.tool_error)
|
||||
}
|
||||
}
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function formatLineRange(
|
||||
input: Record<string, unknown> | null
|
||||
): string | null {
|
||||
if (!input) {
|
||||
return null;
|
||||
}
|
||||
const start = numericValue(input.startLine) ?? numericValue(input.start_line);
|
||||
const end = numericValue(input.endLine) ?? numericValue(input.end_line);
|
||||
if (start === null || end === null) {
|
||||
return null;
|
||||
}
|
||||
return start === end ? `L${start}` : `L${start}-${end}`;
|
||||
}
|
||||
|
||||
export function optionRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
export function objectValue(value: unknown): Record<string, unknown> | null {
|
||||
return optionRecord(value);
|
||||
}
|
||||
|
||||
export function arrayValue(value: unknown): unknown[] | null {
|
||||
return Array.isArray(value) ? value : null;
|
||||
}
|
||||
|
||||
export function stringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function numericValue(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function firstNonEmptyText(...values: Array<unknown>): string | null {
|
||||
for (const value of values) {
|
||||
const text = structuredText(value);
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function structuredText(value: unknown): string | null {
|
||||
return structuredToolText(value);
|
||||
}
|
||||
|
||||
export function RawPayloadSection({
|
||||
payload
|
||||
}: {
|
||||
payload: unknown;
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const rawJson = rawPayloadJson(payload);
|
||||
if (!rawJson) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-raw">
|
||||
<button
|
||||
type="button"
|
||||
className="group/raw-payload inline-flex items-center gap-1.5 border-0 bg-transparent p-0 text-left text-[11px] font-normal text-[var(--text-secondary)]"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
<span>{translate("agentHost.agentTool.details.rawPayload")}</span>
|
||||
{expanded ? (
|
||||
<ChevronDown
|
||||
size={12}
|
||||
strokeWidth={2.2}
|
||||
aria-hidden="true"
|
||||
className="shrink-0 opacity-0 transition-opacity duration-150 group-hover/raw-payload:opacity-100 group-focus-visible/raw-payload:opacity-100"
|
||||
/>
|
||||
) : (
|
||||
<ChevronRight
|
||||
size={12}
|
||||
strokeWidth={2.2}
|
||||
aria-hidden="true"
|
||||
className="shrink-0 opacity-0 transition-opacity duration-150 group-hover/raw-payload:opacity-100 group-focus-visible/raw-payload:opacity-100"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
<CollapsibleReveal expanded={expanded} preMountOnIdle>
|
||||
<pre className="workspace-agents-status-panel__detail-scroll-region mt-2 max-h-[320px] overflow-auto rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-2 text-[11px] leading-[1.45] text-[var(--text-secondary)]">
|
||||
<code>{rawJson}</code>
|
||||
</pre>
|
||||
</CollapsibleReveal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function rawPayloadFromCall(
|
||||
call: AgentToolRendererProps["call"]
|
||||
): Record<string, unknown> | null {
|
||||
const payload: Record<string, unknown> = {};
|
||||
if (call.input) {
|
||||
payload.input = call.input;
|
||||
}
|
||||
if (call.output) {
|
||||
payload.output = call.output;
|
||||
}
|
||||
if (call.error) {
|
||||
payload.error = call.error;
|
||||
}
|
||||
if (call.metadata) {
|
||||
payload.metadata = call.metadata;
|
||||
}
|
||||
return Object.keys(payload).length > 0 ? payload : null;
|
||||
}
|
||||
|
||||
function rawPayloadJson(value: unknown): string | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(stripImagePayloadData(value), null, 2);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function dedupeToolSummary(
|
||||
summary: string,
|
||||
...otherValues: Array<string | null>
|
||||
): string {
|
||||
return dedupeToolSectionContent(summary, ...otherValues);
|
||||
}
|
||||
|
||||
export function dedupeToolSectionContent(
|
||||
content: string | null | undefined,
|
||||
...previousValues: Array<string | null | undefined>
|
||||
): string {
|
||||
const normalizedContent = content?.trim() ?? "";
|
||||
if (!normalizedContent) {
|
||||
return "";
|
||||
}
|
||||
const contentKey = normalizeToolSectionContent(normalizedContent);
|
||||
const duplicate = previousValues.some(
|
||||
(value) => normalizeToolSectionContent(value) === contentKey
|
||||
);
|
||||
return duplicate ? "" : normalizedContent;
|
||||
}
|
||||
|
||||
export function normalizeToolSectionContent(
|
||||
value: string | null | undefined
|
||||
): string {
|
||||
return (value ?? "").trim().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function askUserAnswer(
|
||||
question: Record<string, unknown>,
|
||||
index: number,
|
||||
output: Record<string, unknown> | null
|
||||
): string | null {
|
||||
if (!output) {
|
||||
return null;
|
||||
}
|
||||
const questionId = stringValue(question.id);
|
||||
const answersById = optionRecord(output.answersByQuestionId);
|
||||
if (questionId) {
|
||||
const byId = firstNonEmptyText(answersById?.[questionId]);
|
||||
if (byId) {
|
||||
return byId;
|
||||
}
|
||||
}
|
||||
const answers = optionRecord(output.answers);
|
||||
const questionText = stringValue(question.question);
|
||||
if (questionText) {
|
||||
const byQuestion = firstNonEmptyText(answers?.[questionText]);
|
||||
if (byQuestion) {
|
||||
return byQuestion;
|
||||
}
|
||||
}
|
||||
return (
|
||||
firstNonEmptyText((output.answers as unknown[] | undefined)?.[index]) ??
|
||||
firstNonEmptyText((output.selected as unknown[] | undefined)?.[index]) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export function humanizeToolLabel(name: string): string {
|
||||
switch (
|
||||
(name ?? "")
|
||||
.trim()
|
||||
.replace(/[_\s-]+/g, "")
|
||||
.toLowerCase()
|
||||
) {
|
||||
case "bash":
|
||||
case "shell":
|
||||
case "exec":
|
||||
case "execcommand":
|
||||
case "runshellcommand":
|
||||
return translate("agentHost.agentTool.labels.runCommand");
|
||||
case "read":
|
||||
case "readfile":
|
||||
return translate("agentHost.agentTool.labels.readFile");
|
||||
case "write":
|
||||
case "writefile":
|
||||
return translate("agentHost.agentTool.labels.writeFile");
|
||||
case "edit":
|
||||
case "editfile":
|
||||
case "multiedit":
|
||||
return translate("agentHost.agentTool.labels.editFile");
|
||||
case "ls":
|
||||
case "list":
|
||||
case "listdirectory":
|
||||
case "listfiles":
|
||||
return translate("agentHost.agentTool.labels.listFiles");
|
||||
case "glob":
|
||||
case "find":
|
||||
case "findfiles":
|
||||
return translate("agentHost.agentTool.labels.findFiles");
|
||||
case "search":
|
||||
case "searchfiles":
|
||||
case "searchfilecontent":
|
||||
case "grep":
|
||||
return translate("agentHost.agentTool.labels.searchFiles");
|
||||
case "websearch":
|
||||
case "websearchpreview":
|
||||
case "googlewebsearch":
|
||||
return translate("agentHost.agentTool.labels.webSearch");
|
||||
case "webfetch":
|
||||
case "fetchurl":
|
||||
return translate("agentHost.agentTool.labels.webFetch");
|
||||
case "applypatch":
|
||||
return translate("agentHost.agentTool.labels.applyPatch");
|
||||
case "bashoutput":
|
||||
case "readcommandoutput":
|
||||
return translate("agentHost.agentTool.labels.readCommandOutput");
|
||||
case "killbash":
|
||||
case "stopcommand":
|
||||
return translate("agentHost.agentTool.labels.stopCommand");
|
||||
case "notebookread":
|
||||
case "readnotebook":
|
||||
return translate("agentHost.agentTool.labels.readNotebook");
|
||||
case "notebookedit":
|
||||
case "editnotebook":
|
||||
return translate("agentHost.agentTool.labels.editNotebook");
|
||||
case "todowrite":
|
||||
case "updatetodos":
|
||||
case "todo":
|
||||
case "writetodos":
|
||||
return translate("agentHost.agentTool.labels.updateTodos");
|
||||
case "task":
|
||||
case "delegatetask":
|
||||
case "subagent":
|
||||
case "agent":
|
||||
return translate("agentHost.agentTool.labels.delegateAgent");
|
||||
case "closeagent":
|
||||
return translate("agentHost.agentTool.labels.closeAgent");
|
||||
case "wait":
|
||||
return translate("agentHost.agentTool.labels.waitAgent");
|
||||
default:
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import { useMemo, useState, type JSX } from "react";
|
||||
import { translate } from "../../../../../i18n/index";
|
||||
import { workspaceFilePathBasename } from "../../../../../actions/workspaceFilePathCandidate";
|
||||
import { AgentPathTailLabel } from "../AgentPathTailLabel";
|
||||
|
||||
const MAX_VISIBLE_LINES = 120;
|
||||
|
||||
export function AgentCodeBlock({
|
||||
path,
|
||||
content,
|
||||
language,
|
||||
showHeader = true,
|
||||
collapsible = false,
|
||||
flat = false
|
||||
}: {
|
||||
path?: string | null;
|
||||
content: string;
|
||||
language?: string | null;
|
||||
showHeader?: boolean;
|
||||
collapsible?: boolean;
|
||||
flat?: boolean;
|
||||
}): JSX.Element {
|
||||
"use memo";
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const normalized = content.trimEnd();
|
||||
const isEmpty = !normalized;
|
||||
const emptyPlaceholder = translate(
|
||||
"agentHost.agentGui.codeBlockEmptyContent"
|
||||
);
|
||||
const lines = useMemo(
|
||||
() => (isEmpty ? [] : normalized.split("\n")),
|
||||
[isEmpty, normalized]
|
||||
);
|
||||
const lineCount = lines.length;
|
||||
const truncated = collapsible && !expanded && lineCount > MAX_VISIBLE_LINES;
|
||||
const visibleContent = truncated
|
||||
? lines.slice(0, MAX_VISIBLE_LINES).join("\n")
|
||||
: isEmpty
|
||||
? emptyPlaceholder
|
||||
: normalized;
|
||||
const visibleLines = useMemo(
|
||||
() =>
|
||||
(truncated ? lines.slice(0, MAX_VISIBLE_LINES) : lines).map(
|
||||
(line, lineIndex) => ({
|
||||
key: `${lineIndex + 1}:${line}`,
|
||||
line,
|
||||
lineNumber: lineIndex + 1
|
||||
})
|
||||
),
|
||||
[lines, truncated]
|
||||
);
|
||||
const addedCount = lineCount;
|
||||
const fileLabel = fileNameFromPath(path) ?? path ?? "Code";
|
||||
const disclosureButton =
|
||||
collapsible && lineCount > MAX_VISIBLE_LINES ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center px-3 py-2 text-left text-[11px] font-medium text-[var(--tutti-purple)] transition-colors"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded
|
||||
? translate("agentHost.agentTool.details.collapseContent")
|
||||
: translate("agentHost.agentTool.details.showFullContent", {
|
||||
count: lineCount
|
||||
})}
|
||||
</button>
|
||||
) : null;
|
||||
return (
|
||||
<div
|
||||
className={`workspace-agents-status-panel__detail-tool-code overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--background-panel)] ${
|
||||
flat ? "workspace-agents-status-panel__detail-tool-code--flat" : ""
|
||||
}`}
|
||||
{...(isEmpty ? { "data-agent-code-empty": "true" } : {})}
|
||||
>
|
||||
{flat ? (
|
||||
<>
|
||||
{showHeader ? (
|
||||
<div className="flex items-center justify-between gap-3 border-b border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-1.5 text-[11px]">
|
||||
<span
|
||||
className="truncate font-[var(--tsh-font-mono)] text-[var(--text-secondary)]"
|
||||
title={path ?? undefined}
|
||||
>
|
||||
{fileLabel}
|
||||
</span>
|
||||
{addedCount > 0 ? (
|
||||
<span className="shrink-0 font-semibold text-[var(--state-success)]">
|
||||
+{addedCount}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="workspace-agents-status-panel__detail-scroll-region max-h-[240px] overflow-auto bg-[var(--background-panel)]">
|
||||
{isEmpty ? (
|
||||
<pre className="m-0 px-3 py-2 font-[var(--tsh-font-mono)] text-[11px] leading-6 text-[var(--text-primary)]">
|
||||
<code>{emptyPlaceholder}</code>
|
||||
</pre>
|
||||
) : (
|
||||
<>
|
||||
{visibleLines.map((line) => (
|
||||
<div
|
||||
key={line.key}
|
||||
className="grid grid-cols-[56px_minmax(0,1fr)] border-l-[3px] border-l-[var(--state-success)] font-[var(--tsh-font-mono)] text-[11px] leading-6"
|
||||
>
|
||||
<div className="select-none px-2.5 text-right text-[color:color-mix(in_srgb,var(--state-success)_90%,transparent)]">
|
||||
{line.lineNumber}
|
||||
</div>
|
||||
<pre className="m-0 overflow-x-auto px-3 py-0 text-[var(--text-primary)]">
|
||||
<code>{line.line || " "}</code>
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
{disclosureButton}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{showHeader ? (
|
||||
<div className="flex items-center justify-between gap-3 border-b border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-1.5 text-[11px] text-[var(--text-secondary)]">
|
||||
<AgentPathTailLabel
|
||||
path={path}
|
||||
fallback="Code"
|
||||
className="font-[var(--tsh-font-mono)]"
|
||||
/>
|
||||
<span className="shrink-0">
|
||||
{language ? `${language} · ` : ""}
|
||||
{lineCount} lines
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
<pre className="workspace-agents-status-panel__detail-scroll-region max-h-[200px] overflow-auto px-3 py-2 text-[11px] leading-5 text-[var(--text-primary)]">
|
||||
<code>{visibleContent}</code>
|
||||
</pre>
|
||||
{disclosureButton}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function fileNameFromPath(path: string | null | undefined): string | null {
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
const normalized = path.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
return workspaceFilePathBasename(normalized) || normalized;
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
import { act, render, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { MonacoModule } from "./loadMonaco";
|
||||
import { loadMonaco } from "./loadMonaco";
|
||||
import { AgentMonacoDiffViewer } from "./AgentMonacoDiffViewer";
|
||||
|
||||
vi.mock("./loadMonaco", () => ({
|
||||
loadMonaco: vi.fn()
|
||||
}));
|
||||
|
||||
describe("AgentMonacoDiffViewer", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(loadMonaco).mockReset();
|
||||
});
|
||||
|
||||
it("detaches models before disposing the editor and owned models", async () => {
|
||||
const harness = createMonacoHarness();
|
||||
vi.mocked(loadMonaco).mockResolvedValue(harness.monaco);
|
||||
|
||||
const view = render(
|
||||
<AgentMonacoDiffViewer
|
||||
oldValue="before"
|
||||
newValue="after"
|
||||
path="/workspace/file.ts"
|
||||
showHeader={false}
|
||||
/>
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(harness.createDiffEditor).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
view.unmount();
|
||||
|
||||
expect(harness.events).toEqual([
|
||||
"editor.setModel",
|
||||
"editor.setModel(null)",
|
||||
"editor.dispose",
|
||||
"originalModel.dispose",
|
||||
"modifiedModel.dispose"
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create Monaco resources after unmounting during load", async () => {
|
||||
const harness = createMonacoHarness();
|
||||
let resolveMonaco: ((monaco: MonacoModule) => void) | null = null;
|
||||
vi.mocked(loadMonaco).mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
resolveMonaco = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
const view = render(
|
||||
<AgentMonacoDiffViewer
|
||||
oldValue="before"
|
||||
newValue="after"
|
||||
showHeader={false}
|
||||
/>
|
||||
);
|
||||
view.unmount();
|
||||
await act(async () => {
|
||||
resolveMonaco?.(harness.monaco);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(harness.createModel).not.toHaveBeenCalled();
|
||||
expect(harness.createDiffEditor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates the existing models when diff content changes", async () => {
|
||||
const harness = createMonacoHarness();
|
||||
vi.mocked(loadMonaco).mockResolvedValue(harness.monaco);
|
||||
|
||||
const view = render(
|
||||
<AgentMonacoDiffViewer
|
||||
oldValue="before"
|
||||
newValue="after"
|
||||
path="/workspace/file.ts"
|
||||
showHeader={false}
|
||||
/>
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(harness.createDiffEditor).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
view.rerender(
|
||||
<AgentMonacoDiffViewer
|
||||
oldValue="older"
|
||||
newValue="newer"
|
||||
path="/workspace/file.ts"
|
||||
showHeader={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(harness.originalModel.setValue).toHaveBeenCalledWith("older");
|
||||
expect(harness.modifiedModel.setValue).toHaveBeenCalledWith("newer");
|
||||
expect(harness.createDiffEditor).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
function createMonacoHarness(): {
|
||||
monaco: MonacoModule;
|
||||
events: string[];
|
||||
createModel: ReturnType<typeof vi.fn>;
|
||||
createDiffEditor: ReturnType<typeof vi.fn>;
|
||||
originalModel: ReturnType<typeof createTextModel>;
|
||||
modifiedModel: ReturnType<typeof createTextModel>;
|
||||
} {
|
||||
const events: string[] = [];
|
||||
const originalModel = createTextModel("before", "typescript", () => {
|
||||
events.push("originalModel.dispose");
|
||||
});
|
||||
const modifiedModel = createTextModel("after", "typescript", () => {
|
||||
events.push("modifiedModel.dispose");
|
||||
});
|
||||
const createModel = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(originalModel)
|
||||
.mockReturnValueOnce(modifiedModel);
|
||||
const editor = {
|
||||
setModel: vi.fn((model: unknown) => {
|
||||
events.push(model === null ? "editor.setModel(null)" : "editor.setModel");
|
||||
}),
|
||||
dispose: vi.fn(() => {
|
||||
events.push("editor.dispose");
|
||||
})
|
||||
};
|
||||
const createDiffEditor = vi.fn(() => editor);
|
||||
const monaco = {
|
||||
editor: {
|
||||
createModel,
|
||||
createDiffEditor,
|
||||
setTheme: vi.fn(),
|
||||
setModelLanguage: vi.fn()
|
||||
}
|
||||
} as unknown as MonacoModule;
|
||||
|
||||
return {
|
||||
monaco,
|
||||
events,
|
||||
createModel,
|
||||
createDiffEditor,
|
||||
originalModel,
|
||||
modifiedModel
|
||||
};
|
||||
}
|
||||
|
||||
function createTextModel(
|
||||
initialValue: string,
|
||||
language: string,
|
||||
onDispose: () => void
|
||||
) {
|
||||
let value = initialValue;
|
||||
let disposed = false;
|
||||
return {
|
||||
getValue: vi.fn(() => value),
|
||||
setValue: vi.fn((nextValue: string) => {
|
||||
value = nextValue;
|
||||
}),
|
||||
getLanguageId: vi.fn(() => language),
|
||||
isDisposed: vi.fn(() => disposed),
|
||||
dispose: vi.fn(() => {
|
||||
disposed = true;
|
||||
onDispose();
|
||||
})
|
||||
};
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
import { Component, createRef, type JSX } from "react";
|
||||
import { AtomIcon } from "../../../../../app/renderer/components/icons/AtomIcon";
|
||||
import { translate } from "../../../../../i18n/index";
|
||||
import { AgentPathTailLabel } from "../AgentPathTailLabel";
|
||||
import { loadMonaco, type MonacoModule } from "./loadMonaco";
|
||||
|
||||
interface MonacoDiffResources {
|
||||
monaco: MonacoModule;
|
||||
editor: import("monaco-editor").editor.IStandaloneDiffEditor;
|
||||
originalModel: import("monaco-editor").editor.ITextModel;
|
||||
modifiedModel: import("monaco-editor").editor.ITextModel;
|
||||
}
|
||||
|
||||
interface MonacoDiffContent {
|
||||
oldValue: string;
|
||||
newValue: string;
|
||||
language: string;
|
||||
}
|
||||
|
||||
type MonacoDiffEditorSurfaceProps = MonacoDiffContent;
|
||||
|
||||
interface MonacoDiffEditorSurfaceState {
|
||||
loadError: Error | null;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function AgentMonacoDiffViewer({
|
||||
path,
|
||||
oldValue,
|
||||
newValue,
|
||||
flat = false,
|
||||
showHeader = true
|
||||
}: {
|
||||
path?: string | null;
|
||||
oldValue: string;
|
||||
newValue: string;
|
||||
flat?: boolean;
|
||||
showHeader?: boolean;
|
||||
}): JSX.Element {
|
||||
"use memo";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--background-panel)] ${
|
||||
flat ? "workspace-agents-status-panel__detail-tool-monaco--flat" : ""
|
||||
}`}
|
||||
>
|
||||
{showHeader ? (
|
||||
<div
|
||||
className="border-b border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-1.5 text-[11px] text-[var(--text-secondary)]"
|
||||
data-agent-diff-header="true"
|
||||
>
|
||||
<AgentPathTailLabel
|
||||
path={path}
|
||||
fallback="Diff"
|
||||
className="font-[var(--tsh-font-mono)]"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="h-[220px] bg-[var(--background-panel)]">
|
||||
<MonacoDiffEditorSurface
|
||||
oldValue={oldValue}
|
||||
newValue={newValue}
|
||||
language={languageForPath(path)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Monaco's diff editor and its two text models form one imperative resource
|
||||
// lifetime. A class component makes the required mount/update/unmount ordering
|
||||
// explicit without coordinating multiple React effects.
|
||||
class MonacoDiffEditorSurface extends Component<
|
||||
MonacoDiffEditorSurfaceProps,
|
||||
MonacoDiffEditorSurfaceState
|
||||
> {
|
||||
private readonly containerRef = createRef<HTMLDivElement>();
|
||||
private resources: MonacoDiffResources | null = null;
|
||||
private loadGeneration = 0;
|
||||
|
||||
state: MonacoDiffEditorSurfaceState = {
|
||||
loadError: null,
|
||||
loading: true
|
||||
};
|
||||
|
||||
componentDidMount(): void {
|
||||
const loadGeneration = ++this.loadGeneration;
|
||||
void loadMonaco()
|
||||
.then((monaco) => {
|
||||
const container = this.containerRef.current;
|
||||
if (loadGeneration !== this.loadGeneration || !container) {
|
||||
return;
|
||||
}
|
||||
this.resources = createMonacoDiffResources(
|
||||
monaco,
|
||||
container,
|
||||
this.props
|
||||
);
|
||||
this.setState({ loading: false });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (loadGeneration === this.loadGeneration) {
|
||||
this.setState({
|
||||
loadError: error instanceof Error ? error : new Error(String(error))
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
componentDidUpdate(): void {
|
||||
if (this.resources) {
|
||||
updateMonacoDiffResources(this.resources, this.props);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount(): void {
|
||||
this.loadGeneration += 1;
|
||||
const resources = this.resources;
|
||||
this.resources = null;
|
||||
if (resources) {
|
||||
disposeMonacoDiffResources(resources);
|
||||
}
|
||||
}
|
||||
|
||||
render(): JSX.Element {
|
||||
if (this.state.loadError) {
|
||||
throw this.state.loadError;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<div ref={this.containerRef} className="h-full w-full" />
|
||||
{this.state.loading ? (
|
||||
<div className="absolute inset-0 flex items-start gap-1.5 px-3 py-2.5 text-[11px] text-[var(--text-secondary)]">
|
||||
<AtomIcon
|
||||
size={14}
|
||||
active
|
||||
aria-hidden="true"
|
||||
className="shrink-0"
|
||||
/>
|
||||
<span>{translate("agentHost.agentTool.details.loadingDiff")}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function createMonacoDiffResources(
|
||||
monaco: MonacoModule,
|
||||
container: HTMLDivElement,
|
||||
content: MonacoDiffContent
|
||||
): MonacoDiffResources {
|
||||
const originalModel = monaco.editor.createModel(
|
||||
content.oldValue,
|
||||
content.language
|
||||
);
|
||||
const modifiedModel = monaco.editor.createModel(
|
||||
content.newValue,
|
||||
content.language
|
||||
);
|
||||
let editor: import("monaco-editor").editor.IStandaloneDiffEditor | null =
|
||||
null;
|
||||
|
||||
try {
|
||||
monaco.editor.setTheme("light");
|
||||
editor = monaco.editor.createDiffEditor(container, {
|
||||
readOnly: true,
|
||||
renderSideBySide: true,
|
||||
minimap: { enabled: false },
|
||||
scrollBeyondLastLine: false,
|
||||
wordWrap: "on",
|
||||
automaticLayout: true
|
||||
});
|
||||
editor.setModel({
|
||||
original: originalModel,
|
||||
modified: modifiedModel
|
||||
});
|
||||
return { monaco, editor, originalModel, modifiedModel };
|
||||
} catch (error) {
|
||||
if (editor) {
|
||||
try {
|
||||
editor.setModel(null);
|
||||
} finally {
|
||||
try {
|
||||
editor.dispose();
|
||||
} finally {
|
||||
disposeMonacoModels(originalModel, modifiedModel);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
disposeMonacoModels(originalModel, modifiedModel);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function updateMonacoDiffResources(
|
||||
resources: MonacoDiffResources,
|
||||
content: MonacoDiffContent
|
||||
): void {
|
||||
if (resources.originalModel.getValue() !== content.oldValue) {
|
||||
resources.originalModel.setValue(content.oldValue);
|
||||
}
|
||||
if (resources.modifiedModel.getValue() !== content.newValue) {
|
||||
resources.modifiedModel.setValue(content.newValue);
|
||||
}
|
||||
|
||||
const currentLanguage = resources.originalModel.getLanguageId();
|
||||
if (currentLanguage !== content.language) {
|
||||
resources.monaco.editor.setModelLanguage(
|
||||
resources.originalModel,
|
||||
content.language
|
||||
);
|
||||
resources.monaco.editor.setModelLanguage(
|
||||
resources.modifiedModel,
|
||||
content.language
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function disposeMonacoDiffResources(resources: MonacoDiffResources): void {
|
||||
try {
|
||||
resources.editor.setModel(null);
|
||||
} finally {
|
||||
try {
|
||||
resources.editor.dispose();
|
||||
} finally {
|
||||
disposeMonacoModels(resources.originalModel, resources.modifiedModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disposeMonacoModels(
|
||||
originalModel: import("monaco-editor").editor.ITextModel,
|
||||
modifiedModel: import("monaco-editor").editor.ITextModel
|
||||
): void {
|
||||
try {
|
||||
originalModel.dispose();
|
||||
} finally {
|
||||
modifiedModel.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function languageForPath(path: string | null | undefined): string {
|
||||
const extension = path?.split(".").pop()?.toLowerCase();
|
||||
switch (extension) {
|
||||
case "ts":
|
||||
case "tsx":
|
||||
return "typescript";
|
||||
case "js":
|
||||
case "jsx":
|
||||
return "javascript";
|
||||
case "go":
|
||||
return "go";
|
||||
case "md":
|
||||
return "markdown";
|
||||
case "json":
|
||||
return "json";
|
||||
default:
|
||||
return "plaintext";
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
import { useMemo, useState, type JSX } from "react";
|
||||
import { translate } from "../../../../../i18n/index";
|
||||
import { workspaceFilePathBasename } from "../../../../../actions/workspaceFilePathCandidate";
|
||||
import { AgentToolScrollArea } from "../AgentToolScrollArea";
|
||||
import { AgentPathTailLabel } from "../AgentPathTailLabel";
|
||||
import {
|
||||
parseAgentUnifiedDiffLines,
|
||||
parseAgentUnifiedDiffStats
|
||||
} from "./agentUnifiedDiff";
|
||||
|
||||
const MAX_VISIBLE_LINES = 120;
|
||||
|
||||
export function AgentUnifiedPatchViewer({
|
||||
path,
|
||||
diffText,
|
||||
showHeader = true,
|
||||
collapsible = false,
|
||||
compact = false,
|
||||
flat = false
|
||||
}: {
|
||||
path?: string | null;
|
||||
diffText: string;
|
||||
showHeader?: boolean;
|
||||
collapsible?: boolean;
|
||||
compact?: boolean;
|
||||
flat?: boolean;
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const normalized = diffText.trimEnd();
|
||||
const lines = useMemo(
|
||||
() => (normalized ? visiblePatchLines(normalized, compact) : []),
|
||||
[compact, normalized]
|
||||
);
|
||||
const diffLines = useMemo(
|
||||
() => (flat && normalized ? parseAgentUnifiedDiffLines(normalized) : []),
|
||||
[flat, normalized]
|
||||
);
|
||||
const stats = useMemo(
|
||||
() =>
|
||||
normalized
|
||||
? parseAgentUnifiedDiffStats(normalized)
|
||||
: { added: 0, removed: 0 },
|
||||
[normalized]
|
||||
);
|
||||
const fileLabel = fileNameFromPath(path) ?? path ?? "Patch";
|
||||
const truncated =
|
||||
collapsible && !expanded && lines.length > MAX_VISIBLE_LINES;
|
||||
const visibleLines = useMemo(
|
||||
() =>
|
||||
(truncated ? lines.slice(0, MAX_VISIBLE_LINES) : lines).map(
|
||||
(line, lineIndex) => ({
|
||||
key: `${lineIndex + 1}:${line}`,
|
||||
line
|
||||
})
|
||||
),
|
||||
[lines, truncated]
|
||||
);
|
||||
const visibleDiffLines = useMemo(
|
||||
() =>
|
||||
(collapsible && !expanded && diffLines.length > MAX_VISIBLE_LINES
|
||||
? diffLines.slice(0, MAX_VISIBLE_LINES)
|
||||
: diffLines
|
||||
).map((line) => ({
|
||||
key: `${line.kind}:${line.oldLineNumber ?? "x"}:${line.newLineNumber ?? "x"}:${line.text}`,
|
||||
line
|
||||
})),
|
||||
[collapsible, diffLines, expanded]
|
||||
);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const disclosureButton =
|
||||
collapsible && lines.length > MAX_VISIBLE_LINES ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center px-3 py-2 text-left text-[11px] font-medium text-[var(--tutti-purple)] transition-colors"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded
|
||||
? translate("agentHost.agentTool.details.collapseContent")
|
||||
: translate("agentHost.agentTool.details.showFullDiff", {
|
||||
count: lines.length
|
||||
})}
|
||||
</button>
|
||||
) : null;
|
||||
return (
|
||||
<div
|
||||
className={`workspace-agents-status-panel__detail-tool-diff overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--background-panel)] ${
|
||||
flat ? "workspace-agents-status-panel__detail-tool-diff--flat" : ""
|
||||
}`}
|
||||
>
|
||||
{flat ? (
|
||||
<>
|
||||
{showHeader ? (
|
||||
<div
|
||||
className="flex items-center justify-between gap-3 border-b border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-1.5 text-[11px]"
|
||||
data-agent-diff-header="true"
|
||||
>
|
||||
<span
|
||||
className="truncate font-[var(--tsh-font-mono)] text-[var(--text-secondary)]"
|
||||
title={path ?? undefined}
|
||||
>
|
||||
{fileLabel}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-2 text-[11px] font-semibold">
|
||||
<span className="text-[var(--state-success)]">
|
||||
+{stats.added}
|
||||
</span>
|
||||
<span className="text-[var(--state-danger)]">
|
||||
-{stats.removed}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
<AgentToolScrollArea viewportClassName="agent-tool-diff__viewport">
|
||||
{visibleDiffLines.map(({ key, line }) => (
|
||||
<div key={key} className={flatLineClassName(line.kind)}>
|
||||
<div className="select-none px-2.5 text-right text-[var(--text-tertiary)]">
|
||||
{line.newLineNumber ?? line.oldLineNumber ?? ""}
|
||||
</div>
|
||||
<pre className="m-0 overflow-x-auto px-3 py-0 text-[var(--text-primary)]">
|
||||
<code>{line.text || " "}</code>
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
{disclosureButton}
|
||||
</AgentToolScrollArea>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{showHeader ? (
|
||||
<div
|
||||
className="border-b border-[var(--line-2)] bg-[var(--transparency-block)] px-3 py-1.5 text-[11px] text-[var(--text-secondary)]"
|
||||
data-agent-diff-header="true"
|
||||
>
|
||||
<AgentPathTailLabel
|
||||
path={path}
|
||||
fallback="Patch"
|
||||
className="font-[var(--tsh-font-mono)]"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<AgentToolScrollArea viewportClassName="agent-tool-diff__viewport px-4 py-3 text-[11px] leading-5">
|
||||
{visibleLines.map(({ key, line }) => (
|
||||
<div key={key} className={lineClassName(line)}>
|
||||
{line || " "}
|
||||
</div>
|
||||
))}
|
||||
</AgentToolScrollArea>
|
||||
{disclosureButton}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function fileNameFromPath(path: string | null | undefined): string | null {
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
const normalized = path.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
return workspaceFilePathBasename(normalized) || normalized;
|
||||
}
|
||||
|
||||
function flatLineClassName(kind: "add" | "remove" | "context"): string {
|
||||
if (kind === "add") {
|
||||
return "grid grid-cols-[48px_minmax(0,1fr)] border-l-[2px] border-l-[var(--state-success)] bg-[color:color-mix(in_srgb,var(--state-success)_10%,transparent)] font-[var(--tsh-font-mono)] text-[11px] leading-6";
|
||||
}
|
||||
if (kind === "remove") {
|
||||
return "grid grid-cols-[48px_minmax(0,1fr)] border-l-[2px] border-l-[var(--state-danger)] bg-[color:color-mix(in_srgb,var(--state-danger)_10%,transparent)] font-[var(--tsh-font-mono)] text-[11px] leading-6";
|
||||
}
|
||||
return "agent-tool-diff__line grid grid-cols-[48px_minmax(0,1fr)] font-[var(--tsh-font-mono)] text-[11px] leading-6";
|
||||
}
|
||||
|
||||
function visiblePatchLines(value: string, compact: boolean): string[] {
|
||||
const lines = value.split("\n");
|
||||
if (!compact) {
|
||||
return lines;
|
||||
}
|
||||
const firstHunkIndex = lines.findIndex((line) => line.startsWith("@@"));
|
||||
if (firstHunkIndex <= 0) {
|
||||
return lines;
|
||||
}
|
||||
return lines.slice(firstHunkIndex);
|
||||
}
|
||||
|
||||
function lineClassName(line: string): string {
|
||||
if (line.startsWith("@@")) {
|
||||
return "border-y border-[var(--line-2)] bg-[var(--transparency-block)] px-2 py-1 text-[var(--text-secondary)]";
|
||||
}
|
||||
if (
|
||||
line.startsWith("diff --git") ||
|
||||
line.startsWith("index ") ||
|
||||
line.startsWith("--- ") ||
|
||||
line.startsWith("+++ ")
|
||||
) {
|
||||
return "px-2 py-0.5 text-[var(--text-tertiary)]";
|
||||
}
|
||||
if (line.startsWith("+")) {
|
||||
return "bg-[color:color-mix(in_srgb,var(--state-success)_10%,transparent)] px-2 py-0.5 text-[var(--state-success)]";
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
return "bg-[color:color-mix(in_srgb,var(--state-danger)_10%,transparent)] px-2 py-0.5 text-[var(--state-danger)]";
|
||||
}
|
||||
return "px-2 py-0.5 text-[var(--text-primary)]";
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
agentFileChangeStats,
|
||||
countAgentTextLines,
|
||||
isAgentUnifiedDiff,
|
||||
parseAgentUnifiedDiff,
|
||||
parseAgentUnifiedDiffLines,
|
||||
parseAgentUnifiedDiffStats
|
||||
} from "./agentUnifiedDiff";
|
||||
|
||||
describe("agentUnifiedDiff", () => {
|
||||
const diffText = [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/src/a.ts",
|
||||
"+++ b/src/a.ts",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"-const ready = false",
|
||||
"+const ready = true",
|
||||
" export const value = 1"
|
||||
].join("\n");
|
||||
|
||||
it("parses unified diff into old/new strings", () => {
|
||||
expect(parseAgentUnifiedDiff(diffText)).toEqual({
|
||||
oldString: "const ready = false\nexport const value = 1",
|
||||
newString: "const ready = true\nexport const value = 1"
|
||||
});
|
||||
});
|
||||
|
||||
it("parses added/removed diff stats", () => {
|
||||
expect(parseAgentUnifiedDiffStats(diffText)).toEqual({
|
||||
added: 1,
|
||||
removed: 1
|
||||
});
|
||||
});
|
||||
|
||||
it("does not treat file content as a unified diff", () => {
|
||||
const content = [
|
||||
"# 你好,我是 Liying 👋",
|
||||
"",
|
||||
"欢迎来到我的个人主页!",
|
||||
"",
|
||||
"我是 Liying。",
|
||||
"",
|
||||
"- 👤 名字:Liying",
|
||||
"- 🌱 正在持续学习与成长",
|
||||
"- ✨ 喜欢尝试新事物、记录想法"
|
||||
].join("\n");
|
||||
|
||||
expect(isAgentUnifiedDiff(content)).toBe(false);
|
||||
expect(parseAgentUnifiedDiffStats(content)).toEqual({
|
||||
added: 0,
|
||||
removed: 0
|
||||
});
|
||||
expect(
|
||||
agentFileChangeStats({
|
||||
changeType: "created",
|
||||
unifiedDiff: content,
|
||||
content: null,
|
||||
oldString: null,
|
||||
newString: null
|
||||
})
|
||||
).toEqual({ added: 9, removed: 0 });
|
||||
});
|
||||
|
||||
it("rejects pseudo hunk headers", () => {
|
||||
expect(isAgentUnifiedDiff("@@ notes\n- bullet")).toBe(false);
|
||||
expect(parseAgentUnifiedDiffStats("@@ notes\n- bullet")).toEqual({
|
||||
added: 0,
|
||||
removed: 0
|
||||
});
|
||||
});
|
||||
|
||||
it("counts blank lines consistently with file content", () => {
|
||||
expect(countAgentTextLines("first\n\nthird\n")).toBe(3);
|
||||
expect(countAgentTextLines("\n")).toBe(1);
|
||||
expect(countAgentTextLines(" ")).toBe(1);
|
||||
});
|
||||
|
||||
it("does not count an invalid modified body as additions", () => {
|
||||
expect(
|
||||
agentFileChangeStats({
|
||||
changeType: "modified",
|
||||
unifiedDiff: "README\n- bullet\n",
|
||||
content: null,
|
||||
oldString: null,
|
||||
newString: null
|
||||
})
|
||||
).toEqual({ added: 0, removed: 0 });
|
||||
});
|
||||
|
||||
it("computes conservative stats for modified text bodies", () => {
|
||||
expect(
|
||||
agentFileChangeStats({
|
||||
changeType: "modified",
|
||||
unifiedDiff: null,
|
||||
content: null,
|
||||
oldString: "one\ntwo\n",
|
||||
newString: "one\nthree\n"
|
||||
})
|
||||
).toEqual({ added: 1, removed: 1 });
|
||||
});
|
||||
|
||||
it("parses unified diff into numbered display lines", () => {
|
||||
expect(parseAgentUnifiedDiffLines(diffText)).toEqual([
|
||||
{
|
||||
kind: "remove",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: null,
|
||||
text: "const ready = false"
|
||||
},
|
||||
{
|
||||
kind: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
text: "const ready = true"
|
||||
},
|
||||
{
|
||||
kind: "context",
|
||||
oldLineNumber: 2,
|
||||
newLineNumber: 2,
|
||||
text: "export const value = 1"
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses deleted git diff stats", () => {
|
||||
const deletedDiff = [
|
||||
"diff --git a/a.md b/a.md",
|
||||
"deleted file mode 100644",
|
||||
"--- a/a.md",
|
||||
"+++ /dev/null",
|
||||
"@@ -1 +0,0 @@",
|
||||
"-aaaaa"
|
||||
].join("\n");
|
||||
|
||||
expect(parseAgentUnifiedDiffStats(deletedDiff)).toEqual({
|
||||
added: 0,
|
||||
removed: 1
|
||||
});
|
||||
});
|
||||
|
||||
it("parses deleted apply_patch stats", () => {
|
||||
const deletedPatch = [
|
||||
"*** Begin Patch",
|
||||
"*** Delete File: a.md",
|
||||
"@@",
|
||||
"-aaaaa",
|
||||
"*** End Patch"
|
||||
].join("\n");
|
||||
|
||||
expect(parseAgentUnifiedDiffStats(deletedPatch)).toEqual({
|
||||
added: 0,
|
||||
removed: 1
|
||||
});
|
||||
});
|
||||
|
||||
it("handles escaped newline JSON payload wrappers", () => {
|
||||
const wrapped = JSON.stringify({ content: diffText.replace(/\n/g, "\\n") });
|
||||
expect(parseAgentUnifiedDiff(wrapped)).toEqual({
|
||||
oldString: "const ready = false\nexport const value = 1",
|
||||
newString: "const ready = true\nexport const value = 1"
|
||||
});
|
||||
});
|
||||
});
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
extractAgentPatchPath,
|
||||
inferAgentPatchChangeType,
|
||||
normalizeAgentPatchText,
|
||||
type AgentPatchChangeType
|
||||
} from "../../../rules/agentPatchMetadata";
|
||||
import { isAgentUnifiedDiffText } from "../../../rules/agentUnifiedDiffValidation";
|
||||
|
||||
export { extractAgentPatchPath, inferAgentPatchChangeType };
|
||||
export type AgentUnifiedDiffChangeType = AgentPatchChangeType;
|
||||
|
||||
export interface ParsedAgentUnifiedDiff {
|
||||
oldString: string;
|
||||
newString: string;
|
||||
}
|
||||
|
||||
export interface ParsedAgentUnifiedDiffLine {
|
||||
kind: "add" | "remove" | "context";
|
||||
oldLineNumber: number | null;
|
||||
newLineNumber: number | null;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export type AgentFileChangeType =
|
||||
| "created"
|
||||
| "modified"
|
||||
| "deleted"
|
||||
| "unknown";
|
||||
|
||||
const DIFF_META_PREFIXES = [
|
||||
"diff --git ",
|
||||
"index ",
|
||||
"--- ",
|
||||
"+++ ",
|
||||
"*** "
|
||||
] as const;
|
||||
|
||||
export function parseAgentUnifiedDiff(
|
||||
diffText: string
|
||||
): ParsedAgentUnifiedDiff | null {
|
||||
if (!isAgentUnifiedDiff(diffText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedText = normalizeAgentPatchText(diffText);
|
||||
const oldLines: string[] = [];
|
||||
const newLines: string[] = [];
|
||||
let sawChangeLine = false;
|
||||
let sawHunkHeader = false;
|
||||
let hunkActive = false;
|
||||
|
||||
for (const line of normalizedText.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (/^@@(?: -\d|$)/.test(line)) {
|
||||
if (sawHunkHeader && (oldLines.length > 0 || newLines.length > 0)) {
|
||||
oldLines.push("");
|
||||
newLines.push("");
|
||||
}
|
||||
sawHunkHeader = true;
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (line === "@@" && isApplyPatch(normalizedText)) {
|
||||
if (sawHunkHeader && (oldLines.length > 0 || newLines.length > 0)) {
|
||||
oldLines.push("");
|
||||
newLines.push("");
|
||||
}
|
||||
sawHunkHeader = true;
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (hunkActive && line.startsWith("diff --git ")) {
|
||||
hunkActive = false;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(!hunkActive &&
|
||||
DIFF_META_PREFIXES.some((prefix) => line.startsWith(prefix))) ||
|
||||
(hunkActive && isApplyPatch(normalizedText) && line.startsWith("*** "))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (line === "\\ No newline at end of file") {
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("+")) {
|
||||
newLines.push(line.slice(1));
|
||||
sawChangeLine = true;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
oldLines.push(line.slice(1));
|
||||
sawChangeLine = true;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(" ")) {
|
||||
const content = line.slice(1);
|
||||
oldLines.push(content);
|
||||
newLines.push(content);
|
||||
}
|
||||
}
|
||||
|
||||
if (!sawChangeLine) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
oldString: oldLines.join("\n"),
|
||||
newString: newLines.join("\n")
|
||||
};
|
||||
}
|
||||
|
||||
export function parseAgentUnifiedDiffLines(
|
||||
diffText: string
|
||||
): ParsedAgentUnifiedDiffLine[] {
|
||||
if (!isAgentUnifiedDiff(diffText)) {
|
||||
return [];
|
||||
}
|
||||
const normalized = normalizeAgentPatchText(diffText);
|
||||
if (!normalized.trim()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const lines: ParsedAgentUnifiedDiffLine[] = [];
|
||||
let oldLineNumber = 0;
|
||||
let newLineNumber = 0;
|
||||
let hunkActive = false;
|
||||
|
||||
for (const line of normalized.replace(/\r\n/g, "\n").split("\n")) {
|
||||
const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (match) {
|
||||
oldLineNumber = Number.parseInt(match[1] ?? "0", 10);
|
||||
newLineNumber = Number.parseInt(match[2] ?? "0", 10);
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (line === "@@" && isApplyPatch(normalized)) {
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (hunkActive && line.startsWith("diff --git ")) {
|
||||
hunkActive = false;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(!hunkActive &&
|
||||
DIFF_META_PREFIXES.some((prefix) => line.startsWith(prefix))) ||
|
||||
(hunkActive && isApplyPatch(normalized) && line.startsWith("*** "))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (line === "\\ No newline at end of file") {
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("+")) {
|
||||
lines.push({
|
||||
kind: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber,
|
||||
text: line.slice(1)
|
||||
});
|
||||
newLineNumber += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
lines.push({
|
||||
kind: "remove",
|
||||
oldLineNumber,
|
||||
newLineNumber: null,
|
||||
text: line.slice(1)
|
||||
});
|
||||
oldLineNumber += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(" ")) {
|
||||
lines.push({
|
||||
kind: "context",
|
||||
oldLineNumber,
|
||||
newLineNumber,
|
||||
text: line.slice(1)
|
||||
});
|
||||
oldLineNumber += 1;
|
||||
newLineNumber += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function isAgentUnifiedDiff(diffText: string): boolean {
|
||||
return isAgentUnifiedDiffText(diffText);
|
||||
}
|
||||
|
||||
export function countAgentTextLines(value: string | null | undefined): number {
|
||||
if (typeof value !== "string" || value.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const lines = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
||||
if (lines.at(-1) === "") {
|
||||
lines.pop();
|
||||
}
|
||||
return lines.length;
|
||||
}
|
||||
|
||||
export function agentFileChangeStats({
|
||||
changeType,
|
||||
unifiedDiff,
|
||||
content,
|
||||
oldString,
|
||||
newString
|
||||
}: {
|
||||
changeType: AgentFileChangeType;
|
||||
unifiedDiff: string | null | undefined;
|
||||
content: string | null | undefined;
|
||||
oldString: string | null | undefined;
|
||||
newString: string | null | undefined;
|
||||
}): { added: number; removed: number } {
|
||||
const diff = typeof unifiedDiff === "string" ? unifiedDiff : null;
|
||||
if (diff && isAgentUnifiedDiff(diff)) {
|
||||
return parseAgentUnifiedDiffStats(diff);
|
||||
}
|
||||
|
||||
if (changeType === "deleted") {
|
||||
return {
|
||||
added: 0,
|
||||
removed: countAgentTextLines(oldString ?? content ?? diff)
|
||||
};
|
||||
}
|
||||
if (changeType === "created") {
|
||||
return {
|
||||
added: countAgentTextLines(content ?? newString ?? diff),
|
||||
removed: 0
|
||||
};
|
||||
}
|
||||
if (typeof oldString === "string" && typeof newString === "string") {
|
||||
return agentTextDiffStats(oldString, newString);
|
||||
}
|
||||
return { added: 0, removed: 0 };
|
||||
}
|
||||
|
||||
export function parseAgentUnifiedDiffStats(diffText: string): {
|
||||
added: number;
|
||||
removed: number;
|
||||
} {
|
||||
if (!isAgentUnifiedDiff(diffText)) {
|
||||
return { added: 0, removed: 0 };
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
let hunkActive = false;
|
||||
const normalized = normalizeAgentPatchText(diffText);
|
||||
for (const line of normalized.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.test(line)) {
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (line === "@@" && isApplyPatch(normalized)) {
|
||||
hunkActive = true;
|
||||
continue;
|
||||
}
|
||||
if (hunkActive && line.startsWith("diff --git ")) {
|
||||
hunkActive = false;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(!hunkActive &&
|
||||
DIFF_META_PREFIXES.some((prefix) => line.startsWith(prefix))) ||
|
||||
(hunkActive && isApplyPatch(normalized) && line.startsWith("*** "))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (line === "\\ No newline at end of file" || !hunkActive) {
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("+")) {
|
||||
added += 1;
|
||||
} else if (line.startsWith("-")) {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
return { added, removed };
|
||||
}
|
||||
|
||||
function agentTextDiffStats(
|
||||
oldString: string,
|
||||
newString: string
|
||||
): { added: number; removed: number } {
|
||||
const oldLines = splitAgentTextLines(oldString);
|
||||
const newLines = splitAgentTextLines(newString);
|
||||
if (oldLines.length === 0 && newLines.length === 0) {
|
||||
return { added: 0, removed: 0 };
|
||||
}
|
||||
if (oldLines.length * newLines.length > 2_000_000) {
|
||||
return { added: 0, removed: 0 };
|
||||
}
|
||||
|
||||
let previous = Array.from({ length: newLines.length + 1 }, () => 0);
|
||||
for (const oldLine of oldLines) {
|
||||
const current = Array.from({ length: newLines.length + 1 }, () => 0);
|
||||
for (let newIndex = 1; newIndex <= newLines.length; newIndex += 1) {
|
||||
current[newIndex] =
|
||||
oldLine === newLines[newIndex - 1]
|
||||
? previous[newIndex - 1]! + 1
|
||||
: Math.max(previous[newIndex]!, current[newIndex - 1]!);
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
|
||||
const commonLines = previous[newLines.length] ?? 0;
|
||||
return {
|
||||
added: newLines.length - commonLines,
|
||||
removed: oldLines.length - commonLines
|
||||
};
|
||||
}
|
||||
|
||||
function splitAgentTextLines(value: string): string[] {
|
||||
if (value.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const lines = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
||||
if (lines.at(-1) === "") {
|
||||
lines.pop();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isApplyPatch(value: string): boolean {
|
||||
return (
|
||||
value.includes("*** Begin Patch") &&
|
||||
(value.includes("*** Add File:") ||
|
||||
value.includes("*** Delete File:") ||
|
||||
value.includes("*** Update File:"))
|
||||
);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export type MonacoModule = typeof import("monaco-editor");
|
||||
|
||||
export function loadMonaco(): Promise<MonacoModule> {
|
||||
return import("monaco-editor");
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../../i18n/index";
|
||||
import { ToolMarkdownBlock } from "../agentToolContentShared";
|
||||
import {
|
||||
itemPrimaryText,
|
||||
itemSecondaryText,
|
||||
parsedItems,
|
||||
type AgentMcpNormalizedPayload
|
||||
} from "./agentMcpShared";
|
||||
|
||||
export function renderAtlassianMcp(
|
||||
payload: AgentMcpNormalizedPayload
|
||||
): JSX.Element | null {
|
||||
const items = parsedItems(payload.structured);
|
||||
if (items.length > 0) {
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-result-list overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)]">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={`${itemPrimaryText(item) ?? "item"}::${itemSecondaryText(item) ?? ""}`}
|
||||
className={`px-3 py-2 ${index > 0 ? "border-t border-[var(--line-2)]" : ""}`}
|
||||
>
|
||||
<div className="text-[11px] font-semibold text-[var(--text-primary)]">
|
||||
{itemPrimaryText(item) ??
|
||||
translate("agentHost.agentTool.details.mcpItem", {
|
||||
index: index + 1
|
||||
})}
|
||||
</div>
|
||||
{itemSecondaryText(item) ? (
|
||||
<div className="text-[11px] text-[var(--text-tertiary)]">
|
||||
{itemSecondaryText(item)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return payload.text ? (
|
||||
<ToolMarkdownBlock content={payload.text} collapsible />
|
||||
) : null;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { JSX } from "react";
|
||||
import { translate } from "../../../../../i18n/index";
|
||||
import { ToolMarkdownBlock } from "../agentToolContentShared";
|
||||
import {
|
||||
itemPrimaryText,
|
||||
itemSecondaryText,
|
||||
parsedItems,
|
||||
type AgentMcpNormalizedPayload
|
||||
} from "./agentMcpShared";
|
||||
|
||||
export function renderContext7Mcp(
|
||||
payload: AgentMcpNormalizedPayload
|
||||
): JSX.Element | null {
|
||||
const items = parsedItems(payload.structured);
|
||||
if (items.length > 0) {
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-result-list overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--transparency-block)]">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={`${itemPrimaryText(item) ?? "doc"}::${itemSecondaryText(item) ?? ""}`}
|
||||
className={`px-3 py-2 ${index > 0 ? "border-t border-[var(--line-2)]" : ""}`}
|
||||
>
|
||||
<div className="text-[11px] font-semibold text-[var(--text-primary)]">
|
||||
{itemPrimaryText(item) ??
|
||||
translate("agentHost.agentTool.details.mcpDoc", {
|
||||
index: index + 1
|
||||
})}
|
||||
</div>
|
||||
{itemSecondaryText(item) ? (
|
||||
<div className="text-[11px] text-[var(--text-tertiary)]">
|
||||
{itemSecondaryText(item)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return payload.text ? (
|
||||
<ToolMarkdownBlock content={payload.text} collapsible />
|
||||
) : null;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import type { JSX } from "react";
|
||||
import { renderAtlassianMcp } from "./agentAtlassianRenderers";
|
||||
import { renderContext7Mcp } from "./agentContext7Renderers";
|
||||
import type { AgentMcpNormalizedPayload } from "./agentMcpShared";
|
||||
|
||||
export function renderRegisteredMcp(
|
||||
payload: AgentMcpNormalizedPayload
|
||||
): JSX.Element | null {
|
||||
const identity =
|
||||
`${payload.server ?? ""} ${payload.tool ?? ""}`.toLowerCase();
|
||||
if (
|
||||
identity.includes("jira") ||
|
||||
identity.includes("confluence") ||
|
||||
identity.includes("atlassian")
|
||||
) {
|
||||
return renderAtlassianMcp(payload);
|
||||
}
|
||||
if (identity.includes("context7")) {
|
||||
return renderContext7Mcp(payload);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
import type { AgentToolCallVM } from "../../../contracts/agentToolCallVM";
|
||||
import { extractAgentMcpToolTarget } from "../../../../agentMcpToolTarget";
|
||||
import {
|
||||
arrayValue,
|
||||
objectValue,
|
||||
stringValue
|
||||
} from "../agentToolContentShared";
|
||||
import { structuredToolText } from "../render-data/structuredToolText";
|
||||
|
||||
export interface AgentMcpNormalizedPayload {
|
||||
server: string | null;
|
||||
tool: string | null;
|
||||
inputSummary: string | null;
|
||||
structured: unknown;
|
||||
text: string | null;
|
||||
errorText: string | null;
|
||||
}
|
||||
|
||||
export function normalizeMcpPayload(
|
||||
call: AgentToolCallVM
|
||||
): AgentMcpNormalizedPayload {
|
||||
const target = extractAgentMcpToolTarget({
|
||||
input: call.input,
|
||||
metadata: call.metadata,
|
||||
payload: call.payload,
|
||||
toolName: call.toolName,
|
||||
name: call.name
|
||||
});
|
||||
const server =
|
||||
target?.server ??
|
||||
stringValue(call.metadata?.server) ??
|
||||
stringValue(call.metadata?.serverName) ??
|
||||
stringValue(call.metadata?.mcpServer) ??
|
||||
null;
|
||||
const tool =
|
||||
target?.tool ??
|
||||
stringValue(call.metadata?.tool) ??
|
||||
stringValue(call.metadata?.toolName) ??
|
||||
call.toolName;
|
||||
|
||||
const structured = firstStructuredValue(
|
||||
call.output?.structuredContent,
|
||||
parseJsonString(call.output?.text),
|
||||
parseJsonString(call.output?.stdout)
|
||||
);
|
||||
const status = (call.status ?? "").trim().toLowerCase();
|
||||
const failed =
|
||||
call.statusKind === "failed" || status === "failed" || status === "error";
|
||||
|
||||
return {
|
||||
server,
|
||||
tool,
|
||||
inputSummary: firstString(
|
||||
stringValue(call.input?.query),
|
||||
stringValue(call.input?.url),
|
||||
stringValue(call.input?.path),
|
||||
stringValue(call.input?.prompt),
|
||||
stringValue(call.input?.command)
|
||||
),
|
||||
structured,
|
||||
text: firstString(
|
||||
stringValue(call.output?.text),
|
||||
stringValue(call.output?.stdout)
|
||||
),
|
||||
errorText:
|
||||
structuredToolText(call.error) ??
|
||||
(failed ? structuredToolText(call.output) : null)
|
||||
};
|
||||
}
|
||||
|
||||
export function parsedItems(value: unknown): Array<Record<string, unknown>> {
|
||||
if (Array.isArray(value)) {
|
||||
return value.flatMap((entry) => {
|
||||
const record = objectValue(entry);
|
||||
return record ? [record] : [];
|
||||
});
|
||||
}
|
||||
const record = objectValue(value);
|
||||
if (!record) {
|
||||
return [];
|
||||
}
|
||||
const candidateArrays = [
|
||||
arrayValue(record.issues),
|
||||
arrayValue(record.pages),
|
||||
arrayValue(record.results),
|
||||
arrayValue(record.resources),
|
||||
arrayValue(record.documents),
|
||||
arrayValue(record.docs),
|
||||
arrayValue(record.items)
|
||||
];
|
||||
for (const candidate of candidateArrays) {
|
||||
if (candidate && candidate.length > 0) {
|
||||
return candidate.flatMap((entry) => {
|
||||
const item = objectValue(entry);
|
||||
return item ? [item] : [];
|
||||
});
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function itemPrimaryText(item: Record<string, unknown>): string | null {
|
||||
return firstString(
|
||||
stringValue(item.key),
|
||||
stringValue(item.title),
|
||||
stringValue(item.name),
|
||||
stringValue(item.path),
|
||||
stringValue(item.url),
|
||||
stringValue(item.id)
|
||||
);
|
||||
}
|
||||
|
||||
export function itemSecondaryText(
|
||||
item: Record<string, unknown>
|
||||
): string | null {
|
||||
return firstString(
|
||||
stringValue(item.summary),
|
||||
stringValue(item.description),
|
||||
stringValue(item.status),
|
||||
stringValue(item.type)
|
||||
);
|
||||
}
|
||||
|
||||
function firstStructuredValue(...values: unknown[]): unknown {
|
||||
for (const value of values) {
|
||||
if (Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseJsonString(value: unknown): unknown {
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function firstString(...values: Array<string | null>): string | null {
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+587
@@ -0,0 +1,587 @@
|
||||
import type { AgentToolCallVM } from "../../../contracts/agentToolCallVM";
|
||||
import {
|
||||
extractAgentPatchPath,
|
||||
inferAgentPatchChangeType
|
||||
} from "../../../rules/agentPatchMetadata";
|
||||
import {
|
||||
agentFileChangeStats,
|
||||
isAgentUnifiedDiff
|
||||
} from "../file-diff/agentUnifiedDiff";
|
||||
import {
|
||||
fileChangeEntriesFromChanges,
|
||||
fileChangeTypeValue
|
||||
} from "../../../../workspaceAgentFileChangePayload";
|
||||
|
||||
export interface AgentFileChangeRenderData {
|
||||
path: string;
|
||||
changeType: "created" | "modified" | "deleted" | "unknown";
|
||||
language: string | null;
|
||||
content: string | null;
|
||||
oldString: string | null;
|
||||
newString: string | null;
|
||||
unifiedDiff: string | null;
|
||||
added: number;
|
||||
removed: number;
|
||||
}
|
||||
|
||||
export function getFileChangeRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentFileChangeRenderData[] {
|
||||
const payloadInput = recordValue(call.payload?.input);
|
||||
const payloadOutput = recordValue(call.payload?.output);
|
||||
const inputLocations =
|
||||
arrayValue(call.locations) ??
|
||||
arrayValue(call.input?.locations) ??
|
||||
arrayValue(payloadInput?.locations);
|
||||
const fromStructuredPatch = structuredPatchFiles(
|
||||
call.output?.structuredPatch ??
|
||||
payloadOutput?.structuredPatch ??
|
||||
call.payload?.structuredPatch ??
|
||||
call.output?.files ??
|
||||
payloadOutput?.files
|
||||
);
|
||||
if (fromStructuredPatch.length > 0) {
|
||||
return fromStructuredPatch;
|
||||
}
|
||||
|
||||
const fromDetailedContent = detailedDiffFiles(
|
||||
call.output?.detailedContent ??
|
||||
payloadOutput?.detailedContent ??
|
||||
call.payload?.detailedContent
|
||||
);
|
||||
if (fromDetailedContent.length > 0) {
|
||||
return fromDetailedContent;
|
||||
}
|
||||
|
||||
const fromFileChanges = fileChangesFiles(
|
||||
call.input?.fileChanges ??
|
||||
call.payload?.fileChanges ??
|
||||
payloadOutput?.fileChanges
|
||||
);
|
||||
if (fromFileChanges.length > 0) {
|
||||
return fromFileChanges;
|
||||
}
|
||||
|
||||
const fromChangeMap = changeMapFiles(
|
||||
call.output?.changes ??
|
||||
payloadOutput?.changes ??
|
||||
call.input?.changes ??
|
||||
payloadInput?.changes
|
||||
);
|
||||
if (fromChangeMap.length > 0) {
|
||||
return fromChangeMap;
|
||||
}
|
||||
|
||||
const inputPath = firstString(
|
||||
stringValue(call.input?.file_path),
|
||||
stringValue(call.input?.filePath),
|
||||
stringValue(call.input?.path),
|
||||
stringValue(payloadInput?.file_path),
|
||||
stringValue(payloadInput?.filePath),
|
||||
stringValue(payloadInput?.path),
|
||||
firstLocationPath(inputLocations)
|
||||
);
|
||||
const diffValues = [
|
||||
call.output?.patch,
|
||||
payloadOutput?.patch,
|
||||
call.output?.diff,
|
||||
payloadOutput?.diff
|
||||
];
|
||||
const rawDiff = firstRawString(...diffValues);
|
||||
const path = firstString(
|
||||
inputPath,
|
||||
rawDiff ? extractAgentPatchPath(rawDiff) : null
|
||||
);
|
||||
if (!path) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const content = firstFileString(call.input?.content, payloadInput?.content);
|
||||
const oldString = firstFileString(
|
||||
call.input?.old_string,
|
||||
call.input?.oldString,
|
||||
payloadInput?.old_string,
|
||||
payloadInput?.oldString,
|
||||
call.output?.oldString,
|
||||
payloadOutput?.oldString
|
||||
);
|
||||
const newString = firstFileString(
|
||||
call.input?.new_string,
|
||||
call.input?.newString,
|
||||
payloadInput?.new_string,
|
||||
payloadInput?.newString,
|
||||
call.output?.newString,
|
||||
payloadOutput?.newString
|
||||
);
|
||||
const rendered = normalizeFileChangeRenderData({
|
||||
path,
|
||||
toolName: call.toolName,
|
||||
allowSyntheticDiff: true,
|
||||
diffValues,
|
||||
content,
|
||||
oldString,
|
||||
newString
|
||||
});
|
||||
return rendered ? [rendered] : [];
|
||||
}
|
||||
|
||||
function structuredPatchFiles(value: unknown): AgentFileChangeRenderData[] {
|
||||
const patches = arrayValue(value);
|
||||
if (!patches) {
|
||||
return [];
|
||||
}
|
||||
return patches.flatMap((item) => {
|
||||
const patch = recordValue(item);
|
||||
const path = firstString(
|
||||
stringValue(patch?.filePath),
|
||||
stringValue(patch?.path)
|
||||
);
|
||||
if (!path) {
|
||||
return [];
|
||||
}
|
||||
const rendered = normalizeFileChangeRenderData({
|
||||
path,
|
||||
explicitChangeType: normalizeChangeType(fileChangeTypeValue(patch ?? {})),
|
||||
allowSyntheticDiff: false,
|
||||
diffValues: [patch?.diff, patch?.patch],
|
||||
content: firstFileString(patch?.content),
|
||||
oldString: firstFileString(patch?.oldString, patch?.old_string),
|
||||
newString: firstFileString(patch?.newString, patch?.new_string)
|
||||
});
|
||||
return rendered ? [rendered] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function detailedDiffFiles(value: unknown): AgentFileChangeRenderData[] {
|
||||
const diff = firstRawString(value);
|
||||
if (diff === null) {
|
||||
return [];
|
||||
}
|
||||
const path = diffPath(diff);
|
||||
if (!path) {
|
||||
return [];
|
||||
}
|
||||
const rendered = normalizeFileChangeRenderData({
|
||||
path,
|
||||
diffValues: [diff],
|
||||
content: null,
|
||||
oldString: null,
|
||||
newString: null
|
||||
});
|
||||
return rendered ? [rendered] : [];
|
||||
}
|
||||
|
||||
function fileChangesFiles(value: unknown): AgentFileChangeRenderData[] {
|
||||
const record = recordValue(value);
|
||||
const files = arrayValue(record?.files);
|
||||
if (!files) {
|
||||
return [];
|
||||
}
|
||||
return files.flatMap((item) => {
|
||||
const file = recordValue(item);
|
||||
const path = stringValue(file?.path);
|
||||
if (!file || !path) {
|
||||
return [];
|
||||
}
|
||||
const rendered = normalizeFileChangeRenderData({
|
||||
path,
|
||||
explicitChangeType: normalizeChangeType(fileChangeTypeValue(file)),
|
||||
diffValues: [
|
||||
file?.diff,
|
||||
file?.patch,
|
||||
file?.unifiedDiff,
|
||||
file?.unified_diff
|
||||
],
|
||||
content: firstFileString(file?.content),
|
||||
oldString: firstFileString(file?.oldString, file?.old_string),
|
||||
newString: firstFileString(file?.newString, file?.new_string)
|
||||
});
|
||||
return rendered ? [rendered] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeFileChangeRenderData({
|
||||
path,
|
||||
toolName = null,
|
||||
explicitChangeType = "unknown",
|
||||
allowSyntheticDiff = false,
|
||||
diffValues,
|
||||
content: initialContent,
|
||||
oldString: initialOldString,
|
||||
newString: initialNewString
|
||||
}: {
|
||||
path: string;
|
||||
toolName?: string | null;
|
||||
explicitChangeType?: AgentFileChangeRenderData["changeType"];
|
||||
allowSyntheticDiff?: boolean;
|
||||
diffValues: unknown[];
|
||||
content: string | null;
|
||||
oldString: string | null;
|
||||
newString: string | null;
|
||||
}): AgentFileChangeRenderData | null {
|
||||
const rawDiff = firstRawString(...diffValues);
|
||||
const unifiedDiff = firstValidUnifiedDiff(...diffValues);
|
||||
let content = initialContent;
|
||||
let oldString = initialOldString;
|
||||
let newString = initialNewString;
|
||||
let changeType = firstKnownChangeType(
|
||||
explicitChangeType,
|
||||
inferFileChangeType(toolName, unifiedDiff, content, oldString, newString)
|
||||
);
|
||||
|
||||
if (unifiedDiff === null && rawDiff !== null) {
|
||||
switch (changeType) {
|
||||
case "created":
|
||||
if (newString === null && content === null) {
|
||||
newString = fileTextValue(rawDiff);
|
||||
}
|
||||
content ??= newString;
|
||||
break;
|
||||
case "deleted":
|
||||
if (oldString === null && content === null) {
|
||||
oldString = fileTextValue(rawDiff);
|
||||
}
|
||||
if (oldString !== null && newString === null) {
|
||||
newString = "";
|
||||
}
|
||||
content = null;
|
||||
break;
|
||||
default:
|
||||
if (oldString === null && newString === null && content === null) {
|
||||
content = fileTextValue(rawDiff);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (changeType === "unknown" && content !== null) {
|
||||
changeType = "modified";
|
||||
}
|
||||
}
|
||||
if (changeType === "created" && content === null && newString !== null) {
|
||||
content = newString;
|
||||
}
|
||||
|
||||
const normalizedUnifiedDiff =
|
||||
allowSyntheticDiff &&
|
||||
unifiedDiff === null &&
|
||||
oldString !== null &&
|
||||
newString !== null
|
||||
? syntheticUnifiedDiff(path, changeType, oldString, newString)
|
||||
: unifiedDiff;
|
||||
if (
|
||||
normalizedUnifiedDiff === null &&
|
||||
content === null &&
|
||||
oldString === null &&
|
||||
newString === null &&
|
||||
changeType === "unknown"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const stats = fileChangeStats(
|
||||
changeType,
|
||||
normalizedUnifiedDiff,
|
||||
content,
|
||||
oldString,
|
||||
newString
|
||||
);
|
||||
return {
|
||||
path,
|
||||
changeType,
|
||||
language: languageForPath(path),
|
||||
content,
|
||||
oldString,
|
||||
newString,
|
||||
unifiedDiff: normalizedUnifiedDiff,
|
||||
added: stats.added,
|
||||
removed: stats.removed
|
||||
};
|
||||
}
|
||||
|
||||
function changeMapFiles(value: unknown): AgentFileChangeRenderData[] {
|
||||
return fileChangeEntriesFromChanges(value).flatMap((entry) => {
|
||||
const change = entry.change;
|
||||
const normalizedPath = entry.path.trim();
|
||||
if (!normalizedPath) {
|
||||
return [];
|
||||
}
|
||||
const normalizedType = normalizeChangeType(fileChangeTypeValue(change));
|
||||
const explicitContent = firstFileString(change.content);
|
||||
let oldString = firstFileString(change.old_string, change.oldString);
|
||||
let newString = firstFileString(
|
||||
change.new_string,
|
||||
change.newString,
|
||||
explicitContent
|
||||
);
|
||||
if (
|
||||
normalizedType === "created" &&
|
||||
oldString === null &&
|
||||
newString !== null
|
||||
) {
|
||||
oldString = "";
|
||||
}
|
||||
if (
|
||||
normalizedType === "deleted" &&
|
||||
oldString === null &&
|
||||
newString !== null
|
||||
) {
|
||||
oldString = newString;
|
||||
newString = "";
|
||||
}
|
||||
if (
|
||||
normalizedType === "deleted" &&
|
||||
newString === null &&
|
||||
oldString !== null
|
||||
) {
|
||||
newString = "";
|
||||
}
|
||||
const content = firstFileString(
|
||||
normalizedType === "deleted" ? null : explicitContent,
|
||||
normalizedType === "created" ? newString : null
|
||||
);
|
||||
const rendered = normalizeFileChangeRenderData({
|
||||
path: normalizedPath,
|
||||
explicitChangeType: normalizedType ?? "unknown",
|
||||
allowSyntheticDiff: true,
|
||||
diffValues: [
|
||||
change.unified_diff,
|
||||
change.unifiedDiff,
|
||||
change.diff,
|
||||
change.patch
|
||||
],
|
||||
content,
|
||||
oldString,
|
||||
newString
|
||||
});
|
||||
return rendered ? [rendered] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function inferFileChangeType(
|
||||
toolName: string | null,
|
||||
unifiedDiff: string | null,
|
||||
content: string | null,
|
||||
oldString: string | null,
|
||||
newString: string | null
|
||||
): AgentFileChangeRenderData["changeType"] {
|
||||
if (unifiedDiff && isAgentUnifiedDiff(unifiedDiff)) {
|
||||
return inferAgentPatchChangeType(unifiedDiff);
|
||||
}
|
||||
const normalizedToolName = normalizeToolName(toolName);
|
||||
if (
|
||||
normalizedToolName === "write" &&
|
||||
(content !== null || newString !== null)
|
||||
) {
|
||||
return "created";
|
||||
}
|
||||
if (
|
||||
normalizedToolName === "edit" ||
|
||||
oldString !== null ||
|
||||
newString !== null
|
||||
) {
|
||||
return "modified";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeChangeType(
|
||||
value: string | null
|
||||
): AgentFileChangeRenderData["changeType"] {
|
||||
switch ((value ?? "").trim().toLowerCase()) {
|
||||
case "add":
|
||||
case "create":
|
||||
case "created":
|
||||
case "added":
|
||||
return "created";
|
||||
case "edit":
|
||||
case "modify":
|
||||
case "modified":
|
||||
case "change":
|
||||
case "changed":
|
||||
case "update":
|
||||
case "updated":
|
||||
return "modified";
|
||||
case "delete":
|
||||
case "deleted":
|
||||
case "remove":
|
||||
case "removed":
|
||||
return "deleted";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function firstKnownChangeType(
|
||||
...values: Array<AgentFileChangeRenderData["changeType"]>
|
||||
): AgentFileChangeRenderData["changeType"] {
|
||||
for (const value of values) {
|
||||
if (value !== "unknown") {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function diffPath(value: string): string | null {
|
||||
const match = value.match(/^diff --git a\/(.+?) b\/(.+)$/m);
|
||||
return match?.[2]?.trim() ?? match?.[1]?.trim() ?? null;
|
||||
}
|
||||
|
||||
function fileChangeStats(
|
||||
changeType: AgentFileChangeRenderData["changeType"],
|
||||
unifiedDiff: string | null,
|
||||
content: string | null,
|
||||
oldString: string | null,
|
||||
newString: string | null
|
||||
): { added: number; removed: number } {
|
||||
return agentFileChangeStats({
|
||||
changeType,
|
||||
unifiedDiff,
|
||||
content,
|
||||
oldString,
|
||||
newString
|
||||
});
|
||||
}
|
||||
|
||||
function syntheticUnifiedDiff(
|
||||
path: string,
|
||||
changeType: AgentFileChangeRenderData["changeType"],
|
||||
oldString: string,
|
||||
newString: string
|
||||
): string {
|
||||
const oldLines = patchLines(oldString);
|
||||
const newLines = patchLines(newString);
|
||||
switch (changeType) {
|
||||
case "created":
|
||||
return [
|
||||
`diff --git a/${path} b/${path}`,
|
||||
"new file mode 100644",
|
||||
"--- /dev/null",
|
||||
`+++ b/${path}`,
|
||||
`@@ -0,0 +1,${newLines.length} @@`,
|
||||
...newLines.map((line) => `+${line}`)
|
||||
].join("\n");
|
||||
case "deleted":
|
||||
return [
|
||||
`diff --git a/${path} b/${path}`,
|
||||
"deleted file mode 100644",
|
||||
`--- a/${path}`,
|
||||
"+++ /dev/null",
|
||||
`@@ -1,${oldLines.length} +0,0 @@`,
|
||||
...oldLines.map((line) => `-${line}`)
|
||||
].join("\n");
|
||||
default:
|
||||
return [
|
||||
`diff --git a/${path} b/${path}`,
|
||||
`--- a/${path}`,
|
||||
`+++ b/${path}`,
|
||||
`@@ -1,${oldLines.length} +1,${newLines.length} @@`,
|
||||
...oldLines.map((line) => `-${line}`),
|
||||
...newLines.map((line) => `+${line}`)
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
function patchLines(value: string): string[] {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
|
||||
return normalized ? normalized.split("\n") : [];
|
||||
}
|
||||
|
||||
function languageForPath(path: string): string | null {
|
||||
const extension = path.split(".").pop()?.toLowerCase();
|
||||
switch (extension) {
|
||||
case "ts":
|
||||
case "tsx":
|
||||
return "typescript";
|
||||
case "js":
|
||||
case "jsx":
|
||||
return "javascript";
|
||||
case "go":
|
||||
return "go";
|
||||
case "md":
|
||||
return "markdown";
|
||||
case "json":
|
||||
return "json";
|
||||
default:
|
||||
return extension || null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeToolName(value: string | null): string {
|
||||
return (value ?? "")
|
||||
.trim()
|
||||
.replace(/[_\s-]+/g, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function firstString(
|
||||
...values: Array<string | null | undefined>
|
||||
): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function firstRawString(...values: unknown[]): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function firstValidUnifiedDiff(...values: unknown[]): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && isAgentUnifiedDiff(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function firstFileString(...values: unknown[]): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string") {
|
||||
return fileTextValue(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fileTextValue(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : value;
|
||||
}
|
||||
|
||||
function recordValue(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function arrayValue(value: unknown): unknown[] | null {
|
||||
return Array.isArray(value) ? value : null;
|
||||
}
|
||||
|
||||
function firstLocationPath(value: unknown[] | null): string | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
for (const item of value) {
|
||||
const record = recordValue(item);
|
||||
const path = stringValue(record?.path);
|
||||
if (path) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
+1035
File diff suppressed because it is too large.
Load diff
+658
@@ -0,0 +1,658 @@
|
||||
import type { AgentToolCallVM } from "../../../contracts/agentToolCallVM";
|
||||
import { extractImageGenerationPreview } from "../../../../imageGenerationTool";
|
||||
import { workspaceFilePathBasename } from "../../../../../actions/workspaceFilePathCandidate";
|
||||
import type { AgentTaskStepVM } from "../../../contracts/agentTaskItemVM";
|
||||
import { structuredToolText } from "./structuredToolText";
|
||||
import type {
|
||||
AgentCommandRenderData,
|
||||
AgentCommandStatus,
|
||||
AgentImageGenerationRenderData,
|
||||
AgentMcpRenderData,
|
||||
AgentPlanModeRenderData,
|
||||
AgentSearchRenderData,
|
||||
AgentSkillRenderData,
|
||||
AgentTaskRenderData,
|
||||
AgentTodoRenderData,
|
||||
AgentToolFallbackText,
|
||||
AgentToolSearchRenderData,
|
||||
AgentWebFetchRenderData,
|
||||
AgentWebSearchRenderData
|
||||
} from "./agentToolRenderDataTypes";
|
||||
export type * from "./agentToolRenderDataTypes";
|
||||
export {
|
||||
getFileChangeRenderData,
|
||||
type AgentFileChangeRenderData
|
||||
} from "./agentToolFileChangeRenderData";
|
||||
|
||||
export function getCommandRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentCommandRenderData {
|
||||
const payloadInput = recordValue(call.payload?.input);
|
||||
return {
|
||||
command: firstString(
|
||||
stringValue(call.input?.command),
|
||||
stringValue(call.input?.cmd),
|
||||
commandArrayToString(call.input?.command),
|
||||
stringValue(call.payload?.command),
|
||||
stringValue(payloadInput?.command),
|
||||
stringValue(payloadInput?.cmd)
|
||||
),
|
||||
cwd: firstString(
|
||||
stringValue(call.input?.cwd),
|
||||
stringValue(payloadInput?.cwd)
|
||||
),
|
||||
stdout:
|
||||
firstRawString(
|
||||
rawStringValue(call.output?.stdout),
|
||||
rawStringValue(call.output?.text),
|
||||
rawStringValue(call.error?.stdout),
|
||||
rawStringValue(call.error?.text)
|
||||
) ?? "",
|
||||
stderr:
|
||||
firstRawString(
|
||||
rawStringValue(call.output?.stderr),
|
||||
rawStringValue(call.error?.stderr)
|
||||
) ?? "",
|
||||
exitCode:
|
||||
numberValue(call.output?.exitCode) ?? numberValue(call.error?.exitCode),
|
||||
durationMs:
|
||||
durationToMs(call.output?.duration) ??
|
||||
numberValue(call.output?.durationMs) ??
|
||||
durationToMs(call.error?.duration) ??
|
||||
numberValue(call.error?.durationMs),
|
||||
status: normalizeCommandStatus(call.statusKind ?? call.status)
|
||||
};
|
||||
}
|
||||
|
||||
export function getSearchRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentSearchRenderData {
|
||||
const canonicalFiles = locationPaths(call.locations);
|
||||
const output =
|
||||
firstString(
|
||||
stringValue(call.output?.text),
|
||||
stringValue(call.output?.stdout),
|
||||
stringValue(call.summary),
|
||||
""
|
||||
) ?? "";
|
||||
const outputLines = output.split("\n").filter(Boolean);
|
||||
const mode =
|
||||
canonicalFiles.length > 0 && !output
|
||||
? "list_files"
|
||||
: searchMode(call.output, output);
|
||||
const filenames =
|
||||
canonicalFiles.length > 0
|
||||
? canonicalFiles
|
||||
: stringArray(call.output?.filenames);
|
||||
return {
|
||||
query: firstString(
|
||||
stringValue(call.input?.pattern),
|
||||
stringValue(call.input?.query),
|
||||
stringValue(call.input?.search_query),
|
||||
stringValue(call.input?.searchQuery),
|
||||
stringValue(call.input?.glob)
|
||||
),
|
||||
scope: firstString(
|
||||
stringValue(call.input?.path),
|
||||
stringValue(call.input?.file_path),
|
||||
stringValue(call.input?.glob)
|
||||
),
|
||||
mode,
|
||||
files:
|
||||
filenames.length > 0
|
||||
? filenames
|
||||
: mode === "list_files"
|
||||
? outputLines
|
||||
: [],
|
||||
lines: outputLines,
|
||||
output,
|
||||
error:
|
||||
firstString(
|
||||
stringValue(call.error?.text),
|
||||
stringValue(call.error?.stdout),
|
||||
stringValue(call.error?.stderr),
|
||||
stringValue(call.error?.message),
|
||||
structuredText(call.error)
|
||||
) ?? ""
|
||||
};
|
||||
}
|
||||
|
||||
export function getWebSearchRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentWebSearchRenderData {
|
||||
const queries = normalizedQueries(
|
||||
call.input?.search_query,
|
||||
call.input?.searchQuery,
|
||||
recordValue(call.input?.action)?.search_query,
|
||||
recordValue(call.input?.action)?.searchQuery
|
||||
);
|
||||
return {
|
||||
query: firstString(
|
||||
stringValue(call.input?.query),
|
||||
stringValue(recordValue(call.input?.action)?.query),
|
||||
queries[0] ?? null
|
||||
),
|
||||
queries,
|
||||
url: firstString(
|
||||
stringValue(call.input?.url),
|
||||
stringValue(recordValue(call.input?.action)?.url)
|
||||
),
|
||||
output:
|
||||
firstString(
|
||||
stringValue(call.output?.text),
|
||||
stringValue(call.output?.stdout)
|
||||
) ?? "",
|
||||
error:
|
||||
firstString(
|
||||
stringValue(call.error?.message),
|
||||
stringValue(call.error?.stdout),
|
||||
structuredText(call.error)
|
||||
) ?? ""
|
||||
};
|
||||
}
|
||||
|
||||
export function getWebFetchRenderData(
|
||||
call: AgentToolCallVM,
|
||||
maxContentLength = 3000
|
||||
): AgentWebFetchRenderData {
|
||||
const url = firstString(
|
||||
stringValue(call.input?.url),
|
||||
stringValue(recordValue(call.input?.action)?.url)
|
||||
);
|
||||
const content = firstString(
|
||||
stringValue(call.output?.text),
|
||||
stringValue(call.output?.stdout)
|
||||
);
|
||||
return {
|
||||
url,
|
||||
domain: domainForUrl(url),
|
||||
content,
|
||||
visibleContent: content ? content.slice(0, maxContentLength) : null,
|
||||
isTruncated: Boolean(content && content.length > maxContentLength)
|
||||
};
|
||||
}
|
||||
|
||||
export function getTodoRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentTodoRenderData[] {
|
||||
const todos = arrayValue(call.input?.todos);
|
||||
if (!todos) {
|
||||
return [];
|
||||
}
|
||||
return todos.flatMap((todo) => {
|
||||
const record = recordValue(todo);
|
||||
const content = firstString(
|
||||
stringValue(record?.content),
|
||||
stringValue(record?.text)
|
||||
);
|
||||
if (!content) {
|
||||
return [];
|
||||
}
|
||||
return [{ content, status: stringValue(record?.status) }];
|
||||
});
|
||||
}
|
||||
|
||||
export function getMcpRenderData(call: AgentToolCallVM): AgentMcpRenderData {
|
||||
return {
|
||||
server: firstString(
|
||||
stringValue(call.metadata?.server),
|
||||
stringValue(call.metadata?.serverName),
|
||||
stringValue(call.metadata?.mcpServer)
|
||||
),
|
||||
tool: call.toolName,
|
||||
summary: stringValue(call.summary),
|
||||
output:
|
||||
firstString(
|
||||
stringValue(call.output?.text),
|
||||
stringValue(call.output?.stdout)
|
||||
) ?? ""
|
||||
};
|
||||
}
|
||||
|
||||
export function getToolSearchRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentToolSearchRenderData {
|
||||
const query = stringValue(call.input?.query);
|
||||
const matches =
|
||||
arrayValue(call.output?.matches)
|
||||
?.map(stringValue)
|
||||
.filter((value): value is string => value !== null) ?? [];
|
||||
const totalDeferredTools = numberValue(call.output?.totalDeferredTools);
|
||||
const mode: AgentToolSearchRenderData["mode"] = query?.startsWith("select:")
|
||||
? "direct"
|
||||
: "search";
|
||||
const displayQuery = query?.startsWith("select:")
|
||||
? query.slice("select:".length)
|
||||
: query?.startsWith("+")
|
||||
? query.slice(1)
|
||||
: query;
|
||||
return {
|
||||
query,
|
||||
displayQuery: displayQuery ?? null,
|
||||
mode,
|
||||
matches,
|
||||
totalDeferredTools
|
||||
};
|
||||
}
|
||||
|
||||
export function getPlanModeRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentPlanModeRenderData {
|
||||
const enterText =
|
||||
call.rendererKind === "plan-enter"
|
||||
? firstString(
|
||||
stringValue(call.planMode?.plan),
|
||||
stringValue(call.output?.text),
|
||||
nonEmpty(call.summary),
|
||||
"Exploring codebase and designing implementation approach."
|
||||
)
|
||||
: null;
|
||||
const filePath = firstString(
|
||||
stringValue(call.input?.filePath),
|
||||
stringValue(call.input?.file_path)
|
||||
);
|
||||
return {
|
||||
enterText,
|
||||
plan:
|
||||
call.rendererKind === "plan-enter"
|
||||
? null
|
||||
: firstString(
|
||||
stringValue(call.input?.plan),
|
||||
stringValue(call.payload?.plan),
|
||||
nonEmpty(call.summary)
|
||||
),
|
||||
filePath,
|
||||
fileName: filePath ? workspaceFilePathBasename(filePath) : null
|
||||
};
|
||||
}
|
||||
|
||||
export function getTaskRenderData(call: AgentToolCallVM): AgentTaskRenderData {
|
||||
const task = call.task;
|
||||
const steps: AgentTaskStepVM[] =
|
||||
task?.steps ?? normalizeTaskStepsFromCall(call);
|
||||
return {
|
||||
title: task?.title ?? call.name,
|
||||
status:
|
||||
task?.status ??
|
||||
stringValue(call.metadata?.taskStatus) ??
|
||||
stringValue(call.metadata?.subagentStatus),
|
||||
durationText:
|
||||
typeof task?.durationMs === "number" && Number.isFinite(task.durationMs)
|
||||
? formatDuration(task.durationMs)
|
||||
: null,
|
||||
latestStepSummary:
|
||||
task?.status === "running" ? (steps.at(-1)?.summary ?? null) : null,
|
||||
prompt: firstString(
|
||||
stringValue(task?.prompt),
|
||||
stringValue(call.input?.prompt),
|
||||
stringValue(call.input?.description),
|
||||
stringValue(call.payload?.description)
|
||||
),
|
||||
childSessionId: firstString(
|
||||
stringValue(task?.delegateSessionId),
|
||||
stringValue(call.metadata?.childSessionID),
|
||||
stringValue(call.metadata?.child_session_id),
|
||||
stringValue(call.metadata?.subagentSessionID),
|
||||
stringValue(call.metadata?.subagent_session_id),
|
||||
stringValue(call.metadata?.subagentAgentId),
|
||||
stringValue(call.metadata?.agentId)
|
||||
),
|
||||
steps,
|
||||
resultMarkdown: firstString(
|
||||
stringValue(task?.resultMarkdown),
|
||||
firstNonEmptyStructuredText(call.output)
|
||||
),
|
||||
errorMarkdown: firstNonEmptyStructuredText(call.error)
|
||||
};
|
||||
}
|
||||
|
||||
export function getSkillRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentSkillRenderData {
|
||||
const success = booleanValue(call.output?.success);
|
||||
return {
|
||||
skill: firstString(
|
||||
stringValue(call.input?.skill),
|
||||
stringValue(call.output?.commandName),
|
||||
nonEmpty(call.summary)
|
||||
),
|
||||
args: stringValue(call.input?.args),
|
||||
success,
|
||||
statusText:
|
||||
success === null
|
||||
? null
|
||||
: success
|
||||
? "Skill loaded"
|
||||
: "Failed to load skill"
|
||||
};
|
||||
}
|
||||
|
||||
export function getImageGenerationRenderData(
|
||||
call: AgentToolCallVM
|
||||
): AgentImageGenerationRenderData {
|
||||
const preview = extractImageGenerationPreview({
|
||||
toolName: call.toolName,
|
||||
displayName: call.name,
|
||||
outputSavedPath: stringValue(call.output?.savedPath),
|
||||
outputSavedPaths: call.output?.savedPaths,
|
||||
outputMimeType: call.output?.imageMimeType,
|
||||
outputText: call.output?.text,
|
||||
inputPrompt: call.input?.prompt,
|
||||
payloadInputPrompt: recordValue(call.payload?.input)?.prompt
|
||||
});
|
||||
return {
|
||||
prompt: preview.prompt,
|
||||
imageUri: preview.imageUri,
|
||||
mimeType: preview.mimeType
|
||||
};
|
||||
}
|
||||
|
||||
export function getToolFallbackText(
|
||||
call: AgentToolCallVM
|
||||
): AgentToolFallbackText {
|
||||
return {
|
||||
summary: nonEmpty(call.summary),
|
||||
input: structuredText(call.input),
|
||||
output: structuredText(call.output),
|
||||
error: structuredText(call.error)
|
||||
};
|
||||
}
|
||||
|
||||
export function isFailedToolCall(call: AgentToolCallVM): boolean {
|
||||
if (call.statusKind === "failed") {
|
||||
return true;
|
||||
}
|
||||
const normalized = (call.status ?? "").trim().toLowerCase();
|
||||
return normalized === "failed" || normalized === "error";
|
||||
}
|
||||
|
||||
/** Human-readable failure detail for collapsed/expanded tool rows. */
|
||||
export function getToolCallFailureText(call: AgentToolCallVM): string | null {
|
||||
const fallback = getToolFallbackText(call);
|
||||
const raw = firstString(
|
||||
fallback.error,
|
||||
isFailedToolCall(call) ? fallback.output : null
|
||||
);
|
||||
return unwrapToolUseErrorText(raw);
|
||||
}
|
||||
|
||||
function unwrapToolUseErrorText(value: string | null): string | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
const match = value.match(
|
||||
/<tool_use_error>\s*([\s\S]*?)\s*<\/tool_use_error>/i
|
||||
);
|
||||
const unwrapped = match?.[1]?.trim();
|
||||
if (unwrapped) {
|
||||
return unwrapped;
|
||||
}
|
||||
return value.trim() || null;
|
||||
}
|
||||
|
||||
function normalizeTaskStepsFromCall(call: AgentToolCallVM): AgentTaskStepVM[] {
|
||||
const steps =
|
||||
arrayValue(call.metadata?.steps) ??
|
||||
arrayValue(call.output?.steps) ??
|
||||
arrayValue(call.payload?.steps) ??
|
||||
[];
|
||||
return steps.flatMap((value, index) => {
|
||||
const step = recordValue(value);
|
||||
if (!step) {
|
||||
return [];
|
||||
}
|
||||
const toolName =
|
||||
stringValue(step.toolName) ??
|
||||
stringValue(step.tool_name) ??
|
||||
stringValue(step.name) ??
|
||||
null;
|
||||
const name = toolName ? humanizeToolName(toolName) : `Step ${index + 1}`;
|
||||
const status =
|
||||
stringValue(step.status) ??
|
||||
stringValue(recordValue(step.toolResult)?.status) ??
|
||||
stringValue(recordValue(step.tool_result)?.status) ??
|
||||
null;
|
||||
const summary =
|
||||
firstNonEmptyStructuredText(
|
||||
recordValue(step.toolResult),
|
||||
recordValue(step.tool_result),
|
||||
recordValue(step.toolInput),
|
||||
recordValue(step.tool_input)
|
||||
) ?? "";
|
||||
return [
|
||||
{
|
||||
id:
|
||||
stringValue(step.toolUseId) ??
|
||||
stringValue(step.id) ??
|
||||
`step-${index + 1}`,
|
||||
turnId: call.turnId,
|
||||
name,
|
||||
toolName,
|
||||
status,
|
||||
summary,
|
||||
payload: {
|
||||
input: recordValue(step.toolInput) ?? recordValue(step.tool_input),
|
||||
output: recordValue(step.toolResult) ?? recordValue(step.tool_result),
|
||||
error: recordValue(step.toolError) ?? recordValue(step.tool_error)
|
||||
},
|
||||
tool: null,
|
||||
occurredAtUnixMs: null
|
||||
}
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function humanizeToolName(value: string): string {
|
||||
return value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.replace(/^\w/, (match) => match.toUpperCase());
|
||||
}
|
||||
|
||||
function firstNonEmptyStructuredText(...values: Array<unknown>): string | null {
|
||||
for (const value of values) {
|
||||
const text = structuredText(value);
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
export function formatAgentToolDurationMs(value: number): string {
|
||||
return formatDuration(value);
|
||||
}
|
||||
|
||||
function formatDuration(value: number): string {
|
||||
if (value < 1000) {
|
||||
return `${value}ms`;
|
||||
}
|
||||
if (value < 60_000) {
|
||||
return `${(value / 1000).toFixed(value >= 10_000 ? 0 : 1)}s`;
|
||||
}
|
||||
const minutes = Math.floor(value / 60_000);
|
||||
const seconds = Math.round((value % 60_000) / 1000);
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
function domainForUrl(url: string | null): string | null {
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCommandStatus(
|
||||
value: string | null | undefined
|
||||
): AgentCommandStatus {
|
||||
switch ((value ?? "").trim().toLowerCase()) {
|
||||
case "working":
|
||||
case "running":
|
||||
case "in_progress":
|
||||
return "running";
|
||||
case "completed":
|
||||
case "done":
|
||||
return "completed";
|
||||
case "failed":
|
||||
case "error":
|
||||
return "failed";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function searchMode(
|
||||
output: Record<string, unknown> | null,
|
||||
outputText: string
|
||||
): AgentSearchRenderData["mode"] {
|
||||
const mode = stringValue(output?.mode);
|
||||
if (
|
||||
mode === "files_with_matches" ||
|
||||
mode === "content" ||
|
||||
mode === "count" ||
|
||||
mode === "list_files"
|
||||
) {
|
||||
return mode;
|
||||
}
|
||||
if (stringArray(output?.filenames).length > 0) {
|
||||
return "files_with_matches";
|
||||
}
|
||||
if (outputText.includes(":")) {
|
||||
return "content";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function commandArrayToString(value: unknown): string | null {
|
||||
const array = arrayValue(value);
|
||||
if (!array) {
|
||||
return null;
|
||||
}
|
||||
const parts = array.flatMap((item) =>
|
||||
typeof item === "string" && item.trim() ? [item.trim()] : []
|
||||
);
|
||||
return parts.length > 0 ? parts.join(" ") : null;
|
||||
}
|
||||
|
||||
function durationToMs(value: unknown): number | null {
|
||||
const record = recordValue(value);
|
||||
if (!record) {
|
||||
return null;
|
||||
}
|
||||
const secs = numberValue(record.secs) ?? 0;
|
||||
const nanos = numberValue(record.nanos) ?? 0;
|
||||
if (secs === 0 && nanos === 0) {
|
||||
return null;
|
||||
}
|
||||
return secs * 1000 + nanos / 1_000_000;
|
||||
}
|
||||
|
||||
function structuredText(value: unknown): string | null {
|
||||
return structuredToolText(value);
|
||||
}
|
||||
|
||||
function firstString(
|
||||
...values: Array<string | null | undefined>
|
||||
): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function firstRawString(
|
||||
...values: Array<string | null | undefined>
|
||||
): string | null {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function nonEmpty(value: string | null | undefined): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function recordValue(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function arrayValue(value: unknown): unknown[] | null {
|
||||
return Array.isArray(value) ? value : null;
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function rawStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value : null;
|
||||
}
|
||||
|
||||
function numberValue(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function stringArray(value: unknown): string[] {
|
||||
const array = arrayValue(value);
|
||||
if (!array) {
|
||||
return [];
|
||||
}
|
||||
return array.flatMap((item) =>
|
||||
typeof item === "string" && item.trim() ? [item.trim()] : []
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedQueries(...values: Array<unknown>): string[] {
|
||||
for (const value of values) {
|
||||
const queries = stringArray(value);
|
||||
if (queries.length > 0) {
|
||||
return queries;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function locationPaths(value: unknown): string[] {
|
||||
const locations = arrayValue(value);
|
||||
if (!locations) {
|
||||
return [];
|
||||
}
|
||||
const paths = locations.flatMap((location) => {
|
||||
const record = recordValue(location);
|
||||
if (!record) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
firstString(
|
||||
stringValue(record.path),
|
||||
stringValue(record.filePath),
|
||||
stringValue(record.file_path)
|
||||
)
|
||||
].filter((path): path is string => path !== null);
|
||||
});
|
||||
return Array.from(new Set(paths));
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import type { AgentTaskStepVM } from "../../../contracts/agentTaskItemVM";
|
||||
|
||||
export type AgentCommandStatus = "running" | "completed" | "failed" | "unknown";
|
||||
|
||||
export interface AgentCommandRenderData {
|
||||
command: string | null;
|
||||
cwd: string | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
status: AgentCommandStatus;
|
||||
}
|
||||
|
||||
export interface AgentSearchRenderData {
|
||||
query: string | null;
|
||||
scope: string | null;
|
||||
mode: "files_with_matches" | "content" | "count" | "list_files" | "unknown";
|
||||
files: string[];
|
||||
lines: string[];
|
||||
output: string;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface AgentWebSearchRenderData {
|
||||
query: string | null;
|
||||
queries: string[];
|
||||
url: string | null;
|
||||
output: string;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface AgentWebFetchRenderData {
|
||||
url: string | null;
|
||||
domain: string | null;
|
||||
content: string | null;
|
||||
visibleContent: string | null;
|
||||
isTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface AgentTodoRenderData {
|
||||
content: string;
|
||||
status: string | null;
|
||||
}
|
||||
|
||||
export interface AgentMcpRenderData {
|
||||
server: string | null;
|
||||
tool: string | null;
|
||||
summary: string | null;
|
||||
output: string;
|
||||
}
|
||||
|
||||
export interface AgentToolSearchRenderData {
|
||||
query: string | null;
|
||||
displayQuery: string | null;
|
||||
mode: "direct" | "search";
|
||||
matches: string[];
|
||||
totalDeferredTools: number | null;
|
||||
}
|
||||
|
||||
export interface AgentPlanModeRenderData {
|
||||
enterText: string | null;
|
||||
plan: string | null;
|
||||
filePath: string | null;
|
||||
fileName: string | null;
|
||||
}
|
||||
|
||||
export interface AgentTaskRenderData {
|
||||
title: string;
|
||||
status: string | null;
|
||||
durationText: string | null;
|
||||
latestStepSummary: string | null;
|
||||
prompt: string | null;
|
||||
childSessionId: string | null;
|
||||
steps: AgentTaskStepVM[];
|
||||
resultMarkdown: string | null;
|
||||
errorMarkdown: string | null;
|
||||
}
|
||||
|
||||
export interface AgentSkillRenderData {
|
||||
skill: string | null;
|
||||
args: string | null;
|
||||
success: boolean | null;
|
||||
statusText: string | null;
|
||||
}
|
||||
|
||||
export interface AgentImageGenerationRenderData {
|
||||
prompt: string | null;
|
||||
imageUri: string | null;
|
||||
mimeType: string | null;
|
||||
}
|
||||
|
||||
export interface AgentToolFallbackText {
|
||||
summary: string | null;
|
||||
input: string | null;
|
||||
output: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { structuredToolText } from "../../../../utils/structuredToolText";
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { useMemo, useState, type JSX } from "react";
|
||||
import { AgentToolScrollArea } from "../AgentToolScrollArea";
|
||||
|
||||
const MAX_OUTPUT_LINES = 200;
|
||||
|
||||
export function AgentTerminalBlock({
|
||||
command,
|
||||
stdout,
|
||||
stderr,
|
||||
status
|
||||
}: {
|
||||
command: string | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
status: "running" | "completed" | "failed" | "unknown";
|
||||
}): JSX.Element | null {
|
||||
"use memo";
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const outputText = useMemo(
|
||||
() => [stdout, stderr].filter(Boolean).join("\n"),
|
||||
[stdout, stderr]
|
||||
);
|
||||
const outputLines = useMemo(
|
||||
() => (outputText ? outputText.split("\n") : []),
|
||||
[outputText]
|
||||
);
|
||||
const truncated = !expanded && outputLines.length > MAX_OUTPUT_LINES;
|
||||
const visibleOutput = truncated
|
||||
? outputLines.slice(0, MAX_OUTPUT_LINES).join("\n")
|
||||
: outputText;
|
||||
const failed = status === "failed";
|
||||
const hasOutput = Boolean(visibleOutput);
|
||||
const disclosureButton =
|
||||
outputLines.length > MAX_OUTPUT_LINES ? (
|
||||
<button
|
||||
type="button"
|
||||
className="mt-2 flex w-fit items-center border-0 bg-transparent p-0 text-left text-[11px] font-medium text-[var(--tutti-purple)] transition-colors hover:underline focus-visible:underline focus-visible:outline-none"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded
|
||||
? "Collapse output"
|
||||
: `Show full output (${outputLines.length} lines)`}
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="workspace-agents-status-panel__detail-tool-terminal overflow-hidden rounded-[8px] border border-[var(--line-2)] bg-[var(--background-panel)]">
|
||||
{command ? (
|
||||
<div
|
||||
className={`flex min-w-0 items-center gap-3 px-3 text-[11px] text-[var(--text-secondary)] ${
|
||||
hasOutput
|
||||
? "border-b border-[var(--line-2)] bg-[var(--transparency-block)] py-1.5"
|
||||
: "bg-[var(--transparency-block)] py-2"
|
||||
}`}
|
||||
data-agent-terminal-command-row="true"
|
||||
>
|
||||
<span className="shrink-0 font-semibold text-[var(--tutti-purple)]">
|
||||
$
|
||||
</span>
|
||||
<span
|
||||
className="min-w-0 flex-1 whitespace-pre-wrap [overflow-wrap:anywhere]"
|
||||
data-agent-terminal-command="true"
|
||||
>
|
||||
{command}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{hasOutput ? (
|
||||
<AgentToolScrollArea
|
||||
maxHeightClassName="max-h-[160px]"
|
||||
viewportClassName={`px-3 py-2 text-[11px] leading-5 ${
|
||||
failed ? "text-[var(--state-danger)]" : "text-[var(--text-primary)]"
|
||||
}`}
|
||||
>
|
||||
<pre className="m-0 min-w-0 max-w-full whitespace-pre-wrap [overflow-wrap:anywhere]">
|
||||
<code>{visibleOutput}</code>
|
||||
</pre>
|
||||
{disclosureButton}
|
||||
</AgentToolScrollArea>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user