mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add hybrid SQLite+WAL reader, side-question dedup, and cache throttling
- Read local conversation_summaries.db and <id>.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 <elbertoo001@gmail.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -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 = '';
|
||||
|
||||
@@ -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) &&
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user