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 { existsSync, readFileSync } from 'node:fs';
|
||||||
import { basename, join } from 'node:path';
|
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 { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||||
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
|
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
|
||||||
import {
|
import {
|
||||||
@@ -611,22 +613,7 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
|||||||
? decoded.annotations.sideQuestionCascadeIds
|
? decoded.annotations.sideQuestionCascadeIds
|
||||||
: [];
|
: [];
|
||||||
const sideQuestionTitles = decoded?.annotations?.sideQuestionTitles || {};
|
const sideQuestionTitles = decoded?.annotations?.sideQuestionTitles || {};
|
||||||
let workspaceUri = '';
|
const workspaceUri = parseWorkspaceUrisColumn(row?.workspace_uris)[0] || '';
|
||||||
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 entry = {
|
const entry = {
|
||||||
cascadeId: cidLower,
|
cascadeId: cidLower,
|
||||||
@@ -1687,15 +1674,7 @@ function mapRunningGenericToolStepType(rawToolName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function cleanShortPromptTitle(rawText, maxChars = 80) {
|
function cleanShortPromptTitle(rawText, maxChars = 80) {
|
||||||
const withoutTags = String(rawText || '')
|
return extractShortPromptTitle(rawText, maxChars);
|
||||||
.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()}…`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasContextBreakdownPayload(chat) {
|
function hasContextBreakdownPayload(chat) {
|
||||||
@@ -2040,3 +2019,189 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
|||||||
return null;
|
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 宽度计算)。
|
* 避免深色背景色块突兀及 OSC 序列干扰 Bubble Tea 宽度计算)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { delimiter, dirname, join } from 'node:path';
|
import { delimiter, dirname, join } from 'node:path';
|
||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { writeTextFileAtomicSync } from './fs-atomic.mjs';
|
||||||
import {
|
import {
|
||||||
HERE,
|
HERE,
|
||||||
lsRuntimeEndpoint,
|
lsRuntimeEndpoint,
|
||||||
@@ -503,18 +504,7 @@ export function ensureCliStatusLineConfigured({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const serialized = `${JSON.stringify(applied.object, null, 2).replace(/\n/g, eol)}${eol}`;
|
const serialized = `${JSON.stringify(applied.object, null, 2).replace(/\n/g, eol)}${eol}`;
|
||||||
const tmpPath = `${settingsPath}.tmp-${process.pid}`;
|
writeTextFileAtomicSync(settingsPath, serialized);
|
||||||
try {
|
|
||||||
writeFileSync(tmpPath, serialized, 'utf8');
|
|
||||||
renameSync(tmpPath, settingsPath);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
if (existsSync(tmpPath)) unlinkSync(tmpPath);
|
|
||||||
} catch {
|
|
||||||
// 忽略临时文件清理异常
|
|
||||||
}
|
|
||||||
writeFileSync(settingsPath, serialized, 'utf8');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
checked: true,
|
checked: true,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ async function loadCcProxyNodeModules() {
|
|||||||
https: httpsMod.default || httpsMod,
|
https: httpsMod.default || httpsMod,
|
||||||
tls: tlsMod.default || tlsMod,
|
tls: tlsMod.default || tlsMod,
|
||||||
zlib: zlibMod.default || zlibMod,
|
zlib: zlibMod.default || zlibMod,
|
||||||
execFileSync: cpMod.execFileSync,
|
execFile: cpMod.execFile,
|
||||||
openSync: fsMod.openSync,
|
openSync: fsMod.openSync,
|
||||||
readSync: fsMod.readSync,
|
readSync: fsMod.readSync,
|
||||||
closeSync: fsMod.closeSync,
|
closeSync: fsMod.closeSync,
|
||||||
@@ -187,6 +187,47 @@ function parseWindowsProxyServerValue(rawVal) {
|
|||||||
return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`;
|
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 } = {}) {
|
export async function detectSystemHttpsProxy(targetHostname = '', { env = process.env, platform = process.platform } = {}) {
|
||||||
const noProxy = env?.NO_PROXY || env?.no_proxy || '';
|
const noProxy = env?.NO_PROXY || env?.no_proxy || '';
|
||||||
if (shouldCcProxyBypassHost(targetHostname, noProxy)) return '';
|
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 (envProxy) return /^https?:\/\//i.test(envProxy) ? envProxy : `http://${envProxy}`;
|
||||||
if (platform !== 'win32') return '';
|
if (platform !== 'win32') return '';
|
||||||
try {
|
try {
|
||||||
const { execFileSync } = await loadCcProxyNodeModules();
|
const out = await readWindowsInternetSettingsAsync();
|
||||||
const out = execFileSync(
|
if (!out || !/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(out)) return '';
|
||||||
'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 overrideMatch = out.match(/ProxyOverride\s+REG_SZ\s+([^\r\n]+)/i);
|
const overrideMatch = out.match(/ProxyOverride\s+REG_SZ\s+([^\r\n]+)/i);
|
||||||
if (overrideMatch && shouldCcProxyBypassHost(targetHostname, overrideMatch[1])) {
|
if (overrideMatch && shouldCcProxyBypassHost(targetHostname, overrideMatch[1])) {
|
||||||
return '';
|
return '';
|
||||||
|
|||||||
@@ -8,14 +8,21 @@
|
|||||||
* 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。
|
* 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 { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
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 { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||||
|
import {
|
||||||
|
CACHE_RUNNING_SAVE_INTERVAL_MS,
|
||||||
|
createTrajectoryCacheStore,
|
||||||
|
} from './trajectory-cache-store.mjs';
|
||||||
import { normalizeFullSettings } from './settings-schema.mjs';
|
import { normalizeFullSettings } from './settings-schema.mjs';
|
||||||
|
|
||||||
|
export { CACHE_RUNNING_SAVE_INTERVAL_MS, isPlainObject };
|
||||||
|
|
||||||
export {
|
export {
|
||||||
CLI_STATUSLINE_PRESETS,
|
CLI_STATUSLINE_PRESETS,
|
||||||
CONTEXT_AGENT_MODES,
|
CONTEXT_AGENT_MODES,
|
||||||
@@ -290,16 +297,6 @@ export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
|||||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
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`。
|
* 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。
|
||||||
*
|
*
|
||||||
@@ -329,7 +326,7 @@ export function saveJson(filePath, data) {
|
|||||||
if (filePath === CACHE_FILE) {
|
if (filePath === CACHE_FILE) {
|
||||||
writeTrajectoryCacheFile(filePath, data);
|
writeTrajectoryCacheFile(filePath, data);
|
||||||
} else {
|
} else {
|
||||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
writeJsonAtomicSync(filePath, data);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -355,12 +352,22 @@ export function roundMetric(value) {
|
|||||||
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
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}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function computeRuntimeCodeVersion() {
|
export function computeRuntimeCodeVersion(options = {}) {
|
||||||
|
const nowMs = Date.now();
|
||||||
|
if (!options?.force && cachedRuntimeCodeVersion && nowMs < cachedRuntimeCodeVersionExpiresAt) {
|
||||||
|
return cachedRuntimeCodeVersion;
|
||||||
|
}
|
||||||
let maxMtime = 0;
|
let maxMtime = 0;
|
||||||
const candidates = [
|
const candidates = [
|
||||||
join(HERE, 'app.js'),
|
join(HERE, 'app.js'),
|
||||||
@@ -389,168 +396,66 @@ export function computeRuntimeCodeVersion() {
|
|||||||
}
|
}
|
||||||
for (const file of candidates) {
|
for (const file of candidates) {
|
||||||
try {
|
try {
|
||||||
if (existsSync(file)) {
|
const st = statSync(file, { throwIfNoEntry: false });
|
||||||
const mtime = Math.floor(statSync(file).mtimeMs || 0);
|
if (st) {
|
||||||
|
const mtime = Math.floor(st.mtimeMs || 0);
|
||||||
if (mtime > maxMtime) maxMtime = mtime;
|
if (mtime > maxMtime) maxMtime = mtime;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略单文件 stat 异常
|
// 忽略单文件 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);
|
const localTrajectoryCacheStore = createTrajectoryCacheStore({
|
||||||
if (isPlainObject(loadedTrajectoryCache)) {
|
cacheFilePath: CACHE_FILE,
|
||||||
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
|
loadJsonFn: loadJson,
|
||||||
if (!id || !isPlainObject(entry)) {
|
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
|
||||||
initialCacheMigrated = true;
|
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||||
continue;
|
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||||
}
|
registerExitHook: true,
|
||||||
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
});
|
||||||
if (!Array.isArray(entry.steps)) {
|
|
||||||
initialCacheMigrated = true;
|
|
||||||
}
|
|
||||||
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
|
|
||||||
if (objectSteps.length !== rawSteps.length) {
|
|
||||||
initialCacheMigrated = true;
|
|
||||||
}
|
|
||||||
const normalizedSteps = objectSteps.map((s) => {
|
|
||||||
const norm = normalizeCachedStep(s);
|
|
||||||
if (norm !== s) initialCacheMigrated = true;
|
|
||||||
return norm;
|
|
||||||
});
|
|
||||||
const finalSteps = inferCompactionStepModels(normalizedSteps);
|
|
||||||
for (let i = 0; i < finalSteps.length; i++) {
|
|
||||||
if (finalSteps[i] !== normalizedSteps[i]) {
|
|
||||||
initialCacheMigrated = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
trajectoryCache[id] = { ...entry, steps: finalSteps };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getCachedTrajectory(cascadeId) {
|
export function getCachedTrajectory(cascadeId) {
|
||||||
return trajectoryCache[cascadeId];
|
return localTrajectoryCacheStore.getCachedTrajectory(cascadeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedTrajectoryEntryByLower(cascadeId) {
|
||||||
|
return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listCachedTrajectoryEntries() {
|
export function listCachedTrajectoryEntries() {
|
||||||
return Object.entries(trajectoryCache);
|
return localTrajectoryCacheStore.listCachedTrajectoryEntries();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setCachedTrajectory(cascadeId, entry) {
|
export function setCachedTrajectory(cascadeId, entry) {
|
||||||
trajectoryCache[cascadeId] = entry;
|
localTrajectoryCacheStore.setCachedTrajectory(cascadeId, entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeCachedTrajectory(cascadeId) {
|
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() {
|
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() {
|
export function flushTrajectoryCacheNow() {
|
||||||
cancelPendingCacheFlushTimer();
|
return localTrajectoryCacheStore.flushTrajectoryCacheNow();
|
||||||
const ok = saveJson(CACHE_FILE, trajectoryCache);
|
|
||||||
cacheState.needsSave = !ok;
|
|
||||||
if (ok) {
|
|
||||||
cacheState.lastSavedAtMs = Date.now();
|
|
||||||
}
|
|
||||||
return ok;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export function persistTrajectoryCacheIfNeeded(options = {}) {
|
||||||
* 按当前是否存在运行中会话决定立即写盘还是 30 秒节流延迟写盘。
|
localTrajectoryCacheStore.persistTrajectoryCacheIfNeeded(options);
|
||||||
* 默认单元测试沙箱(`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 const externalDeepStatsMemo = {
|
export const externalDeepStatsMemo = {
|
||||||
@@ -614,13 +519,7 @@ export const pluginUpdateState = {
|
|||||||
* @returns {boolean} 是否成功写回空白缓存文件
|
* @returns {boolean} 是否成功写回空白缓存文件
|
||||||
*/
|
*/
|
||||||
export function clearRuntimeCaches() {
|
export function clearRuntimeCaches() {
|
||||||
if (!saveJson(CACHE_FILE, {})) return false;
|
if (!localTrajectoryCacheStore.clearCache()) return false;
|
||||||
cancelPendingCacheFlushTimer();
|
|
||||||
for (const key of Object.keys(trajectoryCache)) {
|
|
||||||
delete trajectoryCache[key];
|
|
||||||
}
|
|
||||||
cacheState.needsSave = false;
|
|
||||||
cacheState.lastSavedAtMs = 0;
|
|
||||||
externalDeepStatsMemo.sig = '';
|
externalDeepStatsMemo.sig = '';
|
||||||
externalDeepStatsMemo.convos.clear();
|
externalDeepStatsMemo.convos.clear();
|
||||||
localSummaryMemo.sig = '';
|
localSummaryMemo.sig = '';
|
||||||
|
|||||||
@@ -34,7 +34,8 @@ import {
|
|||||||
} from 'node:fs';
|
} from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { basename, dirname, join, win32 as pathWin32 } from 'node:path';
|
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';
|
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) {
|
function writeTextFileAtomically(filePath, content, fsOps) {
|
||||||
const { mkdirFn, writeFn, renameFn, unlinkFn } = fsOps;
|
writeTextFileAtomicSync(filePath, content, 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');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -769,293 +757,18 @@ export function probeWindowsShortcutsFast({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const WIN_SHORTCUT_PROVISION_PS = `
|
let cachedWinShortcutProvisionPs = '';
|
||||||
[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]
|
function getWinShortcutProvisionPs() {
|
||||||
$seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
if (!cachedWinShortcutProvisionPs) {
|
||||||
|
cachedWinShortcutProvisionPs = readFileSync(
|
||||||
function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir, [bool]$recordDiscovered) {
|
join(HERE, 'backend', 'windows-shortcut-provision.ps1'),
|
||||||
if (-not $dirPath) { return }
|
'utf8'
|
||||||
if (-not $seenScanDir.Add($dirPath)) { return }
|
).trim();
|
||||||
$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 {}
|
|
||||||
}
|
}
|
||||||
|
return cachedWinShortcutProvisionPs;
|
||||||
}
|
}
|
||||||
|
|
||||||
Add-ScanDir $userDesktopDir $false 'desktop' $false $true
|
|
||||||
foreach ($d in @(
|
|
||||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }),
|
|
||||||
$(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' })
|
|
||||||
)) {
|
|
||||||
Add-ScanDir $d $false 'desktop' $false $false
|
|
||||||
}
|
|
||||||
foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) {
|
|
||||||
if ($od) {
|
|
||||||
Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false $false
|
|
||||||
Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false $false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Add-ScanDir $userProgramsDir $false 'programs' $true $true
|
|
||||||
Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false $false
|
|
||||||
Add-ScanDir $userStartupDir $false 'startup' $false $true
|
|
||||||
if ($env:APPDATA) {
|
|
||||||
Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false $false
|
|
||||||
}
|
|
||||||
Add-ScanDir $commonDesktopDir $true 'desktop' $false $true
|
|
||||||
Add-ScanDir $commonProgramsDir $true 'programs' $true $true
|
|
||||||
|
|
||||||
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
|
||||||
foreach ($spec in $flatSpecs) {
|
|
||||||
$dir = [string]$spec.Dir
|
|
||||||
$items = @()
|
|
||||||
try {
|
|
||||||
$items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue)
|
|
||||||
} catch { continue }
|
|
||||||
|
|
||||||
foreach ($item in $items) {
|
|
||||||
if ($item.Length -lt 32 -or $item.Length -gt 65536) { continue }
|
|
||||||
$lnkPath = [string]$item.FullName
|
|
||||||
if (-not $seen.Add($lnkPath)) { continue }
|
|
||||||
try {
|
|
||||||
$rawBytes = [System.IO.File]::ReadAllBytes($lnkPath)
|
|
||||||
$u16 = [System.Text.Encoding]::Unicode.GetString($rawBytes)
|
|
||||||
$lat = [System.Text.Encoding]::GetEncoding(28591).GetString($rawBytes)
|
|
||||||
if ($u16.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0 -and
|
|
||||||
$lat.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }
|
|
||||||
$sc = $ws.CreateShortcut($lnkPath)
|
|
||||||
$target = [string]$sc.TargetPath
|
|
||||||
if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue }
|
|
||||||
$curArgs = [string]$sc.Arguments
|
|
||||||
if ($enableFlag) {
|
|
||||||
if ($curArgs -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($lnkPath)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$nextArgs = ($curArgs.Trim() + ' --remote-debugging-port=0').Trim()
|
|
||||||
try {
|
|
||||||
$sc.Arguments = $nextArgs
|
|
||||||
$sc.Save()
|
|
||||||
$updated.Add($lnkPath)
|
|
||||||
$configured.Add($lnkPath)
|
|
||||||
} catch {
|
|
||||||
$readOnly.Add($lnkPath)
|
|
||||||
if ($spec.IsCommon -and $spec.Kind -eq 'programs' -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir -ErrorAction SilentlyContinue)) {
|
|
||||||
$fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath))
|
|
||||||
if (-not (Test-Path -LiteralPath $fallbackLnk -ErrorAction SilentlyContinue)) {
|
|
||||||
try {
|
|
||||||
$uSc = $ws.CreateShortcut($fallbackLnk)
|
|
||||||
$uSc.TargetPath = $target
|
|
||||||
$uSc.Arguments = $nextArgs
|
|
||||||
if ($sc.WorkingDirectory) { $uSc.WorkingDirectory = $sc.WorkingDirectory }
|
|
||||||
if ($sc.IconLocation) { $uSc.IconLocation = $sc.IconLocation }
|
|
||||||
if ($sc.Description) { $uSc.Description = $sc.Description }
|
|
||||||
$uSc.Save()
|
|
||||||
$updated.Add($fallbackLnk)
|
|
||||||
$configured.Add($fallbackLnk)
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$stripped = ([regex]::Replace($curArgs, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
|
||||||
if ($stripped -ne $curArgs.Trim()) {
|
|
||||||
try {
|
|
||||||
$sc.Arguments = $stripped
|
|
||||||
$sc.Save()
|
|
||||||
$updated.Add($lnkPath)
|
|
||||||
} catch {
|
|
||||||
$readOnly.Add($lnkPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($lnkPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$runTargets = @(
|
|
||||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' },
|
|
||||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' },
|
|
||||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run' }
|
|
||||||
)
|
|
||||||
foreach ($rt in $runTargets) {
|
|
||||||
try {
|
|
||||||
$runReadKey = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
|
||||||
if (-not $runReadKey) { continue }
|
|
||||||
$runNames = @($runReadKey.GetValueNames())
|
|
||||||
$runReadKey.Close()
|
|
||||||
foreach ($valName in $runNames) {
|
|
||||||
$rk = $rt.Root.OpenSubKey($rt.SubPath, $false)
|
|
||||||
if (-not $rk) { continue }
|
|
||||||
$rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
|
||||||
$rk.Close()
|
|
||||||
if (-not $rawCmd) { continue }
|
|
||||||
if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue }
|
|
||||||
$exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
|
||||||
$restPart = [string]$Matches[3]
|
|
||||||
if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue }
|
|
||||||
$quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate }
|
|
||||||
$entryId = if ($rt.Label -eq 'HKLM') { "HKLM:Run:$($rt.SubPath)|$valName" } else { "HKCU:Run:$valName" }
|
|
||||||
if ($enableFlag) {
|
|
||||||
if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($entryId)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim()
|
|
||||||
$nextVal = "$quotedExe $nextRest"
|
|
||||||
$saved = $false
|
|
||||||
try {
|
|
||||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
|
||||||
if ($wk) {
|
|
||||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
|
||||||
$wk.Close()
|
|
||||||
$saved = $true
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
if ($saved) {
|
|
||||||
$updated.Add($entryId)
|
|
||||||
$configured.Add($entryId)
|
|
||||||
} elseif ($rt.Label -eq 'HKLM') {
|
|
||||||
$readOnly.Add($entryId)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
|
||||||
$nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe }
|
|
||||||
if ($nextVal -ne $rawCmd.Trim()) {
|
|
||||||
$saved = $false
|
|
||||||
try {
|
|
||||||
$wk = $rt.Root.OpenSubKey($rt.SubPath, $true)
|
|
||||||
if ($wk) {
|
|
||||||
$wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String)
|
|
||||||
$wk.Close()
|
|
||||||
$saved = $true
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
if ($saved) {
|
|
||||||
$updated.Add($entryId)
|
|
||||||
} elseif ($rt.Label -eq 'HKLM') {
|
|
||||||
$readOnly.Add($entryId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($entryId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
$exactClassSubKeys = @(
|
|
||||||
'Software\\Classes\\antigravity\\shell\\open\\command',
|
|
||||||
'Software\\Classes\\Applications\\Antigravity.exe\\shell\\open\\command',
|
|
||||||
'Software\\Classes\\AntigravitySourceFile\\shell\\open\\command'
|
|
||||||
)
|
|
||||||
$classRoots = @(
|
|
||||||
@{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; FullPrefix = 'HKEY_CURRENT_USER' },
|
|
||||||
@{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; FullPrefix = 'HKEY_LOCAL_MACHINE' }
|
|
||||||
)
|
|
||||||
foreach ($cr in $classRoots) {
|
|
||||||
foreach ($relSubKey in $exactClassSubKeys) {
|
|
||||||
try {
|
|
||||||
$rOpen = $cr.Root.OpenSubKey($relSubKey, $false)
|
|
||||||
if (-not $rOpen) { continue }
|
|
||||||
$rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
|
||||||
$rOpen.Close()
|
|
||||||
if (-not $rawOpen) { continue }
|
|
||||||
if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue }
|
|
||||||
$exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
|
||||||
$restOpen = ([string]$Matches[3]).Trim()
|
|
||||||
if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue }
|
|
||||||
$quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand }
|
|
||||||
$fullKeyName = if ($cr.Label -eq 'HKLM') { "HKLM:Class:$relSubKey" } else { "$($cr.FullPrefix)\\$relSubKey" }
|
|
||||||
if ($enableFlag) {
|
|
||||||
if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($fullKeyName)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" }
|
|
||||||
$saved = $false
|
|
||||||
try {
|
|
||||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
|
||||||
if ($wOpen) {
|
|
||||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
|
||||||
$wOpen.Close()
|
|
||||||
$saved = $true
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
if ($saved) {
|
|
||||||
$updated.Add($fullKeyName)
|
|
||||||
$configured.Add($fullKeyName)
|
|
||||||
} elseif ($cr.Label -eq 'HKLM') {
|
|
||||||
$readOnly.Add($fullKeyName)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
|
||||||
$nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe }
|
|
||||||
if ($nextOpen -ne $rawOpen.Trim()) {
|
|
||||||
$saved = $false
|
|
||||||
try {
|
|
||||||
$wOpen = $cr.Root.OpenSubKey($relSubKey, $true)
|
|
||||||
if ($wOpen) {
|
|
||||||
$wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String)
|
|
||||||
$wOpen.Close()
|
|
||||||
$saved = $true
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
if ($saved) {
|
|
||||||
$updated.Add($fullKeyName)
|
|
||||||
} elseif ($cr.Label -eq 'HKLM') {
|
|
||||||
$readOnly.Add($fullKeyName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
|
||||||
$configured.Add($fullKeyName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[pscustomobject]@{
|
|
||||||
ok = $true
|
|
||||||
updatedPaths = @($updated)
|
|
||||||
configuredPaths = @($configured)
|
|
||||||
readOnlyPaths = @($readOnly)
|
|
||||||
discoveredDirs = @($discoveredDirs)
|
|
||||||
} | ConvertTo-Json -Compress
|
|
||||||
`.trim();
|
|
||||||
|
|
||||||
const cachedDiscoveredWinDirsByHome = new Map();
|
const cachedDiscoveredWinDirsByHome = new Map();
|
||||||
|
|
||||||
function getCachedWinDiscoveredDirs(homeDir) {
|
function getCachedWinDiscoveredDirs(homeDir) {
|
||||||
@@ -1226,7 +939,7 @@ export async function ensureDesktopLaunchEntriesConfigured({
|
|||||||
const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, ops.existsFn);
|
const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, ops.existsFn);
|
||||||
const out = await runner(
|
const out = await runner(
|
||||||
psExe,
|
psExe,
|
||||||
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS],
|
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', getWinShortcutProvisionPs()],
|
||||||
{
|
{
|
||||||
timeoutMs: 10000,
|
timeoutMs: 10000,
|
||||||
env: {
|
env: {
|
||||||
@@ -1590,6 +1303,83 @@ function psSingleQuote(val) {
|
|||||||
* @param {{ readOnlyShortcutPaths?: string[], psExePath?: string }} [extra]
|
* @param {{ readOnlyShortcutPaths?: string[], psExePath?: string }} [extra]
|
||||||
* @returns {string}
|
* @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(
|
export function buildWindowsRelaunchInnerScript(
|
||||||
executablePath,
|
executablePath,
|
||||||
stalePortFiles = [],
|
stalePortFiles = [],
|
||||||
@@ -1598,6 +1388,7 @@ export function buildWindowsRelaunchInnerScript(
|
|||||||
) {
|
) {
|
||||||
const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity';
|
const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity';
|
||||||
const psExe = String(extra?.psExePath || 'powershell.exe').trim() || 'powershell.exe';
|
const psExe = String(extra?.psExePath || 'powershell.exe').trim() || 'powershell.exe';
|
||||||
|
const { fnLines, quotedLines } = buildReadonlyShortcutPatchPsBlock();
|
||||||
const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : [])
|
const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : [])
|
||||||
.map((p) => String(p || '').trim())
|
.map((p) => String(p || '').trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
@@ -1626,70 +1417,7 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) {
|
|||||||
if ($livePath) { $exe = [string]$livePath }
|
if ($livePath) { $exe = [string]$livePath }
|
||||||
}
|
}
|
||||||
|
|
||||||
function Patch-ShortcutList($paths) {
|
${fnLines}
|
||||||
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 {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($readOnlyShortcuts.Count -gt 0) {
|
if ($readOnlyShortcuts.Count -gt 0) {
|
||||||
if ($isSelfElevated) {
|
if ($isSelfElevated) {
|
||||||
@@ -1699,68 +1427,7 @@ if ($readOnlyShortcuts.Count -gt 0) {
|
|||||||
$roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', '
|
$roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', '
|
||||||
$elevBody = @(
|
$elevBody = @(
|
||||||
('$targets = @(' + $roJoined + ')'),
|
('$targets = @(' + $roJoined + ')'),
|
||||||
'$ws = $null',
|
${quotedLines}
|
||||||
'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 {}',
|
|
||||||
' }',
|
|
||||||
'}',
|
|
||||||
'Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue'
|
'Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue'
|
||||||
) -join "\`r\`n"
|
) -join "\`r\`n"
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -10,18 +10,15 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
import { mkdirSync } from 'node:fs';
|
import { join } from 'node:path';
|
||||||
import { dirname, join } from 'node:path';
|
|
||||||
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
|
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
|
||||||
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
|
||||||
import {
|
import {
|
||||||
CACHE_RUNNING_SAVE_INTERVAL_MS,
|
|
||||||
DATA_DIR,
|
DATA_DIR,
|
||||||
clearRuntimeCaches,
|
clearRuntimeCaches,
|
||||||
flushTrajectoryCacheNow,
|
flushTrajectoryCacheNow,
|
||||||
getCachedTrajectory,
|
getCachedTrajectory,
|
||||||
|
getCachedTrajectoryEntryByLower,
|
||||||
hasPendingTrajectoryCacheSave,
|
hasPendingTrajectoryCacheSave,
|
||||||
isPlainObject,
|
|
||||||
listCachedTrajectoryEntries,
|
listCachedTrajectoryEntries,
|
||||||
loadJson,
|
loadJson,
|
||||||
lsRuntimeEndpoint,
|
lsRuntimeEndpoint,
|
||||||
@@ -30,7 +27,7 @@ import {
|
|||||||
removeCachedTrajectory,
|
removeCachedTrajectory,
|
||||||
setCachedTrajectory,
|
setCachedTrajectory,
|
||||||
} from './config.mjs';
|
} 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_ID_REMOTE_RE = /^remote:[a-zA-Z0-9._:@-]{1,120}$/;
|
||||||
const ENDPOINT_STALE_TTL_MS = 60_000;
|
const ENDPOINT_STALE_TTL_MS = 60_000;
|
||||||
@@ -123,38 +120,6 @@ function buildRemoteCacheFilePath(stableHostKey) {
|
|||||||
return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`);
|
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() {
|
function createRemoteQuotaCache() {
|
||||||
return {
|
return {
|
||||||
ts: 0,
|
ts: 0,
|
||||||
@@ -167,108 +132,12 @@ function createRemoteQuotaCache() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createRemoteEndpointStore(cacheFilePath) {
|
function createRemoteEndpointStore(cacheFilePath) {
|
||||||
const loaded = cacheFilePath ? loadJson(cacheFilePath, {}) : {};
|
return createTrajectoryCacheStore({
|
||||||
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 {
|
|
||||||
cacheFilePath,
|
cacheFilePath,
|
||||||
cacheState: state,
|
loadJsonFn: loadJson,
|
||||||
cancelFlushTimer,
|
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||||
getCachedTrajectory: (cascadeId) => cacheObj[cascadeId],
|
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||||
listCachedTrajectoryEntries: () => Object.entries(cacheObj),
|
});
|
||||||
setCachedTrajectory: (cascadeId, entry) => {
|
|
||||||
cacheObj[cascadeId] = entry;
|
|
||||||
},
|
|
||||||
removeCachedTrajectory: (cascadeId) => {
|
|
||||||
delete cacheObj[cascadeId];
|
|
||||||
},
|
|
||||||
hasPendingTrajectoryCacheSave: () => state.needsSave,
|
|
||||||
persistTrajectoryCacheIfNeeded: persistIfNeeded,
|
|
||||||
flushTrajectoryCacheNow: writeCacheNow,
|
|
||||||
clearCache,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -445,6 +314,7 @@ export function getEndpointCacheStore(endpointOrId = null) {
|
|||||||
isRemote: false,
|
isRemote: false,
|
||||||
endpointId: LOCAL_ENDPOINT_ID,
|
endpointId: LOCAL_ENDPOINT_ID,
|
||||||
getCachedTrajectory,
|
getCachedTrajectory,
|
||||||
|
getCachedTrajectoryEntryByLower,
|
||||||
listCachedTrajectoryEntries,
|
listCachedTrajectoryEntries,
|
||||||
setCachedTrajectory,
|
setCachedTrajectory,
|
||||||
removeCachedTrajectory,
|
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;
|
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` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
|
||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
extractModelSteps,
|
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 CONV_FILE_RE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i;
|
||||||
const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
const brainDirListingMemo = new Map();
|
||||||
|
const knownExistingTranscriptPaths = new Set();
|
||||||
|
let knownBrainCascadeSet = null;
|
||||||
|
let knownBrainCascadeSetRootsKey = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 联合扫描本地多端(Desktop / CLI / IDE)的 `conversations` 与 `brain/<id>/.system_generated/logs/transcript.jsonl`,
|
* 联合扫描本地多端(Desktop / CLI / IDE)的 `conversations` 与 `brain/<id>/.system_generated/logs/transcript.jsonl`,
|
||||||
* 按小写 `cascadeId` 归并关联磁盘文件路径。
|
* 按小写 `cascadeId` 归并关联磁盘文件路径。
|
||||||
@@ -76,15 +82,35 @@ function discoverLocalConversationFiles() {
|
|||||||
|
|
||||||
const brainDirs =
|
const brainDirs =
|
||||||
Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
||||||
|
const nextBrainUuidSet = new Set();
|
||||||
for (const dir of brainDirs) {
|
for (const dir of brainDirs) {
|
||||||
if (!dir || !existsSync(dir)) continue;
|
if (!dir || !existsSync(dir)) continue;
|
||||||
try {
|
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)) {
|
for (const rawName of readdirSync(dir)) {
|
||||||
const name = String(rawName || '').trim();
|
const name = String(rawName || '').trim();
|
||||||
const cascadeId = name.toLowerCase();
|
const cascadeId = name.toLowerCase();
|
||||||
if (!TRANSCRIPT_UUID_RE.test(cascadeId)) continue;
|
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');
|
const transcriptPath = join(dir, name, '.system_generated', 'logs', 'transcript.jsonl');
|
||||||
|
if (!knownExistingTranscriptPaths.has(transcriptPath)) {
|
||||||
if (!existsSync(transcriptPath)) continue;
|
if (!existsSync(transcriptPath)) continue;
|
||||||
|
if (dirMtimeMs > 0) {
|
||||||
|
knownExistingTranscriptPaths.add(transcriptPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!map.has(cascadeId)) map.set(cascadeId, []);
|
if (!map.has(cascadeId)) map.set(cascadeId, []);
|
||||||
map.get(cascadeId).push(transcriptPath);
|
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 : [];
|
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
||||||
if (annotationDirs.length > 0 && map.size > 0) {
|
if (annotationDirs.length > 0 && map.size > 0) {
|
||||||
@@ -381,6 +409,9 @@ export function clearScannerRuntimeMemos(endpointId = null) {
|
|||||||
liveActivityMemo.clear();
|
liveActivityMemo.clear();
|
||||||
transcriptTailMemo.clear();
|
transcriptTailMemo.clear();
|
||||||
swarmManifestMemo.clear();
|
swarmManifestMemo.clear();
|
||||||
|
brainDirListingMemo.clear();
|
||||||
|
knownExistingTranscriptPaths.clear();
|
||||||
|
knownBrainCascadeSet = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function findSwarmMembersPath(cascadeId) {
|
function findSwarmMembersPath(cascadeId) {
|
||||||
@@ -388,6 +419,13 @@ function findSwarmMembersPath(cascadeId) {
|
|||||||
const normId = String(cascadeId).trim().toLowerCase();
|
const normId = String(cascadeId).trim().toLowerCase();
|
||||||
if (!UUID_RE.test(normId)) return '';
|
if (!UUID_RE.test(normId)) return '';
|
||||||
const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
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 bestPath = '';
|
||||||
let bestMtime = -1;
|
let bestMtime = -1;
|
||||||
for (const dir of dirs) {
|
for (const dir of dirs) {
|
||||||
@@ -541,21 +579,7 @@ function inferConversationAppSource(diskFiles = [], extMatch = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function extractOfflineUserTitle(rawContent) {
|
function extractOfflineUserTitle(rawContent) {
|
||||||
if (typeof rawContent !== 'string' || !rawContent.trim()) return '';
|
return extractShortPromptTitle(rawContent, 48, { firstLineOnly: true });
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_TITLE_PROBE_CACHE = 2000;
|
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 || '')));
|
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;
|
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;
|
let best = null;
|
||||||
for (const rawPath of diskFiles) {
|
for (const rawPath of diskFiles) {
|
||||||
const p = String(rawPath || '').trim();
|
const p = String(rawPath || '').trim();
|
||||||
if (!/\.db$/i.test(p)) continue;
|
if (!/\.db$/i.test(p)) continue;
|
||||||
const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p);
|
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 (!walInfo.exists) continue;
|
||||||
if (!best || walInfo.mtimeMs > best.mtimeMs) {
|
if (!best || walInfo.mtimeMs > best.mtimeMs) {
|
||||||
best = {
|
best = {
|
||||||
@@ -1629,7 +1667,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
const localSum = localSummaryByLower.get(cidLower) || null;
|
const localSum = localSummaryByLower.get(cidLower) || null;
|
||||||
const cached = getEntry(cascadeId);
|
const cached = getEntry(cascadeId);
|
||||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
const diskFiles = diskConvMap.get(cidLower) || [];
|
||||||
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
|
const sqliteDbInfo = sqliteAvailable
|
||||||
|
? resolveBestSqliteDbInfo(diskFiles, { skipMissingWalFromListing: true })
|
||||||
|
: null;
|
||||||
const dbPath = sqliteDbInfo?.dbPath || '';
|
const dbPath = sqliteDbInfo?.dbPath || '';
|
||||||
const diskFileSig = sqliteDbInfo?.sig || '';
|
const diskFileSig = sqliteDbInfo?.sig || '';
|
||||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||||
@@ -1906,6 +1946,15 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
let lazyExternalByLower = null;
|
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`)。
|
* 批量拉取会话轨迹并提取步骤、子代理元数据 (`trajectory.metadata`) 与子代理调用引用 (`invokeSubagent`)。
|
||||||
@@ -2063,7 +2112,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||||
const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps);
|
const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps);
|
||||||
const ownSwarmManifest =
|
const ownSwarmManifest =
|
||||||
!isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
!isRemote && !conv.isSubagent ? getPollSwarmManifest(cidLower) : null;
|
||||||
if (ownSwarmManifest?.workerRefs?.length) {
|
if (ownSwarmManifest?.workerRefs?.length) {
|
||||||
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
||||||
for (const wRef of ownSwarmManifest.workerRefs) {
|
for (const wRef of ownSwarmManifest.workerRefs) {
|
||||||
@@ -2422,10 +2471,19 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (hasMissingStepFields(cached)) return true;
|
if (hasMissingStepFields(cached)) return true;
|
||||||
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
||||||
if (!conv.inSummaries) {
|
if (!conv.inSummaries) {
|
||||||
if (isRunning || cached.wasRunning) return true;
|
|
||||||
if (conv.dbPath && sqliteAvailable) {
|
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 (
|
if (
|
||||||
cached.offlineTranscriptFallback &&
|
cached.offlineTranscriptFallback &&
|
||||||
!cached.offlineSqliteTelemetry &&
|
!cached.offlineSqliteTelemetry &&
|
||||||
@@ -2504,7 +2562,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||||
const swarmManifest =
|
const swarmManifest =
|
||||||
!isRemote && !parentConv.isSubagent
|
!isRemote && !parentConv.isSubagent
|
||||||
? readSwarmManifestForCascade(parentConv.cascadeId)
|
? getPollSwarmManifest(parentConv.cascadeId)
|
||||||
: null;
|
: null;
|
||||||
let refs = baseRefs;
|
let refs = baseRefs;
|
||||||
if (swarmManifest?.workerRefs?.length) {
|
if (swarmManifest?.workerRefs?.length) {
|
||||||
@@ -2800,7 +2858,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
for (const rootConv of conversations) {
|
for (const rootConv of conversations) {
|
||||||
const cid = rootConv.cascadeId.toLowerCase();
|
const cid = rootConv.cascadeId.toLowerCase();
|
||||||
const rootCached = getEntry(rootConv.cascadeId);
|
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();
|
const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim();
|
||||||
if (swarmTitle) {
|
if (swarmTitle) {
|
||||||
rootConv.swarmTitle = swarmTitle;
|
rootConv.swarmTitle = swarmTitle;
|
||||||
|
|||||||
@@ -13,6 +13,13 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
|
||||||
|
import {
|
||||||
|
parseWorkspaceDisplayLabel,
|
||||||
|
parseWorkspaceUrisColumn,
|
||||||
|
toDesktopEncodedWorkspaceUri,
|
||||||
|
toRawWorkspaceFileUri,
|
||||||
|
} from '../shared/workspace-uri.mjs';
|
||||||
import {
|
import {
|
||||||
cpSync,
|
cpSync,
|
||||||
existsSync,
|
existsSync,
|
||||||
@@ -115,97 +122,19 @@ function migratorFormatSqliteUtcTime(epochMs) {
|
|||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function migratorToRawFileUri(rawInput) {
|
export function migratorToRawFileUri(rawInput) {
|
||||||
const raw = String(rawInput || '').trim();
|
return toRawWorkspaceFileUri(rawInput);
|
||||||
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}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 将 `file://` URI 或本地路径规整为 Antigravity 桌面端标准编码格式(Windows 盘符小写 + `%3A`)。
|
|
||||||
*
|
|
||||||
* @param {string} rawInput
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
export function migratorToDesktopEncodedUri(rawInput) {
|
export function migratorToDesktopEncodedUri(rawInput) {
|
||||||
const raw = String(rawInput || '').trim();
|
return toDesktopEncodedWorkspaceUri(rawInput);
|
||||||
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}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 从 `file:///` URI 提取可读路径和末级项目显示名。
|
|
||||||
*
|
|
||||||
* @param {string} rawUri
|
|
||||||
* @returns {{ name: string, displayPath: string }}
|
|
||||||
*/
|
|
||||||
export function migratorParseWorkspaceLabel(rawUri) {
|
export function migratorParseWorkspaceLabel(rawUri) {
|
||||||
const raw = String(rawUri || '').trim();
|
return parseWorkspaceDisplayLabel(rawUri);
|
||||||
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 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function migratorParseWorkspaceUrisColumn(rawVal) {
|
function migratorParseWorkspaceUrisColumn(rawVal) {
|
||||||
const str = String(rawVal || '').trim();
|
return parseWorkspaceUrisColumn(rawVal);
|
||||||
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];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function migratorEscapePbtxtString(text) {
|
function migratorEscapePbtxtString(text) {
|
||||||
@@ -217,15 +146,7 @@ function migratorEscapePbtxtString(text) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function migratorCleanPromptTitle(rawText, maxChars = 72) {
|
function migratorCleanPromptTitle(rawText, maxChars = 72) {
|
||||||
const cleaned = String(rawText || '')
|
return extractShortPromptTitle(rawText, maxChars);
|
||||||
.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()}…`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function migratorDecodeUserPromptFromStepPayload(rawBlob) {
|
function migratorDecodeUserPromptFromStepPayload(rawBlob) {
|
||||||
@@ -1129,13 +1050,15 @@ export function migrateSessions(params = {}, options = {}) {
|
|||||||
// 写入目标摘要库前自动留存滚动备份(移动模式同时备份源摘要库)
|
// 写入目标摘要库前自动留存滚动备份(移动模式同时备份源摘要库)
|
||||||
const backupRoot = migratorResolveBackupRoot(options.backupDir);
|
const backupRoot = migratorResolveBackupRoot(options.backupDir);
|
||||||
let backupPath = '';
|
let backupPath = '';
|
||||||
|
const warnings = [];
|
||||||
try {
|
try {
|
||||||
backupPath = migratorBackupSummaryDb(dstSumDbPath, dstDef.id, backupRoot);
|
backupPath = migratorBackupSummaryDb(dstSumDbPath, dstDef.id, backupRoot);
|
||||||
if (mode === 'move' && existsSync(srcSumDbPath)) {
|
if (mode === 'move' && existsSync(srcSumDbPath)) {
|
||||||
migratorBackupSummaryDb(srcSumDbPath, srcDef.id, backupRoot);
|
migratorBackupSummaryDb(srcSumDbPath, srcDef.id, backupRoot);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (bakErr) {
|
||||||
backupPath = '';
|
backupPath = '';
|
||||||
|
warnings.push(`summary_backup_failed: ${bakErr?.message || 'unknown'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const archiveSrcDir = join(backupRoot, 'archived-sources', srcDef.id);
|
const archiveSrcDir = join(backupRoot, 'archived-sources', srcDef.id);
|
||||||
@@ -1575,6 +1498,7 @@ export function migrateSessions(params = {}, options = {}) {
|
|||||||
migratedCount,
|
migratedCount,
|
||||||
failedCount,
|
failedCount,
|
||||||
backupPath,
|
backupPath,
|
||||||
|
...(warnings.length > 0 ? { warnings } : {}),
|
||||||
needsWindowReload: dstDef.id === 'desktop' && migratedCount > 0,
|
needsWindowReload: dstDef.id === 'desktop' && migratedCount > 0,
|
||||||
results,
|
results,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -65,23 +65,22 @@ export function hasBuiltinNodeSqlite() {
|
|||||||
* @param {string} dbPath
|
* @param {string} dbPath
|
||||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||||
*/
|
*/
|
||||||
export function computeSqliteWalSig(dbPath) {
|
export function computeSqliteWalSig(dbPath, { skipWalCheck = false } = {}) {
|
||||||
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
|
if (!dbPath || typeof dbPath !== 'string') {
|
||||||
return { exists: false, mtimeMs: 0, sig: '' };
|
return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
}
|
}
|
||||||
let dbStat = null;
|
let dbStat = null;
|
||||||
try {
|
try {
|
||||||
dbStat = statSync(dbPath);
|
dbStat = statSync(dbPath, { throwIfNoEntry: false });
|
||||||
} catch {
|
} catch {
|
||||||
return { exists: false, mtimeMs: 0, sig: '' };
|
return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
}
|
}
|
||||||
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
|
|
||||||
let walStat = null;
|
let walStat = null;
|
||||||
const walPath = `${dbPath}-wal`;
|
if (!skipWalCheck) {
|
||||||
if (existsSync(walPath)) {
|
|
||||||
try {
|
try {
|
||||||
walStat = statSync(walPath);
|
walStat = statSync(`${dbPath}-wal`, { throwIfNoEntry: false });
|
||||||
} catch {
|
} catch {
|
||||||
walStat = null;
|
walStat = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,6 +96,9 @@ function roundSessionCost(val) {
|
|||||||
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
|
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
|
||||||
if (!cascadeId) return null;
|
if (!cascadeId) return null;
|
||||||
const store = cacheStore || getEndpointCacheStore(null);
|
const store = cacheStore || getEndpointCacheStore(null);
|
||||||
|
if (typeof store.getCachedTrajectoryEntryByLower === 'function') {
|
||||||
|
return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null;
|
||||||
|
}
|
||||||
const entry = store.getCachedTrajectory(cascadeId);
|
const entry = store.getCachedTrajectory(cascadeId);
|
||||||
if (entry) return entry;
|
if (entry) return entry;
|
||||||
const targetLower = String(cascadeId).toLowerCase();
|
const targetLower = String(cascadeId).toLowerCase();
|
||||||
@@ -811,6 +814,105 @@ function getTelemetrySources(
|
|||||||
return pending;
|
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({
|
function buildActiveConversationAssembly({
|
||||||
activeCascadeId,
|
activeCascadeId,
|
||||||
activeConvSummary,
|
activeConvSummary,
|
||||||
@@ -942,9 +1044,7 @@ function buildActiveConversationAssembly({
|
|||||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||||
let totalFamilyOutputTokens = sessionOutputTokens;
|
let totalFamilyOutputTokens = sessionOutputTokens;
|
||||||
|
|
||||||
let normalSubCount = 0;
|
const subCounters = { normal: 0, swarm: 0, side: 0 };
|
||||||
let swarmWorkerCount = 0;
|
|
||||||
let sideQuestionCount = 0;
|
|
||||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||||
const subSum = subagentSummaries[idx];
|
const subSum = subagentSummaries[idx];
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
@@ -953,78 +1053,21 @@ function buildActiveConversationAssembly({
|
|||||||
const subRawSteps = subRawStepsList[idx];
|
const subRawSteps = subRawStepsList[idx];
|
||||||
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
||||||
|
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const {
|
||||||
const isSideQ = Boolean(
|
isSideQ,
|
||||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
subIndex,
|
||||||
);
|
sideIndex,
|
||||||
const rawRole =
|
agentKind,
|
||||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
agentOrdinal,
|
||||||
const parsedSwarm = !isSideQ
|
customRole,
|
||||||
? parseSwarmWorkerRole({
|
swarmState,
|
||||||
role: subSpec?.role || '',
|
isSwarmAuxiliary,
|
||||||
typeName: subSpec?.typeName || '',
|
shortLabel,
|
||||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
badgeText,
|
||||||
memberName: subSum.swarmMemberName || '',
|
roleLabel,
|
||||||
})
|
typeName,
|
||||||
: { isSwarmWorker: false };
|
agentLabel,
|
||||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
} = classifySubagentDisplayMeta(subSum, subEntry, idx, subCounters);
|
||||||
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 subUnit = buildAgentUnitTelemetry({
|
const subUnit = buildAgentUnitTelemetry({
|
||||||
agentId: subCid,
|
agentId: subCid,
|
||||||
@@ -1179,11 +1222,11 @@ function buildActiveConversationAssembly({
|
|||||||
mainAgentTelemetry;
|
mainAgentTelemetry;
|
||||||
|
|
||||||
const roleSummaryParts = [];
|
const roleSummaryParts = [];
|
||||||
if (swarmWorkerCount > 0) roleSummaryParts.push(`${swarmWorkerCount} 蜂群`);
|
if (subCounters.swarm > 0) roleSummaryParts.push(`${subCounters.swarm} 蜂群`);
|
||||||
if (normalSubCount > 0) roleSummaryParts.push(`${normalSubCount} 子代理`);
|
if (subCounters.normal > 0) roleSummaryParts.push(`${subCounters.normal} 子代理`);
|
||||||
if (sideQuestionCount > 0) {
|
if (subCounters.side > 0) {
|
||||||
roleSummaryParts.push(
|
roleSummaryParts.push(
|
||||||
roleSummaryParts.length > 0 ? `${sideQuestionCount} 旁问` : `${sideQuestionCount} 旁路提问`
|
roleSummaryParts.length > 0 ? `${subCounters.side} 旁问` : `${subCounters.side} 旁路提问`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const aggregatedRoleLabel =
|
const aggregatedRoleLabel =
|
||||||
@@ -1290,9 +1333,9 @@ function buildActiveConversationAssembly({
|
|||||||
stepCount: enrichedActiveSteps.length,
|
stepCount: enrichedActiveSteps.length,
|
||||||
hasSubagents: subAgentTelemetries.length > 0,
|
hasSubagents: subAgentTelemetries.length > 0,
|
||||||
subagentCount: subAgentTelemetries.length,
|
subagentCount: subAgentTelemetries.length,
|
||||||
swarmCount: swarmWorkerCount,
|
swarmCount: subCounters.swarm,
|
||||||
normalSubagentCount: normalSubCount,
|
normalSubagentCount: subCounters.normal,
|
||||||
sideQuestionCount,
|
sideQuestionCount: subCounters.side,
|
||||||
totalStepsAllAgents: subAgentTelemetries.length
|
totalStepsAllAgents: subAgentTelemetries.length
|
||||||
? allCombinedEnrichedSteps.length
|
? allCombinedEnrichedSteps.length
|
||||||
: enrichedActiveSteps.length,
|
: enrichedActiveSteps.length,
|
||||||
@@ -1846,80 +1889,27 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const rootFallbackMs =
|
const rootFallbackMs =
|
||||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||||
|
|
||||||
let runNormalSubIdx = 0;
|
const runCounters = { normal: 0, swarm: 0, side: 0 };
|
||||||
let runSwarmIdx = 0;
|
|
||||||
let runSideIdx = 0;
|
|
||||||
const subItems = rawSubs.map((subSum, idx) => {
|
const subItems = rawSubs.map((subSum, idx) => {
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
const subEntry = findTrajectoryCacheEntry(subCid, cacheStore);
|
const subEntry = findTrajectoryCacheEntry(subCid, cacheStore);
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const {
|
||||||
const isSideQ = Boolean(
|
subSpec,
|
||||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
isSideQ,
|
||||||
);
|
isSwarmW,
|
||||||
const rawRole =
|
isSubRunning,
|
||||||
subSpec?.role ||
|
isKilled,
|
||||||
subSum.agentScriptName ||
|
subIndex,
|
||||||
subEntry?.agentScriptName ||
|
sideIndex,
|
||||||
subSpec?.typeName ||
|
agentKind,
|
||||||
'';
|
agentOrdinal,
|
||||||
const parsedSwarm = !isSideQ
|
customRole,
|
||||||
? parseSwarmWorkerRole({
|
swarmState,
|
||||||
role: subSpec?.role || '',
|
isSwarmAuxiliary,
|
||||||
typeName: subSpec?.typeName || '',
|
badgeText,
|
||||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
shortLabel,
|
||||||
memberName: subSum.swarmMemberName || '',
|
runningRole: role,
|
||||||
})
|
} = classifySubagentDisplayMeta(subSum, subEntry, idx, runCounters);
|
||||||
: { 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 stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
||||||
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
||||||
const liveActivity = isSubRunning
|
const liveActivity = isSubRunning
|
||||||
@@ -2088,9 +2078,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0,
|
lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0,
|
||||||
mainActivity: resolvedMainActivity,
|
mainActivity: resolvedMainActivity,
|
||||||
subagentCount: subItems.length,
|
subagentCount: subItems.length,
|
||||||
swarmCount: runSwarmIdx,
|
swarmCount: runCounters.swarm,
|
||||||
normalSubagentCount: runNormalSubIdx,
|
normalSubagentCount: runCounters.normal,
|
||||||
sideQuestionCount: runSideIdx,
|
sideQuestionCount: runCounters.side,
|
||||||
runningSubagentCount: runningSubList.length,
|
runningSubagentCount: runningSubList.length,
|
||||||
runningSwarmCount: runningSubList.filter((s) => s.agentKind === 'swarm_worker').length,
|
runningSwarmCount: runningSubList.filter((s) => s.agentKind === 'swarm_worker').length,
|
||||||
subagents: subItems,
|
subagents: subItems,
|
||||||
@@ -2115,7 +2105,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
windowBridge: getDefaultWindowBridgeStatus(),
|
windowBridge: getDefaultWindowBridgeStatus(),
|
||||||
cloudCodeProxy: getDefaultCloudCodeProxyStatus(),
|
cloudCodeProxy: getDefaultCloudCodeProxyStatus(),
|
||||||
cliStatusLine: getCliStatusLineRuntimeStatus(),
|
cliStatusLine: getCliStatusLineRuntimeStatus(),
|
||||||
settings: loadSettings(),
|
settings,
|
||||||
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
||||||
const latest = group.members.reduce((previous, id) => {
|
const latest = group.members.reduce((previous, id) => {
|
||||||
const reported = reportedContextLimits.get(id);
|
const reported = reportedContextLimits.get(id);
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
|||||||
append('}');
|
append('}');
|
||||||
|
|
||||||
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
||||||
|
let renamed = false;
|
||||||
try {
|
try {
|
||||||
const fd = openSync(temporaryPath, 'wx');
|
const fd = openSync(temporaryPath, 'wx');
|
||||||
try {
|
try {
|
||||||
@@ -72,6 +73,7 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
|||||||
}
|
}
|
||||||
const written = statSync(temporaryPath, { bigint: true });
|
const written = statSync(temporaryPath, { bigint: true });
|
||||||
renameSync(temporaryPath, filePath);
|
renameSync(temporaryPath, filePath);
|
||||||
|
renamed = true;
|
||||||
const file = statSync(filePath, { bigint: true });
|
const file = statSync(filePath, { bigint: true });
|
||||||
lastWritesByPath.delete(filePath);
|
lastWritesByPath.delete(filePath);
|
||||||
if (isSameFile(written, file)) {
|
if (isSameFile(written, file)) {
|
||||||
@@ -82,6 +84,8 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
|||||||
lastWritesByPath.set(filePath, { filePath, file, ranges });
|
lastWritesByPath.set(filePath, { filePath, file, ranges });
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
if (!renamed) {
|
||||||
try { unlinkSync(temporaryPath); } catch {}
|
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 { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { decodeWorkspaceFileUriToPath } from '../shared/workspace-uri.mjs';
|
||||||
import {
|
import {
|
||||||
MEASUREMENT_VERSION,
|
MEASUREMENT_VERSION,
|
||||||
accumulateSpeed,
|
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}
|
* @returns {{ workspaceKey: string, label: string, workspacePath: string }|null}
|
||||||
*/
|
*/
|
||||||
export function normalizeWorkspaceBucket(rawUri) {
|
export function normalizeWorkspaceBucket(rawUri) {
|
||||||
const raw = String(rawUri || '').trim();
|
const decoded = decodeWorkspaceFileUriToPath(rawUri);
|
||||||
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(/\/+$/, '');
|
|
||||||
if (!decoded) return null;
|
if (!decoded) return null;
|
||||||
const parts = decoded.split('/').filter(Boolean);
|
const parts = decoded.split('/').filter(Boolean);
|
||||||
const label = parts.length > 0 ? parts[parts.length - 1] : decoded;
|
const label = parts.length > 0 ? parts[parts.length - 1] : decoded;
|
||||||
@@ -1422,7 +1416,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint);
|
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint);
|
||||||
const familySig = buildFamilySig(familySet);
|
const familySig = buildFamilySig(familySet);
|
||||||
|
|
||||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : '';
|
||||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||||
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
||||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||||
@@ -1944,7 +1938,7 @@ export function aggregateSelectedWindowUsage({
|
|||||||
: collectUsageEntriesToAggregate(familySet, endpoint);
|
: collectUsageEntriesToAggregate(familySet, endpoint);
|
||||||
const familySig = buildFamilySig(familySet);
|
const familySig = buildFamilySig(familySet);
|
||||||
const currentYear = new Date(nowMs).getFullYear();
|
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 snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
|
||||||
const sameSnapshot = Boolean(
|
const sameSnapshot = Boolean(
|
||||||
@@ -2343,6 +2337,20 @@ export function aggregateSessionUsageForFamily({
|
|||||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||||
|
|
||||||
const familyEntries = [];
|
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()) {
|
for (const [cid, entry] of cacheStore.listCachedTrajectoryEntries()) {
|
||||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||||
const cidLower = String(cid || '').toLowerCase();
|
const cidLower = String(cid || '').toLowerCase();
|
||||||
@@ -2355,6 +2363,7 @@ export function aggregateSessionUsageForFamily({
|
|||||||
isCurrentConv: true,
|
isCurrentConv: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return computeFamilySessionBuckets({
|
return computeFamilySessionBuckets({
|
||||||
entries: familyEntries,
|
entries: familyEntries,
|
||||||
|
|||||||
@@ -15,12 +15,11 @@ import {
|
|||||||
mkdirSync,
|
mkdirSync,
|
||||||
readdirSync,
|
readdirSync,
|
||||||
readFileSync,
|
readFileSync,
|
||||||
renameSync,
|
|
||||||
unlinkSync,
|
unlinkSync,
|
||||||
writeFileSync,
|
|
||||||
} from 'node:fs';
|
} from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
|
import { writeTextFileAtomicSync } from './fs-atomic.mjs';
|
||||||
import {
|
import {
|
||||||
BRIDGE_API_PATHS,
|
BRIDGE_API_PATHS,
|
||||||
CONTEXT_WINDOWS_GLOBAL_KEY,
|
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||||
@@ -458,18 +457,7 @@ function patchSingleHostArgvFile(argvPath, { createDir = false, missingReason =
|
|||||||
argvPath,
|
argvPath,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const tmpPath = `${argvPath}.tmp-${process.pid}`;
|
writeTextFileAtomicSync(argvPath, patched.text);
|
||||||
try {
|
|
||||||
writeFileSync(tmpPath, patched.text, 'utf8');
|
|
||||||
renameSync(tmpPath, argvPath);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
unlinkSync(tmpPath);
|
|
||||||
} catch {
|
|
||||||
// 忽略临时文件清理异常
|
|
||||||
}
|
|
||||||
writeFileSync(argvPath, patched.text, 'utf8');
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
checked: true,
|
checked: true,
|
||||||
updated: true,
|
updated: true,
|
||||||
@@ -1335,11 +1323,16 @@ export function createWindowBridgeController(options) {
|
|||||||
res.writeHead(out.status || 200, hdrs);
|
res.writeHead(out.status || 200, hdrs);
|
||||||
res.end(out.body);
|
res.end(out.body);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch((err) => {
|
||||||
if (!res.headersSent) {
|
if (!res.headersSent) {
|
||||||
res.writeHead(500, { 'Content-Type': 'application/json' });
|
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;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1388,11 +1381,16 @@ export function createWindowBridgeController(options) {
|
|||||||
res.writeHead(out.status || 200, hdrs);
|
res.writeHead(out.status || 200, hdrs);
|
||||||
res.end(out.body);
|
res.end(out.body);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch((err) => {
|
||||||
if (!res.headersSent) {
|
if (!res.headersSent) {
|
||||||
res.writeHead(500, { 'Content-Type': 'application/json' });
|
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;
|
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, {
|
saveJson(leaseFilePath, {
|
||||||
pid: process.pid,
|
pid: process.pid,
|
||||||
bundleVersion,
|
bundleVersion,
|
||||||
@@ -1819,8 +1818,8 @@ export function createWindowBridgeController(options) {
|
|||||||
aliveCount: lastBridgeStatus.aliveCount,
|
aliveCount: lastBridgeStatus.aliveCount,
|
||||||
targets: lastBridgeStatus.targets,
|
targets: lastBridgeStatus.targets,
|
||||||
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||||
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
argvConfigured: mergedLauncherConfigured,
|
||||||
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
launcherConfigured: mergedLauncherConfigured,
|
||||||
hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts),
|
hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts),
|
||||||
canRelaunch: Boolean(canRelaunch),
|
canRelaunch: Boolean(canRelaunch),
|
||||||
updatedAtMs: Date.now(),
|
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,
|
summarizeTtft,
|
||||||
} from './trajectory-metrics.mjs';
|
} from './trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
|
readLocalSqliteLiveTail,
|
||||||
|
readLocalSqliteParentLink,
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
readLocalSummaryIndex,
|
readLocalSummaryIndex,
|
||||||
} from './backend/cli-sqlite-reader.mjs';
|
} from './backend/cli-sqlite-reader.mjs';
|
||||||
import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
import { computeSqliteWalSig, withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
||||||
import {
|
import {
|
||||||
buildCliJsonStatusOutput,
|
buildCliJsonStatusOutput,
|
||||||
ensureCliStatusLineConfigured,
|
ensureCliStatusLineConfigured,
|
||||||
@@ -44,14 +46,17 @@ import {
|
|||||||
import {
|
import {
|
||||||
CLI_STATUS_SNAPSHOT_FILE,
|
CLI_STATUS_SNAPSHOT_FILE,
|
||||||
CLI_STATUSLINE_PRESETS,
|
CLI_STATUSLINE_PRESETS,
|
||||||
|
DATA_DIR,
|
||||||
TOPBAR_SLOT_KEYS,
|
TOPBAR_SLOT_KEYS,
|
||||||
loadJson,
|
loadJson,
|
||||||
loadSettings,
|
loadSettings,
|
||||||
normalizeCliStatusLineSlots,
|
normalizeCliStatusLineSlots,
|
||||||
resolveEffectiveCliStatusLineSlots,
|
resolveEffectiveCliStatusLineSlots,
|
||||||
|
saveJson,
|
||||||
} from './backend/config.mjs';
|
} from './backend/config.mjs';
|
||||||
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
||||||
import { isThirdPartyPoolText } from './shared/telemetry-display-rules.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 CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
||||||
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
||||||
@@ -124,12 +129,7 @@ function readStdinJsonWithTimeout(timeoutMs = 220) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizePathForMatch(rawPath) {
|
function normalizePathForMatch(rawPath) {
|
||||||
const clean = String(rawPath || '')
|
return normalizePathForWorkspaceMatch(rawPath);
|
||||||
.trim()
|
|
||||||
.replace(/^file:\/\/\/?/i, '')
|
|
||||||
.replace(/\\/g, '/')
|
|
||||||
.replace(/\/+$/, '');
|
|
||||||
return process.platform === 'win32' ? clean.toLowerCase() : clean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractConversationIdFromStdin(stdinData) {
|
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) {
|
if (traj?.parentConversationId) {
|
||||||
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
|
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
|
||||||
if (existsSync(rootDb)) {
|
if (rootDb !== dbPath && existsSync(rootDb)) {
|
||||||
const rootTraj = readLocalSqliteTrajectory(rootDb);
|
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
|
||||||
if (rootTraj) {
|
if (rootTraj) {
|
||||||
targetCid = traj.rootConversationId || traj.parentConversationId;
|
targetCid = traj.rootConversationId || traj.parentConversationId;
|
||||||
dbPath = rootDb;
|
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 (!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 {
|
return {
|
||||||
found: false,
|
found: false,
|
||||||
cascadeId: targetCid,
|
cascadeId: targetCid,
|
||||||
@@ -320,46 +434,30 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
targetIsRunning: freshRunningRootIds.includes(String(targetCid || '').toLowerCase()),
|
targetIsRunning: freshRunningRootIds.includes(String(targetCid || '').toLowerCase()),
|
||||||
targetIsWaiting: false,
|
targetIsWaiting: false,
|
||||||
targetWaitingApprovalFresh: false,
|
targetWaitingApprovalFresh: false,
|
||||||
otherLocalWaiting: false,
|
otherLocalWaiting,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetLower = String(targetCid || '').toLowerCase();
|
|
||||||
const targetIsRunning = freshRunningRootIds.includes(targetLower);
|
|
||||||
const targetLiveAct = extractLiveActivity(traj.steps, true);
|
const targetLiveAct = extractLiveActivity(traj.steps, true);
|
||||||
const targetIsWaiting = Boolean(
|
const targetIsWaiting = Boolean(
|
||||||
targetLiveAct?.phase === 'waiting' || targetLiveAct?.waitingApproval
|
targetLiveAct?.phase === 'waiting' || targetLiveAct?.waitingApproval
|
||||||
);
|
);
|
||||||
|
const waitingApproval = Boolean(targetLiveAct?.waitingApproval);
|
||||||
const targetWaitingApprovalFresh = Boolean(
|
const targetWaitingApprovalFresh = Boolean(
|
||||||
targetLiveAct?.waitingApproval &&
|
waitingApproval &&
|
||||||
dbMtimeMs > 0 &&
|
dbMtimeMs > 0 &&
|
||||||
nowMs - dbMtimeMs <= CLI_RUNNING_STALE_MS
|
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 || []);
|
const steps = extractModelSteps(traj.steps, traj.generatorMetadata || []);
|
||||||
if (steps.length === 0) {
|
if (steps.length === 0) {
|
||||||
|
if (targetMemoKey) {
|
||||||
|
saveJson(cliTrajMemoFile, {
|
||||||
|
targetKey: targetMemoKey,
|
||||||
|
metrics: { found: false, targetIsWaiting, waitingApproval },
|
||||||
|
otherWaiting: { ...prevOtherCache, ...nextOtherCache },
|
||||||
|
});
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
found: false,
|
found: false,
|
||||||
cascadeId: targetCid,
|
cascadeId: targetCid,
|
||||||
@@ -467,17 +565,15 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
const sessionCacheHitPct =
|
const sessionCacheHitPct =
|
||||||
totalPromptAll > 0 ? +((totalCacheReadTokens / totalPromptAll) * 100).toFixed(1) : null;
|
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,
|
found: true,
|
||||||
cascadeId: targetCid,
|
|
||||||
dbMtimeMs,
|
|
||||||
stepCount: steps.length,
|
stepCount: steps.length,
|
||||||
runningRootCount,
|
|
||||||
runningSubCount,
|
|
||||||
targetIsRunning,
|
|
||||||
targetIsWaiting,
|
targetIsWaiting,
|
||||||
targetWaitingApprovalFresh,
|
waitingApproval,
|
||||||
otherLocalWaiting,
|
|
||||||
tps: latestTps,
|
tps: latestTps,
|
||||||
avgTps: speedSum?.avgTokPerSec != null ? +speedSum.avgTokPerSec.toFixed(1) : null,
|
avgTps: speedSum?.avgTokPerSec != null ? +speedSum.avgTokPerSec.toFixed(1) : null,
|
||||||
ttft: latestTtft ?? ttftSum?.avgSec ?? null,
|
ttft: latestTtft ?? ttftSum?.avgSec ?? null,
|
||||||
@@ -490,10 +586,40 @@ export function resolveCliLocalSessionMetrics({
|
|||||||
sessionAnomalyCount,
|
sessionAnomalyCount,
|
||||||
latestModelHint,
|
latestModelHint,
|
||||||
hasReportedLimit,
|
hasReportedLimit,
|
||||||
usedPct:
|
usedPct: resolvedUsedPct,
|
||||||
latestLimitTokens > 0 && latestContextTokens > 0
|
};
|
||||||
? Math.min(100, +((latestContextTokens / latestLimitTokens) * 100).toFixed(1))
|
if (targetMemoKey) {
|
||||||
: null,
|
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 charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1795356783419">
|
<link rel="stylesheet" href="/styles.css?v=1795400571874">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1795356783419"></script>
|
<script src="/app.js?v=1795400571874"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ const REGEX_PRECEDING_KEYWORDS = new Set([
|
|||||||
'await',
|
'await',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const REGEX_AFTER_PAREN_KEYWORDS = new Set(['if', 'while', 'for', 'with']);
|
||||||
|
|
||||||
function isIdentStart(ch) {
|
function isIdentStart(ch) {
|
||||||
if (!ch) return false;
|
if (!ch) return false;
|
||||||
const code = ch.charCodeAt(0);
|
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);
|
const peekFrom = skipSpacesAndComments(source, idx);
|
||||||
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
||||||
const specIdx = skipSpacesAndComments(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 specEnd = skipSimpleString(source, specIdx);
|
||||||
const specifier = source.slice(specIdx + 1, specEnd - 1);
|
const specifier = source.slice(specIdx + 1, specEnd - 1);
|
||||||
onImport?.(specifier, braceBody ? `{ ${braceBody} } from` : '');
|
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;
|
idx = specEnd;
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (braceBody && onExport) {
|
emitBraceExports();
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,9 +252,11 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
let i = 0;
|
let i = 0;
|
||||||
let braceDepth = 0;
|
let braceDepth = 0;
|
||||||
let parenDepth = 0;
|
let parenDepth = 0;
|
||||||
|
const parenAllowsRegexStack = [];
|
||||||
const tplBraceStack = [];
|
const tplBraceStack = [];
|
||||||
let canStartRegex = true;
|
let canStartRegex = true;
|
||||||
let prevNonWsChar = '';
|
let prevNonWsChar = '';
|
||||||
|
let pendingRegexParenKeyword = '';
|
||||||
|
|
||||||
function scanTemplateChunk(startAfterBacktickOrBrace) {
|
function scanTemplateChunk(startAfterBacktickOrBrace) {
|
||||||
let idx = startAfterBacktickOrBrace;
|
let idx = startAfterBacktickOrBrace;
|
||||||
@@ -294,6 +321,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
out += source.slice(i, end);
|
out += source.slice(i, end);
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
prevNonWsChar = ch;
|
prevNonWsChar = ch;
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
i = end;
|
i = end;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -301,6 +329,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
// Template literal start
|
// Template literal start
|
||||||
if (ch === '`') {
|
if (ch === '`') {
|
||||||
out += '`';
|
out += '`';
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
i = scanTemplateChunk(i + 1);
|
i = scanTemplateChunk(i + 1);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -329,6 +358,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
out += source.slice(i, end);
|
out += source.slice(i, end);
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
prevNonWsChar = '/';
|
prevNonWsChar = '/';
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
i = end;
|
i = end;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -339,11 +369,13 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
out += ch;
|
out += ch;
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ch;
|
prevNonWsChar = ch;
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
i += 1;
|
i += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ch === '}') {
|
if (ch === '}') {
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
if (tplBraceStack.length > 0 && braceDepth === tplBraceStack[tplBraceStack.length - 1] + 1) {
|
if (tplBraceStack.length > 0 && braceDepth === tplBraceStack[tplBraceStack.length - 1] + 1) {
|
||||||
braceDepth -= 1;
|
braceDepth -= 1;
|
||||||
tplBraceStack.pop();
|
tplBraceStack.pop();
|
||||||
@@ -361,6 +393,8 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
|
|
||||||
if (ch === '(') {
|
if (ch === '(') {
|
||||||
parenDepth += 1;
|
parenDepth += 1;
|
||||||
|
parenAllowsRegexStack.push(Boolean(pendingRegexParenKeyword));
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
out += ch;
|
out += ch;
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ch;
|
prevNonWsChar = ch;
|
||||||
@@ -370,8 +404,10 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
|
|
||||||
if (ch === ')') {
|
if (ch === ')') {
|
||||||
parenDepth = Math.max(0, parenDepth - 1);
|
parenDepth = Math.max(0, parenDepth - 1);
|
||||||
|
const allowsRegexAfterParen = parenAllowsRegexStack.pop() ?? false;
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
out += ch;
|
out += ch;
|
||||||
canStartRegex = false;
|
canStartRegex = allowsRegexAfterParen;
|
||||||
prevNonWsChar = ch;
|
prevNonWsChar = ch;
|
||||||
i += 1;
|
i += 1;
|
||||||
continue;
|
continue;
|
||||||
@@ -397,6 +433,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
i = scanImportDeclarationEnd(source, afterImport, onImport);
|
i = scanImportDeclarationEnd(source, afterImport, onImport);
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ';';
|
prevNonWsChar = ';';
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -408,6 +445,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
i = scanExportClauseEnd(source, afterExport, onImport, onExport);
|
i = scanExportClauseEnd(source, afterExport, onImport, onExport);
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ';';
|
prevNonWsChar = ';';
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// `export default ...`
|
// `export default ...`
|
||||||
@@ -421,12 +459,14 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
recordExportedDeclarationIdent(source, afterDefault, onExport);
|
recordExportedDeclarationIdent(source, afterDefault, onExport);
|
||||||
i = afterDefault;
|
i = afterDefault;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
out += 'void ';
|
out += 'void ';
|
||||||
i = afterDefault;
|
i = afterDefault;
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = 'd';
|
prevNonWsChar = 'd';
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// `export const|let|var|function|class|async ...`
|
// `export const|let|var|function|class|async ...`
|
||||||
@@ -441,10 +481,18 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
recordExportedDeclarationIdent(source, afterExport, onExport);
|
recordExportedDeclarationIdent(source, afterExport, onExport);
|
||||||
i = afterExport;
|
i = afterExport;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (prevNonWsChar !== '.' && REGEX_AFTER_PAREN_KEYWORDS.has(word)) {
|
||||||
|
pendingRegexParenKeyword = word;
|
||||||
|
} else if (pendingRegexParenKeyword === 'for' && word === 'await') {
|
||||||
|
pendingRegexParenKeyword = 'for_await';
|
||||||
|
} else {
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
|
}
|
||||||
out += word;
|
out += word;
|
||||||
canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word);
|
canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word);
|
||||||
prevNonWsChar = word[word.length - 1];
|
prevNonWsChar = word[word.length - 1];
|
||||||
@@ -453,6 +501,7 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Numbers & other punctuation
|
// Numbers & other punctuation
|
||||||
|
pendingRegexParenKeyword = '';
|
||||||
out += ch;
|
out += ch;
|
||||||
if (/[0-9\]`]/.test(ch)) {
|
if (/[0-9\]`]/.test(ch)) {
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
@@ -468,19 +517,43 @@ export function stripModuleSyntax(source, onImport, onExport) {
|
|||||||
return out;
|
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();
|
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
|
||||||
if (binding) {
|
if (binding) {
|
||||||
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
||||||
const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
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) {
|
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(',')) {
|
for (const rawItem of named[1].split(',')) {
|
||||||
const name = rawItem.trim();
|
const name = rawItem.trim();
|
||||||
if (!name) continue;
|
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)) {
|
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);
|
moduleImportedNames?.add(name);
|
||||||
}
|
}
|
||||||
@@ -538,12 +611,14 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
|||||||
'src/core/fileExportClient.js',
|
'src/core/fileExportClient.js',
|
||||||
'src/store/telemetryStore.js',
|
'src/store/telemetryStore.js',
|
||||||
'src/components/ui/TopLongPillNav.js',
|
'src/components/ui/TopLongPillNav.js',
|
||||||
|
'src/components/ui/SearchInput.js',
|
||||||
'src/components/ui/CustomSelect.js',
|
'src/components/ui/CustomSelect.js',
|
||||||
'src/components/ui/ActionMenu.js',
|
'src/components/ui/ActionMenu.js',
|
||||||
'src/components/ui/CustomNumberInput.js',
|
'src/components/ui/CustomNumberInput.js',
|
||||||
'src/components/ui/CustomDateTimePicker.js',
|
'src/components/ui/CustomDateTimePicker.js',
|
||||||
'src/components/ui/CustomScrollbar.js',
|
'src/components/ui/CustomScrollbar.js',
|
||||||
'src/components/ui/SegmentedControl.js',
|
'src/components/ui/SegmentedControl.js',
|
||||||
|
'src/components/ui/ToggleSwitch.js',
|
||||||
'src/components/ui/ContextSegmentMeter.js',
|
'src/components/ui/ContextSegmentMeter.js',
|
||||||
'src/components/ui/FourSegmentBar.js',
|
'src/components/ui/FourSegmentBar.js',
|
||||||
'src/components/ui/ConsumptionTooltipContent.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`);
|
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
|
||||||
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
||||||
const moduleImportedNames = new Set();
|
const moduleImportedNames = new Set();
|
||||||
const moduleLocalExports = new Set();
|
const moduleImportAliases = new Map();
|
||||||
|
const moduleLocalExports = new Map();
|
||||||
const stripped = stripModuleSyntax(
|
const stripped = stripModuleSyntax(
|
||||||
raw,
|
raw,
|
||||||
(specifier, clause) =>
|
(specifier, clause) =>
|
||||||
validateBundleImport(path, specifier, clause, bundledPaths, moduleImportedNames),
|
validateBundleImport(
|
||||||
(name, isClauseExport) => {
|
path,
|
||||||
if (isClauseExport && moduleImportedNames.has(name) && outerExportedSymbols.has(name)) {
|
specifier,
|
||||||
|
clause,
|
||||||
|
bundledPaths,
|
||||||
|
moduleImportedNames,
|
||||||
|
moduleImportAliases,
|
||||||
|
outerExportedSymbols
|
||||||
|
),
|
||||||
|
(name, isClauseExport, localName = name) => {
|
||||||
|
if (
|
||||||
|
isClauseExport &&
|
||||||
|
localName === name &&
|
||||||
|
moduleImportedNames.has(name) &&
|
||||||
|
outerExportedSymbols.has(name)
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
moduleLocalExports.add(name);
|
moduleLocalExports.set(name, localName);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
bundledPaths.add(path);
|
bundledPaths.add(path);
|
||||||
const exportList = [...moduleLocalExports];
|
const exportEntries = [...moduleLocalExports.entries()];
|
||||||
for (const sym of exportList) {
|
for (const [sym] of exportEntries) {
|
||||||
outerExportedSymbols.add(sym);
|
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 =
|
const wrapped =
|
||||||
exportList.length > 0
|
exportEntries.length > 0
|
||||||
? `const { ${exportList.join(', ')} } = (() => {\n${body}\nreturn { ${exportList.join(', ')} };\n})();`
|
? `const { ${outerDestructure} } = (() => {\n${bodyWithAliases}\nreturn { ${innerReturnFields} };\n})();`
|
||||||
: `(() => {\n${body}\n})();`;
|
: `(() => {\n${bodyWithAliases}\n})();`;
|
||||||
return `// --- ${rel} ---\n${wrapped}`;
|
return `// --- ${rel} ---\n${wrapped}`;
|
||||||
})
|
})
|
||||||
.join('\n\n');
|
.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 hoveredIdx = -1;
|
||||||
let tickElsByIdx = new Map();
|
let tickElsByIdx = new Map();
|
||||||
let lastSig = '';
|
let lastSig = '';
|
||||||
|
let lastPreSig = '';
|
||||||
|
let lastSummaryBadge = '';
|
||||||
let lastUpdateParams = null;
|
let lastUpdateParams = null;
|
||||||
|
let cachedPlotSvgRect = null;
|
||||||
|
|
||||||
|
function invalidatePlotSvgRect() {
|
||||||
|
cachedPlotSvgRect = null;
|
||||||
|
}
|
||||||
|
|
||||||
function syncViewWidth() {
|
function syncViewWidth() {
|
||||||
const measured = Math.round(
|
const measured = Math.round(
|
||||||
@@ -936,8 +943,14 @@ export function createSessionLineChart() {
|
|||||||
|
|
||||||
plotStage.addEventListener('mousemove', (e) => {
|
plotStage.addEventListener('mousemove', (e) => {
|
||||||
if (!currentPoints.length) return;
|
if (!currentPoints.length) return;
|
||||||
const rect = svg.getBoundingClientRect();
|
if (!cachedPlotSvgRect) {
|
||||||
if (!rect || rect.width <= 0) return;
|
cachedPlotSvgRect = svg.getBoundingClientRect();
|
||||||
|
}
|
||||||
|
const rect = cachedPlotSvgRect;
|
||||||
|
if (!rect || rect.width <= 0) {
|
||||||
|
cachedPlotSvgRect = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||||
@@ -947,14 +960,19 @@ export function createSessionLineChart() {
|
|||||||
);
|
);
|
||||||
showHoverAt(idx);
|
showHoverAt(idx);
|
||||||
});
|
});
|
||||||
plotStage.addEventListener('mouseleave', clearHover);
|
plotStage.addEventListener('mouseleave', () => {
|
||||||
|
invalidatePlotSvgRect();
|
||||||
|
clearHover();
|
||||||
|
});
|
||||||
|
|
||||||
let resizeObs = null;
|
let resizeObs = null;
|
||||||
let onWinResize = null;
|
let onWinResize = null;
|
||||||
if (typeof ResizeObserver === 'function') {
|
if (typeof ResizeObserver === 'function') {
|
||||||
resizeObs = new ResizeObserver(() => {
|
resizeObs = new ResizeObserver(() => {
|
||||||
|
invalidatePlotSvgRect();
|
||||||
if (syncViewWidth() && lastUpdateParams) {
|
if (syncViewWidth() && lastUpdateParams) {
|
||||||
lastSig = '';
|
lastSig = '';
|
||||||
|
lastPreSig = '';
|
||||||
update(lastUpdateParams);
|
update(lastUpdateParams);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1035,6 +1053,9 @@ export function createSessionLineChart() {
|
|||||||
if (!matchedSteps.length) {
|
if (!matchedSteps.length) {
|
||||||
currentPoints = [];
|
currentPoints = [];
|
||||||
lastSig = 'empty';
|
lastSig = 'empty';
|
||||||
|
lastPreSig = '';
|
||||||
|
lastSummaryBadge = t('chart.step.zeroSteps');
|
||||||
|
invalidatePlotSvgRect();
|
||||||
patchAttr(areaPath, 'd', '');
|
patchAttr(areaPath, 'd', '');
|
||||||
patchAttr(linePath, 'd', '');
|
patchAttr(linePath, 'd', '');
|
||||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||||
@@ -1046,7 +1067,23 @@ export function createSessionLineChart() {
|
|||||||
patchAttr(peakPill, 'hidden', true);
|
patchAttr(peakPill, 'hidden', true);
|
||||||
patchAttr(emptyHintEl, 'hidden', false);
|
patchAttr(emptyHintEl, 'hidden', false);
|
||||||
clearHover();
|
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();
|
const modelColorMap = new Map();
|
||||||
@@ -1254,7 +1291,6 @@ export function createSessionLineChart() {
|
|||||||
const validPoints = points.filter((p) => p.valid);
|
const validPoints = points.filter((p) => p.valid);
|
||||||
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
|
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
|
||||||
|
|
||||||
const locale = getEffectiveLocale();
|
|
||||||
const colorSig = Array.from(modelColorMap.entries())
|
const colorSig = Array.from(modelColorMap.entries())
|
||||||
.map(([k, v]) => `${k}=${v}`)
|
.map(([k, v]) => `${k}=${v}`)
|
||||||
.join(',');
|
.join(',');
|
||||||
@@ -1500,6 +1536,8 @@ export function createSessionLineChart() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lastPreSig = preSig;
|
||||||
|
lastSummaryBadge = summaryBadge;
|
||||||
return { summaryBadge };
|
return { summaryBadge };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1764,10 +1802,17 @@ export function createModelFitChart() {
|
|||||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let cachedFitSvgRect = null;
|
||||||
plotStage.addEventListener('mousemove', (e) => {
|
plotStage.addEventListener('mousemove', (e) => {
|
||||||
if (!currentSamples.length) return;
|
if (!currentSamples.length) return;
|
||||||
const rect = svg.getBoundingClientRect();
|
if (!cachedFitSvgRect) {
|
||||||
if (!rect || rect.width <= 0) return;
|
cachedFitSvgRect = svg.getBoundingClientRect();
|
||||||
|
}
|
||||||
|
const rect = cachedFitSvgRect;
|
||||||
|
if (!rect || rect.width <= 0) {
|
||||||
|
cachedFitSvgRect = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||||
let lo = 0;
|
let lo = 0;
|
||||||
let hi = currentSamples.length - 1;
|
let hi = currentSamples.length - 1;
|
||||||
@@ -1785,12 +1830,16 @@ export function createModelFitChart() {
|
|||||||
}
|
}
|
||||||
showHoverAt(bestIdx);
|
showHoverAt(bestIdx);
|
||||||
});
|
});
|
||||||
plotStage.addEventListener('mouseleave', clearHover);
|
plotStage.addEventListener('mouseleave', () => {
|
||||||
|
cachedFitSvgRect = null;
|
||||||
|
clearHover();
|
||||||
|
});
|
||||||
|
|
||||||
let resizeObs = null;
|
let resizeObs = null;
|
||||||
let onWinResize = null;
|
let onWinResize = null;
|
||||||
if (typeof ResizeObserver === 'function') {
|
if (typeof ResizeObserver === 'function') {
|
||||||
resizeObs = new ResizeObserver(() => {
|
resizeObs = new ResizeObserver(() => {
|
||||||
|
cachedFitSvgRect = null;
|
||||||
if (syncViewWidth() && lastUpdateParams) {
|
if (syncViewWidth() && lastUpdateParams) {
|
||||||
lastSig = '';
|
lastSig = '';
|
||||||
update(lastUpdateParams);
|
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) {
|
function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) {
|
||||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
const wrapRect = getCachedWrapRect();
|
||||||
const wrapW =
|
const wrapW =
|
||||||
wrapRect && wrapRect.width > 0
|
wrapRect && wrapRect.width > 0
|
||||||
? wrapRect.width
|
? wrapRect.width
|
||||||
@@ -438,13 +457,8 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
? wrapRect.height
|
? wrapRect.height
|
||||||
: Number(chartWrap.offsetHeight || VIEW_H);
|
: Number(chartWrap.offsetHeight || VIEW_H);
|
||||||
|
|
||||||
const tipRect = tooltipEl.getBoundingClientRect?.() || null;
|
const tipW = Number(tooltipEl.offsetWidth || 0) || 216;
|
||||||
const tipW =
|
const tipH = Number(tooltipEl.offsetHeight || 0) || 104;
|
||||||
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 hasPointer =
|
const hasPointer =
|
||||||
pointer &&
|
pointer &&
|
||||||
@@ -457,8 +471,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
|
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
|
||||||
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
|
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
|
||||||
|
|
||||||
|
if (cachedClipRect === undefined) {
|
||||||
const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null;
|
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(
|
const hasClip = Boolean(
|
||||||
clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0
|
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 =
|
const wrapW =
|
||||||
wrapRect && wrapRect.width > 0
|
wrapRect && wrapRect.width > 0
|
||||||
? wrapRect.width
|
? wrapRect.width
|
||||||
@@ -571,7 +588,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
populateTooltipContent(slot);
|
populateTooltipContent(slot);
|
||||||
}
|
}
|
||||||
|
|
||||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
const wrapRect = getCachedWrapRect();
|
||||||
const cellRect = targetCell.getBoundingClientRect?.() || null;
|
const cellRect = targetCell.getBoundingClientRect?.() || null;
|
||||||
const wrapW =
|
const wrapW =
|
||||||
wrapRect && wrapRect.width > 0
|
wrapRect && wrapRect.width > 0
|
||||||
@@ -596,6 +613,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function clearHover() {
|
function clearHover() {
|
||||||
|
invalidateHoverRects();
|
||||||
cancelTipTrackRaf();
|
cancelTipTrackRaf();
|
||||||
hoveredIdx = -1;
|
hoveredIdx = -1;
|
||||||
lastPointer = null;
|
lastPointer = null;
|
||||||
@@ -642,8 +660,14 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
|
|
||||||
function handlePointerMove(e) {
|
function handlePointerMove(e) {
|
||||||
if (currentIsHeatmap || !currentSlots.length) return;
|
if (currentIsHeatmap || !currentSlots.length) return;
|
||||||
const rect = svg.getBoundingClientRect();
|
if (!cachedSvgRect) {
|
||||||
if (!rect || rect.width <= 0) return;
|
cachedSvgRect = svg.getBoundingClientRect();
|
||||||
|
}
|
||||||
|
const rect = cachedSvgRect;
|
||||||
|
if (!rect || rect.width <= 0) {
|
||||||
|
cachedSvgRect = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||||
@@ -686,8 +710,12 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
return 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) {
|
if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) {
|
||||||
|
cachedHmGridRect = null;
|
||||||
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
||||||
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
||||||
}
|
}
|
||||||
@@ -842,6 +870,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
|||||||
let onWinResize = null;
|
let onWinResize = null;
|
||||||
if (typeof ResizeObserver === 'function') {
|
if (typeof ResizeObserver === 'function') {
|
||||||
resizeObs = new ResizeObserver(() => {
|
resizeObs = new ResizeObserver(() => {
|
||||||
|
invalidateHoverRects();
|
||||||
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||||
lastRenderSig = '';
|
lastRenderSig = '';
|
||||||
update(currentSlots);
|
update(currentSlots);
|
||||||
|
|||||||
@@ -932,6 +932,51 @@ function getLeftSidebarRightEdge(vw) {
|
|||||||
/**
|
/**
|
||||||
* 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
|
* 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `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() {
|
export function mountWindowOverlay() {
|
||||||
if (typeof window === 'undefined' || typeof document === 'undefined') return null;
|
if (typeof window === 'undefined' || typeof document === 'undefined') return null;
|
||||||
|
|
||||||
@@ -1123,10 +1168,7 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
const capsuleShadow = capsuleHost.attachShadow({ mode: 'open' });
|
const capsuleShadow = capsuleHost.attachShadow({ mode: 'open' });
|
||||||
|
attachShadowStyles(capsuleShadow, stylesCss, { slimCapsule: true });
|
||||||
const capsuleStyleEl = document.createElement('style');
|
|
||||||
capsuleStyleEl.textContent = stylesCss;
|
|
||||||
capsuleShadow.appendChild(capsuleStyleEl);
|
|
||||||
|
|
||||||
// 左侧无边框多会话实时触发按钮(固定预占宽度,不随运行数跳动)
|
// 左侧无边框多会话实时触发按钮(固定预占宽度,不随运行数跳动)
|
||||||
const multiDot = h('span', { className: 'wm-multi-dot' });
|
const multiDot = h('span', { className: 'wm-multi-dot' });
|
||||||
@@ -1346,10 +1388,7 @@ export function mountWindowOverlay() {
|
|||||||
portalHost.id = PORTAL_HOST_ID;
|
portalHost.id = PORTAL_HOST_ID;
|
||||||
portalHost.className = 'wm-portal-host';
|
portalHost.className = 'wm-portal-host';
|
||||||
const portalShadow = portalHost.attachShadow({ mode: 'open' });
|
const portalShadow = portalHost.attachShadow({ mode: 'open' });
|
||||||
|
attachShadowStyles(portalShadow, stylesCss, { slimCapsule: false });
|
||||||
const portalStyleEl = document.createElement('style');
|
|
||||||
portalStyleEl.textContent = stylesCss;
|
|
||||||
portalShadow.appendChild(portalStyleEl);
|
|
||||||
|
|
||||||
const initialSettings = telemetryStore.getState().telemetry?.settings;
|
const initialSettings = telemetryStore.getState().telemetry?.settings;
|
||||||
|
|
||||||
@@ -1460,9 +1499,9 @@ export function mountWindowOverlay() {
|
|||||||
[multiHeaderEl, multiEmptyEl, multiRunningWidget.el]
|
[multiHeaderEl, multiEmptyEl, multiRunningWidget.el]
|
||||||
);
|
);
|
||||||
|
|
||||||
// 完整四标签悬浮容器
|
// 完整四标签悬浮容器(首次打开主弹窗时按需懒挂载 App,彻底消除宿主窗口冷启动开销)
|
||||||
uiStore.setState({ monitorVisible: false });
|
uiStore.setState({ monitorVisible: false });
|
||||||
const appInstance = App();
|
let appInstance = null;
|
||||||
const popoverEl = h(
|
const popoverEl = h(
|
||||||
'div',
|
'div',
|
||||||
{
|
{
|
||||||
@@ -1471,9 +1510,17 @@ export function mountWindowOverlay() {
|
|||||||
'aria-label': t('capsule.ariaMonitor'),
|
'aria-label': t('capsule.ariaMonitor'),
|
||||||
hidden: true,
|
hidden: true,
|
||||||
},
|
},
|
||||||
[appInstance.el]
|
[]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
function ensureAppMounted() {
|
||||||
|
if (!appInstance) {
|
||||||
|
appInstance = App();
|
||||||
|
popoverEl.appendChild(appInstance.el);
|
||||||
|
}
|
||||||
|
return appInstance;
|
||||||
|
}
|
||||||
|
|
||||||
function syncPortalAppearance(settings) {
|
function syncPortalAppearance(settings) {
|
||||||
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
|
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
|
||||||
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
|
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
|
||||||
@@ -2218,6 +2265,7 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function refreshActiveViewScrollbars() {
|
function refreshActiveViewScrollbars() {
|
||||||
|
if (!appInstance) return;
|
||||||
const activeView = uiStore.getState().activeView;
|
const activeView = uiStore.getState().activeView;
|
||||||
const refs = appInstance.refs;
|
const refs = appInstance.refs;
|
||||||
if (activeView === 'overview') {
|
if (activeView === 'overview') {
|
||||||
@@ -2315,6 +2363,9 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
if (popoverOpen === targetOpen) return;
|
if (popoverOpen === targetOpen) return;
|
||||||
popoverOpen = targetOpen;
|
popoverOpen = targetOpen;
|
||||||
|
if (popoverOpen) {
|
||||||
|
ensureAppMounted();
|
||||||
|
}
|
||||||
patchClasses(capsuleBtn, { 'is-open': popoverOpen });
|
patchClasses(capsuleBtn, { 'is-open': popoverOpen });
|
||||||
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
|
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
|
||||||
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
|
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
|
||||||
@@ -2670,6 +2721,40 @@ export function mountWindowOverlay() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let hostDomObserver = null;
|
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 {
|
try {
|
||||||
if (typeof ResizeObserver !== 'undefined') {
|
if (typeof ResizeObserver !== 'undefined') {
|
||||||
resizeObserver = new ResizeObserver(() => updateResponsiveLayout());
|
resizeObserver = new ResizeObserver(() => updateResponsiveLayout());
|
||||||
@@ -2708,14 +2793,7 @@ export function mountWindowOverlay() {
|
|||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
syncHostRouteIfChanged();
|
scheduleHostDomMutationCheck();
|
||||||
if (!observedWorkbench) {
|
|
||||||
ensureWorkbenchThemeObserved();
|
|
||||||
}
|
|
||||||
const dock = resolveRuntimeDockTarget();
|
|
||||||
if (!isDockPlacementSynced(dock)) {
|
|
||||||
scheduleDockSync();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
hostDomObserver.observe(document.body, {
|
hostDomObserver.observe(document.body, {
|
||||||
childList: true,
|
childList: true,
|
||||||
@@ -2897,6 +2975,14 @@ export function mountWindowOverlay() {
|
|||||||
cancelAnimationFrame(dockRafId);
|
cancelAnimationFrame(dockRafId);
|
||||||
dockRafId = 0;
|
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();
|
stopPolling();
|
||||||
stopAsyncTelemetryLoop();
|
stopAsyncTelemetryLoop();
|
||||||
unsubStore();
|
unsubStore();
|
||||||
@@ -2928,7 +3014,7 @@ export function mountWindowOverlay() {
|
|||||||
hoverWidgetHost.destroy();
|
hoverWidgetHost.destroy();
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
try {
|
||||||
appInstance.destroy();
|
appInstance?.destroy?.();
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
try {
|
||||||
capsuleHost.remove();
|
capsuleHost.remove();
|
||||||
|
|||||||
@@ -7,37 +7,16 @@
|
|||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||||
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||||
|
import {
|
||||||
|
copyPlainTextToClipboard,
|
||||||
|
createCopiedFeedbackController,
|
||||||
|
} from '../../core/stepInspector.js';
|
||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
import { t } from '../../i18n/index.js';
|
import { t } from '../../i18n/index.js';
|
||||||
import { triggerBridgeHostRelaunch } from '../../store/telemetryStore.js';
|
import { triggerBridgeHostRelaunch } from '../../store/telemetryStore.js';
|
||||||
|
|
||||||
const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0';
|
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({
|
export const BridgeStatusNotice = defineComponent({
|
||||||
name: 'BridgeStatusNotice',
|
name: 'BridgeStatusNotice',
|
||||||
setup({ props, onCleanup }) {
|
setup({ props, onCleanup }) {
|
||||||
@@ -49,11 +28,16 @@ export const BridgeStatusNotice = defineComponent({
|
|||||||
hostPlatform: 'win32',
|
hostPlatform: 'win32',
|
||||||
};
|
};
|
||||||
let dismissed = false;
|
let dismissed = false;
|
||||||
let copied = false;
|
|
||||||
let copiedTimer = null;
|
|
||||||
let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed'
|
let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed'
|
||||||
let relaunchResetTimer = null;
|
let relaunchResetTimer = null;
|
||||||
let destroyed = false;
|
let destroyed = false;
|
||||||
|
const copyFeedback = createCopiedFeedbackController({
|
||||||
|
durationMs: 1800,
|
||||||
|
onCleanup,
|
||||||
|
onChange: () => {
|
||||||
|
if (!destroyed) syncActionButtons();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' });
|
const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' });
|
||||||
const titleEl = h('strong', { className: 'settings-bridge-title', text: '' });
|
const titleEl = h('strong', { className: 'settings-bridge-title', text: '' });
|
||||||
@@ -146,18 +130,9 @@ export const BridgeStatusNotice = defineComponent({
|
|||||||
type: 'button',
|
type: 'button',
|
||||||
className: 'btn-ghost-sm settings-bridge-copy-btn',
|
className: 'btn-ghost-sm settings-bridge-copy-btn',
|
||||||
onClick: async () => {
|
onClick: async () => {
|
||||||
await copyTextToClipboard(LAUNCH_FLAG_TEXT);
|
await copyPlainTextToClipboard(LAUNCH_FLAG_TEXT);
|
||||||
if (destroyed) return;
|
if (destroyed) return;
|
||||||
copied = true;
|
copyFeedback.trigger(true);
|
||||||
if (copiedTimer) clearTimeout(copiedTimer);
|
|
||||||
syncActionButtons();
|
|
||||||
copiedTimer = setTimeout(() => {
|
|
||||||
copiedTimer = null;
|
|
||||||
if (destroyed) return;
|
|
||||||
copied = false;
|
|
||||||
syncActionButtons();
|
|
||||||
}, 1800);
|
|
||||||
copiedTimer?.unref?.();
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[copyBtnIconEl, copyBtnTextEl]
|
[copyBtnIconEl, copyBtnTextEl]
|
||||||
@@ -200,10 +175,11 @@ export const BridgeStatusNotice = defineComponent({
|
|||||||
: t('settings.bridge.relaunchBtn')
|
: t('settings.bridge.relaunchBtn')
|
||||||
);
|
);
|
||||||
|
|
||||||
patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy');
|
const isCopied = copyFeedback.isCopied(true);
|
||||||
|
patchSvgIcon(copyBtnIconEl, isCopied ? 'check' : 'copy');
|
||||||
patchText(
|
patchText(
|
||||||
copyBtnTextEl,
|
copyBtnTextEl,
|
||||||
copied
|
isCopied
|
||||||
? t('settings.bridge.copiedBtn')
|
? t('settings.bridge.copiedBtn')
|
||||||
: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT })
|
: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT })
|
||||||
);
|
);
|
||||||
@@ -288,10 +264,6 @@ export const BridgeStatusNotice = defineComponent({
|
|||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
destroyed = true;
|
destroyed = true;
|
||||||
if (copiedTimer) {
|
|
||||||
clearTimeout(copiedTimer);
|
|
||||||
copiedTimer = null;
|
|
||||||
}
|
|
||||||
if (relaunchResetTimer) {
|
if (relaunchResetTimer) {
|
||||||
clearTimeout(relaunchResetTimer);
|
clearTimeout(relaunchResetTimer);
|
||||||
relaunchResetTimer = null;
|
relaunchResetTimer = null;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||||
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||||
|
import { copyPlainTextToClipboard } from '../../core/stepInspector.js';
|
||||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
@@ -14,35 +15,11 @@ import {
|
|||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { CustomScrollbar } from '../ui/CustomScrollbar.js';
|
import { CustomScrollbar } from '../ui/CustomScrollbar.js';
|
||||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||||
|
import { createSearchInput } from '../ui/SearchInput.js';
|
||||||
import { SegmentedControl } from '../ui/SegmentedControl.js';
|
import { SegmentedControl } from '../ui/SegmentedControl.js';
|
||||||
|
|
||||||
const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project';
|
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) {
|
function smigGetClientLabel(clientId) {
|
||||||
if (clientId === 'cli') return t('settings.oth.migClientCli');
|
if (clientId === 'cli') return t('settings.oth.migClientCli');
|
||||||
if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy');
|
if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy');
|
||||||
@@ -202,41 +179,27 @@ export const SessionMigrationCard = defineComponent({
|
|||||||
projectSelect.el,
|
projectSelect.el,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
searchInput = h('input', {
|
const searchBox = createSearchInput({
|
||||||
type: 'text',
|
wrapClassName: 'smig-search-wrap',
|
||||||
className: 'smig-search-input',
|
iconClassName: 'smig-search-icon',
|
||||||
autocomplete: 'off',
|
inputClassName: 'smig-search-input',
|
||||||
spellcheck: 'false',
|
clearClassName: 'smig-search-clear',
|
||||||
placeholder: t('settings.oth.migSearchPlaceholder'),
|
placeholder: t('settings.oth.migSearchPlaceholder'),
|
||||||
value: '',
|
clearAriaLabel: t('select.clearSearch'),
|
||||||
});
|
closeIconSize: 10,
|
||||||
searchClearBtn = h(
|
onInput: (val) => {
|
||||||
'button',
|
searchQuery = String(val || '').trim();
|
||||||
{
|
renderSessionList();
|
||||||
type: 'button',
|
},
|
||||||
className: 'smig-search-clear',
|
onClear: () => {
|
||||||
hidden: true,
|
|
||||||
'aria-label': t('select.clearSearch'),
|
|
||||||
onClick: () => {
|
|
||||||
searchQuery = '';
|
searchQuery = '';
|
||||||
searchInput.value = '';
|
|
||||||
patchAttr(searchClearBtn, 'hidden', true);
|
|
||||||
renderSessionList();
|
renderSessionList();
|
||||||
searchInput.focus?.();
|
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' }, [
|
searchInput = searchBox.inputEl;
|
||||||
createSvgIcon('search', { size: 12, className: 'smig-search-icon' }),
|
searchClearBtn = searchBox.clearBtnEl;
|
||||||
searchInput,
|
const searchWrap = searchBox.el;
|
||||||
searchClearBtn,
|
|
||||||
]);
|
|
||||||
|
|
||||||
toggleAllBtn = h('button', {
|
toggleAllBtn = h('button', {
|
||||||
type: 'button',
|
type: 'button',
|
||||||
@@ -662,7 +625,7 @@ export const SessionMigrationCard = defineComponent({
|
|||||||
className: 'btn-ghost-sm smig-cmd-copy',
|
className: 'btn-ghost-sm smig-cmd-copy',
|
||||||
text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'),
|
text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'),
|
||||||
onClick: async () => {
|
onClick: async () => {
|
||||||
const ok = await smigCopyText(item.resumeCommand);
|
const ok = await copyPlainTextToClipboard(item.resumeCommand);
|
||||||
if (!ok || destroyed) return;
|
if (!ok || destroyed) return;
|
||||||
copiedCmdId = item.newCascadeId;
|
copiedCmdId = item.newCascadeId;
|
||||||
renderResultBox();
|
renderResultBox();
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
} from '../../core/domPatch.js';
|
} from '../../core/domPatch.js';
|
||||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
|
import { createSearchInput } from './SearchInput.js';
|
||||||
|
|
||||||
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
|
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
|
||||||
const arr = Array.isArray(rawValue)
|
const arr = Array.isArray(rawValue)
|
||||||
@@ -105,44 +106,29 @@ export const CustomSelect = defineComponent({
|
|||||||
[leadIcon, triggerLabel, chevronIcon]
|
[leadIcon, triggerLabel, chevronIcon]
|
||||||
);
|
);
|
||||||
|
|
||||||
const searchIcon = createSvgIcon('search', { size: 12, className: 'select-search-icon' });
|
const searchBox = createSearchInput({
|
||||||
const searchInput = h('input', {
|
wrapClassName: 'select-search-wrap',
|
||||||
type: 'text',
|
iconClassName: 'select-search-icon',
|
||||||
className: 'select-search-input',
|
inputClassName: 'select-search-input',
|
||||||
autocomplete: 'off',
|
clearClassName: 'select-search-clear',
|
||||||
spellcheck: 'false',
|
|
||||||
placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'),
|
placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'),
|
||||||
onClick: (e) => e.stopPropagation(),
|
clearAriaLabel: t('select.clearSearch'),
|
||||||
onInput: (e) => {
|
hidden: true,
|
||||||
searchQuery = String(e?.target?.value ?? searchInput.value ?? '');
|
stopClickPropagation: true,
|
||||||
|
closeIconSize: 10,
|
||||||
|
onInput: (val) => {
|
||||||
|
searchQuery = val;
|
||||||
focusedIndex = 0;
|
focusedIndex = 0;
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
},
|
},
|
||||||
onKeydown: handleKeydown,
|
onClear: () => {
|
||||||
});
|
|
||||||
const searchClearBtn = h(
|
|
||||||
'button',
|
|
||||||
{
|
|
||||||
type: 'button',
|
|
||||||
className: 'select-search-clear',
|
|
||||||
hidden: true,
|
|
||||||
'aria-label': t('select.clearSearch'),
|
|
||||||
onClick: (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
clearSearchQuery(true);
|
clearSearchQuery(true);
|
||||||
},
|
},
|
||||||
},
|
onKeydown: handleKeydown,
|
||||||
[createSvgIcon('close', { size: 10 })]
|
});
|
||||||
);
|
const searchWrap = searchBox.el;
|
||||||
const searchWrap = h(
|
const searchInput = searchBox.inputEl;
|
||||||
'div',
|
const searchClearBtn = searchBox.clearBtnEl;
|
||||||
{
|
|
||||||
className: 'select-search-wrap',
|
|
||||||
hidden: true,
|
|
||||||
onClick: (e) => e.stopPropagation(),
|
|
||||||
},
|
|
||||||
[searchIcon, searchInput, searchClearBtn]
|
|
||||||
);
|
|
||||||
|
|
||||||
const optionsListEl = h('div', { className: 'select-options-list' });
|
const optionsListEl = h('div', { className: 'select-options-list' });
|
||||||
const emptyHintEl = h('div', {
|
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`)并返回真实绝对路径,
|
* 优先调用本机后端 `/api/export-file` 落盘到用户 Downloads(或插件 `.data/exports`)并返回真实绝对路径,
|
||||||
* 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮;
|
* 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮;
|
||||||
* 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。
|
* 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
import { showUiToast } from '../store/uiStore.js';
|
import { showUiToast } from '../store/uiStore.js';
|
||||||
import { callSidecarApi, isWindowOverlayMode } from './httpClient.js';
|
import { callSidecarApi, isWindowOverlayMode } from './httpClient.js';
|
||||||
import { triggerTextFileDownload } from './settingsBackup.js';
|
import { triggerBlobDownload } from './settingsBackup.js';
|
||||||
import { copyPlainTextToClipboard } from './stepInspector.js';
|
import { copyPlainTextToClipboard } from './stepInspector.js';
|
||||||
import { uint8ArrayToBase64 } from './xlsxBuilder.js';
|
import { uint8ArrayToBase64 } from './xlsxBuilder.js';
|
||||||
|
|
||||||
@@ -17,36 +17,6 @@ function isHostEmbeddedWebview() {
|
|||||||
return Boolean(window.sidecar?.fetch) || isWindowOverlayMode();
|
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) {
|
function getPickerTypesForFilename(filename, mimeType) {
|
||||||
const lower = String(filename || '').toLowerCase();
|
const lower = String(filename || '').toLowerCase();
|
||||||
if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) {
|
if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) {
|
||||||
@@ -140,28 +110,15 @@ async function requestLocalBackendExport(payload) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录),
|
* 共享多阶段导出与 Toast 反馈骨架(本机落盘 -> 宿主拦截保护 -> File System Access Picker -> Blob 下载)。
|
||||||
* 仅在真正独立浏览器上下文(非 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 }>}
|
|
||||||
*/
|
*/
|
||||||
export async function exportTextFileWithFeedback(
|
async function runExportPipelineWithFeedback({
|
||||||
filename,
|
safeName,
|
||||||
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,
|
|
||||||
mimeType,
|
mimeType,
|
||||||
});
|
backendPayload,
|
||||||
|
writablePayload,
|
||||||
|
}) {
|
||||||
|
const { res: localRes } = await requestLocalBackendExport(backendPayload);
|
||||||
if (localRes && localRes.ok && localRes.filePath) {
|
if (localRes && localRes.ok && localRes.filePath) {
|
||||||
const savedPath = String(localRes.filePath);
|
const savedPath = String(localRes.filePath);
|
||||||
const savedName = String(localRes.fileName || safeName);
|
const savedName = String(localRes.fileName || safeName);
|
||||||
@@ -178,7 +135,7 @@ export async function exportTextFileWithFeedback(
|
|||||||
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
|
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
|
// 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
|
||||||
if (isHostEmbeddedWebview()) {
|
if (isHostEmbeddedWebview()) {
|
||||||
showUiToast({
|
showUiToast({
|
||||||
message: t('export.failed'),
|
message: t('export.failed'),
|
||||||
@@ -189,7 +146,6 @@ export async function exportTextFileWithFeedback(
|
|||||||
return { ok: false, mode: 'failed' };
|
return { ok: false, mode: 'failed' };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 普通独立浏览器原生「另存为」对话框
|
|
||||||
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
|
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
|
||||||
try {
|
try {
|
||||||
const handle = await window.showSaveFilePicker({
|
const handle = await window.showSaveFilePicker({
|
||||||
@@ -197,7 +153,7 @@ export async function exportTextFileWithFeedback(
|
|||||||
types: getPickerTypesForFilename(safeName, mimeType),
|
types: getPickerTypesForFilename(safeName, mimeType),
|
||||||
});
|
});
|
||||||
const writable = await handle.createWritable();
|
const writable = await handle.createWritable();
|
||||||
await writable.write(text);
|
await writable.write(writablePayload);
|
||||||
await writable.close();
|
await writable.close();
|
||||||
const pickedName = handle.name || safeName;
|
const pickedName = handle.name || safeName;
|
||||||
showUiToast({
|
showUiToast({
|
||||||
@@ -210,12 +166,10 @@ export async function exportTextFileWithFeedback(
|
|||||||
if (err && err.name === 'AbortError') {
|
if (err && err.name === 'AbortError') {
|
||||||
return { ok: false, mode: 'cancelled' };
|
return { ok: false, mode: 'cancelled' };
|
||||||
}
|
}
|
||||||
// 沙箱/iframe 抛出 SecurityError 等时继续降级到 Blob 下载
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 独立浏览器标准 Blob 兜底下载
|
const ok = triggerBlobDownload(safeName, writablePayload, mimeType);
|
||||||
const ok = triggerTextFileDownload(safeName, text, mimeType);
|
|
||||||
if (ok) {
|
if (ok) {
|
||||||
showUiToast({
|
showUiToast({
|
||||||
message: t('export.savedBrowser', { file: safeName }),
|
message: t('export.savedBrowser', { file: safeName }),
|
||||||
@@ -234,9 +188,36 @@ export async function exportTextFileWithFeedback(
|
|||||||
return { ok: false, mode: 'failed' };
|
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 工作簿)。
|
* 统一二进制文件导出入口(用于原生 `.xlsx` Excel 工作簿)。
|
||||||
* 优先转 Base64 经本机后端落盘到 Downloads 并展示完整路径 + 「打开位置」直达按钮。
|
|
||||||
*
|
*
|
||||||
* @param {string} filename
|
* @param {string} filename
|
||||||
* @param {Uint8Array} bytes
|
* @param {Uint8Array} bytes
|
||||||
@@ -253,80 +234,17 @@ export async function exportBinaryFileWithFeedback(
|
|||||||
showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 });
|
showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 });
|
||||||
return { ok: false, mode: 'failed' };
|
return { ok: false, mode: 'failed' };
|
||||||
}
|
}
|
||||||
|
return runExportPipelineWithFeedback({
|
||||||
const base64Content = uint8ArrayToBase64(bytes);
|
safeName,
|
||||||
const { res: localRes } = await requestLocalBackendExport({
|
mimeType,
|
||||||
|
backendPayload: {
|
||||||
filename: safeName,
|
filename: safeName,
|
||||||
content: base64Content,
|
content: uint8ArrayToBase64(bytes),
|
||||||
encoding: 'base64',
|
encoding: 'base64',
|
||||||
mimeType,
|
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',
|
writablePayload: bytes,
|
||||||
durationMs: 7000,
|
|
||||||
});
|
});
|
||||||
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`).
|
* @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`).
|
||||||
* 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。
|
* 通过单一声明式字段描述符表同时驱动导出与导入归一化,消除双遍手写 30 个键的漏同步风险。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -36,17 +36,17 @@ function sanitizePositiveBudgetNum(val) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。
|
* 在浏览器端通过内存 Blob 触发文件下载(统一承载文本与二进制载荷)。
|
||||||
*
|
*
|
||||||
* @param {string} filename
|
* @param {string} filename
|
||||||
* @param {string} content
|
* @param {BlobPart} blobPart
|
||||||
* @param {string} [mimeType]
|
* @param {string} [mimeType]
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function triggerTextFileDownload(
|
export function triggerBlobDownload(
|
||||||
filename,
|
filename,
|
||||||
content,
|
blobPart,
|
||||||
mimeType = 'application/json;charset=utf-8'
|
mimeType = 'application/octet-stream'
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
if (
|
if (
|
||||||
@@ -57,11 +57,11 @@ export function triggerTextFileDownload(
|
|||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const blob = new Blob([String(content ?? '')], { type: mimeType });
|
const blob = new Blob([blobPart], { type: mimeType });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.setAttribute('href', url);
|
a.setAttribute('href', url);
|
||||||
a.setAttribute('download', String(filename || 'export.json'));
|
a.setAttribute('download', String(filename || 'export.dat'));
|
||||||
a.style.display = 'none';
|
a.style.display = 'none';
|
||||||
document.body?.appendChild?.(a);
|
document.body?.appendChild?.(a);
|
||||||
a.click?.();
|
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 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。
|
* 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。
|
||||||
*
|
*
|
||||||
@@ -85,46 +222,15 @@ export function triggerTextFileDownload(
|
|||||||
*/
|
*/
|
||||||
export function buildExportableSettingsJson(settings = {}) {
|
export function buildExportableSettingsJson(settings = {}) {
|
||||||
const src = settings && typeof settings === 'object' ? settings : {};
|
const src = settings && typeof settings === 'object' ? settings : {};
|
||||||
const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
const outSettings = {};
|
||||||
const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true;
|
for (const desc of PORTABLE_SETTING_DESCRIPTORS) {
|
||||||
|
desc.exportTo(src, outSettings);
|
||||||
|
}
|
||||||
const payload = {
|
const payload = {
|
||||||
schema: SETTINGS_BACKUP_SCHEMA,
|
schema: SETTINGS_BACKUP_SCHEMA,
|
||||||
version: 1,
|
version: 1,
|
||||||
exportedAt: new Date().toISOString(),
|
exportedAt: new Date().toISOString(),
|
||||||
settings: {
|
settings: outSettings,
|
||||||
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
|
|
||||||
),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
return `${JSON.stringify(payload, null, 2)}\n`;
|
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 hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k);
|
||||||
const patch = {};
|
const patch = {};
|
||||||
|
|
||||||
if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language);
|
for (const desc of PORTABLE_SETTING_DESCRIPTORS) {
|
||||||
if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent);
|
desc.importTo(src, hasKey, patch);
|
||||||
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
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const appliedCount = Object.keys(patch).length;
|
const appliedCount = Object.keys(patch).length;
|
||||||
|
|||||||
@@ -340,7 +340,11 @@ export async function copyPlainTextToClipboard(text) {
|
|||||||
document.body.appendChild(ta);
|
document.body.appendChild(ta);
|
||||||
ta.select?.();
|
ta.select?.();
|
||||||
const ok = document.execCommand('copy');
|
const ok = document.execCommand('copy');
|
||||||
ta.remove?.();
|
if (typeof ta.remove === 'function') {
|
||||||
|
ta.remove();
|
||||||
|
} else {
|
||||||
|
document.body.removeChild?.(ta);
|
||||||
|
}
|
||||||
return Boolean(ok);
|
return Boolean(ok);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -348,3 +352,63 @@ export async function copyPlainTextToClipboard(text) {
|
|||||||
}
|
}
|
||||||
return false;
|
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;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-wrap {
|
.ui-search-wrap {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
padding: 4px 7px;
|
padding: 2px 8px;
|
||||||
margin-bottom: 4px;
|
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
background: var(--surface-bg);
|
background: var(--surface-subtle);
|
||||||
flex-shrink: 0;
|
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;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-wrap:focus-within {
|
.ui-search-wrap:focus-within {
|
||||||
border-color: var(--accent-primary);
|
border-color: var(--accent-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-icon {
|
.ui-search-icon {
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-input {
|
.ui-search-input {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
border: none;
|
border: none;
|
||||||
@@ -414,11 +417,11 @@
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-input::placeholder {
|
.ui-search-input::placeholder {
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-clear {
|
.ui-search-clear {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -431,17 +434,27 @@
|
|||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
flex-shrink: 0;
|
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);
|
color: var(--text-primary);
|
||||||
background: var(--surface-hover);
|
background: var(--surface-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-clear[hidden] {
|
.ui-search-clear[hidden] {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.select-search-wrap {
|
||||||
|
padding: 4px 7px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
background: var(--surface-bg);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.select-options-list {
|
.select-options-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -750,6 +763,10 @@
|
|||||||
opacity: 0;
|
opacity: 0;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 0;
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmented:hover .seg-glider,
|
||||||
|
.segmented:focus-within .seg-glider {
|
||||||
will-change: transform, width;
|
will-change: transform, width;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -807,6 +824,20 @@
|
|||||||
font-weight: 600;
|
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) --- */
|
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||||
.custom-scroll-host {
|
.custom-scroll-host {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -866,10 +897,14 @@
|
|||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||||
will-change: transform, height;
|
|
||||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
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:hover .scrollbar-thumb,
|
||||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
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 {
|
[data-modern-ui="true"] .segmented {
|
||||||
|
--seg-pad: 2px;
|
||||||
padding: 2px;
|
padding: 2px;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
background: var(--modern-inline-track-bg);
|
background: var(--modern-inline-track-bg);
|
||||||
@@ -631,7 +632,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||||
[data-modern-ui="true"] .collapsible-body,
|
[data-modern-ui="true"] .collapsible-body,
|
||||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||||
[data-modern-ui="true"] .settings-account-entry,
|
|
||||||
[data-modern-ui="true"] .dt-time-row {
|
[data-modern-ui="true"] .dt-time-row {
|
||||||
border-top: none;
|
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"] .number-input,
|
||||||
[data-modern-ui="true"] .dt-trigger,
|
[data-modern-ui="true"] .dt-trigger,
|
||||||
[data-modern-ui="true"] .dt-mini-step,
|
[data-modern-ui="true"] .dt-mini-step,
|
||||||
[data-modern-ui="true"] .settings-text-input,
|
[data-modern-ui="true"] .settings-text-input {
|
||||||
[data-modern-ui="true"] .settings-account-form input {
|
|
||||||
border: none;
|
border: none;
|
||||||
background: var(--modern-surface-subtle);
|
background: var(--modern-surface-subtle);
|
||||||
transition:
|
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"] .number-input:focus-within,
|
||||||
[data-modern-ui="true"] .settings-text-input:focus,
|
[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"] .smig-search-wrap:focus-within,
|
||||||
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
||||||
border: none;
|
border: none;
|
||||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
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"] .smig-search-wrap,
|
||||||
[data-modern-ui="true"] .steps-search-wrap {
|
[data-modern-ui="true"] .steps-search-wrap {
|
||||||
border: none;
|
border: none;
|
||||||
|
|||||||
@@ -641,60 +641,6 @@
|
|||||||
line-height: 1.35;
|
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 {
|
.settings-context-model .select-option-meta {
|
||||||
max-width: 62%;
|
max-width: 62%;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
@@ -1067,69 +1013,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.smig-search-wrap {
|
.smig-search-wrap {
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
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] {
|
.smig-search-clear[hidden] {
|
||||||
|
|||||||
@@ -1238,70 +1238,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.steps-search-wrap {
|
.steps-search-wrap {
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
flex: 1 1 160px;
|
flex: 1 1 160px;
|
||||||
min-width: 120px;
|
min-width: 120px;
|
||||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
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] {
|
.steps-search-clear[hidden] {
|
||||||
|
|||||||
@@ -538,6 +538,8 @@ export const ConsumptionView = defineComponent({
|
|||||||
});
|
});
|
||||||
|
|
||||||
let activeHoverTargetEl = null;
|
let activeHoverTargetEl = null;
|
||||||
|
let cachedBreakdownRootRect = null;
|
||||||
|
let cachedBreakdownAnchorRect = null;
|
||||||
|
|
||||||
const popoverContent = createConsumptionBreakdownContent({
|
const popoverContent = createConsumptionBreakdownContent({
|
||||||
showModelDot: true,
|
showModelDot: true,
|
||||||
@@ -550,6 +552,8 @@ export const ConsumptionView = defineComponent({
|
|||||||
);
|
);
|
||||||
|
|
||||||
function hideBreakdownPopover() {
|
function hideBreakdownPopover() {
|
||||||
|
cachedBreakdownRootRect = null;
|
||||||
|
cachedBreakdownAnchorRect = null;
|
||||||
if (activeHoverTargetEl) {
|
if (activeHoverTargetEl) {
|
||||||
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
||||||
activeHoverTargetEl = null;
|
activeHoverTargetEl = null;
|
||||||
@@ -559,27 +563,29 @@ export const ConsumptionView = defineComponent({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function positionBreakdownPopover(anchorEl, pointerClientX = null, pointerClientY = null) {
|
function positionBreakdownPopover(anchorEl, pointerClientX = null, pointerClientY = null) {
|
||||||
const rootRect = rootEl.getBoundingClientRect?.() || {
|
if (!cachedBreakdownRootRect) {
|
||||||
|
cachedBreakdownRootRect = rootEl.getBoundingClientRect?.() || {
|
||||||
left: 0,
|
left: 0,
|
||||||
top: 0,
|
top: 0,
|
||||||
width: 360,
|
width: 360,
|
||||||
height: 600,
|
height: 600,
|
||||||
};
|
};
|
||||||
const anchorRect = anchorEl?.getBoundingClientRect?.() || {
|
}
|
||||||
|
const rootRect = cachedBreakdownRootRect;
|
||||||
|
if (!cachedBreakdownAnchorRect) {
|
||||||
|
cachedBreakdownAnchorRect = anchorEl?.getBoundingClientRect?.() || {
|
||||||
left: 0,
|
left: 0,
|
||||||
top: 0,
|
top: 0,
|
||||||
bottom: 0,
|
bottom: 0,
|
||||||
width: 0,
|
width: 0,
|
||||||
height: 0,
|
height: 0,
|
||||||
};
|
};
|
||||||
const tipRect = breakdownPopoverEl.getBoundingClientRect?.() || {
|
}
|
||||||
width: 216,
|
const anchorRect = cachedBreakdownAnchorRect;
|
||||||
height: 108,
|
const tipW = Number(breakdownPopoverEl.offsetWidth || 0) || 216;
|
||||||
};
|
const tipH = Number(breakdownPopoverEl.offsetHeight || 0) || 108;
|
||||||
const rootW = rootRect.width > 0 ? rootRect.width : 360;
|
const rootW = rootRect.width > 0 ? rootRect.width : 360;
|
||||||
const rootH = rootRect.height > 0 ? rootRect.height : 600;
|
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 hasPointerX = Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0;
|
||||||
const hasPointerY = Number.isFinite(pointerClientY) && pointerClientY > 0 && rootRect.height > 0;
|
const hasPointerY = Number.isFinite(pointerClientY) && pointerClientY > 0 && rootRect.height > 0;
|
||||||
@@ -625,6 +631,10 @@ export const ConsumptionView = defineComponent({
|
|||||||
}
|
}
|
||||||
if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) {
|
if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) {
|
||||||
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
patchClasses(activeHoverTargetEl, { 'is-hovered': false });
|
||||||
|
cachedBreakdownAnchorRect = null;
|
||||||
|
} else if (!activeHoverTargetEl) {
|
||||||
|
cachedBreakdownRootRect = null;
|
||||||
|
cachedBreakdownAnchorRect = null;
|
||||||
}
|
}
|
||||||
activeHoverTargetEl = anchorEl;
|
activeHoverTargetEl = anchorEl;
|
||||||
patchClasses(anchorEl, { 'is-hovered': true });
|
patchClasses(anchorEl, { 'is-hovered': true });
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ import {
|
|||||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||||
|
import { createSearchInput } from '../components/ui/SearchInput.js';
|
||||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||||
import { StepTableWidget } from '../components/widgets/StepTableWidget.js';
|
import { StepTableWidget } from '../components/widgets/StepTableWidget.js';
|
||||||
import { sortStepsByColumn } from '../registries/stepColumnRegistry.js';
|
import { sortStepsByColumn } from '../registries/stepColumnRegistry.js';
|
||||||
@@ -434,40 +435,30 @@ export const StepsDetailView = defineComponent({
|
|||||||
);
|
);
|
||||||
|
|
||||||
// --- 步骤搜索栏及快捷诊断芯片 ---
|
// --- 步骤搜索栏及快捷诊断芯片 ---
|
||||||
const stepSearchClearBtn = h(
|
const stepSearchBox = createSearchInput({
|
||||||
'button',
|
wrapClassName: 'steps-search-wrap',
|
||||||
{
|
iconClassName: 'steps-search-icon',
|
||||||
type: 'button',
|
inputClassName: 'steps-search-input',
|
||||||
className: 'steps-search-clear',
|
clearClassName: 'steps-search-clear',
|
||||||
hidden: true,
|
placeholder: t('steps.searchPlaceholder'),
|
||||||
'aria-label': t('steps.searchClearAria'),
|
ariaLabel: t('steps.searchPlaceholder'),
|
||||||
onclick: () => {
|
clearAriaLabel: t('steps.searchClearAria'),
|
||||||
|
closeIconSize: 11,
|
||||||
|
onInput: (val) => {
|
||||||
|
stepSearchQuery = String(val ?? '');
|
||||||
|
if (latestSlice) renderStepsData(latestSlice);
|
||||||
|
},
|
||||||
|
onClear: () => {
|
||||||
stepSearchQuery = '';
|
stepSearchQuery = '';
|
||||||
stepSearchInput.value = '';
|
|
||||||
patchAttr(stepSearchClearBtn, 'hidden', true);
|
|
||||||
if (latestSlice) renderStepsData(latestSlice);
|
if (latestSlice) renderStepsData(latestSlice);
|
||||||
stepSearchInput.focus?.();
|
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) => {
|
onKeydown: (e) => {
|
||||||
if (e?.key === 'Escape') {
|
if (e?.key === 'Escape') {
|
||||||
e.stopPropagation?.();
|
e.stopPropagation?.();
|
||||||
if (stepSearchQuery) {
|
if (stepSearchQuery) {
|
||||||
stepSearchQuery = '';
|
stepSearchQuery = '';
|
||||||
stepSearchInput.value = '';
|
stepSearchBox.setValue('');
|
||||||
patchAttr(stepSearchClearBtn, 'hidden', true);
|
|
||||||
if (latestSlice) renderStepsData(latestSlice);
|
if (latestSlice) renderStepsData(latestSlice);
|
||||||
} else {
|
} else {
|
||||||
stepSearchInput.blur?.();
|
stepSearchInput.blur?.();
|
||||||
@@ -475,11 +466,9 @@ export const StepsDetailView = defineComponent({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const stepSearchWrapEl = h('div', { className: 'steps-search-wrap' }, [
|
const stepSearchWrapEl = stepSearchBox.el;
|
||||||
createSvgIcon('search', { size: 12, className: 'steps-search-icon' }),
|
const stepSearchInput = stepSearchBox.inputEl;
|
||||||
stepSearchInput,
|
const stepSearchClearBtn = stepSearchBox.clearBtnEl;
|
||||||
stepSearchClearBtn,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const QUICK_CHIP_DEFS = [
|
const QUICK_CHIP_DEFS = [
|
||||||
{ key: 'anomaly', i18nKey: 'steps.chipAnomaly', tone: 'is-warn' },
|
{ key: 'anomaly', i18nKey: 'steps.chipAnomaly', tone: 'is-warn' },
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
|
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
|
||||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||||
|
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
|
||||||
|
|
||||||
function getLanguageOptions() {
|
function getLanguageOptions() {
|
||||||
return [
|
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() {
|
function getUpdateModeOptions() {
|
||||||
return [
|
return [
|
||||||
{ value: 'manual', label: t('settings.gen.updateManual') },
|
{ value: 'manual', label: t('settings.gen.updateManual') },
|
||||||
@@ -216,10 +210,10 @@ export const SettingsGeneralTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const modernUiSwitch = SegmentedControl({
|
const modernUiSwitch = ToggleSwitch({
|
||||||
ariaLabel: t('settings.gen.modernUi'),
|
ariaLabelKey: 'settings.gen.modernUi',
|
||||||
|
preset: 'modernUi',
|
||||||
modelValue: 'on',
|
modelValue: 'on',
|
||||||
options: getModernUiOptions(),
|
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
const nextModernUi = val !== 'off';
|
const nextModernUi = val !== 'off';
|
||||||
draftModernUi = nextModernUi;
|
draftModernUi = nextModernUi;
|
||||||
@@ -441,7 +435,6 @@ export const SettingsGeneralTab = defineComponent({
|
|||||||
});
|
});
|
||||||
modernUiSwitch.setProps({
|
modernUiSwitch.setProps({
|
||||||
modelValue: draftModernUi ? 'on' : 'off',
|
modelValue: draftModernUi ? 'on' : 'off',
|
||||||
options: getModernUiOptions(),
|
|
||||||
});
|
});
|
||||||
autoUpdateSelect.setProps({
|
autoUpdateSelect.setProps({
|
||||||
modelValue: draftPluginUpdateMode,
|
modelValue: draftPluginUpdateMode,
|
||||||
@@ -523,9 +516,7 @@ export const SettingsGeneralTab = defineComponent({
|
|||||||
options: getFontScaleOptions(),
|
options: getFontScaleOptions(),
|
||||||
});
|
});
|
||||||
modernUiSwitch.setProps({
|
modernUiSwitch.setProps({
|
||||||
ariaLabel: t('settings.gen.modernUi'),
|
|
||||||
modelValue: draftModernUi ? 'on' : 'off',
|
modelValue: draftModernUi ? 'on' : 'off',
|
||||||
options: getModernUiOptions(),
|
|
||||||
});
|
});
|
||||||
autoUpdateSelect.setProps({
|
autoUpdateSelect.setProps({
|
||||||
modelValue: draftPluginUpdateMode,
|
modelValue: draftPluginUpdateMode,
|
||||||
|
|||||||
@@ -27,17 +27,10 @@ import {
|
|||||||
saveSettingsPatch,
|
saveSettingsPatch,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { CustomSelect } from '../../components/ui/CustomSelect.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 { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js';
|
||||||
import { SessionMigrationCard } from '../../components/settings/SessionMigrationCard.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) {
|
function formatQuotaReservationLogForClipboard(snapshot) {
|
||||||
const safe = snapshot && typeof snapshot === 'object' ? snapshot : {};
|
const safe = snapshot && typeof snapshot === 'object' ? snapshot : {};
|
||||||
const buckets = Array.isArray(safe.buckets) ? safe.buckets : [];
|
const buckets = Array.isArray(safe.buckets) ? safe.buckets : [];
|
||||||
@@ -275,16 +268,15 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
[createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText]
|
[createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText]
|
||||||
);
|
);
|
||||||
|
|
||||||
const quotaReserveToggle = SegmentedControl({
|
const quotaReserveToggle = ToggleSwitch({
|
||||||
modelValue: 'off',
|
modelValue: 'off',
|
||||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
ariaLabelKey: 'settings.oth.quotaReserveLabel',
|
||||||
options: getEnableToggleOptions(),
|
preset: 'enable',
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
const nextEnabled = val === 'on';
|
const nextEnabled = val === 'on';
|
||||||
draftExperimentalQuotaReservation = nextEnabled;
|
draftExperimentalQuotaReservation = nextEnabled;
|
||||||
quotaReserveToggle.setProps({
|
quotaReserveToggle.setProps({
|
||||||
modelValue: nextEnabled ? 'on' : 'off',
|
modelValue: nextEnabled ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
});
|
});
|
||||||
showExpFeedback(t('settings.saving'), 0);
|
showExpFeedback(t('settings.saving'), 0);
|
||||||
try {
|
try {
|
||||||
@@ -366,10 +358,10 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
className: 'form-label',
|
className: 'form-label',
|
||||||
text: t('settings.oth.ctxMainLabel'),
|
text: t('settings.oth.ctxMainLabel'),
|
||||||
});
|
});
|
||||||
const ctxMainToggle = SegmentedControl({
|
const ctxMainToggle = ToggleSwitch({
|
||||||
modelValue: 'on',
|
modelValue: 'on',
|
||||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
ariaLabelKey: 'settings.oth.ctxMainLabel',
|
||||||
options: getEnableToggleOptions(),
|
preset: 'enable',
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||||
const nextEnabled = val === 'on';
|
const nextEnabled = val === 'on';
|
||||||
@@ -396,10 +388,10 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
className: 'form-label',
|
className: 'form-label',
|
||||||
text: t('settings.oth.ctxSwarmLabel'),
|
text: t('settings.oth.ctxSwarmLabel'),
|
||||||
});
|
});
|
||||||
const ctxSwarmToggle = SegmentedControl({
|
const ctxSwarmToggle = ToggleSwitch({
|
||||||
modelValue: 'off',
|
modelValue: 'off',
|
||||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
ariaLabelKey: 'settings.oth.ctxSwarmLabel',
|
||||||
options: getEnableToggleOptions(),
|
preset: 'enable',
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||||
const nextEnabled = val === 'on';
|
const nextEnabled = val === 'on';
|
||||||
@@ -519,14 +511,10 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel'));
|
patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel'));
|
||||||
ctxMainToggle.setProps({
|
ctxMainToggle.setProps({
|
||||||
modelValue: draftContextMainEnabled ? 'on' : 'off',
|
modelValue: draftContextMainEnabled ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
|
||||||
});
|
});
|
||||||
patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel'));
|
patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel'));
|
||||||
ctxSwarmToggle.setProps({
|
ctxSwarmToggle.setProps({
|
||||||
modelValue: draftContextSwarmEnabled ? 'on' : 'off',
|
modelValue: draftContextSwarmEnabled ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const syncErrorText =
|
const syncErrorText =
|
||||||
@@ -913,8 +901,6 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
});
|
});
|
||||||
quotaReserveToggle.setProps({
|
quotaReserveToggle.setProps({
|
||||||
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
|
||||||
});
|
});
|
||||||
renderContextWindows();
|
renderContextWindows();
|
||||||
void sessionMigrationCard.refs.ensureLoaded();
|
void sessionMigrationCard.refs.ensureLoaded();
|
||||||
@@ -933,8 +919,6 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn'));
|
patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn'));
|
||||||
quotaReserveToggle.setProps({
|
quotaReserveToggle.setProps({
|
||||||
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
modelValue: draftExperimentalQuotaReservation ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
ariaLabel: t('settings.oth.quotaReserveLabel'),
|
|
||||||
});
|
});
|
||||||
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
||||||
renderContextWindows();
|
renderContextWindows();
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ import { buildStructurePreviewTelemetry } from '../../components/settings/struct
|
|||||||
import { CustomNumberInput } from '../../components/ui/CustomNumberInput.js';
|
import { CustomNumberInput } from '../../components/ui/CustomNumberInput.js';
|
||||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||||
|
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
|
||||||
import {
|
import {
|
||||||
CapsuleBarWidget,
|
CapsuleBarWidget,
|
||||||
buildCapsuleSlotContext,
|
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() {
|
function getPopoverWidthModeOptions() {
|
||||||
return [
|
return [
|
||||||
{ value: 'auto', label: t('settings.str.popoverWidthAuto') },
|
{ value: 'auto', label: t('settings.str.popoverWidthAuto') },
|
||||||
@@ -520,10 +507,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const multiSessionToggle = SegmentedControl({
|
const multiSessionToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.multiToggle'),
|
ariaLabelKey: 'settings.str.multiToggle',
|
||||||
|
preset: 'visibility',
|
||||||
modelValue: 'show',
|
modelValue: 'show',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftShowTopbarMulti = val !== 'hide';
|
draftShowTopbarMulti = val !== 'hide';
|
||||||
syncMountSectionMeta();
|
syncMountSectionMeta();
|
||||||
@@ -549,10 +536,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const cliCapsuleToggle = SegmentedControl({
|
const cliCapsuleToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.cliCapsuleToggle'),
|
ariaLabelKey: 'settings.str.cliCapsuleToggle',
|
||||||
|
preset: 'enable',
|
||||||
modelValue: 'on',
|
modelValue: 'on',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftEnableCliStatusLine = val !== 'off';
|
draftEnableCliStatusLine = val !== 'off';
|
||||||
syncMountSectionMeta();
|
syncMountSectionMeta();
|
||||||
@@ -783,7 +770,6 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
}
|
}
|
||||||
multiSessionToggle.setProps({
|
multiSessionToggle.setProps({
|
||||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
});
|
});
|
||||||
contextAgentModeToggle.setProps({
|
contextAgentModeToggle.setProps({
|
||||||
modelValue: draftContextAgentMode,
|
modelValue: draftContextAgentMode,
|
||||||
@@ -794,7 +780,6 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled);
|
patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled);
|
||||||
cliCapsuleToggle.setProps({
|
cliCapsuleToggle.setProps({
|
||||||
modelValue: draftEnableCliStatusLine ? 'on' : 'off',
|
modelValue: draftEnableCliStatusLine ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
});
|
});
|
||||||
patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine);
|
patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine);
|
||||||
const effectiveCliSlots = getEffectiveDraftCliSlots();
|
const effectiveCliSlots = getEffectiveDraftCliSlots();
|
||||||
@@ -1144,10 +1129,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
text: t('settings.str.stepsColsLabel'),
|
text: t('settings.str.stepsColsLabel'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const stepTurnRailToggle = SegmentedControl({
|
const stepTurnRailToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.stepTurnRailToggle'),
|
ariaLabelKey: 'settings.str.stepTurnRailToggle',
|
||||||
|
preset: 'visibility',
|
||||||
modelValue: 'hide',
|
modelValue: 'hide',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftShowStepTurnRail = val !== 'hide';
|
draftShowStepTurnRail = val !== 'hide';
|
||||||
syncStepsSectionMeta();
|
syncStepsSectionMeta();
|
||||||
@@ -1157,10 +1142,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const stepAgentBadgeToggle = SegmentedControl({
|
const stepAgentBadgeToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.stepAgentBadgeToggle'),
|
ariaLabelKey: 'settings.str.stepAgentBadgeToggle',
|
||||||
|
preset: 'visibility',
|
||||||
modelValue: 'show',
|
modelValue: 'show',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftShowStepAgentBadge = val !== 'hide';
|
draftShowStepAgentBadge = val !== 'hide';
|
||||||
syncStepsSectionMeta();
|
syncStepsSectionMeta();
|
||||||
@@ -1170,10 +1155,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const stepSpeedColorToggle = SegmentedControl({
|
const stepSpeedColorToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.stepSpeedColorToggle'),
|
ariaLabelKey: 'settings.str.stepSpeedColorToggle',
|
||||||
|
preset: 'enable',
|
||||||
modelValue: 'off',
|
modelValue: 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftShowStepSpeedColor = val !== 'off';
|
draftShowStepSpeedColor = val !== 'off';
|
||||||
syncStepsSectionMeta();
|
syncStepsSectionMeta();
|
||||||
@@ -1183,10 +1168,10 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const stepFilterToolbarToggle = SegmentedControl({
|
const stepFilterToolbarToggle = ToggleSwitch({
|
||||||
ariaLabel: t('settings.str.stepFilterToolbarToggle'),
|
ariaLabelKey: 'settings.str.stepFilterToolbarToggle',
|
||||||
|
preset: 'enable',
|
||||||
modelValue: 'off',
|
modelValue: 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
onUpdateModelValue: (val) => {
|
onUpdateModelValue: (val) => {
|
||||||
draftShowStepFilterToolbar = val !== 'off';
|
draftShowStepFilterToolbar = val !== 'off';
|
||||||
syncStepsSectionMeta();
|
syncStepsSectionMeta();
|
||||||
@@ -1365,19 +1350,15 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
function syncStepsSectionMeta() {
|
function syncStepsSectionMeta() {
|
||||||
stepTurnRailToggle.setProps({
|
stepTurnRailToggle.setProps({
|
||||||
modelValue: draftShowStepTurnRail ? 'show' : 'hide',
|
modelValue: draftShowStepTurnRail ? 'show' : 'hide',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
});
|
});
|
||||||
stepAgentBadgeToggle.setProps({
|
stepAgentBadgeToggle.setProps({
|
||||||
modelValue: draftShowStepAgentBadge ? 'show' : 'hide',
|
modelValue: draftShowStepAgentBadge ? 'show' : 'hide',
|
||||||
options: getMultiToggleOptions(),
|
|
||||||
});
|
});
|
||||||
stepSpeedColorToggle.setProps({
|
stepSpeedColorToggle.setProps({
|
||||||
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
});
|
});
|
||||||
stepFilterToolbarToggle.setProps({
|
stepFilterToolbarToggle.setProps({
|
||||||
modelValue: draftShowStepFilterToolbar ? 'on' : 'off',
|
modelValue: draftShowStepFilterToolbar ? 'on' : 'off',
|
||||||
options: getEnableToggleOptions(),
|
|
||||||
});
|
});
|
||||||
if (document?.activeElement !== stepTokenComboInput) {
|
if (document?.activeElement !== stepTokenComboInput) {
|
||||||
stepTokenComboInput.value = rawStepTokenComboText;
|
stepTokenComboInput.value = rawStepTokenComboText;
|
||||||
|
|||||||
+53
-193
@@ -775,32 +775,35 @@ html[data-standalone="true"] .app-shell {
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-wrap {
|
.ui-search-wrap {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
padding: 4px 7px;
|
padding: 2px 8px;
|
||||||
margin-bottom: 4px;
|
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
background: var(--surface-bg);
|
background: var(--surface-subtle);
|
||||||
flex-shrink: 0;
|
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;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-wrap:focus-within {
|
.ui-search-wrap:focus-within {
|
||||||
border-color: var(--accent-primary);
|
border-color: var(--accent-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-icon {
|
.ui-search-icon {
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-input {
|
.ui-search-input {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
border: none;
|
border: none;
|
||||||
@@ -813,11 +816,11 @@ html[data-standalone="true"] .app-shell {
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-input::placeholder {
|
.ui-search-input::placeholder {
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-clear {
|
.ui-search-clear {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -830,17 +833,27 @@ html[data-standalone="true"] .app-shell {
|
|||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
flex-shrink: 0;
|
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);
|
color: var(--text-primary);
|
||||||
background: var(--surface-hover);
|
background: var(--surface-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
.select-search-clear[hidden] {
|
.ui-search-clear[hidden] {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.select-search-wrap {
|
||||||
|
padding: 4px 7px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
background: var(--surface-bg);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.select-options-list {
|
.select-options-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -1149,6 +1162,10 @@ html[data-standalone="true"] .app-shell {
|
|||||||
opacity: 0;
|
opacity: 0;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 0;
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmented:hover .seg-glider,
|
||||||
|
.segmented:focus-within .seg-glider {
|
||||||
will-change: transform, width;
|
will-change: transform, width;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1206,6 +1223,20 @@ html[data-standalone="true"] .app-shell {
|
|||||||
font-weight: 600;
|
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) --- */
|
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||||
.custom-scroll-host {
|
.custom-scroll-host {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -1265,10 +1296,14 @@ html[data-standalone="true"] .app-shell {
|
|||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||||
will-change: transform, height;
|
|
||||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
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:hover .scrollbar-thumb,
|
||||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||||
@@ -5076,70 +5111,9 @@ html[data-standalone="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.steps-search-wrap {
|
.steps-search-wrap {
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
flex: 1 1 160px;
|
flex: 1 1 160px;
|
||||||
min-width: 120px;
|
min-width: 120px;
|
||||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
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] {
|
.steps-search-clear[hidden] {
|
||||||
@@ -6124,60 +6098,6 @@ html[data-standalone="true"] .app-shell {
|
|||||||
line-height: 1.35;
|
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 {
|
.settings-context-model .select-option-meta {
|
||||||
max-width: 62%;
|
max-width: 62%;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
@@ -6550,69 +6470,9 @@ html[data-standalone="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.smig-search-wrap {
|
.smig-search-wrap {
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
min-height: calc(28px * var(--ui-font-scale, 1));
|
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] {
|
.smig-search-clear[hidden] {
|
||||||
@@ -8121,6 +7981,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[data-modern-ui="true"] .segmented {
|
[data-modern-ui="true"] .segmented {
|
||||||
|
--seg-pad: 2px;
|
||||||
padding: 2px;
|
padding: 2px;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
background: var(--modern-inline-track-bg);
|
background: var(--modern-inline-track-bg);
|
||||||
@@ -8559,7 +8420,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||||
[data-modern-ui="true"] .collapsible-body,
|
[data-modern-ui="true"] .collapsible-body,
|
||||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||||
[data-modern-ui="true"] .settings-account-entry,
|
|
||||||
[data-modern-ui="true"] .dt-time-row {
|
[data-modern-ui="true"] .dt-time-row {
|
||||||
border-top: none;
|
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"] .number-input,
|
||||||
[data-modern-ui="true"] .dt-trigger,
|
[data-modern-ui="true"] .dt-trigger,
|
||||||
[data-modern-ui="true"] .dt-mini-step,
|
[data-modern-ui="true"] .dt-mini-step,
|
||||||
[data-modern-ui="true"] .settings-text-input,
|
[data-modern-ui="true"] .settings-text-input {
|
||||||
[data-modern-ui="true"] .settings-account-form input {
|
|
||||||
border: none;
|
border: none;
|
||||||
background: var(--modern-surface-subtle);
|
background: var(--modern-surface-subtle);
|
||||||
transition:
|
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"] .number-input:focus-within,
|
||||||
[data-modern-ui="true"] .settings-text-input:focus,
|
[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"] .smig-search-wrap:focus-within,
|
||||||
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
[data-modern-ui="true"] .steps-search-wrap:focus-within {
|
||||||
border: none;
|
border: none;
|
||||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
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"] .smig-search-wrap,
|
||||||
[data-modern-ui="true"] .steps-search-wrap {
|
[data-modern-ui="true"] .steps-search-wrap {
|
||||||
border: none;
|
border: none;
|
||||||
|
|||||||
@@ -20,11 +20,15 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../shared/settings-normalization.mjs',
|
'../shared/settings-normalization.mjs',
|
||||||
'../shared/telemetry-display-rules.mjs',
|
'../shared/telemetry-display-rules.mjs',
|
||||||
'../shared/window-bridge-protocol.mjs',
|
'../shared/window-bridge-protocol.mjs',
|
||||||
|
'../shared/workspace-uri.mjs',
|
||||||
|
'../shared/prompt-clean.mjs',
|
||||||
|
'../backend/fs-atomic.mjs',
|
||||||
'../backend/context-windows.mjs',
|
'../backend/context-windows.mjs',
|
||||||
'../backend/account-oauth.mjs',
|
'../backend/account-oauth.mjs',
|
||||||
'../backend/account-switch.mjs',
|
'../backend/account-switch.mjs',
|
||||||
'../backend/http-helpers.mjs',
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
|
'../backend/trajectory-cache-store.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
'../backend/endpoint-registry.mjs',
|
'../backend/endpoint-registry.mjs',
|
||||||
'../backend/sqlite-client.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 mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
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 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={
|
const ctx={
|
||||||
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
|
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
|
||||||
...(clock ? { Date: class extends Date {
|
...(clock ? { Date: class extends Date {
|
||||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||||
static now() { return 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)},
|
console:{error:m=>state.errors.push(m)},
|
||||||
cpSync:()=>{},
|
cpSync:()=>{},
|
||||||
rmSync:()=>{},
|
rmSync:()=>{},
|
||||||
renameSync:()=>{},
|
renameSync:(from, to)=>{
|
||||||
unlinkSync:()=>{},
|
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)=>{
|
execFile:execFileImpl || ((cmd,args,opts,cb)=>{
|
||||||
const fn = typeof opts === 'function' ? opts : cb;
|
const fn = typeof opts === 'function' ? opts : cb;
|
||||||
fn(new Error('execFile not mocked'));
|
fn(new Error('execFile not mocked'));
|
||||||
@@ -130,8 +155,9 @@ export function backendHarness({
|
|||||||
if (diskDirs && Array.isArray(diskDirs[norm])) return diskDirs[norm];
|
if (diskDirs && Array.isArray(diskDirs[norm])) return diskDirs[norm];
|
||||||
return [];
|
return [];
|
||||||
},
|
},
|
||||||
statSync:p=>{
|
statSync:(p, opts)=>{
|
||||||
const norm = String(p).replace(/\\/g, '/');
|
const norm = String(p).replace(/\\/g, '/');
|
||||||
|
if (opts?.throwIfNoEntry === false && !ctx.existsSync(p)) return undefined;
|
||||||
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||||
const lines = m && state.transcripts?.[m[1]];
|
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('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||||
if (norm.endsWith('/.git/config')) return String(state.gitConfigText || '');
|
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);
|
return JSON.stringify(cache);
|
||||||
},
|
},
|
||||||
writeFileSync:(p,s)=>{
|
writeFileSync:(p,s)=>{
|
||||||
const norm = String(p).replace(/\\/g, '/');
|
if (/\.tmp-\d+$/.test(String(p))) {
|
||||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
pendingTmpWrites.set(String(p), s);
|
||||||
state.saves.push({path:p,data:parsed});
|
return;
|
||||||
if (norm.endsWith('settings.json')) {
|
|
||||||
state.settings = parsed;
|
|
||||||
}
|
|
||||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
|
||||||
state.remoteCatalog = parsed;
|
|
||||||
}
|
}
|
||||||
|
commitSave(p, s);
|
||||||
},
|
},
|
||||||
writeTrajectoryCacheFile:(p,data)=>{
|
writeTrajectoryCacheFile:(p,data)=>{
|
||||||
if (state.cacheWriteError) throw state.cacheWriteError;
|
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 iconSource = join(tempDir, 'src', 'icons', 'svgRegistry.js');
|
||||||
const original = fs.readFileSync(iconSource, 'utf8');
|
const original = fs.readFileSync(iconSource, 'utf8');
|
||||||
for (const [prefix, error] of [
|
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 { SVG_NS } from './SvgIcon.js';", /svgRegistry\.js.*SvgIcon\.js.*earlier in jsOrder/],
|
||||||
["import './missing.js';", /svgRegistry\.js.*missing\.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/],
|
['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
|
// Per-module closure isolation: unexported private identifiers never collide across modules
|
||||||
fs.writeFileSync(iconSource, `const SVG_NS = "private_local";\n${original}`);
|
fs.writeFileSync(iconSource, `const SVG_NS = "private_local";\n${original}`);
|
||||||
assert.doesNotThrow(() => buildBundle(tempDir));
|
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;
|
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. 严禁基于速率上限裁剪异常值或动态篡改分母(如扣除思考时间或仅取流式片段耗时),保证统计口径客观一致。
|
* 2. 严禁基于速率上限裁剪异常值或动态篡改分母(如扣除思考时间或仅取流式片段耗时),保证统计口径客观一致。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { extractCleanUserRequestBody } from './shared/prompt-clean.mjs';
|
||||||
|
|
||||||
/** 速度测量口径版本号;当耗时或样本过滤算法变更时递增,用于触发旧版缓存测量字段失效重算 */
|
/** 速度测量口径版本号;当耗时或样本过滤算法变更时递增,用于触发旧版缓存测量字段失效重算 */
|
||||||
export const MEASUREMENT_VERSION = 4;
|
export const MEASUREMENT_VERSION = 4;
|
||||||
|
|
||||||
@@ -1020,14 +1022,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('\n');
|
.join('\n');
|
||||||
} else if (typeof step?.content === 'string' && step.content.trim()) {
|
} else if (typeof step?.content === 'string' && step.content.trim()) {
|
||||||
const withoutSummary = step.content
|
raw = extractCleanUserRequestBody(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, '');
|
|
||||||
}
|
}
|
||||||
const cleaned = String(raw || '')
|
const cleaned = String(raw || '')
|
||||||
.split(/\r?\n/)
|
.split(/\r?\n/)
|
||||||
|
|||||||
Reference in New Issue
Block a user