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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mesadev/saguaro",
"version": "0.4.2",
"version": "0.4.21",
"description": "AI code review that enforces your team's rules during development",
"license": "Apache-2.0",
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/daemon-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import type { DaemonFinding, DaemonFindingsFilter, DaemonStatsAggregation, TimeWindow } from '../daemon/stats-types.js';
import { DaemonStore } from '../daemon/store.js';

export type { DaemonFinding, DaemonFindingsFilter, TimeWindow };
export type { DaemonFinding, DaemonFindingsFilter, DaemonStatsAggregation, TimeWindow };

export interface DaemonStatsResult {
stats: DaemonStatsAggregation;
Expand Down
64 changes: 64 additions & 0 deletions src/daemon/__tests__/agent-cli-json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,68 @@ describe('parseAgentJsonOutput', () => {
expect(output.text).toBe('');
expect(output.usage).toBeUndefined();
});

test('captures token usage when total_cost_usd is missing (subscription)', () => {
const json = JSON.stringify({
type: 'result',
subtype: 'success',
result: 'No issues found',
usage: { input_tokens: 5000, output_tokens: 1200, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 },
num_turns: 2,
});
const output = parseAgentJsonOutput(json);
expect(output.text).toBe('No issues found');
expect(output.usage).toBeDefined();
expect(output.usage!.costUsd).toBe(0);
expect(output.usage!.inputTokens).toBe(5000);
expect(output.usage!.outputTokens).toBe(1200);
expect(output.usage!.numTurns).toBe(2);
});

test('extracts result from verbose JSON array (--verbose mode)', () => {
const json = JSON.stringify([
{ type: 'system', subtype: 'init', session_id: 'abc' },
{ type: 'assistant', message: { content: [{ type: 'text', text: '4' }] } },
{
type: 'result',
subtype: 'success',
result: '[error] src/db.ts:5 - missing index',
total_cost_usd: 0.031,
usage: { input_tokens: 2000, output_tokens: 500 },
num_turns: 1,
},
]);
const output = parseAgentJsonOutput(json);
expect(output.text).toBe('[error] src/db.ts:5 - missing index');
expect(output.usage).toBeDefined();
expect(output.usage!.costUsd).toBe(0.031);
expect(output.usage!.inputTokens).toBe(2000);
expect(output.usage!.outputTokens).toBe(500);
});

test('returns empty text when verbose array has no result event', () => {
const json = JSON.stringify([
{ type: 'system', subtype: 'init' },
{ type: 'assistant', message: {} },
]);
const output = parseAgentJsonOutput(json);
expect(output.text).toBe('');
expect(output.usage).toBeUndefined();
});

test('captures token usage when total_cost_usd is zero (subscription)', () => {
const json = JSON.stringify({
type: 'result',
subtype: 'success',
result: '[warning] file.ts:1 - unused import',
total_cost_usd: 0,
usage: { input_tokens: 3000, output_tokens: 800 },
num_turns: 1,
});
const output = parseAgentJsonOutput(json);
expect(output.usage).toBeDefined();
expect(output.usage!.costUsd).toBe(0);
expect(output.usage!.inputTokens).toBe(3000);
expect(output.usage!.outputTokens).toBe(800);
});
});
37 changes: 37 additions & 0 deletions src/daemon/__tests__/store-stats.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,41 @@ describe('getRecentFindings', () => {
const findings = store.getRecentFindings('all', { repo: '/tmp/repo-b' });
expect(findings.length).toBe(0);
});

test('returns review context fields (model, costUsd, completedAt)', () => {
dbPath = makeDbPath();
store = new DaemonStore(dbPath);
seedReviews(store);

const findings = store.getRecentFindings('all');
expect(findings.length).toBe(2);
expect(findings[0].model).toBe('sonnet');
expect(findings[0].costUsd).toBe(0.05);
expect(findings[0].completedAt).toBeDefined();
expect(typeof findings[0].completedAt).toBe('string');
});

test('returns null model/cost when job has no usage data', () => {
dbPath = makeDbPath();
store = new DaemonStore(dbPath);

const j1 = store.queueJob({
sessionId: 's1',
repoPath: '/tmp/repo',
changedFiles: [{ path: 'x.ts', diff_hash: 'hx' }],
agentSummary: null,
})!;
store.claimNextJob(1);
store.completeJob(j1, 'done');
store.insertReview({
jobId: j1,
verdict: 'fail',
findings: [{ file: 'x.ts', line: 1, message: 'dead code found', severity: 'warning' }],
});

const findings = store.getRecentFindings('all');
expect(findings.length).toBe(1);
expect(findings[0].model).toBeNull();
expect(findings[0].costUsd).toBeNull();
});
});
30 changes: 20 additions & 10 deletions src/daemon/agent-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,29 @@ export interface AgentOutput {

export function parseAgentJsonOutput(raw: string): AgentOutput {
try {
const data = JSON.parse(raw);
let data = JSON.parse(raw);

// --verbose mode returns a JSON array of events; extract the "result" event
if (Array.isArray(data)) {
const resultEvent = data.findLast((e: Record<string, unknown>) => e.type === 'result');
if (!resultEvent) return { text: '' };
data = resultEvent;
}

if (typeof data !== 'object' || data === null || typeof data.result !== 'string') {
return { text: data?.result ?? '' };
}
const usage: AgentUsage | undefined =
typeof data.total_cost_usd === 'number'
? {
costUsd: data.total_cost_usd,
inputTokens: data.usage?.input_tokens ?? 0,
outputTokens: data.usage?.output_tokens ?? 0,
numTurns: data.num_turns ?? 0,
}
: undefined;
const hasUsage =
typeof data.total_cost_usd === 'number' ||
(data.usage && (typeof data.usage.input_tokens === 'number' || typeof data.usage.output_tokens === 'number'));
const usage: AgentUsage | undefined = hasUsage
? {
costUsd: typeof data.total_cost_usd === 'number' ? data.total_cost_usd : 0,
inputTokens: data.usage?.input_tokens ?? 0,
outputTokens: data.usage?.output_tokens ?? 0,
numTurns: data.num_turns ?? 0,
}
: undefined;
return { text: data.result, usage };
} catch {
return { text: raw };
Expand Down
3 changes: 3 additions & 0 deletions src/daemon/stats-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ export interface DaemonFinding {
categories: string[];
repoPath: string;
createdAt: string;
model: string | null;
costUsd: number | null;
completedAt: string | null;
}

export interface DaemonFindingsFilter {
Expand Down
14 changes: 12 additions & 2 deletions src/daemon/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,14 +488,21 @@ export class DaemonStore {

const rows = this.db
.prepare(`
SELECT r.findings, rj.repo_path, r.created_at
SELECT r.findings, rj.repo_path, r.created_at, rj.model, rj.cost_usd, rj.completed_at
FROM reviews r
JOIN review_jobs rj ON r.job_id = rj.id
WHERE rj.created_at >= ${windowSql}
AND r.verdict = 'fail' AND r.findings IS NOT NULL AND r.findings != '[]'
ORDER BY r.created_at DESC
`)
.all() as Array<{ findings: string; repo_path: string; created_at: string }>;
.all() as Array<{
findings: string;
repo_path: string;
created_at: string;
model: string | null;
cost_usd: number | null;
completed_at: string | null;
}>;

const results: DaemonFinding[] = [];

Expand All @@ -518,6 +525,9 @@ export class DaemonStore {
categories,
repoPath: row.repo_path,
createdAt: row.created_at,
model: row.model ?? null,
costUsd: row.cost_usd ?? null,
completedAt: row.completed_at ?? null,
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/tui/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { exitTui } from './lib/exit.js';
import { InputBarProvider, useInputBarContext } from './lib/input-bar-context.js';
import { RouterProvider, useRouter } from './lib/router.js';
import { ConfigureScreen } from './screens/configure.js';
import { DaemonStatsScreen } from './screens/daemon-stats.js';
import { DaemonStatsScreen } from './screens/daemon-stats/index.js';
import { HelpScreen } from './screens/help.js';
import { HomeScreen } from './screens/home.js';
import { HookScreen } from './screens/hook.js';
Expand Down
45 changes: 45 additions & 0 deletions src/tui/components/bar-chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { theme } from '../lib/theme.js';

export interface BarChartItem {
label: string;
value: number;
suffix?: string;
}

interface BarChartProps {
items: BarChartItem[];
maxBarWidth?: number;
fillColor?: string;
emptyColor?: string;
}

export function BarChart({
items,
maxBarWidth = 20,
fillColor = theme.info,
emptyColor = theme.border,
}: BarChartProps) {
if (items.length === 0) return null;

const maxValue = Math.max(...items.map((i) => i.value));
const maxLabelLen = Math.max(...items.map((i) => i.label.length));

return (
<box flexDirection="column">
{items.map((item) => {
const filled = maxValue > 0 ? Math.round((item.value / maxValue) * maxBarWidth) : 0;
const empty = maxBarWidth - filled;
const label = item.label.padEnd(maxLabelLen);

return (
<box key={item.label} flexDirection="row">
<text fg={theme.textDim}>{label} </text>
<text fg={fillColor}>{'\u2588'.repeat(filled)}</text>
<text fg={emptyColor}>{'\u2591'.repeat(empty)}</text>
<text fg={theme.text}> {item.suffix ?? item.value}</text>
</box>
);
})}
</box>
);
}
Loading
Loading