From dba34734940fd7c2c4d1e81530f2e7e48ebbc2fd Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 17 Nov 2026 17:37:19 +0900 Subject: [PATCH] feat(panel): add hybrid SQLite+WAL reader, side-question dedup, and cache throttling - Read local conversation_summaries.db and .db (+ .db-wal composite signatures) first while falling back to RPC when local DBs are absent - Deduplicate cloned parent steps and gen_metadata across forks and Side Questions, render zh/en Side Question badges, and protect mainline context watermarks - Throttle trajectory_usage_cache.json writes to 30s during RUNNING sessions and flush immediately on IDLE or exit - Add phased pricing for gemini-4-argon-b and gemini-4-argon-trial, and suppress false upstream update prompts on custom GitHub forks Co-authored-by: orbitoo --- pricing-catalog.json | 6 +- sidecars/panel/app.js | 73 +- sidecars/panel/backend/cli-sqlite-reader.mjs | 2324 +++++++++++++---- sidecars/panel/backend/config.mjs | 139 + sidecars/panel/backend/local-scanner.mjs | 490 +++- sidecars/panel/backend/model-pricing.mjs | 2 +- sidecars/panel/backend/pricing-catalog.mjs | 33 +- sidecars/panel/backend/telemetry-builder.mjs | 129 +- sidecars/panel/backend/usage-aggregator.mjs | 35 +- sidecars/panel/index.html | 4 +- .../src/components/layout/TopSessionHeader.js | 3 +- .../components/widgets/ContextWindowWidget.js | 4 +- .../src/components/widgets/StepTableWidget.js | 4 +- sidecars/panel/src/i18n/en-US.js | 3 + sidecars/panel/src/i18n/zh-CN.js | 3 + sidecars/panel/src/store/telemetryStore.js | 57 +- sidecars/panel/test/backend-harness.mjs | 11 +- .../panel/test/cloud-sync-and-update.test.mjs | 55 + .../sqlite-hybrid-and-side-question.test.mjs | 687 +++++ 19 files changed, 3406 insertions(+), 656 deletions(-) create mode 100644 sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs diff --git a/pricing-catalog.json b/pricing-catalog.json index 62dc114..07669b8 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.17.2", - "updatedAt": "2026-11-17T16:30:00+09:00", + "catalogVersion": "2026.11.17.3", + "updatedAt": "2026-11-17T17:00:00+09:00", "latestPluginVersion": "1.5.0", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", @@ -18,7 +18,9 @@ "gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-b": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-trial": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-hydrogen-xhigh": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7e45c4a..8e479ee 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -327,6 +327,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.sideQuestion': '旁路提问', + 'fmt.sideBadge': '旁{index}', + 'fmt.sideBadgeShort': '旁', 'fmt.selectedCount': '已选 {count} {unit}', 'fmt.selectedListTitle': '已选 ({count}):{names}', 'fmt.selectPlaceholder': '请选择', @@ -851,6 +854,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.sideQuestion': 'Side Question', + 'fmt.sideBadge': 'Q{index}', + 'fmt.sideBadgeShort': 'Q', 'fmt.selectedCount': '{count} {unit} selected', 'fmt.selectedListTitle': 'Selected ({count}): {names}', 'fmt.selectPlaceholder': 'Select', @@ -3901,29 +3907,76 @@ function getAgentBadgeClass(index = 0, isMain = false) { * @returns {string} */ function formatAgentBadgeText(agent) { + const isSideQ = Boolean( + agent?.isSideQuestion || + agent?.typeName === 'side_question' || + /^旁\d*$/.test(String(agent?.badgeText || '')) + ); if (!isEnglishLocale()) { if (!agent || agent.isMain) return agent?.badgeText || '主'; + if (isSideQ) { + const sIdx = Number(agent.sideIndex || 0); + return agent.badgeText || (sIdx > 0 ? `旁${sIdx}` : '旁'); + } return agent.badgeText || `子${agent.index || ''}`; } if (!agent || agent.isMain) return t('fmt.mainBadge'); - return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort'); + if (isSideQ) { + const m = String(agent.badgeText || '').match(/^旁(\d+)$/); + const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); + return sIdx > 0 ? t('fmt.sideBadge', { index: sIdx }) : t('fmt.sideBadgeShort'); + } + const subMatch = String(agent.badgeText || '').match(/^子(\d+)$/); + const subOrd = Number(subMatch ? subMatch[1] : agent.index || 0); + return subOrd > 0 ? t('fmt.subBadge', { index: subOrd }) : t('fmt.subBadgeShort'); } /** - * 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。 + * 格式化主/子代理或旁路提问的完整显示名称(如 `子代理 #1 · Codebase Researcher` / `旁路提问 #1 · ...`)。 * * @param {object|null|undefined} agent * @returns {string} */ function formatAgentLabel(agent) { + const isSideQ = Boolean( + agent?.isSideQuestion || + agent?.typeName === 'side_question' || + /^旁/.test(String(agent?.badgeText || agent?.shortLabel || '')) + ); if (!isEnglishLocale()) { if (!agent) return '主代理'; if (agent.isMain) return agent.shortLabel || '主代理'; + if (isSideQ) { + const sIdx = Number(agent.sideIndex || 0); + const fallbackShort = sIdx > 0 ? `旁路提问 #${sIdx}` : '旁路提问'; + const rolePart = + agent.role && + agent.role !== '旁路提问' && + agent.role !== 'Side Question' && + agent.role !== agent.shortLabel + ? ` · ${agent.role}` + : ''; + return `${agent.shortLabel || fallbackShort}${rolePart}`; + } const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; return `${agent.shortLabel || '子代理'}${rolePart}`; } if (!agent || agent.isMain) return t('fmt.mainAgent'); - const idx = Number(agent.index || 0); + if (isSideQ) { + const m = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); + const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); + const baseLabel = sIdx > 0 ? `${t('fmt.sideQuestion')} #${sIdx}` : t('fmt.sideQuestion'); + const rolePart = + agent.role && + agent.role !== '旁路提问' && + agent.role !== 'Side Question' && + agent.role !== agent.shortLabel + ? ` · ${agent.role}` + : ''; + return `${baseLabel}${rolePart}`; + } + const subMatch = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); + const idx = Number(subMatch ? subMatch[1] : agent.index || 0); const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); const rolePart = agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; @@ -4012,8 +4065,8 @@ function resolveScopedConversation( } if (effectiveCtxScope === 'auto') { ctxAgent = - agents.find((a) => a.agentId === aggregated.activeAgentId) || - agents.find((a) => a.isRunning) || + agents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) || + agents.find((a) => !a.isSideQuestion && a.isRunning) || mainAgent; } } @@ -9359,7 +9412,9 @@ const ContextWindowWidget = defineComponent({ const activeBadgeText = isEnglishLocale() ? rawActiveBadge === '主' ? t('fmt.mainBadge') - : rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) + : rawActiveBadge + .replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) + .replace(/^旁(\d+)$/, (_, n) => t('fmt.sideBadge', { index: n })) : rawActiveBadge; const pillItems = [ @@ -11705,10 +11760,12 @@ const StepTableWidget = defineComponent({ const badgeText = isEnglishLocale() ? formatAgentBadgeText({ isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, index: st.agentIndex || 0, badgeText: st.agentBadge, }) - : st.agentBadge || (st.isSubagent ? '子' : '主'); + : st.agentBadge || (st.isSideQuestion ? '旁' : st.isSubagent ? '子' : '主'); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { @@ -15490,7 +15547,7 @@ const TopSessionHeader = defineComponent({ } else if (isRunning) { const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning); const runSuffix = - hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : ''; + hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : ''; patchSvgIcon(statusIcon, 'bolt'); patchText(statusText, t('header.statusGenerating', { suffix: runSuffix })); patchClasses(statusTag, { diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index d4f6706..01ca02b 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -1,12 +1,13 @@ /** - * @fileoverview 本地 Antigravity CLI / Desktop SQLite 会话轨迹与 Protobuf 文本标题解析器。 + * @fileoverview 本地 Antigravity (Desktop / IDE / CLI) SQLite + WAL 会话摘要、轨迹直读与标题解析器。 * - * 解决 `agy` CLI(进程内嵌随机端口 Language Server、无 `daemon/hub_*.json`、桌面 LS 无法跨目录读取 - * `~/.gemini/antigravity-cli`)下的完整遥测还原: + * 核心能力: * 1. 解析 `/annotations/.pbtxt` 中的真实会话标题(兼容 UTF-8 直出与八进制/十六进制字节转义); - * 2. 通过 Node 22.5+ 内置 `node:sqlite` 只读扫描 `/conversation_summaries.db`,获取标题、实时运行状态与父会话归属; - * 3. 只读解码 `/conversations/.db` 的 `steps.metadata` 与 `gen_metadata.data` 轻量 Protobuf 字段 - * (跳过大体积提示词与工具载荷),完整还原纳秒级耗时、TTFT、思考/正文 Token 拆分、模型展示名与 10 通道上下文构成。 + * 2. 通过 Node 22.5+ 内置 `node:sqlite`(只读 + `SQLITE_BUSY` 退避重试 + WAL `mtime+size` 复合签名缓存)扫描 + * `/conversation_summaries.db`(含 `raw_summary` 与 `conversation_parents` 表),还原会话摘要与旁路提问父子映射; + * 3. 只读解码 `/conversations/.db`,自动过滤分叉/旁路提问克隆自父会话的步骤与 `gen_metadata` + * (`originCid !== cascadeId`),并对 `step_payload` 做按需列投影(仅读取 `USER_INPUT` 轮次提问、`INVOKE_SUBAGENT` + * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 */ import { existsSync, readFileSync, statSync } from 'node:fs'; @@ -14,16 +15,23 @@ import { basename, join } from 'node:path'; import { parseIsoMs } from '../speed-metrics.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; +const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const SQLITE_IN_CHUNK_SIZE = 400; +const utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null; + let sqliteResolved = false; let sqliteDatabaseSyncCtor = null; /** - * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器。 - * 首次加载时静默过滤 Node 22 的实验特性提示,避免污染 CLI 终端或 MCP 日志;不支持时返回 `null`。 + * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。 + * 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。 * * @returns {Function | null} */ export function getNodeSqliteDatabaseSync() { + if (typeof globalThis.DatabaseSync === 'function') { + return globalThis.DatabaseSync; + } if (sqliteResolved) return sqliteDatabaseSyncCtor; sqliteResolved = true; if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { @@ -59,6 +67,84 @@ export function hasBuiltinNodeSqlite() { return Boolean(getNodeSqliteDatabaseSync()); } +/** + * 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。 + * + * @param {string} dbPath + * @returns {{ exists: boolean, mtimeMs: number, sig: string }} + */ +export function computeSqliteWalSig(dbPath) { + if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) { + return { exists: false, mtimeMs: 0, sig: '' }; + } + let dbStat = null; + try { + dbStat = statSync(dbPath); + } catch { + return { exists: false, mtimeMs: 0, sig: '' }; + } + if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' }; + + let walStat = null; + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + try { + walStat = statSync(walPath); + } catch { + walStat = null; + } + } + const dbMtimeMs = Number(dbStat.mtimeMs || 0); + const dbSize = Number(dbStat.size || 0); + const walMtimeMs = Number(walStat?.mtimeMs || 0); + const walSize = Number(walStat?.size || 0); + return { + exists: true, + mtimeMs: Math.max(dbMtimeMs, walMtimeMs), + sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`, + }; +} + +function isSqliteBusyError(err) { + const msg = String(err?.message || err?.code || ''); + return /SQLITE_BUSY|database is locked/i.test(msg); +} + +/** + * 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。 + * 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。 + */ +function withReadOnlySqliteDb(dbPath, queryFn) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return null; + for (let attempt = 0; attempt < 2; attempt++) { + let db = null; + try { + db = new DatabaseSync(dbPath, { readOnly: true }); + try { + db.exec('PRAGMA busy_timeout = 1000;'); + } catch { + // 兼容最小测试桩 + } + return queryFn(db); + } catch (err) { + if (attempt === 0 && isSqliteBusyError(err)) { + continue; + } + throw err; + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + return null; +} + /** * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 * @@ -159,30 +245,477 @@ export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTA function normalizeSqliteIsoTime(value) { const raw = String(value || '').trim(); - if (!raw) return ''; - return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T'); + if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return ''; + return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z'); +} + +// --------------------------------------------------------------------------- +// 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷) +// --------------------------------------------------------------------------- + +const PROTO_STATIC_MODELS = Object.freeze({ + 235: 'MODEL_CHAT_20706', + 246: 'MODEL_GOOGLE_GEMINI_2_5_PRO', + 269: 'MODEL_CHAT_23310', + 281: 'MODEL_CLAUDE_4_SONNET', + 282: 'MODEL_CLAUDE_4_SONNET_THINKING', + 290: 'MODEL_CLAUDE_4_OPUS', + 291: 'MODEL_CLAUDE_4_OPUS_THINKING', + 312: 'MODEL_GOOGLE_GEMINI_2_5_FLASH', + 313: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING', + 327: 'MODEL_GOOGLE_GEMINI_FOR_GOOGLE_2_5_PRO', + 329: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING_TOOLS', + 330: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE', + 332: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW', + 333: 'MODEL_CLAUDE_4_5_SONNET', + 334: 'MODEL_CLAUDE_4_5_SONNET_THINKING', + 340: 'MODEL_CLAUDE_4_5_HAIKU', + 341: 'MODEL_CLAUDE_4_5_HAIKU_THINKING', + 342: 'MODEL_OPENAI_GPT_OSS_120B_MEDIUM', +}); + +const PROTO_API_PROVIDERS = Object.freeze({ + 1: 'API_PROVIDER_INTERNAL', + 3: 'API_PROVIDER_GOOGLE_VERTEX', + 24: 'API_PROVIDER_GOOGLE_GEMINI', + 26: 'API_PROVIDER_ANTHROPIC_VERTEX', + 30: 'API_PROVIDER_GOOGLE_EVERGREEN', + 31: 'API_PROVIDER_OPENAI_VERTEX', + 32: 'API_PROVIDER_OPENAI_RESPONSES_VERTEX', +}); + +const PROTO_STEP_TYPES = Object.freeze({ + 5: 'CORTEX_STEP_TYPE_CODE_ACTION', + 7: 'CORTEX_STEP_TYPE_GREP_SEARCH', + 8: 'CORTEX_STEP_TYPE_VIEW_FILE', + 9: 'CORTEX_STEP_TYPE_LIST_DIRECTORY', + 14: 'CORTEX_STEP_TYPE_USER_INPUT', + 15: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + 17: 'CORTEX_STEP_TYPE_ERROR_MESSAGE', + 21: 'CORTEX_STEP_TYPE_RUN_COMMAND', + 23: 'CORTEX_STEP_TYPE_CHECKPOINT', + 25: 'CORTEX_STEP_TYPE_FIND', + 28: 'CORTEX_STEP_TYPE_COMMAND_STATUS', + 31: 'CORTEX_STEP_TYPE_READ_URL_CONTENT', + 33: 'CORTEX_STEP_TYPE_SEARCH_WEB', + 38: 'CORTEX_STEP_TYPE_MCP_TOOL', + 51: 'CORTEX_STEP_TYPE_LIST_RESOURCES', + 52: 'CORTEX_STEP_TYPE_READ_RESOURCE', + 81: 'CORTEX_STEP_TYPE_TASK_BOUNDARY', + 82: 'CORTEX_STEP_TYPE_NOTIFY_USER', + 85: 'CORTEX_STEP_TYPE_BROWSER_SUBAGENT', + 90: 'CORTEX_STEP_TYPE_EPHEMERAL_MESSAGE', + 91: 'CORTEX_STEP_TYPE_GENERATE_IMAGE', + 100: 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT', + 101: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + 127: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT', + 132: 'CORTEX_STEP_TYPE_GENERIC', + 138: 'CORTEX_STEP_TYPE_ASK_QUESTION', +}); + +const PROTO_STEP_STATUSES = Object.freeze({ + 1: 'CORTEX_STEP_STATUS_PENDING', + 2: 'CORTEX_STEP_STATUS_RUNNING', + 3: 'CORTEX_STEP_STATUS_DONE', + 4: 'CORTEX_STEP_STATUS_INVALID', + 5: 'CORTEX_STEP_STATUS_CLEARED', + 6: 'CORTEX_STEP_STATUS_CANCELED', + 7: 'CORTEX_STEP_STATUS_ERROR', + 8: 'CORTEX_STEP_STATUS_GENERATING', + 9: 'CORTEX_STEP_STATUS_WAITING', + 11: 'CORTEX_STEP_STATUS_QUEUED', + 12: 'CORTEX_STEP_STATUS_INTERRUPTED', +}); + +const PROTO_RUN_STATUSES = Object.freeze({ + 1: 'CASCADE_RUN_STATUS_IDLE', + 2: 'CASCADE_RUN_STATUS_RUNNING', + 3: 'CASCADE_RUN_STATUS_CANCELING', + 4: 'CASCADE_RUN_STATUS_BUSY', +}); + +const PROTO_TRAJECTORY_SOURCES = Object.freeze({ + 1: 'CORTEX_TRAJECTORY_SOURCE_CASCADE_CLIENT', + 12: 'CORTEX_TRAJECTORY_SOURCE_INTERACTIVE_CASCADE', + 15: 'CORTEX_TRAJECTORY_SOURCE_SDK', + 16: 'CORTEX_TRAJECTORY_SOURCE_SUBAGENT', + 17: 'CORTEX_TRAJECTORY_SOURCE_CLI', + 18: 'CORTEX_TRAJECTORY_SOURCE_JETBOX', + 22: 'CORTEX_TRAJECTORY_SOURCE_VSCODE', + 23: 'CORTEX_TRAJECTORY_SOURCE_VISUAL_STUDIO', +}); + +const PROTO_TOKEN_TYPES = Object.freeze({ + 1: 'TOKEN_TYPE_SYSTEM_PROMPT', + 2: 'TOKEN_TYPE_TOOLS', + 3: 'TOKEN_TYPE_RULES', + 4: 'TOKEN_TYPE_MCP_TOOLS', + 5: 'TOKEN_TYPE_SKILLS', + 6: 'TOKEN_TYPE_SUBAGENTS', + 7: 'TOKEN_TYPE_CHAT_MESSAGES', + 8: 'TOKEN_TYPE_WORKFLOWS', + 9: 'TOKEN_TYPE_PLUGINS', + 10: 'TOKEN_TYPE_FLOWS', +}); + +const PROTO_TOKEN_SOURCES = Object.freeze({ + 1: 'TOKEN_SOURCE_SYSTEM', + 2: 'TOKEN_SOURCE_USER', +}); + +const PROTO_CHAT_MSG_SOURCES = Object.freeze({ + 1: 'CHAT_MESSAGE_SOURCE_USER', + 2: 'CHAT_MESSAGE_SOURCE_SYSTEM', + 3: 'CHAT_MESSAGE_SOURCE_UNKNOWN', + 4: 'CHAT_MESSAGE_SOURCE_TOOL', + 5: 'CHAT_MESSAGE_SOURCE_SYSTEM_PROMPT', + 6: 'CHAT_MESSAGE_SOURCE_CONTEXT', +}); + +function toUint8Array(raw) { + if (!raw) return null; + if (raw instanceof Uint8Array) return raw; + if (ArrayBuffer.isView(raw)) { + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + } + if (raw instanceof ArrayBuffer) { + return new Uint8Array(raw); + } + return null; +} + +function decodeUtf8Slice(buf, start, end) { + if (start >= end) return ''; + if (utf8Decoder) { + return utf8Decoder.decode(buf.subarray(start, end)); + } + return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8'); +} + +function readProtoVarint(buf, state, limit = buf.length) { + if (state.off >= limit) return 0n; + const b0 = buf[state.off]; + if (b0 < 0x80) { + state.off += 1; + return BigInt(b0); + } + let result = 0n; + let shift = 0n; + for (let i = 0; i < 10 && state.off < limit; i++) { + const byte = buf[state.off++]; + result |= BigInt(byte & 0x7f) << shift; + if ((byte & 0x80) === 0) { + return BigInt.asUintN(64, result); + } + shift += 7n; + } + while (state.off < limit && (buf[state.off++] & 0x80) !== 0) { + // 安全排空超长 varint 延续字节 + } + return BigInt.asUintN(64, result); +} + +function readSubEnd(buf, state, limit = buf.length) { + const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + return Math.min(limit, state.off + len); +} + +function readProtoString(buf, state, limit = buf.length) { + const end = readSubEnd(buf, state, limit); + const str = decodeUtf8Slice(buf, state.off, end); + state.off = end; + return str; +} + +function skipProtoField(buf, state, wireType, limit = buf.length) { + if (wireType === 0) { + readProtoVarint(buf, state, limit); + } else if (wireType === 1) { + state.off = Math.min(limit, state.off + 8); + } else if (wireType === 2) { + state.off = readSubEnd(buf, state, limit); + } else if (wireType === 5) { + state.off = Math.min(limit, state.off + 4); + } else if (wireType === 3) { + while (state.off < limit) { + const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + const innerWt = innerTag & 7; + if (innerWt === 4) break; + skipProtoField(buf, state, innerWt, limit); + } + } else if (wireType !== 4) { + state.off = limit; + } +} + +function decodeProtoTimestampSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (seconds <= 0n || seconds > 253402300799n) return ''; + const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19); + if (nanos > 0n && nanos < 1_000_000_000n) { + const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); + return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`; + } + return `${baseIso}Z`; +} + +function decodeProtoDurationSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + const totalNs = seconds * 1_000_000_000n + nanos; + if (totalNs < 0n) return ''; + if (totalNs === 0n) return '0s'; + const wholeSec = totalNs / 1_000_000_000n; + const remNs = Number(totalNs % 1_000_000_000n); + if (remNs === 0) return `${wholeSec}s`; + const frac = String(remNs).padStart(9, '0').replace(/0+$/, ''); + return `${wholeSec}.${frac}s`; +} + +function decodeProtoModelEnumInt(val) { + const n = Math.trunc(Number(val)); + if (!Number.isFinite(n) || n <= 0) return ''; + if (n >= 1000 && n < 100000) { + return `MODEL_PLACEHOLDER_M${n - 1000}`; + } + return PROTO_STATIC_MODELS[n] || ''; +} + +function decodeProtoStepTypeEnum(val) { + const n = Math.trunc(Number(val)); + return PROTO_STEP_TYPES[n] || 'CORTEX_STEP_TYPE_GENERIC'; +} + +function decodeProtoStepStatusEnum(val) { + const n = Math.trunc(Number(val)); + return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE'; +} + +function decodeProtoMapStringEntry(buf, state, end) { + let key = ''; + let val = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + key = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + val = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return [key, val]; +} + +function decodeProtoSubagentSpecSlice(buf, state, end) { + let typeName = ''; + let role = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + typeName = readProtoString(buf, state, end).trim(); + } else if (fn === 2 && wt === 2) { + role = readProtoString(buf, state, end).trim(); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return typeName || role ? { typeName, role } : null; +} + +function decodeProtoTrajectoryMetadataSlice(buf, state, end) { + let createdAt = ''; + let parentConversationId = ''; + let rootConversationId = ''; + let nestingDepth = 0; + let subagentSpec = null; + let agentScript = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 2 && wt === 2) { + createdAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 4 && wt === 2) { + const asEnd = readSubEnd(buf, state, end); + let name = ''; + while (state.off < asEnd) { + const asTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, asEnd))); + if ((asTag >>> 3) === 1 && (asTag & 7) === 2) { + name = readProtoString(buf, state, asEnd).trim(); + } else { + skipProtoField(buf, state, asTag & 7, asEnd); + } + } + state.off = asEnd; + if (name) agentScript = { name }; + } else if (fn === 5 && wt === 2) { + parentConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else if (fn === 6 && wt === 2) { + rootConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else if (fn === 8 && wt === 2) { + subagentSpec = decodeProtoSubagentSpecSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 17 && wt === 0) { + nestingDepth = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { + createdAt, + parentConversationId, + rootConversationId, + nestingDepth, + subagentSpec, + agentScript, + }; +} + +function decodeProtoCascadeTrajectorySummary(rawBlob) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return null; + const state = { off: 0 }; + const end = buf.length; + + let summary = ''; + let stepCount; + let lastModifiedTime = ''; + let status = ''; + let createdTime = ''; + let source = ''; + let notFullyIdle; + let trajectoryType = 0; + let killed; + let forkParentConversationId = ''; + let title = ''; + let archived = false; + const sideQuestionCascadeIds = []; + const sideQuestionTitles = {}; + let trajectoryMetadata = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + summary = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 0) { + stepCount = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + } else if (fn === 3 && wt === 2) { + lastModifiedTime = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 5 && wt === 0) { + const sNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + status = PROTO_RUN_STATUSES[sNum] || ''; + } else if (fn === 7 && wt === 2) { + createdTime = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 15 && wt === 2) { + const annEnd = readSubEnd(buf, state, end); + while (state.off < annEnd) { + const aTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, annEnd))); + const aFn = aTag >>> 3; + const aWt = aTag & 7; + if (aFn === 1 && aWt === 2) { + title = readProtoString(buf, state, annEnd); + } else if (aFn === 4 && aWt === 0) { + archived = readProtoVarint(buf, state, annEnd) !== 0n; + } else if (aFn === 17 && aWt === 2) { + const sqId = readProtoString(buf, state, annEnd).trim().toLowerCase(); + if (sqId) sideQuestionCascadeIds.push(sqId); + } else if (aFn === 18 && aWt === 2) { + const [k, v] = decodeProtoMapStringEntry(buf, state, readSubEnd(buf, state, annEnd)); + const lk = k.trim().toLowerCase(); + if (lk) sideQuestionTitles[lk] = v; + } else { + skipProtoField(buf, state, aWt, annEnd); + } + } + state.off = annEnd; + } else if (fn === 17 && wt === 2) { + trajectoryMetadata = decodeProtoTrajectoryMetadataSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 20 && wt === 0) { + const srcNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + source = PROTO_TRAJECTORY_SOURCES[srcNum] || ''; + } else if (fn === 21 && wt === 0) { + notFullyIdle = readProtoVarint(buf, state, end) !== 0n; + } else if (fn === 22 && wt === 0) { + trajectoryType = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + } else if (fn === 23 && wt === 0) { + killed = readProtoVarint(buf, state, end) !== 0n; + } else if (fn === 24 && wt === 2) { + forkParentConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else { + skipProtoField(buf, state, wt, end); + } + } + + return { + summary, + stepCount, + lastModifiedTime, + createdTime, + status, + source, + notFullyIdle, + trajectoryType, + killed, + forkParentConversationId, + annotations: { + title, + archived, + sideQuestionCascadeIds, + sideQuestionTitles, + }, + trajectoryMetadata, + }; } /** - * 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引。 - * 使用 `.db` 与 `.db-wal` 的 `mtimeMs + size` 组合签名做内存 Memoize,未发生写入时零 I/O 返回。 + * 读取并缓存各产品数据根目录(Desktop / IDE / CLI)下的 `conversation_summaries.db` 完整快照。 + * 使用 `.db` 与 `.db-wal` 复合签名做内存 Memoize,未发生写入时零 I/O 返回。 * * @param {string[]} [productRoots=PRODUCT_DATA_ROOTS] - * @returns {Map} + * @param {{ forceRefresh?: boolean }} [options={}] */ -export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { +export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { forceRefresh = false } = {}) { const DatabaseSync = getNodeSqliteDatabaseSync(); - if (!DatabaseSync) return new Map(); + if (!DatabaseSync) { + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; + } const roots = Array.isArray(productRoots) ? productRoots : []; const sigParts = []; const targets = []; @@ -190,335 +723,367 @@ export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { for (const root of roots) { if (!root) continue; const dbPath = join(root, 'conversation_summaries.db'); - if (!existsSync(dbPath)) continue; - try { - const st = statSync(dbPath); - let walPart = '0:0'; - const walPath = `${dbPath}-wal`; - if (existsSync(walPath)) { - try { - const wst = statSync(walPath); - walPart = `${wst.mtimeMs || 0}:${wst.size || 0}`; - } catch { - // 忽略并发清理的 wal 文件 - } - } - sigParts.push(`${dbPath}:${st.mtimeMs || 0}:${st.size || 0}:${walPart}`); - targets.push({ rootName: basename(root).toLowerCase(), dbPath }); - } catch { - // 忽略不可访问的摘要库 - } + const walInfo = computeSqliteWalSig(dbPath); + if (!walInfo.exists) continue; + sigParts.push(`${dbPath}:${walInfo.sig}`); + targets.push({ rootName: basename(root).toLowerCase(), dbPath }); } if (targets.length === 0) { - localSummaryMemo.sig = ''; - localSummaryMemo.byId.clear(); - return localSummaryMemo.byId; + if (productRoots === PRODUCT_DATA_ROOTS) { + localSummaryMemo.sig = ''; + localSummaryMemo.byId.clear(); + localSummaryMemo.available = false; + localSummaryMemo.summariesObj = {}; + localSummaryMemo.sideQuestionParents = {}; + } + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; } - const sig = sigParts.join('|'); - if (localSummaryMemo.sig === sig && localSummaryMemo.byId.size > 0) { - return localSummaryMemo.byId; + const sig = sigParts.join('||'); + if ( + !forceRefresh && + productRoots === PRODUCT_DATA_ROOTS && + localSummaryMemo.sig === sig && + localSummaryMemo.available + ) { + return { + available: true, + sig, + byId: localSummaryMemo.byId, + summariesObj: localSummaryMemo.summariesObj || {}, + sideQuestionParents: localSummaryMemo.sideQuestionParents || {}, + }; } const nextMap = new Map(); + const nextSummariesObj = {}; + const nextSideQuestionParents = {}; + let anyDbSucceeded = false; + for (const { rootName, dbPath } of targets) { - let db = null; try { - db = new DatabaseSync(dbPath, { readOnly: true }); - const rows = db - .prepare( - `SELECT - conversation_id, - title, - status, - parent_conversation_id, - agent_name, - not_fully_idle, - killed, - step_count, - last_modified_time, - app_data_dir - FROM conversation_summaries` - ) - .all(); - for (const row of rows || []) { - const cidLower = String(row?.conversation_id || '').trim().toLowerCase(); - if (!cidLower) continue; - const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase(); - const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName); - const lastModifiedTime = normalizeSqliteIsoTime(row?.last_modified_time); - const lastModifiedMs = parseIsoMs(lastModifiedTime); - const rawStatus = String(row?.status || '').trim(); - const isRunning = - !Number(row?.killed) && - (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || - (Number(row?.not_fully_idle) > 0 && rawStatus !== 'CASCADE_RUN_STATUS_IDLE')); - const entry = { - cascadeId: cidLower, - title: String(row?.title || '').trim(), - status: isRunning ? 'CASCADE_RUN_STATUS_RUNNING' : rawStatus || 'CASCADE_RUN_STATUS_IDLE', - parentConversationId: String(row?.parent_conversation_id || '').trim().toLowerCase(), - agentName: String(row?.agent_name || '').trim(), - stepCount: Math.max(0, Math.floor(Number(row?.step_count) || 0)), - lastModifiedTime, - lastModifiedMs, - appDataDir, - isNativeRootRow, - }; - const prev = nextMap.get(cidLower); - if ( - !prev || - (entry.isNativeRootRow && !prev.isNativeRootRow) || - (entry.isNativeRootRow === prev.isNativeRootRow && - entry.lastModifiedMs >= prev.lastModifiedMs) - ) { - nextMap.set(cidLower, entry); - } - } - } catch { - // 忽略正在初始化或损坏的 SQLite 文件 - } finally { - if (db) { + withReadOnlySqliteDb(dbPath, (db) => { + let rows = []; try { - db.close(); + rows = db + .prepare( + `SELECT + conversation_id, + title, + preview, + status, + source, + parent_conversation_id, + nesting_depth, + agent_name, + not_fully_idle, + killed, + step_count, + last_modified_time, + app_data_dir, + raw_summary + FROM conversation_summaries` + ) + .all(); } catch { - // 忽略关闭异常 + rows = db + .prepare( + `SELECT + conversation_id, + title, + status, + parent_conversation_id, + agent_name, + not_fully_idle, + killed, + step_count, + last_modified_time, + app_data_dir + FROM conversation_summaries` + ) + .all(); } - } + anyDbSucceeded = true; + + let parentRows = []; + try { + parentRows = db + .prepare('SELECT conversation_id, parent_id FROM conversation_parents') + .all(); + } catch { + parentRows = []; + } + + for (const row of rows || []) { + const cidLower = String(row?.conversation_id || '').trim().toLowerCase(); + if (!cidLower) continue; + + let decoded = null; + if (row?.raw_summary) { + try { + decoded = decodeProtoCascadeTrajectorySummary(row.raw_summary); + } catch { + decoded = null; + } + } + + const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase(); + const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName); + const sqlLastMod = normalizeSqliteIsoTime(row?.last_modified_time); + const createdTime = String( + decoded?.createdTime || decoded?.trajectoryMetadata?.createdAt || '' + ); + const lastModifiedTime = String(decoded?.lastModifiedTime || sqlLastMod || createdTime || ''); + const lastModifiedMs = parseIsoMs(lastModifiedTime); + const rawStatus = String(decoded?.status || row?.status || '').trim(); + const killed = Boolean(decoded?.killed ?? Number(row?.killed)); + const notFullyIdle = Boolean(decoded?.notFullyIdle ?? Number(row?.not_fully_idle) > 0); + const isRunning = + !killed && + (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || + (notFullyIdle && rawStatus !== 'CASCADE_RUN_STATUS_IDLE')); + const effectiveStatus = isRunning + ? 'CASCADE_RUN_STATUS_RUNNING' + : rawStatus || 'CASCADE_RUN_STATUS_IDLE'; + + const rawMeta = decoded?.trajectoryMetadata || null; + const parentConversationId = String( + rawMeta?.parentConversationId || row?.parent_conversation_id || '' + ) + .trim() + .toLowerCase(); + const rootConversationId = String(rawMeta?.rootConversationId || '').trim().toLowerCase(); + const agentName = String( + rawMeta?.agentScript?.name || row?.agent_name || '' + ).trim(); + const title = String(decoded?.annotations?.title || row?.title || '').trim(); + const stepCount = Math.max( + 0, + Math.floor(Number(decoded?.stepCount ?? row?.step_count ?? 0) || 0) + ); + const trajectoryType = Number(decoded?.trajectoryType || 0); + const isSideQuestion = trajectoryType === 22; + const forkParentConversationId = String(decoded?.forkParentConversationId || '') + .trim() + .toLowerCase(); + + const sideQuestionIds = Array.isArray(decoded?.annotations?.sideQuestionCascadeIds) + ? decoded.annotations.sideQuestionCascadeIds + : []; + const sideQuestionTitles = decoded?.annotations?.sideQuestionTitles || {}; + + const entry = { + cascadeId: cidLower, + title, + status: effectiveStatus, + parentConversationId, + rootConversationId, + agentName, + subagentSpec: rawMeta?.subagentSpec || null, + stepCount, + lastModifiedTime, + lastModifiedMs, + createdTime, + appDataDir, + isNativeRootRow, + trajectoryType, + isSideQuestion, + forkParentConversationId, + }; + + const summaryRpcShape = { + summary: String(decoded?.summary || row?.preview || ''), + stepCount, + lastModifiedTime, + createdTime, + status: effectiveStatus, + source: String(decoded?.source || row?.source || ''), + appDataDir, + notFullyIdle, + killed, + trajectoryType, + isSideQuestion, + forkParentConversationId, + annotations: { + title, + archived: Boolean(decoded?.annotations?.archived), + sideQuestionCascadeIds: sideQuestionIds, + sideQuestionTitles, + }, + trajectoryMetadata: { + createdAt: String(rawMeta?.createdAt || createdTime || ''), + parentConversationId, + rootConversationId, + nestingDepth: Number(rawMeta?.nestingDepth ?? row?.nesting_depth ?? 0), + subagentSpec: rawMeta?.subagentSpec || null, + agentScript: agentName ? { name: agentName } : null, + }, + }; + + const prev = nextMap.get(cidLower); + if ( + !prev || + (entry.isNativeRootRow && !prev.isNativeRootRow) || + (entry.isNativeRootRow === prev.isNativeRootRow && + entry.lastModifiedMs >= prev.lastModifiedMs) + ) { + nextMap.set(cidLower, entry); + nextSummariesObj[cidLower] = summaryRpcShape; + } + + if (isSideQuestion && forkParentConversationId) { + const existingSq = nextSideQuestionParents[cidLower]; + nextSideQuestionParents[cidLower] = { + parentConversationId: existingSq?.parentConversationId || forkParentConversationId, + title: existingSq?.title || title || '', + }; + } + + for (const sqId of sideQuestionIds) { + const sqLower = String(sqId || '').trim().toLowerCase(); + if (!sqLower) continue; + nextSideQuestionParents[sqLower] = { + parentConversationId: cidLower, + title: String(sideQuestionTitles[sqLower] || nextSideQuestionParents[sqLower]?.title || ''), + }; + } + for (const [sqKey, sqTitle] of Object.entries(sideQuestionTitles)) { + const sqLower = String(sqKey || '').trim().toLowerCase(); + if (!sqLower) continue; + const existingSq = nextSideQuestionParents[sqLower]; + nextSideQuestionParents[sqLower] = { + parentConversationId: existingSq?.parentConversationId || cidLower, + title: String(sqTitle || existingSq?.title || ''), + }; + } + } + + for (const pRow of parentRows || []) { + const sqLower = String(pRow?.conversation_id || '').trim().toLowerCase(); + const parentLower = String(pRow?.parent_id || '').trim().toLowerCase(); + if (!sqLower || !parentLower) continue; + const parentSummary = nextSummariesObj[parentLower]; + const titleFromParent = String( + parentSummary?.annotations?.sideQuestionTitles?.[sqLower] || + nextSideQuestionParents[sqLower]?.title || + '' + ); + nextSideQuestionParents[sqLower] = { + parentConversationId: parentLower, + title: titleFromParent, + }; + } + }); + } catch { + // 忽略正在初始化或不可读的单个 SQLite 摘要库 } } - localSummaryMemo.sig = sig; - localSummaryMemo.byId = nextMap; - return nextMap; -} - -// --------------------------------------------------------------------------- -// 零依赖轻量 Protobuf Wire 解码器(仅提取指标字段,O(1) 跳过大体积 Prompt 载荷) -// --------------------------------------------------------------------------- - -function readProtoVarint(buf, state) { - let result = 0n; - let shift = 0n; - while (state.off < buf.length) { - const byte = BigInt(buf[state.off++]); - result |= (byte & 0x7fn) << shift; - if ((byte & 0x80n) === 0n) return result; - shift += 7n; - if (shift > 70n) throw new Error('Invalid protobuf varint'); + if (!anyDbSucceeded) { + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; } - throw new Error('Unexpected EOF in protobuf varint'); -} -function skipProtoField(buf, state, wireType) { - if (wireType === 0) { - readProtoVarint(buf, state); - } else if (wireType === 1) { - state.off += 8; - } else if (wireType === 2) { - const len = Number(readProtoVarint(buf, state)); - state.off += len; - } else if (wireType === 5) { - state.off += 4; - } else { - throw new Error(`Unsupported protobuf wireType: ${wireType}`); - } - if (state.off > buf.length) { - throw new Error('Protobuf field length out of bounds'); - } -} - -function decodeProtoTimestampIso(buf) { - const st = { off: 0 }; - let seconds = 0n; - let nanos = 0n; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); - } - } - if (seconds <= 0n) return ''; - const baseIso = new Date(Number(seconds) * 1000).toISOString(); - const prefix = baseIso.slice(0, 19); - if (nanos > 0n && nanos < 1_000_000_000n) { - const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); - return frac ? `${prefix}.${frac}Z` : `${prefix}Z`; - } - return `${prefix}Z`; -} - -function decodeProtoDurationStr(buf) { - const st = { off: 0 }; - let seconds = 0n; - let nanos = 0n; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); - } - } - if (seconds < 0n || nanos < 0n) return ''; - if (nanos === 0n) return `${seconds}s`; - const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); - return frac ? `${seconds}.${frac}s` : `${seconds}s`; -} - -function decodeProtoModelEnumInt(val) { - const n = Number(val); - if (Number.isInteger(n) && n >= 1000 && n < 10000) { - return `MODEL_PLACEHOLDER_M${n - 1000}`; - } - return ''; -} - -function decodeProtoTokenTypeEnum(val) { - switch (Number(val)) { - case 1: - return 'TOKEN_TYPE_SYSTEM_PROMPT'; - case 2: - return 'TOKEN_TYPE_TOOLS'; - case 3: - return 'TOKEN_TYPE_RULES'; - case 4: - return 'TOKEN_TYPE_MCP_TOOLS'; - case 5: - return 'TOKEN_TYPE_SKILLS'; - case 6: - return 'TOKEN_TYPE_SUBAGENTS'; - case 7: - return 'TOKEN_TYPE_CHAT_MESSAGES'; - default: - return ''; - } -} - -function decodeProtoStepTypeEnum(val) { - switch (Number(val)) { - case 14: - return 'CORTEX_STEP_TYPE_USER_INPUT'; - case 15: - return 'CORTEX_STEP_TYPE_PLANNER_RESPONSE'; - case 17: - return 'CORTEX_STEP_TYPE_ERROR_MESSAGE'; - case 23: - return 'CORTEX_STEP_TYPE_CHECKPOINT'; - case 101: - return 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'; - default: - return 'CORTEX_STEP_TYPE_GENERIC'; - } -} - -function decodeProtoStepStatusEnum(val) { - switch (Number(val)) { - case 2: - return 'CORTEX_STEP_STATUS_RUNNING'; - case 3: - return 'CORTEX_STEP_STATUS_DONE'; - case 5: - return 'CORTEX_STEP_STATUS_CLEARED'; - case 6: - return 'CORTEX_STEP_STATUS_CANCELED'; - case 7: - return 'CORTEX_STEP_STATUS_ERROR'; - case 8: - return 'CORTEX_STEP_STATUS_GENERATING'; - default: - return 'CORTEX_STEP_STATUS_DONE'; - } -} - -function decodeProtoModelUsage(buf) { - const st = { off: 0 }; - let model = ''; - let inputTokens = 0; - let outputTokens = 0; - let cacheReadTokens = 0; - let apiProviderNum = 0; - let thinkingOutputTokens; - let responseOutputTokens; - - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - model = decodeProtoModelEnumInt(readProtoVarint(buf, st)); - } else if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - model = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else if (fn === 2 && wt === 0) { - inputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 3 && wt === 0) { - outputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 5 && wt === 0) { - cacheReadTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 6 && wt === 0) { - apiProviderNum = Number(readProtoVarint(buf, st)); - } else if (fn === 9 && wt === 0) { - thinkingOutputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 10 && wt === 0) { - responseOutputTokens = Number(readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); - } + if (productRoots === PRODUCT_DATA_ROOTS) { + localSummaryMemo.sig = sig; + localSummaryMemo.byId = nextMap; + localSummaryMemo.available = true; + localSummaryMemo.summariesObj = nextSummariesObj; + localSummaryMemo.sideQuestionParents = nextSideQuestionParents; } return { - ...(model ? { model } : {}), - ...(apiProviderNum === 24 ? { apiProvider: 'API_PROVIDER_GOOGLE_GEMINI' } : {}), - inputTokens, - cacheReadTokens, - outputTokens, - ...(thinkingOutputTokens !== undefined ? { thinkingOutputTokens } : {}), - ...(responseOutputTokens !== undefined ? { responseOutputTokens } : {}), + available: true, + sig, + byId: nextMap, + summariesObj: nextSummariesObj, + sideQuestionParents: nextSideQuestionParents, }; } -function decodeProtoTokenBreakdownGroup(buf, depth = 0) { - const st = { off: 0 }; +/** + * 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引(返回 `Map`,保持向后兼容)。 + * + * @param {string[]} [productRoots=PRODUCT_DATA_ROOTS] + * @returns {Map} + */ +export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { + return readLocalSummarySnapshot(productRoots).byId; +} + +function decodeProtoModelUsageSlice(buf, state, end) { + const usage = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + const m = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); + if (m) usage.model = m; + } else if (fn === 1 && wt === 2) { + const m = readProtoString(buf, state, end).trim(); + if (m) usage.model = m; + } else if (fn === 2 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.inputTokens = v; + } else if (fn === 3 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.outputTokens = v; + } else if (fn === 5 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.cacheReadTokens = v; + } else if (fn === 6 && wt === 0) { + const provNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const prov = PROTO_API_PROVIDERS[provNum] || ''; + if (prov) usage.apiProvider = prov; + } else if (fn === 9 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.thinkingOutputTokens = v; + } else if (fn === 10 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.responseOutputTokens = v; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (usage.inputTokens === undefined) usage.inputTokens = 0; + if (usage.cacheReadTokens === undefined) usage.cacheReadTokens = 0; + if (usage.outputTokens === undefined) usage.outputTokens = 0; + return usage; +} + +function decodeProtoChildTokenGroupSlice(buf, state, end, depth = 0) { let name = ''; let type = ''; let numTokens = 0; const children = []; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - name = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; + name = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2 && depth < 2) { + // 子级 TokenGroup 的 children 位于 field 2 + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), depth + 1)); } else if (fn === 2 && wt === 0) { - type = decodeProtoTokenTypeEnum(readProtoVarint(buf, st)); + const tNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + type = PROTO_TOKEN_TYPES[tNum] || ''; + } else if (fn === 3 && wt === 0) { + // 子级 TokenGroup 的 numTokens 位于 field 3 + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 4 && wt === 0) { - numTokens = Number(readProtoVarint(buf, st)); + // 兼容直接按顶层结构编码的子组(numTokens 位于 field 4) + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 5 && wt === 2 && depth < 2) { - const len = Number(readProtoVarint(buf, st)); - const sub = buf.subarray(st.off, st.off + len); - st.off += len; - children.push(decodeProtoTokenBreakdownGroup(sub, depth + 1)); + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), depth + 1)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } - + state.off = end; return { name, ...(type ? { type } : {}), @@ -527,75 +1092,92 @@ function decodeProtoTokenBreakdownGroup(buf, depth = 0) { }; } -function decodeProtoContextWindowMeta(buf) { - const st = { off: 0 }; +function decodeProtoTopTokenGroupSlice(buf, state, end) { + let name = ''; + let type = ''; + let source = ''; + let numTokens = 0; + const children = []; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + name = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 0) { + const tNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + type = PROTO_TOKEN_TYPES[tNum] || ''; + } else if (fn === 3 && wt === 0) { + const sNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + source = PROTO_TOKEN_SOURCES[sNum] || ''; + } else if (fn === 4 && wt === 0) { + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); + } else if (fn === 5 && wt === 2) { + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), 0)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { + name, + ...(type ? { type } : {}), + ...(source ? { source } : {}), + numTokens, + ...(children.length > 0 ? { children } : {}), + }; +} + +function decodeProtoContextWindowMetaSlice(buf, state, end, includeBreakdown) { let estimatedTokensUsed = 0; let maxContextTokens = 0; const groups = []; + let totalTokens = 0; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 0) { - estimatedTokensUsed = Number(readProtoVarint(buf, st)); + estimatedTokensUsed = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 4 && wt === 0) { - maxContextTokens = Number(readProtoVarint(buf, st)); + maxContextTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 3 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const tbBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const tbSt = { off: 0 }; - while (tbSt.off < tbBuf.length) { - const tbTag = Number(readProtoVarint(tbBuf, tbSt)); - const tbFn = tbTag >>> 3; - const tbWt = tbTag & 7; - if (tbFn === 1 && tbWt === 2) { - const gLen = Number(readProtoVarint(tbBuf, tbSt)); - const gBuf = tbBuf.subarray(tbSt.off, tbSt.off + gLen); - tbSt.off += gLen; - groups.push(decodeProtoTokenBreakdownGroup(gBuf, 0)); - } else { - skipProtoField(tbBuf, tbSt, tbWt); + if (includeBreakdown) { + const tbEnd = readSubEnd(buf, state, end); + while (state.off < tbEnd) { + const tbTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, tbEnd))); + const tbFn = tbTag >>> 3; + const tbWt = tbTag & 7; + if (tbFn === 1 && tbWt === 2) { + groups.push(decodeProtoTopTokenGroupSlice(buf, state, readSubEnd(buf, state, tbEnd))); + } else if (tbFn === 2 && tbWt === 0) { + totalTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, tbEnd))); + } else { + skipProtoField(buf, state, tbWt, tbEnd); + } } + state.off = tbEnd; + } else { + skipProtoField(buf, state, wt, end); } } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } + state.off = end; return { ...(estimatedTokensUsed > 0 ? { estimatedTokensUsed } : {}), ...(maxContextTokens > 0 ? { maxContextTokens } : {}), - ...(groups.length > 0 ? { tokenBreakdown: { groups } } : {}), + ...(includeBreakdown && groups.length > 0 + ? { tokenBreakdown: { groups, ...(totalTokens > 0 ? { totalTokens } : {}) } } + : {}), }; } -function decodeProtoMapStringEntry(buf) { - const st = { off: 0 }; - let key = ''; - let val = ''; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - key = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else if (fn === 2 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - val = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else { - skipProtoField(buf, st, wt); - } - } - return [key, val]; -} - -function decodeProtoChatModelMeta(buf) { - const st = { off: 0 }; +function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { let model = ''; let usage = null; let contextWindowMetadata = null; @@ -604,67 +1186,133 @@ function decodeProtoChatModelMeta(buf) { let responseModel = ''; let modelDisplayName = ''; const extraMeta = {}; + let messagePrompts = null; + let tools = null; + let promptSections = null; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; - if (fn === 3 && wt === 0) { - const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + if (fn === 2 && wt === 2) { + if (includeBreakdown) { + const mpEnd = readSubEnd(buf, state, end); + const msg = {}; + while (state.off < mpEnd) { + const mTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd))); + const mFn = mTag >>> 3; + const mWt = mTag & 7; + if (mFn === 2 && mWt === 0) { + const src = PROTO_CHAT_MSG_SOURCES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd)))]; + if (src) msg.source = src; + } else if (mFn === 3 && mWt === 2) { + msg.prompt = readProtoString(buf, state, mpEnd); + } else if (mFn === 4 && mWt === 0) { + const nt = Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd))); + if (nt > 0) msg.numTokens = nt; + } else { + skipProtoField(buf, state, mWt, mpEnd); + } + } + state.off = mpEnd; + if (!messagePrompts) messagePrompts = []; + messagePrompts.push(msg); + } else { + skipProtoField(buf, state, wt, end); + } + } else if (fn === 3 && wt === 0) { + const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); if (enumStr && !model) model = enumStr; } else if (fn === 4 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - usage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); - st.off += len; + usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 8 && wt === 2) { + if (includeBreakdown) { + const tdEnd = readSubEnd(buf, state, end); + const tool = {}; + while (state.off < tdEnd) { + const tTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, tdEnd))); + const tFn = tTag >>> 3; + const tWt = tTag & 7; + if (tFn === 1 && tWt === 2) tool.name = readProtoString(buf, state, tdEnd); + else if (tFn === 2 && tWt === 2) tool.description = readProtoString(buf, state, tdEnd); + else if (tFn === 3 && tWt === 2) tool.jsonSchemaString = readProtoString(buf, state, tdEnd); + else if (tFn === 6 && tWt === 2) tool.serverName = readProtoString(buf, state, tdEnd); + else skipProtoField(buf, state, tWt, tdEnd); + } + state.off = tdEnd; + if (!tools) tools = []; + tools.push(tool); + } else { + skipProtoField(buf, state, wt, end); + } } else if (fn === 9 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const csBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const csSt = { off: 0 }; - while (csSt.off < csBuf.length) { - const csTag = Number(readProtoVarint(csBuf, csSt)); + const csEnd = readSubEnd(buf, state, end); + while (state.off < csEnd) { + const csTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, csEnd))); const csFn = csTag >>> 3; const csWt = csTag & 7; if (csFn === 10 && csWt === 2) { - const cwLen = Number(readProtoVarint(csBuf, csSt)); - contextWindowMetadata = decodeProtoContextWindowMeta( - csBuf.subarray(csSt.off, csSt.off + cwLen) + contextWindowMetadata = decodeProtoContextWindowMetaSlice( + buf, + state, + readSubEnd(buf, state, csEnd), + includeBreakdown ); - csSt.off += cwLen; } else { - skipProtoField(csBuf, csSt, csWt); + skipProtoField(buf, state, csWt, csEnd); } } + state.off = csEnd; } else if (fn === 11 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - timeToFirstToken = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); - st.off += len; + timeToFirstToken = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 12 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - streamingDuration = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); - st.off += len; + streamingDuration = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 16 && wt === 2) { + if (includeBreakdown) { + const psEnd = readSubEnd(buf, state, end); + const sec = {}; + while (state.off < psEnd) { + const pTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd))); + const pFn = pTag >>> 3; + const pWt = pTag & 7; + if (pFn === 1 && pWt === 2) sec.title = readProtoString(buf, state, psEnd); + else if (pFn === 2 && pWt === 2) sec.content = readProtoString(buf, state, psEnd); + else if (pFn === 6 && pWt === 0) { + const tt = PROTO_TOKEN_TYPES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd)))]; + if (tt) sec.tokenType = tt; + } else if (pFn === 7 && pWt === 0) { + const ts = PROTO_TOKEN_SOURCES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd)))]; + if (ts) sec.tokenSource = ts; + } else { + skipProtoField(buf, state, pWt, psEnd); + } + } + state.off = psEnd; + if (!promptSections) promptSections = []; + promptSections.push(sec); + } else { + skipProtoField(buf, state, wt, end); + } } else if (fn === 19 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - responseModel = buf.subarray(st.off, st.off + len).toString('utf8').trim(); - st.off += len; + responseModel = readProtoString(buf, state, end).trim(); } else if (fn === 20 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const [k, v] = decodeProtoMapStringEntry(buf.subarray(st.off, st.off + len)); - st.off += len; + const [k, v] = decodeProtoMapStringEntry(buf, state, readSubEnd(buf, state, end)); if (k && v) extraMeta[k] = v; } else if (fn === 21 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - modelDisplayName = buf.subarray(st.off, st.off + len).toString('utf8').trim(); - st.off += len; + modelDisplayName = readProtoString(buf, state, end).trim(); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } + state.off = end; if (extraMeta.model_enum) { - model = extraMeta.model_enum.trim(); - if (usage && !usage.model) { - usage.model = model; + const cleanEnum = extraMeta.model_enum.trim(); + if (cleanEnum && !/^MODEL_(?:UNSPECIFIED|UNKNOWN)$/i.test(cleanEnum) && cleanEnum !== '0') { + model = cleanEnum; + if (usage && !usage.model) { + usage.model = model; + } } } if (extraMeta.used_claude === 'true' && usage && !usage.apiProvider) { @@ -675,103 +1323,200 @@ function decodeProtoChatModelMeta(buf) { chatModel: { ...(model ? { model } : {}), ...(usage ? { usage } : {}), - ...(contextWindowMetadata ? { chatStartMetadata: { contextWindowMetadata } } : {}), + ...(contextWindowMetadata && Object.keys(contextWindowMetadata).length > 0 + ? { chatStartMetadata: { contextWindowMetadata } } + : {}), ...(timeToFirstToken ? { timeToFirstToken } : {}), ...(streamingDuration ? { streamingDuration } : {}), ...(responseModel ? { responseModel } : {}), ...(modelDisplayName ? { modelDisplayName } : {}), + ...(messagePrompts ? { messagePrompts } : {}), + ...(tools ? { tools } : {}), + ...(promptSections ? { promptSections } : {}), }, extraMeta, }; } -function decodeProtoGeneratorMeta(buf) { - const st = { off: 0 }; +function decodeProtoPlannerConfigSlice(buf, state, end) { + const pc = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + const pm = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); + if (pm) pc.planModel = pm; + } else if (fn === 28 && wt === 2) { + const mn = readProtoString(buf, state, end).trim(); + if (mn) pc.modelName = mn; + } else if (fn === 60 && wt === 2) { + const pecEnd = readSubEnd(buf, state, end); + let execModel = ''; + while (state.off < pecEnd) { + const pTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, pecEnd))); + if ((pTag >>> 3) === 1 && (pTag & 7) === 0) { + execModel = decodeProtoModelEnumInt(readProtoVarint(buf, state, pecEnd)); + } else { + skipProtoField(buf, state, pTag & 7, pecEnd); + } + } + state.off = pecEnd; + if (execModel) pc.planExecuteConfig = { executionModel: execModel }; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return Object.keys(pc).length > 0 ? pc : null; +} + +function decodeProtoGeneratorMeta(rawBlob, includeBreakdown = true) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return null; + const state = { off: 0 }; + const end = buf.length; const stepIndices = []; let chatDecoded = null; + let plannerConfig = null; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 2 && wt === 0) { - stepIndices.push(Number(readProtoVarint(buf, st))); + stepIndices.push(Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)))); } else if (fn === 2 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const end = st.off + len; - while (st.off < end) { - stepIndices.push(Number(readProtoVarint(buf, st))); + const pEnd = readSubEnd(buf, state, end); + while (state.off < pEnd) { + stepIndices.push(Number(BigInt.asUintN(32, readProtoVarint(buf, state, pEnd)))); } + state.off = pEnd; } else if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - chatDecoded = decodeProtoChatModelMeta(buf.subarray(st.off, st.off + len)); - st.off += len; + chatDecoded = decodeProtoChatModelMetaSlice( + buf, + state, + readSubEnd(buf, state, end), + includeBreakdown + ); + } else if (fn === 3 && wt === 2) { + plannerConfig = decodeProtoPlannerConfigSlice(buf, state, readSubEnd(buf, state, end)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } - if (!chatDecoded) return null; + if (!chatDecoded && !plannerConfig) return null; return { stepIndices, - chatModel: chatDecoded.chatModel, - extraMeta: chatDecoded.extraMeta, + ...(chatDecoded ? { chatModel: chatDecoded.chatModel } : {}), + ...(plannerConfig ? { plannerConfig } : {}), + extraMeta: chatDecoded?.extraMeta || {}, }; } -function decodeProtoStepMeta(buf, fallbackIdx) { - const st = { off: 0 }; +function decodeProtoToolCallSlice(buf, state, end, includeArgs = true) { + const tc = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + tc.id = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + tc.name = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + if (includeArgs) { + tc.argumentsJson = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return tc; +} + +function decodeProtoStepMeta(rawBlob, fallbackIdx) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) { + return { sourceTrajectoryStepInfo: { stepIndex: fallbackIdx, cascadeId: '' } }; + } + const state = { off: 0 }; + const end = buf.length; + let createdAt = ''; let viewableAt = ''; let finishedGeneratingAt = ''; let completedAt = ''; + let startedAt = ''; let modelUsage = null; let generatorModel = ''; + let toolCall = null; + let retryInfos = null; + let toolSummary = ''; let stepIndex = fallbackIdx; + let sawStepIndex = false; + let originCascadeId = ''; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - createdAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + createdAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 4 && wt === 2) { + toolCall = decodeProtoToolCallSlice(buf, state, readSubEnd(buf, state, end), true); } else if (fn === 6 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - viewableAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + viewableAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 7 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - finishedGeneratingAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; - } else if (fn === 32 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - completedAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + finishedGeneratingAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 8 && wt === 2) { + completedAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 9 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - modelUsage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); - st.off += len; + modelUsage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 11 && wt === 0) { - generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); } else if (fn === 20 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const siBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const siSt = { off: 0 }; - while (siSt.off < siBuf.length) { - const siTag = Number(readProtoVarint(siBuf, siSt)); + const siEnd = readSubEnd(buf, state, end); + while (state.off < siEnd) { + const siTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, siEnd))); const siFn = siTag >>> 3; const siWt = siTag & 7; if (siFn === 2 && siWt === 0) { - stepIndex = Number(readProtoVarint(siBuf, siSt)); + stepIndex = Number(BigInt.asUintN(32, readProtoVarint(buf, state, siEnd))); + sawStepIndex = true; + } else if (siFn === 4 && siWt === 2) { + originCascadeId = readProtoString(buf, state, siEnd).trim().toLowerCase(); } else { - skipProtoField(siBuf, siSt, siWt); + skipProtoField(buf, state, siWt, siEnd); } } + state.off = siEnd; + } else if (fn === 28 && wt === 2) { + const riEnd = readSubEnd(buf, state, end); + const ri = {}; + while (state.off < riEnd) { + const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, riEnd))); + const rFn = rTag >>> 3; + const rWt = rTag & 7; + if (rFn === 2 && rWt === 2) { + ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, riEnd)); + } else { + skipProtoField(buf, state, rWt, riEnd); + } + } + state.off = riEnd; + if (!retryInfos) retryInfos = []; + retryInfos.push(ri); + } else if (fn === 30 && wt === 2) { + toolSummary = readProtoString(buf, state, end); + } else if (fn === 32 && wt === 2) { + startedAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } @@ -779,105 +1524,616 @@ function decodeProtoStepMeta(buf, fallbackIdx) { ...(createdAt ? { createdAt } : {}), ...(viewableAt ? { viewableAt } : {}), ...(finishedGeneratingAt ? { finishedGeneratingAt } : {}), - ...(completedAt ? { completedAt } : {}), + ...(completedAt ? { completedAt } : startedAt && !finishedGeneratingAt ? { completedAt: startedAt } : {}), + ...(startedAt ? { startedAt } : {}), ...(generatorModel ? { generatorModel } : {}), - sourceTrajectoryStepInfo: { stepIndex }, + ...(toolCall ? { toolCall } : {}), + ...(retryInfos ? { retryInfos } : {}), + ...(toolSummary ? { toolSummary } : {}), + sourceTrajectoryStepInfo: { + stepIndex: sawStepIndex ? stepIndex : fallbackIdx, + ...(originCascadeId ? { cascadeId: originCascadeId } : {}), + }, ...(modelUsage ? { modelUsage } : {}), }; } +function hasNonWhitespaceUtf8(buf, start, end) { + for (let i = start; i < end; i++) { + const b = buf[i]; + if (b !== 0x20 && b !== 0x09 && b !== 0x0a && b !== 0x0d) return true; + } + return false; +} + +function decodeProtoPlannerResponseSlice(buf, state, end, keepFullText) { + const pr = {}; + let hasText = false; + let toolCalls = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if ((fn === 1 || fn === 8) && wt === 2) { + if (keepFullText) { + const str = readProtoString(buf, state, end); + if (str) { + if (fn === 1) pr.response = str; + else pr.modifiedResponse = str; + } + } else { + const sEnd = readSubEnd(buf, state, end); + if (!hasText && hasNonWhitespaceUtf8(buf, state.off, sEnd)) { + hasText = true; + } + state.off = sEnd; + } + } else if ((fn === 3 || fn === 16) && wt === 2) { + if (keepFullText) { + const str = readProtoString(buf, state, end); + if (str) { + if (fn === 3) pr.thinking = str; + else pr.rawThinking = str; + } + } else { + skipProtoField(buf, state, wt, end); + } + } else if (fn === 7 && wt === 2) { + if (!toolCalls) toolCalls = []; + toolCalls.push(decodeProtoToolCallSlice(buf, state, readSubEnd(buf, state, end), keepFullText)); + } else if (fn === 11 && wt === 2) { + const dur = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + if (dur) pr.thinkingDuration = dur; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (!keepFullText && hasText) { + pr.response = '1'; + } + if (toolCalls) { + pr.toolCalls = toolCalls; + } + return pr; +} + +function decodeProtoUserInputSlice(buf, state, end) { + let query = ''; + let userResponse = ''; + const items = []; + let hasMedia = false; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + query = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + userResponse = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + const itEnd = readSubEnd(buf, state, end); + let itemText = ''; + while (state.off < itEnd) { + const iTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, itEnd))); + if ((iTag >>> 3) === 1 && (iTag & 7) === 2) { + itemText = readProtoString(buf, state, itEnd); + } else { + skipProtoField(buf, state, iTag & 7, itEnd); + } + } + state.off = itEnd; + if (itemText) items.push({ text: itemText }); + } else if ((fn === 4 || fn === 5 || fn === 6) && wt === 2) { + const mEnd = readSubEnd(buf, state, end); + if (mEnd > state.off) hasMedia = true; + state.off = mEnd; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + + const primaryText = userResponse || query || items.map((x) => x.text).join('\n') || ''; + if (!primaryText && !hasMedia) return null; + return { + ...(primaryText ? { userResponse: primaryText } : {}), + ...(items.length > 0 ? { items } : {}), + ...(hasMedia ? { media: [{}] } : {}), + }; +} + +function decodeProtoInvokeSubagentSlice(buf, state, end) { + const subagents = []; + const results = []; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + const spec = decodeProtoSubagentSpecSlice(buf, state, readSubEnd(buf, state, end)); + subagents.push(spec || { typeName: '', role: '' }); + } else if (fn === 2 && wt === 2) { + const resEnd = readSubEnd(buf, state, end); + let conversationId = ''; + while (state.off < resEnd) { + const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); + if ((rTag >>> 3) === 1 && (rTag & 7) === 2) { + conversationId = readProtoString(buf, state, resEnd).trim().toLowerCase(); + } else { + skipProtoField(buf, state, rTag & 7, resEnd); + } + } + state.off = resEnd; + results.push({ conversationId }); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { subagents, results }; +} + +function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { + let invokeSubagent = null; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 2 && wt === 2) { + const resEnd = readSubEnd(buf, state, end); + while (state.off < resEnd) { + const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); + if ((resTag >>> 3) === 6 && (resTag & 7) === 2) { + const anyEnd = readSubEnd(buf, state, resEnd); + let typeUrl = ''; + let valStart = 0; + let valEnd = 0; + while (state.off < anyEnd) { + const aTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, anyEnd))); + if ((aTag >>> 3) === 1 && (aTag & 7) === 2) { + typeUrl = readProtoString(buf, state, anyEnd); + } else if ((aTag >>> 3) === 2 && (aTag & 7) === 2) { + valEnd = readSubEnd(buf, state, anyEnd); + valStart = state.off; + state.off = valEnd; + } else { + skipProtoField(buf, state, aTag & 7, anyEnd); + } + } + state.off = anyEnd; + if ( + valEnd > valStart && + (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || + typeUrl === 'exa.cortex.core.tools.InvokeSubagent') + ) { + invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + } + } else { + skipProtoField(buf, state, resTag & 7, resEnd); + } + } + state.off = resEnd; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return invokeSubagent; +} + +function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagent, keepFullText }) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return {}; + const state = { off: 0 }; + const end = buf.length; + const out = {}; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 19 && wt === 2 && stepTypeNum === 14) { + const ui = decodeProtoUserInputSlice(buf, state, readSubEnd(buf, state, end)); + if (ui) out.userInput = ui; + } else if (fn === 20 && wt === 2 && stepTypeNum === 15) { + out.plannerResponse = decodeProtoPlannerResponseSlice( + buf, + state, + readSubEnd(buf, state, end), + keepFullText + ); + } else if (fn === 140 && wt === 2 && isInvokeSubagent) { + const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); + if (inv) out.invokeSubagent = inv; + } else if (fn === 143 && wt === 2 && isInvokeSubagent) { + out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + return out; +} + +function isInvokeSubagentToolName(rawName) { + return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim()); +} + +function mapRunningGenericToolStepType(rawToolName) { + const name = String(rawToolName || '') + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); + if (!name) return 'CORTEX_STEP_TYPE_GENERIC'; + if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND'; + if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS'; + if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT'; + if ( + name === 'read_file' || + name === 'view_file' || + name === 'view_file_outline' || + name === 'view_code_item' + ) { + return 'CORTEX_STEP_TYPE_VIEW_FILE'; + } + if ( + name === 'edit_file' || + name === 'write_file' || + name === 'write_to_file' || + name === 'replace_file_content' || + name === 'multi_replace_file_content' + ) { + return 'CORTEX_STEP_TYPE_CODE_ACTION'; + } + if (name === 'grep_search' || name === 'ripgrep') return 'CORTEX_STEP_TYPE_GREP_SEARCH'; + if (name === 'find_by_name') return 'CORTEX_STEP_TYPE_FIND'; + if (name === 'list_dir') return 'CORTEX_STEP_TYPE_LIST_DIRECTORY'; + if (name === 'search_web') return 'CORTEX_STEP_TYPE_SEARCH_WEB'; + if (name === 'read_url_content' || name === 'fetch_url') return 'CORTEX_STEP_TYPE_READ_URL_CONTENT'; + if (name === 'ask_question') return 'CORTEX_STEP_TYPE_ASK_QUESTION'; + if (name === 'call_mcp_tool' || name.startsWith('mcp_') || name.startsWith('mcp-')) { + return 'CORTEX_STEP_TYPE_MCP_TOOL'; + } + if (name === 'list_resources') return 'CORTEX_STEP_TYPE_LIST_RESOURCES'; + if (name === 'read_resource') return 'CORTEX_STEP_TYPE_READ_RESOURCE'; + return 'CORTEX_STEP_TYPE_GENERIC'; +} + +function cleanShortPromptTitle(rawText, maxChars = 80) { + const withoutTags = String(rawText || '') + .replace(/[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '') + .replace(/[\s\S]*$/i, '') + .replace(/[\s\S]*$/i, ''); + const reqMatch = withoutTags.match(/([\s\S]*?)<\/USER_REQUEST>/i); + const target = reqMatch ? reqMatch[1] : withoutTags; + const singleLine = target.replace(/\s+/g, ' ').trim(); + if (!singleLine) return ''; + return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`; +} + +function hasContextBreakdownPayload(chat) { + if (!chat || typeof chat !== 'object') return false; + return Boolean( + chat.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown?.groups?.length || + chat.promptSections?.length || + chat.tools?.length || + chat.messagePrompts?.length + ); +} + /** - * 从单个会话的本地 SQLite 数据库(`/conversations/.db`)提取步骤元数据与生成器元数据。 - * 严格只查询 `steps.metadata` 与 `gen_metadata.data`,不加载 `step_payload` 大字段。 + * 从单个会话的本地 SQLite 数据库(`/conversations/.db`)提取步骤元数据、按需载荷与生成器元数据。 + * 自动过滤分叉/旁路提问克隆自父会话的步骤(`originCid !== cascadeId`),并按需解码末尾上下文拆解。 * * @param {string} dbFilePath - * @returns {{ - * steps: Array<{ idx: number, type: string, status: string, metadata: object }>, - * generatorMetadata: Array<{ stepIndices: number[], chatModel: object }>, - * rootConversationId: string, - * parentConversationId: string - * } | null} + * @param {{ cascadeId?: string, isRunning?: boolean }} [options={}] */ -export function readLocalSqliteTrajectory(dbFilePath) { +export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (!dbFilePath || !existsSync(dbFilePath)) return null; const DatabaseSync = getNodeSqliteDatabaseSync(); if (!DatabaseSync) return null; - let db = null; - try { - db = new DatabaseSync(dbFilePath, { readOnly: true }); - const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all(); - const generatorMetadata = []; - const genByStep = new Map(); - let rootConversationId = ''; - let parentConversationId = ''; - - for (const row of genRows || []) { - if (!row?.data) continue; - try { - const decoded = decodeProtoGeneratorMeta(Buffer.from(row.data)); - if (!decoded) continue; - const gmItem = { - stepIndices: decoded.stepIndices, - chatModel: decoded.chatModel, - }; - generatorMetadata.push(gmItem); - for (const sIdx of decoded.stepIndices) { - genByStep.set(Number(sIdx), gmItem); - } - if (!rootConversationId && decoded.extraMeta?.root_cascade_id) { - rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase(); - } - if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) { - parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase(); - } - } catch { - // 忽略单条损坏的 generatorMetadata - } - } - - const stepRows = db - .prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC') - .all(); - const steps = []; - for (const row of stepRows || []) { - const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : steps.length; - const type = decodeProtoStepTypeEnum(row?.step_type); - const status = decodeProtoStepStatusEnum(row?.status); - let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } }; - if (row?.metadata && row.metadata.byteLength > 0) { - try { - metadata = decodeProtoStepMeta(Buffer.from(row.metadata), idx); - } catch { - // 忽略单步元数据解码异常 - } - } - const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? idx; - const gm = genByStep.get(Number(stepIdx)); - if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) { - metadata.modelUsage.model = gm.chatModel.model; - } - steps.push({ idx, type, status, metadata }); - } - - if (steps.length === 0 && generatorMetadata.length === 0) { - return null; - } - return { - steps, - generatorMetadata, - rootConversationId, - parentConversationId, - }; - } catch { - return null; - } finally { - if (db) { - try { - db.close(); - } catch { - // 忽略关闭异常 - } + let normCid = String(options?.cascadeId || '') + .trim() + .toLowerCase(); + if (!normCid) { + const stem = basename(dbFilePath).replace(/\.db$/i, '').trim().toLowerCase(); + if (UUID_FILE_RE.test(stem)) { + normCid = stem; } } + const isRunning = Boolean(options?.isRunning); + + try { + return withReadOnlySqliteDb(dbFilePath, (db) => { + let trajectoryType = 0; + try { + const metaRow = db + .prepare( + 'SELECT trajectory_id, cascade_id, trajectory_type, source FROM trajectory_meta LIMIT 1' + ) + .get(); + if (!normCid && metaRow?.cascade_id) { + normCid = String(metaRow.cascade_id).trim().toLowerCase(); + } + trajectoryType = Number(metaRow?.trajectory_type || 0); + } catch { + // 兼容未包含 trajectory_meta 表的精简库 + } + const isSideQuestion = trajectoryType === 22; + + let trajectoryMetadata = { + createdAt: '', + parentConversationId: '', + rootConversationId: '', + nestingDepth: 0, + subagentSpec: null, + agentScript: null, + }; + try { + const blobRow = db + .prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1") + .get(); + const blobBuf = toUint8Array(blobRow?.data); + if (blobBuf && blobBuf.length > 0) { + trajectoryMetadata = decodeProtoTrajectoryMetadataSlice( + blobBuf, + { off: 0 }, + blobBuf.length + ); + } + } catch { + // 兼容未包含 trajectory_metadata_blob 表的库 + } + + let forkParentConversationId = ''; + try { + const refRows = db.prepare('SELECT idx, data FROM parent_references ORDER BY idx ASC').all(); + for (const refRow of refRows || []) { + const refBuf = toUint8Array(refRow?.data); + if (!refBuf || refBuf.length === 0) continue; + const st = { off: 0 }; + let refCid = ''; + while (st.off < refBuf.length) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(refBuf, st, refBuf.length))); + if ((tag >>> 3) === 6 && (tag & 7) === 2) { + refCid = readProtoString(refBuf, st, refBuf.length).trim().toLowerCase(); + } else { + skipProtoField(refBuf, st, tag & 7, refBuf.length); + } + } + if (refCid && (!normCid || refCid !== normCid)) { + forkParentConversationId = refCid; + } + } + } catch { + // 兼容未包含 parent_references 表的库 + } + + const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all(); + const ownGenRecords = []; + let rootConversationId = trajectoryMetadata.rootConversationId || ''; + let parentConversationId = trajectoryMetadata.parentConversationId || ''; + + for (const row of genRows || []) { + if (!row?.data) continue; + try { + const decoded = decodeProtoGeneratorMeta(row.data, false); + if (!decoded) continue; + const gmCid = String(decoded.extraMeta?.cascade_id || '') + .trim() + .toLowerCase(); + if (gmCid && normCid && gmCid !== normCid) { + // 过滤旁路提问或会话分叉从父会话克隆来的历史生成器记录 + continue; + } + if (!rootConversationId && decoded.extraMeta?.root_cascade_id) { + rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase(); + } + if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) { + parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase(); + } + ownGenRecords.push({ rawData: row.data, gm: decoded }); + } catch { + // 忽略单条损坏的 generatorMetadata + } + } + + if (ownGenRecords.length > 0) { + const lastRec = ownGenRecords[ownGenRecords.length - 1]; + try { + const fullLast = decodeProtoGeneratorMeta(lastRec.rawData, true); + if (fullLast) lastRec.gm = fullLast; + } catch { + // 保留轻量版本 + } + if (!hasContextBreakdownPayload(lastRec.gm?.chatModel) && ownGenRecords.length >= 2) { + const prevRec = ownGenRecords[ownGenRecords.length - 2]; + try { + const fullPrev = decodeProtoGeneratorMeta(prevRec.rawData, true); + if (fullPrev && hasContextBreakdownPayload(fullPrev.chatModel)) { + prevRec.gm = fullPrev; + } + } catch { + // 保留轻量版本 + } + } + } + + const generatorMetadata = []; + const genByStep = new Map(); + for (const { gm } of ownGenRecords) { + const gmItem = { + stepIndices: gm.stepIndices, + ...(gm.chatModel ? { chatModel: gm.chatModel } : {}), + ...(gm.plannerConfig ? { plannerConfig: gm.plannerConfig } : {}), + }; + generatorMetadata.push(gmItem); + for (const sIdx of gm.stepIndices) { + genByStep.set(Number(sIdx), gmItem); + } + } + + const stepRows = db + .prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC') + .all(); + const ownStepRecords = []; + for (const row of stepRows || []) { + const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : ownStepRecords.length; + const stepTypeNum = Number(row?.step_type || 0); + const statusNum = Number(row?.status || 0); + let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } }; + if (row?.metadata && row.metadata.byteLength > 0) { + try { + metadata = decodeProtoStepMeta(row.metadata, idx); + } catch { + // 忽略单步元数据解码异常 + } + } + const originCid = String(metadata.sourceTrajectoryStepInfo?.cascadeId || '') + .trim() + .toLowerCase(); + if (originCid && normCid && originCid !== normCid) { + // 过滤克隆自父会话的步骤,防止双倍重复计费 + continue; + } + ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata }); + } + + const runningTailStart = isRunning + ? Math.max(0, ownStepRecords.length - 16) + : ownStepRecords.length; + + const payloadIndices = []; + try { + for (let i = 0; i < ownStepRecords.length; i++) { + const rec = ownStepRecords[i]; + const inRunningTail = isRunning && i >= runningTailStart; + const isInvSub = + rec.stepTypeNum === 127 || + (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + if ( + rec.stepTypeNum === 14 || + rec.stepTypeNum === 15 || + isInvSub || + (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) + ) { + payloadIndices.push(rec.idx); + } + } + } catch { + // 忽略索引构建异常 + } + + const payloadByIdx = new Map(); + if (payloadIndices.length > 0) { + try { + for (let off = 0; off < payloadIndices.length; off += SQLITE_IN_CHUNK_SIZE) { + const batch = payloadIndices.slice(off, off + SQLITE_IN_CHUNK_SIZE); + const placeholders = batch.map(() => '?').join(','); + const pRows = db + .prepare(`SELECT idx, step_payload FROM steps WHERE idx IN (${placeholders})`) + .all(...batch); + for (const pRow of pRows || []) { + if (pRow?.step_payload && pRow.step_payload.byteLength > 0) { + payloadByIdx.set(Number(pRow.idx), pRow.step_payload); + } + } + } + } catch { + // 兼容不含 step_payload 列的旧表 + } + } + + let firstOwnUserPrompt = ''; + const steps = []; + for (let i = 0; i < ownStepRecords.length; i++) { + const rec = ownStepRecords[i]; + const inRunningTail = isRunning && i >= runningTailStart; + const isInvSub = + rec.stepTypeNum === 127 || + (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + + let type = ''; + if (isInvSub) { + type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + } else if (rec.stepTypeNum === 132 && inRunningTail) { + type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name); + } else { + type = decodeProtoStepTypeEnum(rec.stepTypeNum); + } + const status = decodeProtoStepStatusEnum(rec.statusNum); + const metadata = rec.metadata; + const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? rec.idx; + const gm = genByStep.get(Number(stepIdx)); + if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) { + metadata.modelUsage.model = gm.chatModel.model; + } + + const stepObj = { idx: rec.idx, type, status, metadata }; + const rawPayload = payloadByIdx.get(rec.idx); + if (rawPayload) { + try { + const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, { + stepTypeNum: rec.stepTypeNum, + isInvokeSubagent: isInvSub, + keepFullText: inRunningTail, + }); + if (decodedPayload.userInput) { + stepObj.userInput = decodedPayload.userInput; + if (!firstOwnUserPrompt && decodedPayload.userInput.userResponse) { + firstOwnUserPrompt = cleanShortPromptTitle( + decodedPayload.userInput.userResponse, + 80 + ); + } + } + if (decodedPayload.plannerResponse) { + stepObj.plannerResponse = decodedPayload.plannerResponse; + } + if (decodedPayload.invokeSubagent) { + stepObj.invokeSubagent = decodedPayload.invokeSubagent; + } + } catch { + // 忽略单步载荷解析异常 + } + } + steps.push(stepObj); + } + + if (steps.length === 0 && generatorMetadata.length === 0 && !isSideQuestion) { + return null; + } + + const mergedMetadata = { + ...trajectoryMetadata, + parentConversationId: trajectoryMetadata.parentConversationId || parentConversationId, + rootConversationId: trajectoryMetadata.rootConversationId || rootConversationId, + }; + + return { + cascadeId: normCid, + numTotalSteps: steps.length, + rawTableStepCount: stepRows.length, + trajectoryType, + isSideQuestion, + forkParentConversationId, + firstOwnUserPrompt, + steps, + generatorMetadata, + rootConversationId: mergedMetadata.rootConversationId, + parentConversationId: mergedMetadata.parentConversationId, + trajectory: { + metadata: mergedMetadata, + steps, + generatorMetadata, + }, + }; + }); + } catch { + return null; + } } diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 83dcc04..0b24faf 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -272,6 +272,55 @@ export const DEFAULT_DOWNLOAD_URL = export const DEFAULT_ARCHIVE_FALLBACK_URL = `https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`; +/** + * 检测当前插件目录是否关联了非官方自定义 GitHub Fork 远端(如二次开发分支)。 + * 命中自定义 Fork 时保留上游价格目录热同步,但将插件版本号与更新包地址锚定至用户自己的 Fork,避免误报更新。 + * + * @returns {string} 自定义 Fork 的 `owner/repo`,未命中或为官方仓库时返回 `''` + */ +export function detectCustomGitForkRepo() { + try { + const dotGitPath = join(PLUGIN_ROOT, '.git'); + if (!existsSync(dotGitPath)) return ''; + let gitConfigPath = join(dotGitPath, 'config'); + if (!existsSync(gitConfigPath)) { + const ptrText = readFileSync(dotGitPath, 'utf8'); + const m = typeof ptrText === 'string' && ptrText.match(/^gitdir:\s*(.+)$/im); + if (m) { + const gitDir = m[1].trim(); + const commonDirFile = join(gitDir, 'commondir'); + if (existsSync(commonDirFile)) { + const relCommon = String(readFileSync(commonDirFile, 'utf8') || '').trim(); + gitConfigPath = join(gitDir, relCommon, 'config'); + } else { + gitConfigPath = join(gitDir, 'config'); + } + } + } + if (!existsSync(gitConfigPath)) return ''; + const cfg = readFileSync(gitConfigPath, 'utf8'); + if (typeof cfg !== 'string' || !cfg) return ''; + const originBlock = cfg.match(/\[remote\s+"origin"\]([\s\S]*?)(?:\r?\n\[|$)/i); + if (!originBlock) return ''; + const urlMatch = originBlock[1].match(/^\s*url\s*=\s*(.+)$/im); + if (!urlMatch) return ''; + const rawUrl = urlMatch[1].trim(); + const ghMatch = rawUrl.match(/github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i); + if (!ghMatch) return ''; + const repo = ghMatch[1]; + const lower = repo.toLowerCase(); + if ( + lower === OFFICIAL_GITHUB_REPO.toLowerCase() || + LEGACY_GITHUB_REPOS.some((r) => r.toLowerCase() === lower) + ) { + return ''; + } + return repo; + } catch { + return ''; + } +} + /** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */ export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000; export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000; @@ -441,11 +490,93 @@ export const trajectoryCache = Object.fromEntries(safeCacheEntries); /** * 缓存状态与外部深层统计缓存 Memo。 + * 运行中会话采用 30 秒节流落盘(转入 IDLE、重建缓存或进程退出时立即刷盘),消除高频文件替换开销。 */ +export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000; + export const cacheState = { needsSave: initialCacheMigrated, + lastSavedAtMs: 0, + flushTimer: null, }; +function cancelPendingCacheFlushTimer() { + if (cacheState.flushTimer) { + try { + clearTimeout(cacheState.flushTimer); + } catch { + // 忽略沙箱无 clearTimeout 异常 + } + cacheState.flushTimer = null; + } +} + +/** + * 立即将当前内存态 `trajectoryCache` 原子刷入磁盘并清理挂起定时器。 + * + * @returns {boolean} + */ +export function flushTrajectoryCacheNow() { + cancelPendingCacheFlushTimer(); + const ok = saveJson(CACHE_FILE, trajectoryCache); + cacheState.needsSave = !ok; + if (ok) { + cacheState.lastSavedAtMs = Date.now(); + } + return ok; +} + +/** + * 按当前是否存在运行中会话决定立即写盘还是 30 秒节流延迟写盘。 + * 默认单元测试沙箱(`lsRuntimeEndpoint.addr === 'test.invalid'`)同步落盘以保持断言确定性。 + * + * @param {{ hasRunningSessions?: boolean, allowThrottleInTest?: boolean }} [options={}] + */ +export function persistTrajectoryCacheIfNeeded({ + hasRunningSessions = false, + allowThrottleInTest = false, +} = {}) { + if ( + (lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest) || + typeof setTimeout !== 'function' + ) { + flushTrajectoryCacheNow(); + return; + } + const nowMs = Date.now(); + const elapsedMs = nowMs - (cacheState.lastSavedAtMs || 0); + if ( + !hasRunningSessions || + cacheState.lastSavedAtMs === 0 || + elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS + ) { + flushTrajectoryCacheNow(); + return; + } + cacheState.needsSave = true; + if (!cacheState.flushTimer) { + const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs); + const timer = setTimeout(() => { + cacheState.flushTimer = null; + if (cacheState.needsSave) { + flushTrajectoryCacheNow(); + } + }, delayMs); + if (timer && typeof timer.unref === 'function') { + timer.unref(); + } + cacheState.flushTimer = timer; + } +} + +if (typeof process !== 'undefined' && typeof process?.once === 'function') { + process.once('exit', () => { + if (cacheState.needsSave) { + flushTrajectoryCacheNow(); + } + }); +} + export const externalDeepStatsMemo = { sig: '', convos: new Map(), @@ -454,6 +585,9 @@ export const externalDeepStatsMemo = { export const localSummaryMemo = { sig: '', byId: new Map(), + available: false, + summariesObj: {}, + sideQuestionParents: {}, }; /** 并发请求去重表(防止同一参数并发重复拉取)。 */ @@ -502,14 +636,19 @@ export const pluginUpdateState = { * @returns {boolean} 是否成功写回空白缓存文件 */ export function clearRuntimeCaches() { + cancelPendingCacheFlushTimer(); for (const key of Object.keys(trajectoryCache)) { delete trajectoryCache[key]; } cacheState.needsSave = false; + cacheState.lastSavedAtMs = 0; externalDeepStatsMemo.sig = ''; externalDeepStatsMemo.convos.clear(); localSummaryMemo.sig = ''; localSummaryMemo.byId.clear(); + localSummaryMemo.available = false; + localSummaryMemo.summariesObj = {}; + localSummaryMemo.sideQuestionParents = {}; quotaSummaryCache.ts = 0; quotaSummaryCache.lastAttemptTs = 0; quotaSummaryCache.accountName = ''; diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 9e179c0..5161513 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -21,7 +21,6 @@ import { ANNOTATION_DIRS, BRAIN_DIR, BRAIN_DIRS, - CACHE_FILE, CACHE_SCHEMA_VERSION, CONVERSATIONS_DIR, CONVERSATION_DIRS, @@ -29,10 +28,11 @@ import { cacheState, externalDeepStatsMemo, loadJson, - saveJson, + persistTrajectoryCacheIfNeeded, trajectoryCache, } from './config.mjs'; import { + computeSqliteWalSig, hasBuiltinNodeSqlite, readAnnotationTitleForCascade, readLocalSqliteTrajectory, @@ -348,26 +348,135 @@ function hasLocalSqliteDb(diskFiles = []) { return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || ''))); } -function findBestSqliteDbPath(diskFiles = []) { - if (!Array.isArray(diskFiles) || diskFiles.length === 0) return ''; - let bestPath = ''; - let bestMtime = -1; +function resolveBestSqliteDbInfo(diskFiles = []) { + if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null; + let best = null; for (const rawPath of diskFiles) { const p = String(rawPath || '').trim(); if (!/\.db$/i.test(p)) continue; const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p); - if (!existsSync(fullPath)) continue; - try { - const mtime = Number(statSync(fullPath)?.mtimeMs || 0); - if (mtime > bestMtime) { - bestMtime = mtime; - bestPath = fullPath; - } - } catch { - if (!bestPath) bestPath = fullPath; + const walInfo = computeSqliteWalSig(fullPath); + if (!walInfo.exists) continue; + if (!best || walInfo.mtimeMs > best.mtimeMs) { + best = { + dbPath: fullPath, + mtimeMs: walInfo.mtimeMs, + sig: walInfo.sig, + }; } } - return bestPath; + return best; +} + +function findBestSqliteDbPath(diskFiles = []) { + return resolveBestSqliteDbInfo(diskFiles)?.dbPath || ''; +} + +function inferAppSourceFromSummary(sourceEnum = '', diskFiles = [], fallback = '') { + const fromDisk = inferConversationAppSource(diskFiles, null); + if (fromDisk) return fromDisk; + const src = String(sourceEnum || '').toUpperCase(); + if (src.includes('CLI')) return 'cli'; + if (src.includes('VSCODE') || src.includes('JETBOX') || src.includes('VISUAL_STUDIO')) { + return 'ide'; + } + return fallback || 'standalone'; +} + +function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) { + if (!cidLower || !Array.isArray(sqliteSteps) || sqliteSteps.length === 0) { + return { firstUserTitle: '' }; + } + const needsTranscriptBackfill = sqliteSteps.some( + (s) => + (s?.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !s.userInput) || + (s?.metadata?.modelUsage && !s.metadata.modelUsage.model) + ); + if (!needsTranscriptBackfill) { + return { firstUserTitle: '' }; + } + const transcriptPath = findTranscriptPath(cidLower); + if (!transcriptPath || !existsSync(transcriptPath)) { + return { firstUserTitle: '' }; + } + let raw = ''; + try { + raw = readFileSync(transcriptPath, 'utf8'); + } catch { + return { firstUserTitle: '' }; + } + if (typeof raw !== 'string' || !raw.trim()) { + return { firstUserTitle: '' }; + } + + let firstUserTitle = ''; + const byStepIdx = new Map(); + let lineOrdinal = 0; + for (const rawLine of raw.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (!parsed || typeof parsed !== 'object') continue; + const idx = Number.isFinite(Number(parsed.step_index)) + ? Number(parsed.step_index) + : lineOrdinal; + lineOrdinal += 1; + byStepIdx.set(idx, parsed); + const upperType = String(parsed.type || '').trim().toUpperCase(); + if ( + !firstUserTitle && + (upperType === 'USER_INPUT' || + upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || + (parsed.userInput && typeof parsed.userInput === 'object')) + ) { + firstUserTitle = extractOfflineUserTitle( + typeof parsed.content === 'string' + ? parsed.content + : parsed.userInput?.userResponse || '' + ); + } + } catch { + // 忽略损坏 JSON 行 + } + } + + let maxSqliteIdx = -1; + for (const sq of sqliteSteps) { + const sIdx = Number(sq?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? sq?.idx); + if (Number.isFinite(sIdx) && sIdx > maxSqliteIdx) maxSqliteIdx = sIdx; + const tLine = byStepIdx.get(sIdx); + if (!tLine) continue; + if (sq.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !sq.userInput) { + if (typeof tLine.content === 'string') sq.content = tLine.content; + if (tLine.userInput) sq.userInput = tLine.userInput; + if (Array.isArray(tLine.media)) sq.media = tLine.media; + } else if (sq.metadata?.modelUsage && !sq.metadata.modelUsage.model) { + const fallbackModel = String(tLine.model || tLine.generator_model || '').trim(); + if (fallbackModel) sq.metadata.modelUsage.model = fallbackModel; + } + } + + return { firstUserTitle }; +} + +function filterClonedTrajectorySteps(rawSteps, generatorMeta, targetCidLower) { + if (!targetCidLower) { + return { steps: rawSteps || [], generatorMeta: generatorMeta || [] }; + } + const filteredSteps = (rawSteps || []).filter((s) => { + const originCid = String(s?.metadata?.sourceTrajectoryStepInfo?.cascadeId || '') + .trim() + .toLowerCase(); + return !originCid || originCid === targetCidLower; + }); + const filteredGen = (generatorMeta || []).filter((gm) => { + const gmCid = String(gm?.chatModel?.customMetadata?.cascade_id || '') + .trim() + .toLowerCase(); + return !gmCid || gmCid === targetCidLower; + }); + return { steps: filteredSteps, generatorMeta: filteredGen }; } /** @@ -1017,6 +1126,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) { */ export async function enumerateAndSyncConversations({ summariesObj = {}, + sideQuestionParents = {}, currentAccountName = '', requestedConvId = '', forceRefresh = false, @@ -1038,6 +1148,7 @@ export async function enumerateAndSyncConversations({ const diskConvMap = discoverLocalConversationFiles(); // 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC) + const mergedSideQuestionParents = { ...(sideQuestionParents || {}) }; const canonicalIdByLower = new Map(); const summariesByLower = new Map(); for (const [rawId, summary] of Object.entries(summariesObj || {})) { @@ -1045,6 +1156,42 @@ export async function enumerateAndSyncConversations({ if (!lower) continue; canonicalIdByLower.set(lower, rawId); summariesByLower.set(lower, summary); + + const sqIds = summary?.annotations?.sideQuestionCascadeIds; + const sqTitles = summary?.annotations?.sideQuestionTitles || {}; + if (Array.isArray(sqIds)) { + for (const sqId of sqIds) { + const sqLower = String(sqId || '').trim().toLowerCase(); + if (!sqLower) continue; + mergedSideQuestionParents[sqLower] = { + parentConversationId: lower, + title: String(sqTitles[sqLower] || mergedSideQuestionParents[sqLower]?.title || ''), + }; + } + } + if (sqTitles && typeof sqTitles === 'object') { + for (const [sqKey, sqTitle] of Object.entries(sqTitles)) { + const sqLower = String(sqKey || '').trim().toLowerCase(); + if (!sqLower) continue; + const prevSq = mergedSideQuestionParents[sqLower]; + mergedSideQuestionParents[sqLower] = { + parentConversationId: prevSq?.parentConversationId || lower, + title: String(sqTitle || prevSq?.title || ''), + }; + } + } + const isSummarySideQ = + Boolean(summary?.isSideQuestion) || + Number(summary?.trajectoryType) === 22 || + summary?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION'; + const forkParent = String(summary?.forkParentConversationId || '').trim().toLowerCase(); + if (isSummarySideQ && forkParent) { + const prevSq = mergedSideQuestionParents[lower]; + mergedSideQuestionParents[lower] = { + parentConversationId: prevSq?.parentConversationId || forkParent, + title: String(prevSq?.title || summary?.annotations?.title || ''), + }; + } } for (const rawCacheKey of Object.keys(trajectoryCache)) { @@ -1095,6 +1242,7 @@ export async function enumerateAndSyncConversations({ } const localSummaryByLower = readLocalSummaryIndex(); + const sqliteAvailable = hasBuiltinNodeSqlite(); const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; @@ -1109,31 +1257,78 @@ export async function enumerateAndSyncConversations({ ) { continue; } + const diskFiles = diskConvMap.get(cidLower) || []; + const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null; + const dbPath = sqliteDbInfo?.dbPath || ''; + const diskFileSig = sqliteDbInfo?.sig || ''; const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || ''; const summaryMtimeMs = parseIsoMs(lastModifiedTime); - const diskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskConvMap.get(cidLower)); + const rawDiskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskFiles); + const diskMtimeMs = sqliteDbInfo + ? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0) + : rawDiskMtimeMs; + const appSource = inferAppSourceFromSummary( + item?.source || '', + diskFiles, + cached?.appSource || 'standalone' + ); + + const sqParentInfo = mergedSideQuestionParents[cidLower] || null; + const isSideQuestion = Boolean( + sqParentInfo || + item?.isSideQuestion || + Number(item?.trajectoryType) === 22 || + item?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION' || + localSum?.isSideQuestion || + Number(localSum?.trajectoryType) === 22 || + cached?.isSideQuestion || + cached?.subagentSpec?.typeName === 'side_question' + ); + const rawMeta = item?.trajectoryMetadata || item?.metadata || {}; const parentConversationId = String( rawMeta.parentConversationId || + sqParentInfo?.parentConversationId || + item?.forkParentConversationId || localSum?.parentConversationId || + localSum?.forkParentConversationId || cached?.parentConversationId || '' ).toLowerCase(); - const rootConversationId = String( - rawMeta.rootConversationId || cached?.rootConversationId || parentConversationId || '' - ).toLowerCase(); + const rawRootCid = String( + rawMeta.rootConversationId || localSum?.rootConversationId || '' + ) + .trim() + .toLowerCase(); + const cachedRootCid = String(cached?.rootConversationId || '').trim().toLowerCase(); + const rootConversationId = + (rawRootCid && rawRootCid !== cidLower ? rawRootCid : '') || + (cachedRootCid && cachedRootCid !== cidLower ? cachedRootCid : '') || + parentConversationId || + ''; const localAgentSpec = - parentConversationId && localSum?.agentName ? { role: localSum.agentName } : null; + parentConversationId && (localSum?.subagentSpec || localSum?.agentName) + ? localSum.subagentSpec || { role: localSum.agentName } + : null; + const primarySpec = isSideQuestion + ? { + typeName: 'side_question', + role: String(sqParentInfo?.title || item?.annotations?.title || localSum?.title || '').trim(), + } + : rawMeta.subagentSpec; const subagentSpec = mergeSubagentSpecs( - rawMeta.subagentSpec, + primarySpec, mergeSubagentSpecs(localAgentSpec, cached?.subagentSpec) ); const agentScriptName = rawMeta.agentScript?.name || cached?.agentScriptName || ''; const createdTimeMs = - parseIsoMs(item?.createdTime || rawMeta?.createdAt) || cached?.createdTimeMs || 0; + parseIsoMs(item?.createdTime || rawMeta?.createdAt || localSum?.createdTime) || + cached?.createdTimeMs || + 0; const spawnOrder = Number.isFinite(cached?.spawnOrder) ? cached.spawnOrder : null; const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null; const isSubagent = + isSideQuestion || Boolean(parentConversationId) || Boolean(rootConversationId && rootConversationId !== cidLower); const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0); @@ -1150,19 +1345,29 @@ export async function enumerateAndSyncConversations({ const rawSummaryStepCount = Number(item?.stepCount || 0); const modelStepCount = Array.isArray(cached?.steps) ? cached.steps.length - : rawSummaryStepCount; + : isSideQuestion + ? 0 + : rawSummaryStepCount; rawConversations.push({ cascadeId, title: - item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8), + sqParentInfo?.title || + item?.annotations?.title || + item?.summary || + cached?.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: modelStepCount, rawStepCount: rawSummaryStepCount, status: item?.status || '', lastModifiedTime, lastModifiedMs, diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: true, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1176,9 +1381,13 @@ export async function enumerateAndSyncConversations({ const cachedStepCount = Number(cached.steps?.length || 0); rawConversations.push({ cascadeId, - title: localSum?.title || cached.title || cascadeId.slice(0, 8), + title: + sqParentInfo?.title || + localSum?.title || + cached.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: cachedStepCount, - rawStepCount: localSum?.stepCount || cachedStepCount, + rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount, status: localStatus, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max( @@ -1188,8 +1397,12 @@ export async function enumerateAndSyncConversations({ localSum?.lastModifiedMs || 0 ), diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: false, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1201,16 +1414,23 @@ export async function enumerateAndSyncConversations({ } else { rawConversations.push({ cascadeId, - title: localSum?.title || cascadeId.slice(0, 8), + title: + sqParentInfo?.title || + localSum?.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: 0, rawStepCount: localSum?.stepCount || 0, status: localStatus, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0), diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: false, needsInitialLoad: true, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1228,6 +1448,9 @@ export async function enumerateAndSyncConversations({ const nowPollMs = Date.now(); function buildConvSig(conv) { + if (conv.dbPath && conv.diskFileSig && sqliteAvailable) { + return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}`; + } return conv.inSummaries ? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}` : `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`; @@ -1306,38 +1529,126 @@ export async function enumerateAndSyncConversations({ let partialTailSteps = []; let hasTailStepInfo = false; try { - const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + const cidLower = conv.cascadeId.toLowerCase(); + let trajRes = null; + let loadedViaSqlite = false; + let transcriptFirstTitle = ''; + if (conv.dbPath && sqliteAvailable) { + const sqlRes = readLocalSqliteTrajectory(conv.dbPath, { + cascadeId: conv.cascadeId, + isRunning, + }); + if (sqlRes && Array.isArray(sqlRes.trajectory?.steps)) { + trajRes = sqlRes; + loadedViaSqlite = true; + const enriched = enrichSqliteStepsFromTranscriptIfNeeded( + cidLower, + trajRes.trajectory.steps + ); + transcriptFirstTitle = enriched.firstUserTitle || ''; + } + } + if (!trajRes) { + trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + } if (!Array.isArray(trajRes?.trajectory?.steps)) { throw new Error('Trajectory steps unavailable'); } - const rawSteps = trajRes.trajectory.steps; - if (Number(trajRes.numTotalSteps) > rawSteps.length) { - if (rawSteps.length > 0) { - partialTailSteps = rawSteps; + const rawStepsUnfiltered = trajRes.trajectory.steps; + if (!loadedViaSqlite && Number(trajRes.numTotalSteps) > rawStepsUnfiltered.length) { + if (rawStepsUnfiltered.length > 0) { + partialTailSteps = rawStepsUnfiltered; const tailIdx = - rawSteps[rawSteps.length - 1]?.metadata?.sourceTrajectoryStepInfo?.stepIndex; + rawStepsUnfiltered[rawStepsUnfiltered.length - 1]?.metadata?.sourceTrajectoryStepInfo + ?.stepIndex; hasTailStepInfo = Number.isFinite(Number(tailIdx)); } throw new Error('Incomplete trajectory; retaining cached usage'); } failedFetchCooldownMap.delete(cooldownKey); - const generatorMeta = trajRes?.trajectory?.generatorMetadata || []; + const rawGenMeta = trajRes?.trajectory?.generatorMetadata || []; + const { steps: rawSteps, generatorMeta } = loadedViaSqlite + ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } + : filterClonedTrajectorySteps(rawStepsUnfiltered, rawGenMeta, cidLower); const steps = extractModelSteps(rawSteps, generatorMeta); const nextLast = steps[steps.length - 1]; - // 提取轨迹内携带的子代理归属元数据与派生的子代理引用列表 + // 提取轨迹内携带的子代理归属元数据、旁路提问父归属与派生的子代理引用列表 + const sqParentInfo = mergedSideQuestionParents[cidLower] || null; const extractedMeta = extractTrajectorySubagentMeta(trajRes, conv); - conv.parentConversationId = extractedMeta.parentConversationId; - conv.rootConversationId = extractedMeta.rootConversationId; - conv.subagentSpec = extractedMeta.subagentSpec; - conv.agentScriptName = extractedMeta.agentScriptName; - conv.createdTimeMs = extractedMeta.createdTimeMs; - conv.isSubagent = - Boolean(conv.parentConversationId) || - Boolean( - conv.rootConversationId && - conv.rootConversationId !== conv.cascadeId.toLowerCase() - ); + const detectedSideQuestion = Boolean( + trajRes?.isSideQuestion || + Number(trajRes?.trajectoryType) === 22 || + trajRes?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION' || + conv.isSideQuestion || + sqParentInfo + ); + const defaultShortId = cidLower.slice(0, 8); + const nonShortTitle = (t) => { + const clean = String(t || '').trim(); + return clean && clean.toLowerCase() !== defaultShortId ? clean : ''; + }; + + if (detectedSideQuestion) { + const parentCid = String( + sqParentInfo?.parentConversationId || + trajRes?.forkParentConversationId || + extractedMeta.parentConversationId || + conv.parentConversationId || + '' + ) + .trim() + .toLowerCase(); + const sqTitle = String( + sqParentInfo?.title || + trajRes?.firstOwnUserPrompt || + transcriptFirstTitle || + (prev?.isSideQuestion ? nonShortTitle(prev?.title) : '') || + nonShortTitle(conv.title) || + '' + ).trim(); + const cleanSqRole = sqTitle && sqTitle !== '旁路提问' ? sqTitle : ''; + conv.isSideQuestion = true; + conv.parentConversationId = parentCid; + const extRoot = String(extractedMeta.rootConversationId || '').trim().toLowerCase(); + const prevConvRoot = String(conv.rootConversationId || '').trim().toLowerCase(); + conv.rootConversationId = + (extRoot && extRoot !== cidLower ? extRoot : '') || + (prevConvRoot && prevConvRoot !== cidLower ? prevConvRoot : '') || + parentCid || + ''; + conv.title = cleanSqRole || '旁路提问'; + conv.subagentSpec = { + typeName: 'side_question', + role: cleanSqRole || '旁路提问', + }; + conv.agentScriptName = ''; + conv.createdTimeMs = + extractedMeta.createdTimeMs || steps[0]?.createdAtMs || conv.createdTimeMs || 0; + conv.isSubagent = Boolean(conv.parentConversationId || conv.rootConversationId); + } else { + conv.parentConversationId = extractedMeta.parentConversationId; + conv.rootConversationId = extractedMeta.rootConversationId; + conv.subagentSpec = extractedMeta.subagentSpec; + conv.agentScriptName = extractedMeta.agentScriptName; + conv.createdTimeMs = extractedMeta.createdTimeMs; + conv.isSubagent = + Boolean(conv.parentConversationId) || + Boolean( + conv.rootConversationId && conv.rootConversationId !== cidLower + ); + if (!nonShortTitle(conv.title)) { + const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower)); + const resolvedFallbackTitle = + annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle; + if (resolvedFallbackTitle) { + conv.title = resolvedFallbackTitle; + } + } + } + if (loadedViaSqlite && Number.isFinite(trajRes?.rawTableStepCount) && !conv.inSummaries) { + conv.rawStepCount = trajRes.rawTableStepCount; + } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); conv.subagentRefs = subagentRefs; @@ -1346,6 +1657,7 @@ export async function enumerateAndSyncConversations({ const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs); conv.lastModifiedMs = resolvedLastModMs; conv.stepCount = steps.length; + const finalSig = buildConvSig(conv); const liveAct = resolveBestLiveActivity( conv.cascadeId, @@ -1355,19 +1667,20 @@ export async function enumerateAndSyncConversations({ ); if (liveAct) { conv.liveActivity = liveAct; - liveActivityMemo.set(conv.cascadeId.toLowerCase(), liveAct); + liveActivityMemo.set(cidLower, liveAct); } else { conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + liveActivityMemo.delete(cidLower); } const cacheEntry = { - signature: sig, + signature: finalSig, accountName: prev?.accountName || currentAccountName || '', title: conv.title, lastModifiedMs: resolvedLastModMs, diskMtimeMs: - conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(conv.cascadeId.toLowerCase())), + conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)), + rawStepCount: conv.rawStepCount ?? steps.length, wasRunning: isRunning, contextLimitTelemetry: true, speedClearedTelemetry: true, @@ -1376,6 +1689,13 @@ export async function enumerateAndSyncConversations({ steps, subagentRefs, }; + if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig; + if (conv.appSource && conv.appSource !== 'standalone') { + cacheEntry.appSource = conv.appSource; + } + if (conv.isSideQuestion) { + cacheEntry.isSideQuestion = true; + } if (conv.isSubagent) { cacheEntry.parentConversationId = conv.parentConversationId; cacheEntry.rootConversationId = conv.rootConversationId; @@ -1388,11 +1708,12 @@ export async function enumerateAndSyncConversations({ const metaChanged = !Array.isArray(prev?.subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || - (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || ''); + (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || + Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); const stepsChanged = !prev || Boolean(prev.offlineTranscriptFallback) || - prev.signature !== sig || + prev.signature !== finalSig || Boolean(prev.wasRunning) !== isRunning || !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || @@ -1595,10 +1916,20 @@ export async function enumerateAndSyncConversations({ `${CACHE_SCHEMA_VERSION}:` ); if (!hasCurrentSchema) return true; + if ( + conv.dbPath && + sqliteAvailable && + !String(cached.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:sqlite:`) + ) { + return true; + } if (hasMissingStepFields(cached)) return true; const missingSubagentRefs = !Array.isArray(cached.subagentRefs); if (!conv.inSummaries) { if (isRunning || cached.wasRunning) return true; + if (conv.dbPath && sqliteAvailable) { + return cached.signature !== sig; + } if ( cached.offlineTranscriptFallback && !cached.offlineSqliteTelemetry && @@ -1672,7 +2003,12 @@ export async function enumerateAndSyncConversations({ let subConv = byLowerId.get(subCid); const subCached = trajectoryCache[subConv?.cascadeId || canonSubId]; if (!subConv) { - const diskMtimeMs = readConversationMtime(diskConvMap.get(subCid)); + const subDiskFiles = diskConvMap.get(subCid) || []; + const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null; + const diskMtimeMs = Math.max( + readConversationMtime(subDiskFiles), + subDbInfo?.mtimeMs || 0 + ); const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0; const stepCount = Number(subCached?.steps?.length || 0); subConv = { @@ -1689,9 +2025,13 @@ export async function enumerateAndSyncConversations({ ref.createdTimeMs || 0 ), diskMtimeMs, + dbPath: subDbInfo?.dbPath || '', + diskFileSig: subDbInfo?.sig || '', + appSource: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'), inSummaries: false, needsInitialLoad: !subCached, isSubagent: true, + isSideQuestion: false, parentConversationId: parentId, rootConversationId: rootId, subagentSpec: mergeSubagentSpecs(ref, subCached?.subagentSpec), @@ -1724,7 +2064,11 @@ export async function enumerateAndSyncConversations({ const hasValidSubCache = existingSubCache && !(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) && - String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && + String(existingSubCache.signature || '').startsWith( + subConv.dbPath && sqliteAvailable + ? `${CACHE_SCHEMA_VERSION}:sqlite:` + : `${CACHE_SCHEMA_VERSION}:` + ) && !hasMissingStepFields(existingSubCache) && (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && @@ -1809,6 +2153,9 @@ export async function enumerateAndSyncConversations({ if (!conv.isSubagent) continue; const cid = conv.cascadeId.toLowerCase(); let candidate = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase(); + if (candidate === cid) { + candidate = (conv.parentConversationId || '').toLowerCase(); + } const visited = new Set([cid]); while (candidate && !visited.has(candidate)) { visited.add(candidate); @@ -1832,8 +2179,11 @@ export async function enumerateAndSyncConversations({ } } - if (cacheDirty) { - cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache); + const hasRunningSessions = rawConversations.some( + (c) => c.status === 'CASCADE_RUN_STATUS_RUNNING' + ); + if (cacheDirty || (cacheState.needsSave && !hasRunningSessions)) { + persistTrajectoryCacheIfNeeded({ hasRunningSessions }); } // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要 @@ -1861,12 +2211,28 @@ export async function enumerateAndSyncConversations({ const cid = conv.cascadeId.toLowerCase(); const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase(); const rootTarget = byId.get(rootId); - if (conv.isSubagent) { - if (rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) { + if (conv.isSubagent || conv.isSideQuestion) { + if ( + conv.isSideQuestion && + Number(conv.stepCount || 0) === 0 && + conv.status !== 'CASCADE_RUN_STATUS_RUNNING' && + cid !== reqLower + ) { + continue; + } + if ( + rootId && + rootId !== cid && + rootTarget && + !rootTarget.isSubagent && + !rootTarget.isSideQuestion + ) { if (!subagentsByRoot.has(rootId)) { subagentsByRoot.set(rootId, []); } subagentsByRoot.get(rootId).push(conv); + } else if (conv.isSideQuestion && cid === reqLower) { + conversations.push(conv); } } else { conversations.push(conv); @@ -1877,7 +2243,13 @@ export async function enumerateAndSyncConversations({ const cid = rootConv.cascadeId.toLowerCase(); const subs = subagentsByRoot.get(cid) || []; subs.sort((a, b) => { + const aSide = Boolean(a.isSideQuestion); + const bSide = Boolean(b.isSideQuestion); + if (aSide !== bSide) { + return aSide ? 1 : -1; + } if ( + !aSide && a.parentConversationId === b.parentConversationId && Number.isFinite(a.spawnOrder) && Number.isFinite(b.spawnOrder) && diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index 9c281bc..f44550f 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -131,7 +131,7 @@ export function formatGenericModelSlug(slug = '') { .trim() .replace(/^session-display:/i, ''); if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return ''; - if (/^gemini-4-argon-(?:f|disabled)$/i.test(s)) return 'Gemini 4 Argon'; + if (/^gemini-4-argon-(?:b|f|trial|disabled)$/i.test(s)) return 'Gemini 4 Argon'; if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash'; if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash'; if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash'; diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index c4de037..be91bba 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -23,6 +23,7 @@ import { PLUGIN_ROOT, REMOTE_CATALOG_CACHE_FILE, cloudSyncState, + detectCustomGitForkRepo, loadJson, pluginUpdateState, } from './config.mjs'; @@ -398,10 +399,18 @@ export function rebuildActiveCatalog() { let catalogVersion = 'builtin'; let updatedAt = null; const installedVersion = readInstalledPluginVersion(); + const customForkRepo = detectCustomGitForkRepo(); + const customForkPrefix = customForkRepo ? `/${customForkRepo.toLowerCase()}` : ''; let latestPluginVersion = installedVersion; - let releaseUrl = DEFAULT_RELEASE_URL; - let downloadUrl = DEFAULT_DOWNLOAD_URL; - let archiveFallbackUrl = DEFAULT_ARCHIVE_FALLBACK_URL; + let releaseUrl = customForkRepo + ? `https://github.com/${customForkRepo}/releases/latest` + : DEFAULT_RELEASE_URL; + let downloadUrl = customForkRepo + ? `https://github.com/${customForkRepo}/releases/latest/download/usage-monitor.zip` + : DEFAULT_DOWNLOAD_URL; + let archiveFallbackUrl = customForkRepo + ? `https://codeload.github.com/${customForkRepo}/zip/refs/heads/main` + : DEFAULT_ARCHIVE_FALLBACK_URL; for (const { kind, cat } of layers) { Object.assign(nextPricing, cat.pricing); @@ -411,16 +420,24 @@ export function rebuildActiveCatalog() { } if (cat.catalogVersion) catalogVersion = cat.catalogVersion; if (cat.updatedAt) updatedAt = cat.updatedAt; - if (cat.latestPluginVersion) { - // 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本 + const isFromCustomFork = Boolean( + customForkPrefix && + typeof cat.sourceUrl === 'string' && + cat.sourceUrl.toLowerCase().includes(customForkPrefix) + ); + const shouldAcceptCatalogReleaseMeta = !customForkRepo || isFromCustomFork; + if (shouldAcceptCatalogReleaseMeta && cat.latestPluginVersion) { + // 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本;自定义 Fork 忽略上游版本号 latestPluginVersion = compareSemver(cat.latestPluginVersion, installedVersion) > 0 ? cat.latestPluginVersion : installedVersion; } - if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl; - if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl; - if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; + if (shouldAcceptCatalogReleaseMeta) { + if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl; + if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl; + if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; + } } for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k]; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index e73c7c2..d81e4e3 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -28,6 +28,7 @@ import { trajectoryCache, } from './config.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; +import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs'; @@ -513,6 +514,8 @@ function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, + isSideQuestion = false, + sideIndex = 0, index, shortLabel, badgeText, @@ -540,6 +543,7 @@ function buildAgentUnitTelemetry({ agentRole: role, agentIndex: index, isSubagent: !isMain, + ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), }, reuseInputs ); @@ -561,6 +565,7 @@ function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, + ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), index, shortLabel, badgeText, @@ -607,14 +612,20 @@ function buildAgentUnitTelemetry({ } async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { + const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh }); const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([ - callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), + localSummaries.available + ? Promise.resolve(null) + : callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null, getContextModelCatalog(), ]); const sessions = await enumerateAndSyncConversations({ - summariesObj: allTrajRes?.trajectorySummaries || {}, + summariesObj: localSummaries.available + ? localSummaries.summariesObj + : allTrajRes?.trajectorySummaries || {}, + sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {}, currentAccountName: accountScope, requestedConvId, forceRefresh: forceQuotaRefresh, @@ -751,6 +762,8 @@ export async function buildTelemetryPayloadInternal( let totalFamilyCacheReadTokens = sessionCacheReadTokens; let totalFamilyOutputTokens = sessionOutputTokens; + let normalSubCount = 0; + let sideQuestionCount = 0; for (let idx = 0; idx < subagentSummaries.length; idx++) { const subSum = subagentSummaries[idx]; const subCid = subSum.cascadeId; @@ -760,24 +773,53 @@ export async function buildTelemetryPayloadInternal( for (const step of subRawSteps) allCombinedRawSteps.push(step); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + const isSideQ = Boolean( + subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' + ); const rawRole = subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || ''; const subIndex = idx + 1; - const shortLabel = `子代理 #${subIndex}`; - const badgeText = `子${subIndex}`; - const roleLabel = rawRole || '子代理'; - const typeName = subSpec?.typeName || ''; + let sideIndex = 0; + let shortLabel = ''; + let badgeText = ''; + let roleLabel = ''; + let typeName = ''; + let agentLabel = ''; + if (isSideQ) { + sideIndex = ++sideQuestionCount; + shortLabel = `旁路提问 #${sideIndex}`; + badgeText = `旁${sideIndex}`; + const cleanSideRole = + rawRole && + rawRole !== '旁路提问' && + rawRole !== 'Side Question' && + rawRole !== 'side_question' + ? rawRole + : ''; + roleLabel = cleanSideRole || '旁路提问'; + typeName = 'side_question'; + agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel; + } else { + const subOrd = ++normalSubCount; + shortLabel = `子代理 #${subOrd}`; + badgeText = `子${subOrd}`; + roleLabel = rawRole || '子代理'; + typeName = subSpec?.typeName || ''; + agentLabel = rawRole ? `${shortLabel} · ${rawRole}` : shortLabel; + } const subUnit = buildAgentUnitTelemetry({ agentId: subCid, cascadeId: subCid, isMain: false, + isSideQuestion: isSideQ, + sideIndex, index: subIndex, shortLabel, badgeText, role: roleLabel, typeName, - agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel, + agentLabel, status: subSum.status || 'IDLE', rawSteps: subRawSteps, liveActivity: subSum.liveActivity || null, @@ -882,6 +924,31 @@ export async function buildTelemetryPayloadInternal( .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || latestActiveAgent; + // 汇总视图与自动跟随上下文始终锁定主线(主代理与常规子代理),防止旁路提问抽屉篡改主会话 10 通道上下文水位 + const mainlineAgents = allAgents.filter((a) => !a.isSideQuestion); + const activeMainlineAgent = !latestActiveAgent.isSideQuestion + ? latestActiveAgent + : mainlineAgents.find((a) => a.isRunning) || + mainlineAgents + .slice() + .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || + mainAgentTelemetry; + const mainlineWithSteps = mainlineAgents.filter((a) => a.stepCount > 0); + const contextMetricAgent = !latestMetricAgent.isSideQuestion + ? latestMetricAgent + : mainlineWithSteps.find((a) => a.isRunning) || + mainlineWithSteps + .slice() + .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || + mainAgentTelemetry; + + const aggregatedRoleLabel = + normalSubCount > 0 && sideQuestionCount > 0 + ? `主代理 + ${normalSubCount} 子代理 + ${sideQuestionCount} 旁问` + : sideQuestionCount > 0 + ? `主代理 + ${sideQuestionCount} 旁路提问` + : `主代理 + ${subAgentTelemetries.length} 子代理`; + const totalCostUsd = roundSessionCost(totalRawSessionCostUsd); const totalUnpricedCalls = allAgents.reduce( (sum, a) => sum + (a.sessionUnpricedCalls || 0), @@ -908,6 +975,9 @@ export async function buildTelemetryPayloadInternal( agentRole: activeActivityAgent.role, agentIndex: activeActivityAgent.index, isMain: Boolean(activeActivityAgent.isMain), + ...(activeActivityAgent.isSideQuestion + ? { isSideQuestion: true, sideIndex: activeActivityAgent.sideIndex || 0 } + : {}), parallelCount: runningSubs.length > 1 ? runningSubs.length : 1, } : null; @@ -919,12 +989,12 @@ export async function buildTelemetryPayloadInternal( index: -1, shortLabel: '全部汇总', badgeText: '全部', - role: `主代理 + ${subAgentTelemetries.length} 子代理`, + role: aggregatedRoleLabel, typeName: 'all', - activeAgentId: latestActiveAgent.agentId, - activeAgentShortLabel: latestActiveAgent.shortLabel, - activeAgentBadge: latestActiveAgent.badgeText, - activeAgentRole: latestActiveAgent.role, + activeAgentId: activeMainlineAgent.agentId, + activeAgentShortLabel: activeMainlineAgent.shortLabel, + activeAgentBadge: activeMainlineAgent.badgeText, + activeAgentRole: activeMainlineAgent.role, isRunning: allAgents.some((a) => a.isRunning), status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE', liveActivity: aggregatedLiveActivity, @@ -948,7 +1018,7 @@ export async function buildTelemetryPayloadInternal( activeModelShort: latestMetricAgent.activeModelShort, activeModelLabel: latestMetricAgent.activeModelLabel, activeModelUpstream: latestMetricAgent.activeModelUpstream, - context: latestMetricAgent.context, + context: contextMetricAgent.context, modelBreakdown: combinedModelBreakdown, lastModifiedMs: latestActiveAgent.lastModifiedMs, }; @@ -1273,10 +1343,15 @@ export async function buildTelemetryPayloadInternal( const rootFallbackMs = rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; + let runNormalSubIdx = 0; + let runSideIdx = 0; const subItems = rawSubs.map((subSum, idx) => { const subCid = subSum.cascadeId; const subEntry = findTrajectoryCacheEntry(subCid); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + const isSideQ = Boolean( + subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' + ); const rawRole = subSpec?.role || subSum.agentScriptName || @@ -1284,9 +1359,28 @@ export async function buildTelemetryPayloadInternal( subSpec?.typeName || ''; const subIndex = idx + 1; - const badgeText = `子${subIndex}`; - const shortLabel = `子代理 #${subIndex}`; - const role = rawRole || shortLabel; + let sideIndex = 0; + let badgeText = ''; + let shortLabel = ''; + let role = ''; + if (isSideQ) { + sideIndex = ++runSideIdx; + badgeText = `旁${sideIndex}`; + shortLabel = `旁路提问 #${sideIndex}`; + const cleanSide = + rawRole && + rawRole !== '旁路提问' && + rawRole !== 'Side Question' && + rawRole !== 'side_question' + ? rawRole + : ''; + role = cleanSide || shortLabel; + } else { + const nOrd = ++runNormalSubIdx; + badgeText = `子${nOrd}`; + shortLabel = `子代理 #${nOrd}`; + role = rawRole || shortLabel; + } const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING'; const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0); const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0; @@ -1303,10 +1397,11 @@ export async function buildTelemetryPayloadInternal( return { cascadeId: subCid, index: subIndex, + ...(isSideQ ? { isSideQuestion: true, sideIndex } : {}), badgeText, shortLabel, role, - typeName: subSpec?.typeName || '', + typeName: isSideQ ? 'side_question' : subSpec?.typeName || '', isRunning: isSubRunning, status: subSum.status || 'IDLE', stepCount, diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 4611116..f81688d 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -523,6 +523,11 @@ export function aggregateMultiWindowUsage({ let latestSelectedStepMs = 0; const currentYear = new Date(nowMs).getFullYear(); + const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => + new Date(currentYear, idx, 1).getTime() + ); + const yearStartMs = monthBoundsMs[0]; + const nextYearStartMs = monthBoundsMs[12]; const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ month: idx + 1, label: `${idx + 1}月`, @@ -665,21 +670,25 @@ export function aggregateMultiWindowUsage({ const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens, resolvedCost, savedCost, unpriced }; - if (tMs > 0) { - const stepDate = new Date(tMs); - if (stepDate.getFullYear() === currentYear) { - const mBucket = monthlySeries[stepDate.getMonth()]; - if (mBucket) { - mBucket.calls += 1; - mBucket.inputTokens += inTok; - mBucket.cacheReadTokens += cacheTok; - mBucket.responseTokens += respTok; - mBucket.thinkingTokens += thinkTok; - mBucket.totalTokens += stepTotalTokens; - mBucket.costUsd += resolvedCost; - mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + if (tMs >= yearStartMs && tMs < nextYearStartMs) { + let monthIdx = 11; + for (let m = 0; m < 12; m++) { + if (tMs < monthBoundsMs[m + 1]) { + monthIdx = m; + break; } } + const mBucket = monthlySeries[monthIdx]; + if (mBucket) { + mBucket.calls += 1; + mBucket.inputTokens += inTok; + mBucket.cacheReadTokens += cacheTok; + mBucket.responseTokens += respTok; + mBucket.thinkingTokens += thinkTok; + mBucket.totalTokens += stepTotalTokens; + mBucket.costUsd += resolvedCost; + mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + } } for (const k of presetKeys) { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 6ef5ab6..03aaab4 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index d5a163c..8305be2 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -10,6 +10,7 @@ import { i18nStore, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { fetchTelemetry, + formatAgentBadgeText, normalizeClientUpdateMode, telemetryStore, triggerPluginUpdate, @@ -240,7 +241,7 @@ export const TopSessionHeader = defineComponent({ } else if (isRunning) { const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning); const runSuffix = - hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : ''; + hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : ''; patchSvgIcon(statusIcon, 'bolt'); patchText(statusText, t('header.statusGenerating', { suffix: runSuffix })); patchClasses(statusTag, { diff --git a/sidecars/panel/src/components/widgets/ContextWindowWidget.js b/sidecars/panel/src/components/widgets/ContextWindowWidget.js index 185b33c..83673b5 100644 --- a/sidecars/panel/src/components/widgets/ContextWindowWidget.js +++ b/sidecars/panel/src/components/widgets/ContextWindowWidget.js @@ -313,7 +313,9 @@ export const ContextWindowWidget = defineComponent({ const activeBadgeText = isEnglishLocale() ? rawActiveBadge === '主' ? t('fmt.mainBadge') - : rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) + : rawActiveBadge + .replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) + .replace(/^旁(\d+)$/, (_, n) => t('fmt.sideBadge', { index: n })) : rawActiveBadge; const pillItems = [ diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index f6c6874..7fc52e6 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -347,10 +347,12 @@ export const StepTableWidget = defineComponent({ const badgeText = isEnglishLocale() ? formatAgentBadgeText({ isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, index: st.agentIndex || 0, badgeText: st.agentBadge, }) - : st.agentBadge || (st.isSubagent ? '子' : '主'); + : st.agentBadge || (st.isSideQuestion ? '旁' : st.isSubagent ? '子' : '主'); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 1170e3e..c14b524 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -55,6 +55,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.sideQuestion': 'Side Question', + 'fmt.sideBadge': 'Q{index}', + 'fmt.sideBadgeShort': 'Q', 'fmt.selectedCount': '{count} {unit} selected', 'fmt.selectedListTitle': 'Selected ({count}): {names}', 'fmt.selectPlaceholder': 'Select', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index d11d118..5efb499 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -55,6 +55,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.sideQuestion': '旁路提问', + 'fmt.sideBadge': '旁{index}', + 'fmt.sideBadgeShort': '旁', 'fmt.selectedCount': '已选 {count} {unit}', 'fmt.selectedListTitle': '已选 ({count}):{names}', 'fmt.selectPlaceholder': '请选择', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index f398509..9cc154f 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1358,29 +1358,76 @@ export function getAgentBadgeClass(index = 0, isMain = false) { * @returns {string} */ export function formatAgentBadgeText(agent) { + const isSideQ = Boolean( + agent?.isSideQuestion || + agent?.typeName === 'side_question' || + /^旁\d*$/.test(String(agent?.badgeText || '')) + ); if (!isEnglishLocale()) { if (!agent || agent.isMain) return agent?.badgeText || '主'; + if (isSideQ) { + const sIdx = Number(agent.sideIndex || 0); + return agent.badgeText || (sIdx > 0 ? `旁${sIdx}` : '旁'); + } return agent.badgeText || `子${agent.index || ''}`; } if (!agent || agent.isMain) return t('fmt.mainBadge'); - return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort'); + if (isSideQ) { + const m = String(agent.badgeText || '').match(/^旁(\d+)$/); + const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); + return sIdx > 0 ? t('fmt.sideBadge', { index: sIdx }) : t('fmt.sideBadgeShort'); + } + const subMatch = String(agent.badgeText || '').match(/^子(\d+)$/); + const subOrd = Number(subMatch ? subMatch[1] : agent.index || 0); + return subOrd > 0 ? t('fmt.subBadge', { index: subOrd }) : t('fmt.subBadgeShort'); } /** - * 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。 + * 格式化主/子代理或旁路提问的完整显示名称(如 `子代理 #1 · Codebase Researcher` / `旁路提问 #1 · ...`)。 * * @param {object|null|undefined} agent * @returns {string} */ export function formatAgentLabel(agent) { + const isSideQ = Boolean( + agent?.isSideQuestion || + agent?.typeName === 'side_question' || + /^旁/.test(String(agent?.badgeText || agent?.shortLabel || '')) + ); if (!isEnglishLocale()) { if (!agent) return '主代理'; if (agent.isMain) return agent.shortLabel || '主代理'; + if (isSideQ) { + const sIdx = Number(agent.sideIndex || 0); + const fallbackShort = sIdx > 0 ? `旁路提问 #${sIdx}` : '旁路提问'; + const rolePart = + agent.role && + agent.role !== '旁路提问' && + agent.role !== 'Side Question' && + agent.role !== agent.shortLabel + ? ` · ${agent.role}` + : ''; + return `${agent.shortLabel || fallbackShort}${rolePart}`; + } const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; return `${agent.shortLabel || '子代理'}${rolePart}`; } if (!agent || agent.isMain) return t('fmt.mainAgent'); - const idx = Number(agent.index || 0); + if (isSideQ) { + const m = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); + const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); + const baseLabel = sIdx > 0 ? `${t('fmt.sideQuestion')} #${sIdx}` : t('fmt.sideQuestion'); + const rolePart = + agent.role && + agent.role !== '旁路提问' && + agent.role !== 'Side Question' && + agent.role !== agent.shortLabel + ? ` · ${agent.role}` + : ''; + return `${baseLabel}${rolePart}`; + } + const subMatch = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); + const idx = Number(subMatch ? subMatch[1] : agent.index || 0); const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); const rolePart = agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; @@ -1469,8 +1516,8 @@ export function resolveScopedConversation( } if (effectiveCtxScope === 'auto') { ctxAgent = - agents.find((a) => a.agentId === aggregated.activeAgentId) || - agents.find((a) => a.isRunning) || + agents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) || + agents.find((a) => !a.isSideQuestion && a.isRunning) || mainAgent; } } diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index d4f386d..476528c 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -63,6 +63,7 @@ export function backendHarness({ remoteCatalog=null, pluginManifest=null, hasGitDir=false, + gitConfigText=null, pluginRootPath=null, remoteFetch=null, execFileImpl=null, @@ -73,9 +74,9 @@ export function backendHarness({ const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs'; const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); - const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; + const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1}; const ctx={ - ...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID, + ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, setTimeout, clearTimeout, isDeepStrictEqual, randomUUID, ...(clock ? { Date: class extends Date { constructor(...args) { super(...(args.length ? args : [clock()])); } static now() { return clock(); } @@ -101,7 +102,8 @@ export function backendHarness({ const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); return Boolean(m && state.transcripts?.[m[1]]); } - if (norm.endsWith('/.git')) return Boolean(state.hasGitDir); + if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText); + if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText); if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true; return false; }, @@ -138,6 +140,7 @@ export function backendHarness({ if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog); if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog); if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest); + if (norm.endsWith('/.git/config')) return String(state.gitConfigText || ''); return JSON.stringify(cache); }, writeFileSync:(p,s)=>{ @@ -176,6 +179,6 @@ export function backendHarness({ return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,cacheState,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/cloud-sync-and-update.test.mjs b/sidecars/panel/test/cloud-sync-and-update.test.mjs index 6c7455e..113270e 100644 --- a/sidecars/panel/test/cloud-sync-and-update.test.mjs +++ b/sidecars/panel/test/cloud-sync-and-update.test.mjs @@ -597,3 +597,58 @@ test('pluginUpdateMode supports manual (default), auto, and off with legacy auto await new Promise((r) => setTimeout(r, 20)); assert.equal(gitTriggered, true, 'pluginUpdateMode=auto triggers background update check'); }); + +test('argon-b / argon-trial deployment shards resolve phased pricing without wildcarding unknown single-letter suffixes, and custom Git forks suppress upstream update badges', async () => { + const hPromo = backendHarness({ clock: () => Date.parse('2026-11-20T00:00:00Z') }); + for (const shardSlug of ['gemini-4-argon-b', 'gemini-4-argon-trial']) { + const promoInfo = hPromo.resolveModelInfo(shardSlug); + assert.equal(promoInfo.label, 'Gemini 4 Argon'); + assert.equal(promoInfo.shortName, 'argon-4'); + assert.equal(promoInfo.pricing.input, 2.0); + assert.equal(promoInfo.pricing.output, 10.0); + + const postInfo = hPromo.resolveModelInfo(shardSlug, new Map(), '', '', '', '2026-12-05T00:00:00Z'); + assert.equal(postInfo.pricing.input, 4.0); + assert.equal(postInfo.pricing.output, 20.0); + } + + // Unverified single-letter shard must NOT recklessly fall back to base model pricing + const unknownShard = hPromo.resolveModelInfo('gemini-4-argon-z'); + assert.equal(unknownShard.pricing, null); + + // Custom Git fork: upstream cloud catalog sync updates model pricing, while suppressing upstream version badge + const forkH = backendHarness({ + hasGitDir: true, + gitConfigText: '[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n\turl = https://github.com/custom-contributor/antigravity-usage-monitor.git\n', + pluginManifest: { name: 'usage-monitor', version: '1.5.0' }, + remoteFetch: async () => ({ + ok: true, + json: async () => ({ + schemaVersion: 1, + catalogVersion: '2026.12.10.1', + updatedAt: '2026-12-10T10:00:00Z', + latestPluginVersion: '1.9.0', + pricing: { + 'gemini-5-experimental': { + input: 6.0, + cache: 0.3, + output: 30.0, + short: 'gem-5-exp', + family: 'Gemini', + }, + }, + }), + }), + }); + + assert.equal(forkH.detectCustomGitForkRepo(), 'custom-contributor/antigravity-usage-monitor'); + const statusAfterSync = await forkH.syncCloudCatalog({ force: true }); + assert.equal(statusAfterSync.catalogVersion, '2026.12.10.1'); + assert.equal(statusAfterSync.updateAvailable, false, 'custom fork must not show false update badge from upstream repo'); + assert.equal(statusAfterSync.latestPluginVersion, '1.5.0'); + assert.equal( + statusAfterSync.releaseUrl, + 'https://github.com/custom-contributor/antigravity-usage-monitor/releases/latest' + ); + assert.equal(forkH.resolveModelInfo('gemini-5-experimental').pricing.input, 6.0); +}); diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs new file mode 100644 index 0000000..740c826 --- /dev/null +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -0,0 +1,687 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { backendHarness } from './backend-harness.mjs'; +import { i18nStore } from '../src/i18n/index.js'; +import { + formatAgentBadgeText, + formatAgentLabel, + resolveScopedConversation, +} from '../src/store/telemetryStore.js'; + +function encodeVarint(val) { + let v = BigInt(val); + if (v < 0n) v = BigInt.asUintN(64, v); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeFieldVarint(fieldNo, val) { + return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]); +} + +function encodeFieldBytes(fieldNo, bufOrStr) { + const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8'); + return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]); +} + +function encodeTimestamp(sec, nanos = 0) { + return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]); +} + +function encodeStepMeta({ + createdSec, + finishedSec, + stepIndex, + originCascadeId = '', + modelEnumInt = 0, + inputTokens = 0, + cacheReadTokens = 0, + outputTokens = 0, + thinkingTokens = 0, + responseTokens = 0, +}) { + const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))]; + if (finishedSec) { + parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec))); + } + if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) { + const muParts = []; + if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt)); + if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens)); + if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens)); + if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens)); + muParts.push(encodeFieldVarint(6, 24)); // API_PROVIDER_GOOGLE_GEMINI + if (thinkingTokens) muParts.push(encodeFieldVarint(9, thinkingTokens)); + if (responseTokens) muParts.push(encodeFieldVarint(10, responseTokens)); + parts.push(encodeFieldBytes(9, Buffer.concat(muParts))); + } + const siParts = [encodeFieldVarint(2, stepIndex)]; + if (originCascadeId) { + siParts.push(encodeFieldBytes(4, originCascadeId)); + } + parts.push(encodeFieldBytes(20, Buffer.concat(siParts))); + return Buffer.concat(parts); +} + +function encodeUserInputPayload(text) { + return encodeFieldBytes(19, encodeFieldBytes(2, text)); +} + +function encodePlannerResponsePayload(text) { + return encodeFieldBytes(20, encodeFieldBytes(1, text)); +} + +function encodeGenMeta({ + stepIndex, + cascadeId, + responseModel, + modelDisplayName, + estimatedTokensUsed = 0, + maxContextTokens = 256000, + userMsgTokens = 0, +}) { + const groups = []; + if (userMsgTokens > 0) { + const child = Buffer.concat([ + encodeFieldBytes(1, '0: USER_INPUT'), + encodeFieldVarint(3, userMsgTokens), + ]); + const topGroup = Buffer.concat([ + encodeFieldBytes(1, 'Chat Messages'), + encodeFieldVarint(2, 7), // TOKEN_TYPE_CHAT_MESSAGES + encodeFieldVarint(4, userMsgTokens), + encodeFieldBytes(5, child), + ]); + groups.push(encodeFieldBytes(1, topGroup)); + } + const cwParts = []; + if (estimatedTokensUsed > 0) cwParts.push(encodeFieldVarint(1, estimatedTokensUsed)); + if (groups.length > 0) cwParts.push(encodeFieldBytes(3, Buffer.concat(groups))); + if (maxContextTokens > 0) cwParts.push(encodeFieldVarint(4, maxContextTokens)); + + const mapCascade = Buffer.concat([ + encodeFieldBytes(1, 'cascade_id'), + encodeFieldBytes(2, cascadeId), + ]); + const chatParts = [ + encodeFieldBytes(9, encodeFieldBytes(10, Buffer.concat(cwParts))), + encodeFieldBytes(11, encodeTimestamp(1, 0)), // 1s TTFT + encodeFieldBytes(19, responseModel), + encodeFieldBytes(20, mapCascade), + encodeFieldBytes(21, modelDisplayName), + ]; + return Buffer.concat([ + encodeFieldVarint(2, stepIndex), + encodeFieldBytes(1, Buffer.concat(chatParts)), + ]); +} + +function encodeSummaryBlob({ + title = '', + stepCount = 0, + lastModSec = 0, + statusInt = 1, + trajectoryType = 0, + forkParentId = '', + sideQuestionIds = [], + sideQuestionTitles = {}, + parentConversationId = '', + subagentSpec = null, +}) { + const parts = []; + if (stepCount > 0) parts.push(encodeFieldVarint(2, stepCount)); + if (lastModSec > 0) parts.push(encodeFieldBytes(3, encodeTimestamp(lastModSec))); + if (statusInt > 0) parts.push(encodeFieldVarint(5, statusInt)); + + const annParts = []; + if (title) annParts.push(encodeFieldBytes(1, title)); + for (const sqId of sideQuestionIds) { + annParts.push(encodeFieldBytes(17, sqId)); + } + for (const [k, v] of Object.entries(sideQuestionTitles)) { + annParts.push( + encodeFieldBytes(18, Buffer.concat([encodeFieldBytes(1, k), encodeFieldBytes(2, v)])) + ); + } + if (annParts.length > 0) parts.push(encodeFieldBytes(15, Buffer.concat(annParts))); + + if (parentConversationId || subagentSpec) { + const tmParts = []; + if (parentConversationId) tmParts.push(encodeFieldBytes(5, parentConversationId)); + if (subagentSpec) { + const specParts = []; + if (subagentSpec.typeName) specParts.push(encodeFieldBytes(1, subagentSpec.typeName)); + if (subagentSpec.role) specParts.push(encodeFieldBytes(2, subagentSpec.role)); + tmParts.push(encodeFieldBytes(8, Buffer.concat(specParts))); + } + parts.push(encodeFieldBytes(17, Buffer.concat(tmParts))); + } + + if (trajectoryType > 0) parts.push(encodeFieldVarint(22, trajectoryType)); + if (forkParentId) parts.push(encodeFieldBytes(24, forkParentId)); + return Buffer.concat(parts); +} + +test('Hybrid SQLite+WAL mode skips trajectory RPCs for local DBs, falls back to RPC when DB is absent, deduplicates cloned Side Question steps, protects mainline context, and renders zh/en badges', async (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-hybrid-sqlite-')); + + const mainCid = '11111111-1111-4111-8111-111111111111'; + const subCid = '22222222-2222-4222-8222-222222222222'; + const sideCid = '33333333-3333-4333-8333-333333333333'; + const emptySideCid = '44444444-4444-4444-8444-444444444444'; + const rpcOnlyCid = '55555555-5555-4555-8555-555555555555'; + + // Use promo-period timestamp: 2026-11-18T00:00:00Z = 1794960000 + const baseSec = Math.floor(Date.parse('2026-11-18T00:00:00Z') / 1000); + const rpcCalls = []; + + const mockLsServer = http.createServer((req, res) => { + let rawBody = ''; + req.on('data', (chunk) => { + rawBody += chunk; + }); + req.on('end', () => { + const method = req.url.split('/').pop(); + const body = rawBody ? JSON.parse(rawBody) : {}; + rpcCalls.push({ method, cascadeId: body.cascadeId || '' }); + + res.setHeader('Content-Type', 'application/json'); + if (method === 'GetUserStatus') { + res.end(JSON.stringify({ userStatus: { email: 'dev@example.com' } })); + return; + } + if (method === 'RetrieveUserQuotaSummary') { + res.end(JSON.stringify({ response: { groups: [] } })); + return; + } + if (method === 'GetAvailableModels') { + res.end(JSON.stringify({ response: { models: {} } })); + return; + } + if (method === 'GetCascadeTrajectory' && body.cascadeId === rpcOnlyCid) { + res.end( + JSON.stringify({ + numTotalSteps: 2, + trajectory: { + steps: [ + { + // Cloned step from mainCid over RPC — must ALSO be stripped by filterClonedTrajectorySteps! + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date((baseSec + 50) * 1000).toISOString(), + finishedGeneratingAt: new Date((baseSec + 54) * 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: 0, cascadeId: mainCid }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '5000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date((baseSec + 100) * 1000).toISOString(), + finishedGeneratingAt: new Date((baseSec + 102) * 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: 1, cascadeId: rpcOnlyCid }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M320', // gemini-3.8-flash-low: $0.30/M input + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '1000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + }, + ], + }, + }) + ); + return; + } + res.statusCode = 500; + res.end(JSON.stringify({ error: `unexpected RPC ${method}` })); + }); + }); + + await new Promise((resolve) => mockLsServer.listen(0, '127.0.0.1', resolve)); + const lsPort = mockLsServer.address().port; + + try { + const agyDir = join(tempRoot, 'antigravity'); + const convDir = join(agyDir, 'conversations'); + mkdirSync(convDir, { recursive: true }); + + // 1. Build conversation_summaries.db in WAL mode + const sumDbPath = join(agyDir, 'conversation_summaries.db'); + const sumDb = new DatabaseSync(sumDbPath); + sumDb.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE conversation_summaries ( + conversation_id TEXT PRIMARY KEY, + title TEXT, + preview TEXT, + status TEXT, + source TEXT, + parent_conversation_id TEXT, + nesting_depth INTEGER, + agent_name TEXT, + not_fully_idle INTEGER, + killed INTEGER, + step_count INTEGER, + last_modified_time TEXT, + app_data_dir TEXT, + raw_summary BLOB + ); + CREATE TABLE conversation_parents ( + conversation_id TEXT, + parent_id TEXT + ); + `); + + const insSum = sumDb.prepare(` + INSERT INTO conversation_summaries ( + conversation_id, title, status, parent_conversation_id, step_count, last_modified_time, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, 'antigravity', ?) + `); + + insSum.run( + mainCid, + 'Main Architecture Task', + 'CASCADE_RUN_STATUS_IDLE', + '', + 2, + '2026-11-18T00:01:35Z', + encodeSummaryBlob({ + title: 'Main Architecture Task', + stepCount: 2, + lastModSec: baseSec + 95, + sideQuestionIds: [sideCid, emptySideCid], + sideQuestionTitles: { [sideCid]: '为什么用 WAL 模式?' }, + }) + ); + insSum.run( + subCid, + 'SQLite Researcher', + 'CASCADE_RUN_STATUS_IDLE', + mainCid, + 2, + '2026-11-18T00:01:10Z', + encodeSummaryBlob({ + title: 'SQLite Researcher', + stepCount: 2, + lastModSec: baseSec + 70, + parentConversationId: mainCid, + subagentSpec: { typeName: 'research', role: 'SQLite Researcher' }, + }) + ); + insSum.run( + sideCid, + '', + 'CASCADE_RUN_STATUS_IDLE', + '', + 4, + '2026-11-18T00:02:00Z', + encodeSummaryBlob({ + stepCount: 4, + lastModSec: baseSec + 120, + trajectoryType: 22, + forkParentId: mainCid, + }) + ); + insSum.run( + emptySideCid, + '', + 'CASCADE_RUN_STATUS_IDLE', + '', + 2, + '2026-11-18T00:01:30Z', + encodeSummaryBlob({ + stepCount: 2, + lastModSec: baseSec + 90, + trajectoryType: 22, + forkParentId: mainCid, + }) + ); + // rpcOnlyCid is present in summaries, but has NO local .db file -> must fall back to GetCascadeTrajectory RPC! + insSum.run( + rpcOnlyCid, + 'Remote WSL Session', + 'CASCADE_RUN_STATUS_IDLE', + '', + 1, + '2026-11-18T00:00:30Z', + encodeSummaryBlob({ + title: 'Remote WSL Session', + stepCount: 1, + lastModSec: baseSec + 30, + }) + ); + sumDb.prepare('INSERT INTO conversation_parents (conversation_id, parent_id) VALUES (?, ?)').run(sideCid, mainCid); + sumDb.close(); + + const initConvDb = (cid, trajectoryType = 1) => { + const db = new DatabaseSync(join(convDir, `${cid}.db`)); + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, ?, 1)').run(cid, cid, trajectoryType); + return db; + }; + + // 2. Main conversation DB: 1 USER_INPUT ("设计混合 SQLite 读取") + 1 Carbon High response ($12.10, context 120k/256k) + const mainDb = initConvDb(mainCid, 1); + mainDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }), + encodeUserInputPayload('设计混合 SQLite 读取') + ); + mainDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 50, + finishedSec: baseSec + 54, + stepIndex: 1, + originCascadeId: mainCid, + modelEnumInt: 1429, // MODEL_PLACEHOLDER_M429 -> Carbon High ($2 + $0.1 + $10 = $12.10) + inputTokens: 1_000_000, + cacheReadTokens: 1_000_000, + outputTokens: 1_000_000, + thinkingTokens: 400_000, + responseTokens: 600_000, + }), + encodePlannerResponsePayload('这是混合架构方案。') + ); + mainDb + .prepare('INSERT INTO gen_metadata VALUES (0, ?)') + .run( + encodeGenMeta({ + stepIndex: 1, + cascadeId: mainCid, + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + estimatedTokensUsed: 120_000, + maxContextTokens: 256_000, + userMsgTokens: 120_000, + }) + ); + mainDb.close(); + + // 3. Regular subagent DB: 1 Flash 3.8 Low step ($0.30) + const subDb = initConvDb(subCid, 1); + subDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 10, stepIndex: 0, originCascadeId: subCid }), + encodeUserInputPayload('调研 SQLite WAL') + ); + subDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 11, + finishedSec: baseSec + 13, + stepIndex: 1, + originCascadeId: subCid, + modelEnumInt: 1320, // MODEL_PLACEHOLDER_M320 -> $0.30/1M input + inputTokens: 1_000_000, + }), + encodePlannerResponsePayload('WAL 调研完毕') + ); + subDb.close(); + + // 4. Side Question DB (trajectory_type = 22): + // Contains 2 CLONED parent steps from mainCid ($12.10) + 1 own USER_INPUT + 1 own Flash 3.8 High step ($0.75) + // Context watermark in Side Question is tiny (15k) and later than mainCid — must NOT overwrite mainCid's context! + const sideDb = initConvDb(sideCid, 22); + sideDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }), + encodeUserInputPayload('设计混合 SQLite 读取') + ); + sideDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 50, + finishedSec: baseSec + 54, + stepIndex: 1, + originCascadeId: mainCid, // CLONED FROM PARENT! Must be filtered out! + modelEnumInt: 1429, + inputTokens: 1_000_000, + cacheReadTokens: 1_000_000, + outputTokens: 1_000_000, + }), + encodePlannerResponsePayload('克隆的父回复') + ); + sideDb + .prepare('INSERT INTO steps VALUES (2, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 80, stepIndex: 2, originCascadeId: sideCid }), + encodeUserInputPayload('顺便问下为什么用 WAL?') + ); + sideDb + .prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 81, + finishedSec: baseSec + 83, + stepIndex: 3, + originCascadeId: sideCid, + modelEnumInt: 1318, // MODEL_PLACEHOLDER_M318 -> $0.75/1M input + inputTokens: 1_000_000, + }), + encodePlannerResponsePayload('因为只读不阻塞 checkpoint。') + ); + sideDb + .prepare('INSERT INTO gen_metadata VALUES (0, ?)') + .run( + encodeGenMeta({ + stepIndex: 1, + cascadeId: mainCid, // Cloned gen_metadata from parent! + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + estimatedTokensUsed: 120_000, + maxContextTokens: 256_000, + userMsgTokens: 120_000, + }) + ); + sideDb + .prepare('INSERT INTO gen_metadata VALUES (1, ?)') + .run( + encodeGenMeta({ + stepIndex: 3, + cascadeId: sideCid, + responseModel: 'gemini-3.8-flash-high', + modelDisplayName: 'Gemini 3.8 Flash (High)', + estimatedTokensUsed: 15_000, + maxContextTokens: 256_000, + userMsgTokens: 15_000, + }) + ); + sideDb.close(); + + // 5. Empty Side Question DB: only cloned parent steps, 0 own steps -> must be hidden! + const emptySideDb = initConvDb(emptySideCid, 22); + emptySideDb + .prepare('INSERT INTO steps VALUES (0, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 2, + finishedSec: baseSec + 6, + stepIndex: 1, + originCascadeId: mainCid, + modelEnumInt: 1429, + inputTokens: 1_000_000, + }), + null + ); + emptySideDb.close(); + + const execFileAsync = promisify(execFile); + const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href; + const { stdout: rawJson } = await execFileAsync( + process.execPath, + [ + '--input-type=module', + '-e', + `const { buildTelemetryPayload } = await import(${JSON.stringify(builderUrl)}); + const p = await buildTelemetryPayload(${JSON.stringify(mainCid)}, false, { range: 'all' }); + process.stdout.write(JSON.stringify(p));`, + ], + { + env: { + ...process.env, + ANTIGRAVITY_GEMINI_DIR: tempRoot, + ANTIGRAVITY_APP_DATA_DIR: '', + USAGE_MONITOR_APP_DATA_DIR: '', + ANTIGRAVITY_EXECUTABLE_DATA_DIR: '', + USAGE_MONITOR_DATA_DIR: join(tempRoot, 'sidecar-data'), + ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${lsPort}`, + ANTIGRAVITY_CSRF_TOKEN: 'test-csrf', + }, + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + } + ); + + const payload = JSON.parse(rawJson); + + // A. Verify RPC calls: ZERO GetAllCascadeTrajectories, ZERO GetCascadeTrajectory for local SQLite DBs, + // and exactly ONE GetCascadeTrajectory fallback for rpcOnlyCid! + assert.equal( + rpcCalls.some((c) => c.method === 'GetAllCascadeTrajectories'), + false, + 'local conversation_summaries.db must eliminate GetAllCascadeTrajectories RPC' + ); + const trajRpcTargets = rpcCalls + .filter((c) => c.method === 'GetCascadeTrajectory') + .map((c) => c.cascadeId); + assert.deepEqual( + trajRpcTargets, + [rpcOnlyCid], + 'only conversation missing local .db falls back to GetCascadeTrajectory RPC' + ); + + // B. Top-level conversations list contains ONLY mainCid and rpcOnlyCid (no orphan/empty side questions or subagents) + assert.deepEqual( + payload.conversations.map((c) => c.cascadeId).sort(), + [mainCid, rpcOnlyCid].sort() + ); + + // C. Verify Turn Rail prompt decoded directly from SQLite USER_INPUT step_payload + const mainUnit = payload.activeConversation.agents.find((a) => a.isMain); + assert.ok(mainUnit); + assert.equal(payload.activeConversation.recentSteps[0].turnPrompt, '设计混合 SQLite 读取'); + + // D. Verify agents under mainCid: [main, subagent #1, side question #1] (emptySideCid hidden!) + const agents = payload.activeConversation.agents; + assert.equal(agents.length, 3); + assert.equal(agents[1].badgeText, '子1'); + assert.equal(Boolean(agents[1].isSideQuestion), false); + assert.equal(agents[2].badgeText, '旁1'); + assert.equal(agents[2].isSideQuestion, true); + assert.equal(agents[2].sideIndex, 1); + assert.equal(agents[2].role, '为什么用 WAL 模式?'); + assert.equal(agents[2].stepCount, 1, 'cloned parent steps must be stripped from Side Question'); + assert.equal(agents[2].sessionCostUsd, 0.75, 'Side Question bills ONLY its own step ($0.75), never parent ($12.10)'); + + // E. Verify total session & account costs have ZERO double-counting: + // Session (main $12.10 + sub $0.30 + sideQ $0.75) = $13.15 + // Account (session $13.15 + rpcOnlyCid $0.30) = $13.45 + assert.equal(payload.activeConversation.aggregated.sessionCostUsd, 13.15); + assert.equal(payload.consumption.account.costUsd, 13.45); + assert.equal(payload.activeConversation.aggregated.role, '主代理 + 1 子代理 + 1 旁问'); + + // F. Verify mainline context watermark protection (backend aggregated + frontend auto-follow) + // Main agent has 3_000_000 tokens (1M in + 1M cache + 1M out), Side Question has 15_000/1_000_000 + assert.equal(payload.activeConversation.aggregated.activeAgentId, 'main'); + assert.equal(payload.activeConversation.aggregated.context.totalTokens, mainUnit.context.totalTokens); + + const scopedAuto = resolveScopedConversation(payload, 'all', 'auto', true); + assert.equal(scopedAuto.ctxAgent.agentId, 'main', 'auto context inspector locks onto mainline agent'); + const scopedExplicitSide = resolveScopedConversation(payload, 'all', sideCid, false); + assert.equal(scopedExplicitSide.ctxAgent.agentId, sideCid, 'explicitly selecting Side Question pill still inspects it'); + + // G. Verify zh-CN & en-US badge and label formatting + const prevLocale = i18nStore.getState().locale; + try { + i18nStore.setState({ locale: 'zh-CN', hostLocale: 'zh-CN' }); + assert.equal(formatAgentBadgeText(agents[2]), '旁1'); + assert.equal(formatAgentLabel(agents[2]), '旁路提问 #1 · 为什么用 WAL 模式?'); + + i18nStore.setState({ locale: 'en-US', hostLocale: 'en-US' }); + assert.equal(formatAgentBadgeText(agents[1]), 'S1'); + assert.equal(formatAgentBadgeText(agents[2]), 'Q1'); + assert.equal(formatAgentLabel(agents[2]), 'Side Question #1 · 为什么用 WAL 模式?'); + } finally { + i18nStore.setState({ locale: prevLocale }); + } + } finally { + await new Promise((resolve) => mockLsServer.close(resolve)); + rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and flushes immediately on IDLE or cache rebuild', () => { + let now = 1_000_000; + const h = backendHarness({ clock: () => now }); + + // 1st save (lastSavedAtMs === 0) flushes immediately even while running + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 1); + assert.equal(h.cacheState.needsSave, false); + + // Subsequent saves within 30s window while RUNNING are throttled in memory + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 1, '2s polling during RUNNING must not rewrite disk every tick'); + assert.equal(h.cacheState.needsSave, true); + assert.ok(h.cacheState.flushTimer !== null); + + // Transitioning to IDLE flushes immediately and clears pending timer + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: false, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 2, 'transition to IDLE flushes immediately'); + assert.equal(h.cacheState.needsSave, false); + assert.equal(h.cacheState.flushTimer, null); + + // Re-arming throttle then calling executeRebuildCacheAction cancels timer cleanly + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.ok(h.cacheState.flushTimer !== null); + const rebuildRes = h.executeRebuildCacheAction(); + assert.equal(rebuildRes.ok, true); + assert.equal(h.cacheState.flushTimer, null); + assert.equal(h.cacheState.needsSave, false); +});