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
14 changes: 13 additions & 1 deletion src/app/api/v2/ai/chat/[buildUuid]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,15 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const encoder = new TextEncoder();
let writerClosed = false;

const sendEvent = (data: AIChatSSEEvent | SSEErrorEvent) => {
writer.write(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)).catch(() => {});
if (writerClosed) return;
try {
writer.write(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)).catch(() => {});
} catch {
writerClosed = true;
}
};

const MAX_STORED_JSON_LENGTH = 8000;
Expand All @@ -132,6 +138,7 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
};

req.signal.addEventListener('abort', () => {
writerClosed = true;
try {
writer.close();
} catch {
Expand Down Expand Up @@ -334,6 +341,10 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
iterations: e.iterations,
totalToolCalls: e.totalToolCalls,
totalDurationMs: e.totalDurationMs,
inputTokens: e.inputTokens,
outputTokens: e.outputTokens,
inputCostPerMillion: e.inputCostPerMillion,
outputCostPerMillion: e.outputCostPerMillion,
};
}
} catch {
Expand Down Expand Up @@ -464,6 +475,7 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
modelName: 'AI model',
});
} finally {
writerClosed = true;
try {
await writer.close();
} catch {
Expand Down
23 changes: 22 additions & 1 deletion src/components/ai-agent/ChatContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { ChatInput } from './ChatInput';
import { SuggestedPrompts } from './SuggestedPrompts';
import { MessageList } from './MessageList';
import { globalStyles } from './styles';
import { getFollowUpSuggestions } from './utils';
import { getFollowUpSuggestions, computeCost, formatCost } from './utils';
import type { ServiceInvestigationResult } from './types';

interface ChatContainerProps {
Expand Down Expand Up @@ -82,6 +82,26 @@ export function ChatContainer({ buildUuid }: ChatContainerProps) {
[messages, loading, streaming]
);

const sessionTotalCost = useMemo(() => {
let total = 0;
let hasCost = false;
for (const msg of messages) {
if (msg.debugMetrics?.inputTokens != null) {
const cost = computeCost(
msg.debugMetrics.inputTokens,
msg.debugMetrics.outputTokens || 0,
msg.debugMetrics.inputCostPerMillion,
msg.debugMetrics.outputCostPerMillion
);
if (cost != null) {
total += cost;
hasCost = true;
}
}
}
return hasCost ? formatCost(total) : null;
}, [messages]);

if (!mounted) {
return (
<div className="flex items-center justify-center h-screen bg-white">
Expand All @@ -102,6 +122,7 @@ export function ChatContainer({ buildUuid }: ChatContainerProps) {
hasMessages={messages.length > 0}
onLabelClick={handleLabelClick}
xrayMode={xrayMode}
sessionTotalCost={sessionTotalCost}
/>
</CardHeader>

Expand Down
13 changes: 11 additions & 2 deletions src/components/ai-agent/ModelSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ interface ModelSelectorProps {
hasMessages: boolean;
onLabelClick?: () => void;
xrayMode?: boolean;
sessionTotalCost?: string | null;
}

export function ModelSelector({
Expand All @@ -38,6 +39,7 @@ export function ModelSelector({
hasMessages,
onLabelClick,
xrayMode,
sessionTotalCost,
}: ModelSelectorProps) {
return (
<>
Expand All @@ -57,7 +59,7 @@ export function ModelSelector({
}
labelPlacement="outside-left"
size="sm"
className="w-60"
className="w-72"
variant="bordered"
selectedKeys={selectedModel ? [`${selectedModel.provider}:${selectedModel.modelId}`] : []}
onSelectionChange={(keys) => {
Expand All @@ -66,8 +68,10 @@ export function ModelSelector({
}}
isDisabled={loading}
classNames={{
label: 'text-xs text-gray-600 font-semibold',
label: 'text-xs text-gray-600 font-semibold whitespace-nowrap',
trigger: 'border-gray-200 hover:border-gray-300',
value: 'text-ellipsis overflow-visible',
innerWrapper: 'overflow-visible',
}}
>
{availableModels.map((model) => (
Expand All @@ -77,6 +81,11 @@ export function ModelSelector({
)}
</div>
<div className="flex items-center gap-2">
{xrayMode && sessionTotalCost && (
<span className="text-xs font-mono text-gray-500">
Session: {sessionTotalCost}
</span>
)}
{hasMessages && (
<Button
onClick={onClearHistory}
Expand Down
20 changes: 11 additions & 9 deletions src/components/ai-agent/ServiceCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export function ServiceCard({
{service.errorSourceDetail}
</p>
)}
{service.filePath && (
{service.filePath && !(service.files && service.files.some((f) => f.path === service.filePath)) && (
<div>
{renderFileLink(service.filePath, repository, service.lineNumber, service.lineNumberEnd)}
</div>
Expand All @@ -233,14 +233,16 @@ export function ServiceCard({
<div className="space-y-3">
<div className="flex items-center justify-between">
<h5 className="text-sm font-semibold text-gray-500 uppercase tracking-wider">Error Output</h5>
<Button
size="sm"
variant="light"
onClick={() => setShowDetails(!showDetails)}
className="text-xs"
>
{showDetails ? 'Hide' : 'Show'} raw output
</Button>
{service.keyError.length > 200 && (
<Button
size="sm"
variant="light"
onClick={() => setShowDetails(!showDetails)}
className="text-xs"
>
{showDetails ? 'Hide' : 'Show'} raw output
</Button>
)}
</div>
<div className="bg-danger-50 border-l-4 border-danger p-4 rounded-lg">
<pre className="text-sm text-danger-900 overflow-x-auto m-0 leading-relaxed font-mono whitespace-pre-wrap">
Expand Down
14 changes: 13 additions & 1 deletion src/components/ai-agent/XrayPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import React from 'react';
import { Chip } from '@heroui/react';
import { formatDuration } from './utils';
import { formatDuration, computeCost, formatCost } from './utils';
import type { DebugContextData, DebugMetrics } from './types';

interface XrayContextPanelProps {
Expand Down Expand Up @@ -63,6 +63,18 @@ export function XrayContextPanel({ debugContext, debugMetrics }: XrayContextPane
<span>iterations: {debugMetrics.iterations}</span>
<span>tool calls: {debugMetrics.totalToolCalls}</span>
<span>duration: {formatDuration(debugMetrics.totalDurationMs)}</span>
{debugMetrics.inputTokens != null && (
<span>tokens: {(debugMetrics.inputTokens + (debugMetrics.outputTokens || 0)).toLocaleString()} ({debugMetrics.inputTokens.toLocaleString()} in / {(debugMetrics.outputTokens || 0).toLocaleString()} out)</span>
)}
{debugMetrics.inputTokens != null && (() => {
const cost = computeCost(
debugMetrics.inputTokens!,
debugMetrics.outputTokens || 0,
debugMetrics.inputCostPerMillion,
debugMetrics.outputCostPerMillion
);
return cost != null ? <span>cost: {formatCost(cost)}</span> : null;
})()}
</div>
</div>
)}
Expand Down
4 changes: 4 additions & 0 deletions src/components/ai-agent/hooks/useChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ export function useChat({ buildUuid, selectedModel }: UseChatOptions) {
iterations: data.iterations,
totalToolCalls: data.totalToolCalls,
totalDurationMs: data.totalDurationMs,
inputTokens: data.inputTokens,
outputTokens: data.outputTokens,
inputCostPerMillion: data.inputCostPerMillion,
outputCostPerMillion: data.outputCostPerMillion,
};
setDebugMetrics(localDebugMetrics);
} else if (data.type === 'chunk') {
Expand Down
6 changes: 6 additions & 0 deletions src/components/ai-agent/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export interface ModelOption {
displayName: string;
default: boolean;
maxTokens: number;
inputCostPerMillion?: number;
outputCostPerMillion?: number;
}

export interface DebugToolData {
Expand All @@ -129,4 +131,8 @@ export interface DebugMetrics {
iterations: number;
totalToolCalls: number;
totalDurationMs: number;
inputTokens?: number;
outputTokens?: number;
inputCostPerMillion?: number;
outputCostPerMillion?: number;
}
15 changes: 15 additions & 0 deletions src/components/ai-agent/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@

import type { StructuredDebugResponse, EvidenceItem, ServiceInvestigationResult } from './types';

export function computeCost(
inputTokens: number,
outputTokens: number,
inputCostPerMillion?: number,
outputCostPerMillion?: number
): number | null {
if (inputCostPerMillion == null || outputCostPerMillion == null) return null;
return (inputTokens * inputCostPerMillion + outputTokens * outputCostPerMillion) / 1_000_000;
}

export function formatCost(cost: number): string {
if (cost < 0.01) return `$${cost.toFixed(4)}`;
return `$${cost.toFixed(2)}`;
}

export function formatDuration(durationMs?: number): string {
if (durationMs === undefined || durationMs === null) return '';

Expand Down
2 changes: 2 additions & 0 deletions src/server/lib/validation/aiAgentConfigSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export const aiAgentConfigSchema = {
enabled: { type: 'boolean' },
default: { type: 'boolean' },
maxTokens: { type: 'integer', minimum: 1 },
inputCostPerMillion: { type: 'number', minimum: 0 },
outputCostPerMillion: { type: 'number', minimum: 0 },
},
required: ['id', 'displayName', 'enabled', 'default', 'maxTokens'],
},
Expand Down
1 change: 1 addition & 0 deletions src/server/services/ai/context/gatherer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ export default class AIAgentContextService extends BaseService {
latestCommit: build.pullRequest.latestCommit,
fullName: build.pullRequest.fullName,
commentId: build.pullRequest.commentId,
labels: build.pullRequest.labels || [],
},
environment: {
id: build.environment.id,
Expand Down
28 changes: 20 additions & 8 deletions src/server/services/ai/orchestration/orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export interface OrchestrationResult {
iterations: number;
toolCalls: number;
duration: number;
inputTokens: number;
outputTokens: number;
};
}

Expand All @@ -60,6 +62,8 @@ export class ToolOrchestrator {
const startTime = Date.now();
let iteration = 0;
let totalToolCalls = 0;
let totalInputTokens = 0;
let totalOutputTokens = 0;
let fullResponse = '';
const protection = this.loopDetector.getProtection();

Expand All @@ -74,7 +78,7 @@ export class ToolOrchestrator {
success: false,
error: 'Operation cancelled by user',
cancelled: true,
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

Expand Down Expand Up @@ -110,7 +114,7 @@ export class ToolOrchestrator {
success: false,
error: 'Provider circuit breaker is open',
classifiedError: classified,
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

Expand All @@ -127,7 +131,7 @@ export class ToolOrchestrator {
response: fullResponse || 'The response was interrupted. Here is what was generated before the error.',
error: `Stream interrupted: ${error.message}`,
classifiedError: createClassifiedError(provider.name, error),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

Expand All @@ -138,18 +142,24 @@ export class ToolOrchestrator {
success: false,
error: error.message || 'Provider error',
classifiedError: createClassifiedError(provider.name, error),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

const usageChunk = chunks.find((c) => c.usage);
if (usageChunk?.usage) {
totalInputTokens += usageChunk.usage.inputTokens;
totalOutputTokens += usageChunk.usage.outputTokens;
}

const llmThinkTime = Date.now() - iterationStartTime;
const toolCalls = this.extractToolCalls(chunks);

if (toolCalls.length === 0) {
return {
success: true,
response: fullResponse,
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

Expand All @@ -165,7 +175,7 @@ export class ToolOrchestrator {
error:
`Tool call limit exceeded (${protection.maxToolCalls}). ` +
`The investigation is too broad. Try asking about specific services.`,
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

Expand Down Expand Up @@ -341,19 +351,21 @@ export class ToolOrchestrator {
error:
`Investigation incomplete - hit iteration limit (${protection.maxIterations}). ` +
`This may indicate the issue is complex or unclear from available data.`,
metrics: this.buildMetrics(iteration, totalToolCalls, startTime),
metrics: this.buildMetrics(iteration, totalToolCalls, startTime, totalInputTokens, totalOutputTokens),
};
}

private extractToolCalls(chunks: StreamChunk[]): ToolCall[] {
return chunks.filter((c) => c.type === 'tool_call' && c.toolCalls).flatMap((c) => c.toolCalls || []);
}

private buildMetrics(iterations: number, toolCalls: number, startTime: number) {
private buildMetrics(iterations: number, toolCalls: number, startTime: number, inputTokens = 0, outputTokens = 0) {
return {
iterations,
toolCalls,
duration: Date.now() - startTime,
inputTokens,
outputTokens,
};
}
}
Loading