Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cowork-ui): show tokens per second in the Cowork transcript

thinhlpg432053ed0309
diff --git a/web-app/src/hooks/__tests__/useCoworkRun.test.ts b/web-app/src/hooks/__tests__/useCoworkRun.test.ts
index 90508393e..0aa8a3308 100644
--- a/web-app/src/hooks/__tests__/useCoworkRun.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkRun.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest'
-import { useCoworkRun } from '../useCoworkRun'
+import { useCoworkRun, type StreamEvent } from '../useCoworkRun'
// Covers only the llamacpp-attribution slice (llamacppRuns/pendingLlamacppError)
// added for Cowork's model-load/OOM feedback parity with regular chat — see
@@ -138,6 +138,36 @@ describe('useCoworkRun - subagent lanes', () => {
expect(runs.find((r) => r.runId === 'a')?.turns[0].content).toBe('from a')
expect(runs.find((r) => r.runId === 'b')?.turns).toEqual([])
})
+
+ // The lane renders `MessageItem` from these rows, so the child's step
+ // metadata has to land on the answer row for the speed readout to show.
+ it('hangs a child step metadata block on its answer row', () => {
+ useCoworkRun.getState().resetSubagents('s4')
+ useCoworkRun.getState().startSubagent('s4', 'a', 'one')
+ const route = (event: StreamEvent) =>
+ useCoworkRun.getState().routeIntoSubagent('s4', 'a', event)
+ route({ type: 'token', text: 'answer' })
+ route({
+ type: 'step_metadata',
+ metadata: { tokenSpeed: { tokenSpeed: 20, tokenCount: 40 } },
+ })
+ const turns = useCoworkRun.getState().subagents.s4[0].turns
+ expect(turns[0]).toMatchObject({
+ role: 'assistant',
+ content: 'answer',
+ metadata: { tokenSpeed: { tokenSpeed: 20 } },
+ })
+ })
+
+ it('drops a child step metadata block with no answer row to carry it', () => {
+ useCoworkRun.getState().resetSubagents('s5')
+ useCoworkRun.getState().startSubagent('s5', 'a', 'one')
+ useCoworkRun.getState().routeIntoSubagent('s5', 'a', {
+ type: 'step_metadata',
+ metadata: { tokenSpeed: { tokenSpeed: 20 } },
+ })
+ expect(useCoworkRun.getState().subagents.s5[0].turns).toEqual([])
+ })
})
describe('useCoworkRun - monitors and parking', () => {
diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.ts
index bb0207dc3..e5b4b6317 100644
--- a/web-app/src/hooks/useCoworkRun.ts
+++ b/web-app/src/hooks/useCoworkRun.ts
@@ -24,6 +24,9 @@ export type {
// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").
// Owned here because this store is what consumes/dispatches them.
+//
+// `step_metadata` is the one JS-only variant: a Cowork child's own stream
+// produces it (`coworkSubagent`), and it never crosses the Rust boundary.
export type StreamEvent =
| { type: 'token'; text: string }
| { type: 'reasoning'; text: string }
@@ -46,6 +49,13 @@ export type StreamEvent =
| { type: 'subagent_start'; run_id: string; name: string }
| { type: 'subagent_end'; run_id: string; name: string; usage: Usage | null }
| { type: 'turn_usage'; usage: Usage }
+ | {
+ /** A child's finished step, carrying the metadata `MessageItem` renders
+ * the token-speed popover from. Lane-local: the parent's own steps reach
+ * the transcript through `turnsFor` instead. */
+ type: 'step_metadata'
+ metadata: Record<string, unknown>
+ }
| { type: 'subagent'; run_id: string; name: string; event: StreamEvent }
// Append a streamed token to the last assistant turn, or start a new one.
@@ -155,6 +165,15 @@ function applyInnerToTurns(
diff: inner.diff,
status: 'done',
})
+ // A child's finished step. It lands on the answer row the step streamed
+ // into, so the lane's last assistant message carries the same metadata the
+ // main lane's rows do. A step that answered nothing has no row to hang it
+ // on, and nothing for the popover to describe.
+ case 'step_metadata': {
+ const last = turns[turns.length - 1]
+ if (!last || last.role !== 'assistant') return turns
+ return [...turns.slice(0, -1), { ...last, metadata: inner.metadata }]
+ }
default:
return turns // step / anything else: no visible turn
}
diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.ts
index a30987edb..b7272459d 100644
--- a/web-app/src/lib/__tests__/coworkRunner.test.ts
+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts
@@ -123,6 +123,33 @@ describe('consumeStep', () => {
)
expect(r.errorText).toBe('boom')
})
+
+ // The transcript renders chat's token-speed popover from this block, so the
+ // whole finish metadata has to survive the fold, not just the usage fields.
+ it('keeps the finish metadata the transport stamped on the step', async () => {
+ const tokenSpeed = {
+ tokenSpeed: 42.5,
+ promptSpeed: 120,
+ tokenCount: 300,
+ durationMs: 7000,
+ }
+ const r = await consumeStep(
+ streamOf([
+ { type: 'text-delta', id: 't', delta: 'hi' } as UIMessageChunk,
+ {
+ type: 'finish',
+ messageMetadata: {
+ finishReason: 'stop',
+ usage: { inputTokens: 10, outputTokens: 300, totalTokens: 310 },
+ tokenSpeed,
+ },
+ } as unknown as UIMessageChunk,
+ ]),
+ noopSink()
+ )
+ expect(r.usage?.total_tokens).toBe(310)
+ expect(r.metadata).toMatchObject({ finishReason: 'stop', tokenSpeed })
+ })
})
describe('runTurn', () => {
@@ -407,6 +434,50 @@ describe('reasoning placement', () => {
})
})
+describe('step metadata', () => {
+ const tokenSpeed = {
+ tokenSpeed: 42.5,
+ promptSpeed: 120,
+ tokenCount: 300,
+ durationMs: 7000,
+ }
+ const step: StepResult = {
+ text: 'answer',
+ reasoning: '',
+ toolCalls: [],
+ usage: null,
+ metadata: { usage: { totalTokens: 310 }, tokenSpeed },
+ aborted: false,
+ }
+
+ // The row is what `coworkTurnsToUIMessages` turns into the assistant message
+ // `MessageItem` reads its metadata from.
+ it('rides the row that opens the step, not every row of it', () => {
+ const rows = turnsFor(
+ {
+ ...step,
+ toolCalls: [
+ { toolCallId: 'c1', toolName: 'read', input: {} } as PendingToolCall,
+ ],
+ },
+ new Map()
+ )
+ expect(rows[0].metadata).toEqual(step.metadata)
+ expect(rows[1].metadata).toBeUndefined()
+ })
+
+ // A step that answers nothing produces no rows, so there is nothing to hang
+ // the metadata on -- and no message for it to describe.
+ it('has nothing to attach to when the step produced no rows', () => {
+ expect(
+ turnsFor(
+ { ...step, text: '', reasoning: '', toolCalls: [] },
+ new Map()
+ )
+ ).toEqual([])
+ })
+})
+
describe('diff sidecar', () => {
// A diff is a rendering aid. Sending it to the model doubles the cost of
// every edit and corrupts the output the tool widget parses.
diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.ts
index edc66d013..1e19cb967 100644
--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts
+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts
@@ -473,6 +473,48 @@ describe('runSubagent', () => {
expect(kinds).toContain('token')
})
+ // The lane renders `MessageItem` from these turns, so the child's finish
+ // metadata has to reach it or the subagent rows show no speed at all.
+ it('forwards a finished child step metadata block, before its tool results', async () => {
+ mockSteps([
+ [
+ { type: 'text-delta', delta: 'answer' },
+ { type: 'tool-input-start', toolCallId: 'c1', toolName: 'read' },
+ {
+ type: 'tool-input-available',
+ toolCallId: 'c1',
+ toolName: 'read',
+ input: { path: 'a' },
+ },
+ {
+ type: 'finish',
+ messageMetadata: {
+ usage: { totalTokens: 12 },
+ tokenSpeed: { tokenSpeed: 42.5, tokenCount: 300, durationMs: 7000 },
+ },
+ },
+ ],
+ ])
+ const opts = baseOpts()
+ await runSubagent(opts)
+ const events = (opts.events.onInner.mock.calls as [StreamEvent][]).map(
+ ([e]) => e
+ )
+ const step = events.find((e) => e.type === 'step_metadata')
+ expect(step).toMatchObject({
+ metadata: { tokenSpeed: { tokenSpeed: 42.5, tokenCount: 300 } },
+ })
+ // Before the results: the lane hangs it on the answer row, and a tool row
+ // arriving first would leave it nowhere to land.
+ const kinds = events.map((e) => e.type)
+ expect(kinds.indexOf('step_metadata')).toBeGreaterThan(
+ kinds.indexOf('tool_call')
+ )
+ expect(kinds.indexOf('step_metadata')).toBeLessThan(
+ kinds.indexOf('tool_result')
+ )
+ })
+
it('dispatches the child tool calls', async () => {
mockSteps([toolStep('c1', 'read', { path: 'a' }), textStep('done')])
const opts = baseOpts()
diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.ts
index 5690e20f9..08a0161e7 100644
--- a/web-app/src/lib/__tests__/coworkTurns.test.ts
+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts
@@ -25,6 +25,31 @@ describe('coworkTurnsToUIMessages', () => {
expect(parts[1]).toEqual({ type: 'text', text: 'answer' })
})
+ // `MessageItem` reads the speed popover off the message metadata, so the row
+ // metadata a finished step carries has to land there. Steps fold into one
+ // assistant message until a question splits them, and the popover describes
+ // the newest generation, so the later step wins.
+ it('hands the step metadata to the message its parts fold into', () => {
+ const messages = coworkTurnsToUIMessages([
+ { role: 'user', content: 'q' },
+ {
+ role: 'assistant',
+ content: 'first',
+ metadata: { tokenSpeed: { tokenSpeed: 10 } },
+ },
+ { role: 'tool', content: 'ok', name: 'read', callId: 'c1', status: 'done' },
+ {
+ role: 'assistant',
+ content: 'second',
+ metadata: { tokenSpeed: { tokenSpeed: 20 } },
+ },
+ ] as CoworkTurn[])
+ expect((messages[1] as any).metadata).toEqual({
+ tokenSpeed: { tokenSpeed: 20 },
+ })
+ expect((messages[0] as any).metadata).toBeUndefined()
+ })
+
it('a reasoning-only turn still renders (thought, then straight to a tool)', () => {
const messages = coworkTurnsToUIMessages([
{ role: 'user', content: 'q' },
diff --git a/web-app/src/lib/__tests__/stepMetadata.test.ts b/web-app/src/lib/__tests__/stepMetadata.test.ts
new file mode 100644
index 000000000..54a8bbabc
--- /dev/null
+++ b/web-app/src/lib/__tests__/stepMetadata.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { createStepMetadata } from '../stepMetadata'
+
+const START = new Date('2026-01-01T00:00:00Z')
+
+const finish = (usage: {
+ inputTokens?: number
+ outputTokens?: number
+ totalTokens?: number
+}) => ({
+ type: 'finish',
+ totalUsage: usage,
+ finishReason: 'stop',
+})
+
+describe('createStepMetadata', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ const withClock = () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(START)
+ }
+
+ // llama.cpp reports the engine's own rate; measuring the arrival of tokens
+ // over the wire would report the network and the renderer instead.
+ it('prefers the provider timings when the engine reports them', () => {
+ withClock()
+ const meta = createStepMetadata()
+ meta.onPart({ type: 'text-start' })
+ meta.onPart({
+ type: 'finish-step',
+ providerMetadata: { providerMetadata: { tokensPerSecond: 30, promptPerSecond: 120 } },
+ })
+ vi.advanceTimersByTime(2000)
+
+ const out = meta.onPart(
+ finish({ inputTokens: 900, outputTokens: 60, totalTokens: 960 })
+ )
+ expect(out?.tokenSpeed.tokenSpeed).toBe(30)
+ expect(out?.tokenSpeed.promptSpeed).toBe(120)
+ expect(out?.usage).toEqual({
+ inputTokens: 900,
+ outputTokens: 60,
+ totalTokens: 960,
+ })
+ expect(out?.finishReason).toBe('stop')
+ })
+
+ // The clock starts when the model starts writing, so prompt processing (which
+ // can dwarf generation on a long conversation) is not charged to the rate.
+ it('times the observed rate from the first content part', () => {
+ withClock()
+ const meta = createStepMetadata()
+ vi.advanceTimersByTime(30_000)
+ meta.onPart({ type: 'reasoning-start' })
+ vi.advanceTimersByTime(2000)
+
+ const out = meta.onPart(finish({ outputTokens: 100, totalTokens: 100 }))
+ expect(out?.tokenSpeed.tokenSpeed).toBe(50)
+ expect(out?.tokenSpeed.tokenCount).toBe(100)
+ expect(out?.tokenSpeed.durationMs).toBe(2000)
+ })
+
+ it('reports no rate for a step that produced nothing', () => {
+ withClock()
+ const meta = createStepMetadata()
+ meta.onPart({ type: 'text-start' })
+ vi.advanceTimersByTime(1000)
+
+ const out = meta.onPart(finish({ outputTokens: 0, totalTokens: 40 }))
+ expect(out?.tokenSpeed.tokenSpeed).toBe(0)
+ // A prompt-only total still has to survive: the budget reads it.
+ expect(out?.usage.totalTokens).toBe(40)
+ })
+
+ it('stamps nothing until the step finishes', () => {
+ withClock()
+ const meta = createStepMetadata()
+ expect(meta.onPart({ type: 'text-start' })).toBeUndefined()
+ expect(meta.onPart({ type: 'text-delta' })).toBeUndefined()
+ expect(meta.onPart({ type: 'finish-step' })).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.ts
index 88276a487..728f6ba58 100644
--- a/web-app/src/lib/coworkRunner.ts
+++ b/web-app/src/lib/coworkRunner.ts
@@ -55,6 +55,10 @@ export type StepResult = {
reasoning: string
toolCalls: PendingToolCall[]
usage: Usage | null
+ /** The step's finish metadata, verbatim: `usage` and the `tokenSpeed` block the
+ * transport stamps on the stream's `finish` chunk. Rides the step's transcript
+ * row so `MessageItem` renders the token-speed popover chat shows. */
+ metadata?: Record<string, unknown>
errorText?: string
aborted: boolean
}
@@ -259,9 +263,14 @@ export async function consumeStep(
case 'abort':
result.aborted = true
break
- case 'finish':
+ case 'finish': {
result.usage = usageOf(chunk.messageMetadata) ?? result.usage
+ const meta = chunk.messageMetadata
+ if (meta && typeof meta === 'object') {
+ result.metadata = meta as Record<string, unknown>
+ }
break
+ }
default:
break
}
@@ -340,6 +349,12 @@ export function turnsFor(
status: outcome ? 'done' : 'running',
})
}
+ // The step's finish metadata rides its first row, which is the row that opens
+ // the assistant message these parts fold into. A step that emitted no text and
+ // no calls produces no rows at all, so there is nothing to attach it to.
+ if (step.metadata && turns.length > 0) {
+ turns[0] = { ...turns[0], metadata: step.metadata }
+ }
return turns
}
diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.ts
index a978ca15d..88ef68df7 100644
--- a/web-app/src/lib/coworkSubagent.ts
+++ b/web-app/src/lib/coworkSubagent.ts
@@ -1,4 +1,3 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
import {
convertToModelMessages,
streamText,
@@ -16,6 +15,7 @@ import {
} from '@/lib/coworkTools'
import { MONITOR_TOOL_NAME } from '@/lib/coworkMonitor'
import { MAX_SUBAGENT_STEPS } from '@/lib/coworkBudget'
+import { createStepMetadata } from '@/lib/stepMetadata'
import {
runTurn,
type PendingToolCall,
@@ -465,18 +465,11 @@ function childStep(opts: {
tools: Object.keys(opts.tools).length > 0 ? opts.tools : undefined,
toolChoice: Object.keys(opts.tools).length > 0 ? 'auto' : undefined,
})
+ const stepMetadata = createStepMetadata()
return result.toUIMessageStream({
- messageMetadata: ({ part }) => {
- if (part.type !== 'finish') return undefined
- const usage = (part as any).totalUsage
- return {
- usage: {
- inputTokens: usage?.inputTokens,
- outputTokens: usage?.outputTokens,
- totalTokens: usage?.totalTokens,
- },
- }
- },
+ // The same usage-and-speed block the parent's transport stamps, assembled
+ // by the same helper, so a child's lane shows the readout chat shows.
+ messageMetadata: ({ part }) => stepMetadata.onPart(part),
onError: (error) =>
error instanceof Error ? error.message : String(error),
})
@@ -565,6 +558,11 @@ export async function runSubagent(
sink,
onStep: ({ result, outcomes }) => {
if (result.text.trim()) finalText = result.text
+ // Ahead of the results: the lane hangs it on the child's answer row,
+ // and a tool result that arrives first would put a tool row last.
+ if (result.metadata) {
+ events.onInner({ type: 'step_metadata', metadata: result.metadata })
+ }
for (const [id, o] of outcomes) {
events.onInner({
type: 'tool_result',
diff --git a/web-app/src/lib/coworkTurns.ts b/web-app/src/lib/coworkTurns.ts
index 597f2dd3f..12311ae7a 100644
--- a/web-app/src/lib/coworkTurns.ts
+++ b/web-app/src/lib/coworkTurns.ts
@@ -108,6 +108,12 @@ export function coworkTurnsToUIMessages(
return
}
+ // Whatever the step finished with (usage, token speed) rides the assistant
+ // message its parts fold into, so `MessageItem` renders chat's token-speed
+ // popover from the same metadata shape chat persists. A later step
+ // overwrites it: the popover describes the newest generation, not the run.
+ if (turn.metadata) ensureAssistant(i).metadata = turn.metadata
+
if (turn.role === 'assistant') {
// Natively streamed reasoning rides beside the content (see
// `CoworkTurn.reasoning`) and becomes a reasoning part ahead of the text,
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index d9afdd906..3573f2cb9 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -66,6 +66,7 @@ import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'
import { isPredefinedRemoteProvider } from '@/lib/providerCaps'
import { paramsSettings } from '@/lib/predefinedParams'
import { CHAT_SLOT_ID } from '@/constants/models'
+import { createStepMetadata } from '@/lib/stepMetadata'
export type TokenUsageCallback = (
usage: LanguageModelUsage,
@@ -1529,7 +1530,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
selectedModel
)
- let streamStartTime: number | undefined
useAppState.getState().updatePromptProgress(undefined)
useAppState.getState().updateThreadPromptProgress(threadId, undefined)
useAppState.getState().updateLiveTokenStats(undefined)
@@ -1557,72 +1557,12 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
},
})
- let tokensPerSecond = 0
- let promptPerSecond = 0
+ const stepMetadata = createStepMetadata()
const uiStream = result.toUIMessageStream({
- messageMetadata: ({ part }) => {
- if (
- !streamStartTime &&
- (part.type === 'text-start' || part.type === 'reasoning-start')
- ) {
- streamStartTime = Date.now()
- }
-
- if (part.type === 'finish-step') {
- tokensPerSecond =
- (part.providerMetadata?.providerMetadata
- ?.tokensPerSecond as number) || 0
- promptPerSecond =
- (part.providerMetadata?.providerMetadata
- ?.promptPerSecond as number) || 0
- }
-
- // Add usage and token speed to metadata on finish
- if (part.type === 'finish') {
- const finishPart = part as {
- type: 'finish'
- totalUsage: LanguageModelUsage
- finishReason: string
- }
- const usage = finishPart.totalUsage
- const durationMs = streamStartTime ? Date.now() - streamStartTime : 0
- const durationSec = durationMs / 1000
-
- // Use provider's outputTokens, or llama.cpp completionTokens, or fall back to text delta count
- const outputTokens = usage?.outputTokens ?? 0
- const inputTokens = usage?.inputTokens
-
- // Use llama.cpp's tokens per second if available, otherwise calculate from duration
- let tokenSpeed: number
- if (durationSec > 0 && outputTokens > 0) {
- tokenSpeed =
- tokensPerSecond > 0 ? tokensPerSecond : outputTokens / durationSec
- } else {
- tokenSpeed = 0
- }
-
- return {
- finishReason: finishPart.finishReason,
- usage: {
- inputTokens: inputTokens,
- outputTokens: outputTokens,
- totalTokens:
- usage?.totalTokens ?? (inputTokens ?? 0) + outputTokens,
- },
- tokenSpeed: {
- tokenSpeed: Math.round(tokenSpeed * 100) / 100,
- promptSpeed: promptPerSecond
- ? Math.round(promptPerSecond * 100) / 100
- : undefined,
- tokenCount: outputTokens,
- durationMs,
- },
- }
- }
-
- return undefined
- },
+ // Usage and token speed, assembled by the one implementation every
+ // streaming surface shares (see `lib/stepMetadata`).
+ messageMetadata: ({ part }) => stepMetadata.onPart(part),
onError: (error) => {
// A superseded request (e.g. after Reload) must not clear loading/stream
// state the newer request already owns.
diff --git a/web-app/src/lib/stepMetadata.ts b/web-app/src/lib/stepMetadata.ts
new file mode 100644
index 000000000..652850eb0
--- /dev/null
+++ b/web-app/src/lib/stepMetadata.ts
@@ -0,0 +1,96 @@
+import type { LanguageModelUsage } from 'ai'
+
+/** The speed block the transcript's token-speed popover reads. */
+export type TokenSpeedMeta = {
+ tokenSpeed: number
+ promptSpeed?: number
+ tokenCount: number
+ durationMs: number
+}
+
+/** What a finished step leaves on its message, as `MessageItem` reads it. */
+export type StepMetadata = {
+ finishReason?: string
+ usage: {
+ inputTokens?: number
+ outputTokens: number
+ totalTokens: number
+ }
+ tokenSpeed: TokenSpeedMeta
+}
+
+type StreamPart = {
+ type: string
+ providerMetadata?: unknown
+ totalUsage?: unknown
+ finishReason?: unknown
+}
+
+const round2 = (n: number) => Math.round(n * 100) / 100
+
+/**
+ * Assembles the metadata a streamed step stamps on its message.
+ *
+ * One implementation for every surface that streams a step -- the chat
+ * transport and a subagent's own stream -- so the speed a Cowork lane shows is
+ * computed exactly as chat computes it. Generation speed is the engine's own
+ * when the provider reports timings (llama.cpp, MLX) and the observed output
+ * rate otherwise. The clock starts at the first content part, so prompt
+ * processing is not counted against generation.
+ */
+export function createStepMetadata() {
+ let startedAt: number | undefined
+ let tokensPerSecond = 0
+ let promptPerSecond = 0
+
+ return {
+ /** Feed the parts the AI SDK hands `messageMetadata`; returns the metadata
+ * once the step finishes, and `undefined` for every other part. */
+ onPart(part: StreamPart): StepMetadata | undefined {
+ const startsContent =
+ part.type === 'text-start' || part.type === 'reasoning-start'
+ if (startedAt === undefined && startsContent) startedAt = Date.now()
+
+ if (part.type === 'finish-step') {
+ const timings = (
+ part.providerMetadata as
+ | { providerMetadata?: Record<string, unknown> }
+ | undefined
+ )?.providerMetadata
+ tokensPerSecond = (timings?.tokensPerSecond as number) || 0
+ promptPerSecond = (timings?.promptPerSecond as number) || 0
+ return undefined
+ }
+
+ if (part.type !== 'finish') return undefined
+
+ const usage = part.totalUsage as LanguageModelUsage | undefined
+ const durationMs = startedAt ? Date.now() - startedAt : 0
+ const outputTokens = usage?.outputTokens ?? 0
+ const inputTokens = usage?.inputTokens
+
+ let tokenSpeed = 0
+ if (durationMs > 0 && outputTokens > 0) {
+ tokenSpeed =
+ tokensPerSecond > 0
+ ? tokensPerSecond
+ : outputTokens / (durationMs / 1000)
+ }
+
+ return {
+ finishReason: part.finishReason as string | undefined,
+ usage: {
+ inputTokens,
+ outputTokens,
+ totalTokens: usage?.totalTokens ?? (inputTokens ?? 0) + outputTokens,
+ },
+ tokenSpeed: {
+ tokenSpeed: round2(tokenSpeed),
+ promptSpeed: promptPerSecond ? round2(promptPerSecond) : undefined,
+ tokenCount: outputTokens,
+ durationMs,
+ },
+ }
+ },
+ }
+}
diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.ts
index cbdbb4386..b1856862e 100644
--- a/web-app/src/types/coworkSession.ts
+++ b/web-app/src/types/coworkSession.ts
@@ -38,6 +38,11 @@ export type CoworkTurn = {
isError?: boolean
diff?: string
status?: 'running' | 'done'
+ /** Assistant-row only: the model metadata the step finished with, verbatim
+ * from the stream (`usage`, `tokenSpeed`, `finishReason`). `MessageItem` reads
+ * it exactly as it reads the metadata chat persists on a message, so the token
+ * speed popover works here without a second implementation. */
+ metadata?: Record<string, unknown>
}
/** A pasted or picked image/audio/video, shaped as an AI SDK `file` part. */