refactor(web): project usage and snapshot request context

This commit is contained in:
Hypatia May
2026-07-29 15:27:59 +08:00
parent e37cb23336
commit bf618dabf9
78 changed files with 748 additions and 934 deletions

View File

@@ -12,7 +12,7 @@ export type {
WorkspaceApi, WorkspaceId, WorkspaceView,
CommandsApi, CommandDescriptor, SkillsApi, SkillEntry,
ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning,
ModelReasoningEffort, ModelTarget, SessionMetrics, SessionModels, SessionProjectionsBlock,
ModelReasoningEffort, ModelRequestTelemetry, ModelTarget, SessionModels, SessionProjectionsBlock,
GoalsApi, GoalRef,
} from '@deepseek-ai/dsh-host-apiproxy/api'
export type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools/presentation'

View File

@@ -15,6 +15,7 @@ import type {
AssistantMessage,
ContentBlock,
MessageSource,
TokenUsage,
ToolResultMessage,
UserMessage,
} from '@deepseek-ai/dsh-llm'
@@ -103,6 +104,16 @@ function sid(id: string): SessionId {
return id as SessionId
}
/** Deterministic provider billing attached to fixture assistant messages. */
function fixtureUsage(turn: number, step: number): TokenUsage {
return {
inputTokens: 20 + turn % 5,
outputTokens: 8 + step,
cacheReadTokens: turn === 0 ? 0 : 80,
cacheWriteTokens: turn % 10 === 0 ? 4 : 0,
}
}
/** fx-alpha history script: 60 turns (~130+ messages -> 3 pages at PAGE_MESSAGES=50),
* mixing reasoning blocks / tool call+result / steering / context. */
function buildAlphaLog(): SessionEvent[] {
@@ -110,7 +121,17 @@ function buildAlphaLog(): SessionEvent[] {
let time = Date.now() - 3_600_000
const push = (e: Record<string, unknown>): number => {
const seq = events.length
events.push({ seq, time: (time += 800), ...e })
const data = e['data'] as Record<string, unknown> | undefined
const authored = e['type'] === 'assistant/message' && data !== undefined
? {
...e,
data: {
...data,
usage: fixtureUsage(data['turn'] as number, data['step'] as number),
},
}
: e
events.push({ seq, time: (time += 800), ...authored })
return seq
}
for (let turn = 0; turn < 60; turn++) {
@@ -369,6 +390,60 @@ function permissionSelectOf(
}
}
interface FixtureTokenUsageProjection {
uncachedInputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
}
/** Fixture parallel of token-meter's last-sample-replacing usage projection. */
function tokenUsageOf(log: readonly SessionEvent[]): FixtureTokenUsageProjection {
const totals: FixtureTokenUsageProjection = {
uncachedInputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
}
let last: {
turn: number
step: number
buckets: FixtureTokenUsageProjection
} | null = null
for (const event of log) {
const item = event as unknown as {
type: string
data: {
turn?: number
step?: number
usage?: TokenUsage
chunk?: { type?: string; usage?: TokenUsage }
}
}
const usage = item.type === 'assistant/chunk' && item.data.chunk?.type === 'usage'
? item.data.chunk.usage
: item.type === 'assistant/message'
? item.data.usage
: undefined
if (usage === undefined || item.data.turn === undefined || item.data.step === undefined) continue
const buckets: FixtureTokenUsageProjection = {
uncachedInputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
cacheReadTokens: usage.cacheReadTokens ?? 0,
cacheWriteTokens: usage.cacheWriteTokens ?? 0,
}
const previous = last?.turn === item.data.turn && last.step === item.data.step
? last.buckets
: undefined
totals.uncachedInputTokens += buckets.uncachedInputTokens - (previous?.uncachedInputTokens ?? 0)
totals.outputTokens += buckets.outputTokens - (previous?.outputTokens ?? 0)
totals.cacheReadTokens += buckets.cacheReadTokens - (previous?.cacheReadTokens ?? 0)
totals.cacheWriteTokens += buckets.cacheWriteTokens - (previous?.cacheWriteTokens ?? 0)
last = { turn: item.data.turn, step: item.data.step, buckets }
}
return totals
}
function projectionValuesOf(log: readonly SessionEvent[]): Record<string, unknown> {
const values: Record<string, unknown> = {}
const titleEvent = log.findLast(item => (item as { type: string }).type === 'session/title')
@@ -383,12 +458,28 @@ function projectionValuesOf(log: readonly SessionEvent[]): Record<string, unknow
values['plan'] = planViewOf(log)
// Always present (GoalService unit composed): null before create / after clear.
values['goal'] = backscanGoal(log)
// Always present (token-meter composed): full-log provider billing.
values['tokenUsage'] = tokenUsageOf(log)
return values
}
/** Host push-frame parallel: emit one session/projection frame per key the given event advanced. */
function projectionFramesOf(id: SessionId, log: readonly SessionEvent[], event: SessionEvent): Extract<MuxFrame, { type: 'session/projection' }>[] {
const type = (event as { type: string }).type
if (
(type === 'assistant/chunk'
&& (event as unknown as { data: { chunk?: { type?: string } } }).data.chunk?.type === 'usage')
|| (type === 'assistant/message'
&& (event as unknown as { data: { usage?: TokenUsage } }).data.usage !== undefined)
) {
return [{
type: 'session/projection',
sessionId: id,
key: 'tokenUsage',
value: tokenUsageOf(log),
seq: event.seq,
}]
}
if (type === 'session/title') {
const values = projectionValuesOf(log)
/* v8 ignore next -- the advancing title event is in the log, so the key is present. */
@@ -853,7 +944,16 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
replays.delete(id)
const done = pieces.slice(0, i).join('')
append(id, { type: 'assistant/chunk', data: { turn, step, chunk: { type: 'block-end', index: 0, block: { type: 'text', text: done } } } })
append(id, { type: 'assistant/message', surfaceOp: 'append', data: { turn, step, message: assistantMessage(text(aborted ? `${done}(已中断)` : done)) } })
append(id, {
type: 'assistant/message',
surfaceOp: 'append',
data: {
turn,
step,
message: assistantMessage(text(aborted ? `${done}(已中断)` : done)),
usage: fixtureUsage(turn, step),
},
})
append(id, { type: 'step/end', data: { turn, step } })
append(id, { type: 'turn/end', data: { turn, reason: { kind: aborted ? 'cancelled' : 'completed' } } })
setRunning(id, false)
@@ -1036,6 +1136,19 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
append(id, { type: 'plan/mode', data: { active: plan.wanted } })
}
append(id, { type: 'user/message', surfaceOp: 'append', data: userMessage(content) })
const target = modelTargets.get(id) ?? { provider: 'deepseek', model: 'deepseek-v4-flash' }
const usage = tokenUsageOf(logOf(id))
emitMux({
type: 'session/model-request',
sessionId: id,
turn,
step: 0,
provider: target.provider,
model: target.model,
contextTokens: usage.uncachedInputTokens + usage.outputTokens
+ usage.cacheReadTokens + usage.cacheWriteTokens,
contextWindow: 128_000,
})
startReply(
id,
turn,

View File

@@ -17,7 +17,7 @@ export type {
ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView,
CommandsApi, CommandDescriptor, SkillsApi, SkillEntry,
ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning,
ModelReasoningEffort, ModelTarget, SessionMetrics, SessionModels, SessionProjectionsBlock,
ModelReasoningEffort, ModelRequestTelemetry, ModelTarget, SessionModels, SessionProjectionsBlock,
RpcRequest, RpcResponse, RpcResult, RpcError, RpcErrorCode,
ClientRequest, ServerResponse, ServerRequest, ClientResponse, RpcMessage, RpcReceipt,
IApiClient, SessionId, SessionEvent, ContentBlock, StreamChunk,

View File

@@ -84,6 +84,12 @@ describe('createFixtureApi', () => {
},
plan: { active: false, pending: false },
goal: null,
tokenUsage: {
uncachedInputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
},
} },
})
})
@@ -188,6 +194,20 @@ describe('createFixtureApi', () => {
expect(types).toContain('assistant/chunk')
expect(types).toContain('assistant/message')
expect(types.at(-1)).toBe('turn/end')
expect(frames).toContainEqual({
type: 'session/model-request',
sessionId: id,
turn: 0,
step: 0,
provider: 'deepseek',
model: 'deepseek-v4-flash',
contextTokens: 0,
contextWindow: 128_000,
})
expect(frames.some(frame =>
frame.type === 'session/projection'
&& frame.key === 'tokenUsage'
&& (frame.value as { outputTokens?: number }).outputTokens === 8)).toBe(true)
const finalize = frames.find((f): f is Extract<MuxFrame, { type: 'session/event' }> => f.type === 'session/event' && f.event.type === 'assistant/message')
expect(JSON.stringify(finalize?.event.data)).toContain('(已中断)')
// Idle cancel: no replay in flight, must not explode; running flips false.
@@ -219,7 +239,7 @@ describe('createFixtureApi', () => {
const envelopes: RpcRequest<MuxFrame>[] = []
for await (const envelope of api.events.mux(req({}), abort.signal)) {
envelopes.push(envelope)
if (envelopes.length >= 8) abort.abort()
if (envelopes.length >= 9) abort.abort()
}
return envelopes
}
@@ -227,16 +247,18 @@ describe('createFixtureApi', () => {
const second = await openOnce()
expect(first[0]?.payload).toMatchObject({ type: 'session/subscribed', sessionId: 'fx-alpha' })
expect((first[0]?.payload as { lastSeq: number }).lastSeq).toBeGreaterThan(0)
// Projection baseline frames follow the subscribed frame (title + todos + permissions + plan + goal units).
// Projection baseline frames follow subscribed (domain units + token usage).
expect(first[1]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'title', value: 'Fixture 历史会话' })
expect(first[2]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'todos' })
expect(first[3]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'permissions' })
expect(first[4]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'plan', value: { active: false, pending: false } })
expect(first[5]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'goal', value: null })
expect(first[6]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' })
expect(second[6]?.rpcId).toBe(first[6]?.rpcId) // stable rpcId across replays (host replay semantics)
expect(first[7]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' })
expect(second[7]?.rpcId).toBe(first[7]?.rpcId)
expect(first[6]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'tokenUsage' })
expect(first[7]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' })
expect(second[7]?.rpcId).toBe(first[7]?.rpcId) // stable rpcId across replays (host replay semantics)
expect(first[8]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' })
expect(second[8]?.rpcId).toBe(first[8]?.rpcId)
expect(first.some(envelope => envelope.payload.type === 'session/model-request')).toBe(false)
})
it('steer with no replay in flight falls through to a fresh queued turn; non-text blocks stringify empty', async () => {

View File

@@ -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/runtime/README.md
README.md: 879730733f3d89c3962d8c54bcfd53795a980049
README.zh.md: 1b1d7f03d1f5f03c054dfeaa790a9f6f91e0dca2
README.md: ba9a7d455e8a193f23884411eb1928a10f21ddd0
README.zh.md: 873fefca48585efed010589917f2c63653b08e5b

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list/scope/history state; WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into both managers. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos` and `title`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. Durable `ConversationSnapshot.metrics` instead comes from the separate history-tail value and live `session/metrics` frames because point-in-time token-meter pressure can advance at the same durable log revision; only nondecreasing log and projection revisions are accepted. `ConversationSnapshot.modelRequestContextWindow` separately retains capacity from the latest `session/model-request` observed on the current mux connection. A later request replaces or clears that value, while `session/subscribed` clears both metrics ordering and capacity; reconnect, restore, and a new subscription therefore show no percentage until another request is observed. Missing metrics remain `null` rather than being inferred from the visible node window.
Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list/scope/history state; WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into both managers. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`, `title`, and `tokenUsage`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. `ConversationSnapshot.modelRequest` separately retains the complete latest `session/model-request` observed on the current mux connection. Each frame replaces the whole snapshot, so omitted numerator or capacity fields clear an earlier value. `SessionManager` buffers one pre-instantiation snapshot, while `session/subscribed`, disconnect, and removal clear resident and pending values; reconnect, restore, and a new subscription therefore show no context percentage until another request is observed. Model selection alone does not alter request telemetry.
## Workspace and Session lists

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象、列表/scope/history 状态;WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给两个 manager。客户端 Session 一律由 Host 出生(一次 `session.create` 同瞬产出 Session+Agent+cwd);客户端不持有任何实体化之前的会话状态——Agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时出生,随 prune 死亡。契约:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史尾页的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos` 与 `title`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。持久的 `ConversationSnapshot.metrics` 则来自独立的 history 尾页值与实时 `session/metrics` 帧,因为即时 token-meter 压力可以在相同持久日志修订号上继续变化;客户端只接受日志修订号与投影修订号均不减小的数据。`ConversationSnapshot.modelRequestContextWindow` 另行保留当前 mux 连接观察到的最新 `session/model-request` 容量。后续请求会替换或清除该值,`session/subscribed` 则同时清除指标顺序状态与容量;因此,重连、恢复和新订阅都不会显示百分比,直到观察到另一次请求。缺失的 metrics 保持为 `null`,而不是根据可见节点窗口推断。
客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象、列表/scope/history 状态;WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给两个 manager。客户端 Session 一律由 Host 出生(一次 `session.create` 同瞬产出 Session+Agent+cwd);客户端不持有任何实体化之前的会话状态——Agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时出生,随 prune 死亡。契约:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史尾页的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`、`title` 与 `tokenUsage`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。`ConversationSnapshot.modelRequest` 另行保留当前 mux 连接观察到的最新完整 `session/model-request`。每个帧都会替换整个快照,因此分子或容量字段一旦缺失,就会清除先前值。`SessionManager` 会缓冲一个实例化前快照;`session/subscribed`、断开连接和移除会话则会清除常驻值与待处理值;因此,重连、恢复和新订阅都不会显示上下文百分比,直到观察到另一次请求。仅选择模型不会改变请求观测数据。
## Workspace 与 Session 列表

View File

@@ -6,7 +6,7 @@
import type { CommandId } from '@deepseek-ai/dsh-commands/brand'
import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
import type {
RpcError, SessionId, SessionMetrics, ToolCallView, ToolResultView,
ModelRequestTelemetry, RpcError, SessionId, ToolCallView, ToolResultView,
} from '@deepseek-ai/dsh-client-connection/client'
import type { PendingInteraction } from './pending.ts'
@@ -267,16 +267,6 @@ export interface ConversationSnapshot {
*/
blank: boolean
lastAgentError: string | null
/**
* Host-owned cumulative usage/current pressure. Independent of `nodes`
* pagination; null until a tail response or live metrics frame supplies a
* current durable value.
*/
metrics: SessionMetrics | null
/**
* Capacity from the latest model-request attempt observed on this mux
* generation. Absent before the first such request, after a request whose
* registration exposes no capacity, and after `session/subscribed`.
*/
modelRequestContextWindow?: number
/** Latest atomic model-request snapshot on this mux generation. */
modelRequest: ModelRequestTelemetry | null
}

View File

@@ -2,7 +2,10 @@
// dispatch entry + list state, constructed and held by SessionsService (one per client runtime).
// List data never enters zustand; React connects via subscribe/getListSnapshot.
import type { IApiClient, HostFrame, MuxFrame, RpcError, RpcRequest, RpcResult, SessionId, SessionSummary, WorkspaceId } from '@deepseek-ai/dsh-client-connection/client'
import type {
HostFrame, IApiClient, ModelRequestTelemetry, MuxFrame, RpcError, RpcRequest,
RpcResult, SessionId, SessionSummary, WorkspaceId,
} from '@deepseek-ai/dsh-client-connection/client'
// Value import from the inline-safe wire layer (not the connection plugin):
// plugin-to-plugin value imports are a bundle purity error.
import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api'
@@ -58,11 +61,11 @@ export class SessionManager {
* frames are low-frequency; overflow drops oldest) and dropped on session-removed (audit S7). */
private readonly pendingBuffers = new Map<SessionId, RpcRequest<MuxFrame>[]>()
/**
* Latest model capacity observed for an uninstantiated session on the
* Latest request telemetry observed for an uninstantiated session on the
* current mux generation. Unlike durable history, this transient frame
* cannot be backfilled when get() lazily creates the Session.
*/
private readonly modelRequestContextWindows = new Map<SessionId, number>()
private readonly modelRequests = new Map<SessionId, ModelRequestTelemetry>()
/** Outstanding approval questions per session, keyed by approvalId (idempotent under mux-open
* replays of the same requested frame). Manager-owned rather than read off Session instances
* because the sidebar must light up for sessions never instantiated. Cleared per connection
@@ -171,7 +174,7 @@ export class SessionManager {
}
private createSession(sessionId: SessionId): Session {
const modelRequestContextWindow = this.modelRequestContextWindows.get(sessionId)
const modelRequest = this.modelRequests.get(sessionId)
return new Session(sessionId, this.api, {
// The sender's local first-send flip mirrors into the list row so the
// session surfaces (lists filter on blank) before any host frame lands.
@@ -179,7 +182,7 @@ export class SessionManager {
this.recordMutation({ kind: 'engaged', sessionId: engaged.sessionId })
},
projections: this.projectionStore(sessionId),
...(modelRequestContextWindow === undefined ? {} : { modelRequestContextWindow }),
...(modelRequest === undefined ? {} : { modelRequest }),
})
}
@@ -355,13 +358,13 @@ export class SessionManager {
return
}
if (frame.type === 'session/model-request') {
// Transient and non-replayable: retain the latest capacity until lazy
// instantiation. An absent value explicitly clears an earlier one.
if (frame.contextWindow === undefined) this.modelRequestContextWindows.delete(frame.sessionId)
else this.modelRequestContextWindows.set(frame.sessionId, frame.contextWindow)
// Transient and non-replayable: retain the whole latest request until
// lazy instantiation. Missing fields replace rather than inherit.
const { type: _type, sessionId, ...modelRequest } = frame
this.modelRequests.set(sessionId, modelRequest)
}
if (frame.type === 'session/subscribed') {
this.modelRequestContextWindows.delete(frame.sessionId)
this.modelRequests.delete(frame.sessionId)
// Rows past the host's durable baseline rode state a restart lost; drop
// them so last-wins cannot pin a phantom value over recomputed truth.
this.projectionStores.get(frame.sessionId)?.truncate(frame.lastSeq)
@@ -440,7 +443,7 @@ export class SessionManager {
this.recordMutation({ kind: 'remove', sessionId: frame.sessionId })
this.sessions.get(frame.sessionId)?.handleRemoved() // instance survives (resident-instance rule), only flagged in the snapshot
this.pendingBuffers.delete(frame.sessionId) // a removed session's buffered frames must not replay on a future instantiation
this.modelRequestContextWindows.delete(frame.sessionId) // connection-local request capacity dies with the Host session
this.modelRequests.delete(frame.sessionId) // connection-local request telemetry dies with the Host session
this.waitingApprovals.delete(frame.sessionId) // a removed session cannot wait on anyone
this.projectionStores.delete(frame.sessionId) // removed sessions drop their projection rows with the instance
return
@@ -481,7 +484,7 @@ export class SessionManager {
if (kept.length === 0) this.pendingBuffers.delete(sessionId)
else this.pendingBuffers.set(sessionId, kept)
}
this.modelRequestContextWindows.clear()
this.modelRequests.clear()
for (const session of this.sessions.values()) session.handleReconnecting()
}

View File

@@ -5,7 +5,7 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import type {
HistoryEntry, IApiClient, MuxFrame, RpcError, RpcId, RpcResult,
SessionId, SessionMetrics, ToolEventView,
ModelRequestTelemetry, SessionId, ToolEventView,
} from '@deepseek-ai/dsh-client-connection/client'
// Value import from the inline-safe wire layer (not the connection plugin):
// plugin-to-plugin value imports are a bundle purity error.
@@ -43,8 +43,8 @@ export interface SessionOptions {
* private store (bare object-layer construction).
*/
projections?: ProjectionValueStore
/** Model capacity already observed on this mux generation before lazy construction. */
modelRequestContextWindow?: number
/** Request telemetry already observed on this mux generation before lazy construction. */
modelRequest?: ModelRequestTelemetry
}
/** Queue-row preview cap: the dock renders one line, the full content never leaves the host mirror. */
@@ -110,10 +110,8 @@ export class Session implements SessionFace {
private queueCache: { rev: number; value: QueuedMessage[] } | null = null
private frozenRev = 0
private nodesCache: { folded: readonly ConversationNode[]; frozenRev: number; value: readonly ConversationNode[] } | null = null
/** Host-owned durable usage/current-pressure projection. */
private metrics: SessionMetrics | null = null
/** Latest capacity observed on this mux connection, independent of durable metrics arrival. */
private contextWindow: number | undefined
/** Latest atomic request snapshot observed on this mux connection. */
private modelRequest: ModelRequestTelemetry | null
/** `run_code` sub-dispatches by parent callId (window-derived, like openCalls). Appends
* copy-on-write the per-parent array so published snapshot references never mutate. */
private codeDispatches = new Map<string, readonly CodeSubCall[]>()
@@ -175,7 +173,7 @@ export class Session implements SessionFace {
private readonly options: SessionOptions = {},
) {
this.projections = options.projections ?? new ProjectionValueStore()
this.contextWindow = options.modelRequestContextWindow
this.modelRequest = options.modelRequest ?? null
this.snapshotCache = this.buildSnapshot()
}
@@ -331,10 +329,10 @@ export class Session implements SessionFace {
* in-flight open first — its history request rode the dead connection and must not settle
* the fresh generation into 'error' (audit S4). */
async resync(): Promise<void> {
// Queue, metrics, and request capacity are NOT cleared here: onConnected
// Queue and request telemetry are NOT cleared here: onConnected
// (which drives resync) races the mux frames — fresh-generation state may
// have landed already, and the host never resends it. session/subscribed
// owns the generation reset before the queue snapshot and metrics frames.
// have landed already, and the host never resends request telemetry.
// session/subscribed owns the reset before the queue snapshot.
if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open)
this.openGeneration++
this.openPromise = null
@@ -415,24 +413,22 @@ export class Session implements SessionFace {
this.queueRev++
changed = true
}
if (this.contextWindow !== undefined) {
this.contextWindow = undefined
changed = true
}
if (this.metrics !== null) {
this.metrics = null
if (this.modelRequest !== null) {
this.modelRequest = null
changed = true
}
if (changed) this.notifier.markDirty()
return
}
case 'session/metrics': {
this.installMetrics(frame.metrics)
return
}
case 'session/model-request': {
if (this.contextWindow === frame.contextWindow) return
this.contextWindow = frame.contextWindow
const {
type: _type,
sessionId: _sessionId,
...modelRequest
} = frame
// Whole-frame replacement is load-bearing: an omitted numerator or
// capacity clears that field from the preceding request.
this.modelRequest = modelRequest
this.notifier.markDirty()
return
}
@@ -508,17 +504,16 @@ export class Session implements SessionFace {
/** Connection-loss boundary: clear values that are not replayed before the next stream starts. */
handleReconnecting(): void {
this.openGeneration++
if (this.metrics === null && this.contextWindow === undefined) return
this.metrics = null
this.contextWindow = undefined
if (this.modelRequest === null) return
this.modelRequest = null
this.notifier.markDirty()
}
/** host/session-removed relay: flag the resident snapshot and clear connection-local capacity. */
/** host/session-removed relay: flag the resident snapshot and clear request telemetry. */
handleRemoved(): void {
const changed = !this.removed || this.contextWindow !== undefined
const changed = !this.removed || this.modelRequest !== null
this.removed = true
this.contextWindow = undefined
this.modelRequest = null
if (changed) this.notifier.markDirty()
}
@@ -567,7 +562,6 @@ export class Session implements SessionFace {
result.value.events,
result.value.hasMore,
result.value.projections,
result.value.metrics,
)
// Gap detection (§D.3-4): baseline past the window tail and liveBuffer did not cover it -> pull the tail page once more.
const tailSeq = this.windowTailSeq()
@@ -579,7 +573,6 @@ export class Session implements SessionFace {
result.value.events,
result.value.hasMore,
result.value.projections,
result.value.metrics,
)
}
}
@@ -606,7 +599,6 @@ export class Session implements SessionFace {
entries: HistoryEntry[],
hasMore: boolean,
projections: ProjectionsBaseline | undefined,
metrics: SessionMetrics | undefined,
): void {
this.events = entries.map(e => e.event)
this.views = entries.map(e => e.view)
@@ -615,7 +607,6 @@ export class Session implements SessionFace {
this.foldAdapter.reset(this.events, this.baseSeq, this.views)
this.rebuildDerivedFromWindow()
if (projections !== undefined) this.projections.seed(projections)
if (metrics !== undefined) this.installMetrics(metrics)
const buffered = this.liveBuffer
this.liveBuffer = []
for (const item of buffered) this.appendLive(item.event, item.view)
@@ -668,7 +659,6 @@ export class Session implements SessionFace {
result.value.events,
result.value.hasMore,
result.value.projections,
result.value.metrics,
)
}
} catch (error) {
@@ -854,20 +844,6 @@ export class Session implements SessionFace {
return tail === undefined ? null : tail.seq
}
/** Install a metrics snapshot unless a newer durable or publication revision already landed. */
private installMetrics(metrics: SessionMetrics): void {
const current = this.metrics
if (
current !== null
&& (
metrics.logRevision < current.logRevision
|| metrics.projectionRevision < current.projectionRevision
)
) return
this.metrics = metrics
this.notifier.markDirty()
}
private buildSnapshot(): ConversationSnapshot {
const { nodes: folded, degraded } = this.foldAdapter.nodes()
// Frozen interrupted nodes ride fractional seqs: a stable merge keeps them in flow order.
@@ -920,10 +896,7 @@ export class Session implements SessionFace {
promptError: this.promptError,
blank: this.blankBit,
lastAgentError: this.lastAgentError,
metrics: this.metrics,
...(this.contextWindow === undefined
? {}
: { modelRequestContextWindow: this.contextWindow }),
modelRequest: this.modelRequest,
}
}
}

View File

@@ -102,7 +102,7 @@ describe('runtime client apply', () => {
expect(bench.api.callsOf('session.create')).toHaveLength(1)
})
it('clears connection-local Session state on disconnect but not connected', async () => {
it('clears connection-local request telemetry on reconnect but not connected', async () => {
const bench = await mount()
const sessions = bench.ctx.get('sessions') as SessionsService
bench.sinks?.onHostEnvelope?.({
@@ -112,21 +112,8 @@ describe('runtime client apply', () => {
await Promise.resolve()
const session = sessions.binding('s-state' as never)?.session
if (session === undefined) throw new Error('session binding missing')
const currentMetrics = {
projectionRevision: 4,
logRevision: 10,
uncachedInputTokens: 10,
outputTokens: 4,
cacheReadTokens: 90,
cacheWriteTokens: 3,
contextTokens: 35,
}
bench.sinks?.onMuxEnvelope?.({
rpcId: 'metrics' as never,
payload: { type: 'session/metrics', sessionId: 's-state', metrics: currentMetrics } as never,
})
bench.sinks?.onMuxEnvelope?.({
rpcId: 'capacity' as never,
rpcId: 'request' as never,
payload: {
type: 'session/model-request',
sessionId: 's-state',
@@ -134,19 +121,20 @@ describe('runtime client apply', () => {
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 32_000,
contextWindow: 128_000,
} as never,
})
bench.sinks?.onConnected?.()
expect(session.getSnapshot()).toMatchObject({
metrics: currentMetrics,
modelRequestContextWindow: 128_000,
expect(session.getSnapshot().modelRequest).toMatchObject({
model: 'alpha',
contextTokens: 32_000,
contextWindow: 128_000,
})
bench.sinks?.onDisconnected?.()
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
bench.sinks?.onStateChange?.('reconnecting')
expect(session.getSnapshot().modelRequest).toBeNull()
})
it('stops the stream loop when the plugin fiber unloads', async () => {

View File

@@ -4,7 +4,7 @@
import type { CommandId } from '@deepseek-ai/dsh-commands/brand'
import type {
ClientResponse, CommandDescriptor, HostFrame, IApiClient, ModelTarget, MuxFrame,
RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionMetrics, SessionModels,
RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionModels,
SessionProjectionsBlock, SkillEntry,
WorkspaceId, WorkspaceView,
} from '@deepseek-ai/dsh-client-connection/client'
@@ -69,7 +69,6 @@ export class FakeApiClient implements IApiClient {
events: never[]
hasMore: boolean
projections?: SessionProjectionsBlock
metrics?: SessionMetrics
}>> =
() => Promise.resolve(ok({ events: [], hasMore: false }))

View File

@@ -4,7 +4,7 @@
*/
import { describe, expect, it, vi } from 'vitest'
import type { SessionId, SessionMetrics } from '@deepseek-ai/dsh-client-connection/client'
import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
import { SessionManager } from '../src/client/sessions/manager.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
import { entries, plainTurn } from './event-script.ts'
@@ -41,7 +41,7 @@ describe('instances', () => {
expect(manager.get(S2).getSnapshot().pending).toEqual([])
})
it('retains the latest transient model capacity until lazy instantiation', () => {
it('retains the latest transient request snapshot until lazy instantiation', () => {
const api = new FakeApiClient()
const manager = new SessionManager(api)
manager.handleMuxEnvelope({
@@ -53,6 +53,7 @@ describe('instances', () => {
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 12_000,
contextWindow: 128_000,
},
})
@@ -65,14 +66,22 @@ describe('instances', () => {
step: 2,
provider: 'test',
model: 'beta',
contextTokens: 32_000,
contextWindow: 256_000,
},
})
expect(manager.get(S1).getSnapshot().modelRequestContextWindow).toBe(256_000)
expect(manager.get(S1).getSnapshot().modelRequest).toEqual({
turn: 1,
step: 2,
provider: 'test',
model: 'beta',
contextTokens: 32_000,
contextWindow: 256_000,
})
})
it('retains explicit capacity clearing before lazy instantiation', () => {
it('retains whole-frame replacement before lazy instantiation', () => {
const api = new FakeApiClient()
const manager = new SessionManager(api)
manager.handleMuxEnvelope({
@@ -99,10 +108,15 @@ describe('instances', () => {
},
})
expect(manager.get(S1).getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(manager.get(S1).getSnapshot().modelRequest).toEqual({
turn: 1,
step: 2,
provider: 'test',
model: 'unknown-capacity',
})
})
it('clears retained capacity on subscribed and resident capacity on removal', () => {
it('clears retained request telemetry on subscribed and removal', () => {
const api = new FakeApiClient()
const manager = new SessionManager(api)
manager.handleMuxEnvelope({
@@ -122,7 +136,7 @@ describe('instances', () => {
payload: { type: 'session/subscribed', sessionId: S1, lastSeq: 0 },
})
const session = manager.get(S1)
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toBeNull()
manager.handleMuxEnvelope({
rpcId: 'request-after-subscribe' as never,
@@ -136,12 +150,12 @@ describe('instances', () => {
contextWindow: 256_000,
},
})
expect(session.getSnapshot().modelRequestContextWindow).toBe(256_000)
expect(session.getSnapshot().modelRequest?.contextWindow).toBe(256_000)
manager.handleHostEnvelope({
rpcId: 'removed' as never,
payload: { type: 'host/session-removed', sessionId: S1 },
})
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toBeNull()
manager.handleMuxEnvelope({
rpcId: 'request-before-lazy-removal' as never,
@@ -159,28 +173,15 @@ describe('instances', () => {
rpcId: 'lazy-removed' as never,
payload: { type: 'host/session-removed', sessionId: S2 },
})
expect(manager.get(S2).getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(manager.get(S2).getSnapshot().modelRequest).toBeNull()
})
it('clears resident metrics and capacity plus lazy capacity before reconnect', () => {
it('clears resident and lazy request telemetry on disconnect', () => {
const api = new FakeApiClient()
const manager = new SessionManager(api)
const session = manager.get(S1)
const currentMetrics: SessionMetrics = {
projectionRevision: 4,
logRevision: 10,
uncachedInputTokens: 10,
outputTokens: 4,
cacheReadTokens: 90,
cacheWriteTokens: 3,
contextTokens: 35,
}
manager.handleMuxEnvelope({
rpcId: 'metrics' as never,
payload: { type: 'session/metrics', sessionId: S1, metrics: currentMetrics },
})
manager.handleMuxEnvelope({
rpcId: 'resident-capacity' as never,
rpcId: 'resident-request' as never,
payload: {
type: 'session/model-request',
sessionId: S1,
@@ -188,11 +189,12 @@ describe('instances', () => {
step: 1,
provider: 'test',
model: 'resident',
contextTokens: 35,
contextWindow: 128_000,
},
})
manager.handleMuxEnvelope({
rpcId: 'lazy-capacity' as never,
rpcId: 'lazy-request' as never,
payload: {
type: 'session/model-request',
sessionId: S2,
@@ -200,19 +202,20 @@ describe('instances', () => {
step: 1,
provider: 'test',
model: 'lazy',
contextTokens: 70,
contextWindow: 256_000,
},
})
expect(session.getSnapshot()).toMatchObject({
metrics: currentMetrics,
modelRequestContextWindow: 128_000,
expect(session.getSnapshot().modelRequest).toMatchObject({
model: 'resident',
contextTokens: 35,
contextWindow: 128_000,
})
manager.handleReconnecting()
manager.handleDisconnected()
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(manager.get(S2).getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toBeNull()
expect(manager.get(S2).getSnapshot().modelRequest).toBeNull()
})
it('caps the pending buffer at 32 keeping the newest, and drops it on session-removed', () => {

View File

@@ -10,7 +10,7 @@ import { describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import type {
SessionId, SessionMetrics, SessionProjectionsBlock,
SessionId, SessionProjectionsBlock,
} from '@deepseek-ai/dsh-client-connection/client'
import { Session } from '../src/client/sessions/session.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
@@ -29,34 +29,15 @@ function histResponse(
events: SessionEvent[],
hasMore = false,
projections?: SessionProjectionsBlock,
metrics?: SessionMetrics,
) {
// history now returns HistoryEntry[] ({event, view?}); these tests are view-less.
return Promise.resolve(ok({
events: entries(events) as never[],
hasMore,
...projections === undefined ? {} : { projections },
...metrics === undefined ? {} : { metrics },
}))
}
function metrics(
projectionRevision: number,
logRevision: number,
over: Partial<SessionMetrics> = {},
): SessionMetrics {
return {
projectionRevision,
logRevision,
uncachedInputTokens: 10,
outputTokens: 4,
cacheReadTokens: 90,
cacheWriteTokens: 3,
contextTokens: 35,
...over,
}
}
describe('open', () => {
it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
const { api, session } = makeSession()
@@ -70,19 +51,7 @@ describe('open', () => {
expect(snapshot.openState).toBe('open')
expect(snapshot.hasMore).toBe(true)
expect(snapshot.nodes.map(n => n.kind)).toEqual(['user', 'assistant'])
expect(snapshot.metrics).toBeNull()
})
it('installs full-log metrics independently of older history pages', async () => {
const { api, session } = makeSession()
const tailMetrics = metrics(4, 106)
api.onHistory = () => histResponse(plainTurn(100, 3, '问', '答'), true, undefined, tailMetrics)
await session.open()
expect(session.getSnapshot().metrics).toBe(tailMetrics)
api.onHistory = () => histResponse(plainTurn(94, 2, '旧问', '旧答'))
await session.loadOlder()
expect(session.getSnapshot().metrics).toBe(tailMetrics)
expect(snapshot.modelRequest).toBeNull()
})
it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
@@ -147,17 +116,8 @@ describe('live event path', () => {
expect(session.getSnapshot().nodes).toEqual(before.nodes)
})
it('keeps live capacity separate from durable metrics, replaces or clears it on requests, and resets at subscription', async () => {
it('replaces the whole request snapshot, clears omitted fields, and resets at subscription', async () => {
const { session } = await opened()
const current = metrics(8, 10)
session.handleMuxEnvelope('m1' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: current,
})
expect(session.getSnapshot().metrics).toBe(current)
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
session.handleMuxEnvelope('request-1' as never, {
type: 'session/model-request',
sessionId: SID,
@@ -165,32 +125,17 @@ describe('live event path', () => {
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 32_000,
contextWindow: 128_000,
})
expect(session.getSnapshot().metrics).toBe(current)
expect(session.getSnapshot().modelRequestContextWindow).toBe(128_000)
session.handleMuxEnvelope('m2' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: metrics(9, 9, { uncachedInputTokens: 1 }),
expect(session.getSnapshot().modelRequest).toEqual({
turn: 1,
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 32_000,
contextWindow: 128_000,
})
session.handleMuxEnvelope('m3' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: metrics(7, 11, { uncachedInputTokens: 2 }),
})
expect(session.getSnapshot().metrics).toBe(current)
expect(session.getSnapshot().modelRequestContextWindow).toBe(128_000)
const ordinaryUpdate = metrics(9, 11, { contextTokens: 40 })
session.handleMuxEnvelope('m4' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: ordinaryUpdate,
})
expect(session.getSnapshot().metrics).toBe(ordinaryUpdate)
expect(session.getSnapshot().modelRequestContextWindow).toBe(128_000)
session.handleMuxEnvelope('request-2' as never, {
type: 'session/model-request',
@@ -200,16 +145,19 @@ describe('live event path', () => {
provider: 'test',
model: 'without-capacity',
})
expect(session.getSnapshot().metrics).toEqual(ordinaryUpdate)
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toEqual({
turn: 2,
step: 1,
provider: 'test',
model: 'without-capacity',
})
session.handleMuxEnvelope('sub' as never, {
type: 'session/subscribed',
sessionId: SID,
lastSeq: 5,
})
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toBeNull()
session.handleMuxEnvelope('request-3' as never, {
type: 'session/model-request',
sessionId: SID,
@@ -217,19 +165,17 @@ describe('live event path', () => {
step: 1,
provider: 'test',
model: 'beta',
contextTokens: 20,
contextWindow: 256_000,
})
const nextGeneration = metrics(0, 10, { contextTokens: 20 })
session.handleMuxEnvelope('m5' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: nextGeneration,
expect(session.getSnapshot().modelRequest).toMatchObject({
turn: 3,
contextTokens: 20,
contextWindow: 256_000,
})
expect(session.getSnapshot().metrics).toBe(nextGeneration)
expect(session.getSnapshot().modelRequestContextWindow).toBe(256_000)
})
it('publishes a subscribed reset when capacity arrived before durable metrics', async () => {
it('publishes a subscribed reset when request telemetry arrived first', async () => {
const { session } = await opened()
session.handleMuxEnvelope('request' as never, {
type: 'session/model-request',
@@ -238,17 +184,17 @@ describe('live event path', () => {
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 8_000,
contextWindow: 128_000,
})
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequestContextWindow).toBe(128_000)
expect(session.getSnapshot().modelRequest?.contextWindow).toBe(128_000)
session.handleMuxEnvelope('sub' as never, {
type: 'session/subscribed',
sessionId: SID,
lastSeq: 5,
})
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
expect(session.getSnapshot().modelRequest).toBeNull()
})
it('materializes a command node from live lifecycle frames and reproduces it from a history window', async () => {
@@ -876,72 +822,61 @@ describe('remaining branches', () => {
})
describe('resync', () => {
it('fences pre-disconnect history behind a fresh mux metrics baseline', async () => {
it('clears request telemetry on reconnect and drops a stale in-flight history response', async () => {
const { api, session } = makeSession()
const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = () => stale.promise
const opening = session.open()
const oldLiveMetrics = metrics(8, 10)
session.handleMuxEnvelope('old-metrics' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: oldLiveMetrics,
})
session.handleMuxEnvelope('old-capacity' as never, {
session.handleMuxEnvelope('old-request' as never, {
type: 'session/model-request',
sessionId: SID,
turn: 1,
step: 1,
provider: 'test',
model: 'old',
contextTokens: 20,
contextWindow: 128_000,
})
session.handleReconnecting()
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequestContextWindow).toBeUndefined()
const freshMetrics = metrics(0, 1, { contextTokens: 20 })
session.handleMuxEnvelope('fresh-metrics' as never, {
type: 'session/metrics',
sessionId: SID,
metrics: freshMetrics,
})
expect(session.getSnapshot().modelRequest).toBeNull()
stale.resolve(ok({
events: entries(plainTurn(0, 0, '旧问', '旧答')) as never[],
hasMore: false,
metrics: metrics(99, 99, { contextTokens: 999 }),
}))
await opening
expect(session.getSnapshot().nodes).toEqual([])
expect(session.getSnapshot().metrics).toBe(freshMetrics)
expect(session.getSnapshot().modelRequest).toBeNull()
api.onHistory = () => histResponse(plainTurn(6, 1, '新问', '新答'))
await session.resync()
expect(session.getSnapshot().openState).toBe('open')
expect(session.getSnapshot().nodes.map(node => node.seq)).toEqual([7, 9])
expect(session.getSnapshot().metrics).toBe(freshMetrics)
expect(session.getSnapshot().modelRequest).toBeNull()
})
it('preserves fresh-generation metrics that arrive before a failing history refresh', async () => {
it('preserves a fresh-generation request snapshot when history resync fails', async () => {
const { api, session } = makeSession()
const oldMetrics = metrics(8, 10)
api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'), false, undefined, oldMetrics)
api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
await session.open()
expect(session.getSnapshot().metrics).toBe(oldMetrics)
session.handleMuxEnvelope('sub' as never, {
type: 'session/subscribed',
sessionId: SID,
lastSeq: 5,
})
expect(session.getSnapshot().metrics).toBeNull()
expect(session.getSnapshot().modelRequest).toBeNull()
const freshMetrics = metrics(0, 10, { contextTokens: 20 })
session.handleMuxEnvelope('fresh-metrics' as never, {
type: 'session/metrics',
session.handleMuxEnvelope('fresh-request' as never, {
type: 'session/model-request',
sessionId: SID,
metrics: freshMetrics,
turn: 2,
step: 1,
provider: 'test',
model: 'fresh',
contextTokens: 20,
contextWindow: 256_000,
})
api.onHistory = () => Promise.resolve(err({
code: 'internal',
@@ -953,7 +888,14 @@ describe('resync', () => {
expect(session.getSnapshot()).toMatchObject({
openState: 'error',
metrics: freshMetrics,
modelRequest: {
turn: 2,
step: 1,
provider: 'test',
model: 'fresh',
contextTokens: 20,
contextWindow: 256_000,
},
})
})

View File

@@ -62,6 +62,7 @@ export function conversationSnapshot(sessionId: SessionId): ConversationSnapshot
promptError: null,
blank: false,
lastAgentError: null,
modelRequest: null,
}
}

View File

@@ -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

View File

@@ -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).

View File

@@ -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/*` 子路径获取它们)。

View File

@@ -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:^",

View File

@@ -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"

View File

@@ -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>

View File

@@ -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',

View File

@@ -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,
}
}

View File

@@ -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', () => {

View File

@@ -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,
}
}

View File

@@ -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',

View File

@@ -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,
}
}

View File

@@ -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,

View File

@@ -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,

View File

@@ -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,
}
}

View File

@@ -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,
}
}

View File

@@ -26,6 +26,9 @@
{
"path": "../../session-projection/session-projection"
},
{
"path": "../../llm/token-meter"
},
{
"path": "../../plan/plan-mode"
},