mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
perf(panel): isolate host main.mjs startup, fix standalone CLI args, and close P0 audit bugs
This commit is contained in:
+21
-12
@@ -598,6 +598,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.currentSession': '当前会话',
|
||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||
'live.thinking': '推理中',
|
||||
'live.generating': '生成中',
|
||||
'live.running': '运行中',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
@@ -1125,6 +1126,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.currentSession': 'Current Session',
|
||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||
'live.thinking': 'Thinking',
|
||||
'live.generating': 'Generating',
|
||||
'live.running': 'Running',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
@@ -14357,7 +14359,7 @@ const SettingsStructureTab = defineComponent({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||
minItems: 2,
|
||||
maxItems: 15,
|
||||
maxItems: 14,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
onPreview: (previewItems) => {
|
||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||
@@ -15580,20 +15582,24 @@ const TopSessionHeader = defineComponent({
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
|
||||
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (!currentCascadeId) return;
|
||||
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
const uiSt = uiStore.getState();
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
}
|
||||
} else {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
}
|
||||
|
||||
function renderHeaderState() {
|
||||
const telSt = telemetryStore.getState();
|
||||
const uiSt = uiStore.getState();
|
||||
const telemetry = telSt.telemetry;
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
return;
|
||||
}
|
||||
} else if (currentCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
if (!uiSt.monitorVisible) return;
|
||||
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
@@ -15751,7 +15757,10 @@ const TopSessionHeader = defineComponent({
|
||||
syncState: st.syncState,
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
() => renderHeaderState()
|
||||
(slice) => {
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||
renderHeaderState();
|
||||
}
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
|
||||
@@ -6,13 +6,12 @@
|
||||
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
clearRuntimeCaches,
|
||||
cloudSyncState,
|
||||
@@ -59,60 +58,7 @@ export function setStandalonePortListener(listener) {
|
||||
standalonePortListener = typeof listener === 'function' ? listener : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
* @param {string} relPath 相对路径
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export const readLocalAsync = async (relPath) => {
|
||||
const fullPath = join(HERE, relPath);
|
||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||
return fsPromises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
return readFileSync(fullPath, 'utf8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||
*
|
||||
* @param {object} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLocalHostRequest(req) {
|
||||
if (!req?.headers) return true;
|
||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||
if (host && !hostMatch) {
|
||||
return false;
|
||||
}
|
||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||
return true;
|
||||
}
|
||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||
if (secFetchSite === 'cross-site') {
|
||||
return false;
|
||||
}
|
||||
if (origin) {
|
||||
const originMatch = origin.match(
|
||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||
);
|
||||
if (!originMatch) {
|
||||
return false;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export { isLocalHostRequest, readLocalAsync };
|
||||
|
||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
||||
|
||||
@@ -142,7 +88,8 @@ function projectDisplayStep(st) {
|
||||
};
|
||||
}
|
||||
|
||||
let lastDisplaySteps = null;
|
||||
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8;
|
||||
const displayStepsCache = new Map();
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
@@ -165,23 +112,34 @@ function projectDisplayTelemetry(payload, requestedRevision) {
|
||||
let projected;
|
||||
let revision;
|
||||
if (typeof requestedRevision === 'string') {
|
||||
const cacheKey = active.cascadeId || '__empty__';
|
||||
const scope = [
|
||||
payload.account?.status,
|
||||
payload.account?.email || payload.account?.name || '',
|
||||
active.cascadeId,
|
||||
...agents.map((agent) => agent.agentId),
|
||||
];
|
||||
const previous = lastDisplaySteps;
|
||||
const previous = displayStepsCache.get(cacheKey);
|
||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||
({ revision, steps: projected } = previous);
|
||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||
displayStepsCache.delete(cacheKey);
|
||||
displayStepsCache.set(cacheKey, previous);
|
||||
} else {
|
||||
revision = randomUUID();
|
||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
lastDisplaySteps = { scope, steps: projected, revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
||||
if (!displayStepsCache.has(cacheKey) && displayStepsCache.size >= MAX_DISPLAY_STEP_CACHE_ENTRIES) {
|
||||
displayStepsCache.delete(displayStepsCache.keys().next().value);
|
||||
}
|
||||
displayStepsCache.delete(cacheKey);
|
||||
displayStepsCache.set(cacheKey, {
|
||||
scope,
|
||||
steps: projected,
|
||||
revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined),
|
||||
});
|
||||
}
|
||||
}
|
||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
@@ -452,6 +410,8 @@ export function executeRebuildCacheAction() {
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||
};
|
||||
}
|
||||
displayStepsCache.clear();
|
||||
clearScannerRuntimeMemos();
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
|
||||
@@ -114,7 +114,7 @@ function isSqliteBusyError(err) {
|
||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
*/
|
||||
function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
@@ -729,6 +729,11 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
targets.push({ rootName: basename(root).toLowerCase(), dbPath });
|
||||
}
|
||||
|
||||
const rootsKey = roots
|
||||
.map((r) => String(r || '').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (productRoots === PRODUCT_DATA_ROOTS) {
|
||||
localSummaryMemo.sig = '';
|
||||
@@ -737,23 +742,41 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
localSummaryMemo.summariesObj = {};
|
||||
localSummaryMemo.sideQuestionParents = {};
|
||||
}
|
||||
if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
}
|
||||
return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} };
|
||||
}
|
||||
|
||||
const sig = sigParts.join('||');
|
||||
if (
|
||||
!forceRefresh &&
|
||||
productRoots === PRODUCT_DATA_ROOTS &&
|
||||
localSummaryMemo.sig === sig &&
|
||||
localSummaryMemo.available
|
||||
) {
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: localSummaryMemo.byId,
|
||||
summariesObj: localSummaryMemo.summariesObj || {},
|
||||
sideQuestionParents: localSummaryMemo.sideQuestionParents || {},
|
||||
};
|
||||
if (!forceRefresh) {
|
||||
if (
|
||||
productRoots === PRODUCT_DATA_ROOTS &&
|
||||
localSummaryMemo.sig === sig &&
|
||||
localSummaryMemo.available
|
||||
) {
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: localSummaryMemo.byId,
|
||||
summariesObj: localSummaryMemo.summariesObj || {},
|
||||
sideQuestionParents: localSummaryMemo.sideQuestionParents || {},
|
||||
};
|
||||
}
|
||||
if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
const cached = localSummaryMemo.byRootsKey.get(rootsKey);
|
||||
if (cached && cached.sig === sig && cached.available) {
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
localSummaryMemo.byRootsKey.set(rootsKey, cached);
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: cached.byId,
|
||||
summariesObj: cached.summariesObj,
|
||||
sideQuestionParents: cached.sideQuestionParents,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextMap = new Map();
|
||||
@@ -990,6 +1013,18 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
localSummaryMemo.available = true;
|
||||
localSummaryMemo.summariesObj = nextSummariesObj;
|
||||
localSummaryMemo.sideQuestionParents = nextSideQuestionParents;
|
||||
} else if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
if (!localSummaryMemo.byRootsKey.has(rootsKey) && localSummaryMemo.byRootsKey.size >= 8) {
|
||||
localSummaryMemo.byRootsKey.delete(localSummaryMemo.byRootsKey.keys().next().value);
|
||||
}
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
localSummaryMemo.byRootsKey.set(rootsKey, {
|
||||
available: true,
|
||||
sig,
|
||||
byId: nextMap,
|
||||
summariesObj: nextSummariesObj,
|
||||
sideQuestionParents: nextSideQuestionParents,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1807,8 +1842,8 @@ function cleanShortPromptTitle(rawText, maxChars = 80) {
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
||||
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
const reqMatch = withoutTags.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/i);
|
||||
const target = reqMatch ? reqMatch[1] : withoutTags;
|
||||
const reqMatches = [...withoutTags.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||
const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : withoutTags;
|
||||
const singleLine = target.replace(/\s+/g, ' ').trim();
|
||||
if (!singleLine) return '';
|
||||
return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`;
|
||||
|
||||
@@ -552,6 +552,7 @@ export const localSummaryMemo = {
|
||||
available: false,
|
||||
summariesObj: {},
|
||||
sideQuestionParents: {},
|
||||
byRootsKey: new Map(),
|
||||
};
|
||||
|
||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||
@@ -615,6 +616,7 @@ export function clearRuntimeCaches() {
|
||||
localSummaryMemo.available = false;
|
||||
localSummaryMemo.summariesObj = {};
|
||||
localSummaryMemo.sideQuestionParents = {};
|
||||
localSummaryMemo.byRootsKey.clear();
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.accountName = '';
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @fileoverview 零业务状态依赖的静态资源读取与本机回环请求来源校验工具。
|
||||
*
|
||||
* 独立于 `./config.mjs` 与 `./api-actions.mjs`,使宿主入口 `main.mjs` 在生产环境下无需加载完整后端图谱与轨迹缓存。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
function resolveHttpHelperPanelDir() {
|
||||
const modDir = dirname(fileURLToPath(import.meta.url));
|
||||
return /[\\/]backend$/i.test(modDir) ? dirname(modDir) : modDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
* @param {string} relPath 相对路径
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export const readLocalAsync = async (relPath) => {
|
||||
const fullPath = join(resolveHttpHelperPanelDir(), relPath);
|
||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||
return fsPromises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
return readFileSync(fullPath, 'utf8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||
*
|
||||
* @param {object} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLocalHostRequest(req) {
|
||||
if (!req?.headers) return true;
|
||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||
if (host && !hostMatch) {
|
||||
return false;
|
||||
}
|
||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||
return true;
|
||||
}
|
||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||
if (secFetchSite === 'cross-site') {
|
||||
return false;
|
||||
}
|
||||
if (origin) {
|
||||
const originMatch = origin.match(
|
||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||
);
|
||||
if (!originMatch) {
|
||||
return false;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -354,6 +354,12 @@ const failedFetchCooldownMap = new Map();
|
||||
const liveActivityMemo = new Map();
|
||||
const transcriptTailMemo = new Map();
|
||||
|
||||
export function clearScannerRuntimeMemos() {
|
||||
failedFetchCooldownMap.clear();
|
||||
liveActivityMemo.clear();
|
||||
transcriptTailMemo.clear();
|
||||
}
|
||||
|
||||
function findTranscriptPath(cascadeId) {
|
||||
if (!cascadeId) return '';
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
|
||||
@@ -513,7 +513,7 @@ export async function ensureLsEndpointDiscovered({
|
||||
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||
return false;
|
||||
}
|
||||
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
||||
if (!force && lsRuntimeEndpoint.baseUrl && (lsRuntimeEndpoint.csrfToken || !lsRuntimeEndpoint.isDynamic)) {
|
||||
return true;
|
||||
}
|
||||
if (lsDiscoveryState.inFlight) {
|
||||
|
||||
@@ -356,8 +356,8 @@ export function createStandaloneWebServer(options = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
if (options.lsAddr && options.csrfToken) {
|
||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false });
|
||||
if (options.lsAddr) {
|
||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken || '', { isDynamic: false });
|
||||
}
|
||||
|
||||
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
||||
|
||||
@@ -11,23 +11,18 @@
|
||||
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
bootBundleVersion,
|
||||
bootWindowBridgeRuntime,
|
||||
setStandalonePortListener,
|
||||
} from './backend/api-actions.mjs';
|
||||
import {
|
||||
computeRuntimeCodeVersion,
|
||||
loadSettings,
|
||||
normalizeStandalonePort,
|
||||
} from './backend/config.mjs';
|
||||
import {
|
||||
createStandaloneWebServer,
|
||||
parseStandaloneCliArgs,
|
||||
} from './backend/standalone-server.mjs';
|
||||
import { runStandaloneCli } from './standalone.mjs';
|
||||
|
||||
export function startBridgeDaemon() {
|
||||
export async function startBridgeDaemon() {
|
||||
const [
|
||||
{ bootBundleVersion, bootWindowBridgeRuntime, setStandalonePortListener },
|
||||
{ computeRuntimeCodeVersion, loadSettings, normalizeStandalonePort },
|
||||
{ createStandaloneWebServer, parseStandaloneCliArgs },
|
||||
] = await Promise.all([
|
||||
import('./backend/api-actions.mjs'),
|
||||
import('./backend/config.mjs'),
|
||||
import('./backend/standalone-server.mjs'),
|
||||
]);
|
||||
|
||||
let shuttingDown = false;
|
||||
let sawShutdownDispose = false;
|
||||
let stdinBuf = '';
|
||||
@@ -171,8 +166,8 @@ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||||
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||
const cliArgs = process.argv.slice(2);
|
||||
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
||||
void runStandaloneCli(cliArgs);
|
||||
void import('./standalone.mjs').then(({ runStandaloneCli }) => runStandaloneCli(cliArgs));
|
||||
} else {
|
||||
startBridgeDaemon();
|
||||
void startBridgeDaemon();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,9 +25,9 @@ import {
|
||||
summarizeTtft,
|
||||
} from './trajectory-metrics.mjs';
|
||||
import {
|
||||
getNodeSqliteDatabaseSync,
|
||||
readLocalSqliteTrajectory,
|
||||
readLocalSummaryIndex,
|
||||
withReadOnlySqliteDb,
|
||||
} from './backend/cli-sqlite-reader.mjs';
|
||||
import {
|
||||
ensureCliStatusLineConfigured,
|
||||
@@ -145,43 +145,35 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) {
|
||||
if (!cwd) return '';
|
||||
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
||||
if (!existsSync(summariesDbPath)) return '';
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return '';
|
||||
|
||||
const normCwd = normalizePathForMatch(cwd);
|
||||
if (!normCwd) return '';
|
||||
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(summariesDbPath, { readOnly: true });
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT conversation_id, workspace, last_modified_time
|
||||
FROM conversations_fts
|
||||
WHERE chunk_index = -1
|
||||
ORDER BY last_modified_time DESC
|
||||
LIMIT 40`
|
||||
)
|
||||
.all();
|
||||
for (const row of rows || []) {
|
||||
const ws = normalizePathForMatch(row?.workspace);
|
||||
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
||||
if (cid && ws && ws === normCwd) {
|
||||
return cid;
|
||||
const matched = withReadOnlySqliteDb(summariesDbPath, (db) => {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT conversation_id, workspace, last_modified_time
|
||||
FROM conversations_fts
|
||||
WHERE chunk_index = -1
|
||||
ORDER BY last_modified_time DESC
|
||||
LIMIT 40`
|
||||
)
|
||||
.all();
|
||||
for (const row of rows || []) {
|
||||
const ws = normalizePathForMatch(row?.workspace);
|
||||
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
||||
if (cid && ws && ws === normCwd) {
|
||||
return cid;
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
});
|
||||
return matched || '';
|
||||
} catch {
|
||||
// 忽略不存在 conversations_fts 表或读取失败
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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=1794977386430">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794981269167">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794977386430"></script>
|
||||
<script src="/app.js?v=1794981269167"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+20
-8
@@ -11,12 +11,7 @@
|
||||
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import {
|
||||
bootWindowBridgeRuntime,
|
||||
dispatchBridgeApiRequest,
|
||||
isLocalHostRequest,
|
||||
readLocalAsync,
|
||||
} from './backend/api-actions.mjs';
|
||||
import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs';
|
||||
|
||||
const app = new SidecarApp();
|
||||
|
||||
@@ -144,9 +139,20 @@ async function ensureActiveWorker() {
|
||||
return activeWorker;
|
||||
}
|
||||
|
||||
let testHarnessApiModulePromise = null;
|
||||
|
||||
function getTestHarnessApiModule() {
|
||||
testHarnessApiModulePromise ||= import('./backend/api-actions.mjs');
|
||||
return testHarnessApiModulePromise;
|
||||
}
|
||||
|
||||
async function forwardApiCall(pathname, method, data) {
|
||||
if (isTestHarnessEnv) {
|
||||
return dispatchBridgeApiRequest(pathname, method, data);
|
||||
if (typeof dispatchBridgeApiRequest === 'function') {
|
||||
return dispatchBridgeApiRequest(pathname, method, data);
|
||||
}
|
||||
const mod = await getTestHarnessApiModule();
|
||||
return mod.dispatchBridgeApiRequest(pathname, method, data);
|
||||
}
|
||||
const upperMethod = String(method || 'GET').toUpperCase();
|
||||
try {
|
||||
@@ -223,7 +229,13 @@ app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-up
|
||||
|
||||
app.run();
|
||||
if (isTestHarnessEnv) {
|
||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||
if (typeof bootWindowBridgeRuntime === 'function') {
|
||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||
} else {
|
||||
void getTestHarnessApiModule().then((mod) =>
|
||||
mod.bootWindowBridgeRuntime({ allowDynamicLs: false })
|
||||
);
|
||||
}
|
||||
} else {
|
||||
void ensureActiveWorker();
|
||||
}
|
||||
|
||||
@@ -107,20 +107,24 @@ export const TopSessionHeader = defineComponent({
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
|
||||
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (!currentCascadeId) return;
|
||||
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
const uiSt = uiStore.getState();
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
}
|
||||
} else {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
}
|
||||
|
||||
function renderHeaderState() {
|
||||
const telSt = telemetryStore.getState();
|
||||
const uiSt = uiStore.getState();
|
||||
const telemetry = telSt.telemetry;
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
return;
|
||||
}
|
||||
} else if (currentCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
if (!uiSt.monitorVisible) return;
|
||||
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
@@ -278,7 +282,10 @@ export const TopSessionHeader = defineComponent({
|
||||
syncState: st.syncState,
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
() => renderHeaderState()
|
||||
(slice) => {
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||
renderHeaderState();
|
||||
}
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
|
||||
@@ -182,6 +182,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.currentSession': 'Current Session',
|
||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||
'live.thinking': 'Thinking',
|
||||
'live.generating': 'Generating',
|
||||
'live.running': 'Running',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
|
||||
@@ -182,6 +182,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.currentSession': '当前会话',
|
||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||
'live.thinking': '推理中',
|
||||
'live.generating': '生成中',
|
||||
'live.running': '运行中',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
|
||||
@@ -800,7 +800,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||
minItems: 2,
|
||||
maxItems: 15,
|
||||
maxItems: 14,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
onPreview: (previewItems) => {
|
||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||
|
||||
@@ -22,6 +22,7 @@ const BACKEND_MODULE_FILES = [
|
||||
'../backend/account-switch.mjs',
|
||||
'../shared/settings-normalization.mjs',
|
||||
'../shared/window-bridge-protocol.mjs',
|
||||
'../backend/http-helpers.mjs',
|
||||
'../backend/settings-schema.mjs',
|
||||
'../backend/config.mjs',
|
||||
'../backend/cli-sqlite-reader.mjs',
|
||||
|
||||
@@ -7,6 +7,7 @@ import vm from 'node:vm';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
import {
|
||||
extractContextBreakdown,
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
normalizeCachedStep,
|
||||
} from '../trajectory-metrics.mjs';
|
||||
@@ -966,3 +967,144 @@ test('post-compaction context preserves static channels + checkpoint summary, ca
|
||||
assert.doesNotMatch(stylesCss, /\.structure-preview-canvas[^{]*\{[^}]*zoom:/, 'Structure preview must stay 1:1 without zoom distortion');
|
||||
assert.match(stylesCss, /\.preview-capsule-bar\s*\{[^}]*"Google Sans Flex"/s);
|
||||
});
|
||||
|
||||
test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, dual-window stepRevision LRU, CORTEX_STEP_TYPE_FIND, preview i18n, and header render purity', async () => {
|
||||
// 1. Static import isolation on main.mjs and bridge-daemon.mjs
|
||||
const mainSrc = fs.readFileSync(new URL('../main.mjs', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(
|
||||
mainSrc,
|
||||
/^import\s+[\s\S]*?from\s+['"]\.\/backend\/(?:api-actions|config)\.mjs['"]/m,
|
||||
'main.mjs must not statically import api-actions.mjs or config.mjs in the host parent process'
|
||||
);
|
||||
const daemonSrc = fs.readFileSync(new URL('../bridge-daemon.mjs', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(
|
||||
daemonSrc,
|
||||
/^import\s+[\s\S]*?from\s+['"]\.\/backend\/config\.mjs['"]/m,
|
||||
'bridge-daemon.mjs must not statically import config.mjs before --standalone env overrides'
|
||||
);
|
||||
|
||||
// 2. Dual-window alternating stepDetails='display' stepRevision cache hit + rebuild invalidation
|
||||
const makeConv = (prompt) => ({
|
||||
trajectory: {
|
||||
steps: [
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
userInput: { userResponse: prompt },
|
||||
metadata: { createdAt: '2026-11-18T05:00:00Z' },
|
||||
},
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
plannerResponse: { response: 'done' },
|
||||
metadata: {
|
||||
createdAt: '2026-11-18T05:00:01Z',
|
||||
completedAt: '2026-11-18T05:00:02Z',
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M65',
|
||||
inputTokens: '1200',
|
||||
outputTokens: '60',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const cidA = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
const cidB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
|
||||
const h = backendHarness({
|
||||
summaries: {
|
||||
[cidA]: { summary: 'A', stepCount: 2, lastModifiedTime: '2026-11-18T05:00:02Z' },
|
||||
[cidB]: { summary: 'B', stepCount: 2, lastModifiedTime: '2026-11-18T05:00:03Z' },
|
||||
},
|
||||
trajectories: {
|
||||
[cidA]: makeConv('Prompt A'),
|
||||
[cidB]: makeConv('Prompt B'),
|
||||
},
|
||||
});
|
||||
|
||||
const firstA = JSON.parse(
|
||||
(await h.executeTelemetryAction({ conversationId: cidA, stepDetails: 'display', stepRevision: '' })).body
|
||||
);
|
||||
const firstB = JSON.parse(
|
||||
(await h.executeTelemetryAction({ conversationId: cidB, stepDetails: 'display', stepRevision: '' })).body
|
||||
);
|
||||
const secondA = JSON.parse(
|
||||
(await h.executeTelemetryAction({
|
||||
conversationId: cidA,
|
||||
stepDetails: 'display',
|
||||
stepRevision: firstA.stepRevision,
|
||||
})).body
|
||||
);
|
||||
const secondB = JSON.parse(
|
||||
(await h.executeTelemetryAction({
|
||||
conversationId: cidB,
|
||||
stepDetails: 'display',
|
||||
stepRevision: firstB.stepRevision,
|
||||
})).body
|
||||
);
|
||||
assert.equal(secondA.stepsUnchanged, true);
|
||||
assert.equal(secondB.stepsUnchanged, true);
|
||||
assert.equal(secondA.activeConversation.recentSteps, undefined);
|
||||
assert.equal(secondB.activeConversation.recentSteps, undefined);
|
||||
|
||||
h.executeRebuildCacheAction();
|
||||
const afterRebuildA = JSON.parse(
|
||||
(await h.executeTelemetryAction({
|
||||
conversationId: cidA,
|
||||
stepDetails: 'display',
|
||||
stepRevision: firstA.stepRevision,
|
||||
})).body
|
||||
);
|
||||
assert.equal(afterRebuildA.stepsUnchanged, false);
|
||||
assert.equal(Array.isArray(afterRebuildA.activeConversation.recentSteps), true);
|
||||
|
||||
// 3. CORTEX_STEP_TYPE_FIND live activity resolution
|
||||
const findAct = extractLiveActivity(
|
||||
[
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_FIND',
|
||||
status: 'CORTEX_STEP_STATUS_RUNNING',
|
||||
metadata: { createdAt: '2026-11-18T05:00:00Z' },
|
||||
},
|
||||
],
|
||||
true
|
||||
);
|
||||
assert.equal(findAct?.label, '查找文件');
|
||||
|
||||
// 4. Preview i18n ('live.generating'), stepColumns maxItems: 14, SQLite busy helper reuse, and pure header render
|
||||
const { setI18nLanguage } = await import('../src/i18n/index.js');
|
||||
const { buildStructurePreviewTelemetry } = await import(
|
||||
'../src/components/settings/structurePreviewMock.js'
|
||||
);
|
||||
setI18nLanguage('zh-CN');
|
||||
assert.equal(
|
||||
buildStructurePreviewTelemetry().runningConversations[0].mainActivity.label,
|
||||
'生成中'
|
||||
);
|
||||
setI18nLanguage('en-US');
|
||||
assert.equal(
|
||||
buildStructurePreviewTelemetry().runningConversations[0].mainActivity.label,
|
||||
'Generating'
|
||||
);
|
||||
setI18nLanguage('zh-CN');
|
||||
|
||||
const structureTabSrc = fs.readFileSync(
|
||||
new URL('../src/views/settings/SettingsStructureTab.js', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
assert.match(structureTabSrc, /options:\s*getStepColumnOptions[\s\S]{0,120}?maxItems:\s*14\b/);
|
||||
|
||||
const cliStatusSrc = fs.readFileSync(new URL('../cli-statusline.mjs', import.meta.url), 'utf8');
|
||||
assert.match(cliStatusSrc, /\bwithReadOnlySqliteDb\b/);
|
||||
assert.doesNotMatch(cliStatusSrc, /\bnew\s+DatabaseSync\s*\(/);
|
||||
|
||||
const headerSrc = fs.readFileSync(
|
||||
new URL('../src/components/layout/TopSessionHeader.js', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const renderBody = headerSrc.slice(
|
||||
headerSrc.indexOf('function renderHeaderState()'),
|
||||
headerSrc.indexOf('const unsubTelemetry =')
|
||||
);
|
||||
assert.doesNotMatch(renderBody, /\buiStore\.setState\b/);
|
||||
});
|
||||
|
||||
@@ -1597,7 +1597,11 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
||||
rawName = 'edit_file';
|
||||
} else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) {
|
||||
rawName = 'grep_search';
|
||||
} else if (stepType.includes('FIND_BY_NAME') || fallbackStep?.findByName) {
|
||||
} else if (
|
||||
stepType.includes('FIND_BY_NAME') ||
|
||||
stepType === 'CORTEX_STEP_TYPE_FIND' ||
|
||||
fallbackStep?.findByName
|
||||
) {
|
||||
rawName = 'find_by_name';
|
||||
} else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) {
|
||||
rawName = 'search_web';
|
||||
|
||||
Reference in New Issue
Block a user