refactor(web): project usage and snapshot request context
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md
|
||||
README.md: b74127ffe11df40fcad0c97e2fc6896ec79ad9d1
|
||||
README.zh.md: f6dfc3ca61ea80758c9f64ca98f034b0832ee89e
|
||||
README.md: c60a38ec26d4bca15ce23e51dbaedf3ef36022e4
|
||||
README.zh.md: 65c5554a78960fc4f86a6a370772c95429c648c4
|
||||
|
||||
@@ -20,7 +20,7 @@ Per-session UI state for selection and the active view lives in the declared cha
|
||||
|
||||
The composer bar declares session-scoped single seats for `'conversation.input.plan'` (right of the local access-mode control) and `'conversation.input.model'` (immediately before the pending indicator and send/stop button), plus list slots for overlay, dock, left, and right input extensions. Feature packages own each control and its state; ui-conversation supplies placement, the `locked` owner prop, and the standard slot shares. While the `plan` projection's effective target is plan mode, InputBar swaps its textarea placeholder to the plan-task wording (a host-folded value read through the standard-kit `useProjection`; owner-supplied placeholders win). The resident no-session shell uses `DisabledInputBar` and therefore dispatches no session-scoped control seats.
|
||||
|
||||
The chat stats line reads durable token counters/current pressure from `ConversationSnapshot.metrics` and joins them only at presentation with the separate connection-local `modelRequestContextWindow`; visible nodes supply only the existing turn/step counts. It renders uncached input, output, and cache reads as separate compact values, computes cache hit as `cacheRead / (uncachedInput + cacheRead)` without cache writes, and shows context occupancy only after the current mux connection observes a model request with capacity. Before that request, after reconnect/restore/new subscription, or after a request without capacity, the percentage is omitted and context is labeled unknown rather than queried ahead or reconstructed from history.
|
||||
The chat stats line reads full-log billing from the generic `tokenUsage` projection and joins it only at presentation with the connection-local atomic `ConversationSnapshot.modelRequest`; visible nodes supply only the existing turn/step counts. It renders uncached input, output, and cache reads as separate compact values, computes cache hit as `cacheRead / (uncachedInput + cacheRead)` without cache writes, and shows context occupancy only when the same observed request snapshot contains both `contextTokens` and `contextWindow`. Before that request, after reconnect/restore/new subscription, or after a request missing either field, context is labeled unknown rather than queried from the selected model or reconstructed from history. The existing inline stats row remains the sole context UI; the model selector has no circle or accessory.
|
||||
|
||||
`src/client/` is organized for the future package split: `contract/` is the sole inter-domain shared face (`slots.ts` slot declarations + composed slot props including the tool-row contract, `views.ts` shared primitives, `tool-call-model.ts`); the `skeleton/`, `chat/`, and `toolviews/` (sample registrants) domain directories import contract files and never each other; `apply.ts` is the only assembly point allowed to import all three domains. The `/client` export surface is the contract only — `apply`/`inject`, the two service classes, and the `contract/` type families; implementation components (skeleton, chat rows) and the store factory stay internal and reach the page exclusively through apply's slot registrations (tests take them via the `./src/*` subpath).
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ todo 两个面就是在该形状上的两个注册项,都是普通注册方插
|
||||
|
||||
输入栏为 `'conversation.input.plan'`(位于本地 access 模式控件右侧)和 `'conversation.input.model'`(渲染在 pending 指示器与发送/停止按钮之前)声明会话作用域的单实例 seat,并为 overlay、dock、left 和 right 输入扩展声明列表 slot。各功能包拥有相应控件及其状态;ui-conversation 提供放置位置、`locked` owner prop 和标准 slot share。当 `plan` 投影的有效目标为 plan mode 时,InputBar 将文本框 placeholder 切换为 plan 任务措辞(经标准套件 `useProjection` 读取的 host 折叠值;owner 提供的 placeholder 优先)。常驻无会话壳使用 `DisabledInputBar`,因此不会分发任何会话作用域的控件 seat。
|
||||
|
||||
聊天统计行从 `ConversationSnapshot.metrics` 读取持久的 token 计数/当前压力,并且只在展示时把它们与独立的连接本地 `modelRequestContextWindow` 结合;可见节点仅提供既有的轮次和步骤计数。它以相互独立的紧凑值显示未缓存输入、输出与缓存读取,通过 `cacheRead / (uncachedInput + cacheRead)` 计算缓存命中率而不计入缓存写入,并且只有当前 mux 连接观察到带容量的模型请求后才显示上下文占用率。在该请求之前、重连/恢复/新订阅之后,或在请求不带容量之后,系统都会省略百分比,并把上下文标为「未知」,而不会提前查询或根据历史记录重建。
|
||||
聊天统计行从通用 `tokenUsage` 投影读取完整日志计费用量,并且只在展示时把它与连接本地的原子快照 `ConversationSnapshot.modelRequest` 结合;可见节点仅提供既有的轮次和步骤计数。它以相互独立的紧凑值显示未缓存输入、输出与缓存读取,通过 `cacheRead / (uncachedInput + cacheRead)` 计算缓存命中率而不计入缓存写入,并且只有同一份已观测请求快照同时包含 `contextTokens` 与 `contextWindow` 时才显示上下文占用率。在该请求之前、重连/恢复/新订阅之后,或在请求缺少任一字段之后,系统都会把上下文标为「未知」,而不会从所选模型查询或根据历史记录重建。现有的行内统计行仍是唯一的上下文 UI;模型选择器不增加圆环或附属控件。
|
||||
|
||||
`src/client/` 按未来的包拆分组织:`contract/` 是唯一的跨领域共享表层(`slots.ts` slot 声明 + 组合后的 slot props,包括工具行契约、`views.ts` 共享原语、`tool-call-model.ts`);`skeleton/`、`chat/` 和 `toolviews/`(示例注册方)领域目录只导入 contract 文件,彼此绝不导入;`apply.ts` 是唯一允许导入全部三个领域的组装点。`/client` 导出表层只包含契约:`apply`/`inject`、两个服务类和 `contract/` 类型家族;实现组件(骨架、聊天行)与 store factory 保持内部状态,只能通过 apply 的 slot 注册到达页面(测试通过 `./src/*` 子路径获取它们)。
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
"@deepseek-ai/dsh-client-ui-slash": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"@deepseek-ai/dsh-token-meter": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
@@ -52,6 +53,7 @@
|
||||
"@deepseek-ai/dsh-plan-mode": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:^",
|
||||
"@deepseek-ai/dsh-tool-todo": "workspace:^",
|
||||
"@deepseek-ai/dsh-token-meter": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-layout": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slash": "workspace:^",
|
||||
|
||||
@@ -221,7 +221,9 @@ function StreamingTail({ useSession, onGrow }: {
|
||||
* The chat view slot entry: pure component over the composed props (tool rows
|
||||
* render through the declared keyed hole's renderSlot share).
|
||||
*/
|
||||
export function ChatView({ useSession, useSessions, useStore, renderSlot, sessionId, openFile, loadOlder }: ChatViewSlotProps) {
|
||||
export function ChatView({
|
||||
useProjection, useSession, useSessions, useStore, renderSlot, sessionId, openFile, loadOlder,
|
||||
}: ChatViewSlotProps) {
|
||||
const nodes = useSession(s => s.nodes)
|
||||
// Workspace root off the session list row: path summaries display relative to it.
|
||||
const cwd = useSessions(s => s.byId[sessionId]?.cwd)
|
||||
@@ -381,7 +383,7 @@ export function ChatView({ useSession, useSessions, useStore, renderSlot, sessio
|
||||
{running && <TurnDots />}
|
||||
</div>
|
||||
</div>
|
||||
<StatsLine useSession={useSession} />
|
||||
<StatsLine useSession={useSession} useProjection={useProjection} />
|
||||
{!atBottom && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// Settled-node identity prevents stream-delta updates from rerendering this row.
|
||||
|
||||
import { memo, useMemo } from 'react'
|
||||
import type { ConversationSnapshot } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type {
|
||||
ConversationSnapshot, UseProjection,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ModelRequestTelemetry } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { TokenUsageProjection } from '@deepseek-ai/dsh-token-meter/client'
|
||||
import css from './StatsLine.module.css'
|
||||
|
||||
type SessionMetrics = NonNullable<ConversationSnapshot['metrics']>
|
||||
|
||||
interface VisibleCounts {
|
||||
turns: number
|
||||
steps: number
|
||||
@@ -44,59 +46,59 @@ export function formatMetricTokens(value: number): string {
|
||||
|
||||
/**
|
||||
* Existing Web cache-hit formula over disjoint uncached and cache-read input.
|
||||
* @param metrics - Host-owned durable usage.
|
||||
* @param usage - full-log token usage projection.
|
||||
* @returns rounded integer percent, or null when no input was billed.
|
||||
*/
|
||||
export function cacheHitPercent(metrics: SessionMetrics): number | null {
|
||||
const denominator = metrics.uncachedInputTokens + metrics.cacheReadTokens
|
||||
export function cacheHitPercent(usage: TokenUsageProjection): number | null {
|
||||
const denominator = usage.uncachedInputTokens + usage.cacheReadTokens
|
||||
return denominator === 0
|
||||
? null
|
||||
: Math.round(metrics.cacheReadTokens / denominator * 100)
|
||||
: Math.round(usage.cacheReadTokens / denominator * 100)
|
||||
}
|
||||
|
||||
/**
|
||||
* Current context occupancy using the TUI's integer rounding and upper clamp.
|
||||
* @param metrics - Host-owned durable pressure.
|
||||
* @param contextWindow - capacity from the latest request observed on this mux generation.
|
||||
* @param request - one atomic request snapshot observed on this mux generation.
|
||||
* @returns occupancy percent, or null when either input is unavailable.
|
||||
*/
|
||||
export function contextPercent(metrics: SessionMetrics, contextWindow: number | undefined): number | null {
|
||||
if (metrics.contextTokens === undefined || contextWindow === undefined) return null
|
||||
return Math.min(100, Math.round(metrics.contextTokens / contextWindow * 100))
|
||||
export function contextPercent(request: ModelRequestTelemetry | null): number | null {
|
||||
if (request?.contextTokens === undefined || request.contextWindow === undefined) return null
|
||||
return Math.min(100, Math.round(request.contextTokens / request.contextWindow * 100))
|
||||
}
|
||||
|
||||
/** Props: the conversation-snapshot selector hook (handed down by ChatView). */
|
||||
export interface StatsLineProps { useSession: SnapshotSelectorHook<ConversationSnapshot> }
|
||||
/** Props: standard session hooks handed down by ChatView. */
|
||||
export interface StatsLineProps {
|
||||
useSession: SnapshotSelectorHook<ConversationSnapshot>
|
||||
useProjection: UseProjection
|
||||
}
|
||||
|
||||
export const StatsLine = memo(function StatsLine({ useSession }: StatsLineProps) {
|
||||
export const StatsLine = memo(function StatsLine({ useSession, useProjection }: StatsLineProps) {
|
||||
const nodes = useSession(s => s.nodes)
|
||||
const metrics = useSession(s => s.metrics)
|
||||
const contextWindow = useSession(s => s.modelRequestContextWindow)
|
||||
const modelRequest = useSession(s => s.modelRequest)
|
||||
const usage = useProjection('tokenUsage')
|
||||
const counts = useMemo(() => deriveVisibleCounts(nodes), [nodes])
|
||||
if (counts.steps === 0 && (
|
||||
metrics === null
|
||||
|| (
|
||||
metrics.uncachedInputTokens === 0
|
||||
&& metrics.outputTokens === 0
|
||||
&& metrics.cacheReadTokens === 0
|
||||
&& (metrics.contextTokens ?? 0) === 0
|
||||
)
|
||||
)) return null
|
||||
const hasUsage = usage !== undefined && (
|
||||
usage.uncachedInputTokens !== 0
|
||||
|| usage.outputTokens !== 0
|
||||
|| usage.cacheReadTokens !== 0
|
||||
|| usage.cacheWriteTokens !== 0
|
||||
)
|
||||
const context = contextPercent(modelRequest)
|
||||
if (counts.steps === 0 && !hasUsage && context === null) return null
|
||||
|
||||
const parts: string[] = []
|
||||
if (metrics === null) {
|
||||
if (usage === undefined) {
|
||||
parts.push('usage unknown')
|
||||
parts.push('context unknown')
|
||||
} else {
|
||||
parts.push(`${formatMetricTokens(metrics.uncachedInputTokens)} uncached input`)
|
||||
parts.push(`${formatMetricTokens(metrics.outputTokens)} output`)
|
||||
parts.push(`${formatMetricTokens(metrics.cacheReadTokens)} cache read`)
|
||||
const cacheHit = cacheHitPercent(metrics)
|
||||
parts.push(`${formatMetricTokens(usage.uncachedInputTokens)} uncached input`)
|
||||
parts.push(`${formatMetricTokens(usage.outputTokens)} output`)
|
||||
parts.push(`${formatMetricTokens(usage.cacheReadTokens)} cache read`)
|
||||
const cacheHit = cacheHitPercent(usage)
|
||||
if (cacheHit !== null) parts.push(`cache hit ${cacheHit}%`)
|
||||
const context = contextPercent(metrics, contextWindow)
|
||||
parts.push(context === null
|
||||
? 'context unknown'
|
||||
: `context ${context}% of ${formatMetricTokens(contextWindow as number)}`)
|
||||
}
|
||||
parts.push(context === null || modelRequest?.contextWindow === undefined
|
||||
? 'context unknown'
|
||||
: `context ${context}% of ${formatMetricTokens(modelRequest.contextWindow)}`)
|
||||
parts.push(`${counts.turns} turns`)
|
||||
parts.push(`${counts.steps} steps`)
|
||||
return <div className={css.root}>{parts.join(' · ')}</div>
|
||||
|
||||
@@ -120,18 +120,20 @@ describe('small branch tails', () => {
|
||||
it('StatsLine omits the cache-hit segment when no input accounting exists at all', () => {
|
||||
const snap = {
|
||||
nodes: [{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [], usage: { outputTokens: 10 } }],
|
||||
metrics: {
|
||||
logRevision: 2,
|
||||
projectionRevision: 0,
|
||||
uncachedInputTokens: 0,
|
||||
outputTokens: 10,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 5_000,
|
||||
},
|
||||
modelRequest: null,
|
||||
}
|
||||
const usage = {
|
||||
uncachedInputTokens: 0,
|
||||
outputTokens: 10,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 5_000,
|
||||
}
|
||||
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
|
||||
const view = render(
|
||||
<StatsLine useSession={bindSnapshotSelector(source) as unknown as StatsLineProps['useSession']} />,
|
||||
<StatsLine
|
||||
useSession={bindSnapshotSelector(source) as unknown as StatsLineProps['useSession']}
|
||||
useProjection={(() => usage)}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText(
|
||||
'0 uncached input · 10 output · 0 cache read · context unknown · 1 turns · 1 steps',
|
||||
|
||||
@@ -58,7 +58,7 @@ function snapshotWith(
|
||||
sessionId: SID, nodes, foldDegraded: false, partial: null, runningCalls, codeDispatches,
|
||||
pending: [], queue: [], running: runningCalls.length > 0, composerPhase: 'active', removed: false,
|
||||
openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// @vitest-environment jsdom
|
||||
// StatsLine (rendered inside the chat view body): durable metrics presentation + the RFC
|
||||
// StatsLine (rendered inside the chat view body): projection presentation + the RFC
|
||||
// hard acceptance — zero renders during streaming. Bash sample row: the
|
||||
// canonical sub-agent differential decided INSIDE the component off the
|
||||
// standard useSessions kit (no registry predicates — tool ring dissolved).
|
||||
@@ -7,8 +7,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import type {
|
||||
AssistantMessageNode, ConversationSnapshot, SessionId, SessionListState, ToolResultNode,
|
||||
AssistantMessageNode, ConversationSnapshot, SessionId, SessionListState, ToolResultNode, UseProjection,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { TokenUsageProjection } from '@deepseek-ai/dsh-token-meter/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
@@ -31,7 +32,7 @@ function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +54,27 @@ function makeSource(init?: Partial<ConversationSnapshot>) {
|
||||
}
|
||||
}
|
||||
|
||||
function makeProjection(initial?: TokenUsageProjection) {
|
||||
let value = initial
|
||||
const subs = new Set<() => void>()
|
||||
const useValue = bindSnapshotSelector({
|
||||
getSnapshot: () => value,
|
||||
subscribe: (fn: () => void) => {
|
||||
subs.add(fn)
|
||||
return () => subs.delete(fn)
|
||||
},
|
||||
})
|
||||
return {
|
||||
set(next: TokenUsageProjection | undefined) {
|
||||
value = next
|
||||
for (const fn of [...subs]) fn()
|
||||
},
|
||||
useProjection: ((_key: 'tokenUsage', selector?: (usage: TokenUsageProjection | undefined) => unknown,
|
||||
eq?: (left: unknown, right: unknown) => boolean) =>
|
||||
useValue(selector ?? (usage => usage), eq)) as UseProjection,
|
||||
}
|
||||
}
|
||||
|
||||
describe('stats derivation', () => {
|
||||
it('counts visible turns and steps without reading node usage', () => {
|
||||
const stats = deriveVisibleCounts([
|
||||
@@ -74,20 +96,23 @@ describe('stats derivation', () => {
|
||||
})
|
||||
|
||||
it('keeps the cache formula disjoint from cache writes and rounds/clamps context like the TUI', () => {
|
||||
const durable = {
|
||||
logRevision: 20,
|
||||
projectionRevision: 2,
|
||||
const usage = {
|
||||
uncachedInputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 900,
|
||||
cacheWriteTokens: 50_000,
|
||||
contextTokens: 34_500,
|
||||
}
|
||||
expect(cacheHitPercent(durable)).toBe(90)
|
||||
expect(contextPercent(durable, 100_000)).toBe(35)
|
||||
expect(contextPercent({ ...durable, contextTokens: 200_000 }, 100_000)).toBe(100)
|
||||
expect(contextPercent(durable, undefined)).toBeNull()
|
||||
expect(cacheHitPercent({ ...durable, uncachedInputTokens: 0, cacheReadTokens: 0 })).toBeNull()
|
||||
const request = {
|
||||
turn: 1, step: 1, provider: 'p', model: 'm',
|
||||
contextTokens: 34_500, contextWindow: 100_000,
|
||||
}
|
||||
expect(cacheHitPercent(usage)).toBe(90)
|
||||
expect(contextPercent(request)).toBe(35)
|
||||
expect(contextPercent({ ...request, contextTokens: 200_000 })).toBe(100)
|
||||
expect(contextPercent({
|
||||
turn: 1, step: 1, provider: 'p', model: 'm', contextTokens: 34_500,
|
||||
})).toBeNull()
|
||||
expect(cacheHitPercent({ ...usage, uncachedInputTokens: 0, cacheReadTokens: 0 })).toBeNull()
|
||||
})
|
||||
|
||||
it('formats large values compactly in the existing en-US style', () => {
|
||||
@@ -98,25 +123,28 @@ describe('stats derivation', () => {
|
||||
})
|
||||
|
||||
describe('StatsLine', () => {
|
||||
function props(source: { getSnapshot(): ConversationSnapshot; subscribe(fn: () => void): () => void }): StatsLineProps {
|
||||
return { useSession: bindSnapshotSelector(source) }
|
||||
function props(
|
||||
source: { getSnapshot(): ConversationSnapshot; subscribe(fn: () => void): () => void },
|
||||
projection = makeProjection(),
|
||||
): StatsLineProps {
|
||||
return { useSession: bindSnapshotSelector(source), useProjection: projection.useProjection }
|
||||
}
|
||||
|
||||
it('renders separate durable counters, cache hit, context occupancy, and visible counts', () => {
|
||||
const { source } = makeSource({
|
||||
nodes: [assistant(1, 1, { inputTokens: 10, outputTokens: 5, cacheReadTokens: 90 })],
|
||||
metrics: {
|
||||
logRevision: 30,
|
||||
projectionRevision: 4,
|
||||
uncachedInputTokens: 120_237,
|
||||
outputTokens: 13_881,
|
||||
cacheReadTokens: 2_172_544,
|
||||
cacheWriteTokens: 99_999,
|
||||
contextTokens: 89_600,
|
||||
modelRequest: {
|
||||
turn: 1, step: 1, provider: 'p', model: 'm',
|
||||
contextTokens: 89_600, contextWindow: 256_000,
|
||||
},
|
||||
modelRequestContextWindow: 256_000,
|
||||
})
|
||||
const view = render(<StatsLine {...props(source)} />)
|
||||
const projection = makeProjection({
|
||||
uncachedInputTokens: 120_237,
|
||||
outputTokens: 13_881,
|
||||
cacheReadTokens: 2_172_544,
|
||||
cacheWriteTokens: 99_999,
|
||||
})
|
||||
const view = render(<StatsLine {...props(source, projection)} />)
|
||||
expect(view.getByText(
|
||||
'120.2k uncached input · 13.9k output · 2.2m cache read · cache hit 95% · context 35% of 256k · 1 turns · 1 steps',
|
||||
)).toBeTruthy()
|
||||
@@ -125,68 +153,80 @@ describe('StatsLine', () => {
|
||||
expect(emptyView.container.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('renders durable counters without a percentage before live capacity is observed', () => {
|
||||
it('renders durable counters without a percentage before a complete request snapshot is observed', () => {
|
||||
const { source } = makeSource({
|
||||
nodes: [assistant(1, 1)],
|
||||
metrics: {
|
||||
logRevision: 4,
|
||||
projectionRevision: 1,
|
||||
uncachedInputTokens: 120,
|
||||
outputTokens: 20,
|
||||
cacheReadTokens: 30,
|
||||
cacheWriteTokens: 10,
|
||||
modelRequest: {
|
||||
turn: 1, step: 1, provider: 'p', model: 'm',
|
||||
contextTokens: 8_000,
|
||||
},
|
||||
})
|
||||
const view = render(<StatsLine {...props(source)} />)
|
||||
const projection = makeProjection({
|
||||
uncachedInputTokens: 120,
|
||||
outputTokens: 20,
|
||||
cacheReadTokens: 30,
|
||||
cacheWriteTokens: 10,
|
||||
})
|
||||
const view = render(<StatsLine {...props(source, projection)} />)
|
||||
expect(view.getByText(
|
||||
'120 uncached input · 20 output · 30 cache read · cache hit 20% · context unknown · 1 turns · 1 steps',
|
||||
)).toBeTruthy()
|
||||
expect(view.container.textContent).not.toContain('% of')
|
||||
})
|
||||
|
||||
it('renders honest unknowns when the host projection is missing', () => {
|
||||
it('renders honest unknowns when the tokenUsage key and request snapshot are missing', () => {
|
||||
const { source } = makeSource({ nodes: [assistant(1, 1)] })
|
||||
const view = render(<StatsLine {...props(source)} />)
|
||||
expect(view.getByText('usage unknown · context unknown · 1 turns · 1 steps')).toBeTruthy()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ uncachedInputTokens: 1, outputTokens: 0, cacheReadTokens: 0, contextTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 1, cacheReadTokens: 0, contextTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 1, contextTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 0, contextTokens: 1 },
|
||||
])('keeps a metrics-only row visible for each nonzero projection bucket', (nonzero) => {
|
||||
const { source } = makeSource({
|
||||
metrics: {
|
||||
logRevision: 1,
|
||||
projectionRevision: 0,
|
||||
cacheWriteTokens: 0,
|
||||
...nonzero,
|
||||
{ uncachedInputTokens: 1, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 1, cacheWriteTokens: 0 },
|
||||
{ uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 1 },
|
||||
])('keeps a usage-only row visible for each nonzero projection bucket', (usage) => {
|
||||
const { source } = makeSource()
|
||||
const view = render(<StatsLine {...props(source, makeProjection(usage))} />)
|
||||
expect(view.container.textContent).toContain('0 turns · 0 steps')
|
||||
})
|
||||
|
||||
it('keeps a context-only row visible and hides an all-zero empty session', () => {
|
||||
const context = makeSource({
|
||||
modelRequest: {
|
||||
turn: 1, step: 1, provider: 'p', model: 'm',
|
||||
contextTokens: 1, contextWindow: 10,
|
||||
},
|
||||
})
|
||||
const view = render(<StatsLine {...props(source)} />)
|
||||
expect(view.container.textContent).toContain('0 turns · 0 steps')
|
||||
expect(render(
|
||||
<StatsLine {...props(context.source, makeProjection({
|
||||
uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0,
|
||||
}))} />,
|
||||
).container.textContent).toContain('context 10% of 10')
|
||||
const empty = makeSource()
|
||||
expect(render(
|
||||
<StatsLine {...props(empty.source, makeProjection({
|
||||
uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0,
|
||||
}))} />,
|
||||
).container.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('renders ZERO times during streaming chunk frames (RFC hard acceptance)', () => {
|
||||
const { set, source } = makeSource({
|
||||
nodes: [assistant(1, 1)],
|
||||
metrics: {
|
||||
logRevision: 4,
|
||||
projectionRevision: 0,
|
||||
uncachedInputTokens: 1,
|
||||
outputTokens: 1,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
},
|
||||
})
|
||||
const projection = makeProjection({
|
||||
uncachedInputTokens: 1,
|
||||
outputTokens: 1,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
})
|
||||
let renders = 0
|
||||
function Counting(p: StatsLineProps) {
|
||||
renders += 1
|
||||
return <StatsLine {...p} />
|
||||
}
|
||||
render(<Counting {...props(source)} />)
|
||||
render(<Counting {...props(source, projection)} />)
|
||||
const before = renders
|
||||
// Chunk frames swap partial only; nodes keeps its reference (object-layer contract).
|
||||
act(() => { set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'a' }] } }) })
|
||||
@@ -194,6 +234,28 @@ describe('StatsLine', () => {
|
||||
act(() => { set({ running: true }) })
|
||||
expect(renders).toBe(before)
|
||||
})
|
||||
|
||||
it('updates for a new usage projection or atomic request snapshot', () => {
|
||||
const { set, source } = makeSource({ nodes: [assistant(1, 1)] })
|
||||
const projection = makeProjection()
|
||||
const view = render(<StatsLine {...props(source, projection)} />)
|
||||
expect(view.container.textContent).toContain('usage unknown · context unknown')
|
||||
act(() => {
|
||||
projection.set({
|
||||
uncachedInputTokens: 7, outputTokens: 2, cacheReadTokens: 1, cacheWriteTokens: 0,
|
||||
})
|
||||
})
|
||||
expect(view.container.textContent).toContain('7 uncached input · 2 output · 1 cache read')
|
||||
act(() => {
|
||||
set({
|
||||
modelRequest: {
|
||||
turn: 1, step: 2, provider: 'p', model: 'm',
|
||||
contextTokens: 75, contextWindow: 100,
|
||||
},
|
||||
})
|
||||
})
|
||||
expect(view.container.textContent).toContain('context 75% of 100')
|
||||
})
|
||||
})
|
||||
|
||||
describe('bash sample row', () => {
|
||||
|
||||
@@ -31,7 +31,7 @@ function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ describe('render branch tails', () => {
|
||||
expect(view.container.querySelector('[data-state="ok"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('StatsLine takes durable counters from metrics while keeping visible node counts', () => {
|
||||
it('StatsLine takes durable counters from tokenUsage while keeping visible node counts', () => {
|
||||
const snap = {
|
||||
nodes: [
|
||||
{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [] },
|
||||
@@ -44,18 +44,20 @@ describe('render branch tails', () => {
|
||||
// outputTokens absent: the tokens sum's ?? 0 arm for output.
|
||||
{ kind: 'assistant', seq: 3, turn: 2, step: 1, blocks: [], usage: { inputTokens: 5 } },
|
||||
],
|
||||
metrics: {
|
||||
logRevision: 9,
|
||||
projectionRevision: 1,
|
||||
uncachedInputTokens: 9,
|
||||
outputTokens: 6,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
},
|
||||
modelRequest: null,
|
||||
}
|
||||
const usage = {
|
||||
uncachedInputTokens: 9,
|
||||
outputTokens: 6,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
}
|
||||
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
|
||||
const view = render(
|
||||
<StatsLine useSession={bindSnapshotSelector(source) as unknown as UseSession<ConversationSnapshot>} />,
|
||||
<StatsLine
|
||||
useSession={bindSnapshotSelector(source) as unknown as UseSession<ConversationSnapshot>}
|
||||
useProjection={(() => usage)}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText(
|
||||
'9 uncached input · 6 output · 0 cache read · cache hit 0% · context unknown · 2 turns · 3 steps',
|
||||
|
||||
@@ -23,7 +23,7 @@ function snapshotOf(overrides: Partial<ConversationSnapshot> = {}): Conversation
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
|
||||
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
|
||||
promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: over?.running ?? false, composerPhase: 'active',
|
||||
removed: over?.disabled ?? false, openState: 'open', openError: null, hasMore: false,
|
||||
loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
})
|
||||
const props: InputBarProps = {
|
||||
sessionId: SID,
|
||||
|
||||
@@ -112,7 +112,7 @@ async function scopedBench(register?: (slash: SlashService) => void) {
|
||||
sessionId, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
|
||||
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
|
||||
promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
})
|
||||
const barProps: InputBarProps = {
|
||||
sessionId,
|
||||
|
||||
@@ -20,7 +20,7 @@ function snapshotWith(queue: QueuedMessage[]): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue, running: true, composerPhase: 'active', removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ function conversationSnapshot(overrides: Partial<ConversationSnapshot> = {}): Co
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
|
||||
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
|
||||
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
|
||||
promptError: null, blank: false, lastAgentError: null, metrics: null,
|
||||
promptError: null, blank: false, lastAgentError: null, modelRequest: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,9 @@
|
||||
{
|
||||
"path": "../../session-projection/session-projection"
|
||||
},
|
||||
{
|
||||
"path": "../../llm/token-meter"
|
||||
},
|
||||
{
|
||||
"path": "../../plan/plan-mode"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user