feat(panel): default-lock topbar capsule and hover context to main agent with toggle (#35)

This commit is contained in:
fish
2026-11-22 17:09:00 +09:00
parent 1b61ae0258
commit 97ef8b5ea5
22 changed files with 799 additions and 58 deletions
+225 -21
View File
@@ -2,7 +2,7 @@
'use strict';
// --- shared/settings-normalization.mjs ---
const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => {
const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, normalizeExperimentalModernUi } = (() => {
/**
* @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。
*/
@@ -547,6 +547,20 @@ function normalizeModernUi(val) {
return Boolean(val);
}
const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']);
const DEFAULT_CONTEXT_AGENT_MODE = 'main';
/**
* 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。
*
* @param {unknown} raw
* @returns {'main'|'auto'}
*/
function normalizeContextAgentMode(raw) {
const val = String(raw || '').trim().toLowerCase();
return val === 'auto' ? 'auto' : 'main';
}
/**
* 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。
*
@@ -560,7 +574,7 @@ function normalizeExperimentalModernUi(val) {
}
return Boolean(val);
}
return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi };
return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, normalizeExperimentalModernUi };
})();
// --- shared/telemetry-display-rules.mjs ---
@@ -1792,6 +1806,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.popoverWidthCustom': '指定宽度',
'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px',
'settings.str.multiToggle': '实时运行会话入口',
'settings.str.contextAgentModeLabel': '胶囊及悬浮上下文',
'settings.str.contextAgentModeHint': '锁定主代理时,顶栏百分比及悬停速览始终展示主代理;完整面板内仍可随时点选子代理明细',
'settings.str.contextAgentMain': '锁定主代理',
'settings.str.contextAgentAuto': '跟随活跃',
'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊',
'settings.str.cliSlotsLabel': 'CLI 槽位顺序 (左 → 右,1~6 项,可拖拽)',
'settings.str.addCliSlot': '添加 CLI 槽位 ({count}/{max})',
@@ -2649,6 +2667,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.popoverWidthCustom': 'Custom',
'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px',
'settings.str.multiToggle': 'Active Sessions Pill',
'settings.str.contextAgentModeLabel': 'Capsule & Hover Context',
'settings.str.contextAgentModeHint': 'Lock to Main Agent keeps the topbar percentage and hover HUD on Main Agent; you can still inspect subagents inside the full panel',
'settings.str.contextAgentMain': 'Lock Main Agent',
'settings.str.contextAgentAuto': 'Follow Active',
'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule',
'settings.str.cliSlotsLabel': 'CLI Slot Order (Left → Right, 1–6, draggable)',
'settings.str.addCliSlot': 'Add CLI Slot ({count}/{max})',
@@ -5617,6 +5639,7 @@ function buildExportableSettingsJson(settings = {}) {
cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots),
standalonePort: normalizeStandalonePort(src.standalonePort),
showTopbarMultiSession: src.showTopbarMultiSession !== false,
contextAgentMode: normalizeContextAgentMode(src.contextAgentMode),
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots),
hoverModules: normalizeHoverModules(src.hoverModules),
overviewModules: normalizeOverviewModules(src.overviewModules),
@@ -5716,6 +5739,9 @@ function parseImportedSettingsJson(rawText) {
if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') {
patch.showTopbarMultiSession = src.showTopbarMultiSession;
}
if (hasKey('contextAgentMode')) {
patch.contextAgentMode = normalizeContextAgentMode(src.contextAgentMode);
}
if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) {
patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots);
}
@@ -8204,7 +8230,7 @@ const uiStore = createReactiveStore({
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'main', // 'main' | 'auto' | <subagent cascadeId>
toast: null, // { id, message, detail, actionLabel, onAction, tone, durationMs }
});
@@ -8601,7 +8627,7 @@ return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFee
})();
// --- src/store/telemetryStore.js ---
const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_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, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_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, normalizeClientContextAgentMode, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
/**
* @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
* and granular slice updates.
@@ -8987,6 +9013,7 @@ function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) {
const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
const DEFAULT_CLIENT_CONTEXT_AGENT_MODE = DEFAULT_CONTEXT_AGENT_MODE;
const CLIENT_CLI_STATUSLINE_PRESETS = CLI_STATUSLINE_PRESETS;
const DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS = DEFAULT_CLI_STATUSLINE_SLOTS;
const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS;
@@ -9007,7 +9034,34 @@ const normalizeClientPopoverWidthMode = normalizePopoverWidthMode;
const normalizeClientPopoverWidth = normalizePopoverWidth;
const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
const normalizeClientContextAgentMode = normalizeContextAgentMode;
const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots;
/**
* 根据偏好设置返回默认上下文代理目标(`'main'` 锁定主代理,`'auto'` 跟随活跃)。
*
* @param {Record<string, any>|null|undefined} settings
* @returns {'main'|'auto'}
*/
function getDefaultCtxInspectorAgentId(settings) {
return normalizeContextAgentMode(settings?.contextAgentMode) === 'auto' ? 'auto' : 'main';
}
/**
* 计算顶栏挂载胶囊及悬停速览浮窗应使用的上下文代理目标:
* - 当 `contextAgentMode === 'main'`(默认)时始终锁定 `'main'`,不被后台子代理或面板临时点选带偏;
* - 当 `contextAgentMode === 'auto'` 时跟随面板当前 `ctxInspectorAgentId`(含手动点选 `主`)。
*
* @param {Record<string, any>|null|undefined} telemetry
* @param {string} [ctxInspectorAgentId='auto']
* @returns {string}
*/
function resolveOverlayCtxInspectorAgentId(telemetry, ctxInspectorAgentId = 'auto') {
if (normalizeContextAgentMode(telemetry?.settings?.contextAgentMode) === 'main') {
return 'main';
}
return ctxInspectorAgentId || 'auto';
}
const resolveEffectiveClientCliStatusLineSlots = resolveEffectiveCliStatusLineSlots;
const normalizeClientHoverModules = normalizeHoverModules;
const normalizeClientOverviewModules = normalizeOverviewModules;
@@ -9101,6 +9155,12 @@ function isEquivalentTelemetry(prev, next) {
if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) {
return false;
}
if (
normalizeClientContextAgentMode(pSet?.contextAgentMode) !==
normalizeClientContextAgentMode(nSet?.contextAgentMode)
) {
return false;
}
if (Boolean(pSet?.showStepTurnRail) !== Boolean(nSet?.showStepTurnRail)) {
return false;
}
@@ -10286,6 +10346,9 @@ async function saveSettingsPatch(patch) {
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextAgentMode')) {
safePatch.contextAgentMode = normalizeClientContextAgentMode(safePatch.contextAgentMode);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepTurnRail')) {
safePatch.showStepTurnRail = Boolean(safePatch.showStepTurnRail);
}
@@ -10854,7 +10917,7 @@ function isMacHostPlatform(telemetry) {
}
return false;
}
return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_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, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_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, normalizeClientContextAgentMode, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
})();
// --- src/components/ui/TopLongPillNav.js ---
@@ -19173,16 +19236,26 @@ function createDynamicWidgetHost({
preview = false,
isVisibleFn = () => true,
initialModuleKeys = [],
getCtxAgentId: customGetCtxAgentId = undefined,
setCtxAgentId: customSetCtxAgentId = undefined,
}) {
const instances = new Map();
let currentKeys = [];
let previewCtxAgentId = 'auto';
let previewCtxAgentId = 'main';
let latestUpdatePayload = null;
const getCtxAgentId = preview ? () => previewCtxAgentId : undefined;
const setCtxAgentId = preview
const getCtxAgentId =
typeof customGetCtxAgentId === 'function'
? customGetCtxAgentId
: preview
? () => previewCtxAgentId
: undefined;
const setCtxAgentId =
typeof customSetCtxAgentId === 'function'
? customSetCtxAgentId
: preview
? (nextId) => {
previewCtxAgentId = String(nextId || 'auto');
previewCtxAgentId = String(nextId || 'main');
if (latestUpdatePayload) {
for (const key of currentKeys) {
instances.get(key)?.refs?.update?.(latestUpdatePayload);
@@ -20340,7 +20413,7 @@ const CapsuleBarWidget = defineComponent({
const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
data,
'all',
'auto'
resolveOverlayCtxInspectorAgentId(data, 'auto')
);
const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated });
const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, {
@@ -25049,6 +25122,13 @@ function getPopoverWidthModeOptions() {
];
}
function getContextAgentModeOptions() {
return [
{ value: 'main', label: t('settings.str.contextAgentMain') },
{ value: 'auto', label: t('settings.str.contextAgentAuto') },
];
}
function isSameList(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
@@ -25139,6 +25219,7 @@ const SettingsStructureTab = defineComponent({
let draftEnableCliStatusLine = true;
let draftCliStatusLineSlots = null;
let draftShowTopbarMulti = true;
let draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE;
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
@@ -25175,6 +25256,7 @@ const SettingsStructureTab = defineComponent({
popoverWidth: draftPopoverWidth,
enableCliStatusLine: draftEnableCliStatusLine,
showTopbarMultiSession: draftShowTopbarMulti,
contextAgentMode: draftContextAgentMode,
topbarCapsuleSlots: draftTopbarSlots,
hoverModules: draftHoverModules,
overviewModules: draftOverviewModules,
@@ -25290,6 +25372,14 @@ const SettingsStructureTab = defineComponent({
className: 'form-label',
text: t('settings.str.multiToggle'),
});
const contextAgentModeLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.contextAgentModeLabel'),
});
const contextAgentModeHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.str.contextAgentModeHint'),
});
const cliCapsuleLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.cliCapsuleToggle'),
@@ -25411,6 +25501,22 @@ const SettingsStructureTab = defineComponent({
},
});
const contextAgentModeToggle = SegmentedControl({
ariaLabel: t('settings.str.contextAgentModeLabel'),
modelValue: draftContextAgentMode,
options: getContextAgentModeOptions(),
onUpdateModelValue: (val) => {
const nextMode = normalizeClientContextAgentMode(val);
draftContextAgentMode = nextMode;
uiStore.setState({ ctxInspectorAgentId: nextMode });
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, {
contextAgentMode: nextMode,
});
},
});
const cliCapsuleToggle = SegmentedControl({
ariaLabel: t('settings.str.cliCapsuleToggle'),
modelValue: 'on',
@@ -25528,7 +25634,9 @@ const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine = true;
draftCliStatusLineSlots = null;
draftShowTopbarMulti = true;
draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE;
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
uiStore.setState({ ctxInspectorAgentId: DEFAULT_CLIENT_CONTEXT_AGENT_MODE });
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
@@ -25541,6 +25649,7 @@ const SettingsStructureTab = defineComponent({
enableCliStatusLine: true,
cliStatusLineSlots: null,
showTopbarMultiSession: true,
contextAgentMode: DEFAULT_CLIENT_CONTEXT_AGENT_MODE,
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
},
'settings.resetDone'
@@ -25565,6 +25674,13 @@ const SettingsStructureTab = defineComponent({
multiToggleLabelEl,
multiSessionToggle.el,
]),
h('div', { className: 'form-row' }, [
h('div', { className: 'settings-inline-row' }, [
contextAgentModeLabelEl,
contextAgentModeToggle.el,
]),
contextAgentModeHintEl,
]),
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
cliStatusGroupEl,
],
@@ -25631,6 +25747,11 @@ const SettingsStructureTab = defineComponent({
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
options: getMultiToggleOptions(),
});
contextAgentModeToggle.setProps({
modelValue: draftContextAgentMode,
options: getContextAgentModeOptions(),
ariaLabel: t('settings.str.contextAgentModeLabel'),
});
const cliInstalled = Boolean(latestCliStatusLine?.installed);
patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled);
cliCapsuleToggle.setProps({
@@ -25693,6 +25814,7 @@ const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine === true &&
draftCliStatusLineSlots === null &&
draftShowTopbarMulti === true &&
draftContextAgentMode === DEFAULT_CLIENT_CONTEXT_AGENT_MODE &&
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
mountSection.refs.setResetDisabled(isDefault);
refreshMountPreview();
@@ -25714,6 +25836,11 @@ const SettingsStructureTab = defineComponent({
preview: true,
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover',
initialModuleKeys: [],
getCtxAgentId: () =>
resolveOverlayCtxInspectorAgentId(
{ settings: { contextAgentMode: draftContextAgentMode } },
'auto'
),
});
const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
hoverPreviewTipEl,
@@ -26302,6 +26429,7 @@ const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(settings.cliStatusLineSlots);
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
draftContextAgentMode = normalizeClientContextAgentMode(settings.contextAgentMode);
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
@@ -26335,6 +26463,8 @@ const SettingsStructureTab = defineComponent({
patchText(popoverWidthHintEl, t('settings.str.popoverWidthHint'));
popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') });
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
patchText(contextAgentModeLabelEl, t('settings.str.contextAgentModeLabel'));
patchText(contextAgentModeHintEl, t('settings.str.contextAgentModeHint'));
patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle'));
patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel'));
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
@@ -26408,6 +26538,7 @@ const SettingsStructureTab = defineComponent({
popoverWidthStepper.destroy();
popoverWidthModeToggle.destroy();
multiSessionToggle.destroy();
contextAgentModeToggle.destroy();
cliCapsuleToggle.destroy();
cliSlotsList.destroy();
topbarSlotsList.destroy();
@@ -26436,6 +26567,7 @@ const SettingsStructureTab = defineComponent({
stepTablePreview,
windowMountSelect,
multiSessionToggle,
contextAgentModeToggle,
cliCapsuleToggle,
cliStatusGroupEl,
cliStatusDetailEl,
@@ -27283,6 +27415,7 @@ const TopSessionHeader = defineComponent({
let lastActiveCascadeId = '';
let lastAppliedHostChildRouteId = '';
let preChildCtxInspectorAgentId = '';
function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) {
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
@@ -27291,15 +27424,22 @@ const TopSessionHeader = defineComponent({
const selectedId = String(telSlice?.selectedConversationId || '').trim();
const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim();
const hostRouteLower = hostRouteId.toLowerCase();
const defaultCtxId = getDefaultCtxInspectorAgentId(telemetry?.settings);
if (!selectedId && hostRouteLower) {
const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId);
if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) {
lastActiveCascadeId = currentCascadeId;
if (lastAppliedHostChildRouteId !== hostRouteLower) {
const uiSt = uiStore.getState();
if (!lastAppliedHostChildRouteId) {
preChildCtxInspectorAgentId =
uiSt.ctxInspectorAgentId === 'main' || uiSt.ctxInspectorAgentId === 'auto'
? uiSt.ctxInspectorAgentId
: defaultCtxId;
}
lastAppliedHostChildRouteId = hostRouteLower;
const targetAgentId = routeMatch.childAgent.agentId;
const uiSt = uiStore.getState();
if (
uiSt.selectedAgentScope !== targetAgentId ||
uiSt.ctxInspectorAgentId !== targetAgentId
@@ -27313,23 +27453,30 @@ const TopSessionHeader = defineComponent({
return;
}
if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) {
const restoreCtxId =
preChildCtxInspectorAgentId === 'main' || preChildCtxInspectorAgentId === 'auto'
? preChildCtxInspectorAgentId
: defaultCtxId;
lastAppliedHostChildRouteId = '';
preChildCtxInspectorAgentId = '';
const uiSt = uiStore.getState();
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== restoreCtxId) {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: restoreCtxId });
}
lastActiveCascadeId = currentCascadeId;
return;
}
} else if (lastAppliedHostChildRouteId) {
lastAppliedHostChildRouteId = '';
preChildCtxInspectorAgentId = '';
}
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
lastActiveCascadeId = currentCascadeId;
preChildCtxInspectorAgentId = '';
const uiSt = uiStore.getState();
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== defaultCtxId) {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: defaultCtxId });
}
} else {
lastActiveCascadeId = currentCascadeId;
@@ -29119,7 +29266,9 @@ const ConsumptionView = defineComponent({
activeView: 'steps',
stepsSubTab: 'steps',
selectedAgentScope: 'all',
ctxInspectorAgentId: 'auto',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
});
},
},
@@ -30179,9 +30328,18 @@ const StepsDetailView = defineComponent({
const prevUiScope = uiStore.getState().selectedAgentScope;
lastSyncedUiScope = mappedSingle;
if (prevUiScope !== mappedSingle) {
const curCtxId = uiStore.getState().ctxInspectorAgentId;
const shouldResetSubCtx =
mappedSingle === 'all' && curCtxId && curCtxId !== 'main' && curCtxId !== 'auto';
uiStore.setState({
selectedAgentScope: mappedSingle,
...(mappedSingle === 'all' ? { ctxInspectorAgentId: 'auto' } : {}),
...(shouldResetSubCtx
? {
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
}
: {}),
});
} else if (latestSlice) {
renderStepsData(latestSlice);
@@ -32518,6 +32676,24 @@ const App = defineComponent({
}
);
let syncedSettingsCtxMode = null;
function syncContextAgentModeFromSettings(settings) {
if (!settings || typeof settings !== 'object') return;
const nextMode = getDefaultCtxInspectorAgentId(settings);
if (nextMode === syncedSettingsCtxMode) return;
const prevSynced = syncedSettingsCtxMode;
syncedSettingsCtxMode = nextMode;
const curCtx = uiStore.getState().ctxInspectorAgentId;
if (prevSynced !== null || curCtx === 'main' || curCtx === 'auto') {
if (curCtx !== nextMode) {
uiStore.setState({ ctxInspectorAgentId: nextMode });
}
}
}
syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings);
const unsubStepCount = telemetryStore.subscribe(
(st) => ({
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
@@ -32525,11 +32701,13 @@ const App = defineComponent({
subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0,
windowMountMode: st.telemetry?.settings?.windowMountMode,
enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay,
contextAgentMode: st.telemetry?.settings?.contextAgentMode,
modelContextWindows: st.telemetry?.settings?.modelContextWindows,
windowBridge: st.telemetry?.windowBridge,
hostPlatform: st.telemetry?.hostPlatform,
}),
() => {
syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings);
syncStepsBadge();
syncGlobalBridgeBanner();
}
@@ -33638,7 +33816,9 @@ function mountWindowOverlay() {
uiStore.setState({
activeView: 'overview',
selectedAgentScope: 'all',
ctxInspectorAgentId: 'auto',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
});
void selectConversation(cascadeId);
setMultiOpen(false);
@@ -33917,6 +34097,11 @@ function mountWindowOverlay() {
mode: 'hover',
isVisibleFn: () => Boolean(tooltipOpen && !disposed),
initialModuleKeys: DEFAULT_CLIENT_HOVER_MODULES,
getCtxAgentId: () =>
resolveOverlayCtxInspectorAgentId(
telemetryStore.getState().telemetry,
uiStore.getState().ctxInspectorAgentId
),
});
const hoverTipEl = h(
@@ -34945,12 +35130,16 @@ function mountWindowOverlay() {
return;
}
const overlayCtxAgentId = resolveOverlayCtxInspectorAgentId(
telemetry,
uiSt.ctxInspectorAgentId
);
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
resolveScopedConversation(telemetry, 'all', overlayCtxAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
overlayCtxAgentId
);
const overviewActive = overviewScopedConv || telemetry.activeConversation || {};
const slotCtx = buildCapsuleSlotContext(telemetry, {
@@ -35120,11 +35309,26 @@ function mountWindowOverlay() {
if (currentRouteId === lastObservedRouteId) return;
lastObservedRouteId = currentRouteId;
const st = telemetryStore.getState();
const activeCascadeId = String(st.telemetry?.activeConversation?.cascadeId || '').trim();
const isSameActiveRoot =
Boolean(activeCascadeId) &&
Boolean(currentRouteId) &&
currentRouteId.toLowerCase() === activeCascadeId.toLowerCase();
const isChildOfActiveRoot =
Boolean(currentRouteId) &&
Boolean(resolveHostRouteMatch(st.telemetry, currentRouteId)?.isChildRoute);
const shouldPreserveSameSession =
!currentRouteId || isSameActiveRoot || isChildOfActiveRoot;
const nextSelectedId =
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
? ''
: st.selectedConversationId;
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (!shouldPreserveSameSession) {
uiStore.setState({
selectedAgentScope: 'all',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(st.telemetry?.settings),
});
}
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
}
+3
View File
@@ -18,7 +18,9 @@ import { normalizeFullSettings } from './settings-schema.mjs';
export {
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
@@ -42,6 +44,7 @@ export {
TOPBAR_SLOT_KEYS,
createDefaultSettingsObject,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeFontScale,
normalizeFullSettings,
normalizeHoverModules,
@@ -7,7 +7,9 @@
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
import {
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
@@ -31,6 +33,7 @@ import {
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
normalizeFontScale,
normalizeHoverModules,
@@ -56,7 +59,9 @@ import {
export {
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
@@ -80,6 +85,7 @@ export {
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
normalizeFontScale,
normalizeHoverModules,
@@ -142,6 +148,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
cliStatusLineSlots: null,
standalonePort: 0,
showTopbarMultiSession: true,
contextAgentMode: DEFAULT_CONTEXT_AGENT_MODE,
topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS,
hoverModules: DEFAULT_HOVER_MODULES,
overviewModules: DEFAULT_OVERVIEW_MODULES,
@@ -220,6 +227,7 @@ export function normalizeFullSettings(rawInput) {
cliStatusLineSlots: normalizeCliStatusLineSlots(safeRaw.cliStatusLineSlots),
standalonePort: normalizeStandalonePort(safeRaw.standalonePort),
showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false,
contextAgentMode: normalizeContextAgentMode(safeRaw.contextAgentMode),
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
hoverModules: normalizeHoverModules(safeRaw.hoverModules),
overviewModules: normalizeOverviewModules(safeRaw.overviewModules),
+2 -2
View File
@@ -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=1795319573666">
<link rel="stylesheet" href="/styles.css?v=1795334334959">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795319573666"></script>
<script src="/app.js?v=1795334334959"></script>
</body>
</html>
@@ -542,6 +542,20 @@ export function normalizeModernUi(val) {
return Boolean(val);
}
export const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']);
export const DEFAULT_CONTEXT_AGENT_MODE = 'main';
/**
* 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。
*
* @param {unknown} raw
* @returns {'main'|'auto'}
*/
export function normalizeContextAgentMode(raw) {
const val = String(raw || '').trim().toLowerCase();
return val === 'auto' ? 'auto' : 'main';
}
/**
* 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。
*
+21
View File
@@ -11,6 +11,7 @@ import { createSvgIcon } from './icons/SvgIcon.js';
import { i18nStore, t } from './i18n/index.js';
import {
fetchTelemetry,
getDefaultCtxInspectorAgentId,
normalizeClientWindowMountMode,
resolveScopedConversation,
telemetryStore,
@@ -293,6 +294,24 @@ export const App = defineComponent({
}
);
let syncedSettingsCtxMode = null;
function syncContextAgentModeFromSettings(settings) {
if (!settings || typeof settings !== 'object') return;
const nextMode = getDefaultCtxInspectorAgentId(settings);
if (nextMode === syncedSettingsCtxMode) return;
const prevSynced = syncedSettingsCtxMode;
syncedSettingsCtxMode = nextMode;
const curCtx = uiStore.getState().ctxInspectorAgentId;
if (prevSynced !== null || curCtx === 'main' || curCtx === 'auto') {
if (curCtx !== nextMode) {
uiStore.setState({ ctxInspectorAgentId: nextMode });
}
}
}
syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings);
const unsubStepCount = telemetryStore.subscribe(
(st) => ({
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
@@ -300,11 +319,13 @@ export const App = defineComponent({
subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0,
windowMountMode: st.telemetry?.settings?.windowMountMode,
enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay,
contextAgentMode: st.telemetry?.settings?.contextAgentMode,
modelContextWindows: st.telemetry?.settings?.modelContextWindows,
windowBridge: st.telemetry?.windowBridge,
hostPlatform: st.telemetry?.hostPlatform,
}),
() => {
syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings);
syncStepsBadge();
syncGlobalBridgeBanner();
}
@@ -12,6 +12,7 @@ import {
fetchTelemetry,
formatAgentBadgeText,
formatConversationMeta,
getDefaultCtxInspectorAgentId,
normalizeClientUpdateMode,
resolveHostRouteMatch,
selectConversation,
@@ -125,6 +126,7 @@ export const TopSessionHeader = defineComponent({
let lastActiveCascadeId = '';
let lastAppliedHostChildRouteId = '';
let preChildCtxInspectorAgentId = '';
function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) {
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
@@ -133,15 +135,22 @@ export const TopSessionHeader = defineComponent({
const selectedId = String(telSlice?.selectedConversationId || '').trim();
const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim();
const hostRouteLower = hostRouteId.toLowerCase();
const defaultCtxId = getDefaultCtxInspectorAgentId(telemetry?.settings);
if (!selectedId && hostRouteLower) {
const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId);
if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) {
lastActiveCascadeId = currentCascadeId;
if (lastAppliedHostChildRouteId !== hostRouteLower) {
const uiSt = uiStore.getState();
if (!lastAppliedHostChildRouteId) {
preChildCtxInspectorAgentId =
uiSt.ctxInspectorAgentId === 'main' || uiSt.ctxInspectorAgentId === 'auto'
? uiSt.ctxInspectorAgentId
: defaultCtxId;
}
lastAppliedHostChildRouteId = hostRouteLower;
const targetAgentId = routeMatch.childAgent.agentId;
const uiSt = uiStore.getState();
if (
uiSt.selectedAgentScope !== targetAgentId ||
uiSt.ctxInspectorAgentId !== targetAgentId
@@ -155,23 +164,30 @@ export const TopSessionHeader = defineComponent({
return;
}
if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) {
const restoreCtxId =
preChildCtxInspectorAgentId === 'main' || preChildCtxInspectorAgentId === 'auto'
? preChildCtxInspectorAgentId
: defaultCtxId;
lastAppliedHostChildRouteId = '';
preChildCtxInspectorAgentId = '';
const uiSt = uiStore.getState();
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== restoreCtxId) {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: restoreCtxId });
}
lastActiveCascadeId = currentCascadeId;
return;
}
} else if (lastAppliedHostChildRouteId) {
lastAppliedHostChildRouteId = '';
preChildCtxInspectorAgentId = '';
}
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
lastActiveCascadeId = currentCascadeId;
preChildCtxInspectorAgentId = '';
const uiSt = uiStore.getState();
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== defaultCtxId) {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: defaultCtxId });
}
} else {
lastActiveCascadeId = currentCascadeId;
@@ -46,6 +46,7 @@ import {
DEFAULT_CLIENT_HOVER_MODULES,
extractHostRouteCascadeId,
fetchTelemetry,
getDefaultCtxInspectorAgentId,
isMacHostPlatform,
normalizeClientHoverModules,
normalizeClientPopoverWidth,
@@ -54,6 +55,8 @@ import {
normalizeClientUpdateMode,
normalizeClientWindowMountMode,
resetTelemetryForEndpointSwitch,
resolveHostRouteMatch,
resolveOverlayCtxInspectorAgentId,
resolveScopedConversation,
selectConversation,
startAsyncTelemetryLoop,
@@ -1096,7 +1099,9 @@ export function mountWindowOverlay() {
uiStore.setState({
activeView: 'overview',
selectedAgentScope: 'all',
ctxInspectorAgentId: 'auto',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
});
void selectConversation(cascadeId);
setMultiOpen(false);
@@ -1375,6 +1380,11 @@ export function mountWindowOverlay() {
mode: 'hover',
isVisibleFn: () => Boolean(tooltipOpen && !disposed),
initialModuleKeys: DEFAULT_CLIENT_HOVER_MODULES,
getCtxAgentId: () =>
resolveOverlayCtxInspectorAgentId(
telemetryStore.getState().telemetry,
uiStore.getState().ctxInspectorAgentId
),
});
const hoverTipEl = h(
@@ -2403,12 +2413,16 @@ export function mountWindowOverlay() {
return;
}
const overlayCtxAgentId = resolveOverlayCtxInspectorAgentId(
telemetry,
uiSt.ctxInspectorAgentId
);
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
resolveScopedConversation(telemetry, 'all', overlayCtxAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
overlayCtxAgentId
);
const overviewActive = overviewScopedConv || telemetry.activeConversation || {};
const slotCtx = buildCapsuleSlotContext(telemetry, {
@@ -2578,11 +2592,26 @@ export function mountWindowOverlay() {
if (currentRouteId === lastObservedRouteId) return;
lastObservedRouteId = currentRouteId;
const st = telemetryStore.getState();
const activeCascadeId = String(st.telemetry?.activeConversation?.cascadeId || '').trim();
const isSameActiveRoot =
Boolean(activeCascadeId) &&
Boolean(currentRouteId) &&
currentRouteId.toLowerCase() === activeCascadeId.toLowerCase();
const isChildOfActiveRoot =
Boolean(currentRouteId) &&
Boolean(resolveHostRouteMatch(st.telemetry, currentRouteId)?.isChildRoute);
const shouldPreserveSameSession =
!currentRouteId || isSameActiveRoot || isChildOfActiveRoot;
const nextSelectedId =
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
? ''
: st.selectedConversationId;
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
if (!shouldPreserveSameSession) {
uiStore.setState({
selectedAgentScope: 'all',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(st.telemetry?.settings),
});
}
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
}
@@ -13,6 +13,7 @@ import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistr
import {
normalizeClientTopbarSlots,
normalizeClientWindowMountMode,
resolveOverlayCtxInspectorAgentId,
resolveScopedConversation,
} from '../../store/telemetryStore.js';
import { buildFallbackRunningConversations } from './LiveActivityWidget.js';
@@ -536,7 +537,7 @@ export const CapsuleBarWidget = defineComponent({
const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
data,
'all',
'auto'
resolveOverlayCtxInspectorAgentId(data, 'auto')
);
const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated });
const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, {
@@ -5,6 +5,7 @@
import {
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeFontScale,
normalizeHoverModules,
normalizeLanguageSetting,
@@ -108,6 +109,7 @@ export function buildExportableSettingsJson(settings = {}) {
cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots),
standalonePort: normalizeStandalonePort(src.standalonePort),
showTopbarMultiSession: src.showTopbarMultiSession !== false,
contextAgentMode: normalizeContextAgentMode(src.contextAgentMode),
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots),
hoverModules: normalizeHoverModules(src.hoverModules),
overviewModules: normalizeOverviewModules(src.overviewModules),
@@ -207,6 +209,9 @@ export function parseImportedSettingsJson(rawText) {
if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') {
patch.showTopbarMultiSession = src.showTopbarMultiSession;
}
if (hasKey('contextAgentMode')) {
patch.contextAgentMode = normalizeContextAgentMode(src.contextAgentMode);
}
if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) {
patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots);
}
+4
View File
@@ -617,6 +617,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.popoverWidthCustom': 'Custom',
'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px',
'settings.str.multiToggle': 'Active Sessions Pill',
'settings.str.contextAgentModeLabel': 'Capsule & Hover Context',
'settings.str.contextAgentModeHint': 'Lock to Main Agent keeps the topbar percentage and hover HUD on Main Agent; you can still inspect subagents inside the full panel',
'settings.str.contextAgentMain': 'Lock Main Agent',
'settings.str.contextAgentAuto': 'Follow Active',
'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule',
'settings.str.cliSlotsLabel': 'CLI Slot Order (Left → Right, 1–6, draggable)',
'settings.str.addCliSlot': 'Add CLI Slot ({count}/{max})',
+4
View File
@@ -617,6 +617,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.popoverWidthCustom': '指定宽度',
'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px',
'settings.str.multiToggle': '实时运行会话入口',
'settings.str.contextAgentModeLabel': '胶囊及悬浮上下文',
'settings.str.contextAgentModeHint': '锁定主代理时,顶栏百分比及悬停速览始终展示主代理;完整面板内仍可随时点选子代理明细',
'settings.str.contextAgentMain': '锁定主代理',
'settings.str.contextAgentAuto': '跟随活跃',
'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊',
'settings.str.cliSlotsLabel': 'CLI 槽位顺序 (左 → 右,1~6 项,可拖拽)',
'settings.str.addCliSlot': '添加 CLI 槽位 ({count}/{max})',
@@ -78,16 +78,26 @@ export function createDynamicWidgetHost({
preview = false,
isVisibleFn = () => true,
initialModuleKeys = [],
getCtxAgentId: customGetCtxAgentId = undefined,
setCtxAgentId: customSetCtxAgentId = undefined,
}) {
const instances = new Map();
let currentKeys = [];
let previewCtxAgentId = 'auto';
let previewCtxAgentId = 'main';
let latestUpdatePayload = null;
const getCtxAgentId = preview ? () => previewCtxAgentId : undefined;
const setCtxAgentId = preview
const getCtxAgentId =
typeof customGetCtxAgentId === 'function'
? customGetCtxAgentId
: preview
? () => previewCtxAgentId
: undefined;
const setCtxAgentId =
typeof customSetCtxAgentId === 'function'
? customSetCtxAgentId
: preview
? (nextId) => {
previewCtxAgentId = String(nextId || 'auto');
previewCtxAgentId = String(nextId || 'main');
if (latestUpdatePayload) {
for (const key of currentKeys) {
instances.get(key)?.refs?.update?.(latestUpdatePayload);
@@ -28,6 +28,7 @@ import {
import {
CLI_STATUSLINE_PRESETS,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
@@ -42,6 +43,7 @@ import {
STEP_TABLE_COLUMN_KEYS,
TOPBAR_SLOT_KEYS,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeHoverModules,
normalizeModelDisplayMode,
normalizeOrchestratorIdMode,
@@ -444,6 +446,7 @@ function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) {
export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
export const DEFAULT_CLIENT_CONTEXT_AGENT_MODE = DEFAULT_CONTEXT_AGENT_MODE;
export const CLIENT_CLI_STATUSLINE_PRESETS = CLI_STATUSLINE_PRESETS;
export const DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS = DEFAULT_CLI_STATUSLINE_SLOTS;
export const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS;
@@ -464,7 +467,34 @@ export const normalizeClientPopoverWidthMode = normalizePopoverWidthMode;
export const normalizeClientPopoverWidth = normalizePopoverWidth;
export const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
export const normalizeClientContextAgentMode = normalizeContextAgentMode;
export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots;
/**
* 根据偏好设置返回默认上下文代理目标(`'main'` 锁定主代理,`'auto'` 跟随活跃)。
*
* @param {Record<string, any>|null|undefined} settings
* @returns {'main'|'auto'}
*/
export function getDefaultCtxInspectorAgentId(settings) {
return normalizeContextAgentMode(settings?.contextAgentMode) === 'auto' ? 'auto' : 'main';
}
/**
* 计算顶栏挂载胶囊及悬停速览浮窗应使用的上下文代理目标:
* - 当 `contextAgentMode === 'main'`(默认)时始终锁定 `'main'`,不被后台子代理或面板临时点选带偏;
* - 当 `contextAgentMode === 'auto'` 时跟随面板当前 `ctxInspectorAgentId`(含手动点选 `主`)。
*
* @param {Record<string, any>|null|undefined} telemetry
* @param {string} [ctxInspectorAgentId='auto']
* @returns {string}
*/
export function resolveOverlayCtxInspectorAgentId(telemetry, ctxInspectorAgentId = 'auto') {
if (normalizeContextAgentMode(telemetry?.settings?.contextAgentMode) === 'main') {
return 'main';
}
return ctxInspectorAgentId || 'auto';
}
export const resolveEffectiveClientCliStatusLineSlots = resolveEffectiveCliStatusLineSlots;
export const normalizeClientHoverModules = normalizeHoverModules;
export const normalizeClientOverviewModules = normalizeOverviewModules;
@@ -558,6 +588,12 @@ export function isEquivalentTelemetry(prev, next) {
if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) {
return false;
}
if (
normalizeClientContextAgentMode(pSet?.contextAgentMode) !==
normalizeClientContextAgentMode(nSet?.contextAgentMode)
) {
return false;
}
if (Boolean(pSet?.showStepTurnRail) !== Boolean(nSet?.showStepTurnRail)) {
return false;
}
@@ -1743,6 +1779,9 @@ export async function saveSettingsPatch(patch) {
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextAgentMode')) {
safePatch.contextAgentMode = normalizeClientContextAgentMode(safePatch.contextAgentMode);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepTurnRail')) {
safePatch.showStepTurnRail = Boolean(safePatch.showStepTurnRail);
}
+1 -1
View File
@@ -21,7 +21,7 @@ export const uiStore = createReactiveStore({
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'main', // 'main' | 'auto' | <subagent cascadeId>
toast: null, // { id, message, detail, actionLabel, onAction, tone, durationMs }
});
+4 -1
View File
@@ -47,6 +47,7 @@ import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
import { ActionMenu } from '../components/ui/ActionMenu.js';
import {
getDefaultCtxInspectorAgentId,
prefetchConsumptionPresets,
selectConsumptionTimeRange,
selectConversation,
@@ -1463,7 +1464,9 @@ export const ConsumptionView = defineComponent({
activeView: 'steps',
stepsSubTab: 'steps',
selectedAgentScope: 'all',
ctxInspectorAgentId: 'auto',
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
});
},
},
+11 -1
View File
@@ -56,6 +56,7 @@ import { ActionMenu } from '../components/ui/ActionMenu.js';
import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
import {
formatAgentLabel,
getDefaultCtxInspectorAgentId,
normalizeClientStepColumns,
normalizeClientStepTokenComboFormat,
resolveScopedConversation,
@@ -274,9 +275,18 @@ export const StepsDetailView = defineComponent({
const prevUiScope = uiStore.getState().selectedAgentScope;
lastSyncedUiScope = mappedSingle;
if (prevUiScope !== mappedSingle) {
const curCtxId = uiStore.getState().ctxInspectorAgentId;
const shouldResetSubCtx =
mappedSingle === 'all' && curCtxId && curCtxId !== 'main' && curCtxId !== 'auto';
uiStore.setState({
selectedAgentScope: mappedSingle,
...(mappedSingle === 'all' ? { ctxInspectorAgentId: 'auto' } : {}),
...(shouldResetSubCtx
? {
ctxInspectorAgentId: getDefaultCtxInspectorAgentId(
telemetryStore.getState().telemetry?.settings
),
}
: {}),
});
} else if (latestSlice) {
renderStepsData(latestSlice);
@@ -20,6 +20,7 @@ import {
getOverviewModuleOptions,
} from '../../registries/widgetRegistry.js';
import {
DEFAULT_CLIENT_CONTEXT_AGENT_MODE,
DEFAULT_CLIENT_HOVER_MODULES,
DEFAULT_CLIENT_OVERVIEW_METRICS,
DEFAULT_CLIENT_OVERVIEW_MODULES,
@@ -30,6 +31,7 @@ import {
MAX_CLIENT_POPOVER_WIDTH,
MIN_CLIENT_POPOVER_WIDTH,
normalizeClientCliStatusLineSlots,
normalizeClientContextAgentMode,
normalizeClientHoverModules,
normalizeClientOverviewMetrics,
normalizeClientOverviewModules,
@@ -40,6 +42,7 @@ import {
normalizeClientTopbarSlots,
normalizeClientWindowMountMode,
resolveEffectiveClientCliStatusLineSlots,
resolveOverlayCtxInspectorAgentId,
saveSettingsPatch,
triggerCliStatusLineAction,
} from '../../store/telemetryStore.js';
@@ -95,6 +98,13 @@ function getPopoverWidthModeOptions() {
];
}
function getContextAgentModeOptions() {
return [
{ value: 'main', label: t('settings.str.contextAgentMain') },
{ value: 'auto', label: t('settings.str.contextAgentAuto') },
];
}
function isSameList(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
@@ -185,6 +195,7 @@ export const SettingsStructureTab = defineComponent({
let draftEnableCliStatusLine = true;
let draftCliStatusLineSlots = null;
let draftShowTopbarMulti = true;
let draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE;
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
@@ -221,6 +232,7 @@ export const SettingsStructureTab = defineComponent({
popoverWidth: draftPopoverWidth,
enableCliStatusLine: draftEnableCliStatusLine,
showTopbarMultiSession: draftShowTopbarMulti,
contextAgentMode: draftContextAgentMode,
topbarCapsuleSlots: draftTopbarSlots,
hoverModules: draftHoverModules,
overviewModules: draftOverviewModules,
@@ -336,6 +348,14 @@ export const SettingsStructureTab = defineComponent({
className: 'form-label',
text: t('settings.str.multiToggle'),
});
const contextAgentModeLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.contextAgentModeLabel'),
});
const contextAgentModeHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.str.contextAgentModeHint'),
});
const cliCapsuleLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.cliCapsuleToggle'),
@@ -457,6 +477,22 @@ export const SettingsStructureTab = defineComponent({
},
});
const contextAgentModeToggle = SegmentedControl({
ariaLabel: t('settings.str.contextAgentModeLabel'),
modelValue: draftContextAgentMode,
options: getContextAgentModeOptions(),
onUpdateModelValue: (val) => {
const nextMode = normalizeClientContextAgentMode(val);
draftContextAgentMode = nextMode;
uiStore.setState({ ctxInspectorAgentId: nextMode });
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, {
contextAgentMode: nextMode,
});
},
});
const cliCapsuleToggle = SegmentedControl({
ariaLabel: t('settings.str.cliCapsuleToggle'),
modelValue: 'on',
@@ -574,7 +610,9 @@ export const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine = true;
draftCliStatusLineSlots = null;
draftShowTopbarMulti = true;
draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE;
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
uiStore.setState({ ctxInspectorAgentId: DEFAULT_CLIENT_CONTEXT_AGENT_MODE });
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
@@ -587,6 +625,7 @@ export const SettingsStructureTab = defineComponent({
enableCliStatusLine: true,
cliStatusLineSlots: null,
showTopbarMultiSession: true,
contextAgentMode: DEFAULT_CLIENT_CONTEXT_AGENT_MODE,
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
},
'settings.resetDone'
@@ -611,6 +650,13 @@ export const SettingsStructureTab = defineComponent({
multiToggleLabelEl,
multiSessionToggle.el,
]),
h('div', { className: 'form-row' }, [
h('div', { className: 'settings-inline-row' }, [
contextAgentModeLabelEl,
contextAgentModeToggle.el,
]),
contextAgentModeHintEl,
]),
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
cliStatusGroupEl,
],
@@ -677,6 +723,11 @@ export const SettingsStructureTab = defineComponent({
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
options: getMultiToggleOptions(),
});
contextAgentModeToggle.setProps({
modelValue: draftContextAgentMode,
options: getContextAgentModeOptions(),
ariaLabel: t('settings.str.contextAgentModeLabel'),
});
const cliInstalled = Boolean(latestCliStatusLine?.installed);
patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled);
cliCapsuleToggle.setProps({
@@ -739,6 +790,7 @@ export const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine === true &&
draftCliStatusLineSlots === null &&
draftShowTopbarMulti === true &&
draftContextAgentMode === DEFAULT_CLIENT_CONTEXT_AGENT_MODE &&
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
mountSection.refs.setResetDisabled(isDefault);
refreshMountPreview();
@@ -760,6 +812,11 @@ export const SettingsStructureTab = defineComponent({
preview: true,
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover',
initialModuleKeys: [],
getCtxAgentId: () =>
resolveOverlayCtxInspectorAgentId(
{ settings: { contextAgentMode: draftContextAgentMode } },
'auto'
),
});
const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
hoverPreviewTipEl,
@@ -1348,6 +1405,7 @@ export const SettingsStructureTab = defineComponent({
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(settings.cliStatusLineSlots);
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
draftContextAgentMode = normalizeClientContextAgentMode(settings.contextAgentMode);
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
@@ -1381,6 +1439,8 @@ export const SettingsStructureTab = defineComponent({
patchText(popoverWidthHintEl, t('settings.str.popoverWidthHint'));
popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') });
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
patchText(contextAgentModeLabelEl, t('settings.str.contextAgentModeLabel'));
patchText(contextAgentModeHintEl, t('settings.str.contextAgentModeHint'));
patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle'));
patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel'));
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
@@ -1454,6 +1514,7 @@ export const SettingsStructureTab = defineComponent({
popoverWidthStepper.destroy();
popoverWidthModeToggle.destroy();
multiSessionToggle.destroy();
contextAgentModeToggle.destroy();
cliCapsuleToggle.destroy();
cliSlotsList.destroy();
topbarSlotsList.destroy();
@@ -1482,6 +1543,7 @@ export const SettingsStructureTab = defineComponent({
stepTablePreview,
windowMountSelect,
multiSessionToggle,
contextAgentModeToggle,
cliCapsuleToggle,
cliStatusGroupEl,
cliStatusDetailEl,
+1 -1
View File
@@ -208,6 +208,6 @@ export function backendHarness({
return {ok:true,json:async()=>data};
},
};
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeCliStatusLineSlots,resolveEffectiveCliStatusLineSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,extractManagedCliStatusLineFlags,getCliStatusLineRuntimeStatus,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx);
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeContextAgentMode,normalizeCliStatusLineSlots,resolveEffectiveCliStatusLineSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,extractManagedCliStatusLineFlags,getCliStatusLineRuntimeStatus,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx);
return {...ctx.api,state};
}
+7
View File
@@ -1076,6 +1076,7 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
assert.equal(def.windowMountMode, 'dual');
assert.equal(def.enableWindowOverlay, true);
assert.equal(def.showTopbarMultiSession, true);
assert.equal(def.contextAgentMode, 'main');
assert.equal(def.enableCliStatusLine, true);
assert.deepEqual([...def.topbarCapsuleSlots], ['tps', 'ttft', 'context']);
assert.deepEqual([...def.hoverModules], ['metrics', 'context', 'quotas']);
@@ -1105,12 +1106,16 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
assert.deepEqual([...hDefault.normalizeOverviewModules([])], ['metrics']);
assert.deepEqual([...hDefault.normalizeOverviewMetrics([])], ['tps']);
assert.deepEqual([...hDefault.normalizeStepTableColumns(['cost'])], ['cost', 'step']);
assert.equal(hDefault.normalizeContextAgentMode('auto'), 'auto');
assert.equal(hDefault.normalizeContextAgentMode('main'), 'main');
assert.equal(hDefault.normalizeContextAgentMode('unknown'), 'main');
// 4. Updating preferences must not apply legacy global limits or bulk model updates
const saveRes = hDefault.executeSettingsAction({
language: 'en-US',
themeAccent: 'emerald',
fontScale: 'lg',
contextAgentMode: 'auto',
topbarCapsuleSlots: ['context', 'tps', 'ttft', 'cost'],
hoverModules: ['metrics', 'context'],
overviewModules: ['quotas', 'metrics'],
@@ -1128,6 +1133,7 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
assert.equal(saveRes.updated.language, 'en-US');
assert.equal(saveRes.updated.themeAccent, 'emerald');
assert.equal(saveRes.updated.fontScale, 'lg');
assert.equal(saveRes.updated.contextAgentMode, 'auto');
assert.equal(saveRes.updated.topbarCapsuleSlots.length, 4);
assert.deepEqual([...saveRes.updated.hoverModules], ['metrics', 'context']);
assert.deepEqual([...saveRes.updated.overviewModules], ['quotas', 'metrics']);
@@ -1165,6 +1171,7 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
assert.equal(resetRes.updated.language, 'auto');
assert.equal(resetRes.updated.modernUi, true);
assert.equal(resetRes.updated.themeAccent, 'host');
assert.equal(resetRes.updated.contextAgentMode, 'main');
assert.equal(resetRes.updated.enableCliStatusLine, true);
assert.equal(resetRes.updated.showStepTurnRail, false);
assert.equal(resetRes.updated.showStepAgentBadge, true);
+11
View File
@@ -1276,4 +1276,15 @@ test('Frontend Swarm formatters, bilingual i18n, LiveActivityWidget priority sor
await Promise.resolve();
assert.equal(uiStore.getState().selectedAgentScope, 'all');
assert.equal(uiStore.getState().ctxInspectorAgentId, 'auto');
// Issue #35: Manual `'main'` lock before entering child route `/c/<w2>` must be restored on return to `/c/<rootId>`
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'main' }, { sync: true });
telemetryStore.setState({ hostRouteConversationId: w2 });
await Promise.resolve();
assert.equal(uiStore.getState().selectedAgentScope, w2);
assert.equal(uiStore.getState().ctxInspectorAgentId, w2);
telemetryStore.setState({ hostRouteConversationId: rootId });
await Promise.resolve();
assert.equal(uiStore.getState().selectedAgentScope, 'all');
assert.equal(uiStore.getState().ctxInspectorAgentId, 'main');
});
+293 -3
View File
@@ -651,6 +651,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
windowMountMode: 'dual',
enableWindowOverlay: true,
showTopbarMultiSession: true,
contextAgentMode: 'main',
enableCliStatusLine: true,
topbarCapsuleSlots: ['tps', 'ttft', 'context'],
hoverModules: ['metrics', 'context', 'quotas'],
@@ -1622,9 +1623,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
assert.equal(previewCapsuleBar.getAttribute('data-mount-mode'), 'dual');
// Toggle popover width mode (auto -> custom 640px -> step +10px -> auto), topbar multi-session switch (show -> hide -> show), and CLI bottom capsule switch (on -> off -> on)
// Toggle popover width mode (auto -> custom 640px -> step +10px -> auto), topbar multi-session switch, capsule/hover context agent mode (main -> auto -> main), and CLI bottom capsule switch
const topbarSegBtns = sec0.querySelectorAll('.seg-btn');
assert.equal(topbarSegBtns.length, 6, 'Popover width + Topbar multi-session + CLI bottom capsule toggles render 6 buttons');
assert.equal(topbarSegBtns.length, 8, 'Popover width + Topbar multi-session + Capsule/Hover context mode + CLI bottom capsule toggles render 8 buttons');
const popWidthInput = sec0.querySelector('.num-field');
const popWidthStepBtns = sec0.querySelectorAll('.num-step-btn');
assert.ok(popWidthInput, 'CustomNumberInput field exists without native <input type="number">');
@@ -1659,9 +1660,16 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
topbarSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine');
assert.equal(mockSettings.contextAgentMode, 'auto', 'Capsule/Hover context mode switches to follow active (auto)');
topbarSegBtns[4].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.contextAgentMode, 'main', 'Capsule/Hover context mode switches back to lock main agent');
topbarSegBtns[7].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine');
topbarSegBtns[6].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.enableCliStatusLine, true, 'CLI bottom capsule toggle restores enableCliStatusLine');
// Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓ & mouse drag-and-drop)
@@ -6015,3 +6023,285 @@ test('SettingsStructureTab CLI statusLine controls stay hidden unless CLI is det
globalThis.fetch = prevFetch;
}
});
test('Issue #35: topbar capsule and hover HUD lock to main agent by default, toggle cleanly to follow-active, and preserve manual main selection', async () => {
const {
buildExportableSettingsJson,
parseImportedSettingsJson,
} = await import('../src/core/settingsBackup.js');
// 1. Settings backup exports and re-imports contextAgentMode cleanly
const exported = buildExportableSettingsJson({ contextAgentMode: 'auto' });
const parsedBackup = parseImportedSettingsJson(exported);
assert.equal(parsedBackup.ok, true);
assert.equal(parsedBackup.patch.contextAgentMode, 'auto');
// 2. Compiled app.js E2E with Main Agent (44.3%) vs active running Subagent (63.7%)
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
const rootUuid = '11111111-2222-3333-4444-555555555555';
const subUuid = 'sub-worker-5';
const { document: mockDocument, body, makeElement } = createMockDom({
defaultRect: { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 },
});
const titlebar = makeElement('div');
titlebar.className = 'flex items-center @container/titlebar';
const titleRight = makeElement('div');
titleRight.className = 'flex items-center gap-1';
titlebar.appendChild(titleRight);
body.appendChild(titlebar);
const mockSettings = {
language: 'zh-CN',
themeAccent: 'host',
fontScale: 'md',
modernUi: true,
windowMountMode: 'dual',
enableWindowOverlay: true,
showTopbarMultiSession: true,
contextAgentMode: 'main',
topbarCapsuleSlots: ['tps', 'ttft', 'context'],
hoverModules: ['metrics', 'context'],
overviewModules: ['metrics', 'context'],
overviewMetrics: ['tps', 'ttft', 'avg_tps', 'step_cost'],
stepTableColumns: ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost'],
};
const mainContext = {
totalTokens: 113408,
limitTokens: 256000,
compactionLimitTokens: 256000,
usedPct: 44.3,
messagesTokens: 90000,
toolResultsTokens: 54000,
assistantTokens: 22000,
userInputTokens: 14000,
systemPromptTokens: 10000,
systemToolsTokens: 13408,
};
const subContext = {
totalTokens: 163072,
limitTokens: 256000,
compactionLimitTokens: 256000,
usedPct: 63.7,
messagesTokens: 138000,
toolResultsTokens: 96000,
assistantTokens: 30000,
userInputTokens: 12000,
systemPromptTokens: 11000,
systemToolsTokens: 14072,
};
const buildPayload = () => ({
bundleVersion: 'ver-issue35',
settings: { ...mockSettings },
quotas: { pools: [] },
conversations: [
{
cascadeId: rootUuid,
title: 'Main Task With Active Subagent',
isRunning: true,
stepCount: 12,
subagentCount: 1,
contextUsedPct: 44.3,
},
],
runningConversations: [],
activeConversation: {
cascadeId: rootUuid,
title: 'Main Task With Active Subagent',
isRunning: true,
hasSubagents: true,
subagentCount: 1,
stepCount: 12,
latestTokPerSec: 65,
avgTokPerSec: 60,
latestTtftSec: 1.1,
context: mainContext,
agents: [
{
agentId: 'main',
cascadeId: rootUuid,
isMain: true,
agentKind: 'main',
index: 0,
badgeText: '主',
role: '主代理',
isRunning: false,
stepCount: 8,
latestTokPerSec: 65,
avgTokPerSec: 60,
latestTtftSec: 1.1,
context: mainContext,
recentSteps: [],
},
{
agentId: subUuid,
cascadeId: subUuid,
isMain: false,
agentKind: 'subagent',
agentOrdinal: 1,
index: 1,
badgeText: '子1',
shortLabel: '子代理 #1',
role: 'Subagent Worker',
isRunning: true,
stepCount: 4,
latestTokPerSec: 88,
avgTokPerSec: 80,
latestTtftSec: 0.7,
context: subContext,
recentSteps: [],
},
],
aggregated: {
agentId: 'all',
isRunning: true,
stepCount: 12,
activeAgentId: subUuid,
activeAgentKind: 'subagent',
activeAgentOrdinal: 1,
activeAgentBadge: '子1',
latestTokPerSec: 88,
avgTokPerSec: 70,
latestTtftSec: 0.7,
context: subContext,
},
},
consumption: { range: '7d', summary: {}, trendSeries: [], topModels: [], topConversations: [] },
});
const mockLocation = { pathname: `/c/${rootUuid}`, href: `http://localhost/c/${rootUuid}` };
const mockWindow = {
innerWidth: 1280,
innerHeight: 800,
location: mockLocation,
document: mockDocument,
__AGUsageMonitorBridge: { port: 49235, token: 'tok-35', version: 'ver-issue35', platform: 'win32' },
addEventListener() {},
removeEventListener() {},
getComputedStyle: () => ({ display: 'flex', flexDirection: 'row', visibility: 'visible' }),
requestAnimationFrame: (cb) => setTimeout(cb, 0),
cancelAnimationFrame: (id) => clearTimeout(id),
fetch: async (url, opts = {}) => {
const urlStr = String(url);
if (urlStr.includes('/styles.css')) {
return { ok: true, status: 200, text: async () => stylesCss };
}
if (urlStr.includes('/api/settings') && String(opts.method || '').toUpperCase() === 'POST') {
Object.assign(mockSettings, JSON.parse(opts.body || '{}'));
return { ok: true, status: 200, json: async () => ({ ok: true, settings: { ...mockSettings } }) };
}
return { ok: true, status: 200, json: async () => buildPayload() };
},
};
mockWindow.window = mockWindow;
mockWindow.globalThis = mockWindow;
const sandbox = vm.createContext({
window: mockWindow,
globalThis: mockWindow,
document: mockDocument,
location: mockLocation,
navigator: {},
URLSearchParams,
AbortController,
setTimeout,
clearTimeout,
setInterval,
clearInterval,
queueMicrotask,
fetch: mockWindow.fetch,
console,
});
const readVal = (el) => el?.getAttribute?.('data-od-value') || el?.textContent || '';
vm.runInContext(appJs, sandbox);
await new Promise((r) => setTimeout(r, 50));
const ov = mockWindow.__AGUsageMonitorOverlay;
try {
assert.ok(ov, 'Overlay initialized');
const capsuleHost = mockDocument.getElementById('ag-usage-monitor-capsule');
const portalHost = mockDocument.getElementById('ag-usage-monitor-portal');
const capsuleBtn = capsuleHost.shadowRoot.querySelector('.wm-capsule-btn');
const ctxPctEl = capsuleHost.shadowRoot.querySelector('.wm-ctx-pct');
const hoverTipEl = portalHost.shadowRoot.querySelector('.wm-hover-tip');
// A. Default contextAgentMode === 'main': topbar capsule & hover HUD lock to Main (44% / 44.3%)
assert.equal(readVal(ctxPctEl), '44%', 'Topbar capsule locks to Main Agent (44%) despite active subagent (64%)');
capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 });
await new Promise((r) => setTimeout(r, 20));
const hoverCtxPanel = hoverTipEl.querySelector('.ctx-legend-grid')?.parentNode;
assert.ok(hoverCtxPanel, 'Hover HUD context panel rendered');
assert.match(hoverCtxPanel.textContent, /44\.3%/, 'Hover HUD locks to Main Agent 44.3%');
assert.match(hoverCtxPanel.textContent, /主代理/, 'Hover HUD shows Main Agent badge');
// B. Full panel defaults to Main, and clicking subagent pill inside panel does NOT hijack capsule/hover
ov.open();
await new Promise((r) => setTimeout(r, 25));
const popoverEl = portalHost.shadowRoot.querySelector('.wm-popover-panel');
const overviewCtxPanel = popoverEl.querySelector('.overview-modules-host .ctx-legend-grid')?.parentNode;
assert.ok(overviewCtxPanel, 'Overview context panel rendered');
const subPill = overviewCtxPanel.querySelector(`.ctx-agent-pill[data-pill-key="${subUuid}"]`);
const mainPill = overviewCtxPanel.querySelector('.ctx-agent-pill[data-pill-key="main"]');
assert.equal(mainPill.classList.contains('is-active'), true, 'Full panel defaults to Main Agent pill');
assert.match(overviewCtxPanel.textContent, /44\.3%/);
subPill.onclick({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 25));
assert.equal(subPill.classList.contains('is-active'), true, 'Full panel can still inspect subagent on demand');
assert.match(overviewCtxPanel.textContent, /63\.7%/, 'Full panel shows inspected subagent 63.7%');
assert.equal(readVal(ctxPctEl), '44%', 'Topbar capsule stays locked to Main Agent (44%) while panel inspects subagent');
ov.close();
capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 });
await new Promise((r) => setTimeout(r, 20));
assert.match(hoverCtxPanel.textContent, /44\.3%/, 'Hover HUD stays locked to Main Agent (44.3%)');
// C. Switching toggle to 'auto' (跟随活跃) makes capsule & hover follow active subagent (64% / 63.7%)
ov.open();
await new Promise((r) => setTimeout(r, 20));
const navTabs = popoverEl.querySelectorAll('.pill-tab');
navTabs[navTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} }); // Settings
await new Promise((r) => setTimeout(r, 20));
const settingsRoot = popoverEl.querySelector('.settings-view-root');
const subTabs = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
subTabs[1].dispatchEvent({ type: 'click', stopPropagation() {} }); // Structure
await new Promise((r) => setTimeout(r, 25));
const [, structurePane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const autoBtn = Array.from(structurePane.querySelectorAll('.seg-btn')).find(
(b) => b.textContent.trim() === '跟随活跃'
);
assert.ok(autoBtn, 'Context agent mode toggle renders 跟随活跃 option');
autoBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 35));
assert.equal(mockSettings.contextAgentMode, 'auto');
assert.equal(readVal(ctxPctEl), '64%', 'Topbar capsule follows active subagent (64%) when switched to auto');
ov.close();
capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 });
await new Promise((r) => setTimeout(r, 20));
assert.match(hoverCtxPanel.textContent, /63\.7%/, 'Hover HUD follows active subagent (63.7%) when switched to auto');
// D. Manual '主' lock in auto mode survives same-session syncHostRoute() without resetting to 'auto'
ov.open();
await new Promise((r) => setTimeout(r, 20));
navTabs[0].dispatchEvent({ type: 'click', stopPropagation() {} }); // Overview
await new Promise((r) => setTimeout(r, 20));
const mainPillAfterAuto = overviewCtxPanel.querySelector('.ctx-agent-pill[data-pill-key="main"]');
mainPillAfterAuto.onclick({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.equal(readVal(ctxPctEl), '44%', 'Manual main pill updates topbar capsule to 44% in auto mode');
// Simulate host route refresh on the same root conversation (e.g. focus/subagent jitter)
mockLocation.pathname = '/';
ov.syncHostRoute();
mockLocation.pathname = `/c/${rootUuid}`;
ov.syncHostRoute();
await new Promise((r) => setTimeout(r, 35));
assert.equal(readVal(ctxPctEl), '44%', 'Same-session route refresh preserves manual main lock instead of resetting to auto');
} finally {
ov?.dispose?.();
}
});