mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add Native Swarm mode compatibility and distinct worker telemetry
- Guard conversation_parents against forked Swarm Workers (subagentSpec or trajectoryType != 22) and selectively decode CORTEX_STEP_TYPE_SYSTEM_MESSAGE (step_type = 101) for child trajectories only
- Parse swarm, post_message, read_board, and swarm_wait tool calls, split zero-human-turn worker trajectories on initial brief / @mention / cron wakeup boundaries, and downgrade swarm_wait parked workers from RUNNING to IDLE ('waiting') while surfacing killed workers ('killed')
- Scan brain/<id>/.system_generated/swarm/members.json with mtime+size memoization, sort workers chronologically, assign independent swarm_worker ordinals (蜂k / Wk) separate from standard subagents (子k / Sk) and side questions (问k / Qk), and preserve 100% of worker token/USD billing
- Render Swarm counts, titles, scrollable sorted live worker lists, and one-shot auto-focus when navigating host routes to /c/<worker-uuid>, backed by E2E and binary SQLite tests
This commit is contained in:
+412
-86
@@ -1043,6 +1043,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'header.lockedSession': '已锁定会话 ({id})',
|
||||
'header.lockedMeta': '已锁定',
|
||||
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
|
||||
'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)',
|
||||
'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)',
|
||||
'header.convMetaSteps': '{count}步',
|
||||
'header.hasUpdate': '有新版本',
|
||||
'header.upgradeToVer': '升级 v{ver}',
|
||||
@@ -1081,6 +1083,11 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.subAgent': '子代理',
|
||||
'fmt.subBadge': '子{index}',
|
||||
'fmt.subBadgeShort': '子',
|
||||
'fmt.swarmAgent': '蜂群',
|
||||
'fmt.swarmBadge': '蜂{index}',
|
||||
'fmt.swarmBadgeShort': '蜂',
|
||||
'fmt.swarmMonitorHint': '巡检',
|
||||
'fmt.swarmNarratorHint': '旁白',
|
||||
'fmt.sideQuestion': '旁路提问',
|
||||
'fmt.sideBadge': '旁{index}',
|
||||
'fmt.sideBadgeShort': '旁',
|
||||
@@ -1094,6 +1101,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'capsule.multiZero': '0 运行中',
|
||||
'capsule.multiRunning': '{count} 运行中',
|
||||
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
|
||||
'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂',
|
||||
'capsule.tpsRunning': '生成中',
|
||||
'capsule.tpsIdle': '待命',
|
||||
'capsule.quotaLeft': '余 {pct}%',
|
||||
@@ -1114,6 +1122,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'multi.empty': '当前暂无在线运行的会话',
|
||||
'multi.allIdle': '全部待命',
|
||||
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
|
||||
'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中',
|
||||
'multi.metaMainOnly': '{main} 个会话运行中',
|
||||
'multi.hereTag': '本窗',
|
||||
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
|
||||
@@ -1210,10 +1219,16 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.thinking': '推理中',
|
||||
'live.generating': '生成中',
|
||||
'live.running': '运行中',
|
||||
'live.waiting': '待命中',
|
||||
'live.killed': '已终止',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
'live.waitingWithSteps': '待命中 ({steps} 步)',
|
||||
'live.killedWithSteps': '已终止 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': '子代理 ({total}) {arrow}',
|
||||
'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}',
|
||||
'live.swarmToggleIdle': '蜂群 ({total}) {arrow}',
|
||||
'live.subCollapseTitle': '点击收起子代理列表',
|
||||
'live.subExpandTitle': '点击展开查看子代理缩略状态',
|
||||
|
||||
@@ -1584,6 +1599,15 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.invoke_subagent': '调用子代理',
|
||||
'live.act.send_message': '通信子代理',
|
||||
'live.act.manage_subagents': '管理子代理',
|
||||
'live.act.swarm_add': '派生工蜂',
|
||||
'live.act.swarm_title': '命名蜂群',
|
||||
'live.act.swarm_kill': '终止工蜂',
|
||||
'live.act.swarm_model': '切换工蜂模型',
|
||||
'live.act.swarm_channel': '蜂群频道',
|
||||
'live.act.swarm_status': '巡检蜂群',
|
||||
'live.act.post_message': '发布看板',
|
||||
'live.act.read_board': '读取看板',
|
||||
'live.act.swarm_wait': '看板待命',
|
||||
'live.act.manage_task': '后台任务',
|
||||
'live.act.schedule': '定时任务',
|
||||
'live.act.ask_question': '等待用户选择',
|
||||
@@ -1594,6 +1618,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.compacting': '上下文压缩',
|
||||
'live.act.responding': '正在输出回复',
|
||||
'live.act.waiting_subagent': '等待子代理',
|
||||
'live.act.waiting_swarm': '等待工蜂',
|
||||
'live.act.swarm_waiting': '待命中',
|
||||
'live.act.swarm_killed': '已终止',
|
||||
'live.act.starting': '启动中',
|
||||
'live.act.done': '已完成',
|
||||
'live.act.awaitingApproval': '等待确认 · {label}',
|
||||
@@ -1679,6 +1706,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'header.lockedSession': 'Pinned Session ({id})',
|
||||
'header.lockedMeta': 'Pinned',
|
||||
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
|
||||
'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)',
|
||||
'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)',
|
||||
'header.convMetaSteps': '{count} steps',
|
||||
'header.hasUpdate': 'Update',
|
||||
'header.upgradeToVer': 'Update v{ver}',
|
||||
@@ -1717,6 +1746,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.subAgent': 'Subagent',
|
||||
'fmt.subBadge': 'S{index}',
|
||||
'fmt.subBadgeShort': 'Sub',
|
||||
'fmt.swarmAgent': 'Swarm',
|
||||
'fmt.swarmBadge': 'W{index}',
|
||||
'fmt.swarmBadgeShort': 'Swarm',
|
||||
'fmt.swarmMonitorHint': 'Monitor',
|
||||
'fmt.swarmNarratorHint': 'Narrator',
|
||||
'fmt.sideQuestion': 'Side Question',
|
||||
'fmt.sideBadge': 'Q{index}',
|
||||
'fmt.sideBadgeShort': 'Q',
|
||||
@@ -1730,6 +1764,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'capsule.multiZero': '0 active',
|
||||
'capsule.multiRunning': '{count} active',
|
||||
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
|
||||
'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm',
|
||||
'capsule.tpsRunning': 'Running',
|
||||
'capsule.tpsIdle': 'Idle',
|
||||
'capsule.quotaLeft': '{pct}% left',
|
||||
@@ -1750,6 +1785,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'multi.empty': 'No active running sessions',
|
||||
'multi.allIdle': 'All idle',
|
||||
'multi.metaWithSubs': '{main} main · {subs} subagents active',
|
||||
'multi.metaWithSwarm': '{main} main · {subs} swarm active',
|
||||
'multi.metaMainOnly': '{main} sessions active',
|
||||
'multi.hereTag': 'Here',
|
||||
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
|
||||
@@ -1846,10 +1882,16 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.thinking': 'Thinking',
|
||||
'live.generating': 'Generating',
|
||||
'live.running': 'Running',
|
||||
'live.waiting': 'Waiting',
|
||||
'live.killed': 'Killed',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
'live.waitingWithSteps': 'Waiting ({steps} steps)',
|
||||
'live.killedWithSteps': 'Killed ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': 'Subagents ({total}) {arrow}',
|
||||
'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}',
|
||||
'live.swarmToggleIdle': 'Swarm ({total}) {arrow}',
|
||||
'live.subCollapseTitle': 'Collapse subagent list',
|
||||
'live.subExpandTitle': 'Expand subagent activity list',
|
||||
|
||||
@@ -2220,6 +2262,15 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.invoke_subagent': 'Invoke Subagent',
|
||||
'live.act.send_message': 'Message Subagent',
|
||||
'live.act.manage_subagents': 'Manage Subagents',
|
||||
'live.act.swarm_add': 'Spawn Worker',
|
||||
'live.act.swarm_title': 'Name Swarm',
|
||||
'live.act.swarm_kill': 'Kill Worker',
|
||||
'live.act.swarm_model': 'Switch Worker Model',
|
||||
'live.act.swarm_channel': 'Swarm Channel',
|
||||
'live.act.swarm_status': 'Check Swarm',
|
||||
'live.act.post_message': 'Post to Board',
|
||||
'live.act.read_board': 'Read Board',
|
||||
'live.act.swarm_wait': 'Parked on Board',
|
||||
'live.act.manage_task': 'Manage Task',
|
||||
'live.act.schedule': 'Schedule Task',
|
||||
'live.act.ask_question': 'Waiting for User Choice',
|
||||
@@ -2230,6 +2281,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.compacting': 'Compacting Context',
|
||||
'live.act.responding': 'Responding',
|
||||
'live.act.waiting_subagent': 'Waiting for Subagent',
|
||||
'live.act.waiting_swarm': 'Waiting for Swarm',
|
||||
'live.act.swarm_waiting': 'Waiting',
|
||||
'live.act.swarm_killed': 'Killed',
|
||||
'live.act.starting': 'Starting',
|
||||
'live.act.done': 'Completed',
|
||||
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
|
||||
@@ -2744,7 +2798,7 @@ return { defineComponent };
|
||||
})();
|
||||
|
||||
// --- src/core/formatters.js ---
|
||||
const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail } = (() => {
|
||||
const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail } = (() => {
|
||||
/**
|
||||
* @fileoverview Pure formatting utilities for speed metrics, token counts,
|
||||
* USD estimates, countdown timers, and custom datetime displays.
|
||||
@@ -3230,21 +3284,48 @@ function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
return `badge-sub-${slot}`;
|
||||
}
|
||||
|
||||
function resolveStructuredAgentKind(agent) {
|
||||
if (!agent) return 'main';
|
||||
if (agent.agentKind) return agent.agentKind;
|
||||
if (agent.isMain) return 'main';
|
||||
if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question';
|
||||
if (
|
||||
agent.typeName === 'worker' ||
|
||||
agent.typeName === 'swarm_worker' ||
|
||||
/^Swarm\s+Worker\s*\(/i.test(String(agent.role || ''))
|
||||
) {
|
||||
return 'swarm_worker';
|
||||
}
|
||||
return 'subagent';
|
||||
}
|
||||
|
||||
function normalizeSwarmMemberHandle(rawText) {
|
||||
const trimmed = String(rawText || '').trim();
|
||||
if (!trimmed) return '';
|
||||
const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
|
||||
const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim();
|
||||
if (
|
||||
!inner ||
|
||||
inner === '蜂群' ||
|
||||
inner === '工蜂' ||
|
||||
inner.toLowerCase() === 'swarm' ||
|
||||
inner.toLowerCase() === 'worker' ||
|
||||
inner.toLowerCase() === 'swarm worker'
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
return `@${inner}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
*
|
||||
* @param {object|null|undefined} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
function formatAgentBadgeText(agent) {
|
||||
if (!agent) return t('fmt.mainBadge');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAllShort');
|
||||
if (kind === 'main') return t('fmt.mainBadge');
|
||||
if (kind === 'side_question') {
|
||||
@@ -3253,6 +3334,12 @@ function formatAgentBadgeText(agent) {
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.sideBadgeShort');
|
||||
}
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.swarmBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.swarmBadgeShort');
|
||||
}
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.subBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
@@ -3267,13 +3354,7 @@ function formatAgentBadgeText(agent) {
|
||||
*/
|
||||
function formatAgentLabel(agent) {
|
||||
if (!agent) return t('fmt.mainAgent');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAll');
|
||||
if (kind === 'main') return t('fmt.mainAgent');
|
||||
|
||||
@@ -3294,6 +3375,20 @@ function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent');
|
||||
const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || '');
|
||||
if (!handle) return baseLabel;
|
||||
let auxSuffix = '';
|
||||
if (/^@monitor(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmMonitorHint')})`;
|
||||
} else if (/^@narrator(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmNarratorHint')})`;
|
||||
}
|
||||
return `${baseLabel} · ${handle}${auxSuffix}`;
|
||||
}
|
||||
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
|
||||
const isGeneric =
|
||||
@@ -3305,6 +3400,31 @@ function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。
|
||||
*
|
||||
* @param {object|null|undefined} conv
|
||||
* @returns {string}
|
||||
*/
|
||||
function formatConversationMeta(conv) {
|
||||
if (!conv) return '';
|
||||
const main = Number(conv.stepCount || 0);
|
||||
const totalSubs = Number(conv.subagentCount || 0);
|
||||
const swarm = Number(conv.swarmCount || 0);
|
||||
const otherSubs = Math.max(0, totalSubs - swarm);
|
||||
const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main);
|
||||
if (swarm > 0 && otherSubs > 0) {
|
||||
return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total });
|
||||
}
|
||||
if (swarm > 0) {
|
||||
return t('header.convMetaWithSwarm', { main, swarm, total });
|
||||
}
|
||||
if (totalSubs > 0) {
|
||||
return t('header.convMetaWithSubs', { main, subs: totalSubs, total });
|
||||
}
|
||||
return t('header.convMetaSteps', { count: main });
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
|
||||
*
|
||||
@@ -3344,7 +3464,7 @@ function formatLiveActivityDetail(act) {
|
||||
}
|
||||
return String(act.detail || '');
|
||||
}
|
||||
return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail };
|
||||
return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail };
|
||||
})();
|
||||
|
||||
// --- src/core/httpClient.js ---
|
||||
@@ -3628,7 +3748,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView };
|
||||
})();
|
||||
|
||||
// --- src/store/telemetryStore.js ---
|
||||
const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform } = (() => {
|
||||
const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
|
||||
/**
|
||||
* @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
|
||||
* and granular slice updates.
|
||||
@@ -3889,6 +4009,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||
if ((pAct?.swarmCount || 0) !== (nAct?.swarmCount || 0)) return false;
|
||||
if ((pAct?.swarmTitle || '') !== (nAct?.swarmTitle || '')) return false;
|
||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
if (
|
||||
@@ -3965,6 +4087,9 @@ function isEquivalentTelemetry(prev, next) {
|
||||
const na = nAgents[i];
|
||||
if (
|
||||
pa?.agentId !== na?.agentId ||
|
||||
pa?.agentKind !== na?.agentKind ||
|
||||
pa?.agentOrdinal !== na?.agentOrdinal ||
|
||||
(pa?.swarmState || '') !== (na?.swarmState || '') ||
|
||||
pa?.role !== na?.role ||
|
||||
pa?.stepCount !== na?.stepCount ||
|
||||
pa?.isRunning !== na?.isRunning ||
|
||||
@@ -4250,6 +4375,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pConvs[i]?.status !== nConvs[i]?.status ||
|
||||
pConvs[i]?.stepCount !== nConvs[i]?.stepCount ||
|
||||
pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount ||
|
||||
(pConvs[i]?.swarmCount || 0) !== (nConvs[i]?.swarmCount || 0) ||
|
||||
(pConvs[i]?.swarmTitle || '') !== (nConvs[i]?.swarmTitle || '') ||
|
||||
pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount
|
||||
) {
|
||||
return false;
|
||||
@@ -4268,7 +4395,9 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pr?.isCurrentSelected !== nr?.isCurrentSelected ||
|
||||
pr?.isMainRunning !== nr?.isMainRunning ||
|
||||
pr?.subagentCount !== nr?.subagentCount ||
|
||||
(pr?.swarmCount || 0) !== (nr?.swarmCount || 0) ||
|
||||
pr?.runningSubagentCount !== nr?.runningSubagentCount ||
|
||||
(pr?.runningSwarmCount || 0) !== (nr?.runningSwarmCount || 0) ||
|
||||
pr?.mainActivity?.signature !== nr?.mainActivity?.signature ||
|
||||
pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs
|
||||
) {
|
||||
@@ -4280,6 +4409,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
for (let j = 0; j < pSubs.length; j++) {
|
||||
if (
|
||||
pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId ||
|
||||
pSubs[j]?.agentKind !== nSubs[j]?.agentKind ||
|
||||
(pSubs[j]?.swarmState || '') !== (nSubs[j]?.swarmState || '') ||
|
||||
pSubs[j]?.role !== nSubs[j]?.role ||
|
||||
pSubs[j]?.isRunning !== nSubs[j]?.isRunning ||
|
||||
pSubs[j]?.stepCount !== nSubs[j]?.stepCount ||
|
||||
@@ -4675,6 +4806,54 @@ function stopAsyncTelemetryLoop() {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 在遥测快照中解析宿主当前路由会话 ID(兼容顶层主会话 ID 与子代理/蜂群工蜂 ID)。
|
||||
*
|
||||
* @param {object|null|undefined} telemetry
|
||||
* @param {string} rawRouteId
|
||||
* @returns {{ rootConv: object|null, childAgent: object|null, isChildRoute: boolean } | null}
|
||||
*/
|
||||
function resolveHostRouteMatch(telemetry, rawRouteId) {
|
||||
const routeLower = String(rawRouteId || '').trim().toLowerCase();
|
||||
if (!routeLower || !telemetry) return null;
|
||||
const convs = Array.isArray(telemetry.conversations) ? telemetry.conversations : [];
|
||||
const actConv = telemetry.activeConversation || null;
|
||||
|
||||
const directRoot =
|
||||
convs.find((c) => String(c?.cascadeId || '').toLowerCase() === routeLower) ||
|
||||
(String(actConv?.cascadeId || '').toLowerCase() === routeLower ? actConv : null);
|
||||
if (directRoot) {
|
||||
return { rootConv: directRoot, childAgent: null, isChildRoute: false };
|
||||
}
|
||||
|
||||
const activeChild = (actConv?.agents || []).find(
|
||||
(a) =>
|
||||
!a?.isMain &&
|
||||
(String(a?.cascadeId || '').toLowerCase() === routeLower ||
|
||||
String(a?.agentId || '').toLowerCase() === routeLower)
|
||||
);
|
||||
if (activeChild) {
|
||||
const parentInList = convs.find(
|
||||
(c) => String(c?.cascadeId || '').toLowerCase() === String(actConv?.cascadeId || '').toLowerCase()
|
||||
);
|
||||
return {
|
||||
rootConv: parentInList || actConv,
|
||||
childAgent: activeChild,
|
||||
isChildRoute: true,
|
||||
};
|
||||
}
|
||||
|
||||
const memberParent = convs.find(
|
||||
(c) =>
|
||||
Array.isArray(c?.memberCascadeIds) &&
|
||||
c.memberCascadeIds.some((id) => String(id || '').toLowerCase() === routeLower)
|
||||
);
|
||||
if (memberParent) {
|
||||
return { rootConv: memberParent, childAgent: null, isChildRoute: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
|
||||
* 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。
|
||||
@@ -4820,7 +4999,7 @@ function isMacHostPlatform(telemetry) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform };
|
||||
return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
|
||||
})();
|
||||
|
||||
// --- src/components/ui/TopLongPillNav.js ---
|
||||
@@ -10868,43 +11047,68 @@ function buildFallbackRunningConversations(
|
||||
}
|
||||
const activeConv = data.activeConversation || {};
|
||||
if (!activeConv.isRunning && !aggregated?.isRunning) return [];
|
||||
const childAgents = (agents || []).filter((a) => !a.isMain);
|
||||
const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker');
|
||||
return [
|
||||
{
|
||||
cascadeId: activeConv.cascadeId || 'current',
|
||||
title: activeConv.title || t('live.currentSession'),
|
||||
...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}),
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: Boolean(activeConv.isRunning),
|
||||
isRunning: true,
|
||||
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
|
||||
subagentCount: Math.max(0, (agents?.length || 1) - 1),
|
||||
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
|
||||
subagentCount: childAgents.length,
|
||||
swarmCount: swarmChildren.length,
|
||||
runningSubagentCount: childAgents.filter((a) => a.isRunning).length,
|
||||
runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length,
|
||||
...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}),
|
||||
...(contextUsedPct !== undefined ? { contextUsedPct } : {}),
|
||||
subagents: (agents || [])
|
||||
.filter((a) => !a.isMain)
|
||||
.map((s, idx) => ({
|
||||
subagents: childAgents.map((s, idx) => {
|
||||
const isSwarmW = s.agentKind === 'swarm_worker';
|
||||
const isKilled = Boolean(s.swarmState === 'killed');
|
||||
return {
|
||||
cascadeId: s.cascadeId || s.agentId,
|
||||
index: s.index || idx + 1,
|
||||
agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'),
|
||||
agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
agentOrdinal:
|
||||
s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
customRole: s.customRole,
|
||||
...(s.swarmState ? { swarmState: s.swarmState } : {}),
|
||||
...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}),
|
||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
shortLabel:
|
||||
s.shortLabel ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
role:
|
||||
s.role ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
isRunning: Boolean(s.isRunning),
|
||||
stepCount: Number(s.stepCount || 0),
|
||||
lastModifiedMs: s.lastModifiedMs || 0,
|
||||
liveActivity: s.liveActivity || {
|
||||
phase: s.isRunning ? 'thinking' : 'done',
|
||||
actionKey: s.isRunning ? 'thinking' : 'done',
|
||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||
phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done',
|
||||
actionKey: s.isRunning
|
||||
? 'thinking'
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? 'swarm_killed'
|
||||
: 'swarm_waiting'
|
||||
: 'done',
|
||||
label: s.isRunning
|
||||
? t('live.thinking')
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? t('live.killed')
|
||||
: t('live.waiting')
|
||||
: t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: s.lastModifiedMs || 0,
|
||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||
signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -11190,14 +11394,17 @@ const LiveActivityWidget = defineComponent({
|
||||
const isHere =
|
||||
showSessionExtras &&
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
`${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
@@ -11244,7 +11451,10 @@ const LiveActivityWidget = defineComponent({
|
||||
if (showSessionExtras && refs.hereTagEl && refs.metricsEl) {
|
||||
const isHere =
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
patchText(refs.hereTagEl, t('multi.hereTag'));
|
||||
patchAttr(refs.hereTagEl, 'hidden', !isHere);
|
||||
|
||||
@@ -11265,6 +11475,11 @@ const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const swarmCount = Number(
|
||||
item.swarmCount ??
|
||||
(item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length
|
||||
);
|
||||
const isPureSwarm = subCount > 0 && swarmCount === subCount;
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = resolveIsExpanded(item);
|
||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||
@@ -11274,8 +11489,15 @@ const LiveActivityWidget = defineComponent({
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
const toggleText =
|
||||
runSubCount > 0
|
||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
||||
? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', {
|
||||
run: runSubCount,
|
||||
total: subCount,
|
||||
arrow,
|
||||
})
|
||||
: t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', {
|
||||
total: subCount,
|
||||
arrow,
|
||||
});
|
||||
patchText(refs.subToggleBtn, toggleText);
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
||||
if (interactive) {
|
||||
@@ -11323,11 +11545,28 @@ const LiveActivityWidget = defineComponent({
|
||||
const showSubs = subCount > 0 && isExpanded;
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
if (showSubs) {
|
||||
const subItems = item.subagents || [];
|
||||
const rawSubItems = item.subagents || [];
|
||||
const getSubSortRank = (s) => {
|
||||
if (s?.isRunning) return 0;
|
||||
if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
};
|
||||
const subItems =
|
||||
rawSubItems.length > 1
|
||||
? rawSubItems
|
||||
.slice()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
getSubSortRank(a) - getSubSortRank(b) ||
|
||||
Number(a?.index || 0) - Number(b?.index || 0)
|
||||
)
|
||||
: rawSubItems;
|
||||
patchKeyedList(refs.subListEl, subItems, {
|
||||
keyFn: (sub) => sub.cascadeId,
|
||||
sigFn: (sub) =>
|
||||
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
`${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
createRow: createLiveSubRow,
|
||||
updateRow: (subRefs, sub) => {
|
||||
const subAct = sub.liveActivity || {
|
||||
@@ -11338,7 +11577,17 @@ const LiveActivityWidget = defineComponent({
|
||||
stepProgress: '',
|
||||
startedAtMs: sub.lastModifiedMs || 0,
|
||||
};
|
||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
||||
const isWaitingSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting');
|
||||
const isKilledSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed');
|
||||
patchClasses(subRefs.rowEl, {
|
||||
'is-done': !sub.isRunning && !isWaitingSub,
|
||||
'is-waiting-sub': isWaitingSub,
|
||||
'is-killed-sub': isKilledSub,
|
||||
});
|
||||
|
||||
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
|
||||
const subBadgeText = formatAgentBadgeText({
|
||||
@@ -11352,22 +11601,33 @@ const LiveActivityWidget = defineComponent({
|
||||
const fallbackRole =
|
||||
sub.agentKind === 'side_question' || sub.isSideQuestion
|
||||
? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
: sub.agentKind === 'swarm_worker'
|
||||
? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
const roleText =
|
||||
sub.customRole !== undefined
|
||||
? sub.customRole || fallbackRole
|
||||
: sub.role || sub.shortLabel || fallbackRole;
|
||||
patchText(subRefs.subRole, roleText);
|
||||
|
||||
const idleFallbackKey = isKilledSub
|
||||
? 'live.killed'
|
||||
: isWaitingSub
|
||||
? 'live.waiting'
|
||||
: 'live.done';
|
||||
const subLabel = sub.isRunning
|
||||
? formatLiveActivityLabel(subAct, 'live.running')
|
||||
: formatLiveActivityLabel(subAct, 'live.done');
|
||||
: formatLiveActivityLabel(subAct, idleFallbackKey);
|
||||
const subDetail = formatLiveActivityDetail(subAct);
|
||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||
const summaryStr = showSessionExtras
|
||||
? sub.isRunning
|
||||
? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}`
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isKilledSub
|
||||
? t('live.killedWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isWaitingSub
|
||||
? t('live.waitingWithSteps', { steps: sub.stepCount || 0 })
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' ');
|
||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||
patchText(subRefs.subSummary, summaryStr);
|
||||
@@ -12146,14 +12406,29 @@ function resolveMultiSessionCapsuleState(
|
||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
||||
0
|
||||
);
|
||||
const runningSwarmCount = rawRunningList.reduce(
|
||||
(acc, item) => acc + Number(item.runningSwarmCount || 0),
|
||||
0
|
||||
);
|
||||
const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
||||
const multiBtnText =
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', {
|
||||
count: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('capsule.multiRunning', { count: runningCount })
|
||||
: t('capsule.multiZero');
|
||||
return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText };
|
||||
return {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -16572,16 +16847,7 @@ const { TopSessionHeader } = (() => {
|
||||
|
||||
|
||||
function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return t('header.convMetaWithSubs', {
|
||||
main: c.stepCount || 0,
|
||||
subs,
|
||||
total: c.totalStepCount || c.stepCount || 0,
|
||||
});
|
||||
}
|
||||
return t('header.convMetaSteps', { count: c.stepCount || 0 });
|
||||
return formatConversationMeta(c);
|
||||
}
|
||||
|
||||
const TopSessionHeader = defineComponent({
|
||||
@@ -16659,10 +16925,49 @@ const TopSessionHeader = defineComponent({
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
let lastAppliedHostChildRouteId = '';
|
||||
|
||||
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||
function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) {
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (!currentCascadeId) return;
|
||||
|
||||
const selectedId = String(telSlice?.selectedConversationId || '').trim();
|
||||
const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim();
|
||||
const hostRouteLower = hostRouteId.toLowerCase();
|
||||
|
||||
if (!selectedId && hostRouteLower) {
|
||||
const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId);
|
||||
if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (lastAppliedHostChildRouteId !== hostRouteLower) {
|
||||
lastAppliedHostChildRouteId = hostRouteLower;
|
||||
const targetAgentId = routeMatch.childAgent.agentId;
|
||||
const uiSt = uiStore.getState();
|
||||
if (
|
||||
uiSt.selectedAgentScope !== targetAgentId ||
|
||||
uiSt.ctxInspectorAgentId !== targetAgentId
|
||||
) {
|
||||
uiStore.setState({
|
||||
selectedAgentScope: targetAgentId,
|
||||
ctxInspectorAgentId: targetAgentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
const uiSt = uiStore.getState();
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
}
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
return;
|
||||
}
|
||||
} else if (lastAppliedHostChildRouteId) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
}
|
||||
|
||||
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
const uiSt = uiStore.getState();
|
||||
@@ -16686,34 +16991,44 @@ const TopSessionHeader = defineComponent({
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
const hostMatchedConv = hostRouteId
|
||||
? convs.find((c) => c.cascadeId === hostRouteId) ||
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null;
|
||||
const hostMatchedConv = routeMatch?.rootConv || null;
|
||||
const childRouteBadge =
|
||||
routeMatch?.isChildRoute && routeMatch.childAgent
|
||||
? formatAgentBadgeText(routeMatch.childAgent)
|
||||
: '';
|
||||
const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8);
|
||||
const hostDisplayTitle = childRouteBadge
|
||||
? `${hostBaseTitle} · ${childRouteBadge}`
|
||||
: hostBaseTitle;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? t('header.currentWindowNamed', {
|
||||
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
|
||||
title: hostDisplayTitle,
|
||||
})
|
||||
: convs[0]?.title
|
||||
? t('header.latestNamed', { title: convs[0].title })
|
||||
: t('header.followLatest');
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
stepCount: hostMatchedConv.stepCount,
|
||||
subagentCount: hostMatchedConv.subagentCount,
|
||||
totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents,
|
||||
})
|
||||
? formatConvOptionMeta(hostMatchedConv)
|
||||
: ''
|
||||
: convs[0]
|
||||
? formatConvOptionMeta(convs[0])
|
||||
: '';
|
||||
const options = [
|
||||
{ value: '', label: defaultOptLabel, meta: defaultOptMeta },
|
||||
{
|
||||
value: '',
|
||||
label: defaultOptLabel,
|
||||
meta: defaultOptMeta,
|
||||
...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}),
|
||||
},
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: formatConvOptionMeta(c),
|
||||
...(c.swarmTitle && c.swarmTitle !== c.title
|
||||
? { title: `${c.title || c.cascadeId.slice(0, 8)} · ${c.swarmTitle}` }
|
||||
: {}),
|
||||
})),
|
||||
];
|
||||
const lockedId = telSt.selectedConversationId;
|
||||
@@ -16723,13 +17038,7 @@ const TopSessionHeader = defineComponent({
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: t('header.lockedMeta');
|
||||
const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta');
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
@@ -16836,7 +17145,7 @@ const TopSessionHeader = defineComponent({
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
(slice) => {
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry, slice);
|
||||
renderHeaderState();
|
||||
}
|
||||
);
|
||||
@@ -21583,16 +21892,26 @@ function mountWindowOverlay() {
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||
}
|
||||
|
||||
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
||||
function renderMultiRunningPanel(
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
hostRouteConversationId,
|
||||
runningSwarmCount = 0
|
||||
) {
|
||||
if (!multiOpen || document.hidden) {
|
||||
multiRunningWidget.refs.pauseTicker();
|
||||
return;
|
||||
}
|
||||
const isPureSwarm = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
patchText(
|
||||
multiRunningMetaEl,
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('multi.metaWithSubs', { main: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarm ? 'multi.metaWithSwarm' : 'multi.metaWithSubs', {
|
||||
main: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('multi.metaMainOnly', { main: runningCount })
|
||||
: t('multi.allIdle')
|
||||
);
|
||||
@@ -21663,13 +21982,19 @@ function mountWindowOverlay() {
|
||||
ctxAgent,
|
||||
aggregated,
|
||||
});
|
||||
const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } =
|
||||
resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
const {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
} = resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
|
||||
patchClasses(multiBtn, {
|
||||
'is-running': runningCount > 0 && !hasWaiting,
|
||||
@@ -21681,7 +22006,8 @@ function mountWindowOverlay() {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
telSt.hostRouteConversationId
|
||||
telSt.hostRouteConversationId,
|
||||
runningSwarmCount
|
||||
);
|
||||
|
||||
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||
|
||||
@@ -80,18 +80,24 @@ function projectDisplayStep(st) {
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt,
|
||||
turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia,
|
||||
rootTurnMediaOnly,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt,
|
||||
turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia,
|
||||
rootTurnMediaOnly,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -678,6 +678,16 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
const sqLower = String(pRow?.conversation_id || '').trim().toLowerCase();
|
||||
const parentLower = String(pRow?.parent_id || '').trim().toLowerCase();
|
||||
if (!sqLower || !parentLower) continue;
|
||||
const childSummary = nextSummariesObj[sqLower];
|
||||
if (
|
||||
childSummary &&
|
||||
!childSummary.isSideQuestion &&
|
||||
(childSummary.trajectoryMetadata?.subagentSpec ||
|
||||
(Number(childSummary.trajectoryType) > 0 && Number(childSummary.trajectoryType) !== 22))
|
||||
) {
|
||||
// 排除通过 fork 创建的蜂群工蜂或常规子代理,避免误归入旁路提问
|
||||
continue;
|
||||
}
|
||||
const parentSummary = nextSummariesObj[parentLower];
|
||||
const titleFromParent = String(
|
||||
parentSummary?.annotations?.sideQuestionTitles?.[sqLower] ||
|
||||
@@ -1451,7 +1461,26 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
|
||||
return invokeSubagent;
|
||||
}
|
||||
|
||||
function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagent, keepFullText }) {
|
||||
function decodeProtoSystemMessageSlice(buf, state, end) {
|
||||
let message = '';
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
message = readProtoString(buf, state, end);
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return message;
|
||||
}
|
||||
|
||||
function decodeProtoSelectiveStepPayload(
|
||||
rawBlob,
|
||||
{ stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText }
|
||||
) {
|
||||
const buf = toUint8Array(rawBlob);
|
||||
if (!buf || buf.length === 0) return {};
|
||||
const state = { off: 0 };
|
||||
@@ -1472,6 +1501,9 @@ function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagen
|
||||
readSubEnd(buf, state, end),
|
||||
keepFullText
|
||||
);
|
||||
} else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) {
|
||||
const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (sysMsg) out.systemMessage = { message: sysMsg };
|
||||
} else if (fn === 140 && wt === 2 && isInvokeSubagent) {
|
||||
const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (inv) out.invokeSubagent = inv;
|
||||
@@ -1728,6 +1760,17 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata });
|
||||
}
|
||||
|
||||
const isChildTrajectory =
|
||||
!isSideQuestion &&
|
||||
Boolean(
|
||||
trajectoryMetadata.parentConversationId ||
|
||||
parentConversationId ||
|
||||
(trajectoryMetadata.rootConversationId &&
|
||||
trajectoryMetadata.rootConversationId !== normCid) ||
|
||||
(rootConversationId && rootConversationId !== normCid) ||
|
||||
trajectoryMetadata.subagentSpec
|
||||
);
|
||||
|
||||
const runningTailStart = isRunning
|
||||
? Math.max(0, ownStepRecords.length - 16)
|
||||
: ownStepRecords.length;
|
||||
@@ -1743,6 +1786,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
if (
|
||||
rec.stepTypeNum === 14 ||
|
||||
rec.stepTypeNum === 15 ||
|
||||
(isChildTrajectory && rec.stepTypeNum === 101) ||
|
||||
isInvSub ||
|
||||
(inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson))
|
||||
) {
|
||||
@@ -1805,6 +1849,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, {
|
||||
stepTypeNum: rec.stepTypeNum,
|
||||
isInvokeSubagent: isInvSub,
|
||||
includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101,
|
||||
keepFullText: inRunningTail,
|
||||
});
|
||||
if (decodedPayload.userInput) {
|
||||
@@ -1816,6 +1861,10 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (decodedPayload.systemMessage) {
|
||||
stepObj.systemMessage = decodedPayload.systemMessage;
|
||||
stepObj.content = decodedPayload.systemMessage.message;
|
||||
}
|
||||
if (decodedPayload.plannerResponse) {
|
||||
stepObj.plannerResponse = decodedPayload.plannerResponse;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,9 @@ import {
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
getMaxMeaningfulStepIndex,
|
||||
isParkedOnSwarmWait,
|
||||
parseIsoMs,
|
||||
parseSwarmWorkerRole,
|
||||
} from '../trajectory-metrics.mjs';
|
||||
import {
|
||||
ANNOTATION_DIRS,
|
||||
@@ -353,11 +355,133 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
const failedFetchCooldownMap = new Map();
|
||||
const liveActivityMemo = new Map();
|
||||
const transcriptTailMemo = new Map();
|
||||
const swarmManifestMemo = new Map();
|
||||
|
||||
export function clearScannerRuntimeMemos() {
|
||||
failedFetchCooldownMap.clear();
|
||||
liveActivityMemo.clear();
|
||||
transcriptTailMemo.clear();
|
||||
swarmManifestMemo.clear();
|
||||
}
|
||||
|
||||
function findSwarmMembersPath(cascadeId) {
|
||||
if (!cascadeId) return '';
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return '';
|
||||
const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR];
|
||||
let bestPath = '';
|
||||
let bestMtime = -1;
|
||||
for (const dir of dirs) {
|
||||
if (!dir) continue;
|
||||
const candidate = join(dir, normId, '.system_generated', 'swarm', 'members.json');
|
||||
if (!existsSync(candidate)) continue;
|
||||
if (dirs.length === 1) return candidate;
|
||||
try {
|
||||
const mtime = Number(statSync(candidate)?.mtimeMs || 0);
|
||||
if (mtime > bestMtime) {
|
||||
bestMtime = mtime;
|
||||
bestPath = candidate;
|
||||
}
|
||||
} catch {
|
||||
if (!bestPath) bestPath = candidate;
|
||||
}
|
||||
}
|
||||
return bestPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按会话 ID 精确读取本地 `brain/<cascadeId>/.system_generated/swarm/members.json` 蜂群花名册(O(1) 定点读取 + `mtimeMs + size` 缓存)。
|
||||
*
|
||||
* @param {string} cascadeId
|
||||
* @returns {{
|
||||
* title: string,
|
||||
* coordinator: object|null,
|
||||
* membersByCid: Map<string, object>,
|
||||
* membersByName: Map<string, object>,
|
||||
* workerRefs: Array<object>
|
||||
* } | null}
|
||||
*/
|
||||
export function readSwarmManifestForCascade(cascadeId) {
|
||||
if (!cascadeId) return null;
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return null;
|
||||
const membersPath = findSwarmMembersPath(normId);
|
||||
if (!membersPath) {
|
||||
swarmManifestMemo.delete(normId);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const st = statSync(membersPath);
|
||||
const mtimeMs = Number(st?.mtimeMs || 0);
|
||||
const size = Number(st?.size || 0);
|
||||
const cached = swarmManifestMemo.get(normId);
|
||||
if (
|
||||
cached &&
|
||||
cached.path === membersPath &&
|
||||
cached.mtimeMs === mtimeMs &&
|
||||
cached.size === size &&
|
||||
size > 0
|
||||
) {
|
||||
return cached.manifest;
|
||||
}
|
||||
const raw = readFileSync(membersPath, 'utf8');
|
||||
const parsed = raw ? JSON.parse(raw) : null;
|
||||
if (!parsed || typeof parsed !== 'object') return null;
|
||||
|
||||
const title = String(parsed.title || '').trim();
|
||||
const rawMembers = parsed.members && typeof parsed.members === 'object' ? parsed.members : {};
|
||||
const membersByCid = new Map();
|
||||
const membersByName = new Map();
|
||||
const workerRefs = [];
|
||||
let coordinator = null;
|
||||
|
||||
for (const [rawKey, m] of Object.entries(rawMembers)) {
|
||||
if (!m || typeof m !== 'object') continue;
|
||||
const memberName = String(m.name || rawKey || '').replace(/^@+/, '').trim();
|
||||
const cid = String(m.conversation_id || m.conversationId || '').trim().toLowerCase();
|
||||
if (!cid || !UUID_RE.test(cid)) continue;
|
||||
const role = String(m.role || '').trim().toLowerCase();
|
||||
const wakeMode = String(m.wake_mode || m.wakeMode || '').trim().toLowerCase();
|
||||
const killed = Boolean(m.killed);
|
||||
const workspaceMode = String(m.workspace_mode || m.workspaceMode || 'inherit').trim();
|
||||
const model = String(m.applied_model || m.model || m.desired_model || '').trim();
|
||||
const entry = {
|
||||
memberName,
|
||||
conversationId: cid,
|
||||
role,
|
||||
wakeMode,
|
||||
killed,
|
||||
workspaceMode,
|
||||
model,
|
||||
};
|
||||
membersByCid.set(cid, entry);
|
||||
if (memberName) {
|
||||
membersByName.set(memberName.toLowerCase(), entry);
|
||||
}
|
||||
if (role === 'coordinator' || cid === normId) {
|
||||
coordinator = entry;
|
||||
} else {
|
||||
workerRefs.push({
|
||||
cascadeId: cid,
|
||||
role: memberName ? `Swarm Worker (${memberName})` : 'Swarm Worker',
|
||||
typeName: 'worker',
|
||||
memberName,
|
||||
createdTimeMs: 0,
|
||||
spawnOrder: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const manifest = { title, coordinator, membersByCid, membersByName, workerRefs };
|
||||
if (swarmManifestMemo.size >= MAX_TRANSCRIPT_MEMO_ENTRIES && !swarmManifestMemo.has(normId)) {
|
||||
const oldestKey = swarmManifestMemo.keys().next().value;
|
||||
if (oldestKey !== undefined) swarmManifestMemo.delete(oldestKey);
|
||||
}
|
||||
swarmManifestMemo.set(normId, { path: membersPath, mtimeMs, size, manifest });
|
||||
return manifest;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function findTranscriptPath(cascadeId) {
|
||||
@@ -461,6 +585,7 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) {
|
||||
const needsTranscriptBackfill = sqliteSteps.some(
|
||||
(s) =>
|
||||
(s?.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !s.userInput) ||
|
||||
(s?.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && !s.content && !s.systemMessage) ||
|
||||
(s?.metadata?.modelUsage && !s.metadata.modelUsage.model)
|
||||
);
|
||||
if (!needsTranscriptBackfill) {
|
||||
@@ -522,6 +647,12 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) {
|
||||
if (typeof tLine.content === 'string') sq.content = tLine.content;
|
||||
if (tLine.userInput) sq.userInput = tLine.userInput;
|
||||
if (Array.isArray(tLine.media)) sq.media = tLine.media;
|
||||
} else if (
|
||||
sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' &&
|
||||
!sq.content &&
|
||||
typeof tLine.content === 'string'
|
||||
) {
|
||||
sq.content = tLine.content;
|
||||
} else if (sq.metadata?.modelUsage && !sq.metadata.modelUsage.model) {
|
||||
const fallbackModel = String(tLine.model || tLine.generator_model || '').trim();
|
||||
if (fallbackModel) sq.metadata.modelUsage.model = fallbackModel;
|
||||
@@ -635,6 +766,23 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE') {
|
||||
const sysText =
|
||||
typeof sq.content === 'string' && sq.content
|
||||
? sq.content
|
||||
: typeof tLine?.content === 'string'
|
||||
? tLine.content
|
||||
: '';
|
||||
if (sysText) {
|
||||
sqliteRawSteps.push({
|
||||
type: sq.type,
|
||||
status: sq.status,
|
||||
content: sysText,
|
||||
metadata: sq.metadata,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sq.metadata?.modelUsage) {
|
||||
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
||||
@@ -672,7 +820,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
if (
|
||||
upperType === 'USER_INPUT' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object')
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'
|
||||
) {
|
||||
sqliteRawSteps.push(line);
|
||||
} else if (
|
||||
@@ -721,7 +871,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
if (
|
||||
upperType === 'USER_INPUT' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object')
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'
|
||||
) {
|
||||
syntheticSteps.push(line);
|
||||
continue;
|
||||
@@ -1390,8 +1542,10 @@ export async function enumerateAndSyncConversations({
|
||||
Boolean(cached?.isSubagent) ||
|
||||
Boolean(parentConversationId) ||
|
||||
Boolean(rootConversationId && rootConversationId !== cidLower);
|
||||
const isKilled = Boolean(item?.killed || localSum?.killed);
|
||||
const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0);
|
||||
const localStatus =
|
||||
!isKilled &&
|
||||
localSum?.status === 'CASCADE_RUN_STATUS_RUNNING' &&
|
||||
latestLocalTouchMs > 0 &&
|
||||
nowSweepMs - latestLocalTouchMs <= STALE_LOCAL_RUNNING_MAX_AGE_MS
|
||||
@@ -1417,7 +1571,8 @@ export async function enumerateAndSyncConversations({
|
||||
(isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
stepCount: modelStepCount,
|
||||
rawStepCount: rawSummaryStepCount,
|
||||
status: item?.status || '',
|
||||
status: isKilled ? 'IDLE' : item?.status || '',
|
||||
killed: isKilled,
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
diskMtimeMs,
|
||||
@@ -1448,6 +1603,7 @@ export async function enumerateAndSyncConversations({
|
||||
stepCount: cachedStepCount,
|
||||
rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount,
|
||||
status: localStatus,
|
||||
killed: isKilled,
|
||||
lastModifiedTime: localSum?.lastModifiedTime || '',
|
||||
lastModifiedMs: Math.max(
|
||||
cached.lastModifiedMs || 0,
|
||||
@@ -1480,6 +1636,7 @@ export async function enumerateAndSyncConversations({
|
||||
stepCount: 0,
|
||||
rawStepCount: localSum?.stepCount || 0,
|
||||
status: localStatus,
|
||||
killed: isKilled,
|
||||
lastModifiedTime: localSum?.lastModifiedTime || '',
|
||||
lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0),
|
||||
diskMtimeMs,
|
||||
@@ -1710,6 +1867,19 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
|
||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||
const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
||||
if (ownSwarmManifest?.workerRefs?.length) {
|
||||
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
||||
for (const wRef of ownSwarmManifest.workerRefs) {
|
||||
if (!seenRefCids.has(wRef.cascadeId)) {
|
||||
seenRefCids.add(wRef.cascadeId);
|
||||
subagentRefs.push(wRef);
|
||||
}
|
||||
}
|
||||
if (!nonShortTitle(conv.title) && ownSwarmManifest.title) {
|
||||
conv.title = ownSwarmManifest.title;
|
||||
}
|
||||
}
|
||||
conv.subagentRefs = subagentRefs;
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
@@ -1718,16 +1888,24 @@ export async function enumerateAndSyncConversations({
|
||||
conv.stepCount = steps.length;
|
||||
const finalSig = buildConvSig(conv);
|
||||
|
||||
const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps);
|
||||
if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
conv.status = 'IDLE';
|
||||
}
|
||||
|
||||
const liveAct = resolveBestLiveActivity(
|
||||
conv.cascadeId,
|
||||
rawSteps,
|
||||
isRunning,
|
||||
effectiveIsRunning,
|
||||
resolvedLastModMs || conv.createdTimeMs || 0
|
||||
);
|
||||
if (liveAct) {
|
||||
if (liveAct && liveAct.actionKey !== 'swarm_wait') {
|
||||
conv.liveActivity = liveAct;
|
||||
liveActivityMemo.set(cidLower, liveAct);
|
||||
} else {
|
||||
if (liveAct?.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
}
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(cidLower);
|
||||
}
|
||||
@@ -1747,10 +1925,11 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs:
|
||||
conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)),
|
||||
rawStepCount: conv.rawStepCount ?? stepsWithOwners.length,
|
||||
wasRunning: isRunning,
|
||||
wasRunning: conv.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
wakeupTurnTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
steps: stepsWithOwners,
|
||||
subagentRefs,
|
||||
@@ -1963,6 +2142,12 @@ export async function enumerateAndSyncConversations({
|
||||
return false;
|
||||
}
|
||||
|
||||
function needsWakeupTurnRefresh(conv, cached) {
|
||||
if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false;
|
||||
const steps = cached?.steps || [];
|
||||
return steps.length > 0 && steps.every((s) => !s?.turnIndex);
|
||||
}
|
||||
|
||||
let remainingTimingRefreshes = LEGACY_MIGRATION_BATCH_SIZE;
|
||||
const toFetch = rawConversations.filter((conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
@@ -1979,6 +2164,7 @@ export async function enumerateAndSyncConversations({
|
||||
if (
|
||||
(!cached.turnRailTelemetry ||
|
||||
hasMissingTurnRailFields(cached) ||
|
||||
needsWakeupTurnRefresh(conv, cached) ||
|
||||
hasDroppedContextGroups(cached)) &&
|
||||
isSelectedFamily
|
||||
) {
|
||||
@@ -2056,7 +2242,22 @@ export async function enumerateAndSyncConversations({
|
||||
|
||||
for (const parentConv of [...rawConversations]) {
|
||||
const parentCached = getCachedTrajectory(parentConv.cascadeId);
|
||||
const refs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
const swarmManifest = !parentConv.isSubagent
|
||||
? readSwarmManifestForCascade(parentConv.cascadeId)
|
||||
: null;
|
||||
let refs = baseRefs;
|
||||
if (swarmManifest?.workerRefs?.length) {
|
||||
const merged = Array.isArray(baseRefs) ? baseRefs.slice() : [];
|
||||
const seenRefCids = new Set(merged.map((r) => String(r?.cascadeId || '').toLowerCase()));
|
||||
for (const wRef of swarmManifest.workerRefs) {
|
||||
if (!seenRefCids.has(wRef.cascadeId)) {
|
||||
seenRefCids.add(wRef.cascadeId);
|
||||
merged.push(wRef);
|
||||
}
|
||||
}
|
||||
refs = merged;
|
||||
}
|
||||
if (!Array.isArray(refs) || refs.length === 0) continue;
|
||||
|
||||
const parentId = parentConv.cascadeId.toLowerCase();
|
||||
@@ -2145,6 +2346,7 @@ export async function enumerateAndSyncConversations({
|
||||
(!isSelectedSubFamily ||
|
||||
(Boolean(existingSubCache.turnRailTelemetry) &&
|
||||
!hasMissingTurnRailFields(existingSubCache) &&
|
||||
!needsWakeupTurnRefresh(subConv, existingSubCache) &&
|
||||
!hasDroppedContextGroups(existingSubCache)));
|
||||
|
||||
if (hasValidSubCache) {
|
||||
@@ -2253,16 +2455,33 @@ export async function enumerateAndSyncConversations({
|
||||
persistTrajectoryCacheIfNeeded({ hasRunningSessions });
|
||||
}
|
||||
|
||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要
|
||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态
|
||||
for (const conv of rawConversations) {
|
||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
if (!conv.liveActivity) {
|
||||
const tailSteps = readTranscriptTailSteps(conv.cascadeId);
|
||||
if (isParkedOnSwarmWait(tailSteps)) {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
continue;
|
||||
}
|
||||
const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0;
|
||||
const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs);
|
||||
if (resolved?.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
continue;
|
||||
}
|
||||
conv.liveActivity = resolved;
|
||||
if (resolved) {
|
||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
|
||||
}
|
||||
} else if (conv.liveActivity.actionKey === 'swarm_wait') {
|
||||
conv.status = 'IDLE';
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
}
|
||||
} else {
|
||||
conv.liveActivity = null;
|
||||
@@ -2308,7 +2527,64 @@ export async function enumerateAndSyncConversations({
|
||||
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const swarmManifest = readSwarmManifestForCascade(cid);
|
||||
const swarmTitle = String(swarmManifest?.title || '').trim();
|
||||
if (swarmTitle) {
|
||||
rootConv.swarmTitle = swarmTitle;
|
||||
const curTitle = String(rootConv.title || '').trim();
|
||||
if (!curTitle || curTitle.toLowerCase() === cid.slice(0, 8)) {
|
||||
rootConv.title = swarmTitle;
|
||||
}
|
||||
}
|
||||
if (swarmManifest?.coordinator?.killed || rootConv.killed) {
|
||||
rootConv.status = 'IDLE';
|
||||
rootConv.liveActivity = null;
|
||||
}
|
||||
|
||||
const subs = subagentsByRoot.get(cid) || [];
|
||||
let swarmCount = 0;
|
||||
for (const s of subs) {
|
||||
const subLower = s.cascadeId.toLowerCase();
|
||||
const mEntry = swarmManifest?.membersByCid.get(subLower) || null;
|
||||
const subCached = getCachedTrajectory(s.cascadeId);
|
||||
const parsedSwarm = !s.isSideQuestion
|
||||
? parseSwarmWorkerRole({
|
||||
role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '',
|
||||
typeName: s.subagentSpec?.typeName || subCached?.subagentSpec?.typeName || '',
|
||||
agentScriptName: s.agentScriptName || subCached?.agentScriptName || '',
|
||||
memberName: mEntry?.memberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
if (parsedSwarm.isSwarmWorker) {
|
||||
swarmCount += 1;
|
||||
s.isSwarmWorker = true;
|
||||
s.swarmMemberName = parsedSwarm.memberName;
|
||||
s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary);
|
||||
s.killed = Boolean(s.killed || mEntry?.killed);
|
||||
if (s.killed) {
|
||||
s.status = 'IDLE';
|
||||
s.liveActivity = null;
|
||||
liveActivityMemo.delete(subLower);
|
||||
s.swarmState = 'killed';
|
||||
} else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
const parkedInManifest =
|
||||
Boolean(mEntry) &&
|
||||
(mEntry.wakeMode === 'mentions' || mEntry.wakeMode === 'anything') &&
|
||||
(!s.liveActivity || s.liveActivity.signature === 'init:0');
|
||||
if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) {
|
||||
s.status = 'IDLE';
|
||||
s.liveActivity = null;
|
||||
liveActivityMemo.delete(subLower);
|
||||
s.swarmState = 'waiting';
|
||||
} else {
|
||||
s.swarmState = 'working';
|
||||
}
|
||||
} else {
|
||||
s.swarmState = 'waiting';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
subs.sort((a, b) => {
|
||||
const aSide = Boolean(a.isSideQuestion);
|
||||
const bSide = Boolean(b.isSideQuestion);
|
||||
@@ -2338,6 +2614,7 @@ export async function enumerateAndSyncConversations({
|
||||
});
|
||||
rootConv.subagents = subs;
|
||||
rootConv.subagentCount = subs.length;
|
||||
rootConv.swarmCount = swarmCount;
|
||||
rootConv.totalStepCount =
|
||||
Number(rootConv.stepCount || 0) +
|
||||
subs.reduce((sum, s) => sum + Number(s.stepCount || 0), 0);
|
||||
|
||||
@@ -14,6 +14,7 @@ import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
parseIsoMs,
|
||||
parseSwarmWorkerRole,
|
||||
speedMetric,
|
||||
summarizeSpeed,
|
||||
summarizeTtft,
|
||||
@@ -573,6 +574,8 @@ export function buildAgentUnitTelemetry({
|
||||
agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent',
|
||||
agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0,
|
||||
customRole = '',
|
||||
swarmState = '',
|
||||
isSwarmAuxiliary = false,
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
@@ -628,6 +631,8 @@ export function buildAgentUnitTelemetry({
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
...(swarmState ? { swarmState } : {}),
|
||||
...(isSwarmAuxiliary ? { isSwarmAuxiliary: true } : {}),
|
||||
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
||||
index,
|
||||
shortLabel,
|
||||
@@ -829,6 +834,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
let totalFamilyOutputTokens = sessionOutputTokens;
|
||||
|
||||
let normalSubCount = 0;
|
||||
let swarmWorkerCount = 0;
|
||||
let sideQuestionCount = 0;
|
||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||
const subSum = subagentSummaries[idx];
|
||||
@@ -844,11 +850,22 @@ export async function buildTelemetryPayloadInternal(
|
||||
);
|
||||
const rawRole =
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const parsedSwarm = !isSideQ
|
||||
? parseSwarmWorkerRole({
|
||||
role: subSpec?.role || '',
|
||||
typeName: subSpec?.typeName || '',
|
||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
||||
memberName: subSum.swarmMemberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let swarmState = '';
|
||||
let isSwarmAuxiliary = false;
|
||||
let shortLabel = '';
|
||||
let badgeText = '';
|
||||
let roleLabel = '';
|
||||
@@ -871,6 +888,23 @@ export async function buildTelemetryPayloadInternal(
|
||||
roleLabel = cleanSideRole || '旁路提问';
|
||||
typeName = 'side_question';
|
||||
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
|
||||
} else if (isSwarmW) {
|
||||
const swOrd = ++swarmWorkerCount;
|
||||
agentKind = 'swarm_worker';
|
||||
agentOrdinal = swOrd;
|
||||
const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : '';
|
||||
customRole = memberTag;
|
||||
shortLabel = `蜂群 #${swOrd}`;
|
||||
badgeText = `蜂${swOrd}`;
|
||||
roleLabel = memberTag || '蜂群';
|
||||
typeName = 'worker';
|
||||
agentLabel = memberTag ? `${shortLabel} · ${memberTag}` : shortLabel;
|
||||
swarmState = subSum.killed
|
||||
? 'killed'
|
||||
: subSum.status === 'CASCADE_RUN_STATUS_RUNNING'
|
||||
? 'working'
|
||||
: subSum.swarmState || 'waiting';
|
||||
isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary);
|
||||
} else {
|
||||
const subOrd = ++normalSubCount;
|
||||
agentKind = 'subagent';
|
||||
@@ -892,6 +926,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
swarmState,
|
||||
isSwarmAuxiliary,
|
||||
index: subIndex,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
@@ -1026,12 +1062,18 @@ export async function buildTelemetryPayloadInternal(
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||
mainAgentTelemetry;
|
||||
|
||||
const roleSummaryParts = [];
|
||||
if (swarmWorkerCount > 0) roleSummaryParts.push(`${swarmWorkerCount} 蜂群`);
|
||||
if (normalSubCount > 0) roleSummaryParts.push(`${normalSubCount} 子代理`);
|
||||
if (sideQuestionCount > 0) {
|
||||
roleSummaryParts.push(
|
||||
roleSummaryParts.length > 0 ? `${sideQuestionCount} 旁问` : `${sideQuestionCount} 旁路提问`
|
||||
);
|
||||
}
|
||||
const aggregatedRoleLabel =
|
||||
normalSubCount > 0 && sideQuestionCount > 0
|
||||
? `主代理 + ${normalSubCount} 子代理 + ${sideQuestionCount} 旁问`
|
||||
: sideQuestionCount > 0
|
||||
? `主代理 + ${sideQuestionCount} 旁路提问`
|
||||
: `主代理 + ${subAgentTelemetries.length} 子代理`;
|
||||
roleSummaryParts.length > 0
|
||||
? `主代理 + ${roleSummaryParts.join(' + ')}`
|
||||
: `主代理 + ${subAgentTelemetries.length} 子代理`;
|
||||
|
||||
const totalCostUsd = roundSessionCost(totalRawSessionCostUsd);
|
||||
const totalUnpricedCalls = allAgents.reduce(
|
||||
@@ -1412,6 +1454,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||
|
||||
let runNormalSubIdx = 0;
|
||||
let runSwarmIdx = 0;
|
||||
let runSideIdx = 0;
|
||||
const subItems = rawSubs.map((subSum, idx) => {
|
||||
const subCid = subSum.cascadeId;
|
||||
@@ -1426,11 +1469,22 @@ export async function buildTelemetryPayloadInternal(
|
||||
subEntry?.agentScriptName ||
|
||||
subSpec?.typeName ||
|
||||
'';
|
||||
const parsedSwarm = !isSideQ
|
||||
? parseSwarmWorkerRole({
|
||||
role: subSpec?.role || '',
|
||||
typeName: subSpec?.typeName || '',
|
||||
agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '',
|
||||
memberName: subSum.swarmMemberName || '',
|
||||
})
|
||||
: { isSwarmWorker: false };
|
||||
const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker));
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let swarmState = '';
|
||||
let isSwarmAuxiliary = false;
|
||||
let badgeText = '';
|
||||
let shortLabel = '';
|
||||
let role = '';
|
||||
@@ -1449,6 +1503,16 @@ export async function buildTelemetryPayloadInternal(
|
||||
: '';
|
||||
customRole = cleanSide;
|
||||
role = cleanSide || shortLabel;
|
||||
} else if (isSwarmW) {
|
||||
const swOrd = ++runSwarmIdx;
|
||||
agentKind = 'swarm_worker';
|
||||
agentOrdinal = swOrd;
|
||||
const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : '';
|
||||
customRole = memberTag;
|
||||
badgeText = `蜂${swOrd}`;
|
||||
shortLabel = `蜂群 #${swOrd}`;
|
||||
role = memberTag || shortLabel;
|
||||
isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary);
|
||||
} else {
|
||||
const nOrd = ++runNormalSubIdx;
|
||||
agentKind = 'subagent';
|
||||
@@ -1459,32 +1523,62 @@ export async function buildTelemetryPayloadInternal(
|
||||
role = rawRole || shortLabel;
|
||||
}
|
||||
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const isKilled = Boolean(subSum.killed || subSum.swarmState === 'killed');
|
||||
if (isSwarmW) {
|
||||
swarmState = isKilled ? 'killed' : isSubRunning ? 'working' : subSum.swarmState || 'waiting';
|
||||
}
|
||||
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
||||
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
||||
const liveActivity = isSubRunning
|
||||
? subSum.liveActivity || extractLiveActivity([], true, subModMs)
|
||||
: {
|
||||
phase: 'done',
|
||||
actionKey: 'done',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '已完成',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: subModMs,
|
||||
signature: `done:${stepCount}`,
|
||||
};
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? {
|
||||
phase: 'done',
|
||||
actionKey: 'swarm_killed',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '已终止',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: subModMs,
|
||||
signature: `killed:${stepCount}`,
|
||||
}
|
||||
: {
|
||||
phase: 'waiting',
|
||||
actionKey: 'swarm_waiting',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '待命中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: subModMs,
|
||||
signature: `waiting:${stepCount}`,
|
||||
}
|
||||
: {
|
||||
phase: 'done',
|
||||
actionKey: 'done',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '已完成',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: subModMs,
|
||||
signature: `done:${stepCount}`,
|
||||
};
|
||||
return {
|
||||
cascadeId: subCid,
|
||||
index: subIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
...(swarmState ? { swarmState } : {}),
|
||||
...(isSwarmAuxiliary ? { isSwarmAuxiliary: true } : {}),
|
||||
...(isSideQ ? { isSideQuestion: true, sideIndex } : {}),
|
||||
badgeText,
|
||||
shortLabel,
|
||||
role,
|
||||
typeName: isSideQ ? 'side_question' : subSpec?.typeName || '',
|
||||
typeName: isSideQ ? 'side_question' : isSwarmW ? 'worker' : subSpec?.typeName || '',
|
||||
isRunning: isSubRunning,
|
||||
status: subSum.status || 'IDLE',
|
||||
stepCount,
|
||||
@@ -1498,52 +1592,86 @@ export async function buildTelemetryPayloadInternal(
|
||||
: null;
|
||||
|
||||
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
||||
if (
|
||||
isMainRunning &&
|
||||
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') &&
|
||||
runningSubCount === 0
|
||||
) {
|
||||
const isPendingSubSpawn =
|
||||
mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent';
|
||||
const isPendingSwarmSpawn = mainLiveAct?.actionKey === 'swarm_add';
|
||||
if (isMainRunning && (isPendingSubSpawn || isPendingSwarmSpawn) && runningSubCount === 0) {
|
||||
const pendingIndex = subItems.length + 1;
|
||||
const pendingCustomRole = mainLiveAct.detail || '';
|
||||
const pendingRole = pendingCustomRole || '子代理';
|
||||
subItems.push({
|
||||
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
||||
index: pendingIndex,
|
||||
agentKind: 'subagent',
|
||||
agentOrdinal: pendingIndex,
|
||||
customRole: pendingCustomRole,
|
||||
badgeText: `子${pendingIndex}`,
|
||||
shortLabel: `子代理 #${pendingIndex}`,
|
||||
role: pendingRole,
|
||||
typeName: '',
|
||||
isRunning: true,
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
stepCount: 0,
|
||||
lastModifiedMs: rootFallbackMs,
|
||||
liveActivity: {
|
||||
phase: 'thinking',
|
||||
actionKey: 'starting',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '启动中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: mainLiveAct.startedAtMs || 0,
|
||||
signature: `spawning-sub:${pendingIndex}:${pendingRole}`,
|
||||
},
|
||||
});
|
||||
if (isPendingSwarmSpawn) {
|
||||
const pendingSwarmOrd = ++runSwarmIdx;
|
||||
const pendingRole = pendingCustomRole || `蜂群 #${pendingSwarmOrd}`;
|
||||
subItems.push({
|
||||
cascadeId: `${rootConv.cascadeId}:pending-swarm-${pendingIndex}`,
|
||||
index: pendingIndex,
|
||||
agentKind: 'swarm_worker',
|
||||
agentOrdinal: pendingSwarmOrd,
|
||||
customRole: pendingCustomRole,
|
||||
swarmState: 'working',
|
||||
badgeText: `蜂${pendingSwarmOrd}`,
|
||||
shortLabel: `蜂群 #${pendingSwarmOrd}`,
|
||||
role: pendingRole,
|
||||
typeName: 'worker',
|
||||
isRunning: true,
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
stepCount: 0,
|
||||
lastModifiedMs: rootFallbackMs,
|
||||
liveActivity: {
|
||||
phase: 'thinking',
|
||||
actionKey: 'starting',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '启动中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: mainLiveAct.startedAtMs || 0,
|
||||
signature: `spawning-swarm:${pendingSwarmOrd}:${pendingRole}`,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const pendingNormOrd = ++runNormalSubIdx;
|
||||
const pendingRole = pendingCustomRole || '子代理';
|
||||
subItems.push({
|
||||
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
||||
index: pendingIndex,
|
||||
agentKind: 'subagent',
|
||||
agentOrdinal: pendingNormOrd,
|
||||
customRole: pendingCustomRole,
|
||||
badgeText: `子${pendingNormOrd}`,
|
||||
shortLabel: `子代理 #${pendingNormOrd}`,
|
||||
role: pendingRole,
|
||||
typeName: '',
|
||||
isRunning: true,
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
stepCount: 0,
|
||||
lastModifiedMs: rootFallbackMs,
|
||||
liveActivity: {
|
||||
phase: 'thinking',
|
||||
actionKey: 'starting',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '启动中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: mainLiveAct.startedAtMs || 0,
|
||||
signature: `spawning-sub:${pendingIndex}:${pendingRole}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const runningSubList = subItems.filter((s) => s.isRunning);
|
||||
const allRunningAreSwarm =
|
||||
runningSubList.length > 0 && runningSubList.every((s) => s.agentKind === 'swarm_worker');
|
||||
const resolvedMainActivity =
|
||||
mainLiveAct ||
|
||||
(runningSubList.length > 0
|
||||
? {
|
||||
phase: 'waiting',
|
||||
actionKey: 'waiting_subagent',
|
||||
actionKey: allRunningAreSwarm ? 'waiting_swarm' : 'waiting_subagent',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '等待子代理',
|
||||
label: allRunningAreSwarm ? '等待工蜂' : '等待子代理',
|
||||
detail: runningSubList.map((s) => s.customRole || s.role).join(', '),
|
||||
stepProgress: '',
|
||||
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
|
||||
@@ -1555,6 +1683,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
runningConversations.push({
|
||||
cascadeId: rootConv.cascadeId,
|
||||
title: rootConv.title || rootConv.cascadeId.slice(0, 8),
|
||||
...(rootConv.swarmTitle ? { swarmTitle: rootConv.swarmTitle } : {}),
|
||||
isCurrentSelected:
|
||||
Boolean(activeCascadeId) &&
|
||||
rootConv.cascadeId.toLowerCase() === String(activeCascadeId).toLowerCase(),
|
||||
@@ -1566,7 +1695,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0,
|
||||
mainActivity: resolvedMainActivity,
|
||||
subagentCount: subItems.length,
|
||||
swarmCount: runSwarmIdx,
|
||||
normalSubagentCount: runNormalSubIdx,
|
||||
sideQuestionCount: runSideIdx,
|
||||
runningSubagentCount: runningSubList.length,
|
||||
runningSwarmCount: runningSubList.filter((s) => s.agentKind === 'swarm_worker').length,
|
||||
subagents: subItems,
|
||||
modelShort: qStats.modelShort,
|
||||
modelUpstream: qStats.modelUpstream,
|
||||
@@ -1606,13 +1739,21 @@ export async function buildTelemetryPayloadInternal(
|
||||
const qStats = getConversationQuickStats(c);
|
||||
const rawSubs = Array.isArray(c.subagents) ? c.subagents : [];
|
||||
const runningSubCount = rawSubs.filter((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING').length;
|
||||
const cSwarmCount = Number(c.swarmCount ?? rawSubs.filter((s) => s.isSwarmWorker).length);
|
||||
const cSideCount = rawSubs.filter((s) => s.isSideQuestion).length;
|
||||
const cNormalSubCount = Math.max(0, rawSubs.length - cSwarmCount - cSideCount);
|
||||
return {
|
||||
cascadeId: c.cascadeId,
|
||||
title: c.title,
|
||||
...(c.swarmTitle ? { swarmTitle: c.swarmTitle } : {}),
|
||||
stepCount: c.stepCount,
|
||||
subagentCount: c.subagentCount || 0,
|
||||
swarmCount: cSwarmCount,
|
||||
normalSubagentCount: cNormalSubCount,
|
||||
sideQuestionCount: cSideCount,
|
||||
runningSubagentCount: runningSubCount,
|
||||
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
||||
...(rawSubs.length > 0 ? { memberCascadeIds: rawSubs.map((s) => s.cascadeId) } : {}),
|
||||
isRunning: c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0,
|
||||
status: c.status,
|
||||
lastModifiedTime: c.lastModifiedTime,
|
||||
@@ -1628,12 +1769,16 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeConversation: {
|
||||
cascadeId: activeCascadeId,
|
||||
title: activeConvSummary?.title || '当前会话',
|
||||
...(activeConvSummary?.swarmTitle ? { swarmTitle: activeConvSummary.swarmTitle } : {}),
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
liveActivity: mainAgentTelemetry.liveActivity || null,
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
swarmCount: swarmWorkerCount,
|
||||
normalSubagentCount: normalSubCount,
|
||||
sideQuestionCount,
|
||||
totalStepsAllAgents: subAgentTelemetries.length
|
||||
? allCombinedEnrichedSteps.length
|
||||
: enrichedActiveSteps.length,
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795018723250">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795024412108">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795018723250"></script>
|
||||
<script src="/app.js?v=1795024412108"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -11,7 +11,9 @@ import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentBadgeText,
|
||||
formatConversationMeta,
|
||||
normalizeClientUpdateMode,
|
||||
resolveHostRouteMatch,
|
||||
telemetryStore,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
@@ -19,16 +21,7 @@ import { uiStore } from '../../store/uiStore.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return t('header.convMetaWithSubs', {
|
||||
main: c.stepCount || 0,
|
||||
subs,
|
||||
total: c.totalStepCount || c.stepCount || 0,
|
||||
});
|
||||
}
|
||||
return t('header.convMetaSteps', { count: c.stepCount || 0 });
|
||||
return formatConversationMeta(c);
|
||||
}
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
@@ -106,10 +99,49 @@ export const TopSessionHeader = defineComponent({
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
let lastAppliedHostChildRouteId = '';
|
||||
|
||||
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||
function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) {
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (!currentCascadeId) return;
|
||||
|
||||
const selectedId = String(telSlice?.selectedConversationId || '').trim();
|
||||
const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim();
|
||||
const hostRouteLower = hostRouteId.toLowerCase();
|
||||
|
||||
if (!selectedId && hostRouteLower) {
|
||||
const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId);
|
||||
if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (lastAppliedHostChildRouteId !== hostRouteLower) {
|
||||
lastAppliedHostChildRouteId = hostRouteLower;
|
||||
const targetAgentId = routeMatch.childAgent.agentId;
|
||||
const uiSt = uiStore.getState();
|
||||
if (
|
||||
uiSt.selectedAgentScope !== targetAgentId ||
|
||||
uiSt.ctxInspectorAgentId !== targetAgentId
|
||||
) {
|
||||
uiStore.setState({
|
||||
selectedAgentScope: targetAgentId,
|
||||
ctxInspectorAgentId: targetAgentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
const uiSt = uiStore.getState();
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
}
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
return;
|
||||
}
|
||||
} else if (lastAppliedHostChildRouteId) {
|
||||
lastAppliedHostChildRouteId = '';
|
||||
}
|
||||
|
||||
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
const uiSt = uiStore.getState();
|
||||
@@ -133,34 +165,44 @@ export const TopSessionHeader = defineComponent({
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
const hostMatchedConv = hostRouteId
|
||||
? convs.find((c) => c.cascadeId === hostRouteId) ||
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null;
|
||||
const hostMatchedConv = routeMatch?.rootConv || null;
|
||||
const childRouteBadge =
|
||||
routeMatch?.isChildRoute && routeMatch.childAgent
|
||||
? formatAgentBadgeText(routeMatch.childAgent)
|
||||
: '';
|
||||
const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8);
|
||||
const hostDisplayTitle = childRouteBadge
|
||||
? `${hostBaseTitle} · ${childRouteBadge}`
|
||||
: hostBaseTitle;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? t('header.currentWindowNamed', {
|
||||
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
|
||||
title: hostDisplayTitle,
|
||||
})
|
||||
: convs[0]?.title
|
||||
? t('header.latestNamed', { title: convs[0].title })
|
||||
: t('header.followLatest');
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
stepCount: hostMatchedConv.stepCount,
|
||||
subagentCount: hostMatchedConv.subagentCount,
|
||||
totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents,
|
||||
})
|
||||
? formatConvOptionMeta(hostMatchedConv)
|
||||
: ''
|
||||
: convs[0]
|
||||
? formatConvOptionMeta(convs[0])
|
||||
: '';
|
||||
const options = [
|
||||
{ value: '', label: defaultOptLabel, meta: defaultOptMeta },
|
||||
{
|
||||
value: '',
|
||||
label: defaultOptLabel,
|
||||
meta: defaultOptMeta,
|
||||
...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}),
|
||||
},
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: formatConvOptionMeta(c),
|
||||
...(c.swarmTitle && c.swarmTitle !== c.title
|
||||
? { title: `${c.title || c.cascadeId.slice(0, 8)} · ${c.swarmTitle}` }
|
||||
: {}),
|
||||
})),
|
||||
];
|
||||
const lockedId = telSt.selectedConversationId;
|
||||
@@ -170,13 +212,7 @@ export const TopSessionHeader = defineComponent({
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: t('header.lockedMeta');
|
||||
const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta');
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
@@ -283,7 +319,7 @@ export const TopSessionHeader = defineComponent({
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
(slice) => {
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||
syncSessionScopeOnCascadeChange(slice.telemetry, slice);
|
||||
renderHeaderState();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -2297,16 +2297,26 @@ export function mountWindowOverlay() {
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||
}
|
||||
|
||||
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
||||
function renderMultiRunningPanel(
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
hostRouteConversationId,
|
||||
runningSwarmCount = 0
|
||||
) {
|
||||
if (!multiOpen || document.hidden) {
|
||||
multiRunningWidget.refs.pauseTicker();
|
||||
return;
|
||||
}
|
||||
const isPureSwarm = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
patchText(
|
||||
multiRunningMetaEl,
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('multi.metaWithSubs', { main: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarm ? 'multi.metaWithSwarm' : 'multi.metaWithSubs', {
|
||||
main: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('multi.metaMainOnly', { main: runningCount })
|
||||
: t('multi.allIdle')
|
||||
);
|
||||
@@ -2377,13 +2387,19 @@ export function mountWindowOverlay() {
|
||||
ctxAgent,
|
||||
aggregated,
|
||||
});
|
||||
const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } =
|
||||
resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
const {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
} = resolveMultiSessionCapsuleState(telemetry, {
|
||||
agents,
|
||||
aggregated,
|
||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||
contextUsedPct: slotCtx.usedPct,
|
||||
});
|
||||
|
||||
patchClasses(multiBtn, {
|
||||
'is-running': runningCount > 0 && !hasWaiting,
|
||||
@@ -2395,7 +2411,8 @@ export function mountWindowOverlay() {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
telSt.hostRouteConversationId
|
||||
telSt.hostRouteConversationId,
|
||||
runningSwarmCount
|
||||
);
|
||||
|
||||
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||
|
||||
@@ -94,14 +94,29 @@ export function resolveMultiSessionCapsuleState(
|
||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
||||
0
|
||||
);
|
||||
const runningSwarmCount = rawRunningList.reduce(
|
||||
(acc, item) => acc + Number(item.runningSwarmCount || 0),
|
||||
0
|
||||
);
|
||||
const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount;
|
||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
||||
const multiBtnText =
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
||||
? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', {
|
||||
count: runningCount,
|
||||
subs: runningSubCount,
|
||||
})
|
||||
: t('capsule.multiRunning', { count: runningCount })
|
||||
: t('capsule.multiZero');
|
||||
return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText };
|
||||
return {
|
||||
rawRunningList,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
runningSwarmCount,
|
||||
hasWaiting,
|
||||
multiBtnText,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,43 +40,68 @@ export function buildFallbackRunningConversations(
|
||||
}
|
||||
const activeConv = data.activeConversation || {};
|
||||
if (!activeConv.isRunning && !aggregated?.isRunning) return [];
|
||||
const childAgents = (agents || []).filter((a) => !a.isMain);
|
||||
const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker');
|
||||
return [
|
||||
{
|
||||
cascadeId: activeConv.cascadeId || 'current',
|
||||
title: activeConv.title || t('live.currentSession'),
|
||||
...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}),
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: Boolean(activeConv.isRunning),
|
||||
isRunning: true,
|
||||
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
|
||||
subagentCount: Math.max(0, (agents?.length || 1) - 1),
|
||||
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
|
||||
subagentCount: childAgents.length,
|
||||
swarmCount: swarmChildren.length,
|
||||
runningSubagentCount: childAgents.filter((a) => a.isRunning).length,
|
||||
runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length,
|
||||
...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}),
|
||||
...(contextUsedPct !== undefined ? { contextUsedPct } : {}),
|
||||
subagents: (agents || [])
|
||||
.filter((a) => !a.isMain)
|
||||
.map((s, idx) => ({
|
||||
subagents: childAgents.map((s, idx) => {
|
||||
const isSwarmW = s.agentKind === 'swarm_worker';
|
||||
const isKilled = Boolean(s.swarmState === 'killed');
|
||||
return {
|
||||
cascadeId: s.cascadeId || s.agentId,
|
||||
index: s.index || idx + 1,
|
||||
agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'),
|
||||
agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
agentOrdinal:
|
||||
s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||
customRole: s.customRole,
|
||||
...(s.swarmState ? { swarmState: s.swarmState } : {}),
|
||||
...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}),
|
||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
shortLabel:
|
||||
s.shortLabel ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
role:
|
||||
s.role ||
|
||||
`${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`,
|
||||
isRunning: Boolean(s.isRunning),
|
||||
stepCount: Number(s.stepCount || 0),
|
||||
lastModifiedMs: s.lastModifiedMs || 0,
|
||||
liveActivity: s.liveActivity || {
|
||||
phase: s.isRunning ? 'thinking' : 'done',
|
||||
actionKey: s.isRunning ? 'thinking' : 'done',
|
||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||
phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done',
|
||||
actionKey: s.isRunning
|
||||
? 'thinking'
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? 'swarm_killed'
|
||||
: 'swarm_waiting'
|
||||
: 'done',
|
||||
label: s.isRunning
|
||||
? t('live.thinking')
|
||||
: isSwarmW
|
||||
? isKilled
|
||||
? t('live.killed')
|
||||
: t('live.waiting')
|
||||
: t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: s.lastModifiedMs || 0,
|
||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||
signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -362,14 +387,17 @@ export const LiveActivityWidget = defineComponent({
|
||||
const isHere =
|
||||
showSessionExtras &&
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
`${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
@@ -416,7 +444,10 @@ export const LiveActivityWidget = defineComponent({
|
||||
if (showSessionExtras && refs.hereTagEl && refs.metricsEl) {
|
||||
const isHere =
|
||||
Boolean(hostRouteLower) &&
|
||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||
(String(item.cascadeId || '').toLowerCase() === hostRouteLower ||
|
||||
(item.subagents || []).some(
|
||||
(s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower
|
||||
));
|
||||
patchText(refs.hereTagEl, t('multi.hereTag'));
|
||||
patchAttr(refs.hereTagEl, 'hidden', !isHere);
|
||||
|
||||
@@ -437,6 +468,11 @@ export const LiveActivityWidget = defineComponent({
|
||||
}
|
||||
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const swarmCount = Number(
|
||||
item.swarmCount ??
|
||||
(item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length
|
||||
);
|
||||
const isPureSwarm = subCount > 0 && swarmCount === subCount;
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = resolveIsExpanded(item);
|
||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||
@@ -446,8 +482,15 @@ export const LiveActivityWidget = defineComponent({
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
const toggleText =
|
||||
runSubCount > 0
|
||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
||||
? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', {
|
||||
run: runSubCount,
|
||||
total: subCount,
|
||||
arrow,
|
||||
})
|
||||
: t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', {
|
||||
total: subCount,
|
||||
arrow,
|
||||
});
|
||||
patchText(refs.subToggleBtn, toggleText);
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
||||
if (interactive) {
|
||||
@@ -495,11 +538,28 @@ export const LiveActivityWidget = defineComponent({
|
||||
const showSubs = subCount > 0 && isExpanded;
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
if (showSubs) {
|
||||
const subItems = item.subagents || [];
|
||||
const rawSubItems = item.subagents || [];
|
||||
const getSubSortRank = (s) => {
|
||||
if (s?.isRunning) return 0;
|
||||
if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
};
|
||||
const subItems =
|
||||
rawSubItems.length > 1
|
||||
? rawSubItems
|
||||
.slice()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
getSubSortRank(a) - getSubSortRank(b) ||
|
||||
Number(a?.index || 0) - Number(b?.index || 0)
|
||||
)
|
||||
: rawSubItems;
|
||||
patchKeyedList(refs.subListEl, subItems, {
|
||||
keyFn: (sub) => sub.cascadeId,
|
||||
sigFn: (sub) =>
|
||||
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
`${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
createRow: createLiveSubRow,
|
||||
updateRow: (subRefs, sub) => {
|
||||
const subAct = sub.liveActivity || {
|
||||
@@ -510,7 +570,17 @@ export const LiveActivityWidget = defineComponent({
|
||||
stepProgress: '',
|
||||
startedAtMs: sub.lastModifiedMs || 0,
|
||||
};
|
||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
||||
const isWaitingSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting');
|
||||
const isKilledSub =
|
||||
!sub.isRunning &&
|
||||
(sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed');
|
||||
patchClasses(subRefs.rowEl, {
|
||||
'is-done': !sub.isRunning && !isWaitingSub,
|
||||
'is-waiting-sub': isWaitingSub,
|
||||
'is-killed-sub': isKilledSub,
|
||||
});
|
||||
|
||||
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
|
||||
const subBadgeText = formatAgentBadgeText({
|
||||
@@ -524,22 +594,33 @@ export const LiveActivityWidget = defineComponent({
|
||||
const fallbackRole =
|
||||
sub.agentKind === 'side_question' || sub.isSideQuestion
|
||||
? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
: sub.agentKind === 'swarm_worker'
|
||||
? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`
|
||||
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||
const roleText =
|
||||
sub.customRole !== undefined
|
||||
? sub.customRole || fallbackRole
|
||||
: sub.role || sub.shortLabel || fallbackRole;
|
||||
patchText(subRefs.subRole, roleText);
|
||||
|
||||
const idleFallbackKey = isKilledSub
|
||||
? 'live.killed'
|
||||
: isWaitingSub
|
||||
? 'live.waiting'
|
||||
: 'live.done';
|
||||
const subLabel = sub.isRunning
|
||||
? formatLiveActivityLabel(subAct, 'live.running')
|
||||
: formatLiveActivityLabel(subAct, 'live.done');
|
||||
: formatLiveActivityLabel(subAct, idleFallbackKey);
|
||||
const subDetail = formatLiveActivityDetail(subAct);
|
||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||
const summaryStr = showSessionExtras
|
||||
? sub.isRunning
|
||||
? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}`
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isKilledSub
|
||||
? t('live.killedWithSteps', { steps: sub.stepCount || 0 })
|
||||
: isWaitingSub
|
||||
? t('live.waitingWithSteps', { steps: sub.stepCount || 0 })
|
||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||
: [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' ');
|
||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||
patchText(subRefs.subSummary, summaryStr);
|
||||
|
||||
@@ -496,21 +496,48 @@ export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
return `badge-sub-${slot}`;
|
||||
}
|
||||
|
||||
function resolveStructuredAgentKind(agent) {
|
||||
if (!agent) return 'main';
|
||||
if (agent.agentKind) return agent.agentKind;
|
||||
if (agent.isMain) return 'main';
|
||||
if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question';
|
||||
if (
|
||||
agent.typeName === 'worker' ||
|
||||
agent.typeName === 'swarm_worker' ||
|
||||
/^Swarm\s+Worker\s*\(/i.test(String(agent.role || ''))
|
||||
) {
|
||||
return 'swarm_worker';
|
||||
}
|
||||
return 'subagent';
|
||||
}
|
||||
|
||||
function normalizeSwarmMemberHandle(rawText) {
|
||||
const trimmed = String(rawText || '').trim();
|
||||
if (!trimmed) return '';
|
||||
const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
|
||||
const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim();
|
||||
if (
|
||||
!inner ||
|
||||
inner === '蜂群' ||
|
||||
inner === '工蜂' ||
|
||||
inner.toLowerCase() === 'swarm' ||
|
||||
inner.toLowerCase() === 'worker' ||
|
||||
inner.toLowerCase() === 'swarm worker'
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
return `@${inner}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||
*
|
||||
* @param {object|null|undefined} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAgentBadgeText(agent) {
|
||||
if (!agent) return t('fmt.mainBadge');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAllShort');
|
||||
if (kind === 'main') return t('fmt.mainBadge');
|
||||
if (kind === 'side_question') {
|
||||
@@ -519,6 +546,12 @@ export function formatAgentBadgeText(agent) {
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.sideBadgeShort');
|
||||
}
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.swarmBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
return t('fmt.swarmBadgeShort');
|
||||
}
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
if (ord > 0) return t('fmt.subBadge', { index: ord });
|
||||
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||
@@ -533,13 +566,7 @@ export function formatAgentBadgeText(agent) {
|
||||
*/
|
||||
export function formatAgentLabel(agent) {
|
||||
if (!agent) return t('fmt.mainAgent');
|
||||
const kind =
|
||||
agent.agentKind ||
|
||||
(agent.isMain
|
||||
? 'main'
|
||||
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||
? 'side_question'
|
||||
: 'subagent');
|
||||
const kind = resolveStructuredAgentKind(agent);
|
||||
if (kind === 'all') return t('header.scopeAll');
|
||||
if (kind === 'main') return t('fmt.mainAgent');
|
||||
|
||||
@@ -560,6 +587,20 @@ export function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
if (kind === 'swarm_worker') {
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent');
|
||||
const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || '');
|
||||
if (!handle) return baseLabel;
|
||||
let auxSuffix = '';
|
||||
if (/^@monitor(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmMonitorHint')})`;
|
||||
} else if (/^@narrator(?:-\d+)?$/i.test(handle)) {
|
||||
auxSuffix = ` (${t('fmt.swarmNarratorHint')})`;
|
||||
}
|
||||
return `${baseLabel} · ${handle}${auxSuffix}`;
|
||||
}
|
||||
|
||||
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
|
||||
const isGeneric =
|
||||
@@ -571,6 +612,31 @@ export function formatAgentLabel(agent) {
|
||||
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。
|
||||
*
|
||||
* @param {object|null|undefined} conv
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatConversationMeta(conv) {
|
||||
if (!conv) return '';
|
||||
const main = Number(conv.stepCount || 0);
|
||||
const totalSubs = Number(conv.subagentCount || 0);
|
||||
const swarm = Number(conv.swarmCount || 0);
|
||||
const otherSubs = Math.max(0, totalSubs - swarm);
|
||||
const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main);
|
||||
if (swarm > 0 && otherSubs > 0) {
|
||||
return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total });
|
||||
}
|
||||
if (swarm > 0) {
|
||||
return t('header.convMetaWithSwarm', { main, swarm, total });
|
||||
}
|
||||
if (totalSubs > 0) {
|
||||
return t('header.convMetaWithSubs', { main, subs: totalSubs, total });
|
||||
}
|
||||
return t('header.convMetaSteps', { count: main });
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
|
||||
*
|
||||
|
||||
@@ -17,6 +17,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'header.lockedSession': 'Pinned Session ({id})',
|
||||
'header.lockedMeta': 'Pinned',
|
||||
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
|
||||
'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)',
|
||||
'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)',
|
||||
'header.convMetaSteps': '{count} steps',
|
||||
'header.hasUpdate': 'Update',
|
||||
'header.upgradeToVer': 'Update v{ver}',
|
||||
@@ -55,6 +57,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.subAgent': 'Subagent',
|
||||
'fmt.subBadge': 'S{index}',
|
||||
'fmt.subBadgeShort': 'Sub',
|
||||
'fmt.swarmAgent': 'Swarm',
|
||||
'fmt.swarmBadge': 'W{index}',
|
||||
'fmt.swarmBadgeShort': 'Swarm',
|
||||
'fmt.swarmMonitorHint': 'Monitor',
|
||||
'fmt.swarmNarratorHint': 'Narrator',
|
||||
'fmt.sideQuestion': 'Side Question',
|
||||
'fmt.sideBadge': 'Q{index}',
|
||||
'fmt.sideBadgeShort': 'Q',
|
||||
@@ -68,6 +75,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'capsule.multiZero': '0 active',
|
||||
'capsule.multiRunning': '{count} active',
|
||||
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
|
||||
'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm',
|
||||
'capsule.tpsRunning': 'Running',
|
||||
'capsule.tpsIdle': 'Idle',
|
||||
'capsule.quotaLeft': '{pct}% left',
|
||||
@@ -88,6 +96,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'multi.empty': 'No active running sessions',
|
||||
'multi.allIdle': 'All idle',
|
||||
'multi.metaWithSubs': '{main} main · {subs} subagents active',
|
||||
'multi.metaWithSwarm': '{main} main · {subs} swarm active',
|
||||
'multi.metaMainOnly': '{main} sessions active',
|
||||
'multi.hereTag': 'Here',
|
||||
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
|
||||
@@ -184,10 +193,16 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.thinking': 'Thinking',
|
||||
'live.generating': 'Generating',
|
||||
'live.running': 'Running',
|
||||
'live.waiting': 'Waiting',
|
||||
'live.killed': 'Killed',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
'live.waitingWithSteps': 'Waiting ({steps} steps)',
|
||||
'live.killedWithSteps': 'Killed ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': 'Subagents ({total}) {arrow}',
|
||||
'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}',
|
||||
'live.swarmToggleIdle': 'Swarm ({total}) {arrow}',
|
||||
'live.subCollapseTitle': 'Collapse subagent list',
|
||||
'live.subExpandTitle': 'Expand subagent activity list',
|
||||
|
||||
@@ -558,6 +573,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.invoke_subagent': 'Invoke Subagent',
|
||||
'live.act.send_message': 'Message Subagent',
|
||||
'live.act.manage_subagents': 'Manage Subagents',
|
||||
'live.act.swarm_add': 'Spawn Worker',
|
||||
'live.act.swarm_title': 'Name Swarm',
|
||||
'live.act.swarm_kill': 'Kill Worker',
|
||||
'live.act.swarm_model': 'Switch Worker Model',
|
||||
'live.act.swarm_channel': 'Swarm Channel',
|
||||
'live.act.swarm_status': 'Check Swarm',
|
||||
'live.act.post_message': 'Post to Board',
|
||||
'live.act.read_board': 'Read Board',
|
||||
'live.act.swarm_wait': 'Parked on Board',
|
||||
'live.act.manage_task': 'Manage Task',
|
||||
'live.act.schedule': 'Schedule Task',
|
||||
'live.act.ask_question': 'Waiting for User Choice',
|
||||
@@ -568,6 +592,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'live.act.compacting': 'Compacting Context',
|
||||
'live.act.responding': 'Responding',
|
||||
'live.act.waiting_subagent': 'Waiting for Subagent',
|
||||
'live.act.waiting_swarm': 'Waiting for Swarm',
|
||||
'live.act.swarm_waiting': 'Waiting',
|
||||
'live.act.swarm_killed': 'Killed',
|
||||
'live.act.starting': 'Starting',
|
||||
'live.act.done': 'Completed',
|
||||
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
|
||||
|
||||
@@ -17,6 +17,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'header.lockedSession': '已锁定会话 ({id})',
|
||||
'header.lockedMeta': '已锁定',
|
||||
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
|
||||
'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)',
|
||||
'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)',
|
||||
'header.convMetaSteps': '{count}步',
|
||||
'header.hasUpdate': '有新版本',
|
||||
'header.upgradeToVer': '升级 v{ver}',
|
||||
@@ -55,6 +57,11 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.subAgent': '子代理',
|
||||
'fmt.subBadge': '子{index}',
|
||||
'fmt.subBadgeShort': '子',
|
||||
'fmt.swarmAgent': '蜂群',
|
||||
'fmt.swarmBadge': '蜂{index}',
|
||||
'fmt.swarmBadgeShort': '蜂',
|
||||
'fmt.swarmMonitorHint': '巡检',
|
||||
'fmt.swarmNarratorHint': '旁白',
|
||||
'fmt.sideQuestion': '旁路提问',
|
||||
'fmt.sideBadge': '旁{index}',
|
||||
'fmt.sideBadgeShort': '旁',
|
||||
@@ -68,6 +75,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'capsule.multiZero': '0 运行中',
|
||||
'capsule.multiRunning': '{count} 运行中',
|
||||
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
|
||||
'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂',
|
||||
'capsule.tpsRunning': '生成中',
|
||||
'capsule.tpsIdle': '待命',
|
||||
'capsule.quotaLeft': '余 {pct}%',
|
||||
@@ -88,6 +96,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'multi.empty': '当前暂无在线运行的会话',
|
||||
'multi.allIdle': '全部待命',
|
||||
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
|
||||
'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中',
|
||||
'multi.metaMainOnly': '{main} 个会话运行中',
|
||||
'multi.hereTag': '本窗',
|
||||
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
|
||||
@@ -184,10 +193,16 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.thinking': '推理中',
|
||||
'live.generating': '生成中',
|
||||
'live.running': '运行中',
|
||||
'live.waiting': '待命中',
|
||||
'live.killed': '已终止',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
'live.waitingWithSteps': '待命中 ({steps} 步)',
|
||||
'live.killedWithSteps': '已终止 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': '子代理 ({total}) {arrow}',
|
||||
'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}',
|
||||
'live.swarmToggleIdle': '蜂群 ({total}) {arrow}',
|
||||
'live.subCollapseTitle': '点击收起子代理列表',
|
||||
'live.subExpandTitle': '点击展开查看子代理缩略状态',
|
||||
|
||||
@@ -558,6 +573,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.invoke_subagent': '调用子代理',
|
||||
'live.act.send_message': '通信子代理',
|
||||
'live.act.manage_subagents': '管理子代理',
|
||||
'live.act.swarm_add': '派生工蜂',
|
||||
'live.act.swarm_title': '命名蜂群',
|
||||
'live.act.swarm_kill': '终止工蜂',
|
||||
'live.act.swarm_model': '切换工蜂模型',
|
||||
'live.act.swarm_channel': '蜂群频道',
|
||||
'live.act.swarm_status': '巡检蜂群',
|
||||
'live.act.post_message': '发布看板',
|
||||
'live.act.read_board': '读取看板',
|
||||
'live.act.swarm_wait': '看板待命',
|
||||
'live.act.manage_task': '后台任务',
|
||||
'live.act.schedule': '定时任务',
|
||||
'live.act.ask_question': '等待用户选择',
|
||||
@@ -568,6 +592,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'live.act.compacting': '上下文压缩',
|
||||
'live.act.responding': '正在输出回复',
|
||||
'live.act.waiting_subagent': '等待子代理',
|
||||
'live.act.waiting_swarm': '等待工蜂',
|
||||
'live.act.swarm_waiting': '待命中',
|
||||
'live.act.swarm_killed': '已终止',
|
||||
'live.act.starting': '启动中',
|
||||
'live.act.done': '已完成',
|
||||
'live.act.awaitingApproval': '等待确认 · {label}',
|
||||
|
||||
@@ -8,6 +8,7 @@ import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../c
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
formatConversationMeta,
|
||||
formatLiveActivityDetail,
|
||||
formatLiveActivityLabel,
|
||||
getAgentBadgeClass,
|
||||
@@ -299,6 +300,8 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||
if ((pAct?.swarmCount || 0) !== (nAct?.swarmCount || 0)) return false;
|
||||
if ((pAct?.swarmTitle || '') !== (nAct?.swarmTitle || '')) return false;
|
||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
if (
|
||||
@@ -375,6 +378,9 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
const na = nAgents[i];
|
||||
if (
|
||||
pa?.agentId !== na?.agentId ||
|
||||
pa?.agentKind !== na?.agentKind ||
|
||||
pa?.agentOrdinal !== na?.agentOrdinal ||
|
||||
(pa?.swarmState || '') !== (na?.swarmState || '') ||
|
||||
pa?.role !== na?.role ||
|
||||
pa?.stepCount !== na?.stepCount ||
|
||||
pa?.isRunning !== na?.isRunning ||
|
||||
@@ -660,6 +666,8 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
pConvs[i]?.status !== nConvs[i]?.status ||
|
||||
pConvs[i]?.stepCount !== nConvs[i]?.stepCount ||
|
||||
pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount ||
|
||||
(pConvs[i]?.swarmCount || 0) !== (nConvs[i]?.swarmCount || 0) ||
|
||||
(pConvs[i]?.swarmTitle || '') !== (nConvs[i]?.swarmTitle || '') ||
|
||||
pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount
|
||||
) {
|
||||
return false;
|
||||
@@ -678,7 +686,9 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
pr?.isCurrentSelected !== nr?.isCurrentSelected ||
|
||||
pr?.isMainRunning !== nr?.isMainRunning ||
|
||||
pr?.subagentCount !== nr?.subagentCount ||
|
||||
(pr?.swarmCount || 0) !== (nr?.swarmCount || 0) ||
|
||||
pr?.runningSubagentCount !== nr?.runningSubagentCount ||
|
||||
(pr?.runningSwarmCount || 0) !== (nr?.runningSwarmCount || 0) ||
|
||||
pr?.mainActivity?.signature !== nr?.mainActivity?.signature ||
|
||||
pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs
|
||||
) {
|
||||
@@ -690,6 +700,8 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
for (let j = 0; j < pSubs.length; j++) {
|
||||
if (
|
||||
pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId ||
|
||||
pSubs[j]?.agentKind !== nSubs[j]?.agentKind ||
|
||||
(pSubs[j]?.swarmState || '') !== (nSubs[j]?.swarmState || '') ||
|
||||
pSubs[j]?.role !== nSubs[j]?.role ||
|
||||
pSubs[j]?.isRunning !== nSubs[j]?.isRunning ||
|
||||
pSubs[j]?.stepCount !== nSubs[j]?.stepCount ||
|
||||
@@ -1087,11 +1099,60 @@ export function stopAsyncTelemetryLoop() {
|
||||
export {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
formatConversationMeta,
|
||||
formatLiveActivityDetail,
|
||||
formatLiveActivityLabel,
|
||||
getAgentBadgeClass,
|
||||
};
|
||||
|
||||
/**
|
||||
* 在遥测快照中解析宿主当前路由会话 ID(兼容顶层主会话 ID 与子代理/蜂群工蜂 ID)。
|
||||
*
|
||||
* @param {object|null|undefined} telemetry
|
||||
* @param {string} rawRouteId
|
||||
* @returns {{ rootConv: object|null, childAgent: object|null, isChildRoute: boolean } | null}
|
||||
*/
|
||||
export function resolveHostRouteMatch(telemetry, rawRouteId) {
|
||||
const routeLower = String(rawRouteId || '').trim().toLowerCase();
|
||||
if (!routeLower || !telemetry) return null;
|
||||
const convs = Array.isArray(telemetry.conversations) ? telemetry.conversations : [];
|
||||
const actConv = telemetry.activeConversation || null;
|
||||
|
||||
const directRoot =
|
||||
convs.find((c) => String(c?.cascadeId || '').toLowerCase() === routeLower) ||
|
||||
(String(actConv?.cascadeId || '').toLowerCase() === routeLower ? actConv : null);
|
||||
if (directRoot) {
|
||||
return { rootConv: directRoot, childAgent: null, isChildRoute: false };
|
||||
}
|
||||
|
||||
const activeChild = (actConv?.agents || []).find(
|
||||
(a) =>
|
||||
!a?.isMain &&
|
||||
(String(a?.cascadeId || '').toLowerCase() === routeLower ||
|
||||
String(a?.agentId || '').toLowerCase() === routeLower)
|
||||
);
|
||||
if (activeChild) {
|
||||
const parentInList = convs.find(
|
||||
(c) => String(c?.cascadeId || '').toLowerCase() === String(actConv?.cascadeId || '').toLowerCase()
|
||||
);
|
||||
return {
|
||||
rootConv: parentInList || actConv,
|
||||
childAgent: activeChild,
|
||||
isChildRoute: true,
|
||||
};
|
||||
}
|
||||
|
||||
const memberParent = convs.find(
|
||||
(c) =>
|
||||
Array.isArray(c?.memberCascadeIds) &&
|
||||
c.memberCascadeIds.some((id) => String(id || '').toLowerCase() === routeLower)
|
||||
);
|
||||
if (memberParent) {
|
||||
return { rootConv: memberParent, childAgent: null, isChildRoute: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
|
||||
* 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。
|
||||
|
||||
@@ -265,10 +265,29 @@
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-top: 9px;
|
||||
padding-right: 4px;
|
||||
margin-top: 3px;
|
||||
margin-left: 18px;
|
||||
border-top: 1px dashed var(--border-hairline);
|
||||
min-width: 0;
|
||||
max-height: 196px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border-subtle) transparent;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar-thumb {
|
||||
background: var(--border-subtle);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.live-sub-row {
|
||||
@@ -286,6 +305,14 @@
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.live-sub-row.is-waiting-sub {
|
||||
opacity: 0.86;
|
||||
}
|
||||
|
||||
.live-sub-row.is-killed-sub {
|
||||
opacity: 0.56;
|
||||
}
|
||||
|
||||
.live-sub-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1512,10 +1512,29 @@ html[data-standalone="true"] .app-shell {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-top: 9px;
|
||||
padding-right: 4px;
|
||||
margin-top: 3px;
|
||||
margin-left: 18px;
|
||||
border-top: 1px dashed var(--border-hairline);
|
||||
min-width: 0;
|
||||
max-height: 196px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border-subtle) transparent;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.live-sub-list::-webkit-scrollbar-thumb {
|
||||
background: var(--border-subtle);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.live-sub-row {
|
||||
@@ -1533,6 +1552,14 @@ html[data-standalone="true"] .app-shell {
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.live-sub-row.is-waiting-sub {
|
||||
opacity: 0.86;
|
||||
}
|
||||
|
||||
.live-sub-row.is-killed-sub {
|
||||
opacity: 0.56;
|
||||
}
|
||||
|
||||
.live-sub-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -59,6 +59,7 @@ export function backendHarness({
|
||||
cache={},
|
||||
deepStats=null,
|
||||
transcripts={},
|
||||
swarmMembers={},
|
||||
diskDirs={},
|
||||
settings={},
|
||||
trajectories={},
|
||||
@@ -82,7 +83,7 @@ export function backendHarness({
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1};
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,swarmMembers,swarmMembersMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID,
|
||||
...(clock ? { Date: class extends Date {
|
||||
@@ -110,6 +111,10 @@ export function backendHarness({
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||
return Boolean(m && state.transcripts?.[m[1]]);
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
return Boolean(m && state.swarmMembers?.[m[1]]);
|
||||
}
|
||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText);
|
||||
if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText);
|
||||
if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true;
|
||||
@@ -131,6 +136,14 @@ export function backendHarness({
|
||||
return {mtimeMs:state.transcriptMtimeMs,size:Buffer.byteLength(text,'utf8')};
|
||||
}
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
const obj = m && state.swarmMembers?.[m[1]];
|
||||
if (obj) {
|
||||
const text = typeof obj === 'string' ? obj : JSON.stringify(obj);
|
||||
return {mtimeMs:state.swarmMembersMtimeMs,size:Buffer.byteLength(text,'utf8')};
|
||||
}
|
||||
}
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json') && state.deepStats) {
|
||||
return {mtimeMs:state.deepStatsMtimeMs,size:JSON.stringify(state.deepStats).length};
|
||||
}
|
||||
@@ -143,6 +156,11 @@ export function backendHarness({
|
||||
const lines = m && state.transcripts?.[m[1]];
|
||||
return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || '');
|
||||
}
|
||||
if (norm.endsWith('/.system_generated/swarm/members.json')) {
|
||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i);
|
||||
const obj = m && state.swarmMembers?.[m[1]];
|
||||
return typeof obj === 'string' ? obj : JSON.stringify(obj || {});
|
||||
}
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(state.settings);
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -679,6 +679,78 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
return Boolean(step.userInput && typeof step.userInput === 'object');
|
||||
};
|
||||
|
||||
const hasHumanUserTurn = rawSteps.some(isUserTurnBoundary);
|
||||
|
||||
const isSystemWakeupBoundary = (step) => {
|
||||
if (hasHumanUserTurn || !step || typeof step !== 'object') return false;
|
||||
if (isCheckpointStep(step)) return false;
|
||||
const t = String(step.type || '').trim().toUpperCase();
|
||||
if (t !== 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && t !== 'SYSTEM_MESSAGE') {
|
||||
return false;
|
||||
}
|
||||
const rawMsg = String(step?.systemMessage?.message || step?.content || '').trim();
|
||||
const withoutSummary = rawMsg
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.trim();
|
||||
if (!withoutSummary || /BROWSER_HOST_FACTS/i.test(withoutSummary)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
const extractSystemWakeupInfo = (step) => {
|
||||
let raw = String(step?.systemMessage?.message || step?.content || '').trim();
|
||||
const sysMatches = [...raw.matchAll(/<SYSTEM_MESSAGE>([\s\S]*?)<\/SYSTEM_MESSAGE>/gi)];
|
||||
if (sysMatches.length > 0) {
|
||||
raw = sysMatches[sysMatches.length - 1][1].trim();
|
||||
} else {
|
||||
raw = raw.replace(/^The following is a <SYSTEM_MESSAGE>[\s\S]*?<SYSTEM_MESSAGE>/i, '').replace(/<\/SYSTEM_MESSAGE>\s*$/i, '').trim();
|
||||
}
|
||||
raw = raw.replace(/^\[Message\]\s+timestamp=\S+\s+sender=\S+\s+priority=\S+\s+content=/i, '').trim();
|
||||
|
||||
const doorbellMatch = raw.match(/^\[swarm\]\s+new board message\s+#(\d+)\s*$/i);
|
||||
if (doorbellMatch) {
|
||||
const tag = `[swarm] #${doorbellMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true };
|
||||
}
|
||||
|
||||
const assignMatch = raw.match(
|
||||
/^You have just started\.\s*Your assignment\s*\(recorded on the board as #(\d+)\s+for\s+@?([^\s):]+)\)\s*:\s*([\s\S]*)$/i
|
||||
);
|
||||
if (assignMatch) {
|
||||
const seq = assignMatch[1];
|
||||
const member = assignMatch[2];
|
||||
const bodyLines = String(assignMatch[3] || '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.filter(Boolean);
|
||||
const bodyPreview = bodyLines.join(' ');
|
||||
const full = bodyPreview ? `#${seq} @${member} · ${bodyPreview}` : `#${seq} @${member}`;
|
||||
const cleanText = full.length > 180 ? `${full.slice(0, 179)}…` : full;
|
||||
return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false };
|
||||
}
|
||||
|
||||
const boardDeltaMatch = raw.match(
|
||||
/^\[board\]\s+the latest message is #(\d+)\s*\(you have read up to #(\d+)\)/i
|
||||
);
|
||||
if (boardDeltaMatch) {
|
||||
const tag = `[board] #${boardDeltaMatch[2]} -> #${boardDeltaMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true };
|
||||
}
|
||||
|
||||
const monitorTickMatch = raw.match(/^\[monitor\]\s+tick:[^(]*\(iteration\s+(\d+)\)\s*$/i);
|
||||
if (monitorTickMatch) {
|
||||
const tag = `[monitor] tick #${monitorTickMatch[1]}`;
|
||||
return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: false };
|
||||
}
|
||||
|
||||
const cleaned = raw
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned;
|
||||
return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false };
|
||||
};
|
||||
|
||||
const extractUserTurnInfo = (step) => {
|
||||
const ui = step?.userInput;
|
||||
let raw = '';
|
||||
@@ -717,15 +789,26 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
};
|
||||
|
||||
let pendingTurnCleanPrompts = [];
|
||||
let pendingTurnDoorbellOnly = false;
|
||||
rawSteps.forEach((s, index) => {
|
||||
if (isUserTurnBoundary(s)) {
|
||||
const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s);
|
||||
const isHumanBoundary = isUserTurnBoundary(s);
|
||||
const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s);
|
||||
if (isHumanBoundary || isWakeupBoundary) {
|
||||
const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary
|
||||
? extractUserTurnInfo(s)
|
||||
: extractSystemWakeupInfo(s);
|
||||
if (!hasUnconsumedTurn) {
|
||||
hasUnconsumedTurn = true;
|
||||
pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
|
||||
pendingTurnCleanPrompts = cleanText ? [cleanText] : [];
|
||||
pendingTurnHasMedia = hasMedia;
|
||||
} else {
|
||||
pendingTurnDoorbellOnly = Boolean(isWakeupBoundary && isDoorbellOnly);
|
||||
} else if (isWakeupBoundary && pendingTurnDoorbellOnly && !isDoorbellOnly && cleanText) {
|
||||
// 合并连续唤醒步时,用紧随其后的真实简报/任务正文覆盖前置的纯 #seq 门铃提示
|
||||
pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
|
||||
pendingTurnCleanPrompts = [cleanText];
|
||||
pendingTurnDoorbellOnly = false;
|
||||
} else if (!(isWakeupBoundary && isDoorbellOnly && !pendingTurnDoorbellOnly)) {
|
||||
if (
|
||||
legacyPrompt &&
|
||||
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt
|
||||
@@ -769,6 +852,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
pendingTurnPrompts = [];
|
||||
pendingTurnCleanPrompts = [];
|
||||
pendingTurnHasMedia = false;
|
||||
pendingTurnDoorbellOnly = false;
|
||||
}
|
||||
|
||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||
@@ -1845,6 +1929,144 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'swarm') {
|
||||
const action = pickField(['action', 'Action']).toLowerCase();
|
||||
const memberName = pickField(['name', 'Name']).replace(/^@+/, '').trim();
|
||||
if (action === 'add') {
|
||||
const rawTasks = unwrapArgValue(args?.tasks);
|
||||
const rawCount = Number(unwrapArgValue(args?.n) || 0);
|
||||
const shardCount = Array.isArray(rawTasks) && rawTasks.length > 1
|
||||
? rawTasks.length
|
||||
: rawCount > 1
|
||||
? Math.floor(rawCount)
|
||||
: 0;
|
||||
const detail = memberName
|
||||
? shardCount > 1
|
||||
? `@${memberName}-1..${shardCount}`
|
||||
: `@${memberName}`
|
||||
: '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_add',
|
||||
isAskUser: false,
|
||||
label: '派生工蜂',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
if (action === 'title') {
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_title',
|
||||
isAskUser: false,
|
||||
label: '命名蜂群',
|
||||
detail: cleanSingleLineSnippet(pickField(['title', 'Title']), 44) || '',
|
||||
};
|
||||
}
|
||||
if (action === 'kill') {
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_kill',
|
||||
isAskUser: false,
|
||||
label: '终止工蜂',
|
||||
detail: memberName ? `@${memberName}` : '',
|
||||
};
|
||||
}
|
||||
if (action === 'model') {
|
||||
const target = memberName ? `@${memberName}` : '@coordinator';
|
||||
const nextModel = pickField(['model', 'Model']);
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_model',
|
||||
isAskUser: false,
|
||||
label: '切换工蜂模型',
|
||||
detail: nextModel ? `${target} -> ${nextModel}` : target,
|
||||
};
|
||||
}
|
||||
if (action === 'channel') {
|
||||
const op = pickField(['op', 'Op']);
|
||||
const ch = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_channel',
|
||||
isAskUser: false,
|
||||
label: '蜂群频道',
|
||||
detail: ch ? `${op ? `${op} ` : ''}#${ch}` : op || '',
|
||||
};
|
||||
}
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_status',
|
||||
isAskUser: false,
|
||||
label: '巡检蜂群',
|
||||
detail: action || 'status',
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'post_message') {
|
||||
const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
const textSnippet = cleanSingleLineSnippet(pickField(['text', 'Text']), 48);
|
||||
const detail =
|
||||
channel && channel !== 'main'
|
||||
? `[#${channel}]${textSnippet ? ` ${textSnippet}` : ''}`
|
||||
: textSnippet || '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'post_message',
|
||||
isAskUser: false,
|
||||
label: '发布看板',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'read_board') {
|
||||
const rawStatus = unwrapArgValue(args?.status) ?? pickField(['status']);
|
||||
const isStatus = String(rawStatus).trim().toLowerCase() === 'true';
|
||||
const rawSeqs = unwrapArgValue(args?.seqs);
|
||||
const seqsLabel =
|
||||
Array.isArray(rawSeqs) && rawSeqs.length > 0
|
||||
? `${rawSeqs
|
||||
.slice(0, 4)
|
||||
.map((n) => `#${String(unwrapArgValue(n) ?? n).trim()}`)
|
||||
.join(', ')}${rawSeqs.length > 4 ? '…' : ''}`
|
||||
: '';
|
||||
const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']);
|
||||
const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim();
|
||||
const detail = isStatus
|
||||
? 'status'
|
||||
: [
|
||||
channel && channel !== 'main' ? `#${channel}` : '',
|
||||
seqsLabel ||
|
||||
(sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== ''
|
||||
? `#${String(sinceVal).trim()}+`
|
||||
: ''),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'read_board',
|
||||
isAskUser: false,
|
||||
label: '读取看板',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'swarm_wait') {
|
||||
const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']);
|
||||
const detail =
|
||||
sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== ''
|
||||
? `#${String(sinceVal).trim()}+`
|
||||
: '';
|
||||
return {
|
||||
toolName: nameLower,
|
||||
actionKey: 'swarm_wait',
|
||||
isAskUser: false,
|
||||
isSwarmWait: true,
|
||||
label: '看板待命',
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
if (nameLower === 'manage_task') {
|
||||
const action = pickField(['Action', 'action']);
|
||||
const taskId = pickField(['TaskId', 'taskId']);
|
||||
@@ -2032,7 +2254,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
const info = summarizeToolCall(activeTool, lastStep);
|
||||
const stepProgress =
|
||||
tools.length > 1 && !hasBracketPrefix(info.detail) ? `${tools.length}/${tools.length}` : '';
|
||||
const phase = info.isAskUser ? 'waiting' : 'tool';
|
||||
const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool';
|
||||
return {
|
||||
phase,
|
||||
toolName: info.toolName,
|
||||
@@ -2115,8 +2337,8 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
if (hasBracketPrefix(info.detail)) {
|
||||
stepProgress = '';
|
||||
}
|
||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
||||
const waitingApproval = Boolean(waiting && !info.isAskUser);
|
||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser || Boolean(info.isSwarmWait);
|
||||
const waitingApproval = Boolean(waiting && !info.isAskUser && !info.isSwarmWait);
|
||||
const resolvedStartMs = startMs || prevStepEndMs || 0;
|
||||
const label = waitingApproval ? `等待确认 · ${info.label}` : info.label;
|
||||
|
||||
@@ -2207,7 +2429,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
getRawStepEndMs(lastStep) ||
|
||||
getRawStepEndMs(plannerStep) ||
|
||||
0;
|
||||
const phase = info.isAskUser ? 'waiting' : 'tool';
|
||||
const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool';
|
||||
|
||||
return {
|
||||
phase,
|
||||
@@ -2228,6 +2450,22 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
const infos = pTools.map((t, idx) =>
|
||||
summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep)
|
||||
);
|
||||
const swarmWaitInfo = infos.find((x) => x.isSwarmWait);
|
||||
if (swarmWaitInfo) {
|
||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||
return {
|
||||
phase: 'waiting',
|
||||
toolName: swarmWaitInfo.toolName,
|
||||
actionKey: swarmWaitInfo.actionKey,
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: swarmWaitInfo.label,
|
||||
detail: swarmWaitInfo.detail,
|
||||
stepProgress: '',
|
||||
startedAtMs: startMs,
|
||||
signature: `swarm-wait:${lastStepId}:${swarmWaitInfo.detail}`,
|
||||
};
|
||||
}
|
||||
const lastToolInfo = infos[infos.length - 1];
|
||||
const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey);
|
||||
const detailsList = infos.map((x) => x.detail).filter(Boolean);
|
||||
@@ -2254,13 +2492,28 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
};
|
||||
}
|
||||
|
||||
// B2.5:Connect RPC 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令
|
||||
// B2.5:Connect RPC / SQLite 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令
|
||||
if (lastIdx > lastPlannerIdx) {
|
||||
const stepTypeUpper = String(lastStep?.type || '').toUpperCase();
|
||||
if (!stepTypeUpper.includes('USER_INPUT') && !stepTypeUpper.includes('GENERIC')) {
|
||||
const hasStepToolMeta = Boolean(lastStep?.metadata?.toolCall?.name);
|
||||
if (!stepTypeUpper.includes('USER_INPUT') && (!stepTypeUpper.includes('GENERIC') || hasStepToolMeta)) {
|
||||
const lastInfo = summarizeToolCall(null, lastStep);
|
||||
if (lastInfo.toolName !== 'tool' || lastInfo.detail) {
|
||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||
if (lastInfo.isSwarmWait) {
|
||||
return {
|
||||
phase: 'waiting',
|
||||
toolName: lastInfo.toolName,
|
||||
actionKey: lastInfo.actionKey,
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: lastInfo.label,
|
||||
detail: lastInfo.detail,
|
||||
stepProgress: '',
|
||||
startedAtMs: startMs,
|
||||
signature: `swarm-wait:${lastStepId}:${lastInfo.detail}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: 'thinking',
|
||||
toolName: lastInfo.toolName,
|
||||
@@ -2332,3 +2585,101 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别并规范化蜂群(Native Swarm)工蜂节点的身份信息,剥离冗余的 `Swarm Worker (<name>)` 包裹。
|
||||
*
|
||||
* @param {{ role?: string, typeName?: string, agentScriptName?: string, memberName?: string }} [input={}]
|
||||
* @returns {{ isSwarmWorker: boolean, memberName: string, isMonitor: boolean, isNarrator: boolean, isAuxiliary: boolean }}
|
||||
*/
|
||||
export function parseSwarmWorkerRole(input = {}) {
|
||||
const rawRole = String(input?.role || '').trim();
|
||||
const rawType = String(input?.typeName || '').trim().toLowerCase();
|
||||
const rawScript = String(input?.agentScriptName || '').trim();
|
||||
const explicitMember = String(input?.memberName || '').trim();
|
||||
|
||||
const wrapperMatch = rawRole.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
|
||||
const isSwarmWorker = Boolean(
|
||||
explicitMember || wrapperMatch || rawType === 'worker' || rawType === 'swarm_worker'
|
||||
);
|
||||
if (!isSwarmWorker) {
|
||||
return {
|
||||
isSwarmWorker: false,
|
||||
memberName: '',
|
||||
isMonitor: false,
|
||||
isNarrator: false,
|
||||
isAuxiliary: false,
|
||||
};
|
||||
}
|
||||
|
||||
const candidate =
|
||||
explicitMember ||
|
||||
(wrapperMatch ? wrapperMatch[1] : '') ||
|
||||
rawScript ||
|
||||
(rawRole.toLowerCase() !== 'worker' && rawRole.toLowerCase() !== 'swarm worker' ? rawRole : '');
|
||||
const memberName = String(candidate || '').replace(/^@+/, '').trim();
|
||||
const isMonitor = /^monitor(?:-\d+)?$/i.test(memberName);
|
||||
const isNarrator = /^narrator(?:-\d+)?$/i.test(memberName);
|
||||
return {
|
||||
isSwarmWorker: true,
|
||||
memberName,
|
||||
isMonitor,
|
||||
isNarrator,
|
||||
isAuxiliary: isMonitor || isNarrator,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断原始轨迹步骤是否已调用 `swarm_wait` 进入留言板待命状态(且后续尚未收到新的用户提问或系统唤醒消息)。
|
||||
*
|
||||
* @param {Array<object>} [rawSteps=[]]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isParkedOnSwarmWait(rawSteps = []) {
|
||||
if (!Array.isArray(rawSteps) || rawSteps.length === 0) return false;
|
||||
let lastIdx = rawSteps.length - 1;
|
||||
while (lastIdx > 0 && isAuxiliaryMetaStep(rawSteps[lastIdx]) && isRawStepComplete(rawSteps[lastIdx])) {
|
||||
lastIdx--;
|
||||
}
|
||||
let lastPlannerIdx = -1;
|
||||
for (let i = lastIdx; i >= 0; i--) {
|
||||
const st = rawSteps[i];
|
||||
const t = String(st?.type || '').trim().toUpperCase();
|
||||
if (t.includes('USER_INPUT') || t.includes('SYSTEM_MESSAGE') || isCheckpointStep(st)) {
|
||||
return false;
|
||||
}
|
||||
if (isPlannerStep(st)) {
|
||||
lastPlannerIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastPlannerIdx < 0) return false;
|
||||
|
||||
const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]);
|
||||
if (
|
||||
pTools.some((tc) => {
|
||||
const n = String(tc?.name || tc?.toolName || tc?.function?.name || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^default_api:/, '');
|
||||
return n === 'swarm_wait';
|
||||
})
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) {
|
||||
const st = rawSteps[k];
|
||||
const toolName = String(st?.metadata?.toolCall?.name || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^default_api:/, '');
|
||||
if (toolName === 'swarm_wait') return true;
|
||||
const rawContent = String(st?.content || '').trim();
|
||||
if (/Waiting for a message that calls on you|Waiting for any message posted after/i.test(rawContent)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user