mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
Merge pull request #28 from yuhuan-dev/release/v1.5.2
feat(panel): Native Swarm mode, experimental modern UI, proportional consumption charts, and virtualized step table (v1.5.2)
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
.data/
|
||||
node_modules/
|
||||
plan/
|
||||
dist/
|
||||
usage-monitor.zip
|
||||
*.log
|
||||
*.dpapi
|
||||
.account-test-*
|
||||
|
||||
@@ -117,25 +117,7 @@ English · [简体中文](README.zh-CN.md)
|
||||
|
||||
Keep the folder name as `usage-monitor`. **No `npm install` is needed.**
|
||||
|
||||
### Option 1: Git Clone
|
||||
|
||||
```powershell
|
||||
# Windows (PowerShell)
|
||||
git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
|
||||
```
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
|
||||
```
|
||||
|
||||
Or ask Antigravity directly:
|
||||
|
||||
```text
|
||||
Clone https://github.com/yuhuan-dev/antigravity-usage-monitor to ~/.gemini/config/plugins/usage-monitor and enable the plugin
|
||||
```
|
||||
|
||||
### Option 2: Release ZIP
|
||||
### Option 1: Release ZIP
|
||||
|
||||
Download [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip) and extract it into `~/.gemini/config/plugins/` so the directory path is `~/.gemini/config/plugins/usage-monitor`.
|
||||
|
||||
@@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
|
||||
</details>
|
||||
|
||||
### Option 2: Git Clone
|
||||
|
||||
```powershell
|
||||
# Windows (PowerShell)
|
||||
git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
|
||||
```
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
|
||||
```
|
||||
|
||||
Or ask Antigravity directly:
|
||||
|
||||
```text
|
||||
Clone https://github.com/yuhuan-dev/antigravity-usage-monitor with --filter=blob:none --single-branch to ~/.gemini/config/plugins/usage-monitor and enable the plugin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
+20
-20
@@ -117,30 +117,12 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、
|
||||
|
||||
插件目录名需保持为 `usage-monitor`,**无需运行 `npm install`**。
|
||||
|
||||
### 方式一:Git 克隆
|
||||
|
||||
```powershell
|
||||
# Windows PowerShell
|
||||
git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
|
||||
```
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
|
||||
```
|
||||
|
||||
也可以直接在 Antigravity 对话中执行:
|
||||
|
||||
```text
|
||||
把 https://github.com/yuhuan-dev/antigravity-usage-monitor 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件
|
||||
```
|
||||
|
||||
### 方式二:下载 Release 压缩包
|
||||
### 方式一:下载 Release 压缩包
|
||||
|
||||
下载 [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip),解压到 `~/.gemini/config/plugins/` 下并保持文件夹名为 `usage-monitor`。
|
||||
|
||||
<details>
|
||||
<summary>Windows PowerShell 下载与解压命令</summary>
|
||||
<summary>Windows PowerShell 下载及解压命令</summary>
|
||||
|
||||
```powershell
|
||||
$pluginsDir = "$env:USERPROFILE\.gemini\config\plugins"
|
||||
@@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
|
||||
</details>
|
||||
|
||||
### 方式二:Git 克隆
|
||||
|
||||
```powershell
|
||||
# Windows PowerShell
|
||||
git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
|
||||
```
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
|
||||
```
|
||||
|
||||
也可以直接在 Antigravity 对话中执行:
|
||||
|
||||
```text
|
||||
把 https://github.com/yuhuan-dev/antigravity-usage-monitor 用 --filter=blob:none --single-branch 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 使用方式
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "usage-monitor",
|
||||
"displayName": "Usage & Speed Monitor",
|
||||
"version": "1.5.1",
|
||||
"version": "1.5.2",
|
||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||
"logo": "assets/logo.svg",
|
||||
"suggestedPrompts": [
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"catalogVersion": "2026.11.19.1",
|
||||
"updatedAt": "2026-11-19T09:20:00+09:00",
|
||||
"latestPluginVersion": "1.5.1",
|
||||
"catalogVersion": "2026.11.19.2",
|
||||
"updatedAt": "2026-11-19T09:35:00+09:00",
|
||||
"latestPluginVersion": "1.5.2",
|
||||
"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",
|
||||
"archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
|
||||
|
||||
+5996
-636
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,7 @@ import {
|
||||
cloudSyncState,
|
||||
computeRuntimeCodeVersion,
|
||||
createDefaultSettingsObject,
|
||||
inFlightRequests,
|
||||
isPlainObject,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
@@ -43,7 +44,7 @@ import {
|
||||
syncCloudCatalog,
|
||||
} from './plugin-updater.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||
import { buildTelemetryPayload, clearTelemetryBuilderMemo } from './telemetry-builder.mjs';
|
||||
import {
|
||||
ensureDesktopLaunchEntriesConfigured,
|
||||
triggerDesktopHostRelaunch,
|
||||
@@ -78,26 +79,36 @@ function projectDisplayStep(st) {
|
||||
const {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
streamDurationSec, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt,
|
||||
turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia,
|
||||
rootTurnMediaOnly,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
streamDurationSec, selectedSpeedReason,
|
||||
...(anomaly ? { anomaly, anomalySig } : {}),
|
||||
contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt,
|
||||
turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia,
|
||||
rootTurnMediaOnly,
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8;
|
||||
const displayStepsCache = new Map();
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter(
|
||||
(k) => k !== 'anomaly'
|
||||
);
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
if (!previous || !current) return previous === current;
|
||||
@@ -185,10 +196,18 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
}
|
||||
}
|
||||
}
|
||||
const rawScope = String(data?.scope || '').trim();
|
||||
const scope =
|
||||
rawScope === 'consumption' ||
|
||||
rawScope === 'consumption-presets' ||
|
||||
rawScope === 'conversation'
|
||||
? rawScope
|
||||
: '';
|
||||
const filterOpts = {
|
||||
range: data?.range || 'all',
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||
...(scope ? { scope } : {}),
|
||||
};
|
||||
let payload;
|
||||
try {
|
||||
@@ -209,7 +228,7 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
}
|
||||
if (
|
||||
bootBundleVersion &&
|
||||
payload.uiBundleVersion &&
|
||||
payload?.uiBundleVersion &&
|
||||
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||
) {
|
||||
if (typeof onRestart === 'function') {
|
||||
@@ -218,9 +237,12 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
const responsePayload = data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
const isScopedConsumptionPayload =
|
||||
payload?.scope === 'consumption' || payload?.scope === 'consumption-presets';
|
||||
const responsePayload =
|
||||
!isScopedConsumptionPayload && data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -292,6 +314,16 @@ export function executeSettingsAction(data) {
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
const affectsBackendTelemetry =
|
||||
updated.weeklyLimitMode !== current.weeklyLimitMode ||
|
||||
updated.weeklyTokenBudget !== current.weeklyTokenBudget ||
|
||||
updated.weeklyCostBudget !== current.weeklyCostBudget ||
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode;
|
||||
inFlightRequests.clear();
|
||||
if (affectsBackendTelemetry) {
|
||||
clearTelemetryBuilderMemo();
|
||||
}
|
||||
if (
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode
|
||||
@@ -355,6 +387,8 @@ export async function executeModelContextWindowAction(data) {
|
||||
if (!saveJson(SETTINGS_FILE, current)) {
|
||||
return respond(500, { error: 'Failed to persist model context window' });
|
||||
}
|
||||
inFlightRequests.clear();
|
||||
clearTelemetryBuilderMemo();
|
||||
void notifyModelContextWindowsChanged();
|
||||
return respond(200, { modelContextWindows: current.modelContextWindows });
|
||||
}
|
||||
@@ -371,6 +405,8 @@ export function executeResetSettingsAction() {
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to reset settings' }),
|
||||
};
|
||||
}
|
||||
inFlightRequests.clear();
|
||||
clearTelemetryBuilderMemo();
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
@@ -419,6 +455,7 @@ export function executeRebuildCacheAction() {
|
||||
}
|
||||
displayStepsCache.clear();
|
||||
clearScannerRuntimeMemos();
|
||||
clearTelemetryBuilderMemo();
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -430,6 +467,7 @@ export function executeRebuildCacheAction() {
|
||||
|
||||
export async function executeCloudSyncAction() {
|
||||
const cloudStatus = await syncCloudCatalog({ force: true });
|
||||
clearTelemetryBuilderMemo();
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -450,6 +488,9 @@ export async function executePluginUpdateAction() {
|
||||
|
||||
export async function executeAccountCredentialAction(data) {
|
||||
const result = await handleAccountCredentialAction(data);
|
||||
if (data?.action === 'switch') {
|
||||
clearTelemetryBuilderMemo();
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -460,9 +501,12 @@ export async function executeAccountCredentialAction(data) {
|
||||
|
||||
export async function executeBridgeRelaunchAction() {
|
||||
ensureIdeRemoteDebuggingArgv({ enabled: true });
|
||||
await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(() => {});
|
||||
const launchConfig = await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(
|
||||
() => null
|
||||
);
|
||||
const result = await triggerDesktopHostRelaunch({
|
||||
stalePortFiles: resolveDevToolsPortCandidates(),
|
||||
readOnlyShortcutPaths: launchConfig?.readOnlyPaths || [],
|
||||
});
|
||||
return {
|
||||
status: result.ok ? 200 : Number(result.status || 500),
|
||||
|
||||
@@ -678,6 +678,16 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
const sqLower = String(pRow?.conversation_id || '').trim().toLowerCase();
|
||||
const parentLower = String(pRow?.parent_id || '').trim().toLowerCase();
|
||||
if (!sqLower || !parentLower) continue;
|
||||
const childSummary = nextSummariesObj[sqLower];
|
||||
if (
|
||||
childSummary &&
|
||||
!childSummary.isSideQuestion &&
|
||||
(childSummary.trajectoryMetadata?.subagentSpec ||
|
||||
(Number(childSummary.trajectoryType) > 0 && Number(childSummary.trajectoryType) !== 22))
|
||||
) {
|
||||
// 排除通过 fork 创建的蜂群工蜂或常规子代理,避免误归入旁路提问
|
||||
continue;
|
||||
}
|
||||
const parentSummary = nextSummariesObj[parentLower];
|
||||
const titleFromParent = String(
|
||||
parentSummary?.annotations?.sideQuestionTitles?.[sqLower] ||
|
||||
@@ -904,6 +914,84 @@ function decodeProtoContextWindowMetaSlice(buf, state, end, includeBreakdown) {
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoRetryInfoSlice(buf, state, end) {
|
||||
const ri = {};
|
||||
while (state.off < end) {
|
||||
const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const rFn = rTag >>> 3;
|
||||
const rWt = rTag & 7;
|
||||
if (rFn === 2 && rWt === 2) {
|
||||
ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (rFn === 3 && rWt === 2) {
|
||||
const errStr = readProtoString(buf, state, end).trim();
|
||||
if (errStr) {
|
||||
ri.error = errStr.length > 320 ? `${errStr.slice(0, 319)}…` : errStr;
|
||||
}
|
||||
} else if (rFn === 5 && rWt === 0) {
|
||||
const code = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
if (code > 0) ri.reasonCode = code;
|
||||
} else if (rFn === 7 && rWt === 2) {
|
||||
const dur = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (dur) ri.retryDelay = dur;
|
||||
} else {
|
||||
skipProtoField(buf, state, rWt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return ri;
|
||||
}
|
||||
|
||||
function decodeProtoErrorMessageSlice(buf, state, end) {
|
||||
let userErrorMessage = '';
|
||||
let shortError = '';
|
||||
let errorCode = 0;
|
||||
let shouldShowModel = false;
|
||||
let shouldShowUser = false;
|
||||
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 3 && wt === 2) {
|
||||
const eEnd = readSubEnd(buf, state, end);
|
||||
while (state.off < eEnd) {
|
||||
const eTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd)));
|
||||
const eFn = eTag >>> 3;
|
||||
const eWt = eTag & 7;
|
||||
if (eFn === 1 && eWt === 2) {
|
||||
const s = readProtoString(buf, state, eEnd).trim();
|
||||
if (s) userErrorMessage = s.length > 240 ? `${s.slice(0, 239)}…` : s;
|
||||
} else if (eFn === 2 && eWt === 2) {
|
||||
const s = readProtoString(buf, state, eEnd).trim();
|
||||
if (s) shortError = s.length > 320 ? `${s.slice(0, 319)}…` : s;
|
||||
} else if (eFn === 7 && eWt === 0) {
|
||||
errorCode = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd)));
|
||||
} else {
|
||||
skipProtoField(buf, state, eWt, eEnd);
|
||||
}
|
||||
}
|
||||
state.off = eEnd;
|
||||
} else if (fn === 4 && wt === 0) {
|
||||
shouldShowModel = readProtoVarint(buf, state, end) !== 0n;
|
||||
} else if (fn === 5 && wt === 0) {
|
||||
shouldShowUser = readProtoVarint(buf, state, end) !== 0n;
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
if (!userErrorMessage && !shortError && !errorCode) return null;
|
||||
return {
|
||||
error: {
|
||||
...(userErrorMessage ? { userErrorMessage } : {}),
|
||||
...(shortError ? { shortError } : {}),
|
||||
...(errorCode > 0 ? { errorCode } : {}),
|
||||
},
|
||||
...(shouldShowModel ? { shouldShowModel: true } : {}),
|
||||
...(shouldShowUser ? { shouldShowUser: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
let model = '';
|
||||
let usage = null;
|
||||
@@ -912,6 +1000,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
let streamingDuration = '';
|
||||
let responseModel = '';
|
||||
let modelDisplayName = '';
|
||||
let retryCount = 0;
|
||||
let retryInfos = null;
|
||||
const extraMeta = {};
|
||||
let messagePrompts = null;
|
||||
let tools = null;
|
||||
@@ -994,6 +1084,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
timeToFirstToken = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (fn === 12 && wt === 2) {
|
||||
streamingDuration = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (fn === 14 && wt === 0) {
|
||||
retryCount = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
} else if (fn === 16 && wt === 2) {
|
||||
if (includeBreakdown) {
|
||||
const psEnd = readSubEnd(buf, state, end);
|
||||
@@ -1020,6 +1112,10 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
} else if (fn === 17 && wt === 2) {
|
||||
const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (!retryInfos) retryInfos = [];
|
||||
retryInfos.push(ri);
|
||||
} else if (fn === 19 && wt === 2) {
|
||||
responseModel = readProtoString(buf, state, end).trim();
|
||||
} else if (fn === 20 && wt === 2) {
|
||||
@@ -1046,6 +1142,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
usage.apiProvider = 'API_PROVIDER_ANTHROPIC';
|
||||
}
|
||||
|
||||
const hasRetryEvidence =
|
||||
retryCount > 0 || Boolean(retryInfos && retryInfos.some((r) => r?.error || r?.reasonCode));
|
||||
return {
|
||||
chatModel: {
|
||||
...(model ? { model } : {}),
|
||||
@@ -1055,6 +1153,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
: {}),
|
||||
...(timeToFirstToken ? { timeToFirstToken } : {}),
|
||||
...(streamingDuration ? { streamingDuration } : {}),
|
||||
...(retryCount > 0 ? { retryCount } : {}),
|
||||
...(hasRetryEvidence && retryInfos ? { retryInfos } : {}),
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
...(modelDisplayName ? { modelDisplayName } : {}),
|
||||
...(messagePrompts ? { messagePrompts } : {}),
|
||||
@@ -1223,19 +1323,7 @@ function decodeProtoStepMeta(rawBlob, fallbackIdx) {
|
||||
}
|
||||
state.off = siEnd;
|
||||
} else if (fn === 28 && wt === 2) {
|
||||
const riEnd = readSubEnd(buf, state, end);
|
||||
const ri = {};
|
||||
while (state.off < riEnd) {
|
||||
const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, riEnd)));
|
||||
const rFn = rTag >>> 3;
|
||||
const rWt = rTag & 7;
|
||||
if (rFn === 2 && rWt === 2) {
|
||||
ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, riEnd));
|
||||
} else {
|
||||
skipProtoField(buf, state, rWt, riEnd);
|
||||
}
|
||||
}
|
||||
state.off = riEnd;
|
||||
const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (!retryInfos) retryInfos = [];
|
||||
retryInfos.push(ri);
|
||||
} else if (fn === 30 && wt === 2) {
|
||||
@@ -1451,7 +1539,26 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
|
||||
return invokeSubagent;
|
||||
}
|
||||
|
||||
function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagent, keepFullText }) {
|
||||
function decodeProtoSystemMessageSlice(buf, state, end) {
|
||||
let message = '';
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
message = readProtoString(buf, state, end);
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return message;
|
||||
}
|
||||
|
||||
function decodeProtoSelectiveStepPayload(
|
||||
rawBlob,
|
||||
{ stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText }
|
||||
) {
|
||||
const buf = toUint8Array(rawBlob);
|
||||
if (!buf || buf.length === 0) return {};
|
||||
const state = { off: 0 };
|
||||
@@ -1472,6 +1579,12 @@ function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagen
|
||||
readSubEnd(buf, state, end),
|
||||
keepFullText
|
||||
);
|
||||
} else if (fn === 24 && wt === 2 && stepTypeNum === 17) {
|
||||
const em = decodeProtoErrorMessageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (em) out.errorMessage = em;
|
||||
} else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) {
|
||||
const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (sysMsg) out.systemMessage = { message: sysMsg };
|
||||
} else if (fn === 140 && wt === 2 && isInvokeSubagent) {
|
||||
const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (inv) out.invokeSubagent = inv;
|
||||
@@ -1728,6 +1841,17 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata });
|
||||
}
|
||||
|
||||
const isChildTrajectory =
|
||||
!isSideQuestion &&
|
||||
Boolean(
|
||||
trajectoryMetadata.parentConversationId ||
|
||||
parentConversationId ||
|
||||
(trajectoryMetadata.rootConversationId &&
|
||||
trajectoryMetadata.rootConversationId !== normCid) ||
|
||||
(rootConversationId && rootConversationId !== normCid) ||
|
||||
trajectoryMetadata.subagentSpec
|
||||
);
|
||||
|
||||
const runningTailStart = isRunning
|
||||
? Math.max(0, ownStepRecords.length - 16)
|
||||
: ownStepRecords.length;
|
||||
@@ -1743,6 +1867,8 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
if (
|
||||
rec.stepTypeNum === 14 ||
|
||||
rec.stepTypeNum === 15 ||
|
||||
rec.stepTypeNum === 17 ||
|
||||
(isChildTrajectory && rec.stepTypeNum === 101) ||
|
||||
isInvSub ||
|
||||
(inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson))
|
||||
) {
|
||||
@@ -1805,6 +1931,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, {
|
||||
stepTypeNum: rec.stepTypeNum,
|
||||
isInvokeSubagent: isInvSub,
|
||||
includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101,
|
||||
keepFullText: inRunningTail,
|
||||
});
|
||||
if (decodedPayload.userInput) {
|
||||
@@ -1816,9 +1943,16 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (decodedPayload.systemMessage) {
|
||||
stepObj.systemMessage = decodedPayload.systemMessage;
|
||||
stepObj.content = decodedPayload.systemMessage.message;
|
||||
}
|
||||
if (decodedPayload.plannerResponse) {
|
||||
stepObj.plannerResponse = decodedPayload.plannerResponse;
|
||||
}
|
||||
if (decodedPayload.errorMessage) {
|
||||
stepObj.errorMessage = decodedPayload.errorMessage;
|
||||
}
|
||||
if (decodedPayload.invokeSubagent) {
|
||||
stepObj.invokeSubagent = decodedPayload.invokeSubagent;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,9 @@ import {
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
getMaxMeaningfulStepIndex,
|
||||
isParkedOnSwarmWait,
|
||||
parseIsoMs,
|
||||
parseSwarmWorkerRole,
|
||||
} from '../trajectory-metrics.mjs';
|
||||
import {
|
||||
ANNOTATION_DIRS,
|
||||
@@ -97,13 +99,20 @@ function discoverLocalConversationFiles() {
|
||||
|
||||
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
||||
if (annotationDirs.length > 0 && map.size > 0) {
|
||||
for (const [cascadeId, fileList] of map.entries()) {
|
||||
for (const annDir of annotationDirs) {
|
||||
if (!annDir) continue;
|
||||
const pbtxtPath = join(annDir, `${cascadeId}.pbtxt`);
|
||||
if (existsSync(pbtxtPath)) {
|
||||
fileList.push(pbtxtPath);
|
||||
for (const annDir of annotationDirs) {
|
||||
if (!annDir || !existsSync(annDir)) continue;
|
||||
try {
|
||||
for (const rawName of readdirSync(annDir)) {
|
||||
const name = String(rawName || '');
|
||||
if (!name.toLowerCase().endsWith('.pbtxt')) continue;
|
||||
const cascadeId = name.slice(0, -6).toLowerCase();
|
||||
const fileList = map.get(cascadeId);
|
||||
if (fileList) {
|
||||
fileList.push(join(annDir, name));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略注释目录读取异常
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -353,11 +362,133 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
const failedFetchCooldownMap = new Map();
|
||||
const liveActivityMemo = new Map();
|
||||
const transcriptTailMemo = new Map();
|
||||
const swarmManifestMemo = new Map();
|
||||
|
||||
export function clearScannerRuntimeMemos() {
|
||||
failedFetchCooldownMap.clear();
|
||||
liveActivityMemo.clear();
|
||||
transcriptTailMemo.clear();
|
||||
swarmManifestMemo.clear();
|
||||
}
|
||||
|
||||
function findSwarmMembersPath(cascadeId) {
|
||||
if (!cascadeId) return '';
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return '';
|
||||
const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
||||
let bestPath = '';
|
||||
let bestMtime = -1;
|
||||
for (const dir of dirs) {
|
||||
if (!dir) continue;
|
||||
const candidate = join(dir, normId, '.system_generated', 'swarm', 'members.json');
|
||||
if (!existsSync(candidate)) continue;
|
||||
if (dirs.length === 1) return candidate;
|
||||
try {
|
||||
const mtime = Number(statSync(candidate)?.mtimeMs || 0);
|
||||
if (mtime > bestMtime) {
|
||||
bestMtime = mtime;
|
||||
bestPath = candidate;
|
||||
}
|
||||
} catch {
|
||||
if (!bestPath) bestPath = candidate;
|
||||
}
|
||||
}
|
||||
return bestPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按会话 ID 精确读取本地 `brain/<cascadeId>/.system_generated/swarm/members.json` 蜂群花名册(O(1) 定点读取 + `mtimeMs + size` 缓存)。
|
||||
*
|
||||
* @param {string} cascadeId
|
||||
* @returns {{
|
||||
* title: string,
|
||||
* coordinator: object|null,
|
||||
* membersByCid: Map<string, object>,
|
||||
* membersByName: Map<string, object>,
|
||||
* workerRefs: Array<object>
|
||||
* } | null}
|
||||
*/
|
||||
export function readSwarmManifestForCascade(cascadeId) {
|
||||
if (!cascadeId) return null;
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return null;
|
||||
const membersPath = findSwarmMembersPath(normId);
|
||||
if (!membersPath) {
|
||||
swarmManifestMemo.delete(normId);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const st = statSync(membersPath);
|
||||
const mtimeMs = Number(st?.mtimeMs || 0);
|
||||
const size = Number(st?.size || 0);
|
||||
const cached = swarmManifestMemo.get(normId);
|
||||
if (
|
||||
cached &&
|
||||
cached.path === membersPath &&
|
||||
cached.mtimeMs === mtimeMs &&
|
||||
cached.size === size &&
|
||||
size > 0
|
||||
) {
|
||||
return cached.manifest;
|
||||
}
|
||||
const raw = readFileSync(membersPath, 'utf8');
|
||||
const parsed = raw ? JSON.parse(raw) : null;
|
||||
if (!parsed || typeof parsed !== 'object') return null;
|
||||
|
||||
const title = String(parsed.title || '').trim();
|
||||
const rawMembers = parsed.members && typeof parsed.members === 'object' ? parsed.members : {};
|
||||
const membersByCid = new Map();
|
||||
const membersByName = new Map();
|
||||
const workerRefs = [];
|
||||
let coordinator = null;
|
||||
|
||||
for (const [rawKey, m] of Object.entries(rawMembers)) {
|
||||
if (!m || typeof m !== 'object') continue;
|
||||
const memberName = String(m.name || rawKey || '').replace(/^@+/, '').trim();
|
||||
const cid = String(m.conversation_id || m.conversationId || '').trim().toLowerCase();
|
||||
if (!cid || !UUID_RE.test(cid)) continue;
|
||||
const role = String(m.role || '').trim().toLowerCase();
|
||||
const wakeMode = String(m.wake_mode || m.wakeMode || '').trim().toLowerCase();
|
||||
const killed = Boolean(m.killed);
|
||||
const workspaceMode = String(m.workspace_mode || m.workspaceMode || 'inherit').trim();
|
||||
const model = String(m.applied_model || m.model || m.desired_model || '').trim();
|
||||
const entry = {
|
||||
memberName,
|
||||
conversationId: cid,
|
||||
role,
|
||||
wakeMode,
|
||||
killed,
|
||||
workspaceMode,
|
||||
model,
|
||||
};
|
||||
membersByCid.set(cid, entry);
|
||||
if (memberName) {
|
||||
membersByName.set(memberName.toLowerCase(), entry);
|
||||
}
|
||||
if (role === 'coordinator' || cid === normId) {
|
||||
coordinator = entry;
|
||||
} else {
|
||||
workerRefs.push({
|
||||
cascadeId: cid,
|
||||
role: memberName ? `Swarm Worker (${memberName})` : 'Swarm Worker',
|
||||
typeName: 'worker',
|
||||
memberName,
|
||||
createdTimeMs: 0,
|
||||
spawnOrder: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const manifest = { title, coordinator, membersByCid, membersByName, workerRefs };
|
||||
if (swarmManifestMemo.size >= MAX_TRANSCRIPT_MEMO_ENTRIES && !swarmManifestMemo.has(normId)) {
|
||||
const oldestKey = swarmManifestMemo.keys().next().value;
|
||||
if (oldestKey !== undefined) swarmManifestMemo.delete(oldestKey);
|
||||
}
|
||||
swarmManifestMemo.set(normId, { path: membersPath, mtimeMs, size, manifest });
|
||||
return manifest;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function findTranscriptPath(cascadeId) {
|
||||
@@ -461,6 +592,7 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) {
|
||||
const needsTranscriptBackfill = sqliteSteps.some(
|
||||
(s) =>
|
||||
(s?.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !s.userInput) ||
|
||||
(s?.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && !s.content && !s.systemMessage) ||
|
||||
(s?.metadata?.modelUsage && !s.metadata.modelUsage.model)
|
||||
);
|
||||
if (!needsTranscriptBackfill) {
|
||||
@@ -522,6 +654,12 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) {
|
||||
if (typeof tLine.content === 'string') sq.content = tLine.content;
|
||||
if (tLine.userInput) sq.userInput = tLine.userInput;
|
||||
if (Array.isArray(tLine.media)) sq.media = tLine.media;
|
||||
} else if (
|
||||
sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' &&
|
||||
!sq.content &&
|
||||
typeof tLine.content === 'string'
|
||||
) {
|
||||
sq.content = tLine.content;
|
||||
} else if (sq.metadata?.modelUsage && !sq.metadata.modelUsage.model) {
|
||||
const fallbackModel = String(tLine.model || tLine.generator_model || '').trim();
|
||||
if (fallbackModel) sq.metadata.modelUsage.model = fallbackModel;
|
||||
@@ -635,11 +773,40 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE') {
|
||||
const sysText =
|
||||
typeof sq.content === 'string' && sq.content
|
||||
? sq.content
|
||||
: typeof tLine?.content === 'string'
|
||||
? tLine.content
|
||||
: '';
|
||||
if (sysText) {
|
||||
sqliteRawSteps.push({
|
||||
type: sq.type,
|
||||
status: sq.status,
|
||||
content: sysText,
|
||||
metadata: sq.metadata,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (sq.type === 'CORTEX_STEP_TYPE_ERROR_MESSAGE') {
|
||||
sqliteRawSteps.push({
|
||||
type: sq.type,
|
||||
status: sq.status,
|
||||
...(sq.errorMessage ? { errorMessage: sq.errorMessage } : {}),
|
||||
...(typeof tLine?.error === 'string' && tLine.error ? { error: tLine.error } : {}),
|
||||
...(typeof tLine?.content === 'string' && tLine.content ? { content: tLine.content } : {}),
|
||||
metadata: sq.metadata,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sq.metadata?.modelUsage) {
|
||||
const rawUsage = sq.metadata?.modelUsage || sq.metadata?.retryInfos?.[0]?.usage;
|
||||
if (rawUsage) {
|
||||
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
||||
modelOrdinal += 1;
|
||||
const mu = { ...sq.metadata.modelUsage };
|
||||
const mu = { ...rawUsage };
|
||||
if (!mu.model) {
|
||||
const fallbackModel = String(
|
||||
tLine?.model || tLine?.generator_model || deepStep?.modelKey || ''
|
||||
@@ -672,7 +839,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
if (
|
||||
upperType === 'USER_INPUT' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object')
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ||
|
||||
upperType === 'ERROR_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE'
|
||||
) {
|
||||
sqliteRawSteps.push(line);
|
||||
} else if (
|
||||
@@ -680,14 +851,19 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
line.cache_read_tokens !== undefined ||
|
||||
line.output_tokens !== undefined
|
||||
) {
|
||||
const tailStatus = String(line.status || '').trim().toUpperCase();
|
||||
sqliteRawSteps.push({
|
||||
type:
|
||||
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT'
|
||||
? 'CORTEX_STEP_TYPE_CHECKPOINT'
|
||||
: String(line.type || 'PLANNER_RESPONSE'),
|
||||
status: /CANCEL/i.test(String(line.status || ''))
|
||||
status: /CANCEL/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: 'CORTEX_STEP_STATUS_DONE',
|
||||
: /ERROR/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE',
|
||||
plannerResponse: {
|
||||
response: typeof line.content === 'string' ? line.content : '',
|
||||
thinking: typeof line.thinking === 'string' ? line.thinking : '',
|
||||
@@ -721,7 +897,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
if (
|
||||
upperType === 'USER_INPUT' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object')
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ||
|
||||
upperType === 'ERROR_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE'
|
||||
) {
|
||||
syntheticSteps.push(line);
|
||||
continue;
|
||||
@@ -746,7 +926,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
const rawStatus = String(line.status || '').trim().toUpperCase();
|
||||
const mappedStatus = /CANCEL/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
: /ERROR/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
const finishedAt = String(
|
||||
line.finished_generating_at ||
|
||||
line.finishedGeneratingAt ||
|
||||
@@ -1390,8 +1574,10 @@ export async function enumerateAndSyncConversations({
|
||||
Boolean(cached?.isSubagent) ||
|
||||
Boolean(parentConversationId) ||
|
||||
Boolean(rootConversationId && rootConversationId !== cidLower);
|
||||
const isKilled = Boolean(item?.killed || localSum?.killed);
|
||||
const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0);
|
||||
const localStatus =
|
||||
!isKilled &&
|
||||
localSum?.status === 'CASCADE_RUN_STATUS_RUNNING' &&
|
||||
latestLocalTouchMs > 0 &&
|
||||
nowSweepMs - latestLocalTouchMs <= STALE_LOCAL_RUNNING_MAX_AGE_MS
|
||||
@@ -1417,7 +1603,8 @@ export async function enumerateAndSyncConversations({
|
||||
(isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
stepCount: modelStepCount,
|
||||
rawStepCount: rawSummaryStepCount,
|
||||
status: item?.status || '',
|
||||
status: isKilled ? 'IDLE' : item?.status || '',
|
||||
killed: isKilled,
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
diskMtimeMs,
|
||||
@@ -1448,6 +1635,7 @@ export async function enumerateAndSyncConversations({
|
||||
stepCount: cachedStepCount,
|
||||
rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount,
|
||||
status: localStatus,
|
||||
killed: isKilled,
|
||||
lastModifiedTime: localSum?.lastModifiedTime || '',
|
||||
lastModifiedMs: Math.max(
|
||||
cached.lastModifiedMs || 0,
|
||||
@@ -1480,6 +1668,7 @@ export async function enumerateAndSyncConversations({
|
||||
stepCount: 0,
|
||||
rawStepCount: localSum?.stepCount || 0,
|
||||
status: localStatus,
|
||||
killed: isKilled,
|
||||
lastModifiedTime: localSum?.lastModifiedTime || '',
|
||||
lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0),
|
||||
diskMtimeMs,
|
||||
@@ -1710,6 +1899,19 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
|
||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||
const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
||||
if (ownSwarmManifest?.workerRefs?.length) {
|
||||
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
||||
for (const wRef of ownSwarmManifest.workerRefs) {
|
||||
if (!seenRefCids.has(wRef.cascadeId)) {
|
||||
seenRefCids.add(wRef.cascadeId);
|
||||
subagentRefs.push(wRef);
|
||||
}
|
||||
}
|
||||
if (!nonShortTitle(conv.title) && ownSwarmManifest.title) {
|
||||
conv.title = ownSwarmManifest.title;
|
||||
}
|
||||
}
|
||||
conv.subagentRefs = subagentRefs;
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
@@ -1718,16 +1920,24 @@ export async function enumerateAndSyncConversations({
|
||||
conv.stepCount = steps.length;
|
||||
const finalSig = buildConvSig(conv);
|
||||
|
||||
const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps);
|
||||
if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
conv.status = 'IDLE';
|
||||
}
|
||||
|
||||
const liveAct = resolveBestLiveActivity(
|
||||
conv.cascadeId,
|
||||
rawSteps,
|
||||
isRunning,
|
||||
effectiveIsRunning,
|
||||
resolvedLastModMs || conv.createdTimeMs || 0
|
||||
);
|
||||
if (liveAct) {
|
||||
if (liveAct && liveAct.actionKey !== 'swarm_wait') {
|
||||
conv.liveActivity = liveAct;
|
||||
liveActivityMemo.set(cidLower, liveAct);
|
||||
} else {
|
||||
if (liveAct?.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
}
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(cidLower);
|
||||
}
|
||||
@@ -1747,11 +1957,13 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs:
|
||||
conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)),
|
||||
rawStepCount: conv.rawStepCount ?? stepsWithOwners.length,
|
||||
wasRunning: isRunning,
|
||||
wasRunning: conv.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
wakeupTurnTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
anomalyTelemetry: 1,
|
||||
steps: stepsWithOwners,
|
||||
subagentRefs,
|
||||
};
|
||||
@@ -1785,6 +1997,7 @@ export async function enumerateAndSyncConversations({
|
||||
!prev.speedClearedTelemetry ||
|
||||
!prev.turnRailTelemetry ||
|
||||
!prev.contextGroupsTelemetry ||
|
||||
!prev.anomalyTelemetry ||
|
||||
metaChanged ||
|
||||
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
||||
|
||||
@@ -1854,6 +2067,7 @@ export async function enumerateAndSyncConversations({
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
anomalyTelemetry: 1,
|
||||
steps: offlineStepsWithOwners,
|
||||
subagentRefs: offlineFallback.subagentRefs,
|
||||
};
|
||||
@@ -1963,6 +2177,12 @@ export async function enumerateAndSyncConversations({
|
||||
return false;
|
||||
}
|
||||
|
||||
function needsWakeupTurnRefresh(conv, cached) {
|
||||
if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false;
|
||||
const steps = cached?.steps || [];
|
||||
return steps.length > 0 && steps.every((s) => !s?.turnIndex);
|
||||
}
|
||||
|
||||
let remainingTimingRefreshes = LEGACY_MIGRATION_BATCH_SIZE;
|
||||
const toFetch = rawConversations.filter((conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
@@ -1978,7 +2198,9 @@ export async function enumerateAndSyncConversations({
|
||||
if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true;
|
||||
if (
|
||||
(!cached.turnRailTelemetry ||
|
||||
!cached.anomalyTelemetry ||
|
||||
hasMissingTurnRailFields(cached) ||
|
||||
needsWakeupTurnRefresh(conv, cached) ||
|
||||
hasDroppedContextGroups(cached)) &&
|
||||
isSelectedFamily
|
||||
) {
|
||||
@@ -2056,7 +2278,22 @@ export async function enumerateAndSyncConversations({
|
||||
|
||||
for (const parentConv of [...rawConversations]) {
|
||||
const parentCached = getCachedTrajectory(parentConv.cascadeId);
|
||||
const refs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
const swarmManifest = !parentConv.isSubagent
|
||||
? readSwarmManifestForCascade(parentConv.cascadeId)
|
||||
: null;
|
||||
let refs = baseRefs;
|
||||
if (swarmManifest?.workerRefs?.length) {
|
||||
const merged = Array.isArray(baseRefs) ? baseRefs.slice() : [];
|
||||
const seenRefCids = new Set(merged.map((r) => String(r?.cascadeId || '').toLowerCase()));
|
||||
for (const wRef of swarmManifest.workerRefs) {
|
||||
if (!seenRefCids.has(wRef.cascadeId)) {
|
||||
seenRefCids.add(wRef.cascadeId);
|
||||
merged.push(wRef);
|
||||
}
|
||||
}
|
||||
refs = merged;
|
||||
}
|
||||
if (!Array.isArray(refs) || refs.length === 0) continue;
|
||||
|
||||
const parentId = parentConv.cascadeId.toLowerCase();
|
||||
@@ -2144,7 +2381,9 @@ export async function enumerateAndSyncConversations({
|
||||
!hasMissingStepFields(existingSubCache) &&
|
||||
(!isSelectedSubFamily ||
|
||||
(Boolean(existingSubCache.turnRailTelemetry) &&
|
||||
Boolean(existingSubCache.anomalyTelemetry) &&
|
||||
!hasMissingTurnRailFields(existingSubCache) &&
|
||||
!needsWakeupTurnRefresh(subConv, existingSubCache) &&
|
||||
!hasDroppedContextGroups(existingSubCache)));
|
||||
|
||||
if (hasValidSubCache) {
|
||||
@@ -2253,16 +2492,33 @@ export async function enumerateAndSyncConversations({
|
||||
persistTrajectoryCacheIfNeeded({ hasRunningSessions });
|
||||
}
|
||||
|
||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要
|
||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态
|
||||
for (const conv of rawConversations) {
|
||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
if (!conv.liveActivity) {
|
||||
const tailSteps = readTranscriptTailSteps(conv.cascadeId);
|
||||
if (isParkedOnSwarmWait(tailSteps)) {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
continue;
|
||||
}
|
||||
const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0;
|
||||
const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs);
|
||||
if (resolved?.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
continue;
|
||||
}
|
||||
conv.liveActivity = resolved;
|
||||
if (resolved) {
|
||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
|
||||
}
|
||||
} else if (conv.liveActivity.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
}
|
||||
} else {
|
||||
conv.liveActivity = null;
|
||||
@@ -2308,7 +2564,64 @@ export async function enumerateAndSyncConversations({
|
||||
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const swarmManifest = readSwarmManifestForCascade(cid);
|
||||
const swarmTitle = String(swarmManifest?.title || '').trim();
|
||||
if (swarmTitle) {
|
||||
rootConv.swarmTitle = swarmTitle;
|
||||
const curTitle = String(rootConv.title || '').trim();
|
||||
if (!curTitle || curTitle.toLowerCase() === cid.slice(0, 8)) {
|
||||
rootConv.title = swarmTitle;
|
||||
}
|
||||
}
|
||||
if (swarmManifest?.coordinator?.killed || rootConv.killed) {
|
||||
rootConv.status = 'IDLE';
|
||||
rootConv.liveActivity = null;
|
||||
}
|
||||
|
||||
const subs = subagentsByRoot.get(cid) || [];
|
||||
let swarmCount = 0;
|
||||
for (const s of subs) {
|
||||
const subLower = s.cascadeId.toLowerCase();
|
||||
const mEntry = swarmManifest?.membersByCid.get(subLower) || null;
|
||||
const subCached = getCachedTrajectory(s.cascadeId);
|
||||
const parsedSwarm = !s.isSideQuestion
|
||||
? parseSwarmWorkerRole({
|
||||
role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '',
|
||||
typeName: s.subagentSpec?.typeName || subCached?.subagentSpec?.typeName || '',
|
||||
agentScriptName: s.agentScriptName || subCached?.agentScriptName || '',
|
||||
memberName: mEntry?.memberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
if (parsedSwarm.isSwarmWorker) {
|
||||
swarmCount += 1;
|
||||
s.isSwarmWorker = true;
|
||||
s.swarmMemberName = parsedSwarm.memberName;
|
||||
s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary);
|
||||
s.killed = Boolean(s.killed || mEntry?.killed);
|
||||
if (s.killed) {
|
||||
s.status = 'IDLE';
|
||||
s.liveActivity = null;
|
||||
liveActivityMemo.delete(subLower);
|
||||
s.swarmState = 'killed';
|
||||
} else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
const parkedInManifest =
|
||||
Boolean(mEntry) &&
|
||||
(mEntry.wakeMode === 'mentions' || mEntry.wakeMode === 'anything') &&
|
||||
(!s.liveActivity || s.liveActivity.signature === 'init:0');
|
||||
if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) {
|
||||
s.status = 'IDLE';
|
||||
s.liveActivity = null;
|
||||
liveActivityMemo.delete(subLower);
|
||||
s.swarmState = 'waiting';
|
||||
} else {
|
||||
s.swarmState = 'working';
|
||||
}
|
||||
} else {
|
||||
s.swarmState = 'waiting';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
subs.sort((a, b) => {
|
||||
const aSide = Boolean(a.isSideQuestion);
|
||||
const bSide = Boolean(b.isSideQuestion);
|
||||
@@ -2338,6 +2651,7 @@ export async function enumerateAndSyncConversations({
|
||||
});
|
||||
rootConv.subagents = subs;
|
||||
rootConv.subagentCount = subs.length;
|
||||
rootConv.swarmCount = swarmCount;
|
||||
rootConv.totalStepCount =
|
||||
Number(rootConv.stepCount || 0) +
|
||||
subs.reduce((sum, s) => sum + Number(s.stepCount || 0), 0);
|
||||
|
||||
@@ -494,7 +494,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
`Expand-Archive -LiteralPath '${zipFile.replace(/'/g, "''")}' -DestinationPath '${extractDir.replace(/'/g, "''")}' -Force`,
|
||||
`Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipFile.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`,
|
||||
]);
|
||||
} else {
|
||||
await runExecFile('unzip', ['-oq', zipFile, '-d', extractDir]);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
normalizeExperimentalModernUi,
|
||||
normalizeFontScale,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
@@ -67,6 +68,7 @@ export {
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
normalizeExperimentalModernUi,
|
||||
normalizeFontScale,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
@@ -108,6 +110,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
language: 'zh-CN',
|
||||
themeAccent: 'host',
|
||||
fontScale: 'md',
|
||||
experimentalModernUi: false,
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
weeklyLimitMode: 'official',
|
||||
@@ -174,6 +177,7 @@ export function normalizeFullSettings(rawInput) {
|
||||
language: normalizeLanguageSetting(safeRaw.language),
|
||||
themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
|
||||
fontScale: normalizeFontScale(safeRaw.fontScale),
|
||||
experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi),
|
||||
weeklyTokenBudget: schemaSanitizePositiveNum(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit,
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,15 @@
|
||||
* 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import {
|
||||
@@ -54,46 +62,110 @@ const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
|
||||
|
||||
/**
|
||||
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
||||
* Linux 额外兼容全小写目录名、自定义 `XDG_CONFIG_HOME` 回退以及 Flatpak / Snap 一级容器配置目录。
|
||||
*
|
||||
* @param {Record<string, string|undefined>} [env=process.env]
|
||||
* @param {string} [platform=process.platform]
|
||||
* @param {string} [homeDir=homedir()]
|
||||
* @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function resolveDevToolsPortCandidates(
|
||||
env = process.env,
|
||||
platform = process.platform,
|
||||
homeDir = homedir()
|
||||
homeDir = homedir(),
|
||||
fsOps = null
|
||||
) {
|
||||
const explicitFile = String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim();
|
||||
if (explicitFile) {
|
||||
return [explicitFile];
|
||||
}
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const pushUnique = (p) => {
|
||||
const clean = String(p || '').trim();
|
||||
if (clean && !seen.has(clean)) {
|
||||
seen.add(clean);
|
||||
out.push(clean);
|
||||
}
|
||||
};
|
||||
const portableRoot = String(env?.VSCODE_PORTABLE || '').trim();
|
||||
|
||||
if (platform === 'win32') {
|
||||
const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming');
|
||||
const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local');
|
||||
return [
|
||||
join(appData, 'Antigravity', 'DevToolsActivePort'),
|
||||
join(localAppData, 'Antigravity', 'DevToolsActivePort'),
|
||||
join(appData, 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
join(localAppData, 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
];
|
||||
pushUnique(join(appData, 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(localAppData, 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(appData, 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
pushUnique(join(localAppData, 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
if (portableRoot) {
|
||||
pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort'));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (platform === 'darwin') {
|
||||
return [
|
||||
join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'),
|
||||
join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'),
|
||||
join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort'),
|
||||
join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'),
|
||||
join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
];
|
||||
pushUnique(join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(
|
||||
join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort')
|
||||
);
|
||||
pushUnique(join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(
|
||||
join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort')
|
||||
);
|
||||
pushUnique(join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
if (portableRoot) {
|
||||
pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort'));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config');
|
||||
return [
|
||||
join(configHome, 'Antigravity', 'DevToolsActivePort'),
|
||||
join(configHome, 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
];
|
||||
|
||||
const defaultConfigHome = join(homeDir, '.config');
|
||||
const configHome = env?.XDG_CONFIG_HOME || defaultConfigHome;
|
||||
pushUnique(join(configHome, 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(configHome, 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
pushUnique(join(configHome, 'antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(configHome, 'antigravity-ide', 'DevToolsActivePort'));
|
||||
if (configHome !== defaultConfigHome) {
|
||||
pushUnique(join(defaultConfigHome, 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(defaultConfigHome, 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
pushUnique(join(defaultConfigHome, 'antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(defaultConfigHome, 'antigravity-ide', 'DevToolsActivePort'));
|
||||
}
|
||||
if (portableRoot) {
|
||||
pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort'));
|
||||
}
|
||||
|
||||
const readdirFn = fsOps?.readdirFn || readdirSync;
|
||||
const flatpakRoot = join(homeDir, '.var', 'app');
|
||||
try {
|
||||
for (const rawEntry of readdirFn(flatpakRoot) || []) {
|
||||
const appId = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || '');
|
||||
if (!appId || !/antigravity/i.test(appId)) continue;
|
||||
pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(flatpakRoot, appId, 'config', 'antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
}
|
||||
} catch {
|
||||
// 宿主机未安装 Flatpak 或目录不可读时静默忽略
|
||||
}
|
||||
|
||||
const snapRoot = join(homeDir, 'snap');
|
||||
try {
|
||||
for (const rawEntry of readdirFn(snapRoot) || []) {
|
||||
const snapName = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || '');
|
||||
if (!snapName || !/antigravity/i.test(snapName)) continue;
|
||||
pushUnique(join(snapRoot, snapName, 'current', '.config', 'Antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(join(snapRoot, snapName, 'current', '.config', 'antigravity', 'DevToolsActivePort'));
|
||||
pushUnique(
|
||||
join(snapRoot, snapName, 'current', '.config', 'Antigravity IDE', 'DevToolsActivePort')
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// 宿主机未安装 Snap 或目录不可读时静默忽略
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -714,6 +786,7 @@ export function createWindowBridgeController(options) {
|
||||
onVersionDrift = null,
|
||||
leaseFilePath = '',
|
||||
autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined,
|
||||
launcherRecheckIntervalMs = 15 * 60 * 1000,
|
||||
launcherExecFileFn = null,
|
||||
launcherFsOps = null,
|
||||
allowDesktopLauncherInTest = false,
|
||||
@@ -743,21 +816,23 @@ export function createWindowBridgeController(options) {
|
||||
let hadInjectedTargets = false;
|
||||
let hadInjectedChatFrames = false;
|
||||
let cdpFallbackActive = false;
|
||||
let ideArgvProvisioned = false;
|
||||
let lastLauncherProvisionAtMs = 0;
|
||||
let hostLauncherPromise = null;
|
||||
let argvUpdatedThisBoot = false;
|
||||
let argvConfigured = false;
|
||||
let launcherConfigured = false;
|
||||
let hasReadOnlyShortcuts = false;
|
||||
const hostExecInfo = resolveDesktopHostExecutable({
|
||||
env,
|
||||
platform,
|
||||
homeDir,
|
||||
existsFn: existsHostFn,
|
||||
});
|
||||
// Windows / macOS 支持从运行中宿主进程动态反查任意盘符路径,因此桌面端环境下即使自定义安装路径不在默认盘符也可一键重拉
|
||||
// Windows / macOS / Linux 均支持从运行中宿主进程动态反查路径(含自定义盘符与 AppImage),自定义安装路径亦可一键重拉
|
||||
const canRelaunch = Boolean(
|
||||
hostExecInfo.found ||
|
||||
((platform === 'win32' || platform === 'darwin') && options?.existsHostFn === undefined)
|
||||
((platform === 'win32' || platform === 'darwin' || platform === 'linux') &&
|
||||
options?.existsHostFn === undefined)
|
||||
);
|
||||
let lastPersistedLeaseSig = '';
|
||||
let lastBridgeStatus = {
|
||||
@@ -768,6 +843,7 @@ export function createWindowBridgeController(options) {
|
||||
argvUpdatedThisBoot: false,
|
||||
argvConfigured: false,
|
||||
launcherConfigured: false,
|
||||
hasReadOnlyShortcuts: false,
|
||||
canRelaunch,
|
||||
updatedAtMs: 0,
|
||||
};
|
||||
@@ -1209,11 +1285,12 @@ export function createWindowBridgeController(options) {
|
||||
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
||||
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
||||
hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts),
|
||||
canRelaunch: Boolean(canRelaunch),
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
if (leasedBySelf && leaseFilePath) {
|
||||
const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`;
|
||||
const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.hasReadOnlyShortcuts ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`;
|
||||
if (sig !== lastPersistedLeaseSig) {
|
||||
lastPersistedLeaseSig = sig;
|
||||
saveJson(leaseFilePath, {
|
||||
@@ -1227,6 +1304,7 @@ export function createWindowBridgeController(options) {
|
||||
argvUpdatedThisBoot: lastBridgeStatus.argvUpdatedThisBoot,
|
||||
argvConfigured: lastBridgeStatus.argvConfigured,
|
||||
launcherConfigured: lastBridgeStatus.launcherConfigured,
|
||||
hasReadOnlyShortcuts: lastBridgeStatus.hasReadOnlyShortcuts,
|
||||
canRelaunch: lastBridgeStatus.canRelaunch,
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
@@ -1234,13 +1312,13 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
}
|
||||
|
||||
function provisionHostLaunchersOnce() {
|
||||
if (ideArgvProvisioned) return Promise.resolve();
|
||||
function provisionHostLaunchersOnce({ fastCheckIfActive = false } = {}) {
|
||||
if (hostLauncherPromise) return hostLauncherPromise;
|
||||
hostLauncherPromise = (async () => {
|
||||
const ideRes = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true });
|
||||
const desktopRes = await ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: true,
|
||||
fastCheckIfActive,
|
||||
env,
|
||||
platform,
|
||||
homeDir,
|
||||
@@ -1254,10 +1332,13 @@ export function createWindowBridgeController(options) {
|
||||
if (ideRes.updated || ideRes.alreadyConfigured) {
|
||||
argvConfigured = true;
|
||||
}
|
||||
if (desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured) {
|
||||
launcherConfigured = true;
|
||||
launcherConfigured = Boolean(
|
||||
desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured
|
||||
);
|
||||
if (!desktopRes.fastPath) {
|
||||
hasReadOnlyShortcuts = Boolean(desktopRes.hasReadOnlyShortcuts);
|
||||
}
|
||||
ideArgvProvisioned = true;
|
||||
lastLauncherProvisionAtMs = Date.now();
|
||||
})().finally(() => {
|
||||
hostLauncherPromise = null;
|
||||
});
|
||||
@@ -1280,10 +1361,6 @@ export function createWindowBridgeController(options) {
|
||||
const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||
const contextWindows = curSettings.modelContextWindows || {};
|
||||
const hasContextWindows = Object.keys(contextWindows).length > 0;
|
||||
const provPending =
|
||||
(enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned
|
||||
? provisionHostLaunchersOnce()
|
||||
: hostLauncherPromise;
|
||||
|
||||
let leasedBySelf = false;
|
||||
let currentLease = null;
|
||||
@@ -1311,6 +1388,7 @@ export function createWindowBridgeController(options) {
|
||||
argvUpdatedThisBoot: Boolean(lease?.argvUpdatedThisBoot || argvUpdatedThisBoot),
|
||||
argvConfigured: mergedConfigured,
|
||||
launcherConfigured: mergedConfigured,
|
||||
hasReadOnlyShortcuts: Boolean(lease?.hasReadOnlyShortcuts || hasReadOnlyShortcuts),
|
||||
canRelaunch: Boolean(lease?.canRelaunch ?? canRelaunch),
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
@@ -1330,13 +1408,24 @@ export function createWindowBridgeController(options) {
|
||||
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
||||
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
||||
hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts),
|
||||
canRelaunch: Boolean(canRelaunch),
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const shouldCheckLaunchers =
|
||||
(enabled || hasContextWindows) &&
|
||||
autoConfigureIdeArgv &&
|
||||
(lastLauncherProvisionAtMs === 0 ||
|
||||
Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs);
|
||||
const isInitialLauncherPass = lastLauncherProvisionAtMs === 0;
|
||||
|
||||
const cdpPorts = findActiveDevToolsPorts();
|
||||
if (!cdpPorts.length) {
|
||||
const provPending = shouldCheckLaunchers
|
||||
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
||||
: hostLauncherPromise;
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
@@ -1351,6 +1440,9 @@ export function createWindowBridgeController(options) {
|
||||
|
||||
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
|
||||
if (reachableCount === 0) {
|
||||
const provPending = shouldCheckLaunchers
|
||||
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
||||
: hostLauncherPromise;
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
@@ -1362,6 +1454,11 @@ export function createWindowBridgeController(options) {
|
||||
});
|
||||
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
|
||||
}
|
||||
|
||||
if (shouldCheckLaunchers) {
|
||||
// 调试端口已正常连通时走纯 Node.js 零子进程快检(<2ms),仅在发现未配参快捷方式时才拉起 PowerShell
|
||||
void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {});
|
||||
}
|
||||
if (!targets.length) {
|
||||
updateBridgeStatus(enabled ? 'no_targets' : 'disabled', {
|
||||
enabled,
|
||||
@@ -1842,6 +1939,8 @@ export function createWindowBridgeController(options) {
|
||||
const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0;
|
||||
if (!hasCtx && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
void ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: false,
|
||||
env,
|
||||
@@ -1853,7 +1952,7 @@ export function createWindowBridgeController(options) {
|
||||
}).catch(() => {});
|
||||
}
|
||||
} else {
|
||||
ideArgvProvisioned = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
hadInjectedChatFrames = true;
|
||||
}
|
||||
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||
@@ -1865,9 +1964,11 @@ export function createWindowBridgeController(options) {
|
||||
const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||
const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0;
|
||||
if (hasCtx) {
|
||||
ideArgvProvisioned = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
} else if (!overlayOn && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
void ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: false,
|
||||
env,
|
||||
@@ -1908,6 +2009,7 @@ export function getDefaultWindowBridgeStatus() {
|
||||
argvUpdatedThisBoot: false,
|
||||
argvConfigured: false,
|
||||
launcherConfigured: false,
|
||||
hasReadOnlyShortcuts: false,
|
||||
canRelaunch: false,
|
||||
updatedAtMs: 0,
|
||||
};
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795006728154">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795098443766">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795006728154"></script>
|
||||
<script src="/app.js?v=1795098443766"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "usage-monitor-panel",
|
||||
"version": "1.5.1",
|
||||
"version": "1.5.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
"scripts": {
|
||||
"build": "node scripts/build-bundle.mjs",
|
||||
"pack:release": "node scripts/pack-release-zip.mjs",
|
||||
"standalone": "node standalone.mjs",
|
||||
"test": "node --test test/*.test.mjs"
|
||||
}
|
||||
|
||||
@@ -504,6 +504,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/overlay.css',
|
||||
'src/styles/modern-ui.css',
|
||||
];
|
||||
|
||||
const cssBundle =
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @fileoverview Pure Node.js whitelist packager for `usage-monitor.zip`.
|
||||
*
|
||||
* Packs ONLY the runtime-essential plugin files (~520 KB compressed) into a
|
||||
* cross-platform PKZIP archive prefixed with `usage-monitor/`, excluding dev-only
|
||||
* frontend sources (`src/`), unit tests (`test/`), build scripts (`scripts/`),
|
||||
* README preview PNGs (`assets/*.png`), local data (`.data/`), and planning docs (`plan/`).
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { deflateRawSync } from 'node:zlib';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const DEFAULT_REPO_ROOT = resolve(__dirname, '..', '..', '..');
|
||||
export const DEFAULT_ZIP_OUT = join(DEFAULT_REPO_ROOT, 'dist', 'usage-monitor.zip');
|
||||
export const RELEASE_ARCHIVE_ROOT = 'usage-monitor';
|
||||
|
||||
const ROOT_WHITELIST = Object.freeze([
|
||||
'plugin.json',
|
||||
'mcp_config.json',
|
||||
'pricing-catalog.json',
|
||||
'LICENSE',
|
||||
'assets/logo.svg',
|
||||
]);
|
||||
|
||||
const PANEL_TOP_WHITELIST = Object.freeze([
|
||||
'sidecars/panel/sidecar.json',
|
||||
'sidecars/panel/index.html',
|
||||
'sidecars/panel/app.js',
|
||||
'sidecars/panel/styles.css',
|
||||
'sidecars/panel/main.mjs',
|
||||
'sidecars/panel/mcp-entry.mjs',
|
||||
'sidecars/panel/bridge-daemon.mjs',
|
||||
'sidecars/panel/standalone.mjs',
|
||||
'sidecars/panel/cli-statusline.mjs',
|
||||
'sidecars/panel/trajectory-metrics.mjs',
|
||||
]);
|
||||
|
||||
const RUNTIME_SUBDIRS = Object.freeze([
|
||||
'sidecars/panel/backend',
|
||||
'sidecars/panel/shared',
|
||||
]);
|
||||
|
||||
const ALLOWED_SUBDIR_EXT_RE = /\.(?:mjs|ps1|sh|json)$/i;
|
||||
const FORBIDDEN_PATH_RE =
|
||||
/(?:^|\/)(?:\.git|\.data|node_modules|plan|dist|src|test|scripts)(?:\/|$)|\.png$|\.jpg$|\.jpeg$|\.webp$|\.log$|\.dpapi$/i;
|
||||
|
||||
const CRC32_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let i = 0; i < 256; i += 1) {
|
||||
let c = i;
|
||||
for (let k = 0; k < 8; k += 1) {
|
||||
c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
table[i] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf) {
|
||||
let crc = 0xffffffff;
|
||||
for (let i = 0; i < buf.length; i += 1) {
|
||||
crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function toDosTimeDate(date) {
|
||||
const d = date instanceof Date && Number.isFinite(date.getTime()) ? date : new Date(2026, 0, 1);
|
||||
const year = Math.max(1980, Math.min(2107, d.getFullYear()));
|
||||
const dosTime =
|
||||
((d.getHours() & 0x1f) << 11) |
|
||||
((d.getMinutes() & 0x3f) << 5) |
|
||||
((Math.floor(d.getSeconds() / 2)) & 0x1f);
|
||||
const dosDate =
|
||||
(((year - 1980) & 0x7f) << 9) |
|
||||
(((d.getMonth() + 1) & 0x0f) << 5) |
|
||||
(d.getDate() & 0x1f);
|
||||
return { dosTime, dosDate };
|
||||
}
|
||||
|
||||
function collectRuntimeSubdirFiles(repoRoot, relDir, out) {
|
||||
const absDir = join(repoRoot, relDir);
|
||||
if (!existsSync(absDir)) {
|
||||
throw new Error(`Missing required runtime directory: ${relDir}`);
|
||||
}
|
||||
const entries = readdirSync(absDir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name)
|
||||
);
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.')) continue;
|
||||
const childRel = `${relDir}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
collectRuntimeSubdirFiles(repoRoot, childRel, out);
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
if (!ALLOWED_SUBDIR_EXT_RE.test(entry.name)) continue;
|
||||
if (entry.name.includes('.test.')) continue;
|
||||
out.push(childRel);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the deterministic whitelist of runtime-essential repository paths
|
||||
* (POSIX relative paths from `repoRoot`).
|
||||
*
|
||||
* @param {string} [repoRoot=DEFAULT_REPO_ROOT]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function collectReleaseRuntimeFiles(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
const files = [...ROOT_WHITELIST, ...PANEL_TOP_WHITELIST];
|
||||
for (const rel of files) {
|
||||
const abs = join(repoRoot, rel);
|
||||
if (!existsSync(abs) || !statSync(abs).isFile()) {
|
||||
throw new Error(`Missing required runtime file: ${rel}`);
|
||||
}
|
||||
}
|
||||
for (const relDir of RUNTIME_SUBDIRS) {
|
||||
collectRuntimeSubdirFiles(repoRoot, relDir, files);
|
||||
}
|
||||
const uniqueSorted = Array.from(new Set(files)).sort((a, b) => a.localeCompare(b));
|
||||
for (const rel of uniqueSorted) {
|
||||
if (FORBIDDEN_PATH_RE.test(rel)) {
|
||||
throw new Error(`Forbidden non-runtime file matched release list: ${rel}`);
|
||||
}
|
||||
}
|
||||
return uniqueSorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a standard PKZIP (DEFLATE level 9, UTF-8 POSIX entry names) buffer in pure Node.js.
|
||||
*
|
||||
* @param {Array<{ name: string, data: Buffer, mtime?: Date }>} entries
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
export function buildZipBuffer(entries) {
|
||||
const localParts = [];
|
||||
const centralParts = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const nameStr = String(entry.name || '').replace(/\\/g, '/').replace(/^\/+/, '');
|
||||
const nameBuf = Buffer.from(nameStr, 'utf8');
|
||||
const rawBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || '');
|
||||
const deflated = deflateRawSync(rawBuf, { level: 9 });
|
||||
const useDeflate = deflated.length < rawBuf.length;
|
||||
const payload = useDeflate ? deflated : rawBuf;
|
||||
const method = useDeflate ? 8 : 0;
|
||||
const checksum = crc32(rawBuf);
|
||||
const { dosTime, dosDate } = toDosTimeDate(entry.mtime);
|
||||
|
||||
const localHeader = Buffer.alloc(30);
|
||||
localHeader.writeUInt32LE(0x04034b50, 0);
|
||||
localHeader.writeUInt16LE(20, 4); // version needed: 2.0
|
||||
localHeader.writeUInt16LE(0x0800, 6); // UTF-8 filename flag
|
||||
localHeader.writeUInt16LE(method, 8);
|
||||
localHeader.writeUInt16LE(dosTime, 10);
|
||||
localHeader.writeUInt16LE(dosDate, 12);
|
||||
localHeader.writeUInt32LE(checksum, 14);
|
||||
localHeader.writeUInt32LE(payload.length, 18);
|
||||
localHeader.writeUInt32LE(rawBuf.length, 22);
|
||||
localHeader.writeUInt16LE(nameBuf.length, 26);
|
||||
localHeader.writeUInt16LE(0, 28);
|
||||
|
||||
localParts.push(localHeader, nameBuf, payload);
|
||||
|
||||
const centralHeader = Buffer.alloc(46);
|
||||
centralHeader.writeUInt32LE(0x02014b50, 0);
|
||||
centralHeader.writeUInt16LE((3 << 8) | 20, 4); // version made by: Unix / 2.0
|
||||
centralHeader.writeUInt16LE(20, 6); // version needed: 2.0
|
||||
centralHeader.writeUInt16LE(0x0800, 8); // UTF-8 filename flag
|
||||
centralHeader.writeUInt16LE(method, 10);
|
||||
centralHeader.writeUInt16LE(dosTime, 12);
|
||||
centralHeader.writeUInt16LE(dosDate, 14);
|
||||
centralHeader.writeUInt32LE(checksum, 16);
|
||||
centralHeader.writeUInt32LE(payload.length, 20);
|
||||
centralHeader.writeUInt32LE(rawBuf.length, 24);
|
||||
centralHeader.writeUInt16LE(nameBuf.length, 28);
|
||||
centralHeader.writeUInt16LE(0, 30);
|
||||
centralHeader.writeUInt16LE(0, 32);
|
||||
centralHeader.writeUInt16LE(0, 34);
|
||||
centralHeader.writeUInt16LE(0, 36);
|
||||
centralHeader.writeUInt32LE((0o100644 << 16) >>> 0, 38); // regular file mode
|
||||
centralHeader.writeUInt32LE(offset, 42);
|
||||
|
||||
centralParts.push(centralHeader, nameBuf);
|
||||
offset += localHeader.length + nameBuf.length + payload.length;
|
||||
}
|
||||
|
||||
const centralDirBuf = Buffer.concat(centralParts);
|
||||
const eocd = Buffer.alloc(22);
|
||||
eocd.writeUInt32LE(0x06054b50, 0);
|
||||
eocd.writeUInt16LE(0, 4);
|
||||
eocd.writeUInt16LE(0, 6);
|
||||
eocd.writeUInt16LE(entries.length, 8);
|
||||
eocd.writeUInt16LE(entries.length, 10);
|
||||
eocd.writeUInt32LE(centralDirBuf.length, 12);
|
||||
eocd.writeUInt32LE(offset, 16);
|
||||
eocd.writeUInt16LE(0, 20);
|
||||
|
||||
return Buffer.concat([...localParts, centralDirBuf, eocd]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the runtime-only `usage-monitor.zip` release bundle.
|
||||
*
|
||||
* @param {{ repoRoot?: string, outFile?: string, rootPrefix?: string }} [options]
|
||||
*/
|
||||
export function packReleaseZip({
|
||||
repoRoot = DEFAULT_REPO_ROOT,
|
||||
outFile = DEFAULT_ZIP_OUT,
|
||||
rootPrefix = RELEASE_ARCHIVE_ROOT,
|
||||
} = {}) {
|
||||
const relFiles = collectReleaseRuntimeFiles(repoRoot);
|
||||
let totalRawBytes = 0;
|
||||
const zipEntries = relFiles.map((rel) => {
|
||||
const abs = join(repoRoot, rel);
|
||||
const data = readFileSync(abs);
|
||||
const st = statSync(abs);
|
||||
totalRawBytes += data.length;
|
||||
return {
|
||||
name: rootPrefix ? `${rootPrefix}/${rel}` : rel,
|
||||
data,
|
||||
mtime: st.mtime,
|
||||
};
|
||||
});
|
||||
|
||||
const zipBuf = buildZipBuffer(zipEntries);
|
||||
mkdirSync(dirname(outFile), { recursive: true });
|
||||
writeFileSync(outFile, zipBuf);
|
||||
|
||||
return {
|
||||
outFile,
|
||||
fileCount: relFiles.length,
|
||||
files: relFiles,
|
||||
rawBytes: totalRawBytes,
|
||||
zipBytes: zipBuf.length,
|
||||
};
|
||||
}
|
||||
|
||||
function parseCliOutArg(argv) {
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--out' && argv[i + 1]) {
|
||||
return resolve(argv[i + 1]);
|
||||
}
|
||||
if (arg.startsWith('--out=')) {
|
||||
return resolve(arg.slice(6));
|
||||
}
|
||||
}
|
||||
return DEFAULT_ZIP_OUT;
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const outFile = parseCliOutArg(process.argv.slice(2));
|
||||
const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile });
|
||||
console.log(
|
||||
`Packed ${summary.outFile} (${summary.fileCount} runtime files, raw ${(summary.rawBytes / 1024).toFixed(1)} KB -> zip ${(summary.zipBytes / 1024).toFixed(1)} KB)`
|
||||
);
|
||||
}
|
||||
@@ -446,3 +446,17 @@ export function normalizeStandalonePort(port) {
|
||||
if (num >= 1024 && num <= 65535) return num;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实验性现代化新 UI 开关(默认 `false`)。
|
||||
*
|
||||
* @param {unknown} val
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function normalizeExperimentalModernUi(val) {
|
||||
if (typeof val === 'string') {
|
||||
const lower = val.trim().toLowerCase();
|
||||
return lower === 'true' || lower === '1' || lower === 'on';
|
||||
}
|
||||
return Boolean(val);
|
||||
}
|
||||
|
||||
@@ -119,6 +119,7 @@ export const App = defineComponent({
|
||||
} else if (activeView === 'consumption') {
|
||||
consumptionView.refs?.viewScrollbar?.refresh();
|
||||
} else if (activeView === 'steps') {
|
||||
stepsView.refs?.refreshStepTableViewport?.();
|
||||
stepsView.refs?.stepsScroll?.refresh();
|
||||
stepsView.refs?.modelsScroll?.refresh();
|
||||
} else if (activeView === 'settings') {
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
formatStepAnomalyInlineSummary,
|
||||
formatTokens,
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
@@ -327,7 +330,7 @@ export function computePublicationFit(
|
||||
|
||||
if (sw <= 1e-12) {
|
||||
const fallbackVal = ols.intercept + ols.slope * x0;
|
||||
return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n };
|
||||
return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n };
|
||||
}
|
||||
|
||||
const mx = swx / sw;
|
||||
@@ -343,6 +346,7 @@ export function computePublicationFit(
|
||||
const useSlope = sxxW > 1e-12;
|
||||
const inverseWeightSum = 1 / sw;
|
||||
const slopeScale = useSlope ? dx0 / sxxW : 0;
|
||||
const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0);
|
||||
let rawFit = 0;
|
||||
let leverageNormSq = 0;
|
||||
let diagHat = 0;
|
||||
@@ -356,21 +360,53 @@ export function computePublicationFit(
|
||||
if (j === diagIdx) diagHat = lj;
|
||||
}
|
||||
|
||||
return { rawFit, leverageNormSq, diagHat };
|
||||
return { rawFit, leverageNormSq, diagHat, localHatDiag };
|
||||
}
|
||||
|
||||
const rawSampleFits = new Float64Array(n);
|
||||
const sampleLevSq = new Float64Array(n);
|
||||
let sse = 0;
|
||||
let traceL = 0;
|
||||
let precomputedGridEval = null;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const res = evalLoessPoint(xs[i], i);
|
||||
rawSampleFits[i] = res.rawFit;
|
||||
sampleLevSq[i] = res.leverageNormSq;
|
||||
traceL += res.diagHat;
|
||||
const diff = ys[i] - res.rawFit;
|
||||
sse += diff * diff;
|
||||
// 大样本(n > 200 且 x 单调有序)采用与 R `stats::loess(surface = "interpolate")` 一致的网格插值加速:
|
||||
// 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值与杠杆度,避免 O(N²) 阻塞主线程。
|
||||
if (n > 200 && sortedXs && M >= 2) {
|
||||
const gridRawFit = new Float64Array(M);
|
||||
const gridLevSq = new Float64Array(M);
|
||||
const gridHatDiag = new Float64Array(M);
|
||||
for (let k = 0; k < M; k++) {
|
||||
const res = evalLoessPoint(gridXs[k], -1);
|
||||
gridRawFit[k] = res.rawFit;
|
||||
gridLevSq[k] = res.leverageNormSq;
|
||||
gridHatDiag[k] = res.localHatDiag;
|
||||
}
|
||||
precomputedGridEval = { gridRawFit, gridLevSq };
|
||||
|
||||
const invSpan = (M - 1) / xSpan;
|
||||
const maxK0 = M - 2;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const u = (xs[i] - xMin) * invSpan;
|
||||
const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u);
|
||||
const frac = Math.max(0, Math.min(1, u - k0));
|
||||
const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]);
|
||||
const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0]));
|
||||
const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]);
|
||||
rawSampleFits[i] = rf;
|
||||
sampleLevSq[i] = ls;
|
||||
traceL += hd;
|
||||
const diff = ys[i] - rf;
|
||||
sse += diff * diff;
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const res = evalLoessPoint(xs[i], i);
|
||||
rawSampleFits[i] = res.rawFit;
|
||||
sampleLevSq[i] = res.leverageNormSq;
|
||||
traceL += res.diagHat;
|
||||
const diff = ys[i] - res.rawFit;
|
||||
sse += diff * diff;
|
||||
}
|
||||
}
|
||||
|
||||
const dfRes = Math.max(1, n - traceL);
|
||||
@@ -394,16 +430,27 @@ export function computePublicationFit(
|
||||
clampedSse += d * d;
|
||||
}
|
||||
|
||||
const grid = gridXs.map((gx) => {
|
||||
const res = evalLoessPoint(gx, -1);
|
||||
const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq);
|
||||
return {
|
||||
x: gx,
|
||||
fit: clampValue(res.rawFit, minVal, maxVal),
|
||||
ciLow: clampValue(res.rawFit - half, minVal, maxVal),
|
||||
ciHigh: clampValue(res.rawFit + half, minVal, maxVal),
|
||||
};
|
||||
});
|
||||
const grid = precomputedGridEval
|
||||
? gridXs.map((gx, k) => {
|
||||
const rf = precomputedGridEval.gridRawFit[k];
|
||||
const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k]));
|
||||
return {
|
||||
x: gx,
|
||||
fit: clampValue(rf, minVal, maxVal),
|
||||
ciLow: clampValue(rf - half, minVal, maxVal),
|
||||
ciHigh: clampValue(rf + half, minVal, maxVal),
|
||||
};
|
||||
})
|
||||
: gridXs.map((gx) => {
|
||||
const res = evalLoessPoint(gx, -1);
|
||||
const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq);
|
||||
return {
|
||||
x: gx,
|
||||
fit: clampValue(res.rawFit, minVal, maxVal),
|
||||
ciLow: clampValue(res.rawFit - half, minVal, maxVal),
|
||||
ciHigh: clampValue(res.rawFit + half, minVal, maxVal),
|
||||
};
|
||||
});
|
||||
|
||||
const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1;
|
||||
|
||||
@@ -597,9 +644,9 @@ function formatChartMetricValue(metric, val) {
|
||||
case 'context':
|
||||
return `${formatTokensPrecise(val)} tok`;
|
||||
case 'tps':
|
||||
return `${val.toFixed(1)} tok/s`;
|
||||
return formatSpeedMetric(val, ' tok/s');
|
||||
case 'ttft':
|
||||
return `${val.toFixed(1)}s`;
|
||||
return formatMetric(val, 's');
|
||||
case 'cache':
|
||||
return `${val.toFixed(1)}%`;
|
||||
case 'cost':
|
||||
@@ -616,9 +663,9 @@ function formatChartMetricCompact(metric, val) {
|
||||
case 'context':
|
||||
return formatTokens(val);
|
||||
case 'tps':
|
||||
return `${val.toFixed(1)} tok/s`;
|
||||
return formatSpeedMetric(val, ' tok/s');
|
||||
case 'ttft':
|
||||
return `${val.toFixed(1)}s`;
|
||||
return formatMetric(val, 's');
|
||||
case 'cache':
|
||||
return `${val.toFixed(1)}%`;
|
||||
case 'cost':
|
||||
@@ -706,6 +753,10 @@ export function createSessionLineChart() {
|
||||
const dotsGroup = document.createElementNS(SVG_NS, 'g');
|
||||
svg.appendChild(dotsGroup);
|
||||
|
||||
const anomalyDotsGroup = document.createElementNS(SVG_NS, 'g');
|
||||
anomalyDotsGroup.setAttribute('class', 'sstep-anomaly-dots');
|
||||
svg.appendChild(anomalyDotsGroup);
|
||||
|
||||
const hoverLine = document.createElementNS(SVG_NS, 'line');
|
||||
hoverLine.setAttribute('class', 'trend-hover-line');
|
||||
hoverLine.setAttribute('y1', '10');
|
||||
@@ -732,10 +783,12 @@ export function createSessionLineChart() {
|
||||
const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
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 tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]),
|
||||
tipSub,
|
||||
tipAnomaly,
|
||||
]);
|
||||
|
||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||
@@ -783,6 +836,7 @@ export function createSessionLineChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
hoveredIdx = idx;
|
||||
const pt = currentPoints[idx];
|
||||
patchAttr(hoverLine, 'hidden', false);
|
||||
@@ -792,7 +846,12 @@ export function createSessionLineChart() {
|
||||
patchAttr(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
patchStyleVar(hoverDot, '--hover-dot-color', pt.hoverColor || 'var(--ctx-cached)');
|
||||
const hoverAccent = pt.anomalySummary
|
||||
? pt.anomalySeverity === 'danger'
|
||||
? 'var(--metric-danger)'
|
||||
: 'var(--metric-warn)'
|
||||
: pt.hoverColor || 'var(--ctx-cached)';
|
||||
patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent);
|
||||
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
@@ -808,11 +867,30 @@ export function createSessionLineChart() {
|
||||
if (pt.subDetail) {
|
||||
patchText(tipSub, pt.subDetail);
|
||||
}
|
||||
patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary);
|
||||
if (pt.anomalySummary) {
|
||||
patchText(tipAnomaly, pt.anomalySummary);
|
||||
patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' });
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', '0px');
|
||||
if (wasHidden) {
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
void tooltipEl.offsetWidth;
|
||||
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
|
||||
window.requestAnimationFrame(() => {
|
||||
if (!tooltipEl.hasAttribute('hidden')) {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
}
|
||||
}
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
@@ -824,6 +902,7 @@ export function createSessionLineChart() {
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
if (currentPoints.some((p) => p.valid)) {
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
}
|
||||
@@ -938,6 +1017,7 @@ export function createSessionLineChart() {
|
||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||
while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild);
|
||||
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
|
||||
while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
patchAttr(modelLegendEl, 'hidden', true);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
@@ -1054,7 +1134,7 @@ export function createSessionLineChart() {
|
||||
valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0;
|
||||
value = valid ? Number(st.tokPerSec) : 0;
|
||||
secondaryRight = Number.isFinite(st.ttftSec)
|
||||
? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) })
|
||||
? t('chart.step.ttftShort', { sec: formatMetric(st.ttftSec, '') })
|
||||
: '';
|
||||
subDetail = valid
|
||||
? t('chart.step.outAndCtx', {
|
||||
@@ -1066,7 +1146,7 @@ export function createSessionLineChart() {
|
||||
} else if (metric === 'ttft') {
|
||||
valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0;
|
||||
value = valid ? Number(st.ttftSec) : 0;
|
||||
secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : '';
|
||||
secondaryRight = Number.isFinite(st.tokPerSec) ? formatSpeedMetric(st.tokPerSec, ' tok/s') : '';
|
||||
subDetail = valid
|
||||
? t('chart.step.ctxAndCache', {
|
||||
ctxTok: formatTokens(ctxTok),
|
||||
@@ -1105,6 +1185,7 @@ export function createSessionLineChart() {
|
||||
}
|
||||
|
||||
const dotColor = modelColorMap.get(gk) || accentColor;
|
||||
const anomalySummary = formatStepAnomalyInlineSummary(st.anomaly);
|
||||
return {
|
||||
idx,
|
||||
st,
|
||||
@@ -1117,6 +1198,8 @@ export function createSessionLineChart() {
|
||||
value,
|
||||
secondaryRight,
|
||||
subDetail,
|
||||
anomalySummary,
|
||||
anomalySeverity: st.anomaly?.severity || '',
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1152,7 +1235,10 @@ export function createSessionLineChart() {
|
||||
const sig =
|
||||
`${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` +
|
||||
points
|
||||
.map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`)
|
||||
.map(
|
||||
(p) =>
|
||||
`${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}:${p.st?.anomalySig || ''}`
|
||||
)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastSig) {
|
||||
@@ -1160,6 +1246,7 @@ export function createSessionLineChart() {
|
||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||
while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild);
|
||||
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
|
||||
while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild);
|
||||
|
||||
if (isMultiCompare) {
|
||||
patchAttr(linePath, 'd', '');
|
||||
@@ -1255,6 +1342,19 @@ export function createSessionLineChart() {
|
||||
}
|
||||
}
|
||||
|
||||
for (const pt of points) {
|
||||
if (!pt.valid || !pt.anomalySummary) continue;
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', pt.x.toFixed(1));
|
||||
aDot.setAttribute('cy', pt.y.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
anomalyDotsGroup.appendChild(aDot);
|
||||
}
|
||||
|
||||
const tickIndices = computeStepTickIndices(points.length);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
tickElsByIdx = new Map();
|
||||
@@ -1482,10 +1582,12 @@ export function createModelFitChart() {
|
||||
const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
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 tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]),
|
||||
tipSub,
|
||||
tipAnomaly,
|
||||
]);
|
||||
|
||||
const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') });
|
||||
@@ -1576,7 +1678,12 @@ export function createModelFitChart() {
|
||||
patchAttr(hoverRawDot, 'hidden', false);
|
||||
patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1));
|
||||
patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1));
|
||||
patchClasses(hoverRawDot, {
|
||||
'is-anomaly': Boolean(sp.anomalySummary),
|
||||
'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'),
|
||||
});
|
||||
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
patchText(tipHeadLeft, sp.stepTag);
|
||||
patchText(tipHeadRight, sp.modelText);
|
||||
@@ -1607,11 +1714,30 @@ export function createModelFitChart() {
|
||||
})
|
||||
);
|
||||
}
|
||||
patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary);
|
||||
if (sp.anomalySummary) {
|
||||
patchText(tipAnomaly, sp.anomalySummary);
|
||||
patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' });
|
||||
}
|
||||
|
||||
const rawPct = (sp.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', '0px');
|
||||
if (wasHidden) {
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
void tooltipEl.offsetWidth;
|
||||
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
|
||||
window.requestAnimationFrame(() => {
|
||||
if (!tooltipEl.hasAttribute('hidden')) {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
@@ -1620,6 +1746,7 @@ export function createModelFitChart() {
|
||||
patchAttr(hoverFitDot, 'hidden', true);
|
||||
patchAttr(hoverRawDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
}
|
||||
|
||||
plotStage.addEventListener('mousemove', (e) => {
|
||||
@@ -1627,14 +1754,19 @@ export function createModelFitChart() {
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
let bestIdx = 0;
|
||||
let bestDist = Math.abs(currentSamples[0].x - relX);
|
||||
for (let i = 1; i < currentSamples.length; i++) {
|
||||
const d = Math.abs(currentSamples[i].x - relX);
|
||||
if (d < bestDist) {
|
||||
bestDist = d;
|
||||
bestIdx = i;
|
||||
}
|
||||
let lo = 0;
|
||||
let hi = currentSamples.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if (currentSamples[mid].x < relX) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
let bestIdx = lo;
|
||||
if (
|
||||
lo > 0 &&
|
||||
Math.abs(currentSamples[lo - 1].x - relX) <= Math.abs(currentSamples[lo].x - relX)
|
||||
) {
|
||||
bestIdx = lo - 1;
|
||||
}
|
||||
showHoverAt(bestIdx);
|
||||
});
|
||||
@@ -1871,6 +2003,8 @@ export function createModelFitChart() {
|
||||
rawVal,
|
||||
stepTag: formatStepAxisTag(st, showAgentPrefix),
|
||||
modelText: disp.baseText || disp.text,
|
||||
anomalySummary: formatStepAnomalyInlineSummary(st.anomaly),
|
||||
anomalySeverity: st.anomaly?.severity || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2024,7 +2158,12 @@ export function createModelFitChart() {
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.key}:${s.colorVar}:` +
|
||||
s.samples.map((p) => `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}`).join(',')
|
||||
s.samples
|
||||
.map(
|
||||
(p) =>
|
||||
`${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}:${p.st?.anomalySig || ''}`
|
||||
)
|
||||
.join(',')
|
||||
)
|
||||
.join('||');
|
||||
|
||||
@@ -2048,16 +2187,33 @@ export function createModelFitChart() {
|
||||
|
||||
const dotRadius =
|
||||
combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4';
|
||||
const dedupOverdraw = combinedSamples.length > 200;
|
||||
const scatterTarget =
|
||||
typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: scatterGroup;
|
||||
const anomalyOverlayDots = [];
|
||||
|
||||
for (const s of seriesList) {
|
||||
const binCounts = dedupOverdraw ? new Map() : null;
|
||||
for (const sp of s.samples) {
|
||||
if (sp.anomalySummary) {
|
||||
anomalyOverlayDots.push(sp);
|
||||
continue;
|
||||
}
|
||||
if (binCounts) {
|
||||
const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2);
|
||||
const prevCnt = binCounts.get(binKey) || 0;
|
||||
if (prevCnt >= 6) continue;
|
||||
binCounts.set(binKey, prevCnt + 1);
|
||||
}
|
||||
const dot = document.createElementNS(SVG_NS, 'circle');
|
||||
dot.setAttribute('cx', sp.x.toFixed(1));
|
||||
dot.setAttribute('cy', sp.rawY.toFixed(1));
|
||||
dot.setAttribute('r', dotRadius);
|
||||
dot.setAttribute('class', 'sstep-scatter-dot is-multi');
|
||||
patchStyleVar(dot, '--sstep-fit-accent', s.colorVar);
|
||||
scatterGroup.appendChild(dot);
|
||||
scatterTarget.appendChild(dot);
|
||||
}
|
||||
|
||||
if (s.samples.length === 1) {
|
||||
@@ -2107,6 +2263,20 @@ export function createModelFitChart() {
|
||||
multiCurveGroup.appendChild(curveEl);
|
||||
}
|
||||
}
|
||||
for (const sp of anomalyOverlayDots) {
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', sp.x.toFixed(1));
|
||||
aDot.setAttribute('cy', sp.rawY.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
scatterTarget.appendChild(aDot);
|
||||
}
|
||||
if (scatterTarget !== scatterGroup) {
|
||||
scatterGroup.appendChild(scatterTarget);
|
||||
}
|
||||
|
||||
while (multiLegendEl.firstChild) multiLegendEl.removeChild(multiLegendEl.firstChild);
|
||||
for (const s of seriesList) {
|
||||
@@ -2220,7 +2390,11 @@ export function createModelFitChart() {
|
||||
|
||||
const sig =
|
||||
`single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
||||
samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|');
|
||||
samples
|
||||
.map(
|
||||
(s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}:${s.st?.anomalySig || ''}`
|
||||
)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastSig) {
|
||||
lastSig = sig;
|
||||
@@ -2239,13 +2413,43 @@ export function createModelFitChart() {
|
||||
// 2. 绘制半透明冷蓝灰实心观测散点(自然呈现局部密度,不抢夺拟合曲线焦点)
|
||||
while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild);
|
||||
const dotRadius = samples.length > 80 ? '1.8' : samples.length > 36 ? '2.1' : '2.4';
|
||||
const binCounts = samples.length > 200 ? new Map() : null;
|
||||
const scatterTarget =
|
||||
typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: scatterGroup;
|
||||
const singleAnomalyDots = [];
|
||||
for (const s of samples) {
|
||||
if (s.anomalySummary) {
|
||||
singleAnomalyDots.push(s);
|
||||
continue;
|
||||
}
|
||||
if (binCounts) {
|
||||
const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2);
|
||||
const prevCnt = binCounts.get(binKey) || 0;
|
||||
if (prevCnt >= 6) continue;
|
||||
binCounts.set(binKey, prevCnt + 1);
|
||||
}
|
||||
const dot = document.createElementNS(SVG_NS, 'circle');
|
||||
dot.setAttribute('cx', s.x.toFixed(1));
|
||||
dot.setAttribute('cy', s.rawY.toFixed(1));
|
||||
dot.setAttribute('r', dotRadius);
|
||||
dot.setAttribute('class', 'sstep-scatter-dot');
|
||||
scatterGroup.appendChild(dot);
|
||||
scatterTarget.appendChild(dot);
|
||||
}
|
||||
for (const s of singleAnomalyDots) {
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', s.x.toFixed(1));
|
||||
aDot.setAttribute('cy', s.rawY.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
scatterTarget.appendChild(aDot);
|
||||
}
|
||||
if (scatterTarget !== scatterGroup) {
|
||||
scatterGroup.appendChild(scatterTarget);
|
||||
}
|
||||
|
||||
// 3. 绘制 95% CI 置信带闭合多边形与回归拟合曲线(绝不向底部 X 轴填充面积!)
|
||||
|
||||
@@ -6,7 +6,14 @@
|
||||
* 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
@@ -196,9 +203,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
const DEFAULT_VIEW_W = 460;
|
||||
const VIEW_H = 120;
|
||||
const TOP_Y = 24;
|
||||
const BOTTOM_Y = 102;
|
||||
const VIEW_H = 184;
|
||||
const TOP_Y = 26;
|
||||
const BOTTOM_Y = 164;
|
||||
const SPAN_Y = BOTTOM_Y - TOP_Y;
|
||||
|
||||
let viewW = DEFAULT_VIEW_W;
|
||||
@@ -243,7 +250,12 @@ export function createTrendAreaChart() {
|
||||
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
hGridGroup.setAttribute('class', 'trend-grid');
|
||||
const hGridLines = [];
|
||||
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
|
||||
for (const y of [
|
||||
TOP_Y,
|
||||
Math.round(TOP_Y + SPAN_Y / 3),
|
||||
Math.round(TOP_Y + (SPAN_Y * 2) / 3),
|
||||
BOTTOM_Y,
|
||||
]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', '0');
|
||||
line.setAttribute('y1', String(y));
|
||||
@@ -292,12 +304,28 @@ export function createTrendAreaChart() {
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
|
||||
// 共享悬停详情浮层卡片(曲线图与热力格子图共用)
|
||||
function createTooltipModelRow() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot' });
|
||||
const nameEl = h('span', { className: 'cons-pop-model-name' });
|
||||
const tokEl = h('span', { className: 'cons-pop-model-tok' });
|
||||
const pctEl = h('strong', { className: 'cons-pop-model-pct' });
|
||||
const rowEl = h('div', { className: 'cons-pop-model-row' }, [
|
||||
h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]),
|
||||
h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]),
|
||||
]);
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { rowEl, dotEl, nameEl, tokEl, pctEl },
|
||||
};
|
||||
}
|
||||
|
||||
// 共享悬停详情浮层卡片(曲线图与热力格子图共用,含该时段分模型占比明细)
|
||||
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
||||
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||
const tipTokensEl = h('strong', { className: 'trend-tip-tokens 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 tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true });
|
||||
|
||||
const tooltipEl = h(
|
||||
'div',
|
||||
@@ -306,6 +334,7 @@ export function createTrendAreaChart() {
|
||||
h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]),
|
||||
tipSubEl,
|
||||
tipModelsEl,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -374,6 +403,34 @@ export function createTrendAreaChart() {
|
||||
let hoveredIdx = -1;
|
||||
let hoveredCellEl = null;
|
||||
let lastRenderSig = '';
|
||||
let tipTrackRaf = 0;
|
||||
|
||||
function cancelTipTrackRaf() {
|
||||
if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') {
|
||||
window.cancelAnimationFrame(tipTrackRaf);
|
||||
}
|
||||
tipTrackRaf = 0;
|
||||
}
|
||||
|
||||
function armTooltipTracking(wasHidden) {
|
||||
if (!wasHidden) return;
|
||||
patchClasses(tooltipEl, { 'is-tracking': false });
|
||||
patchClasses(hoverDot, { 'is-tracking': false });
|
||||
void tooltipEl.offsetWidth;
|
||||
cancelTipTrackRaf();
|
||||
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
|
||||
tipTrackRaf = window.requestAnimationFrame(() => {
|
||||
tipTrackRaf = 0;
|
||||
if (!tooltipEl.hasAttribute('hidden')) {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
patchClasses(hoverDot, { 'is-tracking': true });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
patchClasses(tooltipEl, { 'is-tracking': true });
|
||||
patchClasses(hoverDot, { 'is-tracking': true });
|
||||
}
|
||||
}
|
||||
|
||||
function populateTooltipContent(slot) {
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
@@ -407,6 +464,21 @@ export function createTrendAreaChart() {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : [];
|
||||
patchAttr(tipModelsEl, 'hidden', modelSegs.length === 0);
|
||||
patchKeyedList(tipModelsEl, modelSegs, {
|
||||
keyFn: (r) => r.key,
|
||||
sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`,
|
||||
createRow: createTooltipModelRow,
|
||||
updateRow: (rRefs, r) => {
|
||||
patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) });
|
||||
patchStyleVar(rRefs.dotEl, '--dot-color', r.color);
|
||||
patchText(rRefs.nameEl, r.label);
|
||||
patchText(rRefs.tokEl, r.tokText);
|
||||
patchText(rRefs.pctEl, r.pctText);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function showLineHoverAtIndex(idx) {
|
||||
@@ -414,6 +486,7 @@ export function createTrendAreaChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
hoveredIdx = idx;
|
||||
const slot = currentSlots[idx];
|
||||
const pt = currentPts[idx];
|
||||
@@ -426,15 +499,31 @@ export function createTrendAreaChart() {
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
|
||||
const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': isLineLow,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
|
||||
let tipY = 0;
|
||||
if (isLineLow) {
|
||||
const wrapH = Number(chartWrap.offsetHeight || 0);
|
||||
const tipH = Number(tooltipEl.offsetHeight || 0);
|
||||
if (wrapH > 0 && tipH > 0) {
|
||||
tipY = Math.max(0, wrapH - tipH - 22);
|
||||
}
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`);
|
||||
armTooltipTracking(wasHidden);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
@@ -462,10 +551,12 @@ export function createTrendAreaChart() {
|
||||
const row = Number(targetCell.getAttribute('data-hm-row') || 0);
|
||||
const col = Number(targetCell.getAttribute('data-hm-col') || 0);
|
||||
|
||||
// 上半区(周一~周四)浮层停靠底部,下半区(周五~周日)停靠顶部,互不遮挡被悬停格子且永不越界裁剪
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
// 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': row <= 3,
|
||||
'is-hm-top': row > 3,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
@@ -487,14 +578,23 @@ export function createTrendAreaChart() {
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', '0px');
|
||||
armTooltipTracking(wasHidden);
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
cancelTipTrackRaf();
|
||||
hoveredIdx = -1;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': false,
|
||||
'is-tracking': false,
|
||||
});
|
||||
patchClasses(hoverDot, { 'is-tracking': false });
|
||||
if (!currentIsHeatmap) {
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
}
|
||||
@@ -706,6 +806,7 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
cancelTipTrackRaf();
|
||||
resizeObs?.disconnect();
|
||||
resizeObs = null;
|
||||
if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
||||
@@ -776,12 +877,18 @@ export function createTrendAreaChart() {
|
||||
const sig =
|
||||
`${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` +
|
||||
slots
|
||||
.map(
|
||||
(s) =>
|
||||
`${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`
|
||||
)
|
||||
.map((s) => {
|
||||
const mSig = Array.isArray(s?.modelSegments)
|
||||
? s.modelSegments.map((m) => `${m.key}:${m.color}:${m.pctText}`).join(',')
|
||||
: '';
|
||||
return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`;
|
||||
})
|
||||
.join('|');
|
||||
|
||||
if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) {
|
||||
populateTooltipContent(slots[hoveredIdx]);
|
||||
}
|
||||
|
||||
if (useHeatmap) {
|
||||
currentPts = [];
|
||||
if (sig !== lastRenderSig) {
|
||||
@@ -813,13 +920,18 @@ export function createTrendAreaChart() {
|
||||
hmMonthsEl.appendChild(mEl);
|
||||
}
|
||||
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天)
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排
|
||||
while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild);
|
||||
hoveredCellEl = null;
|
||||
currentCellEls = new Array(slots.length);
|
||||
const gridFrag =
|
||||
typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: null;
|
||||
const gridTarget = gridFrag || hmGridEl;
|
||||
|
||||
for (let pad = 0; pad < firstDow; pad++) {
|
||||
hmGridEl.appendChild(
|
||||
gridTarget.appendChild(
|
||||
h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' })
|
||||
);
|
||||
}
|
||||
@@ -838,9 +950,12 @@ export function createTrendAreaChart() {
|
||||
'data-hm-row': String(row),
|
||||
role: 'gridcell',
|
||||
});
|
||||
hmGridEl.appendChild(cellEl);
|
||||
gridTarget.appendChild(cellEl);
|
||||
currentCellEls[i] = cellEl;
|
||||
}
|
||||
if (gridFrag) {
|
||||
hmGridEl.appendChild(gridFrag);
|
||||
}
|
||||
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
|
||||
@@ -11,7 +11,10 @@ import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentBadgeText,
|
||||
formatConversationMeta,
|
||||
normalizeClientUpdateMode,
|
||||
resolveHostRouteMatch,
|
||||
selectConversation,
|
||||
telemetryStore,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
@@ -19,16 +22,7 @@ import { uiStore } from '../../store/uiStore.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return t('header.convMetaWithSubs', {
|
||||
main: c.stepCount || 0,
|
||||
subs,
|
||||
total: c.totalStepCount || c.stepCount || 0,
|
||||
});
|
||||
}
|
||||
return t('header.convMetaSteps', { count: c.stepCount || 0 });
|
||||
return formatConversationMeta(c);
|
||||
}
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
@@ -40,8 +34,7 @@ export const TopSessionHeader = defineComponent({
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(nextConvId);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -106,10 +99,49 @@ export const TopSessionHeader = defineComponent({
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
let lastAppliedHostChildRouteId = '';
|
||||
|
||||
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||
function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) {
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (!currentCascadeId) return;
|
||||
|
||||
const selectedId = String(telSlice?.selectedConversationId || '').trim();
|
||||
const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim();
|
||||
const hostRouteLower = hostRouteId.toLowerCase();
|
||||
|
||||
if (!selectedId && hostRouteLower) {
|
||||
const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId);
|
||||
if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (lastAppliedHostChildRouteId !== hostRouteLower) {
|
||||
lastAppliedHostChildRouteId = hostRouteLower;
|
||||
const targetAgentId = routeMatch.childAgent.agentId;
|
||||
const uiSt = uiStore.getState();
|
||||
if (
|
||||
uiSt.selectedAgentScope !== targetAgentId ||
|
||||
uiSt.ctxInspectorAgentId !== targetAgentId
|
||||
) {
|
||||
uiStore.setState({
|
||||
selectedAgentScope: targetAgentId,
|
||||
ctxInspectorAgentId: targetAgentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
const uiSt = uiStore.getState();
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
}
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
return;
|
||||
}
|
||||
} else if (lastAppliedHostChildRouteId) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
}
|
||||
|
||||
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
const uiSt = uiStore.getState();
|
||||
@@ -133,34 +165,44 @@ export const TopSessionHeader = defineComponent({
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
const hostMatchedConv = hostRouteId
|
||||
? convs.find((c) => c.cascadeId === hostRouteId) ||
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null;
|
||||
const hostMatchedConv = routeMatch?.rootConv || null;
|
||||
const childRouteBadge =
|
||||
routeMatch?.isChildRoute && routeMatch.childAgent
|
||||
? formatAgentBadgeText(routeMatch.childAgent)
|
||||
: '';
|
||||
const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8);
|
||||
const hostDisplayTitle = childRouteBadge
|
||||
? `${hostBaseTitle} · ${childRouteBadge}`
|
||||
: hostBaseTitle;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? t('header.currentWindowNamed', {
|
||||
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
|
||||
title: hostDisplayTitle,
|
||||
})
|
||||
: convs[0]?.title
|
||||
? t('header.latestNamed', { title: convs[0].title })
|
||||
: t('header.followLatest');
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
stepCount: hostMatchedConv.stepCount,
|
||||
subagentCount: hostMatchedConv.subagentCount,
|
||||
totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents,
|
||||
})
|
||||
? formatConvOptionMeta(hostMatchedConv)
|
||||
: ''
|
||||
: convs[0]
|
||||
? formatConvOptionMeta(convs[0])
|
||||
: '';
|
||||
const options = [
|
||||
{ value: '', label: defaultOptLabel, meta: defaultOptMeta },
|
||||
{
|
||||
value: '',
|
||||
label: defaultOptLabel,
|
||||
meta: defaultOptMeta,
|
||||
...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}),
|
||||
},
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: formatConvOptionMeta(c),
|
||||
...(c.swarmTitle && c.swarmTitle !== c.title
|
||||
? { title: `${c.title || c.cascadeId.slice(0, 8)} · ${c.swarmTitle}` }
|
||||
: {}),
|
||||
})),
|
||||
];
|
||||
const lockedId = telSt.selectedConversationId;
|
||||
@@ -170,13 +212,7 @@ export const TopSessionHeader = defineComponent({
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: t('header.lockedMeta');
|
||||
const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta');
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
@@ -283,7 +319,7 @@ export const TopSessionHeader = defineComponent({
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
(slice) => {
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry, slice);
|
||||
renderHeaderState();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
PANEL_SCALE_FACTORS,
|
||||
applyAppearanceToRoot,
|
||||
normalizeClientFontScale,
|
||||
normalizeClientModernUi,
|
||||
} from '../../core/appearance.js';
|
||||
import {
|
||||
h,
|
||||
@@ -33,6 +34,7 @@ import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
buildCapsuleSlotContext,
|
||||
createCapsuleSlotNode,
|
||||
patchCapsuleOdometerText,
|
||||
resolveMultiSessionCapsuleState,
|
||||
syncCapsuleSlotNodes,
|
||||
} from '../widgets/CapsuleBarWidget.js';
|
||||
@@ -50,6 +52,7 @@ import {
|
||||
normalizeClientUpdateMode,
|
||||
normalizeClientWindowMountMode,
|
||||
resolveScopedConversation,
|
||||
selectConversation,
|
||||
startAsyncTelemetryLoop,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
@@ -1084,8 +1087,7 @@ export function mountWindowOverlay() {
|
||||
selectedAgentScope: 'all',
|
||||
ctxInspectorAgentId: 'auto',
|
||||
});
|
||||
telemetryStore.setState({ selectedConversationId: cascadeId });
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(cascadeId);
|
||||
setMultiOpen(false);
|
||||
setPopoverOpen(true);
|
||||
}
|
||||
@@ -1397,6 +1399,7 @@ export function mountWindowOverlay() {
|
||||
onSelectSession: inspectSessionInMonitor,
|
||||
onLayoutChange: () => {
|
||||
if (multiOpen) {
|
||||
patchClasses(multiPanelEl, { 'is-instant': true });
|
||||
positionFloatingElements();
|
||||
}
|
||||
},
|
||||
@@ -1454,9 +1457,23 @@ export function mountWindowOverlay() {
|
||||
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
|
||||
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
|
||||
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||
popoverEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
hoverTipEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
multiPanelEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi);
|
||||
const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light';
|
||||
for (const el of [popoverEl, hoverTipEl, multiPanelEl]) {
|
||||
if (el.getAttribute?.('data-font-scale') !== scaleKey) {
|
||||
el.setAttribute?.('data-font-scale', scaleKey);
|
||||
}
|
||||
if (el.getAttribute?.('data-color-scheme') !== colorScheme) {
|
||||
el.setAttribute?.('data-color-scheme', colorScheme);
|
||||
}
|
||||
if (isModernUi) {
|
||||
if (el.getAttribute?.('data-modern-ui') !== 'true') {
|
||||
el.setAttribute?.('data-modern-ui', 'true');
|
||||
}
|
||||
} else if (el.hasAttribute?.('data-modern-ui')) {
|
||||
el.removeAttribute?.('data-modern-ui');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
portalShadow.appendChild(multiPanelEl);
|
||||
@@ -1591,6 +1608,7 @@ export function mountWindowOverlay() {
|
||||
|
||||
function ensureWorkbenchThemeObserved() {
|
||||
const wb = syncWorkbenchThemeVars();
|
||||
syncPortalAppearance(telemetryStore.getState().telemetry?.settings);
|
||||
if (wb && wb !== observedWorkbench && themeObserver) {
|
||||
observedWorkbench = wb;
|
||||
try {
|
||||
@@ -2186,6 +2204,7 @@ export function mountWindowOverlay() {
|
||||
} else if (activeView === 'consumption') {
|
||||
refs?.consumptionView?.refs?.viewScrollbar?.refresh();
|
||||
} else if (activeView === 'steps') {
|
||||
refs?.stepsView?.refs?.refreshStepTableViewport?.();
|
||||
refs?.stepsView?.refs?.stepsScroll?.refresh();
|
||||
refs?.stepsView?.refs?.modelsScroll?.refresh();
|
||||
} else if (activeView === 'settings') {
|
||||
@@ -2297,16 +2316,26 @@ export function mountWindowOverlay() {
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||
}
|
||||
|
||||
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
||||
function renderMultiRunningPanel(
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
hostRouteConversationId,
|
||||
runningSwarmCount = 0
|
||||
) {
|
||||
if (!multiOpen || document.hidden) {
|
||||
multiRunningWidget.refs.pauseTicker();
|
||||
return;
|
||||
}
|
||||
const isPureSwarm = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
patchText(
|
||||
multiRunningMetaEl,
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('multi.metaWithSubs', { main: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarm ? 'multi.metaWithSwarm' : 'multi.metaWithSubs', {
|
||||
main: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('multi.metaMainOnly', { main: runningCount })
|
||||
: t('multi.allIdle')
|
||||
);
|
||||
@@ -2355,7 +2384,7 @@ export function mountWindowOverlay() {
|
||||
|
||||
if (!telemetry) {
|
||||
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
|
||||
patchText(multiLabel, t('capsule.multiZero'));
|
||||
patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' });
|
||||
patchText(multiRunningMetaEl, t('multi.loading'));
|
||||
multiRunningWidget.refs.stopLiveTicker();
|
||||
|
||||
@@ -2377,25 +2406,32 @@ export function mountWindowOverlay() {
|
||||
ctxAgent,
|
||||
aggregated,
|
||||
});
|
||||
const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } =
|
||||
resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
const {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
} = resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
|
||||
patchClasses(multiBtn, {
|
||||
'is-running': runningCount > 0 && !hasWaiting,
|
||||
'is-waiting': runningCount > 0 && hasWaiting,
|
||||
});
|
||||
patchText(multiLabel, multiBtnText);
|
||||
patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' });
|
||||
|
||||
renderMultiRunningPanel(
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
telSt.hostRouteConversationId
|
||||
telSt.hostRouteConversationId,
|
||||
runningSwarmCount
|
||||
);
|
||||
|
||||
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||
@@ -2531,13 +2567,12 @@ export function mountWindowOverlay() {
|
||||
if (currentRouteId === lastObservedRouteId) return;
|
||||
lastObservedRouteId = currentRouteId;
|
||||
const st = telemetryStore.getState();
|
||||
const patch = { hostRouteConversationId: currentRouteId };
|
||||
if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) {
|
||||
patch.selectedConversationId = '';
|
||||
}
|
||||
const nextSelectedId =
|
||||
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
|
||||
? ''
|
||||
: st.selectedConversationId;
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState(patch);
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
|
||||
}
|
||||
|
||||
const onDocMouseDown = (e) => {
|
||||
@@ -2603,6 +2638,7 @@ export function mountWindowOverlay() {
|
||||
if (typeof MutationObserver !== 'undefined') {
|
||||
themeObserver = new MutationObserver(() => {
|
||||
syncWorkbenchThemeVars();
|
||||
syncPortalAppearance(telemetryStore.getState().telemetry?.settings);
|
||||
});
|
||||
if (document.head) {
|
||||
themeObserver.observe(document.head, {
|
||||
@@ -2611,6 +2647,18 @@ export function mountWindowOverlay() {
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
if (document.documentElement) {
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'],
|
||||
});
|
||||
}
|
||||
if (document.body) {
|
||||
themeObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'],
|
||||
});
|
||||
}
|
||||
if (document.body) {
|
||||
hostDomObserver = new MutationObserver((records) => {
|
||||
if (
|
||||
|
||||
@@ -186,6 +186,7 @@ export const BridgeStatusNotice = defineComponent({
|
||||
|
||||
function syncActionButtons() {
|
||||
const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false;
|
||||
const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts);
|
||||
patchAttr(relaunchBtnEl, 'hidden', !canRelaunch);
|
||||
patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching');
|
||||
patchText(
|
||||
@@ -194,7 +195,9 @@ export const BridgeStatusNotice = defineComponent({
|
||||
? t('settings.bridge.relaunchingBtn')
|
||||
: relaunchState === 'failed'
|
||||
? t('settings.bridge.relaunchFailed')
|
||||
: t('settings.bridge.relaunchBtn')
|
||||
: needsAuth
|
||||
? t('settings.bridge.relaunchAuthBtn')
|
||||
: t('settings.bridge.relaunchBtn')
|
||||
);
|
||||
|
||||
patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy');
|
||||
@@ -227,38 +230,44 @@ export const BridgeStatusNotice = defineComponent({
|
||||
patchAttr(rootEl, 'hidden', !shouldShow);
|
||||
if (!shouldShow) return;
|
||||
|
||||
const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase();
|
||||
const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts);
|
||||
const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured;
|
||||
const isAutoConfigured = Boolean(
|
||||
wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured
|
||||
);
|
||||
const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop);
|
||||
|
||||
patchClasses(rootEl, {
|
||||
'is-restart': isAutoConfigured,
|
||||
'is-warn': !isAutoConfigured,
|
||||
'is-restart': useRestartTheme,
|
||||
'is-warn': !useRestartTheme,
|
||||
});
|
||||
patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning');
|
||||
patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning');
|
||||
|
||||
let titleText = '';
|
||||
if (isAutoConfigured) {
|
||||
let bodyText = '';
|
||||
if (hasReadOnlyShortcuts) {
|
||||
titleText = contextMode
|
||||
? t('settings.bridge.ctxReadOnlyTitle')
|
||||
: t('settings.bridge.readOnlyTitle');
|
||||
bodyText = t('settings.bridge.readOnlyBody');
|
||||
} else if (isMacDesktop) {
|
||||
titleText = contextMode
|
||||
? t('settings.bridge.ctxMacTitle')
|
||||
: t('settings.bridge.macTitle');
|
||||
bodyText = t('settings.bridge.guideMac');
|
||||
} else if (isAutoConfigured) {
|
||||
titleText = contextMode
|
||||
? t('settings.bridge.ctxRestartTitle')
|
||||
: t('settings.bridge.restartTitle');
|
||||
} else if (contextMode) {
|
||||
titleText = t('settings.bridge.ctxTitle');
|
||||
} else if (state === 'cdp_unreachable') {
|
||||
titleText = t('settings.bridge.unreachableTitle');
|
||||
} else {
|
||||
titleText = t('settings.bridge.noPortTitle');
|
||||
}
|
||||
|
||||
const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase();
|
||||
let bodyText = '';
|
||||
if (isAutoConfigured) {
|
||||
bodyText = t('settings.bridge.restartBody');
|
||||
} else if (plat === 'darwin') {
|
||||
bodyText = t('settings.bridge.guideMac');
|
||||
} else if (plat === 'linux') {
|
||||
bodyText = t('settings.bridge.guideLinux');
|
||||
} else {
|
||||
bodyText = t('settings.bridge.guideWin');
|
||||
titleText = contextMode
|
||||
? t('settings.bridge.ctxTitle')
|
||||
: state === 'cdp_unreachable'
|
||||
? t('settings.bridge.unreachableTitle')
|
||||
: t('settings.bridge.noPortTitle');
|
||||
bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin');
|
||||
}
|
||||
|
||||
patchText(titleEl, titleText);
|
||||
|
||||
@@ -6,22 +6,25 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js';
|
||||
import { formatTokens } from '../../core/formatters.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
const SEGMENT_DEFS = [
|
||||
{ key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) },
|
||||
{ key: 'toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) },
|
||||
{ key: 'assistant', labelKey: 'ctx.ch.assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) },
|
||||
{ key: 'toolResults', labelKey: 'ctx.ch.toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) },
|
||||
{
|
||||
key: 'userInput',
|
||||
labelKey: 'ctx.ch.userInput',
|
||||
cls: 'seg-user-input',
|
||||
getVal: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{ key: 'subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) },
|
||||
{ key: 'checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) },
|
||||
{ key: 'systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) },
|
||||
{ key: 'systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) },
|
||||
{ key: 'mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) },
|
||||
{ key: 'skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) },
|
||||
{ key: 'userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) },
|
||||
{ key: 'subagent', labelKey: 'ctx.ch.subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) },
|
||||
{ key: 'checkpoint', labelKey: 'ctx.ch.checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) },
|
||||
{ key: 'systemPrompt', labelKey: 'ctx.ch.systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) },
|
||||
{ key: 'systemTools', labelKey: 'ctx.ch.systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) },
|
||||
{ key: 'mcpTools', labelKey: 'ctx.ch.mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) },
|
||||
{ key: 'skills', labelKey: 'ctx.ch.skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) },
|
||||
{ key: 'userRules', labelKey: 'ctx.ch.userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) },
|
||||
];
|
||||
|
||||
export const ContextSegmentMeter = defineComponent({
|
||||
@@ -35,7 +38,7 @@ export const ContextSegmentMeter = defineComponent({
|
||||
const trackEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'progress-track',
|
||||
className: 'progress-track ctx-segment-meter',
|
||||
role: 'progressbar',
|
||||
'aria-valuemin': '0',
|
||||
'aria-valuemax': '100',
|
||||
@@ -67,11 +70,23 @@ export const ContextSegmentMeter = defineComponent({
|
||||
|
||||
patchClasses(trackEl, { 'is-reordering': orderChanged });
|
||||
|
||||
let seenActive = false;
|
||||
for (let i = 0; i < slotEls.length; i++) {
|
||||
const slotEl = slotEls[i];
|
||||
const item = scored[i];
|
||||
patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`);
|
||||
patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`);
|
||||
const isActive = item.val > 0 && item.pct > 0;
|
||||
const hasSep = isActive && seenActive;
|
||||
if (isActive) seenActive = true;
|
||||
const cls = `progress-seg ${item.def.cls}${isActive ? ' is-active' : ''}${hasSep ? ' has-sep' : ''}`;
|
||||
patchAttr(slotEl, 'class', cls);
|
||||
patchStyleVar(slotEl, '--seg-w', isActive ? `${item.pct.toFixed(2)}%` : '0%');
|
||||
patchAttr(
|
||||
slotEl,
|
||||
'title',
|
||||
isActive
|
||||
? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${item.pct.toFixed(1)}%)`
|
||||
: null
|
||||
);
|
||||
}
|
||||
|
||||
patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0));
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
positionAnchoredPopup,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatCompactDateTime } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
@@ -195,15 +196,47 @@ export const CustomDateTimePicker = defineComponent({
|
||||
|
||||
const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]);
|
||||
|
||||
function positionPopover() {
|
||||
if (!isOpen) return;
|
||||
positionAnchoredPopup(rootEl, triggerBtn, popoverEl, {
|
||||
margin: 6,
|
||||
gap: 4,
|
||||
maxHeight: 0,
|
||||
minFlipSpace: 260,
|
||||
});
|
||||
}
|
||||
|
||||
let boundReposition = false;
|
||||
function handleViewportChange() {
|
||||
if (!isOpen) return;
|
||||
positionPopover();
|
||||
}
|
||||
|
||||
function setRepositionListeners(active) {
|
||||
if (active === boundReposition) return;
|
||||
boundReposition = active;
|
||||
if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
if (active) {
|
||||
window.addEventListener('resize', handleViewportChange, { passive: true });
|
||||
window.addEventListener('scroll', handleViewportChange, true);
|
||||
} else {
|
||||
window.removeEventListener('resize', handleViewportChange);
|
||||
window.removeEventListener('scroll', handleViewportChange, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function togglePopover(nextOpen) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
patchAttr(popoverEl, 'hidden', !isOpen);
|
||||
patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false');
|
||||
setRepositionListeners(isOpen);
|
||||
if (isOpen) {
|
||||
const cur = new Date(getProps().modelValue || Date.now());
|
||||
viewYear = cur.getFullYear();
|
||||
viewMonth = cur.getMonth();
|
||||
renderCalendar();
|
||||
positionPopover();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +298,12 @@ export const CustomDateTimePicker = defineComponent({
|
||||
|
||||
if (typeof document !== 'undefined' && document.addEventListener) {
|
||||
document.addEventListener('click', handleDocClick, true);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick, true));
|
||||
onCleanup(() => {
|
||||
setRepositionListeners(false);
|
||||
document.removeEventListener('click', handleDocClick, true);
|
||||
});
|
||||
} else {
|
||||
onCleanup(() => setRepositionListeners(false));
|
||||
}
|
||||
|
||||
syncDisplay();
|
||||
|
||||
@@ -34,6 +34,7 @@ export const CustomScrollbar = defineComponent({
|
||||
let isDragging = false;
|
||||
let dragStartY = 0;
|
||||
let dragStartScrollTop = 0;
|
||||
let scrollRafId = 0;
|
||||
|
||||
function syncThumb() {
|
||||
const scrollHeight = Number(contentEl.scrollHeight || 0);
|
||||
@@ -60,7 +61,15 @@ export const CustomScrollbar = defineComponent({
|
||||
}
|
||||
|
||||
function onContentScroll() {
|
||||
syncThumb();
|
||||
if (isDragging || typeof requestAnimationFrame !== 'function') {
|
||||
syncThumb();
|
||||
return;
|
||||
}
|
||||
if (scrollRafId) return;
|
||||
scrollRafId = requestAnimationFrame(() => {
|
||||
scrollRafId = 0;
|
||||
syncThumb();
|
||||
});
|
||||
}
|
||||
|
||||
function onDocMouseMove(e) {
|
||||
@@ -115,7 +124,7 @@ export const CustomScrollbar = defineComponent({
|
||||
syncThumb();
|
||||
});
|
||||
|
||||
contentEl.addEventListener('scroll', onContentScroll);
|
||||
contentEl.addEventListener('scroll', onContentScroll, { passive: true });
|
||||
hostEl.addEventListener('mouseenter', syncThumb);
|
||||
|
||||
let resizeObserver = null;
|
||||
@@ -129,6 +138,10 @@ export const CustomScrollbar = defineComponent({
|
||||
|
||||
onCleanup(() => {
|
||||
onDocMouseUp();
|
||||
if (scrollRafId && typeof cancelAnimationFrame === 'function') {
|
||||
cancelAnimationFrame(scrollRafId);
|
||||
scrollRafId = 0;
|
||||
}
|
||||
contentEl.removeEventListener('scroll', onContentScroll);
|
||||
hostEl.removeEventListener('mouseenter', syncThumb);
|
||||
if (resizeObserver) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
positionAnchoredPopup,
|
||||
} from '../../core/domPatch.js';
|
||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
@@ -102,6 +103,37 @@ export const CustomSelect = defineComponent({
|
||||
return new Set(normalizeMultiSelection(modelValue, options, allValue));
|
||||
}
|
||||
|
||||
function positionMenu() {
|
||||
if (!isOpen) return;
|
||||
positionAnchoredPopup(rootEl, triggerBtn, menuEl, {
|
||||
margin: 6,
|
||||
gap: 4,
|
||||
maxHeight: 220,
|
||||
minFlipSpace: 140,
|
||||
});
|
||||
}
|
||||
|
||||
let boundReposition = false;
|
||||
function handleViewportChange(e) {
|
||||
if (!isOpen) return;
|
||||
if (e?.type === 'scroll' && e.target === menuEl) return;
|
||||
positionMenu();
|
||||
}
|
||||
|
||||
function setRepositionListeners(active) {
|
||||
if (active === boundReposition) return;
|
||||
boundReposition = active;
|
||||
if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
if (active) {
|
||||
window.addEventListener('resize', handleViewportChange, { passive: true });
|
||||
window.addEventListener('scroll', handleViewportChange, true);
|
||||
} else {
|
||||
window.removeEventListener('resize', handleViewportChange);
|
||||
window.removeEventListener('scroll', handleViewportChange, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toggleOpen(nextOpen) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
if (isOpen) {
|
||||
@@ -117,6 +149,10 @@ export const CustomSelect = defineComponent({
|
||||
patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false');
|
||||
patchAttr(menuEl, 'hidden', !isOpen);
|
||||
patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down');
|
||||
setRepositionListeners(isOpen);
|
||||
if (isOpen) {
|
||||
positionMenu();
|
||||
}
|
||||
}
|
||||
|
||||
function chooseOption(option) {
|
||||
@@ -307,6 +343,7 @@ export const CustomSelect = defineComponent({
|
||||
patchAttr(triggerBtn, 'title', titleText);
|
||||
if (isOpen) {
|
||||
renderMenuOptions();
|
||||
positionMenu();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,7 +355,12 @@ export const CustomSelect = defineComponent({
|
||||
|
||||
if (typeof document !== 'undefined' && document.addEventListener) {
|
||||
document.addEventListener('click', handleDocClick, true);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick, true));
|
||||
onCleanup(() => {
|
||||
setRepositionListeners(false);
|
||||
document.removeEventListener('click', handleDocClick, true);
|
||||
});
|
||||
} else {
|
||||
onCleanup(() => setRepositionListeners(false));
|
||||
}
|
||||
|
||||
syncTriggerAndMenu();
|
||||
|
||||
@@ -33,14 +33,30 @@ export function createFourSegmentBar() {
|
||||
]);
|
||||
|
||||
/**
|
||||
* 根据四类 Token 数量重新计算并写入各分段百分比宽度。
|
||||
* 根据四类 Token 数量与整体行宽占比系数 (`scaleRatio`,默认 `1` 占满 100%) 重新计算并写入各分段百分比宽度。
|
||||
*/
|
||||
function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) {
|
||||
const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens);
|
||||
patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`);
|
||||
function update({
|
||||
inputTokens = 0,
|
||||
cacheReadTokens = 0,
|
||||
responseTokens = 0,
|
||||
thinkingTokens = 0,
|
||||
scaleRatio = 1,
|
||||
}) {
|
||||
const sum = inputTokens + cacheReadTokens + responseTokens + thinkingTokens;
|
||||
const clampedRatio = Number.isFinite(Number(scaleRatio))
|
||||
? Math.min(1, Math.max(0, Number(scaleRatio)))
|
||||
: 1;
|
||||
if (sum <= 0 || clampedRatio <= 0) {
|
||||
patchStyleVar(segInput, '--seg-w', '0%');
|
||||
patchStyleVar(segCached, '--seg-w', '0%');
|
||||
patchStyleVar(segOutput, '--seg-w', '0%');
|
||||
patchStyleVar(segThinking, '--seg-w', '0%');
|
||||
return;
|
||||
}
|
||||
patchStyleVar(segInput, '--seg-w', `${((inputTokens / sum) * 100 * clampedRatio).toFixed(2)}%`);
|
||||
patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / sum) * 100 * clampedRatio).toFixed(2)}%`);
|
||||
patchStyleVar(segOutput, '--seg-w', `${((responseTokens / sum) * 100 * clampedRatio).toFixed(2)}%`);
|
||||
patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / sum) * 100 * clampedRatio).toFixed(2)}%`);
|
||||
}
|
||||
|
||||
return { el, update };
|
||||
|
||||
@@ -1,54 +1,215 @@
|
||||
/**
|
||||
* @fileoverview Micro-bezel (2px radius) SegmentedControl switcher
|
||||
* for time-range filtering, context limit selection, and sub-table switching.
|
||||
* @fileoverview Sliding SegmentedControl switcher with variable-width GPU glider.
|
||||
* Measures active button geometry via ResizeObserver so both inline variable-width
|
||||
* segments (e.g. "今天 / 1天 / ... / 自定义", "按步查看 (1520) / 总汇总") and equal-width
|
||||
* grid bars ("常规 / 结构 / 其他") glide smoothly without stretching from 0px on tab reveal.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
|
||||
export const SegmentedControl = defineComponent({
|
||||
name: 'SegmentedControl',
|
||||
setup({ getProps, setProps, emit }) {
|
||||
const rootEl = h('div', {
|
||||
className: 'segmented',
|
||||
role: 'group',
|
||||
'aria-label': getProps().ariaLabel || '分段切换器',
|
||||
});
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' });
|
||||
const rootEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'segmented',
|
||||
role: 'group',
|
||||
'aria-label': getProps().ariaLabel || '分段切换器',
|
||||
},
|
||||
[gliderEl]
|
||||
);
|
||||
|
||||
const btnMap = new Map();
|
||||
let orderedBtns = [];
|
||||
let activeBtnEl = null;
|
||||
let observedBtnEl = null;
|
||||
let hasMeasuredVisible = false;
|
||||
let readyRafId = 0;
|
||||
|
||||
function cancelReadyRaf() {
|
||||
if (readyRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') {
|
||||
window.cancelAnimationFrame(readyRafId);
|
||||
}
|
||||
readyRafId = 0;
|
||||
}
|
||||
|
||||
function syncGliderGeometry() {
|
||||
if (!activeBtnEl) {
|
||||
cancelReadyRaf();
|
||||
hasMeasuredVisible = false;
|
||||
patchClasses(rootEl, { 'has-glider': false });
|
||||
patchClasses(gliderEl, { 'is-ready': false });
|
||||
return;
|
||||
}
|
||||
|
||||
const w = Number(activeBtnEl.offsetWidth || 0);
|
||||
const h = Number(activeBtnEl.offsetHeight || 0);
|
||||
if (!(w > 0 && h > 0)) {
|
||||
// Hidden parent tab or headless Mock DOM: keep .seg-btn.is-active fallback background
|
||||
// and snap cleanly on first real paint when tab becomes visible.
|
||||
cancelReadyRaf();
|
||||
hasMeasuredVisible = false;
|
||||
patchClasses(rootEl, { 'has-glider': false });
|
||||
patchClasses(gliderEl, { 'is-ready': false });
|
||||
return;
|
||||
}
|
||||
|
||||
const x = Number(activeBtnEl.offsetLeft || 0);
|
||||
const y = Number(activeBtnEl.offsetTop || 0);
|
||||
patchStyleVar(gliderEl, '--glider-x', `${x}px`);
|
||||
patchStyleVar(gliderEl, '--glider-y', `${y}px`);
|
||||
patchStyleVar(gliderEl, '--glider-w', `${w}px`);
|
||||
patchStyleVar(gliderEl, '--glider-h', `${h}px`);
|
||||
patchClasses(rootEl, { 'has-glider': true });
|
||||
|
||||
if (!hasMeasuredVisible) {
|
||||
hasMeasuredVisible = true;
|
||||
patchClasses(gliderEl, { 'is-ready': false });
|
||||
void gliderEl.offsetWidth;
|
||||
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
|
||||
cancelReadyRaf();
|
||||
readyRafId = window.requestAnimationFrame(() => {
|
||||
readyRafId = 0;
|
||||
if (hasMeasuredVisible) {
|
||||
patchClasses(gliderEl, { 'is-ready': true });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
patchClasses(gliderEl, { 'is-ready': true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resizeObs = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
syncGliderGeometry();
|
||||
});
|
||||
resizeObs.observe(rootEl);
|
||||
}
|
||||
|
||||
function updateObservedActiveButton(nextActiveBtn) {
|
||||
if (!resizeObs || observedBtnEl === nextActiveBtn) return;
|
||||
if (observedBtnEl) {
|
||||
try {
|
||||
resizeObs.unobserve(observedBtnEl);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
observedBtnEl = nextActiveBtn || null;
|
||||
if (observedBtnEl) {
|
||||
try {
|
||||
resizeObs.observe(observedBtnEl);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function selectValue(nextVal) {
|
||||
if (getProps().modelValue !== nextVal) {
|
||||
setProps({ modelValue: nextVal });
|
||||
emit('update:modelValue', nextVal);
|
||||
}
|
||||
}
|
||||
|
||||
function syncSegments() {
|
||||
const { options = [], modelValue } = getProps();
|
||||
patchKeyedList(rootEl, options, {
|
||||
keyFn: (opt) => opt.value,
|
||||
sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`,
|
||||
createRow: (opt) => {
|
||||
const btn = h('button', {
|
||||
const { options = [], modelValue, ariaLabel } = getProps();
|
||||
if (ariaLabel) {
|
||||
patchAttr(rootEl, 'aria-label', ariaLabel);
|
||||
}
|
||||
|
||||
const validKeys = new Set(options.map((opt) => String(opt.value)));
|
||||
for (const [key, btn] of btnMap.entries()) {
|
||||
if (!validKeys.has(key)) {
|
||||
if (btn.parentNode === rootEl) {
|
||||
rootEl.removeChild(btn);
|
||||
}
|
||||
btnMap.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
orderedBtns = [];
|
||||
let nextActiveBtn = null;
|
||||
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const opt = options[i];
|
||||
const key = String(opt.value);
|
||||
let btn = btnMap.get(key);
|
||||
if (!btn) {
|
||||
btn = h('button', {
|
||||
type: 'button',
|
||||
className: 'seg-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (getProps().modelValue !== opt.value) {
|
||||
setProps({ modelValue: opt.value });
|
||||
emit('update:modelValue', opt.value);
|
||||
selectValue(opt.value);
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
const curOpts = getProps().options || [];
|
||||
if (!curOpts.length) return;
|
||||
const curIdx = Math.max(
|
||||
0,
|
||||
curOpts.findIndex((o) => String(o.value) === key)
|
||||
);
|
||||
const delta = e.key === 'ArrowRight' ? 1 : -1;
|
||||
const nextIdx = (curIdx + delta + curOpts.length) % curOpts.length;
|
||||
const targetOpt = curOpts[nextIdx];
|
||||
if (targetOpt) {
|
||||
selectValue(targetOpt.value);
|
||||
btnMap.get(String(targetOpt.value))?.focus?.();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return { el: btn, refs: {} };
|
||||
},
|
||||
updateRow: (_refs, opt, _idx, el) => {
|
||||
const active = opt.value === modelValue;
|
||||
patchText(el, opt.label);
|
||||
patchClasses(el, { 'is-active': active });
|
||||
patchAttr(el, 'aria-pressed', active ? 'true' : 'false');
|
||||
patchAttr(el, 'data-seg-value', opt.value);
|
||||
},
|
||||
});
|
||||
btnMap.set(key, btn);
|
||||
}
|
||||
|
||||
const active = opt.value === modelValue;
|
||||
patchText(btn, opt.label);
|
||||
patchClasses(btn, { 'is-active': active });
|
||||
patchAttr(btn, 'aria-pressed', active ? 'true' : 'false');
|
||||
patchAttr(btn, 'data-seg-value', opt.value);
|
||||
orderedBtns.push(btn);
|
||||
if (active) {
|
||||
nextActiveBtn = btn;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure gliderEl remains index 0 and buttons follow in exact option order
|
||||
if (rootEl.firstChild !== gliderEl) {
|
||||
rootEl.insertBefore(gliderEl, rootEl.firstChild);
|
||||
}
|
||||
for (let i = 0; i < orderedBtns.length; i++) {
|
||||
const targetNode = orderedBtns[i];
|
||||
const currentAtSlot = rootEl.children[i + 1] || null;
|
||||
if (currentAtSlot !== targetNode) {
|
||||
rootEl.insertBefore(targetNode, currentAtSlot);
|
||||
}
|
||||
}
|
||||
|
||||
activeBtnEl = nextActiveBtn || orderedBtns[0] || null;
|
||||
updateObservedActiveButton(activeBtnEl);
|
||||
syncGliderGeometry();
|
||||
}
|
||||
|
||||
syncSegments();
|
||||
|
||||
onCleanup(() => {
|
||||
cancelReadyRaf();
|
||||
resizeObs?.disconnect?.();
|
||||
resizeObs = null;
|
||||
observedBtnEl = null;
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {},
|
||||
refs: { gliderEl, refreshGlider: syncGliderGeometry },
|
||||
onPropsChange: syncSegments,
|
||||
getValue: () => getProps().modelValue,
|
||||
};
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* real-UI structure preview (`SettingsStructureTab.js`), ensuring 100% DOM/CSS parity.
|
||||
*/
|
||||
|
||||
import { isModernUiActiveForElement } from '../../core/appearance.js';
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, SVG_NS } from '../../icons/SvgIcon.js';
|
||||
import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js';
|
||||
@@ -19,6 +20,165 @@ import { buildFallbackRunningConversations } from './LiveActivityWidget.js';
|
||||
export const RING_RADIUS = 5.2;
|
||||
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
|
||||
|
||||
const ODOMETER_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||||
const capsuleOdometerState = new WeakMap();
|
||||
|
||||
/**
|
||||
* 将胶囊指标文本拆分为「按数位对齐的数字滚轮 + 静态字符片段」:
|
||||
* - 整数部分从右向左按位次键控(个位 `i:0`、十位 `i:1`...),小数部分从左向右键控(`f:0`...);
|
||||
* - 位数增减时既有数位节点原地复用,仅发生变化的数字位执行 0.15s 老虎机垂直滚动,未变位与单位纹丝不动。
|
||||
*
|
||||
* @param {string} rawText
|
||||
* @returns {Array<{ key: string, kind: 'digit' | 'static', digit?: number, text?: string }>}
|
||||
*/
|
||||
export function tokenizeCapsuleOdometerText(rawText) {
|
||||
const str = String(rawText ?? '');
|
||||
if (!str) return [];
|
||||
const parts = str.split(/(\d+(?:\.\d+)?)/g);
|
||||
const tokens = [];
|
||||
let numIdx = 0;
|
||||
let staticIdx = 0;
|
||||
|
||||
for (let p = 0; p < parts.length; p += 1) {
|
||||
const seg = parts[p];
|
||||
if (!seg) continue;
|
||||
if (/^\d+(?:\.\d+)?$/.test(seg)) {
|
||||
const dotPos = seg.indexOf('.');
|
||||
const intPart = dotPos >= 0 ? seg.slice(0, dotPos) : seg;
|
||||
const fracPart = dotPos >= 0 ? seg.slice(dotPos + 1) : '';
|
||||
const intLen = intPart.length;
|
||||
for (let i = 0; i < intLen; i += 1) {
|
||||
const place = intLen - 1 - i;
|
||||
tokens.push({
|
||||
key: `n:${numIdx}:i:${place}`,
|
||||
kind: 'digit',
|
||||
digit: Number(intPart[i]),
|
||||
});
|
||||
}
|
||||
if (dotPos >= 0) {
|
||||
tokens.push({ key: `n:${numIdx}:dot`, kind: 'static', text: '.' });
|
||||
for (let j = 0; j < fracPart.length; j += 1) {
|
||||
tokens.push({
|
||||
key: `n:${numIdx}:f:${j}`,
|
||||
kind: 'digit',
|
||||
digit: Number(fracPart[j]),
|
||||
});
|
||||
}
|
||||
}
|
||||
numIdx += 1;
|
||||
} else {
|
||||
tokens.push({ key: `s:${staticIdx}`, kind: 'static', text: seg });
|
||||
staticIdx += 1;
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function createOdometerDigitReel(initialDigit) {
|
||||
const cells = ODOMETER_DIGITS.map((d) => h('span', { className: 'wm-od-cell', text: d }));
|
||||
const trackEl = h('span', { className: 'wm-od-track' }, cells);
|
||||
patchStyleVar(trackEl, '--od-val', String(initialDigit));
|
||||
const digitEl = h('span', { className: 'wm-od-digit', 'aria-hidden': 'true' }, [trackEl]);
|
||||
return { el: digitEl, trackEl, kind: 'digit', digit: initialDigit };
|
||||
}
|
||||
|
||||
/**
|
||||
* 在实验性新 UI (`[data-modern-ui="true"]`) 下将胶囊数字渲染为 0.15s 老虎机垂直滚轮;
|
||||
* 经典 UI 或无数字占位文本(如 `-- t/s`)严格退回原生纯文本 `patchText`,零多余 DOM 与动画。
|
||||
*/
|
||||
export function patchCapsuleOdometerText(
|
||||
el,
|
||||
nextValue,
|
||||
{ resetKey = '', modernUi = undefined } = {}
|
||||
) {
|
||||
if (!el) return false;
|
||||
const nextStr = String(nextValue ?? '');
|
||||
const isModern = typeof modernUi === 'boolean' ? modernUi : isModernUiActiveForElement(el);
|
||||
const prev = capsuleOdometerState.get(el);
|
||||
|
||||
if (!isModern || !/\d/.test(nextStr)) {
|
||||
if (prev?.active) {
|
||||
while (el.firstChild) el.removeChild(el.firstChild);
|
||||
patchAttr(el, 'data-od-active', null);
|
||||
patchAttr(el, 'data-od-value', null);
|
||||
patchAttr(el, 'aria-label', null);
|
||||
}
|
||||
const changed = patchText(el, nextStr);
|
||||
capsuleOdometerState.set(el, { active: false, text: nextStr, resetKey, nodes: null });
|
||||
return changed;
|
||||
}
|
||||
|
||||
if (prev?.active && prev.text === nextStr && prev.resetKey === resetKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let nodes;
|
||||
if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) {
|
||||
while (el.firstChild) el.removeChild(el.firstChild);
|
||||
nodes = new Map();
|
||||
} else {
|
||||
nodes = prev.nodes;
|
||||
}
|
||||
|
||||
const tokens = tokenizeCapsuleOdometerText(nextStr);
|
||||
const nextKeys = new Set();
|
||||
const orderedEls = [];
|
||||
|
||||
for (let i = 0; i < tokens.length; i += 1) {
|
||||
const tok = tokens[i];
|
||||
nextKeys.add(tok.key);
|
||||
let rec = nodes.get(tok.key);
|
||||
if (!rec || rec.kind !== tok.kind) {
|
||||
if (rec?.el?.parentNode === el) {
|
||||
el.removeChild(rec.el);
|
||||
}
|
||||
if (tok.kind === 'digit') {
|
||||
rec = createOdometerDigitReel(tok.digit);
|
||||
} else {
|
||||
rec = {
|
||||
el: h('span', { className: 'wm-od-static', 'aria-hidden': 'true', text: tok.text }),
|
||||
trackEl: null,
|
||||
kind: 'static',
|
||||
text: tok.text,
|
||||
};
|
||||
}
|
||||
nodes.set(tok.key, rec);
|
||||
} else if (tok.kind === 'digit') {
|
||||
if (rec.digit !== tok.digit) {
|
||||
patchStyleVar(rec.trackEl, '--od-val', String(tok.digit));
|
||||
rec.digit = tok.digit;
|
||||
}
|
||||
} else if (rec.text !== tok.text) {
|
||||
patchText(rec.el, tok.text);
|
||||
rec.text = tok.text;
|
||||
}
|
||||
orderedEls.push(rec.el);
|
||||
}
|
||||
|
||||
for (const [oldKey, rec] of nodes.entries()) {
|
||||
if (!nextKeys.has(oldKey)) {
|
||||
if (rec.el?.parentNode === el) {
|
||||
el.removeChild(rec.el);
|
||||
}
|
||||
nodes.delete(oldKey);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < orderedEls.length; i += 1) {
|
||||
const targetNode = orderedEls[i];
|
||||
const currentNode = el.children[i] || null;
|
||||
if (currentNode !== targetNode) {
|
||||
el.insertBefore(targetNode, currentNode);
|
||||
}
|
||||
}
|
||||
|
||||
patchAttr(el, 'data-od-active', '1');
|
||||
patchAttr(el, 'data-od-value', nextStr);
|
||||
patchAttr(el, 'aria-label', nextStr);
|
||||
capsuleOdometerState.set(el, { active: true, text: nextStr, resetKey, nodes });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation.
|
||||
*/
|
||||
@@ -94,14 +254,29 @@ export function resolveMultiSessionCapsuleState(
|
||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
||||
0
|
||||
);
|
||||
const runningSwarmCount = rawRunningList.reduce(
|
||||
(acc, item) => acc + Number(item.runningSwarmCount || 0),
|
||||
0
|
||||
);
|
||||
const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
||||
const multiBtnText =
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', {
|
||||
count: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('capsule.multiRunning', { count: runningCount })
|
||||
: t('capsule.multiZero');
|
||||
return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText };
|
||||
return {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +384,7 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt
|
||||
patchAttr(slot.el, 'class', fullSegClass);
|
||||
const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`;
|
||||
patchAttr(slot.textSpan, 'class', fullTextClass);
|
||||
patchText(slot.textSpan, pres.text);
|
||||
patchCapsuleOdometerText(slot.textSpan, pres.text, { resetKey: pres.metric });
|
||||
|
||||
if (pres.showRing) {
|
||||
slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset));
|
||||
@@ -355,7 +530,7 @@ export const CapsuleBarWidget = defineComponent({
|
||||
|
||||
if (!data) {
|
||||
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
|
||||
patchText(multiLabel, t('capsule.multiZero'));
|
||||
patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' });
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false });
|
||||
return;
|
||||
}
|
||||
@@ -376,7 +551,7 @@ export const CapsuleBarWidget = defineComponent({
|
||||
'is-running': runningCount > 0 && !hasWaiting,
|
||||
'is-waiting': runningCount > 0 && hasWaiting,
|
||||
});
|
||||
patchText(multiLabel, multiBtnText);
|
||||
patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' });
|
||||
|
||||
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { isModernUiActiveForElement } from '../../core/appearance.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
@@ -30,8 +31,8 @@ const CTX_ASCII_CHAR_PX = 6.1;
|
||||
const CTX_PILL_GAP_PX = 4;
|
||||
const CTX_DEFAULT_BAR_WIDTH_PX = 310;
|
||||
|
||||
function estimateCtxPillWidth(text) {
|
||||
let w = CTX_PILL_BASE_PAD_PX;
|
||||
function estimateCtxPillWidth(text, withChevron = false) {
|
||||
let w = CTX_PILL_BASE_PAD_PX + (withChevron ? 14 : 0);
|
||||
for (const ch of String(text || '')) {
|
||||
w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX;
|
||||
}
|
||||
@@ -244,9 +245,30 @@ export const ContextWindowWidget = defineComponent({
|
||||
|
||||
let latestData = null;
|
||||
let ctxPillsExpanded = false;
|
||||
let isCollapsingCtxPills = false;
|
||||
let ctxCollapseTimer = null;
|
||||
let lastCascadeId = '';
|
||||
let cachedBarWidth = 0;
|
||||
|
||||
function clearCtxExpandAnim() {
|
||||
if (ctxCollapseTimer) {
|
||||
clearTimeout(ctxCollapseTimer);
|
||||
ctxCollapseTimer = null;
|
||||
}
|
||||
isCollapsingCtxPills = false;
|
||||
ctxInspectorBar.ontransitionend = null;
|
||||
ctxInspectorBar.style.height = '';
|
||||
ctxInspectorBar.style.overflow = '';
|
||||
ctxInspectorBar.style.transition = '';
|
||||
for (const child of ctxPillGroup.children) {
|
||||
child.onanimationend = null;
|
||||
patchClasses(child, {
|
||||
'is-pill-entering': false,
|
||||
'is-pill-collapsing': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function update({ data } = {}) {
|
||||
latestData = data || null;
|
||||
const curLocale = getEffectiveLocale();
|
||||
@@ -277,6 +299,7 @@ export const ContextWindowWidget = defineComponent({
|
||||
const currentCascadeId = data.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && currentCascadeId !== lastCascadeId) {
|
||||
if (lastCascadeId) {
|
||||
clearCtxExpandAnim();
|
||||
ctxPillsExpanded = false;
|
||||
}
|
||||
lastCascadeId = currentCascadeId;
|
||||
@@ -308,7 +331,10 @@ export const ContextWindowWidget = defineComponent({
|
||||
|
||||
if (interactiveInspector) {
|
||||
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
||||
if (hasSubagents && ctxAgent) {
|
||||
if (!hasSubagents && isCollapsingCtxPills) {
|
||||
clearCtxExpandAnim();
|
||||
}
|
||||
if (hasSubagents && ctxAgent && !isCollapsingCtxPills) {
|
||||
const activeBadgeText = formatAgentBadgeText({
|
||||
agentKind:
|
||||
aggregated?.activeAgentKind ||
|
||||
@@ -355,7 +381,7 @@ export const ContextWindowWidget = defineComponent({
|
||||
|
||||
if (needsCollapse && !ctxPillsExpanded) {
|
||||
const toggleSample = t('ctx.expandMore', { count: allAgentPills.length });
|
||||
const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample);
|
||||
const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true);
|
||||
let usedW = firstPillWidth;
|
||||
let fitCount = 0;
|
||||
for (let i = 0; i < allAgentPills.length; i += 1) {
|
||||
@@ -386,6 +412,7 @@ export const ContextWindowWidget = defineComponent({
|
||||
title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
isExpanded: false,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
} else {
|
||||
@@ -397,6 +424,7 @@ export const ContextWindowWidget = defineComponent({
|
||||
title: t('ctx.collapseTitle'),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
isExpanded: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
}
|
||||
@@ -405,22 +433,117 @@ export const ContextWindowWidget = defineComponent({
|
||||
patchKeyedList(ctxPillGroup, pillItems, {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: (item) =>
|
||||
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`,
|
||||
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`,
|
||||
createRow: () => {
|
||||
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' });
|
||||
return { el: btn, refs: { btn } };
|
||||
const labelSpan = h('span', { className: 'ctx-pill-label' });
|
||||
const chevronEl = createSvgIcon('chevron-down', {
|
||||
size: 11,
|
||||
className: 'ctx-toggle-chevron',
|
||||
});
|
||||
patchAttr(chevronEl, 'hidden', true);
|
||||
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }, [
|
||||
labelSpan,
|
||||
chevronEl,
|
||||
]);
|
||||
return { el: btn, refs: { btn, labelSpan, chevronEl } };
|
||||
},
|
||||
updateRow: (refs, item) => {
|
||||
patchText(refs.btn, item.label);
|
||||
patchText(refs.labelSpan, item.label);
|
||||
patchAttr(refs.chevronEl, 'hidden', !item.isMoreToggle);
|
||||
patchAttr(refs.btn, 'title', item.title);
|
||||
patchAttr(refs.btn, 'data-pill-key', item.key);
|
||||
patchClasses(refs.btn, {
|
||||
'is-active': item.isActive,
|
||||
'is-more-toggle': Boolean(item.isMoreToggle),
|
||||
'is-expanded': Boolean(item.isExpanded),
|
||||
'is-pill-collapsing': false,
|
||||
});
|
||||
refs.btn.onclick = () => {
|
||||
if (item.mode === 'toggle-expand') {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
if (latestData) update({ data: latestData });
|
||||
const modern = isModernUiActiveForElement(ctxPanel);
|
||||
const startH = Number(ctxInspectorBar.offsetHeight || 0);
|
||||
clearCtxExpandAnim();
|
||||
if (!modern || !(startH > 0)) {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
if (latestData) update({ data: latestData });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ctxPillsExpanded) {
|
||||
const prevKeys = new Set(
|
||||
Array.from(ctxPillGroup.children, (el) => el.getAttribute?.('data-pill-key') || '')
|
||||
);
|
||||
ctxPillsExpanded = true;
|
||||
if (latestData) update({ data: latestData });
|
||||
const endH = Number(ctxPillGroup.offsetHeight || 0);
|
||||
for (const child of ctxPillGroup.children) {
|
||||
const k = child.getAttribute?.('data-pill-key') || '';
|
||||
if (k && k !== '__toggle_more__' && !prevKeys.has(k)) {
|
||||
patchClasses(child, { 'is-pill-entering': true });
|
||||
child.onanimationend = () => {
|
||||
child.onanimationend = null;
|
||||
patchClasses(child, { 'is-pill-entering': false });
|
||||
};
|
||||
}
|
||||
}
|
||||
if (endH > startH + 1) {
|
||||
ctxInspectorBar.style.height = `${startH}px`;
|
||||
ctxInspectorBar.style.overflow = 'hidden';
|
||||
void ctxInspectorBar.offsetHeight;
|
||||
ctxInspectorBar.style.transition =
|
||||
'height 220ms cubic-bezier(0.16, 1, 0.3, 1)';
|
||||
ctxInspectorBar.style.height = `${endH}px`;
|
||||
const finishExpand = () => clearCtxExpandAnim();
|
||||
ctxInspectorBar.ontransitionend = (ev) => {
|
||||
if (
|
||||
ev?.target === ctxInspectorBar &&
|
||||
(!ev.propertyName || ev.propertyName === 'height')
|
||||
) {
|
||||
finishExpand();
|
||||
}
|
||||
};
|
||||
ctxCollapseTimer = setTimeout(finishExpand, 260);
|
||||
}
|
||||
} else {
|
||||
const firstPill = ctxPillGroup.children[0] || null;
|
||||
const firstTop = Number(firstPill?.offsetTop || 0);
|
||||
let firstRowH = Number(firstPill?.offsetHeight || 20);
|
||||
for (const child of ctxPillGroup.children) {
|
||||
const top = Number(child.offsetTop || 0);
|
||||
if (top <= firstTop + 4) {
|
||||
const bottom = top - firstTop + Number(child.offsetHeight || 0);
|
||||
if (bottom > firstRowH) firstRowH = bottom;
|
||||
}
|
||||
}
|
||||
const targetH = Math.max(18, firstRowH);
|
||||
ctxPillsExpanded = false;
|
||||
isCollapsingCtxPills = true;
|
||||
patchClasses(refs.btn, { 'is-expanded': false });
|
||||
for (const child of ctxPillGroup.children) {
|
||||
if (Number(child.offsetTop || 0) > firstTop + 4) {
|
||||
patchClasses(child, { 'is-pill-collapsing': true });
|
||||
}
|
||||
}
|
||||
ctxInspectorBar.style.height = `${startH}px`;
|
||||
ctxInspectorBar.style.overflow = 'hidden';
|
||||
void ctxInspectorBar.offsetHeight;
|
||||
ctxInspectorBar.style.transition =
|
||||
'height 200ms cubic-bezier(0.16, 1, 0.3, 1)';
|
||||
ctxInspectorBar.style.height = `${targetH}px`;
|
||||
const finishCollapse = () => {
|
||||
clearCtxExpandAnim();
|
||||
if (latestData) update({ data: latestData });
|
||||
};
|
||||
ctxInspectorBar.ontransitionend = (ev) => {
|
||||
if (
|
||||
ev?.target === ctxInspectorBar &&
|
||||
(!ev.propertyName || ev.propertyName === 'height')
|
||||
) {
|
||||
finishCollapse();
|
||||
}
|
||||
};
|
||||
ctxCollapseTimer = setTimeout(finishCollapse, 240);
|
||||
}
|
||||
} else {
|
||||
setCtxAgentId(item.key);
|
||||
}
|
||||
@@ -499,6 +622,7 @@ export const ContextWindowWidget = defineComponent({
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
clearCtxExpandAnim();
|
||||
if (ro) ro.disconnect();
|
||||
ctxSegmentBar.destroy();
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { isModernUiActiveForElement } from '../../core/appearance.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
@@ -24,11 +25,12 @@ import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
extractHostRouteCascadeId,
|
||||
fetchTelemetry,
|
||||
resolveScopedConversation,
|
||||
selectConversation,
|
||||
telemetryStore,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
import { CustomScrollbar } from '../ui/CustomScrollbar.js';
|
||||
|
||||
export function buildFallbackRunningConversations(
|
||||
data,
|
||||
@@ -40,43 +42,68 @@ export function buildFallbackRunningConversations(
|
||||
}
|
||||
const activeConv = data.activeConversation || {};
|
||||
if (!activeConv.isRunning && !aggregated?.isRunning) return [];
|
||||
const childAgents = (agents || []).filter((a) => !a.isMain);
|
||||
const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker');
|
||||
return [
|
||||
{
|
||||
cascadeId: activeConv.cascadeId || 'current',
|
||||
title: activeConv.title || t('live.currentSession'),
|
||||
...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}),
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: Boolean(activeConv.isRunning),
|
||||
isRunning: true,
|
||||
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
|
||||
subagentCount: Math.max(0, (agents?.length || 1) - 1),
|
||||
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
|
||||
subagentCount: childAgents.length,
|
||||
swarmCount: swarmChildren.length,
|
||||
runningSubagentCount: childAgents.filter((a) => a.isRunning).length,
|
||||
runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length,
|
||||
...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}),
|
||||
...(contextUsedPct !== undefined ? { contextUsedPct } : {}),
|
||||
subagents: (agents || [])
|
||||
.filter((a) => !a.isMain)
|
||||
.map((s, idx) => ({
|
||||
subagents: childAgents.map((s, idx) => {
|
||||
const isSwarmW = s.agentKind === 'swarm_worker';
|
||||
const isKilled = Boolean(s.swarmState === 'killed');
|
||||
return {
|
||||
cascadeId: s.cascadeId || s.agentId,
|
||||
index: s.index || idx + 1,
|
||||
agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'),
|
||||
agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
agentOrdinal:
|
||||
s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
customRole: s.customRole,
|
||||
...(s.swarmState ? { swarmState: s.swarmState } : {}),
|
||||
...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}),
|
||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
shortLabel:
|
||||
s.shortLabel ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
role:
|
||||
s.role ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
isRunning: Boolean(s.isRunning),
|
||||
stepCount: Number(s.stepCount || 0),
|
||||
lastModifiedMs: s.lastModifiedMs || 0,
|
||||
liveActivity: s.liveActivity || {
|
||||
phase: s.isRunning ? 'thinking' : 'done',
|
||||
actionKey: s.isRunning ? 'thinking' : 'done',
|
||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||
phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done',
|
||||
actionKey: s.isRunning
|
||||
? 'thinking'
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? 'swarm_killed'
|
||||
: 'swarm_waiting'
|
||||
: 'done',
|
||||
label: s.isRunning
|
||||
? t('live.thinking')
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? t('live.killed')
|
||||
: t('live.waiting')
|
||||
: t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: s.lastModifiedMs || 0,
|
||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||
signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -172,6 +199,38 @@ export const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
function readComputedPx(el, prop, fallback) {
|
||||
if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
const val = parseFloat(window.getComputedStyle(el)?.[prop]);
|
||||
return Number.isFinite(val) ? val : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function clearSubExpandAnim(refs) {
|
||||
if (!refs) return;
|
||||
if (refs.subAnimTimer) {
|
||||
clearTimeout(refs.subAnimTimer);
|
||||
refs.subAnimTimer = null;
|
||||
}
|
||||
refs.isCollapsingSubs = false;
|
||||
const host = refs.subScroll?.el;
|
||||
if (host) {
|
||||
host.ontransitionend = null;
|
||||
patchClasses(host, { 'is-sub-animating': false });
|
||||
host.style.height = '';
|
||||
host.style.paddingTop = '';
|
||||
host.style.marginTop = '';
|
||||
host.style.opacity = '';
|
||||
host.style.overflow = '';
|
||||
host.style.transition = '';
|
||||
}
|
||||
}
|
||||
|
||||
function createLiveTaskCard() {
|
||||
const dotIcon = createSvgIcon('dot', { size: 11 });
|
||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
||||
@@ -194,12 +253,23 @@ export const LiveActivityWidget = defineComponent({
|
||||
text: '',
|
||||
})
|
||||
: null;
|
||||
const subToggleBtn = h('button', {
|
||||
type: 'button',
|
||||
className: 'live-sub-toggle',
|
||||
hidden: true,
|
||||
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
|
||||
const subToggleLabel = h('span', {
|
||||
className: 'live-sub-toggle-label',
|
||||
text: t('live.subToggleIdle', { total: 0 }),
|
||||
});
|
||||
const subToggleChevron = createSvgIcon('chevron-down', {
|
||||
size: 11,
|
||||
className: 'live-sub-toggle-chevron',
|
||||
});
|
||||
const subToggleBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'live-sub-toggle',
|
||||
hidden: true,
|
||||
},
|
||||
[subToggleLabel, subToggleChevron]
|
||||
);
|
||||
const elapsedEl = h('span', {
|
||||
className: 'live-activity-elapsed text-mono',
|
||||
text: '0s',
|
||||
@@ -248,7 +318,16 @@ export const LiveActivityWidget = defineComponent({
|
||||
]);
|
||||
|
||||
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
||||
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
||||
const subScroll = CustomScrollbar({
|
||||
contentEl: subListEl,
|
||||
className: 'live-sub-scroll-host',
|
||||
});
|
||||
patchAttr(subScroll.el, 'hidden', true);
|
||||
const cardEl = h('div', { className: 'live-task-card' }, [
|
||||
headerEl,
|
||||
mainRowEl,
|
||||
subScroll.el,
|
||||
]);
|
||||
|
||||
return {
|
||||
el: cardEl,
|
||||
@@ -259,6 +338,8 @@ export const LiveActivityWidget = defineComponent({
|
||||
hereTagEl,
|
||||
metricsEl,
|
||||
subToggleBtn,
|
||||
subToggleLabel,
|
||||
subToggleChevron,
|
||||
elapsedEl,
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
@@ -266,6 +347,9 @@ export const LiveActivityWidget = defineComponent({
|
||||
mainSep,
|
||||
mainDetail,
|
||||
subListEl,
|
||||
subScroll,
|
||||
subAnimTimer: null,
|
||||
isCollapsingSubs: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -327,7 +411,12 @@ export const LiveActivityWidget = defineComponent({
|
||||
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
|
||||
if (!hasRunningTasks) {
|
||||
stopLiveTicker();
|
||||
patchKeyedList(liveActivityBar, [], {});
|
||||
patchKeyedList(liveActivityBar, [], {
|
||||
destroyRow: (refs) => {
|
||||
clearSubExpandAnim(refs);
|
||||
refs?.subScroll?.destroy?.();
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -362,14 +451,17 @@ export const LiveActivityWidget = defineComponent({
|
||||
const isHere =
|
||||
showSessionExtras &&
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
`${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
@@ -407,8 +499,7 @@ export const LiveActivityWidget = defineComponent({
|
||||
onSelectSession(item.cascadeId);
|
||||
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(item.cascadeId);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -416,7 +507,10 @@ export const LiveActivityWidget = defineComponent({
|
||||
if (showSessionExtras && refs.hereTagEl && refs.metricsEl) {
|
||||
const isHere =
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
patchText(refs.hereTagEl, t('multi.hereTag'));
|
||||
patchAttr(refs.hereTagEl, 'hidden', !isHere);
|
||||
|
||||
@@ -437,18 +531,27 @@ export const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const swarmCount = Number(
|
||||
item.swarmCount ??
|
||||
(item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length
|
||||
);
|
||||
const isPureSwarm = subCount > 0 && swarmCount === subCount;
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = resolveIsExpanded(item);
|
||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||
if (subCount > 0) {
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
const toggleText =
|
||||
runSubCount > 0
|
||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
||||
patchText(refs.subToggleBtn, toggleText);
|
||||
? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', {
|
||||
run: runSubCount,
|
||||
total: subCount,
|
||||
})
|
||||
: t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', {
|
||||
total: subCount,
|
||||
});
|
||||
patchText(refs.subToggleLabel, toggleText);
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
||||
if (interactive) {
|
||||
patchAttr(
|
||||
@@ -458,11 +561,108 @@ export const LiveActivityWidget = defineComponent({
|
||||
);
|
||||
refs.subToggleBtn.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
manualSubExpandMap.set(item.cascadeId, !isExpanded);
|
||||
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||
onLayoutChange?.();
|
||||
const nextExpanded = !resolveIsExpanded(item);
|
||||
const host = refs.subScroll.el;
|
||||
const curH = Number(host.offsetHeight || 0);
|
||||
const curPadTop = readComputedPx(host, 'paddingTop', 6);
|
||||
const curMarginTop = readComputedPx(host, 'marginTop', 3);
|
||||
const curOpacity = readComputedPx(host, 'opacity', 1);
|
||||
const parentGap = readComputedPx(refs.cardEl, 'rowGap', 7);
|
||||
const collapsedMarginTop = -Math.max(0, Math.round(parentGap));
|
||||
const wasMidAnim = Boolean(refs.subAnimTimer);
|
||||
clearSubExpandAnim(refs);
|
||||
manualSubExpandMap.set(item.cascadeId, nextExpanded);
|
||||
|
||||
const modern = isModernUiActiveForElement(refs.cardEl);
|
||||
if (!modern) {
|
||||
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||
onLayoutChange?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextExpanded) {
|
||||
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||
const endH = Number(host.offsetHeight || host.scrollHeight || 0);
|
||||
const endPadTop = readComputedPx(host, 'paddingTop', 6);
|
||||
const endMarginTop = readComputedPx(host, 'marginTop', 3);
|
||||
const fromH = wasMidAnim && curH > 0 ? curH : 0;
|
||||
const fromPadTop = wasMidAnim && curH > 0 ? curPadTop : 0;
|
||||
const fromMarginTop = wasMidAnim && curH > 0 ? curMarginTop : collapsedMarginTop;
|
||||
const fromOpacity = wasMidAnim && curH > 0 ? curOpacity : 0;
|
||||
if (endH > 0) {
|
||||
patchClasses(host, { 'is-sub-animating': true });
|
||||
host.style.height = `${fromH}px`;
|
||||
host.style.paddingTop = `${fromPadTop}px`;
|
||||
host.style.marginTop = `${fromMarginTop}px`;
|
||||
host.style.opacity = `${fromOpacity}`;
|
||||
host.style.overflow = 'hidden';
|
||||
void host.offsetHeight;
|
||||
host.style.transition =
|
||||
'height 220ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 220ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 220ms cubic-bezier(0.16, 1, 0.3, 1), opacity 180ms ease-out';
|
||||
host.style.height = `${endH}px`;
|
||||
host.style.paddingTop = `${endPadTop}px`;
|
||||
host.style.marginTop = `${endMarginTop}px`;
|
||||
host.style.opacity = '1';
|
||||
const finishExpand = () => {
|
||||
clearSubExpandAnim(refs);
|
||||
refs.subScroll.refresh();
|
||||
onLayoutChange?.();
|
||||
};
|
||||
host.ontransitionend = (ev) => {
|
||||
if (
|
||||
ev?.target === host &&
|
||||
(!ev.propertyName || ev.propertyName === 'height')
|
||||
) {
|
||||
finishExpand();
|
||||
}
|
||||
};
|
||||
refs.subAnimTimer = setTimeout(finishExpand, 260);
|
||||
} else {
|
||||
onLayoutChange?.();
|
||||
}
|
||||
} else {
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': false });
|
||||
patchAttr(refs.subToggleBtn, 'title', t('live.subExpandTitle'));
|
||||
if (curH > 0) {
|
||||
refs.isCollapsingSubs = true;
|
||||
patchClasses(host, { 'is-sub-animating': true });
|
||||
host.style.height = `${curH}px`;
|
||||
host.style.paddingTop = `${curPadTop}px`;
|
||||
host.style.marginTop = `${curMarginTop}px`;
|
||||
host.style.opacity = `${curOpacity}`;
|
||||
host.style.overflow = 'hidden';
|
||||
void host.offsetHeight;
|
||||
host.style.transition =
|
||||
'height 200ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 200ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 150ms ease-out';
|
||||
host.style.height = '0px';
|
||||
host.style.paddingTop = '0px';
|
||||
host.style.marginTop = `${collapsedMarginTop}px`;
|
||||
host.style.opacity = '0';
|
||||
const finishCollapse = () => {
|
||||
clearSubExpandAnim(refs);
|
||||
patchAttr(host, 'hidden', true);
|
||||
patchAttr(refs.subListEl, 'hidden', true);
|
||||
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||
onLayoutChange?.();
|
||||
};
|
||||
host.ontransitionend = (ev) => {
|
||||
if (
|
||||
ev?.target === host &&
|
||||
(!ev.propertyName || ev.propertyName === 'height')
|
||||
) {
|
||||
finishCollapse();
|
||||
}
|
||||
};
|
||||
refs.subAnimTimer = setTimeout(finishCollapse, 240);
|
||||
} else {
|
||||
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||
onLayoutChange?.();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
} else if (refs.isCollapsingSubs) {
|
||||
clearSubExpandAnim(refs);
|
||||
}
|
||||
|
||||
const mainLabel = formatLiveActivityLabel(act, 'live.thinking');
|
||||
@@ -493,13 +693,33 @@ export const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
|
||||
const showSubs = subCount > 0 && isExpanded;
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
if (!refs.isCollapsingSubs) {
|
||||
patchAttr(refs.subScroll.el, 'hidden', !showSubs);
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
}
|
||||
if (showSubs) {
|
||||
const subItems = item.subagents || [];
|
||||
const rawSubItems = item.subagents || [];
|
||||
const getSubSortRank = (s) => {
|
||||
if (s?.isRunning) return 0;
|
||||
if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
};
|
||||
const subItems =
|
||||
rawSubItems.length > 1
|
||||
? rawSubItems
|
||||
.slice()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
getSubSortRank(a) - getSubSortRank(b) ||
|
||||
Number(a?.index || 0) - Number(b?.index || 0)
|
||||
)
|
||||
: rawSubItems;
|
||||
patchKeyedList(refs.subListEl, subItems, {
|
||||
keyFn: (sub) => sub.cascadeId,
|
||||
sigFn: (sub) =>
|
||||
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
`${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
createRow: createLiveSubRow,
|
||||
updateRow: (subRefs, sub) => {
|
||||
const subAct = sub.liveActivity || {
|
||||
@@ -510,7 +730,17 @@ export const LiveActivityWidget = defineComponent({
|
||||
stepProgress: '',
|
||||
startedAtMs: sub.lastModifiedMs || 0,
|
||||
};
|
||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
||||
const isWaitingSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting');
|
||||
const isKilledSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed');
|
||||
patchClasses(subRefs.rowEl, {
|
||||
'is-done': !sub.isRunning && !isWaitingSub,
|
||||
'is-waiting-sub': isWaitingSub,
|
||||
'is-killed-sub': isKilledSub,
|
||||
});
|
||||
|
||||
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
|
||||
const subBadgeText = formatAgentBadgeText({
|
||||
@@ -524,22 +754,33 @@ export const LiveActivityWidget = defineComponent({
|
||||
const fallbackRole =
|
||||
sub.agentKind === 'side_question' || sub.isSideQuestion
|
||||
? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
: sub.agentKind === 'swarm_worker'
|
||||
? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
const roleText =
|
||||
sub.customRole !== undefined
|
||||
? sub.customRole || fallbackRole
|
||||
: sub.role || sub.shortLabel || fallbackRole;
|
||||
patchText(subRefs.subRole, roleText);
|
||||
|
||||
const idleFallbackKey = isKilledSub
|
||||
? 'live.killed'
|
||||
: isWaitingSub
|
||||
? 'live.waiting'
|
||||
: 'live.done';
|
||||
const subLabel = sub.isRunning
|
||||
? formatLiveActivityLabel(subAct, 'live.running')
|
||||
: formatLiveActivityLabel(subAct, 'live.done');
|
||||
: formatLiveActivityLabel(subAct, idleFallbackKey);
|
||||
const subDetail = formatLiveActivityDetail(subAct);
|
||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||
const summaryStr = showSessionExtras
|
||||
? sub.isRunning
|
||||
? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}`
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isKilledSub
|
||||
? t('live.killedWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isWaitingSub
|
||||
? t('live.waitingWithSteps', { steps: sub.stepCount || 0 })
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' ');
|
||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||
patchText(subRefs.subSummary, summaryStr);
|
||||
@@ -570,8 +811,13 @@ export const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
},
|
||||
});
|
||||
refs.subScroll.refresh();
|
||||
}
|
||||
},
|
||||
destroyRow: (refs) => {
|
||||
clearSubExpandAnim(refs);
|
||||
refs?.subScroll?.destroy?.();
|
||||
},
|
||||
});
|
||||
|
||||
for (const key of [...activityTimersMap.keys()]) {
|
||||
@@ -585,6 +831,12 @@ export const LiveActivityWidget = defineComponent({
|
||||
|
||||
onCleanup(() => {
|
||||
stopLiveTicker();
|
||||
patchKeyedList(liveActivityBar, [], {
|
||||
destroyRow: (refs) => {
|
||||
clearSubExpandAnim(refs);
|
||||
refs?.subScroll?.destroy?.();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -38,23 +38,342 @@ export function normalizeClientFontScale(raw) {
|
||||
return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md';
|
||||
}
|
||||
|
||||
export function normalizeClientModernUi(raw) {
|
||||
if (typeof raw === 'string') {
|
||||
const lower = raw.trim().toLowerCase();
|
||||
return lower === 'true' || lower === '1' || lower === 'on';
|
||||
}
|
||||
return Boolean(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`.
|
||||
*
|
||||
* @param {Node | null | undefined} el
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isModernUiActiveForElement(el) {
|
||||
let cur = el || null;
|
||||
while (cur) {
|
||||
if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') {
|
||||
return true;
|
||||
}
|
||||
if (cur.parentNode) {
|
||||
cur = cur.parentNode;
|
||||
} else if (cur.host) {
|
||||
cur = cur.host;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (typeof document !== 'undefined' && document.documentElement) {
|
||||
return document.documentElement.getAttribute?.('data-modern-ui') === 'true';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const LIGHT_THEME_CLASSES = new Set([
|
||||
'light',
|
||||
'vs-light',
|
||||
'vscode-light',
|
||||
'hc-light',
|
||||
'vscode-high-contrast-light',
|
||||
]);
|
||||
|
||||
const DARK_THEME_CLASSES = new Set([
|
||||
'dark',
|
||||
'vs-dark',
|
||||
'vscode-dark',
|
||||
'hc-black',
|
||||
'vscode-high-contrast',
|
||||
]);
|
||||
|
||||
function hslToRgb(hDeg, sPct, lPct) {
|
||||
const h = (((hDeg % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, sPct / 100));
|
||||
const l = Math.max(0, Math.min(1, lPct / 100));
|
||||
if (s === 0) {
|
||||
const v = l * 255;
|
||||
return [v, v, v];
|
||||
}
|
||||
const hue2rgb = (p, q, t) => {
|
||||
let tt = t;
|
||||
if (tt < 0) tt += 1;
|
||||
if (tt > 1) tt -= 1;
|
||||
if (tt < 1 / 6) return p + (q - p) * 6 * tt;
|
||||
if (tt < 1 / 2) return q;
|
||||
if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return [
|
||||
hue2rgb(p, q, h + 1 / 3) * 255,
|
||||
hue2rgb(p, q, h) * 255,
|
||||
hue2rgb(p, q, h - 1 / 3) * 255,
|
||||
];
|
||||
}
|
||||
|
||||
function parseAlphaToken(rawAlpha) {
|
||||
if (rawAlpha == null || rawAlpha === '') return 1;
|
||||
const str = String(rawAlpha).trim();
|
||||
if (!str) return 1;
|
||||
if (str.endsWith('%')) {
|
||||
const pct = parseFloat(str);
|
||||
return Number.isFinite(pct) ? pct / 100 : 1;
|
||||
}
|
||||
const num = parseFloat(str);
|
||||
return Number.isFinite(num) ? num : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`.
|
||||
* Returns `null` when transparent (`alpha <= 0.15`) or unparseable.
|
||||
*
|
||||
* @param {string | null | undefined} rawColor
|
||||
* @returns {number | null}
|
||||
*/
|
||||
export function parseCssColorLuminance(rawColor) {
|
||||
const str = String(rawColor ?? '').trim().toLowerCase();
|
||||
if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (str.startsWith('#')) {
|
||||
const hex = str.slice(1);
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let a = 1;
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
r = parseInt(hex[0] + hex[0], 16);
|
||||
g = parseInt(hex[1] + hex[1], 16);
|
||||
b = parseInt(hex[2] + hex[2], 16);
|
||||
if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255;
|
||||
} else if (hex.length === 6 || hex.length === 8) {
|
||||
r = parseInt(hex.slice(0, 2), 16);
|
||||
g = parseInt(hex.slice(2, 4), 16);
|
||||
b = parseInt(hex.slice(4, 6), 16);
|
||||
if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) {
|
||||
return null;
|
||||
}
|
||||
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
}
|
||||
|
||||
const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/);
|
||||
if (rgbMatch) {
|
||||
const body = rgbMatch[1].trim();
|
||||
const [channelsPart, slashAlpha] = body.split('/');
|
||||
const parts = channelsPart
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.filter(Boolean);
|
||||
if (parts.length < 3) return null;
|
||||
const parseChan = (tok) =>
|
||||
tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok);
|
||||
const r = parseChan(parts[0]);
|
||||
const g = parseChan(parts[1]);
|
||||
const b = parseChan(parts[2]);
|
||||
const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]);
|
||||
if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) {
|
||||
return null;
|
||||
}
|
||||
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
}
|
||||
|
||||
const hslMatch = str.match(/^hsla?\(([^)]+)\)$/);
|
||||
if (hslMatch) {
|
||||
const body = hslMatch[1].trim();
|
||||
const [channelsPart, slashAlpha] = body.split('/');
|
||||
const parts = channelsPart
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.filter(Boolean);
|
||||
if (parts.length < 3) return null;
|
||||
const h = parseFloat(parts[0]);
|
||||
const s = parseFloat(parts[1]);
|
||||
const l = parseFloat(parts[2]);
|
||||
const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]);
|
||||
if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) {
|
||||
return null;
|
||||
}
|
||||
const [r, g, b] = hslToRgb(h, s, l);
|
||||
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readStyleProp(el, cs, prop) {
|
||||
if (prop.startsWith('--')) {
|
||||
const inlineVal =
|
||||
typeof el?.style?.getPropertyValue === 'function'
|
||||
? el.style.getPropertyValue(prop)
|
||||
: el?.style?.[prop];
|
||||
if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim();
|
||||
const compVal = cs?.getPropertyValue?.(prop);
|
||||
return compVal ? String(compVal).trim() : '';
|
||||
}
|
||||
const inlineVal = el?.style?.[prop];
|
||||
if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim();
|
||||
const compVal = cs?.[prop];
|
||||
return compVal ? String(compVal).trim() : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect whether the active host surface is `'light'` or `'dark'`.
|
||||
* Inspects explicit Antigravity / VS Code theme classes & attributes first,
|
||||
* then actual computed surface/text luminance, then `prefers-color-scheme`.
|
||||
*
|
||||
* @param {HTMLElement | null | undefined} [targetEl]
|
||||
* @returns {'light' | 'dark'}
|
||||
*/
|
||||
export function detectHostColorScheme(targetEl = null) {
|
||||
const doc = typeof document !== 'undefined' ? document : null;
|
||||
const win = typeof window !== 'undefined' ? window : null;
|
||||
let workbenchEl = null;
|
||||
try {
|
||||
workbenchEl =
|
||||
typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null;
|
||||
} catch {
|
||||
workbenchEl = null;
|
||||
}
|
||||
|
||||
const candidates = [];
|
||||
for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) {
|
||||
if (el && !candidates.includes(el)) {
|
||||
candidates.push(el);
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme)
|
||||
for (const el of candidates) {
|
||||
const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (vscodeKind) {
|
||||
if (vscodeKind.includes('light')) return 'light';
|
||||
if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark';
|
||||
}
|
||||
const dataTheme = String(
|
||||
el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || ''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light';
|
||||
if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark';
|
||||
|
||||
const rawCls = typeof el.className === 'string' ? el.className : '';
|
||||
if (rawCls) {
|
||||
const tokens = rawCls.trim().toLowerCase().split(/\s+/);
|
||||
for (const tok of tokens) {
|
||||
if (LIGHT_THEME_CLASSES.has(tok)) return 'light';
|
||||
if (DARK_THEME_CLASSES.has(tok)) return 'dark';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Computed / inline surface background luminance
|
||||
const bgTargets = [];
|
||||
for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) {
|
||||
if (el && !bgTargets.includes(el)) {
|
||||
bgTargets.push(el);
|
||||
}
|
||||
}
|
||||
const bgProps = [
|
||||
'--background',
|
||||
'--card',
|
||||
'--vscode-sideBar-background',
|
||||
'--vscode-editor-background',
|
||||
'backgroundColor',
|
||||
];
|
||||
for (const el of bgTargets) {
|
||||
let cs = null;
|
||||
try {
|
||||
cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null;
|
||||
} catch {
|
||||
cs = null;
|
||||
}
|
||||
for (const prop of bgProps) {
|
||||
const lum = parseCssColorLuminance(readStyleProp(el, cs, prop));
|
||||
if (lum !== null) {
|
||||
return lum > 0.52 ? 'light' : 'dark';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Computed / inline foreground text luminance
|
||||
const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color'];
|
||||
for (const el of bgTargets) {
|
||||
let cs = null;
|
||||
try {
|
||||
cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null;
|
||||
} catch {
|
||||
cs = null;
|
||||
}
|
||||
for (const prop of fgProps) {
|
||||
const lum = parseCssColorLuminance(readStyleProp(el, cs, prop));
|
||||
if (lum !== null) {
|
||||
return lum < 0.48 ? 'light' : 'dark';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. OS media query fallback
|
||||
try {
|
||||
if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) {
|
||||
return 'dark';
|
||||
}
|
||||
} catch {
|
||||
// ignore matchMedia errors
|
||||
}
|
||||
|
||||
return 'light';
|
||||
}
|
||||
|
||||
function setAttrIfChanged(el, name, value) {
|
||||
if (!el || typeof el.setAttribute !== 'function') return;
|
||||
if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return;
|
||||
el.setAttribute(name, value);
|
||||
}
|
||||
|
||||
function removeAttrIfPresent(el, name) {
|
||||
if (!el || typeof el.removeAttribute !== 'function') return;
|
||||
if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return;
|
||||
el.removeAttribute(name);
|
||||
}
|
||||
|
||||
function setOrClearStyleVar(el, propName, value) {
|
||||
if (!el || !el.style) return;
|
||||
const cur =
|
||||
typeof el.style.getPropertyValue === 'function'
|
||||
? el.style.getPropertyValue(propName)
|
||||
: el.style[propName] || '';
|
||||
if (value) {
|
||||
if (cur === value) return;
|
||||
if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, value);
|
||||
} else {
|
||||
el.style[propName] = value;
|
||||
}
|
||||
} else if (typeof el.style.removeProperty === 'function') {
|
||||
el.style.removeProperty(propName);
|
||||
} else if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, '');
|
||||
} else if (cur) {
|
||||
if (typeof el.style.removeProperty === 'function') {
|
||||
el.style.removeProperty(propName);
|
||||
} else if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, '');
|
||||
} else {
|
||||
el.style[propName] = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize theme accent and (optionally) font scale tokens onto a root/host element.
|
||||
* Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens
|
||||
* onto a root/host element.
|
||||
*
|
||||
* @param {HTMLElement | null | undefined} targetEl
|
||||
* @param {object | null | undefined} settings
|
||||
@@ -72,7 +391,17 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t
|
||||
setOrClearStyleVar(targetEl, '--user-accent-primary', '');
|
||||
setOrClearStyleVar(targetEl, '--user-accent-contrast', '');
|
||||
}
|
||||
targetEl.setAttribute?.('data-accent', preset.key);
|
||||
setAttrIfChanged(targetEl, 'data-accent', preset.key);
|
||||
|
||||
const colorScheme = detectHostColorScheme(targetEl);
|
||||
setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme);
|
||||
|
||||
const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi);
|
||||
if (isModernUi) {
|
||||
setAttrIfChanged(targetEl, 'data-modern-ui', 'true');
|
||||
} else {
|
||||
removeAttrIfPresent(targetEl, 'data-modern-ui');
|
||||
}
|
||||
|
||||
if (includeFontScale) {
|
||||
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||
@@ -80,12 +409,10 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t
|
||||
const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1;
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
|
||||
setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor));
|
||||
targetEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
setAttrIfChanged(targetEl, 'data-font-scale', scaleKey);
|
||||
} else {
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
|
||||
setOrClearStyleVar(targetEl, '--ui-panel-scale', '');
|
||||
if (typeof targetEl.removeAttribute === 'function') {
|
||||
targetEl.removeAttribute('data-font-scale');
|
||||
}
|
||||
removeAttrIfPresent(targetEl, 'data-font-scale');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,11 @@ const keyedListState = new WeakMap();
|
||||
* Keyed incremental list reconciler.
|
||||
* Reuses existing DOM nodes by key and patches only changed items in-place.
|
||||
*/
|
||||
export function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) {
|
||||
export function patchKeyedList(
|
||||
container,
|
||||
items,
|
||||
{ keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {}
|
||||
) {
|
||||
if (!container) return;
|
||||
let map = keyedListState.get(container);
|
||||
if (!map) {
|
||||
@@ -175,6 +179,7 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
||||
if (record.el.parentNode === container) {
|
||||
container.removeChild(record.el);
|
||||
}
|
||||
destroyRow?.(record.refs, record.el);
|
||||
map.delete(oldKey);
|
||||
}
|
||||
}
|
||||
@@ -197,3 +202,194 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CLIPPING_OVERFLOW_RE = /(?:hidden|clip|auto|scroll)/i;
|
||||
|
||||
/**
|
||||
* 解析浮层所在的可视裁剪边界(兼容 Shadow DOM 悬浮窗 `.wm-popover-panel`、
|
||||
* 侧栏 `.app-shell`、自定义滚动容器 `.custom-scroll-content` 与窗口视口)。
|
||||
*
|
||||
* @param {HTMLElement} anchorRootEl
|
||||
* @returns {{ left: number, top: number, right: number, bottom: number, width: number, height: number } | null}
|
||||
*/
|
||||
function resolvePopupBoundaryRect(anchorRootEl) {
|
||||
if (!anchorRootEl) return null;
|
||||
const winW = typeof window !== 'undefined' ? Number(window.innerWidth || 0) : 0;
|
||||
const winH = typeof window !== 'undefined' ? Number(window.innerHeight || 0) : 0;
|
||||
let boundLeft = 0;
|
||||
let boundTop = 0;
|
||||
let boundRight = winW > 0 ? winW : Infinity;
|
||||
let boundBottom = winH > 0 ? winH : Infinity;
|
||||
let hasBoundary = winW > 0 && winH > 0;
|
||||
|
||||
const getStyle =
|
||||
typeof window !== 'undefined' && typeof window.getComputedStyle === 'function'
|
||||
? window.getComputedStyle
|
||||
: null;
|
||||
|
||||
let cur = anchorRootEl.parentNode || null;
|
||||
while (cur) {
|
||||
if (cur.nodeType === 1 || typeof cur.getBoundingClientRect === 'function') {
|
||||
const cls = cur.classList;
|
||||
const isShell = Boolean(
|
||||
cls?.contains?.('wm-popover-panel') ||
|
||||
cls?.contains?.('wm-multi-panel') ||
|
||||
cls?.contains?.('app-shell') ||
|
||||
cls?.contains?.('custom-scroll-host') ||
|
||||
cls?.contains?.('custom-scroll-content')
|
||||
);
|
||||
let clipsX = isShell;
|
||||
let clipsY = isShell;
|
||||
if (!isShell && getStyle) {
|
||||
try {
|
||||
const cs = getStyle(cur);
|
||||
if (cs) {
|
||||
clipsX = CLIPPING_OVERFLOW_RE.test(cs.overflowX || cs.overflow || '');
|
||||
clipsY = CLIPPING_OVERFLOW_RE.test(cs.overflowY || cs.overflow || '');
|
||||
}
|
||||
} catch {
|
||||
// 忽略 Mock DOM 样式查询异常
|
||||
}
|
||||
}
|
||||
if (clipsX || clipsY) {
|
||||
const r = cur.getBoundingClientRect?.();
|
||||
if (r && r.width > 0 && r.height > 0) {
|
||||
hasBoundary = true;
|
||||
if (clipsX) {
|
||||
boundLeft = Math.max(boundLeft, r.left);
|
||||
boundRight = Math.min(boundRight, r.right);
|
||||
}
|
||||
if (clipsY) {
|
||||
boundTop = Math.max(boundTop, r.top);
|
||||
boundBottom = Math.min(boundBottom, r.bottom);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 到达 ShadowRoot 或文档顶层后停止,避免误受宿主页面外层容器干扰
|
||||
if (!cur.parentNode) break;
|
||||
cur = cur.parentNode;
|
||||
}
|
||||
|
||||
if (!hasBoundary || !Number.isFinite(boundRight) || !Number.isFinite(boundBottom)) {
|
||||
return null;
|
||||
}
|
||||
const width = Math.max(0, boundRight - boundLeft);
|
||||
const height = Math.max(0, boundBottom - boundTop);
|
||||
if (width <= 0 || height <= 0) return null;
|
||||
return { left: boundLeft, top: boundTop, right: boundRight, bottom: boundBottom, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* 为锚定在触发器上的绝对定位下拉浮层执行水平/垂直碰撞检测与边界夹紧:
|
||||
* - 水平方向优先左对齐,右侧溢出时切右对齐,仍越界则直接夹紧在容器可视安全区内;
|
||||
* - 垂直方向底部空间不足且上方更宽裕时自动向上翻转(追加 `.is-above`),并按可用空间收紧 `max-height`。
|
||||
*
|
||||
* @param {HTMLElement} rootEl 定位基准容器 (`position: relative`)
|
||||
* @param {HTMLElement} triggerEl 触发按钮
|
||||
* @param {HTMLElement} popupEl 下拉浮层 (`position: absolute`)
|
||||
* @param {{ margin?: number, gap?: number, maxHeight?: number, minFlipSpace?: number }} [opts]
|
||||
*/
|
||||
export function positionAnchoredPopup(
|
||||
rootEl,
|
||||
triggerEl,
|
||||
popupEl,
|
||||
{ margin = 6, gap = 4, maxHeight = 220, minFlipSpace = 140 } = {}
|
||||
) {
|
||||
if (!rootEl || !triggerEl || !popupEl || !popupEl.style) return;
|
||||
if (popupEl.hasAttribute?.('hidden')) return;
|
||||
|
||||
const rootRect = rootEl.getBoundingClientRect?.();
|
||||
const triggerRect = triggerEl.getBoundingClientRect?.();
|
||||
if (
|
||||
!rootRect ||
|
||||
!triggerRect ||
|
||||
!(triggerRect.width > 0 && triggerRect.height > 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bound = resolvePopupBoundaryRect(rootEl);
|
||||
if (!bound) return;
|
||||
|
||||
// 清除旧的动态夹紧值以便读取自然布局宽度
|
||||
popupEl.style.left = '';
|
||||
popupEl.style.right = '';
|
||||
popupEl.style.top = '';
|
||||
popupEl.style.bottom = '';
|
||||
popupEl.style.minWidth = '';
|
||||
popupEl.style.maxWidth = '';
|
||||
popupEl.style.maxHeight = '';
|
||||
|
||||
const availWidth = Math.max(120, Math.floor(bound.width - margin * 2));
|
||||
popupEl.style.maxWidth = `${availWidth}px`;
|
||||
|
||||
const rawRect = popupEl.getBoundingClientRect?.();
|
||||
// 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小
|
||||
const naturalW = Math.max(
|
||||
Number(popupEl.offsetWidth || 0),
|
||||
Math.ceil(Number(rawRect?.width || 0))
|
||||
);
|
||||
if (naturalW > availWidth) {
|
||||
popupEl.style.minWidth = '0px';
|
||||
}
|
||||
const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210));
|
||||
|
||||
const safeLeft = bound.left + margin;
|
||||
const safeRight = bound.right - margin;
|
||||
const rawLeft = Number(rawRect?.left);
|
||||
const rawRight = Number(rawRect?.right);
|
||||
const hasRawBox = Number.isFinite(rawLeft) && Number.isFinite(rawRight) && rawRight > rawLeft;
|
||||
// 若入场缩放动画(如 scale(0.975))正在首帧生效,按对称补偿还原终态边界再判断是否越界
|
||||
const scalePadX = hasRawBox ? Math.max(0, (popupW - (rawRight - rawLeft)) / 2) : 0;
|
||||
const naturalLeft = hasRawBox ? rawLeft - scalePadX : triggerRect.left;
|
||||
const naturalRight = hasRawBox
|
||||
? Math.max(rawRight + scalePadX, naturalLeft + popupW)
|
||||
: naturalLeft + popupW;
|
||||
const fitsAsDefault = hasRawBox && naturalLeft >= safeLeft && naturalRight <= safeRight;
|
||||
|
||||
if (!fitsAsDefault) {
|
||||
let targetLeft = triggerRect.left;
|
||||
if (targetLeft + popupW > safeRight) {
|
||||
const rightAlignedLeft = triggerRect.right - popupW;
|
||||
if (rightAlignedLeft >= safeLeft) {
|
||||
targetLeft = rightAlignedLeft;
|
||||
} else {
|
||||
targetLeft = Math.max(safeLeft, safeRight - popupW);
|
||||
}
|
||||
}
|
||||
if (targetLeft < safeLeft) {
|
||||
targetLeft = safeLeft;
|
||||
}
|
||||
|
||||
const offsetLeft = Math.round(targetLeft - rootRect.left);
|
||||
popupEl.style.left = `${offsetLeft}px`;
|
||||
popupEl.style.right = 'auto';
|
||||
}
|
||||
|
||||
const spaceBelow = Math.max(0, bound.bottom - triggerRect.bottom - gap - margin);
|
||||
const spaceAbove = Math.max(0, triggerRect.top - bound.top - gap - margin);
|
||||
const naturalH = Math.max(
|
||||
Number(popupEl.scrollHeight || 0),
|
||||
Number(popupEl.offsetHeight || 0),
|
||||
Math.ceil(Number(rawRect?.height || 0))
|
||||
);
|
||||
const desiredH = maxHeight > 0 ? Math.min(maxHeight, naturalH || maxHeight) : naturalH || 240;
|
||||
const shouldOpenAbove =
|
||||
spaceBelow < Math.min(desiredH, minFlipSpace) && spaceAbove > spaceBelow;
|
||||
|
||||
patchClasses(popupEl, { 'is-above': shouldOpenAbove });
|
||||
if (shouldOpenAbove) {
|
||||
popupEl.style.top = 'auto';
|
||||
popupEl.style.bottom = `calc(100% + ${gap}px)`;
|
||||
if (maxHeight > 0) {
|
||||
popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceAbove)))}px`;
|
||||
}
|
||||
} else {
|
||||
popupEl.style.top = `calc(100% + ${gap}px)`;
|
||||
popupEl.style.bottom = 'auto';
|
||||
if (maxHeight > 0) {
|
||||
popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceBelow)))}px`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,13 @@ const EN_MONTH_SHORT = Object.freeze([
|
||||
]);
|
||||
|
||||
export function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
if (!Number.isFinite(value)) return '—';
|
||||
const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1);
|
||||
return `${numStr}${unit}`;
|
||||
}
|
||||
|
||||
export function formatSpeedMetric(value, unit = ' tok/s') {
|
||||
return formatMetric(value, unit);
|
||||
}
|
||||
|
||||
export function formatCachePct(value) {
|
||||
@@ -98,6 +104,8 @@ const SPEED_REASON_LABELS = {
|
||||
__proto__: null,
|
||||
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
|
||||
canceled: 'fmt.speedCanceled',
|
||||
error: 'fmt.speedError',
|
||||
interrupted: 'fmt.speedInterrupted',
|
||||
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
|
||||
invalid_output_tokens: 'fmt.speedInvalidOutput',
|
||||
inconsistent_timing: 'fmt.speedInconsistent',
|
||||
@@ -110,6 +118,135 @@ export function speedReasonText(reason) {
|
||||
return label ? t(label) : '';
|
||||
}
|
||||
|
||||
const ANOMALY_KIND_ORDER = Object.freeze([
|
||||
'rate_limit',
|
||||
'timeout',
|
||||
'capacity',
|
||||
'disconnect',
|
||||
'upstream',
|
||||
'model_output',
|
||||
'safety',
|
||||
'auth_or_model',
|
||||
'error',
|
||||
]);
|
||||
|
||||
export function formatAnomalyKindLabel(kind) {
|
||||
const k = String(kind || 'error');
|
||||
const key = `steps.anomalyKind.${k}`;
|
||||
const text = t(key);
|
||||
return text === key ? t('steps.anomalyKind.error') : text;
|
||||
}
|
||||
|
||||
export function formatAnomalyTagText(primaryKind, count = 1) {
|
||||
const n = Math.max(1, Math.floor(Number(count) || 1));
|
||||
const k = String(primaryKind || 'error');
|
||||
if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle');
|
||||
if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle');
|
||||
const key = `steps.anomalyTag.${k}`;
|
||||
const formatted = t(key, { n });
|
||||
return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted;
|
||||
}
|
||||
|
||||
export function resolveModelAnomalySummary(m) {
|
||||
const count = Math.max(0, Number(m?.anomalyCount || 0));
|
||||
const steps = Math.max(0, Number(m?.anomalySteps || 0));
|
||||
if (count <= 0 && steps <= 0) return null;
|
||||
const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {};
|
||||
const entries = Object.entries(byKind)
|
||||
.map(([k, v]) => [k, Math.max(0, Number(v || 0))])
|
||||
.filter(([, v]) => v > 0)
|
||||
.sort((a, b) => {
|
||||
if (b[1] !== a[1]) return b[1] - a[1];
|
||||
const pa = ANOMALY_KIND_ORDER.indexOf(a[0]);
|
||||
const pb = ANOMALY_KIND_ORDER.indexOf(b[0]);
|
||||
return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb);
|
||||
});
|
||||
const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps;
|
||||
const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error';
|
||||
const severity =
|
||||
Number(m?.anomalyDangerCount || 0) > 0 ||
|
||||
entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model')
|
||||
? 'danger'
|
||||
: 'warn';
|
||||
return {
|
||||
count: totalCount,
|
||||
steps: steps || totalCount,
|
||||
totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)),
|
||||
primaryKind,
|
||||
severity,
|
||||
entries,
|
||||
tagText: formatAnomalyTagText(primaryKind, totalCount),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStepAnomalyInlineSummary(anomaly) {
|
||||
if (!anomaly || !(Number(anomaly.count) > 0)) return '';
|
||||
const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count);
|
||||
const label = formatAnomalyKindLabel(anomaly.primaryKind);
|
||||
const delaySec = Number(anomaly.totalDelaySec || 0);
|
||||
const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : '';
|
||||
return `${tag} · ${label}${delayPart}`;
|
||||
}
|
||||
|
||||
export function buildStepAnomalyDiagnostic(st) {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return null;
|
||||
const title = t('steps.anomalyStepTitle', {
|
||||
step: Number(st.stepIndex ?? 0),
|
||||
count: Number(a.count),
|
||||
});
|
||||
const delaySec = Number(a.totalDelaySec || 0);
|
||||
const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : '';
|
||||
const events = Array.isArray(a.events) ? a.events : [];
|
||||
const rows = events.map((ev, idx) => {
|
||||
const label = formatAnomalyKindLabel(ev.kind);
|
||||
const parts = [`#${ev.attempt || idx + 1} ${label}`];
|
||||
if (Number(ev.delaySec) > 0) {
|
||||
parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec }));
|
||||
}
|
||||
if (ev.terminal) {
|
||||
parts.push(t('steps.anomalyTerminalTag'));
|
||||
}
|
||||
return {
|
||||
text: parts.join(' · '),
|
||||
detail: ev.message || '',
|
||||
danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'),
|
||||
};
|
||||
});
|
||||
return {
|
||||
title,
|
||||
sub,
|
||||
rows,
|
||||
hint: '',
|
||||
severity: a.severity === 'danger' ? 'danger' : 'warn',
|
||||
};
|
||||
}
|
||||
|
||||
export function buildModelAnomalyDiagnostic(m) {
|
||||
const sum = resolveModelAnomalySummary(m);
|
||||
if (!sum) return null;
|
||||
const title = t('steps.anomalyModelTitle', {
|
||||
model: m?.displayText || m?.shortName || m?.label || '—',
|
||||
count: sum.count,
|
||||
});
|
||||
const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })];
|
||||
if (sum.totalDelaySec > 0) {
|
||||
subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec }));
|
||||
}
|
||||
const rows = sum.entries.map(([k, v]) => ({
|
||||
text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }),
|
||||
detail: '',
|
||||
danger: k === 'rate_limit' || k === 'auth_or_model',
|
||||
}));
|
||||
return {
|
||||
title,
|
||||
sub: subParts.join(' · '),
|
||||
rows,
|
||||
hint: t('steps.anomalyModelClickHint'),
|
||||
severity: sum.severity,
|
||||
};
|
||||
}
|
||||
|
||||
export function sampleSummary(summary) {
|
||||
const valid = summary?.sampleCount || 0;
|
||||
const excluded = summary?.excludedCount || 0;
|
||||
@@ -389,6 +526,12 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0,
|
||||
ttftWeight: hasTtft ? ttftWeight : 0,
|
||||
ttftSampleCount,
|
||||
anomalySteps: Math.max(0, Number(m.anomalySteps || 0)),
|
||||
anomalyCount: Math.max(0, Number(m.anomalyCount || 0)),
|
||||
anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)),
|
||||
anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)),
|
||||
anomalyByKind:
|
||||
m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {},
|
||||
};
|
||||
if (m.upstreamName) acc.upstreamSet.add(m.upstreamName);
|
||||
byDisplay.set(key, acc);
|
||||
@@ -417,6 +560,17 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
acc.costUsd += costUsd;
|
||||
acc.unpricedCalls += unpricedCalls;
|
||||
|
||||
acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0));
|
||||
acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0));
|
||||
acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0));
|
||||
acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0));
|
||||
if (m.anomalyByKind && typeof m.anomalyByKind === 'object') {
|
||||
for (const [ak, av] of Object.entries(m.anomalyByKind)) {
|
||||
const cnt = Math.max(0, Number(av || 0));
|
||||
if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasSpeed) {
|
||||
acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight;
|
||||
acc.speedWeight += speedWeight;
|
||||
@@ -467,6 +621,15 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
avgTokPerSec,
|
||||
avgTtftSec,
|
||||
ttftSampleCount: acc.ttftSampleCount,
|
||||
...(acc.anomalyCount > 0
|
||||
? {
|
||||
anomalySteps: acc.anomalySteps,
|
||||
anomalyCount: acc.anomalyCount,
|
||||
anomalyDangerCount: acc.anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind: acc.anomalyByKind,
|
||||
}
|
||||
: {}),
|
||||
speedSummary: acc.baseItem.speedSummary
|
||||
? {
|
||||
...acc.baseItem.speedSummary,
|
||||
@@ -496,21 +659,48 @@ export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
return `badge-sub-${slot}`;
|
||||
}
|
||||
|
||||
function resolveStructuredAgentKind(agent) {
|
||||
if (!agent) return 'main';
|
||||
if (agent.agentKind) return agent.agentKind;
|
||||
if (agent.isMain) return 'main';
|
||||
if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question';
|
||||
if (
|
||||
agent.typeName === 'worker' ||
|
||||
agent.typeName === 'swarm_worker' ||
|
||||
/^Swarm\s+Worker\s*\(/i.test(String(agent.role || ''))
|
||||
) {
|
||||
return 'swarm_worker';
|
||||
}
|
||||
return 'subagent';
|
||||
}
|
||||
|
||||
function normalizeSwarmMemberHandle(rawText) {
|
||||
const trimmed = String(rawText || '').trim();
|
||||
if (!trimmed) return '';
|
||||
const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
|
||||
const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim();
|
||||
if (
|
||||
!inner ||
|
||||
inner === '蜂群' ||
|
||||
inner === '工蜂' ||
|
||||
inner.toLowerCase() === 'swarm' ||
|
||||
inner.toLowerCase() === 'worker' ||
|
||||
inner.toLowerCase() === 'swarm worker'
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
return `@${inner}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
*
|
||||
* @param {object|null|undefined} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAgentBadgeText(agent) {
|
||||
if (!agent) return t('fmt.mainBadge');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAllShort');
|
||||
if (kind === 'main') return t('fmt.mainBadge');
|
||||
if (kind === 'side_question') {
|
||||
@@ -519,6 +709,12 @@ export function formatAgentBadgeText(agent) {
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.sideBadgeShort');
|
||||
}
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.swarmBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.swarmBadgeShort');
|
||||
}
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.subBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
@@ -533,13 +729,7 @@ export function formatAgentBadgeText(agent) {
|
||||
*/
|
||||
export function formatAgentLabel(agent) {
|
||||
if (!agent) return t('fmt.mainAgent');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAll');
|
||||
if (kind === 'main') return t('fmt.mainAgent');
|
||||
|
||||
@@ -560,6 +750,20 @@ export function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent');
|
||||
const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || '');
|
||||
if (!handle) return baseLabel;
|
||||
let auxSuffix = '';
|
||||
if (/^@monitor(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmMonitorHint')})`;
|
||||
} else if (/^@narrator(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmNarratorHint')})`;
|
||||
}
|
||||
return `${baseLabel} · ${handle}${auxSuffix}`;
|
||||
}
|
||||
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
|
||||
const isGeneric =
|
||||
@@ -571,6 +775,31 @@ export function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。
|
||||
*
|
||||
* @param {object|null|undefined} conv
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatConversationMeta(conv) {
|
||||
if (!conv) return '';
|
||||
const main = Number(conv.stepCount || 0);
|
||||
const totalSubs = Number(conv.subagentCount || 0);
|
||||
const swarm = Number(conv.swarmCount || 0);
|
||||
const otherSubs = Math.max(0, totalSubs - swarm);
|
||||
const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main);
|
||||
if (swarm > 0 && otherSubs > 0) {
|
||||
return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total });
|
||||
}
|
||||
if (swarm > 0) {
|
||||
return t('header.convMetaWithSwarm', { main, swarm, total });
|
||||
}
|
||||
if (totalSubs > 0) {
|
||||
return t('header.convMetaWithSubs', { main, subs: totalSubs, total });
|
||||
}
|
||||
return t('header.convMetaSteps', { count: main });
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
|
||||
*
|
||||
@@ -610,3 +839,162 @@ export function formatLiveActivityDetail(act) {
|
||||
}
|
||||
return String(act.detail || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 20 色感知均匀色环(无特定模型绑定,兼顾亮/暗背景可读性,彻底消除标准 HSL 绿色/暗红区过度聚集撞色)。
|
||||
* 每项为 `[hue, saturationPct, lightnessPct]`。
|
||||
*/
|
||||
const PERCEPTUAL_MODEL_COLOR_RING = [
|
||||
[217, 82, 53], // Royal Blue
|
||||
[14, 80, 52], // Coral / Vermilion
|
||||
[162, 74, 41], // Teal / Jade
|
||||
[272, 74, 58], // Vivid Violet
|
||||
[36, 88, 47], // Rich Amber
|
||||
[336, 78, 53], // Rose / Raspberry
|
||||
[193, 84, 43], // Cerulean / Cyan
|
||||
[138, 66, 41], // Emerald Green
|
||||
[246, 74, 60], // Indigo
|
||||
[25, 86, 50], // Tangerine Orange
|
||||
[306, 70, 52], // Magenta / Orchid
|
||||
[177, 76, 39], // Deep Seafoam
|
||||
[355, 76, 54], // Crimson Red
|
||||
[205, 80, 48], // Ocean Blue
|
||||
[45, 88, 44], // Warm Gold
|
||||
[288, 68, 55], // Amethyst Purple
|
||||
[102, 60, 42], // Leaf Green
|
||||
[230, 76, 57], // Cobalt Blue
|
||||
[322, 74, 51], // Berry Pink
|
||||
[185, 72, 46], // Turquoise
|
||||
];
|
||||
|
||||
/**
|
||||
* 提取跨平台、跨语言、同屏三栏(模型排行 / 客户端来源 / 月度统计)严格一致的模型颜色种子字符串。
|
||||
*
|
||||
* 优先取单模型稳定 `sourceLabels[0]`;若多个外层槽位已在当前显示策略下合并(如 `4-argon`),
|
||||
* 则以规范化 `displayText` 为种子,确保跨客户端与跨月份聚合子集不同时依然映射至完全相同的颜色。
|
||||
*
|
||||
* @param {object|string|null|undefined} model
|
||||
* @returns {string}
|
||||
*/
|
||||
export function getCanonicalModelColorSeed(model) {
|
||||
if (typeof model === 'string') {
|
||||
return model.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
if (!model || typeof model !== 'object') return '';
|
||||
if (
|
||||
Number(model.mergedCount || 0) <= 1 &&
|
||||
Array.isArray(model.sourceLabels) &&
|
||||
model.sourceLabels.length === 1 &&
|
||||
model.sourceLabels[0]
|
||||
) {
|
||||
return String(model.sourceLabels[0]).trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
const raw =
|
||||
model.displayText ||
|
||||
model.label ||
|
||||
model.modelId ||
|
||||
model.baseItem?.modelId ||
|
||||
model.shortName ||
|
||||
model.name ||
|
||||
'';
|
||||
return String(raw).trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function hashModelSeed32(str) {
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
h ^= str.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
h ^= h >>> 16;
|
||||
h = Math.imul(h, 0x85ebca6b);
|
||||
h ^= h >>> 13;
|
||||
h = Math.imul(h, 0xc2b2ae35);
|
||||
h ^= h >>> 16;
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
function formatRingSlotHsl(slotIdx, shiftLight = 0) {
|
||||
const [hue, sat, light] = PERCEPTUAL_MODEL_COLOR_RING[slotIdx % PERCEPTUAL_MODEL_COLOR_RING.length];
|
||||
const clampedLight = Math.min(66, Math.max(34, light + shiftLight));
|
||||
return `hsl(${hue} ${sat}% ${clampedLight}%)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于模型标识通过 32 位雪崩哈希映射至 20 色感知均匀色环,确保跨电脑同模型同色且无需硬编码颜色表。
|
||||
*
|
||||
* @param {object|string|null|undefined} seedOrModel
|
||||
* @returns {string}
|
||||
*/
|
||||
export function resolveDeterministicModelColor(seedOrModel) {
|
||||
const seed = getCanonicalModelColorSeed(seedOrModel);
|
||||
if (!seed) return 'var(--accent-primary)';
|
||||
const h = hashModelSeed32(seed);
|
||||
return formatRingSlotHsl(h % PERCEPTUAL_MODEL_COLOR_RING.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为一组模型构建确定性颜色映射表(双遍固有槽位保护):
|
||||
* 1. 所有无槽位冲突的模型 100% 保持其纯哈希固有色,不受长尾模型增减影响;
|
||||
* 2. 仅当同屏两个模型恰好落入同一色环槽位时,按严格字典序以互质步长 `+7` 优先探查未被任何模型占用的空闲槽位。
|
||||
*
|
||||
* @param {Array<object|string>} [models=[]]
|
||||
* @returns {Map<string, string>} `canonicalSeed -> hsl(...)`
|
||||
*/
|
||||
export function buildDeterministicModelColorMap(models = []) {
|
||||
const ringLen = PERCEPTUAL_MODEL_COLOR_RING.length;
|
||||
const uniqueSeeds = Array.from(
|
||||
new Set(
|
||||
(Array.isArray(models) ? models : [])
|
||||
.map((m) => getCanonicalModelColorSeed(m))
|
||||
.filter(Boolean)
|
||||
)
|
||||
).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
|
||||
const naturalSlotCounts = new Map();
|
||||
for (const seed of uniqueSeeds) {
|
||||
const nat = hashModelSeed32(seed) % ringLen;
|
||||
naturalSlotCounts.set(nat, (naturalSlotCounts.get(nat) || 0) + 1);
|
||||
}
|
||||
|
||||
const usedSlots = new Set();
|
||||
const colorMap = new Map();
|
||||
|
||||
for (const seed of uniqueSeeds) {
|
||||
const h = hashModelSeed32(seed);
|
||||
const nat = h % ringLen;
|
||||
if (!usedSlots.has(nat)) {
|
||||
usedSlots.add(nat);
|
||||
colorMap.set(seed, formatRingSlotHsl(nat));
|
||||
continue;
|
||||
}
|
||||
|
||||
let picked = -1;
|
||||
for (let k = 1; k < ringLen; k++) {
|
||||
const cand = (nat + k * 7) % ringLen;
|
||||
if (!usedSlots.has(cand) && !naturalSlotCounts.has(cand)) {
|
||||
picked = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (picked < 0) {
|
||||
for (let k = 1; k < ringLen; k++) {
|
||||
const cand = (nat + k * 7) % ringLen;
|
||||
if (!usedSlots.has(cand)) {
|
||||
picked = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (picked >= 0) {
|
||||
usedSlots.add(picked);
|
||||
colorMap.set(seed, formatRingSlotHsl(picked));
|
||||
} else {
|
||||
const shift = (h >>> 8) & 1 ? 9 : -8;
|
||||
colorMap.set(seed, formatRingSlotHsl(nat, shift));
|
||||
}
|
||||
}
|
||||
|
||||
return colorMap;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,15 @@ import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mj
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
|
||||
export function abortSidecarApiKey(abortKey) {
|
||||
if (!abortKey) return;
|
||||
const prev = activeControllers.get(abortKey);
|
||||
if (prev) {
|
||||
activeControllers.delete(abortKey);
|
||||
prev.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||
*
|
||||
|
||||
@@ -17,6 +17,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'header.lockedSession': 'Pinned Session ({id})',
|
||||
'header.lockedMeta': 'Pinned',
|
||||
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
|
||||
'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)',
|
||||
'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)',
|
||||
'header.convMetaSteps': '{count} steps',
|
||||
'header.hasUpdate': 'Update',
|
||||
'header.upgradeToVer': 'Update v{ver}',
|
||||
@@ -35,6 +37,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.pending': 'N/A',
|
||||
'fmt.speedIncomplete': 'Incomplete timing',
|
||||
'fmt.speedCanceled': 'Canceled',
|
||||
'fmt.speedError': 'Call error',
|
||||
'fmt.speedInterrupted': 'Interrupted',
|
||||
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
|
||||
'fmt.speedInvalidOutput': 'No valid output',
|
||||
'fmt.speedInconsistent': 'Invalid timing',
|
||||
@@ -55,6 +59,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.subAgent': 'Subagent',
|
||||
'fmt.subBadge': 'S{index}',
|
||||
'fmt.subBadgeShort': 'Sub',
|
||||
'fmt.swarmAgent': 'Swarm',
|
||||
'fmt.swarmBadge': 'W{index}',
|
||||
'fmt.swarmBadgeShort': 'Swarm',
|
||||
'fmt.swarmMonitorHint': 'Monitor',
|
||||
'fmt.swarmNarratorHint': 'Narrator',
|
||||
'fmt.sideQuestion': 'Side Question',
|
||||
'fmt.sideBadge': 'Q{index}',
|
||||
'fmt.sideBadgeShort': 'Q',
|
||||
@@ -68,6 +77,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'capsule.multiZero': '0 active',
|
||||
'capsule.multiRunning': '{count} active',
|
||||
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
|
||||
'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm',
|
||||
'capsule.tpsRunning': 'Running',
|
||||
'capsule.tpsIdle': 'Idle',
|
||||
'capsule.quotaLeft': '{pct}% left',
|
||||
@@ -88,6 +98,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'multi.empty': 'No active running sessions',
|
||||
'multi.allIdle': 'All idle',
|
||||
'multi.metaWithSubs': '{main} main · {subs} subagents active',
|
||||
'multi.metaWithSwarm': '{main} main · {subs} swarm active',
|
||||
'multi.metaMainOnly': '{main} sessions active',
|
||||
'multi.hereTag': 'Here',
|
||||
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
|
||||
@@ -136,9 +147,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
// Context Window Widget
|
||||
'ctx.followActive': 'Follow Active ({badge})',
|
||||
'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window',
|
||||
'ctx.expandMore': '+{count} More ▾',
|
||||
'ctx.expandMore': '+{count} More',
|
||||
'ctx.expandMoreTitle': 'Expand all {count} subagent context pills',
|
||||
'ctx.collapse': 'Less ▴',
|
||||
'ctx.collapse': 'Less',
|
||||
'ctx.collapseTitle': 'Collapse extra subagent pills',
|
||||
'ctx.ch.assistant': 'Assistant',
|
||||
'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments',
|
||||
@@ -184,14 +195,21 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.thinking': 'Thinking',
|
||||
'live.generating': 'Generating',
|
||||
'live.running': 'Running',
|
||||
'live.waiting': 'Waiting',
|
||||
'live.killed': 'Killed',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': 'Subagents ({total}) {arrow}',
|
||||
'live.waitingWithSteps': 'Waiting ({steps} steps)',
|
||||
'live.killedWithSteps': 'Killed ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total}',
|
||||
'live.subToggleIdle': 'Subagents ({total})',
|
||||
'live.swarmToggleRunning': 'Swarm {run}/{total}',
|
||||
'live.swarmToggleIdle': 'Swarm ({total})',
|
||||
'live.subCollapseTitle': 'Collapse subagent list',
|
||||
'live.subExpandTitle': 'Expand subagent activity list',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeCycle': 'Cycle',
|
||||
'cons.rangeToday': 'Today',
|
||||
'cons.range24h': '24h',
|
||||
'cons.range7d': '7d',
|
||||
@@ -223,6 +241,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'cons.clientSources': 'Client Sources',
|
||||
'cons.monthlyTitle': 'Monthly Breakdown',
|
||||
'cons.monthLabel': 'M{m}',
|
||||
'cons.monthFullLabel': 'M{m}, {year}',
|
||||
'cons.hoverModelsHint': 'Hover for models',
|
||||
'cons.otherModelsCount': 'Others ({count})',
|
||||
'cons.legInput': 'Input',
|
||||
'cons.legCache': 'Cache',
|
||||
'cons.legOutput': 'Output',
|
||||
@@ -280,6 +301,38 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)',
|
||||
'steps.turnMediaOnly': '[Media Attachment]',
|
||||
'steps.turnMediaSuffix': '[Media]',
|
||||
'steps.anomalyTag.timeout': 'TO{n}',
|
||||
'steps.anomalyTag.rate_limit': '429×{n}',
|
||||
'steps.anomalyTag.capacity': '503×{n}',
|
||||
'steps.anomalyTag.capacitySingle': '503',
|
||||
'steps.anomalyTag.disconnect': 'Drop{n}',
|
||||
'steps.anomalyTag.upstream': '500×{n}',
|
||||
'steps.anomalyTag.upstreamSingle': '500',
|
||||
'steps.anomalyTag.model_output': 'Fix{n}',
|
||||
'steps.anomalyTag.safety': 'Safe{n}',
|
||||
'steps.anomalyTag.auth_or_model': 'Err{n}',
|
||||
'steps.anomalyTag.error': 'Err{n}',
|
||||
'steps.anomalyTag.mixed': 'Warn{n}',
|
||||
'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout',
|
||||
'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached',
|
||||
'steps.anomalyKind.capacity': '503 No Capacity Available',
|
||||
'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted',
|
||||
'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error',
|
||||
'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call',
|
||||
'steps.anomalyKind.safety': 'Content Safety Filter',
|
||||
'steps.anomalyKind.auth_or_model': 'Request / Model Rejected',
|
||||
'steps.anomalyKind.error': 'Call Error',
|
||||
'steps.anomalyKind.canceled': 'Canceled by User',
|
||||
'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors',
|
||||
'steps.anomalyDelayPart': 'Backoff {sec}s',
|
||||
'steps.anomalyTerminalTag': 'Stopped',
|
||||
'steps.anomalyModelTitle': '{model} · {count} Retries / Errors',
|
||||
'steps.anomalyModelSub': '{steps} steps affected',
|
||||
'steps.anomalyModelKindRow': '{kind}: {count}',
|
||||
'steps.anomalyModelClickHint': 'Click to filter anomalous steps',
|
||||
'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)',
|
||||
'steps.anomalyFilterLabel': 'Anomalies Only ({count})',
|
||||
'steps.anomalyFilterAll': 'Show All Steps',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': 'Step',
|
||||
@@ -388,6 +441,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.gen.fontLg': 'Large',
|
||||
'settings.gen.fontXl': 'XL',
|
||||
'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact',
|
||||
'settings.gen.modernUi': 'Modern UI (Experimental)',
|
||||
'settings.gen.modernUiOff': 'Off',
|
||||
'settings.gen.modernUiOn': 'On',
|
||||
'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations',
|
||||
'settings.gen.updateTitle': 'Updates & Pricing',
|
||||
'settings.gen.updateMode': 'Update Policy',
|
||||
'settings.gen.updateManual': 'Notify only, update manually',
|
||||
@@ -437,14 +494,20 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate',
|
||||
'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override',
|
||||
'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.',
|
||||
'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.',
|
||||
'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate',
|
||||
'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override',
|
||||
'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.',
|
||||
'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount',
|
||||
'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override',
|
||||
'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive',
|
||||
'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive',
|
||||
'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending',
|
||||
'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.',
|
||||
'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.',
|
||||
'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).',
|
||||
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.',
|
||||
'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount',
|
||||
'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch',
|
||||
'settings.bridge.relaunchingBtn': 'Relaunching Host...',
|
||||
'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry',
|
||||
'settings.bridge.dismissAria': 'Dismiss notice for now',
|
||||
@@ -552,6 +615,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.invoke_subagent': 'Invoke Subagent',
|
||||
'live.act.send_message': 'Message Subagent',
|
||||
'live.act.manage_subagents': 'Manage Subagents',
|
||||
'live.act.swarm_add': 'Spawn Worker',
|
||||
'live.act.swarm_title': 'Name Swarm',
|
||||
'live.act.swarm_kill': 'Kill Worker',
|
||||
'live.act.swarm_model': 'Switch Worker Model',
|
||||
'live.act.swarm_channel': 'Swarm Channel',
|
||||
'live.act.swarm_status': 'Check Swarm',
|
||||
'live.act.post_message': 'Post to Board',
|
||||
'live.act.read_board': 'Read Board',
|
||||
'live.act.swarm_wait': 'Parked on Board',
|
||||
'live.act.manage_task': 'Manage Task',
|
||||
'live.act.schedule': 'Schedule Task',
|
||||
'live.act.ask_question': 'Waiting for User Choice',
|
||||
@@ -562,6 +634,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.compacting': 'Compacting Context',
|
||||
'live.act.responding': 'Responding',
|
||||
'live.act.waiting_subagent': 'Waiting for Subagent',
|
||||
'live.act.waiting_swarm': 'Waiting for Swarm',
|
||||
'live.act.swarm_waiting': 'Waiting',
|
||||
'live.act.swarm_killed': 'Killed',
|
||||
'live.act.starting': 'Starting',
|
||||
'live.act.done': 'Completed',
|
||||
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
|
||||
|
||||
@@ -17,6 +17,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'header.lockedSession': '已锁定会话 ({id})',
|
||||
'header.lockedMeta': '已锁定',
|
||||
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
|
||||
'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)',
|
||||
'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)',
|
||||
'header.convMetaSteps': '{count}步',
|
||||
'header.hasUpdate': '有新版本',
|
||||
'header.upgradeToVer': '升级 v{ver}',
|
||||
@@ -35,6 +37,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.pending': '待定',
|
||||
'fmt.speedIncomplete': '计时不完整',
|
||||
'fmt.speedCanceled': '已取消',
|
||||
'fmt.speedError': '调用报错',
|
||||
'fmt.speedInterrupted': '连接中断',
|
||||
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
|
||||
'fmt.speedInvalidOutput': '无有效输出',
|
||||
'fmt.speedInconsistent': '耗时数据异常',
|
||||
@@ -55,6 +59,11 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.subAgent': '子代理',
|
||||
'fmt.subBadge': '子{index}',
|
||||
'fmt.subBadgeShort': '子',
|
||||
'fmt.swarmAgent': '蜂群',
|
||||
'fmt.swarmBadge': '蜂{index}',
|
||||
'fmt.swarmBadgeShort': '蜂',
|
||||
'fmt.swarmMonitorHint': '巡检',
|
||||
'fmt.swarmNarratorHint': '旁白',
|
||||
'fmt.sideQuestion': '旁路提问',
|
||||
'fmt.sideBadge': '旁{index}',
|
||||
'fmt.sideBadgeShort': '旁',
|
||||
@@ -68,6 +77,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'capsule.multiZero': '0 运行中',
|
||||
'capsule.multiRunning': '{count} 运行中',
|
||||
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
|
||||
'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂',
|
||||
'capsule.tpsRunning': '生成中',
|
||||
'capsule.tpsIdle': '待命',
|
||||
'capsule.quotaLeft': '余 {pct}%',
|
||||
@@ -88,6 +98,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'multi.empty': '当前暂无在线运行的会话',
|
||||
'multi.allIdle': '全部待命',
|
||||
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
|
||||
'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中',
|
||||
'multi.metaMainOnly': '{main} 个会话运行中',
|
||||
'multi.hereTag': '本窗',
|
||||
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
|
||||
@@ -136,9 +147,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
// Context Window Widget
|
||||
'ctx.followActive': '跟随活跃 ({badge})',
|
||||
'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口',
|
||||
'ctx.expandMore': '+{count} 展开 ▾',
|
||||
'ctx.expandMore': '+{count} 展开',
|
||||
'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊',
|
||||
'ctx.collapse': '收起 ▴',
|
||||
'ctx.collapse': '收起',
|
||||
'ctx.collapseTitle': '折叠多余子代理胶囊',
|
||||
'ctx.ch.assistant': '模型回复',
|
||||
'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参',
|
||||
@@ -184,14 +195,21 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.thinking': '推理中',
|
||||
'live.generating': '生成中',
|
||||
'live.running': '运行中',
|
||||
'live.waiting': '待命中',
|
||||
'live.killed': '已终止',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': '子代理 ({total}) {arrow}',
|
||||
'live.waitingWithSteps': '待命中 ({steps} 步)',
|
||||
'live.killedWithSteps': '已终止 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total}',
|
||||
'live.subToggleIdle': '子代理 ({total})',
|
||||
'live.swarmToggleRunning': '蜂群 {run}/{total}',
|
||||
'live.swarmToggleIdle': '蜂群 ({total})',
|
||||
'live.subCollapseTitle': '点击收起子代理列表',
|
||||
'live.subExpandTitle': '点击展开查看子代理缩略状态',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeCycle': '周期',
|
||||
'cons.rangeToday': '今天',
|
||||
'cons.range24h': '1天',
|
||||
'cons.range7d': '7天',
|
||||
@@ -223,6 +241,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'cons.clientSources': '客户端来源',
|
||||
'cons.monthlyTitle': '月度统计',
|
||||
'cons.monthLabel': '{m}月',
|
||||
'cons.monthFullLabel': '{year}年 {m}月',
|
||||
'cons.hoverModelsHint': '悬停查看模型',
|
||||
'cons.otherModelsCount': '其他 ({count})',
|
||||
'cons.legInput': '输入',
|
||||
'cons.legCache': '缓存',
|
||||
'cons.legOutput': '输出',
|
||||
@@ -280,6 +301,38 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
|
||||
'steps.turnMediaOnly': '[图片/附件提问]',
|
||||
'steps.turnMediaSuffix': '[附图]',
|
||||
'steps.anomalyTag.timeout': '超时{n}',
|
||||
'steps.anomalyTag.rate_limit': '限流{n}',
|
||||
'steps.anomalyTag.capacity': '503×{n}',
|
||||
'steps.anomalyTag.capacitySingle': '503',
|
||||
'steps.anomalyTag.disconnect': '断连{n}',
|
||||
'steps.anomalyTag.upstream': '500×{n}',
|
||||
'steps.anomalyTag.upstreamSingle': '500',
|
||||
'steps.anomalyTag.model_output': '纠偏{n}',
|
||||
'steps.anomalyTag.safety': '过滤{n}',
|
||||
'steps.anomalyTag.auth_or_model': '受限{n}',
|
||||
'steps.anomalyTag.error': '报错{n}',
|
||||
'steps.anomalyTag.mixed': '异常{n}',
|
||||
'steps.anomalyKind.timeout': '流空闲 / 连接超时',
|
||||
'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽',
|
||||
'steps.anomalyKind.capacity': '503 上游算力不足',
|
||||
'steps.anomalyKind.disconnect': '连接中断 / 断流',
|
||||
'steps.anomalyKind.upstream': '上游 5xx 内部错误',
|
||||
'steps.anomalyKind.model_output': '模型输出 / 工具参数无效',
|
||||
'steps.anomalyKind.safety': '内容安全过滤',
|
||||
'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用',
|
||||
'steps.anomalyKind.error': '调用异常',
|
||||
'steps.anomalyKind.canceled': '用户取消',
|
||||
'steps.anomalyStepTitle': '#{step} · 异常 {count} 次',
|
||||
'steps.anomalyDelayPart': '退避 {sec}s',
|
||||
'steps.anomalyTerminalTag': '中止',
|
||||
'steps.anomalyModelTitle': '{model} · 异常 {count} 次',
|
||||
'steps.anomalyModelSub': '涉及 {steps} 步',
|
||||
'steps.anomalyModelKindRow': '{kind}:{count} 次',
|
||||
'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步',
|
||||
'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)',
|
||||
'steps.anomalyFilterLabel': '仅看异常 ({count})',
|
||||
'steps.anomalyFilterAll': '返回全部步骤',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': '步序',
|
||||
@@ -388,6 +441,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.gen.fontLg': '大',
|
||||
'settings.gen.fontXl': '特大',
|
||||
'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高',
|
||||
'settings.gen.modernUi': '新 UI(实验性)',
|
||||
'settings.gen.modernUiOff': '关闭',
|
||||
'settings.gen.modernUiOn': '开启',
|
||||
'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画',
|
||||
'settings.gen.updateTitle': '版本更新',
|
||||
'settings.gen.updateMode': '更新方式',
|
||||
'settings.gen.updateManual': '仅提示新版本,手动更新',
|
||||
@@ -437,14 +494,20 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊',
|
||||
'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写',
|
||||
'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。',
|
||||
'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。',
|
||||
'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效',
|
||||
'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写',
|
||||
'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。',
|
||||
'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载',
|
||||
'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写',
|
||||
'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效',
|
||||
'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效',
|
||||
'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入',
|
||||
'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。',
|
||||
'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。',
|
||||
'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。',
|
||||
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。',
|
||||
'settings.bridge.relaunchBtn': '立即重启并启用挂载',
|
||||
'settings.bridge.relaunchAuthBtn': '授权修补并立即重启',
|
||||
'settings.bridge.relaunchingBtn': '正在重启客户端...',
|
||||
'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试',
|
||||
'settings.bridge.dismissAria': '暂时关闭提示',
|
||||
@@ -552,6 +615,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.invoke_subagent': '调用子代理',
|
||||
'live.act.send_message': '通信子代理',
|
||||
'live.act.manage_subagents': '管理子代理',
|
||||
'live.act.swarm_add': '派生工蜂',
|
||||
'live.act.swarm_title': '命名蜂群',
|
||||
'live.act.swarm_kill': '终止工蜂',
|
||||
'live.act.swarm_model': '切换工蜂模型',
|
||||
'live.act.swarm_channel': '蜂群频道',
|
||||
'live.act.swarm_status': '巡检蜂群',
|
||||
'live.act.post_message': '发布看板',
|
||||
'live.act.read_board': '读取看板',
|
||||
'live.act.swarm_wait': '看板待命',
|
||||
'live.act.manage_task': '后台任务',
|
||||
'live.act.schedule': '定时任务',
|
||||
'live.act.ask_question': '等待用户选择',
|
||||
@@ -562,6 +634,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.compacting': '上下文压缩',
|
||||
'live.act.responding': '正在输出回复',
|
||||
'live.act.waiting_subagent': '等待子代理',
|
||||
'live.act.waiting_swarm': '等待工蜂',
|
||||
'live.act.swarm_waiting': '待命中',
|
||||
'live.act.swarm_killed': '已终止',
|
||||
'live.act.starting': '启动中',
|
||||
'live.act.done': '已完成',
|
||||
'live.act.awaitingApproval': '等待确认 · {label}',
|
||||
|
||||
@@ -29,10 +29,48 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||
syncDocAppearance
|
||||
);
|
||||
|
||||
let hostThemeObserver = null;
|
||||
let colorSchemeMql = null;
|
||||
const onHostThemeChange = () => {
|
||||
syncDocAppearance(telemetryStore.getState().telemetry?.settings);
|
||||
};
|
||||
try {
|
||||
if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
|
||||
hostThemeObserver = new MutationObserver(onHostThemeChange);
|
||||
if (document.documentElement) {
|
||||
hostThemeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'],
|
||||
});
|
||||
}
|
||||
if (document.body) {
|
||||
hostThemeObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'],
|
||||
});
|
||||
}
|
||||
if (document.head) {
|
||||
hostThemeObserver.observe(document.head, {
|
||||
childList: true,
|
||||
characterData: true,
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
|
||||
colorSchemeMql = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
colorSchemeMql?.addEventListener?.('change', onHostThemeChange);
|
||||
}
|
||||
} catch {
|
||||
// ignore observer setup errors in constrained environments
|
||||
}
|
||||
|
||||
const stopPolling = startAsyncTelemetryLoop(2000);
|
||||
return {
|
||||
appInstance,
|
||||
stopPolling: () => {
|
||||
hostThemeObserver?.disconnect?.();
|
||||
colorSchemeMql?.removeEventListener?.('change', onHostThemeChange);
|
||||
unsubAppearance();
|
||||
stopPolling();
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ import { h, patchAttr, patchText } from '../core/domPatch.js';
|
||||
import {
|
||||
formatCachePct,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
getCacheToneClass,
|
||||
@@ -191,7 +192,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
patchText(refs.speedMain, formatSpeedMetric(st.tokPerSec, ' tok/s'));
|
||||
const hasValidSpeed =
|
||||
st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0;
|
||||
const toneCls =
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -54,6 +54,10 @@ td {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button:focus:not(:focus-visible) {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
|
||||
@@ -31,10 +31,10 @@
|
||||
|
||||
.steps-inline-scope-select .select-menu,
|
||||
.steps-inline-model-select .select-menu {
|
||||
left: auto;
|
||||
right: 0;
|
||||
left: 0;
|
||||
right: auto;
|
||||
min-width: 220px;
|
||||
max-width: min(320px, 82vw);
|
||||
max-width: min(320px, calc(100vw - 24px));
|
||||
}
|
||||
|
||||
.session-left {
|
||||
@@ -95,6 +95,7 @@
|
||||
color: var(--text-secondary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition:
|
||||
@@ -104,6 +105,17 @@
|
||||
transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.icon-btn:focus-visible,
|
||||
.pill-tab:focus-visible,
|
||||
.select-trigger:focus-visible,
|
||||
.seg-btn:focus-visible,
|
||||
.btn-primary:focus-visible,
|
||||
.btn-secondary:focus-visible,
|
||||
.btn-ghost-sm:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
@@ -155,6 +167,7 @@
|
||||
min-height: calc(26px * var(--ui-font-scale, 1));
|
||||
padding: 2px var(--space-2);
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-base);
|
||||
@@ -569,17 +582,51 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */
|
||||
/* --- 6. 微边框分段控制器 (Micro-Bezel Sliding Segmented Control) --- */
|
||||
.segmented {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
align-self: flex-start;
|
||||
width: fit-content;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.seg-glider {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: var(--glider-w, 0px);
|
||||
height: var(--glider-h, 0px);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--accent-primary-soft);
|
||||
transform: translate3d(var(--glider-x, 0px), var(--glider-y, 0px), 0);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
will-change: transform, width;
|
||||
}
|
||||
|
||||
.segmented.has-glider .seg-glider {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.seg-glider.is-ready {
|
||||
transition:
|
||||
transform var(--dur-fast) var(--ease-fast),
|
||||
width var(--dur-fast) var(--ease-fast),
|
||||
height var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.seg-btn {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -587,6 +634,7 @@
|
||||
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||
padding: 2px 7px;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-md);
|
||||
@@ -608,6 +656,17 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.segmented.has-glider .seg-btn:hover {
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.segmented.has-glider .seg-btn.is-active {
|
||||
background: transparent;
|
||||
color: var(--accent-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
|
||||
@@ -0,0 +1,861 @@
|
||||
/*
|
||||
* 实验性现代化无边框主题与流畅动画样式层 (modern-ui.css).
|
||||
* 仅在根容器或 Shadow Host 携带 [data-modern-ui="true"] 时激活:
|
||||
* 1. 移除绝大部分面板、矩阵、表格、徽章、按钮、输入框与悬浮窗的 1px 线框及分隔线;
|
||||
* 2. 面板内部子数据块(如版本更新价格表/当前版本、消费矩阵指标格、汇总折线区)保持透明扁平,绝不套叠二层背景卡片;
|
||||
* 3. 区分深色与浅色极性 ([data-color-scheme="light" | "dark"]):
|
||||
* - 深色模式采用柔和提亮顶层卡片与轻薄半透雾面滑槽(绝不混入重黑色块);
|
||||
* - 浅色模式采用微凉白瓷画布 (#f7f9fb) + 纯白悬浮顶层卡片 (#ffffff) + 纯白立体滑块;
|
||||
* 4. 全局分段切换器 (.segmented / .long-pill-nav / .settings-thirdnav-bar) 按内容宽度贴合滑动。
|
||||
*/
|
||||
|
||||
:root[data-modern-ui="true"],
|
||||
:host([data-modern-ui="true"]),
|
||||
[data-modern-ui="true"] {
|
||||
--radius-sm: 10px;
|
||||
--radius-xs: 7px;
|
||||
--ease-modern: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
--dur-fast: 180ms;
|
||||
--dur-normal: 240ms;
|
||||
--modern-canvas-bg: var(--surface-bg);
|
||||
--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-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent));
|
||||
--modern-card-shadow: none;
|
||||
--modern-nav-track-bg: var(--modern-surface-card);
|
||||
--modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent);
|
||||
--modern-glider-bg: color-mix(in srgb, var(--accent-primary) 17%, color-mix(in srgb, var(--text-primary) 4%, transparent));
|
||||
--modern-glider-shadow: none;
|
||||
--modern-progress-track: color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
--modern-stripe-bg: rgb(255 255 255 / 0.022);
|
||||
--text-secondary: color-mix(in srgb, var(--text-primary) 80%, transparent);
|
||||
--text-muted: color-mix(in srgb, var(--text-primary) 62%, transparent);
|
||||
--modern-active-accent: color-mix(in srgb, var(--accent-primary) 86%, var(--text-primary) 14%);
|
||||
--shadow-popover: 0 10px 28px rgb(0 0 0 / 0.28), 0 2px 8px rgb(0 0 0 / 0.14);
|
||||
--shadow-overlay: 0 22px 52px rgb(0 0 0 / 0.42), 0 4px 16px rgb(0 0 0 / 0.20);
|
||||
}
|
||||
|
||||
:root[data-modern-ui="true"][data-color-scheme="light"],
|
||||
:host([data-modern-ui="true"][data-color-scheme="light"]),
|
||||
[data-modern-ui="true"][data-color-scheme="light"] {
|
||||
--modern-canvas-bg: color-mix(in srgb, var(--surface-bg) 95.5%, hsl(216 34% 48%) 4.5%);
|
||||
--modern-surface-card: #ffffff;
|
||||
--modern-surface-subtle: hsl(216 42% 97.2%);
|
||||
--modern-surface-hover: hsl(216 56% 94.4%);
|
||||
--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-inline-track-bg: hsl(216 32% 96.2%);
|
||||
--modern-glider-bg: #ffffff;
|
||||
--modern-glider-shadow: 0 1px 2px rgb(15 23 42 / 0.08), 0 1px 1px rgb(15 23 42 / 0.04);
|
||||
--modern-progress-track: hsl(216 28% 93.4%);
|
||||
--modern-stripe-bg: hsl(216 40% 97.8%);
|
||||
--text-secondary: color-mix(in srgb, var(--text-primary) 72%, transparent);
|
||||
--text-muted: color-mix(in srgb, var(--text-primary) 58%, transparent);
|
||||
--modern-active-accent: var(--accent-primary);
|
||||
--shadow-popover: 0 10px 28px rgb(15 23 42 / 0.10), 0 2px 8px rgb(15 23 42 / 0.05);
|
||||
--shadow-overlay: 0 20px 48px rgb(15 23 42 / 0.14), 0 4px 14px rgb(15 23 42 / 0.06);
|
||||
}
|
||||
|
||||
@keyframes anim-modern-view-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate3d(0, 5px, 0);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-pop-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-4px) scale(0.975);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-pop-in-up {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px) scale(0.975);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-tip-fade {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-step-row-in {
|
||||
0% {
|
||||
opacity: 0;
|
||||
background-color: transparent;
|
||||
animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
20% {
|
||||
opacity: 0.84;
|
||||
background-color: color-mix(in srgb, var(--accent-primary) 7.5%, transparent);
|
||||
animation-timing-function: ease-out;
|
||||
}
|
||||
36% {
|
||||
opacity: 1;
|
||||
background-color: color-mix(in srgb, var(--accent-primary) 6%, transparent);
|
||||
animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
70% {
|
||||
opacity: 1;
|
||||
background-color: color-mix(in srgb, var(--accent-primary) 2%, transparent);
|
||||
animation-timing-function: ease-out;
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
background-color: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-step-cell-in {
|
||||
from {
|
||||
transform: translate3d(0, -3px, 0);
|
||||
}
|
||||
to {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes anim-modern-pill-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- 1. 外壳画布、顶层卡片与按量贴合滑动轨道 (Canvas, Top-Level Cards & Fit-Content Sliding Tracks) --- */
|
||||
html[data-standalone="true"][data-modern-ui="true"] #app-root {
|
||||
min-height: 100dvh;
|
||||
background: var(--modern-canvas-bg);
|
||||
}
|
||||
|
||||
html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
border-left: none;
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .app-shell {
|
||||
background: var(--modern-canvas-bg);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .view-pane {
|
||||
animation: anim-modern-view-in 220ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .panel,
|
||||
[data-modern-ui="true"] .session-header {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--modern-card-shadow);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .panel .panel {
|
||||
background: var(--modern-surface-subtle);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .long-pill-nav,
|
||||
[data-modern-ui="true"] .settings-thirdnav-bar {
|
||||
border: none;
|
||||
background: var(--modern-nav-track-bg);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .settings-subnav-bar {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .segmented {
|
||||
padding: 2px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--modern-inline-track-bg);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .settings-subnav-bar .segmented {
|
||||
padding: 3px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--modern-nav-track-bg);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .pill-glider {
|
||||
border: none;
|
||||
background: var(--modern-glider-bg);
|
||||
box-shadow: var(--modern-glider-shadow);
|
||||
transition: transform 230ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .seg-glider {
|
||||
border: none;
|
||||
background: var(--modern-glider-bg);
|
||||
box-shadow: var(--modern-glider-shadow);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .seg-glider.is-ready {
|
||||
transition:
|
||||
transform 220ms var(--ease-modern),
|
||||
width 220ms var(--ease-modern),
|
||||
height 180ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .segmented:not(.has-glider) .seg-btn.is-active {
|
||||
background: var(--modern-glider-bg);
|
||||
box-shadow: var(--modern-glider-shadow);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .thirdnav-glider {
|
||||
border: none;
|
||||
background: var(--modern-glider-bg);
|
||||
box-shadow: var(--modern-glider-shadow);
|
||||
transition: transform 220ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .pill-tab,
|
||||
[data-modern-ui="true"] .seg-btn,
|
||||
[data-modern-ui="true"] .structure-thirdnav-btn {
|
||||
transition:
|
||||
color 160ms var(--ease-modern),
|
||||
transform 140ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .pill-tab:active,
|
||||
[data-modern-ui="true"] .seg-btn:active,
|
||||
[data-modern-ui="true"] .structure-thirdnav-btn:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
/* --- 2. 按钮、状态标签、代理徽章与胶囊全面去边框 --- */
|
||||
[data-modern-ui="true"] .status-tag,
|
||||
[data-modern-ui="true"] .status-tag.state-running,
|
||||
[data-modern-ui="true"] .status-tag.state-synced,
|
||||
[data-modern-ui="true"] .status-tag.state-warn,
|
||||
[data-modern-ui="true"] .update-badge-btn,
|
||||
[data-modern-ui="true"] .wm-update-btn,
|
||||
[data-modern-ui="true"] .wm-hover-update-bar,
|
||||
:host([data-modern-ui="true"]) .wm-update-btn {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .icon-btn,
|
||||
[data-modern-ui="true"] .btn-secondary,
|
||||
[data-modern-ui="true"] .btn-ghost-sm,
|
||||
[data-modern-ui="true"] .live-sub-toggle,
|
||||
[data-modern-ui="true"] .ctx-agent-pill,
|
||||
[data-modern-ui="true"] .theme-host-chip,
|
||||
[data-modern-ui="true"] .collapsible-badge {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
transition:
|
||||
background-color 160ms var(--ease-modern),
|
||||
color 160ms var(--ease-modern),
|
||||
transform 140ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .session-header .icon-btn {
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .icon-btn:hover,
|
||||
[data-modern-ui="true"] .btn-secondary:hover:not(:disabled),
|
||||
[data-modern-ui="true"] .btn-ghost-sm:hover:not(:disabled),
|
||||
[data-modern-ui="true"] .live-sub-toggle:hover,
|
||||
[data-modern-ui="true"] .ctx-agent-pill:hover,
|
||||
[data-modern-ui="true"] .theme-host-chip:hover {
|
||||
border: none;
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .pill-tab.is-active,
|
||||
[data-modern-ui="true"] .pill-tab.is-active .svg-icon,
|
||||
[data-modern-ui="true"] .pill-tab.is-active .pill-tab-badge,
|
||||
[data-modern-ui="true"] .seg-btn.is-active,
|
||||
[data-modern-ui="true"] .structure-thirdnav-btn.is-active {
|
||||
color: var(--modern-active-accent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-toggle.is-expanded,
|
||||
[data-modern-ui="true"] .ctx-agent-pill.is-active,
|
||||
[data-modern-ui="true"] .theme-host-chip.is-active {
|
||||
border: none;
|
||||
color: var(--modern-active-accent);
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ctx-agent-pill.is-more-toggle {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .btn-ghost-sm:disabled {
|
||||
opacity: 0.54;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-row.is-done {
|
||||
opacity: 0.82;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-row.is-waiting-sub {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-row.is-killed-sub {
|
||||
opacity: 0.68;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-toggle-chevron,
|
||||
[data-modern-ui="true"] .ctx-toggle-chevron {
|
||||
transition: transform 200ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ctx-agent-pill.is-pill-entering {
|
||||
animation: anim-modern-pill-in 180ms ease-out both;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ctx-agent-pill.is-pill-collapsing {
|
||||
opacity: 0;
|
||||
transition: opacity 150ms ease-out;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .btn-primary {
|
||||
border: none;
|
||||
transition:
|
||||
opacity 160ms var(--ease-modern),
|
||||
transform 140ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .agent-badge,
|
||||
[data-modern-ui="true"] .agent-badge.is-clickable:hover,
|
||||
[data-modern-ui="true"] .step-anomaly-tag {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .agent-badge:not(.badge-main):not([class*="badge-sub-"]) {
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
/* --- 3. 实时概览矩阵与任务卡片:顶层独立卡片,面板内子块绝不叠套背景 --- */
|
||||
[data-modern-ui="true"] .telemetry-matrix {
|
||||
border: none;
|
||||
background: transparent;
|
||||
gap: 6px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .matrix-cell {
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--modern-card-shadow);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 8px 10px;
|
||||
transition: background-color 160ms var(--ease-modern);
|
||||
}
|
||||
|
||||
/* 面板内的双栏信息项(如版本更新中的「价格表 / 当前版本」)不套二层背景 */
|
||||
[data-modern-ui="true"] .dual-grid > .matrix-cell {
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
/* 结构页预览画布内的测速卡与任务卡保持轻微层次以呈现真实预览布局 */
|
||||
[data-modern-ui="true"] .structure-preview-canvas .matrix-cell {
|
||||
background: var(--modern-surface-subtle);
|
||||
box-shadow: none;
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-task-card {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--modern-card-shadow);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .structure-preview-canvas .live-task-card {
|
||||
background: var(--modern-surface-subtle);
|
||||
box-shadow: none;
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-scroll-host {
|
||||
border-top: none;
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .live-sub-scroll-host.is-sub-animating > .scrollbar-rail {
|
||||
opacity: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .progress-track {
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--modern-progress-track);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .progress-track.ctx-segment-meter {
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--modern-progress-track);
|
||||
}
|
||||
|
||||
/* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */
|
||||
[data-modern-ui="true"] .cons-box,
|
||||
[data-modern-ui="true"] .cons-custom-range-bar {
|
||||
border: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .dt-popover .icon-btn {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .dt-popover .icon-btn:hover {
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-unified-matrix {
|
||||
border: none;
|
||||
background: transparent;
|
||||
gap: 10px 12px;
|
||||
padding: 2px 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-split-3 {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-matrix-bottom {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-col,
|
||||
[data-modern-ui="true"] .cons-col.is-bordered-col {
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-peak-pill,
|
||||
[data-modern-ui="true"] .trend-hm-cell.lv-0,
|
||||
[data-modern-ui="true"] .trend-hm-swatch.lv-0 {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tip-sub,
|
||||
[data-modern-ui="true"] .trend-tip-anomaly,
|
||||
[data-modern-ui="true"] .cons-pop-models {
|
||||
border-top: none;
|
||||
padding-top: 3px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
|
||||
[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar,
|
||||
[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack,
|
||||
[data-modern-ui="true"] .month-col.is-hovered .month-stack {
|
||||
box-shadow: none;
|
||||
filter: brightness(1.06);
|
||||
transform: scaleY(1.06);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-source-model-bar,
|
||||
[data-modern-ui="true"] .month-stack {
|
||||
transition:
|
||||
height var(--dur-normal) var(--ease-modern),
|
||||
transform 150ms var(--ease-modern),
|
||||
filter 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
/* --- 5. 调用记录表格与模型分析区去横线边框且不套内层背景 --- */
|
||||
[data-modern-ui="true"] .table-scroll-host {
|
||||
border-top: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .table-viewport,
|
||||
[data-modern-ui="true"] .data-table th {
|
||||
background: var(--modern-surface-card);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table th,
|
||||
[data-modern-ui="true"] .data-table td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer) {
|
||||
transition: background-color 130ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering {
|
||||
animation: anim-modern-step-row-in 850ms cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering > td {
|
||||
animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even {
|
||||
background: var(--modern-stripe-bg);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even:hover {
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[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.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 19%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger,
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-danger:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 14%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 21%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
|
||||
[data-modern-ui="true"] .steps-inline-model-select .select-trigger,
|
||||
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .sstep-card,
|
||||
[data-modern-ui="true"] .smodel-empty {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding-left: 2px;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .smodel-card {
|
||||
border: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .step-table-preview-host {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .smodel-card:hover {
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .smodel-card.is-fit-active {
|
||||
border: none;
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar,
|
||||
[data-modern-ui="true"] .steps-anomaly-strip {
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--metric-warn-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar {
|
||||
margin: 4px 2px 2px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .sstep-anomaly-dot,
|
||||
[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--modern-surface-card);
|
||||
}
|
||||
|
||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||
[data-modern-ui="true"] .collapsible-body,
|
||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||
[data-modern-ui="true"] .settings-account-entry,
|
||||
[data-modern-ui="true"] .dt-time-row {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .settings-divider {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .editable-slot-row,
|
||||
[data-modern-ui="true"] .editable-slot-empty,
|
||||
[data-modern-ui="true"] .structure-preview-empty,
|
||||
[data-modern-ui="true"] .preview-sidebar-note,
|
||||
[data-modern-ui="true"] .preview-capsule-bar,
|
||||
[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn,
|
||||
[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn,
|
||||
[data-modern-ui="true"] .preview-composer-chip {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .slot-add-btn,
|
||||
[data-modern-ui="true"] .settings-bridge-relaunch-btn {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .ctx-risk-mask,
|
||||
[data-modern-ui="true"] .settings-bridge-notice,
|
||||
[data-modern-ui="true"] .settings-bridge-notice.is-restart {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .number-input,
|
||||
[data-modern-ui="true"] .dt-trigger,
|
||||
[data-modern-ui="true"] .dt-mini-step,
|
||||
[data-modern-ui="true"] .settings-text-input,
|
||||
[data-modern-ui="true"] .settings-account-form input {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
transition:
|
||||
background-color 150ms var(--ease-modern),
|
||||
box-shadow 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .num-step-btn {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .num-field {
|
||||
border-left: none;
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .number-input:focus-within,
|
||||
[data-modern-ui="true"] .settings-text-input:focus,
|
||||
[data-modern-ui="true"] .settings-account-form input:focus {
|
||||
border: none;
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
||||
}
|
||||
|
||||
/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */
|
||||
[data-modern-ui="true"] .select-menu,
|
||||
[data-modern-ui="true"] .dt-popover,
|
||||
[data-modern-ui="true"] .sstep-tooltip {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--shadow-popover);
|
||||
animation: anim-modern-pop-in 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-menu.is-above,
|
||||
[data-modern-ui="true"] .dt-popover.is-above {
|
||||
animation-name: anim-modern-pop-in-up;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip,
|
||||
[data-modern-ui="true"] .cons-breakdown-popover,
|
||||
[data-modern-ui="true"] .turn-prompt-tip,
|
||||
[data-modern-ui="true"] .step-anomaly-tip {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--shadow-popover);
|
||||
animation: anim-modern-tip-fade 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .step-anomaly-tip-list,
|
||||
[data-modern-ui="true"] .step-anomaly-tip-hint {
|
||||
border-top-color: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
||||
top: 2px;
|
||||
bottom: auto;
|
||||
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip.is-tracking {
|
||||
transition:
|
||||
left 150ms var(--ease-modern),
|
||||
top 150ms var(--ease-modern),
|
||||
bottom 150ms var(--ease-modern),
|
||||
transform 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-hover-dot.is-tracking {
|
||||
transition:
|
||||
cx 150ms var(--ease-modern),
|
||||
cy 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-breakdown-popover.is-tracking,
|
||||
[data-modern-ui="true"] .turn-prompt-tip.is-tracking {
|
||||
transition:
|
||||
left 150ms var(--ease-modern),
|
||||
top 150ms var(--ease-modern),
|
||||
transform 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"].wm-popover-panel,
|
||||
[data-modern-ui="true"].wm-hover-tip,
|
||||
[data-modern-ui="true"].wm-multi-panel,
|
||||
:host([data-modern-ui="true"]) .wm-popover-panel,
|
||||
:host([data-modern-ui="true"]) .wm-hover-tip,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel {
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: var(--modern-canvas-bg);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
animation: anim-modern-pop-in 200ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"].wm-popover-panel.is-above,
|
||||
[data-modern-ui="true"].wm-hover-tip.is-above,
|
||||
[data-modern-ui="true"].wm-multi-panel.is-above,
|
||||
:host([data-modern-ui="true"]) .wm-popover-panel.is-above,
|
||||
:host([data-modern-ui="true"]) .wm-hover-tip.is-above,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel.is-above {
|
||||
animation-name: anim-modern-pop-in-up;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .wm-multi-header,
|
||||
:host([data-modern-ui="true"]) .wm-multi-header,
|
||||
[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card {
|
||||
border: none;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"].wm-multi-panel,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel {
|
||||
background: var(--modern-surface-card);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"].wm-multi-panel .live-activity-list,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel .live-activity-list {
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"].wm-multi-panel .live-task-card,
|
||||
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card {
|
||||
padding: 10px 2px;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
/* --- 8. 顶栏胶囊老虎机滚动数字 (0.15s) 与语义色平滑渐变 (0.1s),严格限定实验性新 UI --- */
|
||||
:host([data-modern-ui="true"]) .wm-cap-slot,
|
||||
:host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text,
|
||||
:host([data-modern-ui="true"]) .wm-multi-label,
|
||||
[data-modern-ui="true"] .wm-cap-slot,
|
||||
[data-modern-ui="true"] .wm-cap-slot .wm-slot-text,
|
||||
[data-modern-ui="true"] .wm-multi-label {
|
||||
transition: color 100ms ease-out;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-ring-fill,
|
||||
[data-modern-ui="true"] .wm-ring-fill {
|
||||
transition:
|
||||
stroke-dashoffset var(--dur-normal) var(--ease-modern),
|
||||
stroke 100ms ease-out;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-multi-dot,
|
||||
[data-modern-ui="true"] .wm-multi-dot {
|
||||
transition: background-color 100ms ease-out;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-slot-text[data-od-active="1"],
|
||||
:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-slot-text[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-digit,
|
||||
[data-modern-ui="true"] .wm-od-digit {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
overflow: hidden;
|
||||
vertical-align: top;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-track,
|
||||
[data-modern-ui="true"] .wm-od-track {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
transform: translate3d(0, calc(var(--od-val, 0) * -18px), 0);
|
||||
transition: transform 150ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-cell,
|
||||
[data-modern-ui="true"] .wm-od-cell {
|
||||
display: block;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-static,
|
||||
[data-modern-ui="true"] .wm-od-static {
|
||||
display: inline-block;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
vertical-align: top;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:host([data-modern-ui="true"]) .wm-od-track,
|
||||
[data-modern-ui="true"] .wm-od-track,
|
||||
:host([data-modern-ui="true"]) .wm-cap-slot,
|
||||
:host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text,
|
||||
:host([data-modern-ui="true"]) .wm-multi-label,
|
||||
:host([data-modern-ui="true"]) .wm-ring-fill,
|
||||
:host([data-modern-ui="true"]) .wm-multi-dot,
|
||||
[data-modern-ui="true"] .wm-cap-slot,
|
||||
[data-modern-ui="true"] .wm-cap-slot .wm-slot-text,
|
||||
[data-modern-ui="true"] .wm-multi-label,
|
||||
[data-modern-ui="true"] .wm-ring-fill,
|
||||
[data-modern-ui="true"] .wm-multi-dot {
|
||||
transition: none !important;
|
||||
}
|
||||
}
|
||||
@@ -89,16 +89,16 @@
|
||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent);
|
||||
|
||||
/* Context Window 10-Channel Palette */
|
||||
--ctx-assistant: hsl(217 82% 54%);
|
||||
--ctx-tool-results: hsl(192 82% 43%);
|
||||
--ctx-user-input: hsl(245 72% 62%);
|
||||
--ctx-subagent-msg: hsl(280 70% 58%);
|
||||
--ctx-checkpoint: hsl(38 90% 50%);
|
||||
--ctx-system-tools: hsl(22 86% 50%);
|
||||
--ctx-mcp-tools: hsl(316 72% 54%);
|
||||
--ctx-skills: hsl(145 64% 38%);
|
||||
--ctx-system-prompt: hsl(168 72% 40%);
|
||||
--ctx-user-rules: hsl(346 78% 54%);
|
||||
--ctx-assistant: hsl(215 62% 52%);
|
||||
--ctx-tool-results: hsl(172 68% 40%);
|
||||
--ctx-user-input: hsl(256 76% 62%);
|
||||
--ctx-subagent-msg: hsl(286 64% 58%);
|
||||
--ctx-checkpoint: hsl(42 90% 49%);
|
||||
--ctx-system-tools: hsl(24 86% 52%);
|
||||
--ctx-mcp-tools: hsl(336 78% 58%);
|
||||
--ctx-skills: hsl(150 60% 41%);
|
||||
--ctx-system-prompt: hsl(214 26% 54%);
|
||||
--ctx-user-rules: hsl(352 78% 56%);
|
||||
|
||||
/* Legacy 4-Channel Palette (retained for compatibility) */
|
||||
--ctx-cached: hsl(217 82% 51%);
|
||||
@@ -123,6 +123,21 @@
|
||||
--space-5: 12px;
|
||||
}
|
||||
|
||||
:root[data-color-scheme="dark"],
|
||||
:host([data-color-scheme="dark"]),
|
||||
[data-color-scheme="dark"] {
|
||||
--ctx-assistant: hsl(216 30% 58%);
|
||||
--ctx-tool-results: hsl(168 72% 54%);
|
||||
--ctx-user-input: hsl(258 86% 73%);
|
||||
--ctx-subagent-msg: hsl(288 72% 70%);
|
||||
--ctx-checkpoint: hsl(43 94% 58%);
|
||||
--ctx-system-tools: hsl(24 90% 62%);
|
||||
--ctx-mcp-tools: hsl(338 82% 69%);
|
||||
--ctx-skills: hsl(150 64% 55%);
|
||||
--ctx-system-prompt: hsl(214 28% 68%);
|
||||
--ctx-user-rules: hsl(354 82% 66%);
|
||||
}
|
||||
|
||||
:root[data-font-scale="sm"],
|
||||
:host([data-font-scale="sm"]),
|
||||
[data-font-scale="sm"] {
|
||||
|
||||
@@ -14,6 +14,25 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cons-overview-head .segmented {
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.cons-overview-head .seg-btn {
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.cons-custom-range-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 2px 0 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.cons-badge {
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
@@ -157,15 +176,28 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:root,
|
||||
:host {
|
||||
--cons-other-seg: color-mix(in srgb, var(--text-secondary) 46%, var(--surface-panel));
|
||||
}
|
||||
|
||||
.dot-swatch.seg-input { background: var(--ctx-input); }
|
||||
.dot-swatch.seg-cached { background: var(--ctx-cached); }
|
||||
.dot-swatch.seg-output { background: var(--ctx-output); }
|
||||
.dot-swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
.dot-swatch.cons-model-dot { background: var(--dot-color, var(--accent-primary)); }
|
||||
|
||||
.progress-seg.cons-model-seg,
|
||||
.month-seg.cons-model-seg {
|
||||
background-color: var(--seg-color, var(--accent-primary));
|
||||
}
|
||||
|
||||
/* --- 3. 热门模型与数据来源行头部对齐 (Popular Models & Sources Row Header) --- */
|
||||
.cons-row-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||
line-height: 1.3;
|
||||
font-size: var(--fs-base);
|
||||
@@ -173,6 +205,18 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-row-title-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-title-model-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-row-metrics {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -238,7 +282,7 @@
|
||||
|
||||
.trend-svg {
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
height: 184px;
|
||||
display: block;
|
||||
overflow: visible;
|
||||
}
|
||||
@@ -301,19 +345,19 @@
|
||||
|
||||
.trend-tooltip {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
top: 2px;
|
||||
left: var(--tip-x, 50%);
|
||||
transform: translateX(var(--tip-shift, -50%));
|
||||
width: max-content;
|
||||
min-width: 152px;
|
||||
min-width: 196px;
|
||||
max-width: min(320px, calc(100% - 8px));
|
||||
padding: 5px 9px;
|
||||
padding: 6px 10px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: none;
|
||||
box-shadow: var(--shadow-popover);
|
||||
pointer-events: none;
|
||||
z-index: 15;
|
||||
z-index: 25;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
@@ -378,14 +422,19 @@
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-line-low {
|
||||
top: auto;
|
||||
bottom: 20px;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-hm-top {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
top: auto;
|
||||
bottom: calc(100% + 6px);
|
||||
}
|
||||
|
||||
.trend-tooltip.is-hm-bottom {
|
||||
top: auto;
|
||||
bottom: 0;
|
||||
top: calc(100% + 6px);
|
||||
bottom: auto;
|
||||
}
|
||||
|
||||
.trend-x-axis {
|
||||
@@ -426,8 +475,8 @@
|
||||
.trend-heatmap-stage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding-top: 2px;
|
||||
gap: 8px;
|
||||
padding-top: 4px;
|
||||
width: 100%;
|
||||
user-select: none;
|
||||
}
|
||||
@@ -435,7 +484,7 @@
|
||||
.trend-heatmap-body {
|
||||
--hm-weeks: 26;
|
||||
--hm-gap: 2px;
|
||||
--hm-cell: 9px;
|
||||
--hm-cell: 12px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
@@ -446,9 +495,9 @@
|
||||
@supports (width: 1cqi) {
|
||||
.trend-heatmap-body {
|
||||
--hm-cell: clamp(
|
||||
6.5px,
|
||||
11px,
|
||||
calc((100cqi - 18px - (var(--hm-weeks) - 1) * var(--hm-gap)) / var(--hm-weeks)),
|
||||
18px
|
||||
20px
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -620,11 +669,214 @@
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-view-stage {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cons-item-foot strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cons-source-row {
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.cons-source-bar-hit {
|
||||
padding: 5px 0;
|
||||
margin: -5px 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-source-bar-hit:hover .cons-source-model-bar,
|
||||
.cons-source-bar-hit.is-hovered .cons-source-model-bar {
|
||||
box-shadow: 0 0 0 1px var(--border-strong);
|
||||
}
|
||||
|
||||
.cons-source-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
min-height: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cons-source-top-models {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-source-top-models[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.cons-source-top-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.cons-source-top-item:first-child {
|
||||
flex-shrink: 0.5;
|
||||
}
|
||||
|
||||
.cons-source-top-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-source-top-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
color: var(--text-secondary);
|
||||
transition: color 120ms ease;
|
||||
}
|
||||
|
||||
.cons-source-top-models:hover .cons-source-top-name,
|
||||
.cons-source-top-models.is-hovered .cons-source-top-name {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-source-top-pct {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cons-source-foot > .cons-calls-stat {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@container (max-width: 340px) {
|
||||
.cons-source-top-item:nth-child(n + 3) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 210px) {
|
||||
.cons-source-top-item:nth-child(n + 2) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.month-col.is-interactive {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.month-col.is-interactive:hover .month-stack,
|
||||
.month-col.is-hovered .month-stack {
|
||||
box-shadow: 0 0 0 1px var(--text-primary);
|
||||
}
|
||||
|
||||
.month-col.is-interactive:hover .month-label,
|
||||
.month-col.is-hovered .month-label {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 共享模型构成悬浮详情卡 (Client Sources & Monthly Breakdown Popover) --- */
|
||||
.cons-breakdown-popover {
|
||||
position: absolute;
|
||||
left: var(--pop-x, 8px);
|
||||
top: var(--pop-y, 8px);
|
||||
width: max-content;
|
||||
min-width: 196px;
|
||||
max-width: min(310px, calc(100% - 16px));
|
||||
padding: 6px 10px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: var(--shadow-popover);
|
||||
pointer-events: none;
|
||||
z-index: 30;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.cons-pop-models {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
padding-top: 4px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.cons-pop-model-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.cons-pop-model-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-pop-model-name {
|
||||
max-width: 156px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-pop-model-row.is-other .cons-pop-model-name {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cons-pop-model-right {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-tok {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cons-pop-model-pct {
|
||||
min-width: 40px;
|
||||
text-align: right;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
|
||||
.monthly-grid {
|
||||
display: grid;
|
||||
|
||||
@@ -172,6 +172,7 @@
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
@@ -180,6 +181,15 @@
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.live-sub-toggle-chevron {
|
||||
flex-shrink: 0;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.live-sub-toggle.is-expanded .live-sub-toggle-chevron {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
.live-sub-toggle:hover {
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-primary);
|
||||
@@ -260,10 +270,7 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-sub-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
.live-sub-scroll-host {
|
||||
padding-top: 9px;
|
||||
margin-top: 3px;
|
||||
margin-left: 18px;
|
||||
@@ -271,6 +278,25 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.live-sub-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-right: 8px;
|
||||
min-width: 0;
|
||||
max-height: 196px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.live-sub-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -286,6 +312,14 @@
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.live-sub-row.is-waiting-sub {
|
||||
opacity: 0.86;
|
||||
}
|
||||
|
||||
.live-sub-row.is-killed-sub {
|
||||
opacity: 0.56;
|
||||
}
|
||||
|
||||
.live-sub-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -424,6 +458,48 @@
|
||||
width var(--dur-normal) var(--ease-fast) 0.05s;
|
||||
}
|
||||
|
||||
/* 块状微圆角风格上下文进度条(保持 6px 紧凑高度 + 色块间 2px 轻间隙 + 每段 2px 边缘圆润处理) */
|
||||
.progress-track.ctx-segment-meter {
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.progress-track.ctx-segment-meter .progress-seg {
|
||||
flex: 0 1 auto;
|
||||
box-sizing: border-box;
|
||||
width: 0%;
|
||||
min-width: 0;
|
||||
margin-left: 0;
|
||||
border-radius: 2px;
|
||||
transition:
|
||||
background-color 0.08s ease,
|
||||
width var(--dur-normal) var(--ease-fast),
|
||||
margin-left var(--dur-fast) var(--ease-fast),
|
||||
filter 120ms ease;
|
||||
}
|
||||
|
||||
.progress-track.ctx-segment-meter.is-reordering .progress-seg {
|
||||
transition:
|
||||
background-color 0.05s ease,
|
||||
width var(--dur-normal) var(--ease-fast) 0.05s,
|
||||
margin-left var(--dur-fast) var(--ease-fast),
|
||||
filter 120ms ease;
|
||||
}
|
||||
|
||||
.progress-track.ctx-segment-meter .progress-seg.is-active {
|
||||
width: var(--seg-w, 0%);
|
||||
min-width: 3px;
|
||||
}
|
||||
|
||||
.progress-track.ctx-segment-meter .progress-seg.is-active.has-sep {
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
.progress-track.ctx-segment-meter .progress-seg.is-active:hover {
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
|
||||
.progress-seg.seg-assistant {
|
||||
background-color: var(--ctx-assistant);
|
||||
}
|
||||
@@ -537,7 +613,7 @@
|
||||
/* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */
|
||||
.ctx-inspector-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
@@ -559,6 +635,7 @@
|
||||
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
outline: none;
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-md);
|
||||
@@ -593,6 +670,14 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ctx-toggle-chevron {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-more-toggle.is-expanded .ctx-toggle-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.panel-title .agent-badge {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
align-self: stretch;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
@@ -44,13 +45,37 @@
|
||||
|
||||
/* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */
|
||||
.settings-thirdnav-bar {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
padding: 3px;
|
||||
gap: 0;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
flex-shrink: 0;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thirdnav-glider {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
bottom: 3px;
|
||||
left: 3px;
|
||||
width: calc((100% - 6px) / 4);
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
border-radius: var(--radius-xs);
|
||||
transform: translate3d(calc(var(--active-third-index, 0) * 100%), 0, 0);
|
||||
transition: transform var(--dur-fast) var(--ease-fast);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -58,29 +83,28 @@
|
||||
min-height: calc(25px * var(--ui-font-scale, 1));
|
||||
min-width: 0;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border: none;
|
||||
outline: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--surface-subtle);
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
transition: color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent);
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn:hover {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn.is-active {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
|
||||
.table-viewport.is-step-table {
|
||||
overflow-x: auto;
|
||||
overflow-anchor: none;
|
||||
}
|
||||
|
||||
/* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */
|
||||
@@ -72,10 +73,44 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
.data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.data-table tbody tr.step-vspacer,
|
||||
.data-table tbody tr.step-vspacer:hover,
|
||||
.data-table tbody tr.step-vsizer,
|
||||
.data-table tbody tr.step-vsizer:hover {
|
||||
background: transparent !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.data-table tbody tr.step-vsizer {
|
||||
visibility: hidden;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.data-table tbody tr.step-vsizer td {
|
||||
padding-top: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
border: none !important;
|
||||
line-height: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.step-vsizer-inner {
|
||||
display: block;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table tbody tr.step-vspacer td.step-vspacer-cell {
|
||||
padding: 0 !important;
|
||||
border: none !important;
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
.step-model-cell {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
@@ -260,6 +295,248 @@
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */
|
||||
.data-table tbody tr.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 18%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-warn);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-warn);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 13%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 20%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-danger);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.step-anomaly-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
margin-left: 4px;
|
||||
padding: 0 3.5px;
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
border-radius: 3px;
|
||||
color: var(--metric-warn);
|
||||
background: var(--metric-warn-soft);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 34%, transparent);
|
||||
cursor: help;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-anomaly-tag.is-danger {
|
||||
color: var(--metric-danger);
|
||||
background: var(--metric-danger-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 36%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tag[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag {
|
||||
margin-left: 0;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 22%, transparent);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag.is-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 22%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tip {
|
||||
position: absolute;
|
||||
z-index: 46;
|
||||
max-width: min(300px, calc(100% - 16px));
|
||||
min-width: 176px;
|
||||
padding: 7px 9px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.38;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-strong));
|
||||
border-radius: var(--radius-xs);
|
||||
box-shadow: var(--shadow-popover);
|
||||
pointer-events: none;
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger {
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong));
|
||||
}
|
||||
|
||||
.step-anomaly-tip[hidden],
|
||||
.step-anomaly-tip-sub[hidden],
|
||||
.step-anomaly-tip-list[hidden],
|
||||
.step-anomaly-tip-hint[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-title {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger .step-anomaly-tip-title {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-sub {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row {
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-detail {
|
||||
font-size: var(--fs-2xs);
|
||||
line-height: 1.35;
|
||||
color: var(--text-muted);
|
||||
word-break: break-word;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-hint {
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--text-muted);
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
background: color-mix(in srgb, var(--metric-warn) 8%, var(--surface-panel));
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-label {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-clear {
|
||||
flex-shrink: 0;
|
||||
padding: 1px 7px;
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 6px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline));
|
||||
border-radius: var(--radius-xs);
|
||||
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
|
||||
}
|
||||
|
||||
.steps-anomaly-strip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-tags {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */
|
||||
.models-analytics-pane {
|
||||
display: flex;
|
||||
@@ -482,6 +759,47 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-anomaly {
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.85;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot,
|
||||
.sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--surface-panel);
|
||||
fill-opacity: 1;
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot.is-danger,
|
||||
.sstep-scatter-dot.is-anomaly.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly {
|
||||
margin-top: 3px;
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.trend-tip-anomaly.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.sstep-empty-hint {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,12 +14,17 @@ import {
|
||||
patchText,
|
||||
} from '../core/domPatch.js';
|
||||
import {
|
||||
buildModelAnomalyDiagnostic,
|
||||
formatAnomalyKindLabel,
|
||||
formatAnomalyTagText,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
resolveModelAnomalySummary,
|
||||
resolveModelDisplayInfo,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
@@ -77,6 +82,11 @@ function mergeSelectedAgentUnits(units) {
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
anomalySteps: 0,
|
||||
anomalyCount: 0,
|
||||
anomalyDangerCount: 0,
|
||||
anomalyTotalDelaySec: 0,
|
||||
anomalyByKind: {},
|
||||
_speedWeightedSum: 0,
|
||||
_speedWeight: 0,
|
||||
_ttftWeightedSum: 0,
|
||||
@@ -116,6 +126,16 @@ function mergeSelectedAgentUnits(units) {
|
||||
acc.totalTokens += totTok;
|
||||
acc.costUsd += costUsd;
|
||||
acc.unpricedCalls += unpricedCalls;
|
||||
acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0));
|
||||
acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0));
|
||||
acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0));
|
||||
acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0));
|
||||
if (m.anomalyByKind && typeof m.anomalyByKind === 'object') {
|
||||
for (const [kind, cnt] of Object.entries(m.anomalyByKind)) {
|
||||
const n = Math.max(0, Number(cnt || 0));
|
||||
if (n > 0) acc.anomalyByKind[kind] = (acc.anomalyByKind[kind] || 0) + n;
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) {
|
||||
const w = Math.max(1, outTok || calls || 1);
|
||||
@@ -164,6 +184,15 @@ function mergeSelectedAgentUnits(units) {
|
||||
avgTtftSec:
|
||||
acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null,
|
||||
cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0,
|
||||
...(acc.anomalyCount > 0
|
||||
? {
|
||||
anomalySteps: acc.anomalySteps,
|
||||
anomalyCount: acc.anomalyCount,
|
||||
anomalyDangerCount: acc.anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind: acc.anomalyByKind,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls);
|
||||
@@ -197,6 +226,8 @@ export const StepsDetailView = defineComponent({
|
||||
let lastSyncedUiScope = uiStore.getState().selectedAgentScope || 'all';
|
||||
let selectedTableModels = ['__all__'];
|
||||
let selectedLineModels = ['__all__'];
|
||||
let onlyAnomalies = false;
|
||||
let anomalyKindFilter = '';
|
||||
|
||||
function applyAgentScopesSelection(nextScopes) {
|
||||
selectedAgentScopes = nextScopes;
|
||||
@@ -220,7 +251,6 @@ export const StepsDetailView = defineComponent({
|
||||
collapseAll: true,
|
||||
multiUnit: t('steps.unitAgent'),
|
||||
modelValue: selectedAgentScopes,
|
||||
icon: 'layers',
|
||||
placeholder: t('steps.allAgents'),
|
||||
className: 'steps-inline-scope-select',
|
||||
options: [{ value: 'all', label: t('steps.allAgents') }],
|
||||
@@ -261,8 +291,10 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
|
||||
// --- 子视图 1:单步明细表(委托给可复用的 `StepTableWidget` 解耦组件) ---
|
||||
let stepsScroll = null;
|
||||
const stepTableWidget = StepTableWidget({
|
||||
onSelectAgentScopes: applyAgentScopesSelection,
|
||||
onVirtualHeightChange: () => stepsScroll?.refresh(),
|
||||
});
|
||||
const {
|
||||
stepsTablePane,
|
||||
@@ -270,15 +302,36 @@ export const StepsDetailView = defineComponent({
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
hideTurnTip,
|
||||
showAnomalyTip,
|
||||
hideAnomalyTip,
|
||||
syncTableHeaderColumns,
|
||||
renderStepTable,
|
||||
refreshViewport: refreshStepTableViewport,
|
||||
} = stepTableWidget.refs;
|
||||
const stepsScroll = CustomScrollbar({
|
||||
stepsScroll = CustomScrollbar({
|
||||
contentEl: stepsTablePane,
|
||||
className: 'table-scroll-host',
|
||||
});
|
||||
|
||||
const anomalyFilterLabelEl = h('span', { className: 'steps-anomaly-filter-label text-mono' });
|
||||
const anomalyFilterClearBtn = h('button', {
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm steps-anomaly-filter-clear',
|
||||
text: t('steps.anomalyFilterAll'),
|
||||
onclick: () => {
|
||||
onlyAnomalies = false;
|
||||
anomalyKindFilter = '';
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
},
|
||||
});
|
||||
const anomalyFilterBarEl = h(
|
||||
'div',
|
||||
{ className: 'steps-anomaly-filterbar', hidden: true },
|
||||
[anomalyFilterLabelEl, anomalyFilterClearBtn]
|
||||
);
|
||||
|
||||
// --- 子视图 2:总汇总分析面板 ---
|
||||
let selectedLineMetric = 'totalTokens';
|
||||
let selectedFitMetric = 'tps';
|
||||
@@ -381,6 +434,24 @@ export const StepsDetailView = defineComponent({
|
||||
className: 'cons-badge text-mono',
|
||||
text: t('cons.callsCount', { calls: 0 }),
|
||||
});
|
||||
const modelsAnomalyMetaEl = h('button', {
|
||||
type: 'button',
|
||||
className: 'steps-anomaly-strip-meta text-mono',
|
||||
onclick: () => {
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = '';
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
},
|
||||
});
|
||||
const modelsAnomalyTagsEl = h('div', { className: 'steps-anomaly-strip-tags' });
|
||||
const modelsAnomalyStripEl = h(
|
||||
'div',
|
||||
{ className: 'steps-anomaly-strip', hidden: true },
|
||||
[modelsAnomalyMetaEl, modelsAnomalyTagsEl]
|
||||
);
|
||||
let lastAnomalyStripSig = '';
|
||||
const modelsEmptyEl = h('div', {
|
||||
className: 'smodel-empty text-muted',
|
||||
text: t('steps.modelsEmpty'),
|
||||
@@ -388,6 +459,7 @@ export const StepsDetailView = defineComponent({
|
||||
const modelsListEl = h('div', { className: 'smodel-list' });
|
||||
const modelsSummarySection = h('div', { className: 'smodel-section' }, [
|
||||
h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]),
|
||||
modelsAnomalyStripEl,
|
||||
modelsEmptyEl,
|
||||
modelsListEl,
|
||||
]);
|
||||
@@ -397,6 +469,8 @@ export const StepsDetailView = defineComponent({
|
||||
modelFitCard,
|
||||
modelsSummarySection,
|
||||
]);
|
||||
const onModelsPaneScroll = () => hideAnomalyTip();
|
||||
modelsAnalyticsPane.addEventListener('scroll', onModelsPaneScroll, { passive: true });
|
||||
const modelsScroll = CustomScrollbar({
|
||||
contentEl: modelsAnalyticsPane,
|
||||
className: 'table-scroll-host',
|
||||
@@ -422,9 +496,11 @@ export const StepsDetailView = defineComponent({
|
||||
subTabSwitch.el,
|
||||
]),
|
||||
]),
|
||||
anomalyFilterBarEl,
|
||||
stepsScroll.el,
|
||||
modelsScroll.el,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
]
|
||||
);
|
||||
stepTableWidget.refs.setBoundsElGetter(() => panelEl);
|
||||
@@ -433,6 +509,19 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
let cachedChronoSrc = null;
|
||||
let cachedChronoMerged = false;
|
||||
let cachedChronoOut = [];
|
||||
|
||||
function getMemoizedChronoSteps(steps, isMergedMultiAgents) {
|
||||
if (cachedChronoSrc === steps && cachedChronoMerged === isMergedMultiAgents) {
|
||||
return cachedChronoOut;
|
||||
}
|
||||
cachedChronoSrc = steps;
|
||||
cachedChronoMerged = isMergedMultiAgents;
|
||||
cachedChronoOut = toChronologicalSteps(steps, isMergedMultiAgents);
|
||||
return cachedChronoOut;
|
||||
}
|
||||
|
||||
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
|
||||
if (scopedConv?.hasKnownModel !== false) {
|
||||
@@ -482,6 +571,8 @@ export const StepsDetailView = defineComponent({
|
||||
patchText(fitTitleEl, t('steps.fitTitle'));
|
||||
patchText(modelsSectionTitleEl, t('steps.modelsTitle'));
|
||||
patchText(modelsEmptyEl, t('steps.modelsEmpty'));
|
||||
patchText(anomalyFilterClearBtn, t('steps.anomalyFilterAll'));
|
||||
lastAnomalyStripSig = '';
|
||||
lineMetricSwitch.setProps({
|
||||
modelValue: selectedLineMetric,
|
||||
options: getLineMetricSwitchOptions(),
|
||||
@@ -503,7 +594,7 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
function renderStepsData(slice) {
|
||||
function renderStepsData(slice, { allowNewRowFade = false } = {}) {
|
||||
if (!slice) return;
|
||||
const uiSt = uiStore.getState();
|
||||
const locale = getEffectiveLocale();
|
||||
@@ -515,6 +606,8 @@ export const StepsDetailView = defineComponent({
|
||||
lastSyncedUiScope = uiSt.selectedAgentScope || 'all';
|
||||
selectedTableModels = ['__all__'];
|
||||
selectedLineModels = ['__all__'];
|
||||
onlyAnomalies = false;
|
||||
anomalyKindFilter = '';
|
||||
}
|
||||
fitLockedCascadeId = currentCid;
|
||||
fitUserPicked = false;
|
||||
@@ -619,33 +712,14 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
const showAgentPrefix = isMergedMultiAgents;
|
||||
const showModels = uiSt.stepsSubTab === 'models';
|
||||
const chronoSteps = toChronologicalSteps(steps, isMergedMultiAgents);
|
||||
|
||||
const stepTtftFallbackMap = new Map();
|
||||
const stepModelOptionMap = new Map();
|
||||
for (const st of chronoSteps) {
|
||||
const gk = getStepModelGroupKey(st);
|
||||
if (!stepModelOptionMap.has(gk)) {
|
||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
||||
stepModelOptionMap.set(gk, {
|
||||
label: disp.baseText || disp.text || gk,
|
||||
calls: 0,
|
||||
});
|
||||
}
|
||||
stepModelOptionMap.get(gk).calls += 1;
|
||||
|
||||
if (showModels && !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
|
||||
const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 };
|
||||
prev.sum += Number(st.ttftSec);
|
||||
prev.count += 1;
|
||||
stepTtftFallbackMap.set(gk, prev);
|
||||
}
|
||||
}
|
||||
|
||||
const availableModelKeys = new Set();
|
||||
const modelColorByGroup = new Map();
|
||||
const perModelOptions = [];
|
||||
let breakdownCalls = 0;
|
||||
for (const m of models) {
|
||||
if (!m || typeof m !== 'object') continue;
|
||||
breakdownCalls += Math.max(0, Number(m.calls || 0));
|
||||
const gk = getStepModelGroupKey(m);
|
||||
if (availableModelKeys.has(gk)) continue;
|
||||
availableModelKeys.add(gk);
|
||||
@@ -663,18 +737,35 @@ export const StepsDetailView = defineComponent({
|
||||
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
|
||||
});
|
||||
}
|
||||
for (const [gk, info] of stepModelOptionMap.entries()) {
|
||||
if (!availableModelKeys.has(gk)) {
|
||||
availableModelKeys.add(gk);
|
||||
modelColorByGroup.set(
|
||||
gk,
|
||||
MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length]
|
||||
);
|
||||
perModelOptions.push({
|
||||
value: gk,
|
||||
label: info.label,
|
||||
meta: t('header.convMetaSteps', { count: info.calls }),
|
||||
});
|
||||
|
||||
const needStepModelFallback =
|
||||
steps.length > 0 && (models.length === 0 || breakdownCalls < steps.length);
|
||||
if (needStepModelFallback) {
|
||||
const stepModelOptionMap = new Map();
|
||||
for (const st of steps) {
|
||||
const gk = getStepModelGroupKey(st);
|
||||
if (!stepModelOptionMap.has(gk)) {
|
||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
||||
stepModelOptionMap.set(gk, {
|
||||
label: disp.baseText || disp.text || gk,
|
||||
calls: 0,
|
||||
});
|
||||
}
|
||||
stepModelOptionMap.get(gk).calls += 1;
|
||||
}
|
||||
for (const [gk, info] of stepModelOptionMap.entries()) {
|
||||
if (!availableModelKeys.has(gk)) {
|
||||
availableModelKeys.add(gk);
|
||||
modelColorByGroup.set(
|
||||
gk,
|
||||
MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length]
|
||||
);
|
||||
perModelOptions.push({
|
||||
value: gk,
|
||||
label: info.label,
|
||||
meta: t('header.convMetaSteps', { count: info.calls }),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -710,9 +801,29 @@ export const StepsDetailView = defineComponent({
|
||||
const tableModelFilterSet = selectedTableModels.includes('__all__')
|
||||
? null
|
||||
: new Set(selectedTableModels);
|
||||
const tableSteps = tableModelFilterSet
|
||||
const modelFilteredSteps = tableModelFilterSet
|
||||
? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st)))
|
||||
: steps;
|
||||
const tableSteps = onlyAnomalies
|
||||
? modelFilteredSteps.filter((st) => {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return false;
|
||||
if (anomalyKindFilter) {
|
||||
return Number(a.kinds?.[anomalyKindFilter] || 0) > 0;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
: modelFilteredSteps;
|
||||
|
||||
const showAnomalyFilterBar = !showModels && onlyAnomalies;
|
||||
patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar);
|
||||
if (showAnomalyFilterBar) {
|
||||
const baseLabel = t('steps.anomalyFilterLabel', { count: tableSteps.length });
|
||||
const kindSuffix = anomalyKindFilter
|
||||
? ` · ${formatAnomalyKindLabel(anomalyKindFilter)}`
|
||||
: '';
|
||||
patchText(anomalyFilterLabelEl, `${baseLabel}${kindSuffix}`);
|
||||
}
|
||||
|
||||
const stepsTabLabel =
|
||||
tableSteps.length !== steps.length
|
||||
@@ -729,6 +840,12 @@ export const StepsDetailView = defineComponent({
|
||||
],
|
||||
});
|
||||
|
||||
const allConversationSteps = hasSubagents
|
||||
? aggregated?.recentSteps || []
|
||||
: slice.recentSteps || [];
|
||||
const shouldAnimateNewRows = Boolean(
|
||||
allowNewRowFade && slice.experimentalModernUi && !showModels
|
||||
);
|
||||
if (!showModels) {
|
||||
const colKeys = normalizeClientStepColumns(slice.stepTableColumns);
|
||||
renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, {
|
||||
@@ -740,8 +857,27 @@ export const StepsDetailView = defineComponent({
|
||||
showStepSpeedColor: slice.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: slice.stepTokenComboFormat,
|
||||
displaySettings,
|
||||
allConversationSteps,
|
||||
allowNewRowFade: shouldAnimateNewRows,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
fitPinnedWhileVisible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const chronoSteps = getMemoizedChronoSteps(steps, isMergedMultiAgents);
|
||||
const stepTtftFallbackMap = new Map();
|
||||
const needTtftFallback = models.some((m) => m && m.avgTtftSec == null);
|
||||
if (needTtftFallback) {
|
||||
for (const st of chronoSteps) {
|
||||
if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
|
||||
const gk = getStepModelGroupKey(st);
|
||||
const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 };
|
||||
prev.sum += Number(st.ttftSec);
|
||||
prev.count += 1;
|
||||
stepTtftFallbackMap.set(gk, prev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 顶部“会话走势”更新
|
||||
@@ -761,15 +897,11 @@ export const StepsDetailView = defineComponent({
|
||||
? ['__all__']
|
||||
: Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k))));
|
||||
|
||||
if (!showModels) {
|
||||
fitPinnedWhileVisible = false;
|
||||
}
|
||||
if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) {
|
||||
fitLockedModelKeys = [defaultActiveModelKey];
|
||||
} else {
|
||||
fitLockedModelKeys = sanitizedLocked;
|
||||
}
|
||||
if (!showModels) return;
|
||||
if (availableModelKeys.size > 0) fitPinnedWhileVisible = true;
|
||||
|
||||
patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels);
|
||||
@@ -829,10 +961,79 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
// 4. 极简模型总览列表增量对账
|
||||
const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' });
|
||||
const needStepAnomalyFallback = displayModels.every((m) => !(Number(m?.anomalyCount) > 0));
|
||||
let stepAnomalyByGroup = null;
|
||||
if (needStepAnomalyFallback) {
|
||||
for (const st of chronoSteps) {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) continue;
|
||||
if (!stepAnomalyByGroup) stepAnomalyByGroup = new Map();
|
||||
const gk = getStepModelGroupKey(st);
|
||||
let acc = stepAnomalyByGroup.get(gk);
|
||||
if (!acc) {
|
||||
acc = {
|
||||
anomalySteps: 0,
|
||||
anomalyCount: 0,
|
||||
anomalyDangerCount: 0,
|
||||
anomalyTotalDelaySec: 0,
|
||||
anomalyByKind: {},
|
||||
};
|
||||
stepAnomalyByGroup.set(gk, acc);
|
||||
}
|
||||
acc.anomalySteps += 1;
|
||||
acc.anomalyCount += Number(a.count) || 0;
|
||||
if (a.severity === 'danger') acc.anomalyDangerCount += 1;
|
||||
acc.anomalyTotalDelaySec += Number(a.totalDelaySec) || 0;
|
||||
if (a.kinds && typeof a.kinds === 'object') {
|
||||
for (const [k, cnt] of Object.entries(a.kinds)) {
|
||||
const n = Math.max(0, Number(cnt || 0));
|
||||
if (n > 0) acc.anomalyByKind[k] = (acc.anomalyByKind[k] || 0) + n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolveEffectiveAnomalyModel = (m) => {
|
||||
if (Number(m?.anomalyCount) > 0 || !stepAnomalyByGroup) return m;
|
||||
const gk = getStepModelGroupKey(m);
|
||||
const groupKeys =
|
||||
Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0
|
||||
? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl }))))
|
||||
: [gk];
|
||||
let anomalySteps = 0;
|
||||
let anomalyCount = 0;
|
||||
let anomalyDangerCount = 0;
|
||||
let anomalyTotalDelaySec = 0;
|
||||
const anomalyByKind = {};
|
||||
for (const key of groupKeys) {
|
||||
const hit = stepAnomalyByGroup.get(key);
|
||||
if (!hit) continue;
|
||||
anomalySteps += hit.anomalySteps;
|
||||
anomalyCount += hit.anomalyCount;
|
||||
anomalyDangerCount += hit.anomalyDangerCount;
|
||||
anomalyTotalDelaySec += hit.anomalyTotalDelaySec;
|
||||
for (const [k, cnt] of Object.entries(hit.anomalyByKind)) {
|
||||
anomalyByKind[k] = (anomalyByKind[k] || 0) + cnt;
|
||||
}
|
||||
}
|
||||
if (anomalyCount <= 0) return m;
|
||||
return {
|
||||
...m,
|
||||
anomalySteps,
|
||||
anomalyCount,
|
||||
anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind,
|
||||
};
|
||||
};
|
||||
|
||||
let sumCalls = 0;
|
||||
let sumTokens = 0;
|
||||
let sumCost = 0;
|
||||
let sumUnpriced = 0;
|
||||
let sumAnomalyCount = 0;
|
||||
let sumAnomalySteps = 0;
|
||||
const sumAnomalyByKind = {};
|
||||
const effectiveAnomalyModels = new Map();
|
||||
for (const m of displayModels) {
|
||||
sumCalls += Math.max(0, Number(m.calls || 0));
|
||||
sumTokens += Math.max(0, Number(m.totalTokens || 0));
|
||||
@@ -840,6 +1041,54 @@ export const StepsDetailView = defineComponent({
|
||||
if (Number.isFinite(Number(m.costUsd))) {
|
||||
sumCost += Math.max(0, Number(m.costUsd));
|
||||
}
|
||||
const effM = resolveEffectiveAnomalyModel(m);
|
||||
effectiveAnomalyModels.set(m, effM);
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
if (anomSum) {
|
||||
sumAnomalyCount += anomSum.count;
|
||||
sumAnomalySteps += anomSum.steps;
|
||||
for (const [k, v] of anomSum.entries) {
|
||||
sumAnomalyByKind[k] = (sumAnomalyByKind[k] || 0) + v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sumAnomalyCount > 0) {
|
||||
patchAttr(modelsAnomalyStripEl, 'hidden', false);
|
||||
const sortedKinds = Object.entries(sumAnomalyByKind)
|
||||
.filter(([, v]) => v > 0)
|
||||
.sort((a, b) => b[1] - a[1]);
|
||||
const stripSig = `${locale}:${sumAnomalyCount}:${sumAnomalySteps}:${sortedKinds.map(([k, v]) => `${k}=${v}`).join(',')}`;
|
||||
if (stripSig !== lastAnomalyStripSig) {
|
||||
lastAnomalyStripSig = stripSig;
|
||||
patchText(
|
||||
modelsAnomalyMetaEl,
|
||||
t('steps.anomalySummaryMeta', { count: sumAnomalyCount, steps: sumAnomalySteps })
|
||||
);
|
||||
while (modelsAnomalyTagsEl.firstChild) {
|
||||
modelsAnomalyTagsEl.removeChild(modelsAnomalyTagsEl.firstChild);
|
||||
}
|
||||
for (const [kind, cnt] of sortedKinds) {
|
||||
const isDanger = kind === 'rate_limit' || kind === 'auth_or_model';
|
||||
const btn = h('button', {
|
||||
type: 'button',
|
||||
className: `step-anomaly-tag smodel-anomaly-tag text-mono${isDanger ? ' is-danger' : ''}`,
|
||||
text: formatAnomalyTagText(kind, cnt),
|
||||
title: `${formatAnomalyKindLabel(kind)} · ${t('steps.anomalyModelClickHint')}`,
|
||||
onclick: () => {
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = kind;
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
},
|
||||
});
|
||||
modelsAnomalyTagsEl.appendChild(btn);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lastAnomalyStripSig = '';
|
||||
patchAttr(modelsAnomalyStripEl, 'hidden', true);
|
||||
}
|
||||
|
||||
if (displayModels.length === 0) {
|
||||
@@ -883,11 +1132,21 @@ export const StepsDetailView = defineComponent({
|
||||
: [gk];
|
||||
const isActiveFit =
|
||||
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
|
||||
const effM = effectiveAnomalyModels.get(m) || m;
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
const anomSig = anomSum
|
||||
? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}`
|
||||
: '';
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const nameEl = h('strong', { className: 'smodel-name' });
|
||||
const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' });
|
||||
const anomalyTagEl = h('span', {
|
||||
className: 'step-anomaly-tag smodel-anomaly-tag text-mono',
|
||||
title: '',
|
||||
hidden: true,
|
||||
});
|
||||
const tokEl = h('span', { className: 'smodel-tok text-mono' });
|
||||
const costEl = h('strong', { className: 'smodel-cost text-mono' });
|
||||
const segBar = createFourSegmentBar();
|
||||
@@ -898,7 +1157,7 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
const cardEl = h('div', { className: 'smodel-card' }, [
|
||||
h('div', { className: 'smodel-head' }, [
|
||||
h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl]),
|
||||
h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl, anomalyTagEl]),
|
||||
h('div', { className: 'smodel-totals' }, [tokEl, costEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
@@ -907,7 +1166,18 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
return {
|
||||
el: cardEl,
|
||||
refs: { nameEl, callsPillEl, tokEl, costEl, segBar, perfEl, splitEl },
|
||||
refs: {
|
||||
nameEl,
|
||||
callsPillEl,
|
||||
anomalyTagEl,
|
||||
tokEl,
|
||||
costEl,
|
||||
segBar,
|
||||
perfEl,
|
||||
splitEl,
|
||||
cardTitle: '',
|
||||
isHoveringAnomaly: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
updateRow: (refs, m, _idx, cardEl) => {
|
||||
@@ -932,6 +1202,40 @@ export const StepsDetailView = defineComponent({
|
||||
: t('steps.modelCallsOnly', { calls })
|
||||
);
|
||||
|
||||
const effM = effectiveAnomalyModels.get(m) || m;
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
patchAttr(refs.anomalyTagEl, 'hidden', !anomSum);
|
||||
if (anomSum) {
|
||||
patchText(refs.anomalyTagEl, anomSum.tagText);
|
||||
patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' });
|
||||
patchAttr(refs.anomalyTagEl, 'title', '');
|
||||
refs.anomalyTagEl.onmouseenter = () => {
|
||||
refs.isHoveringAnomaly = true;
|
||||
patchAttr(cardEl, 'title', null);
|
||||
showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM));
|
||||
};
|
||||
refs.anomalyTagEl.onmouseleave = () => {
|
||||
refs.isHoveringAnomaly = false;
|
||||
patchAttr(cardEl, 'title', refs.cardTitle || null);
|
||||
hideAnomalyTip();
|
||||
};
|
||||
refs.anomalyTagEl.onclick = (e) => {
|
||||
e?.stopPropagation?.();
|
||||
refs.isHoveringAnomaly = false;
|
||||
patchAttr(cardEl, 'title', refs.cardTitle || null);
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = '';
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
};
|
||||
} else {
|
||||
refs.isHoveringAnomaly = false;
|
||||
refs.anomalyTagEl.onmouseenter = null;
|
||||
refs.anomalyTagEl.onmouseleave = null;
|
||||
refs.anomalyTagEl.onclick = null;
|
||||
}
|
||||
|
||||
const inTok = Math.max(0, Number(m.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(m.outputTokens || 0));
|
||||
@@ -975,7 +1279,7 @@ export const StepsDetailView = defineComponent({
|
||||
patchText(
|
||||
refs.perfEl,
|
||||
t('steps.modelPerfFoot', {
|
||||
tps: formatMetric(m.avgTokPerSec, ' tok/s'),
|
||||
tps: formatSpeedMetric(m.avgTokPerSec, ' tok/s'),
|
||||
ttft: formatMetric(resolvedAvgTtft, 's'),
|
||||
cache: resolvedCachePct,
|
||||
})
|
||||
@@ -993,15 +1297,12 @@ export const StepsDetailView = defineComponent({
|
||||
const isActiveFit =
|
||||
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
|
||||
patchClasses(cardEl, { 'is-fit-active': isActiveFit });
|
||||
patchAttr(
|
||||
cardEl,
|
||||
'title',
|
||||
!hasMultipleModels
|
||||
? dispTitle
|
||||
: isActiveFit
|
||||
? t('steps.fitActiveCardTitle', { title: dispTitle })
|
||||
: t('steps.fitInactiveCardTitle', { text: dispText })
|
||||
);
|
||||
refs.cardTitle = !hasMultipleModels
|
||||
? dispTitle
|
||||
: isActiveFit
|
||||
? t('steps.fitActiveCardTitle', { title: dispTitle })
|
||||
: t('steps.fitInactiveCardTitle', { text: dispText });
|
||||
patchAttr(cardEl, 'title', refs.isHoveringAnomaly ? null : refs.cardTitle);
|
||||
cardEl.onclick = (e) => {
|
||||
if (!hasMultipleModels) return;
|
||||
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && !isFitPooledAll) {
|
||||
@@ -1036,12 +1337,15 @@ export const StepsDetailView = defineComponent({
|
||||
(st) => st.stepsSubTab,
|
||||
(tab) => {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
subTabSwitch.setValue(tab);
|
||||
patchAttr(anomalyFilterBarEl, 'hidden', tab !== 'steps' || !onlyAnomalies);
|
||||
patchAttr(stepsScroll.el, 'hidden', tab !== 'steps');
|
||||
patchAttr(modelsScroll.el, 'hidden', tab !== 'models');
|
||||
if (getVisibleMonitorView() === 'steps' && latestSlice) {
|
||||
renderStepsData(latestSlice);
|
||||
} else if (tab === 'steps') {
|
||||
refreshStepTableViewport();
|
||||
stepsScroll.refresh();
|
||||
} else {
|
||||
modelsScroll.refresh();
|
||||
@@ -1070,6 +1374,7 @@ export const StepsDetailView = defineComponent({
|
||||
st.telemetry?.settings?.stepTokenComboFormat
|
||||
),
|
||||
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
|
||||
experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi),
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
@@ -1081,7 +1386,9 @@ export const StepsDetailView = defineComponent({
|
||||
return;
|
||||
}
|
||||
isDirty = false;
|
||||
renderStepsData(slice);
|
||||
renderStepsData(slice, {
|
||||
allowNewRowFade: uiStore.getState().stepsSubTab === 'steps',
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1104,6 +1411,7 @@ export const StepsDetailView = defineComponent({
|
||||
prevActiveView = uiSlice.activeView;
|
||||
if (uiSlice.activeView !== 'steps') {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
fitPinnedWhileVisible = false;
|
||||
if (scopeChanged) isDirty = true;
|
||||
return;
|
||||
@@ -1128,6 +1436,7 @@ export const StepsDetailView = defineComponent({
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll);
|
||||
unsubUi();
|
||||
unsubTelemetry();
|
||||
unsubView();
|
||||
@@ -1153,6 +1462,9 @@ export const StepsDetailView = defineComponent({
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
anomalyFilterBarEl,
|
||||
modelsAnomalyStripEl,
|
||||
modelsListEl,
|
||||
inlineScopeSelect,
|
||||
stepsModelSelect,
|
||||
@@ -1163,6 +1475,7 @@ export const StepsDetailView = defineComponent({
|
||||
fitMetricSwitch,
|
||||
stepsScroll,
|
||||
modelsScroll,
|
||||
refreshStepTableViewport,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -6,10 +6,13 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
applyAppearanceToRoot,
|
||||
normalizeClientFontScale,
|
||||
normalizeClientModernUi,
|
||||
normalizeClientThemeAccent,
|
||||
} from '../../core/appearance.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { normalizeI18nLanguage, setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
@@ -39,6 +42,13 @@ function getFontScaleOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getModernUiOptions() {
|
||||
return [
|
||||
{ value: 'off', label: t('settings.gen.modernUiOff') },
|
||||
{ value: 'on', label: t('settings.gen.modernUiOn') },
|
||||
];
|
||||
}
|
||||
|
||||
function getUpdateModeOptions() {
|
||||
return [
|
||||
{ value: 'manual', label: t('settings.gen.updateManual') },
|
||||
@@ -66,10 +76,12 @@ export const SettingsGeneralTab = defineComponent({
|
||||
let draftLanguage = 'zh-CN';
|
||||
let draftThemeAccent = 'host';
|
||||
let draftFontScale = 'md';
|
||||
let draftModernUi = false;
|
||||
let draftPluginUpdateMode = 'manual';
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let appearanceTimer = null;
|
||||
let appearanceSaveSeq = 0;
|
||||
let cloudTimer = null;
|
||||
|
||||
const appearanceStatusText = h('span', {
|
||||
@@ -123,6 +135,14 @@ export const SettingsGeneralTab = defineComponent({
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.gen.fontHint'),
|
||||
});
|
||||
const modernUiLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.gen.modernUi'),
|
||||
});
|
||||
const modernUiHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.gen.modernUiHint'),
|
||||
});
|
||||
|
||||
const languageSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.language'),
|
||||
@@ -133,13 +153,18 @@ export const SettingsGeneralTab = defineComponent({
|
||||
draftLanguage = nextLang;
|
||||
setI18nLanguage(nextLang);
|
||||
languageSwitch.setValue(nextLang);
|
||||
const saveToken = ++appearanceSaveSeq;
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ language: nextLang });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
}
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -150,13 +175,18 @@ export const SettingsGeneralTab = defineComponent({
|
||||
const nextAccent = normalizeClientThemeAccent(val);
|
||||
draftThemeAccent = nextAccent;
|
||||
themeColorPicker.refs.setValue(nextAccent);
|
||||
const saveToken = ++appearanceSaveSeq;
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ themeAccent: nextAccent });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
}
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -169,14 +199,56 @@ export const SettingsGeneralTab = defineComponent({
|
||||
const nextScale = normalizeClientFontScale(val);
|
||||
draftFontScale = nextScale;
|
||||
fontScaleSwitch.setValue(nextScale);
|
||||
const saveToken = ++appearanceSaveSeq;
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ fontScale: nextScale });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
}
|
||||
props.onLayoutChange?.();
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const modernUiSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.modernUi'),
|
||||
modelValue: 'off',
|
||||
options: getModernUiOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextModernUi = val === 'on';
|
||||
draftModernUi = nextModernUi;
|
||||
modernUiSwitch.setValue(nextModernUi ? 'on' : 'off');
|
||||
if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) {
|
||||
applyAppearanceToRoot(
|
||||
document.documentElement,
|
||||
{
|
||||
...(latestSettings || {}),
|
||||
themeAccent: draftThemeAccent,
|
||||
fontScale: draftFontScale,
|
||||
experimentalModernUi: nextModernUi,
|
||||
},
|
||||
{ includeFontScale: true }
|
||||
);
|
||||
}
|
||||
const saveToken = ++appearanceSaveSeq;
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ experimentalModernUi: nextModernUi });
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
}
|
||||
props.onLayoutChange?.();
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (saveToken === appearanceSaveSeq) {
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -192,6 +264,7 @@ export const SettingsGeneralTab = defineComponent({
|
||||
h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]),
|
||||
h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]),
|
||||
h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]),
|
||||
h('div', { className: 'form-row' }, [modernUiLabelEl, modernUiSwitch.el, modernUiHintEl]),
|
||||
]);
|
||||
|
||||
// --- Card 2: 版本更新 ---
|
||||
@@ -350,6 +423,7 @@ export const SettingsGeneralTab = defineComponent({
|
||||
draftLanguage = normalizeI18nLanguage(settings.language);
|
||||
draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent);
|
||||
draftFontScale = normalizeClientFontScale(settings.fontScale);
|
||||
draftModernUi = normalizeClientModernUi(settings.experimentalModernUi);
|
||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||
settings.pluginUpdateMode,
|
||||
settings.autoUpdatePlugin
|
||||
@@ -364,6 +438,10 @@ export const SettingsGeneralTab = defineComponent({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
modernUiSwitch.setProps({
|
||||
modelValue: draftModernUi ? 'on' : 'off',
|
||||
options: getModernUiOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
@@ -425,6 +503,8 @@ export const SettingsGeneralTab = defineComponent({
|
||||
patchText(accentLabelEl, t('settings.gen.themeAccent'));
|
||||
patchText(fontLabelEl, t('settings.gen.fontScale'));
|
||||
patchText(fontHintEl, t('settings.gen.fontHint'));
|
||||
patchText(modernUiLabelEl, t('settings.gen.modernUi'));
|
||||
patchText(modernUiHintEl, t('settings.gen.modernUiHint'));
|
||||
patchText(updateTitleEl, t('settings.gen.updateTitle'));
|
||||
patchText(updateModeLabelEl, t('settings.gen.updateMode'));
|
||||
patchText(pricingCellLabelEl, t('settings.gen.pricingLabel'));
|
||||
@@ -441,6 +521,11 @@ export const SettingsGeneralTab = defineComponent({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
modernUiSwitch.setProps({
|
||||
ariaLabel: t('settings.gen.modernUi'),
|
||||
modelValue: draftModernUi ? 'on' : 'off',
|
||||
options: getModernUiOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
@@ -458,6 +543,7 @@ export const SettingsGeneralTab = defineComponent({
|
||||
languageSwitch.destroy();
|
||||
themeColorPicker.destroy();
|
||||
fontScaleSwitch.destroy();
|
||||
modernUiSwitch.destroy();
|
||||
autoUpdateSelect.destroy();
|
||||
});
|
||||
|
||||
@@ -467,6 +553,7 @@ export const SettingsGeneralTab = defineComponent({
|
||||
languageSwitch,
|
||||
themeColorPicker,
|
||||
fontScaleSwitch,
|
||||
modernUiSwitch,
|
||||
autoUpdateSelect,
|
||||
syncPricingBtn,
|
||||
updatePluginBtn,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
@@ -177,10 +177,29 @@ export const SettingsStructureTab = defineComponent({
|
||||
'aria-selected': item.key === activeThirdTab ? 'true' : 'false',
|
||||
'data-structure-tab': item.key,
|
||||
onClick: () => {
|
||||
applyActiveThirdTab(item.key);
|
||||
if (uiStore.getState().settingsStructureTab !== item.key) {
|
||||
uiStore.setState({ settingsStructureTab: item.key });
|
||||
} else {
|
||||
applyActiveThirdTab(item.key);
|
||||
}
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
const curIdx = Math.max(
|
||||
0,
|
||||
STRUCTURE_THIRD_TABS.findIndex((it) => it.key === item.key)
|
||||
);
|
||||
const delta = e.key === 'ArrowRight' ? 1 : -1;
|
||||
const nextIdx =
|
||||
(curIdx + delta + STRUCTURE_THIRD_TABS.length) % STRUCTURE_THIRD_TABS.length;
|
||||
const nextItem = STRUCTURE_THIRD_TABS[nextIdx];
|
||||
if (nextItem) {
|
||||
applyActiveThirdTab(nextItem.key);
|
||||
if (uiStore.getState().settingsStructureTab !== nextItem.key) {
|
||||
uiStore.setState({ settingsStructureTab: nextItem.key });
|
||||
}
|
||||
thirdNavBtnMap.get(nextItem.key)?.btn?.focus?.();
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -190,6 +209,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
return btn;
|
||||
});
|
||||
|
||||
const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' });
|
||||
const thirdNavBar = h(
|
||||
'div',
|
||||
{
|
||||
@@ -197,7 +217,15 @@ export const SettingsStructureTab = defineComponent({
|
||||
role: 'tablist',
|
||||
'aria-label': t('settings.str.thirdTabAria'),
|
||||
},
|
||||
thirdNavBtns
|
||||
[thirdNavGlider, ...thirdNavBtns]
|
||||
);
|
||||
patchStyleVar(
|
||||
thirdNavBar,
|
||||
'--active-third-index',
|
||||
Math.max(
|
||||
0,
|
||||
STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab)
|
||||
)
|
||||
);
|
||||
|
||||
// --- Pane 1: 挂载与胶囊栏 (`mount`) ---
|
||||
@@ -973,6 +1001,11 @@ export const SettingsStructureTab = defineComponent({
|
||||
function applyActiveThirdTab(nextRawTab) {
|
||||
const nextTab = normalizeStructureTabKey(nextRawTab);
|
||||
activeThirdTab = nextTab;
|
||||
const activeIdx = Math.max(
|
||||
0,
|
||||
STRUCTURE_THIRD_TABS.findIndex((it) => it.key === nextTab)
|
||||
);
|
||||
patchStyleVar(thirdNavBar, '--active-third-index', activeIdx);
|
||||
for (const [key, entry] of thirdNavBtnMap.entries()) {
|
||||
const isActive = key === nextTab;
|
||||
patchClasses(entry.btn, { 'is-active': isActive });
|
||||
|
||||
+1666
-46
File diff suppressed because it is too large
Load Diff
@@ -59,6 +59,7 @@ export function backendHarness({
|
||||
cache={},
|
||||
deepStats=null,
|
||||
transcripts={},
|
||||
swarmMembers={},
|
||||
diskDirs={},
|
||||
settings={},
|
||||
trajectories={},
|
||||
@@ -82,7 +83,7 @@ export function backendHarness({
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs: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={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID,
|
||||
...(clock ? { Date: class extends Date {
|
||||
@@ -110,6 +111,10 @@ export function backendHarness({
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||
return Boolean(m && state.transcripts?.[m[1]]);
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
return Boolean(m && state.swarmMembers?.[m[1]]);
|
||||
}
|
||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText);
|
||||
if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText);
|
||||
if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true;
|
||||
@@ -131,6 +136,14 @@ export function backendHarness({
|
||||
return {mtimeMs:state.transcriptMtimeMs,size:Buffer.byteLength(text,'utf8')};
|
||||
}
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
const obj = m && state.swarmMembers?.[m[1]];
|
||||
if (obj) {
|
||||
const text = typeof obj === 'string' ? obj : JSON.stringify(obj);
|
||||
return {mtimeMs:state.swarmMembersMtimeMs,size:Buffer.byteLength(text,'utf8')};
|
||||
}
|
||||
}
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json') && state.deepStats) {
|
||||
return {mtimeMs:state.deepStatsMtimeMs,size:JSON.stringify(state.deepStats).length};
|
||||
}
|
||||
@@ -143,6 +156,11 @@ export function backendHarness({
|
||||
const lines = m && state.transcripts?.[m[1]];
|
||||
return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || '');
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
const obj = m && state.swarmMembers?.[m[1]];
|
||||
return typeof obj === 'string' ? obj : JSON.stringify(obj || {});
|
||||
}
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(state.settings);
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
|
||||
@@ -2423,3 +2423,394 @@ test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display
|
||||
rmSync(workerTemp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('scope=consumption and scope=consumption-presets bypass matchesConv, >30s idle, and visual settings, match full aggregation, and invalidate on weeklyLimitMode/cache rebuild', async (t) => {
|
||||
let clockMs = Date.parse('2026-11-19T12:00:00.000Z');
|
||||
const mkStep = (idx, offsetMs, tok) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
...(offsetMs !== null
|
||||
? {
|
||||
createdAt: new Date(clockMs - offsetMs).toISOString(),
|
||||
completedAt: new Date(clockMs - offsetMs + 1200).toISOString(),
|
||||
}
|
||||
: {}),
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||
modelUsage: {
|
||||
model: 'MODEL_CLAUDE_4_5_SONNET',
|
||||
inputTokens: String(tok),
|
||||
cacheReadTokens: '0',
|
||||
outputTokens: '0',
|
||||
},
|
||||
},
|
||||
plannerResponse: { response: `step-${idx}` },
|
||||
});
|
||||
|
||||
const h = backendHarness({
|
||||
clock: () => clockMs,
|
||||
trajectories: {
|
||||
'conv-old': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 20 * 86400_000, 1000),
|
||||
mkStep(2, null, 250),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-recent': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 4 * 86400_000, 3000),
|
||||
mkStep(2, 2 * 3600_000, 500),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-old': {
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 20 * 86400_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-recent': {
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 2 * 3600_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const initBody = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.ok(Number(initBody.consumption?.revision || 0) > 0);
|
||||
const rpcCallsAfterInit = h.state.calls.length;
|
||||
|
||||
// Advance clock by 2 minutes and toggle visual-only settings
|
||||
clockMs += 120_000;
|
||||
h.executeSettingsAction({ themeAccent: 'emerald', fontScale: 'lg' });
|
||||
|
||||
// Query from a DIFFERENT conversationId (simulating sidebar vs overlay mismatch)
|
||||
const presetsRes = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-different-pane',
|
||||
scope: 'consumption-presets',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(presetsRes.scope, 'consumption-presets');
|
||||
assert.equal(presetsRes.activeConversation, undefined);
|
||||
assert.equal(presetsRes.quotas, undefined);
|
||||
assert.equal(presetsRes.ranges.today.account.totalTokens, 500);
|
||||
assert.equal(presetsRes.ranges['7d'].account.totalTokens, 3500);
|
||||
assert.equal(presetsRes.ranges['30d'].account.totalTokens, 4500);
|
||||
assert.equal(presetsRes.ranges.all.account.totalTokens, 4750);
|
||||
|
||||
const liteCustom = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-different-pane',
|
||||
range: 'custom',
|
||||
startMs: String(clockMs - 6 * 86400_000),
|
||||
endMs: String(clockMs - 2 * 86400_000),
|
||||
scope: 'consumption',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(liteCustom.scope, 'consumption');
|
||||
assert.equal(liteCustom.activeConversation, undefined);
|
||||
assert.equal(liteCustom.consumption.account.totalTokens, 3000);
|
||||
assert.equal(
|
||||
h.state.calls.length,
|
||||
rpcCallsAfterInit,
|
||||
'scope=consumption / presets must skip LS RPCs across pane mismatch, >30s idle, and visual settings changes'
|
||||
);
|
||||
|
||||
// Changing weeklyLimitMode DOES invalidate snapshot and trigger fresh full build
|
||||
h.executeSettingsAction({ weeklyLimitMode: 'custom_tokens' });
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: '7d',
|
||||
scope: 'consumption',
|
||||
});
|
||||
const rpcCallsAfterWeeklyChange = h.state.calls.length;
|
||||
assert.ok(
|
||||
rpcCallsAfterWeeklyChange > rpcCallsAfterInit,
|
||||
'Changing weeklyLimitMode must invalidate cached fast consumption snapshot'
|
||||
);
|
||||
|
||||
// Cache rebuild also invalidates snapshot and falls back to full RPC sync
|
||||
h.executeRebuildCacheAction();
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: 'all',
|
||||
scope: 'consumption',
|
||||
});
|
||||
assert.ok(
|
||||
h.state.calls.length > rpcCallsAfterWeeklyChange,
|
||||
'Cache rebuild must invalidate cached fast consumption snapshot'
|
||||
);
|
||||
|
||||
// Verify frontend selectConsumptionTimeRange sends scope=consumption without force=1
|
||||
const {
|
||||
clearConsumptionRangeCache,
|
||||
selectConsumptionTimeRange,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} = await import('../src/store/telemetryStore.js');
|
||||
const prevRange = telemetryStore.getState().selectedTimeRange;
|
||||
const requestedUrls = [];
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
telemetryStore.setState({ selectedTimeRange: prevRange });
|
||||
});
|
||||
clearConsumptionRangeCache();
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requestedUrls.push(String(url));
|
||||
return { ok: true, json: async () => liteCustom };
|
||||
});
|
||||
await selectConsumptionTimeRange('30d');
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
assert.match(requestedUrls[0], /range=30d/);
|
||||
assert.match(requestedUrls[0], /scope=consumption/);
|
||||
assert.doesNotMatch(requestedUrls[0], /force=1/);
|
||||
assert.doesNotMatch(requestedUrls[0], /fastRange=1/);
|
||||
});
|
||||
|
||||
test('scope=conversation switches sessions with zero LS RPCs, preserves usageRevision, reuses stepRevision/multi-agent cache, and powers 0ms client cache switching', async (t) => {
|
||||
const clockMs = Date.parse('2026-11-19T14:00:00.000Z');
|
||||
const mkStep = (idx, offsetMs, model, tok) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: new Date(clockMs - offsetMs).toISOString(),
|
||||
completedAt: new Date(clockMs - offsetMs + 1000).toISOString(),
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||
modelUsage: {
|
||||
model,
|
||||
inputTokens: String(tok),
|
||||
cacheReadTokens: '0',
|
||||
outputTokens: '120',
|
||||
},
|
||||
},
|
||||
plannerResponse: { response: `step-${idx}` },
|
||||
});
|
||||
|
||||
const h = backendHarness({
|
||||
clock: () => clockMs,
|
||||
quotaSummary: {
|
||||
groups: [
|
||||
{
|
||||
displayName: 'Gemini',
|
||||
remainingFraction: 0.85,
|
||||
resetTime: new Date(clockMs + 3 * 3600_000).toISOString(),
|
||||
},
|
||||
{
|
||||
displayName: 'Claude & GPT',
|
||||
remainingFraction: 0.42,
|
||||
resetTime: new Date(clockMs + 4 * 3600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
trajectories: {
|
||||
'conv-claude': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 30 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1200),
|
||||
mkStep(2, 20 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1800),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-gemini': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 10 * 60_000, 'MODEL_PLACEHOLDER_M37', 4000),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-gemini-sub': {
|
||||
trajectory: {
|
||||
metadata: {
|
||||
parentConversationId: 'conv-gemini',
|
||||
rootConversationId: 'conv-gemini',
|
||||
subagentSpec: { typeName: 'research', role: 'Helper' },
|
||||
},
|
||||
steps: [
|
||||
mkStep(1, 9 * 60_000, 'MODEL_PLACEHOLDER_M37', 900),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-claude': {
|
||||
annotations: { title: 'Claude Session' },
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 20 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-gemini': {
|
||||
annotations: { title: 'Gemini Swarm' },
|
||||
stepCount: 1,
|
||||
lastModifiedTime: new Date(clockMs - 10 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-gemini-sub': {
|
||||
stepCount: 1,
|
||||
lastModifiedTime: new Date(clockMs - 9 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
trajectoryMetadata: {
|
||||
parentConversationId: 'conv-gemini',
|
||||
rootConversationId: 'conv-gemini',
|
||||
subagentSpec: { typeName: 'research', role: 'Helper' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 1. Initial full telemetry load on conv-gemini (multi-agent root)
|
||||
const initRes = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-gemini',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(initRes.activeConversation.cascadeId, 'conv-gemini');
|
||||
assert.equal(initRes.activeConversation.subagentCount, 1);
|
||||
assert.equal(initRes.quotas.activePool.family, 'Gemini');
|
||||
const initialUsageRev = Number(initRes.consumption.revision);
|
||||
const rpcAfterInit = h.state.calls.length;
|
||||
|
||||
// 2. Fast switch to conv-claude via scope=conversation: ZERO LS RPCs!
|
||||
const switchClaude = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-claude',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
scope: 'conversation',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(h.state.calls.length, rpcAfterInit, 'scope=conversation must make 0 LS RPC calls');
|
||||
assert.equal(switchClaude.scope, 'conversation');
|
||||
assert.equal(switchClaude.activeConversation.cascadeId, 'conv-claude');
|
||||
assert.equal(switchClaude.activeConversation.stepCount, 2);
|
||||
assert.equal(switchClaude.activeConversation.recentSteps.length, 2);
|
||||
assert.equal(switchClaude.quotas.activePool.family, 'Claude & GPT');
|
||||
assert.equal(switchClaude.consumption.session.calls, 2);
|
||||
assert.equal(switchClaude.needsBackgroundSync, false);
|
||||
assert.ok(switchClaude.stepRevision);
|
||||
|
||||
// 3. Fast switch back to conv-gemini with cached stepRevision -> stepsUnchanged=true & 0 RPCs
|
||||
const switchBackGemini = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-gemini',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: initRes.stepRevision,
|
||||
scope: 'conversation',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(h.state.calls.length, rpcAfterInit);
|
||||
assert.equal(switchBackGemini.scope, 'conversation');
|
||||
assert.equal(switchBackGemini.stepsUnchanged, true);
|
||||
assert.equal(switchBackGemini.activeConversation.recentSteps, undefined);
|
||||
assert.equal(switchBackGemini.quotas.activePool.family, 'Gemini');
|
||||
|
||||
// 4. Subsequent full poll on conv-claude keeps usageRevision identical (decoupled from isCurrentConv!)
|
||||
const fullClaude = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-claude',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: switchClaude.stepRevision,
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(fullClaude.consumption.revision, initialUsageRev);
|
||||
assert.equal(fullClaude.stepsUnchanged, true);
|
||||
assert.equal(fullClaude.consumption.session.calls, 2);
|
||||
|
||||
// 5. Frontend selectConversation: first switch hits scope=conversation; repeat switch hits 0ms client cache + rehydrates stepsUnchanged
|
||||
const {
|
||||
clearConsumptionRangeCache,
|
||||
clearConversationViewCache,
|
||||
selectConversation,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} = await import('../src/store/telemetryStore.js');
|
||||
const prevTel = telemetryStore.getState().telemetry;
|
||||
const prevSel = telemetryStore.getState().selectedConversationId;
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
telemetryStore.setState({ selectedConversationId: prevSel, telemetry: prevTel });
|
||||
});
|
||||
clearConversationViewCache();
|
||||
telemetryStore.setState({ selectedConversationId: 'conv-gemini', telemetry: initRes }, { sync: true });
|
||||
|
||||
const fetchedUrls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const u = String(url);
|
||||
fetchedUrls.push(u);
|
||||
const parsed = new URL(u, 'http://127.0.0.1');
|
||||
const q = Object.fromEntries(parsed.searchParams.entries());
|
||||
const out = await h.executeTelemetryAction(q);
|
||||
return { ok: true, json: async () => JSON.parse(out.body) };
|
||||
});
|
||||
|
||||
// Seed cache by visiting conv-claude first
|
||||
await selectConversation('conv-claude');
|
||||
assert.equal(fetchedUrls.length, 1);
|
||||
assert.match(fetchedUrls[0], /scope=conversation/);
|
||||
assert.match(fetchedUrls[0], /conversationId=conv-claude/);
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-claude');
|
||||
assert.equal(telemetryStore.getState().telemetry.quotas.activePool.family, 'Claude & GPT');
|
||||
|
||||
// Visit conv-gemini (cached from initRes? Let's visit once to cache, then toggle back to conv-claude for 0ms hit!)
|
||||
await selectConversation('conv-gemini');
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-gemini');
|
||||
|
||||
// Toggle back to conv-claude: store MUST update synchronously BEFORE fetch resolves!
|
||||
let releaseSecondFetch;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
fetchedUrls.push(String(url));
|
||||
await new Promise((resolve) => {
|
||||
releaseSecondFetch = resolve;
|
||||
});
|
||||
const parsed = new URL(String(url), 'http://127.0.0.1');
|
||||
const out = await h.executeTelemetryAction(Object.fromEntries(parsed.searchParams.entries()));
|
||||
return { ok: true, json: async () => JSON.parse(out.body) };
|
||||
});
|
||||
|
||||
const pendingSwitch = selectConversation('conv-claude');
|
||||
assert.equal(
|
||||
telemetryStore.getState().telemetry.activeConversation.cascadeId,
|
||||
'conv-claude',
|
||||
'Repeat conversation switch must update activeConversation synchronously in 0ms from client LRU cache'
|
||||
);
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2);
|
||||
assert.match(fetchedUrls[fetchedUrls.length - 1], new RegExp(`stepRevision=${switchClaude.stepRevision}`));
|
||||
releaseSecondFetch();
|
||||
await pendingSwitch;
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,669 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createMockDom } from './mock-dom.mjs';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
import {
|
||||
buildDeterministicModelColorMap,
|
||||
getCanonicalModelColorSeed,
|
||||
mergeModelsByDisplayName,
|
||||
resolveDeterministicModelColor,
|
||||
} from '../src/core/formatters.js';
|
||||
import {
|
||||
clearConsumptionRangeCache,
|
||||
fetchTelemetry,
|
||||
isEquivalentTelemetry,
|
||||
prefetchConsumptionPresets,
|
||||
selectConsumptionTimeRange,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} from '../src/store/telemetryStore.js';
|
||||
import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js';
|
||||
import { uiStore } from '../src/store/uiStore.js';
|
||||
import { i18nStore, setI18nLanguage } from '../src/i18n/index.js';
|
||||
import { createFourSegmentBar } from '../src/components/ui/FourSegmentBar.js';
|
||||
import { ConsumptionView } from '../src/views/ConsumptionView.js';
|
||||
|
||||
function parsePctVar(el, prop = '--seg-w') {
|
||||
const raw = el?.style?.getPropertyValue?.(prop) || '';
|
||||
return Number.parseFloat(raw.replace('%', '')) || 0;
|
||||
}
|
||||
|
||||
test('Perceptual 20-color ring: deterministic cross-machine assignment without green pileups or hardcoded tables', () => {
|
||||
const realUserModels = [
|
||||
'3.7-flash',
|
||||
'3-flash-b',
|
||||
'3.8-flash',
|
||||
'pro-default',
|
||||
'3-flash-c',
|
||||
'3.6-flash',
|
||||
'opus-4-6-thinking',
|
||||
'3.1-flash-lite',
|
||||
'sonnet-4-6',
|
||||
'2.5-flash-lite',
|
||||
'4-argon',
|
||||
'4-carbon',
|
||||
'3.8-flash-n',
|
||||
'4-hydrogen',
|
||||
'orchestrator-carbon',
|
||||
'worker-agy-hydrogen',
|
||||
];
|
||||
|
||||
const mapForward = buildDeterministicModelColorMap(realUserModels);
|
||||
const mapReversed = buildDeterministicModelColorMap([...realUserModels].reverse());
|
||||
assert.deepEqual([...mapForward.entries()], [...mapReversed.entries()]);
|
||||
|
||||
// All 16 models receive 16 completely distinct perceptual HSL colors
|
||||
const uniqueColors = new Set(mapForward.values());
|
||||
assert.equal(uniqueColors.size, realUserModels.length);
|
||||
|
||||
// Merged upstream buckets ('4-carbon' across App vs CLI with different sourceLabels subsets) share identical seed
|
||||
const appMergedCarbon = {
|
||||
displayText: '4-carbon',
|
||||
mergedCount: 2,
|
||||
sourceLabels: ['Gemini 4 Carbon (High)', 'Gemini 4 Carbon (Medium)'],
|
||||
};
|
||||
const cliMergedCarbon = {
|
||||
displayText: '4-carbon',
|
||||
mergedCount: 1,
|
||||
sourceLabels: ['Gemini 4 Carbon (Low)'],
|
||||
label: 'Gemini 4 Carbon (Low)',
|
||||
};
|
||||
assert.equal(getCanonicalModelColorSeed(appMergedCarbon), '4-carbon');
|
||||
const singleModeModels = mergeModelsByDisplayName(
|
||||
[
|
||||
{
|
||||
label: 'Gemini 4 Carbon (Low)',
|
||||
shortName: '4-carbon',
|
||||
upstreamName: '4-carbon',
|
||||
calls: 2,
|
||||
totalTokens: 1000,
|
||||
},
|
||||
],
|
||||
{ modelDisplayMode: 'upstream', showUpstreamModel: true }
|
||||
);
|
||||
assert.equal(singleModeModels[0].displayText, '4-carbon');
|
||||
|
||||
// Arbitrary future models work without hardcoding
|
||||
const future = resolveDeterministicModelColor('Gemini 9 Krypton (Ultra)');
|
||||
assert.match(future, /^hsl\(\d+\s+\d+%\s+\d+%\)$/);
|
||||
assert.equal(future, resolveDeterministicModelColor(' gemini 9 krypton (ultra) '));
|
||||
assert.ok(cliMergedCarbon);
|
||||
});
|
||||
|
||||
test('FourSegmentBar supports percentage scaling while keeping 100% default for Overview', () => {
|
||||
const prevDoc = globalThis.document;
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
try {
|
||||
const barFull = createFourSegmentBar();
|
||||
barFull.update({
|
||||
inputTokens: 200,
|
||||
cacheReadTokens: 500,
|
||||
responseTokens: 200,
|
||||
thinkingTokens: 100,
|
||||
});
|
||||
const segsFull = barFull.el.querySelectorAll('.progress-seg');
|
||||
const sumFull = segsFull.reduce((acc, el) => acc + parsePctVar(el), 0);
|
||||
assert.ok(Math.abs(sumFull - 100) < 0.05);
|
||||
|
||||
const barScaled = createFourSegmentBar();
|
||||
barScaled.update({
|
||||
inputTokens: 200,
|
||||
cacheReadTokens: 500,
|
||||
responseTokens: 200,
|
||||
thinkingTokens: 100,
|
||||
scaleRatio: 0.4,
|
||||
});
|
||||
const segsScaled = barScaled.el.querySelectorAll('.progress-seg');
|
||||
const sumScaled = segsScaled.reduce((acc, el) => acc + parsePctVar(el), 0);
|
||||
assert.ok(Math.abs(sumScaled - 40) < 0.05);
|
||||
} finally {
|
||||
globalThis.document = prevDoc;
|
||||
}
|
||||
});
|
||||
|
||||
test('Backend aggregates per-model breakdown on both sourcesBreakdown and monthlySeries', async () => {
|
||||
const nowMs = Date.parse('2026-11-18T12:00:00Z');
|
||||
const nowIso = '2026-11-18T12:00:00Z';
|
||||
const appCid = 'aaaaaaaa-1111-4111-8111-111111111111';
|
||||
const cliCid = 'cccccccc-2222-4222-8222-222222222222';
|
||||
|
||||
const harness = backendHarness({
|
||||
clock: () => nowMs,
|
||||
trajectories: {
|
||||
[appCid]: {
|
||||
trajectory: {
|
||||
steps: [
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
userInput: { userResponse: 'Hello App' },
|
||||
metadata: { createdAt: nowIso },
|
||||
},
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: nowIso,
|
||||
completedAt: '2026-11-18T12:00:03Z',
|
||||
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M429',
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '6000',
|
||||
cacheReadTokens: '2000',
|
||||
outputTokens: '2000',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: '2026-11-18T12:00:05Z',
|
||||
completedAt: '2026-11-18T12:00:08Z',
|
||||
sourceTrajectoryStepInfo: { stepIndex: 2 },
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M405',
|
||||
apiProvider: 'API_PROVIDER_ANTHROPIC',
|
||||
inputTokens: '4000',
|
||||
cacheReadTokens: '0',
|
||||
outputTokens: '1000',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
[appCid]: {
|
||||
summary: 'App Session',
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
stepCount: 3,
|
||||
createdTime: nowIso,
|
||||
lastModifiedTime: '2026-11-18T12:00:08Z',
|
||||
},
|
||||
},
|
||||
deepStats: {
|
||||
perConvo: {
|
||||
[`cli:${cliCid}`]: {
|
||||
appSource: 'cli',
|
||||
entries: [
|
||||
{
|
||||
ts: '2026-11-18T12:01:00Z',
|
||||
modelRuntimeId: 'MODEL_PLACEHOLDER_M429',
|
||||
inp: 3000,
|
||||
cache: 1000,
|
||||
out: 800,
|
||||
reasoning: 200,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const payload = await harness.buildTelemetryPayloadInternal({ range: 'all' });
|
||||
const sources = payload.consumption?.sourcesBreakdown || [];
|
||||
assert.equal(sources.length, 2);
|
||||
assert.equal(sources[0].name, 'Antigravity App');
|
||||
assert.equal(sources[0].totalTokens, 15_000);
|
||||
assert.equal(sources[0].models.length, 2);
|
||||
assert.equal(sources[1].name, 'Antigravity CLI');
|
||||
assert.equal(sources[1].totalTokens, 5_000);
|
||||
assert.equal(sources[1].models.length, 1);
|
||||
|
||||
// November (index 10) in monthlySeries also carries aggregated per-model breakdown
|
||||
const novBucket = payload.consumption?.monthlySeries?.[10];
|
||||
assert.ok(novBucket);
|
||||
assert.equal(novBucket.totalTokens, 20_000);
|
||||
assert.equal(novBucket.models.length, 2);
|
||||
|
||||
// Active trendSeries bucket carries per-model breakdown while zero-token buckets omit models
|
||||
const trendSlots = payload.consumption?.trendSeries || [];
|
||||
const activeTrendSlot = trendSlots.find((s) => s.tokens > 0);
|
||||
const zeroTrendSlot = trendSlots.find((s) => s.tokens === 0);
|
||||
assert.ok(activeTrendSlot);
|
||||
assert.equal(activeTrendSlot.tokens, 20_000);
|
||||
assert.equal(activeTrendSlot.models.length, 2);
|
||||
if (zeroTrendSlot) {
|
||||
assert.equal(zeroTrendSlot.models, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources + Monthly model bars with long-tail folding & hover popover', async (t) => {
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevTelState = { ...telemetryStore.getState() };
|
||||
const prevUiState = { ...uiStore.getState() };
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
location: { pathname: '/' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
requestAnimationFrame: (cb) => setTimeout(cb, 0),
|
||||
cancelAnimationFrame: (id) => clearTimeout(id),
|
||||
};
|
||||
|
||||
let view = null;
|
||||
t.after(() => {
|
||||
if (view) view.destroy();
|
||||
setI18nLanguage(prevLocale);
|
||||
telemetryStore.setState(prevTelState, { sync: true });
|
||||
uiStore.setState(prevUiState, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
setI18nLanguage('zh-CN');
|
||||
uiStore.setState(
|
||||
{ monitorVisible: true, activeView: 'consumption', settingsOpen: false },
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
const mkModel = (name, tok, calls = 2, costUsd = 0.1) => ({
|
||||
label: name,
|
||||
shortName: name,
|
||||
upstreamName: name,
|
||||
calls,
|
||||
inputTokens: Math.floor(tok * 0.2),
|
||||
cacheReadTokens: Math.floor(tok * 0.6),
|
||||
outputTokens: Math.floor(tok * 0.2),
|
||||
responseTokens: Math.floor(tok * 0.15),
|
||||
thinkingTokens: tok - Math.floor(tok * 0.2) - Math.floor(tok * 0.6) - Math.floor(tok * 0.15),
|
||||
totalTokens: tok,
|
||||
costUsd,
|
||||
unpricedCalls: 0,
|
||||
});
|
||||
|
||||
const mArgon = mkModel('4-argon', 50_000, 10, 0.5);
|
||||
const mCarbon = mkModel('4-carbon', 30_000, 6, 0.3);
|
||||
const mFlash = mkModel('3.8-flash-n', 18_000, 4, 0.12);
|
||||
const mTail1 = mkModel('opus-4-6-thinking', 800, 1, 0.02);
|
||||
const mTail2 = mkModel('3.1-flash-lite', 700, 1, 0.01);
|
||||
const mTail3 = mkModel('2.5-flash-lite', 500, 1, 0.01);
|
||||
|
||||
const emptyMonths = Array.from({ length: 12 }, (_, idx) => ({
|
||||
month: idx + 1,
|
||||
label: `${idx + 1}月`,
|
||||
calls: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
models: [],
|
||||
}));
|
||||
emptyMonths[10] = {
|
||||
month: 11,
|
||||
label: '11月',
|
||||
calls: 23,
|
||||
totalTokens: 100_000,
|
||||
costUsd: 0.96,
|
||||
models: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3],
|
||||
};
|
||||
|
||||
const baseTelemetry = {
|
||||
settings: {
|
||||
language: 'zh-CN',
|
||||
modelDisplayMode: 'upstream',
|
||||
showUpstreamModel: true,
|
||||
},
|
||||
modelBreakdown: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3],
|
||||
consumption: {
|
||||
selectedRange: { key: 'all', label: '全部', startMs: 1_700_000_000_000, endMs: 1_700_086_400_000 },
|
||||
account: {
|
||||
totalTokens: 100_000,
|
||||
inputTokens: 20_000,
|
||||
cacheReadTokens: 60_000,
|
||||
outputTokens: 20_000,
|
||||
responseTokens: 15_000,
|
||||
thinkingTokens: 5_000,
|
||||
calls: 23,
|
||||
costUsd: 0.96,
|
||||
savedCostUsd: 0.25,
|
||||
cacheHitPct: 75.0,
|
||||
},
|
||||
trendSeries: [
|
||||
{
|
||||
index: 0,
|
||||
granularity: 'day',
|
||||
label: '11/17',
|
||||
fullLabel: '11月17日 (周二)',
|
||||
tokens: 0,
|
||||
calls: 0,
|
||||
costUsd: 0,
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
granularity: 'day',
|
||||
label: '11/18',
|
||||
fullLabel: '11月18日 (周三)',
|
||||
tokens: 100_000,
|
||||
inputTokens: 20_000,
|
||||
cacheReadTokens: 60_000,
|
||||
outputTokens: 20_000,
|
||||
calls: 23,
|
||||
costUsd: 0.96,
|
||||
models: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3],
|
||||
},
|
||||
],
|
||||
monthlyYear: 2026,
|
||||
monthlySeries: emptyMonths,
|
||||
sourcesBreakdown: [
|
||||
{
|
||||
name: 'Antigravity App',
|
||||
calls: 20,
|
||||
totalTokens: 80_000,
|
||||
costUsd: 0.8,
|
||||
unpricedCalls: 0,
|
||||
models: [
|
||||
mkModel('4-argon', 40_000, 8, 0.4),
|
||||
mkModel('4-carbon', 25_000, 5, 0.25),
|
||||
mkModel('3.8-flash-n', 13_000, 4, 0.1),
|
||||
mTail1,
|
||||
mTail2,
|
||||
mTail3,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Antigravity CLI',
|
||||
calls: 3,
|
||||
totalTokens: 20_000,
|
||||
costUsd: 0.16,
|
||||
unpricedCalls: 0,
|
||||
models: [
|
||||
mkModel('4-argon', 10_000, 2, 0.1),
|
||||
mkModel('4-carbon', 5_000, 1, 0.05),
|
||||
mkModel('3.8-flash-n', 5_000, 0, 0.01),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
isEquivalentTelemetry(baseTelemetry, {
|
||||
...baseTelemetry,
|
||||
consumption: {
|
||||
...baseTelemetry.consumption,
|
||||
monthlySeries: emptyMonths.map((m, idx) =>
|
||||
idx === 10 ? { ...m, models: [mArgon] } : m
|
||||
),
|
||||
},
|
||||
}),
|
||||
false,
|
||||
'isEquivalentTelemetry must detect model breakdown changes inside monthlySeries'
|
||||
);
|
||||
|
||||
telemetryStore.setState(
|
||||
{ selectedTimeRange: 'all', telemetry: baseTelemetry },
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
view = ConsumptionView({});
|
||||
document.body.appendChild(view.el);
|
||||
await Promise.resolve();
|
||||
|
||||
const allRows = view.el.querySelectorAll('.cons-item-row');
|
||||
const modelRows = allRows.filter((r) => !r.classList.contains('cons-source-row'));
|
||||
const sourceRows = view.el.querySelectorAll('.cons-source-row');
|
||||
assert.equal(modelRows.length, 6);
|
||||
assert.equal(sourceRows.length, 2);
|
||||
|
||||
// 1. Top Models: colored dot appears right after model name & 4-segment bar scales to 50% (not 100%)
|
||||
const argonTitleDot = modelRows[0].querySelector('.cons-title-model-dot');
|
||||
assert.ok(argonTitleDot && !argonTitleDot.hasAttribute('hidden'));
|
||||
const argonDotColor = argonTitleDot.style.getPropertyValue('--dot-color');
|
||||
assert.match(argonDotColor, /^hsl\(/);
|
||||
|
||||
const argonSegSum = modelRows[0]
|
||||
.querySelectorAll('.progress-seg')
|
||||
.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(argonSegSum - 50) < 0.1, `Expected 50% width for 4-argon row, got ${argonSegSum}`);
|
||||
|
||||
// 2. Client Sources: NO multi-line .cons-source-model-chip dump; renders single-line Top 2-3 models + 1 merged '__other__' segment on the bar!
|
||||
assert.equal(sourceRows[0].querySelectorAll('.cons-source-model-chip').length, 0);
|
||||
const appTopItems = sourceRows[0].querySelectorAll('.cons-source-top-item');
|
||||
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-pct')?.textContent, '50%');
|
||||
assert.equal(appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'), argonDotColor);
|
||||
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[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n');
|
||||
assert.equal(appTopItems[2].querySelector('.cons-source-top-pct')?.textContent, '16%');
|
||||
|
||||
const appSegs = sourceRows[0].querySelectorAll('.cons-model-seg');
|
||||
assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment');
|
||||
assert.equal(appSegs[0].style.getPropertyValue('--seg-color'), argonDotColor);
|
||||
assert.equal(appSegs[3].style.getPropertyValue('--seg-color'), 'var(--cons-other-seg)');
|
||||
const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(appBarSum - 80) < 0.1);
|
||||
|
||||
// Hovering Client Source bar hit area OR top-models summary opens shared popover with model details + '其他 (3)'
|
||||
const popover = view.refs.breakdownPopoverEl;
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit');
|
||||
appBarHit.dispatchEvent({ type: 'mouseenter', clientX: 120 });
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App');
|
||||
const popRows = popover.querySelectorAll('.cons-pop-model-row');
|
||||
assert.equal(popRows.length, 4);
|
||||
assert.equal(popRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon');
|
||||
assert.equal(popRows[0].querySelector('.cons-pop-model-pct')?.textContent, '50.0%');
|
||||
assert.equal(popRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)');
|
||||
|
||||
appBarHit.dispatchEvent({ type: 'mouseleave' });
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
|
||||
const appTopModelsEl = sourceRows[0].querySelector('.cons-source-top-models');
|
||||
appTopModelsEl.dispatchEvent({ type: 'mouseenter', clientX: 90 });
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App');
|
||||
appTopModelsEl.dispatchEvent({ type: 'mouseleave' });
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
|
||||
// Verify single-line non-wrapping CSS rules exist for client source top models
|
||||
const { readFileSync } = await import('node:fs');
|
||||
const consCss = readFileSync(new URL('../src/styles/views-consumption.css', import.meta.url), 'utf8');
|
||||
assert.match(consCss, /\.cons-source-foot\s*\{[\s\S]*flex-wrap:\s*nowrap/);
|
||||
assert.match(consCss, /\.cons-source-top-models\s*\{[\s\S]*flex-wrap:\s*nowrap/);
|
||||
assert.match(consCss, /@container\s*\(max-width:\s*340px\)\s*\{\s*\.cons-source-top-item:nth-child\(n\s*\+\s*3\)/);
|
||||
|
||||
// 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & hover popover
|
||||
assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0);
|
||||
const monthCols = view.el.querySelectorAll('.month-col');
|
||||
const novCol = monthCols[10];
|
||||
const novSegs = novCol.querySelectorAll('.month-seg.cons-model-seg');
|
||||
assert.equal(novSegs.length, 4, '3 main models + 1 merged other segment stacked vertically');
|
||||
// Bottom segment of vertical stack is the #1 model (4-argon) with exact matching color
|
||||
assert.equal(novSegs[novSegs.length - 1].style.getPropertyValue('--seg-color'), argonDotColor);
|
||||
const novSegHeightSum = novSegs.reduce((s, el) => s + parsePctVar(el, '--seg-h'), 0);
|
||||
assert.ok(Math.abs(novSegHeightSum - 100) < 0.1);
|
||||
|
||||
novCol.dispatchEvent({ type: 'mouseenter' });
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, '2026年 11月');
|
||||
assert.equal(popover.querySelectorAll('.cons-pop-model-row').length, 4);
|
||||
|
||||
// 4. Usage Trend: taller 184px viewBox & hovering x-axis tick opens trend tooltip with identical model colors + long-tail '其他 (3)'
|
||||
const trendSvg = view.el.querySelector('.trend-svg');
|
||||
assert.match(trendSvg?.getAttribute('viewBox') || '', /\s184$/);
|
||||
const trendTicks = view.el.querySelectorAll('.trend-x-tick');
|
||||
assert.equal(trendTicks.length, 2);
|
||||
trendTicks[1].onclick();
|
||||
const trendTip = view.el.querySelector('.trend-tooltip');
|
||||
assert.equal(trendTip?.hasAttribute('hidden'), false);
|
||||
const trendTipModelRows = trendTip.querySelectorAll('.cons-pop-model-row');
|
||||
assert.equal(trendTipModelRows.length, 4);
|
||||
assert.equal(trendTipModelRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon');
|
||||
assert.equal(
|
||||
trendTipModelRows[0].querySelector('.cons-model-dot')?.style.getPropertyValue('--dot-color'),
|
||||
argonDotColor
|
||||
);
|
||||
assert.equal(trendTipModelRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)');
|
||||
});
|
||||
|
||||
test('selectConsumptionTimeRange serves prefetched presets with 0 network calls, blocks stale 2s poll overwrites, and TrendAreaChart heatmap batches via DocumentFragment', async (t) => {
|
||||
const prevTelState = { ...telemetryStore.getState() };
|
||||
const prevDoc = globalThis.document;
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
telemetryStore.setState(prevTelState, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
});
|
||||
|
||||
clearConsumptionRangeCache();
|
||||
const mkSlice = (key, label, totalTokens, rev = 7) => ({
|
||||
revision: rev,
|
||||
selectedRange: { key, label, startMs: 1_700_000_000_000, endMs: 1_700_086_400_000 },
|
||||
session: { totalTokens },
|
||||
account: { totalTokens, calls: 2, inputTokens: totalTokens, cacheReadTokens: 0, outputTokens: 0, costUsd: 0.1, savedCostUsd: 0, cacheHitPct: 0 },
|
||||
trendSeries: [{ index: 0, label: '11/19', fullLabel: '11月19日', tokens: totalTokens, calls: 2, costUsd: 0.1 }],
|
||||
sourcesBreakdown: [{ name: 'Antigravity App', calls: 2, totalTokens, costUsd: 0.1, models: [] }],
|
||||
modelBreakdown: [{ label: 'Claude 4.5 Sonnet', shortName: 'Sonnet 4.5', calls: 2, totalTokens, costUsd: 0.1 }],
|
||||
});
|
||||
|
||||
const baseTelemetry = {
|
||||
account: { email: 'u@example.com', status: 'signedIn' },
|
||||
settings: { language: 'zh-CN', weeklyLimitMode: 'official' },
|
||||
cloudStatus: { catalogVersion: 'v1' },
|
||||
activeConversation: { cascadeId: 'c1', recentSteps: [], agents: [] },
|
||||
consumption: {
|
||||
...mkSlice('today', '今日', 1000, 7),
|
||||
presets: { today: { label: '今日', account: { totalTokens: 1000 } } },
|
||||
monthlyYear: 2026,
|
||||
monthlySeries: [],
|
||||
},
|
||||
modelBreakdown: mkSlice('today', '今日', 1000, 7).modelBreakdown,
|
||||
};
|
||||
telemetryStore.setState({ selectedTimeRange: 'today', telemetry: baseTelemetry }, { sync: true });
|
||||
|
||||
const requestedUrls = [];
|
||||
let resolveStalePoll = null;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const u = String(url);
|
||||
requestedUrls.push(u);
|
||||
if (u.includes('scope=consumption-presets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
scope: 'consumption-presets',
|
||||
usageRevision: 7,
|
||||
ranges: {
|
||||
cycle: mkSlice('cycle', '当前周期', 4000, 7),
|
||||
today: mkSlice('today', '今日', 1000, 7),
|
||||
'24h': mkSlice('24h', '近 24 小时', 1500, 7),
|
||||
'7d': mkSlice('7d', '近 7 天', 7000, 7),
|
||||
'14d': mkSlice('14d', '近 14 天', 14000, 7),
|
||||
'30d': mkSlice('30d', '近 30 天', 30000, 7),
|
||||
all: mkSlice('all', '全部时间', 90000, 7),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (u.includes('scope=consumption') && u.includes('range=30d')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
scope: 'consumption',
|
||||
usageRevision: 8,
|
||||
consumption: mkSlice('30d', '近 30 天', 31000, 8),
|
||||
modelBreakdown: mkSlice('30d', '近 30 天', 31000, 8).modelBreakdown,
|
||||
}),
|
||||
};
|
||||
}
|
||||
// Simulated slow 2s background poll started on 'today' that resolves later with rev=8
|
||||
return {
|
||||
ok: true,
|
||||
json: async () =>
|
||||
new Promise((resolve) => {
|
||||
resolveStalePoll = () =>
|
||||
resolve({
|
||||
...baseTelemetry,
|
||||
consumption: {
|
||||
...baseTelemetry.consumption,
|
||||
...mkSlice('today', '今日', 1200, 8),
|
||||
},
|
||||
modelBreakdown: mkSlice('today', '今日', 1200, 8).modelBreakdown,
|
||||
});
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
// 1. Entering ConsumptionView prefetches all 7 presets once
|
||||
assert.equal(await prefetchConsumptionPresets(), true);
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
assert.match(requestedUrls[0], /scope=consumption-presets/);
|
||||
|
||||
// 2. Switching across presets hits rangeCache with ZERO network requests and atomic state swap
|
||||
await selectConsumptionTimeRange('7d');
|
||||
assert.equal(requestedUrls.length, 1, 'Cached preset switch must issue 0 HTTP requests');
|
||||
assert.equal(telemetryStore.getState().selectedTimeRange, '7d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '7d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 7000);
|
||||
|
||||
await selectConsumptionTimeRange('today');
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
|
||||
// 3. Stale in-flight 2s background poll ('today', rev=8) finishes AFTER user switched to '30d' locally:
|
||||
// must NOT overwrite view back to 'today', and should trigger silent background revalidation for '30d'
|
||||
const stalePollPromise = fetchTelemetry({ force: false });
|
||||
await Promise.resolve();
|
||||
await selectConsumptionTimeRange('30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 30000);
|
||||
|
||||
assert.equal(typeof resolveStalePoll, 'function');
|
||||
resolveStalePoll();
|
||||
await stalePollPromise;
|
||||
// Wait microtasks for silent background scope=consumption revalidation of 30d
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.equal(telemetryStore.getState().selectedTimeRange, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 31000);
|
||||
|
||||
// 4. TrendAreaChart >90d heatmap builds all cells cleanly via DocumentFragment when available
|
||||
const { document } = createMockDom();
|
||||
let fragUsed = false;
|
||||
document.createDocumentFragment = () => {
|
||||
fragUsed = true;
|
||||
const holder = document.createElement('div');
|
||||
holder.isFragment = true;
|
||||
return holder;
|
||||
};
|
||||
const origAppend = Object.getPrototypeOf(document.createElement('div')).appendChild;
|
||||
globalThis.document = document;
|
||||
const chart = createTrendAreaChart();
|
||||
const hmGrid = chart.el.querySelector('.trend-hm-grid');
|
||||
hmGrid.appendChild = function (node) {
|
||||
if (node?.isFragment) {
|
||||
for (const child of [...(node.children || [])]) {
|
||||
origAppend.call(this, child);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
return origAppend.call(this, node);
|
||||
};
|
||||
const startDay = Date.parse('2026-06-01T00:00:00.000Z');
|
||||
const slots = Array.from({ length: 100 }, (_, i) => ({
|
||||
index: i,
|
||||
granularity: 'day',
|
||||
startMs: startDay + i * 86400_000,
|
||||
label: `D${i}`,
|
||||
fullLabel: `Day ${i}`,
|
||||
tokens: (i % 5) * 1000,
|
||||
calls: i % 5,
|
||||
costUsd: 0.05,
|
||||
}));
|
||||
chart.update(slots);
|
||||
assert.equal(fragUsed, true);
|
||||
assert.equal(
|
||||
chart.el.querySelectorAll('.trend-hm-cell').filter((c) => !c.classList.contains('is-pad')).length,
|
||||
100
|
||||
);
|
||||
chart.destroy();
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -649,4 +649,17 @@ test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window
|
||||
p.quotas.weekly.costUsd,
|
||||
+(geminiPool.cycleWeekly.costUsd + argonPool.cycleWeekly.costUsd + claudePool.cycleWeekly.costUsd).toFixed(2)
|
||||
);
|
||||
|
||||
// Consumption preset 'cycle' and selected range 'cycle' match quotas.weekly across heterogeneous pool reset windows
|
||||
assert.equal(p.consumption.presets.cycle.account.calls, 5);
|
||||
assert.equal(p.consumption.presets.cycle.account.totalTokens, 155_000);
|
||||
|
||||
const pCycle = await h.buildTelemetryPayloadInternal('multiCycleConv', false, { range: 'cycle' });
|
||||
assert.equal(pCycle.consumption.selectedRange.key, 'cycle');
|
||||
assert.equal(pCycle.consumption.account.calls, 5);
|
||||
assert.equal(pCycle.consumption.account.totalTokens, 155_000);
|
||||
const cycleModelsTok = pCycle.modelBreakdown.reduce((sum, m) => sum + m.totalTokens, 0);
|
||||
assert.equal(cycleModelsTok, 155_000);
|
||||
const cycleSourcesTok = pCycle.consumption.sourcesBreakdown.reduce((sum, s) => sum + s.totalTokens, 0);
|
||||
assert.equal(cycleSourcesTok, 155_000);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import {
|
||||
DEFAULT_REPO_ROOT,
|
||||
collectReleaseRuntimeFiles,
|
||||
packReleaseZip,
|
||||
} from '../scripts/pack-release-zip.mjs';
|
||||
|
||||
test('pack-release-zip ships only runtime-essential files, excludes dev bloat, and extracts a self-contained runnable plugin', async (t) => {
|
||||
const relFiles = collectReleaseRuntimeFiles(DEFAULT_REPO_ROOT);
|
||||
|
||||
// Required runtime files exist in whitelist
|
||||
for (const mustHave of [
|
||||
'plugin.json',
|
||||
'mcp_config.json',
|
||||
'pricing-catalog.json',
|
||||
'LICENSE',
|
||||
'assets/logo.svg',
|
||||
'sidecars/panel/sidecar.json',
|
||||
'sidecars/panel/index.html',
|
||||
'sidecars/panel/app.js',
|
||||
'sidecars/panel/styles.css',
|
||||
'sidecars/panel/main.mjs',
|
||||
'sidecars/panel/mcp-entry.mjs',
|
||||
'sidecars/panel/bridge-daemon.mjs',
|
||||
'sidecars/panel/standalone.mjs',
|
||||
'sidecars/panel/cli-statusline.mjs',
|
||||
'sidecars/panel/trajectory-metrics.mjs',
|
||||
'sidecars/panel/backend/api-actions.mjs',
|
||||
'sidecars/panel/backend/account-credentials.ps1',
|
||||
'sidecars/panel/shared/settings-normalization.mjs',
|
||||
]) {
|
||||
assert.ok(relFiles.includes(mustHave), `Release whitelist must include ${mustHave}`);
|
||||
}
|
||||
|
||||
// Non-runtime dev/doc/test/preview files must NEVER enter the release ZIP
|
||||
for (const rel of relFiles) {
|
||||
assert.doesNotMatch(rel, /^sidecars\/panel\/(?:src|test|scripts)\//);
|
||||
assert.doesNotMatch(rel, /\.png$/i);
|
||||
assert.doesNotMatch(rel, /^README/i);
|
||||
assert.doesNotMatch(rel, /^\.gitignore$/);
|
||||
assert.doesNotMatch(rel, /(?:^|\/)(?:\.git|\.data|node_modules|plan|dist)(?:\/|$)/);
|
||||
}
|
||||
assert.equal(relFiles.includes('sidecars/panel/package.json'), false);
|
||||
|
||||
const workDir = mkdtempSync(join(tmpdir(), 'ag-um-pack-test-'));
|
||||
t.after(() => {
|
||||
try {
|
||||
rmSync(workDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore temp cleanup error
|
||||
}
|
||||
});
|
||||
|
||||
const zipPath = join(workDir, 'usage-monitor.zip');
|
||||
const extractDir = join(workDir, 'extracted');
|
||||
const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile: zipPath });
|
||||
|
||||
assert.ok(existsSync(zipPath));
|
||||
assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend');
|
||||
assert.ok(
|
||||
summary.zipBytes < 750 * 1024,
|
||||
`Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB`
|
||||
);
|
||||
|
||||
// Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists)
|
||||
mkdirSync(extractDir, { recursive: true });
|
||||
if (process.platform === 'win32') {
|
||||
execFileSync(
|
||||
'powershell.exe',
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
`Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipPath.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`,
|
||||
],
|
||||
{ stdio: 'pipe', windowsHide: true }
|
||||
);
|
||||
} else {
|
||||
execFileSync('unzip', ['-oq', zipPath, '-d', extractDir], { stdio: 'pipe' });
|
||||
}
|
||||
|
||||
const pluginRoot = join(extractDir, 'usage-monitor');
|
||||
assert.ok(existsSync(join(pluginRoot, 'plugin.json')));
|
||||
const manifest = JSON.parse(readFileSync(join(pluginRoot, 'plugin.json'), 'utf8'));
|
||||
assert.equal(manifest.name, 'usage-monitor');
|
||||
assert.ok(existsSync(join(pluginRoot, manifest.logo)));
|
||||
|
||||
// Verify zero broken syntax and clean standalone ESM load from the extracted clean tree (no src/, test/, package.json)
|
||||
for (const rel of relFiles) {
|
||||
if (rel.endsWith('.mjs') || rel === 'sidecars/panel/app.js') {
|
||||
execFileSync(process.execPath, ['--check', join(pluginRoot, rel)], { stdio: 'pipe' });
|
||||
}
|
||||
}
|
||||
|
||||
const apiMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/backend/api-actions.mjs')).href);
|
||||
assert.equal(typeof apiMod.executeTelemetryAction, 'function');
|
||||
const cliMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/cli-statusline.mjs')).href);
|
||||
assert.equal(typeof cliMod.runCliStatusLineMain, 'function');
|
||||
});
|
||||
@@ -0,0 +1,827 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs';
|
||||
import { classifyStepAnomalyError, extractModelSteps } from '../trajectory-metrics.mjs';
|
||||
import { buildScopedModelBreakdown } from '../backend/usage-aggregator.mjs';
|
||||
import { createMockDom } from './mock-dom.mjs';
|
||||
import { i18nStore } from '../src/i18n/index.js';
|
||||
import {
|
||||
buildModelAnomalyDiagnostic,
|
||||
buildStepAnomalyDiagnostic,
|
||||
formatAnomalyTagText,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
} from '../src/core/formatters.js';
|
||||
import { ContextSegmentMeter } from '../src/components/ui/ContextSegmentMeter.js';
|
||||
import { STEP_COLUMN_REGISTRY } from '../src/registries/stepColumnRegistry.js';
|
||||
import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js';
|
||||
import {
|
||||
createModelFitChart,
|
||||
createSessionLineChart,
|
||||
} from '../src/components/charts/SessionStepCharts.js';
|
||||
import { StepsDetailView } from '../src/views/StepsDetailView.js';
|
||||
import { telemetryStore } from '../src/store/telemetryStore.js';
|
||||
import { uiStore } from '../src/store/uiStore.js';
|
||||
|
||||
function encodeVarint(val) {
|
||||
let v = BigInt(val);
|
||||
if (v < 0n) v = BigInt.asUintN(64, v);
|
||||
const out = [];
|
||||
while (v >= 0x80n) {
|
||||
out.push(Number((v & 0x7fn) | 0x80n));
|
||||
v >>= 7n;
|
||||
}
|
||||
out.push(Number(v));
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
function encodeFieldVarint(fieldNo, val) {
|
||||
return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]);
|
||||
}
|
||||
|
||||
function encodeFieldBytes(fieldNo, bufOrStr) {
|
||||
const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8');
|
||||
return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]);
|
||||
}
|
||||
|
||||
function encodeTimestamp(sec, nanos = 0) {
|
||||
return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]);
|
||||
}
|
||||
|
||||
function encodeRetryInfo({ error = '', reasonCode = 1, delaySec = 0, delayNanos = 0 } = {}) {
|
||||
const parts = [];
|
||||
if (error) parts.push(encodeFieldBytes(3, error));
|
||||
if (reasonCode) parts.push(encodeFieldVarint(5, reasonCode));
|
||||
if (delaySec || delayNanos) {
|
||||
parts.push(encodeFieldBytes(7, encodeTimestamp(delaySec, delayNanos)));
|
||||
}
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function encodeStepMeta({
|
||||
createdSec,
|
||||
finishedSec,
|
||||
stepIndex,
|
||||
modelEnumInt = 0,
|
||||
inputTokens = 0,
|
||||
cacheReadTokens = 0,
|
||||
outputTokens = 0,
|
||||
retryInfos = [],
|
||||
}) {
|
||||
const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))];
|
||||
if (finishedSec) parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec)));
|
||||
if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) {
|
||||
const muParts = [];
|
||||
if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt));
|
||||
if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens));
|
||||
if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens));
|
||||
if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens));
|
||||
muParts.push(encodeFieldVarint(6, 24));
|
||||
parts.push(encodeFieldBytes(9, Buffer.concat(muParts)));
|
||||
}
|
||||
parts.push(encodeFieldBytes(20, encodeFieldVarint(2, stepIndex)));
|
||||
for (const ri of retryInfos) {
|
||||
parts.push(encodeFieldBytes(28, encodeRetryInfo(ri)));
|
||||
}
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function encodeErrorMessagePayload({
|
||||
userErrorMessage = '',
|
||||
shortError = '',
|
||||
errorCode = '',
|
||||
shouldShowModel = false,
|
||||
shouldShowUser = false,
|
||||
}) {
|
||||
const errParts = [];
|
||||
if (userErrorMessage) errParts.push(encodeFieldBytes(1, userErrorMessage));
|
||||
if (shortError) errParts.push(encodeFieldBytes(2, shortError));
|
||||
if (errorCode) errParts.push(encodeFieldBytes(7, errorCode));
|
||||
const inner = [encodeFieldBytes(3, Buffer.concat(errParts))];
|
||||
if (shouldShowModel) inner.push(encodeFieldVarint(4, 1));
|
||||
if (shouldShowUser) inner.push(encodeFieldVarint(5, 1));
|
||||
return encodeFieldBytes(24, Buffer.concat(inner));
|
||||
}
|
||||
|
||||
function encodeGenMeta({
|
||||
stepIndex,
|
||||
cascadeId,
|
||||
responseModel,
|
||||
modelDisplayName,
|
||||
retryCount = 0,
|
||||
retryInfos = [],
|
||||
}) {
|
||||
const mapCascade = Buffer.concat([
|
||||
encodeFieldBytes(1, 'cascade_id'),
|
||||
encodeFieldBytes(2, cascadeId),
|
||||
]);
|
||||
const chatParts = [
|
||||
encodeFieldBytes(11, encodeTimestamp(1, 0)),
|
||||
encodeFieldBytes(19, responseModel),
|
||||
encodeFieldBytes(20, mapCascade),
|
||||
encodeFieldBytes(21, modelDisplayName),
|
||||
];
|
||||
if (retryCount > 0) chatParts.push(encodeFieldVarint(14, retryCount));
|
||||
for (const ri of retryInfos) {
|
||||
chatParts.push(encodeFieldBytes(17, encodeRetryInfo(ri)));
|
||||
}
|
||||
return Buffer.concat([
|
||||
encodeFieldVarint(2, stepIndex),
|
||||
encodeFieldBytes(1, Buffer.concat(chatParts)),
|
||||
]);
|
||||
}
|
||||
|
||||
function installMockBrowser() {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevRaf = globalThis.requestAnimationFrame;
|
||||
const prevCaf = globalThis.cancelAnimationFrame;
|
||||
const prevResizeObs = globalThis.ResizeObserver;
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
innerWidth: 960,
|
||||
innerHeight: 720,
|
||||
getComputedStyle: () => ({ getPropertyValue: () => '' }),
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
globalThis.requestAnimationFrame = (fn) => {
|
||||
fn();
|
||||
return 1;
|
||||
};
|
||||
globalThis.cancelAnimationFrame = () => {};
|
||||
globalThis.ResizeObserver = class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
};
|
||||
return {
|
||||
document,
|
||||
restore() {
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.requestAnimationFrame = prevRaf;
|
||||
globalThis.cancelAnimationFrame = prevCaf;
|
||||
globalThis.ResizeObserver = prevResizeObs;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('SQLite protobuf decoder + trajectory-metrics + usage-aggregator decode chatModel retries, checkpoint retries, deduplicated ERROR_MESSAGE, and trailing terminal errors', (t) => {
|
||||
const sqliteMod =
|
||||
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||
if (!sqliteMod?.DatabaseSync) {
|
||||
t.skip('node:sqlite DatabaseSync unavailable');
|
||||
return;
|
||||
}
|
||||
const { DatabaseSync } = sqliteMod;
|
||||
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-anomaly-sqlite-'));
|
||||
t.after(() => rmSync(tempRoot, { recursive: true, force: true }));
|
||||
|
||||
const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||
const dbPath = join(tempRoot, `${cid}.db`);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||
`);
|
||||
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||
|
||||
const baseSec = 1794960000;
|
||||
// Step 0: USER_INPUT (step_type=14)
|
||||
db.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec, finishedSec: baseSec, stepIndex: 0 }),
|
||||
encodeFieldBytes(19, encodeFieldBytes(2, '帮我排查超时'))
|
||||
);
|
||||
// Step 1: Normal model response (zero anomalies)
|
||||
db.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 1,
|
||||
finishedSec: baseSec + 3,
|
||||
stepIndex: 1,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 260,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, 'ok'))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 1,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-flash',
|
||||
modelDisplayName: 'Gemini 3 Flash',
|
||||
})
|
||||
);
|
||||
|
||||
// Step 2: Preceding ERROR_MESSAGE (duplicate of retryInfo capacity 503) — should be deduplicated against step 3 retryInfos
|
||||
db.prepare('INSERT INTO steps VALUES (2, 17, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec + 4, finishedSec: baseSec + 4, stepIndex: 2 }),
|
||||
encodeErrorMessagePayload({
|
||||
shortError: 'HTTP 503 No capacity available for model',
|
||||
errorCode: 'UNAVAILABLE',
|
||||
shouldShowUser: false,
|
||||
})
|
||||
);
|
||||
// Step 3: Retried model response with 2 retryInfos (timeout 2.5s + capacity 5s)
|
||||
db.prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 5,
|
||||
finishedSec: baseSec + 15,
|
||||
stepIndex: 3,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 600,
|
||||
cacheReadTokens: 3000,
|
||||
outputTokens: 300,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, 'retried ok'))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 3,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-flash',
|
||||
modelDisplayName: 'Gemini 3 Flash',
|
||||
retryCount: 2,
|
||||
retryInfos: [
|
||||
{
|
||||
error: 'stream idle timeout: no data received for 60s',
|
||||
reasonCode: 1,
|
||||
delaySec: 2,
|
||||
delayNanos: 500_000_000,
|
||||
},
|
||||
{
|
||||
error: 'HTTP 503 No capacity available for model',
|
||||
reasonCode: 1,
|
||||
delaySec: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
// Step 4: CHECKPOINT (step_type=18) with metadata.fn=28 retryInfo (model_output)
|
||||
db.prepare('INSERT INTO steps VALUES (4, 18, 3, ?, NULL)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 16,
|
||||
finishedSec: baseSec + 19,
|
||||
stepIndex: 4,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 400,
|
||||
outputTokens: 120,
|
||||
retryInfos: [
|
||||
{
|
||||
error: 'invalid tool call arguments JSON',
|
||||
reasonCode: 2,
|
||||
delaySec: 1,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
// Step 5: Model step followed by turn-ending terminal ERROR_MESSAGE (status=7 CORTEX_STEP_STATUS_ERROR)
|
||||
db.prepare('INSERT INTO steps VALUES (5, 15, 7, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 20,
|
||||
finishedSec: baseSec + 25,
|
||||
stepIndex: 5,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 200,
|
||||
outputTokens: 0,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, ''))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 5,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-pro',
|
||||
modelDisplayName: 'Gemini 3 Pro',
|
||||
})
|
||||
);
|
||||
// Step 6: Trailing terminal ERROR_MESSAGE (should attach to step 5)
|
||||
db.prepare('INSERT INTO steps VALUES (6, 17, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec + 25, finishedSec: baseSec + 25, stepIndex: 6 }),
|
||||
encodeErrorMessagePayload({
|
||||
userErrorMessage: 'TLS handshake timeout while reaching upstream',
|
||||
shortError: 'dial tcp: TLS handshake timeout',
|
||||
errorCode: 'DEADLINE_EXCEEDED',
|
||||
shouldShowUser: true,
|
||||
})
|
||||
);
|
||||
db.close();
|
||||
|
||||
const traj = readLocalSqliteTrajectory(dbPath);
|
||||
assert.ok(traj, 'SQLite trajectory decoded');
|
||||
const gen1 = traj.generatorMetadata.find((g) => g.stepIndices?.includes(3));
|
||||
assert.equal(gen1?.chatModel?.retryCount, 2);
|
||||
assert.equal(gen1?.chatModel?.retryInfos?.length, 2);
|
||||
assert.equal(gen1?.chatModel?.retryInfos?.[0]?.retryDelay, '2.5s');
|
||||
assert.equal(traj.steps[4]?.metadata?.retryInfos?.length, 1);
|
||||
assert.equal(traj.steps[6]?.errorMessage?.shouldShowUser, true);
|
||||
assert.match(traj.steps[6]?.errorMessage?.error?.userErrorMessage || '', /TLS handshake timeout/);
|
||||
|
||||
const extracted = extractModelSteps(traj.steps, traj.generatorMetadata);
|
||||
const s1 = extracted.find((s) => s.stepIndex === 1);
|
||||
const s3 = extracted.find((s) => s.stepIndex === 3);
|
||||
const s4 = extracted.find((s) => s.stepIndex === 4);
|
||||
const s5 = extracted.find((s) => s.stepIndex === 5);
|
||||
|
||||
assert.equal(s1.anomaly, undefined, 'Normal step carries zero anomaly payload');
|
||||
assert.equal(s1.anomalySig, undefined, 'Normal step omits anomalySig');
|
||||
|
||||
assert.ok(s3.anomaly, 'Step 3 has anomaly record');
|
||||
assert.equal(s3.anomaly.count, 2, 'Duplicate preceding 503 ERROR_MESSAGE is deduplicated against retryInfos');
|
||||
assert.equal(s3.anomaly.totalDelaySec, 7.5);
|
||||
assert.equal(s3.anomaly.kinds.timeout, 1);
|
||||
assert.equal(s3.anomaly.kinds.capacity, 1);
|
||||
assert.equal(s3.anomaly.severity, 'warn');
|
||||
|
||||
assert.ok(s4.anomaly, 'Checkpoint step 4 decodes metadata.fn=28 retryInfo');
|
||||
assert.equal(s4.anomaly.primaryKind, 'model_output');
|
||||
assert.equal(s4.anomaly.count, 1);
|
||||
|
||||
assert.ok(s5.anomaly, 'Trailing turn-ending ERROR_MESSAGE attaches to step 5');
|
||||
assert.equal(s5.anomaly.primaryKind, 'timeout');
|
||||
assert.equal(s5.anomaly.severity, 'danger', 'Terminal error escalates severity to danger');
|
||||
assert.equal(s5.anomaly.events[0]?.terminal, true);
|
||||
assert.equal(s5.speedReason, 'error');
|
||||
assert.equal(s5.totalTokPerSec, null);
|
||||
|
||||
// Also check classifyStepAnomalyError directly for rate_limit & safety
|
||||
assert.equal(classifyStepAnomalyError('HTTP 429 RESOURCE_EXHAUSTED quota exceeded'), 'rate_limit');
|
||||
assert.equal(classifyStepAnomalyError('blocked by safety filter policy'), 'safety');
|
||||
|
||||
const breakdown = buildScopedModelBreakdown(extracted, (st) => ({
|
||||
label: st.responseModel || 'Unknown',
|
||||
shortName: st.responseModel || 'Unknown',
|
||||
rawModel: st.model || '',
|
||||
upstreamName: st.responseModel || '',
|
||||
costUsd: 0.01,
|
||||
}));
|
||||
const flash = breakdown.find((m) => m.label === 'gemini-3-flash');
|
||||
const pro = breakdown.find((m) => m.label === 'gemini-3-pro');
|
||||
assert.ok(flash && pro);
|
||||
assert.equal(flash.anomalySteps, 1);
|
||||
assert.equal(flash.anomalyCount, 2);
|
||||
assert.equal(flash.anomalyTotalDelaySec, 7.5);
|
||||
assert.equal(pro.anomalySteps, 1);
|
||||
assert.equal(pro.anomalyCount, 1);
|
||||
assert.equal(pro.anomalyDangerCount, 1);
|
||||
assert.equal(pro.anomalyByKind.timeout, 1);
|
||||
});
|
||||
|
||||
test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY.tps renders integer speeds and error reasons', () => {
|
||||
const env = installMockBrowser();
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
|
||||
assert.equal(formatSpeedMetric(100), '100 tok/s');
|
||||
assert.equal(formatSpeedMetric(128.4), '128 tok/s');
|
||||
assert.equal(formatSpeedMetric(145.6), '146 tok/s');
|
||||
assert.equal(formatSpeedMetric(99.9), '99.9 tok/s');
|
||||
assert.equal(formatSpeedMetric(65.7), '65.7 tok/s');
|
||||
assert.equal(formatSpeedMetric(0), '0.0 tok/s');
|
||||
assert.equal(formatSpeedMetric(null), '—');
|
||||
|
||||
const fastCell = STEP_COLUMN_REGISTRY.tps.createCell();
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 128.4 }, { showStepSpeedColor: false });
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '128 tok/s');
|
||||
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 65.7 }, { showStepSpeedColor: false });
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '65.7 tok/s');
|
||||
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(
|
||||
fastCell.refs,
|
||||
{ tokPerSec: null, selectedSpeedReason: 'error' },
|
||||
{ showStepSpeedColor: false }
|
||||
);
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '—');
|
||||
assert.equal(fastCell.refs.speedReason.textContent, '调用报错');
|
||||
|
||||
// Seconds >= 100s also drop decimals in ttft & duration columns
|
||||
assert.equal(formatMetric(100, 's'), '100s');
|
||||
assert.equal(formatMetric(142.6, 's'), '143s');
|
||||
assert.equal(formatMetric(99.9, 's'), '99.9s');
|
||||
|
||||
const ttftCell = STEP_COLUMN_REGISTRY.ttft.createCell();
|
||||
STEP_COLUMN_REGISTRY.ttft.updateCell(ttftCell.refs, { ttftSec: 124.7 });
|
||||
assert.equal(ttftCell.refs.valEl.textContent, '125s');
|
||||
STEP_COLUMN_REGISTRY.ttft.updateCell(ttftCell.refs, { ttftSec: 14.2 });
|
||||
assert.equal(ttftCell.refs.valEl.textContent, '14.2s');
|
||||
|
||||
const durCell = STEP_COLUMN_REGISTRY.duration.createCell();
|
||||
STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 108.4 });
|
||||
assert.equal(durCell.refs.valEl.textContent, '108s');
|
||||
STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 42.3 });
|
||||
assert.equal(durCell.refs.valEl.textContent, '42.3s');
|
||||
|
||||
// ContextSegmentMeter renders crisp separated blocks (.ctx-segment-meter + .is-active + .has-sep)
|
||||
const meter = ContextSegmentMeter({
|
||||
context: {
|
||||
limitTokens: 200_000,
|
||||
toolResultsTokens: 60_000,
|
||||
assistantTokens: 20_000,
|
||||
skillsTokens: 1_000,
|
||||
},
|
||||
});
|
||||
assert.equal(meter.el.classList.contains('ctx-segment-meter'), true);
|
||||
const activeSegs = meter.refs.segments.filter((s) => s.classList.contains('is-active'));
|
||||
assert.equal(activeSegs.length, 3);
|
||||
assert.equal(activeSegs[0].classList.contains('has-sep'), false, 'First active segment has no left cut gap');
|
||||
assert.equal(activeSegs[1].classList.contains('has-sep'), true, 'Second active segment has 2px cut gap');
|
||||
assert.equal(activeSegs[2].classList.contains('has-sep'), true, 'Third active segment has 2px cut gap');
|
||||
assert.match(activeSegs[0].getAttribute('title') || '', /60\.0k/);
|
||||
const inactiveSegs = meter.refs.segments.filter((s) => !s.classList.contains('is-active'));
|
||||
assert.equal(inactiveSegs.length, 7);
|
||||
assert.equal(inactiveSegs.every((s) => !s.classList.contains('has-sep') && !s.getAttribute('title')), true);
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('StepTableWidget tints entire anomaly rows with zero extra column width and reveals full diagnostic popover on row hover', () => {
|
||||
const env = installMockBrowser();
|
||||
const widget = StepTableWidget({ standalone: true });
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
|
||||
const colKeys = ['step', 'model', 'tps', 'ttft'];
|
||||
const steps = [
|
||||
{
|
||||
stepIndex: 4924,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: 132.6,
|
||||
ttftSec: 2.1,
|
||||
anomalySig: 'timeout:1:w:2.5',
|
||||
anomaly: {
|
||||
count: 1,
|
||||
primaryKind: 'timeout',
|
||||
severity: 'warn',
|
||||
totalDelaySec: 2.5,
|
||||
kinds: { timeout: 1 },
|
||||
events: [
|
||||
{
|
||||
attempt: 1,
|
||||
kind: 'timeout',
|
||||
delaySec: 2.5,
|
||||
terminal: false,
|
||||
message: 'stream idle timeout: no data received',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
stepIndex: 4922,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: null,
|
||||
selectedSpeedReason: 'error',
|
||||
ttftSec: null,
|
||||
anomalySig: 'rate_limit:1:d:0',
|
||||
anomaly: {
|
||||
count: 1,
|
||||
primaryKind: 'rate_limit',
|
||||
severity: 'danger',
|
||||
totalDelaySec: 0,
|
||||
kinds: { rate_limit: 1 },
|
||||
events: [
|
||||
{
|
||||
attempt: 1,
|
||||
kind: 'rate_limit',
|
||||
delaySec: 0,
|
||||
terminal: true,
|
||||
message: 'HTTP 429 RESOURCE_EXHAUSTED',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
stepIndex: 4920,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: 65.7,
|
||||
ttftSec: 1.4,
|
||||
anomalySig: '',
|
||||
},
|
||||
];
|
||||
|
||||
widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', {
|
||||
hasSubagents: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepTurnRail: false,
|
||||
});
|
||||
|
||||
// Zero extra columns and zero inline text badges added to table cells
|
||||
assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length);
|
||||
const rows = widget.refs.stepsTbody.children;
|
||||
assert.equal(rows.length, 3);
|
||||
assert.equal(rows[0].children.length, colKeys.length);
|
||||
assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column');
|
||||
|
||||
// Row 0: warn tint (orange) + integer speed 133 tok/s
|
||||
assert.equal(rows[0].classList.contains('is-anomaly-warn'), true);
|
||||
assert.equal(rows[0].classList.contains('is-anomaly-danger'), false);
|
||||
assert.equal(rows[0].children[2].textContent, '133 tok/s');
|
||||
|
||||
// Row 1: danger tint (red)
|
||||
assert.equal(rows[1].classList.contains('is-anomaly-danger'), true);
|
||||
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
|
||||
assert.equal(rows[2].classList.contains('is-anomaly-warn'), false);
|
||||
assert.equal(rows[2].classList.contains('is-anomaly-danger'), false);
|
||||
assert.equal(rows[2].children[2].textContent, '65.7 tok/s');
|
||||
|
||||
// Hovering the tinted row expands the structured diagnostic popover
|
||||
const tipEl = widget.refs.anomalyTipEl;
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
rows[0].onmouseenter();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), false);
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/);
|
||||
assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s');
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/);
|
||||
|
||||
rows[0].onmouseleave();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Hovering danger row sets danger style on tooltip
|
||||
rows[1].onmouseenter();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), false);
|
||||
assert.equal(tipEl.classList.contains('is-danger'), true);
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/);
|
||||
rows[1].onmouseleave();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Verify helper outputs cleanly
|
||||
assert.equal(formatAnomalyTagText('capacity', 1), '503');
|
||||
assert.equal(formatAnomalyTagText('capacity', 3), '503×3');
|
||||
assert.ok(buildStepAnomalyDiagnostic(steps[0]));
|
||||
assert.equal(buildStepAnomalyDiagnostic(steps[2]), null);
|
||||
} finally {
|
||||
widget.destroy();
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('StepsDetailView total summary cards, session anomaly strip, click-to-filter jump, and line/fit chart anomaly markers & hover tooltips work across UI modes', async () => {
|
||||
const env = installMockBrowser();
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
let view = null;
|
||||
let lineChart = null;
|
||||
let fitChart = null;
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
view = StepsDetailView();
|
||||
|
||||
const anomalyObj = {
|
||||
count: 2,
|
||||
primaryKind: 'timeout',
|
||||
severity: 'danger',
|
||||
totalDelaySec: 4.5,
|
||||
kinds: { timeout: 2 },
|
||||
events: [
|
||||
{ attempt: 1, kind: 'timeout', delaySec: 2, terminal: false, message: 'idle timeout #1' },
|
||||
{ attempt: 2, kind: 'timeout', delaySec: 2.5, terminal: true, message: 'TLS handshake timeout' },
|
||||
],
|
||||
};
|
||||
|
||||
const recentSteps = [
|
||||
{
|
||||
stepIndex: 10,
|
||||
createdAtMs: 1794960100000,
|
||||
modelLabel: 'Gemini 3 Pro',
|
||||
modelShort: '3-pro',
|
||||
tokPerSec: 120.4,
|
||||
ttftSec: 1.5,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 4000,
|
||||
outputTokens: 300,
|
||||
thinkingTokens: 100,
|
||||
responseTokens: 200,
|
||||
contextTokens: 5300,
|
||||
cacheHitPct: 80,
|
||||
costUsd: 0.02,
|
||||
anomalySig: 'timeout:2:d:4.5',
|
||||
anomaly: anomalyObj,
|
||||
},
|
||||
{
|
||||
stepIndex: 9,
|
||||
createdAtMs: 1794960050000,
|
||||
modelLabel: 'Gemini 3 Flash',
|
||||
modelShort: '3-flash',
|
||||
tokPerSec: 88.2,
|
||||
ttftSec: 0.9,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 150,
|
||||
thinkingTokens: 50,
|
||||
responseTokens: 100,
|
||||
contextTokens: 2650,
|
||||
cacheHitPct: 80,
|
||||
costUsd: 0.005,
|
||||
anomalySig: '',
|
||||
},
|
||||
];
|
||||
|
||||
const modelBreakdown = [
|
||||
{
|
||||
label: 'Gemini 3 Pro',
|
||||
shortName: '3-pro',
|
||||
calls: 1,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 4000,
|
||||
outputTokens: 300,
|
||||
thinkingTokens: 100,
|
||||
responseTokens: 200,
|
||||
totalTokens: 5300,
|
||||
costUsd: 0.02,
|
||||
avgTokPerSec: 120.4,
|
||||
avgTtftSec: 1.5,
|
||||
cacheHitPct: 80,
|
||||
anomalySteps: 1,
|
||||
anomalyCount: 2,
|
||||
anomalyDangerCount: 1,
|
||||
anomalyTotalDelaySec: 4.5,
|
||||
anomalyByKind: { timeout: 2 },
|
||||
},
|
||||
{
|
||||
label: 'Gemini 3 Flash',
|
||||
shortName: '3-flash',
|
||||
calls: 1,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 150,
|
||||
thinkingTokens: 50,
|
||||
responseTokens: 100,
|
||||
totalTokens: 2650,
|
||||
costUsd: 0.005,
|
||||
avgTokPerSec: 88.2,
|
||||
avgTtftSec: 0.9,
|
||||
cacheHitPct: 80,
|
||||
},
|
||||
];
|
||||
|
||||
uiStore.setState({
|
||||
monitorVisible: true,
|
||||
activeView: 'steps',
|
||||
stepsSubTab: 'models',
|
||||
selectedAgentScope: 'all',
|
||||
});
|
||||
telemetryStore.setState({
|
||||
telemetry: {
|
||||
settings: {
|
||||
stepTableColumns: ['step', 'model', 'tps', 'ttft'],
|
||||
experimentalModernUi: false,
|
||||
},
|
||||
activeConversation: {
|
||||
cascadeId: 'cid-summary-test',
|
||||
recentSteps,
|
||||
modelBreakdown,
|
||||
},
|
||||
},
|
||||
});
|
||||
await Promise.resolve();
|
||||
|
||||
// Session-level anomaly strip is visible with timeout tag
|
||||
const stripEl = view.refs.modelsAnomalyStripEl;
|
||||
assert.equal(stripEl.hasAttribute('hidden'), false);
|
||||
assert.match(stripEl.textContent, /异常 2 次.*1 步/);
|
||||
|
||||
// Model summary cards: Pro shows danger anomaly badge + integer 120 tok/s; Flash hides badge + keeps 88.2 tok/s
|
||||
const cards = view.refs.modelsListEl.querySelectorAll('.smodel-card');
|
||||
assert.equal(cards.length, 2);
|
||||
const proBadge = cards[0].querySelector('.smodel-anomaly-tag');
|
||||
const flashBadge = cards[1].querySelector('.smodel-anomaly-tag');
|
||||
assert.equal(proBadge.hasAttribute('hidden'), false);
|
||||
assert.equal(proBadge.textContent, '超时2');
|
||||
assert.equal(proBadge.classList.contains('is-danger'), true);
|
||||
assert.match(cards[0].querySelector('.smodel-perf').textContent, /120 tok\/s/);
|
||||
assert.equal(flashBadge.hasAttribute('hidden'), true);
|
||||
assert.match(cards[1].querySelector('.smodel-perf').textContent, /88\.2 tok\/s/);
|
||||
|
||||
// Hovering model card anomaly badge opens diagnostic popover with click hint AND suppresses parent card native title tooltip
|
||||
const modelDiag = buildModelAnomalyDiagnostic(modelBreakdown[0]);
|
||||
assert.ok(modelDiag && modelDiag.hint);
|
||||
assert.ok(cards[0].getAttribute('title'), 'Model card has native fit-chart title before hovering anomaly badge');
|
||||
proBadge.onmouseenter();
|
||||
assert.equal(cards[0].getAttribute('title'), null, 'Parent model card native title must be suppressed while hovering anomaly badge');
|
||||
assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), false);
|
||||
assert.match(view.refs.anomalyTipEl.querySelector('.step-anomaly-tip-hint').textContent, /按步查看/);
|
||||
proBadge.onmouseleave();
|
||||
assert.ok(cards[0].getAttribute('title'), 'Parent model card native title restores after leaving anomaly badge');
|
||||
assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Clicking model card anomaly badge jumps to 'steps', activates anomaly filterbar, and filters to only anomaly step #10
|
||||
proBadge.onclick({ stopPropagation() {} });
|
||||
await Promise.resolve();
|
||||
assert.equal(uiStore.getState().stepsSubTab, 'steps');
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
assert.match(view.refs.stepsTbody.children[0].children[0].textContent, /#10/);
|
||||
|
||||
// Clicking "返回全部步骤" restores all rows and hides the filterbar
|
||||
view.refs.anomalyFilterBarEl
|
||||
.querySelector('.steps-anomaly-filter-clear')
|
||||
.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), true);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
|
||||
// Switch back to 'models' and click a session-level anomaly strip category pill -> jumps to 'steps' filtered by kind
|
||||
uiStore.setState({ stepsSubTab: 'models' });
|
||||
await Promise.resolve();
|
||||
const stripTagBtn = stripEl.querySelector('.smodel-anomaly-tag');
|
||||
assert.ok(stripTagBtn, 'Session anomaly strip renders clickable category micro-tag');
|
||||
assert.equal(stripTagBtn.textContent, '超时2');
|
||||
stripTagBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await Promise.resolve();
|
||||
assert.equal(uiStore.getState().stepsSubTab, 'steps');
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false);
|
||||
assert.match(view.refs.anomalyFilterBarEl.textContent, /流空闲 \/ 连接超时/);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
|
||||
// Line chart (>64 points still renders anomaly ring overlay!) and Fit chart scatter anomaly overlay + hover tooltip linkage
|
||||
const manySteps = Array.from({ length: 70 }, (_, idx) => ({
|
||||
stepIndex: idx + 1,
|
||||
createdAtMs: 1794960000000 + idx * 1000,
|
||||
modelLabel: 'Gemini 3 Pro',
|
||||
modelShort: '3-pro',
|
||||
tokPerSec: 90 + (idx % 25),
|
||||
ttftSec: 1.2,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 3000,
|
||||
outputTokens: 200,
|
||||
contextTokens: 4200,
|
||||
cacheHitPct: 75,
|
||||
costUsd: 0.01,
|
||||
...(idx === 35 ? { anomalySig: 'timeout:2:d:4.5', anomaly: anomalyObj } : { anomalySig: '' }),
|
||||
}));
|
||||
|
||||
lineChart = createSessionLineChart();
|
||||
lineChart.update({
|
||||
steps: manySteps,
|
||||
modelGroupKey: '__all__',
|
||||
modelGroupKeys: ['__all__'],
|
||||
metric: 'tps',
|
||||
});
|
||||
const lineAnomalyDots = lineChart.el.querySelectorAll('.sstep-anomaly-dot');
|
||||
assert.equal(lineAnomalyDots.length, 1, 'Line chart renders anomaly ring marker even when steps > 64');
|
||||
assert.equal(lineAnomalyDots[0].classList.contains('is-danger'), true);
|
||||
|
||||
fitChart = createModelFitChart();
|
||||
fitChart.update({
|
||||
steps: manySteps,
|
||||
modelGroupKey: 'Gemini 3 Pro',
|
||||
modelGroupKeys: ['Gemini 3 Pro'],
|
||||
metric: 'tps',
|
||||
});
|
||||
const fitAnomalyDots = fitChart.el.querySelectorAll('.sstep-scatter-dot.is-anomaly');
|
||||
assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders anomaly ring overlay without overdraw drop');
|
||||
assert.equal(fitAnomalyDots[0].classList.contains('is-danger'), true);
|
||||
assert.ok(fitChart.el.querySelector('.trend-tip-anomaly'), 'Fit chart tooltip mounts linked anomaly diagnostic row');
|
||||
} finally {
|
||||
lineChart?.destroy?.();
|
||||
fitChart?.destroy?.();
|
||||
view?.destroy?.();
|
||||
uiStore.setState(prevUi);
|
||||
telemetryStore.setState(prevTel);
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('Compiled styles.css centers odometer capsule slot text and ships both classic & modern-ui anomaly styles', () => {
|
||||
const builtCss = readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
|
||||
|
||||
// Capsule bar alignment fix: centered by default for fixed-width slots, flex-start for ctx-pct and multi-label
|
||||
assert.match(
|
||||
builtCss,
|
||||
/\.wm-slot-text\[data-od-active="1"\][\s\S]*?justify-content:\s*center;/,
|
||||
'Odometer active slot text centers horizontally inside fixed-width capsule slots'
|
||||
);
|
||||
assert.match(
|
||||
builtCss,
|
||||
/\.wm-slot-text\.wm-ctx-pct\[data-od-active="1"\][\s\S]*?justify-content:\s*flex-start;/,
|
||||
'Context percentage slot stays left-aligned next to its progress ring'
|
||||
);
|
||||
|
||||
// Universal Classic + Modern UI anomaly styling
|
||||
assert.match(builtCss, /tr\.is-anomaly-warn\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, /\.step-anomaly-tag\s*\{/);
|
||||
assert.match(builtCss, /\.step-anomaly-tip\s*\{/);
|
||||
assert.match(builtCss, /\.steps-anomaly-strip\s*\{/);
|
||||
assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/);
|
||||
assert.match(builtCss, /\.sstep-anomaly-dot/);
|
||||
assert.match(builtCss, /\.trend-tip-anomaly/);
|
||||
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+\.progress-seg\s*\{[\s\S]*?border-radius:\s*2px;/);
|
||||
assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s+\.progress-seg\.is-active\.has-sep\s*\{[\s\S]*?margin-left:\s*2px;/);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,9 +25,13 @@ import {
|
||||
buildWindowsRelaunchInnerScript,
|
||||
ensureDesktopLaunchEntriesConfigured,
|
||||
ensureRemoteDebugFlagInArgs,
|
||||
inspectWindowsLnkBuffer,
|
||||
patchLinuxDesktopEntryText,
|
||||
patchWindowsRunRegistryCommand,
|
||||
patchWindowsShellOpenCommand,
|
||||
probeWindowsShortcutsFast,
|
||||
resolveDesktopHostExecutable,
|
||||
resolveWindowsPowerShellExecutable,
|
||||
triggerDesktopHostRelaunch,
|
||||
} from '../backend/desktop-launcher-config.mjs';
|
||||
import {
|
||||
@@ -109,9 +113,40 @@ test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and stri
|
||||
);
|
||||
|
||||
const linuxPaths = resolveDevToolsPortCandidates({ XDG_CONFIG_HOME: '/home/dev/.config' }, 'linux', '/home/dev');
|
||||
assert.equal(linuxPaths.length, 2);
|
||||
assert.equal(linuxPaths.length, 4);
|
||||
assert.equal(linuxPaths[0], path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort'));
|
||||
assert.equal(linuxPaths[1], path.join('/home/dev/.config', 'Antigravity IDE', 'DevToolsActivePort'));
|
||||
assert.equal(linuxPaths[2], path.join('/home/dev/.config', 'antigravity', 'DevToolsActivePort'));
|
||||
assert.equal(linuxPaths[3], path.join('/home/dev/.config', 'antigravity-ide', 'DevToolsActivePort'));
|
||||
|
||||
const linuxContainerPaths = resolveDevToolsPortCandidates(
|
||||
{ XDG_CONFIG_HOME: '/home/dev/.custom-cfg', VSCODE_PORTABLE: '/opt/ag-portable' },
|
||||
'linux',
|
||||
'/home/dev',
|
||||
{
|
||||
readdirFn: (dir) => {
|
||||
if (dir === path.join('/home/dev', '.var', 'app')) {
|
||||
return ['org.mozilla.firefox', 'com.google.Antigravity'];
|
||||
}
|
||||
if (dir === path.join('/home/dev', 'snap')) {
|
||||
return ['firefox', 'antigravity'];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
}
|
||||
);
|
||||
assert.ok(linuxContainerPaths.includes(path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort')));
|
||||
assert.ok(linuxContainerPaths.includes(path.join('/opt/ag-portable', 'user-data', 'DevToolsActivePort')));
|
||||
assert.ok(
|
||||
linuxContainerPaths.includes(
|
||||
path.join('/home/dev', '.var', 'app', 'com.google.Antigravity', 'config', 'Antigravity', 'DevToolsActivePort')
|
||||
)
|
||||
);
|
||||
assert.ok(
|
||||
linuxContainerPaths.includes(
|
||||
path.join('/home/dev', 'snap', 'antigravity', 'current', '.config', 'antigravity', 'DevToolsActivePort')
|
||||
)
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
isAntigravityMainPageTarget({
|
||||
@@ -1366,11 +1401,29 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(structurePane.hasAttribute('hidden'), true);
|
||||
assert.equal(otherPane.hasAttribute('hidden'), true);
|
||||
|
||||
// --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, pluginUpdateMode) ---
|
||||
// --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, modernUiSwitch, pluginUpdateMode) ---
|
||||
const generalSegControls = generalPane.querySelectorAll('.segmented');
|
||||
assert.equal(generalSegControls.length, 2, 'General tab has Language and FontScale segmented controls');
|
||||
assert.equal(
|
||||
generalSegControls.length,
|
||||
3,
|
||||
'General tab has Language, FontScale, and Experimental Modern UI segmented controls'
|
||||
);
|
||||
const langBtns = generalSegControls[0].querySelectorAll('.seg-btn');
|
||||
const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn');
|
||||
const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn');
|
||||
assert.equal(modernUiBtns.length, 2, 'Experimental Modern UI switch has 关闭 / 开启');
|
||||
|
||||
modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.experimentalModernUi, true);
|
||||
assert.equal(portalHost.getAttribute('data-modern-ui'), 'true');
|
||||
assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true');
|
||||
assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true');
|
||||
modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.experimentalModernUi, false);
|
||||
assert.equal(portalHost.hasAttribute('data-modern-ui'), false);
|
||||
assert.equal(popoverEl.hasAttribute('data-modern-ui'), false);
|
||||
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');
|
||||
@@ -2029,7 +2082,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
);
|
||||
assert.equal(
|
||||
plotStageEl.querySelector('.trend-svg').getAttribute('viewBox'),
|
||||
'0 0 180 120',
|
||||
'0 0 180 184',
|
||||
'TrendAreaChart dynamically adapts viewBox width to measured container width (180px in MockNode)'
|
||||
);
|
||||
assert.match(
|
||||
@@ -2049,10 +2102,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
'Heatmap palette uses unified project blue tokens instead of hardcoded green'
|
||||
);
|
||||
|
||||
// Click '全部' (option index 5 in ConsumptionView timeFilterSwitch) to load 120-day series
|
||||
// Click '全部' ('all' in ConsumptionView timeFilterSwitch) to load 120-day series
|
||||
const consPane = allPanes[1];
|
||||
const consTimeSegBtns = consPane.querySelectorAll('.seg-btn');
|
||||
consTimeSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const allRangeBtn =
|
||||
consTimeSegBtns.find((btn) => btn.getAttribute('data-seg-value') === 'all') ||
|
||||
consTimeSegBtns[6];
|
||||
allRangeBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 35));
|
||||
|
||||
assert.equal(plotStageEl.hasAttribute('hidden'), true, 'Line chart hidden when trend exceeds 90 days');
|
||||
@@ -2418,7 +2474,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
smodelCards = modelsAnalyticsPane.querySelectorAll('.smodel-card');
|
||||
assert.equal(smodelCards.length, 1, 'Scoped to subagent #1 model only');
|
||||
assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-3-flash');
|
||||
assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145\.0 tok\/s$/);
|
||||
assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145 tok\/s$/);
|
||||
assert.equal(
|
||||
lineModelSelectEl.hasAttribute('hidden'),
|
||||
true,
|
||||
@@ -4909,6 +4965,120 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
);
|
||||
assert.equal(winRunIdeIgnored.matched, false);
|
||||
|
||||
// System32 PowerShell resolution & HKCU\Software\Classes shell\open\command patching
|
||||
assert.equal(
|
||||
resolveWindowsPowerShellExecutable(
|
||||
{ SystemRoot: 'D:\\WinSys' },
|
||||
(p) => p === 'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
|
||||
),
|
||||
'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
|
||||
);
|
||||
assert.equal(
|
||||
resolveWindowsPowerShellExecutable({ SystemRoot: 'D:\\Missing' }, () => false),
|
||||
'powershell.exe'
|
||||
);
|
||||
|
||||
const shellOpenPatched = patchWindowsShellOpenCommand(
|
||||
'"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"',
|
||||
{ enabled: true }
|
||||
);
|
||||
assert.equal(shellOpenPatched.matched, true);
|
||||
assert.equal(shellOpenPatched.changed, true);
|
||||
assert.equal(
|
||||
shellOpenPatched.value,
|
||||
'"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --remote-debugging-port=0 -- "%1"',
|
||||
'Inserts flag before -- "%1" so Chromium parses it as a switch'
|
||||
);
|
||||
const shellOpenRollback = patchWindowsShellOpenCommand(shellOpenPatched.value, { enabled: false });
|
||||
assert.equal(shellOpenRollback.changed, true);
|
||||
assert.equal(
|
||||
shellOpenRollback.value,
|
||||
'"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"'
|
||||
);
|
||||
assert.equal(
|
||||
patchWindowsShellOpenCommand(
|
||||
'"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity IDE\\Antigravity IDE.exe" "--open-url" "--" "%1"',
|
||||
{ enabled: true }
|
||||
).matched,
|
||||
false
|
||||
);
|
||||
|
||||
// Zero-subprocess binary .lnk inspection & non-recursive folder boundary verification
|
||||
const makeFakeLnkBuf = (targetPath, argsStr = '') =>
|
||||
Buffer.concat([
|
||||
Buffer.alloc(76, 0x4c),
|
||||
Buffer.from(`${targetPath}\0${argsStr}\0`, 'utf16le'),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
inspectWindowsLnkBuffer(
|
||||
makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0')
|
||||
),
|
||||
{ matched: true, hasDebugPort: true }
|
||||
);
|
||||
assert.deepEqual(
|
||||
inspectWindowsLnkBuffer(makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '')),
|
||||
{ matched: false, hasDebugPort: false }
|
||||
);
|
||||
|
||||
const visitedDirs = [];
|
||||
const fakeDesktopDir = 'C:\\Users\\Dev\\Desktop';
|
||||
const fakeRedirectedDesktopDir = 'D:\\LocalizedDesktop';
|
||||
const fakeProgramsDir = 'C:\\Users\\Dev\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs';
|
||||
const fakeAgySubDir = `${fakeProgramsDir}\\Antigravity`;
|
||||
const fakeGoogleSubDir = `${fakeProgramsDir}\\Google`;
|
||||
const fastProbeRes = probeWindowsShortcutsFast({
|
||||
env: {
|
||||
USERPROFILE: 'C:\\Users\\Dev',
|
||||
APPDATA: 'C:\\Users\\Dev\\AppData\\Roaming',
|
||||
PUBLIC: 'C:\\Users\\Public',
|
||||
ProgramData: 'C:\\ProgramData',
|
||||
},
|
||||
homeDir: 'C:\\Users\\Dev',
|
||||
extraDirs: [fakeRedirectedDesktopDir],
|
||||
fsOps: {
|
||||
readdirFn: (dir) => {
|
||||
visitedDirs.push(dir);
|
||||
if (dir === fakeDesktopDir) {
|
||||
return [
|
||||
{ name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false },
|
||||
{ name: 'huge-repo-with-node_modules', isFile: () => false, isDirectory: () => true },
|
||||
];
|
||||
}
|
||||
if (dir === fakeRedirectedDesktopDir) {
|
||||
return [{ name: 'Antigravity-Redir.lnk', isFile: () => true, isDirectory: () => false }];
|
||||
}
|
||||
if (dir === fakeProgramsDir) {
|
||||
return [
|
||||
{ name: 'Visual Studio 2022', isFile: () => false, isDirectory: () => true },
|
||||
{ name: 'Antigravity', isFile: () => false, isDirectory: () => true },
|
||||
{ name: 'Google', isFile: () => false, isDirectory: () => true },
|
||||
];
|
||||
}
|
||||
if (dir === fakeAgySubDir) {
|
||||
return [{ name: 'Antigravity IDE.lnk', isFile: () => true, isDirectory: () => false }];
|
||||
}
|
||||
if (dir === fakeGoogleSubDir) {
|
||||
return [{ name: 'Antigravity-Google.lnk', isFile: () => true, isDirectory: () => false }];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
statFn: () => ({ size: 512 }),
|
||||
readFn: (p) =>
|
||||
p.endsWith('Antigravity IDE.lnk')
|
||||
? makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '')
|
||||
: makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'),
|
||||
},
|
||||
});
|
||||
assert.equal(fastProbeRes.allConfigured, true);
|
||||
assert.equal(fastProbeRes.configuredPaths.length, 3);
|
||||
assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Redir.lnk')));
|
||||
assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Google.lnk')));
|
||||
assert.equal(
|
||||
visitedDirs.some((d) => d.includes('huge-repo') || d.includes('Visual Studio')),
|
||||
false,
|
||||
'Never recurses into Desktop subfolders or unrelated Start Menu vendor folders'
|
||||
);
|
||||
|
||||
const linuxDesktopRaw = [
|
||||
'[Desktop Entry]',
|
||||
'Name=Antigravity',
|
||||
@@ -4924,6 +5094,50 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
assert.equal(linuxReverted.changed, true);
|
||||
assert.equal(linuxReverted.text, linuxDesktopRaw);
|
||||
|
||||
const linuxAppImageRaw = [
|
||||
'[Desktop Entry]',
|
||||
'Name=Antigravity',
|
||||
'Exec=env DESKTOPINTEGRATION=false "/home/alice/Apps/Antigravity-2.33.0-x86_64.AppImage" %U',
|
||||
'Type=Application',
|
||||
'',
|
||||
].join('\n');
|
||||
const linuxAppImagePatched = patchLinuxDesktopEntryText(linuxAppImageRaw, { enabled: true });
|
||||
assert.equal(linuxAppImagePatched.matched, true);
|
||||
assert.equal(linuxAppImagePatched.changed, true);
|
||||
assert.match(
|
||||
linuxAppImagePatched.text,
|
||||
/Exec=env DESKTOPINTEGRATION=false "\/home\/alice\/Apps\/Antigravity-2\.33\.0-x86_64\.AppImage" --remote-debugging-port=0 %U/
|
||||
);
|
||||
assert.equal(
|
||||
patchLinuxDesktopEntryText(linuxAppImagePatched.text, { enabled: false }).text,
|
||||
linuxAppImageRaw
|
||||
);
|
||||
assert.equal(
|
||||
patchLinuxDesktopEntryText('Exec=env FOO=1 /opt/antigravity-ide/antigravity-ide %F', {
|
||||
enabled: true,
|
||||
}).matched,
|
||||
false
|
||||
);
|
||||
const linuxGoogleDashRaw = 'Exec=env -u BAD_VAR /usr/bin/google-antigravity -- %U';
|
||||
const linuxGoogleDashPatched = patchLinuxDesktopEntryText(linuxGoogleDashRaw, { enabled: true });
|
||||
assert.equal(linuxGoogleDashPatched.matched, true);
|
||||
assert.equal(
|
||||
linuxGoogleDashPatched.text,
|
||||
'Exec=env -u BAD_VAR /usr/bin/google-antigravity --remote-debugging-port=0 -- %U'
|
||||
);
|
||||
|
||||
const resolvedLinuxAppImage = resolveDesktopHostExecutable({
|
||||
env: {
|
||||
APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage',
|
||||
ANTIGRAVITY_AGENTAPI_EXE: '/tmp/.mount_Antigr123/resources/bin/language_server_linux_x64',
|
||||
},
|
||||
platform: 'linux',
|
||||
homeDir: '/home/alice',
|
||||
existsFn: (p) => p === '/home/alice/Apps/Antigravity-2.33.0.AppImage',
|
||||
});
|
||||
assert.equal(resolvedLinuxAppImage.found, true);
|
||||
assert.equal(resolvedLinuxAppImage.executablePath, '/home/alice/Apps/Antigravity-2.33.0.AppImage');
|
||||
|
||||
// 3. Host executable resolution from ANTIGRAVITY_AGENTAPI_EXE & clean relaunch env sanitization
|
||||
const resolvedWinHost = resolveDesktopHostExecutable({
|
||||
env: {
|
||||
@@ -4958,7 +5172,8 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
assert.equal(resolvedMacHost.appBundlePath, '/Applications/Antigravity.app');
|
||||
|
||||
const sanitizedEnv = buildSanitizedDesktopRelaunchEnv({
|
||||
PATH: 'C:\\Windows\\System32',
|
||||
PATH: '/tmp/.mount_Antigr123/usr/bin:/usr/local/bin:/usr/bin',
|
||||
LD_LIBRARY_PATH: '/tmp/.mount_Antigr123/usr/lib:/usr/lib/x86_64-linux-gnu',
|
||||
USERPROFILE: 'C:\\Users\\Administrator',
|
||||
ANTIGRAVITY_LS_ADDRESS: 'localhost:13088',
|
||||
ANTIGRAVITY_CSRF_TOKEN: 'secret',
|
||||
@@ -4966,11 +5181,22 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
USAGE_MONITOR_HOST_PPID: '123',
|
||||
ELECTRON_RUN_AS_NODE: '1',
|
||||
NODE_OPTIONS: '--inspect',
|
||||
APPIMAGE: '/home/alice/Antigravity.AppImage',
|
||||
APPDIR: '/tmp/.mount_Antigr123',
|
||||
OWD: '/home/alice',
|
||||
ARGV0: '/home/alice/Antigravity.AppImage',
|
||||
APPIMAGE_EXTRACT_AND_RUN: '1',
|
||||
});
|
||||
assert.deepEqual(sanitizedEnv, {
|
||||
PATH: 'C:\\Windows\\System32',
|
||||
PATH: '/usr/local/bin:/usr/bin',
|
||||
LD_LIBRARY_PATH: '/usr/lib/x86_64-linux-gnu',
|
||||
USERPROFILE: 'C:\\Users\\Administrator',
|
||||
});
|
||||
assert.equal(
|
||||
buildSanitizedDesktopRelaunchEnv({ LD_LIBRARY_PATH: '/tmp/.mount_Only/lib' }).LD_LIBRARY_PATH,
|
||||
undefined,
|
||||
'Omits LD_LIBRARY_PATH completely when only AppImage mount entries were present'
|
||||
);
|
||||
|
||||
// 4. Linux .desktop provisioning on real temp dir + Windows shortcut provisioning + stale DevToolsActivePort (cdp_unreachable) + relaunch dispatch
|
||||
const simTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-233-auto-'));
|
||||
@@ -5038,8 +5264,108 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
/--remote-debugging-port=0 %U/
|
||||
);
|
||||
|
||||
// Verify Windows shortcut auto-provisioning + stale port (`cdp_unreachable`) status reporting + clean rollback on disable
|
||||
// Dynamic Linux .desktop discovery: vendor/AppImageLauncher/capitalized filenames across user, system, XDG_DATA_DIRS, and autostart
|
||||
const linuxDynData = path.join(simTmp, 'xdg-data-dyn');
|
||||
const linuxDynCfg = path.join(simTmp, 'xdg-cfg-dyn');
|
||||
const linuxSysVendor = path.join(simTmp, 'sys-vendor-share');
|
||||
const appImageDesktop = path.join(
|
||||
linuxDynData,
|
||||
'applications',
|
||||
'appimagekit_1a2b3c-Antigravity.desktop'
|
||||
);
|
||||
const vendorSysDesktop = path.join(linuxSysVendor, 'applications', 'google-antigravity.desktop');
|
||||
const unrelatedSysDesktop = path.join(linuxSysVendor, 'applications', 'firefox.desktop');
|
||||
const capAutostart = path.join(linuxDynCfg, 'autostart', 'Antigravity.desktop');
|
||||
fs.mkdirSync(path.dirname(appImageDesktop), { recursive: true });
|
||||
fs.mkdirSync(path.dirname(vendorSysDesktop), { recursive: true });
|
||||
fs.mkdirSync(path.dirname(capAutostart), { recursive: true });
|
||||
fs.writeFileSync(appImageDesktop, linuxAppImageRaw, 'utf8');
|
||||
fs.writeFileSync(
|
||||
vendorSysDesktop,
|
||||
'[Desktop Entry]\nName=Antigravity\nExec=/usr/bin/google-antigravity %U\nType=Application\n',
|
||||
'utf8'
|
||||
);
|
||||
fs.writeFileSync(unrelatedSysDesktop, '[Desktop Entry]\nName=Firefox\nExec=firefox %u\n', 'utf8');
|
||||
fs.writeFileSync(capAutostart, linuxDesktopRaw, 'utf8');
|
||||
const linuxDynProv = await ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: true,
|
||||
env: {
|
||||
XDG_DATA_HOME: linuxDynData,
|
||||
XDG_CONFIG_HOME: linuxDynCfg,
|
||||
XDG_DATA_DIRS: linuxSysVendor,
|
||||
},
|
||||
platform: 'linux',
|
||||
homeDir,
|
||||
allowInTest: true,
|
||||
fsOps: {
|
||||
existsFn: fs.existsSync,
|
||||
readFn: fs.readFileSync,
|
||||
writeFn: fs.writeFileSync,
|
||||
mkdirFn: fs.mkdirSync,
|
||||
renameFn: fs.renameSync,
|
||||
unlinkFn: fs.unlinkSync,
|
||||
readdirFn: fs.readdirSync,
|
||||
statFn: fs.statSync,
|
||||
},
|
||||
});
|
||||
assert.equal(linuxDynProv.updated, true);
|
||||
assert.equal(linuxDynProv.updatedPaths.length, 3);
|
||||
assert.match(fs.readFileSync(appImageDesktop, 'utf8'), /--remote-debugging-port=0 %U/);
|
||||
assert.match(
|
||||
fs.readFileSync(path.join(linuxDynData, 'applications', 'google-antigravity.desktop'), 'utf8'),
|
||||
/google-antigravity --remote-debugging-port=0 %U/
|
||||
);
|
||||
assert.match(fs.readFileSync(capAutostart, 'utf8'), /--remote-debugging-port=0 %U/);
|
||||
assert.equal(fs.existsSync(path.join(linuxDynData, 'applications', 'firefox.desktop')), false);
|
||||
|
||||
// Verify Windows PowerShell provisioning covers HKLM Run/WOW6432Node/Classes + caches discoveredDirs for subsequent fastCheckIfActive
|
||||
let capturedWinProvPs = '';
|
||||
const redirHome = 'C:\\Users\\RedirUser';
|
||||
const redirDesktop = 'D:\\RedirectedDesktop';
|
||||
await ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: true,
|
||||
env: { USERPROFILE: redirHome },
|
||||
platform: 'win32',
|
||||
homeDir: redirHome,
|
||||
allowInTest: true,
|
||||
execFileFn: async (_f, args) => {
|
||||
capturedWinProvPs = args[args.length - 1];
|
||||
return JSON.stringify({
|
||||
ok: true,
|
||||
updatedPaths: [`${redirDesktop}\\Antigravity.lnk`],
|
||||
configuredPaths: [`${redirDesktop}\\Antigravity.lnk`],
|
||||
readOnlyPaths: [],
|
||||
discoveredDirs: [redirDesktop],
|
||||
});
|
||||
},
|
||||
});
|
||||
assert.match(capturedWinProvPs, /LocalMachine/);
|
||||
assert.match(capturedWinProvPs, /WOW6432Node/);
|
||||
assert.match(capturedWinProvPs, /HKLM:Run:/);
|
||||
assert.match(capturedWinProvPs, /HKLM:Class:/);
|
||||
const fastCachedRes = await ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: true,
|
||||
fastCheckIfActive: true,
|
||||
env: { USERPROFILE: redirHome, APPDATA: '', PUBLIC: '', ProgramData: '' },
|
||||
platform: 'win32',
|
||||
homeDir: redirHome,
|
||||
allowInTest: true,
|
||||
fsOps: {
|
||||
readdirFn: (dir) =>
|
||||
dir === redirDesktop
|
||||
? [{ name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false }]
|
||||
: [],
|
||||
statFn: () => ({ size: 512 }),
|
||||
readFn: () => makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'),
|
||||
},
|
||||
});
|
||||
assert.equal(fastCachedRes.fastPath, true);
|
||||
assert.equal(fastCachedRes.allConfigured ?? fastCachedRes.configured, true);
|
||||
assert.ok(fastCachedRes.configuredPaths.some((p) => p.includes('RedirectedDesktop')));
|
||||
|
||||
// Verify Windows shortcut auto-provisioning + read-only public shortcut tracking + periodic recheck + clean rollback
|
||||
const winPsCalls = [];
|
||||
let simulateReadOnlyPublicDesktop = false;
|
||||
const mockWinExec = async (file, args, opts) => {
|
||||
winPsCalls.push({ file, args, env: opts?.env });
|
||||
const enabledFlag = opts?.env?.AGY_LAUNCH_ENABLED === '1';
|
||||
@@ -5051,6 +5377,10 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
configuredPaths: enabledFlag
|
||||
? ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk', 'C:\\TaskBar\\Antigravity.lnk']
|
||||
: [],
|
||||
readOnlyPaths:
|
||||
enabledFlag && simulateReadOnlyPublicDesktop
|
||||
? ['C:\\Users\\Public\\Desktop\\Antigravity.lnk']
|
||||
: [],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -5069,6 +5399,7 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
homeDir,
|
||||
leaseFilePath: leaseFile,
|
||||
autoConfigureIdeArgv: true,
|
||||
launcherRecheckIntervalMs: 25,
|
||||
launcherExecFileFn: mockWinExec,
|
||||
allowDesktopLauncherInTest: true,
|
||||
});
|
||||
@@ -5079,10 +5410,18 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
assert.equal(stWin.state, 'cdp_unreachable');
|
||||
assert.equal(stWin.argvUpdatedThisBoot, true);
|
||||
assert.equal(stWin.launcherConfigured, true);
|
||||
assert.equal(stWin.hasReadOnlyShortcuts, false);
|
||||
assert.equal(stWin.canRelaunch, true);
|
||||
assert.equal(winPsCalls.length, 1);
|
||||
assert.equal(winPsCalls[0].env.AGY_LAUNCH_ENABLED, '1');
|
||||
|
||||
// Periodic re-check after cooldown detects NSIS installer-wiped or read-only public shortcuts
|
||||
simulateReadOnlyPublicDesktop = true;
|
||||
await new Promise((r) => setTimeout(r, 35));
|
||||
await ctrlWin.syncAllWindows();
|
||||
assert.equal(winPsCalls.length, 2, 'Re-provisions automatically once cooldown interval elapses');
|
||||
assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, true);
|
||||
|
||||
// Disabling overlay (Sidebar Only) cleanly triggers shortcut flag rollback
|
||||
currentMountSettings = {
|
||||
windowMountMode: 'sidebar',
|
||||
@@ -5091,8 +5430,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
};
|
||||
await ctrlWin.notifySettingChanged(false);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.equal(winPsCalls.length, 2);
|
||||
assert.equal(winPsCalls[1].env.AGY_LAUNCH_ENABLED, '0');
|
||||
assert.equal(winPsCalls.length, 3);
|
||||
assert.equal(winPsCalls[2].env.AGY_LAUNCH_ENABLED, '0');
|
||||
assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, false);
|
||||
await ctrlWin.stop();
|
||||
|
||||
// Verify Windows out-of-job Shell.Application relaunch payload (.ps1 file with UTF-8 BOM) & macOS open -a relaunch
|
||||
@@ -5113,10 +5453,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
assert.equal(relaunchWinRes.ok, true);
|
||||
assert.equal(relaunchWinRes.relaunching, true);
|
||||
assert.equal(capturedRelaunchArgs.includes('-Sta'), true, 'Forces STA for Shell.Application COM');
|
||||
assert.match(
|
||||
capturedRelaunchArgs[capturedRelaunchArgs.length - 1],
|
||||
/-HostElevated /,
|
||||
'Passes -HostElevated via CLI arg so WMI/Shell.Application preserve elevation state'
|
||||
);
|
||||
assert.equal(capturedRelaunchEnv.ANTIGRAVITY_LS_ADDRESS, undefined, 'Strips host LS env');
|
||||
assert.equal(fs.existsSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1), true);
|
||||
const writtenPs1 = fs.readFileSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1, 'utf8');
|
||||
assert.equal(writtenPs1.startsWith('\uFEFF'), true, 'Writes UTF-8 BOM for Windows PowerShell 5.1');
|
||||
assert.match(writtenPs1, /^[\uFEFF]?param\(\[string\]\$HostElevated = '0'\)/);
|
||||
assert.match(writtenPs1, /--remote-debugging-port=0/);
|
||||
assert.ok(writtenPs1.includes(stalePortFile));
|
||||
|
||||
@@ -5157,12 +5503,82 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
});
|
||||
assert.equal(relaunchMacRes.ok, true);
|
||||
assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app');
|
||||
assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity');
|
||||
assert.match(macSpawnArgs.args[1], /if osascript .* then .* fi/);
|
||||
assert.match(macSpawnArgs.args[1], /pkill -TERM -x "\$AGY_APP_NAME"/);
|
||||
assert.match(macSpawnArgs.args[1], /pkill -KILL -x "\$AGY_APP_NAME"/);
|
||||
assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/);
|
||||
|
||||
// Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback still works seamlessly
|
||||
const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop');
|
||||
// macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name
|
||||
let macPsFallbackSpawn = null;
|
||||
const relaunchMacPsRes = await triggerDesktopHostRelaunch({
|
||||
env: { PATH: '/usr/bin:/bin' },
|
||||
platform: 'darwin',
|
||||
homeDir: '/Users/dev',
|
||||
allowInTest: true,
|
||||
existsFn: () => false,
|
||||
execFileFn: async (file) => {
|
||||
if (file === 'osascript') throw new Error('Not authorized to send Apple events (-1743)');
|
||||
if (file === 'ps') {
|
||||
return '/Users/dev/Apps/Antigravity Beta.app/Contents/MacOS/Antigravity Beta\n';
|
||||
}
|
||||
return '';
|
||||
},
|
||||
spawnFn: async (file, args, opts) => {
|
||||
macPsFallbackSpawn = { file, args, env: opts?.env };
|
||||
return { pid: 4322 };
|
||||
},
|
||||
});
|
||||
assert.equal(relaunchMacPsRes.ok, true);
|
||||
assert.equal(macPsFallbackSpawn.env.AGY_RELAUNCH_APP, '/Users/dev/Apps/Antigravity Beta.app');
|
||||
assert.equal(macPsFallbackSpawn.env.AGY_APP_NAME, 'Antigravity Beta');
|
||||
|
||||
// Verify Linux /proc dynamic AppImage discovery, 15-char comm truncation, and SIGKILL fallback
|
||||
let linuxSpawnArgs = null;
|
||||
const relaunchLinuxRes = await triggerDesktopHostRelaunch({
|
||||
env: {
|
||||
PATH: '/tmp/.mount_Ag/bin:/usr/bin:/bin',
|
||||
APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage',
|
||||
LD_LIBRARY_PATH: '/tmp/.mount_Ag/lib',
|
||||
},
|
||||
platform: 'linux',
|
||||
homeDir: '/home/alice',
|
||||
stalePortFiles: ['/home/alice/.config/Antigravity/DevToolsActivePort'],
|
||||
allowInTest: true,
|
||||
existsFn: () => false,
|
||||
execFileFn: async () => '/home/alice/Apps/Antigravity-2.33.0.AppImage\n',
|
||||
spawnFn: async (file, args, opts) => {
|
||||
linuxSpawnArgs = { file, args, env: opts?.env };
|
||||
return { pid: 5678 };
|
||||
},
|
||||
});
|
||||
assert.equal(relaunchLinuxRes.ok, true);
|
||||
assert.equal(linuxSpawnArgs.env.AGY_RELAUNCH_EXE, '/home/alice/Apps/Antigravity-2.33.0.AppImage');
|
||||
assert.equal(linuxSpawnArgs.env.AGY_PROC_COMM, 'Antigravity-2.3');
|
||||
assert.equal(linuxSpawnArgs.env.APPIMAGE, undefined, 'Strips APPIMAGE from relaunch env');
|
||||
assert.equal(linuxSpawnArgs.env.LD_LIBRARY_PATH, undefined, 'Strips mount LD_LIBRARY_PATH');
|
||||
assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity "\$AGY_PROC_COMM"/);
|
||||
assert.match(linuxSpawnArgs.args[1], /pkill -KILL -u "\$uid" -x "\$pn"/);
|
||||
|
||||
// Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback, HKLM UAC patching, single-quoted UAC script safety & de-elevation
|
||||
const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop', {
|
||||
readOnlyShortcutPaths: [
|
||||
'C:\\Users\\Public\\Desktop\\Antigravity.lnk',
|
||||
'HKLM:Run:Software\\Microsoft\\Windows\\CurrentVersion\\Run|Antigravity',
|
||||
'HKLM:Class:Software\\Classes\\antigravity\\shell\\open\\command',
|
||||
],
|
||||
psExePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
|
||||
});
|
||||
assert.match(innerScriptCheck, /CloseMainWindow/);
|
||||
assert.match(innerScriptCheck, /Stop-Process/);
|
||||
assert.match(innerScriptCheck, /-Verb RunAs/);
|
||||
assert.match(innerScriptCheck, /C:\\Users\\Public\\Desktop\\Antigravity\.lnk/);
|
||||
assert.match(innerScriptCheck, /HKLM:Run:/);
|
||||
assert.match(innerScriptCheck, /HKLM:Class:/);
|
||||
assert.match(innerScriptCheck, /'\$ws = \$null'/);
|
||||
assert.match(innerScriptCheck, /'\$mySid = \(Get-Process -Id \$PID\)\.SessionId'/);
|
||||
assert.match(innerScriptCheck, /'Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue'/);
|
||||
assert.match(innerScriptCheck, /\$isSelfElevated -and -not \$wasHostElevated/);
|
||||
} finally {
|
||||
fs.rmSync(simTmp, { recursive: true, force: true });
|
||||
}
|
||||
@@ -5251,7 +5667,23 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
);
|
||||
assert.match(strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.textContent, /正在重启客户端/);
|
||||
|
||||
// macOS unconfigured state -> `.is-warn` with 1-click relaunch + copy button
|
||||
// All-Users read-only Public Desktop shortcut -> `.is-warn` + UAC authorization button copy
|
||||
strTab.refs.renderSettings(
|
||||
{ windowMountMode: 'dual', enableWindowOverlay: true },
|
||||
{
|
||||
state: 'no_devtools_port',
|
||||
argvUpdatedThisBoot: true,
|
||||
argvConfigured: true,
|
||||
launcherConfigured: true,
|
||||
hasReadOnlyShortcuts: true,
|
||||
canRelaunch: true,
|
||||
},
|
||||
'win32'
|
||||
);
|
||||
assert.equal(noticeEl.classList.contains('is-warn'), true);
|
||||
assert.match(noticeEl.textContent, /公共桌面快捷方式受权限保护/);
|
||||
|
||||
// macOS Desktop -> honest code-signing notice with `.is-restart` + 1-click relaunch + copy button
|
||||
strTab.refs.renderSettings(
|
||||
{ windowMountMode: 'dual', enableWindowOverlay: true },
|
||||
{
|
||||
@@ -5259,12 +5691,13 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
argvUpdatedThisBoot: false,
|
||||
argvConfigured: false,
|
||||
launcherConfigured: false,
|
||||
hasReadOnlyShortcuts: false,
|
||||
canRelaunch: true,
|
||||
},
|
||||
'darwin'
|
||||
);
|
||||
assert.equal(noticeEl.classList.contains('is-warn'), true);
|
||||
assert.match(noticeEl.textContent, /open -a "Antigravity" --args --remote-debugging-port=0/);
|
||||
assert.equal(noticeEl.classList.contains('is-restart'), true);
|
||||
assert.match(noticeEl.textContent, /macOS 应用签名限制/);
|
||||
|
||||
strTab.refs.mountBridgeNotice.refs.copyBtnEl.dispatchEvent({ type: 'click' });
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
@@ -5275,10 +5708,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
const globalBanner = BridgeStatusNotice({ dismissible: true });
|
||||
globalBanner.refs.update({
|
||||
visible: true,
|
||||
windowBridge: { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true },
|
||||
windowBridge: {
|
||||
state: 'no_devtools_port',
|
||||
launcherConfigured: true,
|
||||
hasReadOnlyShortcuts: true,
|
||||
canRelaunch: true,
|
||||
},
|
||||
hostPlatform: 'win32',
|
||||
});
|
||||
assert.equal(globalBanner.el.hasAttribute('hidden'), false);
|
||||
assert.match(globalBanner.refs.relaunchBtnEl.textContent, /授权修补并立即重启/);
|
||||
globalBanner.refs.dismissBtnEl.dispatchEvent({ type: 'click' });
|
||||
assert.equal(globalBanner.el.hasAttribute('hidden'), true);
|
||||
globalBanner.refs.update({
|
||||
@@ -5293,10 +5732,21 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi
|
||||
});
|
||||
assert.equal(globalBanner.el.hasAttribute('hidden'), false, 'Re-armed after active cycle');
|
||||
|
||||
// English localization check
|
||||
// English localization check across macOS & read-only shortcut states
|
||||
setI18nLanguage('en-US');
|
||||
strTab.refs.refreshLabels();
|
||||
assert.match(noticeEl.textContent, /Local Debug Port Missing/);
|
||||
assert.match(noticeEl.textContent, /Due to macOS app code signing/);
|
||||
globalBanner.refs.update({
|
||||
visible: true,
|
||||
windowBridge: {
|
||||
state: 'no_devtools_port',
|
||||
launcherConfigured: true,
|
||||
hasReadOnlyShortcuts: true,
|
||||
canRelaunch: true,
|
||||
},
|
||||
hostPlatform: 'win32',
|
||||
});
|
||||
assert.match(globalBanner.refs.relaunchBtnEl.textContent, /Authorize & Relaunch/);
|
||||
|
||||
// Switching to Sidebar Only hides notice immediately
|
||||
strTab.refs.renderSettings(
|
||||
|
||||
@@ -597,6 +597,260 @@ export function extractContextBreakdown(chat) {
|
||||
};
|
||||
}
|
||||
|
||||
const ANOMALY_SEVERITY_PRIORITY = Object.freeze({
|
||||
rate_limit: 9,
|
||||
auth_or_model: 8,
|
||||
timeout: 7,
|
||||
capacity: 6,
|
||||
disconnect: 5,
|
||||
upstream: 4,
|
||||
model_output: 3,
|
||||
safety: 2,
|
||||
error: 1,
|
||||
canceled: 0,
|
||||
});
|
||||
|
||||
/**
|
||||
* 将模型调用重试、超时或错误文本归类为标准化异常类型。
|
||||
*
|
||||
* @param {string} [rawError='']
|
||||
* @param {{ reasonCode?: number, errorCode?: number, isCanceled?: boolean }} [opts]
|
||||
* @returns {'timeout'|'rate_limit'|'capacity'|'disconnect'|'upstream'|'model_output'|'safety'|'auth_or_model'|'canceled'|'error'}
|
||||
*/
|
||||
export function classifyStepAnomalyError(
|
||||
rawError = '',
|
||||
{ reasonCode = 0, errorCode = 0, isCanceled = false } = {}
|
||||
) {
|
||||
const s = String(rawError || '').trim();
|
||||
if (isCanceled || /context canceled by user|stream reading error:\s*context canceled/i.test(s)) {
|
||||
return 'canceled';
|
||||
}
|
||||
if (reasonCode === 2 || /model output error|model produced invalid output|invalid tool call/i.test(s)) {
|
||||
return 'model_output';
|
||||
}
|
||||
if (
|
||||
errorCode === 429 ||
|
||||
/\b429\b|RESOURCE_EXHAUSTED|quota reached|rate.?limit/i.test(s)
|
||||
) {
|
||||
return 'rate_limit';
|
||||
}
|
||||
if (
|
||||
/stream idle timeout|TLS handshake timeout|i\/o timeout|context deadline exceeded|\btimeout\b/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'timeout';
|
||||
}
|
||||
if (
|
||||
errorCode === 503 ||
|
||||
/\b503\b|UNAVAILABLE|No capacity available|overloaded|high demand/i.test(s)
|
||||
) {
|
||||
return 'capacity';
|
||||
}
|
||||
if (
|
||||
/wsarecv|wsasend|forcibly closed|connection reset|broken pipe|ECONNRESET|unexpected EOF|:\s*EOF\b|The stream was interrupted|no such host|dial tcp|tls:|bad record MAC/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'disconnect';
|
||||
}
|
||||
if (/safety filter|content safety|sensitive words/i.test(s)) {
|
||||
return 'safety';
|
||||
}
|
||||
if (
|
||||
errorCode === 500 ||
|
||||
errorCode === 502 ||
|
||||
errorCode === 504 ||
|
||||
/\b(?:500|502|504)\b|\bINTERNAL\b|BAD_GATEWAY/i.test(s)
|
||||
) {
|
||||
return 'upstream';
|
||||
}
|
||||
if (
|
||||
errorCode === 400 ||
|
||||
errorCode === 401 ||
|
||||
errorCode === 403 ||
|
||||
errorCode === 404 ||
|
||||
/\b(?:400|401|403|404)\b|PERMISSION_DENIED|UNAUTHENTICATED|FAILED_PRECONDITION|NOT_FOUND|unknown model|unsupported mime/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'auth_or_model';
|
||||
}
|
||||
return 'error';
|
||||
}
|
||||
|
||||
function cleanAnomalyErrorExcerpt(rawText) {
|
||||
let s = String(rawText || '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!s) return '';
|
||||
s = s.replace(/^API error \(attempt \d+\):\s*/i, '');
|
||||
s = s.replace(/^agent executor error:\s*generating and executing:\s*/i, '');
|
||||
s = s.replace(/^request failed:\s*/i, '');
|
||||
return s.length > 180 ? `${s.slice(0, 179)}…` : s;
|
||||
}
|
||||
|
||||
function extractErrorStepPayload(step) {
|
||||
if (!step || typeof step !== 'object') return null;
|
||||
const em = step.errorMessage;
|
||||
const errObj = em?.error && typeof em.error === 'object' ? em.error : em;
|
||||
const shortErr = String(
|
||||
errObj?.shortError ||
|
||||
errObj?.message ||
|
||||
step.error ||
|
||||
''
|
||||
).trim();
|
||||
const userMsg = String(errObj?.userErrorMessage || '').trim();
|
||||
const fallbackContent =
|
||||
!shortErr && !userMsg && typeof step.content === 'string'
|
||||
? step.content.replace(/^Error:\s*/i, '').trim()
|
||||
: '';
|
||||
const message = shortErr || userMsg || fallbackContent;
|
||||
if (!message) return null;
|
||||
const errorCode = Number(errObj?.errorCode || 0) || 0;
|
||||
const terminal = Boolean(em?.shouldShowUser);
|
||||
return { message, userMsg, errorCode, terminal };
|
||||
}
|
||||
|
||||
function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) {
|
||||
const retryInfosRaw = [
|
||||
...(Array.isArray(chat?.retryInfos) ? chat.retryInfos : []),
|
||||
...(Array.isArray(meta?.retryInfos) ? meta.retryInfos : []),
|
||||
];
|
||||
const retryErrorEntries = [];
|
||||
for (let i = 0; i < retryInfosRaw.length; i += 1) {
|
||||
const ri = retryInfosRaw[i];
|
||||
if (!ri || typeof ri !== 'object') continue;
|
||||
const errText = String(ri.error || ri.errorMessage || '').trim();
|
||||
const reasonCode = Number(ri.reasonCode || 0) || 0;
|
||||
const delaySec = duration(ri.retryDelay);
|
||||
if (!errText && !(reasonCode > 0 && reasonCode !== 3)) continue;
|
||||
const kind = classifyStepAnomalyError(errText, { reasonCode });
|
||||
// 纯用户取消且无其他重试时不重复打告警微标(速度列已有「已取消」)
|
||||
if (kind === 'canceled') continue;
|
||||
retryErrorEntries.push({
|
||||
attempt: retryErrorEntries.length + 1,
|
||||
kind,
|
||||
delaySec: delaySec != null && delaySec > 0 ? +delaySec.toFixed(1) : 0,
|
||||
message: cleanAnomalyErrorExcerpt(errText),
|
||||
terminal: reasonCode === 3,
|
||||
source: 'retry',
|
||||
});
|
||||
}
|
||||
|
||||
const events = [...retryErrorEntries];
|
||||
const declaredRetryCount = Math.max(0, Math.floor(Number(chat?.retryCount || 0)));
|
||||
|
||||
// 合并同一轮前置 ERROR_MESSAGE 步骤(对已被 retryInfos 记录的同源重试做去重,保留断流续跑/安全过滤/离线日志补充)
|
||||
const usedRetryKinds = new Map();
|
||||
for (const ev of retryErrorEntries) {
|
||||
usedRetryKinds.set(ev.kind, (usedRetryKinds.get(ev.kind) || 0) + 1);
|
||||
}
|
||||
const matchedKindBudget = new Map(usedRetryKinds);
|
||||
|
||||
for (const errStep of pendingErrorSteps || []) {
|
||||
const info = extractErrorStepPayload(errStep);
|
||||
if (!info) continue;
|
||||
const kind = classifyStepAnomalyError(info.message, { errorCode: info.errorCode });
|
||||
if (kind === 'canceled') continue;
|
||||
const isInterruptOrSafety =
|
||||
kind === 'safety' ||
|
||||
/The stream was interrupted/i.test(info.message) ||
|
||||
info.terminal;
|
||||
if (!isInterruptOrSafety) {
|
||||
const rem = matchedKindBudget.get(kind) || 0;
|
||||
if (rem > 0) {
|
||||
matchedKindBudget.set(kind, rem - 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
events.push({
|
||||
attempt: events.length + 1,
|
||||
kind,
|
||||
delaySec: 0,
|
||||
message: cleanAnomalyErrorExcerpt(info.message),
|
||||
terminal: Boolean(info.terminal),
|
||||
source: 'error_step',
|
||||
});
|
||||
}
|
||||
|
||||
const isStatusError = step?.status === 'CORTEX_STEP_STATUS_ERROR';
|
||||
const isStatusInterrupted = step?.status === 'CORTEX_STEP_STATUS_INTERRUPTED';
|
||||
if (events.length === 0 && (isStatusError || isStatusInterrupted)) {
|
||||
events.push({
|
||||
attempt: 1,
|
||||
kind: isStatusInterrupted ? 'disconnect' : 'error',
|
||||
delaySec: 0,
|
||||
message: '',
|
||||
terminal: isStatusError,
|
||||
source: 'status',
|
||||
});
|
||||
}
|
||||
|
||||
const count = Math.max(events.length, declaredRetryCount);
|
||||
if (count <= 0) return null;
|
||||
|
||||
if (events.length === 0 && declaredRetryCount > 0) {
|
||||
events.push({
|
||||
attempt: 1,
|
||||
kind: 'error',
|
||||
delaySec: 0,
|
||||
message: '',
|
||||
terminal: false,
|
||||
source: 'retry_count',
|
||||
});
|
||||
}
|
||||
|
||||
const kinds = {};
|
||||
let totalDelaySec = 0;
|
||||
let hasDanger = isStatusError;
|
||||
for (const ev of events) {
|
||||
kinds[ev.kind] = (kinds[ev.kind] || 0) + 1;
|
||||
if (ev.delaySec > 0) totalDelaySec += ev.delaySec;
|
||||
if (ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model') {
|
||||
hasDanger = true;
|
||||
}
|
||||
}
|
||||
// 归并主分类:按出现次数降序,同次数按严重度优先级决胜
|
||||
let primaryKind = events[0].kind;
|
||||
let bestCount = -1;
|
||||
let bestPrio = -1;
|
||||
for (const [k, c] of Object.entries(kinds)) {
|
||||
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
|
||||
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
|
||||
primaryKind = k;
|
||||
bestCount = c;
|
||||
bestPrio = prio;
|
||||
}
|
||||
}
|
||||
|
||||
const roundedDelay = totalDelaySec > 0 ? +totalDelaySec.toFixed(1) : 0;
|
||||
const severity = hasDanger ? 'danger' : 'warn';
|
||||
const compactEvents = events.slice(0, 6).map((ev, idx) => ({
|
||||
attempt: idx + 1,
|
||||
kind: ev.kind,
|
||||
...(ev.delaySec > 0 ? { delaySec: ev.delaySec } : {}),
|
||||
...(ev.message ? { message: ev.message } : {}),
|
||||
...(ev.terminal ? { terminal: true } : {}),
|
||||
}));
|
||||
const kindSig = Object.entries(kinds)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',');
|
||||
const sig = `${primaryKind}:${count}:${severity}:${roundedDelay}:${kindSig}`;
|
||||
return {
|
||||
anomaly: {
|
||||
count,
|
||||
primaryKind,
|
||||
severity,
|
||||
totalDelaySec: roundedDelay,
|
||||
kinds,
|
||||
events: compactEvents,
|
||||
},
|
||||
anomalySig: sig,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从原始轨迹步骤数组与生成器元数据中提取标准化模型步骤指标。
|
||||
*
|
||||
@@ -679,6 +933,78 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
return Boolean(step.userInput && typeof step.userInput === 'object');
|
||||
};
|
||||
|
||||
const hasHumanUserTurn = rawSteps.some(isUserTurnBoundary);
|
||||
|
||||
const isSystemWakeupBoundary = (step) => {
|
||||
if (hasHumanUserTurn || !step || typeof step !== 'object') return false;
|
||||
if (isCheckpointStep(step)) return false;
|
||||
const t = String(step.type || '').trim().toUpperCase();
|
||||
if (t !== 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && t !== 'SYSTEM_MESSAGE') {
|
||||
return false;
|
||||
}
|
||||
const rawMsg = String(step?.systemMessage?.message || step?.content || '').trim();
|
||||
const withoutSummary = rawMsg
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.trim();
|
||||
if (!withoutSummary || /BROWSER_HOST_FACTS/i.test(withoutSummary)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
const extractSystemWakeupInfo = (step) => {
|
||||
let raw = String(step?.systemMessage?.message || step?.content || '').trim();
|
||||
const sysMatches = [...raw.matchAll(/<SYSTEM_MESSAGE>([\s\S]*?)<\/SYSTEM_MESSAGE>/gi)];
|
||||
if (sysMatches.length > 0) {
|
||||
raw = sysMatches[sysMatches.length - 1][1].trim();
|
||||
} else {
|
||||
raw = raw.replace(/^The following is a <SYSTEM_MESSAGE>[\s\S]*?<SYSTEM_MESSAGE>/i, '').replace(/<\/SYSTEM_MESSAGE>\s*$/i, '').trim();
|
||||
}
|
||||
raw = raw.replace(/^\[Message\]\s+timestamp=\S+\s+sender=\S+\s+priority=\S+\s+content=/i, '').trim();
|
||||
|
||||
const doorbellMatch = raw.match(/^\[swarm\]\s+new board message\s+#(\d+)\s*$/i);
|
||||
if (doorbellMatch) {
|
||||
const tag = `[swarm] #${doorbellMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true };
|
||||
}
|
||||
|
||||
const assignMatch = raw.match(
|
||||
/^You have just started\.\s*Your assignment\s*\(recorded on the board as #(\d+)\s+for\s+@?([^\s):]+)\)\s*:\s*([\s\S]*)$/i
|
||||
);
|
||||
if (assignMatch) {
|
||||
const seq = assignMatch[1];
|
||||
const member = assignMatch[2];
|
||||
const bodyLines = String(assignMatch[3] || '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.filter(Boolean);
|
||||
const bodyPreview = bodyLines.join(' ');
|
||||
const full = bodyPreview ? `#${seq} @${member} · ${bodyPreview}` : `#${seq} @${member}`;
|
||||
const cleanText = full.length > 180 ? `${full.slice(0, 179)}…` : full;
|
||||
return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false };
|
||||
}
|
||||
|
||||
const boardDeltaMatch = raw.match(
|
||||
/^\[board\]\s+the latest message is #(\d+)\s*\(you have read up to #(\d+)\)/i
|
||||
);
|
||||
if (boardDeltaMatch) {
|
||||
const tag = `[board] #${boardDeltaMatch[2]} -> #${boardDeltaMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true };
|
||||
}
|
||||
|
||||
const monitorTickMatch = raw.match(/^\[monitor\]\s+tick:[^(]*\(iteration\s+(\d+)\)\s*$/i);
|
||||
if (monitorTickMatch) {
|
||||
const tag = `[monitor] tick #${monitorTickMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: false };
|
||||
}
|
||||
|
||||
const cleaned = raw
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned;
|
||||
return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false };
|
||||
};
|
||||
|
||||
const extractUserTurnInfo = (step) => {
|
||||
const ui = step?.userInput;
|
||||
let raw = '';
|
||||
@@ -717,15 +1043,111 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
};
|
||||
|
||||
let pendingTurnCleanPrompts = [];
|
||||
let pendingTurnDoorbellOnly = false;
|
||||
let pendingErrorSteps = [];
|
||||
|
||||
const isErrorMessageStep = (step) => {
|
||||
if (!step || typeof step !== 'object') return false;
|
||||
const t = String(step.type || '').trim().toUpperCase();
|
||||
return (
|
||||
t === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' ||
|
||||
t === 'ERROR_MESSAGE' ||
|
||||
Boolean(step.errorMessage && typeof step.errorMessage === 'object')
|
||||
);
|
||||
};
|
||||
|
||||
const mergeTrailingErrorsIntoStep = (targetStep, errSteps) => {
|
||||
if (!targetStep || !Array.isArray(errSteps) || errSteps.length === 0) return;
|
||||
const prevEvents = Array.isArray(targetStep.anomaly?.events) ? targetStep.anomaly.events : [];
|
||||
const trailingRec = buildStepAnomalyRecord(null, null, null, errSteps);
|
||||
if (!trailingRec) return;
|
||||
const isStatusOnlyPlaceholder =
|
||||
prevEvents.length === 1 &&
|
||||
Number(targetStep.anomaly?.count || 0) === 1 &&
|
||||
!prevEvents[0].message &&
|
||||
!(Number(prevEvents[0].delaySec) > 0) &&
|
||||
(prevEvents[0].kind === 'error' || prevEvents[0].kind === 'disconnect');
|
||||
if (prevEvents.length === 0 || isStatusOnlyPlaceholder) {
|
||||
const nextAnomaly =
|
||||
isStatusOnlyPlaceholder &&
|
||||
targetStep.anomaly?.severity === 'danger' &&
|
||||
trailingRec.anomaly.severity !== 'danger'
|
||||
? { ...trailingRec.anomaly, severity: 'danger' }
|
||||
: trailingRec.anomaly;
|
||||
targetStep.anomaly = nextAnomaly;
|
||||
targetStep.anomalySig =
|
||||
nextAnomaly === trailingRec.anomaly
|
||||
? trailingRec.anomalySig
|
||||
: trailingRec.anomalySig.replace(':warn:', ':danger:');
|
||||
return;
|
||||
}
|
||||
const mergedKinds = { ...(targetStep.anomaly.kinds || {}) };
|
||||
for (const [k, c] of Object.entries(trailingRec.anomaly.kinds || {})) {
|
||||
mergedKinds[k] = (mergedKinds[k] || 0) + c;
|
||||
}
|
||||
const mergedCount = Number(targetStep.anomaly.count || 0) + Number(trailingRec.anomaly.count || 0);
|
||||
const mergedDelay = +(
|
||||
Number(targetStep.anomaly.totalDelaySec || 0) + Number(trailingRec.anomaly.totalDelaySec || 0)
|
||||
).toFixed(1);
|
||||
const mergedSeverity =
|
||||
targetStep.anomaly.severity === 'danger' || trailingRec.anomaly.severity === 'danger'
|
||||
? 'danger'
|
||||
: 'warn';
|
||||
let primaryKind = targetStep.anomaly.primaryKind || trailingRec.anomaly.primaryKind;
|
||||
let bestCount = -1;
|
||||
let bestPrio = -1;
|
||||
for (const [k, c] of Object.entries(mergedKinds)) {
|
||||
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
|
||||
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
|
||||
primaryKind = k;
|
||||
bestCount = c;
|
||||
bestPrio = prio;
|
||||
}
|
||||
}
|
||||
const combinedEvents = [...prevEvents, ...(trailingRec.anomaly.events || [])]
|
||||
.slice(0, 6)
|
||||
.map((ev, i) => ({ ...ev, attempt: i + 1 }));
|
||||
const kindSig = Object.entries(mergedKinds)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',');
|
||||
targetStep.anomaly = {
|
||||
count: mergedCount,
|
||||
primaryKind,
|
||||
severity: mergedSeverity,
|
||||
totalDelaySec: mergedDelay,
|
||||
kinds: mergedKinds,
|
||||
events: combinedEvents,
|
||||
};
|
||||
targetStep.anomalySig = `${primaryKind}:${mergedCount}:${mergedSeverity}:${mergedDelay}:${kindSig}`;
|
||||
};
|
||||
|
||||
rawSteps.forEach((s, index) => {
|
||||
if (isUserTurnBoundary(s)) {
|
||||
const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s);
|
||||
const isHumanBoundary = isUserTurnBoundary(s);
|
||||
const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s);
|
||||
if (isHumanBoundary || isWakeupBoundary) {
|
||||
if (pendingErrorSteps.length > 0 && result.length > 0) {
|
||||
const lastPrev = result[result.length - 1];
|
||||
if (lastPrev.turnIndex === activeTurnIndex) {
|
||||
mergeTrailingErrorsIntoStep(lastPrev, pendingErrorSteps);
|
||||
}
|
||||
}
|
||||
pendingErrorSteps = [];
|
||||
const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary
|
||||
? extractUserTurnInfo(s)
|
||||
: extractSystemWakeupInfo(s);
|
||||
if (!hasUnconsumedTurn) {
|
||||
hasUnconsumedTurn = true;
|
||||
pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
|
||||
pendingTurnCleanPrompts = cleanText ? [cleanText] : [];
|
||||
pendingTurnHasMedia = hasMedia;
|
||||
} else {
|
||||
pendingTurnDoorbellOnly = Boolean(isWakeupBoundary && isDoorbellOnly);
|
||||
} else if (isWakeupBoundary && pendingTurnDoorbellOnly && !isDoorbellOnly && cleanText) {
|
||||
// 合并连续唤醒步时,用紧随其后的真实简报/任务正文覆盖前置的纯 #seq 门铃提示
|
||||
pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
|
||||
pendingTurnCleanPrompts = [cleanText];
|
||||
pendingTurnDoorbellOnly = false;
|
||||
} else if (!(isWakeupBoundary && isDoorbellOnly && !pendingTurnDoorbellOnly)) {
|
||||
if (
|
||||
legacyPrompt &&
|
||||
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt
|
||||
@@ -742,11 +1164,18 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isErrorMessageStep(s)) {
|
||||
pendingErrorSteps.push(s);
|
||||
return;
|
||||
}
|
||||
|
||||
const m = s?.metadata;
|
||||
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
|
||||
if (!u) {
|
||||
return;
|
||||
}
|
||||
const stepPendingErrors = pendingErrorSteps;
|
||||
pendingErrorSteps = [];
|
||||
|
||||
let stepIsTurnStart = false;
|
||||
let stepTurnPrompt = '';
|
||||
@@ -769,6 +1198,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
pendingTurnPrompts = [];
|
||||
pendingTurnCleanPrompts = [];
|
||||
pendingTurnHasMedia = false;
|
||||
pendingTurnDoorbellOnly = false;
|
||||
}
|
||||
|
||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||
@@ -833,6 +1263,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
let timingReason = null;
|
||||
if (s.status === 'CORTEX_STEP_STATUS_CANCELED') {
|
||||
timingReason = 'canceled';
|
||||
} else if (s.status === 'CORTEX_STEP_STATUS_ERROR') {
|
||||
timingReason = 'error';
|
||||
} else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') {
|
||||
timingReason = 'interrupted';
|
||||
} else if (!complete || !(totalDurationSec > 0)) {
|
||||
timingReason = 'incomplete_or_invalid_timing';
|
||||
} else if (!validCount(u.outputTokens)) {
|
||||
@@ -897,6 +1331,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
? 'Orchestrator Worker (Hydrogen)'
|
||||
: rawDisplayName;
|
||||
|
||||
const anomalyRec = buildStepAnomalyRecord(s, m, chat, stepPendingErrors);
|
||||
|
||||
result.push({
|
||||
stepIndex,
|
||||
isCompactionStep,
|
||||
@@ -936,6 +1372,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
speedSampleEligible:
|
||||
totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
...(anomalyRec ? { anomaly: anomalyRec.anomaly, anomalySig: anomalyRec.anomalySig } : {}),
|
||||
turnIndex: activeTurnIndex,
|
||||
isTurnStart: stepIsTurnStart,
|
||||
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
|
||||
@@ -944,6 +1381,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
});
|
||||
});
|
||||
|
||||
if (pendingErrorSteps.length > 0 && result.length > 0) {
|
||||
const lastStep = result[result.length - 1];
|
||||
if (lastStep.turnIndex === activeTurnIndex) {
|
||||
mergeTrailingErrorsIntoStep(lastStep, pendingErrorSteps);
|
||||
}
|
||||
}
|
||||
|
||||
// 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐
|
||||
if (
|
||||
result.length > 0 &&
|
||||
@@ -1845,6 +2289,144 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'swarm') {
|
||||
const action = pickField(['action', 'Action']).toLowerCase();
|
||||
const memberName = pickField(['name', 'Name']).replace(/^@+/, '').trim();
|
||||
if (action === 'add') {
|
||||
const rawTasks = unwrapArgValue(args?.tasks);
|
||||
const rawCount = Number(unwrapArgValue(args?.n) || 0);
|
||||
const shardCount = Array.isArray(rawTasks) && rawTasks.length > 1
|
||||
? rawTasks.length
|
||||
: rawCount > 1
|
||||
? Math.floor(rawCount)
|
||||
: 0;
|
||||
const detail = memberName
|
||||
? shardCount > 1
|
||||
? `@${memberName}-1..${shardCount}`
|
||||
: `@${memberName}`
|
||||
: '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_add',
|
||||
isAskUser: false,
|
||||
label: '派生工蜂',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
if (action === 'title') {
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_title',
|
||||
isAskUser: false,
|
||||
label: '命名蜂群',
|
||||
detail: cleanSingleLineSnippet(pickField(['title', 'Title']), 44) || '',
|
||||
};
|
||||
}
|
||||
if (action === 'kill') {
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_kill',
|
||||
isAskUser: false,
|
||||
label: '终止工蜂',
|
||||
detail: memberName ? `@${memberName}` : '',
|
||||
};
|
||||
}
|
||||
if (action === 'model') {
|
||||
const target = memberName ? `@${memberName}` : '@coordinator';
|
||||
const nextModel = pickField(['model', 'Model']);
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_model',
|
||||
isAskUser: false,
|
||||
label: '切换工蜂模型',
|
||||
detail: nextModel ? `${target} -> ${nextModel}` : target,
|
||||
};
|
||||
}
|
||||
if (action === 'channel') {
|
||||
const op = pickField(['op', 'Op']);
|
||||
const ch = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_channel',
|
||||
isAskUser: false,
|
||||
label: '蜂群频道',
|
||||
detail: ch ? `${op ? `${op} ` : ''}#${ch}` : op || '',
|
||||
};
|
||||
}
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_status',
|
||||
isAskUser: false,
|
||||
label: '巡检蜂群',
|
||||
detail: action || 'status',
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'post_message') {
|
||||
const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
const textSnippet = cleanSingleLineSnippet(pickField(['text', 'Text']), 48);
|
||||
const detail =
|
||||
channel && channel !== 'main'
|
||||
? `[#${channel}]${textSnippet ? ` ${textSnippet}` : ''}`
|
||||
: textSnippet || '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'post_message',
|
||||
isAskUser: false,
|
||||
label: '发布看板',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'read_board') {
|
||||
const rawStatus = unwrapArgValue(args?.status) ?? pickField(['status']);
|
||||
const isStatus = String(rawStatus).trim().toLowerCase() === 'true';
|
||||
const rawSeqs = unwrapArgValue(args?.seqs);
|
||||
const seqsLabel =
|
||||
Array.isArray(rawSeqs) && rawSeqs.length > 0
|
||||
? `${rawSeqs
|
||||
.slice(0, 4)
|
||||
.map((n) => `#${String(unwrapArgValue(n) ?? n).trim()}`)
|
||||
.join(', ')}${rawSeqs.length > 4 ? '…' : ''}`
|
||||
: '';
|
||||
const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']);
|
||||
const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
const detail = isStatus
|
||||
? 'status'
|
||||
: [
|
||||
channel && channel !== 'main' ? `#${channel}` : '',
|
||||
seqsLabel ||
|
||||
(sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== ''
|
||||
? `#${String(sinceVal).trim()}+`
|
||||
: ''),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'read_board',
|
||||
isAskUser: false,
|
||||
label: '读取看板',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'swarm_wait') {
|
||||
const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']);
|
||||
const detail =
|
||||
sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== ''
|
||||
? `#${String(sinceVal).trim()}+`
|
||||
: '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_wait',
|
||||
isAskUser: false,
|
||||
isSwarmWait: true,
|
||||
label: '看板待命',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'manage_task') {
|
||||
const action = pickField(['Action', 'action']);
|
||||
const taskId = pickField(['TaskId', 'taskId']);
|
||||
@@ -2032,7 +2614,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
const info = summarizeToolCall(activeTool, lastStep);
|
||||
const stepProgress =
|
||||
tools.length > 1 && !hasBracketPrefix(info.detail) ? `${tools.length}/${tools.length}` : '';
|
||||
const phase = info.isAskUser ? 'waiting' : 'tool';
|
||||
const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool';
|
||||
return {
|
||||
phase,
|
||||
toolName: info.toolName,
|
||||
@@ -2115,8 +2697,8 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
if (hasBracketPrefix(info.detail)) {
|
||||
stepProgress = '';
|
||||
}
|
||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
||||
const waitingApproval = Boolean(waiting && !info.isAskUser);
|
||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser || Boolean(info.isSwarmWait);
|
||||
const waitingApproval = Boolean(waiting && !info.isAskUser && !info.isSwarmWait);
|
||||
const resolvedStartMs = startMs || prevStepEndMs || 0;
|
||||
const label = waitingApproval ? `等待确认 · ${info.label}` : info.label;
|
||||
|
||||
@@ -2207,7 +2789,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
getRawStepEndMs(lastStep) ||
|
||||
getRawStepEndMs(plannerStep) ||
|
||||
0;
|
||||
const phase = info.isAskUser ? 'waiting' : 'tool';
|
||||
const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool';
|
||||
|
||||
return {
|
||||
phase,
|
||||
@@ -2228,6 +2810,22 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
const infos = pTools.map((t, idx) =>
|
||||
summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep)
|
||||
);
|
||||
const swarmWaitInfo = infos.find((x) => x.isSwarmWait);
|
||||
if (swarmWaitInfo) {
|
||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||
return {
|
||||
phase: 'waiting',
|
||||
toolName: swarmWaitInfo.toolName,
|
||||
actionKey: swarmWaitInfo.actionKey,
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: swarmWaitInfo.label,
|
||||
detail: swarmWaitInfo.detail,
|
||||
stepProgress: '',
|
||||
startedAtMs: startMs,
|
||||
signature: `swarm-wait:${lastStepId}:${swarmWaitInfo.detail}`,
|
||||
};
|
||||
}
|
||||
const lastToolInfo = infos[infos.length - 1];
|
||||
const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey);
|
||||
const detailsList = infos.map((x) => x.detail).filter(Boolean);
|
||||
@@ -2254,13 +2852,28 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
};
|
||||
}
|
||||
|
||||
// B2.5:Connect RPC 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令
|
||||
// B2.5:Connect RPC / SQLite 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令
|
||||
if (lastIdx > lastPlannerIdx) {
|
||||
const stepTypeUpper = String(lastStep?.type || '').toUpperCase();
|
||||
if (!stepTypeUpper.includes('USER_INPUT') && !stepTypeUpper.includes('GENERIC')) {
|
||||
const hasStepToolMeta = Boolean(lastStep?.metadata?.toolCall?.name);
|
||||
if (!stepTypeUpper.includes('USER_INPUT') && (!stepTypeUpper.includes('GENERIC') || hasStepToolMeta)) {
|
||||
const lastInfo = summarizeToolCall(null, lastStep);
|
||||
if (lastInfo.toolName !== 'tool' || lastInfo.detail) {
|
||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||
if (lastInfo.isSwarmWait) {
|
||||
return {
|
||||
phase: 'waiting',
|
||||
toolName: lastInfo.toolName,
|
||||
actionKey: lastInfo.actionKey,
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: lastInfo.label,
|
||||
detail: lastInfo.detail,
|
||||
stepProgress: '',
|
||||
startedAtMs: startMs,
|
||||
signature: `swarm-wait:${lastStepId}:${lastInfo.detail}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: 'thinking',
|
||||
toolName: lastInfo.toolName,
|
||||
@@ -2332,3 +2945,101 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别并规范化蜂群(Native Swarm)工蜂节点的身份信息,剥离冗余的 `Swarm Worker (<name>)` 包裹。
|
||||
*
|
||||
* @param {{ role?: string, typeName?: string, agentScriptName?: string, memberName?: string }} [input={}]
|
||||
* @returns {{ isSwarmWorker: boolean, memberName: string, isMonitor: boolean, isNarrator: boolean, isAuxiliary: boolean }}
|
||||
*/
|
||||
export function parseSwarmWorkerRole(input = {}) {
|
||||
const rawRole = String(input?.role || '').trim();
|
||||
const rawType = String(input?.typeName || '').trim().toLowerCase();
|
||||
const rawScript = String(input?.agentScriptName || '').trim();
|
||||
const explicitMember = String(input?.memberName || '').trim();
|
||||
|
||||
const wrapperMatch = rawRole.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
|
||||
const isSwarmWorker = Boolean(
|
||||
explicitMember || wrapperMatch || rawType === 'worker' || rawType === 'swarm_worker'
|
||||
);
|
||||
if (!isSwarmWorker) {
|
||||
return {
|
||||
isSwarmWorker: false,
|
||||
memberName: '',
|
||||
isMonitor: false,
|
||||
isNarrator: false,
|
||||
isAuxiliary: false,
|
||||
};
|
||||
}
|
||||
|
||||
const candidate =
|
||||
explicitMember ||
|
||||
(wrapperMatch ? wrapperMatch[1] : '') ||
|
||||
rawScript ||
|
||||
(rawRole.toLowerCase() !== 'worker' && rawRole.toLowerCase() !== 'swarm worker' ? rawRole : '');
|
||||
const memberName = String(candidate || '').replace(/^@+/, '').trim();
|
||||
const isMonitor = /^monitor(?:-\d+)?$/i.test(memberName);
|
||||
const isNarrator = /^narrator(?:-\d+)?$/i.test(memberName);
|
||||
return {
|
||||
isSwarmWorker: true,
|
||||
memberName,
|
||||
isMonitor,
|
||||
isNarrator,
|
||||
isAuxiliary: isMonitor || isNarrator,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断原始轨迹步骤是否已调用 `swarm_wait` 进入留言板待命状态(且后续尚未收到新的用户提问或系统唤醒消息)。
|
||||
*
|
||||
* @param {Array<object>} [rawSteps=[]]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isParkedOnSwarmWait(rawSteps = []) {
|
||||
if (!Array.isArray(rawSteps) || rawSteps.length === 0) return false;
|
||||
let lastIdx = rawSteps.length - 1;
|
||||
while (lastIdx > 0 && isAuxiliaryMetaStep(rawSteps[lastIdx]) && isRawStepComplete(rawSteps[lastIdx])) {
|
||||
lastIdx--;
|
||||
}
|
||||
let lastPlannerIdx = -1;
|
||||
for (let i = lastIdx; i >= 0; i--) {
|
||||
const st = rawSteps[i];
|
||||
const t = String(st?.type || '').trim().toUpperCase();
|
||||
if (t.includes('USER_INPUT') || t.includes('SYSTEM_MESSAGE') || isCheckpointStep(st)) {
|
||||
return false;
|
||||
}
|
||||
if (isPlannerStep(st)) {
|
||||
lastPlannerIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastPlannerIdx < 0) return false;
|
||||
|
||||
const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]);
|
||||
if (
|
||||
pTools.some((tc) => {
|
||||
const n = String(tc?.name || tc?.toolName || tc?.function?.name || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^default_api:/, '');
|
||||
return n === 'swarm_wait';
|
||||
})
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) {
|
||||
const st = rawSteps[k];
|
||||
const toolName = String(st?.metadata?.toolCall?.name || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^default_api:/, '');
|
||||
if (toolName === 'swarm_wait') return true;
|
||||
const rawContent = String(st?.content || '').trim();
|
||||
if (/Waiting for a message that calls on you|Waiting for any message posted after/i.test(rawContent)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user