Merge pull request #34 from yuhuan-dev/release/v1.5.3

feat(panel): SSH remote windows support, Orchestrator (Neon) recognition, and panel UI polish (v1.5.3)
This commit is contained in:
fish
2026-11-21 01:03:24 +09:00
committed by GitHub
58 changed files with 7179 additions and 930 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "usage-monitor", "name": "usage-monitor",
"displayName": "Usage & Speed Monitor", "displayName": "Usage & Speed Monitor",
"version": "1.5.2", "version": "1.5.3",
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
"logo": "assets/logo.svg", "logo": "assets/logo.svg",
"suggestedPrompts": [ "suggestedPrompts": [
+5 -3
View File
@@ -1,8 +1,8 @@
{ {
"schemaVersion": 1, "schemaVersion": 1,
"catalogVersion": "2026.11.19.2", "catalogVersion": "2026.11.21.1",
"updatedAt": "2026-11-19T09:35:00+09:00", "updatedAt": "2026-11-21T00:35:00+09:00",
"latestPluginVersion": "1.5.2", "latestPluginVersion": "1.5.3",
"releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
"downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
"archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main", "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
@@ -165,7 +165,9 @@
"placeholders": { "placeholders": {
"MODEL_PLACEHOLDER_M667": { "modelId": "gemini-pro-orchestrator", "label": "Orchestrator (Carbon)" }, "MODEL_PLACEHOLDER_M667": { "modelId": "gemini-pro-orchestrator", "label": "Orchestrator (Carbon)" },
"MODEL_PLACEHOLDER_M681": { "modelId": "gemini-pro-orchestrator-argon", "label": "Orchestrator (Argon)" }, "MODEL_PLACEHOLDER_M681": { "modelId": "gemini-pro-orchestrator-argon", "label": "Orchestrator (Argon)" },
"MODEL_PLACEHOLDER_M537": { "modelId": "gemini-pro-orchestrator-neon", "label": "Orchestrator (Neon)" },
"MODEL_PLACEHOLDER_M669": { "modelId": "gemini-flash-worker-agy", "label": "Orchestrator Worker (Hydrogen)" }, "MODEL_PLACEHOLDER_M669": { "modelId": "gemini-flash-worker-agy", "label": "Orchestrator Worker (Hydrogen)" },
"MODEL_PLACEHOLDER_M535": { "modelId": "gemini-4-neon-xhigh", "label": "Gemini 4 Neon (XHigh)" },
"MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" }, "MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
"MODEL_PLACEHOLDER_M427": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" }, "MODEL_PLACEHOLDER_M427": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
"MODEL_PLACEHOLDER_M437": { "modelId": "gemini-4-carbon-medium", "label": "Gemini 4 Carbon (Medium)" }, "MODEL_PLACEHOLDER_M437": { "modelId": "gemini-4-carbon-medium", "label": "Gemini 4 Carbon (Medium)" },
+563 -155
View File
File diff suppressed because it is too large Load Diff
+147 -28
View File
@@ -8,8 +8,14 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util'; import { isDeepStrictEqual } from 'node:util';
import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs'; import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
import { handleAccountCredentialAction } from './account-switch.mjs'; import { handleAccountCredentialAction } from './account-switch.mjs';
import {
clearRemoteEndpointCaches,
resolveEndpointContext,
trackEndpointRequestEnd,
trackEndpointRequestStart,
} from './endpoint-registry.mjs';
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs'; import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
import { clearScannerRuntimeMemos } from './local-scanner.mjs'; import { clearScannerRuntimeMemos } from './local-scanner.mjs';
import { import {
@@ -24,6 +30,7 @@ import {
lsRuntimeEndpoint, lsRuntimeEndpoint,
normalizeFullSettings, normalizeFullSettings,
normalizeModelDisplayMode, normalizeModelDisplayMode,
normalizeModernUi,
normalizePluginUpdateMode, normalizePluginUpdateMode,
normalizeWindowMountMode, normalizeWindowMountMode,
saveJson, saveJson,
@@ -104,12 +111,42 @@ function projectDisplayStep(st) {
}; };
} }
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8; const MAX_DISPLAY_STEP_CACHE_ENTRIES = 16;
const displayStepsCache = new Map(); const displayStepsCache = new Map();
const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter( const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter(
(k) => k !== 'anomaly' (k) => k !== 'anomaly'
); );
function buildEndpointErrorResponse(epCtx) {
return {
status: Number(epCtx?.status || 400),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({
error: epCtx?.error || 'Invalid endpointId',
...(epCtx?.retryable ? { retryable: true } : {}),
}),
};
}
function resolveActionEndpoint(data, opts) {
const rawId =
opts && opts.endpointId !== undefined
? opts.endpointId
: isPlainObject(data) && data.endpointId !== undefined
? data.endpointId
: undefined;
return resolveEndpointContext(rawId);
}
function stripEndpointField(data) {
if (!isPlainObject(data) || !Object.prototype.hasOwnProperty.call(data, 'endpointId')) {
return data;
}
const { endpointId: _ignored, ...rest } = data;
return rest;
}
function haveSameDisplaySteps(previous, current) { function haveSameDisplaySteps(previous, current) {
if (!previous || !current) return previous === current; if (!previous || !current) return previous === current;
if (previous.length !== current.length) return false; if (previous.length !== current.length) return false;
@@ -126,12 +163,14 @@ function haveSameDisplaySteps(previous, current) {
function projectDisplayTelemetry(payload, requestedRevision) { function projectDisplayTelemetry(payload, requestedRevision) {
const active = payload.activeConversation; const active = payload.activeConversation;
const agents = active.agents; const agents = active.agents;
const endpointKey = payload.endpoint?.id || LOCAL_ENDPOINT_ID;
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)]; const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
let projected; let projected;
let revision; let revision;
if (typeof requestedRevision === 'string') { if (typeof requestedRevision === 'string') {
const cacheKey = active.cascadeId || '__empty__'; const cacheKey = `${endpointKey}::${active.cascadeId || '__empty__'}`;
const scope = [ const scope = [
endpointKey,
payload.account?.status, payload.account?.status,
payload.account?.email || payload.account?.name || '', payload.account?.email || payload.account?.name || '',
active.cascadeId, active.cascadeId,
@@ -175,17 +214,23 @@ function projectDisplayTelemetry(payload, requestedRevision) {
}; };
} }
export async function executeTelemetryAction(data, { onRestart = null } = {}) { export async function executeTelemetryAction(data, opts = {}) {
const { onRestart = null } = opts || {};
const epCtx = resolveActionEndpoint(data, opts);
if (!epCtx.ok) {
return buildEndpointErrorResponse(epCtx);
}
const isRemote = epCtx.isRemote;
const rawConvId = String( const rawConvId = String(
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' data?.conversationId || (isRemote ? '' : process.env.ANTIGRAVITY_CONVERSATION_ID || '')
).trim(); ).trim();
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : ''; const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
const force = data?.force === '1' || data?.force === true; const force = data?.force === '1' || data?.force === true;
if (lsRuntimeEndpoint.addr !== 'test.invalid') { if (lsRuntimeEndpoint.addr !== 'test.invalid') {
if (!lsRuntimeEndpoint.baseUrl) { if (!isRemote && !lsRuntimeEndpoint.baseUrl) {
await ensureLsEndpointDiscovered({ force: false }); await ensureLsEndpointDiscovered({ force: false });
} }
if (lsRuntimeEndpoint.baseUrl) { if (isRemote || lsRuntimeEndpoint.baseUrl) {
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) { if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
await Promise.race([ await Promise.race([
syncCloudCatalog({ force: true }).catch(() => {}), syncCloudCatalog({ force: true }).catch(() => {}),
@@ -208,8 +253,10 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
startMs: sanitizePositiveFiniteMs(data?.startMs), startMs: sanitizePositiveFiniteMs(data?.startMs),
endMs: sanitizePositiveFiniteMs(data?.endMs), endMs: sanitizePositiveFiniteMs(data?.endMs),
...(scope ? { scope } : {}), ...(scope ? { scope } : {}),
endpoint: epCtx.endpoint,
}; };
let payload; let payload;
trackEndpointRequestStart(epCtx.endpoint);
try { try {
payload = await buildTelemetryPayload(convId, force, filterOpts); payload = await buildTelemetryPayload(convId, force, filterOpts);
} catch (err) { } catch (err) {
@@ -225,6 +272,8 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
} }
} }
throw err; throw err;
} finally {
trackEndpointRequestEnd(epCtx.endpoint);
} }
if ( if (
bootBundleVersion && bootBundleVersion &&
@@ -258,7 +307,7 @@ function sanitizePositiveSettingNumber(val, fallback) {
export function executeSettingsAction(data) { export function executeSettingsAction(data) {
const current = loadSettings(); const current = loadSettings();
const payload = isPlainObject(data) ? data : {}; const payload = isPlainObject(data) ? stripEndpointField(data) : {};
const nextPluginUpdateMode = const nextPluginUpdateMode =
payload.pluginUpdateMode !== undefined payload.pluginUpdateMode !== undefined
? normalizePluginUpdateMode(payload.pluginUpdateMode) ? normalizePluginUpdateMode(payload.pluginUpdateMode)
@@ -285,9 +334,16 @@ export function executeSettingsAction(data) {
? 'upstream' ? 'upstream'
: 'short' : 'short'
: normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel); : normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel);
const nextModernUi =
payload.modernUi !== undefined
? normalizeModernUi(payload.modernUi)
: payload.experimentalModernUi !== undefined
? normalizeModernUi(payload.experimentalModernUi)
: normalizeModernUi(current.modernUi);
const updated = normalizeFullSettings({ const updated = normalizeFullSettings({
...current, ...current,
...payload, ...payload,
modernUi: nextModernUi,
modelContextWindows: current.modelContextWindows, modelContextWindows: current.modelContextWindows,
weeklyTokenBudget: sanitizePositiveSettingNumber( weeklyTokenBudget: sanitizePositiveSettingNumber(
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit, payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
@@ -353,7 +409,11 @@ export function executeSettingsAction(data) {
}; };
} }
export async function executeModelContextWindowAction(data) { export async function executeModelContextWindowAction(data, opts = {}) {
const epCtx = resolveActionEndpoint(data, opts);
if (!epCtx.ok) {
return buildEndpointErrorResponse(epCtx);
}
const { modelId, option } = data || {}; const { modelId, option } = data || {};
const respond = (status, payload) => ({ const respond = (status, payload) => ({
status, status,
@@ -364,12 +424,44 @@ export async function executeModelContextWindowAction(data) {
if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) { if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) {
return respond(400, { error: 'Invalid model context window' }); return respond(400, { error: 'Invalid model context window' });
} }
async function loadGroupsForEndpoint(targetEndpoint) {
const [{ userStatus }, catalog] = await Promise.all([
callLsRpc('GetUserStatus', {}, 5000, targetEndpoint),
getContextModelCatalog(targetEndpoint),
]);
const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs;
if (!Array.isArray(configs) || configs.length === 0) return null;
const models = getContextWindowModels(configs, catalog);
return getContextWindowGroups(models);
}
let group; let group;
let verifiedHostConfigs = false;
trackEndpointRequestStart(epCtx.endpoint);
try { try {
const [{ userStatus }, catalog] = await Promise.all([callLsRpc('GetUserStatus'), getContextModelCatalog()]); let groups = null;
const models = getContextWindowModels(userStatus?.cascadeModelConfigData?.clientModelConfigs, catalog); try {
group = getContextWindowGroups(models).find(({ id }) => id === modelId); groups = await loadGroupsForEndpoint(epCtx.endpoint);
} catch { } catch {
groups = null;
}
if (epCtx.isRemote && !groups) {
// 仅在远端 RPC 异常或未返回模型配置时安全回退本机校验;远端已成功返回时绝不放宽其档位限制
try {
groups = await loadGroupsForEndpoint(null);
} catch {
groups = null;
}
}
if (Array.isArray(groups)) {
verifiedHostConfigs = true;
group = groups.find(({ id }) => id === modelId);
}
} finally {
trackEndpointRequestEnd(epCtx.endpoint);
}
if (!verifiedHostConfigs) {
if (option !== null || modelId.startsWith('model:')) { if (option !== null || modelId.startsWith('model:')) {
return respond(503, { error: 'Unable to verify the host model configuration' }); return respond(503, { error: 'Unable to verify the host model configuration' });
} }
@@ -442,8 +534,14 @@ export function executeResetSettingsAction() {
}; };
} }
export function executeRebuildCacheAction() { export function executeRebuildCacheAction(data = undefined, opts = {}) {
const ok = clearRuntimeCaches(); const epCtx = resolveActionEndpoint(data, opts);
if (!epCtx.ok) {
return buildEndpointErrorResponse(epCtx);
}
const ok = epCtx.isRemote
? clearRemoteEndpointCaches(epCtx.id)
: clearRuntimeCaches();
if (!ok) { if (!ok) {
return { return {
ok: false, ok: false,
@@ -453,15 +551,20 @@ export function executeRebuildCacheAction() {
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }), body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
}; };
} }
displayStepsCache.clear(); const cachePrefix = `${epCtx.id}::`;
clearScannerRuntimeMemos(); for (const key of Array.from(displayStepsCache.keys())) {
clearTelemetryBuilderMemo(); if (key.startsWith(cachePrefix)) {
displayStepsCache.delete(key);
}
}
clearScannerRuntimeMemos(epCtx.isRemote ? epCtx.id : null);
clearTelemetryBuilderMemo(epCtx.id);
return { return {
ok: true, ok: true,
status: 200, status: 200,
contentType: 'application/json', contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' }, headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({ ok: true, clearedAt: Date.now() }), body: JSON.stringify({ ok: true, endpointId: epCtx.id, clearedAt: Date.now() }),
}; };
} }
@@ -486,10 +589,23 @@ export async function executePluginUpdateAction() {
}; };
} }
export async function executeAccountCredentialAction(data) { export async function executeAccountCredentialAction(data, opts = {}) {
const result = await handleAccountCredentialAction(data); const epCtx = resolveActionEndpoint(data, opts);
if (data?.action === 'switch') { if (!epCtx.ok) {
clearTelemetryBuilderMemo(); return buildEndpointErrorResponse(epCtx);
}
if (epCtx.isRemote) {
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({ supported: false, accounts: [], error: 'unsupported' }),
};
}
const cleanData = stripEndpointField(data);
const result = await handleAccountCredentialAction(cleanData);
if (cleanData?.action === 'switch') {
clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID);
} }
return { return {
status: 200, status: 200,
@@ -531,15 +647,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
} }
return executeSettingsAction(data); return executeSettingsAction(data);
case 'accounts_get': case 'accounts_get':
return executeAccountCredentialAction(); return executeAccountCredentialAction(undefined, opts);
case 'accounts_update': case 'accounts_update':
return executeAccountCredentialAction(data); return executeAccountCredentialAction(data, opts);
case 'context_window': case 'context_window':
return executeModelContextWindowAction(data); return executeModelContextWindowAction(data, opts);
case 'settings_reset': case 'settings_reset':
return executeResetSettingsAction(); return executeResetSettingsAction();
case 'cache_rebuild': case 'cache_rebuild':
return executeRebuildCacheAction(); return executeRebuildCacheAction(data, opts);
case 'cloud_sync': case 'cloud_sync':
return executeCloudSyncAction(); return executeCloudSyncAction();
case 'plugin_update': case 'plugin_update':
@@ -585,8 +701,11 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
} }
return startDefaultWindowBridge({ return startDefaultWindowBridge({
handleApiRequest: (pathname, method, data) => handleApiRequest: (pathname, method, data, ctx) =>
dispatchBridgeApiRequest(pathname, method, data, { onRestart: triggerRestart }), dispatchBridgeApiRequest(pathname, method, data, {
onRestart: triggerRestart,
...(ctx?.endpointId !== undefined ? { endpointId: ctx.endpointId } : {}),
}),
readAssetFn: readLocalAsync, readAssetFn: readLocalAsync,
bootBundleVersion, bootBundleVersion,
onVersionDrift: triggerRestart, onVersionDrift: triggerRestart,
@@ -749,11 +749,29 @@ function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true
* }} [options] * }} [options]
* @returns {string} * @returns {string}
*/ */
function detectCliHostLanguageIsEn() {
const envLang = String(
process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || ''
).trim();
if (envLang) {
return !envLang.toLowerCase().startsWith('zh');
}
try {
const navLang = globalThis.navigator?.language;
if (navLang) {
return !String(navLang).toLowerCase().startsWith('zh');
}
} catch {
// 忽略无 navigator 环境
}
return false;
}
export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) {
const slots = normalizeTopbarCapsuleSlots(options.slots); const slots = normalizeTopbarCapsuleSlots(options.slots);
const showMulti = options.showMultiSession !== false; const showMulti = options.showMultiSession !== false;
const normLang = normalizeLanguageSetting(options.language); const normLang = normalizeLanguageSetting(options.language);
const isEn = normLang === 'en-US'; const isEn = normLang === 'auto' ? detectCliHostLanguageIsEn() : normLang === 'en-US';
const useColor = options.color !== false; const useColor = options.color !== false;
const slotSet = new Set(slots); const slotSet = new Set(slots);
+1
View File
@@ -42,6 +42,7 @@ export {
normalizeHoverModules, normalizeHoverModules,
normalizeLanguageSetting, normalizeLanguageSetting,
normalizeModelDisplayMode, normalizeModelDisplayMode,
normalizeModernUi,
normalizeOrchestratorIdMode, normalizeOrchestratorIdMode,
normalizeOverviewMetrics, normalizeOverviewMetrics,
normalizeOverviewModules, normalizeOverviewModules,
+20 -7
View File
@@ -121,18 +121,19 @@ export async function syncHostContextWindows(
rules, rules,
bootId, bootId,
key = '__AGUsageMonitorContextWindows', key = '__AGUsageMonitorContextWindows',
fallbackRules = {} fallbackRules = {},
allowRemoteHost = false
) { ) {
let state = window[key]; let state = window[key];
const appConfig = window.__APP_CONFIG__; const appConfig = window.__APP_CONFIG__;
const csrfToken = appConfig?.csrfToken; const csrfToken = appConfig?.csrfToken || state?.observedCsrfToken || '';
const hasPrefs = Boolean(rules && Object.keys(rules).length > 0); const hasPrefs = Boolean(rules && Object.keys(rules).length > 0);
const safeFallback = const safeFallback =
fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules) fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules)
? fallbackRules ? fallbackRules
: {}; : {};
const hasFallback = Object.keys(safeFallback).length > 0; const hasFallback = Object.keys(safeFallback).length > 0;
if (!hasPrefs || appConfig?.isRemoteControl || (!csrfToken && !hasFallback)) { if (!hasPrefs || (!allowRemoteHost && appConfig?.isRemoteControl) || (!csrfToken && !hasFallback)) {
state?.dispose(); state?.dispose();
return { attached: false, ruleCount: 0 }; return { attached: false, ruleCount: 0 };
} }
@@ -207,12 +208,19 @@ export async function syncHostContextWindows(
: ''; : '';
if (rawUrl && init?.method === 'POST') { if (rawUrl && init?.method === 'POST') {
const url = new URL(rawUrl, window.location.href); const url = new URL(rawUrl, window.location.href);
if (url.origin === window.location.origin && isTargetProcedure(url.pathname)) { if (url.origin === window.location.origin && url.pathname.startsWith(servicePath)) {
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim(); const hdrs = new Headers(init.headers);
const seenCsrf = hdrs.get('x-codeium-csrf-token')?.trim();
if (seenCsrf && state) {
state.observedCsrfToken = seenCsrf;
}
if (isTargetProcedure(url.pathname)) {
const type = hdrs.get('content-type')?.split(';')[0].trim();
const body = rewriteBody(init.body, type); const body = rewriteBody(init.body, type);
if (body !== init.body) nextInit = { ...init, body }; if (body !== init.body) nextInit = { ...init, body };
} }
} }
}
} catch { } catch {
// 未识别的请求格式交回宿主原样发送。 // 未识别的请求格式交回宿主原样发送。
} }
@@ -312,7 +320,12 @@ export async function syncHostContextWindows(
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
} }
export function createContextWindowSyncExpression(preferences, bootId, fallbackRules = {}) { export function createContextWindowSyncExpression(
preferences,
bootId,
fallbackRules = {},
allowRemoteHost = false
) {
return `(() => { return `(() => {
${isContextWindowModelId.toString()} ${isContextWindowModelId.toString()}
${isContextWindowSettingId.toString()} ${isContextWindowSettingId.toString()}
@@ -321,6 +334,6 @@ export function createContextWindowSyncExpression(preferences, bootId, fallbackR
${getContextWindowGroups.toString()} ${getContextWindowGroups.toString()}
${resolveContextWindowOption.toString()} ${resolveContextWindowOption.toString()}
${resolveContextWindowRules.toString()} ${resolveContextWindowRules.toString()}
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}); return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))});
})()`; })()`;
} }
@@ -2005,10 +2005,11 @@ export async function triggerDesktopHostRelaunch({
bundleDerivedName || (hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'); bundleDerivedName || (hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity');
const shScript = [ const shScript = [
'sleep 0.45', 'sleep 0.45',
'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi', 'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi',
'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi', 'if pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -ax "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi',
'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi', 'if pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -ax "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi',
'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"',
'sleep 0.4',
'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1', 'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1',
].join('; '); ].join('; ');
await spawner('/bin/sh', ['-c', shScript], { await spawner('/bin/sh', ['-c', shScript], {
@@ -0,0 +1,603 @@
/**
* @fileoverview 多窗口 / SSH 远端端点注册表与按端点隔离的运行时状态存储。
*
* 职责:
* 1. 管理 `'local'`(委托既有本机全局状态,100% 向后兼容)与每个 SSH/远端窗口的独立端点上下文;
* 2. 为每个远端端点维护隔离的轨迹缓存、配额缓存、模型目录缓存、扫描冷却表与实时活动缓存;
* 3. 对具备稳定主机标识的 SSH 端点按 `<prefix>-<sha256_12>.json` 原子持久化至 `DATA_DIR/remote_caches/`,
* 临时端口端点仅驻留内存,防止磁盘残留垃圾文件;
* 4. 维护同一远端主机的多窗口 CDP `targets` 映射、Tier-1 失败熔断器与 `inFlightCount` 防误回收保护。
*/
import { createHash } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
import {
CACHE_RUNNING_SAVE_INTERVAL_MS,
DATA_DIR,
clearRuntimeCaches,
flushTrajectoryCacheNow,
getCachedTrajectory,
hasPendingTrajectoryCacheSave,
isPlainObject,
listCachedTrajectoryEntries,
loadJson,
lsRuntimeEndpoint,
persistTrajectoryCacheIfNeeded,
quotaSummaryCache,
removeCachedTrajectory,
setCachedTrajectory,
} from './config.mjs';
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
const ENDPOINT_ID_REMOTE_RE = /^remote:[a-zA-Z0-9._:@-]{1,120}$/;
const ENDPOINT_STALE_TTL_MS = 60_000;
const ENDPOINT_TIER2_COOLDOWN_MS = 60_000;
const ENDPOINT_REMOTE_CACHE_DIR = join(DATA_DIR, 'remote_caches');
const remoteEndpointRegistry = new Map();
let nextEndpointInstanceId = 0;
let registeredWindowRpcInvoker = null;
/**
* 校验并归一化 `endpointId`;空值默认回退 `'local'`,非法格式返回 `null`。
*
* @param {unknown} rawId
* @returns {string|null}
*/
export function normalizeEndpointId(rawId) {
if (rawId === undefined || rawId === null || rawId === '') {
return LOCAL_ENDPOINT_ID;
}
const text = String(rawId).trim();
if (!text || text === LOCAL_ENDPOINT_ID) {
return LOCAL_ENDPOINT_ID;
}
if (!ENDPOINT_ID_REMOTE_RE.test(text)) {
return null;
}
return text;
}
/**
* 根据稳定主机名或回环 origin 构造确定性的远端 `endpointId` 与磁盘持久化标识。
*
* @param {{ origin?: string, hostLabel?: string, stableHostKey?: string }} info
* @returns {{ id: string, label: string, stableHostKey: string, hasStableHostKey: boolean }}
*/
export function buildRemoteEndpointIdentity({ origin = '', hostLabel = '', stableHostKey = '' } = {}) {
const cleanStable = String(stableHostKey || '').trim();
const cleanLabel = String(hostLabel || cleanStable || '').trim();
const cleanOrigin = String(origin || '').trim();
let parsedHostPort = '';
if (cleanOrigin) {
try {
const parsed = new URL(cleanOrigin);
parsedHostPort = parsed.host;
} catch {
// 忽略非法 URL
}
}
if (cleanStable) {
const safePrefix = cleanStable
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 48) || 'ssh';
const hash = createHash('sha256').update(cleanStable.toLowerCase()).digest('hex').slice(0, 12);
return {
id: `remote:ssh-${safePrefix}-${hash}`,
label: cleanLabel || cleanStable,
stableHostKey: cleanStable.toLowerCase(),
hasStableHostKey: true,
};
}
const originBasis = (parsedHostPort || cleanOrigin || 'unknown').toLowerCase();
const safeOrigin = originBasis
.replace(/[^a-z0-9._:-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64) || 'unknown';
const hash = createHash('sha256').update(originBasis).digest('hex').slice(0, 8);
return {
id: `remote:${safeOrigin}-${hash}`,
label: cleanLabel || parsedHostPort || 'SSH',
stableHostKey: '',
hasStableHostKey: false,
};
}
function buildRemoteCacheFilePath(stableHostKey) {
if (!stableHostKey) return '';
const safePrefix = stableHostKey
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 32) || 'ssh';
const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12);
// 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等)
return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`);
}
function hydrateTrajectoryCacheObject(rawLoaded) {
const cacheObj = Object.create(null);
let migrated =
rawLoaded !== null && rawLoaded !== undefined && !isPlainObject(rawLoaded);
if (isPlainObject(rawLoaded)) {
for (const [id, entry] of Object.entries(rawLoaded)) {
if (!id || !isPlainObject(entry)) {
migrated = true;
continue;
}
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
if (!Array.isArray(entry.steps)) migrated = true;
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
if (objectSteps.length !== rawSteps.length) migrated = true;
const normalizedSteps = objectSteps.map((s) => {
const norm = normalizeCachedStep(s);
if (norm !== s) migrated = true;
return norm;
});
const finalSteps = inferCompactionStepModels(normalizedSteps);
for (let i = 0; i < finalSteps.length; i++) {
if (finalSteps[i] !== normalizedSteps[i]) {
migrated = true;
break;
}
}
cacheObj[id] = { ...entry, steps: finalSteps };
}
}
return { cacheObj, migrated };
}
function createRemoteQuotaCache() {
return {
ts: 0,
lastAttemptTs: 0,
accountName: '',
accountGeneration: 0,
data: null,
error: null,
};
}
function createRemoteEndpointStore(cacheFilePath) {
const loaded = cacheFilePath ? loadJson(cacheFilePath, {}) : {};
const { cacheObj, migrated } = hydrateTrajectoryCacheObject(loaded);
const state = {
needsSave: Boolean(cacheFilePath && migrated),
lastSavedAtMs: 0,
flushTimer: null,
};
function cancelFlushTimer() {
if (state.flushTimer) {
try {
clearTimeout(state.flushTimer);
} catch {
// 忽略沙箱异常
}
state.flushTimer = null;
}
}
function writeCacheNow() {
cancelFlushTimer();
if (!cacheFilePath) {
state.needsSave = false;
return true;
}
try {
mkdirSync(dirname(cacheFilePath), { recursive: true });
writeTrajectoryCacheFile(cacheFilePath, cacheObj);
state.needsSave = false;
state.lastSavedAtMs = Date.now();
return true;
} catch (err) {
console.error(`Failed writing remote cache ${cacheFilePath}: ${err.message}`);
state.needsSave = true;
return false;
}
}
function persistIfNeeded({ hasRunningSessions = false } = {}) {
if (!cacheFilePath) {
state.needsSave = false;
return;
}
if (lsRuntimeEndpoint.addr === 'test.invalid' || typeof setTimeout !== 'function') {
writeCacheNow();
return;
}
const nowMs = Date.now();
const elapsedMs = nowMs - (state.lastSavedAtMs || 0);
if (!hasRunningSessions || state.lastSavedAtMs === 0 || elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS) {
writeCacheNow();
return;
}
state.needsSave = true;
if (!state.flushTimer) {
const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs);
const timer = setTimeout(() => {
state.flushTimer = null;
if (state.needsSave) {
writeCacheNow();
}
}, delayMs);
timer?.unref?.();
state.flushTimer = timer;
}
}
function clearCache() {
cancelFlushTimer();
if (cacheFilePath) {
try {
mkdirSync(dirname(cacheFilePath), { recursive: true });
writeTrajectoryCacheFile(cacheFilePath, {});
} catch {
return false;
}
}
for (const key of Object.keys(cacheObj)) {
delete cacheObj[key];
}
state.needsSave = false;
state.lastSavedAtMs = 0;
return true;
}
return {
cacheFilePath,
cacheState: state,
cancelFlushTimer,
getCachedTrajectory: (cascadeId) => cacheObj[cascadeId],
listCachedTrajectoryEntries: () => Object.entries(cacheObj),
setCachedTrajectory: (cascadeId, entry) => {
cacheObj[cascadeId] = entry;
},
removeCachedTrajectory: (cascadeId) => {
delete cacheObj[cascadeId];
},
hasPendingTrajectoryCacheSave: () => state.needsSave,
persistTrajectoryCacheIfNeeded: persistIfNeeded,
flushTrajectoryCacheNow: writeCacheNow,
clearCache,
};
}
/**
* 注册或更新一个 SSH / 远端窗口端点(幂等;同一远端主机多窗口共享端点并保留独立 `wsUrl` 列表)。
*
* @param {{
* id?: string,
* origin?: string,
* baseUrl?: string,
* csrfToken?: string,
* wsUrl?: string,
* label?: string,
* stableHostKey?: string,
* }} info
*/
export function registerRemoteEndpoint(info = {}) {
const identity = info.id && ENDPOINT_ID_REMOTE_RE.test(info.id)
? {
id: info.id,
label: String(info.label || info.stableHostKey || 'SSH').trim() || 'SSH',
stableHostKey: String(info.stableHostKey || '').trim().toLowerCase(),
hasStableHostKey: Boolean(String(info.stableHostKey || '').trim()),
}
: buildRemoteEndpointIdentity({
origin: info.origin || info.baseUrl,
hostLabel: info.label,
stableHostKey: info.stableHostKey,
});
const nowMs = Date.now();
const cleanOrigin = String(info.origin || '').trim().replace(/\/+$/, '');
const cleanBaseUrl = String(info.baseUrl || cleanOrigin).trim().replace(/\/+$/, '');
const cleanCsrf = String(info.csrfToken || '').trim();
const cleanWsUrl = String(info.wsUrl || '').trim();
let entry = remoteEndpointRegistry.get(identity.id);
if (!entry) {
const cacheFilePath = identity.hasStableHostKey
? buildRemoteCacheFilePath(identity.stableHostKey)
: '';
entry = {
id: identity.id,
instanceId: ++nextEndpointInstanceId,
isRemote: true,
label: identity.label,
stableHostKey: identity.stableHostKey,
hasStableHostKey: identity.hasStableHostKey,
origin: cleanOrigin,
baseUrl: cleanBaseUrl,
csrfToken: cleanCsrf,
targets: new Map(),
lastSeenMs: nowMs,
preferTier2UntilMs: 0,
inFlightCount: 0,
store: createRemoteEndpointStore(cacheFilePath),
quotaSummaryCache: createRemoteQuotaCache(),
contextModelCatalog: null,
failedFetchCooldownMap: new Map(),
liveActivityMemo: new Map(),
};
remoteEndpointRegistry.set(identity.id, entry);
} else {
entry.lastSeenMs = nowMs;
if (identity.label) entry.label = identity.label;
if (cleanOrigin) entry.origin = cleanOrigin;
const existingTarget = cleanWsUrl ? entry.targets.get(cleanWsUrl) : null;
const isAlreadyKnownPair = Array.from(entry.targets.values()).some(
(t) =>
(!cleanBaseUrl || t.baseUrl === cleanBaseUrl) &&
(!cleanCsrf || t.csrfToken === cleanCsrf)
);
const baseUrlChanged = Boolean(cleanBaseUrl && entry.baseUrl && entry.baseUrl !== cleanBaseUrl);
if (cleanBaseUrl) {
if (baseUrlChanged && !isAlreadyKnownPair) {
entry.preferTier2UntilMs = 0;
if (!cleanCsrf) {
// 远端隧道换端口重连且 2.33.0+ 未暴露 csrfToken 时清除旧端口残留令牌
entry.csrfToken = '';
}
}
entry.baseUrl = cleanBaseUrl;
}
if (cleanCsrf) {
if (entry.csrfToken !== cleanCsrf && !isAlreadyKnownPair) {
entry.preferTier2UntilMs = 0;
}
entry.csrfToken = cleanCsrf;
} else if (existingTarget && baseUrlChanged && !isAlreadyKnownPair) {
entry.csrfToken = '';
}
}
if (cleanWsUrl) {
entry.targets.set(cleanWsUrl, {
wsUrl: cleanWsUrl,
origin: cleanOrigin || entry.origin,
baseUrl: cleanBaseUrl || entry.baseUrl,
csrfToken: cleanCsrf,
lastSeenMs: nowMs,
});
}
return entry;
}
/**
* 获取已注册的远端端点对象;`'local'` 或未注册时返回 `null`。
*
* @param {string} endpointId
*/
export function getRegisteredRemoteEndpoint(endpointId) {
const norm = normalizeEndpointId(endpointId);
if (!norm || norm === LOCAL_ENDPOINT_ID) return null;
return remoteEndpointRegistry.get(norm) || null;
}
/**
* 解析并校验请求目标端点:
* - `'local'` 返回 `{ ok: true, isRemote: false, id: 'local', endpoint: null }`;
* - 已注册远端返回 `{ ok: true, isRemote: true, id, endpoint }`;
* - 非法格式返回 `{ ok: false, status: 400, error: 'Invalid endpointId' }`;
* - 合法但暂未注册的远端返回 `{ ok: false, status: 503, retryable: true, error: 'Remote endpoint initializing' }`。
*
* @param {unknown} rawEndpointId
*/
export function resolveEndpointContext(rawEndpointId) {
const norm = normalizeEndpointId(rawEndpointId);
if (norm === null) {
return { ok: false, status: 400, retryable: false, error: 'Invalid endpointId' };
}
if (norm === LOCAL_ENDPOINT_ID) {
return { ok: true, isRemote: false, id: LOCAL_ENDPOINT_ID, label: '', endpoint: null };
}
const entry = remoteEndpointRegistry.get(norm);
if (!entry) {
return {
ok: false,
status: 503,
retryable: true,
error: 'Remote endpoint initializing',
};
}
return {
ok: true,
isRemote: true,
id: entry.id,
label: entry.label || 'SSH',
endpoint: entry,
};
}
/**
* 返回目标端点对应的统一轨迹缓存读写适配器(`'local'` 委托给 `config.mjs` 原生缓存)。
*
* @param {object|string|null} [endpointOrId=null]
*/
export function getEndpointCacheStore(endpointOrId = null) {
const ep =
typeof endpointOrId === 'string'
? getRegisteredRemoteEndpoint(endpointOrId)
: endpointOrId && typeof endpointOrId === 'object' && endpointOrId.isRemote
? endpointOrId
: null;
if (ep?.store) {
return {
isRemote: true,
endpointId: ep.id,
...ep.store,
};
}
return {
isRemote: false,
endpointId: LOCAL_ENDPOINT_ID,
getCachedTrajectory,
listCachedTrajectoryEntries,
setCachedTrajectory,
removeCachedTrajectory,
hasPendingTrajectoryCacheSave,
persistTrajectoryCacheIfNeeded,
flushTrajectoryCacheNow,
clearCache: clearRuntimeCaches,
};
}
/**
* 返回目标端点对应的配额缓存容器。
*
* @param {object|string|null} [endpointOrId=null]
*/
export function getEndpointQuotaCache(endpointOrId = null) {
const ep =
typeof endpointOrId === 'string'
? getRegisteredRemoteEndpoint(endpointOrId)
: endpointOrId && typeof endpointOrId === 'object' && endpointOrId.isRemote
? endpointOrId
: null;
return ep?.quotaSummaryCache || quotaSummaryCache;
}
/**
* 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。
*
* @param {string} endpointId
* @returns {boolean}
*/
export function clearRemoteEndpointCaches(endpointId) {
const ep = getRegisteredRemoteEndpoint(endpointId);
if (!ep) return false;
const ok = ep.store.clearCache();
if (!ok) return false;
ep.failedFetchCooldownMap.clear();
ep.liveActivityMemo.clear();
ep.contextModelCatalog = null;
ep.quotaSummaryCache.ts = 0;
ep.quotaSummaryCache.lastAttemptTs = 0;
ep.quotaSummaryCache.accountName = '';
ep.quotaSummaryCache.accountGeneration += 1;
ep.quotaSummaryCache.data = null;
ep.quotaSummaryCache.error = null;
return true;
}
/**
* 为远端端点挑选存活的 CDP `wsUrl` 列表(按最近活跃时间倒序,便于多窗口故障转移)。
*
* @param {object|null} endpoint
* @returns {string[]}
*/
export function getRemoteEndpointTargetWsUrls(endpoint) {
if (!endpoint?.targets || !(endpoint.targets instanceof Map)) return [];
return Array.from(endpoint.targets.values())
.sort((a, b) => (b.lastSeenMs || 0) - (a.lastSeenMs || 0))
.map((t) => t.wsUrl)
.filter(Boolean);
}
/**
* 当 Tier-1 回环直连失败(如 401/403/TLS/连接错误)时启用 60 秒熔断,优先改走 Tier-2 窗口同源通道。
*/
export function markRemoteEndpointPreferTier2(endpoint, cooldownMs = ENDPOINT_TIER2_COOLDOWN_MS) {
if (endpoint && typeof endpoint === 'object') {
endpoint.preferTier2UntilMs = Date.now() + Math.max(1000, Number(cooldownMs) || ENDPOINT_TIER2_COOLDOWN_MS);
}
}
export function shouldRemoteEndpointPreferTier2(endpoint) {
return Boolean(endpoint && Number(endpoint.preferTier2UntilMs || 0) > Date.now());
}
/**
* 标记端点正在执行请求,避免并发 pruning 期间提前销毁。
*/
export function trackEndpointRequestStart(endpoint) {
if (endpoint && typeof endpoint === 'object') {
endpoint.inFlightCount = Math.max(0, Number(endpoint.inFlightCount || 0)) + 1;
}
}
export function trackEndpointRequestEnd(endpoint) {
if (endpoint && typeof endpoint === 'object') {
endpoint.inFlightCount = Math.max(0, Number(endpoint.inFlightCount || 0) - 1);
}
}
/**
* 清理已关闭且超过宽限期(默认 60 秒)且无在途请求的远端端点;清理前刷盘并取消定时器。
*
* @param {Set<string>} activeRemoteWsUrls
* @param {number} [ttlMs=60000]
*/
export function pruneStaleRemoteEndpoints(activeRemoteWsUrls, ttlMs = ENDPOINT_STALE_TTL_MS) {
const nowMs = Date.now();
const activeSet = activeRemoteWsUrls instanceof Set ? activeRemoteWsUrls : new Set();
for (const [id, ep] of remoteEndpointRegistry.entries()) {
for (const [wsUrl, tInfo] of ep.targets.entries()) {
if (!activeSet.has(wsUrl) && nowMs - (tInfo.lastSeenMs || 0) >= ttlMs) {
ep.targets.delete(wsUrl);
}
}
const stillActive = Array.from(ep.targets.keys()).some((wsUrl) => activeSet.has(wsUrl));
if (stillActive) {
ep.lastSeenMs = nowMs;
continue;
}
if (ep.inFlightCount > 0) continue;
if (nowMs - (ep.lastSeenMs || 0) >= ttlMs) {
if (ep.store.hasPendingTrajectoryCacheSave()) {
ep.store.flushTrajectoryCacheNow();
}
ep.store.cancelFlushTimer();
remoteEndpointRegistry.delete(id);
}
}
}
export function listRegisteredRemoteEndpoints() {
return Array.from(remoteEndpointRegistry.values());
}
export function clearRemoteEndpointRegistry() {
for (const ep of remoteEndpointRegistry.values()) {
ep.store.cancelFlushTimer();
}
remoteEndpointRegistry.clear();
}
/**
* 注册 Tier-2 窗口同源 RPC 执行器(由 `window-bridge.mjs` 绑定 CDP `evaluateOnTarget`)。
*
* @param {((endpoint: object, method: string, body: object, timeoutMs: number) => Promise<object>)|null} invoker
*/
export function setRemoteWindowRpcInvoker(invoker) {
registeredWindowRpcInvoker = typeof invoker === 'function' ? invoker : null;
}
export function getRemoteWindowRpcInvoker() {
return registeredWindowRpcInvoker;
}
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
process.once('exit', () => {
for (const ep of remoteEndpointRegistry.values()) {
if (ep.store.hasPendingTrajectoryCacheSave()) {
ep.store.flushTrajectoryCacheNow();
}
ep.store.cancelFlushTimer();
}
});
}
+187 -86
View File
@@ -14,6 +14,7 @@ import { isDeepStrictEqual } from 'node:util';
import { import {
extractLiveActivity, extractLiveActivity,
extractModelSteps, extractModelSteps,
extractSwarmMetaFromSteps,
getMaxMeaningfulStepIndex, getMaxMeaningfulStepIndex,
isParkedOnSwarmWait, isParkedOnSwarmWait,
parseIsoMs, parseIsoMs,
@@ -27,15 +28,10 @@ import {
CONVERSATIONS_DIR, CONVERSATIONS_DIR,
CONVERSATION_DIRS, CONVERSATION_DIRS,
DEEP_STATS_CACHE_CANDIDATES, DEEP_STATS_CACHE_CANDIDATES,
getCachedTrajectory,
hasPendingTrajectoryCacheSave,
listCachedTrajectoryEntries,
externalDeepStatsMemo, externalDeepStatsMemo,
loadJson, loadJson,
persistTrajectoryCacheIfNeeded,
removeCachedTrajectory,
setCachedTrajectory,
} from './config.mjs'; } from './config.mjs';
import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs';
import { import {
computeSqliteWalSig, computeSqliteWalSig,
hasBuiltinNodeSqlite, hasBuiltinNodeSqlite,
@@ -364,7 +360,15 @@ const liveActivityMemo = new Map();
const transcriptTailMemo = new Map(); const transcriptTailMemo = new Map();
const swarmManifestMemo = new Map(); const swarmManifestMemo = new Map();
export function clearScannerRuntimeMemos() { export function clearScannerRuntimeMemos(endpointId = null) {
if (endpointId && endpointId !== 'local') {
const ep = getRegisteredRemoteEndpoint(endpointId);
if (ep) {
ep.failedFetchCooldownMap.clear();
ep.liveActivityMemo.clear();
}
return;
}
failedFetchCooldownMap.clear(); failedFetchCooldownMap.clear();
liveActivityMemo.clear(); liveActivityMemo.clear();
transcriptTailMemo.clear(); transcriptTailMemo.clear();
@@ -1192,11 +1196,17 @@ function scoreLiveActivitySpecificity(act) {
return 1; return 1;
} }
function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) { function resolveBestLiveActivity(
cascadeId,
rpcRawSteps,
isRunning,
fallbackMs,
{ isRemote = false, liveActivityMemoMap = liveActivityMemo } = {}
) {
if (!isRunning) return null; if (!isRunning) return null;
const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0; const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0;
const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null; const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null;
const transcriptSteps = readTranscriptTailSteps(cascadeId); const transcriptSteps = isRemote ? [] : readTranscriptTailSteps(cascadeId);
const transcriptAct = const transcriptAct =
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null; transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
@@ -1226,7 +1236,7 @@ function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs)
return ( return (
transcriptAct || transcriptAct ||
rpcAct || rpcAct ||
liveActivityMemo.get(String(cascadeId || '').toLowerCase()) || liveActivityMemoMap.get(String(cascadeId || '').toLowerCase()) ||
extractLiveActivity([], true, fallbackMs) extractLiveActivity([], true, fallbackMs)
); );
} }
@@ -1385,22 +1395,35 @@ export async function enumerateAndSyncConversations({
currentAccountName = '', currentAccountName = '',
requestedConvId = '', requestedConvId = '',
forceRefresh = false, forceRefresh = false,
endpoint = null,
}) { }) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
const cacheStore = getEndpointCacheStore(endpoint);
const getEntry = cacheStore.getCachedTrajectory;
const setEntry = cacheStore.setCachedTrajectory;
const removeEntry = cacheStore.removeCachedTrajectory;
const listEntries = cacheStore.listCachedTrajectoryEntries;
const hasPendingSave = cacheStore.hasPendingTrajectoryCacheSave;
const persistCacheIfNeeded = cacheStore.persistTrajectoryCacheIfNeeded;
const activeCooldownMap = isRemote ? endpoint.failedFetchCooldownMap : failedFetchCooldownMap;
const activeLiveActivityMemo = isRemote ? endpoint.liveActivityMemo : liveActivityMemo;
const maxConcurrentRpc = isRemote ? 2 : MAX_CONCURRENT_RPC;
const nowSweepMs = Date.now(); const nowSweepMs = Date.now();
if (forceRefresh) { if (forceRefresh) {
failedFetchCooldownMap.clear(); activeCooldownMap.clear();
} else { } else {
for (const [k, rec] of failedFetchCooldownMap.entries()) { for (const [k, rec] of activeCooldownMap.entries()) {
const failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0; const failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0;
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS; const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS;
if (nowSweepMs - failedAt >= cooldownMs) { if (nowSweepMs - failedAt >= cooldownMs) {
failedFetchCooldownMap.delete(k); activeCooldownMap.delete(k);
} }
} }
} }
let cacheDirty = hasPendingTrajectoryCacheSave(); let cacheDirty = hasPendingSave();
const diskConvMap = discoverLocalConversationFiles(); const diskConvMap = isRemote ? new Map() : discoverLocalConversationFiles();
// 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC) // 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC)
const mergedSideQuestionParents = { ...(sideQuestionParents || {}) }; const mergedSideQuestionParents = { ...(sideQuestionParents || {}) };
@@ -1449,7 +1472,7 @@ export async function enumerateAndSyncConversations({
} }
} }
for (const [rawCacheKey] of listCachedTrajectoryEntries()) { for (const [rawCacheKey] of listEntries()) {
const lower = String(rawCacheKey || '').trim().toLowerCase(); const lower = String(rawCacheKey || '').trim().toLowerCase();
if (!lower) continue; if (!lower) continue;
const existingCanon = canonicalIdByLower.get(lower); const existingCanon = canonicalIdByLower.get(lower);
@@ -1457,18 +1480,18 @@ export async function enumerateAndSyncConversations({
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目 // 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey; const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
if (normalizedKey !== rawCacheKey) { if (normalizedKey !== rawCacheKey) {
setCachedTrajectory(normalizedKey, getCachedTrajectory(rawCacheKey)); setEntry(normalizedKey, getEntry(rawCacheKey));
removeCachedTrajectory(rawCacheKey); removeEntry(rawCacheKey);
cacheDirty = true; cacheDirty = true;
} }
canonicalIdByLower.set(lower, normalizedKey); canonicalIdByLower.set(lower, normalizedKey);
} else if (existingCanon !== rawCacheKey) { } else if (existingCanon !== rawCacheKey) {
const targetEntry = getCachedTrajectory(existingCanon); const targetEntry = getEntry(existingCanon);
const dupEntry = getCachedTrajectory(rawCacheKey); const dupEntry = getEntry(rawCacheKey);
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) { if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
setCachedTrajectory(existingCanon, dupEntry); setEntry(existingCanon, dupEntry);
} }
removeCachedTrajectory(rawCacheKey); removeEntry(rawCacheKey);
cacheDirty = true; cacheDirty = true;
} }
} }
@@ -1480,7 +1503,7 @@ export async function enumerateAndSyncConversations({
} }
// 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失 // 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失
for (const [, entry] of listCachedTrajectoryEntries()) { for (const [, entry] of listEntries()) {
for (const ref of entry?.subagentRefs || []) { for (const ref of entry?.subagentRefs || []) {
const refCid = String(ref?.cascadeId || '').trim().toLowerCase(); const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
if (refCid && !canonicalIdByLower.has(refCid)) { if (refCid && !canonicalIdByLower.has(refCid)) {
@@ -1489,15 +1512,15 @@ export async function enumerateAndSyncConversations({
} }
} }
const localSummaryByLower = readLocalSummaryIndex(); const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex();
const sqliteAvailable = hasBuiltinNodeSqlite(); const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite();
const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000;
const reqLower = String(requestedConvId || '').trim().toLowerCase(); const reqLower = String(requestedConvId || '').trim().toLowerCase();
const rawConversations = []; const rawConversations = [];
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) { for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
const item = summariesByLower.get(cidLower); const item = summariesByLower.get(cidLower);
const localSum = item ? null : localSummaryByLower.get(cidLower) || null; const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
const cached = getCachedTrajectory(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) : null;
const dbPath = sqliteDbInfo?.dbPath || ''; const dbPath = sqliteDbInfo?.dbPath || '';
@@ -1508,7 +1531,9 @@ export async function enumerateAndSyncConversations({
const diskMtimeMs = sqliteDbInfo const diskMtimeMs = sqliteDbInfo
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0) ? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
: rawDiskMtimeMs; : rawDiskMtimeMs;
const appSource = inferAppSourceFromSummary( const appSource = isRemote
? 'ssh'
: inferAppSourceFromSummary(
item?.source || '', item?.source || '',
diskFiles, diskFiles,
cached?.appSource || 'standalone' cached?.appSource || 'standalone'
@@ -1707,12 +1732,12 @@ export async function enumerateAndSyncConversations({
function isFetchInCooldown(conv, sig) { function isFetchInCooldown(conv, sig) {
if (forceRefresh) return false; if (forceRefresh) return false;
const key = `${conv.cascadeId.toLowerCase()}::${sig}`; const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
const rec = failedFetchCooldownMap.get(key); const rec = activeCooldownMap.get(key);
if (!rec) return false; if (!rec) return false;
const failedAt = typeof rec === 'number' ? rec : rec.failedAt; const failedAt = typeof rec === 'number' ? rec : rec.failedAt;
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs; const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs;
if (nowPollMs - failedAt >= cooldownMs) { if (nowPollMs - failedAt >= cooldownMs) {
failedFetchCooldownMap.delete(key); activeCooldownMap.delete(key);
return false; return false;
} }
return true; return true;
@@ -1765,15 +1790,15 @@ export async function enumerateAndSyncConversations({
for (const c of targetConvs) { for (const c of targetConvs) {
attemptedFetchIds.add(c.cascadeId.toLowerCase()); attemptedFetchIds.add(c.cascadeId.toLowerCase());
} }
for (let i = 0; i < targetConvs.length; i += MAX_CONCURRENT_RPC) { for (let i = 0; i < targetConvs.length; i += maxConcurrentRpc) {
const batch = targetConvs.slice(i, i + MAX_CONCURRENT_RPC); const batch = targetConvs.slice(i, i + maxConcurrentRpc);
await Promise.all( await Promise.all(
batch.map(async (conv) => { batch.map(async (conv) => {
const sig = buildConvSig(conv); const sig = buildConvSig(conv);
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`; const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower); const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
const prev = getCachedTrajectory(conv.cascadeId); const prev = getEntry(conv.cascadeId);
let partialTailSteps = []; let partialTailSteps = [];
let hasTailStepInfo = false; let hasTailStepInfo = false;
try { try {
@@ -1781,7 +1806,7 @@ export async function enumerateAndSyncConversations({
let trajRes = null; let trajRes = null;
let loadedViaSqlite = false; let loadedViaSqlite = false;
let transcriptFirstTitle = ''; let transcriptFirstTitle = '';
if (conv.dbPath && sqliteAvailable) { if (!isRemote && conv.dbPath && sqliteAvailable) {
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, { const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
cascadeId: conv.cascadeId, cascadeId: conv.cascadeId,
isRunning, isRunning,
@@ -1797,7 +1822,12 @@ export async function enumerateAndSyncConversations({
} }
} }
if (!trajRes) { if (!trajRes) {
trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); trajRes = await callLsRpc(
'GetCascadeTrajectory',
{ cascadeId: conv.cascadeId },
5000,
endpoint
);
} }
if (!Array.isArray(trajRes?.trajectory?.steps)) { if (!Array.isArray(trajRes?.trajectory?.steps)) {
throw new Error('Trajectory steps unavailable'); throw new Error('Trajectory steps unavailable');
@@ -1813,7 +1843,7 @@ export async function enumerateAndSyncConversations({
} }
throw new Error('Incomplete trajectory; retaining cached usage'); throw new Error('Incomplete trajectory; retaining cached usage');
} }
failedFetchCooldownMap.delete(cooldownKey); activeCooldownMap.delete(cooldownKey);
const rawGenMeta = trajRes?.trajectory?.generatorMetadata || []; const rawGenMeta = trajRes?.trajectory?.generatorMetadata || [];
const { steps: rawSteps, generatorMeta } = loadedViaSqlite const { steps: rawSteps, generatorMeta } = loadedViaSqlite
? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta }
@@ -1885,7 +1915,7 @@ export async function enumerateAndSyncConversations({
Boolean( Boolean(
conv.rootConversationId && conv.rootConversationId !== cidLower conv.rootConversationId && conv.rootConversationId !== cidLower
); );
if (!nonShortTitle(conv.title)) { if (!isRemote && !nonShortTitle(conv.title)) {
const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower)); const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower));
const resolvedFallbackTitle = const resolvedFallbackTitle =
annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle; annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle;
@@ -1899,7 +1929,9 @@ export async function enumerateAndSyncConversations({
} }
const subagentRefs = extractSubagentRefsFromSteps(rawSteps); const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps);
const ownSwarmManifest =
!isRemote && !conv.isSubagent ? readSwarmManifestForCascade(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) {
@@ -1908,9 +1940,12 @@ export async function enumerateAndSyncConversations({
subagentRefs.push(wRef); subagentRefs.push(wRef);
} }
} }
if (!nonShortTitle(conv.title) && ownSwarmManifest.title) {
conv.title = ownSwarmManifest.title;
} }
const resolvedSwarmTitle = !conv.isSubagent
? String(ownSwarmManifest?.title || rpcSwarmMeta?.title || '').trim()
: '';
if (!nonShortTitle(conv.title) && resolvedSwarmTitle) {
conv.title = resolvedSwarmTitle;
} }
conv.subagentRefs = subagentRefs; conv.subagentRefs = subagentRefs;
@@ -1920,7 +1955,8 @@ export async function enumerateAndSyncConversations({
conv.stepCount = steps.length; conv.stepCount = steps.length;
const finalSig = buildConvSig(conv); const finalSig = buildConvSig(conv);
const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps); const isParkedSwarm = isParkedOnSwarmWait(rawSteps);
const effectiveIsRunning = isRunning && !isParkedSwarm;
if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
conv.status = 'IDLE'; conv.status = 'IDLE';
} }
@@ -1929,20 +1965,21 @@ export async function enumerateAndSyncConversations({
conv.cascadeId, conv.cascadeId,
rawSteps, rawSteps,
effectiveIsRunning, effectiveIsRunning,
resolvedLastModMs || conv.createdTimeMs || 0 resolvedLastModMs || conv.createdTimeMs || 0,
{ isRemote, liveActivityMemoMap: activeLiveActivityMemo }
); );
if (liveAct && liveAct.actionKey !== 'swarm_wait') { if (liveAct && liveAct.actionKey !== 'swarm_wait') {
conv.liveActivity = liveAct; conv.liveActivity = liveAct;
liveActivityMemo.set(cidLower, liveAct); activeLiveActivityMemo.set(cidLower, liveAct);
} else { } else {
if (liveAct?.actionKey === 'swarm_wait') { if (liveAct?.actionKey === 'swarm_wait') {
conv.status = 'IDLE'; conv.status = 'IDLE';
} }
conv.liveActivity = null; conv.liveActivity = null;
liveActivityMemo.delete(cidLower); activeLiveActivityMemo.delete(cidLower);
} }
const entryAccountName = prev ? prev.accountName || '' : currentAccountName || ''; const entryAccountName = prev?.accountName || currentAccountName || '';
const stepsWithOwners = attachStepAccountOwners( const stepsWithOwners = attachStepAccountOwners(
steps, steps,
prev, prev,
@@ -1967,6 +2004,8 @@ export async function enumerateAndSyncConversations({
steps: stepsWithOwners, steps: stepsWithOwners,
subagentRefs, subagentRefs,
}; };
if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta;
if (isParkedSwarm) cacheEntry.parkedOnSwarmWait = true;
if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig; if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig;
if (conv.appSource && conv.appSource !== 'standalone') { if (conv.appSource && conv.appSource !== 'standalone') {
cacheEntry.appSource = conv.appSource; cacheEntry.appSource = conv.appSource;
@@ -1986,13 +2025,15 @@ export async function enumerateAndSyncConversations({
const metaChanged = const metaChanged =
!Array.isArray(prev?.subagentRefs) || !Array.isArray(prev?.subagentRefs) ||
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
!isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) ||
Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) ||
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') ||
Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion);
const stepsChanged = const stepsChanged =
!prev || !prev ||
Boolean(prev.offlineTranscriptFallback) || Boolean(prev.offlineTranscriptFallback) ||
prev.signature !== finalSig || prev.signature !== finalSig ||
Boolean(prev.wasRunning) !== isRunning || Boolean(prev.wasRunning) !== Boolean(cacheEntry.wasRunning) ||
!prev.contextLimitTelemetry || !prev.contextLimitTelemetry ||
!prev.speedClearedTelemetry || !prev.speedClearedTelemetry ||
!prev.turnRailTelemetry || !prev.turnRailTelemetry ||
@@ -2002,13 +2043,13 @@ export async function enumerateAndSyncConversations({
!isDeepStrictEqual(prev.steps, stepsWithOwners); !isDeepStrictEqual(prev.steps, stepsWithOwners);
if (!stepsChanged) cacheEntry.steps = prev.steps; if (!stepsChanged) cacheEntry.steps = prev.steps;
setCachedTrajectory(conv.cascadeId, cacheEntry); setEntry(conv.cascadeId, cacheEntry);
if (stepsChanged) { if (stepsChanged) {
cacheDirty = true; cacheDirty = true;
} }
} catch (err) { } catch (err) {
let offlineRecovered = false; let offlineRecovered = false;
if (!conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) { if (!isRemote && !conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) {
if (!lazyExternalByLower) { if (!lazyExternalByLower) {
lazyExternalByLower = new Map(); lazyExternalByLower = new Map();
for (const ext of loadExternalDeepStatsCache().values()) { for (const ext of loadExternalDeepStatsCache().values()) {
@@ -2044,9 +2085,8 @@ export async function enumerateAndSyncConversations({
Boolean(conv.parentConversationId) || Boolean(conv.parentConversationId) ||
Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower); Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower);
const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles);
const offlineAccountName = prev const offlineAccountName =
? prev.accountName || offlineFallback.accountName || '' prev?.accountName || offlineFallback.accountName || currentAccountName || '';
: offlineFallback.accountName || currentAccountName || '';
const offlineStepsWithOwners = attachStepAccountOwners( const offlineStepsWithOwners = attachStepAccountOwners(
offlineFallback.steps, offlineFallback.steps,
prev, prev,
@@ -2087,7 +2127,7 @@ export async function enumerateAndSyncConversations({
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) || Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
!isDeepStrictEqual(prev.steps, offlineEntry.steps); !isDeepStrictEqual(prev.steps, offlineEntry.steps);
if (!changed) offlineEntry.steps = prev.steps; if (!changed) offlineEntry.steps = prev.steps;
setCachedTrajectory(conv.cascadeId, offlineEntry); setEntry(conv.cascadeId, offlineEntry);
if (changed) { if (changed) {
cacheDirty = true; cacheDirty = true;
} }
@@ -2107,30 +2147,45 @@ export async function enumerateAndSyncConversations({
if (!(isRunning && (hasTailStepInfo || offlineRecovered))) { if (!(isRunning && (hasTailStepInfo || offlineRecovered))) {
const cooldownMs = const cooldownMs =
isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS;
failedFetchCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); activeCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs });
} }
if (!isRunning) { const tailStepsOnErr =
liveActivityMemo.delete(conv.cascadeId.toLowerCase()); partialTailSteps.length > 0
? partialTailSteps
: isRemote
? []
: readTranscriptTailSteps(conv.cascadeId);
const parkedOnErr =
tailStepsOnErr.length > 0
? isParkedOnSwarmWait(tailStepsOnErr)
: Boolean(prev?.parkedOnSwarmWait) && prev.signature === sig;
if (!isRunning || (!offlineRecovered && parkedOnErr)) {
if (isRunning) {
conv.status = 'IDLE';
conv.liveActivity = null;
}
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
} else { } else {
const fallbackLive = resolveBestLiveActivity( const fallbackLive = resolveBestLiveActivity(
conv.cascadeId, conv.cascadeId,
partialTailSteps, partialTailSteps,
true, true,
conv.lastModifiedMs || conv.createdTimeMs || 0 conv.lastModifiedMs || conv.createdTimeMs || 0,
{ isRemote, liveActivityMemoMap: activeLiveActivityMemo }
); );
conv.liveActivity = fallbackLive; conv.liveActivity = fallbackLive;
if (fallbackLive) { if (fallbackLive) {
liveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive); activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive);
} }
} }
if ( if (
!offlineRecovered && !offlineRecovered &&
prev && prev &&
getCachedTrajectory(conv.cascadeId) === prev && getEntry(conv.cascadeId) === prev &&
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
!Array.isArray(prev.subagentRefs) !Array.isArray(prev.subagentRefs)
) { ) {
setCachedTrajectory(conv.cascadeId, { ...prev, subagentRefs: [] }); setEntry(conv.cascadeId, { ...prev, subagentRefs: [] });
cacheDirty = true; cacheDirty = true;
} }
} }
@@ -2188,7 +2243,7 @@ export async function enumerateAndSyncConversations({
const sig = buildConvSig(conv); const sig = buildConvSig(conv);
if (isFetchInCooldown(conv, sig)) return false; if (isFetchInCooldown(conv, sig)) return false;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
const cached = getCachedTrajectory(conv.cascadeId); const cached = getEntry(conv.cascadeId);
if (!cached || conv.needsInitialLoad) return true; if (!cached || conv.needsInitialLoad) return true;
const lowerCid = conv.cascadeId.toLowerCase(); const lowerCid = conv.cascadeId.toLowerCase();
const isSelectedFamily = const isSelectedFamily =
@@ -2277,9 +2332,10 @@ export async function enumerateAndSyncConversations({
const missingSubagentsToFetch = []; const missingSubagentsToFetch = [];
for (const parentConv of [...rawConversations]) { for (const parentConv of [...rawConversations]) {
const parentCached = getCachedTrajectory(parentConv.cascadeId); const parentCached = getEntry(parentConv.cascadeId);
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || []; const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
const swarmManifest = !parentConv.isSubagent const swarmManifest =
!isRemote && !parentConv.isSubagent
? readSwarmManifestForCascade(parentConv.cascadeId) ? readSwarmManifestForCascade(parentConv.cascadeId)
: null; : null;
let refs = baseRefs; let refs = baseRefs;
@@ -2310,7 +2366,7 @@ export async function enumerateAndSyncConversations({
const canonSubId = canonicalIdByLower.get(subCid) || subCid; const canonSubId = canonicalIdByLower.get(subCid) || subCid;
canonicalIdByLower.set(subCid, canonSubId); canonicalIdByLower.set(subCid, canonSubId);
let subConv = byLowerId.get(subCid); let subConv = byLowerId.get(subCid);
const subCached = getCachedTrajectory(subConv?.cascadeId || canonSubId); const subCached = getEntry(subConv?.cascadeId || canonSubId);
if (!subConv) { if (!subConv) {
const subDiskFiles = diskConvMap.get(subCid) || []; const subDiskFiles = diskConvMap.get(subCid) || [];
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null; const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
@@ -2336,7 +2392,9 @@ export async function enumerateAndSyncConversations({
diskMtimeMs, diskMtimeMs,
dbPath: subDbInfo?.dbPath || '', dbPath: subDbInfo?.dbPath || '',
diskFileSig: subDbInfo?.sig || '', diskFileSig: subDbInfo?.sig || '',
appSource: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'), appSource: isRemote
? 'ssh'
: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
inSummaries: false, inSummaries: false,
needsInitialLoad: !subCached, needsInitialLoad: !subCached,
isSubagent: true, isSubagent: true,
@@ -2368,7 +2426,7 @@ export async function enumerateAndSyncConversations({
} }
const targetCacheKey = subConv.cascadeId; const targetCacheKey = subConv.cascadeId;
const existingSubCache = getCachedTrajectory(targetCacheKey); const existingSubCache = getEntry(targetCacheKey);
const isSelectedSubFamily = rootId === selectedRootId; const isSelectedSubFamily = rootId === selectedRootId;
const hasValidSubCache = const hasValidSubCache =
existingSubCache && existingSubCache &&
@@ -2417,7 +2475,7 @@ export async function enumerateAndSyncConversations({
updatedMetadata.subagentRefs = []; updatedMetadata.subagentRefs = [];
} }
if (Object.keys(updatedMetadata).length > 0) { if (Object.keys(updatedMetadata).length > 0) {
setCachedTrajectory(targetCacheKey, { ...existingSubCache, ...updatedMetadata }); setEntry(targetCacheKey, { ...existingSubCache, ...updatedMetadata });
cacheDirty = true; cacheDirty = true;
} }
} else { } else {
@@ -2443,7 +2501,7 @@ export async function enumerateAndSyncConversations({
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) { if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
return false; return false;
} }
const cached = getCachedTrajectory(c.cascadeId); const cached = getEntry(c.cascadeId);
return cached && !Array.isArray(cached.subagentRefs); return cached && !Array.isArray(cached.subagentRefs);
}) })
.slice(0, LEGACY_MIGRATION_BATCH_SIZE); .slice(0, LEGACY_MIGRATION_BATCH_SIZE);
@@ -2477,9 +2535,9 @@ export async function enumerateAndSyncConversations({
} }
if (candidate && candidate !== conv.rootConversationId) { if (candidate && candidate !== conv.rootConversationId) {
conv.rootConversationId = candidate; conv.rootConversationId = candidate;
const cached = getCachedTrajectory(conv.cascadeId); const cached = getEntry(conv.cascadeId);
if (cached && cached.rootConversationId !== candidate) { if (cached && cached.rootConversationId !== candidate) {
setCachedTrajectory(conv.cascadeId, { ...cached, rootConversationId: candidate }); setEntry(conv.cascadeId, { ...cached, rootConversationId: candidate });
cacheDirty = true; cacheDirty = true;
} }
} }
@@ -2488,41 +2546,49 @@ export async function enumerateAndSyncConversations({
const hasRunningSessions = rawConversations.some( const hasRunningSessions = rawConversations.some(
(c) => c.status === 'CASCADE_RUN_STATUS_RUNNING' (c) => c.status === 'CASCADE_RUN_STATUS_RUNNING'
); );
if (cacheDirty || (hasPendingTrajectoryCacheSave() && !hasRunningSessions)) { if (cacheDirty || (hasPendingSave() && !hasRunningSessions)) {
persistTrajectoryCacheIfNeeded({ hasRunningSessions }); persistCacheIfNeeded({ hasRunningSessions });
} }
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态 // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态
for (const conv of rawConversations) { for (const conv of rawConversations) {
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
if (!conv.liveActivity) { if (!conv.liveActivity) {
const tailSteps = readTranscriptTailSteps(conv.cascadeId); const cachedConv = getEntry(conv.cascadeId);
if (isParkedOnSwarmWait(tailSteps)) { const parkedByCache =
Boolean(cachedConv?.parkedOnSwarmWait) &&
cachedConv.signature === buildConvSig(conv);
const tailSteps = isRemote ? [] : readTranscriptTailSteps(conv.cascadeId);
const isParked = tailSteps.length > 0 ? isParkedOnSwarmWait(tailSteps) : parkedByCache;
if (isParked) {
conv.status = 'IDLE'; conv.status = 'IDLE';
conv.liveActivity = null; conv.liveActivity = null;
liveActivityMemo.delete(conv.cascadeId.toLowerCase()); activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
continue; continue;
} }
const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0; const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0;
const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs); const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs, {
isRemote,
liveActivityMemoMap: activeLiveActivityMemo,
});
if (resolved?.actionKey === 'swarm_wait') { if (resolved?.actionKey === 'swarm_wait') {
conv.status = 'IDLE'; conv.status = 'IDLE';
conv.liveActivity = null; conv.liveActivity = null;
liveActivityMemo.delete(conv.cascadeId.toLowerCase()); activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
continue; continue;
} }
conv.liveActivity = resolved; conv.liveActivity = resolved;
if (resolved) { if (resolved) {
liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved); activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
} }
} else if (conv.liveActivity.actionKey === 'swarm_wait') { } else if (conv.liveActivity.actionKey === 'swarm_wait') {
conv.status = 'IDLE'; conv.status = 'IDLE';
conv.liveActivity = null; conv.liveActivity = null;
liveActivityMemo.delete(conv.cascadeId.toLowerCase()); activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
} }
} else { } else {
conv.liveActivity = null; conv.liveActivity = null;
liveActivityMemo.delete(conv.cascadeId.toLowerCase()); activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
} }
} }
@@ -2564,8 +2630,9 @@ 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 swarmManifest = readSwarmManifestForCascade(cid); const rootCached = getEntry(rootConv.cascadeId);
const swarmTitle = String(swarmManifest?.title || '').trim(); const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid);
const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim();
if (swarmTitle) { if (swarmTitle) {
rootConv.swarmTitle = swarmTitle; rootConv.swarmTitle = swarmTitle;
const curTitle = String(rootConv.title || '').trim(); const curTitle = String(rootConv.title || '').trim();
@@ -2579,11 +2646,29 @@ export async function enumerateAndSyncConversations({
} }
const subs = subagentsByRoot.get(cid) || []; const subs = subagentsByRoot.get(cid) || [];
const rpcKilledByMember = new Map();
const mergeRpcKilled = (killedMap) => {
if (!killedMap || typeof killedMap !== 'object') return;
for (const [memberKey, killMs] of Object.entries(killedMap)) {
const normMember = String(memberKey || '').trim().toLowerCase();
if (!normMember) continue;
const numMs = Number(killMs || 0);
const prevMs = rpcKilledByMember.get(normMember);
if (prevMs === undefined || numMs > prevMs) {
rpcKilledByMember.set(normMember, numMs);
}
}
};
mergeRpcKilled(rootCached?.swarmMeta?.killedMembers);
for (const s of subs) {
mergeRpcKilled(getEntry(s.cascadeId)?.swarmMeta?.killedMembers);
}
let swarmCount = 0; let swarmCount = 0;
for (const s of subs) { for (const s of subs) {
const subLower = s.cascadeId.toLowerCase(); const subLower = s.cascadeId.toLowerCase();
const mEntry = swarmManifest?.membersByCid.get(subLower) || null; const mEntry = swarmManifest?.membersByCid.get(subLower) || null;
const subCached = getCachedTrajectory(s.cascadeId); const subCached = getEntry(s.cascadeId);
const parsedSwarm = !s.isSideQuestion const parsedSwarm = !s.isSideQuestion
? parseSwarmWorkerRole({ ? parseSwarmWorkerRole({
role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '', role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '',
@@ -2597,11 +2682,27 @@ export async function enumerateAndSyncConversations({
s.isSwarmWorker = true; s.isSwarmWorker = true;
s.swarmMemberName = parsedSwarm.memberName; s.swarmMemberName = parsedSwarm.memberName;
s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary); s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary);
s.killed = Boolean(s.killed || mEntry?.killed); const memberKey = String(parsedSwarm.memberName || '').trim().toLowerCase();
const rpcKilledAtMs =
memberKey && rpcKilledByMember.has(memberKey)
? rpcKilledByMember.get(memberKey)
: undefined;
const subCreatedMs =
s.createdTimeMs || subCached?.createdTimeMs || subCached?.steps?.[0]?.createdAtMs || 0;
const subLastStepMs =
subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
const killedByRpc =
rpcKilledAtMs !== undefined &&
!(
rpcKilledAtMs > 0 &&
((subCreatedMs > 0 && subCreatedMs > rpcKilledAtMs) ||
subLastStepMs > rpcKilledAtMs)
);
s.killed = Boolean(s.killed || (mEntry ? mEntry.killed : killedByRpc));
if (s.killed) { if (s.killed) {
s.status = 'IDLE'; s.status = 'IDLE';
s.liveActivity = null; s.liveActivity = null;
liveActivityMemo.delete(subLower); activeLiveActivityMemo.delete(subLower);
s.swarmState = 'killed'; s.swarmState = 'killed';
} else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') { } else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') {
const parkedInManifest = const parkedInManifest =
@@ -2611,7 +2712,7 @@ export async function enumerateAndSyncConversations({
if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) { if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) {
s.status = 'IDLE'; s.status = 'IDLE';
s.liveActivity = null; s.liveActivity = null;
liveActivityMemo.delete(subLower); activeLiveActivityMemo.delete(subLower);
s.swarmState = 'waiting'; s.swarmState = 'waiting';
} else { } else {
s.swarmState = 'working'; s.swarmState = 'working';
@@ -2639,12 +2740,12 @@ export async function enumerateAndSyncConversations({
} }
const aStart = const aStart =
a.createdTimeMs || a.createdTimeMs ||
getCachedTrajectory(a.cascadeId)?.steps?.[0]?.createdAtMs || getEntry(a.cascadeId)?.steps?.[0]?.createdAtMs ||
a.lastModifiedMs || a.lastModifiedMs ||
0; 0;
const bStart = const bStart =
b.createdTimeMs || b.createdTimeMs ||
getCachedTrajectory(b.cascadeId)?.steps?.[0]?.createdAtMs || getEntry(b.cascadeId)?.steps?.[0]?.createdAtMs ||
b.lastModifiedMs || b.lastModifiedMs ||
0; 0;
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId)); return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
+94
View File
@@ -552,3 +552,97 @@ export async function ensureLsEndpointDiscovered({
return lsDiscoveryState.inFlight; return lsDiscoveryState.inFlight;
} }
const LOCAL_HUB_PORTS_TTL_MS = 4000;
const localHubPortsCache = {
ts: 0,
key: '',
value: null,
};
/**
* 收集本机活跃 Hub / Language Server 占用的回环端口集合(含 `httpPort`、`httpsPort` 与当前 `lsRuntimeEndpoint`),
* 不跳过缺少 `csrfToken` 的存活 `hub_*.json` 文件,供 `window-bridge.mjs` 准确区分本地窗口与 SSH 远端窗口。
*
* @param {{ daemonDirs?: string[], isPidAliveFn?: (pid: number) => boolean, force?: boolean }} [options]
* @returns {{ allPorts: Set<number>, httpPorts: Set<number>, httpsPorts: Set<number>, csrfTokens: Set<string> }}
*/
export function getLocalHubPorts({
daemonDirs = DAEMON_DIRS,
isPidAliveFn = defaultIsLsPidAlive,
force = false,
} = {}) {
const dirs = Array.isArray(daemonDirs) ? daemonDirs : [];
const cacheKey = `${dirs.join('|')}::${lsRuntimeEndpoint.baseUrl || ''}::${lsRuntimeEndpoint.csrfToken || ''}`;
const now = Date.now();
if (
!force &&
localHubPortsCache.value &&
localHubPortsCache.key === cacheKey &&
now - localHubPortsCache.ts < LOCAL_HUB_PORTS_TTL_MS
) {
return localHubPortsCache.value;
}
const allPorts = new Set();
const httpPorts = new Set();
const httpsPorts = new Set();
const csrfTokens = new Set();
if (lsRuntimeEndpoint.csrfToken) {
csrfTokens.add(String(lsRuntimeEndpoint.csrfToken).trim());
}
if (lsRuntimeEndpoint.baseUrl) {
try {
const parsed = new URL(lsRuntimeEndpoint.baseUrl);
const port = Number(parsed.port || 0);
if (Number.isInteger(port) && port > 0 && port <= 65535) {
allPorts.add(port);
if (parsed.protocol === 'https:') httpsPorts.add(port);
else httpPorts.add(port);
}
} catch {
// 忽略非法 URL
}
}
for (const dir of dirs) {
if (!dir || !existsSync(dir)) continue;
let names = [];
try {
names = readdirSync(dir);
} catch {
continue;
}
for (const name of names) {
if (!/^hub_.*\.json$/i.test(name)) continue;
const fullPath = join(dir, name);
try {
const parsed = JSON.parse(readFileSync(fullPath, 'utf8'));
const pid = Number(parsed?.pid) || 0;
if (pid > 0 && !isPidAliveFn(pid)) continue;
const csrf = String(parsed?.csrfToken || parsed?.csrf_token || '').trim();
if (csrf) csrfTokens.add(csrf);
const hPort = Number(parsed?.httpPort || parsed?.port) || 0;
const sPort = Number(parsed?.httpsPort) || 0;
if (Number.isInteger(hPort) && hPort > 0 && hPort <= 65535) {
allPorts.add(hPort);
httpPorts.add(hPort);
}
if (Number.isInteger(sPort) && sPort > 0 && sPort <= 65535) {
allPorts.add(sPort);
httpsPorts.add(sPort);
}
} catch {
// 忽略损坏或瞬态 daemon 文件
}
}
}
const snapshot = { allPorts, httpPorts, httpsPorts, csrfTokens };
localHubPortsCache.ts = now;
localHubPortsCache.key = cacheKey;
localHubPortsCache.value = snapshot;
return snapshot;
}
+280 -46
View File
@@ -2,27 +2,203 @@
* @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。 * @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。
* *
* 负责: * 负责:
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`); * 1. 向本地或 SSH 远端窗口对应的 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却, * 2. 对远端 SSH 端点采用双层传输:
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。 * - Tier-1:严格限定回环地址 (`127.0.0.1`/`localhost`/`::1`) 的 HTTP/HTTPS 直连(HTTPS 仅对回环允许宿主自签证书);
* - Tier-2:Tier-1 不可用或鉴权依赖 Electron Partition Cookie / 2.33.0+ 省略 `csrfToken` 时,
* 自动熔断并回退至窗口内同源 `window.fetch` / `/connect-websocket`(通过 CDP 按需执行);
* 3. 拉取并按端点隔离缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要与 `GetAvailableModels` 模型目录。
*/ */
import { lsRuntimeEndpoint, quotaSummaryCache } from './config.mjs'; import { lsRuntimeEndpoint } from './config.mjs';
import {
getEndpointQuotaCache,
getRemoteWindowRpcInvoker,
markRemoteEndpointPreferTier2,
shouldRemoteEndpointPreferTier2,
} from './endpoint-registry.mjs';
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
const QUOTA_CACHE_TTL_MS = 10_000; const QUOTA_CACHE_TTL_MS = 10_000;
const QUOTA_RETRY_COOLDOWN_MS = 5_000; const QUOTA_RETRY_COOLDOWN_MS = 5_000;
const REMOTE_HTTPS_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
const REMOTE_ALLOWED_LS_METHODS = new Set([
'GetUserStatus',
'GetAvailableModels',
'GetAllCascadeTrajectories',
'GetCascadeTrajectory',
'RetrieveUserQuotaSummary',
]);
let contextModelCatalog = null; let contextModelCatalog = null;
let loopbackHttpsModulePromise = null;
let customLoopbackHttpsRequester = null;
export function setLoopbackHttpsRequester(requester) {
customLoopbackHttpsRequester = typeof requester === 'function' ? requester : null;
}
function isStrictLoopbackUrl(rawUrl) {
try {
const parsed = new URL(String(rawUrl || ''));
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
const host = parsed.hostname.toLowerCase();
return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]';
} catch {
return false;
}
}
async function getLoopbackHttpsRequestFn() {
if (customLoopbackHttpsRequester) return customLoopbackHttpsRequester;
if (typeof globalThis !== 'undefined' && typeof globalThis.__agLoopbackHttpsRequest === 'function') {
return globalThis.__agLoopbackHttpsRequest;
}
if (!loopbackHttpsModulePromise) {
loopbackHttpsModulePromise = import('node:https')
.then((mod) => (mod.default || mod)?.request || null)
.catch(() => null);
}
return loopbackHttpsModulePromise;
}
async function postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs) {
const parsed = new URL(urlStr);
if (!isStrictLoopbackUrl(urlStr) || parsed.protocol !== 'https:') {
throw new Error('Refusing non-loopback HTTPS request');
}
const requestFn = await getLoopbackHttpsRequestFn();
if (typeof requestFn !== 'function') {
return fetch(urlStr, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}),
},
body: bodyText,
signal: AbortSignal.timeout(timeoutMs),
});
}
return new Promise((resolve, reject) => {
let settled = false;
let wallTimer = null;
const clearWallTimer = () => {
if (wallTimer) {
clearTimeout(wallTimer);
wallTimer = null;
}
};
const finishErr = (err) => {
if (settled) return;
settled = true;
clearWallTimer();
reject(err);
};
const bodyBuf = Buffer.from(bodyText, 'utf8');
const req = requestFn(
{
hostname: parsed.hostname.replace(/^\[|\]$/g, ''),
port: Number(parsed.port || 443),
path: `${parsed.pathname}${parsed.search}`,
method: 'POST',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': bodyBuf.length,
...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}),
},
},
(res) => {
const chunks = [];
let totalBytes = 0;
res.on('data', (chunk) => {
if (settled) return;
totalBytes += chunk.length;
if (totalBytes > REMOTE_HTTPS_MAX_RESPONSE_BYTES) {
const sizeErr = new Error('Remote LS response exceeded size limit');
finishErr(sizeErr);
req.destroy(sizeErr);
return;
}
chunks.push(chunk);
});
res.on('aborted', () => {
finishErr(new Error('Remote LS HTTPS response aborted'));
});
res.on('end', () => {
if (settled) return;
settled = true;
clearWallTimer();
const status = Number(res.statusCode || 0);
const rawText = Buffer.concat(chunks).toString('utf8');
resolve({
ok: status >= 200 && status < 300,
status,
json: async () => JSON.parse(rawText || '{}'),
text: async () => rawText,
});
});
res.on('error', finishErr);
}
);
wallTimer = setTimeout(() => {
const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`);
finishErr(timeoutErr);
req.destroy(timeoutErr);
}, timeoutMs);
wallTimer?.unref?.();
req.setTimeout(timeoutMs, () => {
const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`);
finishErr(timeoutErr);
req.destroy(timeoutErr);
});
req.on('error', finishErr);
req.write(bodyBuf);
req.end();
});
}
export function getContextModelCatalog(endpoint = null) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
if (isRemote) {
const baseUrl = endpoint.baseUrl || endpoint.origin || '';
const csrfToken = endpoint.csrfToken || '';
const cached = endpoint.contextModelCatalog;
if (
!cached ||
cached.baseUrl !== baseUrl ||
cached.csrfToken !== csrfToken ||
Date.now() >= cached.expiresAt
) {
endpoint.contextModelCatalog = {
baseUrl,
csrfToken,
expiresAt: Date.now() + 30000,
promise: callLsRpc('GetAvailableModels', {}, 2500, endpoint)
.then((data) => data?.response?.models)
.catch(() => null),
};
}
return endpoint.contextModelCatalog.promise;
}
export function getContextModelCatalog() {
const { baseUrl, csrfToken } = lsRuntimeEndpoint; const { baseUrl, csrfToken } = lsRuntimeEndpoint;
if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken || if (
Date.now() >= contextModelCatalog.expiresAt) { !contextModelCatalog ||
contextModelCatalog.baseUrl !== baseUrl ||
contextModelCatalog.csrfToken !== csrfToken ||
Date.now() >= contextModelCatalog.expiresAt
) {
contextModelCatalog = { contextModelCatalog = {
baseUrl, baseUrl,
csrfToken, csrfToken,
expiresAt: Date.now() + 30000, expiresAt: Date.now() + 30000,
promise: callLsRpc('GetAvailableModels', {}, 1500).then((data) => data?.response?.models).catch(() => null), promise: callLsRpc('GetAvailableModels', {}, 1500)
.then((data) => data?.response?.models)
.catch(() => null),
}; };
} }
return contextModelCatalog.promise; return contextModelCatalog.promise;
@@ -40,15 +216,77 @@ async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
}); });
} }
async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
if (!REMOTE_ALLOWED_LS_METHODS.has(method)) {
throw new Error(`RPC method ${method} is not allowed on remote endpoints`);
}
const baseUrl = String(endpoint.baseUrl || endpoint.origin || '').trim().replace(/\/+$/, '');
const csrfToken = String(endpoint.csrfToken || '').trim();
const windowInvoker = getRemoteWindowRpcInvoker();
const canTryTier1 =
Boolean(baseUrl) &&
isStrictLoopbackUrl(baseUrl) &&
Boolean(csrfToken) &&
!shouldRemoteEndpointPreferTier2(endpoint);
let tier1Err = null;
if (canTryTier1) {
try {
const urlStr = `${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`;
const bodyText = JSON.stringify(body || {});
const res = urlStr.startsWith('https://')
? await postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs)
: await postLsRpcOnce(baseUrl, csrfToken, method, body || {}, timeoutMs);
if (res?.ok) {
return await res.json();
}
const status = Number(res?.status || 0);
const text = await res?.text?.().catch(() => '') || '';
tier1Err = new Error(`Remote RPC ${method} failed (${status}): ${text}`);
const isTransportAuthOrRouteMiss =
status === 0 ||
status === 401 ||
status === 403 ||
(status === 404 && method !== 'GetCascadeTrajectory');
if (isTransportAuthOrRouteMiss) {
markRemoteEndpointPreferTier2(endpoint);
} else {
// 业务级 4xx(如单个会话已被删除导致的 GetCascadeTrajectory 404)直接上抛,不误触熔断
throw tier1Err;
}
} catch (err) {
if (err === tier1Err) {
throw err;
}
tier1Err = err;
markRemoteEndpointPreferTier2(endpoint);
}
}
if (typeof windowInvoker === 'function') {
return windowInvoker(endpoint, method, body || {}, timeoutMs);
}
if (tier1Err) {
throw tier1Err;
}
throw new Error(`Remote LS transport unavailable for endpoint ${endpoint.id}`);
}
/** /**
* 调用本地 `LanguageServerService` 的指定 RPC 方法(支持按需发现与宿主重启重连)。 * 调用本地或远端 SSH `LanguageServerService` 的指定 RPC 方法(本地支持按需发现与宿主重启重连)。
* *
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`) * @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
* @param {object} [body={}] 请求 JSON 载荷 * @param {object} [body={}] 请求 JSON 载荷
* @param {number} [timeoutMs=5000] 超时时间(毫秒) * @param {number} [timeoutMs=5000] 超时时间(毫秒)
* @param {object|null} [endpoint=null] 可选远端端点对象;缺省调用本机 LS
* @returns {Promise<object>} * @returns {Promise<object>}
*/ */
export async function callLsRpc(method, body = {}, timeoutMs = 5000) { export async function callLsRpc(method, body = {}, timeoutMs = 5000, endpoint = null) {
if (endpoint && endpoint.isRemote) {
return callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs);
}
if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') { if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') {
await ensureLsEndpointDiscovered({ force: false }); await ensureLsEndpointDiscovered({ force: false });
} }
@@ -113,35 +351,31 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
} }
/** /**
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`)。 * 获取官方实时配额摘要(`RetrieveUserQuotaSummary`),按端点与账号隔离短期缓存。
*
* 缓存策略:
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
* - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞;
* - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
* *
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却 * @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存 * @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
* @param {object|null} [endpoint=null] 可选远端端点对象
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>} * @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
*/ */
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') { export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '', endpoint = null) {
if (quotaSummaryCache.accountName !== accountName) { const qCache = getEndpointQuotaCache(endpoint);
Object.assign(quotaSummaryCache, { if (qCache.accountName !== accountName) {
Object.assign(qCache, {
accountName, accountName,
accountGeneration: quotaSummaryCache.accountGeneration + 1, accountGeneration: qCache.accountGeneration + 1,
ts: 0, ts: 0,
lastAttemptTs: 0, lastAttemptTs: 0,
data: null, data: null,
error: null, error: null,
}); });
} }
const generation = quotaSummaryCache.accountGeneration; const generation = qCache.accountGeneration;
const now = Date.now(); const now = Date.now();
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) { if (!forceRefresh && qCache.data && now - qCache.ts < QUOTA_CACHE_TTL_MS) {
return { return {
data: quotaSummaryCache.data, data: qCache.data,
fetchedAtMs: quotaSummaryCache.ts, fetchedAtMs: qCache.ts,
isStale: false, isStale: false,
refreshFailed: false, refreshFailed: false,
error: null, error: null,
@@ -150,35 +384,35 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
} }
if ( if (
!forceRefresh && !forceRefresh &&
quotaSummaryCache.lastAttemptTs > 0 && qCache.lastAttemptTs > 0 &&
now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS && now - qCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
quotaSummaryCache.error qCache.error
) { ) {
return { return {
data: quotaSummaryCache.data, data: qCache.data,
fetchedAtMs: quotaSummaryCache.ts || 0, fetchedAtMs: qCache.ts || 0,
isStale: Boolean(quotaSummaryCache.data), isStale: Boolean(qCache.data),
refreshFailed: true, refreshFailed: true,
error: quotaSummaryCache.error, error: qCache.error,
fromCache: true, fromCache: true,
}; };
} }
quotaSummaryCache.lastAttemptTs = now; qCache.lastAttemptTs = now;
try { try {
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000); const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000, endpoint);
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000); const { userStatus } = await callLsRpc('GetUserStatus', {}, 2500, endpoint);
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {}; if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
if (generation !== quotaSummaryCache.accountGeneration) return {}; if (generation !== qCache.accountGeneration) return {};
const payload = res?.response !== undefined ? res.response : res; const payload = res?.response !== undefined ? res.response : res;
if (payload && typeof payload === 'object' && !Array.isArray(payload)) { if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
const normalized = const normalized =
Array.isArray(payload.groups) || Array.isArray(payload.buckets) Array.isArray(payload.groups) || Array.isArray(payload.buckets)
? payload ? payload
: { ...payload, groups: [] }; : { ...payload, groups: [] };
quotaSummaryCache.ts = now; qCache.ts = now;
quotaSummaryCache.data = normalized; qCache.data = normalized;
quotaSummaryCache.error = null; qCache.error = null;
return { return {
data: normalized, data: normalized,
fetchedAtMs: now, fetchedAtMs: now,
@@ -188,18 +422,18 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
fromCache: false, fromCache: false,
}; };
} }
quotaSummaryCache.error = 'Quota summary empty'; qCache.error = 'Quota summary empty';
} catch (err) { } catch (err) {
if (generation !== quotaSummaryCache.accountGeneration) return {}; if (generation !== qCache.accountGeneration) return {};
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`); console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
quotaSummaryCache.error = err.message; qCache.error = err.message;
} }
return { return {
data: quotaSummaryCache.data, data: qCache.data,
fetchedAtMs: quotaSummaryCache.ts || 0, fetchedAtMs: qCache.ts || 0,
isStale: Boolean(quotaSummaryCache.data), isStale: Boolean(qCache.data),
refreshFailed: true, refreshFailed: true,
error: quotaSummaryCache.error || 'Quota RPC unavailable', error: qCache.error || 'Quota RPC unavailable',
fromCache: false, fromCache: false,
}; };
} }
+65 -8
View File
@@ -49,6 +49,7 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
combined.includes('GEMINI') || combined.includes('GEMINI') ||
combined.includes('CARBON') || combined.includes('CARBON') ||
combined.includes('ARGON') || combined.includes('ARGON') ||
combined.includes('NEON') ||
combined.includes('HYDROGEN') || combined.includes('HYDROGEN') ||
combined.includes('ORCHESTRATOR') || combined.includes('ORCHESTRATOR') ||
combined.includes('HELIX') || combined.includes('HELIX') ||
@@ -60,6 +61,23 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
return 'Other'; return 'Other';
} }
/**
* 判断一组模型标识字段是否指向 Gemini 4 Neon 系列模型(含 M535 及 M537 Orchestrator (Neon))。
*
* @param {...string} parts 待检测的标识片段
* @returns {boolean}
*/
export function isNeonModelIdentifier(...parts) {
const text = parts.filter(Boolean).join(' ');
if (
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) &&
!/\bneon\b|MODEL_PLACEHOLDER_M53[57]\b/i.test(text)
) {
return false;
}
return /\bneon\b|gemini-(?:4-)?neon|MODEL_PLACEHOLDER_M53[57]\b/i.test(text);
}
/** /**
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 及 M681 Orchestrator (Argon))。 * 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 及 M681 Orchestrator (Argon))。
* *
@@ -77,8 +95,27 @@ export function isArgonModelIdentifier(...parts) {
return /argon|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text); return /argon|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text);
} }
/**
* 从一组标识字段中提取显式的非通用 Orchestrator 变体代号(如 `Orchestrator (Xenon)` -> `'xenon'`、
* `gemini-pro-orchestrator-neon` -> `'neon'`)。未命中时返回空字符串。
*
* @param {string} text
* @returns {string}
*/
function extractExplicitOrchestratorVariant(text = '') {
const parenMatch = text.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i);
if (parenMatch) return parenMatch[1].toLowerCase();
const slugMatch = text.match(/\b(?:gemini-pro-orchestrator|orchestrator|orch)-([a-z0-9]+)\b/i);
if (slugMatch && slugMatch[1].toLowerCase() !== 'worker') {
return slugMatch[1].toLowerCase();
}
return '';
}
/** /**
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M427/M429/M437/M438 及 M667 Orchestrator (Carbon))。 * 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M427/M429/M437/M438 及 M667 Orchestrator (Carbon))。
* 仅当显式命中 Carbon 标识,或裸 `gemini-pro-orchestrator` 不携带任何其他变体代号时才判定为 Carbon,
* 防止未来新增 `Orchestrator (<新代号>)` 被静默误判为 Carbon。
* *
* @param {...string} parts 待检测的标识片段 * @param {...string} parts 待检测的标识片段
* @returns {boolean} * @returns {boolean}
@@ -88,15 +125,23 @@ export function isCarbonModelIdentifier(...parts) {
if (/\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M(?:42[79]|43[78]|667)\b/i.test(text)) { if (/\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M(?:42[79]|43[78]|667)\b/i.test(text)) {
return true; return true;
} }
if (/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text)) { if (
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) ||
/\bneon\b|gemini-(?:4-)?neon|MODEL_PLACEHOLDER_M53[57]\b/i.test(text) ||
/\bargon\b|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text)
) {
return false; return false;
} }
return /\bgemini-pro-orchestrator\b(?!-argon)/i.test(text); const explicitVariant = extractExplicitOrchestratorVariant(text);
if (explicitVariant && explicitVariant !== 'carbon') {
return false;
}
return /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(text);
} }
/** /**
* 剥离模型展示名称末尾的思考档位后缀(如 `(XHigh)`、`(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。 * 剥离模型展示名称末尾的思考档位后缀(如 `(XHigh)`、`(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
* 保留 `(Carbon)` / `(Argon)` 后缀,以便 `Orchestrator (Carbon)` 与 `Orchestrator (Argon)` 在汇总表中保持分列。 * 保留 `(Carbon)` / `(Argon)` / `(Neon)` 后缀,以便不同 Orchestrator 系列在汇总表中保持分列。
* *
* @param {string} [label=''] * @param {string} [label='']
* @returns {string} * @returns {string}
@@ -138,7 +183,7 @@ export function formatGenericModelSlug(slug = '') {
if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash'; if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash';
if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro'; if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro';
const m = s.match( const m = s.match(
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i /^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i
); );
if (m) { if (m) {
const ver = m[1]; const ver = m[1];
@@ -148,12 +193,18 @@ export function formatGenericModelSlug(slug = '') {
const tierSuffix = SLUG_TIER_LABELS[suffixKey] ? ` (${SLUG_TIER_LABELS[suffixKey]})` : ''; const tierSuffix = SLUG_TIER_LABELS[suffixKey] ? ` (${SLUG_TIER_LABELS[suffixKey]})` : '';
return `Gemini ${ver} ${tier}${lite}${tierSuffix}`; return `Gemini ${ver} ${tier}${lite}${tierSuffix}`;
} }
const codenameMatch = s.match(/^gemini-(hydrogen|helix)$/i); const codenameMatch = s.match(/^gemini-(hydrogen|helix|neon)$/i);
if (codenameMatch) { if (codenameMatch) {
const codename = const codename =
codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase(); codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase();
return `Gemini ${codename}`; return `Gemini ${codename}`;
} }
const orchVariantMatch = s.match(/^gemini-pro-orchestrator-([a-z0-9]+)$/i);
if (orchVariantMatch) {
const variant =
orchVariantMatch[1].charAt(0).toUpperCase() + orchVariantMatch[1].slice(1).toLowerCase();
return `Orchestrator (${variant})`;
}
if (/^gemini-flash-worker-agy$/i.test(s)) { if (/^gemini-flash-worker-agy$/i.test(s)) {
return 'Orchestrator Worker (Hydrogen)'; return 'Orchestrator Worker (Hydrogen)';
} }
@@ -298,6 +349,11 @@ function resolveModelCatalogEntry(
const isOpaqueOrchestratorResp = Boolean( const isOpaqueOrchestratorResp = Boolean(
cleanResponseModel && /\borchestrator\b/i.test(cleanResponseModel) cleanResponseModel && /\borchestrator\b/i.test(cleanResponseModel)
); );
const isBareOpaqueOrchestratorResp = /^gemini-pro-orchestrator$/i.test(cleanResponseModel);
const allowOpaqueOrchestratorFallback =
isOpaqueOrchestratorResp &&
(!isBareOpaqueOrchestratorResp ||
isCarbonModelIdentifier(rawModelKey, modelId, derivedDisplay, cleanResponseModel));
const explicitPricing = const explicitPricing =
MODEL_PRICING[modelId] || MODEL_PRICING[modelId] ||
MODEL_PRICING[rawModelKey] || MODEL_PRICING[rawModelKey] ||
@@ -308,9 +364,7 @@ function resolveModelCatalogEntry(
MODEL_PRICING[tieredDashedSlug] || MODEL_PRICING[tieredDashedSlug] ||
MODEL_PRICING[canonicalSlug] || MODEL_PRICING[canonicalSlug] ||
MODEL_PRICING[dashedSlug] || MODEL_PRICING[dashedSlug] ||
(cleanResponseModel && isOpaqueOrchestratorResp (allowOpaqueOrchestratorFallback ? MODEL_PRICING[cleanResponseModel] : null);
? MODEL_PRICING[cleanResponseModel]
: null);
if (explicitPricing) { if (explicitPricing) {
return { return {
@@ -469,6 +523,9 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
) { ) {
return `${s} (hydrogen-4)`; return `${s} (hydrogen-4)`;
} }
if (isNeonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
return `${s} (neon-4)`;
}
if (isArgonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) { if (isArgonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
return `${s} (argon-4)`; return `${s} (argon-4)`;
} }
+9 -3
View File
@@ -31,6 +31,7 @@ import {
normalizeHoverModules, normalizeHoverModules,
normalizeLanguageSetting, normalizeLanguageSetting,
normalizeModelDisplayMode, normalizeModelDisplayMode,
normalizeModernUi,
normalizeOrchestratorIdMode, normalizeOrchestratorIdMode,
normalizeOverviewMetrics, normalizeOverviewMetrics,
normalizeOverviewModules, normalizeOverviewModules,
@@ -73,6 +74,7 @@ export {
normalizeHoverModules, normalizeHoverModules,
normalizeLanguageSetting, normalizeLanguageSetting,
normalizeModelDisplayMode, normalizeModelDisplayMode,
normalizeModernUi,
normalizeOrchestratorIdMode, normalizeOrchestratorIdMode,
normalizeOverviewMetrics, normalizeOverviewMetrics,
normalizeOverviewModules, normalizeOverviewModules,
@@ -107,10 +109,11 @@ export function normalizeModelContextWindows(value) {
} }
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
language: 'zh-CN', language: 'auto',
themeAccent: 'host', themeAccent: 'host',
fontScale: 'md', fontScale: 'md',
experimentalModernUi: false, modernUi: true,
experimentalModernUi: true,
weeklyTokenBudget: 150000000, weeklyTokenBudget: 150000000,
weeklyCostBudget: 100, weeklyCostBudget: 100,
weeklyLimitMode: 'official', weeklyLimitMode: 'official',
@@ -173,11 +176,14 @@ export function normalizeFullSettings(rawInput) {
safeRaw.modelDisplayMode, safeRaw.modelDisplayMode,
safeRaw.showUpstreamModel safeRaw.showUpstreamModel
); );
const modernUi =
safeRaw.modernUi !== undefined ? normalizeModernUi(safeRaw.modernUi) : true;
return { return {
language: normalizeLanguageSetting(safeRaw.language), language: normalizeLanguageSetting(safeRaw.language),
themeAccent: normalizeThemeAccent(safeRaw.themeAccent), themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
fontScale: normalizeFontScale(safeRaw.fontScale), fontScale: normalizeFontScale(safeRaw.fontScale),
experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi), modernUi,
experimentalModernUi: modernUi,
weeklyTokenBudget: schemaSanitizePositiveNum( weeklyTokenBudget: schemaSanitizePositiveNum(
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit, safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit,
DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget
+142 -49
View File
@@ -10,6 +10,7 @@
*/ */
import { isDeepStrictEqual } from 'node:util'; import { isDeepStrictEqual } from 'node:util';
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs'; import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
import { import {
extractLiveActivity, extractLiveActivity,
@@ -22,14 +23,13 @@ import {
import { import {
CLI_STATUS_SNAPSHOT_FILE, CLI_STATUS_SNAPSHOT_FILE,
computeRuntimeCodeVersion, computeRuntimeCodeVersion,
getCachedTrajectory,
inFlightRequests, inFlightRequests,
listCachedTrajectoryEntries,
loadSettings, loadSettings,
lsRuntimeEndpoint, lsRuntimeEndpoint,
roundMetric, roundMetric,
saveJson, saveJson,
} from './config.mjs'; } from './config.mjs';
import { getEndpointCacheStore } from './endpoint-registry.mjs';
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs'; import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs';
import { enumerateAndSyncConversations } from './local-scanner.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs';
@@ -57,17 +57,30 @@ import {
const MAX_RECENT_CONVERSATIONS = 30; const MAX_RECENT_CONVERSATIONS = 30;
const MAX_CONVERSATION_ASSEMBLY_CACHE = 8; const MAX_CONVERSATION_ASSEMBLY_CACHE = 8;
const MAX_TELEMETRY_SNAPSHOT_ENDPOINTS = 8;
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
const inFlightTelemetrySources = new Map(); const inFlightTelemetrySources = new Map();
const trajectoryModelFacts = new WeakMap(); const trajectoryModelFacts = new WeakMap();
let agentStepPrepCache = new WeakMap(); let agentStepPrepCache = new WeakMap();
const conversationAssemblyCache = new Map(); const conversationAssemblyCache = new Map();
let lastCompletedTelemetrySnapshot = null; const lastCompletedTelemetrySnapshotsByEndpoint = new Map();
export function clearTelemetryBuilderMemo() { export function clearTelemetryBuilderMemo(endpointId = null) {
if (endpointId) {
const epKey = String(endpointId);
lastCompletedTelemetrySnapshotsByEndpoint.delete(epKey);
const prefix = `${epKey}::`;
for (const key of Array.from(conversationAssemblyCache.keys())) {
if (key.startsWith(prefix)) {
conversationAssemblyCache.delete(key);
}
}
clearUsageAggregatorMemo(epKey);
return;
}
agentStepPrepCache = new WeakMap(); agentStepPrepCache = new WeakMap();
conversationAssemblyCache.clear(); conversationAssemblyCache.clear();
lastCompletedTelemetrySnapshot = null; lastCompletedTelemetrySnapshotsByEndpoint.clear();
clearUsageAggregatorMemo(); clearUsageAggregatorMemo();
} }
@@ -76,12 +89,13 @@ function roundSessionCost(val) {
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2); return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
} }
function findTrajectoryCacheEntry(cascadeId) { function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
if (!cascadeId) return null; if (!cascadeId) return null;
const entry = getCachedTrajectory(cascadeId); const store = cacheStore || getEndpointCacheStore(null);
const entry = store.getCachedTrajectory(cascadeId);
if (entry) return entry; if (entry) return entry;
const targetLower = String(cascadeId).toLowerCase(); const targetLower = String(cascadeId).toLowerCase();
for (const [k, v] of listCachedTrajectoryEntries()) { for (const [k, v] of store.listCachedTrajectoryEntries()) {
if (k.toLowerCase() === targetLower) return v; if (k.toLowerCase() === targetLower) return v;
} }
return null; return null;
@@ -120,9 +134,10 @@ function readTrajectoryModelFacts(steps) {
} }
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */ /** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
function buildKnownUpstreamModelMap(contextLimits) { function buildKnownUpstreamModelMap(contextLimits, cacheStore = null) {
const store = cacheStore || getEndpointCacheStore(null);
const knownUpstreamByModelKey = new Map(); const knownUpstreamByModelKey = new Map();
for (const [, entry] of listCachedTrajectoryEntries()) { for (const [, entry] of store.listCachedTrajectoryEntries()) {
if (!entry?.steps?.length) continue; if (!entry?.steps?.length) continue;
const facts = readTrajectoryModelFacts(entry.steps); const facts = readTrajectoryModelFacts(entry.steps);
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model); for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
@@ -736,14 +751,24 @@ export function buildAgentUnitTelemetry({
}; };
} }
async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { async function readTelemetrySources(
const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh }); requestedConvId,
forceQuotaRefresh,
currentAccountName,
accountScope,
userStatus,
endpoint = null
) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
const localSummaries = isRemote
? { available: false, summariesObj: {}, sideQuestionParents: {} }
: readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh });
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([ const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
localSummaries.available localSummaries.available
? Promise.resolve(null) ? Promise.resolve(null)
: callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), : callLsRpc('GetAllCascadeTrajectories', {}, 5000, endpoint).catch(() => ({})),
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null, userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName, endpoint) : null,
getContextModelCatalog(), getContextModelCatalog(endpoint),
]); ]);
const sessions = await enumerateAndSyncConversations({ const sessions = await enumerateAndSyncConversations({
@@ -754,16 +779,25 @@ async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentA
currentAccountName: accountScope, currentAccountName: accountScope,
requestedConvId, requestedConvId,
forceRefresh: forceQuotaRefresh, forceRefresh: forceQuotaRefresh,
endpoint,
}); });
return { officialQuotaInfo, contextModelCatalog, sessions }; return { officialQuotaInfo, contextModelCatalog, sessions };
} }
function getTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { function getTelemetrySources(
requestedConvId,
forceQuotaRefresh,
currentAccountName,
accountScope,
userStatus,
endpoint = null
) {
const endpointKey = endpoint?.isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID;
const read = () => readTelemetrySources( const read = () => readTelemetrySources(
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint
); );
if (forceQuotaRefresh) return read(); if (forceQuotaRefresh) return read();
const key = JSON.stringify([requestedConvId || '', accountScope, Boolean(userStatus)]); const key = JSON.stringify([endpointKey, requestedConvId || '', accountScope, Boolean(userStatus)]);
const existing = inFlightTelemetrySources.get(key); const existing = inFlightTelemetrySources.get(key);
if (existing) return existing; if (existing) return existing;
const pending = read().finally(() => { const pending = read().finally(() => {
@@ -781,12 +815,17 @@ function buildActiveConversationAssembly({
knownUpstreamByModelKey, knownUpstreamByModelKey,
modelInputs, modelInputs,
accountScope, accountScope,
endpointId = LOCAL_ENDPOINT_ID,
cacheStore = null,
}) { }) {
const activeSteps = activeEntry?.steps || []; const activeSteps = activeEntry?.steps || [];
const subagentSummaries = activeConvSummary?.subagents || []; const subagentSummaries = activeConvSummary?.subagents || [];
const cacheKey = String(activeCascadeId || '__empty__').toLowerCase(); const epKey = String(endpointId || LOCAL_ENDPOINT_ID);
const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`;
const subEntries = subagentSummaries.map((subSum) => findTrajectoryCacheEntry(subSum.cascadeId)); const subEntries = subagentSummaries.map((subSum) =>
findTrajectoryCacheEntry(subSum.cascadeId, cacheStore)
);
const subRawStepsList = subEntries.map((entry) => entry?.steps || []); const subRawStepsList = subEntries.map((entry) => entry?.steps || []);
const combinedFallbackKeys = new Set(); const combinedFallbackKeys = new Set();
for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) { for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) {
@@ -849,7 +888,7 @@ function buildActiveConversationAssembly({
return cachedAssembly.result; return cachedAssembly.result;
} }
const agentReuseInputs = { ...modelInputs, activeCascadeId, accountScope }; const agentReuseInputs = { ...modelInputs, endpointId: epKey, activeCascadeId, accountScope };
const mainUnit = buildAgentUnitTelemetry({ const mainUnit = buildAgentUnitTelemetry({
agentId: 'main', agentId: 'main',
cascadeId: activeCascadeId, cascadeId: activeCascadeId,
@@ -1492,7 +1531,7 @@ function buildActivePoolAndWeeklyQuotas({
* *
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话) * @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
* @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避 * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项 * @param {{ range?: string, startMs?: number, endMs?: number, endpoint?: object|null }} [filterOpts={}] 时间范围筛选选项与可选远端端点
* @returns {Promise<object>} * @returns {Promise<object>}
*/ */
export async function buildTelemetryPayloadInternal( export async function buildTelemetryPayloadInternal(
@@ -1500,11 +1539,18 @@ export async function buildTelemetryPayloadInternal(
forceQuotaRefresh = false, forceQuotaRefresh = false,
filterOpts = {} filterOpts = {}
) { ) {
const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
const isRemote = Boolean(endpoint);
const endpointId = isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID;
const endpointLabel = isRemote ? String(endpoint.label || 'SSH') : '';
const cacheStore = getEndpointCacheStore(endpoint);
const settings = loadSettings(); const settings = loadSettings();
let userStatus = await callLsRpc('GetUserStatus', {}) let userStatus = await callLsRpc('GetUserStatus', {}, 5000, endpoint)
.then((data) => data?.userStatus) .then((data) => data?.userStatus)
.catch(() => null); .catch(() => null);
if ( if (
!isRemote &&
!userStatus && !userStatus &&
lsRuntimeEndpoint.addr !== 'test.invalid' && lsRuntimeEndpoint.addr !== 'test.invalid' &&
(!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic) (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic)
@@ -1529,7 +1575,7 @@ export async function buildTelemetryPayloadInternal(
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName; const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources( const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint
); );
const { conversations, activeConvSummary, activeCascadeId } = sessions; const { conversations, activeConvSummary, activeCascadeId } = sessions;
@@ -1546,8 +1592,8 @@ export async function buildTelemetryPayloadInternal(
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
const reportedContextLimits = new Map(); const reportedContextLimits = new Map();
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits); const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId); const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
const modelInputs = { const modelInputs = {
catalogRevision: pricingCatalogRevision, catalogRevision: pricingCatalogRevision,
phaseEpoch: getPricingPhaseEpoch(), phaseEpoch: getPricingPhaseEpoch(),
@@ -1565,6 +1611,8 @@ export async function buildTelemetryPayloadInternal(
knownUpstreamByModelKey, knownUpstreamByModelKey,
modelInputs, modelInputs,
accountScope, accountScope,
endpointId,
cacheStore,
}); });
// 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT) // 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT)
@@ -1623,6 +1671,7 @@ export async function buildTelemetryPayloadInternal(
resolveStepModel, resolveStepModel,
quotaPoolsMap, quotaPoolsMap,
modelInputs, modelInputs,
endpoint,
}); });
for (const [pk, poolObj] of quotaPoolsMap.entries()) { for (const [pk, poolObj] of quotaPoolsMap.entries()) {
@@ -1665,7 +1714,7 @@ export async function buildTelemetryPayloadInternal(
if (cidKey && quickStatsMemo.has(cidKey)) { if (cidKey && quickStatsMemo.has(cidKey)) {
return quickStatsMemo.get(cidKey); return quickStatsMemo.get(cidKey);
} }
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId); const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore);
const rootSteps = rootEntry?.steps || []; const rootSteps = rootEntry?.steps || [];
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : []; const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
@@ -1686,7 +1735,7 @@ export async function buildTelemetryPayloadInternal(
let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep); let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep);
for (const subSum of rawSubs) { for (const subSum of rawSubs) {
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
const subSteps = subEntry?.steps || []; const subSteps = subEntry?.steps || [];
if (subSteps.length === 0) continue; if (subSteps.length === 0) continue;
accumulateStepsCost(subSteps); accumulateStepsCost(subSteps);
@@ -1752,7 +1801,7 @@ export async function buildTelemetryPayloadInternal(
continue; continue;
} }
const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId); const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId, cacheStore);
const rootFallbackMs = const rootFallbackMs =
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
@@ -1761,7 +1810,7 @@ export async function buildTelemetryPayloadInternal(
let runSideIdx = 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); const subEntry = findTrajectoryCacheEntry(subCid, cacheStore);
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
const isSideQ = Boolean( const isSideQ = Boolean(
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
@@ -2016,6 +2065,11 @@ export async function buildTelemetryPayloadInternal(
const finalPayload = { const finalPayload = {
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
hostPlatform: process.platform || 'unknown', hostPlatform: process.platform || 'unknown',
endpoint: {
id: endpointId,
isRemote,
label: endpointLabel,
},
uiBundleVersion, uiBundleVersion,
windowBridge: getDefaultWindowBridgeStatus(), windowBridge: getDefaultWindowBridgeStatus(),
settings: loadSettings(), settings: loadSettings(),
@@ -2104,8 +2158,20 @@ export async function buildTelemetryPayloadInternal(
modelBreakdown, modelBreakdown,
}; };
lastCompletedTelemetrySnapshot = { const endpointSig = isRemote
lsAddr: String(lsRuntimeEndpoint.addr || ''), ? `${Number(endpoint?.instanceId || 0)}|${String(endpoint?.baseUrl || '')}|${String(endpoint?.csrfToken || '')}`
: String(lsRuntimeEndpoint.addr || '');
lastCompletedTelemetrySnapshotsByEndpoint.delete(endpointId);
if (lastCompletedTelemetrySnapshotsByEndpoint.size >= MAX_TELEMETRY_SNAPSHOT_ENDPOINTS) {
const oldestKey = lastCompletedTelemetrySnapshotsByEndpoint.keys().next().value;
if (oldestKey !== undefined) {
lastCompletedTelemetrySnapshotsByEndpoint.delete(oldestKey);
}
}
lastCompletedTelemetrySnapshotsByEndpoint.set(endpointId, {
endpointId,
isRemote,
endpointSig,
weeklyLimitMode: settings.weeklyLimitMode, weeklyLimitMode: settings.weeklyLimitMode,
weeklyTokenBudget: settings.weeklyTokenBudget, weeklyTokenBudget: settings.weeklyTokenBudget,
weeklyCostBudget: settings.weeklyCostBudget, weeklyCostBudget: settings.weeklyCostBudget,
@@ -2132,10 +2198,11 @@ export async function buildTelemetryPayloadInternal(
resolveStepModel, resolveStepModel,
quotaPoolsMap, quotaPoolsMap,
modelInputs, modelInputs,
endpoint,
}, },
}; });
if (lsRuntimeEndpoint.addr !== 'test.invalid') { if (!isRemote && lsRuntimeEndpoint.addr !== 'test.invalid') {
try { try {
saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now())); saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now()));
} catch { } catch {
@@ -2146,10 +2213,15 @@ export async function buildTelemetryPayloadInternal(
return finalPayload; return finalPayload;
} }
function resolveValidFastSnapshot() { function resolveValidFastSnapshot(endpoint = null) {
const snap = lastCompletedTelemetrySnapshot; const isRemote = Boolean(endpoint?.isRemote);
const endpointId = isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID;
const snap = lastCompletedTelemetrySnapshotsByEndpoint.get(endpointId);
if (!snap || !snap.basePayload || !snap.aggContext) return null; if (!snap || !snap.basePayload || !snap.aggContext) return null;
if (snap.lsAddr !== String(lsRuntimeEndpoint.addr || '')) return null; const expectedSig = isRemote
? `${Number(endpoint?.instanceId || 0)}|${String(endpoint?.baseUrl || '')}|${String(endpoint?.csrfToken || '')}`
: String(lsRuntimeEndpoint.addr || '');
if (snap.endpointSig !== expectedSig) return null;
if ( if (
snap.catalogRevision !== pricingCatalogRevision || snap.catalogRevision !== pricingCatalogRevision ||
snap.phaseEpoch !== getPricingPhaseEpoch() snap.phaseEpoch !== getPricingPhaseEpoch()
@@ -2177,7 +2249,10 @@ function entryNeedsLazyTelemetryUpgrade(entry) {
} }
function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
const snap = resolveValidFastSnapshot(); const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
const endpointId = endpoint ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID;
const cacheStore = getEndpointCacheStore(endpoint);
const snap = resolveValidFastSnapshot(endpoint);
if (!snap || !Array.isArray(snap.sessions?.conversations)) return null; if (!snap || !Array.isArray(snap.sessions?.conversations)) return null;
const convList = snap.sessions.conversations; const convList = snap.sessions.conversations;
@@ -2192,7 +2267,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
if (!activeConvSummary?.cascadeId) return null; if (!activeConvSummary?.cascadeId) return null;
const activeCascadeId = activeConvSummary.cascadeId; const activeCascadeId = activeConvSummary.cascadeId;
const activeEntry = findTrajectoryCacheEntry(activeCascadeId); const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
if (!activeEntry) return null; if (!activeEntry) return null;
const subagentSummaries = Array.isArray(activeConvSummary.subagents) const subagentSummaries = Array.isArray(activeConvSummary.subagents)
@@ -2207,7 +2282,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
needsBackgroundSync = true; needsBackgroundSync = true;
break; break;
} }
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) { if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
needsBackgroundSync = true; needsBackgroundSync = true;
break; break;
@@ -2228,6 +2303,8 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
knownUpstreamByModelKey: snap.knownUpstreamByModelKey, knownUpstreamByModelKey: snap.knownUpstreamByModelKey,
modelInputs: snap.aggContext.modelInputs, modelInputs: snap.aggContext.modelInputs,
accountScope: snap.aggContext.currentAccountName, accountScope: snap.aggContext.currentAccountName,
endpointId,
cacheStore,
}); });
const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep( const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep(
@@ -2255,11 +2332,13 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
activeFamilyCascadeIds, activeFamilyCascadeIds,
resolveStepModel: snap.aggContext.resolveStepModel, resolveStepModel: snap.aggContext.resolveStepModel,
quotaPoolsMap: snap.quotaContext.quotaPoolsMap, quotaPoolsMap: snap.quotaContext.quotaPoolsMap,
endpoint,
}); });
return { return {
scope: 'conversation', scope: 'conversation',
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
endpoint: snap.basePayload.endpoint,
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
account: snap.basePayload.account, account: snap.basePayload.account,
activeCascadeId, activeCascadeId,
@@ -2277,15 +2356,18 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
} }
function tryBuildFastConsumptionPayload(filterOpts = {}) { function tryBuildFastConsumptionPayload(filterOpts = {}) {
const snap = resolveValidFastSnapshot(); const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
const snap = resolveValidFastSnapshot(endpoint);
if (!snap) return null; if (!snap) return null;
const agg = aggregateSelectedWindowUsage({ const agg = aggregateSelectedWindowUsage({
filterOpts, filterOpts,
...snap.aggContext, ...snap.aggContext,
endpoint,
}); });
return { return {
scope: 'consumption', scope: 'consumption',
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
endpoint: snap.basePayload.endpoint,
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
usageRevision: agg.usageRevision, usageRevision: agg.usageRevision,
consumption: { consumption: {
@@ -2305,13 +2387,18 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
}; };
} }
function tryBuildConsumptionPresetsPayload() { function tryBuildConsumptionPresetsPayload(filterOpts = {}) {
const snap = resolveValidFastSnapshot(); const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
const snap = resolveValidFastSnapshot(endpoint);
if (!snap) return null; if (!snap) return null;
const bundle = aggregateConsumptionPresetBundle(snap.aggContext); const bundle = aggregateConsumptionPresetBundle({
...snap.aggContext,
endpoint,
});
return { return {
scope: 'consumption-presets', scope: 'consumption-presets',
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
endpoint: snap.basePayload.endpoint,
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
usageRevision: bundle.usageRevision, usageRevision: bundle.usageRevision,
ranges: bundle.ranges, ranges: bundle.ranges,
@@ -2370,6 +2457,9 @@ export function buildTelemetryPayload(
forceQuotaRefresh = false, forceQuotaRefresh = false,
filterOpts = {} filterOpts = {}
) { ) {
const endpointKey = filterOpts?.endpoint?.isRemote
? String(filterOpts.endpoint.id || 'remote')
: LOCAL_ENDPOINT_ID;
if (!forceQuotaRefresh) { if (!forceQuotaRefresh) {
if (filterOpts?.scope === 'conversation') { if (filterOpts?.scope === 'conversation') {
const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts); const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts);
@@ -2378,16 +2468,19 @@ export function buildTelemetryPayload(
} }
} }
if (filterOpts?.scope === 'consumption-presets') { if (filterOpts?.scope === 'consumption-presets') {
const presetsPayload = tryBuildConsumptionPresetsPayload(); const presetsPayload = tryBuildConsumptionPresetsPayload(filterOpts);
if (presetsPayload) { if (presetsPayload) {
return Promise.resolve(presetsPayload); return Promise.resolve(presetsPayload);
} }
const key = `${requestedConvId || '__auto__'}::presets-cold`; const key = `${endpointKey}::${requestedConvId || '__auto__'}::presets-cold`;
if (inFlightRequests.has(key)) { if (inFlightRequests.has(key)) {
return inFlightRequests.get(key); return inFlightRequests.get(key);
} }
const p = buildTelemetryPayloadInternal(requestedConvId, false, { range: 'today' }) const coldFilterOpts = filterOpts?.endpoint
.then(() => tryBuildConsumptionPresetsPayload()) ? { range: 'today', endpoint: filterOpts.endpoint }
: { range: 'today' };
const p = buildTelemetryPayloadInternal(requestedConvId, false, coldFilterOpts)
.then(() => tryBuildConsumptionPresetsPayload(filterOpts))
.finally(() => { .finally(() => {
inFlightRequests.delete(key); inFlightRequests.delete(key);
}); });
@@ -2402,7 +2495,7 @@ export function buildTelemetryPayload(
} }
} }
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
if (inFlightRequests.has(key)) { if (inFlightRequests.has(key)) {
return inFlightRequests.get(key); return inFlightRequests.get(key);
} }
@@ -3,7 +3,8 @@ import {
} from 'node:fs'; } from 'node:fs';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
let lastWrite = null; const MAX_TRACKED_CACHE_FILES = 16;
const lastWritesByPath = new Map();
function isSameFile(a, b) { function isSameFile(a, b) {
return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino && return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino &&
@@ -29,7 +30,7 @@ function readReusableBytes(filePath, expected) {
// 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。 // 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。
export function writeTrajectoryCacheFile(filePath, data) { export function writeTrajectoryCacheFile(filePath, data) {
const previous = lastWrite?.filePath === filePath ? lastWrite : null; const previous = lastWritesByPath.get(filePath) || null;
const bytes = previous ? readReusableBytes(filePath, previous.file) : null; const bytes = previous ? readReusableBytes(filePath, previous.file) : null;
const ranges = new WeakMap(); const ranges = new WeakMap();
const parts = []; const parts = [];
@@ -72,7 +73,14 @@ export function writeTrajectoryCacheFile(filePath, data) {
const written = statSync(temporaryPath, { bigint: true }); const written = statSync(temporaryPath, { bigint: true });
renameSync(temporaryPath, filePath); renameSync(temporaryPath, filePath);
const file = statSync(filePath, { bigint: true }); const file = statSync(filePath, { bigint: true });
lastWrite = isSameFile(written, file) ? { filePath, file, ranges } : null; lastWritesByPath.delete(filePath);
if (isSameFile(written, file)) {
if (lastWritesByPath.size >= MAX_TRACKED_CACHE_FILES) {
const oldestPath = lastWritesByPath.keys().next().value;
if (oldestPath !== undefined) lastWritesByPath.delete(oldestPath);
}
lastWritesByPath.set(filePath, { filePath, file, ranges });
}
} finally { } finally {
try { unlinkSync(temporaryPath); } catch {} try { unlinkSync(temporaryPath); } catch {}
} }
+158 -51
View File
@@ -14,7 +14,8 @@ import {
finishSpeed, finishSpeed,
parseIsoMs, parseIsoMs,
} from '../trajectory-metrics.mjs'; } from '../trajectory-metrics.mjs';
import { listCachedTrajectoryEntries, roundMetric } from './config.mjs'; import { roundMetric } from './config.mjs';
import { getEndpointCacheStore } from './endpoint-registry.mjs';
import { loadExternalDeepStatsCache } from './local-scanner.mjs'; import { loadExternalDeepStatsCache } from './local-scanner.mjs';
import { import {
computeStepCost, computeStepCost,
@@ -34,6 +35,29 @@ function normalizeOwnerAccount(val) {
return typeof val === 'string' ? val.trim().toLowerCase() : ''; return typeof val === 'string' ? val.trim().toLowerCase() : '';
} }
const COMPACTION_QUOTA_SETTLE_MAX_MS = 180_000;
const STEP_QUOTA_DURATION_CAP_SEC = 600;
/**
* 解析单步用于官方配额周期窗口(`5h` / `weekly` / `cycle`)边界比对的结算时间戳:
* 服务端配额桶的 `resetTime` 锚定在周期内首笔请求完成扣费时刻(而非 `createdAt` 发起时刻),
* 使用完成时刻(无流式计时的自动压缩 `CHECKPOINT` 步按合理结算上限及下一步发起时刻封顶)避免漏计开启新周期的首步。
*/
function resolveStepQuotaBillingMs(st, nextStep, nowMs) {
const tMs = Number(st?.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
if (!(tMs > 0) || tMs > nowMs) return tMs;
const durSec = Number(st?.totalDurationSec);
if (Number.isFinite(durSec) && durSec > 0) {
const endMs = tMs + Math.round(Math.min(durSec, STEP_QUOTA_DURATION_CAP_SEC) * 1000);
return Math.min(nowMs, endMs);
}
if (st?.isCompactionStep) {
const nextMs = Number(nextStep?.createdAtMs) > tMs ? Number(nextStep.createdAtMs) : Infinity;
return Math.min(nowMs, nextMs, tMs + COMPACTION_QUOTA_SETTLE_MAX_MS);
}
return tMs;
}
/** /**
* 获取本地当日 00:00:00.000 的毫秒时间戳。 * 获取本地当日 00:00:00.000 的毫秒时间戳。
* *
@@ -430,7 +454,8 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
return finalizeModelBreakdownMap(perModelStats); return finalizeModelBreakdownMap(perModelStats);
} }
let lastUsageSnapshot = null; const MAX_USAGE_SNAPSHOT_ENDPOINTS = 8;
const lastUsageSnapshotsByEndpoint = new Map();
let usageSnapshotRevisionSeq = 0; let usageSnapshotRevisionSeq = 0;
const stepsTimeBoundsCache = new WeakMap(); const stepsTimeBoundsCache = new WeakMap();
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000; const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
@@ -439,10 +464,15 @@ const USAGE_SOURCE_LABELS = {
standalone: 'Antigravity App', standalone: 'Antigravity App',
ide: 'Antigravity IDE', ide: 'Antigravity IDE',
cli: 'Antigravity CLI', cli: 'Antigravity CLI',
ssh: 'Antigravity SSH',
}; };
export function clearUsageAggregatorMemo() { export function clearUsageAggregatorMemo(endpointId = null) {
lastUsageSnapshot = null; if (endpointId) {
lastUsageSnapshotsByEndpoint.delete(String(endpointId));
} else {
lastUsageSnapshotsByEndpoint.clear();
}
usageSnapshotRevisionSeq += 1; usageSnapshotRevisionSeq += 1;
} }
@@ -466,12 +496,14 @@ function getStepsTimeBounds(steps) {
return bounds; return bounds;
} }
function collectUsageEntriesToAggregate(familySet) { function collectUsageEntriesToAggregate(familySet, endpoint = null) {
const externalConvos = loadExternalDeepStatsCache(); const isRemote = Boolean(endpoint && endpoint.isRemote);
const cacheStore = getEndpointCacheStore(endpoint);
const externalConvos = isRemote ? new Map() : loadExternalDeepStatsCache();
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费 // 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
const allLiveByLower = new Map(); const allLiveByLower = new Map();
for (const [rawId, entry] of listCachedTrajectoryEntries()) { for (const [rawId, entry] of cacheStore.listCachedTrajectoryEntries()) {
const cidLower = String(rawId || '').toLowerCase(); const cidLower = String(rawId || '').toLowerCase();
if (!cidLower || !entry || typeof entry !== 'object') continue; if (!cidLower || !entry || typeof entry !== 'object') continue;
const prev = allLiveByLower.get(cidLower); const prev = allLiveByLower.get(cidLower);
@@ -502,7 +534,7 @@ function collectUsageEntriesToAggregate(familySet) {
).toLowerCase(); ).toLowerCase();
allEntriesToAggregate.push({ allEntriesToAggregate.push({
cascadeId: groupCascadeId, cascadeId: groupCascadeId,
appSource: entry?.appSource || 'standalone', appSource: isRemote ? 'ssh' : entry?.appSource || 'standalone',
accountName: entry?.accountName || extMatch?.accountName || '', accountName: entry?.accountName || extMatch?.accountName || '',
steps: entry?.steps || [], steps: entry?.steps || [],
isCurrentConv: familySet.has(cidLower), isCurrentConv: familySet.has(cidLower),
@@ -891,13 +923,16 @@ function computeFamilySessionBuckets({
const cidLower = String(entry?.cascadeId || '').toLowerCase(); const cidLower = String(entry?.cascadeId || '').toLowerCase();
if (!cidLower || !familySet.has(cidLower)) continue; if (!cidLower || !familySet.has(cidLower)) continue;
const entryOwner = normalizeOwnerAccount(entry.accountName); const entryOwner = normalizeOwnerAccount(entry.accountName);
for (const st of entry.steps || []) { const entrySteps = entry.steps || [];
for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) {
const st = entrySteps[sIdx];
if (!st || typeof st !== 'object') continue; if (!st || typeof st !== 'object') continue;
const nextSt = entrySteps[sIdx + 1] || null;
const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner;
const includeInQuotaPools = const includeInQuotaPools =
normalizedQuotaAccount === null normalizedQuotaAccount === null
? false ? false
: normalizedQuotaAccount === '' : normalizedQuotaAccount === '' || stepOwner === ''
? true ? true
: stepOwner === normalizedQuotaAccount; : stepOwner === normalizedQuotaAccount;
const mInfo = resolveStepModel(st); const mInfo = resolveStepModel(st);
@@ -914,6 +949,7 @@ function computeFamilySessionBuckets({
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
const unpriced = stepCost === null ? 1 : 0; const unpriced = stepCost === null ? 1 : 0;
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs);
const savedCost = mInfo.pricing const savedCost = mInfo.pricing
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
: 0; : 0;
@@ -942,39 +978,42 @@ function computeFamilySessionBuckets({
: null; : null;
let inCurrentCycle = false; let inCurrentCycle = false;
if (tMs > 0 && tMs <= nowMs) { if (qMs > 0 && qMs <= nowMs) {
if (isCustomWeeklyMode) { if (isCustomWeeklyMode) {
inCurrentCycle = tMs >= effectiveWeekStartMs; inCurrentCycle = tMs >= effectiveWeekStartMs;
} else if (poolCycleBuckets.size > 0) { } else if (poolCycleBuckets.size > 0) {
const effCycleStartMs = poolBucketEntry const effCycleStartMs = poolBucketEntry
? poolBucketEntry.startWkMs ? poolBucketEntry.startWkMs
: cycleStartFallbackMs; : cycleStartFallbackMs;
inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs;
} else { } else {
inCurrentCycle = includeInQuotaPools && tMs >= cycleStartFallbackMs; inCurrentCycle = includeInQuotaPools && qMs >= cycleStartFallbackMs;
} }
} }
for (const k of presetKeys) { for (const k of presetKeys) {
const w = presetWindows[k]; const w = presetWindows[k];
const cmpMs = k === '5h' || k === 'week' ? qMs : tMs;
const matchesPreset = const matchesPreset =
k === 'all' k === 'all'
? true ? true
: k === 'cycle' : k === 'cycle'
? inCurrentCycle ? inCurrentCycle
: tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs;
if (matchesPreset) { if (matchesPreset) {
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId); accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId);
} }
} }
if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) {
const selCmpMs =
selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs;
const inSelectedWindow = const inSelectedWindow =
selectedWindow.key === 'all' selectedWindow.key === 'all'
? true ? true
: selectedWindow.key === 'cycle' : selectedWindow.key === 'cycle'
? inCurrentCycle ? inCurrentCycle
: tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) { if (inSelectedWindow) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId);
} }
@@ -1015,16 +1054,33 @@ function usageTimestampBoundary(dates, value, inclusive) {
return start; return start;
} }
function sameUsageWindows(previous, current, dates) { function sortedQuotaBillingTimestamps(entries, nowMs) {
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
let count = 0;
for (const { steps } of entries) {
for (let i = 0; i < steps.length; i++) {
const qMs = resolveStepQuotaBillingMs(steps[i], steps[i + 1] || null, nowMs);
if (qMs > 0) dates[count++] = qMs;
}
}
return dates.subarray(0, count).sort();
}
function isQuotaAnchoredWindowKey(key) {
return key === '5h' || key === 'week' || key === 'cycle' || String(key || '').includes(':');
}
function sameUsageWindows(previous, current, dates, quotaDates = dates) {
return previous.length === current.length && current.every((window, index) => { return previous.length === current.length && current.every((window, index) => {
const before = previous[index]; const before = previous[index];
const refDates = isQuotaAnchoredWindowKey(window.key) ? quotaDates : dates;
return before.key === window.key && before.label === window.label && return before.key === window.key && before.label === window.label &&
(before.startMs === window.startMs || (before.startMs === window.startMs ||
usageTimestampBoundary(dates, before.startMs, false) === usageTimestampBoundary(refDates, before.startMs, false) ===
usageTimestampBoundary(dates, window.startMs, false)) && usageTimestampBoundary(refDates, window.startMs, false)) &&
(before.endMs === window.endMs || (before.endMs === window.endMs ||
usageTimestampBoundary(dates, before.endMs, true) === usageTimestampBoundary(refDates, before.endMs, true) ===
usageTimestampBoundary(dates, window.endMs, true)); usageTimestampBoundary(refDates, window.endMs, true));
}); });
} }
@@ -1051,7 +1107,10 @@ export function aggregateMultiWindowUsage({
resolveStepModel, resolveStepModel,
quotaPoolsMap = null, quotaPoolsMap = null,
modelInputs = null, modelInputs = null,
endpoint = null,
}) { }) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local';
const rawFamilyIds = const rawFamilyIds =
activeFamilyCascadeIds instanceof Set activeFamilyCascadeIds instanceof Set
? Array.from(activeFamilyCascadeIds) ? Array.from(activeFamilyCascadeIds)
@@ -1117,7 +1176,7 @@ export function aggregateMultiWindowUsage({
})); }));
const perSourceStats = new Map(); const perSourceStats = new Map();
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet); const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint);
const familySig = buildFamilySig(familySet); const familySig = buildFamilySig(familySet);
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
@@ -1126,7 +1185,7 @@ export function aggregateMultiWindowUsage({
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs }, { key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
]).flat(); ]).flat();
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows]; const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
const snapshot = lastUsageSnapshot; const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
currentYear === snapshot.currentYear && currentYear === snapshot.currentYear &&
Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) &&
@@ -1145,8 +1204,12 @@ export function aggregateMultiWindowUsage({
if ( if (
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
trend.last === previous.trend.last && trend.last === previous.trend.last &&
sameUsageWindows(previous.windows, windows, sameUsageWindows(
snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) previous.windows,
windows,
(snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)),
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
)
) { ) {
snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.delete(selectedWindow.key);
snapshot.ranges.set(selectedWindow.key, previous); snapshot.ranges.set(selectedWindow.key, previous);
@@ -1198,13 +1261,16 @@ export function aggregateMultiWindowUsage({
const srcKey = entry.appSource || 'standalone'; const srcKey = entry.appSource || 'standalone';
const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
for (const st of entry.steps || []) { const entrySteps = entry.steps || [];
for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) {
const st = entrySteps[sIdx];
if (!st || typeof st !== 'object') continue; if (!st || typeof st !== 'object') continue;
const nextSt = entrySteps[sIdx + 1] || null;
const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner;
const includeInQuotaPools = const includeInQuotaPools =
normalizedQuotaAccount === null normalizedQuotaAccount === null
? false ? false
: normalizedQuotaAccount === '' : normalizedQuotaAccount === '' || stepOwner === ''
? true ? true
: stepOwner === normalizedQuotaAccount; : stepOwner === normalizedQuotaAccount;
const mInfo = resolveStepModel(st); const mInfo = resolveStepModel(st);
@@ -1221,6 +1287,7 @@ export function aggregateMultiWindowUsage({
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
const unpriced = stepCost === null ? 1 : 0; const unpriced = stepCost === null ? 1 : 0;
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs);
const savedCost = mInfo.pricing const savedCost = mInfo.pricing
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
: 0; : 0;
@@ -1258,37 +1325,38 @@ export function aggregateMultiWindowUsage({
hasDedicatedArgonPool hasDedicatedArgonPool
); );
if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) {
if (tMs >= poolBucketEntry.start5hMs) { if (qMs >= poolBucketEntry.start5hMs) {
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
} }
if (tMs >= poolBucketEntry.startWkMs) { if (qMs >= poolBucketEntry.startWkMs) {
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
} }
} }
let inCurrentCycle = false; let inCurrentCycle = false;
if (tMs > 0 && tMs <= nowMs) { if (qMs > 0 && qMs <= nowMs) {
if (isCustomWeeklyMode) { if (isCustomWeeklyMode) {
inCurrentCycle = tMs >= presetWindows.week.startMs; inCurrentCycle = tMs >= presetWindows.week.startMs;
} else if (poolCycleBuckets.size > 0) { } else if (poolCycleBuckets.size > 0) {
const effCycleStartMs = poolBucketEntry const effCycleStartMs = poolBucketEntry
? poolBucketEntry.startWkMs ? poolBucketEntry.startWkMs
: presetWindows.cycle.startMs; : presetWindows.cycle.startMs;
inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs;
} else { } else {
inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; inCurrentCycle = includeInQuotaPools && qMs >= presetWindows.cycle.startMs;
} }
} }
for (const k of presetKeys) { for (const k of presetKeys) {
const w = presetWindows[k]; const w = presetWindows[k];
const cmpMs = k === '5h' || k === 'week' ? qMs : tMs;
const matchesPreset = const matchesPreset =
k === 'all' k === 'all'
? true ? true
: k === 'cycle' : k === 'cycle'
? inCurrentCycle ? inCurrentCycle
: tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs;
if (matchesPreset) { if (matchesPreset) {
accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId);
if (isCurrentConv) { if (isCurrentConv) {
@@ -1300,12 +1368,14 @@ export function aggregateMultiWindowUsage({
} }
} }
const selCmpMs =
selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs;
const inSelectedWindow = const inSelectedWindow =
selectedWindow.key === 'all' selectedWindow.key === 'all'
? true ? true
: selectedWindow.key === 'cycle' : selectedWindow.key === 'cycle'
? inCurrentCycle ? inCurrentCycle
: tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) { if (inSelectedWindow) {
if ( if (
@@ -1459,10 +1529,11 @@ export function aggregateMultiWindowUsage({
: null; : null;
let resolvedUsageRevision = usageSnapshotRevisionSeq; let resolvedUsageRevision = usageSnapshotRevisionSeq;
let activeSnap = snapshot;
if (modelInputs) { if (modelInputs) {
if (!sameSnapshot) { if (!sameSnapshot) {
resolvedUsageRevision = ++usageSnapshotRevisionSeq; resolvedUsageRevision = ++usageSnapshotRevisionSeq;
lastUsageSnapshot = { activeSnap = {
revision: resolvedUsageRevision, revision: resolvedUsageRevision,
timeZone, timeZone,
modelInputs, modelInputs,
@@ -1474,8 +1545,14 @@ export function aggregateMultiWindowUsage({
ranges: new Map(), ranges: new Map(),
selectedRanges: new Map(), selectedRanges: new Map(),
}; };
lastUsageSnapshotsByEndpoint.delete(endpointKey);
if (lastUsageSnapshotsByEndpoint.size >= MAX_USAGE_SNAPSHOT_ENDPOINTS) {
const oldestKey = lastUsageSnapshotsByEndpoint.keys().next().value;
if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey);
}
lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap);
} else { } else {
resolvedUsageRevision = lastUsageSnapshot.revision; resolvedUsageRevision = activeSnap.revision;
} }
} else { } else {
resolvedUsageRevision = ++usageSnapshotRevisionSeq; resolvedUsageRevision = ++usageSnapshotRevisionSeq;
@@ -1500,8 +1577,8 @@ export function aggregateMultiWindowUsage({
poolCycleStats, poolCycleStats,
poolsWeeklySummary, poolsWeeklySummary,
}; };
if (modelInputs && lastUsageSnapshot) { if (modelInputs && activeSnap) {
const { ranges } = lastUsageSnapshot; const { ranges } = activeSnap;
ranges.delete(selectedWindow.key); ranges.delete(selectedWindow.key);
ranges.set(selectedWindow.key, { ranges.set(selectedWindow.key, {
familySig, familySig,
@@ -1536,7 +1613,10 @@ export function aggregateSelectedWindowUsage({
quotaPoolsMap = null, quotaPoolsMap = null,
modelInputs = null, modelInputs = null,
precollectedEntries = null, precollectedEntries = null,
endpoint = null,
}) { }) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local';
const rawFamilyIds = const rawFamilyIds =
activeFamilyCascadeIds instanceof Set activeFamilyCascadeIds instanceof Set
? Array.from(activeFamilyCascadeIds) ? Array.from(activeFamilyCascadeIds)
@@ -1567,12 +1647,12 @@ export function aggregateSelectedWindowUsage({
const allEntriesToAggregate = Array.isArray(precollectedEntries) const allEntriesToAggregate = Array.isArray(precollectedEntries)
? precollectedEntries ? precollectedEntries
: collectUsageEntriesToAggregate(familySet); : 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 ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
const snapshot = lastUsageSnapshot; const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
const sameSnapshot = Boolean( const sameSnapshot = Boolean(
modelInputs && modelInputs &&
snapshot && snapshot &&
@@ -1604,7 +1684,8 @@ export function aggregateSelectedWindowUsage({
sameUsageWindows( sameUsageWindows(
[prevWin], [prevWin],
[selectedWindow], [selectedWindow],
(snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)),
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
) )
) { ) {
const res = candidate.result; const res = candidate.result;
@@ -1639,6 +1720,10 @@ export function aggregateSelectedWindowUsage({
} }
} }
const maxSettlementSlackMs = Math.max(
COMPACTION_QUOTA_SETTLE_MAX_MS,
STEP_QUOTA_DURATION_CAP_SEC * 1000
);
let minCutoffMs = 0; let minCutoffMs = 0;
let maxCutoffMs = Infinity; let maxCutoffMs = Infinity;
let canPruneByTime = false; let canPruneByTime = false;
@@ -1652,9 +1737,14 @@ export function aggregateSelectedWindowUsage({
for (const entry of poolCycleBuckets.values()) { for (const entry of poolCycleBuckets.values()) {
if (entry.startWkMs < minCutoffMs) minCutoffMs = entry.startWkMs; if (entry.startWkMs < minCutoffMs) minCutoffMs = entry.startWkMs;
} }
minCutoffMs = Math.max(0, minCutoffMs - maxSettlementSlackMs);
} else { } else {
minCutoffMs = selectedWindow.startMs; minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs);
} }
} else if (selectedWindow.key === '5h' || selectedWindow.key === 'week') {
canPruneByTime = true;
minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs);
maxCutoffMs = selectedWindow.endMs;
} else if (selectedWindow.key !== 'all') { } else if (selectedWindow.key !== 'all') {
canPruneByTime = true; canPruneByTime = true;
minCutoffMs = selectedWindow.startMs; minCutoffMs = selectedWindow.startMs;
@@ -1684,10 +1774,24 @@ export function aggregateSelectedWindowUsage({
const srcKey = entry.appSource || 'standalone'; const srcKey = entry.appSource || 'standalone';
const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
for (const st of steps) { for (let sIdx = 0; sIdx < steps.length; sIdx++) {
const st = steps[sIdx];
if (!st || typeof st !== 'object') continue; if (!st || typeof st !== 'object') continue;
const nextSt = steps[sIdx + 1] || null;
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
if (canPruneByTime && (tMs <= 0 || tMs < minCutoffMs || tMs > maxCutoffMs)) { const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs);
const isQuotaWin =
selectedWindow.key === 'cycle' ||
selectedWindow.key === '5h' ||
selectedWindow.key === 'week';
const effStepMs = isQuotaWin && !(selectedWindow.key === 'cycle' && isCustomWeeklyMode) ? qMs : tMs;
if (canPruneByTime && (effStepMs <= 0 || effStepMs < minCutoffMs || effStepMs > maxCutoffMs)) {
continue;
}
if (
(selectedWindow.key === '5h' || selectedWindow.key === 'week') &&
effStepMs < selectedWindow.startMs
) {
continue; continue;
} }
@@ -1698,7 +1802,7 @@ export function aggregateSelectedWindowUsage({
const includeInQuotaPools = const includeInQuotaPools =
normalizedQuotaAccount === null normalizedQuotaAccount === null
? false ? false
: normalizedQuotaAccount === '' : normalizedQuotaAccount === '' || stepOwner === ''
? true ? true
: stepOwner === normalizedQuotaAccount; : stepOwner === normalizedQuotaAccount;
let inCurrentCycle = false; let inCurrentCycle = false;
@@ -1718,9 +1822,9 @@ export function aggregateSelectedWindowUsage({
const effCycleStartMs = poolBucketEntry const effCycleStartMs = poolBucketEntry
? poolBucketEntry.startWkMs ? poolBucketEntry.startWkMs
: selectedWindow.startMs; : selectedWindow.startMs;
inCurrentCycle = tMs >= effCycleStartMs; inCurrentCycle = qMs >= effCycleStartMs;
} else { } else {
inCurrentCycle = includeInQuotaPools && tMs >= selectedWindow.startMs; inCurrentCycle = includeInQuotaPools && qMs >= selectedWindow.startMs;
} }
if (!inCurrentCycle) continue; if (!inCurrentCycle) continue;
if ( if (
@@ -1885,7 +1989,10 @@ export function aggregateSessionUsageForFamily({
activeFamilyCascadeIds = null, activeFamilyCascadeIds = null,
resolveStepModel, resolveStepModel,
quotaPoolsMap = null, quotaPoolsMap = null,
endpoint = null,
}) { }) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
const cacheStore = getEndpointCacheStore(endpoint);
const rawFamilyIds = const rawFamilyIds =
activeFamilyCascadeIds instanceof Set activeFamilyCascadeIds instanceof Set
? Array.from(activeFamilyCascadeIds) ? Array.from(activeFamilyCascadeIds)
@@ -1912,13 +2019,13 @@ export function aggregateSessionUsageForFamily({
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
const familyEntries = []; const familyEntries = [];
for (const [cid, entry] of 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();
if (!familySet.has(cidLower)) continue; if (!familySet.has(cidLower)) continue;
familyEntries.push({ familyEntries.push({
cascadeId: cid, cascadeId: cid,
appSource: entry.appSource || 'standalone', appSource: isRemote ? 'ssh' : entry.appSource || 'standalone',
accountName: entry.accountName || '', accountName: entry.accountName || '',
steps: entry.steps, steps: entry.steps,
isCurrentConv: true, isCurrentConv: true,
@@ -1943,7 +2050,7 @@ export function aggregateSessionUsageForFamily({
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
*/ */
export function aggregateConsumptionPresetBundle(params) { export function aggregateConsumptionPresetBundle(params) {
const { activeCascadeId = null, activeFamilyCascadeIds = null } = params || {}; const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {};
const rawFamilyIds = const rawFamilyIds =
activeFamilyCascadeIds instanceof Set activeFamilyCascadeIds instanceof Set
? Array.from(activeFamilyCascadeIds) ? Array.from(activeFamilyCascadeIds)
@@ -1951,7 +2058,7 @@ export function aggregateConsumptionPresetBundle(params) {
? [activeCascadeId] ? [activeCascadeId]
: []; : [];
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()));
const precollectedEntries = collectUsageEntriesToAggregate(familySet); const precollectedEntries = collectUsageEntriesToAggregate(familySet, endpoint);
const ranges = {}; const ranges = {};
let usageRevision = usageSnapshotRevisionSeq; let usageRevision = usageSnapshotRevisionSeq;
+642 -33
View File
@@ -24,6 +24,9 @@ import { dirname, join } from 'node:path';
import { import {
BRIDGE_API_PATHS, BRIDGE_API_PATHS,
CONTEXT_WINDOWS_GLOBAL_KEY, CONTEXT_WINDOWS_GLOBAL_KEY,
LOCAL_ENDPOINT_ID,
WINDOW_BRIDGE_ENDPOINT_HEADER,
WINDOW_BRIDGE_ENDPOINT_KEY,
WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_KEY,
WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ROUTE_KEY,
WINDOW_OVERLAY_KEY, WINDOW_OVERLAY_KEY,
@@ -47,12 +50,22 @@ import {
ensureDesktopLaunchEntriesConfigured, ensureDesktopLaunchEntriesConfigured,
resolveDesktopHostExecutable, resolveDesktopHostExecutable,
} from './desktop-launcher-config.mjs'; } from './desktop-launcher-config.mjs';
import {
getRegisteredRemoteEndpoint,
getRemoteEndpointTargetWsUrls,
normalizeEndpointId,
pruneStaleRemoteEndpoints,
registerRemoteEndpoint,
setRemoteWindowRpcInvoker,
} from './endpoint-registry.mjs';
import { getLocalHubPorts } from './ls-discovery.mjs';
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs'; import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`; const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`; const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`; const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY); const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY);
const overlayMethods = Object.fromEntries( const overlayMethods = Object.fromEntries(
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)]) Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
); );
@@ -719,6 +732,290 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde
}); });
} }
/**
* 从窗口内的 `window.__APP_CONFIG__` 与标题提取远端 / SSH 主机标识元数据。
*
* @param {object|null|undefined} appConfig
* @param {string} [title='']
* @returns {{ hasExplicitRemoteFlag: boolean, stableHostKey: string, hostLabel: string }}
*/
export function extractRemoteHostMetadata(appConfig, title = '') {
const cfg = appConfig && typeof appConfig === 'object' ? appConfig : {};
const rawHost = String(
cfg.sshHost ||
cfg.sshHostName ||
cfg.sshAlias ||
cfg.sshTarget ||
cfg.remoteHost ||
cfg.remoteAuthority ||
cfg.remoteName ||
''
).trim();
const cleanHost = rawHost.replace(/^ssh(?:-remote)?\+/i, '').trim();
const hasExplicitRemoteFlag = Boolean(
cfg.isRemoteControl === true ||
cfg.isRemote === true ||
cfg.isSsh === true ||
/^ssh/i.test(String(cfg.connectionType || cfg.windowMode || '').trim()) ||
cleanHost
);
let bracketedTitleHost = '';
const titleText = String(title || '').trim();
if (titleText) {
const m = titleText.match(/\[SSH:\s*([^\]\r\n]+)\]/i);
if (m && m[1]) {
bracketedTitleHost = String(m[1]).trim();
}
}
const stableHostKey = cleanHost || bracketedTitleHost || '';
const hostLabel = cleanHost || bracketedTitleHost || '';
return { hasExplicitRemoteFlag, stableHostKey, hostLabel, bracketedTitleHost };
}
/**
* 依据三级优先级严格区分本地窗口与 SSH / 远端窗口,避免 2.33.0+ 无 `csrfToken` 或无 `hub_*.json` 时误判本地桌面窗口。
*
* @param {{
* target: object,
* probedInfo?: { origin?: string, csrfToken?: string, observedCsrfToken?: string, appConfig?: object, title?: string }|null,
* localHubInfo?: { allPorts?: Set<number>, httpsPorts?: Set<number>, csrfTokens?: Set<string> }|null,
* confirmedLocalPorts?: Set<number>|null,
* }} params
*/
export function classifyWindowTargetEndpoint({
target,
probedInfo = null,
localHubInfo = null,
confirmedLocalPorts = null,
}) {
if (!target || target.isIdeWorkbench) {
return { isRemote: false, endpointId: LOCAL_ENDPOINT_ID, label: '', origin: '', csrfToken: '' };
}
let origin = String(probedInfo?.origin || '').trim();
if (!origin) {
try {
const parsed = new URL(String(target.url || ''));
if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
origin = parsed.origin;
}
} catch {
origin = '';
}
}
let originPort = 0;
if (origin) {
try {
originPort = Number(new URL(origin).port || 0);
} catch {
originPort = 0;
}
}
const allLocalPorts = localHubInfo?.allPorts instanceof Set ? localHubInfo.allPorts : new Set();
const localHttpsPorts = localHubInfo?.httpsPorts instanceof Set ? localHubInfo.httpsPorts : new Set();
const localCsrfTokens = localHubInfo?.csrfTokens instanceof Set ? localHubInfo.csrfTokens : new Set();
const knownLocalPorts = confirmedLocalPorts instanceof Set ? confirmedLocalPorts : new Set();
const csrfToken = String(probedInfo?.csrfToken || probedInfo?.observedCsrfToken || '').trim();
const remoteMeta = extractRemoteHostMetadata(probedInfo?.appConfig, probedInfo?.title || target.title || '');
// 1. 明确命中本机特征(端口或 CSRF 令牌匹配本机 Hub)且无显式远程标记 -> 本地窗口
const matchesLocalPort = originPort > 0 && (allLocalPorts.has(originPort) || knownLocalPorts.has(originPort));
const matchesLocalCsrf = Boolean(csrfToken && localCsrfTokens.has(csrfToken));
if ((matchesLocalPort || matchesLocalCsrf) && !remoteMeta.hasExplicitRemoteFlag) {
return {
isRemote: false,
endpointId: LOCAL_ENDPOINT_ID,
label: '',
origin,
originPort,
csrfToken,
};
}
// 2. 明确命中远端 / SSH 特征(显式 SSH/Remote 标记,或携带与本机不同的非空 CSRF 令牌)
const hasDifferentCsrf = Boolean(csrfToken && localCsrfTokens.size > 0 && !localCsrfTokens.has(csrfToken));
if (remoteMeta.hasExplicitRemoteFlag || hasDifferentCsrf) {
return {
isRemote: true,
origin,
originPort,
csrfToken,
stableHostKey: remoteMeta.stableHostKey,
hostLabel: remoteMeta.hostLabel || (originPort > 0 ? `SSH:${originPort}` : 'SSH'),
};
}
// 3. 2.33.0+ 省略 csrfToken 时的端口不匹配兜底:仅当存在已确认的本机 HTTPS 端口或已确认本地窗口端口时启用
const hasConfirmedLocalDesktopPort = localHttpsPorts.size > 0 || knownLocalPorts.size > 0;
if (originPort > 0 && hasConfirmedLocalDesktopPort && !matchesLocalPort) {
return {
isRemote: true,
origin,
originPort,
csrfToken,
stableHostKey: remoteMeta.stableHostKey,
hostLabel: remoteMeta.hostLabel || `SSH:${originPort}`,
};
}
return {
isRemote: false,
endpointId: LOCAL_ENDPOINT_ID,
label: '',
origin,
originPort,
csrfToken,
};
}
/**
* 构建无状态、按需执行的窗口内同源 LS RPC 表达式(Tier-2 传输,不常驻修改 `window.fetch`)。
* 优先使用同源 `window.fetch` (`credentials: 'same-origin'`);若被鉴权或协议阻断,防御性回退至同源 `/connect-websocket`。
*
* @param {string} method
* @param {object} [body={}]
* @param {number} [timeoutMs=5000]
* @returns {string}
*/
export function buildWindowRemoteRpcExpression(method, body = {}, timeoutMs = 5000) {
const safeTimeout = Math.max(1000, Math.min(30000, Number(timeoutMs) || 5000));
return `(async () => {
const methodName = ${JSON.stringify(String(method || ''))};
const payloadObj = ${JSON.stringify(body && typeof body === 'object' ? body : {})};
const timeoutMs = ${JSON.stringify(safeTimeout)};
const servicePath = '/exa.language_server_pb.LanguageServerService/';
const procedure = servicePath + methodName;
const origin = String(window.location?.origin || '').replace(/\\/+$/, '');
if (!origin || !/^https?:\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\]):\\d+$/i.test(origin)) {
return { ok: false, status: 0, error: 'Non-loopback window origin' };
}
const csrfToken = String(
window.__APP_CONFIG__?.csrfToken ||
window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]?.observedCsrfToken ||
''
).trim();
const deadlineMs = Date.now() + timeoutMs;
let fetchErrMsg = '';
let fetchStatus = 0;
if (typeof window.fetch === 'function') {
try {
const headers = { 'Content-Type': 'application/json' };
if (csrfToken) headers['x-codeium-csrf-token'] = csrfToken;
const fetchBudgetMs = Math.max(200, deadlineMs - Date.now());
const init = {
method: 'POST',
credentials: 'same-origin',
headers,
body: JSON.stringify(payloadObj),
};
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
init.signal = AbortSignal.timeout(fetchBudgetMs);
}
const res = await window.fetch(origin + procedure, init);
fetchStatus = Number(res?.status || 0);
if (res?.ok) {
const data = await res.json();
return { ok: true, status: fetchStatus, transport: 'fetch', data };
}
fetchErrMsg = (await res?.text?.().catch(() => '')) || ('HTTP ' + fetchStatus);
} catch (err) {
fetchErrMsg = err?.message || 'fetch failed';
}
}
const wsRemainingMs = deadlineMs - Date.now();
if (wsRemainingMs >= 300 && typeof window.WebSocket === 'function' && window.location?.host) {
try {
const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = wsProto + '//' + window.location.host + '/connect-websocket';
const streamId = 'um_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
const wsResult = await new Promise((resolve, reject) => {
let ws = null;
let timer = null;
let done = false;
const finish = (ok, val) => {
if (done) return;
done = true;
if (timer) clearTimeout(timer);
try { ws?.close?.(); } catch {}
if (ok) resolve(val);
else reject(val instanceof Error ? val : new Error(String(val || 'ws failed')));
};
timer = setTimeout(() => finish(false, new Error('connect-websocket timeout')), wsRemainingMs);
try {
ws = new window.WebSocket(wsUrl);
} catch (err) {
finish(false, err);
return;
}
ws.addEventListener('open', () => {
try {
ws.send(JSON.stringify({
type: 'start',
stream: false,
procedure,
streamId,
payload: payloadObj,
}));
} catch (err) {
finish(false, err);
}
}, { once: true });
ws.addEventListener('message', (ev) => {
try {
const raw = typeof ev?.data === 'string' ? ev.data : String(ev?.data || '');
const frame = JSON.parse(raw);
if (!frame || typeof frame !== 'object') return;
if (frame.streamId && frame.streamId !== streamId) return;
if (frame.type === 'error' || frame.error) {
const msg = typeof frame.error === 'string'
? frame.error
: frame.error?.message || frame.message || 'connect-websocket error';
finish(false, new Error(msg));
return;
}
if (frame.payload !== undefined) {
finish(true, frame.payload);
return;
}
if (frame.response !== undefined) {
finish(true, frame.response);
return;
}
if (frame.data !== undefined && frame.type !== 'ping' && frame.type !== 'pong') {
finish(true, frame.data);
return;
}
if (frame.type === 'end') {
finish(true, {});
}
} catch {
// 忽略非 JSON 或无关帧
}
});
ws.addEventListener('error', () => finish(false, new Error('connect-websocket error')), { once: true });
ws.addEventListener('close', () => finish(false, new Error('connect-websocket closed')), { once: true });
});
return { ok: true, status: 200, transport: 'ws', data: wsResult };
} catch (wsErr) {
return {
ok: false,
status: fetchStatus,
error: fetchErrMsg || wsErr?.message || 'Remote window RPC failed',
};
}
}
return { ok: false, status: fetchStatus, error: fetchErrMsg || 'Remote window RPC failed' };
})()`;
}
/** /**
* 校验桥接请求的 `Origin` 是否来自本机 Antigravity 2.0 HTTPS 回环源或 Antigravity IDE `vscode-file` 源。 * 校验桥接请求的 `Origin` 是否来自本机 Antigravity 2.0 HTTPS 回环源或 Antigravity IDE `vscode-file` 源。
* *
@@ -792,6 +1089,8 @@ export function createWindowBridgeController(options) {
allowDesktopLauncherInTest = false, allowDesktopLauncherInTest = false,
existsHostFn = existsSync, existsHostFn = existsSync,
WebSocketImpl = globalThis.WebSocket, WebSocketImpl = globalThis.WebSocket,
bindRemoteRpcInvoker = false,
getLocalHubPortsFn = getLocalHubPorts,
} = options || {}; } = options || {};
function isPidAlive(pid) { function isPidAlive(pid) {
@@ -849,7 +1148,8 @@ export function createWindowBridgeController(options) {
}; };
let hadContextWindows = false; let hadContextWindows = false;
let contextWindowBootId = `${process.pid}:${Date.now()}`; let contextWindowBootId = `${process.pid}:${Date.now()}`;
let cachedBackendCtxModels = { expiresAt: 0, models: [] }; const cachedBackendCtxModelsByEndpoint = new Map();
const targetClassifyCache = new Map();
let nodeDepsPromise = null; let nodeDepsPromise = null;
const allowedDynamicOrigins = new Set(); const allowedDynamicOrigins = new Set();
@@ -868,14 +1168,22 @@ export function createWindowBridgeController(options) {
function applyCorsHeaders(res, origin) { function applyCorsHeaders(res, origin) {
res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Usage-Monitor-Token'); res.setHeader(
'Access-Control-Allow-Headers',
`Content-Type, X-Usage-Monitor-Token, ${WINDOW_BRIDGE_ENDPOINT_HEADER}`
);
res.setHeader('Access-Control-Allow-Private-Network', 'true'); res.setHeader('Access-Control-Allow-Private-Network', 'true');
res.setHeader('Access-Control-Max-Age', '600'); res.setHeader('Access-Control-Max-Age', '600');
res.setHeader('Vary', 'Origin'); res.setHeader('Vary', 'Origin');
res.setHeader('Cache-Control', 'no-store'); res.setHeader('Cache-Control', 'no-store');
} }
async function executeRpcBatch(rpcBatch) { function invokeApiHandler(pathname, method, data, endpointId) {
const authoritativeEndpointId = endpointId || LOCAL_ENDPOINT_ID;
return handleApiRequest(pathname, method, data, { endpointId: authoritativeEndpointId });
}
async function executeRpcBatch(rpcBatch, authoritativeEndpointId = LOCAL_ENDPOINT_ID) {
const responses = []; const responses = [];
for (const item of rpcBatch) { for (const item of rpcBatch) {
const reqId = String(item?.id || ''); const reqId = String(item?.id || '');
@@ -893,7 +1201,12 @@ export function createWindowBridgeController(options) {
: item.body && typeof item.body === 'object' : item.body && typeof item.body === 'object'
? item.body ? item.body
: {}; : {};
const out = await handleApiRequest(parsedUrl.pathname, method, reqData); const out = await invokeApiHandler(
parsedUrl.pathname,
method,
reqData,
authoritativeEndpointId
);
const status = Number(out?.status || 200); const status = Number(out?.status || 200);
const parsedBody = out?.body ? JSON.parse(out.body) : {}; const parsedBody = out?.body ? JSON.parse(out.body) : {};
if (status >= 200 && status < 300) { if (status >= 200 && status < 300) {
@@ -989,9 +1302,23 @@ export function createWindowBridgeController(options) {
return; return;
} }
const headerEndpointRaw = String(
req.headers[WINDOW_BRIDGE_ENDPOINT_HEADER.toLowerCase()] || ''
).trim();
const queryEndpointRaw = String(parsedUrl.searchParams.get('endpointId') || '').trim();
const requestedEndpointRaw = headerEndpointRaw || queryEndpointRaw;
const normalizedReqEndpoint = requestedEndpointRaw
? normalizeEndpointId(requestedEndpointRaw)
: LOCAL_ENDPOINT_ID;
if (normalizedReqEndpoint === null) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid endpointId' }));
return;
}
if (method === 'GET') { if (method === 'GET') {
const queryData = Object.fromEntries(parsedUrl.searchParams.entries()); const queryData = Object.fromEntries(parsedUrl.searchParams.entries());
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'GET', queryData)) Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'GET', queryData, normalizedReqEndpoint))
.then((out) => { .then((out) => {
const hdrs = { const hdrs = {
'Content-Type': out.contentType || 'application/json', 'Content-Type': out.contentType || 'application/json',
@@ -1040,7 +1367,7 @@ export function createWindowBridgeController(options) {
res.end(JSON.stringify({ error: 'Invalid JSON body' })); res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return; return;
} }
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'POST', bodyObj)) Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint))
.then((out) => { .then((out) => {
const hdrs = { const hdrs = {
'Content-Type': out.contentType || 'application/json', 'Content-Type': out.contentType || 'application/json',
@@ -1211,11 +1538,12 @@ export function createWindowBridgeController(options) {
return { reachableCount, targets: merged }; return { reachableCount, targets: merged };
} }
async function evaluateOnTarget(wsUrl, expression) { async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0) {
const WS = WebSocketImpl || globalThis.WebSocket; const WS = WebSocketImpl || globalThis.WebSocket;
if (typeof WS !== 'function') { if (typeof WS !== 'function') {
throw new Error('WebSocket runtime unavailable'); throw new Error('WebSocket runtime unavailable');
} }
const effectiveTimeoutMs = Math.max(500, Number(timeoutMsOverride) || cdpTimeoutMs);
let ws = null; let ws = null;
let timer = null; let timer = null;
try { try {
@@ -1223,7 +1551,7 @@ export function createWindowBridgeController(options) {
const evalResult = await new Promise((resolve, reject) => { const evalResult = await new Promise((resolve, reject) => {
timer = setTimeout(() => { timer = setTimeout(() => {
reject(new Error('CDP Runtime.evaluate timeout')); reject(new Error('CDP Runtime.evaluate timeout'));
}, cdpTimeoutMs); }, effectiveTimeoutMs);
const onOpen = () => { const onOpen = () => {
try { try {
@@ -1423,6 +1751,7 @@ export function createWindowBridgeController(options) {
const cdpPorts = findActiveDevToolsPorts(); const cdpPorts = findActiveDevToolsPorts();
if (!cdpPorts.length) { if (!cdpPorts.length) {
pruneStaleRemoteEndpoints(new Set());
const provPending = shouldCheckLaunchers const provPending = shouldCheckLaunchers
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
: hostLauncherPromise; : hostLauncherPromise;
@@ -1440,6 +1769,7 @@ export function createWindowBridgeController(options) {
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
if (reachableCount === 0) { if (reachableCount === 0) {
pruneStaleRemoteEndpoints(new Set());
const provPending = shouldCheckLaunchers const provPending = shouldCheckLaunchers
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
: hostLauncherPromise; : hostLauncherPromise;
@@ -1460,6 +1790,7 @@ export function createWindowBridgeController(options) {
void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {}); void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {});
} }
if (!targets.length) { if (!targets.length) {
pruneStaleRemoteEndpoints(new Set());
updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { updateBridgeStatus(enabled ? 'no_targets' : 'disabled', {
enabled, enabled,
leasedBySelf, leasedBySelf,
@@ -1469,44 +1800,250 @@ export function createWindowBridgeController(options) {
return { ok: true, enabled, reason: 'no_targets', injected: 0 }; return { ok: true, enabled, reason: 'no_targets', injected: 0 };
} }
if (hasContextWindows || hadContextWindows) {
let fallbackRules = {};
if ( if (
hasContextWindows && !enabled &&
lsRuntimeEndpoint.baseUrl && !hasContextWindows &&
lsRuntimeEndpoint.addr !== 'test.invalid' !hadContextWindows &&
!hadInjectedTargets &&
!hadInjectedChatFrames &&
!forceReinject
) { ) {
if (Date.now() >= cachedBackendCtxModels.expiresAt) { pruneStaleRemoteEndpoints(new Set());
updateBridgeStatus('disabled', {
enabled: false,
targets: targets.length,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
});
return { ok: true, enabled: false, removed: 0 };
}
const classifyExpr = `(() => {
try {
const cfg = typeof window !== 'undefined' && window.__APP_CONFIG__ && typeof window.__APP_CONFIG__ === 'object'
? window.__APP_CONFIG__
: null;
const observedCsrf = String(
(typeof window !== 'undefined' && window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]?.observedCsrfToken) || ''
).trim();
return {
origin: String((typeof window !== 'undefined' && window.location?.origin) || '').trim(),
title: String((typeof document !== 'undefined' && document?.title) || '').trim(),
csrfToken: String(cfg?.csrfToken || '').trim(),
observedCsrfToken: observedCsrf,
appConfig: cfg ? {
isRemoteControl: cfg.isRemoteControl === true,
isRemote: cfg.isRemote === true,
isSsh: cfg.isSsh === true,
connectionType: String(cfg.connectionType || ''),
windowMode: String(cfg.windowMode || ''),
sshHost: String(cfg.sshHost || ''),
sshHostName: String(cfg.sshHostName || ''),
sshAlias: String(cfg.sshAlias || ''),
sshTarget: String(cfg.sshTarget || ''),
remoteHost: String(cfg.remoteHost || ''),
remoteAuthority: String(cfg.remoteAuthority || ''),
remoteName: String(cfg.remoteName || ''),
} : null,
};
} catch {
return { origin: '', title: '', csrfToken: '', observedCsrfToken: '', appConfig: null };
}
})()`;
const nowClassifyMs = Date.now();
const localHubInfo =
typeof getLocalHubPortsFn === 'function' ? getLocalHubPortsFn() : { allPorts: new Set(), httpsPorts: new Set(), csrfTokens: new Set() };
const probedByWsUrl = new Map();
const desktopTargets = targets.filter((t) => !t.isIdeWorkbench && t.webSocketDebuggerUrl);
await Promise.allSettled(
desktopTargets.map(async (target) => {
const wsUrl = String(target.webSocketDebuggerUrl || '');
let targetOriginKey = '';
try {
targetOriginKey = new URL(String(target.url || '')).origin;
} catch {
targetOriginKey = String(target.url || '');
}
const cacheKey = `${wsUrl}::${targetOriginKey}`;
const cached = targetClassifyCache.get(cacheKey);
if (cached && nowClassifyMs - cached.ts < 4000) {
probedByWsUrl.set(wsUrl, cached.info);
return;
}
try {
const res = await evaluateOnTarget(wsUrl, classifyExpr, 1800);
const info = res?.result?.result?.value;
if (info && typeof info === 'object') {
probedByWsUrl.set(wsUrl, info);
targetClassifyCache.set(cacheKey, { ts: nowClassifyMs, info });
}
} catch {
if (cached?.info) probedByWsUrl.set(wsUrl, cached.info);
}
})
);
if (targetClassifyCache.size > 64) {
for (const [k, rec] of targetClassifyCache.entries()) {
if (nowClassifyMs - rec.ts > 30_000) targetClassifyCache.delete(k);
}
}
// 两趟分类:第一趟确认明确归属本机的 Desktop 窗口端口,第二趟据此精准识别 SSH 远端窗口
const confirmedLocalPorts = new Set();
for (const target of desktopTargets) {
const probedInfo = probedByWsUrl.get(String(target.webSocketDebuggerUrl || '')) || null;
const firstPass = classifyWindowTargetEndpoint({
target,
probedInfo,
localHubInfo,
confirmedLocalPorts: null,
});
if (
!firstPass.isRemote &&
firstPass.originPort > 0 &&
(localHubInfo?.allPorts?.has(firstPass.originPort) ||
(firstPass.csrfToken && localHubInfo?.csrfTokens?.has(firstPass.csrfToken)))
) {
confirmedLocalPorts.add(firstPass.originPort);
}
}
const activeRemoteWsUrls = new Set();
for (const target of targets) {
const wsUrl = String(target.webSocketDebuggerUrl || '');
const probedInfo = probedByWsUrl.get(wsUrl) || null;
const cls = classifyWindowTargetEndpoint({
target,
probedInfo,
localHubInfo,
confirmedLocalPorts,
});
if (cls.isRemote && wsUrl) {
const ep = registerRemoteEndpoint({
origin: cls.origin,
baseUrl: cls.origin,
csrfToken: cls.csrfToken,
wsUrl,
label: cls.hostLabel,
stableHostKey: cls.stableHostKey,
});
target.endpointId = ep.id;
target.isRemoteEndpoint = true;
target.endpointLabel = ep.label;
activeRemoteWsUrls.add(wsUrl);
} else {
target.endpointId = LOCAL_ENDPOINT_ID;
target.isRemoteEndpoint = false;
target.endpointLabel = '';
}
}
if (hasContextWindows || hadContextWindows) {
async function resolveFallbackRulesForEndpoint(endpointId) {
if (!hasContextWindows) return { verified: false, rules: {} };
const epObj = endpointId && endpointId !== LOCAL_ENDPOINT_ID
? getRegisteredRemoteEndpoint(endpointId)
: null;
if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) {
return { verified: false, rules: {} };
}
const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID;
let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || {
expiresAt: 0,
verified: false,
models: [],
};
if (Date.now() >= cached.expiresAt) {
try { try {
const [stRes, cat] = await Promise.all([ const [stRes, cat] = await Promise.all([
callLsRpc('GetUserStatus', {}, 1500), callLsRpc('GetUserStatus', {}, 2000, epObj),
getContextModelCatalog(), getContextModelCatalog(epObj),
]); ]);
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs; const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
if (Array.isArray(cfgs)) { if (Array.isArray(cfgs)) {
cachedBackendCtxModels = { cached = {
expiresAt: Date.now() + 10_000, expiresAt: Date.now() + 10_000,
verified: true,
models: getContextWindowModels(cfgs, cat), models: getContextWindowModels(cfgs, cat),
}; };
cachedBackendCtxModelsByEndpoint.delete(cacheKey);
if (cachedBackendCtxModelsByEndpoint.size >= 16) {
const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value;
if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey);
}
cachedBackendCtxModelsByEndpoint.set(cacheKey, cached);
} }
} catch { } catch {
// 忽略瞬态 LS 查询失败,保留上次缓存或交由窗口端解析 // 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退
} }
} }
if (cachedBackendCtxModels.models.length > 0) { if (cached.verified) {
fallbackRules = resolveContextWindowRules(cachedBackendCtxModels.models, contextWindows); return {
verified: true,
rules: cached.models.length > 0
? resolveContextWindowRules(cached.models, contextWindows)
: {},
};
}
return { verified: false, rules: {} };
}
const localFallbackRes = await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID);
const localFallbackRules = localFallbackRes.rules;
const remoteFallbackRulesById = new Map();
const uniqueRemoteIds = new Set(
targets
.filter((t) => !t.isIdeWorkbench && t.isRemoteEndpoint && t.endpointId)
.map((t) => t.endpointId)
);
for (const cachedKey of Array.from(cachedBackendCtxModelsByEndpoint.keys())) {
if (cachedKey !== LOCAL_ENDPOINT_ID && !getRegisteredRemoteEndpoint(cachedKey)) {
cachedBackendCtxModelsByEndpoint.delete(cachedKey);
} }
} }
const chatUrls = [ await Promise.allSettled(
...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl), Array.from(uniqueRemoteIds).map(async (epId) => {
...collectAllChatDebuggerUrls(targets), const res = await resolveFallbackRulesForEndpoint(epId);
]; // 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则
const expression = createContextWindowSyncExpression( remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules);
})
);
const ctxEvalTasks = [];
const seenCtxUrls = new Set();
for (const target of targets) {
if (target.isIdeWorkbench) continue;
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
if (!wsUrl || seenCtxUrls.has(wsUrl)) continue;
seenCtxUrls.add(wsUrl);
const epFallback =
target.isRemoteEndpoint && target.endpointId
? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules
: localFallbackRules;
const expr = createContextWindowSyncExpression(
contextWindows, contextWindows,
contextWindowBootId, contextWindowBootId,
fallbackRules epFallback,
true
); );
await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression))); ctxEvalTasks.push(evaluateOnTarget(wsUrl, expr));
}
const ideChatExpr = createContextWindowSyncExpression(
contextWindows,
contextWindowBootId,
localFallbackRules,
false
);
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
if (!chatUrl || seenCtxUrls.has(chatUrl)) continue;
seenCtxUrls.add(chatUrl);
ctxEvalTasks.push(evaluateOnTarget(chatUrl, ideChatExpr));
}
await Promise.allSettled(ctxEvalTasks);
hadContextWindows = hasContextWindows; hadContextWindows = hasContextWindows;
} }
@@ -1533,6 +2070,7 @@ export function createWindowBridgeController(options) {
} }
if (!enabled) { if (!enabled) {
pruneStaleRemoteEndpoints(activeRemoteWsUrls);
if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) { if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) {
updateBridgeStatus('disabled', { updateBridgeStatus('disabled', {
enabled: false, enabled: false,
@@ -1602,12 +2140,14 @@ export function createWindowBridgeController(options) {
bridgePort: Number(br?.port || 0), bridgePort: Number(br?.port || 0),
hasToken: Boolean(br?.token), hasToken: Boolean(br?.token),
transportMode: String(br?.transportMode || 'http'), transportMode: String(br?.transportMode || 'http'),
endpointId: String(br?.[${windowBridgeEndpointKey}] || ${JSON.stringify(LOCAL_ENDPOINT_ID)}),
endpointLabel: String(br?.endpointLabel || ''),
hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''), hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''),
routeCascadeId, routeCascadeId,
rpcBatch, rpcBatch,
}; };
} catch { } catch {
return { alive: false, dockKind: '', visible: true, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', hostRouteCascadeId: '', routeCascadeId: '', rpcBatch: [] }; return { alive: false, dockKind: '', visible: true, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', endpointId: ${JSON.stringify(LOCAL_ENDPOINT_ID)}, endpointLabel: '', hostRouteCascadeId: '', routeCascadeId: '', rpcBatch: [] };
} }
})()`; })()`;
@@ -1622,6 +2162,10 @@ export function createWindowBridgeController(options) {
if (!wsUrl) return { alive: false, dockKind: '', visible: false }; if (!wsUrl) return { alive: false, dockKind: '', visible: false };
let probedRouteId = ''; let probedRouteId = '';
const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim(); const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim();
const targetEndpointId = String(targetObj.endpointId || LOCAL_ENDPOINT_ID);
const targetIsRemote = Boolean(targetObj.isRemoteEndpoint && targetEndpointId !== LOCAL_ENDPOINT_ID);
const targetEndpointLabel = targetIsRemote ? String(targetObj.endpointLabel || 'SSH') : '';
if (!forceReinject) { if (!forceReinject) {
const probeRes = await evaluateOnTarget(wsUrl, probeExpr); const probeRes = await evaluateOnTarget(wsUrl, probeExpr);
const snap = probeRes?.result?.result?.value; const snap = probeRes?.result?.result?.value;
@@ -1639,8 +2183,21 @@ export function createWindowBridgeController(options) {
}; };
} }
if (snap.bundleVersion === bundleVersion) { if (snap.bundleVersion === bundleVersion) {
if (snap.bridgePort !== port || snap.hasToken !== true) { const snapEndpointId = String(snap.endpointId || LOCAL_ENDPOINT_ID);
const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`; const snapEndpointLabel = String(snap.endpointLabel || '');
if (
snap.bridgePort !== port ||
snap.hasToken !== true ||
snapEndpointId !== targetEndpointId ||
snapEndpointLabel !== targetEndpointLabel
) {
const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({
port,
token,
[WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId,
isRemoteEndpoint: targetIsRemote,
endpointLabel: targetEndpointLabel,
})})`;
await evaluateOnTarget(wsUrl, rebindExpr); await evaluateOnTarget(wsUrl, rebindExpr);
} }
let effectiveDockKind = String(snap.dockKind || ''); let effectiveDockKind = String(snap.dockKind || '');
@@ -1678,7 +2235,7 @@ export function createWindowBridgeController(options) {
} }
if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) { if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) {
sawCdpTransport = true; sawCdpTransport = true;
const rpcResults = await executeRpcBatch(snap.rpcBatch); const rpcResults = await executeRpcBatch(snap.rpcBatch, targetEndpointId);
relayedRpcCount += rpcResults.length; relayedRpcCount += rpcResults.length;
const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`; const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`;
await evaluateOnTarget(wsUrl, deliverExpr); await evaluateOnTarget(wsUrl, deliverExpr);
@@ -1704,12 +2261,17 @@ export function createWindowBridgeController(options) {
try { try {
const routeMatch = String(targetObj.url || '').match(/\/c\/([a-f0-9-]{36})(?:[/?#]|$)/i); const routeMatch = String(targetObj.url || '').match(/\/c\/([a-f0-9-]{36})(?:[/?#]|$)/i);
const targetConvId = routeMatch ? routeMatch[1] : ideRouteId || probedRouteId; const targetConvId = routeMatch ? routeMatch[1] : ideRouteId || probedRouteId;
const initOut = await handleApiRequest('/api/telemetry', 'GET', { const initOut = await invokeApiHandler(
'/api/telemetry',
'GET',
{
conversationId: targetConvId, conversationId: targetConvId,
range: 'today', range: 'today',
stepDetails: 'display', stepDetails: 'display',
stepRevision: '', stepRevision: '',
}); },
targetEndpointId
);
if (Number(initOut?.status || 200) === 200 && initOut?.body) { if (Number(initOut?.status || 200) === 200 && initOut?.body) {
initialTelemetry = JSON.parse(initOut.body); initialTelemetry = JSON.parse(initOut.body);
} }
@@ -1723,6 +2285,9 @@ export function createWindowBridgeController(options) {
bundleVersion, bundleVersion,
platform: String(platform || ''), platform: String(platform || ''),
mountMode, mountMode,
[WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId,
isRemoteEndpoint: targetIsRemote,
endpointLabel: targetEndpointLabel,
[WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '', [WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '',
isIdeChatFrame: Boolean(isIdeChatFrame), isIdeChatFrame: Boolean(isIdeChatFrame),
stylesCss: cachedAssets.stylesCss, stylesCss: cachedAssets.stylesCss,
@@ -1805,6 +2370,7 @@ export function createWindowBridgeController(options) {
} }
} }
pruneStaleRemoteEndpoints(activeRemoteWsUrls);
cdpFallbackActive = sawCdpTransport; cdpFallbackActive = sawCdpTransport;
updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', { updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', {
enabled: true, enabled: true,
@@ -1825,6 +2391,41 @@ export function createWindowBridgeController(options) {
}; };
} }
async function invokeRemoteWindowRpc(endpoint, method, body, timeoutMs = 5000) {
const wsUrls = getRemoteEndpointTargetWsUrls(endpoint);
if (wsUrls.length === 0) {
throw new Error(`No live CDP target for remote endpoint ${endpoint?.id || ''}`);
}
const expr = buildWindowRemoteRpcExpression(method, body, timeoutMs);
const evalTimeoutMs = Math.max(cdpTimeoutMs, (Number(timeoutMs) || 5000) + 1500);
let lastError = null;
for (const wsUrl of wsUrls) {
try {
const res = await evaluateOnTarget(wsUrl, expr, evalTimeoutMs);
if (res?.error || res?.result?.exceptionDetails) {
lastError = new Error(
res?.error?.message ||
res?.result?.exceptionDetails?.text ||
'CDP remote RPC evaluation exception'
);
continue;
}
const val = res?.result?.result?.value;
if (val && val.ok === true) {
return val.data ?? {};
}
lastError = new Error(val?.error || `Remote window RPC ${method} failed (${val?.status || 0})`);
} catch (err) {
lastError = err;
}
}
throw lastError || new Error(`Remote window RPC ${method} failed`);
}
if (bindRemoteRpcInvoker) {
setRemoteWindowRpcInvoker(invokeRemoteWindowRpc);
}
function syncAllWindows(opts = {}) { function syncAllWindows(opts = {}) {
if (syncInFlight) { if (syncInFlight) {
return syncInFlight.then(() => runSyncInternal(opts)); return syncInFlight.then(() => runSyncInternal(opts));
@@ -1853,6 +2454,9 @@ export function createWindowBridgeController(options) {
function start() { function start() {
stopped = false; stopped = false;
contextWindowBootId = `${process.pid}:${Date.now()}`; contextWindowBootId = `${process.pid}:${Date.now()}`;
if (bindRemoteRpcInvoker) {
setRemoteWindowRpcInvoker(invokeRemoteWindowRpc);
}
if (initialTimer) clearTimeout(initialTimer); if (initialTimer) clearTimeout(initialTimer);
if (pollTimer) clearTimeout(pollTimer); if (pollTimer) clearTimeout(pollTimer);
@@ -1923,6 +2527,9 @@ export function createWindowBridgeController(options) {
hadInjectedTargets = false; hadInjectedTargets = false;
hadInjectedChatFrames = false; hadInjectedChatFrames = false;
hadContextWindows = false; hadContextWindows = false;
if (bindRemoteRpcInvoker) {
setRemoteWindowRpcInvoker(null);
}
if (server) { if (server) {
const srv = server; const srv = server;
server = null; server = null;
@@ -1985,6 +2592,7 @@ export function createWindowBridgeController(options) {
return { return {
ensureBridgeServer, ensureBridgeServer,
syncAllWindows, syncAllWindows,
invokeRemoteWindowRpc,
notifySettingChanged, notifySettingChanged,
notifyContextWindowsChanged, notifyContextWindowsChanged,
start, start,
@@ -2026,6 +2634,7 @@ export function startDefaultWindowBridge(options) {
if (!defaultBridgeController) { if (!defaultBridgeController) {
defaultBridgeController = createWindowBridgeController({ defaultBridgeController = createWindowBridgeController({
leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'), leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'),
bindRemoteRpcInvoker: true,
...options, ...options,
}); });
defaultBridgeController.start(); defaultBridgeController.start();
+2 -2
View File
@@ -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=1795098443766"> <link rel="stylesheet" href="/styles.css?v=1795188897587">
<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=1795098443766"></script> <script src="/app.js?v=1795188897587"></script>
</body> </body>
</html> </html>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "usage-monitor-panel", "name": "usage-monitor-panel",
"version": "1.5.2", "version": "1.5.3",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
@@ -142,19 +142,19 @@ export const MAX_POPOVER_WIDTH = 1080;
export const DEFAULT_POPOVER_WIDTH = 580; export const DEFAULT_POPOVER_WIDTH = 580;
/** /**
* 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 * 归一化界面语言枚举(默认 `'auto'`,支持 `'zh-CN'` 及 `'en-US'`)。
* *
* @param {unknown} lang * @param {unknown} lang
* @returns {'auto'|'zh-CN'|'en-US'} * @returns {'auto'|'zh-CN'|'en-US'}
*/ */
export function normalizeLanguageSetting(lang) { export function normalizeLanguageSetting(lang) {
const raw = String(lang ?? '').trim(); const raw = String(lang ?? '').trim();
if (!raw) return 'zh-CN'; if (!raw) return 'auto';
const lower = raw.toLowerCase(); const lower = raw.toLowerCase();
if (lower === 'auto' || lower === 'system') return 'auto'; if (lower === 'auto' || lower === 'system') return 'auto';
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
return 'zh-CN'; return 'auto';
} }
/** /**
@@ -448,7 +448,24 @@ export function normalizeStandalonePort(port) {
} }
/** /**
* 归一化实验性现代化新 UI 开关(默认 `false`)。 * 归一化现代化 UI 开关(默认 `true`)。
*
* @param {unknown} val
* @returns {boolean}
*/
export function normalizeModernUi(val) {
if (val === undefined || val === null || val === '') return true;
if (typeof val === 'string') {
const lower = val.trim().toLowerCase();
if (lower === 'false' || lower === '0' || lower === 'off') return false;
if (lower === 'true' || lower === '1' || lower === 'on') return true;
return true;
}
return Boolean(val);
}
/**
* 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。
* *
* @param {unknown} val * @param {unknown} val
* @returns {boolean} * @returns {boolean}
@@ -1,5 +1,8 @@
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
export const WINDOW_BRIDGE_ENDPOINT_KEY = 'endpointId';
export const WINDOW_BRIDGE_ENDPOINT_HEADER = 'X-Usage-Monitor-Endpoint';
export const LOCAL_ENDPOINT_ID = 'local';
export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
@@ -782,11 +782,23 @@ export function createSessionLineChart() {
const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' }); const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' });
const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' });
const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' });
const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') });
const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') });
const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') });
const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipIoGrid = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [
h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]),
h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]),
h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]),
]);
const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true });
const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true });
const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [
h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]),
h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]),
tipIoGrid,
tipSub, tipSub,
tipAnomaly, tipAnomaly,
]); ]);
@@ -863,8 +875,18 @@ export function createSessionLineChart() {
pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded')
); );
patchText(tipMainRight, pt.secondaryRight || ''); patchText(tipMainRight, pt.secondaryRight || '');
patchAttr(tipSub, 'hidden', !pt.subDetail); const hasIoParts = Boolean(pt.ioParts);
if (pt.subDetail) { patchAttr(tipIoGrid, 'hidden', !hasIoParts);
if (hasIoParts) {
patchText(tipInLabelEl, t('cons.legInput'));
patchText(tipCacheLabelEl, t('cons.legCache'));
patchText(tipOutLabelEl, t('cons.legOutput'));
patchText(tipInValEl, pt.ioParts.inTok);
patchText(tipCacheValEl, pt.ioParts.cacheTok);
patchText(tipOutValEl, pt.ioParts.outTok);
}
patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail);
if (!hasIoParts && pt.subDetail) {
patchText(tipSub, pt.subDetail); patchText(tipSub, pt.subDetail);
} }
patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary);
@@ -1107,15 +1129,17 @@ export function createSessionLineChart() {
let value = 0; let value = 0;
let secondaryRight = ''; let secondaryRight = '';
let subDetail = ''; let subDetail = '';
let ioParts = null;
if (metric === 'totalTokens') { if (metric === 'totalTokens') {
value = isMultiCompare ? modelCumTok : runningTokens; value = isMultiCompare ? modelCumTok : runningTokens;
secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) });
subDetail = t('chart.step.ioSplit', { ioParts = {
inTok: formatTokens(inTok), inTok: formatTokens(inTok),
cacheTok: formatTokens(cacheTok), cacheTok: formatTokens(cacheTok),
outTok: formatTokens(outTok), outTok: formatTokens(outTok),
}); };
subDetail = t('chart.step.ioSplit', ioParts);
} else if (metric === 'context') { } else if (metric === 'context') {
value = ctxTok; value = ctxTok;
if (hasPrevCtx) { if (hasPrevCtx) {
@@ -1198,6 +1222,7 @@ export function createSessionLineChart() {
value, value,
secondaryRight, secondaryRight,
subDetail, subDetail,
ioParts,
anomalySummary, anomalySummary,
anomalySeverity: st.anomaly?.severity || '', anomalySeverity: st.anomaly?.severity || '',
}; };
@@ -324,7 +324,17 @@ export function createTrendAreaChart() {
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' });
const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') });
const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') });
const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') });
const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
const tipSubEl = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [
h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]),
h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]),
h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]),
]);
const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true });
const tooltipEl = h( const tooltipEl = h(
@@ -455,14 +465,12 @@ export function createTrendAreaChart() {
slot.outputTokens !== undefined); slot.outputTokens !== undefined);
patchAttr(tipSubEl, 'hidden', !hasSubBreakdown); patchAttr(tipSubEl, 'hidden', !hasSubBreakdown);
if (hasSubBreakdown) { if (hasSubBreakdown) {
patchText( patchText(tipInLabelEl, t('cons.legInput'));
tipSubEl, patchText(tipCacheLabelEl, t('cons.legCache'));
t('chart.step.ioSplit', { patchText(tipOutLabelEl, t('cons.legOutput'));
inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), patchText(tipInValEl, formatTokensPrecise(safeSlotTokens(slot.inputTokens)));
cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), patchText(tipCacheValEl, formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)));
outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), patchText(tipOutValEl, formatTokensPrecise(safeSlotTokens(slot.outputTokens)));
})
);
} }
const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : []; const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : [];
@@ -76,6 +76,12 @@ export const TopSessionHeader = defineComponent({
[updateBtnIcon, updateBtnText] [updateBtnIcon, updateBtnText]
); );
const sshBadge = h('span', {
className: 'endpoint-ssh-badge',
hidden: true,
text: 'SSH',
});
const statusIcon = createSvgIcon('pulse', { size: 12 }); const statusIcon = createSvgIcon('pulse', { size: 12 });
const statusText = h('span', { text: t('header.statusLive') }); const statusText = h('span', { text: t('header.statusLive') });
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
@@ -93,7 +99,7 @@ export const TopSessionHeader = defineComponent({
const headerRowEl = h('div', { className: 'session-header' }, [ const headerRowEl = h('div', { className: 'session-header' }, [
h('div', { className: 'session-left' }, [convSelect.el]), h('div', { className: 'session-left' }, [convSelect.el]),
h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]), h('div', { className: 'session-right' }, [sshBadge, updateBtn, statusTag, refreshBtn]),
]); ]);
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
@@ -162,6 +168,14 @@ export const TopSessionHeader = defineComponent({
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh')); patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
const ep = telemetry?.endpoint;
const isRemoteEndpoint = Boolean(ep?.isRemote);
patchAttr(sshBadge, 'hidden', !isRemoteEndpoint);
if (isRemoteEndpoint) {
const epLabel = String(ep?.label || 'SSH').trim();
patchAttr(sshBadge, 'title', epLabel && epLabel !== 'SSH' ? `SSH · ${epLabel}` : 'SSH');
}
const actConv = telemetry?.activeConversation; const actConv = telemetry?.activeConversation;
const convs = telemetry?.conversations || []; const convs = telemetry?.conversations || [];
const hostRouteId = telSt.hostRouteConversationId || ''; const hostRouteId = telSt.hostRouteConversationId || '';
@@ -9,6 +9,8 @@
*/ */
import { import {
LOCAL_ENDPOINT_ID,
WINDOW_BRIDGE_ENDPOINT_KEY,
WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_KEY,
WINDOW_OVERLAY_KEY, WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS, WINDOW_OVERLAY_METHODS,
@@ -19,7 +21,7 @@ import {
PANEL_SCALE_FACTORS, PANEL_SCALE_FACTORS,
applyAppearanceToRoot, applyAppearanceToRoot,
normalizeClientFontScale, normalizeClientFontScale,
normalizeClientModernUi, resolveSettingsModernUi,
} from '../../core/appearance.js'; } from '../../core/appearance.js';
import { import {
h, h,
@@ -51,6 +53,7 @@ import {
normalizeClientTopbarSlots, normalizeClientTopbarSlots,
normalizeClientUpdateMode, normalizeClientUpdateMode,
normalizeClientWindowMountMode, normalizeClientWindowMountMode,
resetTelemetryForEndpointSwitch,
resolveScopedConversation, resolveScopedConversation,
selectConversation, selectConversation,
startAsyncTelemetryLoop, startAsyncTelemetryLoop,
@@ -166,7 +169,7 @@ function findHostTitlebar() {
const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR =
'.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]';
const COMPOSER_MODEL_LABEL_RE = const COMPOSER_MODEL_LABEL_RE =
/\b(?:gemini|claude|gpt|argon|carbon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i;
const COMPOSER_MODEL_ATTR_RE = const COMPOSER_MODEL_ATTR_RE =
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
@@ -958,10 +961,18 @@ export function mountWindowOverlay() {
const bridgeConfig = getWindowBridgeConfig(); const bridgeConfig = getWindowBridgeConfig();
const bundleVersion = String(bridgeConfig?.bundleVersion || ''); const bundleVersion = String(bridgeConfig?.bundleVersion || '');
const stylesCss = String(bridgeConfig?.stylesCss || ''); const stylesCss = String(bridgeConfig?.stylesCss || '');
const activeBridgeEndpointId = String(
bridgeConfig?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID
);
const reusableCarryOver =
carryOverTelemetry &&
String(carryOverTelemetry?.endpoint?.id || LOCAL_ENDPOINT_ID) === activeBridgeEndpointId
? carryOverTelemetry
: null;
const seedTelemetry = const seedTelemetry =
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object' (bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
? bridgeConfig.initialTelemetry ? bridgeConfig.initialTelemetry
: null) || carryOverTelemetry; : null) || reusableCarryOver;
if (bridgeConfig?.initialTelemetry) { if (bridgeConfig?.initialTelemetry) {
delete bridgeConfig.initialTelemetry; delete bridgeConfig.initialTelemetry;
} }
@@ -1457,7 +1468,7 @@ export function mountWindowOverlay() {
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
const scaleKey = normalizeClientFontScale(settings?.fontScale); const scaleKey = normalizeClientFontScale(settings?.fontScale);
const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); const isModernUi = resolveSettingsModernUi(settings);
const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light';
for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { for (const el of [popoverEl, hoverTipEl, multiPanelEl]) {
if (el.getAttribute?.('data-font-scale') !== scaleKey) { if (el.getAttribute?.('data-font-scale') !== scaleKey) {
@@ -2741,14 +2752,49 @@ export function mountWindowOverlay() {
const token = String(nextBridge.token || ''); const token = String(nextBridge.token || '');
if (!Number.isInteger(port) || port <= 0 || !token) return false; if (!Number.isInteger(port) || port <= 0 || !token) return false;
const cur = readInjectedWindowBridge() || {}; const cur = readInjectedWindowBridge() || {};
const prevEndpointId = String(cur[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID);
const nextEndpointId =
nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] !== undefined
? String(nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID)
: prevEndpointId;
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token; const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
const endpointChanged = prevEndpointId !== nextEndpointId;
cur.port = port; cur.port = port;
cur.token = token; cur.token = token;
if (portChanged) { cur[WINDOW_BRIDGE_ENDPOINT_KEY] = nextEndpointId;
if (nextBridge.isRemoteEndpoint !== undefined) {
cur.isRemoteEndpoint = Boolean(nextBridge.isRemoteEndpoint);
}
if (nextBridge.endpointLabel !== undefined) {
cur.endpointLabel = String(nextBridge.endpointLabel || '');
}
if (portChanged || endpointChanged) {
cur.transportMode = 'http'; cur.transportMode = 'http';
} }
if (endpointChanged) {
if (Array.isArray(cur.rpcQueue)) {
cur.rpcQueue.length = 0;
}
if (cur.rpcPending instanceof Map) {
for (const pending of cur.rpcPending.values()) {
try {
const switchErr = new Error('Bridge endpoint switched');
switchErr.name = 'AbortError';
pending?.reject?.(switchErr);
} catch {
// 忽略旧端点回调异常
}
}
cur.rpcPending.clear();
}
}
window[WINDOW_BRIDGE_KEY] = cur; window[WINDOW_BRIDGE_KEY] = cur;
if (endpointChanged) {
resetTelemetryForEndpointSwitch();
void fetchTelemetry({ force: true });
} else {
void fetchTelemetry({ force: false }); void fetchTelemetry({ force: false });
}
return true; return true;
}, },
getTelemetrySnapshot() { getTelemetrySnapshot() {
@@ -56,6 +56,7 @@ export const CustomSelect = defineComponent({
setup({ getProps, setProps, emit, onCleanup }) { setup({ getProps, setProps, emit, onCleanup }) {
let isOpen = false; let isOpen = false;
let focusedIndex = -1; let focusedIndex = -1;
let lastOpenMenuLayoutSig = '';
const initialIcon = getProps().icon; const initialIcon = getProps().icon;
const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 }); const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 });
@@ -134,6 +135,15 @@ export const CustomSelect = defineComponent({
} }
} }
function buildMenuLayoutSig(options = [], labelText = '') {
let sig = `${labelText}|${options.length}`;
for (let i = 0; i < options.length; i++) {
const o = options[i];
sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`;
}
return sig;
}
function toggleOpen(nextOpen) { function toggleOpen(nextOpen) {
isOpen = Boolean(nextOpen); isOpen = Boolean(nextOpen);
if (isOpen) { if (isOpen) {
@@ -144,6 +154,9 @@ export const CustomSelect = defineComponent({
opts.findIndex((o) => selSet.has(o.value)) opts.findIndex((o) => selSet.has(o.value))
); );
renderMenuOptions(); renderMenuOptions();
lastOpenMenuLayoutSig = buildMenuLayoutSig(opts, triggerLabel.textContent || '');
} else {
lastOpenMenuLayoutSig = '';
} }
patchClasses(rootEl, { 'is-open': isOpen }); patchClasses(rootEl, { 'is-open': isOpen });
patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false');
@@ -343,9 +356,13 @@ export const CustomSelect = defineComponent({
patchAttr(triggerBtn, 'title', titleText); patchAttr(triggerBtn, 'title', titleText);
if (isOpen) { if (isOpen) {
renderMenuOptions(); renderMenuOptions();
const nextLayoutSig = buildMenuLayoutSig(options, labelText);
if (nextLayoutSig !== lastOpenMenuLayoutSig) {
lastOpenMenuLayoutSig = nextLayoutSig;
positionMenu(); positionMenu();
} }
} }
}
const handleDocClick = (e) => { const handleDocClick = (e) => {
if (isOpen && !isEventInside(e, rootEl)) { if (isOpen && !isEventInside(e, rootEl)) {
@@ -1,7 +1,7 @@
/** /**
* @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar). * @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar).
* 用于在消费概览、热门模型明细及数据来源明细中直观展示: * 用于在消费概览、热门模型明细及模型总览卡片中直观展示:
* 直接输入 (Input)、缓存读取 (Cached)、内容生成 (Output) 与思考推理 (Thinking) 的 Token 占比。 * 直接输入 (Input)、缓存读取 (Cached)、思考推理 (Thinking)、内容生成 (Output) 的 Token 占比。
*/ */
import { h, patchStyleVar } from '../../core/domPatch.js'; import { h, patchStyleVar } from '../../core/domPatch.js';
@@ -18,18 +18,18 @@ import { h, patchStyleVar } from '../../core/domPatch.js';
* responseTokens?: number, * responseTokens?: number,
* thinkingTokens?: number * thinkingTokens?: number
* }) => void * }) => void
* }} 组件根元素与增量更新方法 * }} 组件根元素及增量更新方法
*/ */
export function createFourSegmentBar() { export function createFourSegmentBar() {
const segInput = h('div', { className: 'progress-seg seg-input' }); const segInput = h('div', { className: 'progress-seg seg-input' });
const segCached = h('div', { className: 'progress-seg seg-cached' }); const segCached = h('div', { className: 'progress-seg seg-cached' });
const segOutput = h('div', { className: 'progress-seg seg-output' });
const segThinking = h('div', { className: 'progress-seg seg-thinking' }); const segThinking = h('div', { className: 'progress-seg seg-thinking' });
const segOutput = h('div', { className: 'progress-seg seg-output' });
const el = h('div', { className: 'progress-track cons-seg-bar' }, [ const el = h('div', { className: 'progress-track cons-seg-bar' }, [
segInput, segInput,
segCached, segCached,
segOutput,
segThinking, segThinking,
segOutput,
]); ]);
/** /**
@@ -98,6 +98,7 @@ export function patchCapsuleOdometerText(
if (!isModern || !/\d/.test(nextStr)) { if (!isModern || !/\d/.test(nextStr)) {
if (prev?.active) { if (prev?.active) {
el.textContent = '';
while (el.firstChild) el.removeChild(el.firstChild); while (el.firstChild) el.removeChild(el.firstChild);
patchAttr(el, 'data-od-active', null); patchAttr(el, 'data-od-active', null);
patchAttr(el, 'data-od-value', null); patchAttr(el, 'data-od-value', null);
@@ -114,6 +115,7 @@ export function patchCapsuleOdometerText(
let nodes; let nodes;
if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) {
el.textContent = '';
while (el.firstChild) el.removeChild(el.firstChild); while (el.firstChild) el.removeChild(el.firstChild);
nodes = new Map(); nodes = new Map();
} else { } else {
@@ -472,10 +474,6 @@ export const CapsuleBarWidget = defineComponent({
'div', 'div',
{ className: 'preview-host-left is-composer', hidden: true }, { className: 'preview-host-left is-composer', hidden: true },
[ [
h('span', { className: 'preview-composer-chip' }, [
h('span', { text: 'Auto' }),
createSvgIcon('chevron-down', { size: 10 }),
]),
h('span', { className: 'preview-composer-chip' }, [ h('span', { className: 'preview-composer-chip' }, [
h('span', { text: 'Carbon (High)' }), h('span', { text: 'Carbon (High)' }),
createSvgIcon('chevron-down', { size: 10 }), createSvgIcon('chevron-down', { size: 10 }),
@@ -15,6 +15,7 @@ import {
} from '../../core/domPatch.js'; } from '../../core/domPatch.js';
import { import {
buildStepAnomalyDiagnostic, buildStepAnomalyDiagnostic,
buildStepCompactionDiagnostic,
resolveModelDisplayInfo, resolveModelDisplayInfo,
speedReasonText, speedReasonText,
} from '../../core/formatters.js'; } from '../../core/formatters.js';
@@ -22,6 +23,7 @@ import { getEffectiveLocale, t } from '../../i18n/index.js';
import { import {
DEFAULT_STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS,
STEP_COLUMN_REGISTRY, STEP_COLUMN_REGISTRY,
isCompactionStepItem,
} from '../../registries/stepColumnRegistry.js'; } from '../../registries/stepColumnRegistry.js';
import { import {
formatAgentBadgeText, formatAgentBadgeText,
@@ -329,7 +331,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
let bestModelObj = firstStep; let bestModelObj = firstStep;
for (const cand of modelCandidates.values()) { for (const cand of modelCandidates.values()) {
const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' });
const len = (disp.baseText?.length || 0) + (disp.compactionSuffix?.length || 0); const len = disp.baseText?.length || 0;
if (len > bestModelLen) { if (len > bestModelLen) {
bestModelLen = len; bestModelLen = len;
bestModelObj = cand; bestModelObj = cand;
@@ -509,7 +511,10 @@ export const StepTableWidget = defineComponent({
return; return;
} }
hideTurnTip(); hideTurnTip();
patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' }); patchClasses(anomalyTipEl, {
'is-danger': diag.severity === 'danger',
'is-compaction': diag.severity === 'compaction',
});
patchText(anomalyTipTitleEl, diag.title); patchText(anomalyTipTitleEl, diag.title);
patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub);
if (diag.sub) patchText(anomalyTipSubEl, diag.sub); if (diag.sub) patchText(anomalyTipSubEl, diag.sub);
@@ -527,7 +532,10 @@ export const StepTableWidget = defineComponent({
if (row.detail) { if (row.detail) {
itemChildren.push( itemChildren.push(
h('div', { h('div', {
className: 'step-anomaly-tip-detail text-mono', className:
row.mono === false
? 'step-anomaly-tip-detail'
: 'step-anomaly-tip-detail text-mono',
text: row.detail, text: row.detail,
}) })
); );
@@ -679,16 +687,35 @@ export const StepTableWidget = defineComponent({
if (event?.target === badge) hideTurnTip(); if (event?.target === badge) hideTurnTip();
} }
function buildStepRowDiagnostic(st, displaySettings, hasStepAnomaly, isCompactionRow) {
if (hasStepAnomaly) {
const diag = buildStepAnomalyDiagnostic(st);
if (diag && isCompactionRow) {
return {
...diag,
hint: diag.hint
? `${diag.hint} · ${t('steps.compactionAnomalyHint')}`
: t('steps.compactionAnomalyHint'),
};
}
return diag;
}
if (isCompactionRow) {
return buildStepCompactionDiagnostic(st, displaySettings);
}
return null;
}
function moveAlongTurnRail(event) { function moveAlongTurnRail(event) {
const { badge, prompt, anomalyStep } = hoverRows.get(this); const { badge, prompt, rowDiagGetter } = hoverRows.get(this);
const rect = this.getBoundingClientRect?.(); const rect = this.getBoundingClientRect?.();
const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; const relX = rect ? (event?.clientX ?? 0) - rect.left : 0;
if (event?.target !== badge && relX <= 18) { if (event?.target !== badge && relX <= 18) {
showTurnTip(this, prompt); showTurnTip(this, prompt);
} else { } else {
hideTurnTip(); hideTurnTip();
if (anomalyStep) { if (rowDiagGetter) {
showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep)); showAnomalyTip(this, rowDiagGetter());
} }
} }
} }
@@ -696,8 +723,8 @@ export const StepTableWidget = defineComponent({
function leaveStepCell(event) { function leaveStepCell(event) {
const entry = hoverRows.get(this); const entry = hoverRows.get(this);
hideTurnTip(); hideTurnTip();
if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) {
showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep)); showAnomalyTip(this, entry.rowDiagGetter());
} }
} }
@@ -991,7 +1018,8 @@ export const StepTableWidget = defineComponent({
: ''; : '';
const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N';
const anomalySig = st.anomalySig || ''; const anomalySig = st.anomalySig || '';
return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; const compactSig = isCompactionStepItem(st) ? 'C' : '';
return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${compactSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
}, },
createRow: (item) => { createRow: (item) => {
if (item.isSizer) { if (item.isSizer) {
@@ -1236,14 +1264,20 @@ export const StepTableWidget = defineComponent({
const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0);
const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger');
const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger);
const isCompactionRow = isCompactionStepItem(st);
const hasRowTip = hasStepAnomaly || isCompactionRow;
const rowDiagGetter = hasRowTip
? () => buildStepRowDiagnostic(st, cellCtx.displaySettings, hasStepAnomaly, isCompactionRow)
: null;
patchClasses(tr, { patchClasses(tr, {
'is-compaction': isCompactionRow,
'is-anomaly-warn': isAnomalyWarn, 'is-anomaly-warn': isAnomalyWarn,
'is-anomaly-danger': isAnomalyDanger, 'is-anomaly-danger': isAnomalyDanger,
}); });
if (hasStepAnomaly) { if (hasRowTip) {
const anchorEl = firstTd || tr; const anchorEl = firstTd || tr;
tr.onmouseenter = () => { tr.onmouseenter = () => {
showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st)); showAnomalyTip(anchorEl, rowDiagGetter());
}; };
tr.onmouseleave = hideAnomalyTip; tr.onmouseleave = hideAnomalyTip;
} else { } else {
@@ -1268,10 +1302,10 @@ export const StepTableWidget = defineComponent({
hoverRows.set(hoverTd, { hoverRows.set(hoverTd, {
badge: refs.agentBadgeEl, badge: refs.agentBadgeEl,
prompt, prompt,
anomalyStep: hasStepAnomaly ? st : null, rowDiagGetter,
tr, tr,
}); });
const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly; const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip;
hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null;
hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail;
hoverTd.onmouseleave = leaveStepCell; hoverTd.onmouseleave = leaveStepCell;
@@ -1299,6 +1333,7 @@ export const StepTableWidget = defineComponent({
patchClasses(tr, { patchClasses(tr, {
'is-stripe-even': false, 'is-stripe-even': false,
'is-step-entering': false, 'is-step-entering': false,
'is-compaction': false,
'is-anomaly-warn': false, 'is-anomaly-warn': false,
'is-anomaly-danger': false, 'is-anomaly-danger': false,
}); });
+16 -2
View File
@@ -39,13 +39,27 @@ export function normalizeClientFontScale(raw) {
} }
export function normalizeClientModernUi(raw) { export function normalizeClientModernUi(raw) {
if (raw === undefined || raw === null || raw === '') return true;
if (typeof raw === 'string') { if (typeof raw === 'string') {
const lower = raw.trim().toLowerCase(); const lower = raw.trim().toLowerCase();
return lower === 'true' || lower === '1' || lower === 'on'; if (lower === 'false' || lower === '0' || lower === 'off') return false;
if (lower === 'true' || lower === '1' || lower === 'on') return true;
return true;
} }
return Boolean(raw); return Boolean(raw);
} }
export function resolveSettingsModernUi(settings) {
if (!settings || typeof settings !== 'object') return true;
if (settings.modernUi !== undefined) {
return normalizeClientModernUi(settings.modernUi);
}
if (settings.experimentalModernUi !== undefined) {
return normalizeClientModernUi(settings.experimentalModernUi);
}
return true;
}
/** /**
* Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`.
* *
@@ -396,7 +410,7 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t
const colorScheme = detectHostColorScheme(targetEl); const colorScheme = detectHostColorScheme(targetEl);
setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme);
const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); const isModernUi = resolveSettingsModernUi(settings);
if (isModernUi) { if (isModernUi) {
setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); setAttrIfChanged(targetEl, 'data-modern-ui', 'true');
} else { } else {
+21 -3
View File
@@ -322,7 +322,22 @@ export function positionAnchoredPopup(
popupEl.style.maxHeight = ''; popupEl.style.maxHeight = '';
const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); const availWidth = Math.max(120, Math.floor(bound.width - margin * 2));
popupEl.style.maxWidth = `${availWidth}px`; let cssMaxW = NaN;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const rawMaxW = window.getComputedStyle(popupEl)?.maxWidth;
if (rawMaxW && rawMaxW !== 'none') {
cssMaxW = Number.parseFloat(rawMaxW);
}
} catch {
// 忽略 Mock DOM 样式查询异常
}
}
const effectiveMaxW =
Number.isFinite(cssMaxW) && cssMaxW > 0
? Math.max(120, Math.min(availWidth, Math.floor(cssMaxW)))
: availWidth;
popupEl.style.maxWidth = `${effectiveMaxW}px`;
const rawRect = popupEl.getBoundingClientRect?.(); const rawRect = popupEl.getBoundingClientRect?.();
// 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小
@@ -330,10 +345,13 @@ export function positionAnchoredPopup(
Number(popupEl.offsetWidth || 0), Number(popupEl.offsetWidth || 0),
Math.ceil(Number(rawRect?.width || 0)) Math.ceil(Number(rawRect?.width || 0))
); );
if (naturalW > availWidth) { if (naturalW > effectiveMaxW) {
popupEl.style.minWidth = '0px'; popupEl.style.minWidth = '0px';
} }
const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)); const popupW = Math.min(
effectiveMaxW,
naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)
);
const safeLeft = bound.left + margin; const safeLeft = bound.left + margin;
const safeRight = bound.right - margin; const safeRight = bound.right - margin;
+78 -8
View File
@@ -222,6 +222,42 @@ export function buildStepAnomalyDiagnostic(st) {
}; };
} }
export function buildStepCompactionDiagnostic(st, displaySettings = {}) {
if (!st || typeof st !== 'object') return null;
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '' });
const promptTok =
Math.max(0, Number(st.inputTokens || 0)) + Math.max(0, Number(st.cacheReadTokens || 0));
const outTok = Math.max(0, Number(st.outputTokens || 0));
const title = t('steps.compactionStepTitle', { step: Number(st.stepIndex ?? 0) });
const rows =
promptTok > 0 || outTok > 0
? [
{
text: t('steps.compactionSummaryRow', {
input: formatTokens(promptTok),
output: formatTokens(outTok),
}),
detail: t('steps.compactionDetailHint'),
mono: false,
danger: false,
},
]
: [
{
text: t('steps.compactionDetailHint'),
detail: '',
danger: false,
},
];
return {
title,
sub: disp.baseText || '',
rows,
hint: '',
severity: 'compaction',
};
}
export function buildModelAnomalyDiagnostic(m) { export function buildModelAnomalyDiagnostic(m) {
const sum = resolveModelAnomalySummary(m); const sum = resolveModelAnomalySummary(m);
if (!sum) return null; if (!sum) return null;
@@ -317,8 +353,8 @@ export const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode;
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。 * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
* *
* 规则: * 规则:
* - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`) * - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`Orchestrator (Neon)`、`gemini-flash-worker-agy` / `M669`)
* 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`; * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `orchestrator-neon` / `worker-agy-hydrogen`;
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响; * `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响;
* - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`); * - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`);
* - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 * - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。
@@ -391,22 +427,55 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
/\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-hydrogen\b|\bOrchestrator\s+Worker\b/i.test( /\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-hydrogen\b|\bOrchestrator\s+Worker\b/i.test(
combined combined
); );
const isKnownOrchCarbonPh = /\bMODEL_PLACEHOLDER_M667\b/i.test(combined);
const isKnownOrchArgonPh = /\bMODEL_PLACEHOLDER_M681\b/i.test(combined);
const isKnownOrchNeonPh = /\bMODEL_PLACEHOLDER_M537\b/i.test(combined);
const dynamicOrchVariantMatch =
combined.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i) ||
combined.match(/\bgemini-pro-orchestrator-([a-z0-9-]+)\b/i) ||
combined.match(/\b(?:orchestrator|orch)-([a-z0-9]+)(?=·|\s|$)/i);
const dynamicOrchVariant =
dynamicOrchVariantMatch && dynamicOrchVariantMatch[1].toLowerCase() !== 'worker'
? dynamicOrchVariantMatch[1].toLowerCase()
: '';
const hasBareProOrch = /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(combined);
const isOrchSeries = const isOrchSeries =
isOrchWorker || isOrchWorker ||
/\bgemini-pro-orchestrator(?:-argon)?\b|\borchestrator-(?:carbon|argon)\b|\borch-(?:carbon|argon)(?:·压缩)?(?=\s|$)|Orchestrator\s*\((?:Carbon|Argon)\)|\bMODEL_PLACEHOLDER_M(?:667|681)\b/i.test( Boolean(dynamicOrchVariant) ||
combined isKnownOrchNeonPh ||
); isKnownOrchArgonPh ||
isKnownOrchCarbonPh ||
hasBareProOrch;
if (isOrchSeries) { if (isOrchSeries) {
let compactId = 'orchestrator-carbon'; let compactId = '';
let fullId = 'gemini-pro-orchestrator (carbon-4)'; let fullId = '';
if (isOrchWorker) { if (isOrchWorker) {
compactId = 'worker-agy-hydrogen'; compactId = 'worker-agy-hydrogen';
fullId = 'gemini-flash-worker-agy (hydrogen-4)'; fullId = 'gemini-flash-worker-agy (hydrogen-4)';
} else if (/\bargon\b|\bMODEL_PLACEHOLDER_M681\b|\borch-argon\b/i.test(combined)) { } else if (isKnownOrchNeonPh || dynamicOrchVariant === 'neon') {
compactId = 'orchestrator-neon';
fullId = 'gemini-pro-orchestrator-neon (neon-4)';
} else if (isKnownOrchArgonPh || dynamicOrchVariant === 'argon') {
compactId = 'orchestrator-argon'; compactId = 'orchestrator-argon';
fullId = 'gemini-pro-orchestrator-argon (argon-4)'; fullId = 'gemini-pro-orchestrator-argon (argon-4)';
} else if (
isKnownOrchCarbonPh ||
dynamicOrchVariant === 'carbon' ||
(hasBareProOrch && !dynamicOrchVariant)
) {
compactId = 'orchestrator-carbon';
fullId = 'gemini-pro-orchestrator (carbon-4)';
} else if (dynamicOrchVariant) {
compactId = `orchestrator-${dynamicOrchVariant}`;
const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim();
fullId = cleanUpstream
? cleanUpstream.toLowerCase().includes(dynamicOrchVariant)
? cleanUpstream
: `${cleanUpstream} (${dynamicOrchVariant})`
: `gemini-pro-orchestrator-${dynamicOrchVariant}`;
} }
if (compactId) {
const baseText = orchestratorMode === 'full' ? fullId : compactId; const baseText = orchestratorMode === 'full' ? fullId : compactId;
const text = `${baseText}${compactionSuffix}`; const text = `${baseText}${compactionSuffix}`;
const multiUpstream = const multiUpstream =
@@ -423,6 +492,7 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
isOrchestratorSeries: true, isOrchestratorSeries: true,
}; };
} }
}
const rawSelected = const rawSelected =
(showUpstream (showUpstream
+39 -5
View File
@@ -4,7 +4,12 @@
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
*/ */
import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; import {
LOCAL_ENDPOINT_ID,
WINDOW_BRIDGE_ENDPOINT_HEADER,
WINDOW_BRIDGE_ENDPOINT_KEY,
readInjectedWindowBridge,
} from '../../shared/window-bridge-protocol.mjs';
const inFlightGets = new Map(); const inFlightGets = new Map();
const activeControllers = new Map(); const activeControllers = new Map();
@@ -130,7 +135,10 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs })
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) { export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
const upperMethod = method.toUpperCase(); const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; const activeEndpointId =
String(getWindowBridgeConfig()?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() ||
LOCAL_ENDPOINT_ID;
const dedupKey = upperMethod === 'GET' && !abortKey ? `${activeEndpointId}::${path}` : '';
if (dedupKey && inFlightGets.has(dedupKey)) { if (dedupKey && inFlightGets.has(dedupKey)) {
return inFlightGets.get(dedupKey); return inFlightGets.get(dedupKey);
@@ -148,7 +156,20 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
signal = requestController.signal; signal = requestController.signal;
} }
const ensureEndpointUnchanged = (targetBridge) => {
if (!targetBridge) return;
const currentEndpointId =
String(targetBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() ||
LOCAL_ENDPOINT_ID;
if (currentEndpointId !== activeEndpointId) {
const switchErr = new Error('Bridge endpoint switched');
switchErr.name = 'AbortError';
throw switchErr;
}
};
const execHttpOnce = async (activeBridge) => { const execHttpOnce = async (activeBridge) => {
ensureEndpointUnchanged(activeBridge);
const sidecar = typeof window !== 'undefined' ? window.sidecar : null; const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
const fetchFn = sidecar?.fetch const fetchFn = sidecar?.fetch
? sidecar.fetch.bind(sidecar) ? sidecar.fetch.bind(sidecar)
@@ -162,6 +183,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
} }
if (activeBridge) { if (activeBridge) {
headers['X-Usage-Monitor-Token'] = activeBridge.token; headers['X-Usage-Monitor-Token'] = activeBridge.token;
const epId = String(activeBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || '').trim();
if (epId && epId !== LOCAL_ENDPOINT_ID) {
headers[WINDOW_BRIDGE_ENDPOINT_HEADER] = epId;
}
} }
const res = await fetchFn(requestUrl, { const res = await fetchFn(requestUrl, {
method: upperMethod, method: upperMethod,
@@ -181,7 +206,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
throw abortErr; throw abortErr;
} }
if (!res.ok) { if (!res.ok) {
throw new Error(data.error || `HTTP ${res.status}`); const httpErr = new Error(data.error || `HTTP ${res.status}`);
httpErr.httpStatus = res.status;
httpErr.retryable = Boolean(data?.retryable);
throw httpErr;
} }
if (activeBridge) { if (activeBridge) {
activeBridge.transportMode = 'http'; activeBridge.transportMode = 'http';
@@ -202,8 +230,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
if (signal?.aborted || cdpErr?.name === 'AbortError') { if (signal?.aborted || cdpErr?.name === 'AbortError') {
throw cdpErr; throw cdpErr;
} }
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次 // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次;
// 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点
const latestBridge = getWindowBridgeConfig() || initialBridge; const latestBridge = getWindowBridgeConfig() || initialBridge;
ensureEndpointUnchanged(latestBridge);
latestBridge.transportMode = 'http'; latestBridge.transportMode = 'http';
return execHttpOnce(latestBridge); return execHttpOnce(latestBridge);
} }
@@ -232,7 +262,11 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
} }
throw fetchErr; throw fetchErr;
} }
// 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道 // 仅在网络/CORS 阻断(无 HTTP 状态码)或桥接令牌失配(403)时切换至 CDP 兜底;
// 业务/初始化状态码(如 503 Remote endpoint initializing、400、500)保持 HTTP 通道等待正常重试。
if (fetchErr?.httpStatus && fetchErr.httpStatus !== 403) {
throw fetchErr;
}
return fallbackViaCdpWithRecovery(bridge); return fallbackViaCdpWithRecovery(bridge);
} }
}; };
+7 -3
View File
@@ -31,7 +31,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'header.statusGenerating': 'Running{suffix}', 'header.statusGenerating': 'Running{suffix}',
'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaCached': 'Quota Cached',
'header.statusQuotaOffline': 'Quota Offline', 'header.statusQuotaOffline': 'Quota Offline',
'header.statusLive': 'Live 2s', 'header.statusLive': 'Monitoring',
// Formatters & Common Labels // Formatters & Common Labels
'fmt.pending': 'N/A', 'fmt.pending': 'N/A',
@@ -231,7 +231,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.cacheRead': 'Cache Read', 'cons.cacheRead': 'Cache Read',
'cons.savedCost': 'Saved {cost}', 'cons.savedCost': 'Saved {cost}',
'cons.outputUsage': 'Output', 'cons.outputUsage': 'Output',
'cons.replyAndThink': 'Reply {resp} · Think {think}', 'cons.replyAndThink': 'Think {think} · Reply {resp}',
'cons.trendTitle': 'Usage Trend', 'cons.trendTitle': 'Usage Trend',
'cons.allTime': 'All Time', 'cons.allTime': 'All Time',
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
@@ -325,6 +325,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'steps.anomalyKind.canceled': 'Canceled by User', 'steps.anomalyKind.canceled': 'Canceled by User',
'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors',
'steps.anomalyDelayPart': 'Backoff {sec}s', 'steps.anomalyDelayPart': 'Backoff {sec}s',
'steps.compactionStepTitle': '#{step} · Auto-Compaction',
'steps.compactionSummaryRow': 'Input {input} → Summary {output}',
'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space',
'steps.compactionAnomalyHint': 'This step is also an auto-compaction step',
'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyTerminalTag': 'Stopped',
'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors',
'steps.anomalyModelSub': '{steps} steps affected', 'steps.anomalyModelSub': '{steps} steps affected',
@@ -441,7 +445,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.fontLg': 'Large', 'settings.gen.fontLg': 'Large',
'settings.gen.fontXl': 'XL', 'settings.gen.fontXl': 'XL',
'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact',
'settings.gen.modernUi': 'Modern UI (Experimental)', 'settings.gen.modernUi': 'Modern UI',
'settings.gen.modernUiOff': 'Off', 'settings.gen.modernUiOff': 'Off',
'settings.gen.modernUiOn': 'On', 'settings.gen.modernUiOn': 'On',
'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations',
+2 -2
View File
@@ -29,8 +29,8 @@ export function detectHostSystemLocale() {
} }
export const i18nStore = createReactiveStore({ export const i18nStore = createReactiveStore({
language: 'zh-CN', language: 'auto',
locale: 'zh-CN', locale: detectHostSystemLocale(),
}); });
export function setI18nLanguage(rawLang) { export function setI18nLanguage(rawLang) {
+9 -5
View File
@@ -31,7 +31,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.statusGenerating': '生成中{suffix}', 'header.statusGenerating': '生成中{suffix}',
'header.statusQuotaCached': '额度缓存', 'header.statusQuotaCached': '额度缓存',
'header.statusQuotaOffline': '额度离线', 'header.statusQuotaOffline': '额度离线',
'header.statusLive': '实时 2s', 'header.statusLive': '监控中',
// Formatters & Common Labels // Formatters & Common Labels
'fmt.pending': '待定', 'fmt.pending': '待定',
@@ -231,7 +231,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.cacheRead': '缓存读取', 'cons.cacheRead': '缓存读取',
'cons.savedCost': '节省 {cost}', 'cons.savedCost': '节省 {cost}',
'cons.outputUsage': '输出用量', 'cons.outputUsage': '输出用量',
'cons.replyAndThink': '回复 {resp} · 思考 {think}', 'cons.replyAndThink': '思考 {think} · 回复 {resp}',
'cons.trendTitle': '用量趋势', 'cons.trendTitle': '用量趋势',
'cons.allTime': '全部时间', 'cons.allTime': '全部时间',
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
@@ -296,7 +296,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'steps.modelCallsOnly': '{calls}次', 'steps.modelCallsOnly': '{calls}次',
'steps.modelsSummaryPrefix': '{count} 模型 · ', 'steps.modelsSummaryPrefix': '{count} 模型 · ',
'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%', 'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%',
'steps.modelSplitFoot': '入 {inTok} · 缓 {cacheTok} · 思 {thinkTok} · 正 {respTok}', 'steps.modelSplitFoot': '输入 {inTok} · 缓存 {cacheTok} · 思考 {thinkTok} · 输出 {respTok}',
'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)', 'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)',
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
'steps.turnMediaOnly': '[图片/附件提问]', 'steps.turnMediaOnly': '[图片/附件提问]',
@@ -325,6 +325,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'steps.anomalyKind.canceled': '用户取消', 'steps.anomalyKind.canceled': '用户取消',
'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次',
'steps.anomalyDelayPart': '退避 {sec}s', 'steps.anomalyDelayPart': '退避 {sec}s',
'steps.compactionStepTitle': '#{step} · 自动压缩',
'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}',
'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间',
'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤',
'steps.anomalyTerminalTag': '中止', 'steps.anomalyTerminalTag': '中止',
'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次',
'steps.anomalyModelSub': '涉及 {steps} 步', 'steps.anomalyModelSub': '涉及 {steps} 步',
@@ -441,10 +445,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.fontLg': '大', 'settings.gen.fontLg': '大',
'settings.gen.fontXl': '特大', 'settings.gen.fontXl': '特大',
'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高',
'settings.gen.modernUi': '新 UI(实验性)', 'settings.gen.modernUi': '现代化 UI',
'settings.gen.modernUiOff': '关闭', 'settings.gen.modernUiOff': '关闭',
'settings.gen.modernUiOn': '开启', 'settings.gen.modernUiOn': '开启',
'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色及更流畅的现代过渡动画',
'settings.gen.updateTitle': '版本更新', 'settings.gen.updateTitle': '版本更新',
'settings.gen.updateMode': '更新方式', 'settings.gen.updateMode': '更新方式',
'settings.gen.updateManual': '仅提示新版本,手动更新', 'settings.gen.updateManual': '仅提示新版本,手动更新',
@@ -114,6 +114,13 @@ function formatStepClockTime(createdAtMs) {
return { text: hhmmss, title: full }; return { text: hhmmss, title: full };
} }
export function isCompactionStepItem(st) {
if (!st || typeof st !== 'object') return false;
if (st.isCompactionStep) return true;
const raw = `${st.activeModelShort ?? st.modelShort ?? ''} ${st.activeModelLabel ?? st.modelLabel ?? ''} ${st.activeModelUpstream ?? st.modelUpstream ?? ''}`;
return /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(raw);
}
export const STEP_COLUMN_REGISTRY = Object.freeze({ export const STEP_COLUMN_REGISTRY = Object.freeze({
step: { step: {
key: 'step', key: 'step',
@@ -153,21 +160,17 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
optLabel: () => t('stepCol.model.opt'), optLabel: () => t('stepCol.model.opt'),
sigPart: (st, ctx) => { sigPart: (st, ctx) => {
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
return `${disp.baseText}:${disp.compactionSuffix}:${disp.title}`; return `${disp.baseText}:${disp.title}`;
}, },
createCell: () => { createCell: () => {
const nameEl = h('span', { className: 'step-model-name' }); const nameEl = h('span', { className: 'step-model-name' });
const compactEl = h('span', { className: 'step-model-compact', hidden: true }); const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl]);
const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl, compactEl]);
const td = h('td', {}, [wrapEl]); const td = h('td', {}, [wrapEl]);
return { td, refs: { td, wrapEl, nameEl, compactEl } }; return { td, refs: { td, wrapEl, nameEl } };
}, },
updateCell: (refs, st, ctx) => { updateCell: (refs, st, ctx) => {
const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
patchText(refs.nameEl, modelDisplay.baseText); patchText(refs.nameEl, modelDisplay.baseText);
const suffix = modelDisplay.compactionSuffix || '';
patchText(refs.compactEl, suffix);
patchAttr(refs.compactEl, 'hidden', !suffix);
patchAttr(refs.td, 'title', modelDisplay.title); patchAttr(refs.td, 'title', modelDisplay.title);
}, },
}, },
+65 -9
View File
@@ -23,6 +23,7 @@ import {
normalizeClientFontScale, normalizeClientFontScale,
normalizeClientModernUi, normalizeClientModernUi,
normalizeClientThemeAccent, normalizeClientThemeAccent,
resolveSettingsModernUi,
} from '../core/appearance.js'; } from '../core/appearance.js';
import { import {
DEFAULT_HOVER_MODULES, DEFAULT_HOVER_MODULES,
@@ -53,7 +54,12 @@ import {
normalizeWindowMountMode, normalizeWindowMountMode,
parseStepTokenComboSegments, parseStepTokenComboSegments,
} from '../../shared/settings-normalization.mjs'; } from '../../shared/settings-normalization.mjs';
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; import {
LOCAL_ENDPOINT_ID,
WINDOW_BRIDGE_ENDPOINT_KEY,
WINDOW_BRIDGE_ROUTE_KEY,
readInjectedWindowBridge,
} from '../../shared/window-bridge-protocol.mjs';
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -149,6 +155,7 @@ let activeBundleVersion = 0;
let latestRequestSeq = 0; let latestRequestSeq = 0;
let latestConsumptionReqSeq = 0; let latestConsumptionReqSeq = 0;
let latestConversationSwitchSeq = 0; let latestConversationSwitchSeq = 0;
let endpointSwitchEpoch = 0;
let activeForceCount = 0; let activeForceCount = 0;
let consecutivePollFailures = 0; let consecutivePollFailures = 0;
let inFlightTelemetryPoll = null; let inFlightTelemetryPoll = null;
@@ -201,10 +208,11 @@ export function clearConversationViewCache() {
function buildConsumptionScopeSig(payload) { function buildConsumptionScopeSig(payload) {
if (!payload || typeof payload !== 'object') return ''; if (!payload || typeof payload !== 'object') return '';
const ep = payload.endpoint || {};
const acct = payload.account || {}; const acct = payload.account || {};
const set = payload.settings || {}; const set = payload.settings || {};
const cloud = payload.cloudStatus || {}; const cloud = payload.cloudStatus || {};
return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
} }
function syncConsumptionCacheScope(payload) { function syncConsumptionCacheScope(payload) {
@@ -471,11 +479,18 @@ export function isEquivalentTelemetry(prev, next) {
const pSet = prev.settings; const pSet = prev.settings;
const nSet = next.settings; const nSet = next.settings;
if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; if ((pSet?.language ?? 'auto') !== (nSet?.language ?? 'auto')) return false;
if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false;
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; if (resolveSettingsModernUi(pSet) !== resolveSettingsModernUi(nSet)) return false;
if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false;
if (
(prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) ||
Boolean(prev.endpoint?.isRemote) !== Boolean(next.endpoint?.isRemote) ||
(prev.endpoint?.label || '') !== (next.endpoint?.label || '')
) {
return false;
}
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
return false; return false;
} }
@@ -1014,6 +1029,33 @@ export function isEquivalentTelemetry(prev, next) {
return true; return true;
} }
export function resetTelemetryForEndpointSwitch() {
endpointSwitchEpoch += 1;
latestRequestSeq += 1;
latestConsumptionReqSeq += 1;
latestConversationSwitchSeq += 1;
lastReceivedSteps = null;
inFlightTelemetryPoll = null;
consecutivePollFailures = 0;
consumptionCacheScopeSig = '';
abortSidecarApiKey('telemetry-poll');
abortSidecarApiKey('telemetry-force');
abortSidecarApiKey('consumption-range');
abortSidecarApiKey('consumption-presets');
abortSidecarApiKey('conversation-switch');
clearConsumptionRangeCache();
clearConversationViewCache();
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
telemetryStore.setState({
selectedConversationId: '',
telemetry: null,
syncState: 'idle',
});
}
export async function fetchTelemetry({ force = false } = {}) { export async function fetchTelemetry({ force = false } = {}) {
if (!force && activeForceCount > 0) { if (!force && activeForceCount > 0) {
return telemetryStore.getState().telemetry; return telemetryStore.getState().telemetry;
@@ -1049,11 +1091,17 @@ export async function fetchTelemetry({ force = false } = {}) {
} }
const query = params.toString(); const query = params.toString();
const bridge = overlay ? getWindowBridgeConfig() : null; const bridge = overlay ? getWindowBridgeConfig() : null;
const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID;
const existing = inFlightTelemetryPoll; const existing = inFlightTelemetryPoll;
if (existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token) { if (
existing?.query === query &&
existing.port === bridge?.port &&
existing.token === bridge?.token &&
existing.endpointId === endpointId
) {
return existing.promise; return existing.promise;
} }
const poll = { query, port: bridge?.port, token: bridge?.token, promise: null }; const poll = { query, port: bridge?.port, token: bridge?.token, endpointId, promise: null };
poll.promise = requestTelemetry(params, false).finally(() => { poll.promise = requestTelemetry(params, false).finally(() => {
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null; if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
}); });
@@ -1240,6 +1288,7 @@ async function fetchConsumptionRangeSlice({
customStartMs = 0, customStartMs = 0,
customEndMs = 0, customEndMs = 0,
} = {}) { } = {}) {
const reqEpoch = endpointSwitchEpoch;
const reqSeq = ++latestConsumptionReqSeq; const reqSeq = ++latestConsumptionReqSeq;
const targetRange = String(range || 'today'); const targetRange = String(range || 'today');
const current = telemetryStore.getState(); const current = telemetryStore.getState();
@@ -1258,7 +1307,7 @@ async function fetchConsumptionRangeSlice({
method: 'GET', method: 'GET',
abortKey: 'consumption-range', abortKey: 'consumption-range',
}); });
if (!payload || typeof payload !== 'object') return null; if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
if (payload.scope === 'consumption' && payload.consumption) { if (payload.scope === 'consumption' && payload.consumption) {
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
@@ -1385,13 +1434,14 @@ export async function selectConversation(
params.set('stepRevision', cachedSteps?.revision || ''); params.set('stepRevision', cachedSteps?.revision || '');
params.set('scope', 'conversation'); params.set('scope', 'conversation');
const reqEpoch = endpointSwitchEpoch;
const reqSettingsRev = settingsRevision; const reqSettingsRev = settingsRevision;
try { try {
const payload = await callSidecarApi(`/api/telemetry?${params}`, { const payload = await callSidecarApi(`/api/telemetry?${params}`, {
method: 'GET', method: 'GET',
abortKey: 'conversation-switch', abortKey: 'conversation-switch',
}); });
if (!payload || typeof payload !== 'object') return null; if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
if (switchSeq !== latestConversationSwitchSeq) return payload; if (switchSeq !== latestConversationSwitchSeq) return payload;
const latestSt = telemetryStore.getState(); const latestSt = telemetryStore.getState();
@@ -1550,11 +1600,13 @@ export function prefetchConsumptionPresets() {
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
params.set('scope', 'consumption-presets'); params.set('scope', 'consumption-presets');
const reqEpoch = endpointSwitchEpoch;
const task = callSidecarApi(`/api/telemetry?${params}`, { const task = callSidecarApi(`/api/telemetry?${params}`, {
method: 'GET', method: 'GET',
abortKey: 'consumption-presets', abortKey: 'consumption-presets',
}) })
.then((payload) => { .then((payload) => {
if (reqEpoch !== endpointSwitchEpoch) return false;
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
const rev = Number(payload.usageRevision || currentRev || 0); const rev = Number(payload.usageRevision || currentRev || 0);
for (const [rangeKey, entry] of Object.entries(payload.ranges)) { for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
@@ -1594,7 +1646,11 @@ export async function saveSettingsPatch(patch) {
if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) {
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
} }
if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { if (Object.prototype.hasOwnProperty.call(safePatch, 'modernUi')) {
const normModern = normalizeClientModernUi(safePatch.modernUi);
safePatch.modernUi = normModern;
safePatch.experimentalModernUi = normModern;
} else if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) {
safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi);
} }
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
+49 -3
View File
@@ -31,8 +31,8 @@
.steps-inline-scope-select .select-menu, .steps-inline-scope-select .select-menu,
.steps-inline-model-select .select-menu { .steps-inline-model-select .select-menu {
left: 0; left: auto;
right: auto; right: 0;
min-width: 220px; min-width: 220px;
max-width: min(320px, calc(100vw - 24px)); max-width: min(320px, calc(100vw - 24px));
} }
@@ -52,6 +52,23 @@
flex-shrink: 0; flex-shrink: 0;
} }
.endpoint-ssh-badge {
display: inline-flex;
align-items: center;
padding: 2px 5px;
font-family: var(--font-mono);
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.2;
letter-spacing: 0.02em;
border-radius: var(--radius-xs);
border: 1px solid var(--accent-primary-border);
background: var(--accent-primary-soft);
color: var(--accent-primary);
white-space: nowrap;
flex-shrink: 0;
}
.status-tag { .status-tag {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -289,7 +306,15 @@
font-size: var(--fs-base); font-size: var(--fs-base);
cursor: pointer; cursor: pointer;
text-align: left; text-align: left;
transition: background-color var(--dur-instant) var(--ease-fast); transition:
background-color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast),
box-shadow var(--dur-instant) var(--ease-fast);
}
.select-trigger .svg-icon {
flex-shrink: 0;
color: var(--text-muted);
} }
.select-trigger:hover, .select-trigger:hover,
@@ -297,6 +322,27 @@
background: var(--surface-hover); background: var(--surface-hover);
} }
.form-row > .custom-select > .select-trigger {
min-height: calc(28px * var(--ui-font-scale, 1));
padding: 3px 12px;
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
border: none;
border-radius: var(--radius-pill);
}
.form-row > .custom-select > .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.form-row > .custom-select.is-open > .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
}
.form-row > .custom-select > .select-trigger:disabled {
opacity: 0.52;
cursor: not-allowed;
}
.select-label { .select-label {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
+43 -6
View File
@@ -21,6 +21,9 @@
--modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%);
--modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent);
--modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent));
--modern-pill-select-bg: color-mix(in srgb, var(--text-primary) 8.5%, var(--modern-surface-card));
--modern-pill-select-hover: color-mix(in srgb, var(--text-primary) 12.5%, var(--modern-surface-card));
--modern-pill-select-open: color-mix(in srgb, var(--text-primary) 15%, var(--modern-surface-card));
--modern-card-shadow: none; --modern-card-shadow: none;
--modern-nav-track-bg: var(--modern-surface-card); --modern-nav-track-bg: var(--modern-surface-card);
--modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent);
@@ -42,6 +45,9 @@
--modern-surface-card: #ffffff; --modern-surface-card: #ffffff;
--modern-surface-subtle: hsl(216 42% 97.2%); --modern-surface-subtle: hsl(216 42% 97.2%);
--modern-surface-hover: hsl(216 56% 94.4%); --modern-surface-hover: hsl(216 56% 94.4%);
--modern-pill-select-bg: hsl(220 14% 94%);
--modern-pill-select-hover: hsl(220 14% 90.5%);
--modern-pill-select-open: hsl(220 14% 88.5%);
--modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028);
--modern-nav-track-bg: hsl(216 28% 94.2%); --modern-nav-track-bg: hsl(216 28% 94.2%);
--modern-inline-track-bg: hsl(216 32% 96.2%); --modern-inline-track-bg: hsl(216 32% 96.2%);
@@ -249,6 +255,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
[data-modern-ui="true"] .status-tag.state-running, [data-modern-ui="true"] .status-tag.state-running,
[data-modern-ui="true"] .status-tag.state-synced, [data-modern-ui="true"] .status-tag.state-synced,
[data-modern-ui="true"] .status-tag.state-warn, [data-modern-ui="true"] .status-tag.state-warn,
[data-modern-ui="true"] .endpoint-ssh-badge,
[data-modern-ui="true"] .update-badge-btn, [data-modern-ui="true"] .update-badge-btn,
[data-modern-ui="true"] .wm-update-btn, [data-modern-ui="true"] .wm-update-btn,
[data-modern-ui="true"] .wm-hover-update-bar, [data-modern-ui="true"] .wm-hover-update-bar,
@@ -463,10 +470,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
} }
[data-modern-ui="true"] .trend-tip-sub, [data-modern-ui="true"] .trend-tip-sub,
[data-modern-ui="true"] .trend-tip-anomaly, [data-modern-ui="true"] .trend-tip-cost {
background: transparent;
}
[data-modern-ui="true"] .cons-pop-models { [data-modern-ui="true"] .cons-pop-models {
border-top: none; border-top-color: var(--modern-surface-hover);
padding-top: 3px;
} }
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
@@ -524,6 +533,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
background: var(--modern-surface-hover); background: var(--modern-surface-hover);
} }
[data-modern-ui="true"] .data-table tbody tr.is-compaction,
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-compaction:nth-child(even),
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction {
background: color-mix(in srgb, var(--accent-primary) 12%, transparent);
}
[data-modern-ui="true"] .data-table tbody tr.is-compaction:hover,
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction:hover {
background: color-mix(in srgb, var(--accent-primary) 19%, transparent);
}
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, [data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn,
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), [data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even),
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { [data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn {
@@ -546,11 +566,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
background: color-mix(in srgb, var(--metric-danger) 21%, transparent); background: color-mix(in srgb, var(--metric-danger) 21%, transparent);
} }
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { [data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
border: none; border: none;
background: var(--modern-surface-subtle); box-shadow: none;
border-radius: var(--radius-pill);
background: var(--modern-pill-select-bg);
}
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover {
background: var(--modern-pill-select-hover);
}
[data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger {
background: var(--modern-pill-select-open);
} }
[data-modern-ui="true"] .sstep-card, [data-modern-ui="true"] .sstep-card,
@@ -666,12 +703,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border: none; border: none;
background: var(--modern-surface-card); background: var(--modern-surface-card);
box-shadow: var(--shadow-popover); box-shadow: var(--shadow-popover);
animation: anim-modern-pop-in 150ms var(--ease-modern); animation: anim-modern-tip-fade 120ms var(--ease-modern);
} }
[data-modern-ui="true"] .select-menu.is-above, [data-modern-ui="true"] .select-menu.is-above,
[data-modern-ui="true"] .dt-popover.is-above { [data-modern-ui="true"] .dt-popover.is-above {
animation-name: anim-modern-pop-in-up; transform-origin: bottom right;
} }
[data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .trend-tooltip,
+90 -33
View File
@@ -211,12 +211,6 @@
white-space: nowrap; white-space: nowrap;
} }
.cons-title-model-dot {
width: 7px;
height: 7px;
flex-shrink: 0;
}
.cons-row-metrics { .cons-row-metrics {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -349,9 +343,9 @@
left: var(--tip-x, 50%); left: var(--tip-x, 50%);
transform: translateX(var(--tip-shift, -50%)); transform: translateX(var(--tip-shift, -50%));
width: max-content; width: max-content;
min-width: 196px; min-width: 224px;
max-width: min(320px, calc(100% - 8px)); max-width: min(316px, calc(100% - 8px));
padding: 6px 10px; padding: 9px 11px;
background: var(--surface-panel); background: var(--surface-panel);
border: 1px solid var(--border-strong); border: 1px solid var(--border-strong);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
@@ -360,27 +354,29 @@
z-index: 25; z-index: 25;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 2px; gap: 6px;
} }
.trend-tip-head { .trend-tip-head {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 10px; gap: 12px;
font-size: var(--fs-sm); font-size: var(--fs-xs);
line-height: 1.25;
color: var(--text-secondary); color: var(--text-secondary);
} }
.trend-tip-time { .trend-tip-time {
font-weight: 600; font-weight: 500;
color: var(--text-primary); color: var(--text-secondary);
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
} }
.trend-tip-calls { .trend-tip-calls {
font-size: var(--fs-xs); font-size: var(--fs-xs);
font-weight: 500;
color: var(--text-muted); color: var(--text-muted);
white-space: nowrap; white-space: nowrap;
max-width: 190px; max-width: 190px;
@@ -390,14 +386,17 @@
.trend-tip-main { .trend-tip-main {
display: flex; display: flex;
align-items: baseline; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 10px;
margin-top: -2px;
} }
.trend-tip-tokens { .trend-tip-tokens {
font-size: var(--fs-base); font-size: var(--fs-lg);
font-weight: 700; font-weight: 700;
line-height: 1.18;
letter-spacing: -0.02em;
color: var(--accent-primary); color: var(--accent-primary);
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
@@ -406,20 +405,66 @@
.trend-tip-cost { .trend-tip-cost {
font-size: var(--fs-md); font-size: var(--fs-md);
font-weight: 600; font-weight: 600;
line-height: 1.2;
padding: 0;
border-radius: 0;
color: var(--text-primary); color: var(--text-primary);
background: transparent;
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
} }
.trend-tip-cost:empty {
display: none;
}
.trend-tip-sub { .trend-tip-sub {
padding: 2px 0;
border: none;
border-radius: 0;
background: transparent;
font-size: var(--fs-xs); font-size: var(--fs-xs);
line-height: 1.3;
color: var(--text-secondary); color: var(--text-secondary);
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
border-top: 1px solid var(--border-hairline); }
padding-top: 2px;
margin-top: 1px; .trend-tip-sub[hidden] {
display: none !important;
}
.trend-tip-sub.is-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
padding: 2px 0;
white-space: normal;
overflow: visible;
}
.trend-tip-stat {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.trend-tip-stat-label {
font-size: var(--fs-2xs);
font-weight: 500;
line-height: 1.2;
color: var(--text-muted);
white-space: nowrap;
}
.trend-tip-stat-val {
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.25;
color: var(--text-primary);
white-space: nowrap;
} }
.trend-tooltip.is-line-low { .trend-tooltip.is-line-low {
@@ -807,9 +852,9 @@
left: var(--pop-x, 8px); left: var(--pop-x, 8px);
top: var(--pop-y, 8px); top: var(--pop-y, 8px);
width: max-content; width: max-content;
min-width: 196px; min-width: 224px;
max-width: min(310px, calc(100% - 16px)); max-width: min(316px, calc(100% - 16px));
padding: 6px 10px; padding: 9px 11px;
background: var(--surface-panel); background: var(--surface-panel);
border: 1px solid var(--border-strong); border: 1px solid var(--border-strong);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
@@ -818,24 +863,34 @@
z-index: 30; z-index: 30;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 3px; gap: 6px;
} }
.cons-pop-models { .cons-pop-models {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 3px; gap: 4px;
border-top: 1px solid var(--border-hairline); border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent);
padding-top: 4px; padding-top: 6px;
margin-top: 2px; margin-top: 1px;
}
.cons-pop-models[hidden] {
display: none !important;
}
.trend-tip-sub:not([hidden]) + .cons-pop-models {
border-top: none;
padding-top: 2px;
margin-top: 0;
} }
.cons-pop-model-row { .cons-pop-model-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 10px;
font-size: var(--fs-sm); font-size: var(--fs-xs);
line-height: 1.3; line-height: 1.3;
} }
@@ -849,6 +904,7 @@
.cons-pop-model-name { .cons-pop-model-name {
max-width: 156px; max-width: 156px;
font-weight: 500;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@@ -871,10 +927,11 @@
} }
.cons-pop-model-pct { .cons-pop-model-pct {
min-width: 40px; min-width: 38px;
text-align: right; text-align: right;
font-weight: 600; font-size: var(--fs-xs);
color: var(--text-primary); font-weight: 500;
color: var(--text-secondary);
} }
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
+113 -44
View File
@@ -19,6 +19,14 @@
background: var(--surface-panel); background: var(--surface-panel);
} }
.panel > .table-scroll-host {
margin-right: calc(-1 * var(--space-5) + 2px);
}
.panel > .table-scroll-host > .custom-scroll-content {
padding-right: calc(var(--space-5) - 2px);
}
.table-viewport { .table-viewport {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
@@ -127,57 +135,69 @@
flex: 0 1 auto; flex: 0 1 auto;
} }
.step-model-compact {
flex-shrink: 0;
white-space: nowrap;
color: var(--accent-primary);
font-weight: 500;
}
.step-model-compact[hidden] {
display: none !important;
}
.steps-panel-header { .steps-panel-header {
flex-wrap: wrap; flex-wrap: wrap;
row-gap: 6px; row-gap: 6px;
} }
.steps-panel-title {
flex: 0 0 auto;
}
.steps-header-controls { .steps-header-controls {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end; justify-content: space-between;
gap: 6px; flex-wrap: wrap;
flex: 1 1 280px; gap: 6px 8px;
flex: 1 1 100%;
min-width: 0; min-width: 0;
} }
.steps-header-controls .segmented { .steps-header-controls .segmented {
flex-shrink: 0; flex: 0 0 auto;
}
.steps-header-filters {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 6px;
margin-left: auto;
flex: 1 1 156px;
min-width: 0;
max-width: 100%;
}
.steps-header-filters[hidden] {
display: none !important;
} }
.steps-inline-scope-select, .steps-inline-scope-select,
.steps-inline-model-select { .steps-inline-model-select {
flex: 0 1 165px; flex: 0 1 auto;
min-width: 72px; min-width: 0;
max-width: 175px; max-width: 148px;
} }
.steps-inline-scope-select .select-trigger, .steps-inline-scope-select .select-trigger,
.steps-inline-model-select .select-trigger { .steps-inline-model-select .select-trigger {
min-height: calc(22px * var(--ui-font-scale, 1)); min-height: calc(25px * var(--ui-font-scale, 1));
height: auto; height: auto;
padding: 2px 6px; padding: 2px 10px;
gap: 4px; gap: 6px;
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
font-size: var(--fs-md); font-size: var(--fs-md);
border: 1px solid var(--border-hairline); border: none;
background: var(--surface-subtle); border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
}
.steps-inline-scope-select .select-trigger:hover,
.steps-inline-model-select .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.steps-inline-scope-select.is-open .select-trigger,
.steps-inline-model-select.is-open .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
} }
/* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */ /* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */
@@ -295,7 +315,24 @@
animation: anim-popover-in var(--dur-instant) var(--ease-fast); animation: anim-popover-in var(--dur-instant) var(--ease-fast);
} }
/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ /* --- 2.6 单步压缩 / 异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */
.data-table tbody tr.is-compaction {
background: color-mix(in srgb, var(--accent-primary) 11%, transparent);
}
.data-table tbody tr.is-compaction:hover {
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
}
.data-table tbody tr.is-compaction td:first-child {
box-shadow: inset 2px 0 0 var(--accent-primary);
}
.data-table tbody tr.is-compaction td:first-child > span:not(.agent-badge):not(.turn-rail) {
color: var(--accent-primary);
font-weight: 600;
}
.data-table tbody tr.is-anomaly-warn { .data-table tbody tr.is-anomaly-warn {
background: color-mix(in srgb, var(--metric-warn) 11%, transparent); background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
} }
@@ -399,6 +436,10 @@
border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong));
} }
.step-anomaly-tip.is-compaction {
border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong));
}
.step-anomaly-tip[hidden], .step-anomaly-tip[hidden],
.step-anomaly-tip-sub[hidden], .step-anomaly-tip-sub[hidden],
.step-anomaly-tip-list[hidden], .step-anomaly-tip-list[hidden],
@@ -423,6 +464,10 @@
color: var(--metric-danger); color: var(--metric-danger);
} }
.step-anomaly-tip.is-compaction .step-anomaly-tip-title {
color: var(--accent-primary);
}
.step-anomaly-tip-sub { .step-anomaly-tip-sub {
font-size: var(--fs-xs); font-size: var(--fs-xs);
color: var(--text-secondary); color: var(--text-secondary);
@@ -542,7 +587,9 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--space-3); gap: var(--space-3);
padding: var(--space-3) 0 2px; padding-top: var(--space-3);
padding-bottom: 2px;
padding-left: 0;
} }
.sstep-card { .sstep-card {
@@ -599,15 +646,24 @@
} }
.sstep-fit-model-select .select-trigger { .sstep-fit-model-select .select-trigger {
min-height: calc(22px * var(--ui-font-scale, 1)); min-height: calc(24px * var(--ui-font-scale, 1));
height: auto; height: auto;
padding: 2px 6px; padding: 2px 10px;
gap: 4px; gap: 6px;
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
font-size: var(--fs-sm); font-size: var(--fs-sm);
border: 1px solid var(--border-hairline); border: none;
background: var(--surface-subtle); border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
}
.sstep-fit-model-select .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.sstep-fit-model-select.is-open .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
} }
.sstep-chart-wrap { .sstep-chart-wrap {
@@ -783,9 +839,11 @@
} }
.trend-tip-anomaly { .trend-tip-anomaly {
margin-top: 3px; margin-top: 0;
padding-top: 3px; padding: 4px 8px;
border-top: 1px solid var(--border-hairline); border: none;
border-radius: var(--radius-xs);
background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
font-size: var(--fs-xs); font-size: var(--fs-xs);
font-weight: 600; font-weight: 600;
color: var(--metric-warn); color: var(--metric-warn);
@@ -794,6 +852,7 @@
.trend-tip-anomaly.is-danger { .trend-tip-anomaly.is-danger {
color: var(--metric-danger); color: var(--metric-danger);
background: color-mix(in srgb, var(--metric-danger) 12%, transparent);
} }
.trend-tip-anomaly[hidden] { .trend-tip-anomaly[hidden] {
@@ -1034,17 +1093,27 @@
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
flex-wrap: wrap; flex-wrap: wrap;
gap: 2px 10px; gap: 4px 10px;
font-size: var(--fs-sm); font-size: var(--fs-md);
color: var(--text-secondary); color: var(--text-secondary);
} }
.smodel-perf {
color: var(--text-secondary);
white-space: nowrap;
}
.smodel-split { .smodel-split {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 10px;
color: var(--text-secondary);
}
.smodel-split strong {
color: var(--text-primary);
font-weight: 600;
}
.smodel-perf {
margin-left: auto;
font-size: var(--fs-sm);
color: var(--text-muted); color: var(--text-muted);
white-space: nowrap; white-space: nowrap;
} }
+48 -27
View File
@@ -62,6 +62,22 @@ function getConsumptionTimeRangeOptions() {
]; ];
} }
function floorToStartOfMinuteMs(ms) {
const n = Number(ms);
if (!(n > 0)) return 0;
const d = new Date(n);
d.setSeconds(0, 0);
return d.getTime();
}
function ceilToEndOfMinuteMs(ms) {
const n = Number(ms);
if (!(n > 0)) return 0;
const d = new Date(n);
d.setSeconds(59, 999);
return d.getTime();
}
export const ConsumptionView = defineComponent({ export const ConsumptionView = defineComponent({
name: 'ConsumptionView', name: 'ConsumptionView',
setup({ onCleanup }) { setup({ onCleanup }) {
@@ -69,6 +85,7 @@ export const ConsumptionView = defineComponent({
let draftStartMs = telemetryStore.getState().customStartMs; let draftStartMs = telemetryStore.getState().customStartMs;
let draftEndMs = telemetryStore.getState().customEndMs; let draftEndMs = telemetryStore.getState().customEndMs;
let hasUncommittedCustomDraft = false; let hasUncommittedCustomDraft = false;
let hasCommittedCustomRange = false;
const timeFilterSwitch = SegmentedControl({ const timeFilterSwitch = SegmentedControl({
ariaLabel: t('cons.rangeAria'), ariaLabel: t('cons.rangeAria'),
@@ -77,6 +94,19 @@ export const ConsumptionView = defineComponent({
onUpdateModelValue: (nextRange) => { onUpdateModelValue: (nextRange) => {
if (nextRange === 'custom') { if (nextRange === 'custom') {
const st = telemetryStore.getState(); const st = telemetryStore.getState();
if (!hasCommittedCustomRange && st.selectedTimeRange !== 'custom') {
const nowMs = Date.now();
draftStartMs = floorToStartOfMinuteMs(nowMs - 24 * 3600 * 1000);
draftEndMs = ceilToEndOfMinuteMs(nowMs);
hasUncommittedCustomDraft = false;
startPicker.setValue(draftStartMs);
endPicker.setValue(draftEndMs);
selectConsumptionTimeRange('custom', {
customStartMs: draftStartMs,
customEndMs: draftEndMs,
});
return;
}
draftStartMs = st.customStartMs; draftStartMs = st.customStartMs;
draftEndMs = st.customEndMs; draftEndMs = st.customEndMs;
hasUncommittedCustomDraft = false; hasUncommittedCustomDraft = false;
@@ -117,11 +147,14 @@ export const ConsumptionView = defineComponent({
onClick: () => { onClick: () => {
const sMs = Number(draftStartMs || 0); const sMs = Number(draftStartMs || 0);
const eMs = Number(draftEndMs || 0); const eMs = Number(draftEndMs || 0);
const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; const rawMinMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs;
const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; const rawMaxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs;
const minMs = floorToStartOfMinuteMs(rawMinMs);
const maxMs = ceilToEndOfMinuteMs(rawMaxMs);
draftStartMs = minMs; draftStartMs = minMs;
draftEndMs = maxMs; draftEndMs = maxMs;
hasUncommittedCustomDraft = false; hasUncommittedCustomDraft = false;
hasCommittedCustomRange = true;
startPicker.setValue(minMs); startPicker.setValue(minMs);
endPicker.setValue(maxMs); endPicker.setValue(maxMs);
selectConsumptionTimeRange('custom', { selectConsumptionTimeRange('custom', {
@@ -586,12 +619,11 @@ export const ConsumptionView = defineComponent({
} }
/** /**
* 创建热门模型单行 DOM 结构(模型名称后附专属颜色圆点 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 * 创建热门模型单行 DOM 结构(模型名称 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。
*/ */
function createBreakdownItemRow() { function createBreakdownItemRow() {
const nameTextEl = h('span', { className: 'cons-row-title-text' }); const nameTextEl = h('span', { className: 'cons-row-title-text' });
const modelDotEl = h('span', { className: 'dot-swatch cons-model-dot cons-title-model-dot' }); const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]);
const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl, modelDotEl]);
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' });
@@ -630,16 +662,16 @@ export const ConsumptionView = defineComponent({
cacheLbl, cacheLbl,
cacheVal, cacheVal,
]), ]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
outLbl,
outVal,
]),
h('span', { className: 'legend-left' }, [ h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-thinking' }), h('span', { className: 'dot-swatch seg-thinking' }),
thinkLbl, thinkLbl,
thinkVal, thinkVal,
]), ]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
outLbl,
outVal,
]),
h('span', { className: 'legend-left' }, [ h('span', { className: 'legend-left' }, [
callsLbl, callsLbl,
callsVal, callsVal,
@@ -652,7 +684,6 @@ export const ConsumptionView = defineComponent({
refs: { refs: {
nameEl, nameEl,
nameTextEl, nameTextEl,
modelDotEl,
pctBadge, pctBadge,
totalTokEl, totalTokEl,
costEl, costEl,
@@ -672,9 +703,9 @@ export const ConsumptionView = defineComponent({
} }
/** /**
* 增量更新热门模型单行的指标文本、名称后的专属颜色圆点与按总占比缩放的 4 段比例条宽度。 * 增量更新热门模型单行的指标文本与按总占比缩放的 4 段比例条宽度。
*/ */
function updateBreakdownItemRow(refs, item, grandTotalTokens, modelColor = '') { function updateBreakdownItemRow(refs, item, grandTotalTokens) {
patchText(refs.inLbl, t('cons.footInput')); patchText(refs.inLbl, t('cons.footInput'));
patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.cacheLbl, t('cons.footCache'));
patchText(refs.outLbl, t('cons.footOutput')); patchText(refs.outLbl, t('cons.footOutput'));
@@ -683,10 +714,6 @@ export const ConsumptionView = defineComponent({
const displayLabel = item.label || item.name || item.shortName || '—'; const displayLabel = item.label || item.name || item.shortName || '—';
patchText(refs.nameTextEl, displayLabel); patchText(refs.nameTextEl, displayLabel);
patchAttr(refs.nameEl, 'title', item.title || displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel);
patchAttr(refs.modelDotEl, 'hidden', !modelColor);
if (modelColor) {
patchStyleVar(refs.modelDotEl, '--dot-color', modelColor);
}
const total = Number(item.totalTokens || 0); const total = Number(item.totalTokens || 0);
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
const scaleRatio = const scaleRatio =
@@ -1169,23 +1196,17 @@ export const ConsumptionView = defineComponent({
}); });
trendChart.update(enrichedTrendSeries); trendChart.update(enrichedTrendSeries);
// 3. 同步热门模型列表(名称后带专属颜色圆点 + 4 段条按总占比缩放长度) // 3. 同步热门模型列表(4 段条按总占比缩放长度)
patchKeyedList(modelsListEl, models, { patchKeyedList(modelsListEl, models, {
keyFn: (m) => m.displayText || m.label || m.shortName, keyFn: (m) => m.displayText || m.label || m.shortName,
sigFn: (m) => { sigFn: (m) =>
const seed = getCanonicalModelColorSeed(m); `${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed);
return `${localeSig}:${m.displayText}:${m.displayTitle}:${color}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`;
},
createRow: createBreakdownItemRow, createRow: createBreakdownItemRow,
updateRow: (refs, m) => { updateRow: (refs, m) => {
const seed = getCanonicalModelColorSeed(m);
const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed);
updateBreakdownItemRow( updateBreakdownItemRow(
refs, refs,
{ ...m, label: m.displayText, title: m.displayTitle }, { ...m, label: m.displayText, title: m.displayTitle },
modelsTotalTok, modelsTotalTok
color
); );
}, },
}); });
+59 -22
View File
@@ -5,6 +5,7 @@
* - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。 * - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。
*/ */
import { resolveSettingsModernUi } from '../core/appearance.js';
import { defineComponent } from '../core/component.js'; import { defineComponent } from '../core/component.js';
import { import {
h, h,
@@ -20,6 +21,7 @@ import {
formatMetric, formatMetric,
formatSpeedMetric, formatSpeedMetric,
formatTokens, formatTokens,
formatTokensPrecise,
formatUsd, formatUsd,
mergeModelsByDisplayName, mergeModelsByDisplayName,
normalizeModelDisplayMode, normalizeModelDisplayMode,
@@ -27,7 +29,6 @@ import {
resolveModelAnomalySummary, resolveModelAnomalySummary,
resolveModelDisplayInfo, resolveModelDisplayInfo,
} from '../core/formatters.js'; } from '../core/formatters.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js'; import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
import { import {
formatAgentLabel, formatAgentLabel,
@@ -477,7 +478,11 @@ export const StepsDetailView = defineComponent({
}); });
modelsScroll.el.setAttribute('hidden', ''); modelsScroll.el.setAttribute('hidden', '');
const panelTitleTextEl = h('span', { text: t('steps.title') }); const headerFiltersEl = h('div', { className: 'steps-header-filters', hidden: true }, [
inlineScopeSelect.el,
stepsModelSelect.el,
]);
const panelEl = h( const panelEl = h(
'section', 'section',
{ {
@@ -486,14 +491,9 @@ export const StepsDetailView = defineComponent({
}, },
[ [
h('div', { className: 'panel-header steps-panel-header' }, [ h('div', { className: 'panel-header steps-panel-header' }, [
h('span', { className: 'panel-title steps-panel-title' }, [
createSvgIcon('table', { size: 13 }),
panelTitleTextEl,
]),
h('div', { className: 'steps-header-controls' }, [ h('div', { className: 'steps-header-controls' }, [
inlineScopeSelect.el,
stepsModelSelect.el,
subTabSwitch.el, subTabSwitch.el,
headerFiltersEl,
]), ]),
]), ]),
anomalyFilterBarEl, anomalyFilterBarEl,
@@ -566,7 +566,6 @@ export const StepsDetailView = defineComponent({
} }
function refreshStaticLocaleLabels() { function refreshStaticLocaleLabels() {
patchText(panelTitleTextEl, t('steps.title'));
patchText(lineTitleEl, t('steps.lineTitle')); patchText(lineTitleEl, t('steps.lineTitle'));
patchText(fitTitleEl, t('steps.fitTitle')); patchText(fitTitleEl, t('steps.fitTitle'));
patchText(modelsSectionTitleEl, t('steps.modelsTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle'));
@@ -786,6 +785,7 @@ export const StepsDetailView = defineComponent({
); );
const showStepsModelFilter = uiSt.stepsSubTab === 'steps' && hasMultipleModels; const showStepsModelFilter = uiSt.stepsSubTab === 'steps' && hasMultipleModels;
patchAttr(stepsModelSelect.el, 'hidden', !showStepsModelFilter); patchAttr(stepsModelSelect.el, 'hidden', !showStepsModelFilter);
patchAttr(headerFiltersEl, 'hidden', !hasSubagents && !showStepsModelFilter);
if (hasMultipleModels) { if (hasMultipleModels) {
stepsModelSelect.setProps({ stepsModelSelect.setProps({
modelValue: selectedTableModels, modelValue: selectedTableModels,
@@ -1152,8 +1152,37 @@ export const StepsDetailView = defineComponent({
const segBar = createFourSegmentBar(); const segBar = createFourSegmentBar();
segBar.el.classList.add('smodel-seg-bar'); segBar.el.classList.add('smodel-seg-bar');
const inLbl = h('span', { text: t('cons.footInput') });
const cacheLbl = h('span', { text: t('cons.footCache') });
const thinkLbl = h('span', { text: t('cons.footThinking') });
const outLbl = h('span', { text: t('cons.footOutput') });
const inVal = h('strong', { className: 'text-mono' });
const cacheVal = h('strong', { className: 'text-mono' });
const thinkVal = h('strong', { className: 'text-mono' });
const outVal = h('strong', { className: 'text-mono' });
const splitEl = h('div', { className: 'smodel-split' }, [
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-input' }),
inLbl,
inVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-cached' }),
cacheLbl,
cacheVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-thinking' }),
thinkLbl,
thinkVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
outLbl,
outVal,
]),
]);
const perfEl = h('span', { className: 'smodel-perf text-mono' }); const perfEl = h('span', { className: 'smodel-perf text-mono' });
const splitEl = h('span', { className: 'smodel-split text-mono' });
const cardEl = h('div', { className: 'smodel-card' }, [ const cardEl = h('div', { className: 'smodel-card' }, [
h('div', { className: 'smodel-head' }, [ h('div', { className: 'smodel-head' }, [
@@ -1161,7 +1190,7 @@ export const StepsDetailView = defineComponent({
h('div', { className: 'smodel-totals' }, [tokEl, costEl]), h('div', { className: 'smodel-totals' }, [tokEl, costEl]),
]), ]),
segBar.el, segBar.el,
h('div', { className: 'smodel-foot' }, [perfEl, splitEl]), h('div', { className: 'smodel-foot' }, [splitEl, perfEl]),
]); ]);
return { return {
@@ -1175,6 +1204,14 @@ export const StepsDetailView = defineComponent({
segBar, segBar,
perfEl, perfEl,
splitEl, splitEl,
inLbl,
cacheLbl,
thinkLbl,
outLbl,
inVal,
cacheVal,
thinkVal,
outVal,
cardTitle: '', cardTitle: '',
isHoveringAnomaly: false, isHoveringAnomaly: false,
}, },
@@ -1245,7 +1282,7 @@ export const StepsDetailView = defineComponent({
? Math.max(0, Number(m.responseTokens)) ? Math.max(0, Number(m.responseTokens))
: Math.max(0, outTok - thinkTok); : Math.max(0, outTok - thinkTok);
patchText(refs.tokEl, formatTokens(m.totalTokens || 0)); patchText(refs.tokEl, formatTokensPrecise(m.totalTokens || 0));
const costNum = Number(m.costUsd || 0); const costNum = Number(m.costUsd || 0);
const isAllUnpriced = const isAllUnpriced =
calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0); calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0);
@@ -1276,6 +1313,15 @@ export const StepsDetailView = defineComponent({
? +((cacheTok / promptTok) * 100).toFixed(1) ? +((cacheTok / promptTok) * 100).toFixed(1)
: 0; : 0;
patchText(refs.inLbl, t('cons.footInput'));
patchText(refs.cacheLbl, t('cons.footCache'));
patchText(refs.thinkLbl, t('cons.footThinking'));
patchText(refs.outLbl, t('cons.footOutput'));
patchText(refs.inVal, formatTokensPrecise(inTok));
patchText(refs.cacheVal, formatTokensPrecise(cacheTok));
patchText(refs.thinkVal, formatTokensPrecise(thinkTok));
patchText(refs.outVal, formatTokensPrecise(respTok));
patchText( patchText(
refs.perfEl, refs.perfEl,
t('steps.modelPerfFoot', { t('steps.modelPerfFoot', {
@@ -1284,15 +1330,6 @@ export const StepsDetailView = defineComponent({
cache: resolvedCachePct, cache: resolvedCachePct,
}) })
); );
patchText(
refs.splitEl,
t('steps.modelSplitFoot', {
inTok: formatTokens(inTok),
cacheTok: formatTokens(cacheTok),
thinkTok: formatTokens(thinkTok),
respTok: formatTokens(respTok),
})
);
const isActiveFit = const isActiveFit =
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
@@ -1374,7 +1411,7 @@ export const StepsDetailView = defineComponent({
st.telemetry?.settings?.stepTokenComboFormat st.telemetry?.settings?.stepTokenComboFormat
), ),
stepTableColumns: st.telemetry?.settings?.stepTableColumns, stepTableColumns: st.telemetry?.settings?.stepTableColumns,
experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), experimentalModernUi: resolveSettingsModernUi(st.telemetry?.settings),
}), }),
(slice) => { (slice) => {
latestSlice = slice; latestSlice = slice;
@@ -8,8 +8,8 @@ import { defineComponent } from '../../core/component.js';
import { import {
applyAppearanceToRoot, applyAppearanceToRoot,
normalizeClientFontScale, normalizeClientFontScale,
normalizeClientModernUi,
normalizeClientThemeAccent, normalizeClientThemeAccent,
resolveSettingsModernUi,
} from '../../core/appearance.js'; } from '../../core/appearance.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';
@@ -27,9 +27,9 @@ import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
function getLanguageOptions() { function getLanguageOptions() {
return [ return [
{ value: 'auto', label: t('settings.gen.langAuto') },
{ value: 'zh-CN', label: t('settings.gen.langZh') }, { value: 'zh-CN', label: t('settings.gen.langZh') },
{ value: 'en-US', label: t('settings.gen.langEn') }, { value: 'en-US', label: t('settings.gen.langEn') },
{ value: 'auto', label: t('settings.gen.langAuto') },
]; ];
} }
@@ -44,8 +44,8 @@ function getFontScaleOptions() {
function getModernUiOptions() { function getModernUiOptions() {
return [ return [
{ value: 'off', label: t('settings.gen.modernUiOff') },
{ value: 'on', label: t('settings.gen.modernUiOn') }, { value: 'on', label: t('settings.gen.modernUiOn') },
{ value: 'off', label: t('settings.gen.modernUiOff') },
]; ];
} }
@@ -73,10 +73,10 @@ function formatCloudSyncTimeText(tsMs, updatedAt) {
export const SettingsGeneralTab = defineComponent({ export const SettingsGeneralTab = defineComponent({
name: 'SettingsGeneralTab', name: 'SettingsGeneralTab',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
let draftLanguage = 'zh-CN'; let draftLanguage = 'auto';
let draftThemeAccent = 'host'; let draftThemeAccent = 'host';
let draftFontScale = 'md'; let draftFontScale = 'md';
let draftModernUi = false; let draftModernUi = true;
let draftPluginUpdateMode = 'manual'; let draftPluginUpdateMode = 'manual';
let latestSettings = null; let latestSettings = null;
let latestCloudStatus = null; let latestCloudStatus = null;
@@ -218,10 +218,10 @@ export const SettingsGeneralTab = defineComponent({
const modernUiSwitch = SegmentedControl({ const modernUiSwitch = SegmentedControl({
ariaLabel: t('settings.gen.modernUi'), ariaLabel: t('settings.gen.modernUi'),
modelValue: 'off', modelValue: 'on',
options: getModernUiOptions(), options: getModernUiOptions(),
onUpdateModelValue: async (val) => { onUpdateModelValue: async (val) => {
const nextModernUi = val === 'on'; const nextModernUi = val !== 'off';
draftModernUi = nextModernUi; draftModernUi = nextModernUi;
modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); modernUiSwitch.setValue(nextModernUi ? 'on' : 'off');
if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) {
@@ -231,6 +231,7 @@ export const SettingsGeneralTab = defineComponent({
...(latestSettings || {}), ...(latestSettings || {}),
themeAccent: draftThemeAccent, themeAccent: draftThemeAccent,
fontScale: draftFontScale, fontScale: draftFontScale,
modernUi: nextModernUi,
experimentalModernUi: nextModernUi, experimentalModernUi: nextModernUi,
}, },
{ includeFontScale: true } { includeFontScale: true }
@@ -239,7 +240,7 @@ export const SettingsGeneralTab = defineComponent({
const saveToken = ++appearanceSaveSeq; const saveToken = ++appearanceSaveSeq;
showAppearanceFeedback(t('settings.saving'), 0); showAppearanceFeedback(t('settings.saving'), 0);
try { try {
await saveSettingsPatch({ experimentalModernUi: nextModernUi }); await saveSettingsPatch({ modernUi: nextModernUi });
if (saveToken === appearanceSaveSeq) { if (saveToken === appearanceSaveSeq) {
showAppearanceFeedback(t('settings.saved'), 1500); showAppearanceFeedback(t('settings.saved'), 1500);
} }
@@ -423,7 +424,7 @@ export const SettingsGeneralTab = defineComponent({
draftLanguage = normalizeI18nLanguage(settings.language); draftLanguage = normalizeI18nLanguage(settings.language);
draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent);
draftFontScale = normalizeClientFontScale(settings.fontScale); draftFontScale = normalizeClientFontScale(settings.fontScale);
draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); draftModernUi = resolveSettingsModernUi(settings);
draftPluginUpdateMode = normalizeClientUpdateMode( draftPluginUpdateMode = normalizeClientUpdateMode(
settings.pluginUpdateMode, settings.pluginUpdateMode,
settings.autoUpdatePlugin settings.autoUpdatePlugin
@@ -458,7 +458,7 @@ export const SettingsOtherTab = defineComponent({
showMaintFeedback(t('settings.oth.resettingBtn'), 0); showMaintFeedback(t('settings.oth.resettingBtn'), 0);
try { try {
const res = await resetAllSettings(); const res = await resetAllSettings();
setI18nLanguage(res?.settings?.language || 'zh-CN'); setI18nLanguage(res?.settings?.language || 'auto');
showMaintFeedback(t('settings.oth.resetAllDone'), 2800); showMaintFeedback(t('settings.oth.resetAllDone'), 2800);
} catch { } catch {
showMaintFeedback(t('settings.saveFailed'), 2800); showMaintFeedback(t('settings.saveFailed'), 2800);
+295 -86
View File
@@ -421,8 +421,8 @@ html[data-standalone="true"] .app-shell {
.steps-inline-scope-select .select-menu, .steps-inline-scope-select .select-menu,
.steps-inline-model-select .select-menu { .steps-inline-model-select .select-menu {
left: 0; left: auto;
right: auto; right: 0;
min-width: 220px; min-width: 220px;
max-width: min(320px, calc(100vw - 24px)); max-width: min(320px, calc(100vw - 24px));
} }
@@ -442,6 +442,23 @@ html[data-standalone="true"] .app-shell {
flex-shrink: 0; flex-shrink: 0;
} }
.endpoint-ssh-badge {
display: inline-flex;
align-items: center;
padding: 2px 5px;
font-family: var(--font-mono);
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.2;
letter-spacing: 0.02em;
border-radius: var(--radius-xs);
border: 1px solid var(--accent-primary-border);
background: var(--accent-primary-soft);
color: var(--accent-primary);
white-space: nowrap;
flex-shrink: 0;
}
.status-tag { .status-tag {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -679,7 +696,15 @@ html[data-standalone="true"] .app-shell {
font-size: var(--fs-base); font-size: var(--fs-base);
cursor: pointer; cursor: pointer;
text-align: left; text-align: left;
transition: background-color var(--dur-instant) var(--ease-fast); transition:
background-color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast),
box-shadow var(--dur-instant) var(--ease-fast);
}
.select-trigger .svg-icon {
flex-shrink: 0;
color: var(--text-muted);
} }
.select-trigger:hover, .select-trigger:hover,
@@ -687,6 +712,27 @@ html[data-standalone="true"] .app-shell {
background: var(--surface-hover); background: var(--surface-hover);
} }
.form-row > .custom-select > .select-trigger {
min-height: calc(28px * var(--ui-font-scale, 1));
padding: 3px 12px;
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
border: none;
border-radius: var(--radius-pill);
}
.form-row > .custom-select > .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.form-row > .custom-select.is-open > .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
}
.form-row > .custom-select > .select-trigger:disabled {
opacity: 0.52;
cursor: not-allowed;
}
.select-label { .select-label {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -2282,12 +2328,6 @@ html[data-standalone="true"] .app-shell {
white-space: nowrap; white-space: nowrap;
} }
.cons-title-model-dot {
width: 7px;
height: 7px;
flex-shrink: 0;
}
.cons-row-metrics { .cons-row-metrics {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -2420,9 +2460,9 @@ html[data-standalone="true"] .app-shell {
left: var(--tip-x, 50%); left: var(--tip-x, 50%);
transform: translateX(var(--tip-shift, -50%)); transform: translateX(var(--tip-shift, -50%));
width: max-content; width: max-content;
min-width: 196px; min-width: 224px;
max-width: min(320px, calc(100% - 8px)); max-width: min(316px, calc(100% - 8px));
padding: 6px 10px; padding: 9px 11px;
background: var(--surface-panel); background: var(--surface-panel);
border: 1px solid var(--border-strong); border: 1px solid var(--border-strong);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
@@ -2431,27 +2471,29 @@ html[data-standalone="true"] .app-shell {
z-index: 25; z-index: 25;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 2px; gap: 6px;
} }
.trend-tip-head { .trend-tip-head {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 10px; gap: 12px;
font-size: var(--fs-sm); font-size: var(--fs-xs);
line-height: 1.25;
color: var(--text-secondary); color: var(--text-secondary);
} }
.trend-tip-time { .trend-tip-time {
font-weight: 600; font-weight: 500;
color: var(--text-primary); color: var(--text-secondary);
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
} }
.trend-tip-calls { .trend-tip-calls {
font-size: var(--fs-xs); font-size: var(--fs-xs);
font-weight: 500;
color: var(--text-muted); color: var(--text-muted);
white-space: nowrap; white-space: nowrap;
max-width: 190px; max-width: 190px;
@@ -2461,14 +2503,17 @@ html[data-standalone="true"] .app-shell {
.trend-tip-main { .trend-tip-main {
display: flex; display: flex;
align-items: baseline; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 10px;
margin-top: -2px;
} }
.trend-tip-tokens { .trend-tip-tokens {
font-size: var(--fs-base); font-size: var(--fs-lg);
font-weight: 700; font-weight: 700;
line-height: 1.18;
letter-spacing: -0.02em;
color: var(--accent-primary); color: var(--accent-primary);
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
@@ -2477,20 +2522,66 @@ html[data-standalone="true"] .app-shell {
.trend-tip-cost { .trend-tip-cost {
font-size: var(--fs-md); font-size: var(--fs-md);
font-weight: 600; font-weight: 600;
line-height: 1.2;
padding: 0;
border-radius: 0;
color: var(--text-primary); color: var(--text-primary);
background: transparent;
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
} }
.trend-tip-cost:empty {
display: none;
}
.trend-tip-sub { .trend-tip-sub {
padding: 2px 0;
border: none;
border-radius: 0;
background: transparent;
font-size: var(--fs-xs); font-size: var(--fs-xs);
line-height: 1.3;
color: var(--text-secondary); color: var(--text-secondary);
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
border-top: 1px solid var(--border-hairline); }
padding-top: 2px;
margin-top: 1px; .trend-tip-sub[hidden] {
display: none !important;
}
.trend-tip-sub.is-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
padding: 2px 0;
white-space: normal;
overflow: visible;
}
.trend-tip-stat {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.trend-tip-stat-label {
font-size: var(--fs-2xs);
font-weight: 500;
line-height: 1.2;
color: var(--text-muted);
white-space: nowrap;
}
.trend-tip-stat-val {
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.25;
color: var(--text-primary);
white-space: nowrap;
} }
.trend-tooltip.is-line-low { .trend-tooltip.is-line-low {
@@ -2878,9 +2969,9 @@ html[data-standalone="true"] .app-shell {
left: var(--pop-x, 8px); left: var(--pop-x, 8px);
top: var(--pop-y, 8px); top: var(--pop-y, 8px);
width: max-content; width: max-content;
min-width: 196px; min-width: 224px;
max-width: min(310px, calc(100% - 16px)); max-width: min(316px, calc(100% - 16px));
padding: 6px 10px; padding: 9px 11px;
background: var(--surface-panel); background: var(--surface-panel);
border: 1px solid var(--border-strong); border: 1px solid var(--border-strong);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
@@ -2889,24 +2980,34 @@ html[data-standalone="true"] .app-shell {
z-index: 30; z-index: 30;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 3px; gap: 6px;
} }
.cons-pop-models { .cons-pop-models {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 3px; gap: 4px;
border-top: 1px solid var(--border-hairline); border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent);
padding-top: 4px; padding-top: 6px;
margin-top: 2px; margin-top: 1px;
}
.cons-pop-models[hidden] {
display: none !important;
}
.trend-tip-sub:not([hidden]) + .cons-pop-models {
border-top: none;
padding-top: 2px;
margin-top: 0;
} }
.cons-pop-model-row { .cons-pop-model-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 10px;
font-size: var(--fs-sm); font-size: var(--fs-xs);
line-height: 1.3; line-height: 1.3;
} }
@@ -2920,6 +3021,7 @@ html[data-standalone="true"] .app-shell {
.cons-pop-model-name { .cons-pop-model-name {
max-width: 156px; max-width: 156px;
font-weight: 500;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@@ -2942,10 +3044,11 @@ html[data-standalone="true"] .app-shell {
} }
.cons-pop-model-pct { .cons-pop-model-pct {
min-width: 40px; min-width: 38px;
text-align: right; text-align: right;
font-weight: 600; font-size: var(--fs-xs);
color: var(--text-primary); font-weight: 500;
color: var(--text-secondary);
} }
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
@@ -3062,6 +3165,14 @@ html[data-standalone="true"] .app-shell {
background: var(--surface-panel); background: var(--surface-panel);
} }
.panel > .table-scroll-host {
margin-right: calc(-1 * var(--space-5) + 2px);
}
.panel > .table-scroll-host > .custom-scroll-content {
padding-right: calc(var(--space-5) - 2px);
}
.table-viewport { .table-viewport {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
@@ -3170,57 +3281,69 @@ html[data-standalone="true"] .app-shell {
flex: 0 1 auto; flex: 0 1 auto;
} }
.step-model-compact {
flex-shrink: 0;
white-space: nowrap;
color: var(--accent-primary);
font-weight: 500;
}
.step-model-compact[hidden] {
display: none !important;
}
.steps-panel-header { .steps-panel-header {
flex-wrap: wrap; flex-wrap: wrap;
row-gap: 6px; row-gap: 6px;
} }
.steps-panel-title {
flex: 0 0 auto;
}
.steps-header-controls { .steps-header-controls {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end; justify-content: space-between;
gap: 6px; flex-wrap: wrap;
flex: 1 1 280px; gap: 6px 8px;
flex: 1 1 100%;
min-width: 0; min-width: 0;
} }
.steps-header-controls .segmented { .steps-header-controls .segmented {
flex-shrink: 0; flex: 0 0 auto;
}
.steps-header-filters {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 6px;
margin-left: auto;
flex: 1 1 156px;
min-width: 0;
max-width: 100%;
}
.steps-header-filters[hidden] {
display: none !important;
} }
.steps-inline-scope-select, .steps-inline-scope-select,
.steps-inline-model-select { .steps-inline-model-select {
flex: 0 1 165px; flex: 0 1 auto;
min-width: 72px; min-width: 0;
max-width: 175px; max-width: 148px;
} }
.steps-inline-scope-select .select-trigger, .steps-inline-scope-select .select-trigger,
.steps-inline-model-select .select-trigger { .steps-inline-model-select .select-trigger {
min-height: calc(22px * var(--ui-font-scale, 1)); min-height: calc(25px * var(--ui-font-scale, 1));
height: auto; height: auto;
padding: 2px 6px; padding: 2px 10px;
gap: 4px; gap: 6px;
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
font-size: var(--fs-md); font-size: var(--fs-md);
border: 1px solid var(--border-hairline); border: none;
background: var(--surface-subtle); border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
}
.steps-inline-scope-select .select-trigger:hover,
.steps-inline-model-select .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.steps-inline-scope-select.is-open .select-trigger,
.steps-inline-model-select.is-open .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
} }
/* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */ /* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */
@@ -3338,7 +3461,24 @@ html[data-standalone="true"] .app-shell {
animation: anim-popover-in var(--dur-instant) var(--ease-fast); animation: anim-popover-in var(--dur-instant) var(--ease-fast);
} }
/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ /* --- 2.6 单步压缩 / 异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */
.data-table tbody tr.is-compaction {
background: color-mix(in srgb, var(--accent-primary) 11%, transparent);
}
.data-table tbody tr.is-compaction:hover {
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
}
.data-table tbody tr.is-compaction td:first-child {
box-shadow: inset 2px 0 0 var(--accent-primary);
}
.data-table tbody tr.is-compaction td:first-child > span:not(.agent-badge):not(.turn-rail) {
color: var(--accent-primary);
font-weight: 600;
}
.data-table tbody tr.is-anomaly-warn { .data-table tbody tr.is-anomaly-warn {
background: color-mix(in srgb, var(--metric-warn) 11%, transparent); background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
} }
@@ -3442,6 +3582,10 @@ html[data-standalone="true"] .app-shell {
border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong));
} }
.step-anomaly-tip.is-compaction {
border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong));
}
.step-anomaly-tip[hidden], .step-anomaly-tip[hidden],
.step-anomaly-tip-sub[hidden], .step-anomaly-tip-sub[hidden],
.step-anomaly-tip-list[hidden], .step-anomaly-tip-list[hidden],
@@ -3466,6 +3610,10 @@ html[data-standalone="true"] .app-shell {
color: var(--metric-danger); color: var(--metric-danger);
} }
.step-anomaly-tip.is-compaction .step-anomaly-tip-title {
color: var(--accent-primary);
}
.step-anomaly-tip-sub { .step-anomaly-tip-sub {
font-size: var(--fs-xs); font-size: var(--fs-xs);
color: var(--text-secondary); color: var(--text-secondary);
@@ -3585,7 +3733,9 @@ html[data-standalone="true"] .app-shell {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--space-3); gap: var(--space-3);
padding: var(--space-3) 0 2px; padding-top: var(--space-3);
padding-bottom: 2px;
padding-left: 0;
} }
.sstep-card { .sstep-card {
@@ -3642,15 +3792,24 @@ html[data-standalone="true"] .app-shell {
} }
.sstep-fit-model-select .select-trigger { .sstep-fit-model-select .select-trigger {
min-height: calc(22px * var(--ui-font-scale, 1)); min-height: calc(24px * var(--ui-font-scale, 1));
height: auto; height: auto;
padding: 2px 6px; padding: 2px 10px;
gap: 4px; gap: 6px;
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
font-size: var(--fs-sm); font-size: var(--fs-sm);
border: 1px solid var(--border-hairline); border: none;
background: var(--surface-subtle); border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
}
.sstep-fit-model-select .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.sstep-fit-model-select.is-open .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
} }
.sstep-chart-wrap { .sstep-chart-wrap {
@@ -3826,9 +3985,11 @@ html[data-standalone="true"] .app-shell {
} }
.trend-tip-anomaly { .trend-tip-anomaly {
margin-top: 3px; margin-top: 0;
padding-top: 3px; padding: 4px 8px;
border-top: 1px solid var(--border-hairline); border: none;
border-radius: var(--radius-xs);
background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
font-size: var(--fs-xs); font-size: var(--fs-xs);
font-weight: 600; font-weight: 600;
color: var(--metric-warn); color: var(--metric-warn);
@@ -3837,6 +3998,7 @@ html[data-standalone="true"] .app-shell {
.trend-tip-anomaly.is-danger { .trend-tip-anomaly.is-danger {
color: var(--metric-danger); color: var(--metric-danger);
background: color-mix(in srgb, var(--metric-danger) 12%, transparent);
} }
.trend-tip-anomaly[hidden] { .trend-tip-anomaly[hidden] {
@@ -4077,17 +4239,27 @@ html[data-standalone="true"] .app-shell {
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
flex-wrap: wrap; flex-wrap: wrap;
gap: 2px 10px; gap: 4px 10px;
font-size: var(--fs-sm); font-size: var(--fs-md);
color: var(--text-secondary); color: var(--text-secondary);
} }
.smodel-perf {
color: var(--text-secondary);
white-space: nowrap;
}
.smodel-split { .smodel-split {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 10px;
color: var(--text-secondary);
}
.smodel-split strong {
color: var(--text-primary);
font-weight: 600;
}
.smodel-perf {
margin-left: auto;
font-size: var(--fs-sm);
color: var(--text-muted); color: var(--text-muted);
white-space: nowrap; white-space: nowrap;
} }
@@ -5921,6 +6093,9 @@ html[data-standalone="true"] .app-shell {
--modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%);
--modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent);
--modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent));
--modern-pill-select-bg: color-mix(in srgb, var(--text-primary) 8.5%, var(--modern-surface-card));
--modern-pill-select-hover: color-mix(in srgb, var(--text-primary) 12.5%, var(--modern-surface-card));
--modern-pill-select-open: color-mix(in srgb, var(--text-primary) 15%, var(--modern-surface-card));
--modern-card-shadow: none; --modern-card-shadow: none;
--modern-nav-track-bg: var(--modern-surface-card); --modern-nav-track-bg: var(--modern-surface-card);
--modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent);
@@ -5942,6 +6117,9 @@ html[data-standalone="true"] .app-shell {
--modern-surface-card: #ffffff; --modern-surface-card: #ffffff;
--modern-surface-subtle: hsl(216 42% 97.2%); --modern-surface-subtle: hsl(216 42% 97.2%);
--modern-surface-hover: hsl(216 56% 94.4%); --modern-surface-hover: hsl(216 56% 94.4%);
--modern-pill-select-bg: hsl(220 14% 94%);
--modern-pill-select-hover: hsl(220 14% 90.5%);
--modern-pill-select-open: hsl(220 14% 88.5%);
--modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028);
--modern-nav-track-bg: hsl(216 28% 94.2%); --modern-nav-track-bg: hsl(216 28% 94.2%);
--modern-inline-track-bg: hsl(216 32% 96.2%); --modern-inline-track-bg: hsl(216 32% 96.2%);
@@ -6149,6 +6327,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
[data-modern-ui="true"] .status-tag.state-running, [data-modern-ui="true"] .status-tag.state-running,
[data-modern-ui="true"] .status-tag.state-synced, [data-modern-ui="true"] .status-tag.state-synced,
[data-modern-ui="true"] .status-tag.state-warn, [data-modern-ui="true"] .status-tag.state-warn,
[data-modern-ui="true"] .endpoint-ssh-badge,
[data-modern-ui="true"] .update-badge-btn, [data-modern-ui="true"] .update-badge-btn,
[data-modern-ui="true"] .wm-update-btn, [data-modern-ui="true"] .wm-update-btn,
[data-modern-ui="true"] .wm-hover-update-bar, [data-modern-ui="true"] .wm-hover-update-bar,
@@ -6363,10 +6542,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
} }
[data-modern-ui="true"] .trend-tip-sub, [data-modern-ui="true"] .trend-tip-sub,
[data-modern-ui="true"] .trend-tip-anomaly, [data-modern-ui="true"] .trend-tip-cost {
background: transparent;
}
[data-modern-ui="true"] .cons-pop-models { [data-modern-ui="true"] .cons-pop-models {
border-top: none; border-top-color: var(--modern-surface-hover);
padding-top: 3px;
} }
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
@@ -6424,6 +6605,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
background: var(--modern-surface-hover); background: var(--modern-surface-hover);
} }
[data-modern-ui="true"] .data-table tbody tr.is-compaction,
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-compaction:nth-child(even),
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction {
background: color-mix(in srgb, var(--accent-primary) 12%, transparent);
}
[data-modern-ui="true"] .data-table tbody tr.is-compaction:hover,
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction:hover {
background: color-mix(in srgb, var(--accent-primary) 19%, transparent);
}
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, [data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn,
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), [data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even),
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { [data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn {
@@ -6446,11 +6638,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
background: color-mix(in srgb, var(--metric-danger) 21%, transparent); background: color-mix(in srgb, var(--metric-danger) 21%, transparent);
} }
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { [data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
border: none; border: none;
background: var(--modern-surface-subtle); box-shadow: none;
border-radius: var(--radius-pill);
background: var(--modern-pill-select-bg);
}
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover {
background: var(--modern-pill-select-hover);
}
[data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger {
background: var(--modern-pill-select-open);
} }
[data-modern-ui="true"] .sstep-card, [data-modern-ui="true"] .sstep-card,
@@ -6566,12 +6775,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border: none; border: none;
background: var(--modern-surface-card); background: var(--modern-surface-card);
box-shadow: var(--shadow-popover); box-shadow: var(--shadow-popover);
animation: anim-modern-pop-in 150ms var(--ease-modern); animation: anim-modern-tip-fade 120ms var(--ease-modern);
} }
[data-modern-ui="true"] .select-menu.is-above, [data-modern-ui="true"] .select-menu.is-above,
[data-modern-ui="true"] .dt-popover.is-above { [data-modern-ui="true"] .dt-popover.is-above {
animation-name: anim-modern-pop-in-up; transform-origin: bottom right;
} }
[data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .trend-tooltip,
+4 -3
View File
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from 'node:url';
import vm from 'node:vm'; import vm from 'node:vm';
import { randomUUID } from 'node:crypto'; import { createHash, randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util'; import { isDeepStrictEqual } from 'node:util';
import * as metrics from '../trajectory-metrics.mjs'; import * as metrics from '../trajectory-metrics.mjs';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
@@ -26,6 +26,7 @@ const BACKEND_MODULE_FILES = [
'../backend/http-helpers.mjs', '../backend/http-helpers.mjs',
'../backend/settings-schema.mjs', '../backend/settings-schema.mjs',
'../backend/config.mjs', '../backend/config.mjs',
'../backend/endpoint-registry.mjs',
'../backend/sqlite-client.mjs', '../backend/sqlite-client.mjs',
'../backend/proto-wire.mjs', '../backend/proto-wire.mjs',
'../backend/cli-sqlite-reader.mjs', '../backend/cli-sqlite-reader.mjs',
@@ -85,7 +86,7 @@ export function backendHarness({
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 ctx={ const ctx={
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, 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(); }
@@ -206,6 +207,6 @@ export function backendHarness({
return {ok:true,json:async()=>data}; return {ok:true,json:async()=>data};
}, },
}; };
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx);
return {...ctx.api,state}; return {...ctx.api,state};
} }
+16 -3
View File
@@ -1054,12 +1054,24 @@ test('saving preferences sends the same legacy values normalized by the backend'
}); });
test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => { test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => {
// 1. Default schema matches pre-refactor out-of-box UI 100% // 1. Default schema matches v1.5.3 out-of-box UI (language='auto', modernUi=true)
const hDefault = backendHarness({}); const hDefault = backendHarness({});
const def = hDefault.loadSettings(); const def = hDefault.loadSettings();
assert.equal(def.language, 'zh-CN'); assert.equal(def.language, 'auto');
assert.equal(def.themeAccent, 'host'); assert.equal(def.themeAccent, 'host');
assert.equal(def.fontScale, 'md'); assert.equal(def.fontScale, 'md');
assert.equal(def.modernUi, true);
assert.equal(def.experimentalModernUi, true);
// Upgrading from v1.5.2 settings.json (with experimentalModernUi: false and no modernUi key) enables modernUi=true
const hFrom152 = backendHarness({ settings: { language: 'zh-CN', experimentalModernUi: false } });
const loadedFrom152 = hFrom152.loadSettings();
assert.equal(loadedFrom152.modernUi, true);
assert.equal(loadedFrom152.experimentalModernUi, true);
const optOutRes = hFrom152.executeSettingsAction({ modernUi: false });
assert.equal(optOutRes.ok, true);
assert.equal(optOutRes.updated.modernUi, false);
assert.equal(hFrom152.loadSettings().modernUi, false);
assert.equal(def.pluginUpdateMode, 'manual'); assert.equal(def.pluginUpdateMode, 'manual');
assert.equal(def.windowMountMode, 'dual'); assert.equal(def.windowMountMode, 'dual');
assert.equal(def.enableWindowOverlay, true); assert.equal(def.enableWindowOverlay, true);
@@ -1147,7 +1159,8 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
// 6. executeResetSettingsAction restores full defaults cleanly // 6. executeResetSettingsAction restores full defaults cleanly
const resetRes = hDefault.executeResetSettingsAction(); const resetRes = hDefault.executeResetSettingsAction();
assert.equal(resetRes.ok, true); assert.equal(resetRes.ok, true);
assert.equal(resetRes.updated.language, 'zh-CN'); assert.equal(resetRes.updated.language, 'auto');
assert.equal(resetRes.updated.modernUi, true);
assert.equal(resetRes.updated.themeAccent, 'host'); assert.equal(resetRes.updated.themeAccent, 'host');
assert.equal(resetRes.updated.enableCliStatusLine, true); assert.equal(resetRes.updated.enableCliStatusLine, true);
assert.equal(resetRes.updated.showStepTurnRail, false); assert.equal(resetRes.updated.showStepTurnRail, false);
@@ -103,6 +103,10 @@ test('FourSegmentBar supports percentage scaling while keeping 100% default for
thinkingTokens: 100, thinkingTokens: 100,
}); });
const segsFull = barFull.el.querySelectorAll('.progress-seg'); const segsFull = barFull.el.querySelectorAll('.progress-seg');
assert.deepEqual(
segsFull.map((el) => el.className.split(/\s+/).find((c) => c.startsWith('seg-'))),
['seg-input', 'seg-cached', 'seg-thinking', 'seg-output']
);
const sumFull = segsFull.reduce((acc, el) => acc + parsePctVar(el), 0); const sumFull = segsFull.reduce((acc, el) => acc + parsePctVar(el), 0);
assert.ok(Math.abs(sumFull - 100) < 0.05); assert.ok(Math.abs(sumFull - 100) < 0.05);
@@ -412,11 +416,8 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
assert.equal(modelRows.length, 6); assert.equal(modelRows.length, 6);
assert.equal(sourceRows.length, 2); assert.equal(sourceRows.length, 2);
// 1. Top Models: colored dot appears right after model name & 4-segment bar scales to 50% (not 100%) // 1. Top Models: no color dot next to model name & 4-segment bar scales to 50% (not 100%)
const argonTitleDot = modelRows[0].querySelector('.cons-title-model-dot'); assert.equal(modelRows[0].querySelector('.cons-title-model-dot'), null);
assert.ok(argonTitleDot && !argonTitleDot.hasAttribute('hidden'));
const argonDotColor = argonTitleDot.style.getPropertyValue('--dot-color');
assert.match(argonDotColor, /^hsl\(/);
const argonSegSum = modelRows[0] const argonSegSum = modelRows[0]
.querySelectorAll('.progress-seg') .querySelectorAll('.progress-seg')
@@ -429,7 +430,8 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
assert.equal(appTopItems.length, 3, 'Should show top 3 non-other models in single-line footer'); assert.equal(appTopItems.length, 3, 'Should show top 3 non-other models in single-line footer');
assert.equal(appTopItems[0].querySelector('.cons-source-top-name')?.textContent, '4-argon'); assert.equal(appTopItems[0].querySelector('.cons-source-top-name')?.textContent, '4-argon');
assert.equal(appTopItems[0].querySelector('.cons-source-top-pct')?.textContent, '50%'); assert.equal(appTopItems[0].querySelector('.cons-source-top-pct')?.textContent, '50%');
assert.equal(appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'), argonDotColor); const argonDotColor = appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color');
assert.match(argonDotColor, /^hsl\(/);
assert.equal(appTopItems[1].querySelector('.cons-source-top-name')?.textContent, '4-carbon'); assert.equal(appTopItems[1].querySelector('.cons-source-top-name')?.textContent, '4-carbon');
assert.equal(appTopItems[1].querySelector('.cons-source-top-pct')?.textContent, '31%'); assert.equal(appTopItems[1].querySelector('.cons-source-top-pct')?.textContent, '31%');
assert.equal(appTopItems[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n'); assert.equal(appTopItems[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n');
@@ -963,8 +963,8 @@ test('post-compaction context preserves static channels + checkpoint summary, ca
const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
assert.match(stylesCss, /\.wm-ctx-seg\s*\{[^}]*width:\s*58px;/); assert.match(stylesCss, /\.wm-ctx-seg\s*\{[^}]*width:\s*58px;/);
assert.match(stylesCss, /\.wm-ctx-pct\s*\{[^}]*max-width:\s*none;[^}]*overflow:\s*visible;[^}]*text-overflow:\s*clip;/s); assert.match(stylesCss, /\.wm-ctx-pct\s*\{[^}]*max-width:\s*none;[^}]*overflow:\s*visible;[^}]*text-overflow:\s*clip;/s);
assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*color:\s*var\(--accent-primary\);/); assert.match(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*var\(--accent-primary\)/);
assert.doesNotMatch(stylesCss, /\.step-model-compact\s*\{[^}]*--metric-info/); assert.doesNotMatch(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*--metric-info/);
assert.match(stylesCss, /\.long-pill-nav\s*\{[^}]*container-type:\s*inline-size;[^}]*minmax\(0,\s*1fr\)[^}]*overflow:\s*hidden;/s); assert.match(stylesCss, /\.long-pill-nav\s*\{[^}]*container-type:\s*inline-size;[^}]*minmax\(0,\s*1fr\)[^}]*overflow:\s*hidden;/s);
assert.match(stylesCss, /\.pill-tab\s*\{[^}]*min-width:\s*0;/s); assert.match(stylesCss, /\.pill-tab\s*\{[^}]*min-width:\s*0;/s);
assert.match(stylesCss, /@container\s*\(max-width:\s*30em\)\s*\{[\s\S]*?\.pill-tab-badge\s*\{\s*display:\s*none\s*!important;/); assert.match(stylesCss, /@container\s*\(max-width:\s*30em\)\s*\{[\s\S]*?\.pill-tab-badge\s*\{\s*display:\s*none\s*!important;/);
@@ -1376,3 +1376,119 @@ test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveAc
globalThis.window = prevWin; globalThis.window = prevWin;
} }
}); });
test('5h quota cycle includes cycle-opening compaction CHECKPOINT and cross-boundary steps plus unattributed cold-boot cache entries', async () => {
const nowMs = Date.now();
const start5hMs = nowMs - 2 * 3600_000;
const reset5hIso = new Date(start5hMs + 5 * 3600_000).toISOString();
const resetWkIso = new Date(nowMs + 5 * 24 * 3600_000).toISOString();
// 1. Old step from expired previous cycle (2.5h before start5hMs) -> must be excluded from 5h
const oldCycleStep = {
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
sourceTrajectoryStepInfo: { stepIndex: 1 },
createdAt: new Date(start5hMs - 2.5 * 3600_000).toISOString(),
completedAt: new Date(start5hMs - 2.5 * 3600_000 + 8_000).toISOString(),
modelUsage: {
model: 'MODEL_PLACEHOLDER_M429',
inputTokens: '100000',
cacheReadTokens: '0',
outputTokens: '5000',
},
},
};
// 2. Untimed /compact CHECKPOINT started 70s BEFORE start5hMs that settled & opened the 5h bucket -> must be included!
const compactOpeningStep = {
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
sourceTrajectoryStepInfo: { stepIndex: 2 },
createdAt: new Date(start5hMs - 70_000).toISOString(),
modelUsage: {
model: 'MODEL_PLACEHOLDER_M429',
inputTokens: '300000',
cacheReadTokens: '0',
outputTokens: '4000',
},
},
};
// 3. Normal step after compaction inside 5h window
const postCompactStep = {
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
sourceTrajectoryStepInfo: { stepIndex: 3 },
createdAt: new Date(start5hMs + 120_000).toISOString(),
completedAt: new Date(start5hMs + 135_000).toISOString(),
modelUsage: {
model: 'MODEL_PLACEHOLDER_M429',
inputTokens: '6000',
cacheReadTokens: '80000',
outputTokens: '2000',
},
},
};
// 4. Cold-boot cached conversation initially saved with accountName: '' before email loaded -> included for Alice, while Bob stays excluded
const coldBootStep = {
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
sourceTrajectoryStepInfo: { stepIndex: 1 },
createdAt: new Date(start5hMs - 40_000).toISOString(),
completedAt: new Date(start5hMs + 10_000).toISOString(),
modelUsage: {
model: 'MODEL_PLACEHOLDER_M429',
inputTokens: '10000',
cacheReadTokens: '0',
outputTokens: '1000',
},
},
};
const h = backendHarness({
userStatus: { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } },
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
buckets: [
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.929, resetTime: reset5hIso },
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.395, resetTime: resetWkIso },
],
},
],
},
cache: {
'cold-boot-conv': {
accountName: '',
signature: 'v10-model-identity:cold',
steps: extractModelSteps([coldBootStep]),
},
'bob-conv': {
accountName: 'bob@example.com',
signature: 'v10-model-identity:bob',
steps: extractModelSteps([postCompactStep]),
},
},
summaries: {
'main-conv': { stepCount: 3, lastModifiedTime: new Date(nowMs - 10_000).toISOString(), status: 'IDLE' },
},
trajectories: {
'main-conv': { trajectory: { steps: [oldCycleStep, compactOpeningStep, postCompactStep] } },
},
});
const payload = await h.buildTelemetryPayloadInternal('main-conv', false, { range: '5h' });
const geminiPool = payload.quotas.pools.find((p) => p.poolKey === 'Gemini');
// Includes compactOpeningStep (304,000) + postCompactStep (88,000) + coldBootStep (11,000) = 403,000 tokens (3 calls)
assert.equal(geminiPool.cycle5h.calls, 3);
assert.equal(geminiPool.cycle5h.tokens, 403_000);
// Preset 5h account bucket includes Alice's 3 calls (403k) + Bob's 1 call (88k), excluding oldCycleStep (105k)
assert.equal(payload.consumption.account.calls, 4);
assert.equal(payload.consumption.account.totalTokens, 491_000);
});
+174
View File
@@ -199,6 +199,7 @@ test('frontend considers a model-only correction a real telemetry update', () =>
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667'; const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681'; const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681';
const ORCH_NEON = 'MODEL_PLACEHOLDER_M537';
const ORCH_EXEC_HYDROGEN = 'MODEL_PLACEHOLDER_M669'; const ORCH_EXEC_HYDROGEN = 'MODEL_PLACEHOLDER_M669';
test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolve to orch-carbon and annotate upstream ID', async () => { test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolve to orch-carbon and annotate upstream ID', async () => {
@@ -285,6 +286,148 @@ test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is
assert.equal(h.isCarbonModelIdentifier(ORCH_ARGON, 'gemini-pro-orchestrator-argon', 'Orchestrator (Argon)'), false); assert.equal(h.isCarbonModelIdentifier(ORCH_ARGON, 'gemini-pro-orchestrator-argon', 'Orchestrator (Argon)'), false);
}); });
test('Orchestrator (Neon) resolves to orch-neon, annotates upstream ID, uses Neon pricing, and is not misclassified as Carbon', async () => {
const rows = [step(1, ORCH_NEON), step(2, ORCH_EXEC_HYDROGEN)];
const h = backendHarness({
clock: () => PROMO_CLOCK_MS,
summaries: { test: { stepCount: 2 } },
trajectories: {
test: {
trajectory: {
steps: rows,
generatorMetadata: [
{
stepIndices: [1],
chatModel: {
model: ORCH_NEON,
responseModel: 'gemini-pro-orchestrator-neon',
modelDisplayName: 'Orchestrator (Neon)',
},
plannerConfig: {
planModel: ORCH_NEON,
modelName: 'gemini-pro-orchestrator-neon',
planExecuteConfig: { executionModel: ORCH_EXEC_HYDROGEN },
},
},
{
stepIndices: [2],
chatModel: {
model: ORCH_EXEC_HYDROGEN,
responseModel: 'gemini-flash-worker-agy',
modelDisplayName: 'Gemini Flash',
},
},
],
},
},
},
});
const p = await h.buildTelemetryPayloadInternal('test');
const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1);
const s2 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2);
assert.equal(s1.modelShort, 'orch-neon');
assert.equal(s1.modelLabel, 'Orchestrator (Neon)');
assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator-neon (neon-4)');
// step() fixture: 1000 input ($3/M = 0.003) + 9000 cache ($0.15/M = 0.00135) + 1000 output ($15/M = 0.015) = 0.01935 -> 0.0193 (4-decimal payload rounding)
assert.equal(s1.costUsd, 0.0193);
assert.equal(s2.modelShort, 'hydrogen-4');
assert.equal(s2.modelLabel, 'Orchestrator Worker (Hydrogen)');
assert.equal(s2.modelUpstream, 'gemini-flash-worker-agy (hydrogen-4)');
const neonRow = p.modelBreakdown.find((m) => m.label === 'Orchestrator (Neon)');
assert.ok(neonRow, 'modelBreakdown keeps Orchestrator (Neon) separate');
assert.equal(neonRow.upstreamName, 'gemini-pro-orchestrator-neon (neon-4)');
assert.equal(h.isNeonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), true);
assert.equal(h.isCarbonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), false);
assert.equal(h.isCarbonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator', 'Orchestrator (Neon)'), false);
assert.equal(h.isArgonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), false);
// Pure placeholder lookup without modelDisplayName / responseModel
const neonOrchInfo = h.resolveModelInfo(ORCH_NEON);
assert.equal(neonOrchInfo.shortName, 'orch-neon');
assert.equal(neonOrchInfo.label, 'Orchestrator (Neon)');
assert.equal(neonOrchInfo.pricing.input, 3.0);
assert.equal(neonOrchInfo.pricing.output, 15.0);
const neonXhighInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M535');
assert.equal(neonXhighInfo.shortName, 'neon-4-xhigh');
assert.equal(neonXhighInfo.baseLabel, 'Gemini 4 Neon');
assert.equal(neonXhighInfo.pricing.input, 3.0);
assert.equal(neonXhighInfo.pricing.output, 15.0);
});
test('future uncatalogued Orchestrator variants never fall back to Carbon identity, pricing, or display', async () => {
const FUTURE_ORCH_1 = 'MODEL_PLACEHOLDER_M991';
const FUTURE_ORCH_2 = 'MODEL_PLACEHOLDER_M992';
const rows = [step(1, FUTURE_ORCH_1), step(2, FUTURE_ORCH_2)];
const h = backendHarness({
clock: () => PROMO_CLOCK_MS,
summaries: { test: { stepCount: 2 } },
trajectories: {
test: {
trajectory: {
steps: rows,
generatorMetadata: [
{
stepIndices: [1],
chatModel: {
model: FUTURE_ORCH_1,
responseModel: 'gemini-pro-orchestrator-xenon',
modelDisplayName: 'Orchestrator (Xenon)',
},
},
{
stepIndices: [2],
chatModel: {
model: FUTURE_ORCH_2,
responseModel: 'gemini-pro-orchestrator',
modelDisplayName: 'Orchestrator (Helium)',
},
},
],
},
},
},
});
const p = await h.buildTelemetryPayloadInternal('test');
const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1);
const s2 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2);
// Neither future variant may be misclassified as Carbon, given Carbon pricing, or stamped (carbon-4)
assert.equal(h.isCarbonModelIdentifier(FUTURE_ORCH_1, 'gemini-pro-orchestrator-xenon', 'Orchestrator (Xenon)'), false);
assert.equal(h.isCarbonModelIdentifier(FUTURE_ORCH_2, 'gemini-pro-orchestrator', 'Orchestrator (Helium)'), false);
assert.equal(s1.costUsd, null);
assert.equal(s2.costUsd, null);
assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator-xenon');
assert.equal(s2.modelUpstream, 'gemini-pro-orchestrator');
assert.notEqual(s1.modelShort, 'orch-carbon');
assert.notEqual(s2.modelShort, 'orch-carbon');
// Frontend dynamically renders orchestrator-<variant> without silently falling back to orchestrator-carbon
assert.equal(resolveModelDisplayInfo(s1, { orchestratorIdMode: 'compact' }).text, 'orchestrator-xenon');
assert.equal(resolveModelDisplayInfo(s1, { orchestratorIdMode: 'full' }).text, 'gemini-pro-orchestrator-xenon');
assert.equal(resolveModelDisplayInfo(s2, { orchestratorIdMode: 'compact' }).text, 'orchestrator-helium');
assert.equal(resolveModelDisplayInfo(s2, { orchestratorIdMode: 'full' }).text, 'gemini-pro-orchestrator (helium)');
// Direct non-Orchestrator Carbon/Argon/Neon models remain unaffected
assert.equal(
resolveModelDisplayInfo(
{ modelKey: 'MODEL_PLACEHOLDER_M429', modelShort: 'carbon-4-high', modelLabel: 'Gemini 4 Carbon (High)', modelUpstream: 'gemini-4-carbon-high' },
{ showUpstreamModel: false, orchestratorIdMode: 'compact' }
).text,
'carbon-4-high'
);
assert.equal(
resolveModelDisplayInfo(
{ modelKey: 'MODEL_PLACEHOLDER_M535', modelShort: 'neon-4-xhigh', modelLabel: 'Gemini 4 Neon (XHigh)', modelUpstream: 'gemini-4-neon-xhigh' },
{ showUpstreamModel: false, orchestratorIdMode: 'compact' }
).text,
'neon-4-xhigh'
);
});
test('real-world M669 worker steps (responseModel gemini-flash-worker-agy, displayName Gemini Flash) and uncatalogued executionModel resolve to Hydrogen', async () => { test('real-world M669 worker steps (responseModel gemini-flash-worker-agy, displayName Gemini Flash) and uncatalogued executionModel resolve to Hydrogen', async () => {
const FUTURE_EXEC_PH = 'MODEL_PLACEHOLDER_M799'; const FUTURE_EXEC_PH = 'MODEL_PLACEHOLDER_M799';
const rows = [step(1, ORCH_CARBON), step(2, ORCH_EXEC_HYDROGEN), step(3, FUTURE_EXEC_PH)]; const rows = [step(1, ORCH_CARBON), step(2, ORCH_EXEC_HYDROGEN), step(3, FUTURE_EXEC_PH)];
@@ -428,6 +571,21 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
modelUpstream: 'gemini-pro-orchestrator-argon (argon-4)', modelUpstream: 'gemini-pro-orchestrator-argon (argon-4)',
responseModel: 'gemini-pro-orchestrator-argon', responseModel: 'gemini-pro-orchestrator-argon',
}; };
const orchNeon = {
modelKey: ORCH_NEON,
modelShort: 'orch-neon',
modelLabel: 'Orchestrator (Neon)',
modelUpstream: 'gemini-pro-orchestrator-neon (neon-4)',
responseModel: 'gemini-pro-orchestrator-neon',
};
const orchNeonCompaction = {
modelKey: ORCH_NEON,
modelShort: 'orch-neon·压缩',
modelLabel: 'Orchestrator (Neon) [自动压缩]',
modelUpstream: 'gemini-pro-orchestrator-neon (neon-4)·压缩',
responseModel: 'gemini-pro-orchestrator-neon',
isCompactionStep: true,
};
const orchWorkerCompaction = { const orchWorkerCompaction = {
modelKey: ORCH_EXEC_HYDROGEN, modelKey: ORCH_EXEC_HYDROGEN,
modelShort: 'hydrogen-4·压缩', modelShort: 'hydrogen-4·压缩',
@@ -452,6 +610,14 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
'orchestrator-argon' 'orchestrator-argon'
); );
assert.equal(
resolveModelDisplayInfo(orchNeon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
'orchestrator-neon'
);
assert.equal(
resolveModelDisplayInfo(orchNeonCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
'orchestrator-neon·压缩'
);
assert.equal( assert.equal(
resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
'worker-agy-hydrogen·压缩' 'worker-agy-hydrogen·压缩'
@@ -464,6 +630,14 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'full' }).text, resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
'gemini-pro-orchestrator-argon (argon-4)' 'gemini-pro-orchestrator-argon (argon-4)'
); );
assert.equal(
resolveModelDisplayInfo(orchNeon, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
'gemini-pro-orchestrator-neon (neon-4)'
);
assert.equal(
resolveModelDisplayInfo(orchNeonCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
'gemini-pro-orchestrator-neon (neon-4)·压缩'
);
assert.equal( assert.equal(
resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text, resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
'gemini-flash-worker-agy (hydrogen-4)·压缩' 'gemini-flash-worker-agy (hydrogen-4)·压缩'
+68 -22
View File
@@ -6,6 +6,7 @@ import {
DEFAULT_SETTINGS_SCHEMA, DEFAULT_SETTINGS_SCHEMA,
normalizeExperimentalModernUi, normalizeExperimentalModernUi,
normalizeFullSettings, normalizeFullSettings,
normalizeModernUi,
} from '../backend/settings-schema.mjs'; } from '../backend/settings-schema.mjs';
import { import {
applyAppearanceToRoot, applyAppearanceToRoot,
@@ -38,27 +39,44 @@ import { StepsDetailView } from '../src/views/StepsDetailView.js';
import { SettingsGeneralTab } from '../src/views/settings/SettingsGeneralTab.js'; import { SettingsGeneralTab } from '../src/views/settings/SettingsGeneralTab.js';
import { SettingsStructureTab } from '../src/views/settings/SettingsStructureTab.js'; import { SettingsStructureTab } from '../src/views/settings/SettingsStructureTab.js';
test('experimentalModernUi schema normalization defaults to false and coerces boolean/string values cleanly', () => { test('modernUi schema normalization defaults to true, upgrades 1.5.2 settings without modernUi key to true, and respects explicit false', () => {
assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, false); assert.equal(DEFAULT_SETTINGS_SCHEMA.language, 'auto');
assert.equal(DEFAULT_SETTINGS_SCHEMA.modernUi, true);
assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, true);
assert.equal(normalizeModernUi(undefined), true);
assert.equal(normalizeModernUi(false), false);
assert.equal(normalizeModernUi('off'), false);
assert.equal(normalizeModernUi(true), true);
assert.equal(normalizeModernUi('true'), true);
assert.equal(normalizeModernUi('on'), true);
assert.equal(normalizeExperimentalModernUi(undefined), false); assert.equal(normalizeExperimentalModernUi(undefined), false);
assert.equal(normalizeExperimentalModernUi(false), false); assert.equal(normalizeClientModernUi(undefined), true);
assert.equal(normalizeExperimentalModernUi('off'), false);
assert.equal(normalizeExperimentalModernUi(true), true);
assert.equal(normalizeExperimentalModernUi('true'), true);
assert.equal(normalizeExperimentalModernUi('on'), true);
assert.equal(normalizeClientModernUi('on'), true); assert.equal(normalizeClientModernUi('on'), true);
assert.equal(normalizeClientModernUi(false), false); assert.equal(normalizeClientModernUi(false), false);
assert.equal(normalizeClientModernUi('off'), false);
assert.equal(normalizeFullSettings({}).experimentalModernUi, false); // Fresh 1.5.3 install -> language='auto', modernUi=true
assert.equal(normalizeFullSettings({ experimentalModernUi: true }).experimentalModernUi, true); assert.equal(normalizeFullSettings({}).language, 'auto');
assert.equal(normalizeFullSettings({}).modernUi, true);
assert.equal(normalizeFullSettings({}).experimentalModernUi, true);
// 1.5.2 persisted settings.json (where experimentalModernUi: false was written by default, no modernUi key) -> upgrades to true!
const upgradedFrom152 = normalizeFullSettings({ experimentalModernUi: false });
assert.equal(upgradedFrom152.modernUi, true);
assert.equal(upgradedFrom152.experimentalModernUi, true);
// Explicit 1.5.3 user opt-out (`modernUi: false`) -> stays false!
const explicitOff153 = normalizeFullSettings({ modernUi: false, experimentalModernUi: true });
assert.equal(explicitOff153.modernUi, false);
assert.equal(explicitOff153.experimentalModernUi, false);
assert.equal( assert.equal(
isEquivalentTelemetry( isEquivalentTelemetry(
{ settings: { experimentalModernUi: false } }, { settings: { modernUi: false } },
{ settings: { experimentalModernUi: true } } { settings: { modernUi: true } }
), ),
false, false,
'isEquivalentTelemetry must detect experimentalModernUi changes' 'isEquivalentTelemetry must detect modernUi changes'
); );
}); });
@@ -182,29 +200,41 @@ test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data-
assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false);
assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light');
// 2. SettingsGeneralTab renders '新 UI(实验性)' switch and toggles data-modern-ui immediately // 2. SettingsGeneralTab renders '现代化 UI' (开启 / 关闭) and Language (跟随系统 / 简体中文 / English)
tab = SettingsGeneralTab({}); tab = SettingsGeneralTab({});
document.body.appendChild(tab.el); document.body.appendChild(tab.el);
tab.refs.renderSettings({ tab.refs.renderSettings({
language: 'zh-CN', language: 'auto',
themeAccent: 'host', themeAccent: 'host',
fontScale: 'md', fontScale: 'md',
modernUi: false,
experimentalModernUi: false, experimentalModernUi: false,
pluginUpdateMode: 'manual', pluginUpdateMode: 'manual',
}); });
assert.match(tab.el.textContent, /新 UI(实验性)/); assert.match(tab.el.textContent, /现代化 UI/);
const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); assert.doesNotMatch(tab.el.textContent, /实验性/);
assert.equal(modernBtns.length, 2); const langSegBtns = tab.refs.languageSwitch.el.querySelectorAll('.seg-btn');
assert.equal(modernBtns[0].classList.contains('is-active'), true); assert.deepEqual(
langSegBtns.map((b) => b.textContent),
['跟随系统', '简体中文', 'English']
);
assert.equal(langSegBtns[0].classList.contains('is-active'), true);
// Click '开启' (index 1) const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn');
modernBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); assert.deepEqual(
modernBtns.map((b) => b.textContent),
['开启', '关闭']
);
assert.equal(modernBtns[1].classList.contains('is-active'), true);
// Click '开启' (index 0)
modernBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15)); await new Promise((r) => setTimeout(r, 15));
assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true');
assert.equal(savedPatches.length, 1); assert.equal(savedPatches.length, 1);
assert.equal(savedPatches[0].experimentalModernUi, true); assert.equal(savedPatches[0].modernUi, true);
// 3. Built styles.css contains modern-ui borderless, sliding glider, and crisp pure-white light-mode rules // 3. Built styles.css contains modern-ui borderless, sliding glider, and crisp pure-white light-mode rules
const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
@@ -249,6 +279,18 @@ test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data-
builtStyles, builtStyles,
/\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-tracking\s*\{[^}]*150ms/ /\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-tracking\s*\{[^}]*150ms/
); );
assert.match(
builtStyles,
/\.trend-tip-sub\s*\{[^}]*background:\s*transparent;/
);
assert.match(
builtStyles,
/\.trend-tip-cost\s*\{[^}]*background:\s*transparent;/
);
assert.match(
builtStyles,
/\[data-modern-ui="true"\]\s+\.trend-tip-sub,\s*\[data-modern-ui="true"\]\s+\.trend-tip-cost\s*\{[^}]*background:\s*transparent;/
);
assert.match( assert.match(
builtStyles, builtStyles,
/\[data-modern-ui="true"\]\.wm-multi-panel\s+\.live-task-card[\s\S]*?background:\s*transparent;/ /\[data-modern-ui="true"\]\.wm-multi-panel\s+\.live-task-card[\s\S]*?background:\s*transparent;/
@@ -1147,7 +1189,11 @@ test('Capsule odometer digit rolling (0.15s) and color transition (0.1s) stay st
// 4. Compiled CSS strictly scopes 150ms roll & 100ms color transition under [data-modern-ui="true"] // 4. Compiled CSS strictly scopes 150ms roll & 100ms color transition under [data-modern-ui="true"]
const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
assert.match(builtStyles, /\.steps-inline-scope-select\s+\.select-menu[\s\S]*?left:\s*0;\s*right:\s*auto;/); assert.match(builtStyles, /\.steps-inline-scope-select\s+\.select-menu[\s\S]*?left:\s*auto;\s*right:\s*0;/);
assert.match(
builtStyles,
/\[data-modern-ui="true"\]\s+\.select-menu,[\s\S]*?animation:\s*anim-modern-tip-fade\s+120ms/
);
assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.select-menu\.is-above/); assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.select-menu\.is-above/);
assert.match( assert.match(
builtStyles, builtStyles,
File diff suppressed because it is too large Load Diff
+104 -4
View File
@@ -11,6 +11,7 @@ import { i18nStore } from '../src/i18n/index.js';
import { import {
buildModelAnomalyDiagnostic, buildModelAnomalyDiagnostic,
buildStepAnomalyDiagnostic, buildStepAnomalyDiagnostic,
buildStepCompactionDiagnostic,
formatAnomalyTagText, formatAnomalyTagText,
formatMetric, formatMetric,
formatSpeedMetric, formatSpeedMetric,
@@ -420,6 +421,15 @@ test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY.
STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 42.3 }); STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 42.3 });
assert.equal(durCell.refs.valEl.textContent, '42.3s'); assert.equal(durCell.refs.valEl.textContent, '42.3s');
// Compaction steps keep normal TTFT formatting ("—" when null) instead of overriding the cell
const compactTtftCell = STEP_COLUMN_REGISTRY.ttft.createCell();
i18nStore.setState({ locale: 'zh-CN' });
STEP_COLUMN_REGISTRY.ttft.updateCell(compactTtftCell.refs, { isCompactionStep: true, ttftSec: null });
assert.equal(compactTtftCell.refs.valEl.textContent, '—');
assert.notEqual(compactTtftCell.refs.valEl.getAttribute('class'), 'step-ttft-compaction');
STEP_COLUMN_REGISTRY.ttft.updateCell(compactTtftCell.refs, { isCompactionStep: false, ttftSec: 5.2 });
assert.equal(compactTtftCell.refs.valEl.textContent, '5.2s');
// ContextSegmentMeter renders crisp separated blocks (.ctx-segment-meter + .is-active + .has-sep) // ContextSegmentMeter renders crisp separated blocks (.ctx-segment-meter + .is-active + .has-sep)
const meter = ContextSegmentMeter({ const meter = ContextSegmentMeter({
context: { context: {
@@ -509,6 +519,47 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and
ttftSec: 1.4, ttftSec: 1.4,
anomalySig: '', anomalySig: '',
}, },
{
stepIndex: 4918,
modelShort: '4-neon',
modelLabel: '4-neon',
isCompactionStep: true,
inputTokens: 120000,
cacheReadTokens: 400000,
outputTokens: 4400,
tokPerSec: 86.6,
ttftSec: null,
anomalySig: '',
},
{
stepIndex: 4916,
modelShort: '4-neon',
modelLabel: '4-neon',
isCompactionStep: true,
inputTokens: 100000,
cacheReadTokens: 300000,
outputTokens: 2100,
tokPerSec: null,
selectedSpeedReason: 'error',
ttftSec: null,
anomalySig: 'timeout:1:w:1.5',
anomaly: {
count: 1,
primaryKind: 'timeout',
severity: 'warn',
totalDelaySec: 1.5,
kinds: { timeout: 1 },
events: [
{
attempt: 1,
kind: 'timeout',
delaySec: 1.5,
terminal: false,
message: 'compaction stream idle timeout',
},
],
},
},
]; ];
widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', { widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', {
@@ -520,7 +571,7 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and
// Zero extra columns and zero inline text badges added to table cells // Zero extra columns and zero inline text badges added to table cells
assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length); assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length);
const rows = widget.refs.stepsTbody.children; const rows = widget.refs.stepsTbody.children;
assert.equal(rows.length, 3); assert.equal(rows.length, 5);
assert.equal(rows[0].children.length, colKeys.length); assert.equal(rows[0].children.length, colKeys.length);
assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column'); assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column');
@@ -533,16 +584,24 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and
assert.equal(rows[1].classList.contains('is-anomaly-danger'), true); assert.equal(rows[1].classList.contains('is-anomaly-danger'), true);
assert.equal(rows[1].classList.contains('is-anomaly-warn'), false); assert.equal(rows[1].classList.contains('is-anomaly-warn'), false);
// Row 2: normal step has NO anomaly row classes and keeps 1 decimal < 100 tok/s // Row 2: normal step has NO anomaly/compaction row classes and keeps 1 decimal < 100 tok/s
assert.equal(rows[2].classList.contains('is-anomaly-warn'), false); assert.equal(rows[2].classList.contains('is-anomaly-warn'), false);
assert.equal(rows[2].classList.contains('is-anomaly-danger'), false); assert.equal(rows[2].classList.contains('is-anomaly-danger'), false);
assert.equal(rows[2].classList.contains('is-compaction'), false);
assert.equal(rows[2].children[2].textContent, '65.7 tok/s'); assert.equal(rows[2].children[2].textContent, '65.7 tok/s');
// Row 3: pure compaction step uses host-accent row tint, keeps TTFT as "—", and shows compaction hover popover
assert.equal(rows[3].classList.contains('is-compaction'), true);
assert.equal(rows[3].classList.contains('is-anomaly-warn'), false);
assert.equal(rows[3].classList.contains('is-anomaly-danger'), false);
assert.equal(rows[3].children[3].textContent, '—');
// Hovering the tinted row expands the structured diagnostic popover // Hovering the tinted row expands the structured diagnostic popover
const tipEl = widget.refs.anomalyTipEl; const tipEl = widget.refs.anomalyTipEl;
assert.equal(tipEl.hasAttribute('hidden'), true); assert.equal(tipEl.hasAttribute('hidden'), true);
rows[0].onmouseenter(); rows[0].onmouseenter();
assert.equal(tipEl.hasAttribute('hidden'), false); assert.equal(tipEl.hasAttribute('hidden'), false);
assert.equal(tipEl.classList.contains('is-compaction'), false);
assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/); assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/);
assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s'); assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s');
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/); assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/);
@@ -550,19 +609,44 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and
rows[0].onmouseleave(); rows[0].onmouseleave();
assert.equal(tipEl.hasAttribute('hidden'), true); assert.equal(tipEl.hasAttribute('hidden'), true);
// Hovering danger row sets danger style on tooltip // Hovering compaction row displays host-accent compaction popover matching warning popover structure
rows[3].onmouseenter();
assert.equal(tipEl.hasAttribute('hidden'), false);
assert.equal(tipEl.classList.contains('is-compaction'), true);
assert.equal(tipEl.classList.contains('is-danger'), false);
assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4918.*自动压缩/);
assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '4-neon');
assert.match(tipEl.querySelector('.step-anomaly-tip-row').textContent, /输入 520\.0k → 摘要输出 4\.4k/);
assert.equal(tipEl.querySelector('.step-anomaly-tip-detail').classList.contains('text-mono'), false);
rows[3].onmouseleave();
assert.equal(tipEl.hasAttribute('hidden'), true);
// Hovering danger row sets danger style and clears compaction style on tooltip
rows[1].onmouseenter(); rows[1].onmouseenter();
assert.equal(tipEl.hasAttribute('hidden'), false); assert.equal(tipEl.hasAttribute('hidden'), false);
assert.equal(tipEl.classList.contains('is-danger'), true); assert.equal(tipEl.classList.contains('is-danger'), true);
assert.equal(tipEl.classList.contains('is-compaction'), false);
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/); assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/);
rows[1].onmouseleave(); rows[1].onmouseleave();
assert.equal(tipEl.hasAttribute('hidden'), true); assert.equal(tipEl.hasAttribute('hidden'), true);
// Row 4: hybrid compaction + anomaly keeps anomaly diagnostic and appends compaction hint
assert.equal(rows[4].classList.contains('is-compaction'), true);
assert.equal(rows[4].classList.contains('is-anomaly-warn'), true);
rows[4].onmouseenter();
assert.equal(tipEl.hasAttribute('hidden'), false);
assert.equal(tipEl.classList.contains('is-compaction'), false);
assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4916.*异常 1 次/);
assert.match(tipEl.querySelector('.step-anomaly-tip-hint').textContent, /自动压缩/);
rows[4].onmouseleave();
assert.equal(tipEl.hasAttribute('hidden'), true);
// Verify helper outputs cleanly // Verify helper outputs cleanly
assert.equal(formatAnomalyTagText('capacity', 1), '503'); assert.equal(formatAnomalyTagText('capacity', 1), '503');
assert.equal(formatAnomalyTagText('capacity', 3), '503×3'); assert.equal(formatAnomalyTagText('capacity', 3), '503×3');
assert.ok(buildStepAnomalyDiagnostic(steps[0])); assert.ok(buildStepAnomalyDiagnostic(steps[0]));
assert.equal(buildStepAnomalyDiagnostic(steps[2]), null); assert.equal(buildStepAnomalyDiagnostic(steps[2]), null);
assert.equal(buildStepCompactionDiagnostic(steps[3]).severity, 'compaction');
} finally { } finally {
widget.destroy(); widget.destroy();
env.restore(); env.restore();
@@ -810,15 +894,31 @@ test('Compiled styles.css centers odometer capsule slot text and ships both clas
'Context percentage slot stays left-aligned next to its progress ring' 'Context percentage slot stays left-aligned next to its progress ring'
); );
// Universal Classic + Modern UI anomaly styling // Universal Classic + Modern UI compaction & anomaly styling (anomaly overrides compaction if both occur)
const classicCompactIdx = builtCss.indexOf('tr.is-compaction {');
const classicWarnIdx = builtCss.indexOf('tr.is-anomaly-warn {');
assert.ok(classicCompactIdx > 0 && classicWarnIdx > classicCompactIdx, 'Classic tr.is-compaction precedes tr.is-anomaly-warn');
assert.match(builtCss, /tr\.is-compaction\s*\{[^}]*var\(--accent-primary\)/);
assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-compaction[\s\S]*?var\(--accent-primary\)/);
assert.match(builtCss, /\.step-anomaly-tip\.is-compaction[\s\S]*?var\(--accent-primary\)/);
assert.doesNotMatch(builtCss, /\.step-ttft-compaction/);
assert.match(builtCss, /tr\.is-anomaly-warn\s*\{/); assert.match(builtCss, /tr\.is-anomaly-warn\s*\{/);
assert.match(builtCss, /tr\.is-anomaly-danger\s*\{/); assert.match(builtCss, /tr\.is-anomaly-danger\s*\{/);
assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-anomaly-warn/); assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-anomaly-warn/);
assert.match(builtCss, /\.form-row\s*>\s*\.custom-select\s*>\s*\.select-trigger\s*\{[^}]*border:\s*none;[^}]*border-radius:\s*var\(--radius-pill\)/s);
assert.match(builtCss, /\.steps-header-filters\s*\{[\s\S]*?justify-content:\s*flex-end;[\s\S]*?margin-left:\s*auto;/);
assert.match(builtCss, /\.steps-inline-scope-select,\s*\.steps-inline-model-select\s*\{[\s\S]*?flex:\s*0\s+1\s+auto;/);
assert.match(builtCss, /\.steps-inline-scope-select\s+\.select-trigger[\s\S]*?border-radius:\s*var\(--radius-pill\)/);
assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.form-row\s*>\s*\.custom-select\s*>\s*\.select-trigger,[\s\S]*?\.steps-inline-scope-select\s+\.select-trigger[\s\S]*?border-radius:\s*var\(--radius-pill\)[\s\S]*?var\(--modern-pill-select-bg\)/);
assert.match(builtCss, /\.step-anomaly-tag\s*\{/); assert.match(builtCss, /\.step-anomaly-tag\s*\{/);
assert.match(builtCss, /\.step-anomaly-tip\s*\{/); assert.match(builtCss, /\.step-anomaly-tip\s*\{/);
assert.match(builtCss, /\.steps-anomaly-strip\s*\{/); assert.match(builtCss, /\.steps-anomaly-strip\s*\{/);
assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/); assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/);
assert.match(builtCss, /\.sstep-anomaly-dot/); assert.match(builtCss, /\.sstep-anomaly-dot/);
assert.match(builtCss, /\.panel\s*>\s*\.table-scroll-host\s*\{[\s\S]*?margin-right:\s*calc\(-1\s*\*\s*var\(--space-5\)\s*\+\s*2px\)/);
assert.match(builtCss, /\.panel\s*>\s*\.table-scroll-host\s*>\s*\.custom-scroll-content\s*\{[\s\S]*?padding-right:\s*calc\(var\(--space-5\)\s*-\s*2px\)/);
assert.doesNotMatch(builtCss, /\.models-analytics-pane\s*\{[^}]*padding:\s*var\(--space-3\)\s+0\s+2px/);
assert.match(builtCss, /\.trend-tip-sub\.is-grid\s*\{[\s\S]*?grid-template-columns:\s*repeat\(3,\s*minmax\(0,\s*1fr\)\)/);
assert.match(builtCss, /\.trend-tip-anomaly/); assert.match(builtCss, /\.trend-tip-anomaly/);
assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/); assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/);
assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s*\{[\s\S]*?height:\s*6px;/); assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s*\{[\s\S]*?height:\s*6px;/);
+57 -41
View File
@@ -1234,10 +1234,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
capsuleHost.shadowRoot.children.indexOf(capsuleBtn), capsuleHost.shadowRoot.children.indexOf(capsuleBtn),
'Multi-session button sits immediately to the left of telemetry capsule' 'Multi-session button sits immediately to the left of telemetry capsule'
); );
assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true', 'Modern UI enabled out-of-the-box');
const readCapVal = (el) => el.getAttribute('data-od-value') ?? el.textContent;
assert.equal(multiBtn.querySelector('.svg-icon'), null, 'Multi-session button has zero SVG clutter'); assert.equal(multiBtn.querySelector('.svg-icon'), null, 'Multi-session button has zero SVG clutter');
assert.equal(multiBtn.classList.contains('is-running'), true); assert.equal(multiBtn.classList.contains('is-running'), true);
const multiLabelEl = multiBtn.querySelector('.wm-multi-label'); const multiLabelEl = multiBtn.querySelector('.wm-multi-label');
assert.equal(multiLabelEl.textContent, '2 运行 · 1 子'); assert.equal(readCapVal(multiLabelEl), '2 运行 · 1 子');
// Verify capsule reactive text (default order: 92.4 t/s without bolt SVG, 0.85s TTFT, 50% context) // Verify capsule reactive text (default order: 92.4 t/s without bolt SVG, 0.85s TTFT, 50% context)
const defaultCapSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot'); const defaultCapSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
@@ -1248,9 +1250,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(defaultCapSlots[2].getAttribute('data-metric'), 'context'); assert.equal(defaultCapSlots[2].getAttribute('data-metric'), 'context');
assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG'); assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG');
assert.equal(speedSegEl.querySelector('.svg-icon'), null); assert.equal(speedSegEl.querySelector('.svg-icon'), null);
assert.ok(speedSegEl.children[0].textContent.includes('92.4 t/s')); assert.ok(readCapVal(speedSegEl.children[0]).includes('92.4 t/s'));
assert.equal(defaultCapSlots[1].children[0].textContent, '0.85s'); assert.equal(readCapVal(defaultCapSlots[1].children[0]), '0.85s');
assert.equal(ctxPctEl.textContent, '50%'); assert.equal(readCapVal(ctxPctEl), '50%');
// Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions // Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions
const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel'); const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel');
@@ -1411,22 +1413,28 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const langBtns = generalSegControls[0].querySelectorAll('.seg-btn'); const langBtns = generalSegControls[0].querySelectorAll('.seg-btn');
const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn'); const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn');
const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn'); const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn');
assert.equal(modernUiBtns.length, 2, 'Experimental Modern UI switch has 关闭 / 开启'); assert.equal(modernUiBtns.length, 2, 'Modern UI switch has 开启 / 关闭');
assert.equal(modernUiBtns[0].textContent, '开启');
assert.equal(modernUiBtns[1].textContent, '关闭');
modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.modernUi, false);
assert.equal(mockSettings.experimentalModernUi, false);
assert.equal(portalHost.hasAttribute('data-modern-ui'), false);
assert.equal(popoverEl.hasAttribute('data-modern-ui'), false);
modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.modernUi, true);
assert.equal(mockSettings.experimentalModernUi, true); assert.equal(mockSettings.experimentalModernUi, true);
assert.equal(portalHost.getAttribute('data-modern-ui'), 'true'); assert.equal(portalHost.getAttribute('data-modern-ui'), 'true');
assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true'); assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true');
assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true'); assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true');
modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); assert.equal(langBtns.length, 3, 'Language switch has 跟随系统 / 简体中文 / English');
await new Promise((r) => setTimeout(r, 30)); assert.equal(langBtns[0].textContent, '跟随系统');
assert.equal(mockSettings.experimentalModernUi, false); assert.equal(langBtns[1].textContent, '简体中文');
assert.equal(portalHost.hasAttribute('data-modern-ui'), false); assert.equal(langBtns[2].textContent, 'English');
assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); assert.equal(langBtns[1].classList.contains('is-active'), true, 'mockSettings language zh-CN selects index 1');
assert.equal(langBtns.length, 3, 'Language switch has 简体中文 / English / 跟随宿主');
assert.equal(langBtns[0].textContent, '简体中文');
assert.equal(langBtns[0].classList.contains('is-active'), true, 'Default language is zh-CN');
const generalSelects = generalPane.querySelectorAll('.custom-select'); const generalSelects = generalPane.querySelectorAll('.custom-select');
assert.equal(generalSelects.length, 1, 'General tab has Update Mode select'); assert.equal(generalSelects.length, 1, 'General tab has Update Mode select');
const updateModeSelectEl = generalSelects[0]; const updateModeSelectEl = generalSelects[0];
@@ -1466,8 +1474,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(portalHost.getAttribute('data-font-scale'), 'md'); assert.equal(portalHost.getAttribute('data-font-scale'), 'md');
assert.equal(popoverEl.getAttribute('data-font-scale'), 'md'); assert.equal(popoverEl.getAttribute('data-font-scale'), 'md');
// Live i18n switch: zh-CN -> en-US -> zh-CN without page reload // Live i18n switch: zh-CN -> en-US (index 2) -> auto (index 0) -> zh-CN (index 1) without page reload
langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); langBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.language, 'en-US'); assert.equal(mockSettings.language, 'en-US');
assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, 'Live'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, 'Live');
@@ -1477,6 +1485,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(subNavBtns[2].textContent, 'Other'); assert.equal(subNavBtns[2].textContent, 'Other');
langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.language, 'auto');
langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.language, 'zh-CN'); assert.equal(mockSettings.language, 'zh-CN');
assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, '实时监控'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, '实时监控');
assert.equal(subNavBtns[0].textContent, '常规'); assert.equal(subNavBtns[0].textContent, '常规');
@@ -1570,10 +1581,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview'); assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview');
assert.equal(previewCapsuleBar.querySelector('.preview-win-controls'), null, 'No redundant 3 window dots after capsule'); assert.equal(previewCapsuleBar.querySelector('.preview-win-controls'), null, 'No redundant 3 window dots after capsule');
assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots'); assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots');
assert.equal(previewCapsuleSlots[0].children[0].textContent, '68.4 t/s', 'Preview slot 0 renders simulated speed'); assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '68.4 t/s', 'Preview slot 0 renders simulated speed');
assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards'); assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards');
assert.equal(previewCapsuleSlots[1].children[0].textContent, '1.1s', 'Preview slot 1 renders simulated TTFT'); assert.equal(readCapVal(previewCapsuleSlots[1].children[0]), '1.1s', 'Preview slot 1 renders simulated TTFT');
assert.equal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview slot 2 renders simulated context %'); assert.equal(readCapVal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct')), '56%', 'Preview slot 2 renders simulated context %');
assert.deepEqual(
previewCapsuleBar.querySelectorAll('.preview-composer-chip').map((c) => c.textContent.trim()),
['Carbon (High)'],
'Composer preview bar shows only Carbon (High) chip without Auto'
);
const mountSelectEl = sec0.querySelectorAll('.custom-select')[0]; const mountSelectEl = sec0.querySelectorAll('.custom-select')[0];
// Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar) // Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar)
@@ -1664,26 +1680,26 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
assert.equal(capSlots[0].children[0].textContent, '余 44%'); assert.equal(readCapVal(capSlots[0].children[0]), '余 44%');
assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h'); assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h');
assert.equal(previewCapsuleSlots[0].children[0].textContent, '余 64%', 'Preview slot 0 renders simulated gemini_5h'); assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '余 64%', 'Preview slot 0 renders simulated gemini_5h');
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
assert.equal(capSlots[1].children[0].textContent, '0.85s'); assert.equal(readCapVal(capSlots[1].children[0]), '0.85s');
capRowSelects[2].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[2].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(capSlots[2].getAttribute('data-metric'), 'cost'); assert.equal(capSlots[2].getAttribute('data-metric'), 'cost');
assert.equal(capSlots[2].children.length, 1, 'Ring SVG detached cleanly when slot leaves context'); assert.equal(capSlots[2].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
assert.equal(capSlots[2].children[0].textContent, '$0.040'); assert.equal(readCapVal(capSlots[2].children[0]), '$0.040');
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']);
// Move Row 1 up (left): each row has [up, down, remove], so Row 1 up is index 3 // Move Row 1 up (left): each row has [up, down, remove], so Row 1 up is index 3
capSlotWrap.querySelectorAll('.slot-move-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} }); capSlotWrap.querySelectorAll('.slot-move-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']);
assert.equal(capSlots[0].children[0].textContent, '0.85s'); assert.equal(readCapVal(capSlots[0].children[0]), '0.85s');
assert.equal(capSlots[1].children[0].textContent, '余 44%'); assert.equal(readCapVal(capSlots[1].children[0]), '余 44%');
// Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft'] // Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft']
const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list'); const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list');
@@ -1755,7 +1771,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
assert.equal(capSlots[2].getAttribute('data-metric'), 'context'); assert.equal(capSlots[2].getAttribute('data-metric'), 'context');
assert.equal(capSlots[2].children.length, 2, 'Ring SVG re-attached on Slot 2'); assert.equal(capSlots[2].children.length, 2, 'Ring SVG re-attached on Slot 2');
assert.equal(capSlots[2].querySelector('.wm-ctx-pct').textContent, '50%'); assert.equal(readCapVal(capSlots[2].querySelector('.wm-ctx-pct')), '50%');
// Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview // Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview
const sec1 = accordionSections[1]; const sec1 = accordionSections[1];
@@ -2064,7 +2080,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Consumption sub-label renders CNY approx instead of 步费用待定' 'Consumption sub-label renders CNY approx instead of 步费用待定'
); );
assert.ok(popoverEl.querySelector('.steps-panel-header'), 'Steps header flex wrapper present'); assert.ok(popoverEl.querySelector('.steps-panel-header'), 'Steps header flex wrapper present');
assert.ok(popoverEl.querySelector('.steps-panel-title'), 'Steps title non-shrinking class present'); assert.equal(popoverEl.querySelector('.steps-panel-title'), null, 'Redundant steps header title removed');
// Verify <=90d renders flush edge-to-edge SVG line chart, while >90d ('all' = 120 days) switches to GitHub-style daily heatmap grid // Verify <=90d renders flush edge-to-edge SVG line chart, while >90d ('all' = 120 days) switches to GitHub-style daily heatmap grid
const plotStageEl = popoverEl.querySelector('.trend-plot-stage'); const plotStageEl = popoverEl.querySelector('.trend-plot-stage');
@@ -2093,8 +2109,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.match(stylesCss, /\.app-shell\s*\{[^}]*max-width:\s*none;/, 'Sidecar .app-shell removes 560px width cap'); assert.match(stylesCss, /\.app-shell\s*\{[^}]*max-width:\s*none;/, 'Sidecar .app-shell removes 560px width cap');
assert.match( assert.match(
stylesCss, stylesCss,
/\.models-analytics-pane\s*\{[^}]*padding:\s*var\(--space-3\)\s+0\s+2px;/, /\.models-analytics-pane\s*\{[^}]*padding-left:\s*0;/,
'Models analytics pane eliminates nested horizontal double-padding' 'Models analytics pane eliminates nested left double-padding while preserving right scrollbar clearance'
); );
assert.doesNotMatch( assert.doesNotMatch(
stylesCss, stylesCss,
@@ -2325,7 +2341,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-4-hydrogen'); assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-4-hydrogen');
assert.equal(smodelCards[0].querySelector('.smodel-calls-pill').textContent, '1次 · 50%'); assert.equal(smodelCards[0].querySelector('.smodel-calls-pill').textContent, '1次 · 50%');
assert.match(smodelCards[0].querySelector('.smodel-perf').textContent, /均速 92\.3 tok\/s · 首字 5\.6s · 缓存 93\.3%/); assert.match(smodelCards[0].querySelector('.smodel-perf').textContent, /均速 92\.3 tok\/s · 首字 5\.6s · 缓存 93\.3%/);
assert.match(smodelCards[0].querySelector('.smodel-split').textContent, /入 2\.5k · 缓 34\.6k · 思 420 · 正 265/); assert.match(smodelCards[0].querySelector('.smodel-split').textContent, /输入 2\.5k.*缓存 34\.6k.*思考 420.*输出 265/);
// Simulate live telemetry poll where a subagent spawns on 'Gemini 3 Flash' (changing activeModelLabel) // Simulate live telemetry poll where a subagent spawns on 'Gemini 3 Flash' (changing activeModelLabel)
// while the user remains inside 总汇总 -> fit model MUST NOT jump! // while the user remains inside 总汇总 -> fit model MUST NOT jump!
@@ -2644,13 +2660,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(delivered, 1); assert.equal(delivered, 1);
await new Promise((r) => setTimeout(r, 20)); await new Promise((r) => setTimeout(r, 20));
assert.equal( assert.equal(
defaultCapSlots[2].querySelector('.wm-ctx-pct').textContent, readCapVal(defaultCapSlots[2].querySelector('.wm-ctx-pct')),
'25%', '25%',
'CDP relay delivered live telemetry without HTTP' 'CDP relay delivered live telemetry without HTTP'
); );
assert.equal(defaultCapSlots[0].children[0].textContent, '121 t/s'); assert.equal(readCapVal(defaultCapSlots[0].children[0]), '121 t/s');
assert.equal(defaultCapSlots[1].hasAttribute('hidden'), false, 'TTFT slot stays pre-reserved even when latestTtftSec is absent'); assert.equal(defaultCapSlots[1].hasAttribute('hidden'), false, 'TTFT slot stays pre-reserved even when latestTtftSec is absent');
assert.equal(defaultCapSlots[1].children[0].textContent, '--s'); assert.equal(readCapVal(defaultCapSlots[1].children[0]), '--s');
assert.equal( assert.equal(
hoverLegendGrid.children[0], hoverLegendGrid.children[0],
firstLegendSlotBefore, firstLegendSlotBefore,
@@ -4526,7 +4542,7 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP
// 2. Verify frontend formatters, non-truncating compaction cell, custom token combo, trimmed model ID, adaptive width & CDP recovery // 2. Verify frontend formatters, non-truncating compaction cell, custom token combo, trimmed model ID, adaptive width & CDP recovery
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*flex-shrink:\s*0;/, 'Compaction suffix never shrinks/truncates'); assert.match(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*--accent-primary/, 'Compaction row uses whole-row host accent tint');
assert.match(stylesCss, /\.wm-popover-panel\s*\{[^}]*--wm-popover-w,\s*540px/, 'Popover supports dynamic CSS width variable'); assert.match(stylesCss, /\.wm-popover-panel\s*\{[^}]*--wm-popover-w,\s*540px/, 'Popover supports dynamic CSS width variable');
const savedSettings = { const savedSettings = {
@@ -4729,20 +4745,20 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP
// Adaptive width expands popover to fit wide 660px table (+ 34px chrome + 4px buffer = 698px) // Adaptive width expands popover to fit wide 660px table (+ 34px chrome + 4px buffer = 698px)
assert.equal(popEl.style.width, '698px', 'Popover adaptively widens on wide step table to eliminate horizontal scroll'); assert.equal(popEl.style.width, '698px', 'Popover adaptively widens on wide step table to eliminate horizontal scroll');
// Verify trimmed raw IDs (hiding gemini-, claude-, gpt-) AND non-truncating compaction suffix // Verify trimmed raw IDs (hiding gemini-, claude-, gpt-) AND whole-row compaction tint (no inline ·压缩)
const bodyRows = stepTable.querySelector('tbody').querySelectorAll('tr'); const bodyRows = stepTable.querySelector('tbody').querySelectorAll('tr');
assert.equal(bodyRows.length, 3); assert.equal(bodyRows.length, 3);
const row0ModelName = bodyRows[0].querySelector('.step-model-name').textContent; const row0ModelName = bodyRows[0].querySelector('.step-model-name').textContent;
const row0Compact = bodyRows[0].querySelector('.step-model-compact');
assert.equal(row0ModelName, '4-hydrogen', 'Strips gemini- prefix from gemini-4-hydrogen'); assert.equal(row0ModelName, '4-hydrogen', 'Strips gemini- prefix from gemini-4-hydrogen');
assert.equal(row0Compact.hasAttribute('hidden'), false, 'Compaction badge visible as dedicated flex-shrink:0 span'); assert.equal(bodyRows[0].querySelector('.step-model-compact'), null, 'No inline ·压缩 span inside model cell');
assert.equal(row0Compact.textContent, '·压缩', 'Compaction suffix never merged into ellipsized span'); assert.equal(bodyRows[0].classList.contains('is-compaction'), true, 'Compaction step receives whole-row is-compaction class');
assert.equal(bodyRows[0].children[1].getAttribute('title'), 'gemini-4-hydrogen·压缩', 'Hover title keeps full upstream ID'); assert.equal(bodyRows[0].children[1].getAttribute('title'), 'gemini-4-hydrogen·压缩', 'Hover title keeps full upstream ID');
assert.equal(bodyRows[1].querySelector('.step-model-name').textContent, 'sonnet-4-6', 'Strips claude- prefix'); assert.equal(bodyRows[1].querySelector('.step-model-name').textContent, 'sonnet-4-6', 'Strips claude- prefix');
assert.equal(bodyRows[1].querySelector('.step-model-compact').hasAttribute('hidden'), true); assert.equal(bodyRows[1].classList.contains('is-compaction'), false);
assert.equal(bodyRows[2].querySelector('.step-model-name').textContent, '5.4-mini', 'Strips gpt- prefix'); assert.equal(bodyRows[2].querySelector('.step-model-name').textContent, '5.4-mini', 'Strips gpt- prefix');
assert.equal(bodyRows[2].classList.contains('is-compaction'), false);
// Verify In / Out / Cache column & Custom Combo column ('context:in:cache') // Verify In / Out / Cache column & Custom Combo column ('context:in:cache')
const ths = stepTable.querySelector('thead').querySelectorAll('th'); const ths = stepTable.querySelector('thead').querySelectorAll('th');
@@ -5504,9 +5520,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
assert.equal(relaunchMacRes.ok, true); assert.equal(relaunchMacRes.ok, true);
assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app');
assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity'); assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity');
assert.match(macSpawnArgs.args[1], /if osascript .* then .* fi/); assert.match(macSpawnArgs.args[1], /if osascript .* then .* pgrep -ax "\$AGY_APP_NAME".* fi/);
assert.match(macSpawnArgs.args[1], /pkill -TERM -x "\$AGY_APP_NAME"/); assert.match(macSpawnArgs.args[1], /pkill -TERM -ax "\$AGY_APP_NAME"/);
assert.match(macSpawnArgs.args[1], /pkill -KILL -x "\$AGY_APP_NAME"/); assert.match(macSpawnArgs.args[1], /pkill -KILL -ax "\$AGY_APP_NAME"/);
assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/);
// macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name // macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name
+197 -1
View File
@@ -887,7 +887,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
if ( if (
typeof execModel === 'string' && typeof execModel === 'string' &&
execModel.trim() && execModel.trim() &&
/orchestrator|MODEL_PLACEHOLDER_M(?:667|681)\b/i.test( /orchestrator|MODEL_PLACEHOLDER_M(?:667|681|537)\b/i.test(
`${pc?.modelName || ''} ${pc?.planModel || ''}` `${pc?.modelName || ''} ${pc?.planModel || ''}`
) )
) { ) {
@@ -3042,4 +3042,200 @@ export function isParkedOnSwarmWait(rawSteps = []) {
return false; return false;
} }
function parseSwarmToolArgs(rawToolCall) {
if (!rawToolCall || typeof rawToolCall !== 'object') return null;
const direct = rawToolCall.args || rawToolCall.arguments;
if (direct && typeof direct === 'object' && !Array.isArray(direct)) {
return direct;
}
const rawJson =
typeof rawToolCall.argumentsJson === 'string'
? rawToolCall.argumentsJson
: typeof direct === 'string'
? direct
: typeof rawToolCall.function?.arguments === 'string'
? rawToolCall.function.arguments
: '';
if (!rawJson.trim()) return null;
try {
const parsed = JSON.parse(rawJson);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
} catch {
return null;
}
}
function normalizeSwarmToolName(rawToolCall) {
return String(
rawToolCall?.name || rawToolCall?.toolName || rawToolCall?.function?.name || ''
)
.trim()
.toLowerCase()
.replace(/^default_api:/, '');
}
function isSwarmStepCompletedSuccess(step) {
const st = typeof step?.status === 'string' ? step.status.trim().toUpperCase() : '';
if (st) {
if (!LIVE_TERMINAL_STATUSES.has(st)) {
return false;
}
if (st.includes('ERROR') || st.includes('CANCEL') || st.includes('FAIL')) {
return false;
}
}
const tcSt =
typeof step?.metadata?.toolCall?.status === 'string'
? step.metadata.toolCall.status.trim().toUpperCase()
: '';
if (tcSt) {
if (
tcSt.includes('ERROR') ||
tcSt.includes('CANCEL') ||
tcSt.includes('FAIL') ||
/(?:WAIT|PEND|RUN|GENERAT|IN_PROGRESS|STREAM)/i.test(tcSt)
) {
return false;
}
}
return true;
}
function extractSwarmCallIntent(rawToolCall) {
const args = parseSwarmToolArgs(rawToolCall);
if (!args || typeof args.action !== 'string') return null;
const action = args.action.trim().toLowerCase();
if (action === 'title') {
if (typeof args.title !== 'string') return null;
const nextTitle = args.title.trim();
if (!nextTitle) return null;
return { action: 'title', value: nextTitle, sig: `title:${nextTitle}` };
}
if (action === 'kill') {
if (typeof args.name !== 'string') return null;
const member = args.name.trim().replace(/^@+/, '').toLowerCase();
if (!member) return null;
return { action: 'kill', value: member, sig: `kill:${member}` };
}
return null;
}
/**
* 从原始轨迹 RPC 步骤中提取 Native Swarm 元数据(纯 RPC 解析,无需读取远端磁盘 `members.json`):
* - `title`:最后一次成功调用 `swarm(action: "title")` 设置的蜂群标题;
* - `killedMembers`:被 `swarm(action: "kill")` 终止的工蜂成员名(小写去 `@`)及其终止时间戳映射。
*
* @param {Array<object>} [rawSteps=[]]
* @returns {{ title?: string, killedMembers?: Record<string, number> } | null}
*/
export function extractSwarmMetaFromSteps(rawSteps = []) {
if (!Array.isArray(rawSteps) || rawSteps.length === 0) return null;
const executedToolCallIds = new Set();
for (const st of rawSteps) {
const tc = st?.metadata?.toolCall;
if (!tc || normalizeSwarmToolName(tc) !== 'swarm') continue;
const tcId = String(tc.id || tc.toolCallId || '').trim();
if (tcId) {
executedToolCallIds.add(tcId);
}
}
let title = '';
const killedMap = new Map();
const applyIntent = (intent, stepMs) => {
if (!intent) return;
if (intent.action === 'title') {
title = intent.value;
} else if (intent.action === 'kill') {
const prevMs = killedMap.get(intent.value);
killedMap.set(intent.value, prevMs === undefined ? stepMs : Math.max(prevMs, stepMs));
}
};
for (let i = 0; i < rawSteps.length; i++) {
const st = rawSteps[i];
if (!st || typeof st !== 'object') continue;
const stepMs =
parseIsoMs(st?.metadata?.completedAt || st?.metadata?.createdAt || st?.created_at) || 0;
const execTc = st?.metadata?.toolCall;
if (execTc && normalizeSwarmToolName(execTc) === 'swarm') {
if (isSwarmStepCompletedSuccess(st)) {
applyIntent(extractSwarmCallIntent(execTc), stepMs);
}
continue;
}
if (!isSwarmStepCompletedSuccess(st)) continue;
const plannerCalls = getStepPlannerToolCalls(st);
if (plannerCalls.length === 0) continue;
// 收集同一轮次内无 toolCall.id 的执行步骤签名,防止失败或进行中的无 ID 执行步骤回落误触发 planner 提案
let turnIdlessExecCounts = null;
for (const tc of plannerCalls) {
if (normalizeSwarmToolName(tc) !== 'swarm') continue;
const tcId = String(tc?.id || tc?.toolCallId || '').trim();
if (tcId && executedToolCallIds.has(tcId)) {
continue;
}
const intent = extractSwarmCallIntent(tc);
if (!intent) continue;
if (!tcId) {
if (!turnIdlessExecCounts) {
turnIdlessExecCounts = new Map();
for (let j = i + 1; j < rawSteps.length; j++) {
const nextSt = rawSteps[j];
if (!nextSt || typeof nextSt !== 'object') continue;
const nt = String(nextSt.type || '').trim().toUpperCase();
if (
isPlannerStep(nextSt) ||
nt.includes('USER_INPUT') ||
nt.includes('SYSTEM_MESSAGE') ||
isCheckpointStep(nextSt)
) {
break;
}
const nextExecTc = nextSt?.metadata?.toolCall;
if (!nextExecTc || normalizeSwarmToolName(nextExecTc) !== 'swarm') continue;
const nextExecId = String(nextExecTc.id || nextExecTc.toolCallId || '').trim();
if (nextExecId) continue;
const nextIntent = extractSwarmCallIntent(nextExecTc);
if (!nextIntent) continue;
turnIdlessExecCounts.set(
nextIntent.sig,
(turnIdlessExecCounts.get(nextIntent.sig) || 0) + 1
);
}
}
const matchedCount = turnIdlessExecCounts.get(intent.sig) || 0;
if (matchedCount > 0) {
turnIdlessExecCounts.set(intent.sig, matchedCount - 1);
continue;
}
}
applyIntent(intent, stepMs);
}
}
if (!title && killedMap.size === 0) return null;
let killedMembers = null;
if (killedMap.size > 0) {
killedMembers = {};
for (const [member, killMs] of killedMap.entries()) {
Object.defineProperty(killedMembers, member, {
value: killMs,
enumerable: true,
writable: true,
configurable: true,
});
}
}
return {
...(title ? { title } : {}),
...(killedMembers ? { killedMembers } : {}),
};
}