Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 133 additions & 5 deletions src/app/api/v2/ai/chat/[buildUuid]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,17 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
writer.write(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)).catch(() => {});
};

const MAX_STORED_JSON_LENGTH = 8000;
const truncateForStorage = (value: unknown): unknown => {
try {
const json = JSON.stringify(value);
if (json.length <= MAX_STORED_JSON_LENGTH) return value;
return { _truncated: true, preview: json.slice(0, MAX_STORED_JSON_LENGTH), originalLength: json.length };
} catch {
return { _truncated: true, preview: '[non-serializable]', originalLength: 0 };
}
};

req.signal.addEventListener('abort', () => {
try {
writer.close();
Expand All @@ -146,7 +157,7 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
return;
}

const { message, clearHistory, provider, modelId, isSystemAction } = body;
const { message, clearHistory, provider, modelId, isSystemAction, mode: requestedMode } = body;

getLogger().info(
`AI: v2 chat request received provider=${provider} modelId=${modelId} hasProvider=${!!provider} hasModelId=${!!modelId}`
Expand Down Expand Up @@ -206,9 +217,32 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
let aiResponse = '';
let isJsonResponse = false;
let totalInvestigationTimeMs = 0;
const collectedActivities: Array<{
type: string;
message: string;
status?: 'pending' | 'completed' | 'failed';
details?: { toolDurationMs?: number; totalDurationMs?: number };
toolCallId?: string;
resultPreview?: string;
}> = [];
const collectedEvidence: Array<Record<string, unknown>> = [];
let collectedDebugContext: any = null;
const collectedDebugToolData = new Map<
string,
{
toolCallId: string;
toolName: string;
toolArgs: Record<string, unknown>;
toolResult?: unknown;
toolDurationMs?: number;
}
>();
let collectedDebugMetrics: any = null;
try {
const mode = await llmService.classifyUserIntent(message, conversationHistory);
getLogger().info(`AI: classified user intent mode=${mode}`);
const mode = requestedMode === 'fix' ? 'fix' : 'investigate';
getLogger().info(`AI: using mode=${mode} (requestedMode=${requestedMode})`);

const onToolConfirmation = mode === 'fix' ? async () => true : undefined;

const result = await llmService.processQueryStream(
message,
Expand All @@ -219,12 +253,93 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
},
(activity) => {
sendEvent(activity as AIChatSSEEvent);
if (activity.type === 'tool_call') {
collectedActivities.push({
type: activity.type,
message: activity.message,
status: 'pending',
toolCallId: activity.toolCallId,
});
} else if (activity.type === 'processing') {
const isFailed = !activity.message.startsWith('\u2713');
const matchIdx = collectedActivities.findIndex(
(a) => a.status === 'pending' && activity.toolCallId && a.toolCallId === activity.toolCallId
);
if (matchIdx !== -1) {
collectedActivities[matchIdx] = {
...collectedActivities[matchIdx],
message: activity.message,
status: isFailed ? 'failed' : 'completed',
details: activity.details,
toolCallId: activity.toolCallId,
resultPreview: activity.resultPreview,
};
} else {
collectedActivities.push({
type: activity.type,
message: activity.message,
status: isFailed ? 'failed' : 'completed',
details: activity.details,
toolCallId: activity.toolCallId,
resultPreview: activity.resultPreview,
});
}
} else {
collectedActivities.push({ type: activity.type, message: activity.message });
}
},
(evidenceEvent) => {
sendEvent(evidenceEvent);
collectedEvidence.push(evidenceEvent as unknown as Record<string, unknown>);
},
undefined,
mode
onToolConfirmation,
mode,
(event: AIChatSSEEvent) => {
try {
sendEvent(event);
} catch {
/* SSE send must not block collection */
}
try {
const e = event as any;
if (e.type === 'debug_context') {
collectedDebugContext = {
systemPrompt: e.systemPrompt,
maskingStats: e.maskingStats,
provider: e.provider,
modelId: e.modelId,
};
} else if (e.type === 'debug_tool_call') {
collectedDebugToolData.set(e.toolCallId, {
toolCallId: e.toolCallId,
toolName: e.toolName,
toolArgs: e.toolArgs,
});
} else if (e.type === 'debug_tool_result') {
const existing = collectedDebugToolData.get(e.toolCallId);
if (existing) {
existing.toolResult = e.toolResult;
existing.toolDurationMs = e.toolDurationMs;
} else {
collectedDebugToolData.set(e.toolCallId, {
toolCallId: e.toolCallId,
toolName: e.toolName,
toolArgs: {},
toolResult: e.toolResult,
toolDurationMs: e.toolDurationMs,
});
}
} else if (e.type === 'debug_metrics') {
collectedDebugMetrics = {
iterations: e.iterations,
totalToolCalls: e.totalToolCalls,
totalDurationMs: e.totalDurationMs,
};
}
} catch {
/* debug collection must never disrupt the stream */
}
}
);

aiResponse = result.response;
Expand Down Expand Up @@ -321,6 +436,19 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
role: 'assistant',
content: aiResponse,
timestamp: Date.now(),
activityHistory: collectedActivities.length > 0 ? collectedActivities : undefined,
evidenceItems: collectedEvidence.length > 0 ? collectedEvidence : undefined,
totalInvestigationTimeMs,
debugContext: collectedDebugContext || undefined,
debugToolData:
collectedDebugToolData.size > 0
? Array.from(collectedDebugToolData.values()).map((td) => ({
...td,
toolArgs: truncateForStorage(td.toolArgs),
toolResult: td.toolResult !== undefined ? truncateForStorage(td.toolResult) : undefined,
}))
: undefined,
debugMetrics: collectedDebugMetrics || undefined,
});

sendEvent({ type: 'complete', totalInvestigationTimeMs });
Expand Down
35 changes: 33 additions & 2 deletions src/components/ai-agent/ActivityPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@
import React, { useRef, useEffect } from 'react';
import { Accordion, AccordionItem, Chip, Spinner } from '@heroui/react';
import { formatDuration } from './utils';
import type { ActivityLog } from './types';
import type { ActivityLog, DebugToolData } from './types';

interface ActivityPanelProps {
activities: ActivityLog[];
totalInvestigationTimeMs?: number;
highlightedToolCallId?: string | null;
xrayMode?: boolean;
debugToolDataMap?: Map<string, DebugToolData>;
}

export function ActivityPanel({ activities, totalInvestigationTimeMs, highlightedToolCallId }: ActivityPanelProps) {
export function ActivityPanel({ activities, totalInvestigationTimeMs, highlightedToolCallId, xrayMode, debugToolDataMap }: ActivityPanelProps) {
const highlightRef = useRef<HTMLDivElement>(null);

useEffect(() => {
Expand Down Expand Up @@ -161,6 +163,35 @@ export function ActivityPanel({ activities, totalInvestigationTimeMs, highlighte
{activity.resultPreview}
</div>
)}
{xrayMode && activity.toolCallId && debugToolDataMap?.get(activity.toolCallId) && (() => {
const toolData = debugToolDataMap.get(activity.toolCallId)!;
return (
<div className="ml-6 mt-1 mb-1 border-l-2 border-amber-400 pl-2">
<details className="text-[10px]">
<summary className="text-amber-600 cursor-pointer select-none font-medium hover:text-amber-700">
INPUT: {toolData.toolName}
</summary>
<div className="mt-1 rounded bg-gray-900" style={{ maxHeight: 192, overflowY: 'auto' }}>
<pre className="p-2 text-green-300 text-[10px] font-mono whitespace-pre-wrap break-words m-0">
{JSON.stringify(toolData.toolArgs, null, 2)}
</pre>
</div>
</details>
{toolData.toolResult !== undefined && (
<details className="text-[10px] mt-1">
<summary className="text-amber-600 cursor-pointer select-none font-medium hover:text-amber-700">
OUTPUT{toolData.toolDurationMs ? ` (${toolData.toolDurationMs}ms)` : ''}
</summary>
<div className="mt-1 rounded bg-gray-900" style={{ maxHeight: 192, overflowY: 'auto' }}>
<pre className="p-2 text-cyan-300 text-[10px] font-mono whitespace-pre-wrap break-words m-0">
{JSON.stringify(toolData.toolResult, null, 2)}
</pre>
</div>
</details>
)}
</div>
);
})()}
</div>
);
})}
Expand Down
11 changes: 11 additions & 0 deletions src/components/ai-agent/ChatContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import React, { useRef, useCallback, useState, useMemo } from 'react';
import { Card, CardHeader, CardBody, Button, Spinner } from '@heroui/react';
import { useChat } from './hooks/useChat';
import { useChatModels } from './hooks/useChatModels';
import { useXrayMode } from './hooks/useXrayMode';
import { ModelSelector } from './ModelSelector';
import { ErrorBanner } from './ErrorBanner';
import { ChatInput } from './ChatInput';
Expand All @@ -33,6 +34,7 @@ interface ChatContainerProps {

export function ChatContainer({ buildUuid }: ChatContainerProps) {
const { availableModels, selectedModel, handleModelChange } = useChatModels();
const { xrayMode, handleLabelClick } = useXrayMode();
const {
messages,
input,
Expand All @@ -57,6 +59,9 @@ export function ChatContainer({ buildUuid }: ChatContainerProps) {
scrollToBottom,
messagesEndRef,
inputRef,
debugContext,
debugMetrics,
debugToolDataMapRef,
} = useChat({ buildUuid, selectedModel });

const scrollContainerRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -95,6 +100,8 @@ export function ChatContainer({ buildUuid }: ChatContainerProps) {
onClearHistory={handleClearHistory}
loading={loading}
hasMessages={messages.length > 0}
onLabelClick={handleLabelClick}
xrayMode={xrayMode}
/>
</CardHeader>

Expand Down Expand Up @@ -147,6 +154,10 @@ export function ChatContainer({ buildUuid }: ChatContainerProps) {
onAtBottomChange={handleAtBottomChange}
followUpSuggestions={followUpSuggestions}
onSelectSuggestion={sendMessage}
xrayMode={xrayMode}
debugContext={debugContext}
debugMetrics={debugMetrics}
debugToolDataMap={debugToolDataMapRef.current}
/>

{showJumpToBottom && (
Expand Down
30 changes: 26 additions & 4 deletions src/components/ai-agent/MessageBubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ import { parseStructuredResponse, extractJsonContent } from './utils';
import { MarkdownRenderer } from './MarkdownRenderer';
import { StructuredResponse } from './StructuredResponse';
import { ActivityPanel } from './ActivityPanel';
import type { DebugMessage, ActivityLog, EvidenceItem, ServiceInvestigationResult, StructuredDebugResponse } from './types';
import type { DebugMessage, ActivityLog, EvidenceItem, ServiceInvestigationResult, StructuredDebugResponse, DebugToolData, DebugContextData, DebugMetrics } from './types';
import { useProgressiveJson } from './hooks/useProgressiveJson';
import { XrayContextPanel } from './XrayPanel';

interface RepositoryContext {
owner: string;
Expand All @@ -38,6 +39,10 @@ interface MessageBubbleProps {
onAutoFix: (service: ServiceInvestigationResult) => void;
loading: boolean;
repositoryContext?: RepositoryContext;
xrayMode?: boolean;
debugContext?: DebugContextData | null;
debugMetrics?: DebugMetrics | null;
debugToolDataMap?: Map<string, DebugToolData>;
}

function renderSimpleFallbackService(service: any) {
Expand Down Expand Up @@ -246,7 +251,7 @@ function renderMessage(
return <MarkdownRenderer content={content} repositoryContext={derivedRepoContext || repositoryContext} />;
}

export const MessageBubble = React.memo(function MessageBubble({ message, isStreaming, streamingContent, activityLogs, evidenceItems, onAutoFix, loading, repositoryContext }: MessageBubbleProps) {
export const MessageBubble = React.memo(function MessageBubble({ message, isStreaming, streamingContent, activityLogs, evidenceItems, onAutoFix, loading, repositoryContext, xrayMode, debugContext, debugMetrics, debugToolDataMap }: MessageBubbleProps) {
const [highlightedToolCallId, setHighlightedToolCallId] = useState<string | null>(null);
const highlightTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

Expand Down Expand Up @@ -279,8 +284,11 @@ export const MessageBubble = React.memo(function MessageBubble({ message, isStre
return (
<div className="message-fade-in mb-6 w-[80%]">
<div className="ai-message-content">
{xrayMode && debugContext && (
<XrayContextPanel debugContext={debugContext} debugMetrics={debugMetrics} />
)}
{activityLogs && activityLogs.length > 0 && (
<ActivityPanel activities={activityLogs} highlightedToolCallId={highlightedToolCallId} />
<ActivityPanel activities={activityLogs} highlightedToolCallId={highlightedToolCallId} xrayMode={xrayMode} debugToolDataMap={debugToolDataMap} />
)}
{renderMessage(content, true, onAutoFix, loading, repositoryContext, progressiveResult, evidenceItems, handleHighlightActivity)}
<span className="typing-cursor">&#x258A;</span>
Expand Down Expand Up @@ -328,11 +336,25 @@ export const MessageBubble = React.memo(function MessageBubble({ message, isStre
);
}

const effectiveDebugContext = debugContext || message.debugContext || null;
const effectiveDebugMetrics = debugMetrics || message.debugMetrics || null;
const effectiveDebugToolDataMap = (debugToolDataMap && debugToolDataMap.size > 0) ? debugToolDataMap : (() => {
if (!message.debugToolData || message.debugToolData.length === 0) return undefined;
const map = new Map<string, DebugToolData>();
for (const td of message.debugToolData) {
map.set(td.toolCallId, td);
}
return map;
})();

return (
<div className="message-fade-in mb-6 w-[80%]">
<div className="ai-message-content">
{xrayMode && effectiveDebugContext && (
<XrayContextPanel debugContext={effectiveDebugContext} debugMetrics={effectiveDebugMetrics} />
)}
{message.activityHistory && (
<ActivityPanel activities={message.activityHistory} totalInvestigationTimeMs={message.totalInvestigationTimeMs} highlightedToolCallId={highlightedToolCallId} />
<ActivityPanel activities={message.activityHistory} totalInvestigationTimeMs={message.totalInvestigationTimeMs} highlightedToolCallId={highlightedToolCallId} xrayMode={xrayMode} debugToolDataMap={effectiveDebugToolDataMap} />
)}
{renderMessage(message.content, false, onAutoFix, loading, repositoryContext, undefined, message.evidenceItems, handleHighlightActivity)}
{message.stopped && <div className="mt-2 text-xs text-gray-400 italic">Generation stopped</div>}
Expand Down
Loading