feat: add stats for nerds response details

This commit is contained in:
t3-code[bot] authored and GitHub committed 2026-07-30 19:05:24 +00:00
1 parent e4829603ff
commit 438bf7e534
8 files changed
+397 -14

No files matched your search

+2
View File
@@ -5806,6 +5806,8 @@ function ChatViewContent(props: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
statsForNerdsEnabled={settings.statsForNerdsEnabled}
threadActivities={activeThread.activities}
workspaceRoot={activeWorkspaceRoot}
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
anchorMessageId={timelineAnchorMessageId}
@@ -1,12 +1,98 @@
import { describe, expect, it } from "vite-plus/test";
import { EventId, MessageId, TurnId } from "@t3tools/contracts";
import {
computeStableMessagesTimelineRows,
computeMessageDurationStart,
deriveAgentResponseStatsByTurnId,
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
} from "./MessagesTimeline.logic";
describe("deriveAgentResponseStatsByTurnId", () => {
it("uses the latest turn usage snapshot and provider duration to calculate tps", () => {
const turnId = TurnId.make("turn-1");
const result = deriveAgentResponseStatsByTurnId(
[
{
id: MessageId.make("user-1"),
role: "user",
turnId: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.make("assistant-1"),
role: "assistant",
turnId,
createdAt: "2026-01-01T00:00:02.000Z",
updatedAt: "2026-01-01T00:00:10.000Z",
streaming: false,
},
],
[
{
id: EventId.make("usage-1"),
tone: "info",
kind: "context-window.updated",
summary: "Context window updated",
payload: {
lastInputTokens: 1_200,
lastCachedInputTokens: 800,
lastOutputTokens: 125,
lastReasoningOutputTokens: 25,
durationMs: 5_000,
toolUses: 3,
},
turnId,
createdAt: "2026-01-01T00:00:10.000Z",
},
],
);
expect(result.get(turnId)).toEqual({
tokensPerSecond: 25,
durationMs: 5_000,
inputTokens: 1_200,
cachedInputTokens: 800,
outputTokens: 125,
reasoningOutputTokens: 25,
toolUses: 3,
});
});
it("falls back to elapsed response duration and skips unscoped usage", () => {
const turnId = TurnId.make("turn-2");
const messages = [
{
id: MessageId.make("assistant-2"),
role: "assistant" as const,
turnId,
createdAt: "2026-01-01T00:00:02.000Z",
updatedAt: "2026-01-01T00:00:06.000Z",
streaming: false,
},
];
const activity = {
id: EventId.make("usage-2"),
tone: "info" as const,
kind: "context-window.updated",
summary: "Context window updated",
payload: { outputTokens: 20 },
turnId,
createdAt: "2026-01-01T00:00:06.000Z",
};
expect(
deriveAgentResponseStatsByTurnId(messages, [activity]).get(turnId)?.tokensPerSecond,
).toBe(5);
expect(deriveAgentResponseStatsByTurnId(messages, [{ ...activity, turnId: null }]).size).toBe(
0,
);
});
});
describe("computeMessageDurationStart", () => {
it("returns message createdAt when there is no preceding user message", () => {
const result = computeMessageDurationStart([
@@ -7,7 +7,12 @@ import {
type WorkLogEntry,
} from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
import {
type MessageId,
type OrchestrationLatestTurn,
type OrchestrationThreadActivity,
type TurnId,
} from "@t3tools/contracts";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
@@ -201,6 +206,105 @@ export function computeMessageDurationStart(
return result;
}
export interface AgentResponseStats {
readonly tokensPerSecond: number | null;
readonly durationMs: number;
readonly inputTokens: number | null;
readonly cachedInputTokens: number | null;
readonly outputTokens: number | null;
readonly reasoningOutputTokens: number | null;
readonly toolUses: number | null;
}
function finiteNonNegativeNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
}
function activityPayloadRecord(
activity: OrchestrationThreadActivity,
): Record<string, unknown> | null {
return activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
}
/**
* Match each turn's latest normalized usage snapshot to its terminal assistant
* message. Providers expose different subsets, so every metric except duration
* remains nullable and the UI only renders values the provider supplied.
*/
export function deriveAgentResponseStatsByTurnId(
messages: ReadonlyArray<TimelineDurationMessage & { readonly turnId?: TurnId | null }>,
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyMap<TurnId, AgentResponseStats> {
const usageByTurnId = new Map<TurnId, Record<string, unknown>>();
for (const activity of activities) {
if (activity.kind !== "context-window.updated" || activity.turnId === null) {
continue;
}
const payload = activityPayloadRecord(activity);
if (payload) {
usageByTurnId.set(activity.turnId, payload);
}
}
const durationStartByMessageId = computeMessageDurationStart(messages);
const result = new Map<TurnId, AgentResponseStats>();
for (const message of messages) {
if (message.role !== "assistant" || message.streaming || !message.turnId) {
continue;
}
const usage = usageByTurnId.get(message.turnId);
if (!usage) {
continue;
}
const measuredDurationMs = computeElapsedMs(
durationStartByMessageId.get(message.id) ?? message.createdAt,
message.updatedAt,
);
const durationMs = finiteNonNegativeNumber(usage.durationMs) ?? measuredDurationMs ?? 0;
const inputTokens =
finiteNonNegativeNumber(usage.lastInputTokens) ?? finiteNonNegativeNumber(usage.inputTokens);
const cachedInputTokens =
finiteNonNegativeNumber(usage.lastCachedInputTokens) ??
finiteNonNegativeNumber(usage.cachedInputTokens);
const outputTokens =
finiteNonNegativeNumber(usage.lastOutputTokens) ??
finiteNonNegativeNumber(usage.outputTokens);
const reasoningOutputTokens =
finiteNonNegativeNumber(usage.lastReasoningOutputTokens) ??
finiteNonNegativeNumber(usage.reasoningOutputTokens);
const tokensPerSecond =
outputTokens !== null && durationMs > 0 ? (outputTokens * 1_000) / durationMs : null;
result.set(message.turnId, {
tokensPerSecond,
durationMs,
inputTokens,
cachedInputTokens,
outputTokens,
reasoningOutputTokens,
toolUses: finiteNonNegativeNumber(usage.toolUses),
});
}
return result;
}
export function formatAgentResponseTokenCount(value: number): string {
return new Intl.NumberFormat("en-US").format(Math.round(value));
}
export function formatAgentResponseDuration(durationMs: number): string {
if (durationMs < 1_000) return `${Math.round(durationMs)}ms`;
return `${(durationMs / 1_000).toFixed(1).replace(/\.0$/, "")}s`;
}
export function formatTokensPerSecond(value: number | null): string {
if (value === null) return "-- tok/s";
return `${value.toFixed(1)} tok/s`;
}
export function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
@@ -1,4 +1,4 @@
import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts";
import { CheckpointRef, EnvironmentId, EventId, MessageId, TurnId } from "@t3tools/contracts";
import { createRef, type ReactNode, type Ref } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
@@ -239,6 +239,61 @@ describe("MessagesTimeline", () => {
expect(fadedMarkup).toContain("chat-timeline-scroll-fade");
});
it("replaces assistant timestamps with response speed when stats for nerds is enabled", () => {
const turnId = TurnId.make("turn-with-stats");
const messageId = MessageId.make("assistant-with-stats");
const timelineEntries = [
{
id: "entry-assistant-with-stats",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: messageId,
role: "assistant" as const,
text: "Done.",
turnId,
createdAt: MESSAGE_CREATED_AT,
updatedAt: "2026-03-17T19:12:33.000Z",
streaming: false,
},
},
];
const threadActivities = [
{
id: EventId.make("usage-with-stats"),
tone: "info" as const,
kind: "context-window.updated",
summary: "Context window updated",
payload: {
lastInputTokens: 1_000,
lastCachedInputTokens: 750,
lastOutputTokens: 50,
lastReasoningOutputTokens: 10,
durationMs: 5_000,
toolUses: 2,
},
turnId,
createdAt: "2026-03-17T19:12:33.000Z",
},
];
const defaultMarkup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
);
const statsMarkup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={timelineEntries}
statsForNerdsEnabled
threadActivities={threadActivities}
/>,
);
expect(defaultMarkup).not.toContain("10.0 tok/s");
expect(statsMarkup).toContain("10.0 tok/s");
expect(statsMarkup).toContain('aria-label="Response speed: 10.0 tok/s"');
});
it("keeps assistant changed-files headers sticky below the thread header", () => {
const assistantMessageId = MessageId.make("message-assistant-with-files");
const turnId = TurnId.make("turn-with-files");
+122 -12
View File
@@ -1,6 +1,7 @@
import {
type EnvironmentId,
type MessageId,
type OrchestrationThreadActivity,
type ScopedThreadRef,
type ServerProviderSkill,
type TurnId,
@@ -66,7 +67,11 @@ import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
deriveAgentResponseStatsByTurnId,
deriveMessagesTimelineRows,
formatAgentResponseDuration,
formatAgentResponseTokenCount,
formatTokensPerSecond,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveTimelineIsAtEnd,
@@ -76,6 +81,7 @@ import {
resolveTimelineMinimapIndexFromPointer,
resolveTimelineMinimapInteractiveWidth,
resolveTimelineMinimapTopPercent,
type AgentResponseStats,
type StableMessagesTimelineRowsState,
type MessagesTimelineRow,
TIMELINE_MINIMAP_MIN_ITEMS,
@@ -123,6 +129,8 @@ import {
interface TimelineRowSharedState {
timestampFormat: TimestampFormat;
statsForNerdsEnabled: boolean;
agentResponseStatsByTurnId: ReadonlyMap<TurnId, AgentResponseStats>;
routeThreadKey: string;
threadRef: ScopedThreadRef | null;
markdownCwd: string | undefined;
@@ -150,6 +158,7 @@ const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
const EMPTY_THREAD_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
// ---------------------------------------------------------------------------
// Props (public API)
@@ -174,6 +183,8 @@ interface MessagesTimelineProps {
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
statsForNerdsEnabled?: boolean;
threadActivities?: ReadonlyArray<OrchestrationThreadActivity>;
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
anchorMessageId: MessageId | null;
@@ -209,6 +220,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
markdownCwd,
resolvedTheme,
timestampFormat,
statsForNerdsEnabled = false,
threadActivities = EMPTY_THREAD_ACTIVITIES,
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
anchorMessageId,
@@ -324,6 +337,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
const timelineMessages = useMemo(
() => timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
[timelineEntries],
);
const agentResponseStatsByTurnId = useMemo(
() => deriveAgentResponseStatsByTurnId(timelineMessages, threadActivities),
[threadActivities, timelineMessages],
);
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
null,
@@ -418,6 +439,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
timestampFormat,
statsForNerdsEnabled,
agentResponseStatsByTurnId,
routeThreadKey,
threadRef: parseScopedThreadKey(routeThreadKey),
markdownCwd,
@@ -433,6 +456,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}),
[
timestampFormat,
statsForNerdsEnabled,
agentResponseStatsByTurnId,
routeThreadKey,
markdownCwd,
resolvedTheme,
@@ -1038,18 +1063,15 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
{row.showAssistantMeta ? (
<div className="mt-1.5 flex items-center gap-2 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover/assistant:opacity-100">
<AssistantCopyButton row={row} />
{!row.message.streaming && (
<Tooltip>
<TooltipTrigger
render={<p className="text-muted-foreground text-xs tabular-nums" />}
>
{formatShortTimestamp(row.message.updatedAt, ctx.timestampFormat)}
</TooltipTrigger>
<TooltipPopup>
{formatChatTimestampTooltip(row.message.updatedAt, ctx.timestampFormat)}
</TooltipPopup>
</Tooltip>
)}
{!row.message.streaming &&
(ctx.statsForNerdsEnabled && row.message.turnId ? (
<AssistantResponseStats
stats={ctx.agentResponseStatsByTurnId.get(row.message.turnId) ?? null}
updatedAt={row.message.updatedAt}
/>
) : (
<AssistantResponseTimestamp updatedAt={row.message.updatedAt} />
))}
</div>
) : null}
</div>
@@ -1057,6 +1079,94 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
);
}
function AssistantResponseTimestamp({ updatedAt }: { updatedAt: string }) {
const ctx = use(TimelineRowCtx);
return (
<Tooltip>
<TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
{formatShortTimestamp(updatedAt, ctx.timestampFormat)}
</TooltipTrigger>
<TooltipPopup>{formatChatTimestampTooltip(updatedAt, ctx.timestampFormat)}</TooltipPopup>
</Tooltip>
);
}
function ResponseStatRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-center justify-between gap-6">
<span className="text-muted-foreground/70">{label}</span>
<span className="font-medium text-foreground tabular-nums">{value}</span>
</div>
);
}
function AssistantResponseStats({
stats,
updatedAt,
}: {
stats: AgentResponseStats | null;
updatedAt: string;
}) {
if (!stats) {
return <AssistantResponseTimestamp updatedAt={updatedAt} />;
}
return (
<Tooltip>
<TooltipTrigger
render={
<p
className="cursor-help text-muted-foreground text-xs tabular-nums"
aria-label={`Response speed: ${formatTokensPerSecond(stats.tokensPerSecond)}`}
/>
}
>
{formatTokensPerSecond(stats.tokensPerSecond)}
</TooltipTrigger>
<TooltipPopup className="w-56 max-w-none p-1" align="start">
<div className="flex w-full flex-col gap-1.5 py-1">
<div className="mb-0.5 font-medium text-foreground">Response stats</div>
<ResponseStatRow
label="Tokens per second"
value={formatTokensPerSecond(stats.tokensPerSecond)}
/>
<ResponseStatRow label="Duration" value={formatAgentResponseDuration(stats.durationMs)} />
{stats.inputTokens !== null ? (
<ResponseStatRow
label="Input tokens"
value={formatAgentResponseTokenCount(stats.inputTokens)}
/>
) : null}
{stats.cachedInputTokens !== null ? (
<ResponseStatRow
label="Cached input"
value={formatAgentResponseTokenCount(stats.cachedInputTokens)}
/>
) : null}
{stats.outputTokens !== null ? (
<ResponseStatRow
label="Output tokens"
value={formatAgentResponseTokenCount(stats.outputTokens)}
/>
) : null}
{stats.reasoningOutputTokens !== null ? (
<ResponseStatRow
label="Reasoning tokens"
value={formatAgentResponseTokenCount(stats.reasoningOutputTokens)}
/>
) : null}
{stats.toolUses !== null ? (
<ResponseStatRow
label="Tool calls"
value={formatAgentResponseTokenCount(stats.toolUses)}
/>
) : null}
</div>
</TooltipPopup>
</Tooltip>
);
}
function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const assistantCopyState = resolveAssistantMessageCopyState({
text: row.message.text ?? null,
@@ -59,11 +59,25 @@ export function BetaSettingsPanel() {
const sidebarAutoSettleAfterDays = useClientSettings(
(settings) => settings.sidebarAutoSettleAfterDays,
);
const statsForNerdsEnabled = useClientSettings((settings) => settings.statsForNerdsEnabled);
const updateSettings = useUpdateClientSettings();
return (
<SettingsPageContainer>
<SettingsSection title="Beta features">
<SettingsRow
title="Stats for nerds"
description="Replace assistant response timestamps with tokens per second. Hover the rate to see duration, token usage, and tool calls when the agent provides them."
control={
<Switch
checked={statsForNerdsEnabled}
onCheckedChange={(checked) =>
updateSettings({ statsForNerdsEnabled: Boolean(checked) })
}
aria-label="Enable stats for nerds"
/>
}
/>
<SettingsRow
title="Sidebar v2"
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
+10
View File
@@ -67,6 +67,16 @@ describe("ClientSettings environment identification", () => {
});
});
describe("ClientSettings beta features", () => {
it("defaults stats for nerds off and accepts an explicit choice", () => {
expect(decodeClientSettings({}).statsForNerdsEnabled).toBe(false);
expect(decodeClientSettings({ statsForNerdsEnabled: true }).statsForNerdsEnabled).toBe(true);
expect(decodeClientSettingsPatch({ statsForNerdsEnabled: true }).statsForNerdsEnabled).toBe(
true,
);
});
});
describe("ClientSettings sidebar v2", () => {
it("defaults the beta off with a three-day auto-settle threshold", () => {
const settings = decodeClientSettings({});
+2
View File
@@ -127,6 +127,7 @@ export const ClientSettingsSchema = Schema.Struct({
// there is no way to tell that apart from "left alone", and a channel-derived
// default could never reach them. Mirrors `updateChannelConfiguredByUser`.
sidebarV2ConfiguredByUser: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
statsForNerdsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
timestampFormat: TimestampFormat.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
),
@@ -711,6 +712,7 @@ export const ClientSettingsPatch = Schema.Struct({
sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
sidebarV2Enabled: Schema.optionalKey(Schema.Boolean),
sidebarV2ConfiguredByUser: Schema.optionalKey(Schema.Boolean),
statsForNerdsEnabled: Schema.optionalKey(Schema.Boolean),
timestampFormat: Schema.optionalKey(TimestampFormat),
wordWrap: Schema.optionalKey(Schema.Boolean),
});