mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +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.currentSession': '当前会话',
|
||||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||||
'live.thinking': '推理中',
|
'live.thinking': '推理中',
|
||||||
|
'live.generating': '生成中',
|
||||||
'live.running': '运行中',
|
'live.running': '运行中',
|
||||||
'live.done': '已完成',
|
'live.done': '已完成',
|
||||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||||
@@ -1125,6 +1126,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||||
'live.thinking': 'Thinking',
|
'live.thinking': 'Thinking',
|
||||||
|
'live.generating': 'Generating',
|
||||||
'live.running': 'Running',
|
'live.running': 'Running',
|
||||||
'live.done': 'Done',
|
'live.done': 'Done',
|
||||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||||
@@ -14357,7 +14359,7 @@ const SettingsStructureTab = defineComponent({
|
|||||||
items: draftStepColumns,
|
items: draftStepColumns,
|
||||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||||
minItems: 2,
|
minItems: 2,
|
||||||
maxItems: 15,
|
maxItems: 14,
|
||||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||||
onPreview: (previewItems) => {
|
onPreview: (previewItems) => {
|
||||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||||
@@ -15580,20 +15582,24 @@ const TopSessionHeader = defineComponent({
|
|||||||
|
|
||||||
let lastActiveCascadeId = '';
|
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() {
|
function renderHeaderState() {
|
||||||
const telSt = telemetryStore.getState();
|
const telSt = telemetryStore.getState();
|
||||||
const uiSt = uiStore.getState();
|
const uiSt = uiStore.getState();
|
||||||
const telemetry = telSt.telemetry;
|
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;
|
if (!uiSt.monitorVisible) return;
|
||||||
|
|
||||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||||
@@ -15751,7 +15757,10 @@ const TopSessionHeader = defineComponent({
|
|||||||
syncState: st.syncState,
|
syncState: st.syncState,
|
||||||
telemetry: st.telemetry,
|
telemetry: st.telemetry,
|
||||||
}),
|
}),
|
||||||
() => renderHeaderState()
|
(slice) => {
|
||||||
|
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||||
|
renderHeaderState();
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const unsubI18n = i18nStore.subscribe(
|
const unsubI18n = i18nStore.subscribe(
|
||||||
|
|||||||
@@ -6,13 +6,12 @@
|
|||||||
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
* 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 { randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||||
|
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||||
|
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||||
import {
|
import {
|
||||||
HERE,
|
|
||||||
SETTINGS_FILE,
|
SETTINGS_FILE,
|
||||||
clearRuntimeCaches,
|
clearRuntimeCaches,
|
||||||
cloudSyncState,
|
cloudSyncState,
|
||||||
@@ -59,60 +58,7 @@ export function setStandalonePortListener(listener) {
|
|||||||
standalonePortListener = typeof listener === 'function' ? listener : null;
|
standalonePortListener = typeof listener === 'function' ? listener : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export { isLocalHostRequest, readLocalAsync };
|
||||||
* 异步读取 `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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
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({}));
|
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||||
|
|
||||||
function haveSameDisplaySteps(previous, current) {
|
function haveSameDisplaySteps(previous, current) {
|
||||||
@@ -165,23 +112,34 @@ function projectDisplayTelemetry(payload, requestedRevision) {
|
|||||||
let projected;
|
let projected;
|
||||||
let revision;
|
let revision;
|
||||||
if (typeof requestedRevision === 'string') {
|
if (typeof requestedRevision === 'string') {
|
||||||
|
const cacheKey = active.cascadeId || '__empty__';
|
||||||
const scope = [
|
const scope = [
|
||||||
payload.account?.status,
|
payload.account?.status,
|
||||||
payload.account?.email || payload.account?.name || '',
|
payload.account?.email || payload.account?.name || '',
|
||||||
active.cascadeId,
|
active.cascadeId,
|
||||||
...agents.map((agent) => agent.agentId),
|
...agents.map((agent) => agent.agentId),
|
||||||
];
|
];
|
||||||
const previous = lastDisplaySteps;
|
const previous = displayStepsCache.get(cacheKey);
|
||||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||||
({ revision, steps: projected } = previous);
|
({ revision, steps: projected } = previous);
|
||||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||||
|
displayStepsCache.delete(cacheKey);
|
||||||
|
displayStepsCache.set(cacheKey, previous);
|
||||||
} else {
|
} else {
|
||||||
revision = randomUUID();
|
revision = randomUUID();
|
||||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||||
lastDisplaySteps = { scope, steps: projected, revision,
|
if (!displayStepsCache.has(cacheKey) && displayStepsCache.size >= MAX_DISPLAY_STEP_CACHE_ENTRIES) {
|
||||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
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));
|
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' }),
|
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
displayStepsCache.clear();
|
||||||
|
clearScannerRuntimeMemos();
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ function isSqliteBusyError(err) {
|
|||||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||||
*/
|
*/
|
||||||
function withReadOnlySqliteDb(dbPath, queryFn) {
|
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||||
if (!DatabaseSync) return null;
|
if (!DatabaseSync) return null;
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
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 });
|
targets.push({ rootName: basename(root).toLowerCase(), dbPath });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const rootsKey = roots
|
||||||
|
.map((r) => String(r || '').trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
if (targets.length === 0) {
|
if (targets.length === 0) {
|
||||||
if (productRoots === PRODUCT_DATA_ROOTS) {
|
if (productRoots === PRODUCT_DATA_ROOTS) {
|
||||||
localSummaryMemo.sig = '';
|
localSummaryMemo.sig = '';
|
||||||
@@ -737,23 +742,41 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
|||||||
localSummaryMemo.summariesObj = {};
|
localSummaryMemo.summariesObj = {};
|
||||||
localSummaryMemo.sideQuestionParents = {};
|
localSummaryMemo.sideQuestionParents = {};
|
||||||
}
|
}
|
||||||
|
if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||||
|
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||||
|
}
|
||||||
return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} };
|
return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} };
|
||||||
}
|
}
|
||||||
|
|
||||||
const sig = sigParts.join('||');
|
const sig = sigParts.join('||');
|
||||||
if (
|
if (!forceRefresh) {
|
||||||
!forceRefresh &&
|
if (
|
||||||
productRoots === PRODUCT_DATA_ROOTS &&
|
productRoots === PRODUCT_DATA_ROOTS &&
|
||||||
localSummaryMemo.sig === sig &&
|
localSummaryMemo.sig === sig &&
|
||||||
localSummaryMemo.available
|
localSummaryMemo.available
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
available: true,
|
available: true,
|
||||||
sig,
|
sig,
|
||||||
byId: localSummaryMemo.byId,
|
byId: localSummaryMemo.byId,
|
||||||
summariesObj: localSummaryMemo.summariesObj || {},
|
summariesObj: localSummaryMemo.summariesObj || {},
|
||||||
sideQuestionParents: localSummaryMemo.sideQuestionParents || {},
|
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();
|
const nextMap = new Map();
|
||||||
@@ -990,6 +1013,18 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
|||||||
localSummaryMemo.available = true;
|
localSummaryMemo.available = true;
|
||||||
localSummaryMemo.summariesObj = nextSummariesObj;
|
localSummaryMemo.summariesObj = nextSummariesObj;
|
||||||
localSummaryMemo.sideQuestionParents = nextSideQuestionParents;
|
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 {
|
return {
|
||||||
@@ -1807,8 +1842,8 @@ function cleanShortPromptTitle(rawText, maxChars = 80) {
|
|||||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
||||||
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||||
const reqMatch = withoutTags.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/i);
|
const reqMatches = [...withoutTags.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||||
const target = reqMatch ? reqMatch[1] : withoutTags;
|
const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : withoutTags;
|
||||||
const singleLine = target.replace(/\s+/g, ' ').trim();
|
const singleLine = target.replace(/\s+/g, ' ').trim();
|
||||||
if (!singleLine) return '';
|
if (!singleLine) return '';
|
||||||
return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`;
|
return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`;
|
||||||
|
|||||||
@@ -552,6 +552,7 @@ export const localSummaryMemo = {
|
|||||||
available: false,
|
available: false,
|
||||||
summariesObj: {},
|
summariesObj: {},
|
||||||
sideQuestionParents: {},
|
sideQuestionParents: {},
|
||||||
|
byRootsKey: new Map(),
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||||
@@ -615,6 +616,7 @@ export function clearRuntimeCaches() {
|
|||||||
localSummaryMemo.available = false;
|
localSummaryMemo.available = false;
|
||||||
localSummaryMemo.summariesObj = {};
|
localSummaryMemo.summariesObj = {};
|
||||||
localSummaryMemo.sideQuestionParents = {};
|
localSummaryMemo.sideQuestionParents = {};
|
||||||
|
localSummaryMemo.byRootsKey.clear();
|
||||||
quotaSummaryCache.ts = 0;
|
quotaSummaryCache.ts = 0;
|
||||||
quotaSummaryCache.lastAttemptTs = 0;
|
quotaSummaryCache.lastAttemptTs = 0;
|
||||||
quotaSummaryCache.accountName = '';
|
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 liveActivityMemo = new Map();
|
||||||
const transcriptTailMemo = new Map();
|
const transcriptTailMemo = new Map();
|
||||||
|
|
||||||
|
export function clearScannerRuntimeMemos() {
|
||||||
|
failedFetchCooldownMap.clear();
|
||||||
|
liveActivityMemo.clear();
|
||||||
|
transcriptTailMemo.clear();
|
||||||
|
}
|
||||||
|
|
||||||
function findTranscriptPath(cascadeId) {
|
function findTranscriptPath(cascadeId) {
|
||||||
if (!cascadeId) return '';
|
if (!cascadeId) return '';
|
||||||
const normId = String(cascadeId).trim().toLowerCase();
|
const normId = String(cascadeId).trim().toLowerCase();
|
||||||
|
|||||||
@@ -513,7 +513,7 @@ export async function ensureLsEndpointDiscovered({
|
|||||||
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
if (!force && lsRuntimeEndpoint.baseUrl && (lsRuntimeEndpoint.csrfToken || !lsRuntimeEndpoint.isDynamic)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (lsDiscoveryState.inFlight) {
|
if (lsDiscoveryState.inFlight) {
|
||||||
|
|||||||
@@ -356,8 +356,8 @@ export function createStandaloneWebServer(options = {}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.lsAddr && options.csrfToken) {
|
if (options.lsAddr) {
|
||||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false });
|
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken || '', { isDynamic: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
||||||
|
|||||||
@@ -11,23 +11,18 @@
|
|||||||
|
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
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 shuttingDown = false;
|
||||||
let sawShutdownDispose = false;
|
let sawShutdownDispose = false;
|
||||||
let stdinBuf = '';
|
let stdinBuf = '';
|
||||||
@@ -171,8 +166,8 @@ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
|||||||
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||||
const cliArgs = process.argv.slice(2);
|
const cliArgs = process.argv.slice(2);
|
||||||
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
||||||
void runStandaloneCli(cliArgs);
|
void import('./standalone.mjs').then(({ runStandaloneCli }) => runStandaloneCli(cliArgs));
|
||||||
} else {
|
} else {
|
||||||
startBridgeDaemon();
|
void startBridgeDaemon();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,9 +25,9 @@ import {
|
|||||||
summarizeTtft,
|
summarizeTtft,
|
||||||
} from './trajectory-metrics.mjs';
|
} from './trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
getNodeSqliteDatabaseSync,
|
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
readLocalSummaryIndex,
|
readLocalSummaryIndex,
|
||||||
|
withReadOnlySqliteDb,
|
||||||
} from './backend/cli-sqlite-reader.mjs';
|
} from './backend/cli-sqlite-reader.mjs';
|
||||||
import {
|
import {
|
||||||
ensureCliStatusLineConfigured,
|
ensureCliStatusLineConfigured,
|
||||||
@@ -145,43 +145,35 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) {
|
|||||||
if (!cwd) return '';
|
if (!cwd) return '';
|
||||||
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
||||||
if (!existsSync(summariesDbPath)) return '';
|
if (!existsSync(summariesDbPath)) return '';
|
||||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
|
||||||
if (!DatabaseSync) return '';
|
|
||||||
|
|
||||||
const normCwd = normalizePathForMatch(cwd);
|
const normCwd = normalizePathForMatch(cwd);
|
||||||
if (!normCwd) return '';
|
if (!normCwd) return '';
|
||||||
|
|
||||||
let db = null;
|
|
||||||
try {
|
try {
|
||||||
db = new DatabaseSync(summariesDbPath, { readOnly: true });
|
const matched = withReadOnlySqliteDb(summariesDbPath, (db) => {
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT conversation_id, workspace, last_modified_time
|
`SELECT conversation_id, workspace, last_modified_time
|
||||||
FROM conversations_fts
|
FROM conversations_fts
|
||||||
WHERE chunk_index = -1
|
WHERE chunk_index = -1
|
||||||
ORDER BY last_modified_time DESC
|
ORDER BY last_modified_time DESC
|
||||||
LIMIT 40`
|
LIMIT 40`
|
||||||
)
|
)
|
||||||
.all();
|
.all();
|
||||||
for (const row of rows || []) {
|
for (const row of rows || []) {
|
||||||
const ws = normalizePathForMatch(row?.workspace);
|
const ws = normalizePathForMatch(row?.workspace);
|
||||||
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
||||||
if (cid && ws && ws === normCwd) {
|
if (cid && ws && ws === normCwd) {
|
||||||
return cid;
|
return cid;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return '';
|
||||||
|
});
|
||||||
|
return matched || '';
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略不存在 conversations_fts 表或读取失败
|
// 忽略不存在 conversations_fts 表或读取失败
|
||||||
} finally {
|
return '';
|
||||||
if (db) {
|
|
||||||
try {
|
|
||||||
db.close();
|
|
||||||
} catch {
|
|
||||||
// 忽略关闭异常
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1794977386430">
|
<link rel="stylesheet" href="/styles.css?v=1794981269167">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1794977386430"></script>
|
<script src="/app.js?v=1794981269167"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+20
-8
@@ -11,12 +11,7 @@
|
|||||||
|
|
||||||
import { Worker } from 'node:worker_threads';
|
import { Worker } from 'node:worker_threads';
|
||||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||||
import {
|
import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs';
|
||||||
bootWindowBridgeRuntime,
|
|
||||||
dispatchBridgeApiRequest,
|
|
||||||
isLocalHostRequest,
|
|
||||||
readLocalAsync,
|
|
||||||
} from './backend/api-actions.mjs';
|
|
||||||
|
|
||||||
const app = new SidecarApp();
|
const app = new SidecarApp();
|
||||||
|
|
||||||
@@ -144,9 +139,20 @@ async function ensureActiveWorker() {
|
|||||||
return activeWorker;
|
return activeWorker;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let testHarnessApiModulePromise = null;
|
||||||
|
|
||||||
|
function getTestHarnessApiModule() {
|
||||||
|
testHarnessApiModulePromise ||= import('./backend/api-actions.mjs');
|
||||||
|
return testHarnessApiModulePromise;
|
||||||
|
}
|
||||||
|
|
||||||
async function forwardApiCall(pathname, method, data) {
|
async function forwardApiCall(pathname, method, data) {
|
||||||
if (isTestHarnessEnv) {
|
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();
|
const upperMethod = String(method || 'GET').toUpperCase();
|
||||||
try {
|
try {
|
||||||
@@ -223,7 +229,13 @@ app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-up
|
|||||||
|
|
||||||
app.run();
|
app.run();
|
||||||
if (isTestHarnessEnv) {
|
if (isTestHarnessEnv) {
|
||||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
if (typeof bootWindowBridgeRuntime === 'function') {
|
||||||
|
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||||
|
} else {
|
||||||
|
void getTestHarnessApiModule().then((mod) =>
|
||||||
|
mod.bootWindowBridgeRuntime({ allowDynamicLs: false })
|
||||||
|
);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
void ensureActiveWorker();
|
void ensureActiveWorker();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,20 +107,24 @@ export const TopSessionHeader = defineComponent({
|
|||||||
|
|
||||||
let lastActiveCascadeId = '';
|
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() {
|
function renderHeaderState() {
|
||||||
const telSt = telemetryStore.getState();
|
const telSt = telemetryStore.getState();
|
||||||
const uiSt = uiStore.getState();
|
const uiSt = uiStore.getState();
|
||||||
const telemetry = telSt.telemetry;
|
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;
|
if (!uiSt.monitorVisible) return;
|
||||||
|
|
||||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||||
@@ -278,7 +282,10 @@ export const TopSessionHeader = defineComponent({
|
|||||||
syncState: st.syncState,
|
syncState: st.syncState,
|
||||||
telemetry: st.telemetry,
|
telemetry: st.telemetry,
|
||||||
}),
|
}),
|
||||||
() => renderHeaderState()
|
(slice) => {
|
||||||
|
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||||
|
renderHeaderState();
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const unsubI18n = i18nStore.subscribe(
|
const unsubI18n = i18nStore.subscribe(
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||||
'live.thinking': 'Thinking',
|
'live.thinking': 'Thinking',
|
||||||
|
'live.generating': 'Generating',
|
||||||
'live.running': 'Running',
|
'live.running': 'Running',
|
||||||
'live.done': 'Done',
|
'live.done': 'Done',
|
||||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||||
'live.thinking': '推理中',
|
'live.thinking': '推理中',
|
||||||
|
'live.generating': '生成中',
|
||||||
'live.running': '运行中',
|
'live.running': '运行中',
|
||||||
'live.done': '已完成',
|
'live.done': '已完成',
|
||||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||||
|
|||||||
@@ -800,7 +800,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
items: draftStepColumns,
|
items: draftStepColumns,
|
||||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||||
minItems: 2,
|
minItems: 2,
|
||||||
maxItems: 15,
|
maxItems: 14,
|
||||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||||
onPreview: (previewItems) => {
|
onPreview: (previewItems) => {
|
||||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/account-switch.mjs',
|
'../backend/account-switch.mjs',
|
||||||
'../shared/settings-normalization.mjs',
|
'../shared/settings-normalization.mjs',
|
||||||
'../shared/window-bridge-protocol.mjs',
|
'../shared/window-bridge-protocol.mjs',
|
||||||
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
'../backend/cli-sqlite-reader.mjs',
|
'../backend/cli-sqlite-reader.mjs',
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import vm from 'node:vm';
|
|||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
import {
|
import {
|
||||||
extractContextBreakdown,
|
extractContextBreakdown,
|
||||||
|
extractLiveActivity,
|
||||||
extractModelSteps,
|
extractModelSteps,
|
||||||
normalizeCachedStep,
|
normalizeCachedStep,
|
||||||
} from '../trajectory-metrics.mjs';
|
} 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.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);
|
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';
|
rawName = 'edit_file';
|
||||||
} else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) {
|
} else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) {
|
||||||
rawName = 'grep_search';
|
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';
|
rawName = 'find_by_name';
|
||||||
} else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) {
|
} else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) {
|
||||||
rawName = 'search_web';
|
rawName = 'search_web';
|
||||||
|
|||||||
Reference in New Issue
Block a user