From 438bf7e53439db19db6f0f4143ad7495eb462ab5 Mon Sep 17 00:00:00 2001 From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com> Date: Thu, 30 Jul 2026 19:05:24 +0000 Subject: [PATCH] feat: add stats for nerds response details --- apps/web/src/components/ChatView.tsx | 2 + .../chat/MessagesTimeline.logic.test.ts | 86 +++++++++++ .../components/chat/MessagesTimeline.logic.ts | 106 +++++++++++++- .../components/chat/MessagesTimeline.test.tsx | 57 +++++++- .../src/components/chat/MessagesTimeline.tsx | 134 ++++++++++++++++-- .../components/settings/BetaSettingsPanel.tsx | 14 ++ packages/contracts/src/settings.test.ts | 10 ++ packages/contracts/src/settings.ts | 2 + 8 files changed, 397 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7aaae27890..fa34e07a79 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -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} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 6d74204bc1..c620831278 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -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([ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 3227bac241..5b6bb5d113 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -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 | null { + return activity.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : 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, + activities: ReadonlyArray, +): ReadonlyMap { + const usageByTurnId = new Map>(); + 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(); + 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(); } diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 83ca7d3e95..11cf0a99af 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -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( + , + ); + const statsMarkup = renderToStaticMarkup( + , + ); + + 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"); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index a429b54dea..45305712f3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -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; routeThreadKey: string; threadRef: ScopedThreadRef | null; markdownCwd: string | undefined; @@ -150,6 +158,7 @@ const TIMELINE_LIST_HEADER =
; const TIMELINE_LIST_FADE_HEADER =
; const TIMELINE_LIST_FOOTER =
; const EMPTY_TIMELINE_SKILLS: ReadonlyArray> = []; +const EMPTY_THREAD_ACTIVITIES: ReadonlyArray = []; // --------------------------------------------------------------------------- // Props (public API) @@ -174,6 +183,8 @@ interface MessagesTimelineProps { markdownCwd: string | undefined; resolvedTheme: "light" | "dark"; timestampFormat: TimestampFormat; + statsForNerdsEnabled?: boolean; + threadActivities?: ReadonlyArray; workspaceRoot: string | undefined; skills?: ReadonlyArray>; 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( null, @@ -418,6 +439,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ const sharedState = useMemo( () => ({ 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 - {!row.message.streaming && ( - - } - > - {formatShortTimestamp(row.message.updatedAt, ctx.timestampFormat)} - - - {formatChatTimestampTooltip(row.message.updatedAt, ctx.timestampFormat)} - - - )} + {!row.message.streaming && + (ctx.statsForNerdsEnabled && row.message.turnId ? ( + + ) : ( + + ))}
) : null}
@@ -1057,6 +1079,94 @@ function AssistantTimelineRow({ row }: { row: Extract + }> + {formatShortTimestamp(updatedAt, ctx.timestampFormat)} + + {formatChatTimestampTooltip(updatedAt, ctx.timestampFormat)} + + ); +} + +function ResponseStatRow({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ); +} + +function AssistantResponseStats({ + stats, + updatedAt, +}: { + stats: AgentResponseStats | null; + updatedAt: string; +}) { + if (!stats) { + return ; + } + + return ( + + + } + > + {formatTokensPerSecond(stats.tokensPerSecond)} + + +
+
Response stats
+ + + {stats.inputTokens !== null ? ( + + ) : null} + {stats.cachedInputTokens !== null ? ( + + ) : null} + {stats.outputTokens !== null ? ( + + ) : null} + {stats.reasoningOutputTokens !== null ? ( + + ) : null} + {stats.toolUses !== null ? ( + + ) : null} +
+
+
+ ); +} + function AssistantCopyButton({ row }: { row: Extract }) { const assistantCopyState = resolveAssistantMessageCopyState({ text: row.message.text ?? null, diff --git a/apps/web/src/components/settings/BetaSettingsPanel.tsx b/apps/web/src/components/settings/BetaSettingsPanel.tsx index 5a1ac03607..70d30d3f1f 100644 --- a/apps/web/src/components/settings/BetaSettingsPanel.tsx +++ b/apps/web/src/components/settings/BetaSettingsPanel.tsx @@ -59,11 +59,25 @@ export function BetaSettingsPanel() { const sidebarAutoSettleAfterDays = useClientSettings( (settings) => settings.sidebarAutoSettleAfterDays, ); + const statsForNerdsEnabled = useClientSettings((settings) => settings.statsForNerdsEnabled); const updateSettings = useUpdateClientSettings(); return ( + + updateSettings({ statsForNerdsEnabled: Boolean(checked) }) + } + aria-label="Enable stats for nerds" + /> + } + /> { }); }); +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({}); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7edda2e52e..83ce1d2eea 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -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), });