From d811a995ad4b21eccb686e0caaeca1bf0393590b Mon Sep 17 00:00:00 2001 From: yuhuan2498281558 Date: Thu, 15 Oct 2026 05:00:20 +0800 Subject: [PATCH] feat(diagnostics): observe live state updates without changing TPS --- README.md | 30 +- sidecars/panel/app.js | 18 + sidecars/panel/index.html | 6 + sidecars/panel/main.mjs | 22 + sidecars/panel/stream-diagnostics.mjs | 449 ++++++++++++++++++ sidecars/panel/test/backend-harness.mjs | 1 + .../panel/test/stream-diagnostics.test.mjs | 194 ++++++++ 7 files changed, 711 insertions(+), 9 deletions(-) create mode 100644 sidecars/panel/stream-diagnostics.mjs create mode 100644 sidecars/panel/test/stream-diagnostics.test.mjs diff --git a/README.md b/README.md index 0a869be..63a2294 100644 --- a/README.md +++ b/README.md @@ -158,13 +158,25 @@ git -C ~/.gemini/config/plugins/usage-monitor pull ## 测速试用分支说明 -本地试用分支:`codex/tps-metrics-trial`。该版本不把汇总日志称为服务端真实解码测速。 +本地试用分支:`codex/tps-metrics-trial`。 -- **正文估算**:有思考 Token 时,需要记录的思考阶段时长,并用正文 Token /(请求总时长 − 思考阶段时长)估算;没有思考且正文 Token 等于总输出时,可采用原始流时长。计时来源随每步保存。没有可靠阶段起点的步骤显示未知。 -- **整体吞吐**:输出 Token(含思考)/ 已完成请求的总时长。不包含调用之间的用户停顿或外部工具执行空档。未完成请求或非法时间显示未知。 -- **均速**:有效样本 Token 合计 / 有效样本时长合计,展示有效/普通调用样本数;自动压缩仍计入费用,但不计两种均速。短样本筛选会影响样本覆盖率,均速只代表纳入的样本。 -- **首 Token**:保留原始字段,不使用 `viewableAt` 或 Token 比例替换。`viewableAt` 的延迟仅作为单独诊断字段保存。 -- **旧缓存**:版本升级为 `v6-speed-metrics`,从原始轨迹重新读取。读取失败时保留用量账目,旧版推算的速度和延迟显示未知。 -- **使用**:在 Antigravity 的 Customizations → Installed 中关闭再开启本插件,然后重新打开侧栏,以确保后端与页面一起加载新版本。 -- **退回原版**:先保存试用分支的本地改动,再在插件目录执行 `git switch main`,关闭再开启本插件。原版会按自己的缓存版本重新读取轨迹。 -- **验证**:在 `sidecars/panel` 目录执行 `npm test`。测试不调用模型、真实配额服务或修改用户统计缓存。私有会话回放和浏览器验收结果不包含在仓库测试夹具中。 +- **TPS**:统一采用输出 Token(含思考和工具参数)/ 已完成请求的总时长,不包含相邻工具步骤的执行耗时或用户停顿。完整请求不足 0.5 秒或计时无效时不显示速率。 +- **均速**:有效样本 Token 合计 / 有效样本时长合计。少于 50 个输出 Token 的请求保留单步速率但不计均速;自动压缩仍计费,不计均速。 +- **首 Token**:保留原生数值;缺失显示未知,不使用 Token 比例推算,也不把它直接当作可扣除的等待时间。 +- **缓存**:`v7-request-throughput`,测速调整不改变历史 Token 与费用账目。 +- **验证**:在 `sidecars/panel` 执行 `npm test`。测试使用本地合成数据,不触发模型生成。 +- **退回原版**:保存本地改动后执行 `git switch main`,关闭再开启插件;主分支没有诊断采集器。 + +### 实时诊断采集(试用) + +在面板的「参数设置 → 测速诊断(试用)」中开启或停止。默认关闭;开启后后台自动跟随最近更新的会话,面板关闭后也可继续采集。仅查询本地会话摘要并订阅 `StreamAgentStateUpdates`,不会发送对话或执行工具。 + +诊断使用完整状态流,因为当前版本的普通界面模式会省略工具参数。它记录单调时钟下的接收时间、接收批次、正文/思考/工具参数的字节与 UTF-16 长度变化,以及匹配到的原生 Token 用量和计时。字节数、字符数、更新次数都不是 Token 数;这些观测暂不参与 TPS 或 TTFT 计算。 + +- 初次连接的历史快照不会计作实时输出;中途接入的步骤标记为部分采集。 +- 重复快照不重复计数;同一网络读取中的多个消息保留同一接收时间和批次,避免伪造时间间隔。 +- 内容重写、缩短、断线重新连接分别保留诊断依据;多个更新也不能证明上游没有缓冲。 +- 新建会话最多约 2 秒才会被发现,可能错过第一步;部分采集的步骤不能用来判断完整生成速度。 +- 日志不保存正文、思考内容、工具名称/参数内容、提示词、响应头或凭据。只写入标识、计数和时间字段。 +- 配置独立保存为后台数据目录下的 `stream-diagnostics-config.json`;日志位于 `stream-diagnostics/events.jsonl`,每份约 5 MiB,保留当前和上一份。用户统计缓存与周限额设置不受影响。 +- 连接失败退避重试;「采集中」只证明实时接口已连接,仍需新对话样本确认工具参数是逐段到达还是一次返回。 diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 1890089..498272d 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -412,6 +412,11 @@ function applyTelemetryToDom(data) { $('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000; $('setting-weekly-cost').value = settings.weeklyCostBudget || 100; + const diagnostic = data.diagnostics || {}; + const phase = ({ disabled: '未开启', waiting: '等待会话', connecting: '连接中', collecting: '采集中', error: '连接异常,稍后重试' })[diagnostic.phase] || '未开启'; + $('diagnostics-status').textContent = `诊断${phase} · 已观察 ${diagnostic.contentEvents || 0} 次内容更新${diagnostic.conversationId ? ` · 会话 ${diagnostic.conversationId.slice(0, 8)}` : ''}`; + $('toggle-diagnostics-btn').textContent = diagnostic.enabled ? '停止诊断采集' : '开启诊断采集'; + renderTables(active, data.modelBreakdown); } @@ -493,6 +498,19 @@ async function updateSettings(patch) { function bindEvents() { $('refresh-btn').addEventListener('click', () => refreshTelemetry(true)); + $('toggle-diagnostics-btn').addEventListener('click', async () => { + const button = $('toggle-diagnostics-btn'); + button.disabled = true; + try { + await callApi('/api/diagnostics', { method: 'POST', body: { enabled: !latestTelemetry?.diagnostics?.enabled } }); + await refreshTelemetry(); + } catch { + $('diagnostics-status').textContent = '诊断设置未保存,请稍后重试'; + } finally { + button.disabled = false; + } + }); + $('conv-select').addEventListener('change', (e) => { selectedConversationId = e.target.value; refreshTelemetry(); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 7957ceb..1935622 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -263,6 +263,12 @@
+

测速诊断(试用)

+

记录最新会话的实时更新时刻和内容长度,不保存正文或工具参数内容。诊断结果暂不参与 TPS 计算。

+

诊断采集未开启

+
+ +
diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index a9a93c8..265bdc0 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -5,6 +5,7 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Response, SidecarApp } from 'sidecar_sdk'; import { extractModelSteps, parseIsoMs, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft, createSpeedAccumulator, accumulateSpeed, finishSpeed } from './speed-metrics.mjs'; +import { StreamDiagnostics } from './stream-diagnostics.mjs'; const HERE = dirname(fileURLToPath(import.meta.url)); const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data'); @@ -894,6 +895,7 @@ async function buildTelemetryPayloadInternal( return { timestamp: new Date().toISOString(), settings, + diagnostics: diagnostics.status(), account: { name: userStatus?.name || '', tierName: userStatus?.userTier?.name || 'Google AI', @@ -1017,6 +1019,7 @@ function buildTelemetryPayload(requestedConvId, forceQuotaRefresh = false, filte // --------------------------------------------------------------------------- const app = new SidecarApp(); +const diagnostics = new StreamDiagnostics({ dataDir: DATA_DIR, lsAddress: LS_ADDR, csrfToken: CSRF_TOKEN }); const readLocal = (name) => readFileSync(join(HERE, name), 'utf8'); function isLocalHostRequest(req) { @@ -1088,4 +1091,23 @@ app.api('/api/settings', (data, req) => { return updated; }); +app.api('/api/diagnostics', (_data, req) => { + if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 }); + return new Response(JSON.stringify(diagnostics.status()), { + contentType: 'application/json', headers: { 'Cache-Control': 'no-store' }, + }); +}, 'GET'); + +app.api('/api/diagnostics', (data, req) => { + if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 }); + try { + return diagnostics.configure({ enabled: data?.enabled, conversationId: data?.conversationId || '' }); + } catch (error) { + return new Response(JSON.stringify({ error: error.message === 'invalid_diagnostic_config' ? 'Invalid diagnostic settings' : 'Could not save diagnostic settings' }), { + status: error.message === 'invalid_diagnostic_config' ? 400 : 500, contentType: 'application/json', + }); + } +}); + app.run(); +diagnostics.start(); diff --git a/sidecars/panel/stream-diagnostics.mjs b/sidecars/panel/stream-diagnostics.mjs new file mode 100644 index 0000000..e241613 --- /dev/null +++ b/sidecars/panel/stream-diagnostics.mjs @@ -0,0 +1,449 @@ +// Diagnostic observation of Anti's local state stream, NOT a model token stream. +// Persist only allowlisted counters/timestamps. Never persist response bodies. +import { createHash, randomUUID } from 'node:crypto'; +import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { performance } from 'node:perf_hooks'; + +const SERVICE = '/exa.language_server_pb.LanguageServerService/'; +const MAX_FRAME = 32 * 1024 * 1024; +const MAX_LOG = 5 * 1024 * 1024; +const UUID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +const END = new Set(['CORTEX_STEP_STATUS_DONE', 'CORTEX_STEP_STATUS_ERROR', 'CORTEX_STEP_STATUS_CANCELED', 'CORTEX_STEP_STATUS_CANCELLED']); +const number = value => value !== undefined && value !== null && value !== '' && Number.isSafeInteger(Number(value)) && Number(value) >= 0 ? Number(value) : null; +const digest = value => createHash('sha256').update(value).digest('hex'); +const duration = value => typeof value === 'string' && /^\d+(\.\d+)?s$/.test(value) ? Number(value.slice(0, -1)) : null; +const timestamp = value => typeof value === 'string' && /^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value) && Number.isFinite(Date.parse(value)) ? value : null; +const rounded = value => Math.round(value * 1000) / 1000; + +export function encodeConnectJson(value) { + const body = Buffer.from(JSON.stringify(value)); + const header = Buffer.alloc(5); + header.writeUInt32BE(body.length, 1); + return Buffer.concat([header, body]); +} + +// HTTP chunks and Connect messages are different boundaries. Every message +// completed in one HTTP read keeps that read's timestamp and receiveBatch. +export class ConnectJsonDecoder { + constructor(maxFrame = MAX_FRAME) { this.pending = Buffer.alloc(0); this.maxFrame = maxFrame; this.ended = false; } + push(chunk) { + if (this.ended) throw new Error('data_after_end'); + this.pending = Buffer.concat([this.pending, chunk]); + const messages = []; + while (this.pending.length >= 5) { + const flags = this.pending[0]; + const length = this.pending.readUInt32BE(1); + if (length > this.maxFrame) throw new Error('frame_too_large'); + if (flags !== 0 && flags !== 2) throw new Error('unsupported_frame_flags'); + if (this.pending.length < length + 5) break; + const payload = this.pending.subarray(5, length + 5); + this.pending = this.pending.subarray(length + 5); + let value; + try { value = JSON.parse(payload.toString('utf8')); } catch { throw new Error('invalid_frame_json'); } + messages.push({ end: flags === 2, value }); + if (flags === 2) { + this.ended = true; + if (this.pending.length) throw new Error('data_after_end'); + break; + } + } + return messages; + } + finish() { if (this.pending.length) throw new Error('truncated_frame'); } +} + +function content(step) { + const p = step.plannerResponse || {}; + const tools = Array.isArray(p.toolCalls) ? p.toolCalls : []; + return { + text: typeof (p.modifiedResponse || p.response) === 'string' ? (p.modifiedResponse || p.response) : '', + thinking: typeof (p.rawThinking || p.thinking) === 'string' ? (p.rawThinking || p.thinking) : '', + // Separators are excluded from counters. Per-tool parts avoid treating a + // change in the first of several tool arguments as a pure suffix append. + toolArguments: tools.map(t => typeof t.argumentsJson === 'string' ? t.argumentsJson : ''), + toolCount: tools.length, + }; +} + +function fingerprint(parts) { + return parts.map(s => ({ hash: digest(s), bytes: Buffer.byteLength(s), units: s.length })); +} + +function compareParts(parts, previous = []) { + const next = fingerprint(parts); + let changed = next.length !== previous.length; + let appendOnly = next.length >= previous.length; + for (let i = 0; i < Math.max(parts.length, previous.length); i++) { + const old = previous[i]; + const now = next[i]; + if (!old) { changed ||= Boolean(now?.bytes); continue; } + if (!now) { changed = true; appendOnly = false; continue; } + if (now.hash !== old.hash) { + changed = true; + if (now.units < old.units || digest(parts[i].slice(0, old.units)) !== old.hash) appendOnly = false; + } + } + const bytes = next.reduce((n, p) => n + p.bytes, 0); + const units = next.reduce((n, p) => n + p.units, 0); + const deltaBytes = bytes - previous.reduce((n, p) => n + p.bytes, 0); + return { next, changed, appendOnly, bytes, utf16Units: units, deltaBytes }; +} + +function tokenUsage(usage) { + if (!usage || typeof usage !== 'object') return null; + const result = {}; + for (const key of ['outputTokens', 'thinkingOutputTokens', 'responseOutputTokens']) { + const n = number(usage[key]); + if (n !== null) result[key] = n; + } + return Object.keys(result).length ? result : null; +} + +function timing(metadata = {}) { + const result = {}; + for (const key of ['createdAt', 'viewableAt', 'finishedGeneratingAt', 'completedAt']) { + const value = timestamp(metadata[key]); + if (value) result[key] = value; + } + return result; +} + +export class StreamObservation { + constructor({ conversationId, connectionId = randomUUID(), emit, connectedWallMs = Date.now() }) { + this.conversationId = conversationId; + this.connectionId = connectionId; + this.emit = emit; + this.connectedWallMs = connectedWallMs; + this.initialized = false; + this.baselineLength = 0; + this.states = new Map(); + this.messages = 0; + this.contentEvents = 0; + this.baselineSteps = 0; + this.recent = []; + } + + record(kind, event, data) { + this.emit({ version: 1, kind, conversationId: this.conversationId, connectionId: this.connectionId, + receivedAt: event.receivedAt, elapsedMs: rounded(event.elapsedMs), receiveBatch: event.receiveBatch, ...data }); + } + + accept(message, event) { + const update = message?.update; + if (!update || update.conversationId !== this.conversationId) return; + this.messages++; + const trajectory = update.mainTrajectoryUpdate; + const page = trajectory?.stepsUpdate; + const isInitial = !this.initialized; + if (isInitial && !page) return; + if (isInitial) { + this.initialized = true; + this.baselineLength = number(page?.totalLength) ?? 0; + this.baselineSteps = Array.isArray(page?.steps) ? page.steps.length : 0; + this.record('baseline', event, { totalSteps: this.baselineLength, receivedSteps: this.baselineSteps, historical: true }); + } + if (page) { + const steps = Array.isArray(page.steps) ? page.steps : []; + const indices = Array.isArray(page.indices) ? page.indices : []; + if (steps.length !== indices.length) throw new Error('invalid_step_indices'); + for (let i = 0; i < steps.length; i++) { + const index = number(indices[i]); + if (index === null) throw new Error('invalid_step_index'); + this.observeStep(index, steps[i], event, isInitial); + } + } + const generators = trajectory?.generatorMetadatasUpdate?.generatorMetadatas; + if (Array.isArray(generators)) for (const gen of generators) { + const cm = gen.chatModel; + if (!cm) continue; + const data = { usage: tokenUsage(cm.usage), nativeTtftSec: duration(cm.timeToFirstToken), nativeStreamSec: duration(cm.streamingDuration) }; + for (const index of gen.stepIndices || []) { + const state = this.states.get(index); + if (!state || state.historical) continue; + const signature = JSON.stringify(data); + if (signature === state.generatorSignature) continue; + state.generatorSignature = signature; + state.nativeTtftSec = data.nativeTtftSec; + state.nativeStreamSec = data.nativeStreamSec; + if (data.usage) state.usage = data.usage; + this.record('model_timing', event, { stepIndex: index, ...data }); + this.refreshRecent(state); + } + } + } + + observeStep(index, step, event, initial) { + if (!step || (step.type !== 'CORTEX_STEP_TYPE_PLANNER_RESPONSE' && !step.plannerResponse)) return; + const sourceTiming = timing(step.metadata); + const complete = Boolean(sourceTiming.finishedGeneratingAt) || END.has(step.status); + let state = this.states.get(index); + if (!state) { + const historical = initial && complete; + // Earlier indices can be rehydrated later. They are never fresh output. + if (historical || (index < this.baselineLength && complete)) return; + state = { index, historical, partialCapture: initial || index < this.baselineLength || + !sourceTiming.createdAt || Date.parse(sourceTiming.createdAt) < this.connectedWallMs, + channels: {}, events: 0, toolEvents: 0, revisions: 0, firstContentMs: null, lastContentMs: null, + contentBatches: new Set(), observedCompletion: false, toolCount: 0, usage: null }; + this.states.set(index, state); + if (this.states.size > 512) { + const finished = [...this.states].find(([, s]) => s.observedCompletion); + if (!finished) throw new Error('too_many_active_steps'); + this.states.delete(finished[0]); + } + } + const c = content(step); + const changes = {}; + let contentChanged = false; + for (const key of ['text', 'thinking', 'toolArguments']) { + const parts = key === 'toolArguments' ? c[key] : [c[key]]; + const previous = state.channels[key]; + const diff = compareParts(parts, previous?.parts); + const channel = previous || { events: 0, firstMs: null, lastMs: null }; + channel.parts = diff.next; + channel.bytes = diff.bytes; + channel.utf16Units = diff.utf16Units; + // Empty initial snapshots establish a baseline, never a content event. + const changed = diff.changed && (diff.bytes > 0 || (previous && diff.deltaBytes !== 0)); + if (changed && !initial) { + channel.events++; + channel.firstMs ??= event.elapsedMs; + channel.lastMs = event.elapsedMs; + changes[key] = { bytes: diff.bytes, utf16Units: diff.utf16Units, deltaBytes: diff.deltaBytes, appendOnly: diff.appendOnly }; + contentChanged = true; + if (!diff.appendOnly) state.revisions++; + if (key === 'toolArguments') state.toolEvents++; + } + state.channels[key] = channel; + } + if (contentChanged) { + state.events++; + this.contentEvents++; + state.firstContentMs ??= event.elapsedMs; + state.lastContentMs = event.elapsedMs; + state.contentBatches.add(event.receiveBatch); + } + const usage = tokenUsage(step.metadata?.modelUsage) || state.usage; + const status = typeof step.status === 'string' && /^CORTEX_STEP_STATUS_[A-Z_]+$/.test(step.status) ? step.status : 'UNKNOWN'; + const signature = JSON.stringify({ status, complete, sourceTiming, usage, toolCount: c.toolCount }); + const changed = state.signature !== signature; + state.signature = signature; + state.status = status; + state.observedCompletion ||= !initial && complete; + state.toolCount = c.toolCount; + state.usage = usage; + if (!initial && (contentChanged || changed)) { + this.record('step_update', event, { stepIndex: index, status, complete, partialCapture: state.partialCapture, + toolCount: c.toolCount, changes, usage, sourceTiming }); + this.refreshRecent(state); + } + } + + refreshRecent(state) { + const channels = Object.fromEntries(Object.entries(state.channels).map(([key, ch]) => [key, { + events: ch.events, bytes: ch.bytes, utf16Units: ch.utf16Units, + observedSpanMs: ch.firstMs === null ? null : rounded(ch.lastMs - ch.firstMs), + }])); + const item = { stepIndex: state.index, complete: state.observedCompletion, partialCapture: state.partialCapture, + contentEvents: state.events, contentReceiveBatches: state.contentBatches.size, toolArgumentEvents: state.toolEvents, + toolCount: state.toolCount, revisions: state.revisions, + observation: state.partialCapture ? 'partial_capture' : state.events === 0 ? 'no_content_observed' : + state.contentBatches.size < 2 ? 'single_receive_batch' : 'multiple_receive_batches', + observedSpanMs: state.firstContentMs === null ? null : rounded(state.lastContentMs - state.firstContentMs), + usage: state.usage, nativeTtftSec: state.nativeTtftSec ?? null, nativeStreamSec: state.nativeStreamSec ?? null, channels }; + this.recent = [item, ...this.recent.filter(r => r.stepIndex !== state.index)].slice(0, 30); + } + + status() { + return { initialized: this.initialized, baselineSteps: this.baselineSteps, messages: this.messages, + contentEvents: this.contentEvents, recentSteps: this.recent }; + } +} + +class DiagnosticLog { + constructor(directory) { this.directory = directory; this.path = join(directory, 'events.jsonl'); this.size = null; } + write(record) { + if (this.size === null) { + mkdirSync(this.directory, { recursive: true }); + this.size = existsSync(this.path) ? statSync(this.path).size : 0; + } + const line = JSON.stringify(record) + '\n'; + const bytes = Buffer.byteLength(line); + if (this.size + bytes > MAX_LOG) { + const previous = this.path + '.1'; + if (existsSync(previous)) unlinkSync(previous); + if (existsSync(this.path)) renameSync(this.path, previous); + this.size = 0; + } + appendFileSync(this.path, line, 'utf8'); + this.size += bytes; + } +} + +export class StreamDiagnostics { + constructor({ dataDir, lsAddress, csrfToken, fetchImpl = fetch, pollMs = 2000, retryMs = 5000 }) { + this.dataDir = dataDir; + this.lsAddress = lsAddress; + this.csrfToken = csrfToken; + this.fetch = fetchImpl; + this.pollMs = pollMs; + this.retryMs = retryMs; + this.configPath = join(dataDir, 'stream-diagnostics-config.json'); + this.log = new DiagnosticLog(join(dataDir, 'stream-diagnostics')); + this.config = { enabled: false, conversationId: '' }; + try { + const config = JSON.parse(readFileSync(this.configPath, 'utf8')); + this.config = { enabled: config.enabled === true, conversationId: UUID.test(config.conversationId) ? config.conversationId : '' }; + } catch { /* Diagnostic capture is opt-in and independent of billing. */ } + this.phase = 'disabled'; + this.error = null; + this.current = null; + this.lastObservation = null; + this.nextRetryAt = 0; + this.timer = null; + this.discoveryController = null; + this.discovering = false; + } + + start() { + if (this.timer || !this.config.enabled) return; + this.phase = 'waiting'; + this.tick(); + this.timer = setInterval(() => this.tick(), this.pollMs); + this.timer.unref?.(); + } + + stop() { + clearInterval(this.timer); + this.timer = null; + this.discoveryController?.abort(); + this.current?.controller.abort(); + this.current = null; + this.phase = 'disabled'; + } + + configure({ enabled, conversationId = '' }) { + if (typeof enabled !== 'boolean' || (conversationId !== '' && !UUID.test(conversationId))) throw new Error('invalid_diagnostic_config'); + const config = { enabled, conversationId }; + mkdirSync(this.dataDir, { recursive: true }); + writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf8'); + this.stop(); + this.config = config; + this.error = null; + this.nextRetryAt = 0; + this.start(); + return this.status(); + } + + status() { + return { enabled: this.config.enabled, phase: this.phase, error: this.error, + targetMode: this.config.conversationId ? 'fixed' : 'latest', + conversationId: this.current?.id || this.lastObservation?.conversationId || '', + connectedAt: this.current?.connectedAt || null, + ...(this.current?.observation || this.lastObservation)?.status(), + source: 'antigravity_state_stream', affectsTps: false }; + } + + async tick() { + if (!this.config.enabled || this.discovering || Date.now() < this.nextRetryAt) return; + this.discovering = true; + const controller = new AbortController(); + this.discoveryController = controller; + const timeout = setTimeout(() => controller.abort(), 5000); + try { + const res = await this.fetch(`http://${this.lsAddress}${SERVICE}GetAllCascadeTrajectories`, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'x-codeium-csrf-token': this.csrfToken }, + body: '{}', signal: controller.signal, + }); + if (!res.ok) throw new Error('discovery_http_' + res.status); + const body = await res.json(); + if (controller.signal.aborted || !this.config.enabled) return; + const entries = Object.entries(body?.trajectorySummaries || {}).filter(([id]) => UUID.test(id)); + entries.sort((a, b) => (Date.parse(b[1].lastModifiedTime || b[1].createdTime) || 0) - (Date.parse(a[1].lastModifiedTime || a[1].createdTime) || 0)); + const selected = this.config.conversationId ? entries.find(([id]) => id === this.config.conversationId) : entries[0]; + if (!selected) { if (!this.current) this.phase = 'waiting'; return; } + const [id, summary] = selected; + if (this.current?.id === id) return; + this.current?.controller.abort(); + const session = { id, controller: new AbortController(), observation: null, connectedAt: null }; + this.current = session; + this.consume(session, number(summary.stepCount) || 0); + } catch (error) { + if (!this.config.enabled || controller.signal.aborted && this.discoveryController !== controller) return; + if (!this.current) this.phase = 'error'; + this.error = /^discovery_http_\d+$/.test(error.message) ? error.message : 'discovery_failed'; + this.nextRetryAt = Date.now() + this.retryMs; + } finally { + clearTimeout(timeout); + if (this.discoveryController === controller) this.discoveryController = null; + this.discovering = false; + } + } + + async consume(session, stepCount) { + let reader; + let firstTimer; + this.phase = 'connecting'; + const started = performance.now(); + const connectedWallMs = Date.now(); + const connectionId = randomUUID(); + let receiveBatch = 0; + try { + firstTimer = setTimeout(() => session.controller.abort(), 15000); + const res = await this.fetch(`http://${this.lsAddress}${SERVICE}StreamAgentStateUpdates`, { + method: 'POST', headers: { 'Content-Type': 'application/connect+json', 'Connect-Protocol-Version': '1', + 'Connect-Accept-Encoding': 'identity', 'x-codeium-csrf-token': this.csrfToken }, + body: encodeConnectJson({ conversationId: session.id, subscriberId: 'usage-monitor-' + connectionId, + initialStepsPageBounds: { startIndex: Math.max(0, stepCount - 16), endIndexExclusive: 2147483647 }, + initialGeneratorMetadatasPageBounds: { startIndex: 0, endIndexExclusive: 2147483647 }, + initialExecutorMetadatasPageBounds: { startIndex: 2147483647, endIndexExclusive: 2147483647 }, + trajectoryVerbosity: 'CLIENT_TRAJECTORY_VERBOSITY_FULL' }), + signal: session.controller.signal, + }); + if (!res.ok) throw new Error('stream_http_' + res.status); + if (!res.headers.get('content-type')?.startsWith('application/connect+json') || !res.body) throw new Error('unsupported_stream_content_type'); + const observation = new StreamObservation({ conversationId: session.id, connectionId, connectedWallMs, + emit: record => this.log.write(record) }); + session.observation = observation; + this.lastObservation = observation; + session.connectedAt = new Date(connectedWallMs).toISOString(); + this.log.write({ version: 1, kind: 'connection', conversationId: session.id, connectionId, + receivedAt: session.connectedAt, elapsedMs: 0, source: 'antigravity_state_stream' }); + const decoder = new ConnectJsonDecoder(); + reader = res.body.getReader(); + while (!session.controller.signal.aborted) { + const { value, done } = await reader.read(); + if (done) break; + const event = { elapsedMs: performance.now() - started, receivedAt: new Date().toISOString(), receiveBatch: ++receiveBatch }; + for (const message of decoder.push(value)) { + if (message.end) { + if (message.value?.error) throw new Error('stream_rpc_error'); + continue; + } + observation.accept(message.value, event); + if (observation.initialized) { + clearTimeout(firstTimer); + if (this.current === session) { this.phase = 'collecting'; this.error = null; } + } + } + if (decoder.ended) break; + } + decoder.finish(); + if (!session.controller.signal.aborted) throw new Error('stream_ended'); + } catch (error) { + if (this.current === session && this.config.enabled) { + this.phase = 'error'; + // Never expose error bodies: they may contain model text or credentials. + this.error = /^(stream_http_\d+|unsupported_stream_content_type|frame_too_large|unsupported_frame_flags|invalid_frame_json|truncated_frame|invalid_step_indices|invalid_step_index|too_many_active_steps|stream_rpc_error|stream_ended|data_after_end)$/.test(error.message) + ? error.message : session.controller.signal.aborted ? 'stream_timeout' : 'stream_failed'; + this.nextRetryAt = Date.now() + this.retryMs; + } + } finally { + clearTimeout(firstTimer); + session.controller.abort(); + try { await reader?.cancel(); } catch { /* socket already closed */ } + if (this.current === session) this.current = null; + } + } +} diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 1498005..05357d1 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -18,6 +18,7 @@ export function backendHarness({cache={},settings={},trajectories={},summaries={ homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs', Response:class {constructor(body,options){this.body=body;this.options=options;}}, SidecarApp:class {page(){} api(){} run(){}}, + StreamDiagnostics:class {status(){return {enabled:false};} start(){}}, fetch:async(url,options)=>{ const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body}); if(method==='GetCascadeTrajectory') { diff --git a/sidecars/panel/test/stream-diagnostics.test.mjs b/sidecars/panel/test/stream-diagnostics.test.mjs new file mode 100644 index 0000000..149dcc9 --- /dev/null +++ b/sidecars/panel/test/stream-diagnostics.test.mjs @@ -0,0 +1,194 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs'; + +const ID = '12345678-1234-1234-1234-123456789abc'; +const CREATED = '2026-10-15T01:00:00.000Z'; +const FINISHED = '2026-10-15T01:00:08.000Z'; +const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED }); +const model = (p = {}, done = false, extra = {}) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING', + metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) }, + plannerResponse: p, ...extra, +}); +const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID, + mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } }); +function observer() { + const records = []; + const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) }); + return { records, observation }; +} + +test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => { + const a = { update: { text: '中文🙂' } }; + const b = { update: { text: 'second' } }; + const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]); + const decoder = new ConnectJsonDecoder(); + const messages = []; + for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3))); + decoder.finish(); + assert.deepEqual(messages.map(m => m.value), [a, b]); + const end = encodeConnectJson({}); end[0] = 2; + assert.equal(decoder.push(end)[0].end, true); + assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/); +}); + +test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => { + const huge = Buffer.from([0, 0, 0, 1, 0]); + assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/); + const compressed = encodeConnectJson({}); compressed[0] = 1; + assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/); + assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/); + const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0])); + assert.throws(() => decoder.finish(), /truncated_frame/); +}); + +test('history, delayed rehydration and status-only notifications never become live output', () => { + const { observation: o, records } = observer(); + o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0)); + assert.equal(o.initialized, false); + o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1)); + o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2)); + assert.equal(o.contentEvents, 0); + assert.equal(o.recent.length, 0); + assert.deepEqual(records.map(r => r.kind), ['baseline']); +}); + +test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => { + const { observation: o, records } = observer(); + o.accept(update([], [], 10), event(0)); + o.accept(update([10], [model()], 11), event(10)); + o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2)); + o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2)); + const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true); + o.accept(update([10], [full], 11), event(120, 3)); + o.accept(update([10], [full], 11), event(300, 4)); + o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: { + usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } }, + timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret', + } }] } }), event(400, 5)); + const r = o.recent[0]; + assert.equal(r.contentEvents, 3); + assert.equal(r.contentReceiveBatches, 2); + assert.equal(r.toolArgumentEvents, 3); + assert.equal(r.observedSpanMs, 100); + assert.equal(r.channels.text.bytes, 6); + assert.equal(r.channels.text.utf16Units, 2); + assert.equal(r.usage.outputTokens, 400); + assert.equal(r.nativeStreamSec, 0.001); + assert.equal(r.partialCapture, false); + const serialized = JSON.stringify([records, r]); + for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret)); + assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized)); +}); + +test('same-batch delivery is not reported as a timed stream, even with several updates', () => { + const { observation: o } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1)); + o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1)); + assert.equal(o.recent[0].observation, 'single_receive_batch'); + assert.equal(o.recent[0].observedSpanMs, 0); +}); + +test('rewrites, shrinking output and tool-only updates are retained as revisions', () => { + const { observation: o, records } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30)); + assert.equal(o.recent[0].revisions, 2); + assert.equal(o.recent[0].toolArgumentEvents, 3); + assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2); + assert.equal(records.at(-1).changes.toolArguments.appendOnly, false); +}); + +test('joining during generation marks partial capture and excludes initial content from updates', () => { + const { observation: o } = observer(); + o.accept(update([2], [model({ response: 'already there' })], 3), event(10)); + o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20)); + assert.equal(o.recent[0].partialCapture, true); + assert.equal(o.recent[0].contentEvents, 1); + assert.equal(o.recent[0].observation, 'partial_capture'); +}); + +test('missing or earlier creation time never claims a complete observation', () => { + const { observation: o } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20)); + assert.equal(o.recent[0].partialCapture, true); + assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/); +}); + +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +async function until(check) { + for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); } + assert.fail('timed out'); +} +function temp(t) { + const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-')); + t.after(() => { + const absolute = resolve(dir); + assert.equal(dirname(absolute), resolve(tmpdir())); + assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-'))); + rmSync(absolute, { recursive: true, force: true }); + }); + return dir; +} + +test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => { + const dir = temp(t); + const calls = []; + let streamController; + const fetchImpl = async (url, options) => { + calls.push({ url, options }); + if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } })); + assert.ok(url.endsWith('StreamAgentStateUpdates')); + const request = new ConnectJsonDecoder().push(options.body)[0].value; + assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL'); + const stream = new ReadableStream({ start(c) { + streamController = c; + c.enqueue(encodeConnectJson(update([], [], 0))); + options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true }); + } }); + return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } }); + }; + const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 }); + t.after(() => d.stop()); + assert.equal(d.status().enabled, false); + d.configure({ enabled: true }); + await until(() => d.status().phase === 'collecting'); + streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1))); + await until(() => d.status().contentEvents === 1); + assert.equal(d.status().affectsTps, false); + d.configure({ enabled: false }); + await sleep(10); + assert.equal(d.status().phase, 'disabled'); + assert.equal(d.current, null); + const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8'); + assert.ok(!log.includes('secret-csrf')); + assert.ok(!log.includes('private-arguments')); + assert.ok(log.includes('step_update')); + assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']); + assert.equal(calls.length, 2); +}); + +test('failed subscriptions back off and never expose the server error body', async t => { + const dir = temp(t); + let calls = 0; + const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000, + fetchImpl: async url => { + calls++; + if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } })); + return new Response('private server error with credentials', { status: 403 }); + } }); + t.after(() => d.stop()); + d.configure({ enabled: true }); + await until(() => d.status().error === 'stream_http_403'); + await sleep(40); + assert.equal(calls, 2); + assert.ok(!JSON.stringify(d.status()).includes('private')); +});