fix(web): fence request telemetry lifecycles

This commit is contained in:
Hypatia May
2026-07-29 17:19:01 +08:00
parent 872cdfc774
commit 55b47657e5
19 changed files with 121 additions and 90 deletions

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: ba9a7d455e8a193f23884411eb1928a10f21ddd0
README.zh.md: 873fefca48585efed010589917f2c63653b08e5b
README.md: 03767fb5da46106a756207a0dda6353ae83aebc0
README.zh.md: fe495bb99c81e80695887e9c71b8ebdfe3f7fe78

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`, `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.
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; removal also installs a Host-lifecycle tombstone so a late frame from the independent mux stream cannot repopulate the removed session. 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` 与 `tokenUsage`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。`ConversationSnapshot.modelRequest` 另行保留当前 mux 连接观察到的最新完整 `session/model-request`。每个帧都会替换整个快照,因此分子或容量字段一旦缺失,就会清除先前值。`SessionManager` 会缓冲一个实例化前快照;`session/subscribed`、断开连接和移除会话则会清除常驻值与待处理值;因此,重连、恢复和新订阅都不会显示上下文百分比,直到观察到另一次请求。仅选择模型不会改变请求观测数据。
客户端 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`、断开连接和移除会话则会清除常驻值与待处理值;移除还会安装 Host 生命周期删除标记,避免独立 mux 流中延迟到达的帧重新填充已移除的会话。因此,重连、恢复和新订阅都不会显示上下文百分比,直到观察到另一次请求。仅选择模型不会改变请求观测数据。
## Workspace 与 Session 列表

View File

@@ -66,6 +66,12 @@ export class SessionManager {
* cannot be backfilled when get() lazily creates the Session.
*/
private readonly modelRequests = new Map<SessionId, ModelRequestTelemetry>()
/**
* Host-lifecycle tombstones. Host and mux use independent SSE streams, so a
* frame emitted before removal can arrive after host/session-removed. Keep
* the id fenced until a later authoritative host/session-added.
*/
private readonly removedSessions = new Set<SessionId>()
/** 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
@@ -348,6 +354,7 @@ export class SessionManager {
handleMuxEnvelope(envelope: RpcRequest<MuxFrame>): void {
const frame = envelope.payload
if (frame.type === 'stream/error') return // Controller already treats this as stream failure
if (this.removedSessions.has(frame.sessionId)) return
if (frame.type === 'session/projection') {
// Finished host-computed value: land it in the resident store whether or
// not the Session is instantiated (list rows read the 'title' key). The
@@ -431,6 +438,7 @@ export class SessionManager {
const frame = envelope.payload
switch (frame.type) {
case 'host/session-added': {
this.removedSessions.delete(frame.sessionId)
this.mergeSummary({
sessionId: frame.sessionId, updatedAt: Date.now(), running: false, blank: frame.blank,
...(frame.parentSessionId !== undefined ? { parentSessionId: frame.parentSessionId } : {}),
@@ -440,6 +448,7 @@ export class SessionManager {
return
}
case 'host/session-removed': {
this.removedSessions.add(frame.sessionId)
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

View File

@@ -504,9 +504,24 @@ 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.modelRequest === null) return
this.modelRequest = null
this.notifier.markDirty()
let changed = false
if (this.openState === 'loading') {
// The in-flight history request belongs to the dead generation. Its
// eventual success or failure is fenced below, so settle the visible
// pane now instead of leaving it loading throughout an outage.
this.openState = 'error'
this.openError = {
code: 'internal',
message: 'connection lost while loading session history',
details: { sessionId: this.sessionId },
}
changed = true
}
if (this.modelRequest !== null) {
this.modelRequest = null
changed = true
}
if (changed) this.notifier.markDirty()
}
/** host/session-removed relay: flag the resident snapshot and clear request telemetry. */

View File

@@ -118,7 +118,7 @@ describe('runtime client apply', () => {
type: 'session/model-request',
sessionId: 's-state',
turn: 1,
step: 0,
step: 1,
provider: 'test',
model: 'alpha',
contextTokens: 32_000,
@@ -145,7 +145,7 @@ describe('runtime client apply', () => {
type: 'session/model-request',
sessionId: 's-state',
turn: 2,
step: 0,
step: 1,
provider: 'test',
model: 'beta',
contextTokens: 48_000,

View File

@@ -156,6 +156,19 @@ describe('instances', () => {
payload: { type: 'host/session-removed', sessionId: S1 },
})
expect(session.getSnapshot().modelRequest).toBeNull()
manager.handleMuxEnvelope({
rpcId: 'late-resident-request' as never,
payload: {
type: 'session/model-request',
sessionId: S1,
turn: 2,
step: 1,
provider: 'test',
model: 'late',
contextWindow: 512_000,
},
})
expect(session.getSnapshot().modelRequest).toBeNull()
manager.handleMuxEnvelope({
rpcId: 'request-before-lazy-removal' as never,
@@ -173,6 +186,18 @@ describe('instances', () => {
rpcId: 'lazy-removed' as never,
payload: { type: 'host/session-removed', sessionId: S2 },
})
manager.handleMuxEnvelope({
rpcId: 'late-lazy-request' as never,
payload: {
type: 'session/model-request',
sessionId: S2,
turn: 2,
step: 1,
provider: 'test',
model: 'late-lazy',
contextWindow: 512_000,
},
})
expect(manager.get(S2).getSnapshot().modelRequest).toBeNull()
})

View File

@@ -822,6 +822,33 @@ describe('remaining branches', () => {
})
describe('resync', () => {
it('settles an in-flight open when its connection generation dies', async () => {
const { api, session } = makeSession()
const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = () => stale.promise
const opening = session.open()
expect(session.getSnapshot().openState).toBe('loading')
session.handleReconnecting()
expect(session.getSnapshot()).toMatchObject({
openState: 'error',
openError: {
code: 'internal',
message: 'connection lost while loading session history',
},
})
stale.reject(new Error('dead generation failed'))
await opening
expect(session.getSnapshot()).toMatchObject({
openState: 'error',
openError: {
code: 'internal',
message: 'connection lost while loading session history',
},
})
})
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']>>>()