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:
@@ -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" },
|
||||
|
||||
+65
-8
@@ -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, {
|
||||
|
||||
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;
|
||||
const walInfo = computeSqliteWalSig(fullPath);
|
||||
if (!walInfo.exists) continue;
|
||||
if (!best || walInfo.mtimeMs > best.mtimeMs) {
|
||||
best = {
|
||||
dbPath: fullPath,
|
||||
mtimeMs: walInfo.mtimeMs,
|
||||
sig: walInfo.sig,
|
||||
};
|
||||
}
|
||||
}
|
||||
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 {
|
||||
const mtime = Number(statSync(fullPath)?.mtimeMs || 0);
|
||||
if (mtime > bestMtime) {
|
||||
bestMtime = mtime;
|
||||
bestPath = fullPath;
|
||||
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 {
|
||||
if (!bestPath) bestPath = fullPath;
|
||||
// 忽略损坏 JSON 行
|
||||
}
|
||||
}
|
||||
return bestPath;
|
||||
|
||||
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
|
||||
: 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,27 +1529,104 @@ 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);
|
||||
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;
|
||||
@@ -1335,9 +1635,20 @@ export async function enumerateAndSyncConversations({
|
||||
conv.isSubagent =
|
||||
Boolean(conv.parentConversationId) ||
|
||||
Boolean(
|
||||
conv.rootConversationId &&
|
||||
conv.rootConversationId !== conv.cascadeId.toLowerCase()
|
||||
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,17 +420,25 @@ 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 (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];
|
||||
Object.assign(MODEL_PRICING, nextPricing);
|
||||
|
||||
@@ -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,10 +670,15 @@ 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 (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;
|
||||
@@ -680,7 +690,6 @@ export function aggregateMultiWindowUsage({
|
||||
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1794819376795">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794904298571">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794819376795"></script>
|
||||
<script src="/app.js?v=1794904298571"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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': '请选择',
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user