refactor(panel): extract sqlite/wire primitives, localize charts & structured status, and unify overlay/mock-dom (P2)

This commit is contained in:
fish
2026-11-18 18:46:53 +09:00
parent 1459240751
commit a954a98080
26 changed files with 3393 additions and 3418 deletions
+960 -881
View File
File diff suppressed because it is too large Load Diff
+27 -335
View File
@@ -10,194 +10,38 @@
* 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。
*/ */
import { existsSync, readFileSync, statSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { basename, join } from 'node:path'; import { basename, join } from 'node:path';
import { parseIsoMs } from '../trajectory-metrics.mjs'; import { parseIsoMs } from '../trajectory-metrics.mjs';
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
import {
SQLITE_IN_CHUNK_SIZE,
computeSqliteWalSig,
getNodeSqliteDatabaseSync,
hasBuiltinNodeSqlite,
normalizeSqliteIsoTime,
withReadOnlySqliteDb,
} from './sqlite-client.mjs';
import {
decodeProtoDurationSlice,
decodeProtoMapStringEntry,
decodeProtoTimestampSlice,
readProtoString,
readProtoVarint,
readSubEnd,
skipProtoField,
toUint8Array,
unescapePbtxtString,
} from './proto-wire.mjs';
export {
computeSqliteWalSig,
getNodeSqliteDatabaseSync,
hasBuiltinNodeSqlite,
withReadOnlySqliteDb,
};
const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const SQLITE_IN_CHUNK_SIZE = 400;
const utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
let sqliteResolved = false;
let sqliteDatabaseSyncCtor = null;
/**
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。
* 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。
*
* @returns {Function | null}
*/
export function getNodeSqliteDatabaseSync() {
if (typeof globalThis.DatabaseSync === 'function') {
return globalThis.DatabaseSync;
}
if (sqliteResolved) return sqliteDatabaseSyncCtor;
sqliteResolved = true;
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
return null;
}
const origEmitWarning = process.emitWarning;
try {
if (typeof origEmitWarning === 'function') {
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
if (/SQLite is an experimental feature/i.test(msg)) return;
return origEmitWarning.call(this, warning, ...rest);
};
}
const mod = process.getBuiltinModule('node:sqlite');
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
} catch {
sqliteDatabaseSyncCtor = null;
} finally {
if (typeof origEmitWarning === 'function') {
process.emitWarning = origEmitWarning;
}
}
return sqliteDatabaseSyncCtor;
}
/**
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
*
* @returns {boolean}
*/
export function hasBuiltinNodeSqlite() {
return Boolean(getNodeSqliteDatabaseSync());
}
/**
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
*
* @param {string} dbPath
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
*/
export function computeSqliteWalSig(dbPath) {
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
return { exists: false, mtimeMs: 0, sig: '' };
}
let dbStat = null;
try {
dbStat = statSync(dbPath);
} catch {
return { exists: false, mtimeMs: 0, sig: '' };
}
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
let walStat = null;
const walPath = `${dbPath}-wal`;
if (existsSync(walPath)) {
try {
walStat = statSync(walPath);
} catch {
walStat = null;
}
}
const dbMtimeMs = Number(dbStat.mtimeMs || 0);
const dbSize = Number(dbStat.size || 0);
const walMtimeMs = Number(walStat?.mtimeMs || 0);
const walSize = Number(walStat?.size || 0);
return {
exists: true,
mtimeMs: Math.max(dbMtimeMs, walMtimeMs),
sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`,
};
}
function isSqliteBusyError(err) {
const msg = String(err?.message || err?.code || '');
return /SQLITE_BUSY|database is locked/i.test(msg);
}
/**
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
*/
export function withReadOnlySqliteDb(dbPath, queryFn) {
const DatabaseSync = getNodeSqliteDatabaseSync();
if (!DatabaseSync) return null;
for (let attempt = 0; attempt < 2; attempt++) {
let db = null;
try {
db = new DatabaseSync(dbPath, { readOnly: true });
try {
db.exec('PRAGMA busy_timeout = 1000;');
} catch {
// 兼容最小测试桩
}
return queryFn(db);
} catch (err) {
if (attempt === 0 && isSqliteBusyError(err)) {
continue;
}
throw err;
} finally {
if (db) {
try {
db.close();
} catch {
// 忽略关闭异常
}
}
}
}
return null;
}
/**
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
*
* @param {string} raw
* @returns {string}
*/
function unescapePbtxtString(raw) {
if (typeof raw !== 'string' || !raw) return '';
if (!raw.includes('\\')) return raw;
const bytes = [];
for (let i = 0; i < raw.length; i++) {
const ch = raw[i];
if (ch !== '\\' || i + 1 >= raw.length) {
const encoded = Buffer.from(ch, 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
continue;
}
const next = raw[++i];
if (next >= '0' && next <= '7') {
let oct = next;
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
bytes.push(parseInt(oct, 8) & 0xff);
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
const hex = raw.slice(i + 1, i + 3);
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
bytes.push(parseInt(hex, 16));
i += 2;
} else {
bytes.push(next.charCodeAt(0));
}
} else if (next === 'u' && i + 4 < raw.length) {
const uHex = raw.slice(i + 1, i + 5);
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
i += 4;
} else {
bytes.push(next.charCodeAt(0));
}
} else if (next === 'n') {
bytes.push(0x0a);
} else if (next === 'r') {
bytes.push(0x0d);
} else if (next === 't') {
bytes.push(0x09);
} else {
const encoded = Buffer.from(next, 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
}
}
return Buffer.from(bytes).toString('utf8');
}
/** /**
* 从 `annotations/<cascadeId>.pbtxt` 文本内容中提取顶层 `title` 字段。 * 从 `annotations/<cascadeId>.pbtxt` 文本内容中提取顶层 `title` 字段。
@@ -243,12 +87,6 @@ export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTA
return ''; return '';
} }
function normalizeSqliteIsoTime(value) {
const raw = String(value || '').trim();
if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return '';
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z');
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷) // 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -372,133 +210,6 @@ const PROTO_CHAT_MSG_SOURCES = Object.freeze({
6: 'CHAT_MESSAGE_SOURCE_CONTEXT', 6: 'CHAT_MESSAGE_SOURCE_CONTEXT',
}); });
function toUint8Array(raw) {
if (!raw) return null;
if (raw instanceof Uint8Array) return raw;
if (ArrayBuffer.isView(raw)) {
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
}
if (raw instanceof ArrayBuffer) {
return new Uint8Array(raw);
}
return null;
}
function decodeUtf8Slice(buf, start, end) {
if (start >= end) return '';
if (utf8Decoder) {
return utf8Decoder.decode(buf.subarray(start, end));
}
return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8');
}
function readProtoVarint(buf, state, limit = buf.length) {
if (state.off >= limit) return 0n;
const b0 = buf[state.off];
if (b0 < 0x80) {
state.off += 1;
return BigInt(b0);
}
let result = 0n;
let shift = 0n;
for (let i = 0; i < 10 && state.off < limit; i++) {
const byte = buf[state.off++];
result |= BigInt(byte & 0x7f) << shift;
if ((byte & 0x80) === 0) {
return BigInt.asUintN(64, result);
}
shift += 7n;
}
while (state.off < limit && (buf[state.off++] & 0x80) !== 0) {
// 安全排空超长 varint 延续字节
}
return BigInt.asUintN(64, result);
}
function readSubEnd(buf, state, limit = buf.length) {
const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
return Math.min(limit, state.off + len);
}
function readProtoString(buf, state, limit = buf.length) {
const end = readSubEnd(buf, state, limit);
const str = decodeUtf8Slice(buf, state.off, end);
state.off = end;
return str;
}
function skipProtoField(buf, state, wireType, limit = buf.length) {
if (wireType === 0) {
readProtoVarint(buf, state, limit);
} else if (wireType === 1) {
state.off = Math.min(limit, state.off + 8);
} else if (wireType === 2) {
state.off = readSubEnd(buf, state, limit);
} else if (wireType === 5) {
state.off = Math.min(limit, state.off + 4);
} else if (wireType === 3) {
while (state.off < limit) {
const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
const innerWt = innerTag & 7;
if (innerWt === 4) break;
skipProtoField(buf, state, innerWt, limit);
}
} else if (wireType !== 4) {
state.off = limit;
}
}
function decodeProtoTimestampSlice(buf, state, end) {
let seconds = 0n;
let nanos = 0n;
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 === 0) {
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
} else if (fn === 2 && wt === 0) {
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
if (seconds <= 0n || seconds > 253402300799n) return '';
const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19);
if (nanos > 0n && nanos < 1_000_000_000n) {
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`;
}
return `${baseIso}Z`;
}
function decodeProtoDurationSlice(buf, state, end) {
let seconds = 0n;
let nanos = 0n;
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 === 0) {
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
} else if (fn === 2 && wt === 0) {
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
const totalNs = seconds * 1_000_000_000n + nanos;
if (totalNs < 0n) return '';
if (totalNs === 0n) return '0s';
const wholeSec = totalNs / 1_000_000_000n;
const remNs = Number(totalNs % 1_000_000_000n);
if (remNs === 0) return `${wholeSec}s`;
const frac = String(remNs).padStart(9, '0').replace(/0+$/, '');
return `${wholeSec}.${frac}s`;
}
function decodeProtoModelEnumInt(val) { function decodeProtoModelEnumInt(val) {
const n = Math.trunc(Number(val)); const n = Math.trunc(Number(val));
if (!Number.isFinite(n) || n <= 0) return ''; if (!Number.isFinite(n) || n <= 0) return '';
@@ -518,25 +229,6 @@ function decodeProtoStepStatusEnum(val) {
return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE'; return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE';
} }
function decodeProtoMapStringEntry(buf, state, end) {
let key = '';
let val = '';
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) {
key = readProtoString(buf, state, end);
} else if (fn === 2 && wt === 2) {
val = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return [key, val];
}
function decodeProtoSubagentSpecSlice(buf, state, end) { function decodeProtoSubagentSpecSlice(buf, state, end) {
let typeName = ''; let typeName = '';
let role = ''; let role = '';
+210
View File
@@ -0,0 +1,210 @@
/**
* @fileoverview 零外部依赖的二进制 Protobuf Wire 跳读游标与 `prototext` 字符串反转义原语 (`proto-wire.mjs`)。
*
* 核心能力:
* 1. 无需引入 `protobufjs`,以 `O(1)` 游标位移跳过大体积定长/变长/Group 载荷;
* 2. 基于 `BigInt` 无损解码 64-bit Varint、`google.protobuf.Timestamp` 纳秒级时间戳与 `Duration`;
* 3. 按原始 UTF-8 字节流无损反转义 `prototext` 的 `\ddd` 八进制、`\xHH` 十六进制与 `\uXXXX` 多字节字符。
*/
const protoUtf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
/**
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
*
* @param {string} raw
* @returns {string}
*/
export function unescapePbtxtString(raw) {
if (typeof raw !== 'string' || !raw) return '';
if (!raw.includes('\\')) return raw;
const bytes = [];
for (let i = 0; i < raw.length; i++) {
const ch = raw[i];
if (ch !== '\\' || i + 1 >= raw.length) {
const encoded = Buffer.from(ch, 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
continue;
}
const next = raw[++i];
if (next >= '0' && next <= '7') {
let oct = next;
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
bytes.push(parseInt(oct, 8) & 0xff);
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
const hex = raw.slice(i + 1, i + 3);
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
bytes.push(parseInt(hex, 16));
i += 2;
} else {
bytes.push(next.charCodeAt(0));
}
} else if (next === 'u' && i + 4 < raw.length) {
const uHex = raw.slice(i + 1, i + 5);
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
i += 4;
} else {
bytes.push(next.charCodeAt(0));
}
} else if (next === 'n') {
bytes.push(0x0a);
} else if (next === 'r') {
bytes.push(0x0d);
} else if (next === 't') {
bytes.push(0x09);
} else {
const encoded = Buffer.from(next, 'utf8');
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
}
}
return Buffer.from(bytes).toString('utf8');
}
export function toUint8Array(raw) {
if (!raw) return null;
if (raw instanceof Uint8Array) return raw;
if (ArrayBuffer.isView(raw)) {
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
}
if (raw instanceof ArrayBuffer) {
return new Uint8Array(raw);
}
return null;
}
export function decodeUtf8Slice(buf, start, end) {
if (start >= end) return '';
if (protoUtf8Decoder) {
return protoUtf8Decoder.decode(buf.subarray(start, end));
}
return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8');
}
export function readProtoVarint(buf, state, limit = buf.length) {
if (state.off >= limit) return 0n;
const b0 = buf[state.off];
if (b0 < 0x80) {
state.off += 1;
return BigInt(b0);
}
let result = 0n;
let shift = 0n;
for (let i = 0; i < 10 && state.off < limit; i++) {
const byte = buf[state.off++];
result |= BigInt(byte & 0x7f) << shift;
if ((byte & 0x80) === 0) {
return BigInt.asUintN(64, result);
}
shift += 7n;
}
while (state.off < limit && (buf[state.off++] & 0x80) !== 0) {
// 安全排空超长 varint 延续字节
}
return BigInt.asUintN(64, result);
}
export function readSubEnd(buf, state, limit = buf.length) {
const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
return Math.min(limit, state.off + len);
}
export function readProtoString(buf, state, limit = buf.length) {
const end = readSubEnd(buf, state, limit);
const str = decodeUtf8Slice(buf, state.off, end);
state.off = end;
return str;
}
export function skipProtoField(buf, state, wireType, limit = buf.length) {
if (wireType === 0) {
readProtoVarint(buf, state, limit);
} else if (wireType === 1) {
state.off = Math.min(limit, state.off + 8);
} else if (wireType === 2) {
state.off = readSubEnd(buf, state, limit);
} else if (wireType === 5) {
state.off = Math.min(limit, state.off + 4);
} else if (wireType === 3) {
while (state.off < limit) {
const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
const innerWt = innerTag & 7;
if (innerWt === 4) break;
skipProtoField(buf, state, innerWt, limit);
}
} else if (wireType !== 4) {
state.off = limit;
}
}
export function decodeProtoTimestampSlice(buf, state, end) {
let seconds = 0n;
let nanos = 0n;
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 === 0) {
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
} else if (fn === 2 && wt === 0) {
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
if (seconds <= 0n || seconds > 253402300799n) return '';
const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19);
if (nanos > 0n && nanos < 1_000_000_000n) {
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`;
}
return `${baseIso}Z`;
}
export function decodeProtoDurationSlice(buf, state, end) {
let seconds = 0n;
let nanos = 0n;
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 === 0) {
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
} else if (fn === 2 && wt === 0) {
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
const totalNs = seconds * 1_000_000_000n + nanos;
if (totalNs < 0n) return '';
if (totalNs === 0n) return '0s';
const wholeSec = totalNs / 1_000_000_000n;
const remNs = Number(totalNs % 1_000_000_000n);
if (remNs === 0) return `${wholeSec}s`;
const frac = String(remNs).padStart(9, '0').replace(/0+$/, '');
return `${wholeSec}.${frac}s`;
}
export function decodeProtoMapStringEntry(buf, state, end) {
let key = '';
let val = '';
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) {
key = readProtoString(buf, state, end);
} else if (fn === 2 && wt === 2) {
val = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return [key, val];
}
+155
View File
@@ -0,0 +1,155 @@
/**
* @fileoverview 零业务依赖的本地 SQLite + WAL 非阻塞只读短连接原语 (`sqlite-client.mjs`)。
*
* 核心能力:
* 1. 惰性加载 Node 22.5+ 内置 `node:sqlite`,自动静默实验特性告警,避免污染 CLI / MCP `stdio`;
* 2. 组合主库 `.db` 与 `.db-wal` 的 `mtime + size` 生成复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入;
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
*/
import { existsSync, statSync } from 'node:fs';
export const SQLITE_IN_CHUNK_SIZE = 400;
let sqliteResolved = false;
let sqliteDatabaseSyncCtor = null;
/**
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。
* 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。
*
* @returns {Function | null}
*/
export function getNodeSqliteDatabaseSync() {
if (typeof globalThis.DatabaseSync === 'function') {
return globalThis.DatabaseSync;
}
if (sqliteResolved) return sqliteDatabaseSyncCtor;
sqliteResolved = true;
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
return null;
}
const origEmitWarning = process.emitWarning;
try {
if (typeof origEmitWarning === 'function') {
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
if (/SQLite is an experimental feature/i.test(msg)) return;
return origEmitWarning.call(this, warning, ...rest);
};
}
const mod = process.getBuiltinModule('node:sqlite');
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
} catch {
sqliteDatabaseSyncCtor = null;
} finally {
if (typeof origEmitWarning === 'function') {
process.emitWarning = origEmitWarning;
}
}
return sqliteDatabaseSyncCtor;
}
/**
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
*
* @returns {boolean}
*/
export function hasBuiltinNodeSqlite() {
return Boolean(getNodeSqliteDatabaseSync());
}
/**
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
*
* @param {string} dbPath
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
*/
export function computeSqliteWalSig(dbPath) {
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
return { exists: false, mtimeMs: 0, sig: '' };
}
let dbStat = null;
try {
dbStat = statSync(dbPath);
} catch {
return { exists: false, mtimeMs: 0, sig: '' };
}
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
let walStat = null;
const walPath = `${dbPath}-wal`;
if (existsSync(walPath)) {
try {
walStat = statSync(walPath);
} catch {
walStat = null;
}
}
const dbMtimeMs = Number(dbStat.mtimeMs || 0);
const dbSize = Number(dbStat.size || 0);
const walMtimeMs = Number(walStat?.mtimeMs || 0);
const walSize = Number(walStat?.size || 0);
return {
exists: true,
mtimeMs: Math.max(dbMtimeMs, walMtimeMs),
sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`,
};
}
export function isSqliteBusyError(err) {
const msg = String(err?.message || err?.code || '');
return /SQLITE_BUSY|database is locked/i.test(msg);
}
/**
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
*
* @template T
* @param {string} dbPath
* @param {(db: any) => T} queryFn
* @returns {T | null}
*/
export function withReadOnlySqliteDb(dbPath, queryFn) {
const DatabaseSync = getNodeSqliteDatabaseSync();
if (!DatabaseSync) return null;
for (let attempt = 0; attempt < 2; attempt++) {
let db = null;
try {
db = new DatabaseSync(dbPath, { readOnly: true });
try {
db.exec('PRAGMA busy_timeout = 1000;');
} catch {
// 兼容最小测试桩
}
return queryFn(db);
} catch (err) {
if (attempt === 0 && isSqliteBusyError(err)) {
continue;
}
throw err;
} finally {
if (db) {
try {
db.close();
} catch {
// 忽略关闭异常
}
}
}
}
return null;
}
/**
* 归一化 SQLite `TEXT` 时间列(如 `'2026-11-18 08:12:00+00:00'` -> ISO-8601),剔除零值哨兵时间。
*
* @param {unknown} value
* @returns {string}
*/
export function normalizeSqliteIsoTime(value) {
const raw = String(value || '').trim();
if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return '';
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z');
}
+90 -4
View File
@@ -190,6 +190,10 @@ function enrichActiveConversationSteps(
return { return {
...serializedStep, ...serializedStep,
responseModel: st.responseModel || '', responseModel: st.responseModel || '',
hasKnownModel: Boolean(mInfo.modelId && mInfo.modelId !== 'unknown'),
baseModelUpstream: annotatedUpstreamModel,
baseModelLabel: mInfo.label,
baseModelShort: mInfo.shortName,
modelUpstream, modelUpstream,
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label, modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName, modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
@@ -210,6 +214,7 @@ function enrichActiveConversationSteps(
// 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示 // 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示
let maxTurnIndex = 0; let maxTurnIndex = 0;
const promptByTurn = new Map(); const promptByTurn = new Map();
const mediaByTurn = new Map();
for (const st of enrichedActiveSteps) { for (const st of enrichedActiveSteps) {
const tIdx = st.turnIndex; const tIdx = st.turnIndex;
if (!Number.isInteger(tIdx) || tIdx <= 0) continue; if (!Number.isInteger(tIdx) || tIdx <= 0) continue;
@@ -217,6 +222,13 @@ function enrichActiveConversationSteps(
if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) { if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) {
promptByTurn.set(tIdx, st.turnPrompt); promptByTurn.set(tIdx, st.turnPrompt);
} }
if (st.isTurnStart || !mediaByTurn.has(tIdx)) {
mediaByTurn.set(tIdx, {
cleanPrompt: st.turnPromptClean ?? '',
hasMedia: Boolean(st.turnHasMedia),
mediaOnly: Boolean(st.turnMediaOnly),
});
}
} }
for (const st of enrichedActiveSteps) { for (const st of enrichedActiveSteps) {
const tIdx = st.turnIndex; const tIdx = st.turnIndex;
@@ -225,11 +237,18 @@ function enrichActiveConversationSteps(
st.isTurnStart = false; st.isTurnStart = false;
st.isLatestTurn = false; st.isLatestTurn = false;
st.turnPrompt = ''; st.turnPrompt = '';
st.turnPromptClean = '';
st.turnHasMedia = false;
st.turnMediaOnly = false;
continue; continue;
} }
const turnMedia = mediaByTurn.get(tIdx);
st.isTurnStart = Boolean(st.isTurnStart); st.isTurnStart = Boolean(st.isTurnStart);
st.isLatestTurn = tIdx === maxTurnIndex; st.isLatestTurn = tIdx === maxTurnIndex;
st.turnPrompt = promptByTurn.get(tIdx) || ''; st.turnPrompt = promptByTurn.get(tIdx) || '';
st.turnPromptClean = turnMedia?.cleanPrompt || '';
st.turnHasMedia = Boolean(turnMedia?.hasMedia);
st.turnMediaOnly = Boolean(turnMedia?.mediaOnly);
} }
const latestEnriched = const latestEnriched =
@@ -544,12 +563,15 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
/** /**
* 构建单个代理(主代理或子代理)的标准遥测单元对象。 * 构建单个代理(主代理或子代理)的标准遥测单元对象。
*/ */
function buildAgentUnitTelemetry({ export function buildAgentUnitTelemetry({
agentId, agentId,
cascadeId, cascadeId,
isMain, isMain,
isSideQuestion = false, isSideQuestion = false,
sideIndex = 0, sideIndex = 0,
agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent',
agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0,
customRole = '',
index, index,
shortLabel, shortLabel,
badgeText, badgeText,
@@ -572,6 +594,9 @@ function buildAgentUnitTelemetry({
{ {
agentId, agentId,
agentCascadeId: cascadeId, agentCascadeId: cascadeId,
agentKind,
agentOrdinal,
agentCustomRole: customRole,
agentLabel, agentLabel,
agentBadge: badgeText, agentBadge: badgeText,
agentRole: role, agentRole: role,
@@ -599,6 +624,9 @@ function buildAgentUnitTelemetry({
agentId, agentId,
cascadeId, cascadeId,
isMain, isMain,
agentKind,
agentOrdinal,
customRole,
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
index, index,
shortLabel, shortLabel,
@@ -631,6 +659,9 @@ function buildAgentUnitTelemetry({
: 0, : 0,
latestCacheHitPct: ctxRes.latestCacheHitPct, latestCacheHitPct: ctxRes.latestCacheHitPct,
sessionCacheHitPct: ctxRes.sessionCacheHitPct, sessionCacheHitPct: ctxRes.sessionCacheHitPct,
hasKnownModel: Boolean(enrichedRes.latestEnriched?.hasKnownModel),
activeBaseModelShort: enrichedRes.latestEnriched?.baseModelShort || '',
activeBaseModelLabel: enrichedRes.latestEnriched?.baseModelLabel || '',
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知', activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知', activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
activeModelUpstream: activeModelUpstream:
@@ -814,6 +845,9 @@ export async function buildTelemetryPayloadInternal(
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || ''; subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
const subIndex = idx + 1; const subIndex = idx + 1;
let sideIndex = 0; let sideIndex = 0;
let agentKind = 'subagent';
let agentOrdinal = 0;
let customRole = '';
let shortLabel = ''; let shortLabel = '';
let badgeText = ''; let badgeText = '';
let roleLabel = ''; let roleLabel = '';
@@ -821,6 +855,8 @@ export async function buildTelemetryPayloadInternal(
let agentLabel = ''; let agentLabel = '';
if (isSideQ) { if (isSideQ) {
sideIndex = ++sideQuestionCount; sideIndex = ++sideQuestionCount;
agentKind = 'side_question';
agentOrdinal = sideIndex;
shortLabel = `旁路提问 #${sideIndex}`; shortLabel = `旁路提问 #${sideIndex}`;
badgeText = `旁${sideIndex}`; badgeText = `旁${sideIndex}`;
const cleanSideRole = const cleanSideRole =
@@ -830,11 +866,15 @@ export async function buildTelemetryPayloadInternal(
rawRole !== 'side_question' rawRole !== 'side_question'
? rawRole ? rawRole
: ''; : '';
customRole = cleanSideRole;
roleLabel = cleanSideRole || '旁路提问'; roleLabel = cleanSideRole || '旁路提问';
typeName = 'side_question'; typeName = 'side_question';
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel; agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
} else { } else {
const subOrd = ++normalSubCount; const subOrd = ++normalSubCount;
agentKind = 'subagent';
agentOrdinal = subOrd;
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
shortLabel = `子代理 #${subOrd}`; shortLabel = `子代理 #${subOrd}`;
badgeText = `子${subOrd}`; badgeText = `子${subOrd}`;
roleLabel = rawRole || '子代理'; roleLabel = rawRole || '子代理';
@@ -848,6 +888,9 @@ export async function buildTelemetryPayloadInternal(
isMain: false, isMain: false,
isSideQuestion: isSideQ, isSideQuestion: isSideQ,
sideIndex, sideIndex,
agentKind,
agentOrdinal,
customRole,
index: subIndex, index: subIndex,
shortLabel, shortLabel,
badgeText, badgeText,
@@ -897,6 +940,9 @@ export async function buildTelemetryPayloadInternal(
turnIndex: tIdx, turnIndex: tIdx,
startMs: mSt.createdAtMs || 0, startMs: mSt.createdAtMs || 0,
prompt: mSt.turnPrompt || '', prompt: mSt.turnPrompt || '',
cleanPrompt: mSt.turnPromptClean ?? '',
hasMedia: Boolean(mSt.turnHasMedia),
mediaOnly: Boolean(mSt.turnMediaOnly),
}); });
} }
} }
@@ -923,6 +969,9 @@ export async function buildTelemetryPayloadInternal(
st.rootTurnIndex = matched.turnIndex; st.rootTurnIndex = matched.turnIndex;
st.isRootLatestTurn = matched.turnIndex === maxRootTurn; st.isRootLatestTurn = matched.turnIndex === maxRootTurn;
st.rootTurnPrompt = matched.prompt || ''; st.rootTurnPrompt = matched.prompt || '';
st.rootTurnPromptClean = matched.cleanPrompt ?? '';
st.rootTurnHasMedia = Boolean(matched.hasMedia);
st.rootTurnMediaOnly = Boolean(matched.mediaOnly);
if (!seenRootStarts.has(matched.turnIndex)) { if (!seenRootStarts.has(matched.turnIndex)) {
seenRootStarts.add(matched.turnIndex); seenRootStarts.add(matched.turnIndex);
st.isRootTurnStart = true; st.isRootTurnStart = true;
@@ -1004,6 +1053,8 @@ export async function buildTelemetryPayloadInternal(
? { ? {
...activeActivityAgent.liveActivity, ...activeActivityAgent.liveActivity,
agentId: activeActivityAgent.agentId, agentId: activeActivityAgent.agentId,
agentKind: activeActivityAgent.agentKind || (activeActivityAgent.isMain ? 'main' : activeActivityAgent.isSideQuestion ? 'side_question' : 'subagent'),
agentOrdinal: activeActivityAgent.agentOrdinal || 0,
agentBadge: activeActivityAgent.badgeText, agentBadge: activeActivityAgent.badgeText,
agentShortLabel: activeActivityAgent.shortLabel, agentShortLabel: activeActivityAgent.shortLabel,
agentRole: activeActivityAgent.role, agentRole: activeActivityAgent.role,
@@ -1020,12 +1071,16 @@ export async function buildTelemetryPayloadInternal(
agentId: 'all', agentId: 'all',
cascadeId: activeCascadeId, cascadeId: activeCascadeId,
isMain: false, isMain: false,
agentKind: 'all',
agentOrdinal: 0,
index: -1, index: -1,
shortLabel: '全部汇总', shortLabel: '全部汇总',
badgeText: '全部', badgeText: '全部',
role: aggregatedRoleLabel, role: aggregatedRoleLabel,
typeName: 'all', typeName: 'all',
activeAgentId: activeMainlineAgent.agentId, activeAgentId: activeMainlineAgent.agentId,
activeAgentKind: activeMainlineAgent.agentKind || (activeMainlineAgent.isMain ? 'main' : activeMainlineAgent.isSideQuestion ? 'side_question' : 'subagent'),
activeAgentOrdinal: activeMainlineAgent.agentOrdinal || 0,
activeAgentShortLabel: activeMainlineAgent.shortLabel, activeAgentShortLabel: activeMainlineAgent.shortLabel,
activeAgentBadge: activeMainlineAgent.badgeText, activeAgentBadge: activeMainlineAgent.badgeText,
activeAgentRole: activeMainlineAgent.role, activeAgentRole: activeMainlineAgent.role,
@@ -1049,6 +1104,9 @@ export async function buildTelemetryPayloadInternal(
latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0, latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0,
latestCacheHitPct: latestMetricAgent.latestCacheHitPct, latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
sessionCacheHitPct: combinedSessionCacheHitPct, sessionCacheHitPct: combinedSessionCacheHitPct,
hasKnownModel: Boolean(latestMetricAgent.hasKnownModel),
activeBaseModelShort: latestMetricAgent.activeBaseModelShort || '',
activeBaseModelLabel: latestMetricAgent.activeBaseModelLabel || '',
activeModelShort: latestMetricAgent.activeModelShort, activeModelShort: latestMetricAgent.activeModelShort,
activeModelLabel: latestMetricAgent.activeModelLabel, activeModelLabel: latestMetricAgent.activeModelLabel,
activeModelUpstream: latestMetricAgent.activeModelUpstream, activeModelUpstream: latestMetricAgent.activeModelUpstream,
@@ -1369,11 +1427,16 @@ export async function buildTelemetryPayloadInternal(
''; '';
const subIndex = idx + 1; const subIndex = idx + 1;
let sideIndex = 0; let sideIndex = 0;
let agentKind = 'subagent';
let agentOrdinal = 0;
let customRole = '';
let badgeText = ''; let badgeText = '';
let shortLabel = ''; let shortLabel = '';
let role = ''; let role = '';
if (isSideQ) { if (isSideQ) {
sideIndex = ++runSideIdx; sideIndex = ++runSideIdx;
agentKind = 'side_question';
agentOrdinal = sideIndex;
badgeText = `旁${sideIndex}`; badgeText = `旁${sideIndex}`;
shortLabel = `旁路提问 #${sideIndex}`; shortLabel = `旁路提问 #${sideIndex}`;
const cleanSide = const cleanSide =
@@ -1383,9 +1446,13 @@ export async function buildTelemetryPayloadInternal(
rawRole !== 'side_question' rawRole !== 'side_question'
? rawRole ? rawRole
: ''; : '';
customRole = cleanSide;
role = cleanSide || shortLabel; role = cleanSide || shortLabel;
} else { } else {
const nOrd = ++runNormalSubIdx; const nOrd = ++runNormalSubIdx;
agentKind = 'subagent';
agentOrdinal = nOrd;
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
badgeText = `子${nOrd}`; badgeText = `子${nOrd}`;
shortLabel = `子代理 #${nOrd}`; shortLabel = `子代理 #${nOrd}`;
role = rawRole || shortLabel; role = rawRole || shortLabel;
@@ -1397,6 +1464,9 @@ export async function buildTelemetryPayloadInternal(
? subSum.liveActivity || extractLiveActivity([], true, subModMs) ? subSum.liveActivity || extractLiveActivity([], true, subModMs)
: { : {
phase: 'done', phase: 'done',
actionKey: 'done',
waitingApproval: false,
detailKey: '',
label: '已完成', label: '已完成',
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -1406,6 +1476,9 @@ export async function buildTelemetryPayloadInternal(
return { return {
cascadeId: subCid, cascadeId: subCid,
index: subIndex, index: subIndex,
agentKind,
agentOrdinal,
customRole,
...(isSideQ ? { isSideQuestion: true, sideIndex } : {}), ...(isSideQ ? { isSideQuestion: true, sideIndex } : {}),
badgeText, badgeText,
shortLabel, shortLabel,
@@ -1426,14 +1499,18 @@ export async function buildTelemetryPayloadInternal(
const runningSubCount = subItems.filter((s) => s.isRunning).length; const runningSubCount = subItems.filter((s) => s.isRunning).length;
if ( if (
isMainRunning && isMainRunning &&
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') && (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') &&
runningSubCount === 0 runningSubCount === 0
) { ) {
const pendingIndex = subItems.length + 1; const pendingIndex = subItems.length + 1;
const pendingRole = mainLiveAct.detail || '子代理'; const pendingCustomRole = mainLiveAct.detail || '';
const pendingRole = pendingCustomRole || '子代理';
subItems.push({ subItems.push({
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`, cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
index: pendingIndex, index: pendingIndex,
agentKind: 'subagent',
agentOrdinal: pendingIndex,
customRole: pendingCustomRole,
badgeText: `子${pendingIndex}`, badgeText: `子${pendingIndex}`,
shortLabel: `子代理 #${pendingIndex}`, shortLabel: `子代理 #${pendingIndex}`,
role: pendingRole, role: pendingRole,
@@ -1444,6 +1521,9 @@ export async function buildTelemetryPayloadInternal(
lastModifiedMs: rootFallbackMs, lastModifiedMs: rootFallbackMs,
liveActivity: { liveActivity: {
phase: 'thinking', phase: 'thinking',
actionKey: 'starting',
waitingApproval: false,
detailKey: '',
label: '启动中', label: '启动中',
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -1459,8 +1539,11 @@ export async function buildTelemetryPayloadInternal(
(runningSubList.length > 0 (runningSubList.length > 0
? { ? {
phase: 'waiting', phase: 'waiting',
actionKey: 'waiting_subagent',
waitingApproval: false,
detailKey: '',
label: '等待子代理', label: '等待子代理',
detail: runningSubList.map((s) => s.role).join(', '), detail: runningSubList.map((s) => s.customRole || s.role).join(', '),
stepProgress: '', stepProgress: '',
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs, startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`, signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`,
@@ -1570,6 +1653,9 @@ export async function buildTelemetryPayloadInternal(
: 0, : 0,
latestCacheHitPct, latestCacheHitPct,
sessionCacheHitPct, sessionCacheHitPct,
hasKnownModel: Boolean(latestEnriched?.hasKnownModel),
activeBaseModelShort: latestEnriched?.baseModelShort || '',
activeBaseModelLabel: latestEnriched?.baseModelLabel || '',
activeModelShort: latestEnriched?.modelShort || '模型未知', activeModelShort: latestEnriched?.modelShort || '模型未知',
activeModelLabel: latestEnriched?.modelLabel || '模型未知', activeModelLabel: latestEnriched?.modelLabel || '模型未知',
activeModelUpstream: activeModelUpstream:
+1 -1
View File
@@ -27,8 +27,8 @@ import {
import { import {
readLocalSqliteTrajectory, readLocalSqliteTrajectory,
readLocalSummaryIndex, readLocalSummaryIndex,
withReadOnlySqliteDb,
} from './backend/cli-sqlite-reader.mjs'; } from './backend/cli-sqlite-reader.mjs';
import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
import { import {
ensureCliStatusLineConfigured, ensureCliStatusLineConfigured,
formatCliStatusLineCapsule, formatCliStatusLineCapsule,
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1794988117189"> <link rel="stylesheet" href="/styles.css?v=1794994568891">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1794988117189"></script> <script src="/app.js?v=1794994568891"></script>
</body> </body>
</html> </html>
@@ -10,6 +10,7 @@
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
import { import {
formatAgentBadgeText,
formatTokens, formatTokens,
formatTokensPrecise, formatTokensPrecise,
formatUsd, formatUsd,
@@ -17,6 +18,7 @@ import {
speedReasonText, speedReasonText,
} from '../../core/formatters.js'; } from '../../core/formatters.js';
import { SVG_NS } from '../../icons/SvgIcon.js'; import { SVG_NS } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
let sessionChartUid = 0; let sessionChartUid = 0;
@@ -38,16 +40,16 @@ export const MODEL_COLOR_VARS = Object.freeze([
* @returns {string} * @returns {string}
*/ */
export function getStepModelGroupKey(step) { export function getStepModelGroupKey(step) {
if (!step || typeof step !== 'object') return '模型未知'; if (!step || typeof step !== 'object') return t('fmt.unknownModel');
const rawLabel = String(step.modelLabel || step.label || '') const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '')
.replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\[自动压缩\]\s*$/u, '')
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
.trim(); .trim();
if (rawLabel) return rawLabel; if (rawLabel) return rawLabel;
const rawShort = String(step.modelShort || step.shortName || '') const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '')
.replace(/·压缩\s*$/u, '') .replace(/·(?:压缩|Compact)\s*$/iu, '')
.trim(); .trim();
return rawShort || '模型未知'; return rawShort || t('fmt.unknownModel');
} }
/** /**
@@ -574,7 +576,17 @@ function computeStepTickIndices(count) {
function formatStepAxisTag(st, showAgentPrefix) { function formatStepAxisTag(st, showAgentPrefix) {
const num = `#${Number(st?.stepIndex ?? 0)}`; const num = `#${Number(st?.stepIndex ?? 0)}`;
if (!showAgentPrefix) return num; if (!showAgentPrefix) return num;
const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主'); const badge = formatAgentBadgeText({
agentKind:
st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'),
agentOrdinal:
st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0),
isMain: !st?.isSubagent,
isSideQuestion: Boolean(st?.isSideQuestion),
sideIndex: st?.sideIndex || 0,
index: st?.agentIndex || 0,
badgeText: st?.agentBadge,
});
return `${badge}${num}`; return `${badge}${num}`;
} }
@@ -709,7 +721,7 @@ export function createSessionLineChart() {
const emptyHintEl = h('div', { const emptyHintEl = h('div', {
className: 'sstep-empty-hint text-muted', className: 'sstep-empty-hint text-muted',
text: '当前范围暂无可绘制的调用步骤', text: t('chart.step.empty'),
hidden: true, hidden: true,
}); });
@@ -787,7 +799,10 @@ export function createSessionLineChart() {
patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadLeft, pt.stepTag);
patchText(tipHeadRight, pt.modelText); patchText(tipHeadRight, pt.modelText);
patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入'); patchText(
tipMainLeft,
pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded')
);
patchText(tipMainRight, pt.secondaryRight || ''); patchText(tipMainRight, pt.secondaryRight || '');
patchAttr(tipSub, 'hidden', !pt.subDetail); patchAttr(tipSub, 'hidden', !pt.subDetail);
if (pt.subDetail) { if (pt.subDetail) {
@@ -914,6 +929,7 @@ export function createSessionLineChart() {
? steps ? steps
: steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st)));
patchText(emptyHintEl, t('chart.step.empty'));
if (!matchedSteps.length) { if (!matchedSteps.length) {
currentPoints = []; currentPoints = [];
lastSig = 'empty'; lastSig = 'empty';
@@ -927,7 +943,7 @@ export function createSessionLineChart() {
patchAttr(peakPill, 'hidden', true); patchAttr(peakPill, 'hidden', true);
patchAttr(emptyHintEl, 'hidden', false); patchAttr(emptyHintEl, 'hidden', false);
clearHover(); clearHover();
return { summaryBadge: '0 步' }; return { summaryBadge: t('chart.step.zeroSteps') };
} }
const modelColorMap = new Map(); const modelColorMap = new Map();
@@ -941,7 +957,7 @@ export function createSessionLineChart() {
const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, {
fallback: gk, fallback: gk,
}); });
modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); modelLabelByGroup.set(gk, disp.baseText || disp.text || gk);
} }
} }
for (const st of matchedSteps) { for (const st of matchedSteps) {
@@ -954,7 +970,7 @@ export function createSessionLineChart() {
} }
if (!modelLabelByGroup.has(gk)) { if (!modelLabelByGroup.has(gk)) {
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); modelLabelByGroup.set(gk, disp.baseText || disp.text || gk);
} }
} }
@@ -1014,41 +1030,62 @@ export function createSessionLineChart() {
if (metric === 'totalTokens') { if (metric === 'totalTokens') {
value = isMultiCompare ? modelCumTok : runningTokens; value = isMultiCompare ? modelCumTok : runningTokens;
secondaryRight = `本步 +${formatTokens(stepTotalTok)}`; secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) });
subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`; subDetail = t('chart.step.ioSplit', {
inTok: formatTokens(inTok),
cacheTok: formatTokens(cacheTok),
outTok: formatTokens(outTok),
});
} else if (metric === 'context') { } else if (metric === 'context') {
value = ctxTok; value = ctxTok;
if (hasPrevCtx) { if (hasPrevCtx) {
const sign = ctxDelta >= 0 ? '+' : '-'; const sign = ctxDelta >= 0 ? '+' : '-';
secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`;
} else { } else {
secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`; secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) });
} }
subDetail = st.isCompactionStep subDetail = st.isCompactionStep
? '上下文自动压缩检查点' ? t('chart.step.compactionCheckpoint')
: `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`; : t('chart.step.cacheHitOut', {
pct: Number(st.cacheHitPct ?? 0),
outTok: formatTokens(outTok),
});
} else if (metric === 'tps') { } else if (metric === 'tps') {
valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0;
value = valid ? Number(st.tokPerSec) : 0; value = valid ? Number(st.tokPerSec) : 0;
secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : ''; secondaryRight = Number.isFinite(st.ttftSec)
? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) })
: '';
subDetail = valid subDetail = valid
? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}` ? t('chart.step.outAndCtx', {
: speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本'); outTok: formatTokens(outTok),
ctxTok: formatTokens(ctxTok),
})
: speedReasonText(st.selectedSpeedReason) ||
(st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample'));
} else if (metric === 'ttft') { } else if (metric === 'ttft') {
valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0;
value = valid ? Number(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) ? `${st.tokPerSec.toFixed(1)} tok/s` : '';
subDetail = valid subDetail = valid
? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%` ? t('chart.step.ctxAndCache', {
ctxTok: formatTokens(ctxTok),
pct: Number(st.cacheHitPct ?? 0),
})
: st.isCompactionStep : st.isCompactionStep
? '上下文压缩步' ? t('chart.step.compactionStep')
: '无首字计时样本'; : t('chart.step.noTtftSample');
} else if (metric === 'cost') { } else if (metric === 'cost') {
valid = stepCost !== null; valid = stepCost !== null;
value = valid ? stepCost : 0; value = valid ? stepCost : 0;
const shownCumCost = isMultiCompare ? modelCumCost : runningCost; const shownCumCost = isMultiCompare ? modelCumCost : runningCost;
secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`; secondaryRight = t('chart.step.cumCost', {
subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`; cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }),
});
subDetail = t('chart.step.cacheAndStepTok', {
pct: Number(st.cacheHitPct ?? 0),
tokens: formatTokens(stepTotalTok),
});
} }
if (valid) { if (valid) {
@@ -1108,11 +1145,12 @@ export function createSessionLineChart() {
const validPoints = points.filter((p) => p.valid); const validPoints = points.filter((p) => p.valid);
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
const locale = getEffectiveLocale();
const colorSig = Array.from(modelColorMap.entries()) const colorSig = Array.from(modelColorMap.entries())
.map(([k, v]) => `${k}=${v}`) .map(([k, v]) => `${k}=${v}`)
.join(','); .join(',');
const sig = const sig =
`${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` +
points 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'}`)
.join('|'); .join('|');
@@ -1247,12 +1285,12 @@ export function createSessionLineChart() {
patchStyleVar(swatch, '--swatch-bg', colorVar); patchStyleVar(swatch, '--swatch-bg', colorVar);
const stStat = perModelStats.get(gk); const stStat = perModelStats.get(gk);
const baseLabel = modelLabelByGroup.get(gk) || gk; const baseLabel = modelLabelByGroup.get(gk) || gk;
let summarySuffix = '无样本'; let summarySuffix = t('chart.step.noSamples');
if (stStat && stStat.count > 0) { if (stStat && stStat.count > 0) {
if (metric === 'totalTokens') { if (metric === 'totalTokens') {
summarySuffix = formatTokens(stStat.cumTok); summarySuffix = formatTokens(stStat.cumTok);
} else if (metric === 'context') { } else if (metric === 'context') {
summarySuffix = `峰 ${formatTokens(stStat.max)}`; summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) });
} else if (metric === 'tps' || metric === 'ttft') { } else if (metric === 'tps' || metric === 'ttft') {
summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count);
} else if (metric === 'cost') { } else if (metric === 'cost') {
@@ -1290,7 +1328,10 @@ export function createSessionLineChart() {
const peakPt = points[peakIdx]; const peakPt = points[peakIdx];
patchText( patchText(
peakPill, peakPill,
`峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}` t('chart.step.peakPill', {
tag: peakPt.stepTag,
val: formatChartMetricCompact(metric, peakPt.value),
})
); );
patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor);
const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100));
@@ -1306,28 +1347,42 @@ export function createSessionLineChart() {
showHoverAt(hoveredIdx); showHoverAt(hoveredIdx);
} }
let summaryBadge = `${matchedSteps.length}步`; let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length });
const activeCompareCount = isMultiCompare ? targetKeys.length : 1; const activeCompareCount = isMultiCompare ? targetKeys.length : 1;
const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : ''; const multiPrefix = isMultiCompare
? t('chart.step.multiPrefix', { count: activeCompareCount })
: '';
if (metric === 'totalTokens') { if (metric === 'totalTokens') {
summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`; summaryBadge = t('chart.step.sumTokens', {
prefix: multiPrefix,
tokens: formatTokens(runningTokens),
});
} else if (metric === 'context') { } else if (metric === 'context') {
const lastCtx = points[points.length - 1]?.value || 0; const lastCtx = points[points.length - 1]?.value || 0;
summaryBadge = isMultiCompare summaryBadge = isMultiCompare
? `${multiPrefix}峰值 ${formatTokens(maxVal)}` ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) })
: `当前 ${formatTokens(lastCtx)}`; : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) });
} else if (metric === 'tps') { } else if (metric === 'tps') {
summaryBadge = summaryBadge =
validCount > 0 validCount > 0
? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s` ? t('chart.step.meanTps', {
: '暂无有效样本'; prefix: multiPrefix,
val: (validSum / validCount).toFixed(1),
})
: t('chart.step.noValidSamples');
} else if (metric === 'ttft') { } else if (metric === 'ttft') {
summaryBadge = summaryBadge =
validCount > 0 validCount > 0
? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s` ? t('chart.step.meanSec', {
: '暂无有效样本'; prefix: multiPrefix,
val: (validSum / validCount).toFixed(1),
})
: t('chart.step.noValidSamples');
} else if (metric === 'cost') { } else if (metric === 'cost') {
summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`; summaryBadge = t('chart.step.sumCost', {
prefix: multiPrefix,
cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }),
});
} }
return { summaryBadge }; return { summaryBadge };
@@ -1418,7 +1473,7 @@ export function createModelFitChart() {
const emptyHintEl = h('div', { const emptyHintEl = h('div', {
className: 'sstep-empty-hint text-muted', className: 'sstep-empty-hint text-muted',
text: '该模型暂无有效拟合样本', text: t('chart.fit.empty'),
hidden: true, hidden: true,
}); });
@@ -1433,14 +1488,16 @@ export function createModelFitChart() {
tipSub, tipSub,
]); ]);
const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' }); const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') });
const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') });
const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [
h('span', { className: 'sstep-fit-swatch is-ols' }), h('span', { className: 'sstep-fit-swatch is-ols' }),
h('span', { text: 'OLS 线性' }), olsLegendTextEl,
]); ]);
const obsLegendTextEl = h('span', { text: t('chart.fit.observed') });
const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [
h('span', { className: 'sstep-fit-swatch is-scatter' }), h('span', { className: 'sstep-fit-swatch is-scatter' }),
h('span', { text: '观测值' }), obsLegendTextEl,
h('span', { className: 'sstep-fit-swatch is-curve' }), h('span', { className: 'sstep-fit-swatch is-curve' }),
fitMethodLabelEl, fitMethodLabelEl,
h('span', { className: 'sstep-fit-swatch is-ci' }), h('span', { className: 'sstep-fit-swatch is-ci' }),
@@ -1523,8 +1580,14 @@ export function createModelFitChart() {
patchAttr(tooltipEl, 'hidden', false); patchAttr(tooltipEl, 'hidden', false);
patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadLeft, sp.stepTag);
patchText(tipHeadRight, sp.modelText); patchText(tipHeadRight, sp.modelText);
patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`); patchText(
patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`); tipMainLeft,
t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) })
);
patchText(
tipMainRight,
t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) })
);
patchAttr(tipSub, 'hidden', false); patchAttr(tipSub, 'hidden', false);
if (sp.compareHint) { if (sp.compareHint) {
@@ -1538,7 +1601,10 @@ export function createModelFitChart() {
const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0));
patchText( patchText(
tipSub, tipSub,
`上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%` t('chart.step.ctxAndCache', {
ctxTok: formatTokens(ctxTok),
pct: Number(sp.st?.cacheHitPct ?? 0),
})
); );
} }
@@ -1804,11 +1870,16 @@ export function createModelFitChart() {
xVal: globalX, xVal: globalX,
rawVal, rawVal,
stepTag: formatStepAxisTag(st, showAgentPrefix), stepTag: formatStepAxisTag(st, showAgentPrefix),
modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text, modelText: disp.baseText || disp.text,
}); });
} }
} }
const locale = getEffectiveLocale();
patchText(emptyHintEl, t('chart.fit.empty'));
patchText(obsLegendTextEl, t('chart.fit.observed'));
patchText(olsLegendTextEl, t('chart.fit.olsLinear'));
if (fitCacheMetric !== metric) { if (fitCacheMetric !== metric) {
fitCache.clear(); fitCache.clear();
fitCacheMetric = metric; fitCacheMetric = metric;
@@ -1832,9 +1903,10 @@ export function createModelFitChart() {
patchAttr(singleLegendEl, 'hidden', false); patchAttr(singleLegendEl, 'hidden', false);
patchAttr(multiLegendEl, 'hidden', true); patchAttr(multiLegendEl, 'hidden', true);
patchAttr(emptyHintEl, 'hidden', false); patchAttr(emptyHintEl, 'hidden', false);
patchText(fitMethodLabelEl, t('chart.fit.loess'));
patchText(fitStatsEl, 'n = 0'); patchText(fitStatsEl, 'n = 0');
clearHover(); clearHover();
return { sampleCount: 0, summaryBadge: '0 样本' }; return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') };
} }
patchAttr(emptyHintEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', true);
@@ -1916,7 +1988,12 @@ export function createModelFitChart() {
if (interp !== null) { if (interp !== null) {
peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`);
} else { } else {
peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`); peerParts.push(
t('chart.fit.peerMean', {
label: other.label,
val: formatChartMetricCompact(metric, other.pubFit.mean),
})
);
} }
} }
return { return {
@@ -1929,7 +2006,10 @@ export function createModelFitChart() {
ciHigh: s.pubFit.sampleCiHigh[i], ciHigh: s.pubFit.sampleCiHigh[i],
ciHalf: s.pubFit.sampleCiHalf[i], ciHalf: s.pubFit.sampleCiHalf[i],
seriesColor: s.colorVar, seriesColor: s.colorVar,
compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '', compareHint:
peerParts.length > 0
? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') })
: '',
}; };
}); });
s.samples = sSamples; s.samples = sSamples;
@@ -1939,7 +2019,7 @@ export function createModelFitChart() {
currentSamples = combinedSamples; currentSamples = combinedSamples;
const sig = const sig =
`multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
seriesList seriesList
.map( .map(
(s) => (s) =>
@@ -2053,7 +2133,7 @@ export function createModelFitChart() {
fitStatsEl, fitStatsEl,
seriesList.length <= 2 seriesList.length <= 2
? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ')
: `${seriesList.length} 条拟合线` : t('chart.fit.curvesCount', { count: seriesList.length })
); );
patchAttr(fitStatsEl, 'title', r2SummaryTitle); patchAttr(fitStatsEl, 'title', r2SummaryTitle);
@@ -2065,7 +2145,10 @@ export function createModelFitChart() {
return { return {
sampleCount: combinedSamples.length, sampleCount: combinedSamples.length,
summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`, summaryBadge: t('chart.fit.multiBadge', {
steps: combinedSamples.length,
models: seriesList.length,
}),
}; };
} }
@@ -2080,7 +2163,10 @@ export function createModelFitChart() {
const rawYs = filtered.map((d) => d.rawVal); const rawYs = filtered.map((d) => d.rawVal);
const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); patchText(
fitMethodLabelEl,
pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg')
);
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
let dataMin = Infinity; let dataMin = Infinity;
@@ -2133,7 +2219,7 @@ export function createModelFitChart() {
currentSamples = samples; currentSamples = samples;
const sig = const sig =
`single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + `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)}`).join('|');
if (sig !== lastSig) { if (sig !== lastSig) {
@@ -2209,7 +2295,10 @@ export function createModelFitChart() {
} }
} }
const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`; const summaryBadge = t('chart.fit.singleBadge', {
steps: samples.length,
mean: formatChartMetricCompact(metric, pubFit.mean),
});
if (samples.length >= 2) { if (samples.length >= 2) {
const rSign = pubFit.r >= 0 ? '+' : ''; const rSign = pubFit.r >= 0 ? '+' : '';
const slopeSign = pubFit.slope >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : '';
@@ -2217,7 +2306,11 @@ export function createModelFitChart() {
patchAttr( patchAttr(
fitStatsEl, fitStatsEl,
'title', 'title',
`OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}` t('chart.fit.olsTitle', {
slope: `${slopeSign}${pubFit.slope.toFixed(3)}`,
intercept: pubFit.intercept.toFixed(2),
sd: pubFit.sd.toFixed(2),
})
); );
} else { } else {
patchText(fitStatsEl, `n = ${samples.length}`); patchText(fitStatsEl, `n = ${samples.length}`);
@@ -9,6 +9,7 @@
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
import { SVG_NS } from '../../icons/SvgIcon.js'; import { SVG_NS } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
export const HEATMAP_DAYS_THRESHOLD = 90; export const HEATMAP_DAYS_THRESHOLD = 90;
@@ -176,7 +177,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue;
if (ticks.length > 0 && c.col < nextAllowedCol) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue;
const showYear = crossYear && (c.month === 1 || ticks.length === 0); const showYear = crossYear && (c.month === 1 || ticks.length === 0);
const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`; const text = showYear
? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month })
: t('chart.trend.hmMonthOnly', { month: c.month });
ticks.push({ col: c.col, text }); ticks.push({ col: c.col, text });
nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap);
} }
@@ -311,26 +314,41 @@ export function createTrendAreaChart() {
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]); const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
// 类 GitHub 每日小格子热力图容器(> 90 天模式) // 类 GitHub 每日小格子热力图容器(> 90 天模式)
const weekdayLabels = ['一', '', '三', '', '五', '', '日']; const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') });
const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') });
const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') });
const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') });
const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [
h('span', { className: 'trend-hm-month-spacer' }), h('span', { className: 'trend-hm-month-spacer' }),
...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })), wdayMonEl,
h('span', { className: 'trend-hm-wday', text: '' }),
wdayWedEl,
h('span', { className: 'trend-hm-wday', text: '' }),
wdayFriEl,
h('span', { className: 'trend-hm-wday', text: '' }),
wdaySunEl,
]); ]);
const hmMonthsEl = h('div', { className: 'trend-hm-months' }); const hmMonthsEl = h('div', { className: 'trend-hm-months' });
const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' }); const hmGridEl = h('div', {
className: 'trend-hm-grid',
role: 'grid',
'aria-label': t('chart.trend.hmAria'),
});
const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]);
const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]);
const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]);
const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' });
const hmLessEl = h('span', { text: t('chart.trend.hmLess') });
const hmMoreEl = h('span', { text: t('chart.trend.hmMore') });
const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [
h('span', { text: '少' }), hmLessEl,
h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-0' }),
h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-1' }),
h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-2' }),
h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-3' }),
h('span', { className: 'trend-hm-swatch lv-4' }), h('span', { className: 'trend-hm-swatch lv-4' }),
h('span', { text: '多' }), hmMoreEl,
]); ]);
const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]);
const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [
@@ -359,7 +377,10 @@ export function createTrendAreaChart() {
function populateTooltipContent(slot) { function populateTooltipContent(slot) {
patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); patchText(
tipCallsEl,
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) })
);
const slotTok = safeSlotTokens(slot.tokens); const slotTok = safeSlotTokens(slot.tokens);
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
@@ -379,7 +400,11 @@ export function createTrendAreaChart() {
if (hasSubBreakdown) { if (hasSubBreakdown) {
patchText( patchText(
tipSubEl, tipSubEl,
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` t('chart.step.ioSplit', {
inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)),
cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)),
outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)),
})
); );
} }
} }
@@ -728,19 +753,28 @@ export function createTrendAreaChart() {
const nonZeroVals = []; const nonZeroVals = [];
for (let i = 0; i < slots.length; i++) { for (let i = 0; i < slots.length; i++) {
const t = safeSlotTokens(slots[i]?.tokens); const tokVal = safeSlotTokens(slots[i]?.tokens);
if (t > 0) { if (tokVal > 0) {
activeDays++; activeDays++;
nonZeroVals.push(t); nonZeroVals.push(tokVal);
} }
if (t >= maxTokens) { if (tokVal >= maxTokens) {
maxTokens = t; maxTokens = tokVal;
peakIdx = i; peakIdx = i;
} }
} }
const locale = getEffectiveLocale();
patchText(wdayMonEl, t('chart.trend.wdayMon'));
patchText(wdayWedEl, t('chart.trend.wdayWed'));
patchText(wdayFriEl, t('chart.trend.wdayFri'));
patchText(wdaySunEl, t('chart.trend.wdaySun'));
patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria'));
patchText(hmLessEl, t('chart.trend.hmLess'));
patchText(hmMoreEl, t('chart.trend.hmMore'));
const sig = const sig =
`${useHeatmap ? 'hm' : `line:${viewW}`}|` + `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` +
slots slots
.map( .map(
(s) => (s) =>
@@ -820,8 +854,13 @@ export function createTrendAreaChart() {
const peakSlot = slots[peakIdx]; const peakSlot = slots[peakIdx];
const summaryText = const summaryText =
maxTokens > 0 && peakSlot?.label maxTokens > 0 && peakSlot?.label
? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` ? t('chart.trend.hmActivePeak', {
: `活跃 0/${slots.length} 天`; active: activeDays,
total: slots.length,
label: peakSlot.label,
tokens: formatTokensPrecise(maxTokens),
})
: t('chart.trend.hmActiveZero', { total: slots.length });
patchText(hmSummaryEl, summaryText); patchText(hmSummaryEl, summaryText);
if (hoveredIdx >= slots.length) { if (hoveredIdx >= slots.length) {
@@ -920,7 +959,10 @@ export function createTrendAreaChart() {
const peakSlot = slots[peakIdx]; const peakSlot = slots[peakIdx];
const peakText = const peakText =
maxTokens > 0 && peakSlot?.label maxTokens > 0 && peakSlot?.label
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` ? t('chart.trend.peakPill', {
label: peakSlot.label,
tokens: formatTokensPrecise(maxTokens),
})
: formatTokensPrecise(maxTokens); : formatTokensPrecise(maxTokens);
patchText(peakPill, peakText); patchText(peakPill, peakText);
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
@@ -25,25 +25,23 @@ import {
isEventInside, isEventInside,
patchAttr, patchAttr,
patchClasses, patchClasses,
patchKeyedList,
patchText, patchText,
} from '../../core/domPatch.js'; } from '../../core/domPatch.js';
import { formatElapsedSec } from '../../core/formatters.js';
import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js'; import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js';
import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; import { i18nStore, setI18nLanguage, t } from '../../i18n/index.js';
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
import { import {
RING_CIRCUMFERENCE, buildCapsuleSlotContext,
createCapsuleSlotNode, createCapsuleSlotNode,
resolveMultiSessionCapsuleState,
syncCapsuleSlotNodes, syncCapsuleSlotNodes,
} from '../widgets/CapsuleBarWidget.js'; } from '../widgets/CapsuleBarWidget.js';
import { LiveActivityWidget } from '../widgets/LiveActivityWidget.js';
import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js'; import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js';
import { import {
DEFAULT_CLIENT_HOVER_MODULES, DEFAULT_CLIENT_HOVER_MODULES,
extractHostRouteCascadeId, extractHostRouteCascadeId,
fetchTelemetry, fetchTelemetry,
formatAgentBadgeText,
getAgentBadgeClass,
isMacHostPlatform, isMacHostPlatform,
normalizeClientHoverModules, normalizeClientHoverModules,
normalizeClientPopoverWidth, normalizeClientPopoverWidth,
@@ -982,9 +980,6 @@ export function mountWindowOverlay() {
let multiPinned = false; let multiPinned = false;
let hoverLeaveTimer = null; let hoverLeaveTimer = null;
let multiLeaveTimer = null; let multiLeaveTimer = null;
const manualSubExpandMap = new Map();
const multiTimersMap = new Map();
let multiLiveTickTimer = null;
let hasPointerCoords = Boolean( let hasPointerCoords = Boolean(
carryOverPointer && carryOverPointer &&
Number.isFinite(carryOverPointer.x) && Number.isFinite(carryOverPointer.x) &&
@@ -1082,52 +1077,6 @@ export function mountWindowOverlay() {
}, 90); }, 90);
} }
function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
const now = Date.now();
const prev = multiTimersMap.get(timerKey);
let startMs = prev?.startMs || 0;
if (!prev || prev.sig !== sig) {
const validRaw = Number(rawStartMs || 0);
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
startMs = Number(rawStartMs);
}
multiTimersMap.set(timerKey, { sig, startMs, el: targetEl });
const elapsedSec = Math.max(0, (now - startMs) / 1000);
patchText(targetEl, formatElapsedSec(elapsedSec));
}
function tickMultiElapsedDisplay() {
const now = Date.now();
for (const entry of multiTimersMap.values()) {
if (!entry?.el) continue;
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
patchText(entry.el, formatElapsedSec(elapsedSec));
}
}
function pauseMultiLiveTicker() {
if (multiLiveTickTimer) {
clearInterval(multiLiveTickTimer);
multiLiveTickTimer = null;
}
}
function stopMultiLiveTicker() {
pauseMultiLiveTicker();
multiTimersMap.clear();
}
function ensureMultiLiveTicker() {
if (multiTimersMap.size === 0) {
stopMultiLiveTicker();
return;
}
if (!multiLiveTickTimer) {
multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000);
}
}
function inspectSessionInMonitor(cascadeId) { function inspectSessionInMonitor(cascadeId) {
if (!cascadeId || cascadeId === 'current') return; if (!cascadeId || cascadeId === 'current') return;
uiStore.setState({ uiStore.setState({
@@ -1424,105 +1373,7 @@ export function mountWindowOverlay() {
[hoverUpdateBar, hoverWidgetsContainer] [hoverUpdateBar, hoverWidgetsContainer]
); );
// 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) // 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机)
function createMultiLiveSubRow() {
const subBadge = h('span', {
className: 'agent-badge badge-sub-1',
text: t('fmt.subBadge', { index: 1 }),
});
const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') });
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
const rowEl = h('div', { className: 'live-sub-row' }, [
h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]),
subElapsed,
]);
return {
el: rowEl,
refs: { rowEl, subBadge, subRole, subSummary, subElapsed },
};
}
function createMultiLiveTaskCard() {
const dotIcon = createSvgIcon('dot', { size: 11 });
patchClasses(dotIcon, { 'is-pulsing': true });
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') });
const hereTagEl = h('span', {
className: 'wm-session-tag is-here',
hidden: true,
text: t('multi.hereTag'),
});
const metricsEl = h('span', {
className: 'wm-task-metrics text-mono',
hidden: true,
text: '',
});
const subToggleBtn = h('button', {
type: 'button',
className: 'live-sub-toggle',
hidden: true,
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
});
const elapsedEl = h('span', {
className: 'live-activity-elapsed text-mono',
text: '0s',
});
const headerEl = h('div', { className: 'live-task-header' }, [
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]),
h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]),
]);
const mainBadge = h('span', {
className: 'agent-badge badge-main',
hidden: true,
text: t('fmt.mainBadge'),
});
const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') });
const mainProgress = h('span', {
className: 'live-activity-progress text-mono',
hidden: true,
text: '',
});
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
const mainDetail = h('span', {
className: 'live-activity-detail',
hidden: true,
text: '',
});
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
mainBadge,
mainPhase,
mainProgress,
mainSep,
mainDetail,
]);
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
return {
el: cardEl,
refs: {
cardEl,
dotIcon,
titleEl,
hereTagEl,
metricsEl,
subToggleBtn,
elapsedEl,
mainBadge,
mainPhase,
mainProgress,
mainSep,
mainDetail,
subListEl,
},
};
}
const multiPinBadge = h('span', { const multiPinBadge = h('span', {
className: 'wm-pin-badge', className: 'wm-pin-badge',
hidden: true, hidden: true,
@@ -1539,10 +1390,16 @@ export function mountWindowOverlay() {
multiEmptyTextEl, multiEmptyTextEl,
]), ]),
]); ]);
const multiRunningListEl = h('div', { const multiRunningWidget = LiveActivityWidget({
className: 'live-activity-list', defaultExpandRunningSubs: true,
hidden: true, showSessionExtras: true,
'aria-live': 'polite', isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed),
onSelectSession: inspectSessionInMonitor,
onLayoutChange: () => {
if (multiOpen) {
positionFloatingElements();
}
},
}); });
const multiTitleTextEl = h('span', { text: t('multi.title') }); const multiTitleTextEl = h('span', { text: t('multi.title') });
@@ -1576,7 +1433,7 @@ export function mountWindowOverlay() {
} }
}, },
}, },
[multiHeaderEl, multiEmptyEl, multiRunningListEl] [multiHeaderEl, multiEmptyEl, multiRunningWidget.el]
); );
// 完整四标签悬浮容器 // 完整四标签悬浮容器
@@ -2360,12 +2217,13 @@ export function mountWindowOverlay() {
patchAttr(multiPanelEl, 'hidden', !multiOpen); patchAttr(multiPanelEl, 'hidden', !multiOpen);
if (multiOpen) { if (multiOpen) {
renderCapsuleTelemetry(); renderCapsuleTelemetry();
multiRunningWidget.refs.resumeTicker();
positionFloatingElements(); positionFloatingElements();
if (typeof requestAnimationFrame === 'function') { if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => positionFloatingElements()); requestAnimationFrame(() => positionFloatingElements());
} }
} else { } else {
pauseMultiLiveTicker(); multiRunningWidget.refs.pauseTicker();
} }
} }
@@ -2440,18 +2298,10 @@ export function mountWindowOverlay() {
} }
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
if (manualSubExpandMap.size > 0) { if (!multiOpen || document.hidden) {
const runningIds = new Set(rawRunningList.map((item) => item.cascadeId)); multiRunningWidget.refs.pauseTicker();
for (const id of manualSubExpandMap.keys()) { return;
if (!runningIds.has(id)) manualSubExpandMap.delete(id);
}
} }
if (!multiOpen || document.hidden) return;
const localeKey = getEffectiveLocale();
const hostRouteLower = String(
hostRouteConversationId || extractHostRouteCascadeId() || ''
).toLowerCase();
patchText( patchText(
multiRunningMetaEl, multiRunningMetaEl,
runningCount > 0 runningCount > 0
@@ -2461,201 +2311,10 @@ export function mountWindowOverlay() {
: t('multi.allIdle') : t('multi.allIdle')
); );
patchAttr(multiEmptyEl, 'hidden', runningCount > 0); patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
patchAttr(multiRunningListEl, 'hidden', runningCount === 0); multiRunningWidget.refs.update({
items: rawRunningList,
if (runningCount === 0) { hostRouteConversationId,
stopMultiLiveTicker(); });
patchKeyedList(multiRunningListEl, [], {});
} else {
const activeTimerKeys = new Set();
for (const item of rawRunningList) {
activeTimerKeys.add(`main:${item.cascadeId}`);
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
const runSubs = Number(item.runningSubagentCount || 0);
const isExp = manualSubExpandMap.has(item.cascadeId)
? manualSubExpandMap.get(item.cascadeId)
: runSubs > 0;
if (subCount > 0 && isExp) {
for (const sub of item.subagents || []) {
if (sub?.isRunning) {
activeTimerKeys.add(`sub:${sub.cascadeId}`);
}
}
}
}
patchKeyedList(multiRunningListEl, rawRunningList, {
keyFn: (item) => item.cascadeId,
sigFn: (item) => {
const runSubs = Number(item.runningSubagentCount || 0);
const isExp = manualSubExpandMap.has(item.cascadeId)
? manualSubExpandMap.get(item.cascadeId)
: runSubs > 0;
const isHere =
Boolean(hostRouteLower) &&
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
const subSig = (item.subagents || [])
.map(
(s) =>
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
)
.join('|');
return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
},
createRow: createMultiLiveTaskCard,
updateRow: (refs, item) => {
const act = item.mainActivity || {
phase: 'thinking',
label: t('live.thinking'),
detail: '',
stepProgress: '',
startedAtMs: item.lastModifiedMs || 0,
signature: `fallback:${item.lastModifiedMs || 0}`,
};
const isWaiting = act.phase === 'waiting';
const isCompacting = act.phase === 'compacting';
patchClasses(refs.cardEl, {
'is-waiting': isWaiting,
'is-compacting': isCompacting,
});
patchClasses(refs.dotIcon, { 'is-pulsing': true });
const convTitle =
item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
patchText(refs.titleEl, convTitle);
patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle }));
refs.titleEl.onclick = (e) => {
e.stopPropagation();
inspectSessionInMonitor(item.cascadeId);
};
const isHere =
Boolean(hostRouteLower) &&
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
patchText(refs.hereTagEl, t('multi.hereTag'));
patchAttr(refs.hereTagEl, 'hidden', !isHere);
const metricParts = [];
if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) {
metricParts.push(
`${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s`
);
}
if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) {
metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`);
}
const metricsStr = metricParts.join(' · ');
patchAttr(refs.metricsEl, 'hidden', !metricsStr);
if (metricsStr) {
patchText(refs.metricsEl, metricsStr);
}
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
const runSubCount = Number(item.runningSubagentCount || 0);
const isExpanded = manualSubExpandMap.has(item.cascadeId)
? manualSubExpandMap.get(item.cascadeId)
: runSubCount > 0;
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);
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
refs.subToggleBtn.onclick = (e) => {
e.stopPropagation();
manualSubExpandMap.set(item.cascadeId, !isExpanded);
renderCapsuleTelemetry();
if (multiOpen) {
positionFloatingElements();
}
};
}
const mainTimerKey = `main:${item.cascadeId}`;
activeTimerKeys.add(mainTimerKey);
bindMultiElapsedTimer(
mainTimerKey,
`${item.cascadeId}:${act.signature || act.label}`,
act.startedAtMs,
refs.elapsedEl
);
patchText(refs.mainPhase, act.label || t('live.thinking'));
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
patchAttr(refs.mainProgress, 'hidden', !progText);
if (progText) {
patchText(refs.mainProgress, progText);
}
const detailStr = act.detail || '';
patchAttr(refs.mainSep, 'hidden', !detailStr);
patchAttr(refs.mainDetail, 'hidden', !detailStr);
patchText(refs.mainDetail, detailStr);
const showSubs = subCount > 0 && isExpanded;
patchAttr(refs.subListEl, 'hidden', !showSubs);
if (showSubs) {
const subItems = item.subagents || [];
patchKeyedList(refs.subListEl, subItems, {
keyFn: (sub) => sub.cascadeId,
sigFn: (sub) =>
`${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
createRow: createMultiLiveSubRow,
updateRow: (subRefs, sub) => {
const subAct = sub.liveActivity || {
phase: sub.isRunning ? 'thinking' : 'done',
label: sub.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: sub.lastModifiedMs || 0,
};
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
const subBadgeCls = getAgentBadgeClass(sub.index || 1, false);
patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`);
patchText(subRefs.subBadge, formatAgentBadgeText(sub));
patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent'));
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
const summaryText = sub.isRunning
? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}`
: t('live.doneWithSteps', { steps: sub.stepCount || 0 });
patchText(subRefs.subSummary, summaryText);
const subTimerKey = `sub:${sub.cascadeId}`;
if (sub.isRunning) {
activeTimerKeys.add(subTimerKey);
bindMultiElapsedTimer(
subTimerKey,
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
subAct.startedAtMs || sub.lastModifiedMs,
subRefs.subElapsed
);
} else {
multiTimersMap.delete(subTimerKey);
patchText(
subRefs.subElapsed,
t('header.convMetaSteps', { count: sub.stepCount || 0 })
);
}
},
});
}
},
});
for (const k of [...multiTimersMap.keys()]) {
if (!activeTimerKeys.has(k)) {
multiTimersMap.delete(k);
}
}
ensureMultiLiveTicker();
tickMultiElapsedDisplay();
}
} }
function renderHoverWidgets() { function renderHoverWidgets() {
@@ -2698,7 +2357,7 @@ export function mountWindowOverlay() {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero')); patchText(multiLabel, t('capsule.multiZero'));
patchText(multiRunningMetaEl, t('multi.loading')); patchText(multiRunningMetaEl, t('multi.loading'));
stopMultiLiveTicker(); multiRunningWidget.refs.stopLiveTicker();
applyCapsuleSlots(slotKeys, { hasTelemetry: false }); applyCapsuleSlots(slotKeys, { hasTelemetry: false });
return; return;
@@ -2711,138 +2370,36 @@ export function mountWindowOverlay() {
uiSt.selectedAgentScope, uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId uiSt.ctxInspectorAgentId
); );
const activeConv = telemetry.activeConversation || {}; const overviewActive = overviewScopedConv || telemetry.activeConversation || {};
const overviewActive = overviewScopedConv || activeConv; const slotCtx = buildCapsuleSlotContext(telemetry, {
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; scopedConv: capsuleScopedConv,
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); overviewConv: overviewActive,
const totalTokens = Number(ctx.totalTokens || 0); ctxAgent,
const usedPct = aggregated,
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; });
const dashOffset = +( const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } =
RING_CIRCUMFERENCE * resolveMultiSessionCapsuleState(telemetry, {
(1 - Math.max(0, Math.min(100, usedPct)) / 100) agents,
).toFixed(2); aggregated,
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- latestTokPerSec: overviewActive.latestTokPerSec ?? null,
const rawRunningList = contextUsedPct: slotCtx.usedPct,
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 });
? telemetry.runningConversations
: activeConv.isRunning || aggregated?.isRunning
? [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
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,
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
contextUsedPct: usedPct,
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }),
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
isRunning: Boolean(s.isRunning),
stepCount: Number(s.stepCount || 0),
lastModifiedMs: s.lastModifiedMs || 0,
liveActivity: s.liveActivity || {
phase: s.isRunning ? 'thinking' : 'done',
label: s.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
]
: [];
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
patchClasses(multiBtn, { patchClasses(multiBtn, {
'is-running': runningCount > 0 && !hasWaiting, 'is-running': runningCount > 0 && !hasWaiting,
'is-waiting': runningCount > 0 && hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting,
}); });
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
patchText(multiLabel, multiBtnText); patchText(multiLabel, multiBtnText);
renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId); renderMultiRunningPanel(
rawRunningList,
runningCount,
runningSubCount,
telSt.hostRouteConversationId
);
// --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); applyCapsuleSlots(slotKeys, slotCtx);
const capActive = capsuleScopedConv || aggregated || activeConv || {};
const tps =
capsuleScopedConv?.latestTokPerSec ??
aggregated?.latestTokPerSec ??
activeConv.latestTokPerSec ??
null;
const avgTps =
capsuleScopedConv?.avgTokPerSec ??
aggregated?.avgTokPerSec ??
activeConv.avgTokPerSec ??
null;
const ttft =
capsuleScopedConv?.latestTtftSec ??
aggregated?.latestTtftSec ??
activeConv.latestTtftSec ??
null;
const capsuleStepCost =
capsuleScopedConv?.latestStepCostUsd ??
aggregated?.latestStepCostUsd ??
activeConv.latestStepCostUsd ??
null;
const sessionCost =
capsuleScopedConv?.sessionCostUsd ??
aggregated?.sessionCostUsd ??
activeConv.sessionCostUsd ??
null;
const cacheHitPct =
Number(capActive.stepCount || 0) > 0
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
: null;
const latestPromptTokens = capActive.latestPromptTokens ?? null;
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
: null;
patchClasses(capsuleBtn, { 'is-running': isRunning });
applyCapsuleSlots(slotKeys, {
hasTelemetry: true,
usedPct,
dashOffset,
isRunning,
tps,
avgTps,
ttft,
stepCost: capsuleStepCost,
sessionCost,
cacheHitPct,
latestPromptTokens,
sessionTokens,
quotas: telemetry.quotas,
});
const updateMode = normalizeClientUpdateMode( const updateMode = normalizeClientUpdateMode(
telemetry.settings?.pluginUpdateMode, telemetry.settings?.pluginUpdateMode,
@@ -3019,7 +2576,7 @@ export function mountWindowOverlay() {
const onVisibilityChange = () => { const onVisibilityChange = () => {
if (document.hidden) { if (document.hidden) {
uiStore.setState({ monitorVisible: false }); uiStore.setState({ monitorVisible: false });
pauseMultiLiveTicker(); multiRunningWidget.refs.pauseTicker();
hasPointerCoords = false; hasPointerCoords = false;
if (tooltipOpen) { if (tooltipOpen) {
setTooltipOpen(false); setTooltipOpen(false);
@@ -3212,7 +2769,7 @@ export function mountWindowOverlay() {
clearTimeout(multiLeaveTimer); clearTimeout(multiLeaveTimer);
multiLeaveTimer = null; multiLeaveTimer = null;
} }
stopMultiLiveTicker(); multiRunningWidget.refs.stopLiveTicker();
if (dockRafId && typeof cancelAnimationFrame === 'function') { if (dockRafId && typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(dockRafId); cancelAnimationFrame(dockRafId);
dockRafId = 0; dockRafId = 0;
@@ -328,8 +328,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
...mainAgent, ...mainAgent,
agentId: 'all', agentId: 'all',
isMain: false, isMain: false,
badgeText: '全部', agentKind: 'all',
agentOrdinal: 0,
badgeText: t('header.scopeAllShort'),
activeAgentId: 'main', activeAgentId: 'main',
activeAgentKind: 'main',
activeAgentOrdinal: 0,
stepCount: 24, stepCount: 24,
speedSampleCount: 23, speedSampleCount: 23,
speedSummary: { sampleCount: 23, excludedCount: 1 }, speedSummary: { sampleCount: 23, excludedCount: 1 },
@@ -343,7 +347,7 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
cacheReadTokens: 1540000, cacheReadTokens: 1540000,
outputTokens: 28400, outputTokens: 28400,
totalTokens: 1754800, totalTokens: 1754800,
activeAgentBadge: '主', activeAgentBadge: t('fmt.mainBadge'),
modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown],
recentSteps: mockSteps, recentSteps: mockSteps,
}; };
@@ -14,10 +14,96 @@ import {
normalizeClientWindowMountMode, normalizeClientWindowMountMode,
resolveScopedConversation, resolveScopedConversation,
} from '../../store/telemetryStore.js'; } from '../../store/telemetryStore.js';
import { buildFallbackRunningConversations } from './LiveActivityWidget.js';
export const RING_RADIUS = 5.2; export const RING_RADIUS = 5.2;
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
/**
* Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation.
*/
export function buildCapsuleSlotContext(
data,
{ scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {}
) {
if (!data) return { hasTelemetry: false };
const activeConv = data.activeConversation || {};
const overviewActive = overviewConv || scopedConv || aggregated || activeConv;
const capActive = scopedConv || aggregated || activeConv || {};
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {};
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const dashOffset = +(
RING_CIRCUMFERENCE *
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
).toFixed(2);
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
: null;
return {
hasTelemetry: true,
usedPct,
dashOffset,
isRunning,
tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null,
avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null,
ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null,
stepCost:
scopedConv?.latestStepCostUsd ??
aggregated?.latestStepCostUsd ??
activeConv.latestStepCostUsd ??
null,
sessionCost:
scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null,
cacheHitPct:
Number(capActive.stepCount || 0) > 0
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
: null,
latestPromptTokens: capActive.latestPromptTokens ?? null,
sessionTokens,
quotas: data.quotas,
};
}
/**
* Compute multi-session button state & normalized running conversation list.
*/
export function resolveMultiSessionCapsuleState(
data,
{ agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {}
) {
const rawRunningList = buildFallbackRunningConversations(data, {
agents,
aggregated,
latestTokPerSec,
contextUsedPct,
});
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText };
}
/** /**
* Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring.
*/ */
@@ -274,75 +360,26 @@ export const CapsuleBarWidget = defineComponent({
return; return;
} }
const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
data, data,
'all', 'all',
'auto' 'auto'
); );
const activeConv = data.activeConversation || {}; const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated });
const capActive = scopedConv || aggregated || activeConv; const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, {
const ctx = ctxAgent?.context || capActive.context || activeConv.context || {}; agents,
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); aggregated,
const totalTokens = Number(ctx.totalTokens || 0); contextUsedPct: slotCtx.usedPct,
const usedPct = });
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const dashOffset = +(
RING_CIRCUMFERENCE *
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
).toFixed(2);
const rawRunningList = Array.isArray(data.runningConversations)
? data.runningConversations
: [];
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
patchClasses(multiBtn, { patchClasses(multiBtn, {
'is-running': runningCount > 0 && !hasWaiting, 'is-running': runningCount > 0 && !hasWaiting,
'is-waiting': runningCount > 0 && hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting,
}); });
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
patchText(multiLabel, multiBtnText); patchText(multiLabel, multiBtnText);
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
: null;
patchClasses(capsuleBtn, { 'is-running': isRunning });
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, {
hasTelemetry: true,
usedPct,
dashOffset,
isRunning,
tps: capActive.latestTokPerSec ?? null,
avgTps: capActive.avgTokPerSec ?? null,
ttft: capActive.latestTtftSec ?? null,
stepCost: capActive.latestStepCostUsd ?? null,
sessionCost: capActive.sessionCostUsd ?? null,
cacheHitPct:
Number(capActive.stepCount || 0) > 0
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
: null,
latestPromptTokens: capActive.latestPromptTokens ?? null,
sessionTokens,
quotas: data.quotas,
});
} }
return { return {
@@ -309,14 +309,16 @@ export const ContextWindowWidget = defineComponent({
if (interactiveInspector) { if (interactiveInspector) {
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
if (hasSubagents && ctxAgent) { if (hasSubagents && ctxAgent) {
const rawActiveBadge = aggregated?.activeAgentBadge || '主'; const activeBadgeText = formatAgentBadgeText({
const activeBadgeText = isEnglishLocale() agentKind:
? rawActiveBadge === '主' aggregated?.activeAgentKind ||
? t('fmt.mainBadge') (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main'
: rawActiveBadge ? 'main'
.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) : 'subagent'),
.replace(/^旁(\d+)$/, (_, n) => t('fmt.sideBadge', { index: n })) agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0),
: rawActiveBadge; isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main',
badgeText: aggregated?.activeAgentBadge,
});
const pillItems = [ const pillItems = [
{ {
@@ -1,7 +1,8 @@
/** /**
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
* Displays active multi-session running conversations & collapsible subagent activity * Displays active multi-session running conversations & collapsible subagent activity
* with an isolated 1s elapsed timer lifecycle. * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode
* and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`).
*/ */
import { defineComponent } from '../../core/component.js'; import { defineComponent } from '../../core/component.js';
@@ -12,23 +13,85 @@ import {
patchKeyedList, patchKeyedList,
patchText, patchText,
} from '../../core/domPatch.js'; } from '../../core/domPatch.js';
import { formatElapsedSec } from '../../core/formatters.js'; import {
formatAgentBadgeText,
formatElapsedSec,
formatLiveActivityDetail,
formatLiveActivityLabel,
getAgentBadgeClass,
} from '../../core/formatters.js';
import { createSvgIcon } from '../../icons/SvgIcon.js'; import { createSvgIcon } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js'; import { getEffectiveLocale, t } from '../../i18n/index.js';
import { import {
extractHostRouteCascadeId,
fetchTelemetry, fetchTelemetry,
formatAgentBadgeText,
getAgentBadgeClass,
resolveScopedConversation, resolveScopedConversation,
telemetryStore, telemetryStore,
} from '../../store/telemetryStore.js'; } from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js'; import { uiStore } from '../../store/uiStore.js';
export function buildFallbackRunningConversations(
data,
{ agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {}
) {
if (!data) return [];
if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) {
return data.runningConversations;
}
const activeConv = data.activeConversation || {};
if (!activeConv.isRunning && !aggregated?.isRunning) return [];
return [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
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,
...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}),
...(contextUsedPct !== undefined ? { contextUsedPct } : {}),
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
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),
customRole: s.customRole,
...(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}`,
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'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
];
}
export const LiveActivityWidget = defineComponent({ export const LiveActivityWidget = defineComponent({
name: 'LiveActivityWidget', name: 'LiveActivityWidget',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
const interactive = props.interactive !== false; const interactive = props.interactive !== false;
const preview = Boolean(props.preview); const preview = Boolean(props.preview);
const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs);
const showSessionExtras = Boolean(props.showSessionExtras);
const onSelectSession =
typeof props.onSelectSession === 'function' ? props.onSelectSession : null;
const onLayoutChange =
typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null;
const getCtxAgentId = const getCtxAgentId =
typeof props.getCtxAgentId === 'function' typeof props.getCtxAgentId === 'function'
? props.getCtxAgentId ? props.getCtxAgentId
@@ -42,10 +105,19 @@ export const LiveActivityWidget = defineComponent({
'aria-live': 'polite', 'aria-live': 'polite',
}); });
const expandedTaskConvIds = new Set(); const manualSubExpandMap = new Map();
const activityTimersMap = new Map(); const activityTimersMap = new Map();
let liveTickTimer = null; let liveTickTimer = null;
let latestData = null; let latestUpdateArgs = null;
function resolveIsExpanded(item) {
const runSubCount = Number(item?.runningSubagentCount || 0);
if (!interactive) return runSubCount > 0;
if (manualSubExpandMap.has(item.cascadeId)) {
return Boolean(manualSubExpandMap.get(item.cascadeId));
}
return defaultExpandRunningSubs ? runSubCount > 0 : false;
}
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
const now = Date.now(); const now = Date.now();
@@ -108,6 +180,20 @@ export const LiveActivityWidget = defineComponent({
className: 'live-task-title', className: 'live-task-title',
text: t('live.currentSession'), text: t('live.currentSession'),
}); });
const hereTagEl = showSessionExtras
? h('span', {
className: 'wm-session-tag is-here',
hidden: true,
text: t('multi.hereTag'),
})
: null;
const metricsEl = showSessionExtras
? h('span', {
className: 'wm-task-metrics text-mono',
hidden: true,
text: '',
})
: null;
const subToggleBtn = h('button', { const subToggleBtn = h('button', {
type: 'button', type: 'button',
className: 'live-sub-toggle', className: 'live-sub-toggle',
@@ -120,8 +206,16 @@ export const LiveActivityWidget = defineComponent({
}); });
const headerEl = h('div', { className: 'live-task-header' }, [ const headerEl = h('div', { className: 'live-task-header' }, [
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), h('div', { className: 'live-task-title-wrap' }, [
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), dotWrap,
titleEl,
...(hereTagEl ? [hereTagEl] : []),
]),
h('div', { className: 'live-task-header-right' }, [
...(metricsEl ? [metricsEl] : []),
subToggleBtn,
elapsedEl,
]),
]); ]);
const mainBadge = h('span', { const mainBadge = h('span', {
@@ -162,6 +256,8 @@ export const LiveActivityWidget = defineComponent({
cardEl, cardEl,
dotIcon, dotIcon,
titleEl, titleEl,
hereTagEl,
metricsEl,
subToggleBtn, subToggleBtn,
elapsedEl, elapsedEl,
mainBadge, mainBadge,
@@ -200,103 +296,86 @@ export const LiveActivityWidget = defineComponent({
}; };
} }
function update({ data } = {}) { function update({ data = null, items = null, hostRouteConversationId = '' } = {}) {
latestData = data || null; latestUpdateArgs = { data, items, hostRouteConversationId };
if (!data) { if (!data && !Array.isArray(items)) {
patchAttr(liveActivityBar, 'hidden', true); patchAttr(liveActivityBar, 'hidden', true);
stopLiveTicker(); stopLiveTicker();
return; return;
} }
const { agents, aggregated } = resolveScopedConversation( let rawRunningList = Array.isArray(items) ? items : null;
data, if (!rawRunningList) {
'all', const { agents, aggregated } = resolveScopedConversation(
getCtxAgentId() data,
); 'all',
getCtxAgentId()
);
rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated });
}
const rawRunningList = if (manualSubExpandMap.size > 0) {
Array.isArray(data.runningConversations) && data.runningConversations.length > 0 const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
? data.runningConversations for (const id of [...manualSubExpandMap.keys()]) {
: data.activeConversation?.isRunning || aggregated?.isRunning if (!runningIdsSet.has(id)) {
? [ manualSubExpandMap.delete(id);
{ }
cascadeId: data.activeConversation?.cascadeId || 'current', }
title: data.activeConversation?.title || t('live.currentSession'), }
isCurrentSelected: true,
isMainRunning: Boolean(data.activeConversation?.isRunning),
isRunning: true,
mainActivity:
data.activeConversation?.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, agents.length - 1),
runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length,
subagents: agents
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
isRunning: Boolean(s.isRunning),
stepCount: Number(s.stepCount || 0),
lastModifiedMs: s.lastModifiedMs || 0,
liveActivity: s.liveActivity || {
phase: s.isRunning ? 'thinking' : 'done',
label: s.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
]
: [];
const hasRunningTasks = rawRunningList.length > 0; const hasRunningTasks = rawRunningList.length > 0;
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
if (!hasRunningTasks) { if (!hasRunningTasks) {
stopLiveTicker(); stopLiveTicker();
expandedTaskConvIds.clear(); patchKeyedList(liveActivityBar, [], {});
return; return;
} }
if (!isVisibleFn()) {
pauseTicker();
return;
}
const locale = getEffectiveLocale();
const hostRouteLower = showSessionExtras
? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase()
: '';
const activeTimerKeys = new Set(); const activeTimerKeys = new Set();
for (const item of rawRunningList) { for (const item of rawRunningList) {
activeTimerKeys.add(`main:${item.cascadeId}`); activeTimerKeys.add(`main:${item.cascadeId}`);
for (const sub of item.subagents || []) { const subCount = Number(item.subagentCount || item.subagents?.length || 0);
if (sub?.isRunning) { const isExp = resolveIsExpanded(item);
activeTimerKeys.add(`sub:${sub.cascadeId}`); if (subCount > 0 && isExp) {
for (const sub of item.subagents || []) {
if (sub?.isRunning) {
activeTimerKeys.add(`sub:${sub.cascadeId}`);
}
} }
} }
} }
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
for (const id of [...expandedTaskConvIds]) {
if (!runningIdsSet.has(id)) {
expandedTaskConvIds.delete(id);
}
}
const locale = getEffectiveLocale();
patchKeyedList(liveActivityBar, rawRunningList, { patchKeyedList(liveActivityBar, rawRunningList, {
keyFn: (item) => item.cascadeId, keyFn: (item) => item.cascadeId,
sigFn: (item) => { sigFn: (item) => {
const isExp = interactive const isExp = resolveIsExpanded(item);
? expandedTaskConvIds.has(item.cascadeId) const isHere =
: Number(item.runningSubagentCount || 0) > 0; showSessionExtras &&
Boolean(hostRouteLower) &&
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
const subSig = (item.subagents || []) const subSig = (item.subagents || [])
.map( .map(
(s) => (s) =>
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
) )
.join('|'); .join('|');
return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; 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}`;
}, },
createRow: createLiveTaskCard, createRow: createLiveTaskCard,
updateRow: (refs, item) => { updateRow: (refs, item) => {
const act = item.mainActivity || { const act = item.mainActivity || {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
label: t('live.thinking'), label: t('live.thinking'),
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -315,9 +394,18 @@ export const LiveActivityWidget = defineComponent({
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
patchText(refs.titleEl, convTitle); patchText(refs.titleEl, convTitle);
if (interactive && !preview) { if (interactive && !preview) {
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); patchAttr(
refs.titleEl.onclick = () => { refs.titleEl,
if (item.cascadeId && item.cascadeId !== 'current') { 'title',
onSelectSession
? t('multi.inspectSessionTitle', { title: convTitle })
: t('live.switchSessionTitle', { title: convTitle })
);
refs.titleEl.onclick = (e) => {
e?.stopPropagation?.();
if (onSelectSession) {
onSelectSession(item.cascadeId);
} else if (item.cascadeId && item.cascadeId !== 'current') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
telemetryStore.setState({ selectedConversationId: item.cascadeId }); telemetryStore.setState({ selectedConversationId: item.cascadeId });
fetchTelemetry({ force: false }); fetchTelemetry({ force: false });
@@ -325,11 +413,32 @@ export const LiveActivityWidget = defineComponent({
}; };
} }
if (showSessionExtras && refs.hereTagEl && refs.metricsEl) {
const isHere =
Boolean(hostRouteLower) &&
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
patchText(refs.hereTagEl, t('multi.hereTag'));
patchAttr(refs.hereTagEl, 'hidden', !isHere);
const metricParts = [];
if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) {
metricParts.push(
`${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s`
);
}
if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) {
metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`);
}
const metricsStr = metricParts.join(' · ');
patchAttr(refs.metricsEl, 'hidden', !metricsStr);
if (metricsStr) {
patchText(refs.metricsEl, metricsStr);
}
}
const subCount = Number(item.subagentCount || item.subagents?.length || 0); const subCount = Number(item.subagentCount || item.subagents?.length || 0);
const runSubCount = Number(item.runningSubagentCount || 0); const runSubCount = Number(item.runningSubagentCount || 0);
const isExpanded = interactive const isExpanded = resolveIsExpanded(item);
? expandedTaskConvIds.has(item.cascadeId)
: runSubCount > 0;
patchText(refs.mainBadge, t('fmt.mainBadge')); patchText(refs.mainBadge, t('fmt.mainBadge'));
patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.mainBadge, 'hidden', subCount === 0);
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
@@ -349,39 +458,37 @@ export const LiveActivityWidget = defineComponent({
); );
refs.subToggleBtn.onclick = (e) => { refs.subToggleBtn.onclick = (e) => {
e.stopPropagation(); e.stopPropagation();
if (expandedTaskConvIds.has(item.cascadeId)) { manualSubExpandMap.set(item.cascadeId, !isExpanded);
expandedTaskConvIds.delete(item.cascadeId); if (latestUpdateArgs) update(latestUpdateArgs);
} else { onLayoutChange?.();
expandedTaskConvIds.add(item.cascadeId);
}
if (latestData) update({ data: latestData });
}; };
} }
} }
const mainLabel = formatLiveActivityLabel(act, 'live.thinking');
const detailStr = formatLiveActivityDetail(act);
const mainTimerKey = `main:${item.cascadeId}`; const mainTimerKey = `main:${item.cascadeId}`;
activeTimerKeys.add(mainTimerKey); activeTimerKeys.add(mainTimerKey);
bindLiveElapsedTimer( bindLiveElapsedTimer(
mainTimerKey, mainTimerKey,
`${item.cascadeId}:${act.signature || act.label}`, `${item.cascadeId}:${act.signature || mainLabel}`,
act.startedAtMs, act.startedAtMs,
refs.elapsedEl refs.elapsedEl
); );
patchText(refs.mainPhase, act.label || t('live.thinking')); patchText(refs.mainPhase, mainLabel);
const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
patchAttr(refs.mainProgress, 'hidden', !progText); patchAttr(refs.mainProgress, 'hidden', !progText);
if (progText) { if (progText) {
patchText(refs.mainProgress, progText); patchText(refs.mainProgress, progText);
} }
const detailStr = act.detail || '';
patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainSep, 'hidden', !detailStr);
patchAttr(refs.mainDetail, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr);
patchText(refs.mainDetail, detailStr); patchText(refs.mainDetail, detailStr);
if (interactive) { if (interactive && !showSessionExtras) {
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
patchAttr(refs.cardEl, 'title', fullTooltip); patchAttr(refs.cardEl, 'title', fullTooltip);
} }
@@ -397,6 +504,7 @@ export const LiveActivityWidget = defineComponent({
updateRow: (subRefs, sub) => { updateRow: (subRefs, sub) => {
const subAct = sub.liveActivity || { const subAct = sub.liveActivity || {
phase: sub.isRunning ? 'thinking' : 'done', phase: sub.isRunning ? 'thinking' : 'done',
actionKey: sub.isRunning ? 'thinking' : 'done',
label: sub.isRunning ? t('live.thinking') : t('live.done'), label: sub.isRunning ? t('live.thinking') : t('live.done'),
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -413,20 +521,30 @@ export const LiveActivityWidget = defineComponent({
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
patchText(subRefs.subBadge, subBadgeText); patchText(subRefs.subBadge, subBadgeText);
const roleText = sub.role || sub.shortLabel || t('fmt.subAgent'); 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}` : ''}`;
const roleText =
sub.customRole !== undefined
? sub.customRole || fallbackRole
: sub.role || sub.shortLabel || fallbackRole;
patchText(subRefs.subRole, roleText); patchText(subRefs.subRole, roleText);
const rawSubLabel = sub.isRunning const subLabel = sub.isRunning
? subAct.label || '' ? formatLiveActivityLabel(subAct, 'live.running')
: subAct.label || t('live.done'); : formatLiveActivityLabel(subAct, 'live.done');
const subDetail = formatLiveActivityDetail(subAct);
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || ''] const summaryStr = showSessionExtras
.filter(Boolean) ? sub.isRunning
.join(' '); ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}`
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
: [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' ');
patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
patchText(subRefs.subSummary, summaryStr); patchText(subRefs.subSummary, summaryStr);
if (interactive) { if (interactive && !showSessionExtras) {
patchAttr( patchAttr(
subRefs.rowEl, subRefs.rowEl,
'title', 'title',
@@ -439,8 +557,8 @@ export const LiveActivityWidget = defineComponent({
activeTimerKeys.add(subTimerKey); activeTimerKeys.add(subTimerKey);
bindLiveElapsedTimer( bindLiveElapsedTimer(
subTimerKey, subTimerKey,
`${sub.cascadeId}:${subAct.signature || subAct.label}`, `${sub.cascadeId}:${subAct.signature || subLabel}`,
subAct.startedAtMs, subAct.startedAtMs || sub.lastModifiedMs,
subRefs.subElapsed subRefs.subElapsed
); );
} else { } else {
@@ -13,7 +13,7 @@ import {
patchKeyedList, patchKeyedList,
patchText, patchText,
} from '../../core/domPatch.js'; } from '../../core/domPatch.js';
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js'; import { getEffectiveLocale, t } from '../../i18n/index.js';
import { import {
DEFAULT_STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS,
STEP_COLUMN_REGISTRY, STEP_COLUMN_REGISTRY,
@@ -25,14 +25,11 @@ import {
normalizeClientStepTokenComboFormat, normalizeClientStepTokenComboFormat,
} from '../../store/telemetryStore.js'; } from '../../store/telemetryStore.js';
export function formatTurnPromptText(rawPrompt) { export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) {
const text = String(rawPrompt || '').trim(); const text = String(rawPrompt || '').trim();
if (!text || !isEnglishLocale()) return text; if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly');
if (text === '[图片/附件提问]') return t('steps.turnMediaOnly'); if (!text) return '';
if (text.endsWith(' [附图]')) { return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text;
return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`;
}
return text;
} }
export const StepTableWidget = defineComponent({ export const StepTableWidget = defineComponent({
@@ -212,7 +209,13 @@ export const StepTableWidget = defineComponent({
const getStepIsLatest = (st) => const getStepIsLatest = (st) =>
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
const getStepPrompt = (st) => const getStepPrompt = (st) =>
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; (useRootTurn
? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt)
: (st?.turnPromptClean ?? st?.turnPrompt)) || '';
const getStepHasMedia = (st) =>
Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia);
const getStepMediaOnly = (st) =>
Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly);
const turnKeys = showStepTurnRail ? tableSteps.map((st) => { const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
const tIdx = getStepTurnIdx(st); const tIdx = getStepTurnIdx(st);
if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
@@ -221,8 +224,13 @@ export const StepTableWidget = defineComponent({
const formattedPrompts = new Map(); const formattedPrompts = new Map();
function formattedTurnPrompt(st) { function formattedTurnPrompt(st) {
const raw = getStepPrompt(st); const raw = getStepPrompt(st);
if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw)); const hasMedia = getStepHasMedia(st);
return formattedPrompts.get(raw); const mediaOnly = getStepMediaOnly(st);
const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`;
if (!formattedPrompts.has(cacheKey)) {
formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly }));
}
return formattedPrompts.get(cacheKey);
} }
const decoratedSteps = tableSteps.map((st, idx) => { const decoratedSteps = tableSteps.map((st, idx) => {
@@ -344,28 +352,38 @@ export const StepTableWidget = defineComponent({
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : '';
patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`);
const badgeText = isEnglishLocale() const badgeText = formatAgentBadgeText({
? formatAgentBadgeText({ agentKind:
isMain: !st.isSubagent, st.agentKind ||
isSideQuestion: Boolean(st.isSideQuestion), (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'),
sideIndex: st.sideIndex || 0, agentOrdinal:
index: st.agentIndex || 0, st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0),
badgeText: st.agentBadge, isMain: !st.isSubagent,
}) isSideQuestion: Boolean(st.isSideQuestion),
: st.agentBadge || (st.isSideQuestion ? '旁' : st.isSubagent ? '子' : '主'); sideIndex: st.sideIndex || 0,
index: st.agentIndex || 0,
badgeText: st.agentBadge,
});
patchText(refs.agentBadgeEl, badgeText); patchText(refs.agentBadgeEl, badgeText);
if (interactiveBadges && onSelectAgentScopes) { if (interactiveBadges && onSelectAgentScopes) {
const targetScope = st.agentId || 'main'; const targetScope = st.agentId || 'main';
const isSoleTarget = const isSoleTarget =
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
const agentName = isEnglishLocale() const agentName = formatAgentLabel({
? formatAgentLabel({ agentKind:
isMain: !st.isSubagent, st.agentKind ||
index: st.agentIndex || 0, (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'),
role: st.agentRole || '', agentOrdinal:
}) st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0),
: st.agentLabel || t('steps.unitAgent'); customRole: st.agentCustomRole,
isMain: !st.isSubagent,
isSideQuestion: Boolean(st.isSideQuestion),
sideIndex: st.sideIndex || 0,
index: st.agentIndex || 0,
role: st.agentRole || '',
shortLabel: st.agentLabel || '',
});
patchAttr( patchAttr(
refs.agentBadgeEl, refs.agentBadgeEl,
'title', 'title',
+147 -7
View File
@@ -217,23 +217,35 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
} }
const shortText = String( const shortText = String(
target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' target.activeBaseModelShort ??
target.baseModelShort ??
target.activeModelShort ??
target.modelShort ??
target.shortName ??
''
).trim(); ).trim();
const labelText = String( const labelText = String(
target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' target.activeBaseModelLabel ??
target.baseModelLabel ??
target.activeModelLabel ??
target.modelLabel ??
target.label ??
''
).trim(); ).trim();
const upstreamText = String( const upstreamText = String(
target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? '' target.baseModelUpstream ??
target.activeModelUpstream ??
target.modelUpstream ??
target.upstreamName ??
''
).trim(); ).trim();
const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`;
const responseText = String(target.responseModel ?? '').trim(); const responseText = String(target.responseModel ?? '').trim();
const modelKeyText = String(target.modelKey ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim();
const isCompaction = const isCompaction =
Boolean(target.isCompactionStep) || Boolean(target.isCompactionStep) ||
/·(?:压缩|compact)\s*$/iu.test(shortText) || /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText);
/·(?:压缩|compact)\s*$/iu.test(upstreamText) ||
/·(?:压缩|compact)\s*$/iu.test(labelText) ||
/\[自动压缩\]\s*$/u.test(labelText);
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
@@ -470,3 +482,131 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
}; };
}); });
} }
/**
* 根据代理索引返回对应的微边框语义徽章样式类名。
*
* @param {number} [index=0]
* @param {boolean} [isMain=false]
* @returns {string}
*/
export function getAgentBadgeClass(index = 0, isMain = false) {
if (isMain || index <= 0) return 'badge-main';
const slot = ((index - 1) % 3) + 1;
return `badge-sub-${slot}`;
}
/**
* 基于结构化 `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');
if (kind === 'all') return t('header.scopeAllShort');
if (kind === 'main') return t('fmt.mainBadge');
if (kind === 'side_question') {
const ord = Number(agent.agentOrdinal || agent.sideIndex || 0);
if (ord > 0) return t('fmt.sideBadge', { index: ord });
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
return t('fmt.sideBadgeShort');
}
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);
return t('fmt.subBadgeShort');
}
/**
* 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。
*
* @param {object|null|undefined} agent
* @returns {string}
*/
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');
if (kind === 'all') return t('header.scopeAll');
if (kind === 'main') return t('fmt.mainAgent');
const rawCustom =
agent.customRole !== undefined
? String(agent.customRole || '').trim()
: String(agent.role || '').trim();
if (kind === 'side_question') {
const ord = Number(agent.agentOrdinal || agent.sideIndex || 0);
const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion');
const isGeneric =
!rawCustom ||
rawCustom === baseLabel ||
rawCustom === agent.shortLabel ||
rawCustom === t('fmt.sideQuestion') ||
rawCustom === 'Side Question' ||
rawCustom === 'side_question';
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
}
const ord = Number(agent.agentOrdinal || agent.index || 0);
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
const isGeneric =
!rawCustom ||
rawCustom === baseLabel ||
rawCustom === agent.shortLabel ||
rawCustom === t('fmt.subAgent') ||
rawCustom === 'Subagent';
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
}
/**
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
*
* @param {object|null|undefined} act
* @param {string} [fallbackKey='live.thinking']
* @returns {string}
*/
export function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') {
if (!act || typeof act !== 'object') return t(fallbackKey);
let baseLabel = '';
if (act.actionKey) {
const i18nKey = `live.act.${act.actionKey}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) {
baseLabel = translated;
}
}
if (!baseLabel) {
baseLabel = String(act.label || '').trim() || t(fallbackKey);
}
if (act.waitingApproval) {
return t('live.act.awaitingApproval', { label: baseLabel });
}
return baseLabel;
}
/**
* 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。
*
* @param {object|null|undefined} act
* @returns {string}
*/
export function formatLiveActivityDetail(act) {
if (!act || typeof act !== 'object') return '';
if (act.detailKey === 'compaction_resuming') {
return t('live.act.compactionResuming');
}
return String(act.detail || '');
}
+83
View File
@@ -523,4 +523,87 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resettingBtn': 'Resetting…',
'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.resetAllDone': 'All preferences restored to defaults',
// Structured Live Activity Actions
'live.act.run_command': 'Run Command',
'live.act.read_file': 'Read File',
'live.act.edit_file': 'Edit File',
'live.act.write_file': 'Write File',
'live.act.grep_search': 'Search Code',
'live.act.find_file': 'Find Files',
'live.act.read_url': 'Read Web Page',
'live.act.search_web': 'Search Web',
'live.act.invoke_subagent': 'Invoke Subagent',
'live.act.send_message': 'Message Subagent',
'live.act.manage_subagents': 'Manage Subagents',
'live.act.manage_task': 'Manage Task',
'live.act.schedule': 'Schedule Task',
'live.act.ask_question': 'Waiting for User Choice',
'live.act.search_marketplace': 'Search Plugins',
'live.act.mcp_tool': 'Call MCP Tool',
'live.act.tool_call': 'Call Tool',
'live.act.thinking': 'Thinking',
'live.act.compacting': 'Compacting Context',
'live.act.responding': 'Responding',
'live.act.waiting_subagent': 'Waiting for Subagent',
'live.act.starting': 'Starting',
'live.act.done': 'Completed',
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
'live.act.compactionResuming': 'Compaction finished, resuming reasoning',
// SVG Charts (SessionStepCharts & TrendAreaChart)
'chart.step.empty': 'No plottable steps in current scope',
'chart.step.excluded': 'Excluded',
'chart.step.zeroSteps': '0 steps',
'chart.step.stepAdd': 'Step +{tokens}',
'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}',
'chart.step.cacheShort': 'Cache {pct}%',
'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint',
'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}',
'chart.step.ttftShort': 'TTFT {sec}s',
'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}',
'chart.step.compactionStep': 'Compaction step',
'chart.step.noSpeedSample': 'No speed sample',
'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%',
'chart.step.noTtftSample': 'No TTFT sample',
'chart.step.cumCost': 'Total {cost}',
'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}',
'chart.step.noSamples': 'No samples',
'chart.step.peakShort': 'Peak {val}',
'chart.step.peakPill': 'Peak {tag} · {val}',
'chart.step.stepsCount': '{count} steps',
'chart.step.multiPrefix': '{count} models · ',
'chart.step.sumTokens': '{prefix}Total {tokens}',
'chart.step.peakTokens': '{prefix}Peak {tokens}',
'chart.step.currentCtx': 'Current {tokens}',
'chart.step.meanTps': '{prefix}Avg {val} tok/s',
'chart.step.meanSec': '{prefix}Avg {val}s',
'chart.step.noValidSamples': 'No valid samples',
'chart.step.sumCost': '{prefix}Total {cost}',
'chart.fit.empty': 'No valid regression samples for this model',
'chart.fit.loess': 'LOESS Fit',
'chart.fit.olsLinear': 'OLS Linear',
'chart.fit.olsReg': 'OLS Reg',
'chart.fit.observed': 'Observed',
'chart.fit.tipFit': 'Fit {val}',
'chart.fit.tipObs': 'Obs {val}',
'chart.fit.zeroSamples': '0 samples',
'chart.fit.peerMean': '{label} Avg {val}',
'chart.fit.peerCompare': 'Compare: {peers}',
'chart.fit.curvesCount': '{count} fit curves',
'chart.fit.multiBadge': '{steps} steps · {models} models',
'chart.fit.singleBadge': '{steps} steps · Avg {mean}',
'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}',
'chart.trend.hmMonthYear': "{month}/{yy}",
'chart.trend.hmMonthOnly': 'M{month}',
'chart.trend.wdayMon': 'M',
'chart.trend.wdayWed': 'W',
'chart.trend.wdayFri': 'F',
'chart.trend.wdaySun': 'S',
'chart.trend.hmAria': 'Daily usage heatmap',
'chart.trend.hmLess': 'Less',
'chart.trend.hmMore': 'More',
'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}',
'chart.trend.hmActiveZero': 'Active 0/{total}d',
'chart.trend.peakPill': 'Peak {label} · {tokens}',
}); });
+83
View File
@@ -523,4 +523,87 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resetConfirmBtn': '再次点击确认重置',
'settings.oth.resettingBtn': '重置中…', 'settings.oth.resettingBtn': '重置中…',
'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.resetAllDone': '已恢复全部默认设置',
// Structured Live Activity Actions
'live.act.run_command': '执行命令',
'live.act.read_file': '读取文件',
'live.act.edit_file': '修改文件',
'live.act.write_file': '写入文件',
'live.act.grep_search': '搜索代码',
'live.act.find_file': '查找文件',
'live.act.read_url': '读取网页',
'live.act.search_web': '网页搜索',
'live.act.invoke_subagent': '调用子代理',
'live.act.send_message': '通信子代理',
'live.act.manage_subagents': '管理子代理',
'live.act.manage_task': '后台任务',
'live.act.schedule': '定时任务',
'live.act.ask_question': '等待用户选择',
'live.act.search_marketplace': '查询插件',
'live.act.mcp_tool': '调用 MCP',
'live.act.tool_call': '调用工具',
'live.act.thinking': '推理中',
'live.act.compacting': '上下文压缩',
'live.act.responding': '正在输出回复',
'live.act.waiting_subagent': '等待子代理',
'live.act.starting': '启动中',
'live.act.done': '已完成',
'live.act.awaitingApproval': '等待确认 · {label}',
'live.act.compactionResuming': '已完成压缩,正在恢复推理',
// SVG Charts (SessionStepCharts & TrendAreaChart)
'chart.step.empty': '当前范围暂无可绘制的调用步骤',
'chart.step.excluded': '未纳入',
'chart.step.zeroSteps': '0 步',
'chart.step.stepAdd': '本步 +{tokens}',
'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}',
'chart.step.cacheShort': '缓存 {pct}%',
'chart.step.compactionCheckpoint': '上下文自动压缩检查点',
'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}',
'chart.step.ttftShort': '首字 {sec}s',
'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}',
'chart.step.compactionStep': '上下文压缩步',
'chart.step.noSpeedSample': '无测速样本',
'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%',
'chart.step.noTtftSample': '无首字计时样本',
'chart.step.cumCost': '累计 {cost}',
'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}',
'chart.step.noSamples': '无样本',
'chart.step.peakShort': '峰 {val}',
'chart.step.peakPill': '峰值 {tag} · {val}',
'chart.step.stepsCount': '{count}步',
'chart.step.multiPrefix': '{count} 模型 · ',
'chart.step.sumTokens': '{prefix}累计 {tokens}',
'chart.step.peakTokens': '{prefix}峰值 {tokens}',
'chart.step.currentCtx': '当前 {tokens}',
'chart.step.meanTps': '{prefix}均值 {val} tok/s',
'chart.step.meanSec': '{prefix}均值 {val}s',
'chart.step.noValidSamples': '暂无有效样本',
'chart.step.sumCost': '{prefix}累计 {cost}',
'chart.fit.empty': '该模型暂无有效拟合样本',
'chart.fit.loess': 'LOESS 拟合',
'chart.fit.olsLinear': 'OLS 线性',
'chart.fit.olsReg': 'OLS 回归',
'chart.fit.observed': '观测值',
'chart.fit.tipFit': '拟合 {val}',
'chart.fit.tipObs': '观测 {val}',
'chart.fit.zeroSamples': '0 样本',
'chart.fit.peerMean': '{label} 均 {val}',
'chart.fit.peerCompare': '同图对比:{peers}',
'chart.fit.curvesCount': '{count} 条拟合线',
'chart.fit.multiBadge': '{steps}步 · {models} 模型对比',
'chart.fit.singleBadge': '{steps}步 · 均 {mean}',
'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}',
'chart.trend.hmMonthYear': '{yy}年{month}月',
'chart.trend.hmMonthOnly': '{month}月',
'chart.trend.wdayMon': '一',
'chart.trend.wdayWed': '三',
'chart.trend.wdayFri': '五',
'chart.trend.wdaySun': '日',
'chart.trend.hmAria': '每日用量热力格子图',
'chart.trend.hmLess': '少',
'chart.trend.hmMore': '多',
'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}',
'chart.trend.hmActiveZero': '活跃 0/{total} 天',
'chart.trend.peakPill': '峰值 {label} · {tokens}',
}); });
+12 -10
View File
@@ -6,6 +6,7 @@
*/ */
import { import {
formatAgentBadgeText,
formatCachePct, formatCachePct,
formatMetric, formatMetric,
formatTokens, formatTokens,
@@ -345,15 +346,16 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
}; };
} }
function translateRawAgentBadge(rawBadge) { function resolveActiveBadgeText(active) {
if (!rawBadge) return ''; if (!active?.activeAgentBadge && !active?.activeAgentKind) return '';
if (!isEnglishLocale()) return String(rawBadge); return formatAgentBadgeText({
const str = String(rawBadge).trim(); agentKind:
if (str === '主') return t('fmt.mainBadge'); active.activeAgentKind ||
const m = str.match(/^子(\d+)$/); (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'),
if (m) return t('fmt.subBadge', { index: m[1] }); agentOrdinal: Number(active.activeAgentOrdinal || 0),
if (str === '子') return t('fmt.subBadgeShort'); isMain: !active.activeAgentId || active.activeAgentId === 'main',
return str; badgeText: active.activeAgentBadge,
});
} }
/** /**
@@ -375,7 +377,7 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
fallback: t('fmt.unknownModel'), fallback: t('fmt.unknownModel'),
}).text; }).text;
const reason = speedReasonText(active.latestSpeedReason); const reason = speedReasonText(active.latestSpeedReason);
const badgeStr = translateRawAgentBadge(active.activeAgentBadge); const badgeStr = resolveActiveBadgeText(active);
const modelAndAgent = const modelAndAgent =
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0;
+15 -96
View File
@@ -5,7 +5,14 @@
import { createReactiveStore } from '../core/reactive.js'; import { createReactiveStore } from '../core/reactive.js';
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js'; import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js'; import {
formatAgentBadgeText,
formatAgentLabel,
formatLiveActivityDetail,
formatLiveActivityLabel,
getAgentBadgeClass,
} from '../core/formatters.js';
import { normalizeI18nLanguage, t } from '../i18n/index.js';
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
import { import {
DEFAULT_HOVER_MODULES, DEFAULT_HOVER_MODULES,
@@ -1053,101 +1060,13 @@ export function stopAsyncTelemetryLoop() {
} }
} }
/** export {
* 根据代理索引返回对应的微边框语义徽章样式类名。 formatAgentBadgeText,
* formatAgentLabel,
* @param {number} [index=0] formatLiveActivityDetail,
* @param {boolean} [isMain=false] formatLiveActivityLabel,
* @returns {string} getAgentBadgeClass,
*/ };
export function getAgentBadgeClass(index = 0, isMain = false) {
if (isMain || index <= 0) return 'badge-main';
const slot = ((index - 1) % 3) + 1;
return `badge-sub-${slot}`;
}
/**
* 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。
*
* @param {object|null|undefined} agent
* @returns {string}
*/
export function formatAgentBadgeText(agent) {
const isSideQ = Boolean(
agent?.isSideQuestion ||
agent?.typeName === 'side_question' ||
/^旁\d*$/.test(String(agent?.badgeText || ''))
);
if (!isEnglishLocale()) {
if (!agent || agent.isMain) return agent?.badgeText || '主';
if (isSideQ) {
const sIdx = Number(agent.sideIndex || 0);
return agent.badgeText || (sIdx > 0 ? `旁${sIdx}` : '旁');
}
return agent.badgeText || `子${agent.index || ''}`;
}
if (!agent || agent.isMain) return t('fmt.mainBadge');
if (isSideQ) {
const m = String(agent.badgeText || '').match(/^旁(\d+)$/);
const sIdx = Number(agent.sideIndex || (m ? m[1] : 0));
return sIdx > 0 ? t('fmt.sideBadge', { index: sIdx }) : t('fmt.sideBadgeShort');
}
const subMatch = String(agent.badgeText || '').match(/^子(\d+)$/);
const subOrd = Number(subMatch ? subMatch[1] : agent.index || 0);
return subOrd > 0 ? t('fmt.subBadge', { index: subOrd }) : t('fmt.subBadgeShort');
}
/**
* 格式化主/子代理或旁路提问的完整显示名称(如 `子代理 #1 · Codebase Researcher` / `旁路提问 #1 · ...`)。
*
* @param {object|null|undefined} agent
* @returns {string}
*/
export function formatAgentLabel(agent) {
const isSideQ = Boolean(
agent?.isSideQuestion ||
agent?.typeName === 'side_question' ||
/^旁/.test(String(agent?.badgeText || agent?.shortLabel || ''))
);
if (!isEnglishLocale()) {
if (!agent) return '主代理';
if (agent.isMain) return agent.shortLabel || '主代理';
if (isSideQ) {
const sIdx = Number(agent.sideIndex || 0);
const fallbackShort = sIdx > 0 ? `旁路提问 #${sIdx}` : '旁路提问';
const rolePart =
agent.role &&
agent.role !== '旁路提问' &&
agent.role !== 'Side Question' &&
agent.role !== agent.shortLabel
? ` · ${agent.role}`
: '';
return `${agent.shortLabel || fallbackShort}${rolePart}`;
}
const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : '';
return `${agent.shortLabel || '子代理'}${rolePart}`;
}
if (!agent || agent.isMain) return t('fmt.mainAgent');
if (isSideQ) {
const m = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/);
const sIdx = Number(agent.sideIndex || (m ? m[1] : 0));
const baseLabel = sIdx > 0 ? `${t('fmt.sideQuestion')} #${sIdx}` : t('fmt.sideQuestion');
const rolePart =
agent.role &&
agent.role !== '旁路提问' &&
agent.role !== 'Side Question' &&
agent.role !== agent.shortLabel
? ` · ${agent.role}`
: '';
return `${baseLabel}${rolePart}`;
}
const subMatch = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/);
const idx = Number(subMatch ? subMatch[1] : agent.index || 0);
const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent');
const rolePart =
agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : '';
return `${baseLabel}${rolePart}`;
}
/** /**
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
+16 -13
View File
@@ -435,17 +435,20 @@ export const StepsDetailView = defineComponent({
let isDirty = false; let isDirty = false;
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
const activeCand = getStepModelGroupKey({ if (scopedConv?.hasKnownModel !== false) {
modelLabel: scopedConv?.activeModelLabel, const activeCand = getStepModelGroupKey({
modelShort: scopedConv?.activeModelShort, baseModelLabel: scopedConv?.activeBaseModelLabel,
}); baseModelShort: scopedConv?.activeBaseModelShort,
if ( modelLabel: scopedConv?.activeModelLabel,
activeCand && modelShort: scopedConv?.activeModelShort,
activeCand !== '模型未知' && });
activeCand !== t('fmt.unknownModel') && if (
availableModelKeys.has(activeCand) activeCand &&
) { activeCand !== t('fmt.unknownModel') &&
return activeCand; availableModelKeys.has(activeCand)
) {
return activeCand;
}
} }
for (let i = chronoSteps.length - 1; i >= 0; i--) { for (let i = chronoSteps.length - 1; i >= 0; i--) {
const st = chronoSteps[i]; const st = chronoSteps[i];
@@ -625,7 +628,7 @@ export const StepsDetailView = defineComponent({
if (!stepModelOptionMap.has(gk)) { if (!stepModelOptionMap.has(gk)) {
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
stepModelOptionMap.set(gk, { stepModelOptionMap.set(gk, {
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, label: disp.baseText || disp.text || gk,
calls: 0, calls: 0,
}); });
} }
@@ -656,7 +659,7 @@ export const StepsDetailView = defineComponent({
}); });
perModelOptions.push({ perModelOptions.push({
value: gk, value: gk,
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, label: disp.baseText || disp.text || gk,
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
}); });
} }
+2
View File
@@ -26,6 +26,8 @@ const BACKEND_MODULE_FILES = [
'../backend/http-helpers.mjs', '../backend/http-helpers.mjs',
'../backend/settings-schema.mjs', '../backend/settings-schema.mjs',
'../backend/config.mjs', '../backend/config.mjs',
'../backend/sqlite-client.mjs',
'../backend/proto-wire.mjs',
'../backend/cli-sqlite-reader.mjs', '../backend/cli-sqlite-reader.mjs',
'../backend/cli-statusline-config.mjs', '../backend/cli-statusline-config.mjs',
'../backend/ls-discovery.mjs', '../backend/ls-discovery.mjs',
@@ -1183,3 +1183,195 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(appJs.includes('SettingsAccountTab.js'), false); assert.equal(appJs.includes('SettingsAccountTab.js'), false);
assert.equal(appJs.includes('function renderQuotaRows('), false); assert.equal(appJs.includes('function renderQuotaRows('), false);
}); });
test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => {
// 1. Standalone sqlite-client & proto-wire primitives (zero config/metrics imports)
const sqliteClientSrc = fs.readFileSync(
new URL('../backend/sqlite-client.mjs', import.meta.url),
'utf8'
);
const protoWireSrc = fs.readFileSync(
new URL('../backend/proto-wire.mjs', import.meta.url),
'utf8'
);
assert.doesNotMatch(sqliteClientSrc, /config\.mjs|trajectory-metrics\.mjs/);
assert.doesNotMatch(protoWireSrc, /config\.mjs|trajectory-metrics\.mjs/);
const protoWire = await import('../backend/proto-wire.mjs');
assert.equal(protoWire.unescapePbtxtString('\\344\\275\\240\\345\\245\\275'), '你好');
const varState = { off: 0 };
assert.equal(protoWire.readProtoVarint(new Uint8Array([0xac, 0x02]), varState), 300n);
// 2. Bilingual dictionary 100% key parity
const { I18N_MESSAGES_ZH_CN } = await import('../src/i18n/zh-CN.js');
const { I18N_MESSAGES_EN_US } = await import('../src/i18n/en-US.js');
const zhKeys = Object.keys(I18N_MESSAGES_ZH_CN).sort();
const enKeys = Object.keys(I18N_MESSAGES_EN_US).sort();
assert.deepEqual(enKeys, zhKeys);
// 3. Structured liveActivity, agent badges/labels, turn media, and en-US SVG charts (zero Chinese leakage)
const { createMockDom } = await import('./mock-dom.mjs');
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const { document: mockDoc } = createMockDom();
globalThis.document = mockDoc;
globalThis.window = {
innerWidth: 1280,
innerHeight: 800,
devicePixelRatio: 1,
document: mockDoc,
addEventListener() {},
removeEventListener() {},
getComputedStyle: () => ({ getPropertyValue: () => '' }),
};
try {
const { setI18nLanguage } = await import('../src/i18n/index.js');
const {
formatAgentBadgeText,
formatAgentLabel,
formatLiveActivityDetail,
formatLiveActivityLabel,
} = await import('../src/core/formatters.js');
const { formatTurnPromptText } = await import('../src/components/widgets/StepTableWidget.js');
const { LiveActivityWidget } = await import('../src/components/widgets/LiveActivityWidget.js');
const { buildCapsuleSlotContext } = await import('../src/components/widgets/CapsuleBarWidget.js');
const { createModelFitChart, createSessionLineChart } = await import(
'../src/components/charts/SessionStepCharts.js'
);
const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js');
const waitCmdAct = extractLiveActivity(
[
{
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE',
plannerResponse: {
toolCalls: [{ name: 'run_command', argumentsJson: '{"CommandLine":"npm test"}' }],
},
},
{ type: 'CORTEX_STEP_TYPE_RUN_COMMAND', status: 'CORTEX_STEP_STATUS_WAITING' },
],
true
);
assert.equal(waitCmdAct?.actionKey, 'run_command');
assert.equal(waitCmdAct?.waitingApproval, true);
setI18nLanguage('en-US');
assert.equal(formatLiveActivityLabel(waitCmdAct), 'Awaiting Approval · Run Command');
assert.equal(
formatLiveActivityDetail({ detailKey: 'compaction_resuming' }),
'Compaction finished, resuming reasoning'
);
assert.equal(
formatAgentBadgeText({ agentKind: 'side_question', agentOrdinal: 2 }),
'Q2'
);
assert.equal(
formatAgentLabel({ agentKind: 'subagent', agentOrdinal: 1, customRole: 'Auditor' }),
'Subagent #1 · Auditor'
);
assert.equal(
formatTurnPromptText('Check image', { hasMedia: true, mediaOnly: false }),
'Check image [Media]'
);
assert.equal(formatTurnPromptText('', { hasMedia: true, mediaOnly: true }), '[Media Attachment]');
// Controlled LiveActivityWidget auto-expands running subagents and renders session extras
let selectedCid = '';
const controlledLive = LiveActivityWidget({
defaultExpandRunningSubs: true,
showSessionExtras: true,
onSelectSession: (cid) => {
selectedCid = cid;
},
});
controlledLive.refs.update({
hostRouteConversationId: 'conv-en-ctrl',
items: [
{
cascadeId: 'conv-en-ctrl',
title: 'Controlled Multi Panel',
isMainRunning: true,
isRunning: true,
latestTokPerSec: 82.4,
contextUsedPct: 44,
mainActivity: waitCmdAct,
subagentCount: 1,
runningSubagentCount: 1,
subagents: [
{
cascadeId: 'sub-ctrl-1',
index: 1,
agentKind: 'subagent',
agentOrdinal: 1,
customRole: 'Verifier',
isRunning: true,
stepCount: 2,
liveActivity: {
phase: 'compacting',
actionKey: 'compacting',
detailKey: 'compaction_resuming',
signature: 'cp:1',
},
},
],
},
],
});
assert.equal(controlledLive.el.querySelector('.live-sub-list').hasAttribute('hidden'), false);
assert.equal(controlledLive.el.querySelector('.wm-session-tag.is-here').hasAttribute('hidden'), false);
assert.equal(controlledLive.el.querySelector('.wm-task-metrics').textContent, '82.4 t/s · 44%');
assert.equal(/[\u4e00-\u9fff]/.test(controlledLive.el.textContent), false);
controlledLive.el.querySelector('.live-task-title').onclick({});
assert.equal(selectedCid, 'conv-en-ctrl');
controlledLive.refs.stopLiveTicker();
// SVG charts in en-US emit zero Chinese characters
const sampleSteps = Array.from({ length: 6 }, (_, i) => ({
stepIndex: i + 1,
baseModelLabel: 'Gemini 4 Carbon',
baseModelShort: 'carbon-4',
tokPerSec: 70 + i * 4,
ttftSec: 1.1,
cacheHitPct: 88,
inputTokens: 1000,
cacheReadTokens: 8000,
outputTokens: 300,
contextTokens: 12000,
costUsd: 0.01,
}));
const lineChart = createSessionLineChart();
const lineRes = lineChart.update({ steps: sampleSteps, metric: 'tps' });
assert.equal(/[\u4e00-\u9fff]/.test(lineRes.summaryBadge), false);
assert.equal(/[\u4e00-\u9fff]/.test(lineChart.el.textContent), false);
lineChart.destroy();
const fitChart = createModelFitChart();
const fitRes = fitChart.update({ steps: sampleSteps, metric: 'tps' });
assert.equal(/[\u4e00-\u9fff]/.test(fitRes.summaryBadge), false);
assert.equal(/[\u4e00-\u9fff]/.test(fitChart.el.textContent), false);
fitChart.destroy();
const trendChart = createTrendAreaChart();
const hmSlots = Array.from({ length: 95 }, (_, i) => {
const iso = new Date(Date.UTC(2026, 6, 1 + i)).toISOString().slice(0, 10);
return { dateKey: iso, label: iso.slice(5), fullLabel: iso, tokens: (i + 1) * 500, calls: 2, costUsd: 0.02 };
});
trendChart.update(hmSlots);
assert.equal(/[\u4e00-\u9fff]/.test(trendChart.el.textContent), false);
trendChart.destroy();
const slotCtx = buildCapsuleSlotContext(
{ activeConversation: { isRunning: true, stepCount: 2, latestTokPerSec: 64.5, context: { totalTokens: 64000, limitTokens: 256000 } } },
{}
);
assert.equal(slotCtx.usedPct, 25);
assert.equal(slotCtx.tps, 64.5);
setI18nLanguage('zh-CN');
} finally {
globalThis.document = prevDoc;
globalThis.window = prevWin;
}
});
+548
View File
@@ -0,0 +1,548 @@
/**
* @fileoverview Shared lightweight W3C-compatible Mock DOM for Node `vm` UI & overlay tests.
* Replaces 6 separate copy-pasted inline mock DOM classes across `window-bridge.test.mjs`.
*/
const ATTR_TOKEN_RE = /\[\s*([a-zA-Z0-9_:-]+)\s*(?:([*^$~|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]]*)))?\s*\]/g;
function matchCompoundSelector(node, rawCompound) {
if (!node || !node.tagName || String(node.tagName).startsWith('#')) return false;
let rem = String(rawCompound || '').trim();
if (!rem) return false;
if (rem === '*') return true;
// Match attribute clauses `[attr]`, `[attr="v"]`, `[attr^="v"]`, `[attr*="v"]`, `[attr$="v"]`
const attrs = [];
rem = rem.replace(ATTR_TOKEN_RE, (_m, name, op, dq, sq, bare) => {
attrs.push({ name, op: op || '', val: dq ?? sq ?? (bare ? bare.trim() : '') });
return '';
});
for (const a of attrs) {
if (!a.op) {
if (!node.hasAttribute(a.name)) return false;
continue;
}
const actual = node.getAttribute(a.name);
if (actual === null || actual === undefined) return false;
const str = String(actual);
if (a.op === '=' && str !== a.val) return false;
if (a.op === '^=' && !str.startsWith(a.val)) return false;
if (a.op === '*=' && !str.includes(a.val)) return false;
if (a.op === '$=' && !str.endsWith(a.val)) return false;
if (a.op === '~=' && !str.split(/\s+/).includes(a.val)) return false;
}
// Extract `#id` and `.class` tokens
let idReq = '';
const classReqs = [];
rem = rem.replace(/#([a-zA-Z0-9_-]+)/g, (_m, id) => {
idReq = id;
return '';
});
rem = rem.replace(/\.([a-zA-Z0-9_@/-]+)/g, (_m, cls) => {
classReqs.push(cls);
return '';
});
if (idReq && node.id !== idReq) return false;
for (const cls of classReqs) {
if (!node.classList.contains(cls)) return false;
}
const tag = rem.trim();
if (tag && node.tagName.toLowerCase() !== tag.toLowerCase()) return false;
return true;
}
function splitTopLevelCommas(selector) {
const out = [];
let depth = 0;
let quote = '';
let start = 0;
const s = String(selector || '');
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (quote) {
if (ch === quote && s[i - 1] !== '\\') quote = '';
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
} else if (ch === '[') {
depth++;
} else if (ch === ']') {
depth = Math.max(0, depth - 1);
} else if (ch === ',' && depth === 0) {
const part = s.slice(start, i).trim();
if (part) out.push(part);
start = i + 1;
}
}
const tail = s.slice(start).trim();
if (tail) out.push(tail);
return out;
}
function tokenizeCombinators(singleSelector) {
const tokens = [];
let depth = 0;
let quote = '';
let buf = '';
let pendingDirect = false;
const s = String(singleSelector || '').trim();
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (quote) {
buf += ch;
if (ch === quote && s[i - 1] !== '\\') quote = '';
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
buf += ch;
continue;
}
if (ch === '[') {
depth++;
buf += ch;
continue;
}
if (ch === ']') {
depth = Math.max(0, depth - 1);
buf += ch;
continue;
}
if (depth === 0 && (ch === '>' || /\s/.test(ch))) {
if (buf) {
tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' });
buf = '';
pendingDirect = false;
}
if (ch === '>') pendingDirect = true;
continue;
}
buf += ch;
}
if (buf) {
tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' });
}
return tokens;
}
function matchChainFromScope(node, scopeRoot, tokens, idx) {
const step = tokens[idx];
if (step.compound === ':scope') {
return node === scopeRoot;
}
if (!matchCompoundSelector(node, step.compound)) return false;
if (idx === 0) return true;
if (step.combinator === '>') {
const p = node.parentNode;
if (!p) return false;
return matchChainFromScope(p, scopeRoot, tokens, idx - 1);
}
let p = node.parentNode;
while (p) {
if (matchChainFromScope(p, scopeRoot, tokens, idx - 1)) return true;
if (p === scopeRoot) break;
p = p.parentNode;
}
return false;
}
export class MockMutationObserver {
constructor(cb, registry = null) {
this.cb = cb;
this.targets = [];
if (Array.isArray(registry)) registry.push(this);
}
observe(target, options) {
this.targets.push({ target, options });
}
disconnect() {
this.targets = [];
}
}
export class MockDomNode {
constructor(tag = 'div', rect = null, domOptions = null) {
this._domOptions = domOptions || null;
this.tagName = String(tag || 'div').toUpperCase();
this.nodeName = this.tagName;
this.nodeType = this.tagName === '#TEXT' ? 3 : 1;
this.id = '';
this.value = '';
this._text = '';
this._rect = null;
this._ownRect = rect || null;
this.offsetWidth = 0;
this.offsetHeight = 0;
this.clientWidth = 0;
this.scrollWidth = 0;
this.dataset = {};
this.attributes = new Map();
this._classes = new Set();
this.children = [];
this.parentNode = null;
this.shadowRoot = null;
this._listeners = new Map();
const styleVars = new Map();
this.style = {
width: '',
height: '',
maxHeight: '',
marginLeft: '',
top: '',
left: '',
right: '',
display: '',
visibility: '',
opacity: '',
_vars: styleVars,
setProperty(k, v) {
const s = String(v ?? '');
styleVars.set(k, s);
this[k] = s;
},
getPropertyValue(k) {
return styleVars.get(k) || this[k] || '';
},
removeProperty(k) {
styleVars.delete(k);
delete this[k];
},
};
const self = this;
this.classList = {
add(...tokens) {
for (const t of tokens) if (t) self._classes.add(t);
self._syncClassAttr();
},
remove(...tokens) {
for (const t of tokens) self._classes.delete(t);
self._syncClassAttr();
},
contains(tok) {
return self._classes.has(tok);
},
toggle(tok, force) {
const should = force === undefined ? !self._classes.has(tok) : Boolean(force);
if (should) self._classes.add(tok);
else self._classes.delete(tok);
self._syncClassAttr();
return should;
},
};
}
_syncClassAttr() {
const joined = [...this._classes].join(' ');
if (joined) this.attributes.set('class', joined);
else this.attributes.delete('class');
}
get className() {
return [...this._classes].join(' ');
}
set className(v) {
this._classes.clear();
for (const part of String(v || '').split(/\s+/)) {
if (part) this._classes.add(part);
}
this._syncClassAttr();
}
get textContent() {
if (this.children.length === 0) return this._text;
return this._text + this.children.map((c) => c.textContent ?? '').join('');
}
set textContent(v) {
for (const c of this.children) {
if (c) c.parentNode = null;
}
this.children = [];
this._text = String(v ?? '');
}
get parentElement() {
return this.parentNode;
}
set parentElement(v) {
this.parentNode = v;
}
get firstChild() {
return this.children[0] || null;
}
get lastChild() {
return this.children[this.children.length - 1] || null;
}
get firstElementChild() {
return this.children[0] || null;
}
get lastElementChild() {
return this.children[this.children.length - 1] || null;
}
get nextSibling() {
if (!this.parentNode) return null;
const idx = this.parentNode.children.indexOf(this);
return idx >= 0 ? this.parentNode.children[idx + 1] || null : null;
}
get nextElementSibling() {
return this.nextSibling;
}
get isConnected() {
let cur = this;
while (cur) {
if (cur.isDocumentRoot) return true;
cur = cur.parentNode || cur.host || null;
}
return false;
}
setAttribute(k, v) {
const s = String(v);
if (k === 'class') {
this.className = s;
return;
}
this.attributes.set(k, s);
if (k === 'id') this.id = s;
}
getAttribute(k) {
if (k === 'class') return this.attributes.has('class') ? this.className : null;
return this.attributes.has(k) ? this.attributes.get(k) : null;
}
hasAttribute(k) {
return this.attributes.has(k);
}
removeAttribute(k) {
if (k === 'class') {
this._classes.clear();
}
this.attributes.delete(k);
}
appendChild(child) {
if (!child) return child;
if (child.parentNode?.removeChild) child.parentNode.removeChild(child);
child.parentNode = this;
this.children.push(child);
return child;
}
insertBefore(node, refNode) {
if (!refNode) return this.appendChild(node);
if (node.parentNode?.removeChild) node.parentNode.removeChild(node);
const idx = this.children.indexOf(refNode);
node.parentNode = this;
if (idx < 0) this.children.push(node);
else this.children.splice(idx, 0, node);
return node;
}
removeChild(child) {
const idx = this.children.indexOf(child);
if (idx >= 0) {
this.children.splice(idx, 1);
child.parentNode = null;
}
return child;
}
remove() {
if (this.parentNode?.removeChild) this.parentNode.removeChild(this);
}
attachShadow() {
const sr = new MockDomNode('#shadow-root', null, this._domOptions);
sr.host = this;
this.shadowRoot = sr;
return sr;
}
contains(other) {
let cur = other;
while (cur) {
if (cur === this) return true;
cur = cur.parentNode;
}
return false;
}
closest(sel) {
let cur = this;
while (cur && cur.nodeType === 1) {
if (cur.matches(sel)) return cur;
cur = cur.parentNode;
}
return null;
}
addEventListener(type, fn) {
if (!this._listeners.has(type)) this._listeners.set(type, []);
this._listeners.get(type).push(fn);
}
removeEventListener(type, fn) {
const arr = this._listeners.get(type);
if (!arr) return;
const idx = arr.indexOf(fn);
if (idx >= 0) arr.splice(idx, 1);
}
dispatchEvent(ev) {
for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev);
}
setRect(rect) {
this._ownRect = rect;
}
getBoundingClientRect() {
if (typeof this._domOptions?.resolveRect === 'function') {
const custom = this._domOptions.resolveRect(this);
if (custom) return custom;
}
if (this._ownRect) return this._ownRect;
if (this._rect) return this._rect;
if (this._domOptions?.inheritAncestorRect) {
let cur = this.parentNode || this.host || null;
while (cur) {
if (cur._ownRect) return cur._ownRect;
if (cur._rect) return cur._rect;
cur = cur.parentNode || cur.host || null;
}
}
return (
this._domOptions?.defaultRect || {
left: 900,
right: 1080,
top: 6,
bottom: 32,
width: 180,
height: 26,
}
);
}
matches(selector) {
const groups = splitTopLevelCommas(selector);
if (groups.length === 0) return false;
return groups.some((g) => {
const tokens = tokenizeCombinators(g);
if (tokens.length === 0) return false;
return matchChainFromScope(this, null, tokens, tokens.length - 1);
});
}
querySelectorAll(selector) {
const groups = splitTopLevelCommas(selector);
if (groups.length === 0) return [];
const parsedGroups = groups.map(tokenizeCombinators).filter((t) => t.length > 0);
if (parsedGroups.length === 0) return [];
const out = [];
const walk = (root) => {
for (const child of root.children || []) {
if (
parsedGroups.some((tokens) =>
matchChainFromScope(child, this, tokens, tokens.length - 1)
)
) {
out.push(child);
}
walk(child);
}
};
walk(this);
return out;
}
querySelector(selector) {
return this.querySelectorAll(selector)[0] || null;
}
_find(pred) {
for (const c of this.children) {
if (pred(c)) return c;
const hit = c._find?.(pred);
if (hit) return hit;
}
return null;
}
}
export function createMockDom({
rootRect = null,
defaultRect = null,
inheritAncestorRect = false,
resolveRect = null,
onCreateElement = null,
} = {}) {
const domOptions = { defaultRect, inheritAncestorRect, resolveRect };
const makeElement = (tag, rect = null) => {
const node = new MockDomNode(tag, rect, domOptions);
if (typeof onCreateElement === 'function') onCreateElement(node, tag);
return node;
};
const docRoot = makeElement('html', rootRect);
docRoot.isDocumentRoot = true;
const head = makeElement('head');
const body = makeElement('body', rootRect);
docRoot.appendChild(head);
docRoot.appendChild(body);
const docListeners = new Map();
const document = {
readyState: 'complete',
hidden: false,
activeElement: null,
documentElement: docRoot,
head,
body,
createElement: (tag) => makeElement(tag),
createElementNS: (_ns, tag) => makeElement(tag),
createTextNode: (txt) => {
const t = new MockDomNode('#text', null, domOptions);
t.textContent = String(txt ?? '');
return t;
},
getElementById: (id) => docRoot._find((n) => n.id === id),
querySelector: (sel) => docRoot.querySelector(sel),
querySelectorAll: (sel) => docRoot.querySelectorAll(sel),
addEventListener(type, fn) {
if (!docListeners.has(type)) docListeners.set(type, []);
docListeners.get(type).push(fn);
},
removeEventListener(type, fn) {
const arr = docListeners.get(type);
if (!arr) return;
const idx = arr.indexOf(fn);
if (idx >= 0) arr.splice(idx, 1);
},
dispatchEvent(ev) {
for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev);
},
};
return { docRoot, head, body, document, docListeners, makeElement };
}
File diff suppressed because it is too large Load Diff
+108 -20
View File
@@ -667,6 +667,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
let turnCounter = 0; let turnCounter = 0;
let activeTurnIndex = null; let activeTurnIndex = null;
let pendingTurnPrompts = []; let pendingTurnPrompts = [];
let pendingTurnHasMedia = false;
let hasUnconsumedTurn = false; let hasUnconsumedTurn = false;
const isUserTurnBoundary = (step) => { const isUserTurnBoundary = (step) => {
@@ -678,7 +679,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
return Boolean(step.userInput && typeof step.userInput === 'object'); return Boolean(step.userInput && typeof step.userInput === 'object');
}; };
const extractUserTurnPrompt = (step) => { const extractUserTurnInfo = (step) => {
const ui = step?.userInput; const ui = step?.userInput;
let raw = ''; let raw = '';
if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) { if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) {
@@ -709,24 +710,35 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
? step.media ? step.media
: []; : [];
const hasMedia = mediaArr.length > 0; const hasMedia = mediaArr.length > 0;
if (!cleaned) { const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned;
return hasMedia ? '[图片/附件提问]' : ''; const legacyRaw = !cleaned ? (hasMedia ? '[图片/附件提问]' : '') : hasMedia ? `${cleaned} [附图]` : cleaned;
} const legacyPrompt = legacyRaw.length > 180 ? `${legacyRaw.slice(0, 179)}…` : legacyRaw;
const withMedia = hasMedia ? `${cleaned} [附图]` : cleaned; return { cleanText, legacyPrompt, hasMedia };
return withMedia.length > 180 ? `${withMedia.slice(0, 179)}…` : withMedia;
}; };
let pendingTurnCleanPrompts = [];
rawSteps.forEach((s, index) => { rawSteps.forEach((s, index) => {
if (isUserTurnBoundary(s)) { if (isUserTurnBoundary(s)) {
const promptText = extractUserTurnPrompt(s); const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s);
if (!hasUnconsumedTurn) { if (!hasUnconsumedTurn) {
hasUnconsumedTurn = true; hasUnconsumedTurn = true;
pendingTurnPrompts = promptText ? [promptText] : []; pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
} else if ( pendingTurnCleanPrompts = cleanText ? [cleanText] : [];
promptText && pendingTurnHasMedia = hasMedia;
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== promptText } else {
) { if (
pendingTurnPrompts.push(promptText); legacyPrompt &&
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt
) {
pendingTurnPrompts.push(legacyPrompt);
}
if (
cleanText &&
pendingTurnCleanPrompts[pendingTurnCleanPrompts.length - 1] !== cleanText
) {
pendingTurnCleanPrompts.push(cleanText);
}
if (hasMedia) pendingTurnHasMedia = true;
} }
} }
@@ -738,15 +750,25 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
let stepIsTurnStart = false; let stepIsTurnStart = false;
let stepTurnPrompt = ''; let stepTurnPrompt = '';
let stepTurnPromptClean = '';
let stepTurnHasMedia = false;
let stepTurnMediaOnly = false;
if (hasUnconsumedTurn) { if (hasUnconsumedTurn) {
turnCounter += 1; turnCounter += 1;
activeTurnIndex = turnCounter; activeTurnIndex = turnCounter;
stepIsTurnStart = true; stepIsTurnStart = true;
const joinedPrompt = pendingTurnPrompts.join('\n').trim(); const joinedPrompt = pendingTurnPrompts.join('\n').trim();
const joinedClean = pendingTurnCleanPrompts.join('\n').trim();
stepTurnPrompt = stepTurnPrompt =
joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt; joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt;
stepTurnPromptClean =
joinedClean.length > 180 ? `${joinedClean.slice(0, 179)}…` : joinedClean;
stepTurnHasMedia = pendingTurnHasMedia;
stepTurnMediaOnly = Boolean(pendingTurnHasMedia && !stepTurnPromptClean);
hasUnconsumedTurn = false; hasUnconsumedTurn = false;
pendingTurnPrompts = []; pendingTurnPrompts = [];
pendingTurnCleanPrompts = [];
pendingTurnHasMedia = false;
} }
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
@@ -917,6 +939,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
turnIndex: activeTurnIndex, turnIndex: activeTurnIndex,
isTurnStart: stepIsTurnStart, isTurnStart: stepIsTurnStart,
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}),
...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}),
}); });
}); });
@@ -1678,6 +1702,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
: summary || cmdSnippet || ''; : summary || cmdSnippet || '';
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'run_command',
isAskUser: false, isAskUser: false,
label: '执行命令', label: '执行命令',
detail, detail,
@@ -1704,6 +1729,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
: ''; : '';
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'read_file',
isAskUser: false, isAskUser: false,
label: '读取文件', label: '读取文件',
detail: file ? `${file}${rangeSuffix}` : '', detail: file ? `${file}${rangeSuffix}` : '',
@@ -1721,6 +1747,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
); );
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'edit_file',
isAskUser: false, isAskUser: false,
label: '修改文件', label: '修改文件',
detail: file || '', detail: file || '',
@@ -1733,6 +1760,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
); );
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'write_file',
isAskUser: false, isAskUser: false,
label: '写入文件', label: '写入文件',
detail: file || '', detail: file || '',
@@ -1748,6 +1776,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
: cleanSingleLineSnippet(query, 48) || searchPath || ''; : cleanSingleLineSnippet(query, 48) || searchPath || '';
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'grep_search',
isAskUser: false, isAskUser: false,
label: '搜索代码', label: '搜索代码',
detail, detail,
@@ -1759,6 +1788,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path'])); const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path']));
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'find_file',
isAskUser: false, isAskUser: false,
label: '查找文件', label: '查找文件',
detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '', detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '',
@@ -1770,6 +1800,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const target = pickField(['query', 'Query', 'Url', 'url']); const target = pickField(['query', 'Query', 'Url', 'url']);
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: isUrl ? 'read_url' : 'search_web',
isAskUser: false, isAskUser: false,
label: isUrl ? '读取网页' : '网页搜索', label: isUrl ? '读取网页' : '网页搜索',
detail: cleanSingleLineSnippet(target, 52) || '', detail: cleanSingleLineSnippet(target, 52) || '',
@@ -1785,6 +1816,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
String(subSpec.typeName || '').trim(); String(subSpec.typeName || '').trim();
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'invoke_subagent',
isAskUser: false, isAskUser: false,
label: '调用子代理', label: '调用子代理',
detail: role || '', detail: role || '',
@@ -1795,6 +1827,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const recipient = pickField(['Recipient', 'recipient']); const recipient = pickField(['Recipient', 'recipient']);
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'send_message',
isAskUser: false, isAskUser: false,
label: '通信子代理', label: '通信子代理',
detail: recipient ? recipient.slice(0, 8) : '', detail: recipient ? recipient.slice(0, 8) : '',
@@ -1805,6 +1838,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const subName = pickField(['Name', 'Action', 'action']); const subName = pickField(['Name', 'Action', 'action']);
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'manage_subagents',
isAskUser: false, isAskUser: false,
label: '管理子代理', label: '管理子代理',
detail: subName || '', detail: subName || '',
@@ -1816,6 +1850,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const taskId = pickField(['TaskId', 'taskId']); const taskId = pickField(['TaskId', 'taskId']);
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'manage_task',
isAskUser: false, isAskUser: false,
label: '后台任务', label: '后台任务',
detail: taskId ? `${action || 'status'} (${taskId})` : action || '', detail: taskId ? `${action || 'status'} (${taskId})` : action || '',
@@ -1827,6 +1862,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const cron = pickField(['CronExpression']); const cron = pickField(['CronExpression']);
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'schedule',
isAskUser: false, isAskUser: false,
label: '定时任务', label: '定时任务',
detail: dur ? `${dur}s` : cron || '', detail: dur ? `${dur}s` : cron || '',
@@ -1843,6 +1879,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
); );
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'ask_question',
isAskUser: true, isAskUser: true,
label: '等待用户选择', label: '等待用户选择',
detail: cleanSingleLineSnippet(qText, 50) || '', detail: cleanSingleLineSnippet(qText, 50) || '',
@@ -1854,6 +1891,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : ''; const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : '';
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'search_marketplace',
isAskUser: false, isAskUser: false,
label: '查询插件', label: '查询插件',
detail: cleanSingleLineSnippet(q, 48) || '', detail: cleanSingleLineSnippet(q, 48) || '',
@@ -1864,6 +1902,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · '); const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · ');
return { return {
toolName: nameLower, toolName: nameLower,
actionKey: 'mcp_tool',
isAskUser: false, isAskUser: false,
label: '调用 MCP', label: '调用 MCP',
detail: mcpClean || '', detail: mcpClean || '',
@@ -1872,6 +1911,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
return { return {
toolName: nameLower || 'tool', toolName: nameLower || 'tool',
actionKey: 'tool_call',
isAskUser: false, isAskUser: false,
label: '调用工具', label: '调用工具',
detail: nameLower || '', detail: nameLower || '',
@@ -1919,6 +1959,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const startMs = Math.floor(fallbackStartMs || 0); const startMs = Math.floor(fallbackStartMs || 0);
return { return {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
waitingApproval: false,
detailKey: '',
label: '推理中', label: '推理中',
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -1968,6 +2011,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
if (isCheckpointStep(lastStep)) { if (isCheckpointStep(lastStep)) {
return { return {
phase: 'compacting', phase: 'compacting',
actionKey: 'compacting',
waitingApproval: false,
detailKey: '',
label: '上下文压缩', label: '上下文压缩',
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -1989,11 +2035,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const phase = info.isAskUser ? 'waiting' : 'tool'; const phase = info.isAskUser ? 'waiting' : 'tool';
return { return {
phase, phase,
toolName: info.toolName,
actionKey: info.actionKey,
waitingApproval: false,
detailKey: '',
label: info.label, label: info.label,
detail: info.detail, detail: info.detail,
stepProgress, stepProgress,
startedAtMs: startMs, startedAtMs: startMs,
signature: `planner-tool:${lastStepId}:${tools.length}:${info.label}:${info.detail}`, signature: `planner-tool:${lastStepId}:${tools.length}:${info.actionKey}:${info.detail}`,
}; };
} }
@@ -2001,6 +2051,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const snippet = cleanSingleLineSnippet(respText, 52, true); const snippet = cleanSingleLineSnippet(respText, 52, true);
return { return {
phase: 'responding', phase: 'responding',
actionKey: 'responding',
waitingApproval: false,
detailKey: '',
label: '正在输出回复', label: '正在输出回复',
detail: snippet, detail: snippet,
stepProgress: '', stepProgress: '',
@@ -2013,6 +2066,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const snippet = cleanSingleLineSnippet(thinkText, 52, true); const snippet = cleanSingleLineSnippet(thinkText, 52, true);
return { return {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
waitingApproval: false,
detailKey: '',
label: '推理中', label: '推理中',
detail: snippet, detail: snippet,
stepProgress: '', stepProgress: '',
@@ -2023,6 +2079,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
return { return {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
waitingApproval: false,
detailKey: '',
label: '推理中', label: '推理中',
detail: '', detail: '',
stepProgress: '', stepProgress: '',
@@ -2057,16 +2116,21 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
stepProgress = ''; stepProgress = '';
} }
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
const waitingApproval = Boolean(waiting && !info.isAskUser);
const resolvedStartMs = startMs || prevStepEndMs || 0; const resolvedStartMs = startMs || prevStepEndMs || 0;
const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label; const label = waitingApproval ? `等待确认 · ${info.label}` : info.label;
return { return {
phase: waiting ? 'waiting' : 'tool', phase: waiting ? 'waiting' : 'tool',
toolName: info.toolName,
actionKey: info.actionKey,
waitingApproval,
detailKey: '',
label, label,
detail: info.detail, detail: info.detail,
stepProgress, stepProgress,
startedAtMs: resolvedStartMs, startedAtMs: resolvedStartMs,
signature: `step-run:${lastStepId}:${waiting}:${label}:${stepProgress}:${info.detail}`, signature: `step-run:${lastStepId}:${waiting}:${info.actionKey}:${stepProgress}:${info.detail}`,
}; };
} }
@@ -2102,6 +2166,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
Math.floor(fallbackStartMs || 0); Math.floor(fallbackStartMs || 0);
return { return {
phase: 'compacting', phase: 'compacting',
actionKey: 'compacting',
waitingApproval: false,
detailKey: cpFinishMs > 0 ? 'compaction_resuming' : '',
label: '上下文压缩', label: '上下文压缩',
detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '', detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '',
stepProgress: '', stepProgress: '',
@@ -2144,11 +2211,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
return { return {
phase, phase,
toolName: info.toolName,
actionKey: info.actionKey,
waitingApproval: false,
detailKey: '',
label: info.label, label: info.label,
detail: info.detail, detail: info.detail,
stepProgress, stepProgress,
startedAtMs: startMs, startedAtMs: startMs,
signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.label}:${stepProgress}:${info.detail}`, signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.actionKey}:${stepProgress}:${info.detail}`,
}; };
} }
@@ -2158,7 +2229,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep) summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep)
); );
const lastToolInfo = infos[infos.length - 1]; const lastToolInfo = infos[infos.length - 1];
const allSameLabel = infos.every((x) => x.label === lastToolInfo.label); const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey);
const detailsList = infos.map((x) => x.detail).filter(Boolean); const detailsList = infos.map((x) => x.detail).filter(Boolean);
const combinedDetail = const combinedDetail =
infos.length > 1 && allSameLabel infos.length > 1 && allSameLabel
@@ -2171,11 +2242,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
return { return {
phase: 'thinking', phase: 'thinking',
toolName: lastToolInfo.toolName,
actionKey: lastToolInfo.actionKey,
waitingApproval: false,
detailKey: '',
label: lastToolInfo.label, label: lastToolInfo.label,
detail: combinedDetail, detail: combinedDetail,
stepProgress, stepProgress,
startedAtMs: startMs, startedAtMs: startMs,
signature: `post-tool-think:${lastStepId}:${lastToolInfo.label}:${combinedDetail}`, signature: `post-tool-think:${lastStepId}:${lastToolInfo.actionKey}:${combinedDetail}`,
}; };
} }
@@ -2188,11 +2263,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
return { return {
phase: 'thinking', phase: 'thinking',
toolName: lastInfo.toolName,
actionKey: lastInfo.actionKey,
waitingApproval: false,
detailKey: '',
label: lastInfo.label, label: lastInfo.label,
detail: lastInfo.detail, detail: lastInfo.detail,
stepProgress: '', stepProgress: '',
startedAtMs: startMs, startedAtMs: startMs,
signature: `post-step-tool:${lastStepId}:${lastInfo.label}:${lastInfo.detail}`, signature: `post-step-tool:${lastStepId}:${lastInfo.actionKey}:${lastInfo.detail}`,
}; };
} }
} }
@@ -2208,6 +2287,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
if (snippet) { if (snippet) {
return { return {
phase: 'responding', phase: 'responding',
actionKey: 'responding',
waitingApproval: false,
detailKey: '',
label: '正在输出回复', label: '正在输出回复',
detail: snippet, detail: snippet,
stepProgress: '', stepProgress: '',
@@ -2221,6 +2303,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
if (snippet) { if (snippet) {
return { return {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
waitingApproval: false,
detailKey: '',
label: '推理中', label: '推理中',
detail: snippet, detail: snippet,
stepProgress: '', stepProgress: '',
@@ -2236,6 +2321,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0; const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0;
return { return {
phase: 'thinking', phase: 'thinking',
actionKey: 'thinking',
waitingApproval: false,
detailKey: '',
label: '推理中', label: '推理中',
detail: '', detail: '',
stepProgress: '', stepProgress: '',