Show live per-thread progress, timing, and token usage while reviewing
The in-progress view was a spinner and a counter, which wasted the most interesting moment of a multi-minute sweep. It now shows a progress bar plus a live list of every thread being reviewed — running ones first — with project favicon, a per-thread elapsed clock that ticks while the review runs, and the tokens and cost each review actually consumed. The header aggregates run totals. Usage is real, not estimated: the Claude CLI's `--output-format json` envelope already reports `usage` and `total_cost_usd`, so runClaudeJson now surfaces them through an optional onUsage sink, generateThreadReview attaches them to its result, and the review RPC returns them as an optional `usage` field. Input counts fold in cache-creation and cache-read tokens so the number matches billing. Providers that report nothing simply omit the field. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
8c9dbfc01a
commit
f70a4e59ab
6 files changed
+229
-15
No files matched your search
@@ -442,6 +442,18 @@ export const make = Effect.gen(function* () {
|
||||
settleReason: recommendSettle ? generated.settleReason : null,
|
||||
...(diffStats !== undefined ? { diffStats } : {}),
|
||||
...(prContext !== null ? { prStatus: prContext.status } : {}),
|
||||
...(generated.usage !== undefined
|
||||
? {
|
||||
usage: {
|
||||
inputTokens: generated.usage.inputTokens,
|
||||
outputTokens: generated.usage.outputTokens,
|
||||
durationMs: generated.usage.durationMs,
|
||||
...(generated.usage.costUsd !== undefined
|
||||
? { costUsd: generated.usage.costUsd }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -51,12 +51,34 @@ const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
/**
|
||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
||||
* We only care about `structured_output`.
|
||||
* `structured_output` is the payload; the usage/cost fields are optional
|
||||
* telemetry surfaced to callers that ask for it (the review sweep shows
|
||||
* per-thread tokens and cost while it runs).
|
||||
*/
|
||||
const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
total_cost_usd: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
duration_api_ms: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
usage: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
output_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/** Telemetry a caller can opt into by passing an `onUsage` sink. */
|
||||
export interface ClaudeGenerationUsage {
|
||||
readonly inputTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly costUsd?: number | undefined;
|
||||
readonly durationMs: number;
|
||||
}
|
||||
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
|
||||
|
||||
@@ -113,6 +135,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
onUsage,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
@@ -124,6 +147,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
/** Optional sink for the CLI's reported token/cost telemetry. */
|
||||
onUsage?: ((usage: ClaudeGenerationUsage) => void) | undefined;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = yield* encodeJsonForOperation(
|
||||
operation,
|
||||
@@ -250,6 +275,24 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
}),
|
||||
);
|
||||
|
||||
if (onUsage) {
|
||||
const usage = envelope.usage ?? null;
|
||||
// Cache-creation and cache-read tokens are still input the model
|
||||
// processed; fold them in so the reported number matches billing.
|
||||
const inputTokens =
|
||||
(usage?.input_tokens ?? 0) +
|
||||
(usage?.cache_creation_input_tokens ?? 0) +
|
||||
(usage?.cache_read_input_tokens ?? 0);
|
||||
onUsage({
|
||||
inputTokens: Math.round(inputTokens),
|
||||
outputTokens: Math.round(usage?.output_tokens ?? 0),
|
||||
...(typeof envelope.total_cost_usd === "number"
|
||||
? { costUsd: envelope.total_cost_usd }
|
||||
: {}),
|
||||
durationMs: Math.round(envelope.duration_api_ms ?? 0),
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
|
||||
return yield* decodeOutput(envelope.structured_output).pipe(
|
||||
Effect.catchTags({
|
||||
@@ -369,15 +412,22 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
let usage: TextGeneration.ThreadReviewGenerationUsage | undefined;
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
onUsage: (reported) => {
|
||||
usage = reported;
|
||||
},
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
return {
|
||||
...normalizeThreadReview(generated, input.isActive),
|
||||
...(usage !== undefined ? { usage } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -90,7 +90,16 @@ export interface ThreadReviewGenerationInput {
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationUsage {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd?: number | undefined;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationResult {
|
||||
/** Provider-reported cost of this generation, when available. */
|
||||
usage?: ThreadReviewGenerationUsage | undefined;
|
||||
summary: string;
|
||||
/** One imperative sentence: the user's single next action. */
|
||||
nextStep: string;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Link } from "@tanstack/react-router";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
GitMergeIcon,
|
||||
InfoIcon,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
RotateCcwIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
@@ -400,6 +401,94 @@ function SweepItemCard({
|
||||
);
|
||||
}
|
||||
|
||||
function formatDuration(ms: number): string {
|
||||
const totalSeconds = Math.max(0, Math.round(ms / 1000));
|
||||
if (totalSeconds < 60) return `${totalSeconds}s`;
|
||||
return `${Math.floor(totalSeconds / 60)}m ${String(totalSeconds % 60).padStart(2, "0")}s`;
|
||||
}
|
||||
|
||||
function formatTokens(tokens: number): string {
|
||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
||||
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
|
||||
return String(tokens);
|
||||
}
|
||||
|
||||
/** Live per-thread progress: what's running, for how long, and what each
|
||||
review cost. Replaces a bare spinner so a multi-minute sweep is
|
||||
legible while it works. */
|
||||
function SweepProgressList({
|
||||
items,
|
||||
projectsByKey,
|
||||
}: {
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
projectsByKey: ReadonlyMap<string, { title: string; workspaceRoot: string }>;
|
||||
}) {
|
||||
// Ticking clock so elapsed times advance without store writes.
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setNowMs(Date.now()), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Running first (that's the live part), then queued, then finished.
|
||||
const ordered = useMemo(() => {
|
||||
const rank = (item: SweepItem) =>
|
||||
item.status === "running" ? 0 : item.status === "pending" ? 1 : 2;
|
||||
return [...items].sort((a, b) => rank(a) - rank(b));
|
||||
}, [items]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col divide-y divide-border/50 overflow-hidden rounded-lg border border-border/60">
|
||||
{ordered.map((item) => {
|
||||
const project = projectsByKey.get(
|
||||
scopedProjectKey(scopeProjectRef(item.ref.environmentId, item.projectId)),
|
||||
);
|
||||
const elapsedMs =
|
||||
item.startedAtMs === null ? null : (item.finishedAtMs ?? nowMs) - item.startedAtMs;
|
||||
const usage = item.result?.usage;
|
||||
return (
|
||||
<div
|
||||
key={scopedThreadKey(item.ref)}
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-3 py-2 text-sm",
|
||||
item.status === "pending" && "opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center">
|
||||
{item.status === "running" ? (
|
||||
<Spinner className="size-3.5 text-sky-400" />
|
||||
) : item.status === "done" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : item.status === "error" ? (
|
||||
<CircleAlertIcon className="size-3.5 text-red-400" />
|
||||
) : (
|
||||
<span className="size-1.5 rounded-full bg-muted-foreground/40" />
|
||||
)}
|
||||
</span>
|
||||
{project?.workspaceRoot ? (
|
||||
<ProjectFavicon
|
||||
environmentId={item.ref.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-3.5 shrink-0"
|
||||
/>
|
||||
) : null}
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/90">{item.threadTitle}</span>
|
||||
{usage ? (
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">
|
||||
{formatTokens(usage.inputTokens + usage.outputTokens)} tok
|
||||
{usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="w-16 shrink-0 text-right font-mono text-[11px] text-muted-foreground">
|
||||
{elapsedMs === null ? "—" : formatDuration(elapsedMs)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cost-transparency threshold: at or above this many candidate threads the
|
||||
pre-run screen calls out that the sweep may be slow/expensive. */
|
||||
const SWEEP_COST_NOTE_THRESHOLD = 15;
|
||||
@@ -664,6 +753,22 @@ export function ReviewSweepView() {
|
||||
const running = phase === "running";
|
||||
const [applyingAll, setApplyingAll] = useState(false);
|
||||
const [mergingAll, setMergingAll] = useState(false);
|
||||
// Aggregate what the run has cost so far, from provider-reported usage.
|
||||
const runTotals = useMemo(
|
||||
() =>
|
||||
visibleItems.reduce(
|
||||
(totals, item) => {
|
||||
const usage = item.result?.usage;
|
||||
if (!usage) return totals;
|
||||
return {
|
||||
tokens: totals.tokens + usage.inputTokens + usage.outputTokens,
|
||||
costUsd: totals.costUsd + (usage.costUsd ?? 0),
|
||||
};
|
||||
},
|
||||
{ tokens: 0, costUsd: 0 },
|
||||
),
|
||||
[visibleItems],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
@@ -718,18 +823,32 @@ export function ReviewSweepView() {
|
||||
{phase === "idle" ? (
|
||||
<SweepPreRunSummary />
|
||||
) : running ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<Spinner className="mx-auto size-6 text-muted-foreground" />
|
||||
<EmptyTitle>
|
||||
Reviewing your work — {reviewedCount} of {visibleItems.length}
|
||||
</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<h2 className="text-sm font-medium text-foreground">
|
||||
Reviewing your work — {reviewedCount} of {visibleItems.length}
|
||||
</h2>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{runTotals.tokens > 0 ? `${formatTokens(runTotals.tokens)} tokens` : null}
|
||||
{runTotals.costUsd > 0 ? ` · $${runTotals.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-sky-500 transition-[width] duration-500"
|
||||
style={{
|
||||
width: `${visibleItems.length === 0 ? 0 : Math.round((reviewedCount / visibleItems.length) * 100)}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Results appear all at once when every thread is reviewed, so you can triage in one
|
||||
pass. Feel free to navigate away; the sweep keeps running.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</p>
|
||||
</div>
|
||||
<SweepProgressList items={visibleItems} projectsByKey={projectsByKey} />
|
||||
</div>
|
||||
) : visibleItems.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
|
||||
@@ -102,6 +102,10 @@ export interface SweepItem {
|
||||
readonly dismissed: boolean;
|
||||
readonly mergeStatus: SweepMergeStatus;
|
||||
readonly mergeDetail: string | null;
|
||||
/** Epoch ms when this item's review started (for the live elapsed clock). */
|
||||
readonly startedAtMs: number | null;
|
||||
/** Epoch ms when it finished, successfully or not. */
|
||||
readonly finishedAtMs: number | null;
|
||||
}
|
||||
|
||||
export type SweepPhase = "idle" | "running" | "complete";
|
||||
@@ -225,7 +229,7 @@ async function reviewOne(runId: number, item: SweepItem): Promise<void> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return;
|
||||
const key = scopedThreadKey(item.ref);
|
||||
store.patchItem(key, { status: "running" });
|
||||
store.patchItem(key, { status: "running", startedAtMs: Date.now(), finishedAtMs: null });
|
||||
|
||||
const shell = readThreadShell(item.ref);
|
||||
const canSettleNow = shell !== null && canSettle(shell, { now: new Date().toISOString() });
|
||||
@@ -247,12 +251,18 @@ async function reviewOne(runId: number, item: SweepItem): Promise<void> {
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
if (result._tag === "Success") {
|
||||
current.patchItem(key, { status: "done", result: result.value, errorMessage: null });
|
||||
current.patchItem(key, {
|
||||
status: "done",
|
||||
result: result.value,
|
||||
errorMessage: null,
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
} else {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
current.patchItem(key, {
|
||||
status: "error",
|
||||
errorMessage: error instanceof Error ? error.message : "Review failed.",
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -331,6 +341,8 @@ export function startReviewSweep(): void {
|
||||
dismissed: false,
|
||||
mergeStatus: "idle",
|
||||
mergeDetail: null,
|
||||
startedAtMs: null,
|
||||
finishedAtMs: null,
|
||||
}),
|
||||
);
|
||||
useReviewSweepStore.getState().startRun({
|
||||
|
||||
@@ -76,6 +76,16 @@ export const ReviewThreadPrStatus = Schema.Struct({
|
||||
});
|
||||
export type ReviewThreadPrStatus = typeof ReviewThreadPrStatus.Type;
|
||||
|
||||
/** What the review generation itself cost, reported by the provider CLI. */
|
||||
export const ReviewThreadGenerationUsage = Schema.Struct({
|
||||
inputTokens: Schema.Int,
|
||||
outputTokens: Schema.Int,
|
||||
/** Absent when the provider doesn't report a cost. */
|
||||
costUsd: Schema.optionalKey(Schema.Number),
|
||||
durationMs: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadGenerationUsage = typeof ReviewThreadGenerationUsage.Type;
|
||||
|
||||
export const ReviewThreadSummaryResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
summary: TrimmedNonEmptyString,
|
||||
@@ -90,6 +100,8 @@ export const ReviewThreadSummaryResult = Schema.Struct({
|
||||
diffStats: Schema.optionalKey(ReviewThreadDiffStats),
|
||||
/** Absent when the thread has no PR, the lookup failed, or pre-PR servers. */
|
||||
prStatus: Schema.optionalKey(ReviewThreadPrStatus),
|
||||
/** Absent when the provider doesn't report usage. */
|
||||
usage: Schema.optionalKey(ReviewThreadGenerationUsage),
|
||||
});
|
||||
export type ReviewThreadSummaryResult = typeof ReviewThreadSummaryResult.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user