mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
perf(panel): optimize P1 hot paths and consolidate P2 shared primitives
This commit is contained in:
@@ -12,6 +12,8 @@
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
|
||||
import { parseWorkspaceUrisColumn } from '../shared/workspace-uri.mjs';
|
||||
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
|
||||
import {
|
||||
@@ -611,22 +613,7 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
? decoded.annotations.sideQuestionCascadeIds
|
||||
: [];
|
||||
const sideQuestionTitles = decoded?.annotations?.sideQuestionTitles || {};
|
||||
let workspaceUri = '';
|
||||
const rawWsCol = String(row?.workspace_uris || '').trim();
|
||||
if (rawWsCol) {
|
||||
if (rawWsCol.startsWith('[')) {
|
||||
try {
|
||||
const parsedWs = JSON.parse(rawWsCol);
|
||||
if (Array.isArray(parsedWs)) {
|
||||
workspaceUri = String(parsedWs.find((u) => String(u || '').trim()) || '').trim();
|
||||
}
|
||||
} catch {
|
||||
workspaceUri = rawWsCol;
|
||||
}
|
||||
} else {
|
||||
workspaceUri = rawWsCol;
|
||||
}
|
||||
}
|
||||
const workspaceUri = parseWorkspaceUrisColumn(row?.workspace_uris)[0] || '';
|
||||
|
||||
const entry = {
|
||||
cascadeId: cidLower,
|
||||
@@ -1687,15 +1674,7 @@ function mapRunningGenericToolStepType(rawToolName) {
|
||||
}
|
||||
|
||||
function cleanShortPromptTitle(rawText, maxChars = 80) {
|
||||
const withoutTags = String(rawText || '')
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
||||
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
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()}…`;
|
||||
return extractShortPromptTitle(rawText, maxChars);
|
||||
}
|
||||
|
||||
function hasContextBreakdownPayload(chat) {
|
||||
@@ -2040,3 +2019,189 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量读取本地 SQLite 会话库的父/根会话关联(不扫描或解码 `steps` 全表),
|
||||
* 供 `cli-statusline.mjs` 在当前 ID 为子代理时快速跳转至根会话库。
|
||||
*
|
||||
* @param {string} dbFilePath
|
||||
* @returns {{ parentConversationId: string, rootConversationId: string } | null}
|
||||
*/
|
||||
export function readLocalSqliteParentLink(dbFilePath) {
|
||||
if (!dbFilePath || !existsSync(dbFilePath)) return null;
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
|
||||
const stem = basename(dbFilePath).replace(/\.db$/i, '').trim().toLowerCase();
|
||||
const normCid = UUID_FILE_RE.test(stem) ? stem : '';
|
||||
|
||||
try {
|
||||
return withReadOnlySqliteDb(dbFilePath, (db) => {
|
||||
let parentConversationId = '';
|
||||
let rootConversationId = '';
|
||||
try {
|
||||
const blobRow = db
|
||||
.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1")
|
||||
.get();
|
||||
const blobBuf = toUint8Array(blobRow?.data);
|
||||
if (blobBuf && blobBuf.length > 0) {
|
||||
const tm = decodeProtoTrajectoryMetadataSlice(blobBuf, { off: 0 }, blobBuf.length);
|
||||
parentConversationId = tm.parentConversationId || '';
|
||||
rootConversationId = tm.rootConversationId || '';
|
||||
}
|
||||
} catch {
|
||||
// 兼容未包含 trajectory_metadata_blob 的精简库
|
||||
}
|
||||
|
||||
if (!parentConversationId && !rootConversationId) {
|
||||
try {
|
||||
const genRow = db
|
||||
.prepare('SELECT data FROM gen_metadata ORDER BY idx DESC LIMIT 1')
|
||||
.get();
|
||||
if (genRow?.data) {
|
||||
const decoded = decodeProtoGeneratorMeta(genRow.data, false);
|
||||
const gmCid = String(decoded?.extraMeta?.cascade_id || '').trim().toLowerCase();
|
||||
if (!gmCid || !normCid || gmCid === normCid) {
|
||||
if (decoded?.extraMeta?.root_cascade_id) {
|
||||
rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase();
|
||||
}
|
||||
if (decoded?.extraMeta?.parent_cascade_id) {
|
||||
parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略 gen_metadata 探测异常
|
||||
}
|
||||
}
|
||||
|
||||
return { parentConversationId, rootConversationId };
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅读取本地 SQLite 会话库末尾 `tailLimit` 步(`ORDER BY idx DESC LIMIT ?`),
|
||||
* 供旁路运行会话活体检测(`extractLiveActivity`)使用,避免全表扫描与 `gen_metadata` 解码。
|
||||
*
|
||||
* @param {string} dbFilePath
|
||||
* @param {number} [tailLimit=16]
|
||||
* @returns {{ cascadeId: string, steps: object[] } | null}
|
||||
*/
|
||||
export function readLocalSqliteLiveTail(dbFilePath, tailLimit = 16) {
|
||||
if (!dbFilePath || !existsSync(dbFilePath)) return null;
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
|
||||
const limit = Math.max(1, Math.min(64, Math.floor(Number(tailLimit) || 16)));
|
||||
let normCid = '';
|
||||
const stem = basename(dbFilePath).replace(/\.db$/i, '').trim().toLowerCase();
|
||||
if (UUID_FILE_RE.test(stem)) {
|
||||
normCid = stem;
|
||||
}
|
||||
|
||||
try {
|
||||
return withReadOnlySqliteDb(dbFilePath, (db) => {
|
||||
if (!normCid) {
|
||||
try {
|
||||
const metaRow = db.prepare('SELECT cascade_id FROM trajectory_meta LIMIT 1').get();
|
||||
if (metaRow?.cascade_id) {
|
||||
normCid = String(metaRow.cascade_id).trim().toLowerCase();
|
||||
}
|
||||
} catch {
|
||||
// 忽略无 trajectory_meta 的库
|
||||
}
|
||||
}
|
||||
|
||||
const descRows = db
|
||||
.prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx DESC LIMIT ?')
|
||||
.all(limit);
|
||||
if (!descRows || descRows.length === 0) {
|
||||
return { cascadeId: normCid, steps: [] };
|
||||
}
|
||||
|
||||
const ascRows = descRows.slice().reverse();
|
||||
const ownStepRecords = [];
|
||||
const payloadIndices = [];
|
||||
for (const row of ascRows) {
|
||||
const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : ownStepRecords.length;
|
||||
const stepTypeNum = Number(row?.step_type || 0);
|
||||
const statusNum = Number(row?.status || 0);
|
||||
let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } };
|
||||
if (row?.metadata && row.metadata.byteLength > 0) {
|
||||
try {
|
||||
metadata = decodeProtoStepMeta(row.metadata, idx);
|
||||
} catch {
|
||||
// 忽略单步元数据解码异常
|
||||
}
|
||||
}
|
||||
const originCid = String(metadata.sourceTrajectoryStepInfo?.cascadeId || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (originCid && normCid && originCid !== normCid) continue;
|
||||
ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata });
|
||||
if (stepTypeNum !== 132 || !metadata?.toolCall?.argumentsJson) {
|
||||
payloadIndices.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
const payloadByIdx = new Map();
|
||||
if (payloadIndices.length > 0) {
|
||||
try {
|
||||
const placeholders = payloadIndices.map(() => '?').join(',');
|
||||
const pRows = db
|
||||
.prepare(`SELECT idx, step_payload FROM steps WHERE idx IN (${placeholders})`)
|
||||
.all(...payloadIndices);
|
||||
for (const pRow of pRows || []) {
|
||||
if (pRow?.step_payload && pRow.step_payload.byteLength > 0) {
|
||||
payloadByIdx.set(Number(pRow.idx), pRow.step_payload);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 兼容不含 step_payload 列的旧表
|
||||
}
|
||||
}
|
||||
|
||||
const steps = [];
|
||||
for (const rec of ownStepRecords) {
|
||||
const isInvSub =
|
||||
rec.stepTypeNum === 127 ||
|
||||
(rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name));
|
||||
let type = '';
|
||||
if (isInvSub) {
|
||||
type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT';
|
||||
} else if (rec.stepTypeNum === 132) {
|
||||
type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name);
|
||||
} else {
|
||||
type = decodeProtoStepTypeEnum(rec.stepTypeNum);
|
||||
}
|
||||
const status = decodeProtoStepStatusEnum(rec.statusNum);
|
||||
const stepObj = { idx: rec.idx, type, status, metadata: rec.metadata };
|
||||
const rawPayload = payloadByIdx.get(rec.idx);
|
||||
if (rawPayload) {
|
||||
try {
|
||||
const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, {
|
||||
stepTypeNum: rec.stepTypeNum,
|
||||
isInvokeSubagent: isInvSub,
|
||||
includeSystemMessage: false,
|
||||
keepFullText: true,
|
||||
});
|
||||
if (decodedPayload.userInput) stepObj.userInput = decodedPayload.userInput;
|
||||
if (decodedPayload.plannerResponse) stepObj.plannerResponse = decodedPayload.plannerResponse;
|
||||
if (decodedPayload.errorMessage) stepObj.errorMessage = decodedPayload.errorMessage;
|
||||
if (decodedPayload.invokeSubagent) stepObj.invokeSubagent = decodedPayload.invokeSubagent;
|
||||
} catch {
|
||||
// 忽略单步载荷解析异常
|
||||
}
|
||||
}
|
||||
steps.push(stepObj);
|
||||
}
|
||||
|
||||
return { cascadeId: normCid, steps };
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,11 @@
|
||||
* 避免深色背景色块突兀及 OSC 序列干扰 Bubble Tea 宽度计算)。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { delimiter, dirname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { writeTextFileAtomicSync } from './fs-atomic.mjs';
|
||||
import {
|
||||
HERE,
|
||||
lsRuntimeEndpoint,
|
||||
@@ -503,18 +504,7 @@ export function ensureCliStatusLineConfigured({
|
||||
}
|
||||
|
||||
const serialized = `${JSON.stringify(applied.object, null, 2).replace(/\n/g, eol)}${eol}`;
|
||||
const tmpPath = `${settingsPath}.tmp-${process.pid}`;
|
||||
try {
|
||||
writeFileSync(tmpPath, serialized, 'utf8');
|
||||
renameSync(tmpPath, settingsPath);
|
||||
} catch {
|
||||
try {
|
||||
if (existsSync(tmpPath)) unlinkSync(tmpPath);
|
||||
} catch {
|
||||
// 忽略临时文件清理异常
|
||||
}
|
||||
writeFileSync(settingsPath, serialized, 'utf8');
|
||||
}
|
||||
writeTextFileAtomicSync(settingsPath, serialized);
|
||||
|
||||
return {
|
||||
checked: true,
|
||||
|
||||
@@ -38,7 +38,7 @@ async function loadCcProxyNodeModules() {
|
||||
https: httpsMod.default || httpsMod,
|
||||
tls: tlsMod.default || tlsMod,
|
||||
zlib: zlibMod.default || zlibMod,
|
||||
execFileSync: cpMod.execFileSync,
|
||||
execFile: cpMod.execFile,
|
||||
openSync: fsMod.openSync,
|
||||
readSync: fsMod.readSync,
|
||||
closeSync: fsMod.closeSync,
|
||||
@@ -187,6 +187,47 @@ function parseWindowsProxyServerValue(rawVal) {
|
||||
return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`;
|
||||
}
|
||||
|
||||
let winRegProxyMemo = {
|
||||
rawOut: '',
|
||||
fetchedAtMs: 0,
|
||||
inFlight: null,
|
||||
};
|
||||
|
||||
async function readWindowsInternetSettingsAsync() {
|
||||
const nowMs = Date.now();
|
||||
if (winRegProxyMemo.fetchedAtMs > 0 && nowMs - winRegProxyMemo.fetchedAtMs < CC_PROXY_SYS_PROXY_CACHE_MS) {
|
||||
return winRegProxyMemo.rawOut;
|
||||
}
|
||||
if (winRegProxyMemo.inFlight) {
|
||||
return winRegProxyMemo.inFlight;
|
||||
}
|
||||
winRegProxyMemo.inFlight = (async () => {
|
||||
try {
|
||||
const { execFile } = await loadCcProxyNodeModules();
|
||||
const out = await new Promise((resolveOut) => {
|
||||
execFile(
|
||||
'reg',
|
||||
['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'],
|
||||
{ encoding: 'utf8', timeout: 2500, windowsHide: true },
|
||||
(err, stdout) => {
|
||||
resolveOut(err ? '' : String(stdout || ''));
|
||||
}
|
||||
);
|
||||
});
|
||||
winRegProxyMemo.rawOut = out;
|
||||
winRegProxyMemo.fetchedAtMs = Date.now();
|
||||
return out;
|
||||
} catch {
|
||||
winRegProxyMemo.rawOut = '';
|
||||
winRegProxyMemo.fetchedAtMs = Date.now();
|
||||
return '';
|
||||
} finally {
|
||||
winRegProxyMemo.inFlight = null;
|
||||
}
|
||||
})();
|
||||
return winRegProxyMemo.inFlight;
|
||||
}
|
||||
|
||||
export async function detectSystemHttpsProxy(targetHostname = '', { env = process.env, platform = process.platform } = {}) {
|
||||
const noProxy = env?.NO_PROXY || env?.no_proxy || '';
|
||||
if (shouldCcProxyBypassHost(targetHostname, noProxy)) return '';
|
||||
@@ -196,13 +237,8 @@ export async function detectSystemHttpsProxy(targetHostname = '', { env = proces
|
||||
if (envProxy) return /^https?:\/\//i.test(envProxy) ? envProxy : `http://${envProxy}`;
|
||||
if (platform !== 'win32') return '';
|
||||
try {
|
||||
const { execFileSync } = await loadCcProxyNodeModules();
|
||||
const out = execFileSync(
|
||||
'reg',
|
||||
['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'],
|
||||
{ encoding: 'utf8', timeout: 2500, windowsHide: true }
|
||||
);
|
||||
if (!/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(out)) return '';
|
||||
const out = await readWindowsInternetSettingsAsync();
|
||||
if (!out || !/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(out)) return '';
|
||||
const overrideMatch = out.match(/ProxyOverride\s+REG_SZ\s+([^\r\n]+)/i);
|
||||
if (overrideMatch && shouldCcProxyBypassHost(targetHostname, overrideMatch[1])) {
|
||||
return '';
|
||||
|
||||
@@ -8,14 +8,21 @@
|
||||
* 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||
import { writeJsonAtomicSync } from './fs-atomic.mjs';
|
||||
import { isPlainObject } from './http-helpers.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
import {
|
||||
CACHE_RUNNING_SAVE_INTERVAL_MS,
|
||||
createTrajectoryCacheStore,
|
||||
} from './trajectory-cache-store.mjs';
|
||||
import { normalizeFullSettings } from './settings-schema.mjs';
|
||||
|
||||
export { CACHE_RUNNING_SAVE_INTERVAL_MS, isPlainObject };
|
||||
|
||||
export {
|
||||
CLI_STATUSLINE_PRESETS,
|
||||
CONTEXT_AGENT_MODES,
|
||||
@@ -290,16 +297,6 @@ export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
||||
|
||||
/**
|
||||
* 判断输入值是否为非数组普通对象(Plain Object)。
|
||||
*
|
||||
* @param {unknown} v
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。
|
||||
*
|
||||
@@ -329,7 +326,7 @@ export function saveJson(filePath, data) {
|
||||
if (filePath === CACHE_FILE) {
|
||||
writeTrajectoryCacheFile(filePath, data);
|
||||
} else {
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
writeJsonAtomicSync(filePath, data);
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -355,12 +352,22 @@ export function roundMetric(value) {
|
||||
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
||||
}
|
||||
|
||||
const RUNTIME_CODE_VERSION_TTL_MS = 2_000;
|
||||
let cachedRuntimeCodeVersion = '';
|
||||
let cachedRuntimeCodeVersionExpiresAt = 0;
|
||||
|
||||
/**
|
||||
* 计算前端产物与后端源码文件的最大修改时间戳,用于插件热更新后触发客户端重载。
|
||||
* 内置 2 秒短期记忆化缓存,避免桥接守护与轮询循环高频重复执行 ~80 次同步 `statSync` / `readdirSync`。
|
||||
*
|
||||
* @param {{ force?: boolean }} [options={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function computeRuntimeCodeVersion() {
|
||||
export function computeRuntimeCodeVersion(options = {}) {
|
||||
const nowMs = Date.now();
|
||||
if (!options?.force && cachedRuntimeCodeVersion && nowMs < cachedRuntimeCodeVersionExpiresAt) {
|
||||
return cachedRuntimeCodeVersion;
|
||||
}
|
||||
let maxMtime = 0;
|
||||
const candidates = [
|
||||
join(HERE, 'app.js'),
|
||||
@@ -389,168 +396,66 @@ export function computeRuntimeCodeVersion() {
|
||||
}
|
||||
for (const file of candidates) {
|
||||
try {
|
||||
if (existsSync(file)) {
|
||||
const mtime = Math.floor(statSync(file).mtimeMs || 0);
|
||||
const st = statSync(file, { throwIfNoEntry: false });
|
||||
if (st) {
|
||||
const mtime = Math.floor(st.mtimeMs || 0);
|
||||
if (mtime > maxMtime) maxMtime = mtime;
|
||||
}
|
||||
} catch {
|
||||
// 忽略单文件 stat 异常
|
||||
}
|
||||
}
|
||||
return String(maxMtime || Date.now());
|
||||
cachedRuntimeCodeVersion = String(maxMtime || nowMs);
|
||||
cachedRuntimeCodeVersionExpiresAt = nowMs + RUNTIME_CODE_VERSION_TTL_MS;
|
||||
return cachedRuntimeCodeVersion;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移与损坏结构防御)
|
||||
// 跨模块共享运行时状态容器(首次访问时惰性加载历史轨迹缓存,避免 CLI 状态栏等无缓存消费者付出 13MB 解析开销)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const loadedTrajectoryCache = loadJson(CACHE_FILE, {});
|
||||
let initialCacheMigrated =
|
||||
loadedTrajectoryCache !== null &&
|
||||
loadedTrajectoryCache !== undefined &&
|
||||
!isPlainObject(loadedTrajectoryCache);
|
||||
|
||||
/**
|
||||
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
||||
* 本机内存态轨迹步骤缓存容器(委托 `createTrajectoryCacheStore`,首次读取时惰性加载历史缓存)。
|
||||
*/
|
||||
const trajectoryCache = Object.create(null);
|
||||
if (isPlainObject(loadedTrajectoryCache)) {
|
||||
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
|
||||
if (!id || !isPlainObject(entry)) {
|
||||
initialCacheMigrated = true;
|
||||
continue;
|
||||
}
|
||||
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||
if (!Array.isArray(entry.steps)) {
|
||||
initialCacheMigrated = true;
|
||||
}
|
||||
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
|
||||
if (objectSteps.length !== rawSteps.length) {
|
||||
initialCacheMigrated = true;
|
||||
}
|
||||
const normalizedSteps = objectSteps.map((s) => {
|
||||
const norm = normalizeCachedStep(s);
|
||||
if (norm !== s) initialCacheMigrated = true;
|
||||
return norm;
|
||||
});
|
||||
const finalSteps = inferCompactionStepModels(normalizedSteps);
|
||||
for (let i = 0; i < finalSteps.length; i++) {
|
||||
if (finalSteps[i] !== normalizedSteps[i]) {
|
||||
initialCacheMigrated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
trajectoryCache[id] = { ...entry, steps: finalSteps };
|
||||
}
|
||||
}
|
||||
const localTrajectoryCacheStore = createTrajectoryCacheStore({
|
||||
cacheFilePath: CACHE_FILE,
|
||||
loadJsonFn: loadJson,
|
||||
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
|
||||
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||
registerExitHook: true,
|
||||
});
|
||||
|
||||
export function getCachedTrajectory(cascadeId) {
|
||||
return trajectoryCache[cascadeId];
|
||||
return localTrajectoryCacheStore.getCachedTrajectory(cascadeId);
|
||||
}
|
||||
|
||||
export function getCachedTrajectoryEntryByLower(cascadeId) {
|
||||
return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId);
|
||||
}
|
||||
|
||||
export function listCachedTrajectoryEntries() {
|
||||
return Object.entries(trajectoryCache);
|
||||
return localTrajectoryCacheStore.listCachedTrajectoryEntries();
|
||||
}
|
||||
|
||||
export function setCachedTrajectory(cascadeId, entry) {
|
||||
trajectoryCache[cascadeId] = entry;
|
||||
localTrajectoryCacheStore.setCachedTrajectory(cascadeId, entry);
|
||||
}
|
||||
|
||||
export function removeCachedTrajectory(cascadeId) {
|
||||
delete trajectoryCache[cascadeId];
|
||||
localTrajectoryCacheStore.removeCachedTrajectory(cascadeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存状态与外部深层统计缓存 Memo。
|
||||
* 运行中会话采用 30 秒节流落盘(转入 IDLE、重建缓存或进程退出时立即刷盘),消除高频文件替换开销。
|
||||
*/
|
||||
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
|
||||
|
||||
const cacheState = {
|
||||
needsSave: initialCacheMigrated,
|
||||
lastSavedAtMs: 0,
|
||||
flushTimer: null,
|
||||
};
|
||||
|
||||
export function hasPendingTrajectoryCacheSave() {
|
||||
return cacheState.needsSave;
|
||||
return localTrajectoryCacheStore.hasPendingTrajectoryCacheSave();
|
||||
}
|
||||
|
||||
function cancelPendingCacheFlushTimer() {
|
||||
if (cacheState.flushTimer) {
|
||||
try {
|
||||
clearTimeout(cacheState.flushTimer);
|
||||
} catch {
|
||||
// 忽略沙箱无 clearTimeout 异常
|
||||
}
|
||||
cacheState.flushTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即将当前内存态 `trajectoryCache` 原子刷入磁盘并清理挂起定时器。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function flushTrajectoryCacheNow() {
|
||||
cancelPendingCacheFlushTimer();
|
||||
const ok = saveJson(CACHE_FILE, trajectoryCache);
|
||||
cacheState.needsSave = !ok;
|
||||
if (ok) {
|
||||
cacheState.lastSavedAtMs = Date.now();
|
||||
}
|
||||
return ok;
|
||||
return localTrajectoryCacheStore.flushTrajectoryCacheNow();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前是否存在运行中会话决定立即写盘还是 30 秒节流延迟写盘。
|
||||
* 默认单元测试沙箱(`lsRuntimeEndpoint.addr === 'test.invalid'`)同步落盘以保持断言确定性。
|
||||
*
|
||||
* @param {{ hasRunningSessions?: boolean, allowThrottleInTest?: boolean }} [options={}]
|
||||
*/
|
||||
export function persistTrajectoryCacheIfNeeded({
|
||||
hasRunningSessions = false,
|
||||
allowThrottleInTest = false,
|
||||
} = {}) {
|
||||
if (
|
||||
(lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest) ||
|
||||
typeof setTimeout !== 'function'
|
||||
) {
|
||||
flushTrajectoryCacheNow();
|
||||
return;
|
||||
}
|
||||
const nowMs = Date.now();
|
||||
const elapsedMs = nowMs - (cacheState.lastSavedAtMs || 0);
|
||||
if (
|
||||
!hasRunningSessions ||
|
||||
cacheState.lastSavedAtMs === 0 ||
|
||||
elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS
|
||||
) {
|
||||
flushTrajectoryCacheNow();
|
||||
return;
|
||||
}
|
||||
cacheState.needsSave = true;
|
||||
if (!cacheState.flushTimer) {
|
||||
const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs);
|
||||
const timer = setTimeout(() => {
|
||||
cacheState.flushTimer = null;
|
||||
if (cacheState.needsSave) {
|
||||
flushTrajectoryCacheNow();
|
||||
}
|
||||
}, delayMs);
|
||||
if (timer && typeof timer.unref === 'function') {
|
||||
timer.unref();
|
||||
}
|
||||
cacheState.flushTimer = timer;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
|
||||
process.once('exit', () => {
|
||||
if (cacheState.needsSave) {
|
||||
flushTrajectoryCacheNow();
|
||||
}
|
||||
});
|
||||
export function persistTrajectoryCacheIfNeeded(options = {}) {
|
||||
localTrajectoryCacheStore.persistTrajectoryCacheIfNeeded(options);
|
||||
}
|
||||
|
||||
export const externalDeepStatsMemo = {
|
||||
@@ -614,13 +519,7 @@ export const pluginUpdateState = {
|
||||
* @returns {boolean} 是否成功写回空白缓存文件
|
||||
*/
|
||||
export function clearRuntimeCaches() {
|
||||
if (!saveJson(CACHE_FILE, {})) return false;
|
||||
cancelPendingCacheFlushTimer();
|
||||
for (const key of Object.keys(trajectoryCache)) {
|
||||
delete trajectoryCache[key];
|
||||
}
|
||||
cacheState.needsSave = false;
|
||||
cacheState.lastSavedAtMs = 0;
|
||||
if (!localTrajectoryCacheStore.clearCache()) return false;
|
||||
externalDeepStatsMemo.sig = '';
|
||||
externalDeepStatsMemo.convos.clear();
|
||||
localSummaryMemo.sig = '';
|
||||
|
||||
@@ -34,7 +34,8 @@ import {
|
||||
} from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, dirname, join, win32 as pathWin32 } from 'node:path';
|
||||
import { DATA_DIR, lsRuntimeEndpoint } from './config.mjs';
|
||||
import { DATA_DIR, HERE, lsRuntimeEndpoint } from './config.mjs';
|
||||
import { writeTextFileAtomicSync } from './fs-atomic.mjs';
|
||||
|
||||
export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0';
|
||||
|
||||
@@ -589,20 +590,7 @@ async function spawnDetachedProcess(file, args, options = {}) {
|
||||
}
|
||||
|
||||
function writeTextFileAtomically(filePath, content, fsOps) {
|
||||
const { mkdirFn, writeFn, renameFn, unlinkFn } = fsOps;
|
||||
mkdirFn(dirname(filePath), { recursive: true });
|
||||
const tmpPath = `${filePath}.tmp-${process.pid}`;
|
||||
try {
|
||||
writeFn(tmpPath, content, 'utf8');
|
||||
renameFn(tmpPath, filePath);
|
||||
} catch {
|
||||
try {
|
||||
unlinkFn(tmpPath);
|
||||
} catch {
|
||||
// 忽略临时文件清理异常
|
||||
}
|
||||
writeFn(filePath, content, 'utf8');
|
||||
}
|
||||
writeTextFileAtomicSync(filePath, content, fsOps);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -769,293 +757,18 @@ export function probeWindowsShortcutsFast({
|
||||
};
|
||||
}
|
||||
|
||||
const WIN_SHORTCUT_PROVISION_PS = `
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
$enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1'
|
||||
$updated = New-Object System.Collections.Generic.List[string]
|
||||
$configured = New-Object System.Collections.Generic.List[string]
|
||||
$readOnly = New-Object System.Collections.Generic.List[string]
|
||||
$discoveredDirs = New-Object System.Collections.Generic.List[string]
|
||||
$ws = $null
|
||||
$userDesktopDir = [Environment]::GetFolderPath('Desktop')
|
||||
$commonDesktopDir = [Environment]::GetFolderPath('CommonDesktopDirectory')
|
||||
$userProgramsDir = [Environment]::GetFolderPath('Programs')
|
||||
$commonProgramsDir = [Environment]::GetFolderPath('CommonPrograms')
|
||||
$userStartupDir = [Environment]::GetFolderPath('Startup')
|
||||
$zhDesktop = ([string][char]0x684C + [string][char]0x9762)
|
||||
let cachedWinShortcutProvisionPs = '';
|
||||
|
||||
$flatSpecs = New-Object System.Collections.Generic.List[object]
|
||||
$seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir, [bool]$recordDiscovered) {
|
||||
if (-not $dirPath) { return }
|
||||
if (-not $seenScanDir.Add($dirPath)) { return }
|
||||
$exists = $false
|
||||
try { $exists = [bool](Test-Path -LiteralPath $dirPath -ErrorAction SilentlyContinue) } catch { $exists = $false }
|
||||
if (-not $exists) { return }
|
||||
$flatSpecs.Add(@{ Dir = $dirPath; IsCommon = $isCommon; Kind = $kind })
|
||||
if ($recordDiscovered) { $discoveredDirs.Add($dirPath) }
|
||||
if ($expandVendorSubdir) {
|
||||
try {
|
||||
foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -ErrorAction SilentlyContinue)) {
|
||||
if ($sub -and $sub.Name -and ($sub.Name -match '(?i)antigravity|^google(?:\\b|[\\s_-]|$)') -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) {
|
||||
$flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind })
|
||||
if ($recordDiscovered) { $discoveredDirs.Add([string]$sub.FullName) }
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
function getWinShortcutProvisionPs() {
|
||||
if (!cachedWinShortcutProvisionPs) {
|
||||
cachedWinShortcutProvisionPs = readFileSync(
|
||||
join(HERE, 'backend', 'windows-shortcut-provision.ps1'),
|
||||
'utf8'
|
||||
).trim();
|
||||
}
|
||||
return cachedWinShortcutProvisionPs;
|
||||
}
|
||||
|
||||
Add-ScanDir $userDesktopDir $false 'desktop' $false $true
|
||||
foreach ($d in @(
|
||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }),
|
||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' })
|
||||
)) {
|
||||
Add-ScanDir $d $false 'desktop' $false $false
|
||||
}
|
||||
foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) {
|
||||
if ($od) {
|
||||
Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false $false
|
||||
Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false $false
|
||||
}
|
||||
}
|
||||
Add-ScanDir $userProgramsDir $false 'programs' $true $true
|
||||
Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false $false
|
||||
Add-ScanDir $userStartupDir $false 'startup' $false $true
|
||||
if ($env:APPDATA) {
|
||||
Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false $false
|
||||
}
|
||||
Add-ScanDir $commonDesktopDir $true 'desktop' $false $true
|
||||
Add-ScanDir $commonProgramsDir $true 'programs' $true $true
|
||||
|
||||
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($spec in $flatSpecs) {
|
||||
$dir = [string]$spec.Dir
|
||||
$items = @()
|
||||
try {
|
||||
$items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue)
|
||||
} catch { continue }
|
||||
|
||||
foreach ($item in $items) {
|
||||
if ($item.Length -lt 32 -or $item.Length -gt 65536) { continue }
|
||||
$lnkPath = [string]$item.FullName
|
||||
if (-not $seen.Add($lnkPath)) { continue }
|
||||
try {
|
||||
$rawBytes = [System.IO.File]::ReadAllBytes($lnkPath)
|
||||
$u16 = [System.Text.Encoding]::Unicode.GetString($rawBytes)
|
||||
$lat = [System.Text.Encoding]::GetEncoding(28591).GetString($rawBytes)
|
||||
if ($u16.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0 -and
|
||||
$lat.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0) {
|
||||
continue
|
||||
}
|
||||
if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }
|
||||
$sc = $ws.CreateShortcut($lnkPath)
|
||||
$target = [string]$sc.TargetPath
|
||||
if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue }
|
||||
$curArgs = [string]$sc.Arguments
|
||||
if ($enableFlag) {
|
||||
if ($curArgs -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($lnkPath)
|
||||
continue
|
||||
}
|
||||
$nextArgs = ($curArgs.Trim() + ' --remote-debugging-port=0').Trim()
|
||||
try {
|
||||
$sc.Arguments = $nextArgs
|
||||
$sc.Save()
|
||||
$updated.Add($lnkPath)
|
||||
$configured.Add($lnkPath)
|
||||
} catch {
|
||||
$readOnly.Add($lnkPath)
|
||||
if ($spec.IsCommon -and $spec.Kind -eq 'programs' -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir -ErrorAction SilentlyContinue)) {
|
||||
$fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath))
|
||||
if (-not (Test-Path -LiteralPath $fallbackLnk -ErrorAction SilentlyContinue)) {
|
||||
try {
|
||||
$uSc = $ws.CreateShortcut($fallbackLnk)
|
||||
$uSc.TargetPath = $target
|
||||
$uSc.Arguments = $nextArgs
|
||||
if ($sc.WorkingDirectory) { $uSc.WorkingDirectory = $sc.WorkingDirectory }
|
||||
if ($sc.IconLocation) { $uSc.IconLocation = $sc.IconLocation }
|
||||
if ($sc.Description) { $uSc.Description = $sc.Description }
|
||||
$uSc.Save()
|
||||
$updated.Add($fallbackLnk)
|
||||
$configured.Add($fallbackLnk)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$stripped = ([regex]::Replace($curArgs, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
||||
if ($stripped -ne $curArgs.Trim()) {
|
||||
try {
|
||||
$sc.Arguments = $stripped
|
||||
$sc.Save()
|
||||
$updated.Add($lnkPath)
|
||||
} catch {
|
||||
$readOnly.Add($lnkPath)
|
||||
}
|
||||
}
|
||||
if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($lnkPath)
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
$runTargets = @(
|
||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run' }
|
||||
)
|
||||
foreach ($rt in $runTargets) {
|
||||
try {
|
||||
$runReadKey = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
||||
if (-not $runReadKey) { continue }
|
||||
$runNames = @($runReadKey.GetValueNames())
|
||||
$runReadKey.Close()
|
||||
foreach ($valName in $runNames) {
|
||||
$rk = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
||||
if (-not $rk) { continue }
|
||||
$rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rk.Close()
|
||||
if (-not $rawCmd) { continue }
|
||||
if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue }
|
||||
$exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restPart = [string]$Matches[3]
|
||||
if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue }
|
||||
$quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate }
|
||||
$entryId = if ($rt.Label -eq 'HKLM') { "HKLM:Run:$($rt.SubPath)|$valName" } else { "HKCU:Run:$valName" }
|
||||
if ($enableFlag) {
|
||||
if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($entryId)
|
||||
continue
|
||||
}
|
||||
$nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim()
|
||||
$nextVal = "$quotedExe $nextRest"
|
||||
$saved = $false
|
||||
try {
|
||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
||||
if ($wk) {
|
||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wk.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($entryId)
|
||||
$configured.Add($entryId)
|
||||
} elseif ($rt.Label -eq 'HKLM') {
|
||||
$readOnly.Add($entryId)
|
||||
}
|
||||
} else {
|
||||
$strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
||||
$nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe }
|
||||
if ($nextVal -ne $rawCmd.Trim()) {
|
||||
$saved = $false
|
||||
try {
|
||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
||||
if ($wk) {
|
||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wk.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($entryId)
|
||||
} elseif ($rt.Label -eq 'HKLM') {
|
||||
$readOnly.Add($entryId)
|
||||
}
|
||||
}
|
||||
if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($entryId)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
$exactClassSubKeys = @(
|
||||
'Software\\Classes\\antigravity\\shell\\open\\command',
|
||||
'Software\\Classes\\Applications\\Antigravity.exe\\shell\\open\\command',
|
||||
'Software\\Classes\\AntigravitySourceFile\\shell\\open\\command'
|
||||
)
|
||||
$classRoots = @(
|
||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; FullPrefix = 'HKEY_CURRENT_USER' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; FullPrefix = 'HKEY_LOCAL_MACHINE' }
|
||||
)
|
||||
foreach ($cr in $classRoots) {
|
||||
foreach ($relSubKey in $exactClassSubKeys) {
|
||||
try {
|
||||
$rOpen = $cr.Root.OpenSubKey($relSubKey, $false)
|
||||
if (-not $rOpen) { continue }
|
||||
$rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rOpen.Close()
|
||||
if (-not $rawOpen) { continue }
|
||||
if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue }
|
||||
$exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restOpen = ([string]$Matches[3]).Trim()
|
||||
if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue }
|
||||
$quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand }
|
||||
$fullKeyName = if ($cr.Label -eq 'HKLM') { "HKLM:Class:$relSubKey" } else { "$($cr.FullPrefix)\\$relSubKey" }
|
||||
if ($enableFlag) {
|
||||
if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($fullKeyName)
|
||||
continue
|
||||
}
|
||||
$nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" }
|
||||
$saved = $false
|
||||
try {
|
||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
||||
if ($wOpen) {
|
||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wOpen.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($fullKeyName)
|
||||
$configured.Add($fullKeyName)
|
||||
} elseif ($cr.Label -eq 'HKLM') {
|
||||
$readOnly.Add($fullKeyName)
|
||||
}
|
||||
} else {
|
||||
$strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
||||
$nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe }
|
||||
if ($nextOpen -ne $rawOpen.Trim()) {
|
||||
$saved = $false
|
||||
try {
|
||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
||||
if ($wOpen) {
|
||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wOpen.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($fullKeyName)
|
||||
} elseif ($cr.Label -eq 'HKLM') {
|
||||
$readOnly.Add($fullKeyName)
|
||||
}
|
||||
}
|
||||
if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$configured.Add($fullKeyName)
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
[pscustomobject]@{
|
||||
ok = $true
|
||||
updatedPaths = @($updated)
|
||||
configuredPaths = @($configured)
|
||||
readOnlyPaths = @($readOnly)
|
||||
discoveredDirs = @($discoveredDirs)
|
||||
} | ConvertTo-Json -Compress
|
||||
`.trim();
|
||||
|
||||
const cachedDiscoveredWinDirsByHome = new Map();
|
||||
|
||||
function getCachedWinDiscoveredDirs(homeDir) {
|
||||
@@ -1226,7 +939,7 @@ export async function ensureDesktopLaunchEntriesConfigured({
|
||||
const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, ops.existsFn);
|
||||
const out = await runner(
|
||||
psExe,
|
||||
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS],
|
||||
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', getWinShortcutProvisionPs()],
|
||||
{
|
||||
timeoutMs: 10000,
|
||||
env: {
|
||||
@@ -1590,6 +1303,83 @@ function psSingleQuote(val) {
|
||||
* @param {{ readOnlyShortcutPaths?: string[], psExePath?: string }} [extra]
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildReadonlyShortcutPatchPsBlock() {
|
||||
const coreLines = [
|
||||
'$ws = $null',
|
||||
'foreach ($item in $targets) {',
|
||||
' if (-not $item) { continue }',
|
||||
" if ($item.StartsWith('HKLM:Run:')) {",
|
||||
' try {',
|
||||
' $restKey = $item.Substring(9)',
|
||||
" $sepIdx = $restKey.IndexOf('|')",
|
||||
' if ($sepIdx -gt 0) {',
|
||||
' $subPath = $restKey.Substring(0, $sepIdx)',
|
||||
' $valName = $restKey.Substring($sepIdx + 1)',
|
||||
' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false)',
|
||||
' if ($rk) {',
|
||||
" $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
||||
' $rk.Close()',
|
||||
' if ($rawCmd -match \'^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$\') {',
|
||||
' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }',
|
||||
' $restPart = [string]$Matches[3]',
|
||||
" if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restPart -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {",
|
||||
' $qExe = if ($Matches[1] -or $exeCand -match \'\\s\') { \'"\' + $exeCand + \'"\' } else { $exeCand }',
|
||||
" $nextVal = ($qExe + ' ' + ($restPart.Trim() + ' --remote-debugging-port=0').Trim()).Trim()",
|
||||
' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true)',
|
||||
' if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }',
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' continue',
|
||||
' }',
|
||||
" if ($item.StartsWith('HKLM:Class:')) {",
|
||||
' try {',
|
||||
' $relKey = $item.Substring(11)',
|
||||
' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false)',
|
||||
' if ($rk) {',
|
||||
" $rawOpen = [string]$rk.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
||||
' $rk.Close()',
|
||||
' if ($rawOpen -match \'^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$\') {',
|
||||
' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }',
|
||||
' $restOpen = ([string]$Matches[3]).Trim()',
|
||||
" if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restOpen -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {",
|
||||
' $qExe = if ($Matches[1] -or $exeCand -match \'\\s\') { \'"\' + $exeCand + \'"\' } else { $exeCand }',
|
||||
" $nextOpen = if ($restOpen) { $qExe + ' --remote-debugging-port=0 ' + $restOpen } else { $qExe + ' --remote-debugging-port=0' }",
|
||||
' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true)',
|
||||
" if ($wk) { $wk.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }",
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' continue',
|
||||
' }',
|
||||
' if (Test-Path -LiteralPath $item) {',
|
||||
' try {',
|
||||
' if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }',
|
||||
' $sc = $ws.CreateShortcut($item)',
|
||||
' $cur = [string]$sc.Arguments',
|
||||
" if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {",
|
||||
" $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim()",
|
||||
' $sc.Save()',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' }',
|
||||
'}',
|
||||
];
|
||||
const fnLines = [
|
||||
'function Patch-ShortcutList($targets) {',
|
||||
' if (-not $targets -or $targets.Count -eq 0) { return }',
|
||||
...coreLines.map((line) => ` ${line}`),
|
||||
'}',
|
||||
].join('\n');
|
||||
const quotedLines = coreLines
|
||||
.map((line) => ` '${line.replace(/'/g, "''")}',`)
|
||||
.join('\n');
|
||||
return { fnLines, quotedLines };
|
||||
}
|
||||
|
||||
export function buildWindowsRelaunchInnerScript(
|
||||
executablePath,
|
||||
stalePortFiles = [],
|
||||
@@ -1598,6 +1388,7 @@ export function buildWindowsRelaunchInnerScript(
|
||||
) {
|
||||
const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity';
|
||||
const psExe = String(extra?.psExePath || 'powershell.exe').trim() || 'powershell.exe';
|
||||
const { fnLines, quotedLines } = buildReadonlyShortcutPatchPsBlock();
|
||||
const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : [])
|
||||
.map((p) => String(p || '').trim())
|
||||
.filter(Boolean)
|
||||
@@ -1626,70 +1417,7 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) {
|
||||
if ($livePath) { $exe = [string]$livePath }
|
||||
}
|
||||
|
||||
function Patch-ShortcutList($paths) {
|
||||
if (-not $paths -or $paths.Count -eq 0) { return }
|
||||
$ws = $null
|
||||
foreach ($item in $paths) {
|
||||
if (-not $item) { continue }
|
||||
if ($item.StartsWith('HKLM:Run:')) {
|
||||
try {
|
||||
$restKey = $item.Substring(9)
|
||||
$sepIdx = $restKey.IndexOf('|')
|
||||
if ($sepIdx -gt 0) {
|
||||
$subPath = $restKey.Substring(0, $sepIdx)
|
||||
$valName = $restKey.Substring($sepIdx + 1)
|
||||
$rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false)
|
||||
if ($rk) {
|
||||
$rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rk.Close()
|
||||
if ($rawCmd -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') {
|
||||
$exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restPart = [string]$Matches[3]
|
||||
if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restPart -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand }
|
||||
$nextVal = ($qExe + ' ' + ($restPart.Trim() + ' --remote-debugging-port=0').Trim()).Trim()
|
||||
$wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true)
|
||||
if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
continue
|
||||
}
|
||||
if ($item.StartsWith('HKLM:Class:')) {
|
||||
try {
|
||||
$relKey = $item.Substring(11)
|
||||
$rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false)
|
||||
if ($rk) {
|
||||
$rawOpen = [string]$rk.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rk.Close()
|
||||
if ($rawOpen -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') {
|
||||
$exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restOpen = ([string]$Matches[3]).Trim()
|
||||
if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restOpen -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand }
|
||||
$nextOpen = if ($restOpen) { "$qExe --remote-debugging-port=0 $restOpen" } else { "$qExe --remote-debugging-port=0" }
|
||||
$wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true)
|
||||
if ($wk) { $wk.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
continue
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $item)) { continue }
|
||||
try {
|
||||
if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }
|
||||
$sc = $ws.CreateShortcut($item)
|
||||
$cur = [string]$sc.Arguments
|
||||
if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||
$sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim()
|
||||
$sc.Save()
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
${fnLines}
|
||||
|
||||
if ($readOnlyShortcuts.Count -gt 0) {
|
||||
if ($isSelfElevated) {
|
||||
@@ -1699,68 +1427,7 @@ if ($readOnlyShortcuts.Count -gt 0) {
|
||||
$roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', '
|
||||
$elevBody = @(
|
||||
('$targets = @(' + $roJoined + ')'),
|
||||
'$ws = $null',
|
||||
'foreach ($item in $targets) {',
|
||||
' if (-not $item) { continue }',
|
||||
' if ($item.StartsWith(''HKLM:Run:'')) {',
|
||||
' try {',
|
||||
' $restKey = $item.Substring(9)',
|
||||
' $sepIdx = $restKey.IndexOf(''|'')',
|
||||
' if ($sepIdx -gt 0) {',
|
||||
' $subPath = $restKey.Substring(0, $sepIdx)',
|
||||
' $valName = $restKey.Substring($sepIdx + 1)',
|
||||
' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false)',
|
||||
' if ($rk) {',
|
||||
' $rawCmd = [string]$rk.GetValue($valName, '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)',
|
||||
' $rk.Close()',
|
||||
' if ($rawCmd -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {',
|
||||
' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }',
|
||||
' $restPart = [string]$Matches[3]',
|
||||
' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restPart -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {',
|
||||
' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }',
|
||||
' $nextVal = ($qExe + '' '' + ($restPart.Trim() + '' --remote-debugging-port=0'').Trim()).Trim()',
|
||||
' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true)',
|
||||
' if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }',
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' continue',
|
||||
' }',
|
||||
' if ($item.StartsWith(''HKLM:Class:'')) {',
|
||||
' try {',
|
||||
' $relKey = $item.Substring(11)',
|
||||
' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false)',
|
||||
' if ($rk) {',
|
||||
' $rawOpen = [string]$rk.GetValue('''', '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)',
|
||||
' $rk.Close()',
|
||||
' if ($rawOpen -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {',
|
||||
' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }',
|
||||
' $restOpen = ([string]$Matches[3]).Trim()',
|
||||
' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restOpen -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {',
|
||||
' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }',
|
||||
' $nextOpen = if ($restOpen) { $qExe + '' --remote-debugging-port=0 '' + $restOpen } else { $qExe + '' --remote-debugging-port=0'' }',
|
||||
' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true)',
|
||||
' if ($wk) { $wk.SetValue('''', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }',
|
||||
' }',
|
||||
' }',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' continue',
|
||||
' }',
|
||||
' if (Test-Path -LiteralPath $item) {',
|
||||
' try {',
|
||||
' if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }',
|
||||
' $sc = $ws.CreateShortcut($item)',
|
||||
' $cur = [string]$sc.Arguments',
|
||||
' if ($cur -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {',
|
||||
' $sc.Arguments = ($cur.Trim() + '' --remote-debugging-port=0'').Trim()',
|
||||
' $sc.Save()',
|
||||
' }',
|
||||
' } catch {}',
|
||||
' }',
|
||||
'}',
|
||||
${quotedLines}
|
||||
'Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue'
|
||||
) -join "\`r\`n"
|
||||
try {
|
||||
|
||||
@@ -10,18 +10,15 @@
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { join } from 'node:path';
|
||||
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||
import {
|
||||
CACHE_RUNNING_SAVE_INTERVAL_MS,
|
||||
DATA_DIR,
|
||||
clearRuntimeCaches,
|
||||
flushTrajectoryCacheNow,
|
||||
getCachedTrajectory,
|
||||
getCachedTrajectoryEntryByLower,
|
||||
hasPendingTrajectoryCacheSave,
|
||||
isPlainObject,
|
||||
listCachedTrajectoryEntries,
|
||||
loadJson,
|
||||
lsRuntimeEndpoint,
|
||||
@@ -30,7 +27,7 @@ import {
|
||||
removeCachedTrajectory,
|
||||
setCachedTrajectory,
|
||||
} from './config.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
import { createTrajectoryCacheStore } from './trajectory-cache-store.mjs';
|
||||
|
||||
const ENDPOINT_ID_REMOTE_RE = /^remote:[a-zA-Z0-9._:@-]{1,120}$/;
|
||||
const ENDPOINT_STALE_TTL_MS = 60_000;
|
||||
@@ -123,38 +120,6 @@ function buildRemoteCacheFilePath(stableHostKey) {
|
||||
return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`);
|
||||
}
|
||||
|
||||
function hydrateTrajectoryCacheObject(rawLoaded) {
|
||||
const cacheObj = Object.create(null);
|
||||
let migrated =
|
||||
rawLoaded !== null && rawLoaded !== undefined && !isPlainObject(rawLoaded);
|
||||
if (isPlainObject(rawLoaded)) {
|
||||
for (const [id, entry] of Object.entries(rawLoaded)) {
|
||||
if (!id || !isPlainObject(entry)) {
|
||||
migrated = true;
|
||||
continue;
|
||||
}
|
||||
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||
if (!Array.isArray(entry.steps)) migrated = true;
|
||||
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
|
||||
if (objectSteps.length !== rawSteps.length) migrated = true;
|
||||
const normalizedSteps = objectSteps.map((s) => {
|
||||
const norm = normalizeCachedStep(s);
|
||||
if (norm !== s) migrated = true;
|
||||
return norm;
|
||||
});
|
||||
const finalSteps = inferCompactionStepModels(normalizedSteps);
|
||||
for (let i = 0; i < finalSteps.length; i++) {
|
||||
if (finalSteps[i] !== normalizedSteps[i]) {
|
||||
migrated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
cacheObj[id] = { ...entry, steps: finalSteps };
|
||||
}
|
||||
}
|
||||
return { cacheObj, migrated };
|
||||
}
|
||||
|
||||
function createRemoteQuotaCache() {
|
||||
return {
|
||||
ts: 0,
|
||||
@@ -167,108 +132,12 @@ function createRemoteQuotaCache() {
|
||||
}
|
||||
|
||||
function createRemoteEndpointStore(cacheFilePath) {
|
||||
const loaded = cacheFilePath ? loadJson(cacheFilePath, {}) : {};
|
||||
const { cacheObj, migrated } = hydrateTrajectoryCacheObject(loaded);
|
||||
const state = {
|
||||
needsSave: Boolean(cacheFilePath && migrated),
|
||||
lastSavedAtMs: 0,
|
||||
flushTimer: null,
|
||||
};
|
||||
|
||||
function cancelFlushTimer() {
|
||||
if (state.flushTimer) {
|
||||
try {
|
||||
clearTimeout(state.flushTimer);
|
||||
} catch {
|
||||
// 忽略沙箱异常
|
||||
}
|
||||
state.flushTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCacheNow() {
|
||||
cancelFlushTimer();
|
||||
if (!cacheFilePath) {
|
||||
state.needsSave = false;
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
mkdirSync(dirname(cacheFilePath), { recursive: true });
|
||||
writeTrajectoryCacheFile(cacheFilePath, cacheObj);
|
||||
state.needsSave = false;
|
||||
state.lastSavedAtMs = Date.now();
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing remote cache ${cacheFilePath}: ${err.message}`);
|
||||
state.needsSave = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function persistIfNeeded({ hasRunningSessions = false } = {}) {
|
||||
if (!cacheFilePath) {
|
||||
state.needsSave = false;
|
||||
return;
|
||||
}
|
||||
if (lsRuntimeEndpoint.addr === 'test.invalid' || typeof setTimeout !== 'function') {
|
||||
writeCacheNow();
|
||||
return;
|
||||
}
|
||||
const nowMs = Date.now();
|
||||
const elapsedMs = nowMs - (state.lastSavedAtMs || 0);
|
||||
if (!hasRunningSessions || state.lastSavedAtMs === 0 || elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS) {
|
||||
writeCacheNow();
|
||||
return;
|
||||
}
|
||||
state.needsSave = true;
|
||||
if (!state.flushTimer) {
|
||||
const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs);
|
||||
const timer = setTimeout(() => {
|
||||
state.flushTimer = null;
|
||||
if (state.needsSave) {
|
||||
writeCacheNow();
|
||||
}
|
||||
}, delayMs);
|
||||
timer?.unref?.();
|
||||
state.flushTimer = timer;
|
||||
}
|
||||
}
|
||||
|
||||
function clearCache() {
|
||||
cancelFlushTimer();
|
||||
if (cacheFilePath) {
|
||||
try {
|
||||
mkdirSync(dirname(cacheFilePath), { recursive: true });
|
||||
writeTrajectoryCacheFile(cacheFilePath, {});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (const key of Object.keys(cacheObj)) {
|
||||
delete cacheObj[key];
|
||||
}
|
||||
state.needsSave = false;
|
||||
state.lastSavedAtMs = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
return createTrajectoryCacheStore({
|
||||
cacheFilePath,
|
||||
cacheState: state,
|
||||
cancelFlushTimer,
|
||||
getCachedTrajectory: (cascadeId) => cacheObj[cascadeId],
|
||||
listCachedTrajectoryEntries: () => Object.entries(cacheObj),
|
||||
setCachedTrajectory: (cascadeId, entry) => {
|
||||
cacheObj[cascadeId] = entry;
|
||||
},
|
||||
removeCachedTrajectory: (cascadeId) => {
|
||||
delete cacheObj[cascadeId];
|
||||
},
|
||||
hasPendingTrajectoryCacheSave: () => state.needsSave,
|
||||
persistTrajectoryCacheIfNeeded: persistIfNeeded,
|
||||
flushTrajectoryCacheNow: writeCacheNow,
|
||||
clearCache,
|
||||
};
|
||||
loadJsonFn: loadJson,
|
||||
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -445,6 +314,7 @@ export function getEndpointCacheStore(endpointOrId = null) {
|
||||
isRemote: false,
|
||||
endpointId: LOCAL_ENDPOINT_ID,
|
||||
getCachedTrajectory,
|
||||
getCachedTrajectoryEntryByLower,
|
||||
listCachedTrajectoryEntries,
|
||||
setCachedTrajectory,
|
||||
removeCachedTrajectory,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @fileoverview Shared synchronous atomic text & JSON file writer (`.tmp-${pid}` + `renameSync` with safe cleanup/fallback).
|
||||
*/
|
||||
|
||||
import { mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
/**
|
||||
* Atomically writes UTF-8 text to `filePath` via a sibling `.tmp-${pid}` file and `renameSync`,
|
||||
* falling back to direct overwrite if cross-device or Windows lock contention blocks rename.
|
||||
*
|
||||
* @param {string} filePath
|
||||
* @param {string} content
|
||||
* @param {{
|
||||
* mkdirFn?: typeof mkdirSync,
|
||||
* writeFn?: typeof writeFileSync,
|
||||
* renameFn?: typeof renameSync,
|
||||
* unlinkFn?: typeof unlinkSync,
|
||||
* }|null} [fsOps=null]
|
||||
*/
|
||||
export function writeTextFileAtomicSync(filePath, content, fsOps = null) {
|
||||
const mkdirFn = fsOps?.mkdirFn || mkdirSync;
|
||||
const writeFn = fsOps?.writeFn || writeFileSync;
|
||||
const renameFn = fsOps?.renameFn || renameSync;
|
||||
const unlinkFn = fsOps?.unlinkFn || unlinkSync;
|
||||
mkdirFn(dirname(filePath), { recursive: true });
|
||||
const tmpPath = `${filePath}.tmp-${process.pid}`;
|
||||
let renamed = false;
|
||||
try {
|
||||
writeFn(tmpPath, content, 'utf8');
|
||||
renameFn(tmpPath, filePath);
|
||||
renamed = true;
|
||||
} catch {
|
||||
if (!renamed) {
|
||||
try {
|
||||
unlinkFn(tmpPath);
|
||||
} catch {
|
||||
// Ignore missing or locked temporary file cleanup error
|
||||
}
|
||||
}
|
||||
writeFn(filePath, content, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically serializes and writes a JSON value to `filePath`.
|
||||
*
|
||||
* @param {string} filePath
|
||||
* @param {unknown} data
|
||||
* @param {{
|
||||
* indent?: number,
|
||||
* eol?: string,
|
||||
* trailingNewline?: boolean,
|
||||
* fsOps?: Parameters<typeof writeTextFileAtomicSync>[2],
|
||||
* }} [options={}]
|
||||
*/
|
||||
export function writeJsonAtomicSync(
|
||||
filePath,
|
||||
data,
|
||||
{ indent = 2, eol = '\n', trailingNewline = false, fsOps = null } = {}
|
||||
) {
|
||||
let serialized = JSON.stringify(data, null, indent);
|
||||
if (eol !== '\n') {
|
||||
serialized = serialized.replace(/\n/g, eol);
|
||||
}
|
||||
if (trailingNewline) {
|
||||
serialized += eol;
|
||||
}
|
||||
writeTextFileAtomicSync(filePath, serialized, fsOps);
|
||||
}
|
||||
@@ -13,6 +13,16 @@ function resolveHttpHelperPanelDir() {
|
||||
return /[\\/]backend$/i.test(modDir) ? dirname(modDir) : modDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断输入值是否为非数组普通对象(Plain Object)。
|
||||
*
|
||||
* @param {unknown} v
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
@@ -46,6 +47,11 @@ import { PLACEHOLDER_MAP } from './pricing-catalog.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 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 brainDirListingMemo = new Map();
|
||||
const knownExistingTranscriptPaths = new Set();
|
||||
let knownBrainCascadeSet = null;
|
||||
let knownBrainCascadeSetRootsKey = '';
|
||||
|
||||
/**
|
||||
* 联合扫描本地多端(Desktop / CLI / IDE)的 `conversations` 与 `brain/<id>/.system_generated/logs/transcript.jsonl`,
|
||||
* 按小写 `cascadeId` 归并关联磁盘文件路径。
|
||||
@@ -76,15 +82,35 @@ function discoverLocalConversationFiles() {
|
||||
|
||||
const brainDirs =
|
||||
Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
||||
const nextBrainUuidSet = new Set();
|
||||
for (const dir of brainDirs) {
|
||||
if (!dir || !existsSync(dir)) continue;
|
||||
try {
|
||||
for (const rawName of readdirSync(dir)) {
|
||||
const name = String(rawName || '').trim();
|
||||
const cascadeId = name.toLowerCase();
|
||||
if (!TRANSCRIPT_UUID_RE.test(cascadeId)) continue;
|
||||
const dirSt = statSync(dir);
|
||||
const dirMtimeMs = Math.floor(dirSt?.mtimeMs || 0);
|
||||
let cachedListing = dirMtimeMs > 0 ? brainDirListingMemo.get(dir) : null;
|
||||
if (!cachedListing || cachedListing.mtimeMs !== dirMtimeMs) {
|
||||
const uuidItems = [];
|
||||
for (const rawName of readdirSync(dir)) {
|
||||
const name = String(rawName || '').trim();
|
||||
const cascadeId = name.toLowerCase();
|
||||
if (!TRANSCRIPT_UUID_RE.test(cascadeId)) continue;
|
||||
uuidItems.push({ name, cascadeId });
|
||||
}
|
||||
cachedListing = { mtimeMs: dirMtimeMs, uuidItems };
|
||||
if (dirMtimeMs > 0) {
|
||||
brainDirListingMemo.set(dir, cachedListing);
|
||||
}
|
||||
}
|
||||
for (const { name, cascadeId } of cachedListing.uuidItems) {
|
||||
nextBrainUuidSet.add(cascadeId);
|
||||
const transcriptPath = join(dir, name, '.system_generated', 'logs', 'transcript.jsonl');
|
||||
if (!existsSync(transcriptPath)) continue;
|
||||
if (!knownExistingTranscriptPaths.has(transcriptPath)) {
|
||||
if (!existsSync(transcriptPath)) continue;
|
||||
if (dirMtimeMs > 0) {
|
||||
knownExistingTranscriptPaths.add(transcriptPath);
|
||||
}
|
||||
}
|
||||
if (!map.has(cascadeId)) map.set(cascadeId, []);
|
||||
map.get(cascadeId).push(transcriptPath);
|
||||
}
|
||||
@@ -92,6 +118,8 @@ function discoverLocalConversationFiles() {
|
||||
// 忽略目录读取异常
|
||||
}
|
||||
}
|
||||
knownBrainCascadeSet = nextBrainUuidSet.size > 0 ? nextBrainUuidSet : null;
|
||||
knownBrainCascadeSetRootsKey = brainDirs.join('|');
|
||||
|
||||
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
||||
if (annotationDirs.length > 0 && map.size > 0) {
|
||||
@@ -381,6 +409,9 @@ export function clearScannerRuntimeMemos(endpointId = null) {
|
||||
liveActivityMemo.clear();
|
||||
transcriptTailMemo.clear();
|
||||
swarmManifestMemo.clear();
|
||||
brainDirListingMemo.clear();
|
||||
knownExistingTranscriptPaths.clear();
|
||||
knownBrainCascadeSet = null;
|
||||
}
|
||||
|
||||
function findSwarmMembersPath(cascadeId) {
|
||||
@@ -388,6 +419,13 @@ function findSwarmMembersPath(cascadeId) {
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return '';
|
||||
const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
||||
if (
|
||||
knownBrainCascadeSet &&
|
||||
knownBrainCascadeSetRootsKey === dirs.join('|') &&
|
||||
!knownBrainCascadeSet.has(normId)
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
let bestPath = '';
|
||||
let bestMtime = -1;
|
||||
for (const dir of dirs) {
|
||||
@@ -541,21 +579,7 @@ function inferConversationAppSource(diskFiles = [], extMatch = null) {
|
||||
}
|
||||
|
||||
function extractOfflineUserTitle(rawContent) {
|
||||
if (typeof rawContent !== 'string' || !rawContent.trim()) return '';
|
||||
const withoutSummary = rawContent
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '');
|
||||
const reqMatches = [...withoutSummary.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||
const body =
|
||||
reqMatches.length > 0
|
||||
? reqMatches[reqMatches.length - 1][1]
|
||||
: withoutSummary.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
const firstLine = String(body || '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.find(Boolean);
|
||||
if (!firstLine) return '';
|
||||
return firstLine.length > 48 ? `${firstLine.slice(0, 47)}…` : firstLine;
|
||||
return extractShortPromptTitle(rawContent, 48, { firstLineOnly: true });
|
||||
}
|
||||
|
||||
const MAX_TITLE_PROBE_CACHE = 2000;
|
||||
@@ -660,14 +684,28 @@ function hasLocalSqliteDb(diskFiles = []) {
|
||||
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || '')));
|
||||
}
|
||||
|
||||
function resolveBestSqliteDbInfo(diskFiles = []) {
|
||||
function resolveBestSqliteDbInfo(diskFiles = [], { skipMissingWalFromListing = false } = {}) {
|
||||
if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null;
|
||||
let walPathsLower = null;
|
||||
if (skipMissingWalFromListing) {
|
||||
for (const rawPath of diskFiles) {
|
||||
const s = String(rawPath || '').trim();
|
||||
if (/\.db-wal$/i.test(s)) {
|
||||
if (!walPathsLower) walPathsLower = new Set();
|
||||
const fullWal = /[\\/]|^[a-zA-Z]:/.test(s) ? s : join(CONVERSATIONS_DIR, s);
|
||||
walPathsLower.add(fullWal.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
let best = null;
|
||||
for (const rawPath of diskFiles) {
|
||||
const p = String(rawPath || '').trim();
|
||||
if (!/\.db$/i.test(p)) continue;
|
||||
const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p);
|
||||
const walInfo = computeSqliteWalSig(fullPath);
|
||||
const skipWalCheck =
|
||||
skipMissingWalFromListing &&
|
||||
(!walPathsLower || !walPathsLower.has(`${fullPath.toLowerCase()}-wal`));
|
||||
const walInfo = computeSqliteWalSig(fullPath, { skipWalCheck });
|
||||
if (!walInfo.exists) continue;
|
||||
if (!best || walInfo.mtimeMs > best.mtimeMs) {
|
||||
best = {
|
||||
@@ -1629,7 +1667,9 @@ export async function enumerateAndSyncConversations({
|
||||
const localSum = localSummaryByLower.get(cidLower) || null;
|
||||
const cached = getEntry(cascadeId);
|
||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
||||
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
|
||||
const sqliteDbInfo = sqliteAvailable
|
||||
? resolveBestSqliteDbInfo(diskFiles, { skipMissingWalFromListing: true })
|
||||
: null;
|
||||
const dbPath = sqliteDbInfo?.dbPath || '';
|
||||
const diskFileSig = sqliteDbInfo?.sig || '';
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
@@ -1906,6 +1946,15 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
|
||||
let lazyExternalByLower = null;
|
||||
const pollSwarmManifestByCid = new Map();
|
||||
const getPollSwarmManifest = (cascadeId) => {
|
||||
if (isRemote || !cascadeId) return null;
|
||||
const key = String(cascadeId).trim().toLowerCase();
|
||||
if (pollSwarmManifestByCid.has(key)) return pollSwarmManifestByCid.get(key);
|
||||
const val = readSwarmManifestForCascade(key);
|
||||
pollSwarmManifestByCid.set(key, val);
|
||||
return val;
|
||||
};
|
||||
|
||||
/**
|
||||
* 批量拉取会话轨迹并提取步骤、子代理元数据 (`trajectory.metadata`) 与子代理调用引用 (`invokeSubagent`)。
|
||||
@@ -2063,7 +2112,7 @@ export async function enumerateAndSyncConversations({
|
||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||
const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps);
|
||||
const ownSwarmManifest =
|
||||
!isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
||||
!isRemote && !conv.isSubagent ? getPollSwarmManifest(cidLower) : null;
|
||||
if (ownSwarmManifest?.workerRefs?.length) {
|
||||
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
||||
for (const wRef of ownSwarmManifest.workerRefs) {
|
||||
@@ -2422,10 +2471,19 @@ export async function enumerateAndSyncConversations({
|
||||
if (hasMissingStepFields(cached)) return true;
|
||||
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
||||
if (!conv.inSummaries) {
|
||||
if (isRunning || cached.wasRunning) return true;
|
||||
if (conv.dbPath && sqliteAvailable) {
|
||||
return cached.signature !== sig;
|
||||
if (Boolean(isRunning) !== Boolean(cached.wasRunning) || cached.signature !== sig) {
|
||||
return true;
|
||||
}
|
||||
if (isRunning) {
|
||||
const prevLive = activeLiveActivityMemo.get(lowerCid);
|
||||
if (prevLive) {
|
||||
conv.liveActivity = prevLive;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (isRunning || cached.wasRunning) return true;
|
||||
if (
|
||||
cached.offlineTranscriptFallback &&
|
||||
!cached.offlineSqliteTelemetry &&
|
||||
@@ -2504,7 +2562,7 @@ export async function enumerateAndSyncConversations({
|
||||
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
const swarmManifest =
|
||||
!isRemote && !parentConv.isSubagent
|
||||
? readSwarmManifestForCascade(parentConv.cascadeId)
|
||||
? getPollSwarmManifest(parentConv.cascadeId)
|
||||
: null;
|
||||
let refs = baseRefs;
|
||||
if (swarmManifest?.workerRefs?.length) {
|
||||
@@ -2800,7 +2858,7 @@ export async function enumerateAndSyncConversations({
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const rootCached = getEntry(rootConv.cascadeId);
|
||||
const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid);
|
||||
const swarmManifest = isRemote ? null : getPollSwarmManifest(cid);
|
||||
const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim();
|
||||
if (swarmTitle) {
|
||||
rootConv.swarmTitle = swarmTitle;
|
||||
|
||||
@@ -13,6 +13,13 @@
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
|
||||
import {
|
||||
parseWorkspaceDisplayLabel,
|
||||
parseWorkspaceUrisColumn,
|
||||
toDesktopEncodedWorkspaceUri,
|
||||
toRawWorkspaceFileUri,
|
||||
} from '../shared/workspace-uri.mjs';
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
@@ -115,97 +122,19 @@ function migratorFormatSqliteUtcTime(epochMs) {
|
||||
* @returns {string}
|
||||
*/
|
||||
export function migratorToRawFileUri(rawInput) {
|
||||
const raw = String(rawInput || '').trim();
|
||||
if (!raw) return '';
|
||||
if (/^file:\/\//i.test(raw)) {
|
||||
let body = raw.replace(/^file:\/\/\/?/i, '');
|
||||
try {
|
||||
body = decodeURIComponent(body);
|
||||
} catch {
|
||||
body = body.replace(/%3A/gi, ':');
|
||||
}
|
||||
body = body.replace(/\\/g, '/').replace(/^\/+/, '');
|
||||
if (/^[a-zA-Z]:/.test(body)) {
|
||||
return `file:///${body}`;
|
||||
}
|
||||
return `file:///${body}`;
|
||||
}
|
||||
const normalized = raw.replace(/\\/g, '/');
|
||||
if (/^[a-zA-Z]:\//.test(normalized)) {
|
||||
return `file:///${normalized}`;
|
||||
}
|
||||
if (normalized.startsWith('/')) {
|
||||
return `file://${normalized}`;
|
||||
}
|
||||
return `file:///${normalized}`;
|
||||
return toRawWorkspaceFileUri(rawInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 `file://` URI 或本地路径规整为 Antigravity 桌面端标准编码格式(Windows 盘符小写 + `%3A`)。
|
||||
*
|
||||
* @param {string} rawInput
|
||||
* @returns {string}
|
||||
*/
|
||||
export function migratorToDesktopEncodedUri(rawInput) {
|
||||
const raw = String(rawInput || '').trim();
|
||||
if (!raw) return '';
|
||||
if (/^file:\/\/\/[a-z]%3A\//i.test(raw)) {
|
||||
return raw.replace(/^file:\/\/\/([a-zA-Z])%3A\//i, (_, d) => `file:///${d.toLowerCase()}%3A/`);
|
||||
}
|
||||
const unencoded = migratorToRawFileUri(raw);
|
||||
const body = unencoded.replace(/^file:\/\/\//i, '');
|
||||
const winMatch = body.match(/^([a-zA-Z]):(.*)$/);
|
||||
if (winMatch) {
|
||||
const drive = winMatch[1].toLowerCase();
|
||||
const rest = winMatch[2]
|
||||
.split('/')
|
||||
.map((seg) => (seg ? encodeURIComponent(seg) : ''))
|
||||
.join('/');
|
||||
return `file:///${drive}%3A${rest}`;
|
||||
}
|
||||
const encodedPath = body
|
||||
.split('/')
|
||||
.map((seg) => (seg ? encodeURIComponent(seg) : ''))
|
||||
.join('/');
|
||||
return `file:///${encodedPath}`;
|
||||
return toDesktopEncodedWorkspaceUri(rawInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `file:///` URI 提取可读路径和末级项目显示名。
|
||||
*
|
||||
* @param {string} rawUri
|
||||
* @returns {{ name: string, displayPath: string }}
|
||||
*/
|
||||
export function migratorParseWorkspaceLabel(rawUri) {
|
||||
const raw = String(rawUri || '').trim();
|
||||
if (!raw) return { name: '', displayPath: '' };
|
||||
let decoded = raw.replace(/^file:\/\/\/?/i, '');
|
||||
try {
|
||||
decoded = decodeURIComponent(decoded);
|
||||
} catch {
|
||||
decoded = decoded.replace(/%3A/gi, ':');
|
||||
}
|
||||
decoded = decoded.replace(/\\/g, '/').replace(/\/+$/, '');
|
||||
if (!decoded) return { name: '', displayPath: '' };
|
||||
const parts = decoded.split('/').filter(Boolean);
|
||||
const name = parts.length > 0 ? parts[parts.length - 1] : decoded;
|
||||
return { name, displayPath: decoded };
|
||||
return parseWorkspaceDisplayLabel(rawUri);
|
||||
}
|
||||
|
||||
function migratorParseWorkspaceUrisColumn(rawVal) {
|
||||
const str = String(rawVal || '').trim();
|
||||
if (!str) return [];
|
||||
if (str.startsWith('[')) {
|
||||
try {
|
||||
const parsed = JSON.parse(str);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.map((item) => String(item || '').trim()).filter(Boolean);
|
||||
}
|
||||
} catch {
|
||||
// 退回单值解析
|
||||
}
|
||||
}
|
||||
return [str];
|
||||
return parseWorkspaceUrisColumn(rawVal);
|
||||
}
|
||||
|
||||
function migratorEscapePbtxtString(text) {
|
||||
@@ -217,15 +146,7 @@ function migratorEscapePbtxtString(text) {
|
||||
}
|
||||
|
||||
function migratorCleanPromptTitle(rawText, maxChars = 72) {
|
||||
const cleaned = String(rawText || '')
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
||||
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
const reqMatches = [...cleaned.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||
const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : cleaned;
|
||||
const singleLine = target.replace(/\s+/g, ' ').trim();
|
||||
if (!singleLine) return '';
|
||||
return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`;
|
||||
return extractShortPromptTitle(rawText, maxChars);
|
||||
}
|
||||
|
||||
function migratorDecodeUserPromptFromStepPayload(rawBlob) {
|
||||
@@ -1129,13 +1050,15 @@ export function migrateSessions(params = {}, options = {}) {
|
||||
// 写入目标摘要库前自动留存滚动备份(移动模式同时备份源摘要库)
|
||||
const backupRoot = migratorResolveBackupRoot(options.backupDir);
|
||||
let backupPath = '';
|
||||
const warnings = [];
|
||||
try {
|
||||
backupPath = migratorBackupSummaryDb(dstSumDbPath, dstDef.id, backupRoot);
|
||||
if (mode === 'move' && existsSync(srcSumDbPath)) {
|
||||
migratorBackupSummaryDb(srcSumDbPath, srcDef.id, backupRoot);
|
||||
}
|
||||
} catch {
|
||||
} catch (bakErr) {
|
||||
backupPath = '';
|
||||
warnings.push(`summary_backup_failed: ${bakErr?.message || 'unknown'}`);
|
||||
}
|
||||
|
||||
const archiveSrcDir = join(backupRoot, 'archived-sources', srcDef.id);
|
||||
@@ -1575,6 +1498,7 @@ export function migrateSessions(params = {}, options = {}) {
|
||||
migratedCount,
|
||||
failedCount,
|
||||
backupPath,
|
||||
...(warnings.length > 0 ? { warnings } : {}),
|
||||
needsWindowReload: dstDef.id === 'desktop' && migratedCount > 0,
|
||||
results,
|
||||
};
|
||||
|
||||
@@ -65,23 +65,22 @@ export function hasBuiltinNodeSqlite() {
|
||||
* @param {string} dbPath
|
||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||
*/
|
||||
export function computeSqliteWalSig(dbPath) {
|
||||
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
|
||||
export function computeSqliteWalSig(dbPath, { skipWalCheck = false } = {}) {
|
||||
if (!dbPath || typeof dbPath !== 'string') {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
let dbStat = null;
|
||||
try {
|
||||
dbStat = statSync(dbPath);
|
||||
dbStat = statSync(dbPath, { throwIfNoEntry: false });
|
||||
} catch {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
||||
|
||||
let walStat = null;
|
||||
const walPath = `${dbPath}-wal`;
|
||||
if (existsSync(walPath)) {
|
||||
if (!skipWalCheck) {
|
||||
try {
|
||||
walStat = statSync(walPath);
|
||||
walStat = statSync(`${dbPath}-wal`, { throwIfNoEntry: false });
|
||||
} catch {
|
||||
walStat = null;
|
||||
}
|
||||
|
||||
@@ -96,6 +96,9 @@ function roundSessionCost(val) {
|
||||
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
|
||||
if (!cascadeId) return null;
|
||||
const store = cacheStore || getEndpointCacheStore(null);
|
||||
if (typeof store.getCachedTrajectoryEntryByLower === 'function') {
|
||||
return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null;
|
||||
}
|
||||
const entry = store.getCachedTrajectory(cascadeId);
|
||||
if (entry) return entry;
|
||||
const targetLower = String(cascadeId).toLowerCase();
|
||||
@@ -811,6 +814,105 @@ function getTelemetrySources(
|
||||
return pending;
|
||||
}
|
||||
|
||||
function classifySubagentDisplayMeta(subSum, subEntry, idx, counters) {
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const isSideQ = Boolean(
|
||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||
);
|
||||
const rawRole =
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const parsedSwarm = !isSideQ
|
||||
? parseSwarmWorkerRole({
|
||||
role: subSpec?.role || '',
|
||||
typeName: subSpec?.typeName || '',
|
||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
||||
memberName: subSum.swarmMemberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
||||
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const isKilled = Boolean(subSum.killed || subSum.swarmState === 'killed');
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let swarmState = '';
|
||||
let isSwarmAuxiliary = false;
|
||||
let shortLabel = '';
|
||||
let badgeText = '';
|
||||
let roleLabel = '';
|
||||
let runningRole = '';
|
||||
let typeName = '';
|
||||
let agentLabel = '';
|
||||
|
||||
if (isSideQ) {
|
||||
sideIndex = ++counters.side;
|
||||
agentKind = 'side_question';
|
||||
agentOrdinal = sideIndex;
|
||||
shortLabel = `旁路提问 #${sideIndex}`;
|
||||
badgeText = `旁${sideIndex}`;
|
||||
const cleanSideRole =
|
||||
rawRole &&
|
||||
rawRole !== '旁路提问' &&
|
||||
rawRole !== 'Side Question' &&
|
||||
rawRole !== 'side_question'
|
||||
? rawRole
|
||||
: '';
|
||||
customRole = cleanSideRole;
|
||||
roleLabel = cleanSideRole || '旁路提问';
|
||||
runningRole = cleanSideRole || shortLabel;
|
||||
typeName = 'side_question';
|
||||
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
|
||||
} else if (isSwarmW) {
|
||||
const swOrd = ++counters.swarm;
|
||||
agentKind = 'swarm_worker';
|
||||
agentOrdinal = swOrd;
|
||||
const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : '';
|
||||
customRole = memberTag;
|
||||
shortLabel = `蜂群 #${swOrd}`;
|
||||
badgeText = `蜂${swOrd}`;
|
||||
roleLabel = memberTag || '蜂群';
|
||||
runningRole = memberTag || shortLabel;
|
||||
typeName = 'worker';
|
||||
agentLabel = memberTag ? `${shortLabel} · ${memberTag}` : shortLabel;
|
||||
swarmState = isKilled ? 'killed' : isSubRunning ? 'working' : subSum.swarmState || 'waiting';
|
||||
isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary);
|
||||
} else {
|
||||
const subOrd = ++counters.normal;
|
||||
agentKind = 'subagent';
|
||||
agentOrdinal = subOrd;
|
||||
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||
shortLabel = `子代理 #${subOrd}`;
|
||||
badgeText = `子${subOrd}`;
|
||||
roleLabel = rawRole || '子代理';
|
||||
runningRole = rawRole || shortLabel;
|
||||
typeName = subSpec?.typeName || '';
|
||||
agentLabel = rawRole ? `${shortLabel} · ${rawRole}` : shortLabel;
|
||||
}
|
||||
|
||||
return {
|
||||
subSpec,
|
||||
isSideQ,
|
||||
isSwarmW,
|
||||
isSubRunning,
|
||||
isKilled,
|
||||
subIndex,
|
||||
sideIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
swarmState,
|
||||
isSwarmAuxiliary,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
roleLabel,
|
||||
runningRole,
|
||||
typeName,
|
||||
agentLabel,
|
||||
};
|
||||
}
|
||||
|
||||
function buildActiveConversationAssembly({
|
||||
activeCascadeId,
|
||||
activeConvSummary,
|
||||
@@ -942,9 +1044,7 @@ function buildActiveConversationAssembly({
|
||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||
let totalFamilyOutputTokens = sessionOutputTokens;
|
||||
|
||||
let normalSubCount = 0;
|
||||
let swarmWorkerCount = 0;
|
||||
let sideQuestionCount = 0;
|
||||
const subCounters = { normal: 0, swarm: 0, side: 0 };
|
||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||
const subSum = subagentSummaries[idx];
|
||||
const subCid = subSum.cascadeId;
|
||||
@@ -953,78 +1053,21 @@ function buildActiveConversationAssembly({
|
||||
const subRawSteps = subRawStepsList[idx];
|
||||
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
||||
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const isSideQ = Boolean(
|
||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||
);
|
||||
const rawRole =
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const parsedSwarm = !isSideQ
|
||||
? parseSwarmWorkerRole({
|
||||
role: subSpec?.role || '',
|
||||
typeName: subSpec?.typeName || '',
|
||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
||||
memberName: subSum.swarmMemberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let swarmState = '';
|
||||
let isSwarmAuxiliary = false;
|
||||
let shortLabel = '';
|
||||
let badgeText = '';
|
||||
let roleLabel = '';
|
||||
let typeName = '';
|
||||
let agentLabel = '';
|
||||
if (isSideQ) {
|
||||
sideIndex = ++sideQuestionCount;
|
||||
agentKind = 'side_question';
|
||||
agentOrdinal = sideIndex;
|
||||
shortLabel = `旁路提问 #${sideIndex}`;
|
||||
badgeText = `旁${sideIndex}`;
|
||||
const cleanSideRole =
|
||||
rawRole &&
|
||||
rawRole !== '旁路提问' &&
|
||||
rawRole !== 'Side Question' &&
|
||||
rawRole !== 'side_question'
|
||||
? rawRole
|
||||
: '';
|
||||
customRole = cleanSideRole;
|
||||
roleLabel = cleanSideRole || '旁路提问';
|
||||
typeName = 'side_question';
|
||||
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
|
||||
} else if (isSwarmW) {
|
||||
const swOrd = ++swarmWorkerCount;
|
||||
agentKind = 'swarm_worker';
|
||||
agentOrdinal = swOrd;
|
||||
const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : '';
|
||||
customRole = memberTag;
|
||||
shortLabel = `蜂群 #${swOrd}`;
|
||||
badgeText = `蜂${swOrd}`;
|
||||
roleLabel = memberTag || '蜂群';
|
||||
typeName = 'worker';
|
||||
agentLabel = memberTag ? `${shortLabel} · ${memberTag}` : shortLabel;
|
||||
swarmState = subSum.killed
|
||||
? 'killed'
|
||||
: subSum.status === 'CASCADE_RUN_STATUS_RUNNING'
|
||||
? 'working'
|
||||
: subSum.swarmState || 'waiting';
|
||||
isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary);
|
||||
} else {
|
||||
const subOrd = ++normalSubCount;
|
||||
agentKind = 'subagent';
|
||||
agentOrdinal = subOrd;
|
||||
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||
shortLabel = `子代理 #${subOrd}`;
|
||||
badgeText = `子${subOrd}`;
|
||||
roleLabel = rawRole || '子代理';
|
||||
typeName = subSpec?.typeName || '';
|
||||
agentLabel = rawRole ? `${shortLabel} · ${rawRole}` : shortLabel;
|
||||
}
|
||||
const {
|
||||
isSideQ,
|
||||
subIndex,
|
||||
sideIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
swarmState,
|
||||
isSwarmAuxiliary,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
roleLabel,
|
||||
typeName,
|
||||
agentLabel,
|
||||
} = classifySubagentDisplayMeta(subSum, subEntry, idx, subCounters);
|
||||
|
||||
const subUnit = buildAgentUnitTelemetry({
|
||||
agentId: subCid,
|
||||
@@ -1179,11 +1222,11 @@ function buildActiveConversationAssembly({
|
||||
mainAgentTelemetry;
|
||||
|
||||
const roleSummaryParts = [];
|
||||
if (swarmWorkerCount > 0) roleSummaryParts.push(`${swarmWorkerCount} 蜂群`);
|
||||
if (normalSubCount > 0) roleSummaryParts.push(`${normalSubCount} 子代理`);
|
||||
if (sideQuestionCount > 0) {
|
||||
if (subCounters.swarm > 0) roleSummaryParts.push(`${subCounters.swarm} 蜂群`);
|
||||
if (subCounters.normal > 0) roleSummaryParts.push(`${subCounters.normal} 子代理`);
|
||||
if (subCounters.side > 0) {
|
||||
roleSummaryParts.push(
|
||||
roleSummaryParts.length > 0 ? `${sideQuestionCount} 旁问` : `${sideQuestionCount} 旁路提问`
|
||||
roleSummaryParts.length > 0 ? `${subCounters.side} 旁问` : `${subCounters.side} 旁路提问`
|
||||
);
|
||||
}
|
||||
const aggregatedRoleLabel =
|
||||
@@ -1290,9 +1333,9 @@ function buildActiveConversationAssembly({
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
swarmCount: swarmWorkerCount,
|
||||
normalSubagentCount: normalSubCount,
|
||||
sideQuestionCount,
|
||||
swarmCount: subCounters.swarm,
|
||||
normalSubagentCount: subCounters.normal,
|
||||
sideQuestionCount: subCounters.side,
|
||||
totalStepsAllAgents: subAgentTelemetries.length
|
||||
? allCombinedEnrichedSteps.length
|
||||
: enrichedActiveSteps.length,
|
||||
@@ -1846,80 +1889,27 @@ export async function buildTelemetryPayloadInternal(
|
||||
const rootFallbackMs =
|
||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||
|
||||
let runNormalSubIdx = 0;
|
||||
let runSwarmIdx = 0;
|
||||
let runSideIdx = 0;
|
||||
const runCounters = { normal: 0, swarm: 0, side: 0 };
|
||||
const subItems = rawSubs.map((subSum, idx) => {
|
||||
const subCid = subSum.cascadeId;
|
||||
const subEntry = findTrajectoryCacheEntry(subCid, cacheStore);
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const isSideQ = Boolean(
|
||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||
);
|
||||
const rawRole =
|
||||
subSpec?.role ||
|
||||
subSum.agentScriptName ||
|
||||
subEntry?.agentScriptName ||
|
||||
subSpec?.typeName ||
|
||||
'';
|
||||
const parsedSwarm = !isSideQ
|
||||
? parseSwarmWorkerRole({
|
||||
role: subSpec?.role || '',
|
||||
typeName: subSpec?.typeName || '',
|
||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
||||
memberName: subSum.swarmMemberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let swarmState = '';
|
||||
let isSwarmAuxiliary = false;
|
||||
let badgeText = '';
|
||||
let shortLabel = '';
|
||||
let role = '';
|
||||
if (isSideQ) {
|
||||
sideIndex = ++runSideIdx;
|
||||
agentKind = 'side_question';
|
||||
agentOrdinal = sideIndex;
|
||||
badgeText = `旁${sideIndex}`;
|
||||
shortLabel = `旁路提问 #${sideIndex}`;
|
||||
const cleanSide =
|
||||
rawRole &&
|
||||
rawRole !== '旁路提问' &&
|
||||
rawRole !== 'Side Question' &&
|
||||
rawRole !== 'side_question'
|
||||
? rawRole
|
||||
: '';
|
||||
customRole = cleanSide;
|
||||
role = cleanSide || shortLabel;
|
||||
} else if (isSwarmW) {
|
||||
const swOrd = ++runSwarmIdx;
|
||||
agentKind = 'swarm_worker';
|
||||
agentOrdinal = swOrd;
|
||||
const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : '';
|
||||
customRole = memberTag;
|
||||
badgeText = `蜂${swOrd}`;
|
||||
shortLabel = `蜂群 #${swOrd}`;
|
||||
role = memberTag || shortLabel;
|
||||
isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary);
|
||||
} else {
|
||||
const nOrd = ++runNormalSubIdx;
|
||||
agentKind = 'subagent';
|
||||
agentOrdinal = nOrd;
|
||||
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||
badgeText = `子${nOrd}`;
|
||||
shortLabel = `子代理 #${nOrd}`;
|
||||
role = rawRole || shortLabel;
|
||||
}
|
||||
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const isKilled = Boolean(subSum.killed || subSum.swarmState === 'killed');
|
||||
if (isSwarmW) {
|
||||
swarmState = isKilled ? 'killed' : isSubRunning ? 'working' : subSum.swarmState || 'waiting';
|
||||
}
|
||||
const {
|
||||
subSpec,
|
||||
isSideQ,
|
||||
isSwarmW,
|
||||
isSubRunning,
|
||||
isKilled,
|
||||
subIndex,
|
||||
sideIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
swarmState,
|
||||
isSwarmAuxiliary,
|
||||
badgeText,
|
||||
shortLabel,
|
||||
runningRole: role,
|
||||
} = classifySubagentDisplayMeta(subSum, subEntry, idx, runCounters);
|
||||
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
||||
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
||||
const liveActivity = isSubRunning
|
||||
@@ -2088,9 +2078,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0,
|
||||
mainActivity: resolvedMainActivity,
|
||||
subagentCount: subItems.length,
|
||||
swarmCount: runSwarmIdx,
|
||||
normalSubagentCount: runNormalSubIdx,
|
||||
sideQuestionCount: runSideIdx,
|
||||
swarmCount: runCounters.swarm,
|
||||
normalSubagentCount: runCounters.normal,
|
||||
sideQuestionCount: runCounters.side,
|
||||
runningSubagentCount: runningSubList.length,
|
||||
runningSwarmCount: runningSubList.filter((s) => s.agentKind === 'swarm_worker').length,
|
||||
subagents: subItems,
|
||||
@@ -2115,7 +2105,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
windowBridge: getDefaultWindowBridgeStatus(),
|
||||
cloudCodeProxy: getDefaultCloudCodeProxyStatus(),
|
||||
cliStatusLine: getCliStatusLineRuntimeStatus(),
|
||||
settings: loadSettings(),
|
||||
settings,
|
||||
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
||||
const latest = group.members.reduce((previous, id) => {
|
||||
const reported = reportedContextLimits.get(id);
|
||||
|
||||
@@ -57,6 +57,7 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
||||
append('}');
|
||||
|
||||
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
||||
let renamed = false;
|
||||
try {
|
||||
const fd = openSync(temporaryPath, 'wx');
|
||||
try {
|
||||
@@ -72,6 +73,7 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
||||
}
|
||||
const written = statSync(temporaryPath, { bigint: true });
|
||||
renameSync(temporaryPath, filePath);
|
||||
renamed = true;
|
||||
const file = statSync(filePath, { bigint: true });
|
||||
lastWritesByPath.delete(filePath);
|
||||
if (isSameFile(written, file)) {
|
||||
@@ -82,6 +84,8 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
||||
lastWritesByPath.set(filePath, { filePath, file, ranges });
|
||||
}
|
||||
} finally {
|
||||
try { unlinkSync(temporaryPath); } catch {}
|
||||
if (!renamed) {
|
||||
try { unlinkSync(temporaryPath); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* @fileoverview Shared lazy-loaded, $O(1)$ case-insensitive, 30s-throttled trajectory cache store
|
||||
* reused by both the local sidecar (`config.mjs`) and remote SSH endpoints (`endpoint-registry.mjs`).
|
||||
*/
|
||||
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||
import { isPlainObject } from './http-helpers.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
|
||||
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Normalizes and repairs raw trajectory cache JSON into an unprototyped map.
|
||||
*
|
||||
* @param {unknown} rawLoaded
|
||||
* @returns {{ cacheObj: Record<string, any>, migrated: boolean }}
|
||||
*/
|
||||
export function hydrateTrajectoryCacheObject(rawLoaded) {
|
||||
const cacheObj = Object.create(null);
|
||||
let migrated = rawLoaded !== null && rawLoaded !== undefined && !isPlainObject(rawLoaded);
|
||||
if (isPlainObject(rawLoaded)) {
|
||||
for (const [id, entry] of Object.entries(rawLoaded)) {
|
||||
if (!id || !isPlainObject(entry)) {
|
||||
migrated = true;
|
||||
continue;
|
||||
}
|
||||
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||
if (!Array.isArray(entry.steps)) migrated = true;
|
||||
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
|
||||
if (objectSteps.length !== rawSteps.length) migrated = true;
|
||||
const normalizedSteps = objectSteps.map((s) => {
|
||||
const norm = normalizeCachedStep(s);
|
||||
if (norm !== s) migrated = true;
|
||||
return norm;
|
||||
});
|
||||
const finalSteps = inferCompactionStepModels(normalizedSteps);
|
||||
for (let i = 0; i < finalSteps.length; i += 1) {
|
||||
if (finalSteps[i] !== normalizedSteps[i]) {
|
||||
migrated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
cacheObj[id] = { ...entry, steps: finalSteps };
|
||||
}
|
||||
}
|
||||
return { cacheObj, migrated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an isolated trajectory cache store with lazy first-read hydration,
|
||||
* case-insensitive canonical key index, and 30-second throttled disk flushes.
|
||||
*
|
||||
* @param {{
|
||||
* cacheFilePath: string,
|
||||
* loadJsonFn: (filePath: string, fallback: any) => any,
|
||||
* writeCacheFn?: (filePath: string, cacheObj: Record<string, any>) => boolean,
|
||||
* shouldBypassThrottleFn?: (allowThrottleInTest: boolean) => boolean,
|
||||
* registerExitHook?: boolean,
|
||||
* }} options
|
||||
*/
|
||||
export function createTrajectoryCacheStore({
|
||||
cacheFilePath,
|
||||
loadJsonFn,
|
||||
writeCacheFn = null,
|
||||
shouldBypassThrottleFn = () => false,
|
||||
registerExitHook = false,
|
||||
}) {
|
||||
let cacheObj = Object.create(null);
|
||||
const byLower = new Map();
|
||||
let loadedOnce = false;
|
||||
const state = {
|
||||
needsSave: false,
|
||||
lastSavedAtMs: 0,
|
||||
flushTimer: null,
|
||||
};
|
||||
|
||||
function defaultWriteCache(targetPath, dataObj) {
|
||||
if (!targetPath) return true;
|
||||
try {
|
||||
mkdirSync(dirname(targetPath), { recursive: true });
|
||||
writeTrajectoryCacheFile(targetPath, dataObj);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing trajectory cache ${targetPath}: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const doWrite = writeCacheFn || defaultWriteCache;
|
||||
|
||||
function ensureLoaded() {
|
||||
if (loadedOnce) return;
|
||||
loadedOnce = true;
|
||||
if (!cacheFilePath) return;
|
||||
const loaded = loadJsonFn(cacheFilePath, {});
|
||||
const hydrated = hydrateTrajectoryCacheObject(loaded);
|
||||
cacheObj = hydrated.cacheObj;
|
||||
for (const key of Object.keys(cacheObj)) {
|
||||
byLower.set(key.toLowerCase(), key);
|
||||
}
|
||||
if (hydrated.migrated) {
|
||||
state.needsSave = true;
|
||||
}
|
||||
}
|
||||
|
||||
function cancelFlushTimer() {
|
||||
if (state.flushTimer) {
|
||||
try {
|
||||
clearTimeout(state.flushTimer);
|
||||
} catch {
|
||||
// Ignore sandbox missing clearTimeout
|
||||
}
|
||||
state.flushTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function flushTrajectoryCacheNow() {
|
||||
ensureLoaded();
|
||||
cancelFlushTimer();
|
||||
if (!cacheFilePath) {
|
||||
state.needsSave = false;
|
||||
return true;
|
||||
}
|
||||
const ok = doWrite(cacheFilePath, cacheObj);
|
||||
state.needsSave = !ok;
|
||||
if (ok) {
|
||||
state.lastSavedAtMs = Date.now();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
function persistTrajectoryCacheIfNeeded({
|
||||
hasRunningSessions = false,
|
||||
allowThrottleInTest = false,
|
||||
} = {}) {
|
||||
if (!cacheFilePath) {
|
||||
state.needsSave = false;
|
||||
return;
|
||||
}
|
||||
if (shouldBypassThrottleFn(allowThrottleInTest) || typeof setTimeout !== 'function') {
|
||||
flushTrajectoryCacheNow();
|
||||
return;
|
||||
}
|
||||
const nowMs = Date.now();
|
||||
const elapsedMs = nowMs - (state.lastSavedAtMs || 0);
|
||||
if (
|
||||
!hasRunningSessions ||
|
||||
state.lastSavedAtMs === 0 ||
|
||||
elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS
|
||||
) {
|
||||
flushTrajectoryCacheNow();
|
||||
return;
|
||||
}
|
||||
state.needsSave = true;
|
||||
if (!state.flushTimer) {
|
||||
const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs);
|
||||
const timer = setTimeout(() => {
|
||||
state.flushTimer = null;
|
||||
if (state.needsSave) {
|
||||
flushTrajectoryCacheNow();
|
||||
}
|
||||
}, delayMs);
|
||||
if (timer && typeof timer.unref === 'function') {
|
||||
timer.unref();
|
||||
}
|
||||
state.flushTimer = timer;
|
||||
}
|
||||
}
|
||||
|
||||
function clearCache() {
|
||||
if (cacheFilePath && !doWrite(cacheFilePath, {})) {
|
||||
return false;
|
||||
}
|
||||
cancelFlushTimer();
|
||||
loadedOnce = true;
|
||||
for (const key of Object.keys(cacheObj)) {
|
||||
delete cacheObj[key];
|
||||
}
|
||||
byLower.clear();
|
||||
state.needsSave = false;
|
||||
state.lastSavedAtMs = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (registerExitHook && typeof process !== 'undefined' && typeof process?.once === 'function') {
|
||||
process.once('exit', () => {
|
||||
if (loadedOnce && state.needsSave) {
|
||||
flushTrajectoryCacheNow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
cacheFilePath,
|
||||
cacheState: state,
|
||||
cancelFlushTimer,
|
||||
getCachedTrajectory(cascadeId) {
|
||||
ensureLoaded();
|
||||
return cacheObj[cascadeId];
|
||||
},
|
||||
getCachedTrajectoryEntryByLower(cascadeId) {
|
||||
if (!cascadeId) return null;
|
||||
ensureLoaded();
|
||||
const direct = cacheObj[cascadeId];
|
||||
if (direct) return { id: String(cascadeId), entry: direct };
|
||||
const canon = byLower.get(String(cascadeId).toLowerCase());
|
||||
if (canon && cacheObj[canon]) {
|
||||
return { id: canon, entry: cacheObj[canon] };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
listCachedTrajectoryEntries() {
|
||||
ensureLoaded();
|
||||
return Object.entries(cacheObj);
|
||||
},
|
||||
setCachedTrajectory(cascadeId, entry) {
|
||||
ensureLoaded();
|
||||
const lower = String(cascadeId || '').toLowerCase();
|
||||
const prevCanon = lower ? byLower.get(lower) : undefined;
|
||||
if (
|
||||
prevCanon &&
|
||||
prevCanon !== cascadeId &&
|
||||
Object.prototype.hasOwnProperty.call(cacheObj, prevCanon)
|
||||
) {
|
||||
delete cacheObj[prevCanon];
|
||||
}
|
||||
cacheObj[cascadeId] = entry;
|
||||
if (lower) {
|
||||
byLower.set(lower, String(cascadeId));
|
||||
}
|
||||
},
|
||||
removeCachedTrajectory(cascadeId) {
|
||||
ensureLoaded();
|
||||
const lower = String(cascadeId || '').toLowerCase();
|
||||
if (lower && byLower.get(lower) === cascadeId) {
|
||||
byLower.delete(lower);
|
||||
}
|
||||
delete cacheObj[cascadeId];
|
||||
},
|
||||
hasPendingTrajectoryCacheSave() {
|
||||
ensureLoaded();
|
||||
return state.needsSave;
|
||||
},
|
||||
persistTrajectoryCacheIfNeeded,
|
||||
flushTrajectoryCacheNow,
|
||||
clearCache,
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { decodeWorkspaceFileUriToPath } from '../shared/workspace-uri.mjs';
|
||||
import {
|
||||
MEASUREMENT_VERSION,
|
||||
accumulateSpeed,
|
||||
@@ -207,6 +208,20 @@ function resolveTimeWindow(
|
||||
}
|
||||
}
|
||||
|
||||
const LOCAL_TIMEZONE_TTL_MS = 30_000;
|
||||
let cachedLocalTimeZone = '';
|
||||
let cachedLocalTimeZoneAtMs = 0;
|
||||
|
||||
function resolveCachedLocalTimeZone() {
|
||||
const nowMs = Date.now();
|
||||
if (cachedLocalTimeZone && nowMs - cachedLocalTimeZoneAtMs < LOCAL_TIMEZONE_TTL_MS) {
|
||||
return cachedLocalTimeZone;
|
||||
}
|
||||
cachedLocalTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone || '';
|
||||
cachedLocalTimeZoneAtMs = nowMs;
|
||||
return cachedLocalTimeZone;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个空的用量统计累加桶。
|
||||
*/
|
||||
@@ -580,28 +595,7 @@ const UNBOUND_WORKSPACE_KEY = '__unbound__';
|
||||
* @returns {{ workspaceKey: string, label: string, workspacePath: string }|null}
|
||||
*/
|
||||
export function normalizeWorkspaceBucket(rawUri) {
|
||||
const raw = String(rawUri || '').trim();
|
||||
if (!raw) return null;
|
||||
let decoded = raw;
|
||||
if (/^file:\/\//i.test(decoded)) {
|
||||
decoded = decoded.replace(/^file:\/\//i, '');
|
||||
try {
|
||||
decoded = decodeURIComponent(decoded);
|
||||
} catch {
|
||||
decoded = decoded.replace(/%3A/gi, ':');
|
||||
}
|
||||
// Windows `file:///F:/...` 解码后形如 `/F:/...`,剥离盘符前多余斜杠;POSIX `/Users/...` 保留前导 `/`
|
||||
if (/^\/[A-Za-z]:/.test(decoded)) {
|
||||
decoded = decoded.slice(1);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
decoded = decodeURIComponent(decoded);
|
||||
} catch {
|
||||
// 保留原始文本
|
||||
}
|
||||
}
|
||||
decoded = decoded.replace(/\\/g, '/').replace(/\/+$/, '');
|
||||
const decoded = decodeWorkspaceFileUriToPath(rawUri);
|
||||
if (!decoded) return null;
|
||||
const parts = decoded.split('/').filter(Boolean);
|
||||
const label = parts.length > 0 ? parts[parts.length - 1] : decoded;
|
||||
@@ -1422,7 +1416,7 @@ export function aggregateMultiWindowUsage({
|
||||
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint);
|
||||
const familySig = buildFamilySig(familySet);
|
||||
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : '';
|
||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||
@@ -1944,7 +1938,7 @@ export function aggregateSelectedWindowUsage({
|
||||
: collectUsageEntriesToAggregate(familySet, endpoint);
|
||||
const familySig = buildFamilySig(familySet);
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : '';
|
||||
|
||||
const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
|
||||
const sameSnapshot = Boolean(
|
||||
@@ -2343,17 +2337,32 @@ export function aggregateSessionUsageForFamily({
|
||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||
|
||||
const familyEntries = [];
|
||||
for (const [cid, entry] of cacheStore.listCachedTrajectoryEntries()) {
|
||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||
const cidLower = String(cid || '').toLowerCase();
|
||||
if (!familySet.has(cidLower)) continue;
|
||||
familyEntries.push({
|
||||
cascadeId: cid,
|
||||
appSource: isRemote ? 'ssh' : entry.appSource || 'standalone',
|
||||
accountName: entry.accountName || '',
|
||||
steps: entry.steps,
|
||||
isCurrentConv: true,
|
||||
});
|
||||
if (typeof cacheStore.getCachedTrajectoryEntryByLower === 'function') {
|
||||
for (const fidLower of familySet) {
|
||||
const hit = cacheStore.getCachedTrajectoryEntryByLower(fidLower);
|
||||
const entry = hit?.entry;
|
||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||
familyEntries.push({
|
||||
cascadeId: hit.id,
|
||||
appSource: isRemote ? 'ssh' : entry.appSource || 'standalone',
|
||||
accountName: entry.accountName || '',
|
||||
steps: entry.steps,
|
||||
isCurrentConv: true,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for (const [cid, entry] of cacheStore.listCachedTrajectoryEntries()) {
|
||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||
const cidLower = String(cid || '').toLowerCase();
|
||||
if (!familySet.has(cidLower)) continue;
|
||||
familyEntries.push({
|
||||
cascadeId: cid,
|
||||
appSource: isRemote ? 'ssh' : entry.appSource || 'standalone',
|
||||
accountName: entry.accountName || '',
|
||||
steps: entry.steps,
|
||||
isCurrentConv: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return computeFamilySessionBuckets({
|
||||
|
||||
@@ -15,12 +15,11 @@ import {
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { writeTextFileAtomicSync } from './fs-atomic.mjs';
|
||||
import {
|
||||
BRIDGE_API_PATHS,
|
||||
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||
@@ -458,18 +457,7 @@ function patchSingleHostArgvFile(argvPath, { createDir = false, missingReason =
|
||||
argvPath,
|
||||
};
|
||||
}
|
||||
const tmpPath = `${argvPath}.tmp-${process.pid}`;
|
||||
try {
|
||||
writeFileSync(tmpPath, patched.text, 'utf8');
|
||||
renameSync(tmpPath, argvPath);
|
||||
} catch {
|
||||
try {
|
||||
unlinkSync(tmpPath);
|
||||
} catch {
|
||||
// 忽略临时文件清理异常
|
||||
}
|
||||
writeFileSync(argvPath, patched.text, 'utf8');
|
||||
}
|
||||
writeTextFileAtomicSync(argvPath, patched.text);
|
||||
return {
|
||||
checked: true,
|
||||
updated: true,
|
||||
@@ -1335,11 +1323,16 @@ export function createWindowBridgeController(options) {
|
||||
res.writeHead(out.status || 200, hdrs);
|
||||
res.end(out.body);
|
||||
})
|
||||
.catch(() => {
|
||||
.catch((err) => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { 'Content-Type': 'application/json' });
|
||||
}
|
||||
res.end(JSON.stringify({ error: 'Internal bridge error' }));
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
error: 'Internal bridge error',
|
||||
detail: String(err?.message || err || ''),
|
||||
})
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1388,11 +1381,16 @@ export function createWindowBridgeController(options) {
|
||||
res.writeHead(out.status || 200, hdrs);
|
||||
res.end(out.body);
|
||||
})
|
||||
.catch(() => {
|
||||
.catch((err) => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { 'Content-Type': 'application/json' });
|
||||
}
|
||||
res.end(JSON.stringify({ error: 'Internal bridge error' }));
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
error: 'Internal bridge error',
|
||||
detail: String(err?.message || err || ''),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1809,7 +1807,8 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
}
|
||||
leasedBySelf = true;
|
||||
lastPersistedLeaseSig = '';
|
||||
const mergedLauncherConfigured = Boolean(argvConfigured || launcherConfigured);
|
||||
lastPersistedLeaseSig = `${lastBridgeStatus.state}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${Boolean(argvUpdatedThisBoot) ? 1 : 0}:${mergedLauncherConfigured ? 1 : 0}:${Boolean(hasReadOnlyShortcuts) ? 1 : 0}:${Boolean(canRelaunch) ? 1 : 0}`;
|
||||
saveJson(leaseFilePath, {
|
||||
pid: process.pid,
|
||||
bundleVersion,
|
||||
@@ -1819,8 +1818,8 @@ export function createWindowBridgeController(options) {
|
||||
aliveCount: lastBridgeStatus.aliveCount,
|
||||
targets: lastBridgeStatus.targets,
|
||||
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
||||
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
||||
argvConfigured: mergedLauncherConfigured,
|
||||
launcherConfigured: mergedLauncherConfigured,
|
||||
hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts),
|
||||
canRelaunch: Boolean(canRelaunch),
|
||||
updatedAtMs: Date.now(),
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
$enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1'
|
||||
$updated = New-Object System.Collections.Generic.List[string]
|
||||
$configured = New-Object System.Collections.Generic.List[string]
|
||||
$readOnly = New-Object System.Collections.Generic.List[string]
|
||||
$discoveredDirs = New-Object System.Collections.Generic.List[string]
|
||||
$ws = $null
|
||||
$userDesktopDir = [Environment]::GetFolderPath('Desktop')
|
||||
$commonDesktopDir = [Environment]::GetFolderPath('CommonDesktopDirectory')
|
||||
$userProgramsDir = [Environment]::GetFolderPath('Programs')
|
||||
$commonProgramsDir = [Environment]::GetFolderPath('CommonPrograms')
|
||||
$userStartupDir = [Environment]::GetFolderPath('Startup')
|
||||
$zhDesktop = ([string][char]0x684C + [string][char]0x9762)
|
||||
|
||||
$flatSpecs = New-Object System.Collections.Generic.List[object]
|
||||
$seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir, [bool]$recordDiscovered) {
|
||||
if (-not $dirPath) { return }
|
||||
if (-not $seenScanDir.Add($dirPath)) { return }
|
||||
$exists = $false
|
||||
try { $exists = [bool](Test-Path -LiteralPath $dirPath -ErrorAction SilentlyContinue) } catch { $exists = $false }
|
||||
if (-not $exists) { return }
|
||||
$flatSpecs.Add(@{ Dir = $dirPath; IsCommon = $isCommon; Kind = $kind })
|
||||
if ($recordDiscovered) { $discoveredDirs.Add($dirPath) }
|
||||
if ($expandVendorSubdir) {
|
||||
try {
|
||||
foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -ErrorAction SilentlyContinue)) {
|
||||
if ($sub -and $sub.Name -and ($sub.Name -match '(?i)antigravity|^google(?:\b|[\s_-]|$)') -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) {
|
||||
$flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind })
|
||||
if ($recordDiscovered) { $discoveredDirs.Add([string]$sub.FullName) }
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
Add-ScanDir $userDesktopDir $false 'desktop' $false $true
|
||||
foreach ($d in @(
|
||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }),
|
||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' })
|
||||
)) {
|
||||
Add-ScanDir $d $false 'desktop' $false $false
|
||||
}
|
||||
foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) {
|
||||
if ($od) {
|
||||
Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false $false
|
||||
Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false $false
|
||||
}
|
||||
}
|
||||
Add-ScanDir $userProgramsDir $false 'programs' $true $true
|
||||
Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false $false
|
||||
Add-ScanDir $userStartupDir $false 'startup' $false $true
|
||||
if ($env:APPDATA) {
|
||||
Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar') $false 'taskbar' $false $false
|
||||
}
|
||||
Add-ScanDir $commonDesktopDir $true 'desktop' $false $true
|
||||
Add-ScanDir $commonProgramsDir $true 'programs' $true $true
|
||||
|
||||
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($spec in $flatSpecs) {
|
||||
$dir = [string]$spec.Dir
|
||||
$items = @()
|
||||
try {
|
||||
$items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue)
|
||||
} catch { continue }
|
||||
|
||||
foreach ($item in $items) {
|
||||
if ($item.Length -lt 32 -or $item.Length -gt 65536) { continue }
|
||||
$lnkPath = [string]$item.FullName
|
||||
if (-not $seen.Add($lnkPath)) { continue }
|
||||
try {
|
||||
$rawBytes = [System.IO.File]::ReadAllBytes($lnkPath)
|
||||
$u16 = [System.Text.Encoding]::Unicode.GetString($rawBytes)
|
||||
$lat = [System.Text.Encoding]::GetEncoding(28591).GetString($rawBytes)
|
||||
if ($u16.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0 -and
|
||||
$lat.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0) {
|
||||
continue
|
||||
}
|
||||
if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }
|
||||
$sc = $ws.CreateShortcut($lnkPath)
|
||||
$target = [string]$sc.TargetPath
|
||||
if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue }
|
||||
$curArgs = [string]$sc.Arguments
|
||||
if ($enableFlag) {
|
||||
if ($curArgs -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($lnkPath)
|
||||
continue
|
||||
}
|
||||
$nextArgs = ($curArgs.Trim() + ' --remote-debugging-port=0').Trim()
|
||||
try {
|
||||
$sc.Arguments = $nextArgs
|
||||
$sc.Save()
|
||||
$updated.Add($lnkPath)
|
||||
$configured.Add($lnkPath)
|
||||
} catch {
|
||||
$readOnly.Add($lnkPath)
|
||||
if ($spec.IsCommon -and $spec.Kind -eq 'programs' -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir -ErrorAction SilentlyContinue)) {
|
||||
$fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath))
|
||||
if (-not (Test-Path -LiteralPath $fallbackLnk -ErrorAction SilentlyContinue)) {
|
||||
try {
|
||||
$uSc = $ws.CreateShortcut($fallbackLnk)
|
||||
$uSc.TargetPath = $target
|
||||
$uSc.Arguments = $nextArgs
|
||||
if ($sc.WorkingDirectory) { $uSc.WorkingDirectory = $sc.WorkingDirectory }
|
||||
if ($sc.IconLocation) { $uSc.IconLocation = $sc.IconLocation }
|
||||
if ($sc.Description) { $uSc.Description = $sc.Description }
|
||||
$uSc.Save()
|
||||
$updated.Add($fallbackLnk)
|
||||
$configured.Add($fallbackLnk)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$stripped = ([regex]::Replace($curArgs, '(?:^|\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\s|$)', ' ')).Trim()
|
||||
if ($stripped -ne $curArgs.Trim()) {
|
||||
try {
|
||||
$sc.Arguments = $stripped
|
||||
$sc.Save()
|
||||
$updated.Add($lnkPath)
|
||||
} catch {
|
||||
$readOnly.Add($lnkPath)
|
||||
}
|
||||
}
|
||||
if ($stripped -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($lnkPath)
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
$runTargets = @(
|
||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; SubPath = 'Software\Microsoft\Windows\CurrentVersion\Run' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\Microsoft\Windows\CurrentVersion\Run' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run' }
|
||||
)
|
||||
foreach ($rt in $runTargets) {
|
||||
try {
|
||||
$runReadKey = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
||||
if (-not $runReadKey) { continue }
|
||||
$runNames = @($runReadKey.GetValueNames())
|
||||
$runReadKey.Close()
|
||||
foreach ($valName in $runNames) {
|
||||
$rk = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
||||
if (-not $rk) { continue }
|
||||
$rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rk.Close()
|
||||
if (-not $rawCmd) { continue }
|
||||
if ($rawCmd -notmatch '^\s*(?:"([^"]+)"|([^\s"]+))(.*)$') { continue }
|
||||
$exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restPart = [string]$Matches[3]
|
||||
if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue }
|
||||
$quotedExe = if ($Matches[1] -or $exeCandidate -match '\s') { '"' + $exeCandidate + '"' } else { $exeCandidate }
|
||||
$entryId = if ($rt.Label -eq 'HKLM') { "HKLM:Run:$($rt.SubPath)|$valName" } else { "HKCU:Run:$valName" }
|
||||
if ($enableFlag) {
|
||||
if ($restPart -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($entryId)
|
||||
continue
|
||||
}
|
||||
$nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim()
|
||||
$nextVal = "$quotedExe $nextRest"
|
||||
$saved = $false
|
||||
try {
|
||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
||||
if ($wk) {
|
||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wk.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($entryId)
|
||||
$configured.Add($entryId)
|
||||
} elseif ($rt.Label -eq 'HKLM') {
|
||||
$readOnly.Add($entryId)
|
||||
}
|
||||
} else {
|
||||
$strippedRest = ([regex]::Replace($restPart, '(?:^|\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\s|$)', ' ')).Trim()
|
||||
$nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe }
|
||||
if ($nextVal -ne $rawCmd.Trim()) {
|
||||
$saved = $false
|
||||
try {
|
||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
||||
if ($wk) {
|
||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wk.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($entryId)
|
||||
} elseif ($rt.Label -eq 'HKLM') {
|
||||
$readOnly.Add($entryId)
|
||||
}
|
||||
}
|
||||
if ($strippedRest -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($entryId)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
$exactClassSubKeys = @(
|
||||
'Software\Classes\antigravity\shell\open\command',
|
||||
'Software\Classes\Applications\Antigravity.exe\shell\open\command',
|
||||
'Software\Classes\AntigravitySourceFile\shell\open\command'
|
||||
)
|
||||
$classRoots = @(
|
||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; FullPrefix = 'HKEY_CURRENT_USER' },
|
||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; FullPrefix = 'HKEY_LOCAL_MACHINE' }
|
||||
)
|
||||
foreach ($cr in $classRoots) {
|
||||
foreach ($relSubKey in $exactClassSubKeys) {
|
||||
try {
|
||||
$rOpen = $cr.Root.OpenSubKey($relSubKey, $false)
|
||||
if (-not $rOpen) { continue }
|
||||
$rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
$rOpen.Close()
|
||||
if (-not $rawOpen) { continue }
|
||||
if ($rawOpen -notmatch '^\s*(?:"([^"]+)"|([^\s"]+))(.*)$') { continue }
|
||||
$exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||
$restOpen = ([string]$Matches[3]).Trim()
|
||||
if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue }
|
||||
$quotedOpenExe = if ($Matches[1] -or $exeCand -match '\s') { '"' + $exeCand + '"' } else { $exeCand }
|
||||
$fullKeyName = if ($cr.Label -eq 'HKLM') { "HKLM:Class:$relSubKey" } else { "$($cr.FullPrefix)\$relSubKey" }
|
||||
if ($enableFlag) {
|
||||
if ($restOpen -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($fullKeyName)
|
||||
continue
|
||||
}
|
||||
$nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" }
|
||||
$saved = $false
|
||||
try {
|
||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
||||
if ($wOpen) {
|
||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wOpen.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($fullKeyName)
|
||||
$configured.Add($fullKeyName)
|
||||
} elseif ($cr.Label -eq 'HKLM') {
|
||||
$readOnly.Add($fullKeyName)
|
||||
}
|
||||
} else {
|
||||
$strippedOpen = ([regex]::Replace($restOpen, '(?:^|\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\s|$)', ' ')).Trim()
|
||||
$nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe }
|
||||
if ($nextOpen -ne $rawOpen.Trim()) {
|
||||
$saved = $false
|
||||
try {
|
||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
||||
if ($wOpen) {
|
||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$wOpen.Close()
|
||||
$saved = $true
|
||||
}
|
||||
} catch {}
|
||||
if ($saved) {
|
||||
$updated.Add($fullKeyName)
|
||||
} elseif ($cr.Label -eq 'HKLM') {
|
||||
$readOnly.Add($fullKeyName)
|
||||
}
|
||||
}
|
||||
if ($strippedOpen -match '(?:^|\s)--remote-debugging-port(?:=|\s|$)') {
|
||||
$configured.Add($fullKeyName)
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
[pscustomobject]@{
|
||||
ok = $true
|
||||
updatedPaths = @($updated)
|
||||
configuredPaths = @($configured)
|
||||
readOnlyPaths = @($readOnly)
|
||||
discoveredDirs = @($discoveredDirs)
|
||||
} | ConvertTo-Json -Compress
|
||||
Reference in New Issue
Block a user