mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(panel): guard SQLite schema init and recover .pb sessions (#41)
- Add lock-free 100-byte SQLite header readiness check before opening local DBs so high-frequency scans skip 0-byte, pre-DDL, 32-byte WAL-header-only, and active rollback-journal DBs without triggering schema-init lock races - Separate unready DB skips from confirmed empty-shell DBs and fall back to transcript.jsonl / size-capped transcript_full.jsonl with .pb + transcript signature tracking and subagent ref recovery - Extract shared transcript JSONL fallback parsing reused by local-scanner and cli-statusline, including .pb-aware candidate ranking and root redirect
This commit is contained in:
@@ -24,6 +24,7 @@ import {
|
|||||||
computeSqliteWalSig,
|
computeSqliteWalSig,
|
||||||
getNodeSqliteDatabaseSync,
|
getNodeSqliteDatabaseSync,
|
||||||
hasBuiltinNodeSqlite,
|
hasBuiltinNodeSqlite,
|
||||||
|
isSqliteDbReadyForRead,
|
||||||
normalizeSqliteIsoTime,
|
normalizeSqliteIsoTime,
|
||||||
withReadOnlySqliteDb,
|
withReadOnlySqliteDb,
|
||||||
} from './sqlite-client.mjs';
|
} from './sqlite-client.mjs';
|
||||||
@@ -43,6 +44,7 @@ export {
|
|||||||
computeSqliteWalSig,
|
computeSqliteWalSig,
|
||||||
getNodeSqliteDatabaseSync,
|
getNodeSqliteDatabaseSync,
|
||||||
hasBuiltinNodeSqlite,
|
hasBuiltinNodeSqlite,
|
||||||
|
isSqliteDbReadyForRead,
|
||||||
withReadOnlySqliteDb,
|
withReadOnlySqliteDb,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-r
|
|||||||
import {
|
import {
|
||||||
computeSqliteWalSig,
|
computeSqliteWalSig,
|
||||||
hasBuiltinNodeSqlite,
|
hasBuiltinNodeSqlite,
|
||||||
|
isSqliteDbReadyForRead,
|
||||||
readAnnotationTitleForCascade,
|
readAnnotationTitleForCascade,
|
||||||
readLocalImageDimensionsFromUri,
|
readLocalImageDimensionsFromUri,
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
@@ -46,6 +47,11 @@ import {
|
|||||||
import { callLsRpc } from './ls-rpc.mjs';
|
import { callLsRpc } from './ls-rpc.mjs';
|
||||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||||
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||||
|
import {
|
||||||
|
readTranscriptJsonlLines,
|
||||||
|
resolveTranscriptPathInLogsDir,
|
||||||
|
synthesizeTranscriptModelStep,
|
||||||
|
} from './transcript-fallback.mjs';
|
||||||
|
|
||||||
const CONV_FILE_RE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i;
|
const CONV_FILE_RE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i;
|
||||||
const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
@@ -532,7 +538,7 @@ function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountNa
|
|||||||
export function normalizeEmptyWalSqliteSig(sigStr) {
|
export function normalizeEmptyWalSqliteSig(sigStr) {
|
||||||
const s = String(sigStr || '');
|
const s = String(sigStr || '');
|
||||||
if (!s.includes(':sqlite:')) return s;
|
if (!s.includes(':sqlite:')) return s;
|
||||||
return s.replace(/\|\d+:0$/, '|0:0');
|
return s.replace(/\|\d+:0(?=~fb:|$)/, '|0:0');
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||||
@@ -776,8 +782,10 @@ function findTranscriptPath(cascadeId) {
|
|||||||
let bestMtime = -1;
|
let bestMtime = -1;
|
||||||
for (const dir of dirs) {
|
for (const dir of dirs) {
|
||||||
if (!dir) continue;
|
if (!dir) continue;
|
||||||
const candidate = join(dir, normId, '.system_generated', 'logs', 'transcript.jsonl');
|
const candidate = resolveTranscriptPathInLogsDir(
|
||||||
if (!existsSync(candidate)) continue;
|
join(dir, normId, '.system_generated', 'logs')
|
||||||
|
);
|
||||||
|
if (!candidate) continue;
|
||||||
if (dirs.length === 1) return candidate;
|
if (dirs.length === 1) return candidate;
|
||||||
try {
|
try {
|
||||||
const mtime = Number(statSync(candidate)?.mtimeMs || 0);
|
const mtime = Number(statSync(candidate)?.mtimeMs || 0);
|
||||||
@@ -910,6 +918,45 @@ function hasLocalSqliteDb(diskFiles = []) {
|
|||||||
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || '')));
|
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || '')));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function hasLocalPbFile(diskFiles = []) {
|
||||||
|
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.pb$/i.test(String(f || '')));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算本地 `.pb` 与 `transcript.jsonl` 辅助轨迹文件的复合签名(`mtimeMs + size`)。
|
||||||
|
* 仅在会话不存在有效 SQLite 主库、或同时存在 `.pb` / 处于 `offlineTranscriptFallback` 模式时按需调用,
|
||||||
|
* 确保主 `.db` 因 `database is locked` 沦为空壳而实际数据写入 `.pb` + `transcript.jsonl` 时仍能实时感知变更。
|
||||||
|
*
|
||||||
|
* @param {string[]} [diskFiles=[]]
|
||||||
|
* @returns {{ mtimeMs: number, sig: string }}
|
||||||
|
*/
|
||||||
|
function computeFallbackDiskInfo(diskFiles = []) {
|
||||||
|
if (!Array.isArray(diskFiles) || diskFiles.length === 0) {
|
||||||
|
return { mtimeMs: 0, sig: '' };
|
||||||
|
}
|
||||||
|
let mtimeMs = 0;
|
||||||
|
const parts = [];
|
||||||
|
for (const rawPath of diskFiles) {
|
||||||
|
const p = String(rawPath || '').trim();
|
||||||
|
const isPb = /\.pb$/i.test(p);
|
||||||
|
const isTranscript = /\.jsonl$/i.test(p);
|
||||||
|
if (!isPb && !isTranscript) continue;
|
||||||
|
try {
|
||||||
|
const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p);
|
||||||
|
const st = statSync(fullPath, { throwIfNoEntry: false });
|
||||||
|
if (!st) continue;
|
||||||
|
const m = Number(st.mtimeMs || 0);
|
||||||
|
const sz = Number(st.size || 0);
|
||||||
|
if (m > mtimeMs) mtimeMs = m;
|
||||||
|
parts.push(`${isPb ? 'p' : 't'}:${Math.floor(m)}:${sz}`);
|
||||||
|
} catch {
|
||||||
|
// 忽略单文件瞬时 stat 异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (parts.length > 1) parts.sort();
|
||||||
|
return { mtimeMs, sig: parts.join(',') };
|
||||||
|
}
|
||||||
|
|
||||||
function resolveBestSqliteDbInfo(diskFiles = [], { skipMissingWalFromListing = false } = {}) {
|
function resolveBestSqliteDbInfo(diskFiles = [], { skipMissingWalFromListing = false } = {}) {
|
||||||
if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null;
|
if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null;
|
||||||
let walPathsLower = null;
|
let walPathsLower = null;
|
||||||
@@ -1062,41 +1109,115 @@ function filterClonedTrajectorySteps(rawSteps, generatorMeta, targetCidLower) {
|
|||||||
return { steps: filteredSteps, generatorMeta: filteredGen };
|
return { steps: filteredSteps, generatorMeta: filteredGen };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function unwrapOfflineToolArgString(val) {
|
||||||
|
if (typeof val !== 'string') return '';
|
||||||
|
const trimmed = val.trim();
|
||||||
|
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
if (typeof parsed === 'string') return parsed.trim();
|
||||||
|
} catch {
|
||||||
|
// 忽略非标准二次转义
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return trimmed.replace(/^"+|"+$/g, '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractSubagentRefsFromTranscriptLines(transcriptLines = [], baseSteps = [], cidLower = '') {
|
||||||
|
const refs = extractSubagentRefsFromSteps(baseSteps);
|
||||||
|
const byCid = new Map(refs.map((r) => [r.cascadeId, r]));
|
||||||
|
let nextOrder = refs.length;
|
||||||
|
const pendingSpecs = [];
|
||||||
|
const pendingByCallId = new Map();
|
||||||
|
|
||||||
|
for (const line of transcriptLines || []) {
|
||||||
|
if (!line || typeof line !== 'object') continue;
|
||||||
|
const createdTimeMs = parseIsoMs(line.created_at || line.createdAt) || 0;
|
||||||
|
const toolCalls = Array.isArray(line.tool_calls) ? line.tool_calls : [];
|
||||||
|
for (const tc of toolCalls) {
|
||||||
|
const name = String(tc?.name || tc?.tool_name || '').trim().toLowerCase();
|
||||||
|
if (name === 'invoke_subagent' || name === 'default_api:invoke_subagent') {
|
||||||
|
const args = tc?.args || tc?.arguments || {};
|
||||||
|
const callId = String(tc?.id || tc?.call_id || tc?.tool_call_id || '').trim();
|
||||||
|
const spec = {
|
||||||
|
callId,
|
||||||
|
role: unwrapOfflineToolArgString(args.Role ?? args.role ?? ''),
|
||||||
|
typeName: unwrapOfflineToolArgString(args.TypeName ?? args.typeName ?? ''),
|
||||||
|
createdTimeMs,
|
||||||
|
consumed: false,
|
||||||
|
};
|
||||||
|
pendingSpecs.push(spec);
|
||||||
|
if (callId) pendingByCallId.set(callId, spec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const content = typeof line.content === 'string' ? line.content : '';
|
||||||
|
if (content && content.includes('Created the following subagent')) {
|
||||||
|
const resultCallId = String(line.tool_call_id || line.call_id || '').trim();
|
||||||
|
const matches = content.matchAll(
|
||||||
|
/"conversationId"\s*:\s*"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"/gi
|
||||||
|
);
|
||||||
|
for (const m of matches) {
|
||||||
|
const subCid = String(m[1] || '').trim().toLowerCase();
|
||||||
|
if (!subCid || subCid === cidLower) continue;
|
||||||
|
let spec = null;
|
||||||
|
if (resultCallId && pendingByCallId.has(resultCallId)) {
|
||||||
|
const direct = pendingByCallId.get(resultCallId);
|
||||||
|
if (direct && !direct.consumed) {
|
||||||
|
direct.consumed = true;
|
||||||
|
spec = direct;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!spec) {
|
||||||
|
while (pendingSpecs.length > 0 && pendingSpecs[0].consumed) {
|
||||||
|
pendingSpecs.shift();
|
||||||
|
}
|
||||||
|
spec = pendingSpecs.shift() || null;
|
||||||
|
if (spec) spec.consumed = true;
|
||||||
|
}
|
||||||
|
const prev = byCid.get(subCid);
|
||||||
|
const merged = {
|
||||||
|
cascadeId: subCid,
|
||||||
|
role: spec?.role || prev?.role || '',
|
||||||
|
typeName: spec?.typeName || prev?.typeName || '',
|
||||||
|
createdTimeMs: createdTimeMs || spec?.createdTimeMs || prev?.createdTimeMs || 0,
|
||||||
|
spawnOrder: prev ? prev.spawnOrder : nextOrder++,
|
||||||
|
};
|
||||||
|
byCid.set(subCid, merged);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const swarmManifest = cidLower ? readSwarmManifestForCascade(cidLower) : null;
|
||||||
|
if (swarmManifest?.workerRefs?.length) {
|
||||||
|
for (const wRef of swarmManifest.workerRefs) {
|
||||||
|
if (wRef?.cascadeId && !byCid.has(wRef.cascadeId)) {
|
||||||
|
byCid.set(wRef.cascadeId, wRef);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(byCid.values());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当 Language Server RPC 离线或跨端不可达(如 `agy` CLI 独立会话目录)时,优先融合本地 SQLite
|
* 当 Language Server RPC 离线、跨端不可达(如 `agy` CLI 独立会话目录)或本地 `.db` 因初始化锁冲突降级为 `.pb` 空壳时,
|
||||||
* (`conversations/<id>.db` + `conversation_summaries.db` + `annotations/<id>.pbtxt`) 与 `transcript.jsonl`
|
* 优先融合本地可用 SQLite、`conversation_summaries.db`、`annotations/<id>.pbtxt` 与 `transcript.jsonl`
|
||||||
* (及可选 `.deep_stats_cache.json`)恢复完整步骤耗时、TTFT、思考/正文拆分、10 通道上下文构成与真实标题。
|
* (及可选 `.deep_stats_cache.json`)恢复模型步骤、Token 消耗、轮次提问、派生子代理与真实标题。
|
||||||
*/
|
*/
|
||||||
function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, localSummary = null) {
|
function loadOfflineTranscriptConversation(
|
||||||
|
conv,
|
||||||
|
diskFiles,
|
||||||
|
externalByLower,
|
||||||
|
localSummary = null,
|
||||||
|
{ skipSqlite = false } = {}
|
||||||
|
) {
|
||||||
const cidLower = String(conv?.cascadeId || '').trim().toLowerCase();
|
const cidLower = String(conv?.cascadeId || '').trim().toLowerCase();
|
||||||
if (!cidLower) return null;
|
if (!cidLower) return null;
|
||||||
const extMatch = externalByLower?.get(cidLower) || null;
|
const extMatch = externalByLower?.get(cidLower) || null;
|
||||||
const sqliteDbPath = findBestSqliteDbPath(diskFiles);
|
const sqliteDbPath = skipSqlite ? '' : findBestSqliteDbPath(diskFiles);
|
||||||
const sqliteTraj = sqliteDbPath ? readLocalSqliteTrajectory(sqliteDbPath) : null;
|
const sqliteTraj = sqliteDbPath ? readLocalSqliteTrajectory(sqliteDbPath) : null;
|
||||||
const transcriptPath = findTranscriptPath(cidLower);
|
const transcriptPath = findTranscriptPath(cidLower);
|
||||||
|
|
||||||
const transcriptLines = [];
|
const transcriptLines = transcriptPath ? readTranscriptJsonlLines(transcriptPath) : [];
|
||||||
if (transcriptPath && existsSync(transcriptPath)) {
|
|
||||||
try {
|
|
||||||
const raw = readFileSync(transcriptPath, 'utf8');
|
|
||||||
if (typeof raw === 'string' && raw.trim()) {
|
|
||||||
for (const line of raw.split(/\r?\n/)) {
|
|
||||||
const trimmed = line.trim();
|
|
||||||
if (!trimmed) continue;
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(trimmed);
|
|
||||||
if (parsed && typeof parsed === 'object') {
|
|
||||||
transcriptLines.push(parsed);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// 忽略尾部半行或损坏 JSON 行
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// 忽略文件读取失败
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!sqliteTraj && transcriptLines.length === 0 && !extMatch) {
|
if (!sqliteTraj && transcriptLines.length === 0 && !extMatch) {
|
||||||
return null;
|
return null;
|
||||||
@@ -1295,65 +1416,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
|||||||
|
|
||||||
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
||||||
modelOrdinal += 1;
|
modelOrdinal += 1;
|
||||||
const isCheckpoint =
|
syntheticSteps.push(
|
||||||
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
synthesizeTranscriptModelStep(line, { stepIndex: rawIdx, deepStep })
|
||||||
const rawStatus = String(line.status || '').trim().toUpperCase();
|
);
|
||||||
const mappedStatus = /CANCEL/.test(rawStatus)
|
|
||||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
|
||||||
: /ERROR/.test(rawStatus)
|
|
||||||
? 'CORTEX_STEP_STATUS_ERROR'
|
|
||||||
: /INTERRUPT/.test(rawStatus)
|
|
||||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
|
||||||
: 'CORTEX_STEP_STATUS_DONE';
|
|
||||||
const finishedAt = String(
|
|
||||||
line.finished_generating_at ||
|
|
||||||
line.finishedGeneratingAt ||
|
|
||||||
line.completed_at ||
|
|
||||||
line.completedAt ||
|
|
||||||
''
|
|
||||||
).trim();
|
|
||||||
const modelKey =
|
|
||||||
String(line.model || line.generator_model || deepStep?.modelKey || 'unknown').trim() ||
|
|
||||||
'unknown';
|
|
||||||
const responseModel = String(line.response_model || deepStep?.responseModel || '').trim();
|
|
||||||
const apiProvider = String(line.api_provider || deepStep?.apiProvider || '').trim();
|
|
||||||
const modelDisplayName = String(
|
|
||||||
line.model_display_name || deepStep?.modelDisplayName || ''
|
|
||||||
).trim();
|
|
||||||
const thinkingTokens = Number(line.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0;
|
|
||||||
const responseTokens = line.response_tokens ?? deepStep?.responseTokens;
|
|
||||||
|
|
||||||
syntheticSteps.push({
|
|
||||||
type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE',
|
|
||||||
status: mappedStatus,
|
|
||||||
plannerResponse: {
|
|
||||||
response: typeof line.content === 'string' ? line.content : '',
|
|
||||||
thinking: typeof line.thinking === 'string' ? line.thinking : '',
|
|
||||||
toolCalls: Array.isArray(line.tool_calls) ? line.tool_calls : [],
|
|
||||||
...(thinkingTokens > 0 ? { thinkingTokens } : {}),
|
|
||||||
...(responseTokens !== undefined ? { responseTokens } : {}),
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
createdAt: String(line.created_at || line.createdAt || deepStep?.createdAt || ''),
|
|
||||||
...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}),
|
|
||||||
sourceTrajectoryStepInfo: {
|
|
||||||
stepIndex: Number.isFinite(Number(line.step_index)) ? Number(line.step_index) : rawIdx,
|
|
||||||
},
|
|
||||||
modelUsage: {
|
|
||||||
model: modelKey,
|
|
||||||
...(responseModel ? { responseModel } : {}),
|
|
||||||
...(apiProvider ? { apiProvider } : {}),
|
|
||||||
inputTokens: line.input_tokens ?? deepStep?.inputTokens ?? 0,
|
|
||||||
cacheReadTokens: line.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0,
|
|
||||||
outputTokens: line.output_tokens ?? deepStep?.outputTokens ?? 0,
|
|
||||||
...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}),
|
|
||||||
...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}),
|
|
||||||
},
|
|
||||||
...(modelDisplayName
|
|
||||||
? { generatorMetadata: [{ chatModel: { modelDisplayName } }] }
|
|
||||||
: {}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
steps = syntheticSteps.length > 0 ? extractModelSteps(syntheticSteps, []) : [];
|
steps = syntheticSteps.length > 0 ? extractModelSteps(syntheticSteps, []) : [];
|
||||||
@@ -1423,6 +1488,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
|||||||
rawRootCid && rawRootCid !== cidLower ? rawRootCid : parentConversationId;
|
rawRootCid && rawRootCid !== cidLower ? rawRootCid : parentConversationId;
|
||||||
|
|
||||||
const lastStepMs = steps[steps.length - 1]?.createdAtMs || 0;
|
const lastStepMs = steps[steps.length - 1]?.createdAtMs || 0;
|
||||||
|
const offlineSubagentRefs = extractSubagentRefsFromTranscriptLines(
|
||||||
|
transcriptLines,
|
||||||
|
sqliteTraj?.steps || [],
|
||||||
|
cidLower
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
steps,
|
steps,
|
||||||
fromSqlite,
|
fromSqlite,
|
||||||
@@ -1437,7 +1507,7 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
|||||||
extMatch?.lastModifiedMs || 0,
|
extMatch?.lastModifiedMs || 0,
|
||||||
lastStepMs
|
lastStepMs
|
||||||
),
|
),
|
||||||
subagentRefs: [],
|
subagentRefs: offlineSubagentRefs,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1761,6 +1831,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
|||||||
*/
|
*/
|
||||||
export async function enumerateAndSyncConversations({
|
export async function enumerateAndSyncConversations({
|
||||||
summariesObj = {},
|
summariesObj = {},
|
||||||
|
summariesFromLocalDb = false,
|
||||||
sideQuestionParents = {},
|
sideQuestionParents = {},
|
||||||
currentAccountName = '',
|
currentAccountName = '',
|
||||||
requestedConvId = '',
|
requestedConvId = '',
|
||||||
@@ -1943,12 +2014,22 @@ export async function enumerateAndSyncConversations({
|
|||||||
: null;
|
: null;
|
||||||
const dbPath = sqliteDbInfo?.dbPath || '';
|
const dbPath = sqliteDbInfo?.dbPath || '';
|
||||||
const diskFileSig = sqliteDbInfo?.sig || '';
|
const diskFileSig = sqliteDbInfo?.sig || '';
|
||||||
|
const hasPbFile = !isRemote && hasLocalPbFile(diskFiles);
|
||||||
|
const needFallbackDiskInfo =
|
||||||
|
!isRemote &&
|
||||||
|
diskFiles.length > 0 &&
|
||||||
|
(!sqliteDbInfo || hasPbFile || Boolean(cached?.offlineTranscriptFallback));
|
||||||
|
const fallbackDiskInfo = needFallbackDiskInfo ? computeFallbackDiskInfo(diskFiles) : null;
|
||||||
|
const fallbackDiskSig = fallbackDiskInfo?.sig || '';
|
||||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||||
const summaryMtimeMs = parseIsoMs(lastModifiedTime);
|
const summaryMtimeMs = parseIsoMs(lastModifiedTime);
|
||||||
const rawDiskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskFiles);
|
const rawDiskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskFiles);
|
||||||
const diskMtimeMs = sqliteDbInfo
|
const baseDiskMtimeMs = sqliteDbInfo
|
||||||
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
|
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
|
||||||
: rawDiskMtimeMs;
|
: rawDiskMtimeMs;
|
||||||
|
const diskMtimeMs = fallbackDiskInfo
|
||||||
|
? Math.max(baseDiskMtimeMs || 0, fallbackDiskInfo.mtimeMs || 0)
|
||||||
|
: baseDiskMtimeMs;
|
||||||
const appSource = isRemote
|
const appSource = isRemote
|
||||||
? 'ssh'
|
? 'ssh'
|
||||||
: inferAppSourceFromSummary(
|
: inferAppSourceFromSummary(
|
||||||
@@ -2067,6 +2148,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
diskMtimeMs,
|
diskMtimeMs,
|
||||||
dbPath,
|
dbPath,
|
||||||
diskFileSig,
|
diskFileSig,
|
||||||
|
fallbackDiskSig,
|
||||||
appSource,
|
appSource,
|
||||||
...(workspaceUri ? { workspaceUri } : {}),
|
...(workspaceUri ? { workspaceUri } : {}),
|
||||||
inSummaries: true,
|
inSummaries: true,
|
||||||
@@ -2105,6 +2187,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
diskMtimeMs,
|
diskMtimeMs,
|
||||||
dbPath,
|
dbPath,
|
||||||
diskFileSig,
|
diskFileSig,
|
||||||
|
fallbackDiskSig,
|
||||||
appSource,
|
appSource,
|
||||||
...(workspaceUri ? { workspaceUri } : {}),
|
...(workspaceUri ? { workspaceUri } : {}),
|
||||||
inSummaries: false,
|
inSummaries: false,
|
||||||
@@ -2135,6 +2218,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
diskMtimeMs,
|
diskMtimeMs,
|
||||||
dbPath,
|
dbPath,
|
||||||
diskFileSig,
|
diskFileSig,
|
||||||
|
fallbackDiskSig,
|
||||||
appSource,
|
appSource,
|
||||||
...(workspaceUri ? { workspaceUri } : {}),
|
...(workspaceUri ? { workspaceUri } : {}),
|
||||||
inSummaries: false,
|
inSummaries: false,
|
||||||
@@ -2158,12 +2242,14 @@ export async function enumerateAndSyncConversations({
|
|||||||
const nowPollMs = Date.now();
|
const nowPollMs = Date.now();
|
||||||
|
|
||||||
function buildConvSig(conv) {
|
function buildConvSig(conv) {
|
||||||
|
const fbSuffix = conv.fallbackDiskSig ? `~fb:${conv.fallbackDiskSig}` : '';
|
||||||
if (conv.dbPath && conv.diskFileSig && sqliteAvailable) {
|
if (conv.dbPath && conv.diskFileSig && sqliteAvailable) {
|
||||||
return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}`;
|
return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}${fbSuffix}`;
|
||||||
}
|
}
|
||||||
return conv.inSummaries
|
const base = conv.inSummaries
|
||||||
? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}`
|
? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}`
|
||||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||||
|
return `${base}${fbSuffix}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isFetchInCooldown(conv, sig) {
|
function isFetchInCooldown(conv, sig) {
|
||||||
@@ -2257,12 +2343,17 @@ export async function enumerateAndSyncConversations({
|
|||||||
const prev = getHydratedEntry(conv.cascadeId);
|
const prev = getHydratedEntry(conv.cascadeId);
|
||||||
let partialTailSteps = [];
|
let partialTailSteps = [];
|
||||||
let hasTailStepInfo = false;
|
let hasTailStepInfo = false;
|
||||||
|
let sqliteNotReady = false;
|
||||||
|
let sqliteProbedEmpty = false;
|
||||||
try {
|
try {
|
||||||
const cidLower = conv.cascadeId.toLowerCase();
|
const cidLower = conv.cascadeId.toLowerCase();
|
||||||
let trajRes = null;
|
let trajRes = null;
|
||||||
let loadedViaSqlite = false;
|
let loadedViaSqlite = false;
|
||||||
let transcriptFirstTitle = '';
|
let transcriptFirstTitle = '';
|
||||||
if (!isRemote && conv.dbPath && sqliteAvailable) {
|
if (!isRemote && conv.dbPath && sqliteAvailable) {
|
||||||
|
if (!isSqliteDbReadyForRead(conv.dbPath)) {
|
||||||
|
sqliteNotReady = true;
|
||||||
|
} else {
|
||||||
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
||||||
cascadeId: conv.cascadeId,
|
cascadeId: conv.cascadeId,
|
||||||
isRunning,
|
isRunning,
|
||||||
@@ -2275,6 +2366,27 @@ export async function enumerateAndSyncConversations({
|
|||||||
trajRes.trajectory.steps
|
trajRes.trajectory.steps
|
||||||
);
|
);
|
||||||
transcriptFirstTitle = enriched.firstUserTitle || '';
|
transcriptFirstTitle = enriched.firstUserTitle || '';
|
||||||
|
} else {
|
||||||
|
sqliteProbedEmpty = true;
|
||||||
|
const diskFilesForEmptyCheck = diskConvMap.get(cidLower) || [];
|
||||||
|
if (
|
||||||
|
!isRunning &&
|
||||||
|
Number(conv.rawStepCount || 0) === 0 &&
|
||||||
|
!hasLocalPbFile(diskFilesForEmptyCheck) &&
|
||||||
|
!findTranscriptPath(cidLower)
|
||||||
|
) {
|
||||||
|
// 已初始化但确实为 0 步(无 .pb 降级文件、摘要 0 步且无 transcript)的空本地会话,直接归档空缓存避免无意义 RPC 超时
|
||||||
|
trajRes = {
|
||||||
|
cascadeId: cidLower,
|
||||||
|
numTotalSteps: 0,
|
||||||
|
rawTableStepCount: 0,
|
||||||
|
steps: [],
|
||||||
|
generatorMetadata: [],
|
||||||
|
trajectory: { metadata: {}, steps: [], generatorMetadata: [] },
|
||||||
|
};
|
||||||
|
loadedViaSqlite = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!trajRes) {
|
if (!trajRes) {
|
||||||
@@ -2547,7 +2659,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
let offlineRecovered = false;
|
let offlineRecovered = false;
|
||||||
if (!isRemote && !conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) {
|
const cidLower = conv.cascadeId.toLowerCase();
|
||||||
|
const diskFiles = isRemote ? [] : diskConvMap.get(cidLower) || [];
|
||||||
|
if (!isRemote && (!prev || prev.offlineTranscriptFallback)) {
|
||||||
if (!lazyExternalByLower) {
|
if (!lazyExternalByLower) {
|
||||||
lazyExternalByLower = new Map();
|
lazyExternalByLower = new Map();
|
||||||
for (const ext of loadExternalDeepStatsCache().values()) {
|
for (const ext of loadExternalDeepStatsCache().values()) {
|
||||||
@@ -2559,13 +2673,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const cidLower = conv.cascadeId.toLowerCase();
|
|
||||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
|
||||||
const offlineFallback = loadOfflineTranscriptConversation(
|
const offlineFallback = loadOfflineTranscriptConversation(
|
||||||
conv,
|
conv,
|
||||||
diskFiles,
|
diskFiles,
|
||||||
lazyExternalByLower,
|
lazyExternalByLower,
|
||||||
localSummaryByLower.get(cidLower) || null
|
localSummaryByLower.get(cidLower) || null,
|
||||||
|
{ skipSqlite: sqliteProbedEmpty || sqliteNotReady }
|
||||||
);
|
);
|
||||||
if (offlineFallback) {
|
if (offlineFallback) {
|
||||||
offlineRecovered = true;
|
offlineRecovered = true;
|
||||||
@@ -2598,14 +2711,17 @@ export async function enumerateAndSyncConversations({
|
|||||||
title: offlineFallback.title,
|
title: offlineFallback.title,
|
||||||
...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}),
|
...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}),
|
||||||
...(conv.workspaceUri ? { workspaceUri: conv.workspaceUri } : {}),
|
...(conv.workspaceUri ? { workspaceUri: conv.workspaceUri } : {}),
|
||||||
|
...(conv.diskFileSig ? { diskFileSig: conv.diskFileSig } : {}),
|
||||||
lastModifiedMs: offlineFallback.lastModifiedMs,
|
lastModifiedMs: offlineFallback.lastModifiedMs,
|
||||||
diskMtimeMs: resolvedDiskMtime,
|
diskMtimeMs: resolvedDiskMtime,
|
||||||
|
rawStepCount: conv.rawStepCount ?? offlineStepsWithOwners.length,
|
||||||
wasRunning: isRunning,
|
wasRunning: isRunning,
|
||||||
offlineTranscriptFallback: true,
|
offlineTranscriptFallback: true,
|
||||||
...(offlineFallback.fromSqlite ? { offlineSqliteTelemetry: true } : {}),
|
...(offlineFallback.fromSqlite ? { offlineSqliteTelemetry: true } : {}),
|
||||||
contextLimitTelemetry: true,
|
contextLimitTelemetry: true,
|
||||||
speedClearedTelemetry: true,
|
speedClearedTelemetry: true,
|
||||||
turnRailTelemetry: true,
|
turnRailTelemetry: true,
|
||||||
|
wakeupTurnTelemetry: true,
|
||||||
contextGroupsTelemetry: 3,
|
contextGroupsTelemetry: 3,
|
||||||
anomalyTelemetry: 1,
|
anomalyTelemetry: 1,
|
||||||
steps: offlineStepsWithOwners,
|
steps: offlineStepsWithOwners,
|
||||||
@@ -2628,6 +2744,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
prev.title !== offlineEntry.title ||
|
prev.title !== offlineEntry.title ||
|
||||||
Boolean(prev.wasRunning) !== isRunning ||
|
Boolean(prev.wasRunning) !== isRunning ||
|
||||||
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
|
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
|
||||||
|
JSON.stringify(prev.subagentRefs || []) !== JSON.stringify(offlineEntry.subagentRefs || []) ||
|
||||||
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
|
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
|
||||||
if (!changed) offlineEntry.steps = prev.steps;
|
if (!changed) offlineEntry.steps = prev.steps;
|
||||||
setEntry(conv.cascadeId, offlineEntry);
|
setEntry(conv.cascadeId, offlineEntry);
|
||||||
@@ -2636,10 +2753,19 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
!offlineRecovered &&
|
||||||
|
!prev &&
|
||||||
|
!isRemote &&
|
||||||
|
(sqliteProbedEmpty || (!sqliteNotReady && hasLocalPbFile(diskFiles)))
|
||||||
|
) {
|
||||||
|
// 本地 .db 为空壳或会话仅落盘加密 .pb、且连 transcript.jsonl 与 RPC 均无法恢复步骤时,避免顶栏继续虚标原始 step_count
|
||||||
|
conv.stepCount = 0;
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
!offlineRecovered &&
|
!offlineRecovered &&
|
||||||
!(
|
!(
|
||||||
!conv.inSummaries &&
|
(!conv.inSummaries || summariesFromLocalDb || conv.appSource === 'cli') &&
|
||||||
/(?:\(404\)|\bnot_found\b|Language Server address unavailable)/i.test(
|
/(?:\(404\)|\bnot_found\b|Language Server address unavailable)/i.test(
|
||||||
String(err?.message || '')
|
String(err?.message || '')
|
||||||
)
|
)
|
||||||
@@ -2879,7 +3005,8 @@ export async function enumerateAndSyncConversations({
|
|||||||
cached.offlineTranscriptFallback &&
|
cached.offlineTranscriptFallback &&
|
||||||
!cached.offlineSqliteTelemetry &&
|
!cached.offlineSqliteTelemetry &&
|
||||||
hasBuiltinNodeSqlite() &&
|
hasBuiltinNodeSqlite() &&
|
||||||
hasLocalSqliteDb(diskConvMap.get(lowerCid))
|
hasLocalSqliteDb(diskConvMap.get(lowerCid)) &&
|
||||||
|
!String(cached.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:sqlite:`)
|
||||||
) {
|
) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -2895,8 +3022,13 @@ export async function enumerateAndSyncConversations({
|
|||||||
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
||||||
) return true;
|
) return true;
|
||||||
} else {
|
} else {
|
||||||
|
const shouldRetryOfflineUpgrade =
|
||||||
|
Boolean(cached.offlineTranscriptFallback) &&
|
||||||
|
(!summariesFromLocalDb ||
|
||||||
|
conv.appSource !== 'cli' ||
|
||||||
|
(forceRefresh && lowerCid === reqLower));
|
||||||
if (
|
if (
|
||||||
cached.offlineTranscriptFallback ||
|
shouldRetryOfflineUpgrade ||
|
||||||
missingSubagentRefs ||
|
missingSubagentRefs ||
|
||||||
!sigMatches ||
|
!sigMatches ||
|
||||||
isRunning ||
|
isRunning ||
|
||||||
@@ -2991,9 +3123,17 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (!subConv) {
|
if (!subConv) {
|
||||||
const subDiskFiles = diskConvMap.get(subCid) || [];
|
const subDiskFiles = diskConvMap.get(subCid) || [];
|
||||||
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
|
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
|
||||||
|
const subNeedFb =
|
||||||
|
!isRemote &&
|
||||||
|
subDiskFiles.length > 0 &&
|
||||||
|
(!subDbInfo ||
|
||||||
|
hasLocalPbFile(subDiskFiles) ||
|
||||||
|
Boolean(subCached?.offlineTranscriptFallback));
|
||||||
|
const subFallbackInfo = subNeedFb ? computeFallbackDiskInfo(subDiskFiles) : null;
|
||||||
const diskMtimeMs = Math.max(
|
const diskMtimeMs = Math.max(
|
||||||
readConversationMtime(subDiskFiles),
|
readConversationMtime(subDiskFiles),
|
||||||
subDbInfo?.mtimeMs || 0
|
subDbInfo?.mtimeMs || 0,
|
||||||
|
subFallbackInfo?.mtimeMs || 0
|
||||||
);
|
);
|
||||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||||
const stepCount = Number(subCached?.steps?.length || 0);
|
const stepCount = Number(subCached?.steps?.length || 0);
|
||||||
@@ -3013,6 +3153,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
diskMtimeMs,
|
diskMtimeMs,
|
||||||
dbPath: subDbInfo?.dbPath || '',
|
dbPath: subDbInfo?.dbPath || '',
|
||||||
diskFileSig: subDbInfo?.sig || '',
|
diskFileSig: subDbInfo?.sig || '',
|
||||||
|
fallbackDiskSig: subFallbackInfo?.sig || '',
|
||||||
appSource: isRemote
|
appSource: isRemote
|
||||||
? 'ssh'
|
? 'ssh'
|
||||||
: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
|
: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
|
||||||
@@ -3049,6 +3190,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
const targetCacheKey = subConv.cascadeId;
|
const targetCacheKey = subConv.cascadeId;
|
||||||
const existingSubCache = getEntry(targetCacheKey);
|
const existingSubCache = getEntry(targetCacheKey);
|
||||||
const isSelectedSubFamily = rootId === selectedRootId;
|
const isSelectedSubFamily = rootId === selectedRootId;
|
||||||
|
const subSig = buildConvSig(subConv);
|
||||||
|
const canUpgradeOfflineSub =
|
||||||
|
Boolean(existingSubCache?.offlineTranscriptFallback && subConv.inSummaries) &&
|
||||||
|
(!summariesFromLocalDb || subConv.appSource !== 'cli') &&
|
||||||
|
!attemptedFetchIds.has(subCid) &&
|
||||||
|
!isFetchInCooldown(subConv, subSig);
|
||||||
const isImgGenSub =
|
const isImgGenSub =
|
||||||
String(
|
String(
|
||||||
subConv.subagentSpec?.typeName ||
|
subConv.subagentSpec?.typeName ||
|
||||||
@@ -3060,7 +3207,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
.toLowerCase() === 'image-generator';
|
.toLowerCase() === 'image-generator';
|
||||||
const hasValidSubCache =
|
const hasValidSubCache =
|
||||||
existingSubCache &&
|
existingSubCache &&
|
||||||
!(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) &&
|
!canUpgradeOfflineSub &&
|
||||||
String(existingSubCache.signature || '').startsWith(
|
String(existingSubCache.signature || '').startsWith(
|
||||||
subConv.dbPath && sqliteAvailable
|
subConv.dbPath && sqliteAvailable
|
||||||
? `${CACHE_SCHEMA_VERSION}:sqlite:`
|
? `${CACHE_SCHEMA_VERSION}:sqlite:`
|
||||||
@@ -3110,7 +3257,6 @@ export async function enumerateAndSyncConversations({
|
|||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const subSig = buildConvSig(subConv);
|
|
||||||
if (!attemptedFetchIds.has(subCid) && !isFetchInCooldown(subConv, subSig)) {
|
if (!attemptedFetchIds.has(subCid) && !isFetchInCooldown(subConv, subSig)) {
|
||||||
missingSubagentsToFetch.push(subConv);
|
missingSubagentsToFetch.push(subConv);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,15 @@
|
|||||||
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
|
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync, statSync } from 'node:fs';
|
import { closeSync, existsSync, openSync, readSync, statSync } from 'node:fs';
|
||||||
|
|
||||||
export const SQLITE_IN_CHUNK_SIZE = 400;
|
export const SQLITE_IN_CHUNK_SIZE = 400;
|
||||||
|
const SQLITE_MIN_READY_BYTES = 4096;
|
||||||
|
const SQLITE_HEADER_BYTES = 100;
|
||||||
|
const SQLITE_WAL_HEADER_BYTES = 32;
|
||||||
|
const SQLITE_MAGIC_PREFIX = 'SQLite format 3\0';
|
||||||
|
const MAX_SQLITE_READY_MEMO = 512;
|
||||||
|
const sqliteWalReadyMemo = new Map();
|
||||||
|
|
||||||
let sqliteResolved = false;
|
let sqliteResolved = false;
|
||||||
let sqliteDatabaseSyncCtor = null;
|
let sqliteDatabaseSyncCtor = null;
|
||||||
@@ -59,8 +65,117 @@ export function hasBuiltinNodeSqlite() {
|
|||||||
return Boolean(getNodeSqliteDatabaseSync());
|
return Boolean(getNodeSqliteDatabaseSync());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过零 SQLite 锁的 100 字节文件头探测判断本地 `.db` 是否已完成表结构初始化(或已切入 WAL 且含有效提交帧)。
|
||||||
|
*
|
||||||
|
* Windows 下宿主(如 `agy` CLI)新建 `<cid>.db` 执行 `schema init` / `PRAGMA journal_mode = WAL` 的数毫秒内,
|
||||||
|
* 若外部进程对 0 字节或仍处于回滚日志模式(`writeVersion !== 2`)的库发起 `sqlite3_open_v2` 查询并持有 `SHARED` 锁,
|
||||||
|
* 会直接触发宿主 `trajectory db schema init: database is locked` 并迫使整场会话永久降级至加密 `.pb`。
|
||||||
|
* 纯 `fs.openSync` / `fs.readSync` 不申请任何 SQLite 字节区间锁(`LockFileEx`),可安全跳过初始化途中的半成品库。
|
||||||
|
*
|
||||||
|
* @param {string} dbPath
|
||||||
|
* @param {{ dbStat?: import('node:fs').Stats | null, walStat?: import('node:fs').Stats | null, skipWalStat?: boolean }} [opts={}]
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isSqliteDbReadyForRead(
|
||||||
|
dbPath,
|
||||||
|
{ dbStat: preDbStat = null, walStat: preWalStat = null, skipWalStat = false } = {}
|
||||||
|
) {
|
||||||
|
if (!dbPath || typeof dbPath !== 'string') return false;
|
||||||
|
if (
|
||||||
|
typeof openSync !== 'function' ||
|
||||||
|
typeof readSync !== 'function' ||
|
||||||
|
typeof closeSync !== 'function'
|
||||||
|
) {
|
||||||
|
return typeof globalThis.DatabaseSync === 'function';
|
||||||
|
}
|
||||||
|
|
||||||
|
let dbStat = preDbStat;
|
||||||
|
if (!dbStat) {
|
||||||
|
try {
|
||||||
|
dbStat = statSync(dbPath, { throwIfNoEntry: false });
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const dbSize = Number(dbStat?.size || 0);
|
||||||
|
if (!dbStat || dbSize < SQLITE_MIN_READY_BYTES) {
|
||||||
|
sqliteWalReadyMemo.delete(dbPath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const birthKey = `${Number(dbStat.birthtimeMs || 0)}:${Number(dbStat.ino || 0)}`;
|
||||||
|
const cachedReady = sqliteWalReadyMemo.get(dbPath);
|
||||||
|
if (cachedReady && cachedReady.birthKey === birthKey && dbSize >= cachedReady.minVerifiedSize) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const journalStat = statSync(`${dbPath}-journal`, { throwIfNoEntry: false });
|
||||||
|
if (journalStat && Number(journalStat.size || 0) > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略瞬时回滚日志探测异常
|
||||||
|
}
|
||||||
|
|
||||||
|
let fd = -1;
|
||||||
|
try {
|
||||||
|
fd = openSync(dbPath, 'r');
|
||||||
|
const header = Buffer.allocUnsafe(SQLITE_HEADER_BYTES);
|
||||||
|
const bytesRead = readSync(fd, header, 0, SQLITE_HEADER_BYTES, 0);
|
||||||
|
if (bytesRead < SQLITE_HEADER_BYTES) return false;
|
||||||
|
if (header.toString('latin1', 0, 16) !== SQLITE_MAGIC_PREFIX) return false;
|
||||||
|
|
||||||
|
const writeVersion = header[18];
|
||||||
|
const readVersion = header[19];
|
||||||
|
const pageCount = header.readUInt32BE(28);
|
||||||
|
const schemaCookie = header.readUInt32BE(40);
|
||||||
|
const isWalMode = writeVersion === 2 && readVersion === 2;
|
||||||
|
|
||||||
|
if (isWalMode) {
|
||||||
|
let hasCommittedSchema = pageCount >= 2 && schemaCookie > 0;
|
||||||
|
if (!hasCommittedSchema) {
|
||||||
|
let walStat = preWalStat;
|
||||||
|
if (!walStat && !skipWalStat) {
|
||||||
|
try {
|
||||||
|
walStat = statSync(`${dbPath}-wal`, { throwIfNoEntry: false });
|
||||||
|
} catch {
|
||||||
|
walStat = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hasCommittedSchema = Number(walStat?.size || 0) > SQLITE_WAL_HEADER_BYTES;
|
||||||
|
}
|
||||||
|
if (!hasCommittedSchema) return false;
|
||||||
|
|
||||||
|
if (sqliteWalReadyMemo.size >= MAX_SQLITE_READY_MEMO && !sqliteWalReadyMemo.has(dbPath)) {
|
||||||
|
const oldestKey = sqliteWalReadyMemo.keys().next().value;
|
||||||
|
if (oldestKey !== undefined) sqliteWalReadyMemo.delete(oldestKey);
|
||||||
|
}
|
||||||
|
sqliteWalReadyMemo.set(dbPath, {
|
||||||
|
birthKey,
|
||||||
|
minVerifiedSize: SQLITE_MIN_READY_BYTES,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return pageCount >= 2 && schemaCookie > 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
if (fd >= 0) {
|
||||||
|
try {
|
||||||
|
closeSync(fd);
|
||||||
|
} catch {
|
||||||
|
// 忽略关闭异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
||||||
|
* 实际打开前由 `withReadOnlySqliteDb` 经 `isSqliteDbReadyForRead` 拦截未完成 `schema init` 的空文件。
|
||||||
*
|
*
|
||||||
* @param {string} dbPath
|
* @param {string} dbPath
|
||||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||||
@@ -104,7 +219,7 @@ export function isSqliteBusyError(err) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
* 打开前先执行无锁头部就绪校验;遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||||
*
|
*
|
||||||
* @template T
|
* @template T
|
||||||
* @param {string} dbPath
|
* @param {string} dbPath
|
||||||
@@ -114,6 +229,7 @@ export function isSqliteBusyError(err) {
|
|||||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||||
if (!DatabaseSync) return null;
|
if (!DatabaseSync) return null;
|
||||||
|
if (!isSqliteDbReadyForRead(dbPath)) return null;
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
let db = null;
|
let db = null;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -942,6 +942,7 @@ async function readTelemetrySources(
|
|||||||
summariesObj: localSummaries.available
|
summariesObj: localSummaries.available
|
||||||
? localSummaries.summariesObj
|
? localSummaries.summariesObj
|
||||||
: allTrajRes?.trajectorySummaries || {},
|
: allTrajRes?.trajectorySummaries || {},
|
||||||
|
summariesFromLocalDb: localSummaries.available,
|
||||||
sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {},
|
sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {},
|
||||||
currentAccountName: accountScope,
|
currentAccountName: accountScope,
|
||||||
requestedConvId,
|
requestedConvId,
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 共享的 `transcript.jsonl` / `transcript_full.jsonl` 安全解析与离线模型步骤合成辅助模块。
|
||||||
|
*
|
||||||
|
* 供 `local-scanner.mjs` 与 `cli-statusline.mjs` 共用,避免重复维护状态归一化、Token 字段映射
|
||||||
|
* 以及超大 `transcript_full.jsonl` 的体积保护逻辑。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export const TRANSCRIPT_COMPACT_MAX_BYTES = 24 * 1024 * 1024;
|
||||||
|
export const TRANSCRIPT_FULL_MAX_BYTES = 12 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在单个日志目录内优先解析 `transcript.jsonl`,不存在时按体积上限安全回退至 `transcript_full.jsonl`。
|
||||||
|
*
|
||||||
|
* @param {string} logsDir
|
||||||
|
* @param {{ maxFullBytes?: number }} [opts={}]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function resolveTranscriptPathInLogsDir(
|
||||||
|
logsDir,
|
||||||
|
{ maxFullBytes = TRANSCRIPT_FULL_MAX_BYTES } = {}
|
||||||
|
) {
|
||||||
|
if (!logsDir || typeof logsDir !== 'string') return '';
|
||||||
|
const primary = join(logsDir, 'transcript.jsonl');
|
||||||
|
if (existsSync(primary)) return primary;
|
||||||
|
const full = join(logsDir, 'transcript_full.jsonl');
|
||||||
|
if (!existsSync(full)) return '';
|
||||||
|
if (Number.isFinite(maxFullBytes) && maxFullBytes > 0) {
|
||||||
|
try {
|
||||||
|
const st = statSync(full, { throwIfNoEntry: false });
|
||||||
|
if (st && Number(st.size || 0) > maxFullBytes) return '';
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安全读取并解析 JSONL 格式的 transcript 文件,按文件类型施加体积保护并跳过损坏行。
|
||||||
|
*
|
||||||
|
* @param {string} transcriptPath
|
||||||
|
* @param {{ maxBytes?: number }} [opts={}]
|
||||||
|
* @returns {object[]}
|
||||||
|
*/
|
||||||
|
export function readTranscriptJsonlLines(transcriptPath, { maxBytes } = {}) {
|
||||||
|
if (!transcriptPath || !existsSync(transcriptPath)) return [];
|
||||||
|
const isFullFile = /transcript_full\.jsonl$/i.test(transcriptPath);
|
||||||
|
const limitBytes =
|
||||||
|
Number.isFinite(maxBytes) && maxBytes > 0
|
||||||
|
? maxBytes
|
||||||
|
: isFullFile
|
||||||
|
? TRANSCRIPT_FULL_MAX_BYTES
|
||||||
|
: TRANSCRIPT_COMPACT_MAX_BYTES;
|
||||||
|
try {
|
||||||
|
const st = statSync(transcriptPath, { throwIfNoEntry: false });
|
||||||
|
if (st && Number(st.size || 0) > limitBytes) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
let raw = '';
|
||||||
|
try {
|
||||||
|
raw = readFileSync(transcriptPath, 'utf8');
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||||
|
|
||||||
|
const lines = [];
|
||||||
|
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') {
|
||||||
|
lines.push(parsed);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略尾部半行或损坏 JSON 行
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将单条含 Token 统计的 transcript JSONL 记录合成为标准轨迹模型步骤对象。
|
||||||
|
*
|
||||||
|
* @param {object} line
|
||||||
|
* @param {{ stepIndex?: number, deepStep?: object | null }} [opts={}]
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
export function synthesizeTranscriptModelStep(line, { stepIndex = 0, deepStep = null } = {}) {
|
||||||
|
const rawType = String(line?.type || '').trim();
|
||||||
|
const upperType = rawType.toUpperCase();
|
||||||
|
const isCheckpoint =
|
||||||
|
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||||
|
const rawStatus = String(line?.status || '').trim().toUpperCase();
|
||||||
|
const mappedStatus = /CANCEL/.test(rawStatus)
|
||||||
|
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||||
|
: /ERROR/.test(rawStatus)
|
||||||
|
? 'CORTEX_STEP_STATUS_ERROR'
|
||||||
|
: /INTERRUPT/.test(rawStatus)
|
||||||
|
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||||
|
: 'CORTEX_STEP_STATUS_DONE';
|
||||||
|
const finishedAt = String(
|
||||||
|
line?.finished_generating_at ||
|
||||||
|
line?.finishedGeneratingAt ||
|
||||||
|
line?.completed_at ||
|
||||||
|
line?.completedAt ||
|
||||||
|
''
|
||||||
|
).trim();
|
||||||
|
const modelKey =
|
||||||
|
String(line?.model || line?.generator_model || deepStep?.modelKey || 'unknown').trim() ||
|
||||||
|
'unknown';
|
||||||
|
const responseModel = String(line?.response_model || deepStep?.responseModel || '').trim();
|
||||||
|
const apiProvider = String(line?.api_provider || deepStep?.apiProvider || '').trim();
|
||||||
|
const modelDisplayName = String(
|
||||||
|
line?.model_display_name || deepStep?.modelDisplayName || ''
|
||||||
|
).trim();
|
||||||
|
const thinkingTokens = Number(line?.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0;
|
||||||
|
const responseTokens = line?.response_tokens ?? deepStep?.responseTokens;
|
||||||
|
const resolvedStepIndex = Number.isFinite(Number(line?.step_index))
|
||||||
|
? Number(line.step_index)
|
||||||
|
: stepIndex;
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE',
|
||||||
|
status: mappedStatus,
|
||||||
|
plannerResponse: {
|
||||||
|
response: typeof line?.content === 'string' ? line.content : '',
|
||||||
|
thinking: typeof line?.thinking === 'string' ? line.thinking : '',
|
||||||
|
toolCalls: Array.isArray(line?.tool_calls) ? line.tool_calls : [],
|
||||||
|
...(thinkingTokens > 0 ? { thinkingTokens } : {}),
|
||||||
|
...(responseTokens !== undefined ? { responseTokens } : {}),
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
createdAt: String(line?.created_at || line?.createdAt || deepStep?.createdAt || ''),
|
||||||
|
...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: resolvedStepIndex },
|
||||||
|
modelUsage: {
|
||||||
|
model: modelKey,
|
||||||
|
...(responseModel ? { responseModel } : {}),
|
||||||
|
...(apiProvider ? { apiProvider } : {}),
|
||||||
|
inputTokens: line?.input_tokens ?? deepStep?.inputTokens ?? 0,
|
||||||
|
cacheReadTokens: line?.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0,
|
||||||
|
outputTokens: line?.output_tokens ?? deepStep?.outputTokens ?? 0,
|
||||||
|
...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}),
|
||||||
|
...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}),
|
||||||
|
},
|
||||||
|
...(modelDisplayName
|
||||||
|
? { generatorMetadata: [{ chatModel: { modelDisplayName } }] }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 `transcript.jsonl`(或受体积保护的 `transcript_full.jsonl`)构建 CLI 状态栏兼容的轨迹载荷。
|
||||||
|
*
|
||||||
|
* @param {string} transcriptPath
|
||||||
|
* @param {string} cascadeId
|
||||||
|
* @param {{ maxBytes?: number }} [opts={}]
|
||||||
|
* @returns {{ cascadeId: string, steps: object[], generatorMetadata: object[] } | null}
|
||||||
|
*/
|
||||||
|
export function buildTranscriptFallbackTrajectory(transcriptPath, cascadeId, opts = {}) {
|
||||||
|
const lines = readTranscriptJsonlLines(transcriptPath, opts);
|
||||||
|
if (lines.length === 0) return null;
|
||||||
|
const rawSteps = [];
|
||||||
|
for (let idx = 0; idx < lines.length; idx++) {
|
||||||
|
const parsed = lines[idx];
|
||||||
|
const hasTokens =
|
||||||
|
parsed.input_tokens !== undefined ||
|
||||||
|
parsed.cache_read_tokens !== undefined ||
|
||||||
|
parsed.output_tokens !== undefined;
|
||||||
|
if (!hasTokens) {
|
||||||
|
rawSteps.push(parsed);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rawSteps.push(synthesizeTranscriptModelStep(parsed, { stepIndex: idx }));
|
||||||
|
}
|
||||||
|
return rawSteps.length > 0 ? { cascadeId, steps: rawSteps, generatorMetadata: [] } : null;
|
||||||
|
}
|
||||||
@@ -37,6 +37,10 @@ import {
|
|||||||
readLocalSummaryIndex,
|
readLocalSummaryIndex,
|
||||||
} from './backend/cli-sqlite-reader.mjs';
|
} from './backend/cli-sqlite-reader.mjs';
|
||||||
import { computeSqliteWalSig, withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
import { computeSqliteWalSig, withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
||||||
|
import {
|
||||||
|
buildTranscriptFallbackTrajectory,
|
||||||
|
resolveTranscriptPathInLogsDir,
|
||||||
|
} from './backend/transcript-fallback.mjs';
|
||||||
import {
|
import {
|
||||||
buildCliJsonStatusOutput,
|
buildCliJsonStatusOutput,
|
||||||
ensureCliStatusLineConfigured,
|
ensureCliStatusLineConfigured,
|
||||||
@@ -189,8 +193,13 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveCliTranscriptPath(cliRoot, cid) {
|
||||||
|
if (!cliRoot || !cid) return '';
|
||||||
|
return resolveTranscriptPathInLogsDir(join(cliRoot, 'brain', cid, '.system_generated', 'logs'));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析当前 CLI 窗口对应的本地 `.db` 会话轨迹并计算最新测速、延迟、缓存与成本指标。
|
* 解析当前 CLI 窗口对应的本地 `.db`(或降级 `.pb` + `transcript.jsonl`)会话轨迹并计算最新测速、延迟、缓存与成本指标。
|
||||||
*
|
*
|
||||||
* @param {{ cliRoot: string, stdinData?: object|null, nowMs?: number }} params
|
* @param {{ cliRoot: string, stdinData?: object|null, nowMs?: number }} params
|
||||||
*/
|
*/
|
||||||
@@ -234,18 +243,24 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
'';
|
'';
|
||||||
if (!targetCid && effectiveCwd) {
|
if (!targetCid && effectiveCwd) {
|
||||||
const ftsCid = findConversationIdByWorkspaceFts(cliRoot, effectiveCwd);
|
const ftsCid = findConversationIdByWorkspaceFts(cliRoot, effectiveCwd);
|
||||||
if (ftsCid && existsSync(join(convDir, `${ftsCid}.db`))) {
|
if (
|
||||||
|
ftsCid &&
|
||||||
|
(existsSync(join(convDir, `${ftsCid}.db`)) || existsSync(join(convDir, `${ftsCid}.pb`)))
|
||||||
|
) {
|
||||||
targetCid = ftsCid;
|
targetCid = ftsCid;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let dbPath = targetCid ? join(convDir, `${targetCid}.db`) : '';
|
let dbPath = targetCid ? join(convDir, `${targetCid}.db`) : '';
|
||||||
if (!dbPath || !existsSync(dbPath)) {
|
let pbPath = targetCid ? join(convDir, `${targetCid}.pb`) : '';
|
||||||
|
if (!targetCid || (!existsSync(dbPath) && !existsSync(pbPath))) {
|
||||||
let candidates = [];
|
let candidates = [];
|
||||||
try {
|
try {
|
||||||
candidates = readdirSync(convDir)
|
const byCid = new Map();
|
||||||
.filter((name) => name.endsWith('.db'))
|
for (const name of readdirSync(convDir)) {
|
||||||
.map((name) => {
|
const isDb = name.endsWith('.db');
|
||||||
|
const isPb = !isDb && name.endsWith('.pb');
|
||||||
|
if (!isDb && !isPb) continue;
|
||||||
const cid = name.slice(0, -3).toLowerCase();
|
const cid = name.slice(0, -3).toLowerCase();
|
||||||
const full = join(convDir, name);
|
const full = join(convDir, name);
|
||||||
let mtimeMs = 0;
|
let mtimeMs = 0;
|
||||||
@@ -254,15 +269,23 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
} catch {
|
} catch {
|
||||||
// 忽略单文件 stat 异常
|
// 忽略单文件 stat 异常
|
||||||
}
|
}
|
||||||
|
const existing = byCid.get(cid);
|
||||||
|
if (!existing) {
|
||||||
const summary = summariesMap.get(cid);
|
const summary = summariesMap.get(cid);
|
||||||
return {
|
byCid.set(cid, {
|
||||||
cid,
|
cid,
|
||||||
full,
|
dbFull: isDb ? full : '',
|
||||||
|
pbFull: isPb ? full : '',
|
||||||
mtimeMs,
|
mtimeMs,
|
||||||
isSubagent: Boolean(summary?.parentConversationId),
|
isSubagent: Boolean(summary?.parentConversationId),
|
||||||
};
|
});
|
||||||
})
|
} else {
|
||||||
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
if (isDb) existing.dbFull = full;
|
||||||
|
if (isPb) existing.pbFull = full;
|
||||||
|
if (mtimeMs > existing.mtimeMs) existing.mtimeMs = mtimeMs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates = Array.from(byCid.values()).sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||||
} catch {
|
} catch {
|
||||||
candidates = [];
|
candidates = [];
|
||||||
}
|
}
|
||||||
@@ -270,11 +293,14 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
const picked = candidates.find((c) => !c.isSubagent) || candidates[0];
|
const picked = candidates.find((c) => !c.isSubagent) || candidates[0];
|
||||||
if (picked) {
|
if (picked) {
|
||||||
targetCid = picked.cid;
|
targetCid = picked.cid;
|
||||||
dbPath = picked.full;
|
dbPath = picked.dbFull || join(convDir, `${picked.cid}.db`);
|
||||||
|
pbPath = picked.pbFull || join(convDir, `${picked.cid}.pb`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!dbPath || !existsSync(dbPath)) {
|
const hasDbFile = Boolean(dbPath && existsSync(dbPath));
|
||||||
|
const hasPbFile = Boolean(pbPath && existsSync(pbPath));
|
||||||
|
if (!hasDbFile && !hasPbFile) {
|
||||||
return {
|
return {
|
||||||
found: false,
|
found: false,
|
||||||
runningRootCount,
|
runningRootCount,
|
||||||
@@ -282,23 +308,69 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (hasDbFile) {
|
||||||
const parentLink = readLocalSqliteParentLink(dbPath);
|
const parentLink = readLocalSqliteParentLink(dbPath);
|
||||||
if (parentLink?.parentConversationId || parentLink?.rootConversationId) {
|
if (parentLink?.parentConversationId || parentLink?.rootConversationId) {
|
||||||
const candidateRootId = parentLink.rootConversationId || parentLink.parentConversationId;
|
const candidateRootId = parentLink.rootConversationId || parentLink.parentConversationId;
|
||||||
const rootDb = join(convDir, `${candidateRootId}.db`);
|
const rootDb = join(convDir, `${candidateRootId}.db`);
|
||||||
if (candidateRootId && existsSync(rootDb)) {
|
const rootPb = join(convDir, `${candidateRootId}.pb`);
|
||||||
|
if (candidateRootId && (existsSync(rootDb) || existsSync(rootPb))) {
|
||||||
targetCid = candidateRootId;
|
targetCid = candidateRootId;
|
||||||
dbPath = rootDb;
|
dbPath = rootDb;
|
||||||
|
pbPath = rootPb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const summaryParent = summariesMap.get(targetCid)?.parentConversationId || '';
|
||||||
|
if (summaryParent) {
|
||||||
|
const rootDb = join(convDir, `${summaryParent}.db`);
|
||||||
|
const rootPb = join(convDir, `${summaryParent}.pb`);
|
||||||
|
if (existsSync(rootDb) || existsSync(rootPb)) {
|
||||||
|
targetCid = summaryParent;
|
||||||
|
dbPath = rootDb;
|
||||||
|
pbPath = rootPb;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const walInfo = computeSqliteWalSig(dbPath);
|
const walInfo = dbPath ? computeSqliteWalSig(dbPath) : { exists: false, mtimeMs: 0, sig: '' };
|
||||||
const dbMtimeMs = walInfo.mtimeMs || 0;
|
let fallbackMtimeMs = 0;
|
||||||
|
let fallbackSigPart = '';
|
||||||
|
if (!walInfo.exists || (pbPath && existsSync(pbPath))) {
|
||||||
|
const fbParts = [];
|
||||||
|
if (pbPath) {
|
||||||
|
try {
|
||||||
|
const pbSt = statSync(pbPath, { throwIfNoEntry: false });
|
||||||
|
if (pbSt) {
|
||||||
|
fallbackMtimeMs = Math.max(fallbackMtimeMs, Number(pbSt.mtimeMs || 0));
|
||||||
|
fbParts.push(`p:${Math.floor(Number(pbSt.mtimeMs || 0))}:${Number(pbSt.size || 0)}`);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略 stat 异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const trPath = resolveCliTranscriptPath(cliRoot, targetCid);
|
||||||
|
if (trPath) {
|
||||||
|
try {
|
||||||
|
const trSt = statSync(trPath, { throwIfNoEntry: false });
|
||||||
|
if (trSt) {
|
||||||
|
fallbackMtimeMs = Math.max(fallbackMtimeMs, Number(trSt.mtimeMs || 0));
|
||||||
|
fbParts.push(`t:${Math.floor(Number(trSt.mtimeMs || 0))}:${Number(trSt.size || 0)}`);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略 stat 异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fallbackSigPart = fbParts.join(',');
|
||||||
|
}
|
||||||
|
const dbMtimeMs = Math.max(walInfo.mtimeMs || 0, fallbackMtimeMs);
|
||||||
const targetLower = String(targetCid || '').toLowerCase();
|
const targetLower = String(targetCid || '').toLowerCase();
|
||||||
const targetIsRunning = freshRunningRootIds.includes(targetLower);
|
const targetIsRunning = freshRunningRootIds.includes(targetLower);
|
||||||
|
|
||||||
const cliTrajMemoFile = join(DATA_DIR, 'cli-statusline-traj-memo.json');
|
const effectiveDataDir = String(process.env.USAGE_MONITOR_DATA_DIR || '').trim() || DATA_DIR;
|
||||||
const prevMemo = walInfo.sig ? loadJson(cliTrajMemoFile, null) : null;
|
const cliTrajMemoFile = join(effectiveDataDir, 'cli-statusline-traj-memo.json');
|
||||||
|
const combinedSig = [walInfo.sig, fallbackSigPart].filter(Boolean).join('~');
|
||||||
|
const prevMemo = combinedSig ? loadJson(cliTrajMemoFile, null) : null;
|
||||||
const prevOtherCache =
|
const prevOtherCache =
|
||||||
prevMemo && typeof prevMemo.otherWaiting === 'object' && prevMemo.otherWaiting !== null
|
prevMemo && typeof prevMemo.otherWaiting === 'object' && prevMemo.otherWaiting !== null
|
||||||
? prevMemo.otherWaiting
|
? prevMemo.otherWaiting
|
||||||
@@ -342,7 +414,7 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetMemoKey = walInfo.sig ? `v1::${dbPath}::${walInfo.sig}` : '';
|
const targetMemoKey = combinedSig ? `v1::${targetCid}::${combinedSig}` : '';
|
||||||
if (
|
if (
|
||||||
targetMemoKey &&
|
targetMemoKey &&
|
||||||
prevMemo?.targetKey === targetMemoKey &&
|
prevMemo?.targetKey === targetMemoKey &&
|
||||||
@@ -401,21 +473,44 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let traj = readLocalSqliteTrajectory(dbPath, {
|
let traj = walInfo.exists
|
||||||
|
? readLocalSqliteTrajectory(dbPath, {
|
||||||
cascadeId: targetCid,
|
cascadeId: targetCid,
|
||||||
isRunning: targetIsRunning,
|
isRunning: targetIsRunning,
|
||||||
});
|
})
|
||||||
|
: null;
|
||||||
if (traj?.parentConversationId) {
|
if (traj?.parentConversationId) {
|
||||||
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
|
const rootCid = traj.rootConversationId || traj.parentConversationId;
|
||||||
if (rootDb !== dbPath && existsSync(rootDb)) {
|
const rootDb = join(convDir, `${rootCid}.db`);
|
||||||
|
const rootPb = join(convDir, `${rootCid}.pb`);
|
||||||
|
if (rootCid && rootCid !== targetCid) {
|
||||||
|
if (existsSync(rootDb)) {
|
||||||
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
|
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
|
||||||
if (rootTraj) {
|
if (rootTraj) {
|
||||||
targetCid = traj.rootConversationId || traj.parentConversationId;
|
targetCid = rootCid;
|
||||||
dbPath = rootDb;
|
dbPath = rootDb;
|
||||||
|
pbPath = rootPb;
|
||||||
traj = rootTraj;
|
traj = rootTraj;
|
||||||
|
} else if (existsSync(rootPb) || resolveCliTranscriptPath(cliRoot, rootCid)) {
|
||||||
|
targetCid = rootCid;
|
||||||
|
dbPath = rootDb;
|
||||||
|
pbPath = rootPb;
|
||||||
|
traj = null;
|
||||||
|
}
|
||||||
|
} else if (existsSync(rootPb) || resolveCliTranscriptPath(cliRoot, rootCid)) {
|
||||||
|
targetCid = rootCid;
|
||||||
|
dbPath = rootDb;
|
||||||
|
pbPath = rootPb;
|
||||||
|
traj = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
|
||||||
|
const fallbackTranscriptPath = resolveCliTranscriptPath(cliRoot, targetCid);
|
||||||
|
traj = fallbackTranscriptPath
|
||||||
|
? buildTranscriptFallbackTrajectory(fallbackTranscriptPath, targetCid)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
|
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
|
||||||
if (targetMemoKey) {
|
if (targetMemoKey) {
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/model-pricing.mjs',
|
'../backend/model-pricing.mjs',
|
||||||
'../backend/quota-pools.mjs',
|
'../backend/quota-pools.mjs',
|
||||||
'../backend/quota-reservation.mjs',
|
'../backend/quota-reservation.mjs',
|
||||||
|
'../backend/transcript-fallback.mjs',
|
||||||
'../backend/local-scanner.mjs',
|
'../backend/local-scanner.mjs',
|
||||||
'../backend/usage-aggregator.mjs',
|
'../backend/usage-aggregator.mjs',
|
||||||
'../backend/telemetry-builder.mjs',
|
'../backend/telemetry-builder.mjs',
|
||||||
|
|||||||
@@ -8,9 +8,16 @@ import { tmpdir } from 'node:os';
|
|||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import {
|
import {
|
||||||
computeSqliteWalSig,
|
computeSqliteWalSig,
|
||||||
|
isSqliteDbReadyForRead,
|
||||||
readLocalImageDimensionsFromUri,
|
readLocalImageDimensionsFromUri,
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
|
withReadOnlySqliteDb,
|
||||||
} from '../backend/cli-sqlite-reader.mjs';
|
} from '../backend/cli-sqlite-reader.mjs';
|
||||||
|
import {
|
||||||
|
readTranscriptJsonlLines,
|
||||||
|
resolveTranscriptPathInLogsDir,
|
||||||
|
} from '../backend/transcript-fallback.mjs';
|
||||||
|
import { resolveCliLocalSessionMetrics } from '../cli-statusline.mjs';
|
||||||
import { extractModelSteps } from '../trajectory-metrics.mjs';
|
import { extractModelSteps } from '../trajectory-metrics.mjs';
|
||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
import { i18nStore } from '../src/i18n/index.js';
|
import { i18nStore } from '../src/i18n/index.js';
|
||||||
@@ -1091,3 +1098,437 @@ test('readLocalImageDimensionsFromUri and readLocalSqliteTrajectory decode PNG/J
|
|||||||
assert.equal(modelSteps[0].ttftSec, null);
|
assert.equal(modelSteps[0].ttftSec, null);
|
||||||
assert.ok(Math.abs(modelSteps[0].totalDurationSec - 62.785) < 0.01);
|
assert.ok(Math.abs(modelSteps[0].totalDurationSec - 62.785) < 0.01);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('SQLite header readiness guard skips 0-byte, pre-DDL, 32-byte WAL-header-only, and active rollback-journal DBs without acquiring locks', (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-sqlite-init-guard-'));
|
||||||
|
t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||||
|
|
||||||
|
// 1. Fresh 0-byte DB (just opened by host, before WAL switch or DDL)
|
||||||
|
const zeroDbPath = join(tempRoot, 'zero.db');
|
||||||
|
const writerZero = new DatabaseSync(zeroDbPath);
|
||||||
|
try {
|
||||||
|
let readerCalled = false;
|
||||||
|
assert.equal(isSqliteDbReadyForRead(zeroDbPath), false);
|
||||||
|
assert.equal(computeSqliteWalSig(zeroDbPath).exists, true);
|
||||||
|
const res = withReadOnlySqliteDb(zeroDbPath, () => {
|
||||||
|
readerCalled = true;
|
||||||
|
return 'unexpected';
|
||||||
|
});
|
||||||
|
assert.equal(res, null);
|
||||||
|
assert.equal(readerCalled, false);
|
||||||
|
|
||||||
|
// Host immediately runs page_size + WAL + schema init without hitting SQLITE_BUSY
|
||||||
|
writerZero.exec(`
|
||||||
|
PRAGMA page_size = 32768;
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER);
|
||||||
|
INSERT INTO steps VALUES (0, 14);
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Open uncheckpointed WAL DB (pages=1 in main file, committed frames in .db-wal) IS ready
|
||||||
|
assert.equal(isSqliteDbReadyForRead(zeroDbPath), true);
|
||||||
|
const rowCnt = withReadOnlySqliteDb(zeroDbPath, (db) =>
|
||||||
|
db.prepare('SELECT count(*) AS c FROM steps').get()
|
||||||
|
);
|
||||||
|
assert.equal(rowCnt?.c, 1);
|
||||||
|
} finally {
|
||||||
|
writerZero.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// After close (WAL checkpointed & removed, pages >= 2 & schemaCookie > 0 in main file), still ready
|
||||||
|
assert.equal(isSqliteDbReadyForRead(zeroDbPath), true);
|
||||||
|
|
||||||
|
// 2. 1-page WAL header before any DDL is committed (walSize=0 or 32B WAL header only)
|
||||||
|
const preDdlWalPath = join(tempRoot, 'pre-ddl-wal.db');
|
||||||
|
const writerPreDdl = new DatabaseSync(preDdlWalPath);
|
||||||
|
try {
|
||||||
|
writerPreDdl.exec('PRAGMA page_size = 32768; PRAGMA journal_mode = WAL;');
|
||||||
|
assert.equal(isSqliteDbReadyForRead(preDdlWalPath), false);
|
||||||
|
assert.equal(isSqliteDbReadyForRead(preDdlWalPath, { walStat: { size: 32 } }), false);
|
||||||
|
assert.equal(withReadOnlySqliteDb(preDdlWalPath, () => 1), null);
|
||||||
|
} finally {
|
||||||
|
writerPreDdl.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Active rollback-journal DDL transaction (non-empty <db>-journal before WAL switch)
|
||||||
|
const rollbackDbPath = join(tempRoot, 'rollback-init.db');
|
||||||
|
const writerRollback = new DatabaseSync(rollbackDbPath);
|
||||||
|
try {
|
||||||
|
writerRollback.exec('CREATE TABLE t_seed (x INT);');
|
||||||
|
writerRollback.exec('BEGIN IMMEDIATE; CREATE TABLE steps (idx INT); INSERT INTO steps VALUES (1);');
|
||||||
|
assert.equal(isSqliteDbReadyForRead(rollbackDbPath), false);
|
||||||
|
assert.equal(withReadOnlySqliteDb(rollbackDbPath, () => 1), null);
|
||||||
|
|
||||||
|
// Writer commits and switches to WAL cleanly without lock contention
|
||||||
|
writerRollback.exec('COMMIT; PRAGMA journal_mode = WAL;');
|
||||||
|
assert.equal(isSqliteDbReadyForRead(rollbackDbPath), true);
|
||||||
|
const rbCnt = withReadOnlySqliteDb(rollbackDbPath, (db) =>
|
||||||
|
db.prepare('SELECT count(*) AS c FROM steps').get()
|
||||||
|
);
|
||||||
|
assert.equal(rbCnt?.c, 1);
|
||||||
|
} finally {
|
||||||
|
writerRollback.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Oversized transcript_full.jsonl is safely rejected by size guard
|
||||||
|
const logsDir = join(tempRoot, 'oversize-logs');
|
||||||
|
mkdirSync(logsDir, { recursive: true });
|
||||||
|
const fullPath = join(logsDir, 'transcript_full.jsonl');
|
||||||
|
writeFileSync(fullPath, '{"step_index":0,"input_tokens":10,"output_tokens":5}\n', 'utf8');
|
||||||
|
assert.equal(resolveTranscriptPathInLogsDir(logsDir, { maxFullBytes: 1024 }), fullPath);
|
||||||
|
assert.equal(resolveTranscriptPathInLogsDir(logsDir, { maxFullBytes: 16 }), '');
|
||||||
|
assert.deepEqual(readTranscriptJsonlLines(fullPath, { maxBytes: 16 }), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Empty-shell .db + encrypted .pb fallback recovers CLI conversation steps, subagents, and live updates from transcript.jsonl even when present in conversation_summaries.db', 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-pb-fallback-'));
|
||||||
|
t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||||
|
|
||||||
|
const p3Cid = '73384c09-50e3-4434-9b39-f8336aee5909';
|
||||||
|
const childCid = '1d0dfb7b-2a04-47b6-bcaf-1eb76aa34e34';
|
||||||
|
const orphanPbCid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||||
|
const normalOlderCid = 'bbbbbbbb-1111-4222-8333-cccccccccccc';
|
||||||
|
|
||||||
|
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') {
|
||||||
|
res.statusCode = 404;
|
||||||
|
res.end(JSON.stringify({ code: 'not_found', message: 'conversation not found in desktop LS' }));
|
||||||
|
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;
|
||||||
|
t.after(() => mockLsServer.close());
|
||||||
|
|
||||||
|
const geminiDir = join(tempRoot, '.gemini');
|
||||||
|
const cliDir = join(geminiDir, 'antigravity-cli');
|
||||||
|
const cliConvDir = join(cliDir, 'conversations');
|
||||||
|
const dataDir = join(geminiDir, 'antigravity', 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||||
|
mkdirSync(cliConvDir, { recursive: true });
|
||||||
|
mkdirSync(dataDir, { recursive: true });
|
||||||
|
|
||||||
|
// 1. Create CLI conversation_summaries.db with P3 (step_count=35, empty title), child subagent, and an unreadable .pb-only session
|
||||||
|
const sumDb = new DatabaseSync(join(cliDir, 'conversation_summaries.db'));
|
||||||
|
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
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
const insSum = sumDb.prepare(`
|
||||||
|
INSERT INTO conversation_summaries (
|
||||||
|
conversation_id, title, preview, status, source, parent_conversation_id,
|
||||||
|
nesting_depth, agent_name, not_fully_idle, killed, step_count, last_modified_time, app_data_dir
|
||||||
|
) VALUES (?, ?, '', 'CASCADE_RUN_STATUS_IDLE', 'CORTEX_TRAJECTORY_SOURCE_CLI', ?, ?, '', 0, 0, ?, ?, 'antigravity-cli')
|
||||||
|
`);
|
||||||
|
insSum.run(p3Cid, '', '', 0, 35, '2026-11-24 15:09:34.2531675+00:00');
|
||||||
|
insSum.run(childCid, '', p3Cid, 1, 4, '2026-11-24 15:05:00.0000000+00:00');
|
||||||
|
insSum.run(orphanPbCid, 'Legacy Encrypted Only', '', 0, 20, '2026-11-24 14:00:00.0000000+00:00');
|
||||||
|
sumDb.close();
|
||||||
|
|
||||||
|
// 2. Create empty-shell .db (steps=0, gen_metadata=0) + encrypted .pb for P3 and orphanPbCid
|
||||||
|
for (const emptyCid of [p3Cid, orphanPbCid]) {
|
||||||
|
const emptyDbPath = join(cliConvDir, `${emptyCid}.db`);
|
||||||
|
const emptyDb = new DatabaseSync(emptyDbPath);
|
||||||
|
emptyDb.exec(`
|
||||||
|
PRAGMA page_size = 32768;
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
CREATE TABLE trajectory_meta (trajectory_id TEXT PRIMARY KEY, 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);
|
||||||
|
CREATE TABLE trajectory_metadata_blob (id TEXT PRIMARY KEY, data BLOB);
|
||||||
|
PRAGMA user_version = 1;
|
||||||
|
`);
|
||||||
|
emptyDb.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 0, 0)').run(emptyCid, emptyCid);
|
||||||
|
emptyDb.prepare("INSERT INTO trajectory_metadata_blob VALUES ('main', X'')").run();
|
||||||
|
emptyDb.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const p3PbPath = join(cliConvDir, `${p3Cid}.pb`);
|
||||||
|
const orphanPbPath = join(cliConvDir, `${orphanPbCid}.pb`);
|
||||||
|
writeFileSync(p3PbPath, Buffer.alloc(4096, 0xa5));
|
||||||
|
writeFileSync(orphanPbPath, Buffer.alloc(2048, 0x5a));
|
||||||
|
|
||||||
|
// Older normal SQLite session to ensure cli-statusline prefers newer .pb session mtime
|
||||||
|
const olderDbPath = join(cliConvDir, `${normalOlderCid}.db`);
|
||||||
|
const olderDb = new DatabaseSync(olderDbPath);
|
||||||
|
olderDb.exec(`
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
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);
|
||||||
|
`);
|
||||||
|
olderDb
|
||||||
|
.prepare('INSERT INTO steps (idx, step_type, status, metadata) VALUES (0, 15, 3, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: 1795520000,
|
||||||
|
finishedSec: 1795520002,
|
||||||
|
stepIndex: 0,
|
||||||
|
originCascadeId: normalOlderCid,
|
||||||
|
modelEnumInt: 1429,
|
||||||
|
inputTokens: 500,
|
||||||
|
outputTokens: 50,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
olderDb.close();
|
||||||
|
utimesSync(olderDbPath, 1795520002, 1795520002);
|
||||||
|
utimesSync(join(cliConvDir, `${orphanPbCid}.db`), 1795528800, 1795528800);
|
||||||
|
utimesSync(orphanPbPath, 1795528800, 1795528800);
|
||||||
|
utimesSync(join(cliConvDir, `${p3Cid}.db`), 1795532499, 1795532499);
|
||||||
|
utimesSync(p3PbPath, 1795532974, 1795532974);
|
||||||
|
|
||||||
|
// 3. Write P3 and child subagent transcript.jsonl files
|
||||||
|
const p3LogDir = join(cliDir, 'brain', p3Cid, '.system_generated', 'logs');
|
||||||
|
const childLogDir = join(cliDir, 'brain', childCid, '.system_generated', 'logs');
|
||||||
|
mkdirSync(p3LogDir, { recursive: true });
|
||||||
|
mkdirSync(childLogDir, { recursive: true });
|
||||||
|
|
||||||
|
const p3TranscriptPath = join(p3LogDir, 'transcript.jsonl');
|
||||||
|
const p3Lines = [
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 0,
|
||||||
|
source: 'USER_EXPLICIT',
|
||||||
|
type: 'USER_INPUT',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:01:39Z',
|
||||||
|
content: '<USER_REQUEST>\nPolyglot P3 八道题离线求解\n</USER_REQUEST>',
|
||||||
|
}),
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 1,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'PLANNER_RESPONSE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:01:39Z',
|
||||||
|
model: 'gemini-4-neon-xhigh',
|
||||||
|
input_tokens: 16431,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
output_tokens: 2476,
|
||||||
|
tool_calls: [
|
||||||
|
{
|
||||||
|
id: 'call_sub_1',
|
||||||
|
name: 'invoke_subagent',
|
||||||
|
args: { Role: '"Polyglot Verifier"', TypeName: '"research"' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 2,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'GENERIC',
|
||||||
|
status: 'DONE',
|
||||||
|
tool_call_id: 'call_sub_1',
|
||||||
|
created_at: '2026-11-24T15:02:00Z',
|
||||||
|
content: `Created the following subagent:\n{\n "conversationId": "${childCid}"\n}`,
|
||||||
|
}),
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 34,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'PLANNER_RESPONSE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:02:05Z',
|
||||||
|
model: 'gemini-4-neon-xhigh',
|
||||||
|
input_tokens: 10611,
|
||||||
|
cache_read_tokens: 16432,
|
||||||
|
output_tokens: 54193,
|
||||||
|
content: '已完成全部 8 道题。',
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
writeFileSync(p3TranscriptPath, p3Lines.join('\n'), 'utf8');
|
||||||
|
|
||||||
|
writeFileSync(
|
||||||
|
join(childLogDir, 'transcript.jsonl'),
|
||||||
|
[
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 0,
|
||||||
|
source: 'SYSTEM',
|
||||||
|
type: 'SYSTEM_MESSAGE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:02:01Z',
|
||||||
|
content: 'Verify edge cases for poker and sgf-parsing.',
|
||||||
|
}),
|
||||||
|
JSON.stringify({
|
||||||
|
step_index: 1,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'PLANNER_RESPONSE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:02:03Z',
|
||||||
|
model: 'gemini-4-neon-xhigh',
|
||||||
|
input_tokens: 4000,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
output_tokens: 500,
|
||||||
|
content: 'Verified.',
|
||||||
|
}),
|
||||||
|
].join('\n'),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify cli-statusline picks P3 (via .pb mtime) and recovers metrics from transcript.jsonl
|
||||||
|
const prevDataDirEnv = process.env.USAGE_MONITOR_DATA_DIR;
|
||||||
|
process.env.USAGE_MONITOR_DATA_DIR = dataDir;
|
||||||
|
try {
|
||||||
|
const cliMetrics = resolveCliLocalSessionMetrics({
|
||||||
|
cliRoot: cliDir,
|
||||||
|
stdinData: null,
|
||||||
|
nowMs: Date.parse('2026-11-24T15:10:00Z'),
|
||||||
|
});
|
||||||
|
assert.equal(cliMetrics.found, true);
|
||||||
|
assert.equal(cliMetrics.cascadeId, p3Cid);
|
||||||
|
assert.equal(cliMetrics.stepCount, 2);
|
||||||
|
assert.equal(cliMetrics.sessionTokens, 16431 + 2476 + 10611 + 16432 + 54193);
|
||||||
|
assert.ok(cliMetrics.sessionCost > 0.9, `expected priced Neon cost, got ${cliMetrics.sessionCost}`);
|
||||||
|
assert.match(cliMetrics.latestModelHint, /Neon/i);
|
||||||
|
} finally {
|
||||||
|
if (prevDataDirEnv === undefined) delete process.env.USAGE_MONITOR_DATA_DIR;
|
||||||
|
else process.env.USAGE_MONITOR_DATA_DIR = prevDataDirEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify panel telemetry-builder recovers P3 + subagent, preserves contextGroupsTelemetry=3, avoids steady-state RPC spam, and picks up live transcript growth
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href;
|
||||||
|
const configUrl = new URL('../backend/config.mjs', import.meta.url).href;
|
||||||
|
const script = `
|
||||||
|
import { appendFileSync, utimesSync } from 'node:fs';
|
||||||
|
import { buildTelemetryPayload } from ${JSON.stringify(builderUrl)};
|
||||||
|
import { getCachedTrajectory } from ${JSON.stringify(configUrl)};
|
||||||
|
|
||||||
|
const p1 = await buildTelemetryPayload(${JSON.stringify(p3Cid)}, false, { range: 'all' });
|
||||||
|
const cachedP3 = getCachedTrajectory(${JSON.stringify(p3Cid)});
|
||||||
|
const p2 = await buildTelemetryPayload(${JSON.stringify(p3Cid)}, false, { range: 'all' });
|
||||||
|
|
||||||
|
// Append a new step to P3 transcript.jsonl + touch .pb while empty .db remains untouched
|
||||||
|
appendFileSync(
|
||||||
|
${JSON.stringify(p3TranscriptPath)},
|
||||||
|
'\\n' + JSON.stringify({
|
||||||
|
step_index: 35,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'PLANNER_RESPONSE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-24T15:09:40Z',
|
||||||
|
model: 'gemini-4-neon-xhigh',
|
||||||
|
input_tokens: 2000,
|
||||||
|
cache_read_tokens: 20000,
|
||||||
|
output_tokens: 1000,
|
||||||
|
content: '补充自检通过。',
|
||||||
|
}),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
utimesSync(${JSON.stringify(p3PbPath)}, 1795532985, 1795532985);
|
||||||
|
const p3 = await buildTelemetryPayload(${JSON.stringify(p3Cid)}, false, { range: 'all' });
|
||||||
|
|
||||||
|
const convEntry1 = p1.conversations.find((c) => c.cascadeId === ${JSON.stringify(p3Cid)});
|
||||||
|
const orphanEntry = p1.conversations.find((c) => c.cascadeId === ${JSON.stringify(orphanPbCid)});
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
title: p1.activeConversation?.title,
|
||||||
|
cachedCtxGrpVer: cachedP3?.contextGroupsTelemetry || 0,
|
||||||
|
mainSteps1: p1.activeConversation?.agents?.[0]?.stepCount,
|
||||||
|
subCount1: p1.activeConversation?.subagentCount,
|
||||||
|
subRole1: p1.activeConversation?.agents?.[1]?.role,
|
||||||
|
subSteps1: p1.activeConversation?.agents?.[1]?.stepCount,
|
||||||
|
listStepCount1: convEntry1?.stepCount,
|
||||||
|
listTotalStepCount1: convEntry1?.totalStepCount,
|
||||||
|
mainIn1: p1.activeConversation?.agents?.[0]?.inputTokens,
|
||||||
|
mainCache1: p1.activeConversation?.agents?.[0]?.cacheReadTokens,
|
||||||
|
mainOut1: p1.activeConversation?.agents?.[0]?.outputTokens,
|
||||||
|
orphanStepCount: orphanEntry?.stepCount,
|
||||||
|
mainSteps2: p2.activeConversation?.agents?.[0]?.stepCount,
|
||||||
|
mainSteps3: p3.activeConversation?.agents?.[0]?.stepCount,
|
||||||
|
}));
|
||||||
|
`;
|
||||||
|
|
||||||
|
const { stdout, stderr } = await execFileAsync(
|
||||||
|
process.execPath,
|
||||||
|
['--input-type=module', '-e', script],
|
||||||
|
{
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
ANTIGRAVITY_GEMINI_DIR: geminiDir,
|
||||||
|
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||||
|
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||||
|
ANTIGRAVITY_EXECUTABLE_DATA_DIR: dataDir,
|
||||||
|
ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${lsPort}`,
|
||||||
|
ANTIGRAVITY_LS_PLAIN_HTTP: '1',
|
||||||
|
ANTIGRAVITY_CSRF_TOKEN: 'test-csrf',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(stderr.trim(), '', `expected no noisy stderr on expected CLI 404 fallback, got: ${stderr}`);
|
||||||
|
const res = JSON.parse(stdout.trim().split('\n').pop());
|
||||||
|
assert.equal(res.title, 'Polyglot P3 八道题离线求解');
|
||||||
|
assert.equal(res.cachedCtxGrpVer, 3, 'offline recovered entry keeps contextGroupsTelemetry=3');
|
||||||
|
assert.equal(res.mainSteps1, 2);
|
||||||
|
assert.equal(res.subCount1, 1);
|
||||||
|
assert.equal(res.subRole1, 'Polyglot Verifier');
|
||||||
|
assert.equal(res.subSteps1, 1);
|
||||||
|
assert.equal(res.listStepCount1, 2, 'root stepCount matches 2 recovered main model steps (not raw 35)');
|
||||||
|
assert.equal(res.listTotalStepCount1, 3, 'root totalStepCount matches 2 main + 1 subagent recovered model steps');
|
||||||
|
assert.equal(res.mainIn1, 16431 + 10611);
|
||||||
|
assert.equal(res.mainCache1, 16432);
|
||||||
|
assert.equal(res.mainOut1, 2476 + 54193);
|
||||||
|
assert.equal(res.orphanStepCount, 0, 'unreadable .pb without transcript normalizes stepCount to 0 instead of raw 20');
|
||||||
|
assert.equal(res.mainSteps2, 2);
|
||||||
|
assert.equal(res.mainSteps3, 3, 'growing transcript.jsonl + .pb advances signature even when empty .db is frozen');
|
||||||
|
|
||||||
|
const p3RpcCallsAfter2Polls = rpcCalls.filter(
|
||||||
|
(c) => c.method === 'GetCascadeTrajectory' && c.cascadeId === p3Cid
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
p3RpcCallsAfter2Polls.length,
|
||||||
|
2,
|
||||||
|
'poll 1 and post-growth poll 3 attempted RPC once each; steady poll 2 hit cooldown without hammering LS'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user