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:
+835
-555
File diff suppressed because it is too large
Load Diff
@@ -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 localTrajectoryCacheStore = createTrajectoryCacheStore({
|
||||
cacheFilePath: CACHE_FILE,
|
||||
loadJsonFn: loadJson,
|
||||
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
|
||||
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||
registerExitHook: true,
|
||||
});
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
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,292 +757,17 @@ 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) }
|
||||
function getWinShortcutProvisionPs() {
|
||||
if (!cachedWinShortcutProvisionPs) {
|
||||
cachedWinShortcutProvisionPs = readFileSync(
|
||||
join(HERE, 'backend', 'windows-shortcut-provision.ps1'),
|
||||
'utf8'
|
||||
).trim();
|
||||
}
|
||||
return cachedWinShortcutProvisionPs;
|
||||
}
|
||||
} 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
|
||||
`.trim();
|
||||
|
||||
const cachedDiscoveredWinDirsByHome = new Map();
|
||||
|
||||
@@ -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 {
|
||||
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 (!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 {
|
||||
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,6 +2337,20 @@ export function aggregateSessionUsageForFamily({
|
||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||
|
||||
const familyEntries = [];
|
||||
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();
|
||||
@@ -2355,6 +2363,7 @@ export function aggregateSessionUsageForFamily({
|
||||
isCurrentConv: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return computeFamilySessionBuckets({
|
||||
entries: familyEntries,
|
||||
|
||||
@@ -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
|
||||
@@ -31,10 +31,12 @@ import {
|
||||
summarizeTtft,
|
||||
} from './trajectory-metrics.mjs';
|
||||
import {
|
||||
readLocalSqliteLiveTail,
|
||||
readLocalSqliteParentLink,
|
||||
readLocalSqliteTrajectory,
|
||||
readLocalSummaryIndex,
|
||||
} from './backend/cli-sqlite-reader.mjs';
|
||||
import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
||||
import { computeSqliteWalSig, withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
||||
import {
|
||||
buildCliJsonStatusOutput,
|
||||
ensureCliStatusLineConfigured,
|
||||
@@ -44,14 +46,17 @@ import {
|
||||
import {
|
||||
CLI_STATUS_SNAPSHOT_FILE,
|
||||
CLI_STATUSLINE_PRESETS,
|
||||
DATA_DIR,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
loadJson,
|
||||
loadSettings,
|
||||
normalizeCliStatusLineSlots,
|
||||
resolveEffectiveCliStatusLineSlots,
|
||||
saveJson,
|
||||
} from './backend/config.mjs';
|
||||
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
||||
import { isThirdPartyPoolText } from './shared/telemetry-display-rules.mjs';
|
||||
import { normalizePathForWorkspaceMatch } from './shared/workspace-uri.mjs';
|
||||
|
||||
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
||||
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
||||
@@ -124,12 +129,7 @@ function readStdinJsonWithTimeout(timeoutMs = 220) {
|
||||
}
|
||||
|
||||
function normalizePathForMatch(rawPath) {
|
||||
const clean = String(rawPath || '')
|
||||
.trim()
|
||||
.replace(/^file:\/\/\/?/i, '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/+$/, '');
|
||||
return process.platform === 'win32' ? clean.toLowerCase() : clean;
|
||||
return normalizePathForWorkspaceMatch(rawPath);
|
||||
}
|
||||
|
||||
function extractConversationIdFromStdin(stdinData) {
|
||||
@@ -282,11 +282,133 @@ export function resolveCliLocalSessionMetrics({
|
||||
};
|
||||
}
|
||||
|
||||
let traj = readLocalSqliteTrajectory(dbPath);
|
||||
const parentLink = readLocalSqliteParentLink(dbPath);
|
||||
if (parentLink?.parentConversationId || parentLink?.rootConversationId) {
|
||||
const candidateRootId = parentLink.rootConversationId || parentLink.parentConversationId;
|
||||
const rootDb = join(convDir, `${candidateRootId}.db`);
|
||||
if (candidateRootId && existsSync(rootDb)) {
|
||||
targetCid = candidateRootId;
|
||||
dbPath = rootDb;
|
||||
}
|
||||
}
|
||||
|
||||
const walInfo = computeSqliteWalSig(dbPath);
|
||||
const dbMtimeMs = walInfo.mtimeMs || 0;
|
||||
const targetLower = String(targetCid || '').toLowerCase();
|
||||
const targetIsRunning = freshRunningRootIds.includes(targetLower);
|
||||
|
||||
const cliTrajMemoFile = join(DATA_DIR, 'cli-statusline-traj-memo.json');
|
||||
const prevMemo = walInfo.sig ? loadJson(cliTrajMemoFile, null) : null;
|
||||
const prevOtherCache =
|
||||
prevMemo && typeof prevMemo.otherWaiting === 'object' && prevMemo.otherWaiting !== null
|
||||
? prevMemo.otherWaiting
|
||||
: {};
|
||||
const nextOtherCache = {};
|
||||
let memoDirty = false;
|
||||
|
||||
let otherLocalWaiting = false;
|
||||
let checkedOthers = 0;
|
||||
for (const runCid of freshRunningRootIds) {
|
||||
if (!runCid || runCid === targetLower) continue;
|
||||
if (checkedOthers >= 3) break;
|
||||
const otherDb = join(convDir, `${runCid}.db`);
|
||||
const otherWal = computeSqliteWalSig(otherDb);
|
||||
if (!otherWal.exists) continue;
|
||||
checkedOthers += 1;
|
||||
const prevOther = prevOtherCache[otherDb];
|
||||
if (prevOther && prevOther.sig === otherWal.sig && typeof prevOther.waiting === 'boolean') {
|
||||
nextOtherCache[otherDb] = prevOther;
|
||||
if (prevOther.waiting) {
|
||||
otherLocalWaiting = true;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const otherTail = readLocalSqliteLiveTail(otherDb, 16);
|
||||
let isWaiting = false;
|
||||
if (otherTail && Array.isArray(otherTail.steps) && otherTail.steps.length > 0) {
|
||||
const otherAct = extractLiveActivity(otherTail.steps, true);
|
||||
isWaiting = Boolean(otherAct?.phase === 'waiting' || otherAct?.waitingApproval);
|
||||
}
|
||||
nextOtherCache[otherDb] = { sig: otherWal.sig, waiting: isWaiting };
|
||||
memoDirty = true;
|
||||
if (isWaiting) {
|
||||
otherLocalWaiting = true;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// 忽略单会话读取异常
|
||||
}
|
||||
}
|
||||
|
||||
const targetMemoKey = walInfo.sig ? `v1::${dbPath}::${walInfo.sig}` : '';
|
||||
if (
|
||||
targetMemoKey &&
|
||||
prevMemo?.targetKey === targetMemoKey &&
|
||||
prevMemo?.metrics &&
|
||||
typeof prevMemo.metrics === 'object'
|
||||
) {
|
||||
if (memoDirty) {
|
||||
saveJson(cliTrajMemoFile, {
|
||||
targetKey: targetMemoKey,
|
||||
metrics: prevMemo.metrics,
|
||||
otherWaiting: { ...prevOtherCache, ...nextOtherCache },
|
||||
});
|
||||
}
|
||||
const m = prevMemo.metrics;
|
||||
if (!m.found) {
|
||||
return {
|
||||
found: false,
|
||||
cascadeId: targetCid,
|
||||
dbMtimeMs,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
targetIsRunning,
|
||||
targetIsWaiting: Boolean(m.targetIsWaiting),
|
||||
targetWaitingApprovalFresh: Boolean(
|
||||
m.waitingApproval && dbMtimeMs > 0 && nowMs - dbMtimeMs <= CLI_RUNNING_STALE_MS
|
||||
),
|
||||
otherLocalWaiting,
|
||||
};
|
||||
}
|
||||
return {
|
||||
found: true,
|
||||
cascadeId: targetCid,
|
||||
dbMtimeMs,
|
||||
stepCount: m.stepCount,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
targetIsRunning,
|
||||
targetIsWaiting: Boolean(m.targetIsWaiting),
|
||||
targetWaitingApprovalFresh: Boolean(
|
||||
m.waitingApproval && dbMtimeMs > 0 && nowMs - dbMtimeMs <= CLI_RUNNING_STALE_MS
|
||||
),
|
||||
otherLocalWaiting,
|
||||
tps: m.tps,
|
||||
avgTps: m.avgTps,
|
||||
ttft: m.ttft,
|
||||
stepCost: m.stepCost,
|
||||
sessionCost: m.sessionCost,
|
||||
cacheHitPct: m.cacheHitPct,
|
||||
latestPromptTokens: m.latestPromptTokens,
|
||||
sessionTokens: m.sessionTokens,
|
||||
latestAnomaly: m.latestAnomaly,
|
||||
sessionAnomalyCount: m.sessionAnomalyCount,
|
||||
latestModelHint: m.latestModelHint,
|
||||
hasReportedLimit: m.hasReportedLimit,
|
||||
usedPct: m.usedPct,
|
||||
};
|
||||
}
|
||||
|
||||
let traj = readLocalSqliteTrajectory(dbPath, {
|
||||
cascadeId: targetCid,
|
||||
isRunning: targetIsRunning,
|
||||
});
|
||||
if (traj?.parentConversationId) {
|
||||
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
|
||||
if (existsSync(rootDb)) {
|
||||
const rootTraj = readLocalSqliteTrajectory(rootDb);
|
||||
if (rootDb !== dbPath && existsSync(rootDb)) {
|
||||
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
|
||||
if (rootTraj) {
|
||||
targetCid = traj.rootConversationId || traj.parentConversationId;
|
||||
dbPath = rootDb;
|
||||
@@ -295,22 +417,14 @@ export function resolveCliLocalSessionMetrics({
|
||||
}
|
||||
}
|
||||
|
||||
let dbMtimeMs = 0;
|
||||
try {
|
||||
dbMtimeMs = Math.max(dbMtimeMs, statSync(dbPath).mtimeMs || 0);
|
||||
} catch {
|
||||
// 忽略 stat 异常
|
||||
}
|
||||
try {
|
||||
const walPath = `${dbPath}-wal`;
|
||||
if (existsSync(walPath)) {
|
||||
dbMtimeMs = Math.max(dbMtimeMs, statSync(walPath).mtimeMs || 0);
|
||||
}
|
||||
} catch {
|
||||
// 忽略 WAL stat 异常
|
||||
}
|
||||
|
||||
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
|
||||
if (targetMemoKey) {
|
||||
saveJson(cliTrajMemoFile, {
|
||||
targetKey: targetMemoKey,
|
||||
metrics: { found: false, targetIsWaiting: false, waitingApproval: false },
|
||||
otherWaiting: { ...prevOtherCache, ...nextOtherCache },
|
||||
});
|
||||
}
|
||||
return {
|
||||
found: false,
|
||||
cascadeId: targetCid,
|
||||
@@ -320,46 +434,30 @@ export function resolveCliLocalSessionMetrics({
|
||||
targetIsRunning: freshRunningRootIds.includes(String(targetCid || '').toLowerCase()),
|
||||
targetIsWaiting: false,
|
||||
targetWaitingApprovalFresh: false,
|
||||
otherLocalWaiting: false,
|
||||
otherLocalWaiting,
|
||||
};
|
||||
}
|
||||
|
||||
const targetLower = String(targetCid || '').toLowerCase();
|
||||
const targetIsRunning = freshRunningRootIds.includes(targetLower);
|
||||
const targetLiveAct = extractLiveActivity(traj.steps, true);
|
||||
const targetIsWaiting = Boolean(
|
||||
targetLiveAct?.phase === 'waiting' || targetLiveAct?.waitingApproval
|
||||
);
|
||||
const waitingApproval = Boolean(targetLiveAct?.waitingApproval);
|
||||
const targetWaitingApprovalFresh = Boolean(
|
||||
targetLiveAct?.waitingApproval &&
|
||||
waitingApproval &&
|
||||
dbMtimeMs > 0 &&
|
||||
nowMs - dbMtimeMs <= CLI_RUNNING_STALE_MS
|
||||
);
|
||||
|
||||
let otherLocalWaiting = false;
|
||||
let checkedOthers = 0;
|
||||
for (const runCid of freshRunningRootIds) {
|
||||
if (!runCid || runCid === targetLower) continue;
|
||||
if (checkedOthers >= 3) break;
|
||||
const otherDb = join(convDir, `${runCid}.db`);
|
||||
if (!existsSync(otherDb)) continue;
|
||||
checkedOthers += 1;
|
||||
try {
|
||||
const otherTraj = readLocalSqliteTrajectory(otherDb);
|
||||
if (otherTraj && Array.isArray(otherTraj.steps) && otherTraj.steps.length > 0) {
|
||||
const otherAct = extractLiveActivity(otherTraj.steps, true);
|
||||
if (otherAct?.phase === 'waiting' || otherAct?.waitingApproval) {
|
||||
otherLocalWaiting = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略单会话读取异常
|
||||
}
|
||||
}
|
||||
|
||||
const steps = extractModelSteps(traj.steps, traj.generatorMetadata || []);
|
||||
if (steps.length === 0) {
|
||||
if (targetMemoKey) {
|
||||
saveJson(cliTrajMemoFile, {
|
||||
targetKey: targetMemoKey,
|
||||
metrics: { found: false, targetIsWaiting, waitingApproval },
|
||||
otherWaiting: { ...prevOtherCache, ...nextOtherCache },
|
||||
});
|
||||
}
|
||||
return {
|
||||
found: false,
|
||||
cascadeId: targetCid,
|
||||
@@ -467,17 +565,15 @@ export function resolveCliLocalSessionMetrics({
|
||||
const sessionCacheHitPct =
|
||||
totalPromptAll > 0 ? +((totalCacheReadTokens / totalPromptAll) * 100).toFixed(1) : null;
|
||||
|
||||
return {
|
||||
const resolvedUsedPct =
|
||||
latestLimitTokens > 0 && latestContextTokens > 0
|
||||
? Math.min(100, +((latestContextTokens / latestLimitTokens) * 100).toFixed(1))
|
||||
: null;
|
||||
const computedMetrics = {
|
||||
found: true,
|
||||
cascadeId: targetCid,
|
||||
dbMtimeMs,
|
||||
stepCount: steps.length,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
targetIsRunning,
|
||||
targetIsWaiting,
|
||||
targetWaitingApprovalFresh,
|
||||
otherLocalWaiting,
|
||||
waitingApproval,
|
||||
tps: latestTps,
|
||||
avgTps: speedSum?.avgTokPerSec != null ? +speedSum.avgTokPerSec.toFixed(1) : null,
|
||||
ttft: latestTtft ?? ttftSum?.avgSec ?? null,
|
||||
@@ -490,10 +586,40 @@ export function resolveCliLocalSessionMetrics({
|
||||
sessionAnomalyCount,
|
||||
latestModelHint,
|
||||
hasReportedLimit,
|
||||
usedPct:
|
||||
latestLimitTokens > 0 && latestContextTokens > 0
|
||||
? Math.min(100, +((latestContextTokens / latestLimitTokens) * 100).toFixed(1))
|
||||
: null,
|
||||
usedPct: resolvedUsedPct,
|
||||
};
|
||||
if (targetMemoKey) {
|
||||
saveJson(cliTrajMemoFile, {
|
||||
targetKey: targetMemoKey,
|
||||
metrics: computedMetrics,
|
||||
otherWaiting: { ...prevOtherCache, ...nextOtherCache },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
found: true,
|
||||
cascadeId: targetCid,
|
||||
dbMtimeMs,
|
||||
stepCount: computedMetrics.stepCount,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
targetIsRunning,
|
||||
targetIsWaiting,
|
||||
targetWaitingApprovalFresh,
|
||||
otherLocalWaiting,
|
||||
tps: computedMetrics.tps,
|
||||
avgTps: computedMetrics.avgTps,
|
||||
ttft: computedMetrics.ttft,
|
||||
stepCost: computedMetrics.stepCost,
|
||||
sessionCost: computedMetrics.sessionCost,
|
||||
cacheHitPct: computedMetrics.cacheHitPct,
|
||||
latestPromptTokens: computedMetrics.latestPromptTokens,
|
||||
sessionTokens: computedMetrics.sessionTokens,
|
||||
latestAnomaly: computedMetrics.latestAnomaly,
|
||||
sessionAnomalyCount: computedMetrics.sessionAnomalyCount,
|
||||
latestModelHint: computedMetrics.latestModelHint,
|
||||
hasReportedLimit: computedMetrics.hasReportedLimit,
|
||||
usedPct: computedMetrics.usedPct,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795356783419">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795400571874">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795356783419"></script>
|
||||
<script src="/app.js?v=1795400571874"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -26,6 +26,8 @@ const REGEX_PRECEDING_KEYWORDS = new Set([
|
||||
'await',
|
||||
]);
|
||||
|
||||
const REGEX_AFTER_PAREN_KEYWORDS = new Set(['if', 'while', 'for', 'with']);
|
||||
|
||||
function isIdentStart(ch) {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
@@ -167,6 +169,24 @@ function scanExportClauseEnd(source, afterExportIdx, onImport, onExport) {
|
||||
}
|
||||
}
|
||||
|
||||
function emitBraceExports() {
|
||||
if (!braceBody || !onExport) return;
|
||||
const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ');
|
||||
for (const part of cleaned.split(',')) {
|
||||
const tok = part.trim();
|
||||
if (!tok) continue;
|
||||
const asMatch =
|
||||
/^([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)\s+as\s+([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)$/u.exec(
|
||||
tok
|
||||
);
|
||||
if (asMatch) {
|
||||
onExport(asMatch[2], true, asMatch[1]);
|
||||
} else {
|
||||
onExport(tok, true, tok);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const peekFrom = skipSpacesAndComments(source, idx);
|
||||
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
||||
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
||||
@@ -174,20 +194,25 @@ function scanExportClauseEnd(source, afterExportIdx, onImport, onExport) {
|
||||
const specEnd = skipSimpleString(source, specIdx);
|
||||
const specifier = source.slice(specIdx + 1, specEnd - 1);
|
||||
onImport?.(specifier, braceBody ? `{ ${braceBody} } from` : '');
|
||||
if (braceBody) {
|
||||
const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ');
|
||||
for (const part of cleaned.split(',')) {
|
||||
const tok = part.trim();
|
||||
if (!tok) continue;
|
||||
const asMatch =
|
||||
/^([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)\s+as\s+([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)$/u.exec(
|
||||
tok
|
||||
);
|
||||
const exportedName = asMatch ? asMatch[2] : tok;
|
||||
onExport?.(exportedName, true, exportedName);
|
||||
}
|
||||
}
|
||||
idx = specEnd;
|
||||
return consumeTrailingStatementEnd(source, idx);
|
||||
}
|
||||
}
|
||||
|
||||
if (braceBody && onExport) {
|
||||
const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ');
|
||||
for (const part of cleaned.split(',')) {
|
||||
const tok = part.trim();
|
||||
if (!tok) continue;
|
||||
const asMatch = /^([$_\w]+)\s+as\s+([$_\w]+)$/.exec(tok);
|
||||
onExport(asMatch ? asMatch[2] : tok, true);
|
||||
}
|
||||
}
|
||||
emitBraceExports();
|
||||
return consumeTrailingStatementEnd(source, idx);
|
||||
}
|
||||
|
||||
@@ -227,9 +252,11 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
let i = 0;
|
||||
let braceDepth = 0;
|
||||
let parenDepth = 0;
|
||||
const parenAllowsRegexStack = [];
|
||||
const tplBraceStack = [];
|
||||
let canStartRegex = true;
|
||||
let prevNonWsChar = '';
|
||||
let pendingRegexParenKeyword = '';
|
||||
|
||||
function scanTemplateChunk(startAfterBacktickOrBrace) {
|
||||
let idx = startAfterBacktickOrBrace;
|
||||
@@ -294,6 +321,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
out += source.slice(i, end);
|
||||
canStartRegex = false;
|
||||
prevNonWsChar = ch;
|
||||
pendingRegexParenKeyword = '';
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
@@ -301,6 +329,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
// Template literal start
|
||||
if (ch === '`') {
|
||||
out += '`';
|
||||
pendingRegexParenKeyword = '';
|
||||
i = scanTemplateChunk(i + 1);
|
||||
continue;
|
||||
}
|
||||
@@ -329,6 +358,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
out += source.slice(i, end);
|
||||
canStartRegex = false;
|
||||
prevNonWsChar = '/';
|
||||
pendingRegexParenKeyword = '';
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
@@ -339,11 +369,13 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
out += ch;
|
||||
canStartRegex = true;
|
||||
prevNonWsChar = ch;
|
||||
pendingRegexParenKeyword = '';
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '}') {
|
||||
pendingRegexParenKeyword = '';
|
||||
if (tplBraceStack.length > 0 && braceDepth === tplBraceStack[tplBraceStack.length - 1] + 1) {
|
||||
braceDepth -= 1;
|
||||
tplBraceStack.pop();
|
||||
@@ -361,6 +393,8 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
|
||||
if (ch === '(') {
|
||||
parenDepth += 1;
|
||||
parenAllowsRegexStack.push(Boolean(pendingRegexParenKeyword));
|
||||
pendingRegexParenKeyword = '';
|
||||
out += ch;
|
||||
canStartRegex = true;
|
||||
prevNonWsChar = ch;
|
||||
@@ -370,8 +404,10 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
|
||||
if (ch === ')') {
|
||||
parenDepth = Math.max(0, parenDepth - 1);
|
||||
const allowsRegexAfterParen = parenAllowsRegexStack.pop() ?? false;
|
||||
pendingRegexParenKeyword = '';
|
||||
out += ch;
|
||||
canStartRegex = false;
|
||||
canStartRegex = allowsRegexAfterParen;
|
||||
prevNonWsChar = ch;
|
||||
i += 1;
|
||||
continue;
|
||||
@@ -397,6 +433,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
i = scanImportDeclarationEnd(source, afterImport, onImport);
|
||||
canStartRegex = true;
|
||||
prevNonWsChar = ';';
|
||||
pendingRegexParenKeyword = '';
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -408,6 +445,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
i = scanExportClauseEnd(source, afterExport, onImport, onExport);
|
||||
canStartRegex = true;
|
||||
prevNonWsChar = ';';
|
||||
pendingRegexParenKeyword = '';
|
||||
continue;
|
||||
}
|
||||
// `export default ...`
|
||||
@@ -421,12 +459,14 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
recordExportedDeclarationIdent(source, afterDefault, onExport);
|
||||
i = afterDefault;
|
||||
canStartRegex = false;
|
||||
pendingRegexParenKeyword = '';
|
||||
continue;
|
||||
}
|
||||
out += 'void ';
|
||||
i = afterDefault;
|
||||
canStartRegex = true;
|
||||
prevNonWsChar = 'd';
|
||||
pendingRegexParenKeyword = '';
|
||||
continue;
|
||||
}
|
||||
// `export const|let|var|function|class|async ...`
|
||||
@@ -441,10 +481,18 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
recordExportedDeclarationIdent(source, afterExport, onExport);
|
||||
i = afterExport;
|
||||
canStartRegex = false;
|
||||
pendingRegexParenKeyword = '';
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (prevNonWsChar !== '.' && REGEX_AFTER_PAREN_KEYWORDS.has(word)) {
|
||||
pendingRegexParenKeyword = word;
|
||||
} else if (pendingRegexParenKeyword === 'for' && word === 'await') {
|
||||
pendingRegexParenKeyword = 'for_await';
|
||||
} else {
|
||||
pendingRegexParenKeyword = '';
|
||||
}
|
||||
out += word;
|
||||
canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word);
|
||||
prevNonWsChar = word[word.length - 1];
|
||||
@@ -453,6 +501,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
}
|
||||
|
||||
// Numbers & other punctuation
|
||||
pendingRegexParenKeyword = '';
|
||||
out += ch;
|
||||
if (/[0-9\]`]/.test(ch)) {
|
||||
canStartRegex = false;
|
||||
@@ -468,19 +517,43 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
||||
return out;
|
||||
}
|
||||
|
||||
function validateBundleImport(sourcePath, specifier, clause, bundledPaths, moduleImportedNames) {
|
||||
function validateBundleImport(
|
||||
sourcePath,
|
||||
specifier,
|
||||
clause,
|
||||
bundledPaths,
|
||||
moduleImportedNames,
|
||||
moduleImportAliases,
|
||||
outerExportedSymbols
|
||||
) {
|
||||
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
|
||||
if (binding) {
|
||||
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
||||
const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
||||
const aliasPattern =
|
||||
/^([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)\s+as\s+([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)$/u;
|
||||
if (!named) {
|
||||
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||
throw new Error(`${sourcePath}: only named imports are supported in app.js`);
|
||||
}
|
||||
for (const rawItem of named[1].split(',')) {
|
||||
const name = rawItem.trim();
|
||||
if (!name) continue;
|
||||
const asMatch = aliasPattern.exec(name);
|
||||
if (asMatch) {
|
||||
const [, importedName, localName] = asMatch;
|
||||
if (outerExportedSymbols && !outerExportedSymbols.has(importedName)) {
|
||||
throw new Error(
|
||||
`${sourcePath}: imported symbol '${importedName}' is not exported by an earlier module in jsOrder`
|
||||
);
|
||||
}
|
||||
moduleImportedNames?.add(localName);
|
||||
if (localName !== importedName) {
|
||||
moduleImportAliases?.set(localName, importedName);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!identifier.test(name)) {
|
||||
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||
throw new Error(`${sourcePath}: unsupported import binding '${name}' in app.js`);
|
||||
}
|
||||
moduleImportedNames?.add(name);
|
||||
}
|
||||
@@ -538,12 +611,14 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/core/fileExportClient.js',
|
||||
'src/store/telemetryStore.js',
|
||||
'src/components/ui/TopLongPillNav.js',
|
||||
'src/components/ui/SearchInput.js',
|
||||
'src/components/ui/CustomSelect.js',
|
||||
'src/components/ui/ActionMenu.js',
|
||||
'src/components/ui/CustomNumberInput.js',
|
||||
'src/components/ui/CustomDateTimePicker.js',
|
||||
'src/components/ui/CustomScrollbar.js',
|
||||
'src/components/ui/SegmentedControl.js',
|
||||
'src/components/ui/ToggleSwitch.js',
|
||||
'src/components/ui/ContextSegmentMeter.js',
|
||||
'src/components/ui/FourSegmentBar.js',
|
||||
'src/components/ui/ConsumptionTooltipContent.js',
|
||||
@@ -585,28 +660,50 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
|
||||
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
||||
const moduleImportedNames = new Set();
|
||||
const moduleLocalExports = new Set();
|
||||
const moduleImportAliases = new Map();
|
||||
const moduleLocalExports = new Map();
|
||||
const stripped = stripModuleSyntax(
|
||||
raw,
|
||||
(specifier, clause) =>
|
||||
validateBundleImport(path, specifier, clause, bundledPaths, moduleImportedNames),
|
||||
(name, isClauseExport) => {
|
||||
if (isClauseExport && moduleImportedNames.has(name) && outerExportedSymbols.has(name)) {
|
||||
validateBundleImport(
|
||||
path,
|
||||
specifier,
|
||||
clause,
|
||||
bundledPaths,
|
||||
moduleImportedNames,
|
||||
moduleImportAliases,
|
||||
outerExportedSymbols
|
||||
),
|
||||
(name, isClauseExport, localName = name) => {
|
||||
if (
|
||||
isClauseExport &&
|
||||
localName === name &&
|
||||
moduleImportedNames.has(name) &&
|
||||
outerExportedSymbols.has(name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
moduleLocalExports.add(name);
|
||||
moduleLocalExports.set(name, localName);
|
||||
}
|
||||
);
|
||||
bundledPaths.add(path);
|
||||
const exportList = [...moduleLocalExports];
|
||||
for (const sym of exportList) {
|
||||
const exportEntries = [...moduleLocalExports.entries()];
|
||||
for (const [sym] of exportEntries) {
|
||||
outerExportedSymbols.add(sym);
|
||||
}
|
||||
const body = stripped.trim();
|
||||
const aliasLines = [...moduleImportAliases.entries()].map(
|
||||
([localName, importedName]) => `const ${localName} = ${importedName};`
|
||||
);
|
||||
const bodyWithAliases =
|
||||
aliasLines.length > 0 ? `${aliasLines.join('\n')}\n${stripped.trim()}` : stripped.trim();
|
||||
const outerDestructure = exportEntries.map(([exported]) => exported).join(', ');
|
||||
const innerReturnFields = exportEntries
|
||||
.map(([exported, local]) => (exported === local ? exported : `${exported}: ${local}`))
|
||||
.join(', ');
|
||||
const wrapped =
|
||||
exportList.length > 0
|
||||
? `const { ${exportList.join(', ')} } = (() => {\n${body}\nreturn { ${exportList.join(', ')} };\n})();`
|
||||
: `(() => {\n${body}\n})();`;
|
||||
exportEntries.length > 0
|
||||
? `const { ${outerDestructure} } = (() => {\n${bodyWithAliases}\nreturn { ${innerReturnFields} };\n})();`
|
||||
: `(() => {\n${bodyWithAliases}\n})();`;
|
||||
return `// --- ${rel} ---\n${wrapped}`;
|
||||
})
|
||||
.join('\n\n');
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* @fileoverview Shared user prompt wrapper-tag stripping and short session title extraction.
|
||||
*/
|
||||
|
||||
const PROMPT_CLEAN_CONTEXT_SUMMARY_RE = /<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi;
|
||||
const PROMPT_CLEAN_SYSTEM_MSG_RE = /<SYSTEM_MESSAGE>[\s\S]*$/i;
|
||||
const PROMPT_CLEAN_METADATA_RE = /<ADDITIONAL_METADATA>[\s\S]*$/i;
|
||||
const PROMPT_CLEAN_USER_REQ_RE = /<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi;
|
||||
|
||||
/**
|
||||
* Strips `<CONTEXT_SUMMARY>`, `<SYSTEM_MESSAGE>`, and `<ADDITIONAL_METADATA>` wrapper blocks
|
||||
* and returns the innermost `<USER_REQUEST>` body when present.
|
||||
*
|
||||
* @param {unknown} rawText
|
||||
* @returns {string}
|
||||
*/
|
||||
export function extractCleanUserRequestBody(rawText) {
|
||||
if (typeof rawText !== 'string' || !rawText.trim()) return '';
|
||||
const withoutSummary = rawText
|
||||
.replace(PROMPT_CLEAN_CONTEXT_SUMMARY_RE, '')
|
||||
.replace(PROMPT_CLEAN_SYSTEM_MSG_RE, '');
|
||||
const reqMatches = [...withoutSummary.matchAll(PROMPT_CLEAN_USER_REQ_RE)];
|
||||
const target =
|
||||
reqMatches.length > 0
|
||||
? reqMatches[reqMatches.length - 1][1]
|
||||
: withoutSummary.replace(PROMPT_CLEAN_METADATA_RE, '');
|
||||
return String(target || '').replace(PROMPT_CLEAN_METADATA_RE, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a compact single-line title from raw user prompt text.
|
||||
*
|
||||
* @param {unknown} rawText
|
||||
* @param {number} [maxChars=80]
|
||||
* @param {{ firstLineOnly?: boolean }} [options={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function extractShortPromptTitle(rawText, maxChars = 80, { firstLineOnly = false } = {}) {
|
||||
const body = extractCleanUserRequestBody(rawText);
|
||||
if (!body) return '';
|
||||
const candidate = firstLineOnly
|
||||
? body
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.replace(/\s+/g, ' ').trim())
|
||||
.find(Boolean) || ''
|
||||
: body.replace(/\s+/g, ' ').trim();
|
||||
if (!candidate) return '';
|
||||
return candidate.length <= maxChars ? candidate : `${candidate.slice(0, maxChars - 1).trimEnd()}…`;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* @fileoverview Shared `file://` workspace URI decoding, encoding, and SQLite column parsing helpers.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parses a SQLite `workspace_uris` column value (either a JSON string array or a single URI string).
|
||||
*
|
||||
* @param {unknown} rawVal
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function parseWorkspaceUrisColumn(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 {
|
||||
// Fall back to single URI string
|
||||
}
|
||||
}
|
||||
return [str];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a `file://` URI or raw filesystem path into a clean slash-normalized path string.
|
||||
* Strips the leading slash before Windows drive letters (`/F:/...` -> `F:/...`) while keeping POSIX leading `/`.
|
||||
*
|
||||
* @param {unknown} rawUri
|
||||
* @returns {string}
|
||||
*/
|
||||
export function decodeWorkspaceFileUriToPath(rawUri) {
|
||||
const raw = String(rawUri || '').trim();
|
||||
if (!raw) return '';
|
||||
let decoded = raw;
|
||||
if (/^file:\/\//i.test(decoded)) {
|
||||
decoded = decoded.replace(/^file:\/\//i, '');
|
||||
try {
|
||||
decoded = decodeURIComponent(decoded);
|
||||
} catch {
|
||||
decoded = decoded.replace(/%3A/gi, ':');
|
||||
}
|
||||
if (/^\/[A-Za-z]:/.test(decoded)) {
|
||||
decoded = decoded.slice(1);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
decoded = decodeURIComponent(decoded);
|
||||
} catch {
|
||||
// Keep original text when percent sequences are literal path chars
|
||||
}
|
||||
}
|
||||
return decoded.replace(/\\/g, '/').replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a workspace URI or local path for cross-platform equality comparison.
|
||||
*
|
||||
* @param {unknown} rawPath
|
||||
* @param {string} [platform=process.platform]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizePathForWorkspaceMatch(rawPath, platform = process.platform) {
|
||||
const clean = decodeWorkspaceFileUriToPath(rawPath).replace(/^\/+(?=[A-Za-z]:)/, '');
|
||||
return platform === 'win32' ? clean.toLowerCase() : clean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a `file://` URI or local path into a clean unencoded `file://` URI (`ag-cli` style).
|
||||
*
|
||||
* @param {unknown} rawInput
|
||||
* @returns {string}
|
||||
*/
|
||||
export function toRawWorkspaceFileUri(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(/^\/+/, '');
|
||||
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}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a `file://` URI or local path into Antigravity Desktop encoded URI form
|
||||
* (lowercase Windows drive letter + `%3A`).
|
||||
*
|
||||
* @param {unknown} rawInput
|
||||
* @returns {string}
|
||||
*/
|
||||
export function toDesktopEncodedWorkspaceUri(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 = toRawWorkspaceFileUri(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}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a short project name and readable display path from a `file:///` URI.
|
||||
*
|
||||
* @param {unknown} rawUri
|
||||
* @returns {{ name: string, displayPath: string }}
|
||||
*/
|
||||
export function parseWorkspaceDisplayLabel(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 };
|
||||
}
|
||||
@@ -823,7 +823,14 @@ export function createSessionLineChart() {
|
||||
let hoveredIdx = -1;
|
||||
let tickElsByIdx = new Map();
|
||||
let lastSig = '';
|
||||
let lastPreSig = '';
|
||||
let lastSummaryBadge = '';
|
||||
let lastUpdateParams = null;
|
||||
let cachedPlotSvgRect = null;
|
||||
|
||||
function invalidatePlotSvgRect() {
|
||||
cachedPlotSvgRect = null;
|
||||
}
|
||||
|
||||
function syncViewWidth() {
|
||||
const measured = Math.round(
|
||||
@@ -936,8 +943,14 @@ export function createSessionLineChart() {
|
||||
|
||||
plotStage.addEventListener('mousemove', (e) => {
|
||||
if (!currentPoints.length) return;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
if (!cachedPlotSvgRect) {
|
||||
cachedPlotSvgRect = svg.getBoundingClientRect();
|
||||
}
|
||||
const rect = cachedPlotSvgRect;
|
||||
if (!rect || rect.width <= 0) {
|
||||
cachedPlotSvgRect = null;
|
||||
return;
|
||||
}
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
@@ -947,14 +960,19 @@ export function createSessionLineChart() {
|
||||
);
|
||||
showHoverAt(idx);
|
||||
});
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
plotStage.addEventListener('mouseleave', () => {
|
||||
invalidatePlotSvgRect();
|
||||
clearHover();
|
||||
});
|
||||
|
||||
let resizeObs = null;
|
||||
let onWinResize = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
invalidatePlotSvgRect();
|
||||
if (syncViewWidth() && lastUpdateParams) {
|
||||
lastSig = '';
|
||||
lastPreSig = '';
|
||||
update(lastUpdateParams);
|
||||
}
|
||||
});
|
||||
@@ -1035,6 +1053,9 @@ export function createSessionLineChart() {
|
||||
if (!matchedSteps.length) {
|
||||
currentPoints = [];
|
||||
lastSig = 'empty';
|
||||
lastPreSig = '';
|
||||
lastSummaryBadge = t('chart.step.zeroSteps');
|
||||
invalidatePlotSvgRect();
|
||||
patchAttr(areaPath, 'd', '');
|
||||
patchAttr(linePath, 'd', '');
|
||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||
@@ -1046,7 +1067,23 @@ export function createSessionLineChart() {
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchAttr(emptyHintEl, 'hidden', false);
|
||||
clearHover();
|
||||
return { summaryBadge: t('chart.step.zeroSteps') };
|
||||
return { summaryBadge: lastSummaryBadge };
|
||||
}
|
||||
|
||||
const locale = getEffectiveLocale();
|
||||
const extColorSig = modelColorByGroup
|
||||
? Array.from(modelColorByGroup.entries())
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',')
|
||||
: '';
|
||||
let preStepParts = `${matchedSteps.length}:`;
|
||||
for (let i = 0; i < matchedSteps.length; i += 1) {
|
||||
const s = matchedSteps[i];
|
||||
preStepParts += `${s.stepIndex ?? i},${s.agentIndex ?? 0},${s.modelKey || s.modelShort || ''},${s.inputTokens || 0},${s.cacheReadTokens || 0},${s.outputTokens || 0},${s.contextTokens || 0},${s.tokPerSec ?? ''},${s.ttftSec ?? ''},${s.costUsd ?? ''},${s.anomalySig || ''};`;
|
||||
}
|
||||
const preSig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${displaySettings?.modelDisplayMode || ''}|${Boolean(displaySettings?.showUpstreamModel)}|${displaySettings?.orchestratorIdMode || ''}|${targetKeys.join(',')}|${extColorSig}|${preStepParts}`;
|
||||
if (preSig === lastPreSig && lastSummaryBadge) {
|
||||
return { summaryBadge: lastSummaryBadge };
|
||||
}
|
||||
|
||||
const modelColorMap = new Map();
|
||||
@@ -1254,7 +1291,6 @@ export function createSessionLineChart() {
|
||||
const validPoints = points.filter((p) => p.valid);
|
||||
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
|
||||
|
||||
const locale = getEffectiveLocale();
|
||||
const colorSig = Array.from(modelColorMap.entries())
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',');
|
||||
@@ -1500,6 +1536,8 @@ export function createSessionLineChart() {
|
||||
});
|
||||
}
|
||||
|
||||
lastPreSig = preSig;
|
||||
lastSummaryBadge = summaryBadge;
|
||||
return { summaryBadge };
|
||||
}
|
||||
|
||||
@@ -1764,10 +1802,17 @@ export function createModelFitChart() {
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
}
|
||||
|
||||
let cachedFitSvgRect = null;
|
||||
plotStage.addEventListener('mousemove', (e) => {
|
||||
if (!currentSamples.length) return;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
if (!cachedFitSvgRect) {
|
||||
cachedFitSvgRect = svg.getBoundingClientRect();
|
||||
}
|
||||
const rect = cachedFitSvgRect;
|
||||
if (!rect || rect.width <= 0) {
|
||||
cachedFitSvgRect = null;
|
||||
return;
|
||||
}
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
let lo = 0;
|
||||
let hi = currentSamples.length - 1;
|
||||
@@ -1785,12 +1830,16 @@ export function createModelFitChart() {
|
||||
}
|
||||
showHoverAt(bestIdx);
|
||||
});
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
plotStage.addEventListener('mouseleave', () => {
|
||||
cachedFitSvgRect = null;
|
||||
clearHover();
|
||||
});
|
||||
|
||||
let resizeObs = null;
|
||||
let onWinResize = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
cachedFitSvgRect = null;
|
||||
if (syncViewWidth() && lastUpdateParams) {
|
||||
lastSig = '';
|
||||
update(lastUpdateParams);
|
||||
|
||||
@@ -427,8 +427,27 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
let cachedWrapRect = null;
|
||||
let cachedSvgRect = null;
|
||||
let cachedHmGridRect = null;
|
||||
let cachedClipRect = undefined;
|
||||
|
||||
function invalidateHoverRects() {
|
||||
cachedWrapRect = null;
|
||||
cachedSvgRect = null;
|
||||
cachedHmGridRect = null;
|
||||
cachedClipRect = undefined;
|
||||
}
|
||||
|
||||
function getCachedWrapRect() {
|
||||
if (!cachedWrapRect) {
|
||||
cachedWrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
}
|
||||
return cachedWrapRect;
|
||||
}
|
||||
|
||||
function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) {
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapRect = getCachedWrapRect();
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
@@ -438,13 +457,8 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
? wrapRect.height
|
||||
: Number(chartWrap.offsetHeight || VIEW_H);
|
||||
|
||||
const tipRect = tooltipEl.getBoundingClientRect?.() || null;
|
||||
const tipW =
|
||||
Number(tooltipEl.offsetWidth || 0) ||
|
||||
(tipRect && tipRect.width > 0 ? tipRect.width : 216);
|
||||
const tipH =
|
||||
Number(tooltipEl.offsetHeight || 0) ||
|
||||
(tipRect && tipRect.height > 0 ? tipRect.height : 104);
|
||||
const tipW = Number(tooltipEl.offsetWidth || 0) || 216;
|
||||
const tipH = Number(tooltipEl.offsetHeight || 0) || 104;
|
||||
|
||||
const hasPointer =
|
||||
pointer &&
|
||||
@@ -457,8 +471,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
|
||||
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
|
||||
|
||||
if (cachedClipRect === undefined) {
|
||||
const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null;
|
||||
const clipRect = clipEl?.getBoundingClientRect?.() || null;
|
||||
cachedClipRect = clipEl?.getBoundingClientRect?.() || null;
|
||||
}
|
||||
const clipRect = cachedClipRect;
|
||||
const hasClip = Boolean(
|
||||
clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0
|
||||
);
|
||||
@@ -524,7 +541,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapRect = getCachedWrapRect();
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
@@ -571,7 +588,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
populateTooltipContent(slot);
|
||||
}
|
||||
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapRect = getCachedWrapRect();
|
||||
const cellRect = targetCell.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
@@ -596,6 +613,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
invalidateHoverRects();
|
||||
cancelTipTrackRaf();
|
||||
hoveredIdx = -1;
|
||||
lastPointer = null;
|
||||
@@ -642,8 +660,14 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
|
||||
function handlePointerMove(e) {
|
||||
if (currentIsHeatmap || !currentSlots.length) return;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
if (!cachedSvgRect) {
|
||||
cachedSvgRect = svg.getBoundingClientRect();
|
||||
}
|
||||
const rect = cachedSvgRect;
|
||||
if (!rect || rect.width <= 0) {
|
||||
cachedSvgRect = null;
|
||||
return;
|
||||
}
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
@@ -686,8 +710,12 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rect = hmGridEl.getBoundingClientRect?.();
|
||||
if (!cachedHmGridRect) {
|
||||
cachedHmGridRect = hmGridEl.getBoundingClientRect?.() || null;
|
||||
}
|
||||
const rect = cachedHmGridRect;
|
||||
if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) {
|
||||
cachedHmGridRect = null;
|
||||
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
||||
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
||||
}
|
||||
@@ -842,6 +870,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
let onWinResize = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
invalidateHoverRects();
|
||||
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||
lastRenderSig = '';
|
||||
update(currentSlots);
|
||||
|
||||
@@ -932,6 +932,51 @@ function getLeftSidebarRightEdge(vw) {
|
||||
/**
|
||||
* 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
|
||||
*/
|
||||
const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/controls.css',
|
||||
]);
|
||||
|
||||
let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null };
|
||||
|
||||
function buildSlimCapsuleCss(fullCss) {
|
||||
if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss;
|
||||
return fullCss
|
||||
.split(/(?=\/\* --- src\/styles\/)/)
|
||||
.filter((block) => {
|
||||
const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//);
|
||||
return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]);
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) {
|
||||
if (!shadowRoot) return;
|
||||
if (
|
||||
fullCss &&
|
||||
typeof CSSStyleSheet === 'function' &&
|
||||
Array.isArray(shadowRoot.adoptedStyleSheets)
|
||||
) {
|
||||
try {
|
||||
if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) {
|
||||
const sheet = new CSSStyleSheet();
|
||||
sheet.replaceSync(fullCss);
|
||||
sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet };
|
||||
}
|
||||
shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet];
|
||||
return;
|
||||
} catch {
|
||||
// 降级到传统 <style> 节点
|
||||
}
|
||||
}
|
||||
const styleEl = document.createElement('style');
|
||||
styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss;
|
||||
shadowRoot.appendChild(styleEl);
|
||||
}
|
||||
|
||||
export function mountWindowOverlay() {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return null;
|
||||
|
||||
@@ -1123,10 +1168,7 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
});
|
||||
const capsuleShadow = capsuleHost.attachShadow({ mode: 'open' });
|
||||
|
||||
const capsuleStyleEl = document.createElement('style');
|
||||
capsuleStyleEl.textContent = stylesCss;
|
||||
capsuleShadow.appendChild(capsuleStyleEl);
|
||||
attachShadowStyles(capsuleShadow, stylesCss, { slimCapsule: true });
|
||||
|
||||
// 左侧无边框多会话实时触发按钮(固定预占宽度,不随运行数跳动)
|
||||
const multiDot = h('span', { className: 'wm-multi-dot' });
|
||||
@@ -1346,10 +1388,7 @@ export function mountWindowOverlay() {
|
||||
portalHost.id = PORTAL_HOST_ID;
|
||||
portalHost.className = 'wm-portal-host';
|
||||
const portalShadow = portalHost.attachShadow({ mode: 'open' });
|
||||
|
||||
const portalStyleEl = document.createElement('style');
|
||||
portalStyleEl.textContent = stylesCss;
|
||||
portalShadow.appendChild(portalStyleEl);
|
||||
attachShadowStyles(portalShadow, stylesCss, { slimCapsule: false });
|
||||
|
||||
const initialSettings = telemetryStore.getState().telemetry?.settings;
|
||||
|
||||
@@ -1460,9 +1499,9 @@ export function mountWindowOverlay() {
|
||||
[multiHeaderEl, multiEmptyEl, multiRunningWidget.el]
|
||||
);
|
||||
|
||||
// 完整四标签悬浮容器
|
||||
// 完整四标签悬浮容器(首次打开主弹窗时按需懒挂载 App,彻底消除宿主窗口冷启动开销)
|
||||
uiStore.setState({ monitorVisible: false });
|
||||
const appInstance = App();
|
||||
let appInstance = null;
|
||||
const popoverEl = h(
|
||||
'div',
|
||||
{
|
||||
@@ -1471,9 +1510,17 @@ export function mountWindowOverlay() {
|
||||
'aria-label': t('capsule.ariaMonitor'),
|
||||
hidden: true,
|
||||
},
|
||||
[appInstance.el]
|
||||
[]
|
||||
);
|
||||
|
||||
function ensureAppMounted() {
|
||||
if (!appInstance) {
|
||||
appInstance = App();
|
||||
popoverEl.appendChild(appInstance.el);
|
||||
}
|
||||
return appInstance;
|
||||
}
|
||||
|
||||
function syncPortalAppearance(settings) {
|
||||
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
|
||||
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
|
||||
@@ -2218,6 +2265,7 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
|
||||
function refreshActiveViewScrollbars() {
|
||||
if (!appInstance) return;
|
||||
const activeView = uiStore.getState().activeView;
|
||||
const refs = appInstance.refs;
|
||||
if (activeView === 'overview') {
|
||||
@@ -2315,6 +2363,9 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
if (popoverOpen === targetOpen) return;
|
||||
popoverOpen = targetOpen;
|
||||
if (popoverOpen) {
|
||||
ensureAppMounted();
|
||||
}
|
||||
patchClasses(capsuleBtn, { 'is-open': popoverOpen });
|
||||
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
|
||||
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
|
||||
@@ -2670,6 +2721,40 @@ export function mountWindowOverlay() {
|
||||
};
|
||||
|
||||
let hostDomObserver = null;
|
||||
let hostDomRafId = 0;
|
||||
let hostDomMicrotaskPending = false;
|
||||
function flushHostDomMutationCheck() {
|
||||
if (disposed) return;
|
||||
syncHostRouteIfChanged();
|
||||
if (!observedWorkbench) {
|
||||
ensureWorkbenchThemeObserved();
|
||||
}
|
||||
const dock = resolveRuntimeDockTarget();
|
||||
if (!isDockPlacementSynced(dock)) {
|
||||
scheduleDockSync();
|
||||
}
|
||||
}
|
||||
function scheduleHostDomMutationCheck() {
|
||||
if (disposed) return;
|
||||
const rafFn =
|
||||
(typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
|
||||
? window.requestAnimationFrame.bind(window)
|
||||
: null) || (typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null);
|
||||
if (rafFn) {
|
||||
if (hostDomRafId) return;
|
||||
hostDomRafId = rafFn(() => {
|
||||
hostDomRafId = 0;
|
||||
flushHostDomMutationCheck();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (hostDomMicrotaskPending) return;
|
||||
hostDomMicrotaskPending = true;
|
||||
queueMicrotask(() => {
|
||||
hostDomMicrotaskPending = false;
|
||||
flushHostDomMutationCheck();
|
||||
});
|
||||
}
|
||||
try {
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
resizeObserver = new ResizeObserver(() => updateResponsiveLayout());
|
||||
@@ -2708,14 +2793,7 @@ export function mountWindowOverlay() {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
syncHostRouteIfChanged();
|
||||
if (!observedWorkbench) {
|
||||
ensureWorkbenchThemeObserved();
|
||||
}
|
||||
const dock = resolveRuntimeDockTarget();
|
||||
if (!isDockPlacementSynced(dock)) {
|
||||
scheduleDockSync();
|
||||
}
|
||||
scheduleHostDomMutationCheck();
|
||||
});
|
||||
hostDomObserver.observe(document.body, {
|
||||
childList: true,
|
||||
@@ -2897,6 +2975,14 @@ export function mountWindowOverlay() {
|
||||
cancelAnimationFrame(dockRafId);
|
||||
dockRafId = 0;
|
||||
}
|
||||
if (hostDomRafId) {
|
||||
const cancelRaf =
|
||||
(typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function'
|
||||
? window.cancelAnimationFrame.bind(window)
|
||||
: null) || (typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : null);
|
||||
cancelRaf?.(hostDomRafId);
|
||||
hostDomRafId = 0;
|
||||
}
|
||||
stopPolling();
|
||||
stopAsyncTelemetryLoop();
|
||||
unsubStore();
|
||||
@@ -2928,7 +3014,7 @@ export function mountWindowOverlay() {
|
||||
hoverWidgetHost.destroy();
|
||||
} catch {}
|
||||
try {
|
||||
appInstance.destroy();
|
||||
appInstance?.destroy?.();
|
||||
} catch {}
|
||||
try {
|
||||
capsuleHost.remove();
|
||||
|
||||
@@ -7,37 +7,16 @@
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||
import {
|
||||
copyPlainTextToClipboard,
|
||||
createCopiedFeedbackController,
|
||||
} from '../../core/stepInspector.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { triggerBridgeHostRelaunch } from '../../store/telemetryStore.js';
|
||||
|
||||
const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0';
|
||||
|
||||
async function copyTextToClipboard(text) {
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Fallback to temporary textarea inside restricted webview contexts
|
||||
}
|
||||
try {
|
||||
if (typeof document === 'undefined' || !document.body) return false;
|
||||
const area = document.createElement('textarea');
|
||||
area.value = text;
|
||||
area.setAttribute('readonly', 'true');
|
||||
area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;';
|
||||
document.body.appendChild(area);
|
||||
area.select?.();
|
||||
const ok = Boolean(document.execCommand?.('copy'));
|
||||
document.body.removeChild(area);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const BridgeStatusNotice = defineComponent({
|
||||
name: 'BridgeStatusNotice',
|
||||
setup({ props, onCleanup }) {
|
||||
@@ -49,11 +28,16 @@ export const BridgeStatusNotice = defineComponent({
|
||||
hostPlatform: 'win32',
|
||||
};
|
||||
let dismissed = false;
|
||||
let copied = false;
|
||||
let copiedTimer = null;
|
||||
let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed'
|
||||
let relaunchResetTimer = null;
|
||||
let destroyed = false;
|
||||
const copyFeedback = createCopiedFeedbackController({
|
||||
durationMs: 1800,
|
||||
onCleanup,
|
||||
onChange: () => {
|
||||
if (!destroyed) syncActionButtons();
|
||||
},
|
||||
});
|
||||
|
||||
const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' });
|
||||
const titleEl = h('strong', { className: 'settings-bridge-title', text: '' });
|
||||
@@ -146,18 +130,9 @@ export const BridgeStatusNotice = defineComponent({
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm settings-bridge-copy-btn',
|
||||
onClick: async () => {
|
||||
await copyTextToClipboard(LAUNCH_FLAG_TEXT);
|
||||
await copyPlainTextToClipboard(LAUNCH_FLAG_TEXT);
|
||||
if (destroyed) return;
|
||||
copied = true;
|
||||
if (copiedTimer) clearTimeout(copiedTimer);
|
||||
syncActionButtons();
|
||||
copiedTimer = setTimeout(() => {
|
||||
copiedTimer = null;
|
||||
if (destroyed) return;
|
||||
copied = false;
|
||||
syncActionButtons();
|
||||
}, 1800);
|
||||
copiedTimer?.unref?.();
|
||||
copyFeedback.trigger(true);
|
||||
},
|
||||
},
|
||||
[copyBtnIconEl, copyBtnTextEl]
|
||||
@@ -200,10 +175,11 @@ export const BridgeStatusNotice = defineComponent({
|
||||
: t('settings.bridge.relaunchBtn')
|
||||
);
|
||||
|
||||
patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy');
|
||||
const isCopied = copyFeedback.isCopied(true);
|
||||
patchSvgIcon(copyBtnIconEl, isCopied ? 'check' : 'copy');
|
||||
patchText(
|
||||
copyBtnTextEl,
|
||||
copied
|
||||
isCopied
|
||||
? t('settings.bridge.copiedBtn')
|
||||
: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT })
|
||||
);
|
||||
@@ -288,10 +264,6 @@ export const BridgeStatusNotice = defineComponent({
|
||||
|
||||
onCleanup(() => {
|
||||
destroyed = true;
|
||||
if (copiedTimer) {
|
||||
clearTimeout(copiedTimer);
|
||||
copiedTimer = null;
|
||||
}
|
||||
if (relaunchResetTimer) {
|
||||
clearTimeout(relaunchResetTimer);
|
||||
relaunchResetTimer = null;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||
import { copyPlainTextToClipboard } from '../../core/stepInspector.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
@@ -14,35 +15,11 @@ import {
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { CustomScrollbar } from '../ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
import { createSearchInput } from '../ui/SearchInput.js';
|
||||
import { SegmentedControl } from '../ui/SegmentedControl.js';
|
||||
|
||||
const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project';
|
||||
|
||||
async function smigCopyText(text) {
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// 退回受限 Webview 的隐藏文本域复制
|
||||
}
|
||||
try {
|
||||
if (typeof document === 'undefined' || !document.body) return false;
|
||||
const area = document.createElement('textarea');
|
||||
area.value = text;
|
||||
area.setAttribute('readonly', 'true');
|
||||
area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;';
|
||||
document.body.appendChild(area);
|
||||
area.select?.();
|
||||
const ok = Boolean(document.execCommand?.('copy'));
|
||||
document.body.removeChild(area);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function smigGetClientLabel(clientId) {
|
||||
if (clientId === 'cli') return t('settings.oth.migClientCli');
|
||||
if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy');
|
||||
@@ -202,41 +179,27 @@ export const SessionMigrationCard = defineComponent({
|
||||
projectSelect.el,
|
||||
]);
|
||||
|
||||
searchInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'smig-search-input',
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
const searchBox = createSearchInput({
|
||||
wrapClassName: 'smig-search-wrap',
|
||||
iconClassName: 'smig-search-icon',
|
||||
inputClassName: 'smig-search-input',
|
||||
clearClassName: 'smig-search-clear',
|
||||
placeholder: t('settings.oth.migSearchPlaceholder'),
|
||||
value: '',
|
||||
});
|
||||
searchClearBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'smig-search-clear',
|
||||
hidden: true,
|
||||
'aria-label': t('select.clearSearch'),
|
||||
onClick: () => {
|
||||
clearAriaLabel: t('select.clearSearch'),
|
||||
closeIconSize: 10,
|
||||
onInput: (val) => {
|
||||
searchQuery = String(val || '').trim();
|
||||
renderSessionList();
|
||||
},
|
||||
onClear: () => {
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
patchAttr(searchClearBtn, 'hidden', true);
|
||||
renderSessionList();
|
||||
searchInput.focus?.();
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: 10 })]
|
||||
);
|
||||
searchInput.addEventListener?.('input', () => {
|
||||
searchQuery = String(searchInput.value || '').trim();
|
||||
patchAttr(searchClearBtn, 'hidden', !searchQuery);
|
||||
renderSessionList();
|
||||
});
|
||||
const searchWrap = h('div', { className: 'smig-search-wrap' }, [
|
||||
createSvgIcon('search', { size: 12, className: 'smig-search-icon' }),
|
||||
searchInput,
|
||||
searchClearBtn,
|
||||
]);
|
||||
searchInput = searchBox.inputEl;
|
||||
searchClearBtn = searchBox.clearBtnEl;
|
||||
const searchWrap = searchBox.el;
|
||||
|
||||
toggleAllBtn = h('button', {
|
||||
type: 'button',
|
||||
@@ -662,7 +625,7 @@ export const SessionMigrationCard = defineComponent({
|
||||
className: 'btn-ghost-sm smig-cmd-copy',
|
||||
text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'),
|
||||
onClick: async () => {
|
||||
const ok = await smigCopyText(item.resumeCommand);
|
||||
const ok = await copyPlainTextToClipboard(item.resumeCommand);
|
||||
if (!ok || destroyed) return;
|
||||
copiedCmdId = item.newCascadeId;
|
||||
renderResultBox();
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '../../core/domPatch.js';
|
||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { createSearchInput } from './SearchInput.js';
|
||||
|
||||
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
|
||||
const arr = Array.isArray(rawValue)
|
||||
@@ -105,44 +106,29 @@ export const CustomSelect = defineComponent({
|
||||
[leadIcon, triggerLabel, chevronIcon]
|
||||
);
|
||||
|
||||
const searchIcon = createSvgIcon('search', { size: 12, className: 'select-search-icon' });
|
||||
const searchInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'select-search-input',
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
const searchBox = createSearchInput({
|
||||
wrapClassName: 'select-search-wrap',
|
||||
iconClassName: 'select-search-icon',
|
||||
inputClassName: 'select-search-input',
|
||||
clearClassName: 'select-search-clear',
|
||||
placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'),
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
onInput: (e) => {
|
||||
searchQuery = String(e?.target?.value ?? searchInput.value ?? '');
|
||||
clearAriaLabel: t('select.clearSearch'),
|
||||
hidden: true,
|
||||
stopClickPropagation: true,
|
||||
closeIconSize: 10,
|
||||
onInput: (val) => {
|
||||
searchQuery = val;
|
||||
focusedIndex = 0;
|
||||
renderMenuOptions();
|
||||
},
|
||||
onKeydown: handleKeydown,
|
||||
});
|
||||
const searchClearBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'select-search-clear',
|
||||
hidden: true,
|
||||
'aria-label': t('select.clearSearch'),
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
onClear: () => {
|
||||
clearSearchQuery(true);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: 10 })]
|
||||
);
|
||||
const searchWrap = h(
|
||||
'div',
|
||||
{
|
||||
className: 'select-search-wrap',
|
||||
hidden: true,
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
},
|
||||
[searchIcon, searchInput, searchClearBtn]
|
||||
);
|
||||
onKeydown: handleKeydown,
|
||||
});
|
||||
const searchWrap = searchBox.el;
|
||||
const searchInput = searchBox.inputEl;
|
||||
const searchClearBtn = searchBox.clearBtnEl;
|
||||
|
||||
const optionsListEl = h('div', { className: 'select-options-list' });
|
||||
const emptyHintEl = h('div', {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* @fileoverview Shared compact search input bar (`SearchInput.js`) with leading search icon
|
||||
* and conditional clear button, reused across `CustomSelect`, `StepsDetailView`, and `SessionMigrationCard`.
|
||||
*/
|
||||
|
||||
import { h, patchAttr } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
|
||||
/**
|
||||
* Creates a unified search input box while preserving caller-specific modifier classes.
|
||||
*
|
||||
* @param {{
|
||||
* wrapClassName?: string,
|
||||
* iconClassName?: string,
|
||||
* inputClassName?: string,
|
||||
* clearClassName?: string,
|
||||
* placeholder?: string,
|
||||
* ariaLabel?: string,
|
||||
* clearAriaLabel?: string,
|
||||
* hidden?: boolean,
|
||||
* stopClickPropagation?: boolean,
|
||||
* closeIconSize?: number,
|
||||
* onInput?: (value: string, event: any) => void,
|
||||
* onClear?: (event: any) => void,
|
||||
* onKeydown?: (event: any) => void,
|
||||
* }} [options={}]
|
||||
*/
|
||||
export function createSearchInput({
|
||||
wrapClassName = '',
|
||||
iconClassName = '',
|
||||
inputClassName = '',
|
||||
clearClassName = '',
|
||||
placeholder = '',
|
||||
ariaLabel = '',
|
||||
clearAriaLabel = '',
|
||||
hidden = false,
|
||||
stopClickPropagation = false,
|
||||
closeIconSize = 10,
|
||||
onInput = null,
|
||||
onClear = null,
|
||||
onKeydown = null,
|
||||
} = {}) {
|
||||
const iconEl = createSvgIcon('search', {
|
||||
size: 12,
|
||||
className: ['ui-search-icon', iconClassName].filter(Boolean).join(' '),
|
||||
});
|
||||
|
||||
const inputEl = h('input', {
|
||||
type: 'text',
|
||||
className: ['ui-search-input', inputClassName].filter(Boolean).join(' '),
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
placeholder,
|
||||
...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
|
||||
...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}),
|
||||
onInput: (e) => {
|
||||
const val = String(e?.target?.value ?? inputEl.value ?? '');
|
||||
patchAttr(clearBtnEl, 'hidden', !val.trim());
|
||||
onInput?.(val, e);
|
||||
},
|
||||
...(onKeydown ? { onKeydown } : {}),
|
||||
});
|
||||
|
||||
const clearBtnEl = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: ['ui-search-clear', clearClassName].filter(Boolean).join(' '),
|
||||
hidden: true,
|
||||
...(clearAriaLabel ? { 'aria-label': clearAriaLabel } : {}),
|
||||
onClick: (e) => {
|
||||
if (stopClickPropagation) e?.stopPropagation?.();
|
||||
inputEl.value = '';
|
||||
patchAttr(clearBtnEl, 'hidden', true);
|
||||
if (onClear) {
|
||||
onClear(e);
|
||||
} else {
|
||||
onInput?.('', e);
|
||||
inputEl.focus?.();
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: closeIconSize })]
|
||||
);
|
||||
|
||||
const wrapEl = h(
|
||||
'div',
|
||||
{
|
||||
className: ['ui-search-wrap', wrapClassName].filter(Boolean).join(' '),
|
||||
...(hidden ? { hidden: true } : {}),
|
||||
...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}),
|
||||
},
|
||||
[iconEl, inputEl, clearBtnEl]
|
||||
);
|
||||
|
||||
return {
|
||||
el: wrapEl,
|
||||
iconEl,
|
||||
inputEl,
|
||||
clearBtnEl,
|
||||
getValue() {
|
||||
return String(inputEl.value || '');
|
||||
},
|
||||
setValue(nextVal) {
|
||||
const str = String(nextVal ?? '');
|
||||
inputEl.value = str;
|
||||
patchAttr(clearBtnEl, 'hidden', !str.trim());
|
||||
},
|
||||
syncLabels({ placeholder: nextPlaceholder, ariaLabel: nextAria, clearAriaLabel: nextClearAria } = {}) {
|
||||
if (nextPlaceholder !== undefined) patchAttr(inputEl, 'placeholder', nextPlaceholder);
|
||||
if (nextAria !== undefined) patchAttr(inputEl, 'aria-label', nextAria);
|
||||
if (nextClearAria !== undefined) patchAttr(clearBtnEl, 'aria-label', nextClearAria);
|
||||
},
|
||||
focus() {
|
||||
inputEl.focus?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* @fileoverview Zero-ResizeObserver binary toggle switch (`ToggleSwitch.js`).
|
||||
* Uses a pure-CSS 2-column grid glider (`--seg-active-idx`) so Settings tabs do not
|
||||
* instantiate 10+ ResizeObservers or force synchronous layout measurements for simple
|
||||
* on/off or show/hide switches, while preserving `.segmented` / `.seg-btn` semantics.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { i18nStore, t } from '../../i18n/index.js';
|
||||
|
||||
const TOGGLE_PRESET_DEFS = Object.freeze({
|
||||
enable: Object.freeze([
|
||||
{ value: 'on', labelKey: 'settings.str.on' },
|
||||
{ value: 'off', labelKey: 'settings.str.off' },
|
||||
]),
|
||||
visibility: Object.freeze([
|
||||
{ value: 'show', labelKey: 'settings.str.show' },
|
||||
{ value: 'hide', labelKey: 'settings.str.hide' },
|
||||
]),
|
||||
modernUi: Object.freeze([
|
||||
{ value: 'on', labelKey: 'settings.gen.modernUiOn' },
|
||||
{ value: 'off', labelKey: 'settings.gen.modernUiOff' },
|
||||
]),
|
||||
});
|
||||
|
||||
function resolveToggleOptions(props) {
|
||||
if (Array.isArray(props.options) && props.options.length === 2) {
|
||||
return props.options;
|
||||
}
|
||||
const defs = TOGGLE_PRESET_DEFS[props.preset] || TOGGLE_PRESET_DEFS.enable;
|
||||
return [
|
||||
{ value: defs[0].value, label: t(defs[0].labelKey) },
|
||||
{ value: defs[1].value, label: t(defs[1].labelKey) },
|
||||
];
|
||||
}
|
||||
|
||||
export const ToggleSwitch = defineComponent({
|
||||
name: 'ToggleSwitch',
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
const gliderEl = h('div', { className: 'seg-glider is-ready', 'aria-hidden': 'true' });
|
||||
const btns = [0, 1].map((slotIdx) =>
|
||||
h('button', {
|
||||
type: 'button',
|
||||
className: 'seg-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
const opts = resolveToggleOptions(getProps());
|
||||
const opt = opts[slotIdx];
|
||||
if (opt) selectValue(opt.value);
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
const opts = resolveToggleOptions(getProps());
|
||||
const nextIdx = slotIdx === 0 ? 1 : 0;
|
||||
const targetOpt = opts[nextIdx];
|
||||
if (targetOpt) {
|
||||
selectValue(targetOpt.value);
|
||||
btns[nextIdx]?.focus?.();
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const rootEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'segmented segmented--binary has-glider toggle-switch',
|
||||
role: 'group',
|
||||
'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'),
|
||||
},
|
||||
[gliderEl, btns[0], btns[1]]
|
||||
);
|
||||
|
||||
function selectValue(nextVal) {
|
||||
if (getProps().modelValue !== nextVal) {
|
||||
setProps({ modelValue: nextVal });
|
||||
emit('update:modelValue', nextVal);
|
||||
}
|
||||
}
|
||||
|
||||
function syncToggle() {
|
||||
const props = getProps();
|
||||
const opts = resolveToggleOptions(props);
|
||||
const aria = props.ariaLabelKey ? t(props.ariaLabelKey) : props.ariaLabel || t('ui.seg.defaultAria');
|
||||
patchAttr(rootEl, 'aria-label', aria);
|
||||
|
||||
let activeIdx = 0;
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
const opt = opts[i];
|
||||
const btn = btns[i];
|
||||
const active = opt.value === props.modelValue;
|
||||
if (active) activeIdx = i;
|
||||
patchText(btn, opt.label);
|
||||
patchClasses(btn, { 'is-active': active });
|
||||
patchAttr(btn, 'aria-pressed', active ? 'true' : 'false');
|
||||
patchAttr(btn, 'data-seg-value', opt.value);
|
||||
}
|
||||
patchStyleVar(rootEl, '--seg-active-idx', String(activeIdx));
|
||||
}
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
syncToggle();
|
||||
},
|
||||
{ immediate: false }
|
||||
);
|
||||
onCleanup(unsubI18n);
|
||||
|
||||
syncToggle();
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
onPropsChange: syncToggle,
|
||||
methods: {
|
||||
setValue(val) {
|
||||
setProps({ modelValue: val });
|
||||
},
|
||||
setOptions(options) {
|
||||
setProps({ options });
|
||||
},
|
||||
refreshGeometry() {},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @fileoverview 统一文本文件导出及剪贴板复制客户端 (`fileExportClient.js`)。
|
||||
* @fileoverview 统一文本/二进制文件导出及剪贴板复制客户端 (`fileExportClient.js`)。
|
||||
* 优先调用本机后端 `/api/export-file` 落盘到用户 Downloads(或插件 `.data/exports`)并返回真实绝对路径,
|
||||
* 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮;
|
||||
* 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。
|
||||
@@ -8,7 +8,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { showUiToast } from '../store/uiStore.js';
|
||||
import { callSidecarApi, isWindowOverlayMode } from './httpClient.js';
|
||||
import { triggerTextFileDownload } from './settingsBackup.js';
|
||||
import { triggerBlobDownload } from './settingsBackup.js';
|
||||
import { copyPlainTextToClipboard } from './stepInspector.js';
|
||||
import { uint8ArrayToBase64 } from './xlsxBuilder.js';
|
||||
|
||||
@@ -17,36 +17,6 @@ function isHostEmbeddedWebview() {
|
||||
return Boolean(window.sidecar?.fetch) || isWindowOverlayMode();
|
||||
}
|
||||
|
||||
function triggerBinaryFileDownload(filename, bytes, mimeType) {
|
||||
try {
|
||||
if (
|
||||
typeof Blob === 'undefined' ||
|
||||
typeof URL === 'undefined' ||
|
||||
typeof URL.createObjectURL !== 'function' ||
|
||||
typeof document === 'undefined'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const blob = new Blob([bytes], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.setAttribute('href', url);
|
||||
a.setAttribute('download', String(filename || 'export.xlsx'));
|
||||
a.style.display = 'none';
|
||||
document.body?.appendChild?.(a);
|
||||
a.click?.();
|
||||
a.remove?.();
|
||||
setTimeout(() => {
|
||||
try {
|
||||
URL.revokeObjectURL(url);
|
||||
} catch {}
|
||||
}, 1000);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function getPickerTypesForFilename(filename, mimeType) {
|
||||
const lower = String(filename || '').toLowerCase();
|
||||
if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) {
|
||||
@@ -140,28 +110,15 @@ async function requestLocalBackendExport(payload) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录),
|
||||
* 仅在真正独立浏览器上下文(非 Sidecar / 非 Electron 宿主)下降级为浏览器保存,避免宿主静默吞掉 Blob 下载后误报成功。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {string} content
|
||||
* @param {string} [mimeType='text/plain;charset=utf-8']
|
||||
* @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>}
|
||||
* 共享多阶段导出与 Toast 反馈骨架(本机落盘 -> 宿主拦截保护 -> File System Access Picker -> Blob 下载)。
|
||||
*/
|
||||
export async function exportTextFileWithFeedback(
|
||||
filename,
|
||||
content,
|
||||
mimeType = 'application/json;charset=utf-8'
|
||||
) {
|
||||
const safeName = String(filename || 'export.txt');
|
||||
const text = String(content ?? '');
|
||||
|
||||
// 1. 优先通过本机后端落盘到 Downloads(含 /api/settings 穿透兼容旧常驻 main.mjs)
|
||||
const { res: localRes } = await requestLocalBackendExport({
|
||||
filename: safeName,
|
||||
content: text,
|
||||
async function runExportPipelineWithFeedback({
|
||||
safeName,
|
||||
mimeType,
|
||||
});
|
||||
backendPayload,
|
||||
writablePayload,
|
||||
}) {
|
||||
const { res: localRes } = await requestLocalBackendExport(backendPayload);
|
||||
if (localRes && localRes.ok && localRes.filePath) {
|
||||
const savedPath = String(localRes.filePath);
|
||||
const savedName = String(localRes.fileName || safeName);
|
||||
@@ -178,7 +135,7 @@ export async function exportTextFileWithFeedback(
|
||||
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
|
||||
}
|
||||
|
||||
// 2. 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
|
||||
// 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
|
||||
if (isHostEmbeddedWebview()) {
|
||||
showUiToast({
|
||||
message: t('export.failed'),
|
||||
@@ -189,7 +146,6 @@ export async function exportTextFileWithFeedback(
|
||||
return { ok: false, mode: 'failed' };
|
||||
}
|
||||
|
||||
// 3. 普通独立浏览器原生「另存为」对话框
|
||||
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
|
||||
try {
|
||||
const handle = await window.showSaveFilePicker({
|
||||
@@ -197,7 +153,7 @@ export async function exportTextFileWithFeedback(
|
||||
types: getPickerTypesForFilename(safeName, mimeType),
|
||||
});
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(text);
|
||||
await writable.write(writablePayload);
|
||||
await writable.close();
|
||||
const pickedName = handle.name || safeName;
|
||||
showUiToast({
|
||||
@@ -210,12 +166,10 @@ export async function exportTextFileWithFeedback(
|
||||
if (err && err.name === 'AbortError') {
|
||||
return { ok: false, mode: 'cancelled' };
|
||||
}
|
||||
// 沙箱/iframe 抛出 SecurityError 等时继续降级到 Blob 下载
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 独立浏览器标准 Blob 兜底下载
|
||||
const ok = triggerTextFileDownload(safeName, text, mimeType);
|
||||
const ok = triggerBlobDownload(safeName, writablePayload, mimeType);
|
||||
if (ok) {
|
||||
showUiToast({
|
||||
message: t('export.savedBrowser', { file: safeName }),
|
||||
@@ -234,9 +188,36 @@ export async function exportTextFileWithFeedback(
|
||||
return { ok: false, mode: 'failed' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录),
|
||||
* 仅在真正独立浏览器上下文下降级为浏览器保存。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {string} content
|
||||
* @param {string} [mimeType='application/json;charset=utf-8']
|
||||
* @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>}
|
||||
*/
|
||||
export async function exportTextFileWithFeedback(
|
||||
filename,
|
||||
content,
|
||||
mimeType = 'application/json;charset=utf-8'
|
||||
) {
|
||||
const safeName = String(filename || 'export.txt');
|
||||
const text = String(content ?? '');
|
||||
return runExportPipelineWithFeedback({
|
||||
safeName,
|
||||
mimeType,
|
||||
backendPayload: {
|
||||
filename: safeName,
|
||||
content: text,
|
||||
mimeType,
|
||||
},
|
||||
writablePayload: text,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一二进制文件导出入口(用于原生 `.xlsx` Excel 工作簿)。
|
||||
* 优先转 Base64 经本机后端落盘到 Downloads 并展示完整路径 + 「打开位置」直达按钮。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {Uint8Array} bytes
|
||||
@@ -253,80 +234,17 @@ export async function exportBinaryFileWithFeedback(
|
||||
showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 });
|
||||
return { ok: false, mode: 'failed' };
|
||||
}
|
||||
|
||||
const base64Content = uint8ArrayToBase64(bytes);
|
||||
const { res: localRes } = await requestLocalBackendExport({
|
||||
return runExportPipelineWithFeedback({
|
||||
safeName,
|
||||
mimeType,
|
||||
backendPayload: {
|
||||
filename: safeName,
|
||||
content: base64Content,
|
||||
content: uint8ArrayToBase64(bytes),
|
||||
encoding: 'base64',
|
||||
mimeType,
|
||||
});
|
||||
if (localRes && localRes.ok && localRes.filePath) {
|
||||
const savedPath = String(localRes.filePath);
|
||||
const savedName = String(localRes.fileName || safeName);
|
||||
showUiToast({
|
||||
message: t('export.savedLocal', { file: savedName }),
|
||||
detail: savedPath,
|
||||
actionLabel: t('export.openFolder'),
|
||||
onAction: () => {
|
||||
void revealExportedFile(savedPath);
|
||||
},
|
||||
tone: 'ok',
|
||||
durationMs: 7000,
|
||||
writablePayload: bytes,
|
||||
});
|
||||
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
|
||||
}
|
||||
|
||||
if (isHostEmbeddedWebview()) {
|
||||
showUiToast({
|
||||
message: t('export.failed'),
|
||||
detail: t('export.hostUnavailable'),
|
||||
tone: 'warn',
|
||||
durationMs: 5200,
|
||||
});
|
||||
return { ok: false, mode: 'failed' };
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
|
||||
try {
|
||||
const handle = await window.showSaveFilePicker({
|
||||
suggestedName: safeName,
|
||||
types: getPickerTypesForFilename(safeName, mimeType),
|
||||
});
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(bytes);
|
||||
await writable.close();
|
||||
const pickedName = handle.name || safeName;
|
||||
showUiToast({
|
||||
message: t('export.savedPicked', { file: pickedName }),
|
||||
tone: 'ok',
|
||||
durationMs: 4200,
|
||||
});
|
||||
return { ok: true, mode: 'picker', fileName: pickedName };
|
||||
} catch (err) {
|
||||
if (err && err.name === 'AbortError') {
|
||||
return { ok: false, mode: 'cancelled' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ok = triggerBinaryFileDownload(safeName, bytes, mimeType);
|
||||
if (ok) {
|
||||
showUiToast({
|
||||
message: t('export.savedBrowser', { file: safeName }),
|
||||
detail: t('export.savedBrowserHint'),
|
||||
tone: 'info',
|
||||
durationMs: 5000,
|
||||
});
|
||||
return { ok: true, mode: 'browser', fileName: safeName };
|
||||
}
|
||||
|
||||
showUiToast({
|
||||
message: t('export.failed'),
|
||||
tone: 'warn',
|
||||
durationMs: 3600,
|
||||
});
|
||||
return { ok: false, mode: 'failed' };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`).
|
||||
* 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。
|
||||
* 通过单一声明式字段描述符表同时驱动导出与导入归一化,消除双遍手写 30 个键的漏同步风险。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -36,17 +36,17 @@ function sanitizePositiveBudgetNum(val) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。
|
||||
* 在浏览器端通过内存 Blob 触发文件下载(统一承载文本与二进制载荷)。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {string} content
|
||||
* @param {BlobPart} blobPart
|
||||
* @param {string} [mimeType]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function triggerTextFileDownload(
|
||||
export function triggerBlobDownload(
|
||||
filename,
|
||||
content,
|
||||
mimeType = 'application/json;charset=utf-8'
|
||||
blobPart,
|
||||
mimeType = 'application/octet-stream'
|
||||
) {
|
||||
try {
|
||||
if (
|
||||
@@ -57,11 +57,11 @@ export function triggerTextFileDownload(
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const blob = new Blob([String(content ?? '')], { type: mimeType });
|
||||
const blob = new Blob([blobPart], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.setAttribute('href', url);
|
||||
a.setAttribute('download', String(filename || 'export.json'));
|
||||
a.setAttribute('download', String(filename || 'export.dat'));
|
||||
a.style.display = 'none';
|
||||
document.body?.appendChild?.(a);
|
||||
a.click?.();
|
||||
@@ -77,6 +77,143 @@ export function triggerTextFileDownload(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在浏览器端通过内存 Blob 触发文本文件下载。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {string} content
|
||||
* @param {string} [mimeType]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function triggerTextFileDownload(
|
||||
filename,
|
||||
content,
|
||||
mimeType = 'application/json;charset=utf-8'
|
||||
) {
|
||||
return triggerBlobDownload(
|
||||
String(filename || 'export.json'),
|
||||
String(content ?? ''),
|
||||
mimeType
|
||||
);
|
||||
}
|
||||
|
||||
const normField = (key, normalizeFn) => ({
|
||||
exportTo: (src, out) => {
|
||||
out[key] = normalizeFn(src[key]);
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey(key)) patch[key] = normalizeFn(src[key]);
|
||||
},
|
||||
});
|
||||
|
||||
const boolField = (key, defaultVal) => ({
|
||||
exportTo: (src, out) => {
|
||||
out[key] = defaultVal ? src[key] !== false : src[key] === true;
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey(key) && typeof src[key] === 'boolean') patch[key] = src[key];
|
||||
},
|
||||
});
|
||||
|
||||
const arrayField = (key, normalizeFn) => ({
|
||||
exportTo: (src, out) => {
|
||||
out[key] = normalizeFn(src[key]);
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey(key) && Array.isArray(src[key])) patch[key] = normalizeFn(src[key]);
|
||||
},
|
||||
});
|
||||
|
||||
const positiveBudgetField = (key, fallbackVal) => ({
|
||||
exportTo: (src, out) => {
|
||||
out[key] = sanitizePositiveBudgetNum(src[key]) ?? fallbackVal;
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey(key)) {
|
||||
const num = sanitizePositiveBudgetNum(src[key]);
|
||||
if (num !== null) patch[key] = num;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([
|
||||
normField('language', normalizeLanguageSetting),
|
||||
normField('themeAccent', normalizeThemeAccent),
|
||||
normField('fontScale', normalizeFontScale),
|
||||
{
|
||||
exportTo: (src, out) => {
|
||||
out.modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true;
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey('modernUi')) {
|
||||
const val = normalizeModernUi(src.modernUi);
|
||||
patch.modernUi = val;
|
||||
patch.experimentalModernUi = val;
|
||||
}
|
||||
},
|
||||
},
|
||||
normField('weeklyLimitMode', normalizeWeeklyLimitMode),
|
||||
positiveBudgetField('weeklyTokenBudget', 150000000),
|
||||
positiveBudgetField('weeklyCostBudget', 100),
|
||||
{
|
||||
exportTo: (src, out) => {
|
||||
const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
out.modelDisplayMode = mode;
|
||||
out.showUpstreamModel = mode !== 'short';
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) {
|
||||
const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
patch.modelDisplayMode = mode;
|
||||
patch.showUpstreamModel = mode !== 'short';
|
||||
}
|
||||
},
|
||||
},
|
||||
normField('orchestratorIdMode', normalizeOrchestratorIdMode),
|
||||
{
|
||||
exportTo: (src, out) => {
|
||||
out.pluginUpdateMode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin);
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) {
|
||||
const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin);
|
||||
patch.pluginUpdateMode = mode;
|
||||
patch.autoUpdatePlugin = mode === 'auto';
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
exportTo: (src, out) => {
|
||||
out.windowMountMode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay);
|
||||
},
|
||||
importTo: (src, hasKey, patch) => {
|
||||
if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) {
|
||||
const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay);
|
||||
patch.windowMountMode = mode;
|
||||
patch.enableWindowOverlay = mode !== 'sidebar';
|
||||
}
|
||||
},
|
||||
},
|
||||
normField('popoverWidthMode', normalizePopoverWidthMode),
|
||||
normField('popoverWidth', normalizePopoverWidth),
|
||||
boolField('enableCliStatusLine', true),
|
||||
normField('cliStatusLineSlots', normalizeCliStatusLineSlots),
|
||||
normField('standalonePort', normalizeStandalonePort),
|
||||
boolField('showTopbarMultiSession', true),
|
||||
normField('contextAgentMode', normalizeContextAgentMode),
|
||||
arrayField('topbarCapsuleSlots', normalizeTopbarCapsuleSlots),
|
||||
arrayField('hoverModules', normalizeHoverModules),
|
||||
arrayField('overviewModules', normalizeOverviewModules),
|
||||
arrayField('overviewMetrics', normalizeOverviewMetrics),
|
||||
boolField('showStepTurnRail', false),
|
||||
boolField('showStepAgentBadge', true),
|
||||
boolField('showStepSpeedColor', false),
|
||||
boolField('showStepFilterToolbar', false),
|
||||
normField('stepTokenComboFormat', normalizeStepTokenComboFormat),
|
||||
arrayField('stepTableColumns', normalizeStepTableColumns),
|
||||
normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation),
|
||||
]);
|
||||
|
||||
/**
|
||||
* 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。
|
||||
*
|
||||
@@ -85,46 +222,15 @@ export function triggerTextFileDownload(
|
||||
*/
|
||||
export function buildExportableSettingsJson(settings = {}) {
|
||||
const src = settings && typeof settings === 'object' ? settings : {};
|
||||
const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true;
|
||||
const outSettings = {};
|
||||
for (const desc of PORTABLE_SETTING_DESCRIPTORS) {
|
||||
desc.exportTo(src, outSettings);
|
||||
}
|
||||
const payload = {
|
||||
schema: SETTINGS_BACKUP_SCHEMA,
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
settings: {
|
||||
language: normalizeLanguageSetting(src.language),
|
||||
themeAccent: normalizeThemeAccent(src.themeAccent),
|
||||
fontScale: normalizeFontScale(src.fontScale),
|
||||
modernUi,
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(src.weeklyLimitMode),
|
||||
weeklyTokenBudget: sanitizePositiveBudgetNum(src.weeklyTokenBudget) ?? 150000000,
|
||||
weeklyCostBudget: sanitizePositiveBudgetNum(src.weeklyCostBudget) ?? 100,
|
||||
modelDisplayMode,
|
||||
showUpstreamModel: modelDisplayMode !== 'short',
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(src.orchestratorIdMode),
|
||||
pluginUpdateMode: normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin),
|
||||
windowMountMode: normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay),
|
||||
popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode),
|
||||
popoverWidth: normalizePopoverWidth(src.popoverWidth),
|
||||
enableCliStatusLine: src.enableCliStatusLine !== false,
|
||||
cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots),
|
||||
standalonePort: normalizeStandalonePort(src.standalonePort),
|
||||
showTopbarMultiSession: src.showTopbarMultiSession !== false,
|
||||
contextAgentMode: normalizeContextAgentMode(src.contextAgentMode),
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots),
|
||||
hoverModules: normalizeHoverModules(src.hoverModules),
|
||||
overviewModules: normalizeOverviewModules(src.overviewModules),
|
||||
overviewMetrics: normalizeOverviewMetrics(src.overviewMetrics),
|
||||
showStepTurnRail: src.showStepTurnRail === true,
|
||||
showStepAgentBadge: src.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: src.showStepSpeedColor === true,
|
||||
showStepFilterToolbar: src.showStepFilterToolbar === true,
|
||||
stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat),
|
||||
stepTableColumns: normalizeStepTableColumns(src.stepTableColumns),
|
||||
experimentalQuotaReservation: normalizeExperimentalQuotaReservation(
|
||||
src.experimentalQuotaReservation
|
||||
),
|
||||
},
|
||||
settings: outSettings,
|
||||
};
|
||||
return `${JSON.stringify(payload, null, 2)}\n`;
|
||||
}
|
||||
@@ -158,98 +264,8 @@ export function parseImportedSettingsJson(rawText) {
|
||||
const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k);
|
||||
const patch = {};
|
||||
|
||||
if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language);
|
||||
if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent);
|
||||
if (hasKey('fontScale')) patch.fontScale = normalizeFontScale(src.fontScale);
|
||||
if (hasKey('modernUi')) {
|
||||
const val = normalizeModernUi(src.modernUi);
|
||||
patch.modernUi = val;
|
||||
patch.experimentalModernUi = val;
|
||||
}
|
||||
if (hasKey('weeklyLimitMode')) {
|
||||
patch.weeklyLimitMode = normalizeWeeklyLimitMode(src.weeklyLimitMode);
|
||||
}
|
||||
if (hasKey('weeklyTokenBudget')) {
|
||||
const num = sanitizePositiveBudgetNum(src.weeklyTokenBudget);
|
||||
if (num !== null) patch.weeklyTokenBudget = num;
|
||||
}
|
||||
if (hasKey('weeklyCostBudget')) {
|
||||
const num = sanitizePositiveBudgetNum(src.weeklyCostBudget);
|
||||
if (num !== null) patch.weeklyCostBudget = num;
|
||||
}
|
||||
if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) {
|
||||
const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
patch.modelDisplayMode = mode;
|
||||
patch.showUpstreamModel = mode !== 'short';
|
||||
}
|
||||
if (hasKey('orchestratorIdMode')) {
|
||||
patch.orchestratorIdMode = normalizeOrchestratorIdMode(src.orchestratorIdMode);
|
||||
}
|
||||
if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) {
|
||||
const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin);
|
||||
patch.pluginUpdateMode = mode;
|
||||
patch.autoUpdatePlugin = mode === 'auto';
|
||||
}
|
||||
if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) {
|
||||
const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay);
|
||||
patch.windowMountMode = mode;
|
||||
patch.enableWindowOverlay = mode !== 'sidebar';
|
||||
}
|
||||
if (hasKey('popoverWidthMode')) {
|
||||
patch.popoverWidthMode = normalizePopoverWidthMode(src.popoverWidthMode);
|
||||
}
|
||||
if (hasKey('popoverWidth')) {
|
||||
patch.popoverWidth = normalizePopoverWidth(src.popoverWidth);
|
||||
}
|
||||
if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') {
|
||||
patch.enableCliStatusLine = src.enableCliStatusLine;
|
||||
}
|
||||
if (hasKey('cliStatusLineSlots')) {
|
||||
patch.cliStatusLineSlots = normalizeCliStatusLineSlots(src.cliStatusLineSlots);
|
||||
}
|
||||
if (hasKey('standalonePort')) {
|
||||
patch.standalonePort = normalizeStandalonePort(src.standalonePort);
|
||||
}
|
||||
if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') {
|
||||
patch.showTopbarMultiSession = src.showTopbarMultiSession;
|
||||
}
|
||||
if (hasKey('contextAgentMode')) {
|
||||
patch.contextAgentMode = normalizeContextAgentMode(src.contextAgentMode);
|
||||
}
|
||||
if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) {
|
||||
patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots);
|
||||
}
|
||||
if (hasKey('hoverModules') && Array.isArray(src.hoverModules)) {
|
||||
patch.hoverModules = normalizeHoverModules(src.hoverModules);
|
||||
}
|
||||
if (hasKey('overviewModules') && Array.isArray(src.overviewModules)) {
|
||||
patch.overviewModules = normalizeOverviewModules(src.overviewModules);
|
||||
}
|
||||
if (hasKey('overviewMetrics') && Array.isArray(src.overviewMetrics)) {
|
||||
patch.overviewMetrics = normalizeOverviewMetrics(src.overviewMetrics);
|
||||
}
|
||||
if (hasKey('showStepTurnRail') && typeof src.showStepTurnRail === 'boolean') {
|
||||
patch.showStepTurnRail = src.showStepTurnRail;
|
||||
}
|
||||
if (hasKey('showStepAgentBadge') && typeof src.showStepAgentBadge === 'boolean') {
|
||||
patch.showStepAgentBadge = src.showStepAgentBadge;
|
||||
}
|
||||
if (hasKey('showStepSpeedColor') && typeof src.showStepSpeedColor === 'boolean') {
|
||||
patch.showStepSpeedColor = src.showStepSpeedColor;
|
||||
}
|
||||
if (hasKey('showStepFilterToolbar') && typeof src.showStepFilterToolbar === 'boolean') {
|
||||
patch.showStepFilterToolbar = src.showStepFilterToolbar;
|
||||
}
|
||||
if (hasKey('stepTokenComboFormat')) {
|
||||
patch.stepTokenComboFormat = normalizeStepTokenComboFormat(src.stepTokenComboFormat);
|
||||
}
|
||||
if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) {
|
||||
patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns);
|
||||
}
|
||||
if (hasKey('experimentalQuotaReservation')) {
|
||||
patch.experimentalQuotaReservation = normalizeExperimentalQuotaReservation(
|
||||
src.experimentalQuotaReservation
|
||||
);
|
||||
for (const desc of PORTABLE_SETTING_DESCRIPTORS) {
|
||||
desc.importTo(src, hasKey, patch);
|
||||
}
|
||||
|
||||
const appliedCount = Object.keys(patch).length;
|
||||
|
||||
@@ -340,7 +340,11 @@ export async function copyPlainTextToClipboard(text) {
|
||||
document.body.appendChild(ta);
|
||||
ta.select?.();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove?.();
|
||||
if (typeof ta.remove === 'function') {
|
||||
ta.remove();
|
||||
} else {
|
||||
document.body.removeChild?.(ta);
|
||||
}
|
||||
return Boolean(ok);
|
||||
}
|
||||
} catch {
|
||||
@@ -348,3 +352,63 @@ export async function copyPlainTextToClipboard(text) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一的「已复制」临时反馈计时器控制器(自动重置定时器并在组件销毁时清理)。
|
||||
*
|
||||
* @param {{
|
||||
* durationMs?: number,
|
||||
* onChange?: (copiedKey: any) => void,
|
||||
* onCleanup?: (cleanupFn: () => void) => void,
|
||||
* }} [options={}]
|
||||
*/
|
||||
export function createCopiedFeedbackController({
|
||||
durationMs = 1800,
|
||||
onChange = null,
|
||||
onCleanup = null,
|
||||
} = {}) {
|
||||
let activeKey = null;
|
||||
let timer = null;
|
||||
let disposed = false;
|
||||
|
||||
function clear() {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
if (activeKey !== null) {
|
||||
activeKey = null;
|
||||
if (!disposed) onChange?.(null);
|
||||
}
|
||||
}
|
||||
|
||||
function trigger(key = true) {
|
||||
if (disposed) return;
|
||||
if (timer) clearTimeout(timer);
|
||||
activeKey = key;
|
||||
onChange?.(activeKey);
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
if (disposed) return;
|
||||
activeKey = null;
|
||||
onChange?.(null);
|
||||
}, durationMs);
|
||||
timer?.unref?.();
|
||||
}
|
||||
|
||||
onCleanup?.(() => {
|
||||
disposed = true;
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
activeKey = null;
|
||||
});
|
||||
|
||||
return {
|
||||
isCopied: (key = true) => activeKey === key,
|
||||
getActiveKey: () => activeKey,
|
||||
trigger,
|
||||
clear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -376,32 +376,35 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
.ui-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-search-wrap[hidden] {
|
||||
.ui-search-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap:focus-within {
|
||||
.ui-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.select-search-icon {
|
||||
.ui-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.select-search-input {
|
||||
.ui-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
@@ -414,11 +417,11 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.select-search-input::placeholder {
|
||||
.ui-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.select-search-clear {
|
||||
.ui-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -431,17 +434,27 @@
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-search-clear:hover {
|
||||
.ui-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-search-clear[hidden] {
|
||||
.ui-search-clear[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-options-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -750,6 +763,10 @@
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.segmented:hover .seg-glider,
|
||||
.segmented:focus-within .seg-glider {
|
||||
will-change: transform, width;
|
||||
}
|
||||
|
||||
@@ -807,6 +824,20 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.segmented--binary {
|
||||
--seg-pad: 0px;
|
||||
display: inline-grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.segmented--binary.has-glider > .seg-glider {
|
||||
top: var(--seg-pad, 0px);
|
||||
left: var(--seg-pad, 0px);
|
||||
width: calc((100% - 2 * var(--seg-pad, 0px) - 2px) / 2);
|
||||
height: calc(100% - 2 * var(--seg-pad, 0px));
|
||||
transform: translate3d(calc(var(--seg-active-idx, 0) * (100% + 2px)), 0, 0);
|
||||
}
|
||||
|
||||
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
@@ -866,10 +897,14 @@
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||
will-change: transform, height;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.custom-scroll-host:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
will-change: transform, height;
|
||||
}
|
||||
|
||||
.scrollbar-rail:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||
|
||||
@@ -193,6 +193,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .segmented {
|
||||
--seg-pad: 2px;
|
||||
padding: 2px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--modern-inline-track-bg);
|
||||
@@ -631,7 +632,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||
[data-modern-ui="true"] .collapsible-body,
|
||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||
[data-modern-ui="true"] .settings-account-entry,
|
||||
[data-modern-ui="true"] .dt-time-row {
|
||||
border-top: none;
|
||||
}
|
||||
@@ -671,8 +671,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
[data-modern-ui="true"] .number-input,
|
||||
[data-modern-ui="true"] .dt-trigger,
|
||||
[data-modern-ui="true"] .dt-mini-step,
|
||||
[data-modern-ui="true"] .settings-text-input,
|
||||
[data-modern-ui="true"] .settings-account-form input {
|
||||
[data-modern-ui="true"] .settings-text-input {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
transition:
|
||||
@@ -691,13 +690,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
|
||||
[data-modern-ui="true"] .number-input:focus-within,
|
||||
[data-modern-ui="true"] .settings-text-input:focus,
|
||||
[data-modern-ui="true"] .settings-account-form input:focus,
|
||||
[data-modern-ui="true"] .ui-search-wrap:focus-within,
|
||||
[data-modern-ui="true"] .smig-search-wrap:focus-within,
|
||||
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
||||
border: none;
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ui-search-wrap,
|
||||
[data-modern-ui="true"] .smig-search-wrap,
|
||||
[data-modern-ui="true"] .steps-search-wrap {
|
||||
border: none;
|
||||
|
||||
@@ -641,60 +641,6 @@
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-account-identity {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.settings-account-list,
|
||||
.settings-account-form,
|
||||
.settings-account-form label {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-list:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settings-account-entry {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) 0;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-account-form label {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.settings-account-form input {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
font: inherit;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-account-form button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.settings-account-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-quota {
|
||||
text-align: right;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
@@ -1067,69 +1013,9 @@
|
||||
}
|
||||
|
||||
.smig-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smig-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.smig-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.smig-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.smig-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.smig-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smig-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.smig-search-clear[hidden] {
|
||||
|
||||
@@ -1238,70 +1238,9 @@
|
||||
}
|
||||
|
||||
.steps-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex: 1 1 160px;
|
||||
min-width: 120px;
|
||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.steps-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.steps-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.steps-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.steps-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.steps-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.steps-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.steps-search-clear[hidden] {
|
||||
|
||||
@@ -538,6 +538,8 @@ export const ConsumptionView = defineComponent({
|
||||
});
|
||||
|
||||
let activeHoverTargetEl = null;
|
||||
let cachedBreakdownRootRect = null;
|
||||
let cachedBreakdownAnchorRect = null;
|
||||
|
||||
const popoverContent = createConsumptionBreakdownContent({
|
||||
showModelDot: true,
|
||||
@@ -550,6 +552,8 @@ export const ConsumptionView = defineComponent({
|
||||
);
|
||||
|
||||
function hideBreakdownPopover() {
|
||||
cachedBreakdownRootRect = null;
|
||||
cachedBreakdownAnchorRect = null;
|
||||
if (activeHoverTargetEl) {
|
||||
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
||||
activeHoverTargetEl = null;
|
||||
@@ -559,27 +563,29 @@ export const ConsumptionView = defineComponent({
|
||||
}
|
||||
|
||||
function positionBreakdownPopover(anchorEl, pointerClientX = null, pointerClientY = null) {
|
||||
const rootRect = rootEl.getBoundingClientRect?.() || {
|
||||
if (!cachedBreakdownRootRect) {
|
||||
cachedBreakdownRootRect = rootEl.getBoundingClientRect?.() || {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 360,
|
||||
height: 600,
|
||||
};
|
||||
const anchorRect = anchorEl?.getBoundingClientRect?.() || {
|
||||
}
|
||||
const rootRect = cachedBreakdownRootRect;
|
||||
if (!cachedBreakdownAnchorRect) {
|
||||
cachedBreakdownAnchorRect = anchorEl?.getBoundingClientRect?.() || {
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
};
|
||||
const tipRect = breakdownPopoverEl.getBoundingClientRect?.() || {
|
||||
width: 216,
|
||||
height: 108,
|
||||
};
|
||||
}
|
||||
const anchorRect = cachedBreakdownAnchorRect;
|
||||
const tipW = Number(breakdownPopoverEl.offsetWidth || 0) || 216;
|
||||
const tipH = Number(breakdownPopoverEl.offsetHeight || 0) || 108;
|
||||
const rootW = rootRect.width > 0 ? rootRect.width : 360;
|
||||
const rootH = rootRect.height > 0 ? rootRect.height : 600;
|
||||
const tipW = tipRect.width > 0 ? tipRect.width : 216;
|
||||
const tipH = tipRect.height > 0 ? tipRect.height : 108;
|
||||
|
||||
const hasPointerX = Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0;
|
||||
const hasPointerY = Number.isFinite(pointerClientY) && pointerClientY > 0 && rootRect.height > 0;
|
||||
@@ -625,6 +631,10 @@ export const ConsumptionView = defineComponent({
|
||||
}
|
||||
if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) {
|
||||
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
||||
cachedBreakdownAnchorRect = null;
|
||||
} else if (!activeHoverTargetEl) {
|
||||
cachedBreakdownRootRect = null;
|
||||
cachedBreakdownAnchorRect = null;
|
||||
}
|
||||
activeHoverTargetEl = anchorEl;
|
||||
patchClasses(anchorEl, { 'is-hovered': true });
|
||||
|
||||
@@ -74,6 +74,7 @@ import {
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { createSearchInput } from '../components/ui/SearchInput.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { StepTableWidget } from '../components/widgets/StepTableWidget.js';
|
||||
import { sortStepsByColumn } from '../registries/stepColumnRegistry.js';
|
||||
@@ -434,40 +435,30 @@ export const StepsDetailView = defineComponent({
|
||||
);
|
||||
|
||||
// --- 步骤搜索栏及快捷诊断芯片 ---
|
||||
const stepSearchClearBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'steps-search-clear',
|
||||
hidden: true,
|
||||
'aria-label': t('steps.searchClearAria'),
|
||||
onclick: () => {
|
||||
const stepSearchBox = createSearchInput({
|
||||
wrapClassName: 'steps-search-wrap',
|
||||
iconClassName: 'steps-search-icon',
|
||||
inputClassName: 'steps-search-input',
|
||||
clearClassName: 'steps-search-clear',
|
||||
placeholder: t('steps.searchPlaceholder'),
|
||||
ariaLabel: t('steps.searchPlaceholder'),
|
||||
clearAriaLabel: t('steps.searchClearAria'),
|
||||
closeIconSize: 11,
|
||||
onInput: (val) => {
|
||||
stepSearchQuery = String(val ?? '');
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
},
|
||||
onClear: () => {
|
||||
stepSearchQuery = '';
|
||||
stepSearchInput.value = '';
|
||||
patchAttr(stepSearchClearBtn, 'hidden', true);
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
stepSearchInput.focus?.();
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: 11 })]
|
||||
);
|
||||
const stepSearchInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'steps-search-input',
|
||||
placeholder: t('steps.searchPlaceholder'),
|
||||
'aria-label': t('steps.searchPlaceholder'),
|
||||
onInput: (e) => {
|
||||
stepSearchQuery = String(e?.target?.value ?? '');
|
||||
patchAttr(stepSearchClearBtn, 'hidden', !stepSearchQuery.trim());
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e?.key === 'Escape') {
|
||||
e.stopPropagation?.();
|
||||
if (stepSearchQuery) {
|
||||
stepSearchQuery = '';
|
||||
stepSearchInput.value = '';
|
||||
patchAttr(stepSearchClearBtn, 'hidden', true);
|
||||
stepSearchBox.setValue('');
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
} else {
|
||||
stepSearchInput.blur?.();
|
||||
@@ -475,11 +466,9 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
},
|
||||
});
|
||||
const stepSearchWrapEl = h('div', { className: 'steps-search-wrap' }, [
|
||||
createSvgIcon('search', { size: 12, className: 'steps-search-icon' }),
|
||||
stepSearchInput,
|
||||
stepSearchClearBtn,
|
||||
]);
|
||||
const stepSearchWrapEl = stepSearchBox.el;
|
||||
const stepSearchInput = stepSearchBox.inputEl;
|
||||
const stepSearchClearBtn = stepSearchBox.clearBtnEl;
|
||||
|
||||
const QUICK_CHIP_DEFS = [
|
||||
{ key: 'anomaly', i18nKey: 'steps.chipAnomaly', tone: 'is-warn' },
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
|
||||
|
||||
function getLanguageOptions() {
|
||||
return [
|
||||
@@ -42,13 +43,6 @@ function getFontScaleOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getModernUiOptions() {
|
||||
return [
|
||||
{ value: 'on', label: t('settings.gen.modernUiOn') },
|
||||
{ value: 'off', label: t('settings.gen.modernUiOff') },
|
||||
];
|
||||
}
|
||||
|
||||
function getUpdateModeOptions() {
|
||||
return [
|
||||
{ value: 'manual', label: t('settings.gen.updateManual') },
|
||||
@@ -216,10 +210,10 @@ export const SettingsGeneralTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const modernUiSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.modernUi'),
|
||||
const modernUiSwitch = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.gen.modernUi',
|
||||
preset: 'modernUi',
|
||||
modelValue: 'on',
|
||||
options: getModernUiOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextModernUi = val !== 'off';
|
||||
draftModernUi = nextModernUi;
|
||||
@@ -441,7 +435,6 @@ export const SettingsGeneralTab = defineComponent({
|
||||
});
|
||||
modernUiSwitch.setProps({
|
||||
modelValue: draftModernUi ? 'on' : 'off',
|
||||
options: getModernUiOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
@@ -523,9 +516,7 @@ export const SettingsGeneralTab = defineComponent({
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
modernUiSwitch.setProps({
|
||||
ariaLabel: t('settings.gen.modernUi'),
|
||||
modelValue: draftModernUi ? 'on' : 'off',
|
||||
options: getModernUiOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
|
||||
@@ -27,17 +27,10 @@ import {
|
||||
saveSettingsPatch,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
|
||||
import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js';
|
||||
import { SessionMigrationCard } from '../../components/settings/SessionMigrationCard.js';
|
||||
|
||||
function getEnableToggleOptions() {
|
||||
return [
|
||||
{ value: 'on', label: t('settings.str.on') },
|
||||
{ value: 'off', label: t('settings.str.off') },
|
||||
];
|
||||
}
|
||||
|
||||
function formatQuotaReservationLogForClipboard(snapshot) {
|
||||
const safe = snapshot && typeof snapshot === 'object' ? snapshot : {};
|
||||
const buckets = Array.isArray(safe.buckets) ? safe.buckets : [];
|
||||
@@ -275,16 +268,15 @@ export const SettingsOtherTab = defineComponent({
|
||||
[createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText]
|
||||
);
|
||||
|
||||
const quotaReserveToggle = SegmentedControl({
|
||||
const quotaReserveToggle = ToggleSwitch({
|
||||
modelValue: 'off',
|
||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabelKey: 'settings.oth.quotaReserveLabel',
|
||||
preset: 'enable',
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextEnabled = val === 'on';
|
||||
draftExperimentalQuotaReservation = nextEnabled;
|
||||
quotaReserveToggle.setProps({
|
||||
modelValue: nextEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
showExpFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
@@ -366,10 +358,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
const ctxMainToggle = SegmentedControl({
|
||||
const ctxMainToggle = ToggleSwitch({
|
||||
modelValue: 'on',
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabelKey: 'settings.oth.ctxMainLabel',
|
||||
preset: 'enable',
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
@@ -396,10 +388,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
const ctxSwarmToggle = SegmentedControl({
|
||||
const ctxSwarmToggle = ToggleSwitch({
|
||||
modelValue: 'off',
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabelKey: 'settings.oth.ctxSwarmLabel',
|
||||
preset: 'enable',
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
@@ -519,14 +511,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel'));
|
||||
ctxMainToggle.setProps({
|
||||
modelValue: draftContextMainEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel'));
|
||||
ctxSwarmToggle.setProps({
|
||||
modelValue: draftContextSwarmEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
|
||||
const syncErrorText =
|
||||
@@ -913,8 +901,6 @@ export const SettingsOtherTab = defineComponent({
|
||||
});
|
||||
quotaReserveToggle.setProps({
|
||||
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
||||
});
|
||||
renderContextWindows();
|
||||
void sessionMigrationCard.refs.ensureLoaded();
|
||||
@@ -933,8 +919,6 @@ export const SettingsOtherTab = defineComponent({
|
||||
patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn'));
|
||||
quotaReserveToggle.setProps({
|
||||
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
||||
});
|
||||
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
||||
renderContextWindows();
|
||||
|
||||
@@ -58,6 +58,7 @@ import { buildStructurePreviewTelemetry } from '../../components/settings/struct
|
||||
import { CustomNumberInput } from '../../components/ui/CustomNumberInput.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
|
||||
import {
|
||||
CapsuleBarWidget,
|
||||
buildCapsuleSlotContext,
|
||||
@@ -84,20 +85,6 @@ function getMountModeOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getMultiToggleOptions() {
|
||||
return [
|
||||
{ value: 'show', label: t('settings.str.show') },
|
||||
{ value: 'hide', label: t('settings.str.hide') },
|
||||
];
|
||||
}
|
||||
|
||||
function getEnableToggleOptions() {
|
||||
return [
|
||||
{ value: 'on', label: t('settings.str.on') },
|
||||
{ value: 'off', label: t('settings.str.off') },
|
||||
];
|
||||
}
|
||||
|
||||
function getPopoverWidthModeOptions() {
|
||||
return [
|
||||
{ value: 'auto', label: t('settings.str.popoverWidthAuto') },
|
||||
@@ -520,10 +507,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.multiToggle'),
|
||||
const multiSessionToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.multiToggle',
|
||||
preset: 'visibility',
|
||||
modelValue: 'show',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowTopbarMulti = val !== 'hide';
|
||||
syncMountSectionMeta();
|
||||
@@ -549,10 +536,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const cliCapsuleToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.cliCapsuleToggle'),
|
||||
const cliCapsuleToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.cliCapsuleToggle',
|
||||
preset: 'enable',
|
||||
modelValue: 'on',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftEnableCliStatusLine = val !== 'off';
|
||||
syncMountSectionMeta();
|
||||
@@ -783,7 +770,6 @@ export const SettingsStructureTab = defineComponent({
|
||||
}
|
||||
multiSessionToggle.setProps({
|
||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
contextAgentModeToggle.setProps({
|
||||
modelValue: draftContextAgentMode,
|
||||
@@ -794,7 +780,6 @@ export const SettingsStructureTab = defineComponent({
|
||||
patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled);
|
||||
cliCapsuleToggle.setProps({
|
||||
modelValue: draftEnableCliStatusLine ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine);
|
||||
const effectiveCliSlots = getEffectiveDraftCliSlots();
|
||||
@@ -1144,10 +1129,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
text: t('settings.str.stepsColsLabel'),
|
||||
});
|
||||
|
||||
const stepTurnRailToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepTurnRailToggle'),
|
||||
const stepTurnRailToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.stepTurnRailToggle',
|
||||
preset: 'visibility',
|
||||
modelValue: 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepTurnRail = val !== 'hide';
|
||||
syncStepsSectionMeta();
|
||||
@@ -1157,10 +1142,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const stepAgentBadgeToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepAgentBadgeToggle'),
|
||||
const stepAgentBadgeToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.stepAgentBadgeToggle',
|
||||
preset: 'visibility',
|
||||
modelValue: 'show',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepAgentBadge = val !== 'hide';
|
||||
syncStepsSectionMeta();
|
||||
@@ -1170,10 +1155,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const stepSpeedColorToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepSpeedColorToggle'),
|
||||
const stepSpeedColorToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.stepSpeedColorToggle',
|
||||
preset: 'enable',
|
||||
modelValue: 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepSpeedColor = val !== 'off';
|
||||
syncStepsSectionMeta();
|
||||
@@ -1183,10 +1168,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const stepFilterToolbarToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepFilterToolbarToggle'),
|
||||
const stepFilterToolbarToggle = ToggleSwitch({
|
||||
ariaLabelKey: 'settings.str.stepFilterToolbarToggle',
|
||||
preset: 'enable',
|
||||
modelValue: 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepFilterToolbar = val !== 'off';
|
||||
syncStepsSectionMeta();
|
||||
@@ -1365,19 +1350,15 @@ export const SettingsStructureTab = defineComponent({
|
||||
function syncStepsSectionMeta() {
|
||||
stepTurnRailToggle.setProps({
|
||||
modelValue: draftShowStepTurnRail ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
stepAgentBadgeToggle.setProps({
|
||||
modelValue: draftShowStepAgentBadge ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
stepSpeedColorToggle.setProps({
|
||||
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
stepFilterToolbarToggle.setProps({
|
||||
modelValue: draftShowStepFilterToolbar ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
if (document?.activeElement !== stepTokenComboInput) {
|
||||
stepTokenComboInput.value = rawStepTokenComboText;
|
||||
|
||||
+53
-193
@@ -775,32 +775,35 @@ html[data-standalone="true"] .app-shell {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
.ui-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-search-wrap[hidden] {
|
||||
.ui-search-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap:focus-within {
|
||||
.ui-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.select-search-icon {
|
||||
.ui-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.select-search-input {
|
||||
.ui-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
@@ -813,11 +816,11 @@ html[data-standalone="true"] .app-shell {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.select-search-input::placeholder {
|
||||
.ui-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.select-search-clear {
|
||||
.ui-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -830,17 +833,27 @@ html[data-standalone="true"] .app-shell {
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-search-clear:hover {
|
||||
.ui-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-search-clear[hidden] {
|
||||
.ui-search-clear[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-options-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1149,6 +1162,10 @@ html[data-standalone="true"] .app-shell {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.segmented:hover .seg-glider,
|
||||
.segmented:focus-within .seg-glider {
|
||||
will-change: transform, width;
|
||||
}
|
||||
|
||||
@@ -1206,6 +1223,20 @@ html[data-standalone="true"] .app-shell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.segmented--binary {
|
||||
--seg-pad: 0px;
|
||||
display: inline-grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.segmented--binary.has-glider > .seg-glider {
|
||||
top: var(--seg-pad, 0px);
|
||||
left: var(--seg-pad, 0px);
|
||||
width: calc((100% - 2 * var(--seg-pad, 0px) - 2px) / 2);
|
||||
height: calc(100% - 2 * var(--seg-pad, 0px));
|
||||
transform: translate3d(calc(var(--seg-active-idx, 0) * (100% + 2px)), 0, 0);
|
||||
}
|
||||
|
||||
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
@@ -1265,10 +1296,14 @@ html[data-standalone="true"] .app-shell {
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||
will-change: transform, height;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.custom-scroll-host:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
will-change: transform, height;
|
||||
}
|
||||
|
||||
.scrollbar-rail:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||
@@ -5076,70 +5111,9 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.steps-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex: 1 1 160px;
|
||||
min-width: 120px;
|
||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.steps-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.steps-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.steps-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.steps-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.steps-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.steps-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.steps-search-clear[hidden] {
|
||||
@@ -6124,60 +6098,6 @@ html[data-standalone="true"] .app-shell {
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-account-identity {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.settings-account-list,
|
||||
.settings-account-form,
|
||||
.settings-account-form label {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-list:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settings-account-entry {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) 0;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-account-form label {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.settings-account-form input {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
font: inherit;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-account-form button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.settings-account-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-quota {
|
||||
text-align: right;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
@@ -6550,69 +6470,9 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.smig-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
transition:
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smig-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.smig-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.smig-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.smig-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.smig-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smig-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.smig-search-clear[hidden] {
|
||||
@@ -8121,6 +7981,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .segmented {
|
||||
--seg-pad: 2px;
|
||||
padding: 2px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--modern-inline-track-bg);
|
||||
@@ -8559,7 +8420,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||
[data-modern-ui="true"] .collapsible-body,
|
||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||
[data-modern-ui="true"] .settings-account-entry,
|
||||
[data-modern-ui="true"] .dt-time-row {
|
||||
border-top: none;
|
||||
}
|
||||
@@ -8599,8 +8459,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
[data-modern-ui="true"] .number-input,
|
||||
[data-modern-ui="true"] .dt-trigger,
|
||||
[data-modern-ui="true"] .dt-mini-step,
|
||||
[data-modern-ui="true"] .settings-text-input,
|
||||
[data-modern-ui="true"] .settings-account-form input {
|
||||
[data-modern-ui="true"] .settings-text-input {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
transition:
|
||||
@@ -8619,13 +8478,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
|
||||
[data-modern-ui="true"] .number-input:focus-within,
|
||||
[data-modern-ui="true"] .settings-text-input:focus,
|
||||
[data-modern-ui="true"] .settings-account-form input:focus,
|
||||
[data-modern-ui="true"] .ui-search-wrap:focus-within,
|
||||
[data-modern-ui="true"] .smig-search-wrap:focus-within,
|
||||
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
||||
border: none;
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ui-search-wrap,
|
||||
[data-modern-ui="true"] .smig-search-wrap,
|
||||
[data-modern-ui="true"] .steps-search-wrap {
|
||||
border: none;
|
||||
|
||||
@@ -20,11 +20,15 @@ const BACKEND_MODULE_FILES = [
|
||||
'../shared/settings-normalization.mjs',
|
||||
'../shared/telemetry-display-rules.mjs',
|
||||
'../shared/window-bridge-protocol.mjs',
|
||||
'../shared/workspace-uri.mjs',
|
||||
'../shared/prompt-clean.mjs',
|
||||
'../backend/fs-atomic.mjs',
|
||||
'../backend/context-windows.mjs',
|
||||
'../backend/account-oauth.mjs',
|
||||
'../backend/account-switch.mjs',
|
||||
'../backend/http-helpers.mjs',
|
||||
'../backend/settings-schema.mjs',
|
||||
'../backend/trajectory-cache-store.mjs',
|
||||
'../backend/config.mjs',
|
||||
'../backend/endpoint-registry.mjs',
|
||||
'../backend/sqlite-client.mjs',
|
||||
@@ -88,18 +92,39 @@ export function backendHarness({
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,swarmMembers,swarmMembersMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1};
|
||||
const pendingTmpWrites = new Map();
|
||||
const commitSave = (p, s) => {
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({ path: p, data: parsed });
|
||||
if (norm.endsWith('settings.json')) {
|
||||
state.settings = parsed;
|
||||
}
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
|
||||
...(clock ? { Date: class extends Date {
|
||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||
static now() { return clock(); }
|
||||
} } : {}),
|
||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
process:{pid:12345,platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
cpSync:()=>{},
|
||||
rmSync:()=>{},
|
||||
renameSync:()=>{},
|
||||
unlinkSync:()=>{},
|
||||
renameSync:(from, to)=>{
|
||||
const key = String(from);
|
||||
if (pendingTmpWrites.has(key)) {
|
||||
const staged = pendingTmpWrites.get(key);
|
||||
pendingTmpWrites.delete(key);
|
||||
commitSave(to, staged);
|
||||
}
|
||||
},
|
||||
unlinkSync:(p)=>{
|
||||
pendingTmpWrites.delete(String(p));
|
||||
},
|
||||
execFile:execFileImpl || ((cmd,args,opts,cb)=>{
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
fn(new Error('execFile not mocked'));
|
||||
@@ -130,8 +155,9 @@ export function backendHarness({
|
||||
if (diskDirs && Array.isArray(diskDirs[norm])) return diskDirs[norm];
|
||||
return [];
|
||||
},
|
||||
statSync:p=>{
|
||||
statSync:(p, opts)=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (opts?.throwIfNoEntry === false && !ctx.existsSync(p)) return undefined;
|
||||
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||
const lines = m && state.transcripts?.[m[1]];
|
||||
@@ -171,18 +197,17 @@ export function backendHarness({
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||
if (norm.endsWith('/.git/config')) return String(state.gitConfigText || '');
|
||||
if (norm.endsWith('.ps1')) {
|
||||
return fs.readFileSync(new URL(`../backend/${path.basename(norm)}`, import.meta.url), 'utf8');
|
||||
}
|
||||
return JSON.stringify(cache);
|
||||
},
|
||||
writeFileSync:(p,s)=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({path:p,data:parsed});
|
||||
if (norm.endsWith('settings.json')) {
|
||||
state.settings = parsed;
|
||||
}
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
if (/\.tmp-\d+$/.test(String(p))) {
|
||||
pendingTmpWrites.set(String(p), s);
|
||||
return;
|
||||
}
|
||||
commitSave(p, s);
|
||||
},
|
||||
writeTrajectoryCacheFile:(p,data)=>{
|
||||
if (state.cacheWriteError) throw state.cacheWriteError;
|
||||
|
||||
@@ -585,7 +585,10 @@ test('bundle validation rejects incompatible imports and duplicate bindings befo
|
||||
const iconSource = join(tempDir, 'src', 'icons', 'svgRegistry.js');
|
||||
const original = fs.readFileSync(iconSource, 'utf8');
|
||||
for (const [prefix, error] of [
|
||||
["import { SVG_NS /* comment */ as ns } from './SvgIcon.js';", /svgRegistry\.js.*without aliases/],
|
||||
[
|
||||
"import * as ns from '../../shared/settings-normalization.mjs';",
|
||||
/svgRegistry\.js.*only named imports/,
|
||||
],
|
||||
["import { SVG_NS } from './SvgIcon.js';", /svgRegistry\.js.*SvgIcon\.js.*earlier in jsOrder/],
|
||||
["import './missing.js';", /svgRegistry\.js.*missing\.js.*earlier in jsOrder/],
|
||||
['export const SVG_NS = "duplicate";', /Identifier 'SVG_NS' has already been declared/],
|
||||
@@ -597,6 +600,13 @@ test('bundle validation rejects incompatible imports and duplicate bindings befo
|
||||
}
|
||||
}
|
||||
|
||||
// Named import aliases (`import { a as b }`) from earlier modules in jsOrder are supported inside the module IIFE
|
||||
fs.writeFileSync(
|
||||
iconSource,
|
||||
`import { normalizeStandalonePort /* comment */ as normPort } from '../../shared/settings-normalization.mjs';\nvoid normPort;\n${original}`
|
||||
);
|
||||
assert.doesNotThrow(() => buildBundle(tempDir));
|
||||
|
||||
// Per-module closure isolation: unexported private identifiers never collide across modules
|
||||
fs.writeFileSync(iconSource, `const SVG_NS = "private_local";\n${original}`);
|
||||
assert.doesNotThrow(() => buildBundle(tempDir));
|
||||
|
||||
@@ -2516,3 +2516,337 @@ test('P0 regression: V4 display-projected steps open inspector, preserve waterfa
|
||||
else process.env.ANTIGRAVITY_GEMINI_DIR = prevGemEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test('P1 regression: O(1) lowercase cache index, SQLite live-tail/parent helpers, lazy App mount, adoptedStyleSheets, rAF observer coalescing, and chart DOMRect caching', async (t) => {
|
||||
const {
|
||||
getCachedTrajectoryEntryByLower,
|
||||
removeCachedTrajectory,
|
||||
setCachedTrajectory,
|
||||
} = await import('../backend/config.mjs');
|
||||
const { mountWindowOverlay } = await import('../src/components/layout/WindowOverlayShell.js');
|
||||
const { WINDOW_BRIDGE_KEY } = await import('../shared/window-bridge-protocol.mjs');
|
||||
const { createSessionLineChart } = await import('../src/components/charts/SessionStepCharts.js');
|
||||
const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js');
|
||||
const { uiStore } = await import('../src/store/uiStore.js');
|
||||
const { telemetryStore } = await import('../src/store/telemetryStore.js');
|
||||
|
||||
// 1. O(1) case-insensitive trajectory cache index replaces mixed-case keys cleanly
|
||||
const upperId = 'ABCDEF12-3456-4789-8ABC-DEF123456789';
|
||||
const lowerId = upperId.toLowerCase();
|
||||
try {
|
||||
setCachedTrajectory(upperId, { signature: 'v1', steps: [{ stepIndex: 1 }] });
|
||||
const hit1 = getCachedTrajectoryEntryByLower(lowerId);
|
||||
assert.equal(hit1?.id, upperId);
|
||||
assert.equal(hit1?.entry?.steps?.length, 1);
|
||||
|
||||
setCachedTrajectory(lowerId, { signature: 'v2', steps: [{ stepIndex: 1 }, { stepIndex: 2 }] });
|
||||
const hit2 = getCachedTrajectoryEntryByLower(upperId);
|
||||
assert.equal(hit2?.id, lowerId);
|
||||
assert.equal(hit2?.entry?.steps?.length, 2);
|
||||
} finally {
|
||||
removeCachedTrajectory(upperId);
|
||||
removeCachedTrajectory(lowerId);
|
||||
}
|
||||
|
||||
// 2. WindowOverlayShell lazy App() mount, shared CSSStyleSheet, and rAF MutationObserver coalescing
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevRo = globalThis.ResizeObserver;
|
||||
const prevMo = globalThis.MutationObserver;
|
||||
const prevCssSheet = globalThis.CSSStyleSheet;
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
|
||||
const { document } = createMockDom();
|
||||
const origAttachShadow = document.createElement('div').constructor.prototype.attachShadow;
|
||||
globalThis.document = document;
|
||||
globalThis.ResizeObserver = class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
let bodyObserverCb = null;
|
||||
globalThis.MutationObserver = class {
|
||||
constructor(cb) {
|
||||
this.cb = cb;
|
||||
}
|
||||
observe(target, opts) {
|
||||
if (target === document.body && opts?.subtree) {
|
||||
bodyObserverCb = this.cb;
|
||||
}
|
||||
}
|
||||
disconnect() {}
|
||||
};
|
||||
class MockCSSStyleSheet {
|
||||
constructor() {
|
||||
this.cssText = '';
|
||||
}
|
||||
replaceSync(text) {
|
||||
this.cssText = text;
|
||||
}
|
||||
}
|
||||
globalThis.CSSStyleSheet = MockCSSStyleSheet;
|
||||
|
||||
// Give Mock ShadowRoots adoptedStyleSheets array support
|
||||
const sampleDiv = document.createElement('div');
|
||||
const proto = Object.getPrototypeOf(sampleDiv);
|
||||
proto.attachShadow = function (init) {
|
||||
const sr = origAttachShadow.call(this, init);
|
||||
sr.adoptedStyleSheets = [];
|
||||
return sr;
|
||||
};
|
||||
|
||||
const rafQueue = [];
|
||||
globalThis.window = {
|
||||
innerWidth: 1280,
|
||||
innerHeight: 800,
|
||||
[WINDOW_BRIDGE_KEY]: {
|
||||
port: 19888,
|
||||
token: 'p1-tok',
|
||||
bundleVersion: '1',
|
||||
stylesCss: '/* --- src/styles/tokens.css --- */\n:host { color: inherit; }',
|
||||
},
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
requestAnimationFrame: (fn) => {
|
||||
rafQueue.push(fn);
|
||||
return rafQueue.length;
|
||||
},
|
||||
cancelAnimationFrame: () => {},
|
||||
};
|
||||
|
||||
let ov = null;
|
||||
t.after(() => {
|
||||
ov?.dispose?.();
|
||||
proto.attachShadow = origAttachShadow;
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.ResizeObserver = prevRo;
|
||||
globalThis.MutationObserver = prevMo;
|
||||
globalThis.CSSStyleSheet = prevCssSheet;
|
||||
});
|
||||
|
||||
ov = mountWindowOverlay();
|
||||
const capsuleHost = document.getElementById('ag-usage-monitor-capsule');
|
||||
const portalHost = document.getElementById('ag-usage-monitor-portal');
|
||||
const popoverEl = portalHost.shadowRoot.querySelector('.wm-popover-panel');
|
||||
|
||||
// Cold start: App() is NOT mounted yet, and both ShadowRoots share the exact same CSSStyleSheet object!
|
||||
assert.equal(popoverEl.children.length, 0, 'App() stays unmounted on cold start');
|
||||
assert.equal(capsuleHost.shadowRoot.adoptedStyleSheets.length, 1);
|
||||
assert.equal(
|
||||
capsuleHost.shadowRoot.adoptedStyleSheets[0],
|
||||
portalHost.shadowRoot.adoptedStyleSheets[0],
|
||||
'Capsule and Portal ShadowRoots share single CSSStyleSheet instance'
|
||||
);
|
||||
|
||||
// Opening popover mounts App() on demand
|
||||
ov.open();
|
||||
assert.equal(popoverEl.children.length, 1, 'App() mounts immediately on first open()');
|
||||
|
||||
// 20 streaming DOM mutations coalesce into 0 synchronous scans and 1 rAF flush
|
||||
let qsCalls = 0;
|
||||
const origQs = document.querySelector.bind(document);
|
||||
document.querySelector = (s) => {
|
||||
qsCalls += 1;
|
||||
return origQs(s);
|
||||
};
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
bodyObserverCb?.([{ target: document.body, type: 'childList' }]);
|
||||
}
|
||||
assert.equal(qsCalls, 0, 'Zero synchronous DOM queries during streaming burst');
|
||||
while (rafQueue.length > 0) rafQueue.shift()();
|
||||
assert.ok(qsCalls > 0 && qsCalls <= 10, `Coalesced into single frame check (calls=${qsCalls})`);
|
||||
document.querySelector = origQs;
|
||||
|
||||
// 3. Chart mousemove DOMRect caching & preSig fast path
|
||||
const stepChart = createSessionLineChart();
|
||||
document.body.appendChild(stepChart.el);
|
||||
let stepBcr = 0;
|
||||
const stepSvg = stepChart.el.querySelector('svg');
|
||||
stepSvg.getBoundingClientRect = () => {
|
||||
stepBcr += 1;
|
||||
return { left: 0, top: 0, width: 400, height: 140 };
|
||||
};
|
||||
const stepData = [
|
||||
{ stepIndex: 1, modelShort: '4-neon', tokPerSec: 60, outputTokens: 120, inputTokens: 1000, cacheReadTokens: 2000 },
|
||||
{ stepIndex: 2, modelShort: '4-neon', tokPerSec: 80, outputTokens: 160, inputTokens: 1100, cacheReadTokens: 2200 },
|
||||
];
|
||||
const r1 = stepChart.update({ steps: stepData, metric: 'tps' });
|
||||
const r2 = stepChart.update({ steps: stepData, metric: 'tps' });
|
||||
assert.equal(r1.summaryBadge, r2.summaryBadge, 'preSig fast-path preserves summaryBadge');
|
||||
stepBcr = 0;
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
stepSvg.parentNode.dispatchEvent({ type: 'mousemove', clientX: 40 + i * 5, clientY: 50 });
|
||||
}
|
||||
assert.equal(stepBcr, 1, 'SessionLineChart caches SVG DOMRect across mousemove burst');
|
||||
stepSvg.parentNode.dispatchEvent({ type: 'mouseleave' });
|
||||
stepSvg.parentNode.dispatchEvent({ type: 'mousemove', clientX: 60, clientY: 50 });
|
||||
assert.equal(stepBcr, 2, 'mouseleave invalidates cached SVG DOMRect cleanly');
|
||||
stepChart.destroy();
|
||||
|
||||
const trendChart = createTrendAreaChart();
|
||||
document.body.appendChild(trendChart.el);
|
||||
let trendBcr = 0;
|
||||
const rectStub = () => {
|
||||
trendBcr += 1;
|
||||
return { left: 0, top: 0, width: 400, height: 140 };
|
||||
};
|
||||
trendChart.el.getBoundingClientRect = rectStub;
|
||||
const trendSvg = trendChart.el.querySelector('svg');
|
||||
trendSvg.getBoundingClientRect = rectStub;
|
||||
trendChart.update({
|
||||
series: [
|
||||
{ label: '10:00', fullLabel: '10:00', tokens: 5000, calls: 1 },
|
||||
{ label: '11:00', fullLabel: '11:00', tokens: 8000, calls: 2 },
|
||||
],
|
||||
rangeKey: '24h',
|
||||
});
|
||||
trendBcr = 0;
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
trendSvg.parentNode.dispatchEvent({ type: 'mousemove', clientX: 30 + i * 5, clientY: 50 });
|
||||
}
|
||||
assert.equal(trendBcr, 2, 'TrendAreaChart caches svgRect and wrapRect across mousemove burst');
|
||||
trendChart.destroy();
|
||||
});
|
||||
|
||||
test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic primitives, zero-ResizeObserver ToggleSwitch, SearchInput, and declarative settingsBackup parity', async (t) => {
|
||||
const [{ stripModuleSyntax }, { decodeWorkspaceFileUriToPath, parseWorkspaceUrisColumn }, { extractShortPromptTitle }, { writeJsonAtomicSync }] =
|
||||
await Promise.all([
|
||||
import('../scripts/build-bundle.mjs'),
|
||||
import('../shared/workspace-uri.mjs'),
|
||||
import('../shared/prompt-clean.mjs'),
|
||||
import('../backend/fs-atomic.mjs'),
|
||||
]);
|
||||
|
||||
// 1. Bundler lexer handles regex literals with unbalanced braces after if/while/for-await parens
|
||||
const sampleMod = [
|
||||
'export function f(c, s) { if (c) /a{b/.test(s); }',
|
||||
'export const afterFn = 42;',
|
||||
'export function g(x) { while (x) /c}d/.test(x); }',
|
||||
'export const afterG = 99;',
|
||||
'export async function h(it) { for await (const x of it) /e{f/.test(x); }',
|
||||
'export const divOk = (10 + 2) / (3 + 1);',
|
||||
'const localHidden = 7;',
|
||||
'export { localHidden as publicAlias };',
|
||||
].join('\n');
|
||||
const recordedExports = [];
|
||||
const stripped = stripModuleSyntax(sampleMod, null, (exported, isClause, local) => {
|
||||
recordedExports.push({ exported, isClause, local });
|
||||
});
|
||||
assert.equal(/\bexport\b/.test(stripped), false, 'no raw export keyword remains after regex-after-paren');
|
||||
assert.deepEqual(
|
||||
recordedExports.find((e) => e.exported === 'publicAlias'),
|
||||
{ exported: 'publicAlias', isClause: true, local: 'localHidden' }
|
||||
);
|
||||
|
||||
// 2. Shared workspace URI & prompt cleaner & atomic JSON writer
|
||||
assert.equal(decodeWorkspaceFileUriToPath('file:///f%3A/ppt/demo/'), 'f:/ppt/demo');
|
||||
assert.equal(decodeWorkspaceFileUriToPath('file:///Users/dev/app/'), '/Users/dev/app');
|
||||
assert.deepEqual(parseWorkspaceUrisColumn('["file:///f%3A/ppt/a",""]'), ['file:///f%3A/ppt/a']);
|
||||
assert.equal(
|
||||
extractShortPromptTitle(
|
||||
'<CONTEXT_SUMMARY>old</CONTEXT_SUMMARY><USER_REQUEST>继续P2\n优化代码</USER_REQUEST><ADDITIONAL_METADATA>t</ADDITIONAL_METADATA>',
|
||||
48,
|
||||
{ firstLineOnly: true }
|
||||
),
|
||||
'继续P2'
|
||||
);
|
||||
const fsCalls = [];
|
||||
writeJsonAtomicSync('/cfg/settings.json', { ok: true }, {
|
||||
fsOps: {
|
||||
mkdirFn: () => fsCalls.push('mkdir'),
|
||||
writeFn: (p) => fsCalls.push(`write:${p.endsWith('.json') ? 'direct' : 'tmp'}`),
|
||||
renameFn: () => fsCalls.push('rename'),
|
||||
unlinkFn: () => fsCalls.push('unlink'),
|
||||
},
|
||||
});
|
||||
assert.deepEqual(fsCalls, ['mkdir', 'write:tmp', 'rename']);
|
||||
|
||||
// 3. ToggleSwitch creates 0 ResizeObservers & SearchInput wires clear/input cleanly
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevRO = globalThis.ResizeObserver;
|
||||
const { document } = createMockDom();
|
||||
let roCreated = 0;
|
||||
globalThis.document = document;
|
||||
globalThis.window = { document, addEventListener() {}, removeEventListener() {} };
|
||||
globalThis.ResizeObserver = class {
|
||||
constructor() {
|
||||
roCreated += 1;
|
||||
}
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.ResizeObserver = prevRO;
|
||||
});
|
||||
|
||||
const [{ ToggleSwitch }, { createSearchInput }, { buildExportableSettingsJson, parseImportedSettingsJson }] =
|
||||
await Promise.all([
|
||||
import('../src/components/ui/ToggleSwitch.js'),
|
||||
import('../src/components/ui/SearchInput.js'),
|
||||
import('../src/core/settingsBackup.js'),
|
||||
]);
|
||||
|
||||
let toggledVal = 'off';
|
||||
const sw = ToggleSwitch({
|
||||
preset: 'enable',
|
||||
modelValue: 'off',
|
||||
onUpdateModelValue: (v) => {
|
||||
toggledVal = v;
|
||||
},
|
||||
});
|
||||
assert.equal(roCreated, 0, 'ToggleSwitch must not allocate any ResizeObserver');
|
||||
assert.equal(sw.el.style.getPropertyValue('--seg-active-idx'), '1');
|
||||
sw.el.querySelectorAll('.seg-btn')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(toggledVal, 'on');
|
||||
assert.equal(sw.el.style.getPropertyValue('--seg-active-idx'), '0');
|
||||
sw.destroy();
|
||||
|
||||
let latestQuery = '';
|
||||
const sBox = createSearchInput({
|
||||
wrapClassName: 'steps-search-wrap',
|
||||
placeholder: 'Search',
|
||||
onInput: (v) => {
|
||||
latestQuery = v;
|
||||
},
|
||||
});
|
||||
sBox.inputEl.value = '429';
|
||||
sBox.inputEl.dispatchEvent({ type: 'input', target: sBox.inputEl });
|
||||
assert.equal(latestQuery, '429');
|
||||
assert.equal(sBox.clearBtnEl.hasAttribute('hidden'), false);
|
||||
sBox.clearBtnEl.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(latestQuery, '');
|
||||
assert.equal(sBox.clearBtnEl.hasAttribute('hidden'), true);
|
||||
|
||||
// 4. Declarative settingsBackup round-trips all 30 portable keys + coupled legacy flags
|
||||
const exported = buildExportableSettingsJson({
|
||||
language: 'en-US',
|
||||
modernUi: false,
|
||||
modelDisplayMode: 'upstream_compact',
|
||||
pluginUpdateMode: 'auto',
|
||||
windowMountMode: 'composer',
|
||||
showStepFilterToolbar: true,
|
||||
experimentalQuotaReservation: true,
|
||||
});
|
||||
const parsedExport = JSON.parse(exported);
|
||||
assert.equal(Object.keys(parsedExport.settings).length, 30);
|
||||
const reimported = parseImportedSettingsJson(exported);
|
||||
assert.equal(reimported.ok, true);
|
||||
assert.equal(reimported.patch.modernUi, false);
|
||||
assert.equal(reimported.patch.experimentalModernUi, false);
|
||||
assert.equal(reimported.patch.modelDisplayMode, 'upstream_compact');
|
||||
assert.equal(reimported.patch.showUpstreamModel, true);
|
||||
assert.equal(reimported.patch.pluginUpdateMode, 'auto');
|
||||
assert.equal(reimported.patch.autoUpdatePlugin, true);
|
||||
assert.equal(reimported.patch.windowMountMode, 'composer');
|
||||
assert.equal(reimported.patch.enableWindowOverlay, true);
|
||||
assert.equal(reimported.patch.showStepFilterToolbar, true);
|
||||
assert.equal(reimported.patch.experimentalQuotaReservation, true);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* 2. 严禁基于速率上限裁剪异常值或动态篡改分母(如扣除思考时间或仅取流式片段耗时),保证统计口径客观一致。
|
||||
*/
|
||||
|
||||
import { extractCleanUserRequestBody } from './shared/prompt-clean.mjs';
|
||||
|
||||
/** 速度测量口径版本号;当耗时或样本过滤算法变更时递增,用于触发旧版缓存测量字段失效重算 */
|
||||
export const MEASUREMENT_VERSION = 4;
|
||||
|
||||
@@ -1020,14 +1022,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
} else if (typeof step?.content === 'string' && step.content.trim()) {
|
||||
const withoutSummary = step.content
|
||||
.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)];
|
||||
raw =
|
||||
reqMatches.length > 0
|
||||
? reqMatches[reqMatches.length - 1][1]
|
||||
: withoutSummary.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
raw = extractCleanUserRequestBody(step.content);
|
||||
}
|
||||
const cleaned = String(raw || '')
|
||||
.split(/\r?\n/)
|
||||
|
||||
Reference in New Issue
Block a user