From 174a3d44cb489ce7f86a54be445b58604197472b Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 3 Nov 2026 11:06:57 +0800 Subject: [PATCH] fix: include TTFT in flow chat output speed --- .../dispatch/DispatchJobObserver.test.ts | 4 +- .../modern/FLOWCHAT_VERIFICATION.md | 2 +- .../modern/FLOWCHAT_VIRTUALIZATION.md | 12 ++--- .../modern/TurnUsageMetrics.test.tsx | 8 ++-- .../store/modernFlowChatStore.test.ts | 3 +- .../flow_chat/types/flow-chat-projection.ts | 2 +- .../flow_chat/utils/turnUsageMetrics.test.ts | 47 +++++++++---------- .../src/flow_chat/utils/turnUsageMetrics.ts | 33 ++++++------- src/web-ui/src/locales/en-US/flow-chat.json | 2 +- src/web-ui/src/locales/zh-CN/flow-chat.json | 2 +- 10 files changed, 55 insertions(+), 60 deletions(-) diff --git a/src/web-ui/src/features/dispatch/DispatchJobObserver.test.ts b/src/web-ui/src/features/dispatch/DispatchJobObserver.test.ts index 55f46d7230..ab9c5d2997 100644 --- a/src/web-ui/src/features/dispatch/DispatchJobObserver.test.ts +++ b/src/web-ui/src/features/dispatch/DispatchJobObserver.test.ts @@ -897,10 +897,10 @@ describe('DispatchJobObserver', () => { const rounds = [...turn!.modelRounds, { id: 'model-round-0', index: 0, items: [], isStreaming: false, isComplete: true, status: 'completed' as const, startTime: 0, - ttftMs: 1_500, firstVisibleOutputMs: 1_000, streamDurationMs: 5_000, + durationMs: 5_000, ttftMs: 1_500, firstVisibleOutputMs: 1_000, streamDurationMs: 5_000, }]; expect(getTurnTtftMs(rounds)).toBe(1_500); - expect(getTurnOutputDurationMs(rounds)).toBe(4_000); + expect(getTurnOutputDurationMs(rounds)).toBe(5_000); expect(mocks.dispatchExternal).not.toHaveBeenCalled(); cleanup(); }); diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index bf45388ff2..b36223a41d 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -24,7 +24,7 @@ each missing what the other had. | `exportImageLayout.test.ts` | initiating reading-column width and font settings across wide/narrow panes, hidden sibling sessions, and unmounted source rows; measured DOM fixtures, not native visual or remote-host validation | | `../../utils/exportImageCapture.test.ts`, `../../utils/captureElementToDownloadsPng.test.tsx` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery, font readiness/embedding, timeout cleanup, and widget export save/error handling; rasterizer fixtures, not native WebView or remote-host validation | | `../../../shared/ui/Tooltip.test.tsx` | shared metric click opening, immediate scroll dismissal, delayed-open cancellation, viewport-exit observer cleanup and no automatic reopening; DOM/observer behavior only, not native scrolling or visual proof | -| `../../utils/turnUsageMetrics.test.ts`, `TurnUsageMetrics.test.tsx`, `../../store/modernFlowChatStore.test.ts`, `../../../features/dispatch/DispatchJobObserver.test.ts` | separate request TTFT, effective-output rate excluding waiting and tools, complete multi-round timing, controller setup-row exclusion, legacy/missing/zero telemetry, speed boundaries and projection | +| `../../utils/turnUsageMetrics.test.ts`, `TurnUsageMetrics.test.tsx`, `../../store/modernFlowChatStore.test.ts`, `../../../features/dispatch/DispatchJobObserver.test.ts` | separate request TTFT, request-to-completion output rate including provider wait and excluding tool execution, complete multi-round timing, controller setup-row exclusion, legacy/missing/zero telemetry, speed boundaries and projection | | `../../services/flow-chat-manager/EventHandlerModule.test.ts`, `../../services/flow-chat-manager/PersistenceModule.test.ts`, `../../store/FlowChatStore.test.ts` | live cache aggregation, optional-field persistence and legacy/current hydration; no remote-host claim | | `../../hooks/useSessionReadOnOpen.test.tsx` | opening and foreground results mark read; inactive scenes, background windows, unmounts, and device switches cannot acknowledge from stale views | | `../../selection/conversationExcerptInventory.test.ts` | source session/device isolation, consumed draft/queue marks, sent-number retention without source marks, stable unrelated snapshots | diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index 6548b84ae5..bf7196c99e 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -169,12 +169,12 @@ for the first model call (the accepted attempt after a retry). Text, thinking an tool output count as effective output; metadata-only packets do not. The host reports this optional duration, so controller clock skew and event delivery latency do not affect it. The speed levels use output tokens divided by the sum -of each call's first-effective-output-to-stream-end time, with thresholds at 15, -40 and 80 tokens/s disclosed in the Tooltip. HTTP setup, TTFT, tool execution and -post-stream usage persistence are excluded. Missing or inconsistent timing in -any model call, or retries whose earlier attempt timing is unavailable, omit speed -rather than substituting turn wall time. Negative-index controller setup/audit -rows are presentation only and do not participate in either metric. +of each call's request-to-completion time, including TTFT but excluding tool +execution, with thresholds at 15, 40 and 80 tokens/s disclosed in the Tooltip. +Missing or inconsistent timing in any model call, or retries whose earlier +attempt timing is unavailable, omit speed rather than substituting partial turn +time. Negative-index controller setup/audit rows are presentation only and do +not participate in either metric. Legacy records omit unknown TTFT; reported zero remains valid. Timing survives the normal history save/load path. Total usage and the cache ring form one unit, hidden only when both values are missing. If usage is known but the cache ratio diff --git a/src/web-ui/src/flow_chat/components/modern/TurnUsageMetrics.test.tsx b/src/web-ui/src/flow_chat/components/modern/TurnUsageMetrics.test.tsx index ce6cc7757e..f8bd41ba8c 100644 --- a/src/web-ui/src/flow_chat/components/modern/TurnUsageMetrics.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/TurnUsageMetrics.test.tsx @@ -20,21 +20,21 @@ describe('completed turn usage', () => { const round: ModelRound = { id: 'round', index: 0, startTime: 0, endTime: 90_000, status: 'completed', items: [], isStreaming: false, isComplete: true, - firstChunkMs: 10, firstVisibleOutputMs: 2_000, streamDurationMs: 12_000, ttftMs: 3_000, + firstChunkMs: 10, firstVisibleOutputMs: 2_000, streamDurationMs: 12_000, durationMs: 12_000, ttftMs: 3_000, }; const usage = { inputTokens: 10_000, outputTokens: 2_000, totalTokens: 12_000, timestamp: 90_000 }; - it('shows request TTFT separately and calculates speed only over effective output', () => { + it('shows request TTFT separately and includes it in output speed', () => { const html = renderToStaticMarkup(); expect(html).toContain('TTFT 3 sec'); - expect(html).toContain('200 t/s'); + expect(html).toContain('166.7 t/s'); expect(html).toContain('data-openbitfun-part="ttft"'); expect(html).toContain('data-openbitfun-part="speed"'); }); it('keeps legacy usage visible without inventing TTFT or throughput from wall time', () => { - const legacy = { ...round, firstVisibleOutputMs: undefined, ttftMs: undefined }; + const legacy = { ...round, durationMs: undefined, firstVisibleOutputMs: undefined, ttftMs: undefined }; const html = renderToStaticMarkup(); expect(html).toContain('data-openbitfun-part="tokens"'); diff --git a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts index b38f49125a..1bed253abd 100644 --- a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts @@ -647,6 +647,7 @@ describe('sessionToVirtualItems explore grouping', () => { modelRounds: [makeRound({ id: 'round-with-answer', items: [makeTextItem('text-final', 'Here is the answer.')], + durationMs: 1500, streamDurationMs: 1200, firstChunkMs: 20, firstVisibleOutputMs: 200, @@ -671,7 +672,7 @@ describe('sessionToVirtualItems explore grouping', () => { turnStartedAt: 900, turnEndedAt: 2400, turnDurationMs: 1500, - turnOutputDurationMs: 1000, + turnOutputDurationMs: 1500, turnTtftMs: 350, turnTokenUsage: { inputTokens: 1200, diff --git a/src/web-ui/src/flow_chat/types/flow-chat-projection.ts b/src/web-ui/src/flow_chat/types/flow-chat-projection.ts index 2bcba4c0a4..ab6f530aab 100644 --- a/src/web-ui/src/flow_chat/types/flow-chat-projection.ts +++ b/src/web-ui/src/flow_chat/types/flow-chat-projection.ts @@ -64,7 +64,7 @@ type VirtualContent = turnStartedAt?: number; turnEndedAt?: number; turnDurationMs?: number; - /** Streaming window only; the throughput denominator, not turn wall time. */ + /** Sum of model request durations including TTFT; the throughput denominator. */ turnOutputDurationMs?: number; turnTtftMs?: number; turnTokenUsage?: TokenUsage; diff --git a/src/web-ui/src/flow_chat/utils/turnUsageMetrics.test.ts b/src/web-ui/src/flow_chat/utils/turnUsageMetrics.test.ts index 9c2a069f27..e9e2fec781 100644 --- a/src/web-ui/src/flow_chat/utils/turnUsageMetrics.test.ts +++ b/src/web-ui/src/flow_chat/utils/turnUsageMetrics.test.ts @@ -48,61 +48,60 @@ describe('getTurnUsageMetrics', () => { .toEqual({ totalTokens: null, cacheHitRate: null, outputRate: null, speedLevel: null }); }); - it('divides by streaming time so tool execution cannot deflate the rate', () => { - const rounds = [round({ streamDurationMs: 12_000, firstVisibleOutputMs: 2_000 })]; - // The turn took 90s wall time; the model only streamed for 10s. + it('includes TTFT in request duration so buffered output cannot inflate the rate', () => { + const rounds = [round({ durationMs: 12_000, streamDurationMs: 12_000, firstVisibleOutputMs: 2_000 })]; + // The turn took 90s wall time; the model request took 12s including TTFT. expect(getTurnUsageMetrics({ ...usage, outputTokens: 2_000 }, getTurnOutputDurationMs(rounds))) - .toMatchObject({ outputRate: 200, speedLevel: 4 }); + .toMatchObject({ outputRate: 2_000 / 12, speedLevel: 4 }); }); }); describe('getTurnOutputDurationMs', () => { - it('subtracts TTFT within the stream window, ignoring earlier metadata chunks', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 12_000, firstChunkMs: 50, firstVisibleOutputMs: 2_000, ttftMs: 3_000 })])).toBe(10_000); + it('uses request-to-completion duration, including TTFT and ignoring stream marks', () => { + expect(getTurnOutputDurationMs([round({ durationMs: 12_000, streamDurationMs: 12_000, firstChunkMs: 50, firstVisibleOutputMs: 2_000, ttftMs: 3_000 })])).toBe(12_000); }); - it('uses effective output even when the first upstream chunk is unrecorded', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 9_000, firstVisibleOutputMs: 1_500 })])).toBe(7_500); + it('accepts a pseudo-stream duration when one large output chunk arrives late', () => { + expect(getTurnOutputDurationMs([round({ durationMs: 30_000, streamDurationMs: 30_010, firstVisibleOutputMs: 30_000 })])).toBe(30_000); }); - it('does not invent a generation window when only the first upstream chunk is known', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 9_000, firstChunkMs: 50 })])).toBeUndefined(); + it('does not invent request time when only stream marks are known', () => { + expect(getTurnOutputDurationMs([round({ streamDurationMs: 9_000, firstVisibleOutputMs: 1_500 })])).toBeUndefined(); }); it('sums every round of a multi-round turn', () => { expect(getTurnOutputDurationMs([ - round({ streamDurationMs: 5_000, firstVisibleOutputMs: 1_000 }), - round({ streamDurationMs: 7_000, firstVisibleOutputMs: 2_000 }), - ])).toBe(9_000); + round({ durationMs: 5_000, streamDurationMs: 5_000, firstVisibleOutputMs: 1_000 }), + round({ durationMs: 7_000, streamDurationMs: 7_000, firstVisibleOutputMs: 2_000 }), + ])).toBe(12_000); }); it('excludes controller setup rows while requiring every actual model call to be timed', () => { const setup = round({ index: -1 }); - const timed = round({ streamDurationMs: 5_000, firstVisibleOutputMs: 1_000 }); - expect(getTurnOutputDurationMs([setup, timed])).toBe(4_000); + const timed = round({ durationMs: 5_000, streamDurationMs: 5_000, firstVisibleOutputMs: 1_000 }); + expect(getTurnOutputDurationMs([setup, timed])).toBe(5_000); expect(getTurnOutputDurationMs([setup])).toBeUndefined(); expect(getTurnOutputDurationMs([setup, round({}), timed])).toBeUndefined(); }); - it('accepts zero first-output latency without substituting a later mark', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 2_000, firstChunkMs: 0, firstVisibleOutputMs: 0 })])).toBe(2_000); + it('accepts request duration without requiring a first-output mark', () => { + expect(getTurnOutputDurationMs([round({ durationMs: 2_000, firstChunkMs: 0 })])).toBe(2_000); }); it('does not use accepted-attempt timing for usage that also includes retries', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 2_000, firstVisibleOutputMs: 500, attemptCount: 2 })])).toBeUndefined(); + expect(getTurnOutputDurationMs([round({ durationMs: 2_000, streamDurationMs: 2_000, firstVisibleOutputMs: 500, attemptCount: 2 })])).toBeUndefined(); }); - it.each([-1, NaN, Infinity])('rejects invalid effective-output time %s', firstVisibleOutputMs => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 2_000, firstVisibleOutputMs })])).toBeUndefined(); + it.each([0, -1, NaN, Infinity])('rejects invalid request duration %s', durationMs => { + expect(getTurnOutputDurationMs([round({ durationMs })])).toBeUndefined(); }); - it('never reports a negative or invented window', () => { - expect(getTurnOutputDurationMs([round({ streamDurationMs: 1_000, firstVisibleOutputMs: 4_000 })])).toBeUndefined(); - expect(getTurnOutputDurationMs([round({ streamDurationMs: 2_000, firstVisibleOutputMs: 2_000 })])).toBeUndefined(); + it('does not use a non-positive request duration', () => { + expect(getTurnOutputDurationMs([round({ durationMs: 0 })])).toBeUndefined(); }); it('rejects incomplete turn timing instead of dividing all tokens by partial time', () => { - expect(getTurnOutputDurationMs([round({}), round({ streamDurationMs: 6_000, firstVisibleOutputMs: 1_000 })])) + expect(getTurnOutputDurationMs([round({}), round({ durationMs: 6_000 })])) .toBeUndefined(); expect(getTurnOutputDurationMs([round({}), round({})])).toBeUndefined(); expect(getTurnOutputDurationMs([])).toBeUndefined(); diff --git a/src/web-ui/src/flow_chat/utils/turnUsageMetrics.ts b/src/web-ui/src/flow_chat/utils/turnUsageMetrics.ts index f5e656534f..cc6806c916 100644 --- a/src/web-ui/src/flow_chat/utils/turnUsageMetrics.ts +++ b/src/web-ui/src/flow_chat/utils/turnUsageMetrics.ts @@ -9,30 +9,25 @@ function isPositiveMs(value: unknown): value is number { } /** - * Round-level milliseconds spent actually receiving model output. + * Round-level milliseconds from model request start to stream completion. * - * Both marks use the host's stream-processing clock. The first upstream chunk - * can contain only metadata, so generation starts at the first effective output - * (text, thinking or a tool event), not `firstChunkMs`. Request-level TTFT also - * includes time before streaming starts and must not be subtracted here again. + * This intentionally includes TTFT. Providers can buffer a pseudo-stream and + * deliver a large block after a long idle period; measuring only from the first + * visible output would turn that wait into an implausibly high throughput. */ -function roundOutputDurationMs(round: ModelRound): number | undefined { - if (!isPositiveMs(round.streamDurationMs)) return undefined; - if (!isCount(round.firstVisibleOutputMs) || round.firstVisibleOutputMs >= round.streamDurationMs) { - return undefined; - } +function roundRequestDurationMs(round: ModelRound): number | undefined { + if (!isPositiveMs(round.durationMs)) return undefined; // Turn usage includes all attempts, but timing only covers the accepted one. if ((round.attemptCount ?? 1) > 1) return undefined; - return round.streamDurationMs - round.firstVisibleOutputMs; + return round.durationMs; } /** - * Milliseconds a turn spent streaming model output, summed over its rounds. + * Milliseconds a turn spent in model requests, summed over its rounds. * - * Turn wall time also covers tool execution, permission waits and retries, so - * dividing output tokens by it understates throughput by a wide margin. Returns - * undefined if any round lacks usable timing. Using partial timing with the - * whole turn's token count would overstate throughput; wall time is no fallback. + * Tool execution and permission waits between model calls are not model request + * time. Returns undefined if any model round lacks usable timing; partial timing + * would make the aggregate rate unreliable. */ export function getTurnOutputDurationMs(rounds?: readonly ModelRound[]): number | undefined { if (!rounds?.length) return undefined; @@ -40,7 +35,7 @@ export function getTurnOutputDurationMs(rounds?: readonly ModelRound[]): number for (const round of rounds) { // Negative indexes are controller setup/audit rows, not model calls. if (round.index < 0) continue; - const durationMs = roundOutputDurationMs(round); + const durationMs = roundRequestDurationMs(round); if (durationMs === undefined) return undefined; totalMs += durationMs; } @@ -58,8 +53,8 @@ export function getTurnUsageMetrics(usage?: TokenUsage, outputDurationMs?: numbe const cacheHitRate = isCount(usage?.cachedTokens) && isCount(usage?.inputTokens) && usage.inputTokens > 0 && usage.cachedTokens <= usage.inputTokens ? usage.cachedTokens / usage.inputTokens : null; - // `outputDurationMs` must be the streaming window from `getTurnOutputDurationMs`, - // never turn wall time: tool execution and waiting would deflate the rate. + // `outputDurationMs` is the sum of model request durations from + // `getTurnOutputDurationMs`, including TTFT but excluding tool execution. const rate = isCount(usage?.outputTokens) && isCount(outputDurationMs) && outputDurationMs > 0 ? usage.outputTokens / (outputDurationMs / 1000) : null; const outputRate = rate !== null && Number.isFinite(rate) ? rate : null; diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index f49524c0dd..1da38432c2 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -1836,7 +1836,7 @@ "ttft": "Time to first token", "ttftValue": "TTFT {{value}}", "ttftBasis": "Request start to the first text, thinking or tool output of the first model call in this turn. For retried calls, this measures the accepted attempt.", - "rateBasis": "Output tokens divided by the sum of each model call’s time from first effective output to end of stream, excluding TTFT and tool execution; speed levels change at 15, 40 and 80 tokens/s", + "rateBasis": "Output tokens divided by the sum of each model call’s request-to-completion time, including TTFT and excluding tool execution; speed levels change at 15, 40 and 80 tokens/s", "slow": "Slow", "normal": "Normal", "fast": "Fast", diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index a28fdea016..9faff75f3d 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -1836,7 +1836,7 @@ "ttft": "首 Token 延迟", "ttftValue": "TTFT {{value}}", "ttftBasis": "本轮首次模型调用从发送请求到收到首个文字、思考或工具输出的耗时。发生重试时,显示最终采用的请求耗时。", - "rateBasis": "输出 Token 除以各次模型调用从首个有效输出到流结束的时长之和,不含 TTFT 和工具执行;档位分界为 15、40、80 Token/秒", + "rateBasis": "输出 Token 除以各次模型调用从请求开始到完成的时长之和,包含 TTFT,不含工具执行;档位分界为 15、40、80 Token/秒", "slow": "慢", "normal": "一般", "fast": "快",