feat(panel): add 3rd-level structure menu, real-UI live previews, drag reorder, and unified capsule tones

This commit is contained in:
fish
2026-11-15 20:01:57 +09:00
parent 6517ee434e
commit 73f637a3e6
26 changed files with 4526 additions and 1134 deletions
+1836 -551
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1794735908512"> <link rel="stylesheet" href="/styles.css?v=1794740175626">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1794735908512"></script> <script src="/app.js?v=1794740175626"></script>
</body> </body>
</html> </html>
+3
View File
@@ -479,6 +479,9 @@ export function buildBundle() {
'src/components/widgets/LiveActivityWidget.js', 'src/components/widgets/LiveActivityWidget.js',
'src/registries/widgetRegistry.js', 'src/registries/widgetRegistry.js',
'src/registries/stepColumnRegistry.js', 'src/registries/stepColumnRegistry.js',
'src/components/widgets/CapsuleBarWidget.js',
'src/components/widgets/StepTableWidget.js',
'src/components/settings/structurePreviewMock.js',
'src/components/settings/CollapsibleSection.js', 'src/components/settings/CollapsibleSection.js',
'src/components/settings/EditableSlotList.js', 'src/components/settings/EditableSlotList.js',
'src/components/settings/ThemeColorPicker.js', 'src/components/settings/ThemeColorPicker.js',
@@ -21,8 +21,12 @@ import {
import { formatElapsedSec } from '../../core/formatters.js'; import { formatElapsedSec } from '../../core/formatters.js';
import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js'; import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js';
import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js';
import { createSvgIcon, patchSvgIcon, SVG_NS } from '../../icons/SvgIcon.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js'; import {
RING_CIRCUMFERENCE,
createCapsuleSlotNode,
syncCapsuleSlotNodes,
} from '../widgets/CapsuleBarWidget.js';
import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js'; import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js';
import { import {
DEFAULT_CLIENT_HOVER_MODULES, DEFAULT_CLIENT_HOVER_MODULES,
@@ -46,8 +50,6 @@ const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
const FLOATING_CARD_WIDTH = 522; const FLOATING_CARD_WIDTH = 522;
const MULTI_PANEL_WIDTH = 464; const MULTI_PANEL_WIDTH = 464;
const RING_RADIUS = 5.2;
const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
/** /**
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
@@ -1183,75 +1185,13 @@ export function mountWindowOverlay() {
[multiDot, multiLabel] [multiDot, multiLabel]
); );
// 构建可复用的预占胶囊槽位节点(支持 1..5 项动态槽位,运行期仅就地更新文本与属性) // 构建可复用的预占胶囊槽位节点(由 CapsuleBarWidget 共享创建,支持 1..5 项动态槽位)
function createCapsuleSlot(slotIndex, initialMetric) {
const ringSvg = document.createElementNS(SVG_NS, 'svg');
ringSvg.setAttribute('viewBox', '0 0 14 14');
ringSvg.setAttribute('class', 'wm-ring-svg');
ringSvg.setAttribute('aria-hidden', 'true');
const ringTrack = document.createElementNS(SVG_NS, 'circle');
ringTrack.setAttribute('cx', '7');
ringTrack.setAttribute('cy', '7');
ringTrack.setAttribute('r', String(RING_RADIUS));
ringTrack.setAttribute('class', 'wm-ring-track');
const ringFill = document.createElementNS(SVG_NS, 'circle');
ringFill.setAttribute('cx', '7');
ringFill.setAttribute('cy', '7');
ringFill.setAttribute('r', String(RING_RADIUS));
ringFill.setAttribute('class', 'wm-ring-fill');
ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE));
ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE));
ringSvg.appendChild(ringTrack);
ringSvg.appendChild(ringFill);
const isNone = initialMetric === 'none';
const isCtx = initialMetric === 'context';
const textSpan = h('span', {
className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text',
text: isNone
? ''
: isCtx
? '--%'
: initialMetric === 'tps'
? '-- t/s'
: t('capsule.quotaUnknown'),
});
const el = h(
'span',
{
className: isNone
? 'wm-cap-slot'
: isCtx
? 'wm-cap-slot wm-ctx-seg'
: initialMetric === 'tps'
? 'wm-cap-slot wm-seg-speed'
: 'wm-cap-slot wm-seg-quota',
hidden: isNone,
'data-slot-idx': String(slotIndex),
'data-metric': initialMetric,
'data-vis-rank': isNone ? '' : String(slotIndex + 1),
},
isCtx ? [ringSvg, textSpan] : [textSpan]
);
return {
el,
ringSvg,
ringFill,
textSpan,
ringMounted: isCtx,
};
}
const capsuleSlots = [ const capsuleSlots = [
createCapsuleSlot(0, 'context'), createCapsuleSlotNode(0, 'context'),
createCapsuleSlot(1, 'tps'), createCapsuleSlotNode(1, 'tps'),
createCapsuleSlot(2, 'quota_auto'), createCapsuleSlotNode(2, 'quota_auto'),
createCapsuleSlot(3, 'none'), createCapsuleSlotNode(3, 'none'),
createCapsuleSlot(4, 'none'), createCapsuleSlotNode(4, 'none'),
]; ];
const capsuleSeps = [ const capsuleSeps = [
h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }), h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }),
@@ -2370,53 +2310,7 @@ export function mountWindowOverlay() {
} }
function applyCapsuleSlots(slotKeys, slotCtx) { function applyCapsuleSlots(slotKeys, slotCtx) {
let visRank = 0; syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
const visRanks = [0, 0, 0, 0, 0];
for (let i = 0; i < capsuleSlots.length; i += 1) {
const slot = capsuleSlots[i];
const metricKey = i < slotKeys.length ? slotKeys[i] : 'none';
const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (pres.hidden) {
patchAttr(slot.el, 'hidden', true);
patchAttr(slot.el, 'data-metric', 'none');
patchAttr(slot.el, 'data-vis-rank', '');
continue;
}
visRank += 1;
visRanks[i] = visRank;
patchAttr(slot.el, 'hidden', false);
patchAttr(slot.el, 'data-metric', pres.metric);
patchAttr(slot.el, 'data-vis-rank', String(visRank));
if (pres.showRing && !slot.ringMounted) {
slot.el.insertBefore(slot.ringSvg, slot.textSpan);
slot.ringMounted = true;
} else if (!pres.showRing && slot.ringMounted) {
slot.ringSvg.remove();
slot.ringMounted = false;
}
const fullSegClass =
`${pres.segClass}${pres.running ? ' state-running' : ''}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`;
patchAttr(slot.el, 'class', fullSegClass);
const fullTextClass =
`${pres.textClass}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`;
patchAttr(slot.textSpan, 'class', fullTextClass);
patchText(slot.textSpan, pres.text);
if (pres.showRing) {
slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset));
patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger });
}
}
for (let s = 0; s < capsuleSeps.length; s += 1) {
const sepEl = capsuleSeps[s];
const nextRank = visRanks[s + 1] || 0;
const showSep = nextRank >= 2;
patchAttr(sepEl, 'hidden', !showSep);
patchAttr(sepEl, 'data-sep-for-rank', showSep ? String(nextRank) : '');
}
} }
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) --- // --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) ---
@@ -1,6 +1,7 @@
/** /**
* @fileoverview Reusable Accordion / Collapsible Section (`CollapsibleSection.js`) * @fileoverview Reusable Section Card (`CollapsibleSection.js`)
* for `SettingsStructureTab`. * for `SettingsStructureTab` — supports both accordion mode (`collapsible: true`)
* and static 3rd-level pane card mode (`collapsible: false`).
*/ */
import { defineComponent } from '../../core/component.js'; import { defineComponent } from '../../core/component.js';
@@ -11,38 +12,44 @@ import { t } from '../../i18n/index.js';
export const CollapsibleSection = defineComponent({ export const CollapsibleSection = defineComponent({
name: 'CollapsibleSection', name: 'CollapsibleSection',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
let expanded = Boolean(props.defaultExpanded); const isCollapsible = props.collapsible !== false;
let expanded = isCollapsible ? Boolean(props.defaultExpanded) : true;
let statusTimer = null; let statusTimer = null;
const chevronIcon = createSvgIcon('chevron-right', { const chevronIcon = isCollapsible
size: 12, ? createSvgIcon('chevron-right', {
className: 'collapsible-chevron', size: 12,
}); className: 'collapsible-chevron',
})
: null;
const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null; const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null;
const titleTextEl = h('span', { const titleTextEl = h('span', {
className: 'collapsible-title-text', className: 'collapsible-title-text',
text: props.title || '', text: props.title || '',
}); });
const triggerChildren = [chevronIcon]; const triggerChildren = [];
if (chevronIcon) triggerChildren.push(chevronIcon);
if (sectionIcon) triggerChildren.push(sectionIcon); if (sectionIcon) triggerChildren.push(sectionIcon);
triggerChildren.push(titleTextEl); triggerChildren.push(titleTextEl);
const triggerBtn = h( const triggerBtn = isCollapsible
'button', ? h(
{ 'button',
type: 'button', {
className: 'collapsible-trigger', type: 'button',
'aria-expanded': expanded ? 'true' : 'false', className: 'collapsible-trigger',
onClick: () => { 'aria-expanded': expanded ? 'true' : 'false',
setExpanded(!expanded); onClick: () => {
if (typeof props.onToggle === 'function') { setExpanded(!expanded);
props.onToggle(expanded); if (typeof props.onToggle === 'function') {
} props.onToggle(expanded);
}, }
}, },
triggerChildren },
); triggerChildren
)
: h('div', { className: 'collapsible-title-static' }, triggerChildren);
const statusTextEl = h('span', { className: 'collapsible-status', text: '' }); const statusTextEl = h('span', { className: 'collapsible-status', text: '' });
const badgeEl = h('span', { const badgeEl = h('span', {
@@ -89,12 +96,13 @@ export const CollapsibleSection = defineComponent({
const sectionEl = h( const sectionEl = h(
'section', 'section',
{ {
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}`, className: `panel collapsible-section${expanded ? ' is-expanded' : ''}${isCollapsible ? '' : ' is-static-pane'}`,
}, },
[headerRow, bodyEl] [headerRow, bodyEl]
); );
function setExpanded(next) { function setExpanded(next) {
if (!isCollapsible) return;
expanded = Boolean(next); expanded = Boolean(next);
patchClasses(sectionEl, { 'is-expanded': expanded }); patchClasses(sectionEl, { 'is-expanded': expanded });
patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false'); patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false');
@@ -149,13 +157,15 @@ export const CollapsibleSection = defineComponent({
triggerBtn, triggerBtn,
bodyEl, bodyEl,
resetBtn, resetBtn,
badgeEl,
statusTextEl,
setExpanded, setExpanded,
isExpanded: () => expanded,
setTitle, setTitle,
setBadge, setBadge,
setResetLabel, setResetLabel,
setResetDisabled, setResetDisabled,
showStatus, showStatus,
isExpanded: () => expanded,
}, },
}; };
}, },
@@ -1,15 +1,34 @@
/** /**
* @fileoverview Reusable `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`). * @fileoverview Reusable Drag-Sortable & `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`).
* Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4), * Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4),
* Live Overview Modules (1..4), First-Row Metrics (1..4), and Step Table Columns (2..12). * Live Overview Modules (1..4), First-Row Metrics (1..4), and Step Table Columns (2..12).
* Supports smooth pointer-based drag reordering with live preview callbacks (`onPreview`)
* and single-commit persistence on drop (`onChange`).
*/ */
import { defineComponent } from '../../core/component.js'; import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchText } from '../../core/domPatch.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js'; import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js'; import { t } from '../../i18n/index.js';
import { CustomSelect } from '../ui/CustomSelect.js'; import { CustomSelect } from '../ui/CustomSelect.js';
function isNodeWithin(target, container) {
let cur = target;
while (cur) {
if (cur === container) return true;
cur = cur.parentNode || cur.host || null;
}
return false;
}
function areSlotListsEqual(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false;
}
return true;
}
export const EditableSlotList = defineComponent({ export const EditableSlotList = defineComponent({
name: 'EditableSlotList', name: 'EditableSlotList',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
@@ -19,6 +38,7 @@ export const EditableSlotList = defineComponent({
let currentOptions = Array.isArray(props.options) ? [...props.options] : []; let currentOptions = Array.isArray(props.options) ? [...props.options] : [];
let emptyHintText = String(props.emptyHintText || ''); let emptyHintText = String(props.emptyHintText || '');
let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null; let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null;
let activeDrag = null;
const listEl = h('div', { className: 'editable-slot-list' }); const listEl = h('div', { className: 'editable-slot-list' });
const emptyEl = h('div', { const emptyEl = h('div', {
@@ -52,13 +72,162 @@ export const EditableSlotList = defineComponent({
function emitChange(nextItems) { function emitChange(nextItems) {
currentItems = [...nextItems]; currentItems = [...nextItems];
syncRows(); syncRows();
if (typeof props.onPreview === 'function') {
props.onPreview([...currentItems]);
}
if (typeof props.onChange === 'function') { if (typeof props.onChange === 'function') {
props.onChange([...currentItems]); props.onChange([...currentItems]);
} }
} }
function teardownActiveDrag({ revert = false } = {}) {
if (!activeDrag) return;
const { startItems, hasMoved, cleanupListeners } = activeDrag;
activeDrag = null;
cleanupListeners();
patchClasses(listEl, { 'is-dragging-list': false });
for (const r of rowPool) {
patchClasses(r.rowEl, { 'is-dragging': false });
}
if (revert && hasMoved && !areSlotListsEqual(startItems, currentItems)) {
currentItems = [...startItems];
syncRows();
if (typeof props.onPreview === 'function') {
props.onPreview([...currentItems]);
}
}
}
function startPointerDrag(e, initialRowIdx) {
if (e && e.button != null && e.button !== 0) return;
if (currentItems.length <= 1) return;
if (activeDrag) {
teardownActiveDrag({ revert: false });
}
const startY = Number(e?.clientY ?? 0);
const startItems = [...currentItems];
let dragIdx = initialRowIdx;
let hasMoved = false;
const onPointerMove = (ev) => {
if (!activeDrag) return;
const clientY = Number(ev?.clientY ?? startY);
if (!hasMoved) {
if (Math.abs(clientY - startY) < 4) return;
hasMoved = true;
activeDrag.hasMoved = true;
for (let k = 0; k < currentItems.length; k += 1) {
rowPool[k]?.selectComp?.close?.();
}
patchClasses(listEl, { 'is-dragging-list': true });
if (rowPool[dragIdx]) {
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true });
}
}
ev?.preventDefault?.();
let targetIdx = dragIdx;
const count = currentItems.length;
for (let i = 0; i < dragIdx; i += 1) {
const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.();
if (rect && rect.height > 0 && clientY < rect.top + rect.height * 0.5) {
targetIdx = i;
break;
}
}
if (targetIdx === dragIdx) {
for (let i = count - 1; i > dragIdx; i -= 1) {
const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.();
if (rect && rect.height > 0 && clientY > rect.top + rect.height * 0.5) {
targetIdx = i;
break;
}
}
}
if (targetIdx !== dragIdx) {
if (rowPool[dragIdx]) {
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': false });
}
const next = [...currentItems];
const [moved] = next.splice(dragIdx, 1);
next.splice(targetIdx, 0, moved);
dragIdx = targetIdx;
activeDrag.dragIdx = dragIdx;
currentItems = next;
syncRows();
if (rowPool[dragIdx]) {
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true });
}
if (typeof props.onPreview === 'function') {
props.onPreview([...currentItems]);
}
}
};
const onPointerUp = () => {
if (!activeDrag) return;
const moved = activeDrag.hasMoved;
const changed = !areSlotListsEqual(startItems, currentItems);
teardownActiveDrag({ revert: false });
if (moved && changed) {
emitChange([...currentItems]);
}
};
const onPointerCancel = () => {
teardownActiveDrag({ revert: true });
};
const onKeyDown = (ev) => {
if (ev?.key === 'Escape') {
teardownActiveDrag({ revert: true });
}
};
const docTarget =
typeof document !== 'undefined' && typeof document.addEventListener === 'function'
? document
: null;
if (docTarget) {
docTarget.addEventListener('pointermove', onPointerMove);
docTarget.addEventListener('pointerup', onPointerUp);
docTarget.addEventListener('pointercancel', onPointerCancel);
docTarget.addEventListener('keydown', onKeyDown);
}
activeDrag = {
startItems,
dragIdx,
hasMoved: false,
cleanupListeners: () => {
if (docTarget && typeof docTarget.removeEventListener === 'function') {
docTarget.removeEventListener('pointermove', onPointerMove);
docTarget.removeEventListener('pointerup', onPointerUp);
docTarget.removeEventListener('pointercancel', onPointerCancel);
docTarget.removeEventListener('keydown', onKeyDown);
}
},
};
}
function createSlotRow() { function createSlotRow() {
let rowIndex = 0; let rowIndex = 0;
const dragHandle = h(
'span',
{
className: 'slot-drag-handle',
'aria-hidden': 'true',
onPointerdown: (e) => {
e.preventDefault?.();
e.stopPropagation?.();
startPointerDrag(e, rowIndex);
},
},
[createSvgIcon('grip', { size: 12 })]
);
const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' }); const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' });
const selectComp = CustomSelect({ const selectComp = CustomSelect({
modelValue: '', modelValue: '',
@@ -123,14 +292,25 @@ export const EditableSlotList = defineComponent({
[createSvgIcon('minus', { size: 12 })] [createSvgIcon('minus', { size: 12 })]
); );
const rowEl = h('div', { className: 'editable-slot-row' }, [ const orderBtnsEl = h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]);
indexBadge,
selectComp.el, const rowEl = h(
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]), 'div',
]); {
className: 'editable-slot-row',
onPointerdown: (e) => {
if (isNodeWithin(e?.target, selectComp.el) || isNodeWithin(e?.target, orderBtnsEl)) {
return;
}
startPointerDrag(e, rowIndex);
},
},
[dragHandle, indexBadge, selectComp.el, orderBtnsEl]
);
return { return {
rowEl, rowEl,
dragHandle,
indexBadge, indexBadge,
selectComp, selectComp,
upBtn, upBtn,
@@ -160,6 +340,8 @@ export const EditableSlotList = defineComponent({
tailChild?.remove?.(); tailChild?.remove?.();
} }
const canDrag = count > 1;
const dragTitle = canDrag ? t('settings.slot.dragHint') : '';
const canRemove = count > minItems; const canRemove = count > minItems;
const removeTitle = canRemove const removeTitle = canRemove
? t('settings.slot.remove') ? t('settings.slot.remove')
@@ -171,6 +353,8 @@ export const EditableSlotList = defineComponent({
entry.setIndex(i); entry.setIndex(i);
patchAttr(entry.rowEl, 'data-slot-row', String(i)); patchAttr(entry.rowEl, 'data-slot-row', String(i));
patchText(entry.indexBadge, String(i + 1)); patchText(entry.indexBadge, String(i + 1));
patchClasses(entry.dragHandle, { 'is-disabled': !canDrag });
patchAttr(entry.dragHandle, 'title', dragTitle || null);
const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i)); const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i));
const rowOpts = currentOptions.map((opt) => { const rowOpts = currentOptions.map((opt) => {
@@ -222,7 +406,7 @@ export const EditableSlotList = defineComponent({
} }
function setProps(next = {}) { function setProps(next = {}) {
if (Array.isArray(next.items)) { if (!activeDrag && Array.isArray(next.items)) {
currentItems = [...next.items]; currentItems = [...next.items];
} }
if (Array.isArray(next.options)) { if (Array.isArray(next.options)) {
@@ -240,6 +424,7 @@ export const EditableSlotList = defineComponent({
syncRows(); syncRows();
onCleanup(() => { onCleanup(() => {
teardownActiveDrag({ revert: false });
for (const entry of rowPool) { for (const entry of rowPool) {
entry.selectComp.destroy(); entry.selectComp.destroy();
} }
@@ -0,0 +1,390 @@
/**
* @fileoverview Realistic Simulated Telemetry Builder (`structurePreviewMock.js`)
* for `SettingsStructureTab` real-UI live previews.
* Exercises all 13 capsule metrics, 8 overview metrics, 10 context channels + subagents,
* multi-pool quotas, live running task + subagent, and 12 step table columns.
*/
import { t } from '../../i18n/index.js';
export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) {
const anchorMinMs = Math.floor(Date.now() / 60000) * 60000;
const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString();
const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString();
const resetClaude5hIso = new Date(anchorMinMs + (1 * 60 + 18) * 60000).toISOString();
const mergedSettings = {
...(baseSettings && typeof baseSettings === 'object' ? baseSettings : {}),
...draftOverrides,
};
const sessionTitle = t('settings.mock.sessionTitle');
const subRole = t('settings.mock.subRole');
const promptLatest = t('settings.mock.turnPromptLatest');
const promptPrev = t('settings.mock.turnPromptPrev');
const mainContext = {
totalTokens: 142800,
limitTokens: 256000,
compactionLimitTokens: 256000,
usedPct: 55.8,
toolResultsTokens: 86400,
assistantTokens: 24200,
systemToolsTokens: 11800,
checkpointTokens: 7600,
systemPromptTokens: 5800,
skillsTokens: 3100,
userRulesTokens: 1900,
userInputTokens: 1120,
mcpToolsTokens: 540,
subagentTokens: 340,
};
const subContext = {
totalTokens: 72704,
limitTokens: 256000,
compactionLimitTokens: 256000,
usedPct: 28.4,
toolResultsTokens: 51200,
assistantTokens: 11400,
systemToolsTokens: 5600,
systemPromptTokens: 3400,
userInputTokens: 1104,
checkpointTokens: 0,
skillsTokens: 0,
userRulesTokens: 0,
mcpToolsTokens: 0,
subagentTokens: 0,
};
const mockSteps = [
{
stepIndex: 24,
agentCascadeId: 'mock-main',
agentId: 'main',
agentIndex: 0,
isSubagent: false,
agentBadge: '主',
agentLabel: t('fmt.mainAgent'),
modelLabel: 'Gemini 4 Carbon (High)',
modelShort: 'gemini-4-carbon',
rawModel: 'MODEL_PLACEHOLDER_M37',
upstreamModel: 'gemini-4-carbon-high',
tokPerSec: 68.4,
ttftSec: 1.15,
totalDurationSec: 12.6,
streamDurationSec: 11.45,
contextTokens: 142800,
inputTokens: 7800,
cacheReadTokens: 133580,
outputTokens: 1420,
thinkingTokens: 860,
responseTokens: 560,
cacheHitPct: 94.5,
costUsd: 0.042,
createdAtMs: anchorMinMs - 14_000,
turnIndex: 2,
rootTurnIndex: 2,
isTurnStart: false,
isRootTurnStart: false,
isLatestTurn: true,
isRootLatestTurn: true,
turnPrompt: promptLatest,
rootTurnPrompt: promptLatest,
},
{
stepIndex: 8,
agentCascadeId: 'mock-sub-1',
agentId: 'sub-1',
agentIndex: 1,
isSubagent: true,
agentBadge: '子1',
agentRole: subRole,
agentLabel: subRole,
modelLabel: 'Gemini 3.8 Flash',
modelShort: 'gemini-3.8-flash',
rawModel: 'MODEL_PLACEHOLDER_M42',
upstreamModel: 'gemini-3.8-flash-n',
tokPerSec: 96.2,
ttftSec: 0.68,
totalDurationSec: 5.4,
streamDurationSec: 4.72,
contextTokens: 72704,
inputTokens: 8600,
cacheReadTokens: 63400,
outputTokens: 704,
thinkingTokens: 240,
responseTokens: 464,
cacheHitPct: 88.1,
costUsd: 0.009,
createdAtMs: anchorMinMs - 42_000,
turnIndex: 1,
rootTurnIndex: 2,
isTurnStart: true,
isRootTurnStart: false,
isLatestTurn: true,
isRootLatestTurn: true,
turnPrompt: promptLatest,
rootTurnPrompt: promptLatest,
},
{
stepIndex: 22,
agentCascadeId: 'mock-main',
agentId: 'main',
agentIndex: 0,
isSubagent: false,
agentBadge: '主',
agentLabel: t('fmt.mainAgent'),
modelLabel: 'Gemini 4 Carbon (High)',
modelShort: 'gemini-4-carbon',
rawModel: 'MODEL_PLACEHOLDER_M37',
upstreamModel: 'gemini-4-carbon-high',
tokPerSec: 46.5,
ttftSec: 3.4,
totalDurationSec: 15.8,
streamDurationSec: 12.4,
contextTokens: 128400,
inputTokens: 49200,
cacheReadTokens: 78100,
outputTokens: 1100,
thinkingTokens: 720,
responseTokens: 380,
cacheHitPct: 61.4,
costUsd: 0.068,
createdAtMs: anchorMinMs - 88_000,
turnIndex: 2,
rootTurnIndex: 2,
isTurnStart: true,
isRootTurnStart: true,
isLatestTurn: true,
isRootLatestTurn: true,
turnPrompt: promptLatest,
rootTurnPrompt: promptLatest,
},
{
stepIndex: 19,
agentCascadeId: 'mock-main',
agentId: 'main',
agentIndex: 0,
isSubagent: false,
agentBadge: '主',
agentLabel: t('fmt.mainAgent'),
modelLabel: 'Gemini 4 Carbon (High)',
modelShort: 'gemini-4-carbon',
rawModel: 'MODEL_PLACEHOLDER_M37',
upstreamModel: 'gemini-4-carbon-high',
tokPerSec: 17.8,
ttftSec: 19.4,
totalDurationSec: 31.2,
streamDurationSec: 11.8,
contextTokens: 96200,
inputTokens: 95400,
cacheReadTokens: 0,
outputTokens: 800,
thinkingTokens: 540,
responseTokens: 260,
cacheHitPct: 0,
costUsd: 0.198,
createdAtMs: anchorMinMs - 215_000,
turnIndex: 1,
rootTurnIndex: 1,
isTurnStart: true,
isRootTurnStart: true,
isLatestTurn: false,
isRootLatestTurn: false,
turnPrompt: promptPrev,
rootTurnPrompt: promptPrev,
},
];
const mainAgent = {
agentId: 'main',
cascadeId: 'mock-main',
isMain: true,
index: 0,
badgeText: '主',
role: t('fmt.mainAgent'),
isRunning: true,
stepCount: 16,
speedSampleCount: 15,
latestTokPerSec: 68.4,
avgTokPerSec: 54.8,
latestTtftSec: 1.15,
avgTtftSec: 1.62,
latestStepCostUsd: 0.042,
sessionCostUsd: 1.16,
latestCacheHitPct: 94.5,
sessionCacheHitPct: 89.2,
latestPromptTokens: 141380,
inputTokens: 152400,
cacheReadTokens: 1260000,
outputTokens: 22100,
totalTokens: 1434500,
latestModelLabel: 'Gemini 4 Carbon (High)',
latestModelShort: 'gemini-4-carbon',
latestRawModel: 'MODEL_PLACEHOLDER_M37',
latestUpstreamModel: 'gemini-4-carbon-high',
activeModelLabel: 'Gemini 4 Carbon (High)',
activeModelShort: 'gemini-4-carbon',
context: mainContext,
recentSteps: mockSteps.filter((s) => !s.isSubagent),
};
const subAgent1 = {
agentId: 'sub-1',
cascadeId: 'mock-sub-1',
isMain: false,
index: 1,
badgeText: '子1',
shortLabel: `${t('fmt.subAgent')} #1`,
role: subRole,
isRunning: false,
stepCount: 8,
speedSampleCount: 8,
latestTokPerSec: 96.2,
avgTokPerSec: 88.5,
latestTtftSec: 0.68,
avgTtftSec: 0.82,
latestStepCostUsd: 0.009,
sessionCostUsd: 0.12,
latestCacheHitPct: 88.1,
sessionCacheHitPct: 86.4,
latestPromptTokens: 72000,
inputTokens: 34000,
cacheReadTokens: 280000,
outputTokens: 6300,
totalTokens: 320300,
latestModelLabel: 'Gemini 3.8 Flash',
latestModelShort: 'gemini-3.8-flash',
latestRawModel: 'MODEL_PLACEHOLDER_M42',
latestUpstreamModel: 'gemini-3.8-flash-n',
activeModelLabel: 'Gemini 3.8 Flash',
activeModelShort: 'gemini-3.8-flash',
context: subContext,
recentSteps: mockSteps.filter((s) => s.isSubagent),
};
const aggregated = {
...mainAgent,
stepCount: 24,
speedSampleCount: 23,
avgTokPerSec: 59.6,
avgTtftSec: 1.38,
sessionCostUsd: 1.28,
sessionCacheHitPct: 88.9,
inputTokens: 186400,
cacheReadTokens: 1540000,
outputTokens: 28400,
totalTokens: 1754800,
activeAgentBadge: '主',
recentSteps: mockSteps,
};
return {
settings: mergedSettings,
account: {
planName: 'Google AI Pro',
aiCredits: 1200,
},
quotas: {
activePool: {
family: 'Gemini',
poolKey: 'Gemini',
poolLabel: 'Gemini',
usedPct: 36,
remainingPct: 64,
resetTime: reset5hIso,
weeklyUsedPct: 48,
weeklyRemainingPct: 52,
weeklyResetTime: resetWkIso,
},
pools: [
{
poolKey: 'Gemini',
poolLabel: 'Gemini',
family: 'Gemini',
usedPct: 36,
remainingPct: 64,
resetTime: reset5hIso,
weeklyUsedPct: 48,
weeklyRemainingPct: 52,
weeklyResetTime: resetWkIso,
cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 },
cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 },
},
{
poolKey: 'Claude & GPT',
poolLabel: 'Claude & GPT',
family: 'Claude & GPT',
usedPct: 68,
remainingPct: 32,
resetTime: resetClaude5hIso,
weeklyUsedPct: 41,
weeklyRemainingPct: 59,
weeklyResetTime: resetWkIso,
cycle5h: { tokens: 620000, costUsd: 2.15, calls: 11 },
cycleWeekly: { tokens: 5800000, costUsd: 18.6, calls: 92 },
},
],
weekly: {
isOfficial: true,
usedPct: 48,
remainingPct: 52,
resetTime: resetWkIso,
tokens: 20000000,
costUsd: 30.0,
calls: 278,
},
},
runningConversations: [
{
cascadeId: 'mock-preview-conv',
title: sessionTitle,
isCurrentSelected: true,
isMainRunning: true,
isRunning: true,
subagentCount: 1,
runningSubagentCount: 0,
latestTokPerSec: 68.4,
contextUsedPct: 55.8,
mainActivity: {
phase: 'generating',
label: t('live.generating'),
stepProgress: '#24',
detail: 'src/auth/tokenRefresh.ts',
startedAtMs: Date.now() - 8000,
signature: 'mock-preview:24',
},
subagents: [
{
cascadeId: 'mock-sub-1',
index: 1,
badgeText: '子1',
shortLabel: `${t('fmt.subAgent')} #1`,
role: subRole,
isRunning: false,
stepCount: 8,
lastModifiedMs: anchorMinMs - 42_000,
liveActivity: {
phase: 'done',
label: t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: anchorMinMs - 42_000,
signature: 'mock-sub-1:8',
},
},
],
},
],
activeConversation: {
...mainAgent,
cascadeId: 'mock-preview-conv',
title: sessionTitle,
hasSubagents: true,
agents: [mainAgent, subAgent1],
aggregated,
recentSteps: mockSteps,
},
};
}
@@ -0,0 +1,362 @@
/**
* @fileoverview Shared Decoupled Capsule Bar Primitives & Widget (`CapsuleBarWidget.js`).
* Powers both the live host window capsule (`WindowOverlayShell.js`) and the
* real-UI structure preview (`SettingsStructureTab.js`), ensuring 100% DOM/CSS parity.
*/
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { t } from '../../i18n/index.js';
import { createSvgIcon, SVG_NS } from '../../icons/SvgIcon.js';
import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js';
import {
normalizeClientTopbarSlots,
normalizeClientWindowMountMode,
resolveScopedConversation,
} from '../../store/telemetryStore.js';
export const RING_RADIUS = 5.2;
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
/**
* Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring.
*/
export function createCapsuleSlotNode(slotIndex, initialMetric) {
const ringSvg = document.createElementNS(SVG_NS, 'svg');
ringSvg.setAttribute('viewBox', '0 0 14 14');
ringSvg.setAttribute('class', 'wm-ring-svg');
ringSvg.setAttribute('aria-hidden', 'true');
const ringTrack = document.createElementNS(SVG_NS, 'circle');
ringTrack.setAttribute('cx', '7');
ringTrack.setAttribute('cy', '7');
ringTrack.setAttribute('r', String(RING_RADIUS));
ringTrack.setAttribute('class', 'wm-ring-track');
const ringFill = document.createElementNS(SVG_NS, 'circle');
ringFill.setAttribute('cx', '7');
ringFill.setAttribute('cy', '7');
ringFill.setAttribute('r', String(RING_RADIUS));
ringFill.setAttribute('class', 'wm-ring-fill');
ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE));
ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE));
ringSvg.appendChild(ringTrack);
ringSvg.appendChild(ringFill);
const isNone = initialMetric === 'none';
const isCtx = initialMetric === 'context';
const textSpan = h('span', {
className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text',
text: isNone
? ''
: isCtx
? '--%'
: initialMetric === 'tps'
? '-- t/s'
: t('capsule.quotaUnknown'),
});
const el = h(
'span',
{
className: isNone
? 'wm-cap-slot'
: isCtx
? 'wm-cap-slot wm-ctx-seg'
: initialMetric === 'tps'
? 'wm-cap-slot wm-seg-speed'
: 'wm-cap-slot wm-seg-quota',
hidden: isNone,
'data-slot-idx': String(slotIndex),
'data-metric': initialMetric,
'data-vis-rank': isNone ? '' : String(slotIndex + 1),
},
isCtx ? [ringSvg, textSpan] : [textSpan]
);
return {
el,
ringSvg,
ringFill,
textSpan,
ringMounted: isCtx,
};
}
/**
* Patch 5 pre-allocated capsule slots and 4 separators in-place via `metricRegistry`.
*/
export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) {
let visRank = 0;
const visRanks = [0, 0, 0, 0, 0];
for (let i = 0; i < capsuleSlots.length; i += 1) {
const slot = capsuleSlots[i];
const metricKey = i < slotKeys.length ? slotKeys[i] : 'none';
const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (pres.hidden) {
patchAttr(slot.el, 'hidden', true);
patchAttr(slot.el, 'data-metric', 'none');
patchAttr(slot.el, 'data-vis-rank', '');
continue;
}
visRank += 1;
visRanks[i] = visRank;
patchAttr(slot.el, 'hidden', false);
patchAttr(slot.el, 'data-metric', pres.metric);
patchAttr(slot.el, 'data-vis-rank', String(visRank));
if (pres.showRing && !slot.ringMounted) {
slot.el.insertBefore(slot.ringSvg, slot.textSpan);
slot.ringMounted = true;
} else if (!pres.showRing && slot.ringMounted) {
slot.ringSvg.remove();
slot.ringMounted = false;
}
const toneCls =
pres.toneClass || (pres.danger ? 'tone-danger' : pres.warn ? 'tone-warn' : '');
const fullSegClass = `${pres.segClass}${pres.running ? ' state-running' : ''}${toneCls ? ` ${toneCls}` : ''}`;
patchAttr(slot.el, 'class', fullSegClass);
const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`;
patchAttr(slot.textSpan, 'class', fullTextClass);
patchText(slot.textSpan, pres.text);
if (pres.showRing) {
slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset));
patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger });
}
}
for (let s = 0; s < capsuleSeps.length; s += 1) {
const sepEl = capsuleSeps[s];
const nextRank = visRanks[s + 1] || 0;
const showSep = nextRank >= 2;
patchAttr(sepEl, 'hidden', !showSep);
patchAttr(sepEl, 'data-sep-for-rank', showSep ? String(nextRank) : '');
}
}
/**
* Standalone Capsule Bar Preview Widget mounting the real `.wm-multi-btn` and `.wm-capsule-btn`
* inside a contextual host bar (`dual` titlebar, `composer` toolbar, or `sidebar` disabled state).
*/
export const CapsuleBarWidget = defineComponent({
name: 'CapsuleBarWidget',
setup() {
const multiDot = h('span', { className: 'wm-multi-dot' });
const multiLabel = h('span', {
className: 'wm-multi-label',
text: t('capsule.multiZero'),
});
const multiBtn = h(
'button',
{
type: 'button',
className: 'wm-multi-btn',
tabindex: '-1',
'aria-hidden': 'true',
},
[multiDot, multiLabel]
);
const capsuleSlots = [
createCapsuleSlotNode(0, 'context'),
createCapsuleSlotNode(1, 'tps'),
createCapsuleSlotNode(2, 'quota_auto'),
createCapsuleSlotNode(3, 'none'),
createCapsuleSlotNode(4, 'none'),
];
const capsuleSeps = [
h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }),
h('span', { className: 'wm-sep wm-sep-quota', 'data-sep-for-rank': '3' }),
h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }),
h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }),
];
const capsuleBtn = h(
'button',
{
type: 'button',
className: 'wm-capsule-btn',
tabindex: '-1',
'aria-hidden': 'true',
},
[
capsuleSlots[0].el,
capsuleSeps[0],
capsuleSlots[1].el,
capsuleSeps[1],
capsuleSlots[2].el,
capsuleSeps[2],
capsuleSlots[3].el,
capsuleSeps[3],
capsuleSlots[4].el,
]
);
const capsuleCluster = h('div', { className: 'preview-capsule-cluster' }, [
multiBtn,
capsuleBtn,
]);
// Contextual host chrome affordances for Titlebar vs Composer vs Sidebar-only
const titlebarLeftMock = h('div', { className: 'preview-host-left is-titlebar' }, [
h('span', { className: 'preview-win-title', text: 'Antigravity' }),
]);
const composerLeftMock = h(
'div',
{ className: 'preview-host-left is-composer', hidden: true },
[
h('span', { className: 'preview-composer-chip' }, [
h('span', { text: 'Auto' }),
createSvgIcon('chevron-down', { size: 10 }),
]),
h('span', { className: 'preview-composer-chip' }, [
h('span', { text: 'Carbon (High)' }),
createSvgIcon('chevron-down', { size: 10 }),
]),
]
);
const titlebarRightMock = h('div', { className: 'preview-win-controls', 'aria-hidden': 'true' }, [
h('span', { className: 'preview-win-dot' }),
h('span', { className: 'preview-win-dot' }),
h('span', { className: 'preview-win-dot' }),
]);
const composerSendMock = h(
'span',
{ className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true },
[createSvgIcon('arrow-up', { size: 11 })]
);
const hostBarEl = h(
'div',
{ className: 'preview-capsule-bar', 'data-mount-mode': 'dual' },
[titlebarLeftMock, composerLeftMock, capsuleCluster, titlebarRightMock, composerSendMock]
);
const sidebarHintEl = h('div', {
className: 'preview-sidebar-note',
hidden: true,
text: t('settings.str.previewMountSidebarHint'),
});
const rootEl = h('div', { className: 'capsule-preview-widget' }, [hostBarEl, sidebarHintEl]);
function update({ data } = {}) {
const settings = data?.settings || {};
const mountMode = normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
const showMulti = settings.showTopbarMultiSession !== false;
const slotKeys = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
const isComposer = mountMode === 'composer';
const isSidebar = mountMode === 'sidebar';
patchAttr(hostBarEl, 'data-mount-mode', mountMode);
patchClasses(hostBarEl, {
'is-composer': isComposer,
'is-sidebar-only': isSidebar,
});
patchAttr(titlebarLeftMock, 'hidden', isComposer);
patchAttr(titlebarRightMock, 'hidden', isComposer);
patchAttr(composerLeftMock, 'hidden', !isComposer);
patchAttr(composerSendMock, 'hidden', !isComposer);
patchAttr(sidebarHintEl, 'hidden', !isSidebar);
patchText(sidebarHintEl, t('settings.str.previewMountSidebarHint'));
patchAttr(multiBtn, 'hidden', !showMulti);
if (!data) {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero'));
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false });
return;
}
const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
data,
'all',
'auto'
);
const activeConv = data.activeConversation || {};
const capActive = scopedConv || aggregated || activeConv;
const ctx = ctxAgent?.context || capActive.context || activeConv.context || {};
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const dashOffset = +(
RING_CIRCUMFERENCE *
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
).toFixed(2);
const rawRunningList = Array.isArray(data.runningConversations)
? data.runningConversations
: [];
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
patchClasses(multiBtn, {
'is-running': runningCount > 0 && !hasWaiting,
'is-waiting': runningCount > 0 && hasWaiting,
});
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
patchText(multiLabel, multiBtnText);
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
: null;
patchClasses(capsuleBtn, { 'is-running': isRunning });
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, {
hasTelemetry: true,
usedPct,
dashOffset,
isRunning,
tps: capActive.latestTokPerSec ?? null,
avgTps: capActive.avgTokPerSec ?? null,
ttft: capActive.latestTtftSec ?? null,
stepCost: capActive.latestStepCostUsd ?? null,
sessionCost: capActive.sessionCostUsd ?? null,
cacheHitPct:
Number(capActive.stepCount || 0) > 0
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
: null,
latestPromptTokens: capActive.latestPromptTokens ?? null,
sessionTokens,
quotas: data.quotas,
});
}
return {
el: rootEl,
refs: {
update,
multiBtn,
capsuleBtn,
capsuleSlots,
capsuleSeps,
hostBarEl,
},
};
},
});
@@ -178,6 +178,14 @@ export const ContextWindowWidget = defineComponent({
name: 'ContextWindowWidget', name: 'ContextWindowWidget',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
const interactiveInspector = props.interactiveInspector !== false; const interactiveInspector = props.interactiveInspector !== false;
const getCtxAgentId =
typeof props.getCtxAgentId === 'function'
? props.getCtxAgentId
: () => uiStore.getState().ctxInspectorAgentId;
const setCtxAgentId =
typeof props.setCtxAgentId === 'function'
? props.setCtxAgentId
: (nextId) => uiStore.setState({ ctxInspectorAgentId: nextId });
const isVisibleFn = const isVisibleFn =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true; typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
@@ -275,7 +283,6 @@ export const ContextWindowWidget = defineComponent({
} }
} }
const uiSt = uiStore.getState();
const { const {
hasSubagents, hasSubagents,
effectiveCtxScope, effectiveCtxScope,
@@ -283,7 +290,7 @@ export const ContextWindowWidget = defineComponent({
aggregated, aggregated,
scopedConv, scopedConv,
ctxAgent, ctxAgent,
} = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId); } = resolveScopedConversation(data, 'all', getCtxAgentId());
const active = scopedConv || data.activeConversation || {}; const active = scopedConv || data.activeConversation || {};
const ctx = ctxAgent?.context || active.context || {}; const ctx = ctxAgent?.context || active.context || {};
@@ -411,7 +418,7 @@ export const ContextWindowWidget = defineComponent({
ctxPillsExpanded = !ctxPillsExpanded; ctxPillsExpanded = !ctxPillsExpanded;
if (latestData) update({ data: latestData }); if (latestData) update({ data: latestData });
} else { } else {
uiStore.setState({ ctxInspectorAgentId: item.key }); setCtxAgentId(item.key);
} }
}; };
}, },
@@ -423,6 +430,9 @@ export const ContextWindowWidget = defineComponent({
const totalTokens = Number(ctx.totalTokens || 0); const totalTokens = Number(ctx.totalTokens || 0);
const usedPct = const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const ctxToneCls =
usedPct >= 88 ? 'tone-danger' : usedPct >= 70 ? 'tone-warn' : '';
patchAttr(ctxSummaryText, 'class', ctxToneCls ? `text-mono ${ctxToneCls}` : 'text-mono');
patchText( patchText(
ctxSummaryText, ctxSummaryText,
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
@@ -28,6 +28,11 @@ export const LiveActivityWidget = defineComponent({
name: 'LiveActivityWidget', name: 'LiveActivityWidget',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
const interactive = props.interactive !== false; const interactive = props.interactive !== false;
const preview = Boolean(props.preview);
const getCtxAgentId =
typeof props.getCtxAgentId === 'function'
? props.getCtxAgentId
: () => uiStore.getState().ctxInspectorAgentId;
const isVisibleFn = const isVisibleFn =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true; typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
@@ -203,11 +208,10 @@ export const LiveActivityWidget = defineComponent({
return; return;
} }
const uiSt = uiStore.getState();
const { agents, aggregated } = resolveScopedConversation( const { agents, aggregated } = resolveScopedConversation(
data, data,
'all', 'all',
uiSt.ctxInspectorAgentId getCtxAgentId()
); );
const rawRunningList = const rawRunningList =
@@ -310,7 +314,7 @@ export const LiveActivityWidget = defineComponent({
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
patchText(refs.titleEl, convTitle); patchText(refs.titleEl, convTitle);
if (interactive) { if (interactive && !preview) {
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
refs.titleEl.onclick = () => { refs.titleEl.onclick = () => {
if (item.cascadeId && item.cascadeId !== 'current') { if (item.cascadeId && item.cascadeId !== 'current') {
@@ -23,7 +23,11 @@ import { uiStore } from '../../store/uiStore.js';
export const MetricMatrixWidget = defineComponent({ export const MetricMatrixWidget = defineComponent({
name: 'MetricMatrixWidget', name: 'MetricMatrixWidget',
setup() { setup({ props }) {
const getCtxAgentId =
typeof props?.getCtxAgentId === 'function'
? props.getCtxAgentId
: () => uiStore.getState().ctxInspectorAgentId;
const matrixEl = h('section', { const matrixEl = h('section', {
className: 'telemetry-matrix', className: 'telemetry-matrix',
'aria-label': t('module.metrics'), 'aria-label': t('module.metrics'),
@@ -54,11 +58,10 @@ export const MetricMatrixWidget = defineComponent({
patchAttr(matrixEl, 'data-cols', String(colCount)); patchAttr(matrixEl, 'data-cols', String(colCount));
patchStyleVar(matrixEl, '--matrix-cols', String(colCount)); patchStyleVar(matrixEl, '--matrix-cols', String(colCount));
const uiSt = uiStore.getState();
const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation( const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation(
data, data,
'all', 'all',
uiSt.ctxInspectorAgentId getCtxAgentId()
); );
const active = scopedConv || data?.activeConversation || {}; const active = scopedConv || data?.activeConversation || {};
const ctx = ctxAgent?.context || active.context || {}; const ctx = ctxAgent?.context || active.context || {};
@@ -208,7 +208,7 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
); );
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(refs.fill5h, { patchClasses(refs.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85, 'tone-warn': used5hVal >= 70 && used5hVal < 85,
'tone-danger': used5hVal >= 85, 'tone-danger': used5hVal >= 85,
}); });
@@ -255,7 +255,7 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
); );
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(refs.fillWk, { patchClasses(refs.fillWk, {
'tone-warn': usedWkVal >= 60 && usedWkVal < 85, 'tone-warn': usedWkVal >= 70 && usedWkVal < 85,
'tone-danger': usedWkVal >= 85, 'tone-danger': usedWkVal >= 85,
}); });
} }
@@ -0,0 +1,425 @@
/**
* @fileoverview Reusable Decoupled Step Table Widget (`StepTableWidget.js`).
* Powers both `StepsDetailView` ("按步查看") and `SettingsStructureTab` live preview,
* dynamically rendering 2..12 columns via `stepColumnRegistry.js`, turn rail + prompt
* preview tooltips, and independent Main/Sub agent badges.
*/
import { defineComponent } from '../../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchText,
} from '../../core/domPatch.js';
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
import {
DEFAULT_STEP_COLUMN_KEYS,
STEP_COLUMN_REGISTRY,
} from '../../registries/stepColumnRegistry.js';
import {
formatAgentBadgeText,
formatAgentLabel,
getAgentBadgeClass,
} from '../../store/telemetryStore.js';
export function formatTurnPromptText(rawPrompt) {
const text = String(rawPrompt || '').trim();
if (!text || !isEnglishLocale()) return text;
if (text === '[图片/附件提问]') return t('steps.turnMediaOnly');
if (text.endsWith(' [附图]')) {
return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`;
}
return text;
}
export const StepTableWidget = defineComponent({
name: 'StepTableWidget',
setup({ props, onCleanup }) {
const standalone = Boolean(props.standalone);
const interactiveBadges = props.interactiveBadges !== false;
const onSelectAgentScopes =
typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null;
const stepsTheadRow = h('tr');
const stepsTbody = h('tbody');
function syncTableHeaderColumns(colKeys) {
const locale = getEffectiveLocale();
patchKeyedList(stepsTheadRow, colKeys, {
keyFn: (colKey) => colKey,
sigFn: (colKey) => `${locale}:${colKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel()}`,
createRow: (colKey) => {
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel() });
return { el: th, refs: { th } };
},
updateRow: (refs, colKey) => {
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel());
},
});
}
syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS);
const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [
h('thead', {}, [stepsTheadRow]),
stepsTbody,
]);
const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]);
const turnTipEl = h('div', {
className: 'turn-prompt-tip',
role: 'tooltip',
hidden: true,
});
const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true);
const standaloneHostEl = standalone
? h('div', { className: 'step-table-preview-host' }, [stepsTablePane, turnTipEl])
: null;
let boundsContainerGetter =
typeof props.getBoundsEl === 'function'
? props.getBoundsEl
: () => standaloneHostEl || stepsTablePane;
function setBoundsElGetter(fn) {
if (typeof fn === 'function') {
boundsContainerGetter = fn;
}
}
function showTurnTip(anchorCell, promptText) {
const text = String(promptText || '').trim();
const boundsEl = boundsContainerGetter?.();
if (!anchorCell || !text) {
hideTurnTip();
return;
}
patchText(turnTipEl, text);
patchAttr(turnTipEl, 'hidden', false);
if (
boundsEl &&
typeof boundsEl.getBoundingClientRect === 'function' &&
typeof anchorCell.getBoundingClientRect === 'function'
) {
const panelRect = boundsEl.getBoundingClientRect();
const cellRect = anchorCell.getBoundingClientRect();
if (panelRect.width > 0 && panelRect.height > 0) {
const tipH = turnTipEl.offsetHeight || 36;
const tipW = turnTipEl.offsetWidth || 180;
const placeAbove =
panelRect.bottom - cellRect.bottom < tipH + 10 &&
cellRect.top - panelRect.top > tipH + 6;
const topPx = placeAbove
? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4))
: Math.round(cellRect.bottom - panelRect.top + 4);
const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8));
const leftPx = Math.min(
maxLeft,
Math.max(6, Math.round(cellRect.left - panelRect.left + 4))
);
turnTipEl.style.top = `${topPx}px`;
turnTipEl.style.left = `${leftPx}px`;
}
}
}
stepsTablePane.addEventListener('scroll', hideTurnTip);
stepsTbody.addEventListener('mouseleave', hideTurnTip);
function renderStepTable(
tableSteps,
cascadeId,
colKeys,
locale,
{
effectiveScopes = ['all'],
hasSubagents = false,
isMergedMultiAgents = false,
showStepTurnRail = true,
showStepAgentBadge = true,
displaySettings = {},
} = {}
) {
const colOrderSig = colKeys.join(',');
const wantedSet = new Set(colKeys);
syncTableHeaderColumns(colKeys);
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
const cellCtx = {
hasSubagents,
showAgentBadge,
effectiveScopes,
scopeSigKey: effectiveScopes.join(','),
displaySettings,
onSelectAgentScopes,
};
const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents);
const getStepTurnIdx = (st) =>
useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex;
const getStepIsStart = (st) =>
Boolean(useRootTurn ? (st?.isRootTurnStart ?? st?.isTurnStart) : st?.isTurnStart);
const getStepIsLatest = (st) =>
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
const getStepPrompt = (st) =>
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
const turnKeyOf = (st) => {
if (!showStepTurnRail) return '';
const tIdx = getStepTurnIdx(st);
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`;
};
const decoratedSteps = tableSteps.map((st, idx) => {
const tKey = turnKeyOf(st);
const hasTurn = Boolean(tKey);
const hasUp = Boolean(hasTurn && idx > 0 && turnKeyOf(tableSteps[idx - 1]) === tKey);
const hasDown = Boolean(
hasTurn && idx + 1 < tableSteps.length && turnKeyOf(tableSteps[idx + 1]) === tKey
);
return {
st,
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
hasTurn,
hasUp,
hasDown,
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
isLatest: hasTurn && getStepIsLatest(st),
prompt: hasTurn ? formatTurnPromptText(getStepPrompt(st)) : '',
};
});
const railActive = Boolean(showStepTurnRail && decoratedSteps.some((d) => d.hasTurn));
if (!railActive) {
hideTurnTip();
}
patchClasses(stepsTableEl, { 'has-turn-rail': railActive });
patchKeyedList(stepsTbody, decoratedSteps, {
keyFn: (item) => item.rowKey,
sigFn: (item) => {
const { st } = item;
const parts = colKeys
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
.join('|');
const badgeSig = `${showAgentBadge}:${interactiveBadges}:${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`;
return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
},
createRow: () => {
const tr = h('tr');
const railLineEl = h('span', { className: 'turn-rail-line', hidden: true });
const railDotEl = h('span', { className: 'turn-rail-dot', hidden: true });
const railEl = h(
'span',
{ className: 'turn-rail', 'aria-hidden': 'true', hidden: true },
[railLineEl, railDotEl]
);
const agentBadgeEl = h('span', {
className: 'agent-badge',
hidden: true,
style: 'margin-right: 4px;',
});
return {
el: tr,
refs: {
cellMap: new Map(),
colOrderSig: '',
railEl,
railLineEl,
railDotEl,
agentBadgeEl,
hoverTd: null,
},
};
},
updateRow: (refs, item, _idx, tr) => {
const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item;
if (refs.colOrderSig !== colOrderSig) {
if (refs.hoverTd) {
refs.hoverTd.onmouseenter = null;
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
refs.hoverTd = null;
}
for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) {
if (refs.railEl.parentNode === entry.td) {
entry.td.removeChild(refs.railEl);
}
if (refs.agentBadgeEl.parentNode === entry.td) {
entry.td.removeChild(refs.agentBadgeEl);
}
tr.removeChild(entry.td);
refs.cellMap.delete(oldColKey);
}
}
for (const [i, colKey] of colKeys.entries()) {
if (!refs.cellMap.has(colKey)) {
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
}
const targetTd = refs.cellMap.get(colKey).td;
const currentTd = tr.children[i] || null;
if (currentTd !== targetTd) {
tr.insertBefore(targetTd, currentTd);
}
}
refs.colOrderSig = colOrderSig;
}
for (const colKey of colKeys) {
const cellEntry = refs.cellMap.get(colKey);
STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx);
}
const firstColKey = colKeys[0];
const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null;
if (firstTd) {
if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) {
firstTd.insertBefore(refs.railEl, firstTd.firstChild);
}
const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null;
if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) {
firstTd.insertBefore(refs.agentBadgeEl, afterRail);
}
}
patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd);
if (showAgentBadge && firstTd) {
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : '';
patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`);
const badgeText = isEnglishLocale()
? formatAgentBadgeText({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
badgeText: st.agentBadge,
})
: st.agentBadge || (st.isSubagent ? '子' : '主');
patchText(refs.agentBadgeEl, badgeText);
if (interactiveBadges && onSelectAgentScopes) {
const targetScope = st.agentId || 'main';
const isSoleTarget =
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
const agentName = isEnglishLocale()
? formatAgentLabel({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
role: st.agentRole || '',
})
: st.agentLabel || t('steps.unitAgent');
patchAttr(
refs.agentBadgeEl,
'title',
isSoleTarget
? t('steps.badgeBackAll')
: t('steps.badgeFilterAgent', { agent: agentName })
);
refs.agentBadgeEl.onclick = (e) => {
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
const next = effectiveScopes.includes(targetScope)
? effectiveScopes.filter((id) => id !== targetScope)
: [...effectiveScopes, targetScope];
onSelectAgentScopes(next.length > 0 ? next : ['all']);
} else {
onSelectAgentScopes(isSoleTarget ? ['all'] : [targetScope]);
}
};
} else {
patchAttr(refs.agentBadgeEl, 'title', null);
refs.agentBadgeEl.onclick = null;
}
} else {
refs.agentBadgeEl.onclick = null;
}
const showRowRail = Boolean(railActive && hasTurn && firstTd);
patchAttr(refs.railEl, 'hidden', !showRowRail);
if (showRowRail) {
patchClasses(refs.railEl, {
'is-latest': isLatest,
'has-up': hasUp,
'has-down': hasDown,
});
patchAttr(refs.railLineEl, 'hidden', !hasUp && !hasDown);
const showOrigin = isStart;
const showCap = !showOrigin && !hasUp && hasDown;
patchAttr(refs.railDotEl, 'hidden', !showOrigin && !showCap);
patchClasses(refs.railDotEl, {
'is-origin': showOrigin,
'is-cap': showCap,
});
}
const targetHoverTd = firstTd;
if (refs.hoverTd && refs.hoverTd !== targetHoverTd) {
refs.hoverTd.onmouseenter = null;
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
}
refs.hoverTd = targetHoverTd;
if (targetHoverTd) {
const badgeEl = refs.agentBadgeEl;
if (firstColKey === 'step') {
targetHoverTd.onmouseenter = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
showTurnTip(targetHoverTd, prompt);
};
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
} else {
targetHoverTd.onmouseenter = null;
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
const rect = targetHoverTd.getBoundingClientRect?.();
const relX = rect ? (ev?.clientX ?? 0) - rect.left : 0;
if (relX <= 18) {
showTurnTip(targetHoverTd, prompt);
} else {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
}
}
},
});
}
onCleanup(() => {
stepsTablePane.removeEventListener('scroll', hideTurnTip);
stepsTbody.removeEventListener('mouseleave', hideTurnTip);
});
return {
el: standaloneHostEl || stepsTablePane,
refs: {
stepsTablePane,
stepsTableEl,
stepsTheadRow,
stepsTbody,
turnTipEl,
syncTableHeaderColumns,
renderStepTable,
hideTurnTip,
setBoundsElGetter,
},
};
},
});
+16 -5
View File
@@ -398,6 +398,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.latestSub': 'Up to date ({mode})', 'settings.gen.latestSub': 'Up to date ({mode})',
// Preferences -> Structure Tab // Preferences -> Structure Tab
'settings.str.thirdTabAria': 'Structure section tabs',
'settings.str.tabMount': 'Mount & Bar',
'settings.str.tabHover': 'Hover View',
'settings.str.tabOverview': 'Overview',
'settings.str.tabSteps': 'Step Table',
'settings.str.previewMountSidebarHint': 'Window capsule is disabled in Sidebar Only mode; switching back to Titlebar or Composer applies the capsule above',
'settings.str.mountSection': 'Mount & Capsule Bar', 'settings.str.mountSection': 'Mount & Capsule Bar',
'settings.str.mountBadge': '{count}/5 slots', 'settings.str.mountBadge': '{count}/5 slots',
'settings.str.mountMode': 'Panel Mount Mode', 'settings.str.mountMode': 'Panel Mount Mode',
@@ -407,32 +413,37 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.multiToggle': 'Active Sessions Pill', 'settings.str.multiToggle': 'Active Sessions Pill',
'settings.str.show': 'Show', 'settings.str.show': 'Show',
'settings.str.hide': 'Hide', 'settings.str.hide': 'Hide',
'settings.str.capsuleSlotsLabel': 'Capsule Metrics & Order (Left → Right, 1–5)', 'settings.str.capsuleSlotsLabel': 'Capsule Metrics & Order (Left → Right, 1–5, draggable)',
'settings.str.addCapsuleSlot': 'Add Slot ({count}/{max})', 'settings.str.addCapsuleSlot': 'Add Slot ({count}/{max})',
'settings.str.hoverSection': 'Hover Quick-View', 'settings.str.hoverSection': 'Hover Quick-View',
'settings.str.hoverBadgeOff': 'Off', 'settings.str.hoverBadgeOff': 'Off',
'settings.str.hoverBadgeCount': '{count} modules', 'settings.str.hoverBadgeCount': '{count} modules',
'settings.str.hoverModulesLabel': 'Hover Popup Modules (Top → Bottom, 0–4)', 'settings.str.hoverModulesLabel': 'Hover Popup Modules (Top → Bottom, 0–4, draggable)',
'settings.str.hoverEmptyHint': 'Hover quick-view disabled (click capsule to open full panel)', 'settings.str.hoverEmptyHint': 'Hover quick-view disabled (click capsule to open full panel)',
'settings.str.addHoverModule': 'Add Module ({count}/{max})', 'settings.str.addHoverModule': 'Add Module ({count}/{max})',
'settings.str.overviewSection': 'Live Overview Layout', 'settings.str.overviewSection': 'Live Overview Layout',
'settings.str.overviewBadge': '{modCount} mod · {metCount} cells', 'settings.str.overviewBadge': '{modCount} mod · {metCount} cells',
'settings.str.overviewModulesLabel': 'Overview Modules & Order (Top → Bottom, min 1)', 'settings.str.overviewModulesLabel': 'Overview Modules & Order (Top → Bottom, min 1, draggable)',
'settings.str.addOverviewModule': 'Add Module ({count}/{max})', 'settings.str.addOverviewModule': 'Add Module ({count}/{max})',
'settings.str.overviewMetricsLabel': 'First-Row Metrics (Left → Right, 1–4)', 'settings.str.overviewMetricsLabel': 'First-Row Metrics (Left → Right, 1–4, draggable)',
'settings.str.overviewMetricsInactiveHint': '"Live Metrics" is hidden here; these cells still apply to Hover Quick-View or when re-added', 'settings.str.overviewMetricsInactiveHint': '"Live Metrics" is hidden here; these cells still apply to Hover Quick-View or when re-added',
'settings.str.addOverviewMetric': 'Add Metric ({count}/{max})', 'settings.str.addOverviewMetric': 'Add Metric ({count}/{max})',
'settings.str.stepsSection': 'Step Table Columns', 'settings.str.stepsSection': 'Step Table Columns',
'settings.str.stepsBadge': '{count} cols', 'settings.str.stepsBadge': '{count} cols',
'settings.str.stepTurnRailToggle': 'Turn Rail & Preview', 'settings.str.stepTurnRailToggle': 'Turn Rail & Preview',
'settings.str.stepAgentBadgeToggle': 'Main/Sub Agent Badge', 'settings.str.stepAgentBadgeToggle': 'Main/Sub Agent Badge',
'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2)', 'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2, draggable)',
'settings.str.addStepCol': 'Add Column ({count}/{max})', 'settings.str.addStepCol': 'Add Column ({count}/{max})',
'settings.slot.dragHint': 'Drag up or down to reorder',
'settings.slot.moveUp': 'Move earlier', 'settings.slot.moveUp': 'Move earlier',
'settings.slot.moveDown': 'Move later', 'settings.slot.moveDown': 'Move later',
'settings.slot.remove': 'Remove item', 'settings.slot.remove': 'Remove item',
'settings.slot.minReached': 'Keep at least {min}', 'settings.slot.minReached': 'Keep at least {min}',
'settings.slot.alreadyAdded': 'Added', 'settings.slot.alreadyAdded': 'Added',
'settings.mock.sessionTitle': 'Refactor Auth Middleware & Session Cache',
'settings.mock.subRole': 'API Audit',
'settings.mock.turnPromptLatest': 'Fix token refresh race condition under concurrent requests and add tests',
'settings.mock.turnPromptPrev': 'Audit route guards and expired session cleanup logic',
// Preferences -> Other Tab // Preferences -> Other Tab
'settings.oth.modelTitle': 'Model Identity Display', 'settings.oth.modelTitle': 'Model Identity Display',
+16 -5
View File
@@ -398,6 +398,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.latestSub': '已是最新 ({mode})', 'settings.gen.latestSub': '已是最新 ({mode})',
// Preferences -> Structure Tab // Preferences -> Structure Tab
'settings.str.thirdTabAria': '结构子菜单切换',
'settings.str.tabMount': '挂载与胶囊',
'settings.str.tabHover': '鼠标悬浮窗',
'settings.str.tabOverview': '实时监控布局',
'settings.str.tabSteps': '调用明细字段',
'settings.str.previewMountSidebarHint': '当前为仅侧边栏模式,主窗口不挂载胶囊;切回顶部栏或输入框挂载后将按上方样式呈现',
'settings.str.mountSection': '挂载与胶囊栏', 'settings.str.mountSection': '挂载与胶囊栏',
'settings.str.mountBadge': '{count}/5 项', 'settings.str.mountBadge': '{count}/5 项',
'settings.str.mountMode': '面板挂载方式', 'settings.str.mountMode': '面板挂载方式',
@@ -407,32 +413,37 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.multiToggle': '实时运行会话入口', 'settings.str.multiToggle': '实时运行会话入口',
'settings.str.show': '显示', 'settings.str.show': '显示',
'settings.str.hide': '隐藏', 'settings.str.hide': '隐藏',
'settings.str.capsuleSlotsLabel': '胶囊数值与顺序 (左 → 右,1~5 项)', 'settings.str.capsuleSlotsLabel': '胶囊数值与顺序 (左 → 右,1~5 项,可拖拽)',
'settings.str.addCapsuleSlot': '添加槽位 ({count}/{max})', 'settings.str.addCapsuleSlot': '添加槽位 ({count}/{max})',
'settings.str.hoverSection': '鼠标悬浮窗', 'settings.str.hoverSection': '鼠标悬浮窗',
'settings.str.hoverBadgeOff': '已关闭', 'settings.str.hoverBadgeOff': '已关闭',
'settings.str.hoverBadgeCount': '{count} 模块', 'settings.str.hoverBadgeCount': '{count} 模块',
'settings.str.hoverModulesLabel': '悬浮窗展示模块 (上 → 下,0~4 项)', 'settings.str.hoverModulesLabel': '悬浮窗展示模块 (上 → 下,0~4 项,可拖拽)',
'settings.str.hoverEmptyHint': '已关闭悬浮速览窗(点击胶囊仍可展开完整面板)', 'settings.str.hoverEmptyHint': '已关闭悬浮速览窗(点击胶囊仍可展开完整面板)',
'settings.str.addHoverModule': '添加模块 ({count}/{max})', 'settings.str.addHoverModule': '添加模块 ({count}/{max})',
'settings.str.overviewSection': '实时监控布局', 'settings.str.overviewSection': '实时监控布局',
'settings.str.overviewBadge': '{modCount} 模块 · {metCount} 指标', 'settings.str.overviewBadge': '{modCount} 模块 · {metCount} 指标',
'settings.str.overviewModulesLabel': '监控模块与顺序 (上 → 下,至少 1 项)', 'settings.str.overviewModulesLabel': '监控模块与顺序 (上 → 下,至少 1 项,可拖拽)',
'settings.str.addOverviewModule': '添加模块 ({count}/{max})', 'settings.str.addOverviewModule': '添加模块 ({count}/{max})',
'settings.str.overviewMetricsLabel': '第一行实时指标 (左 → 右,1~4 项)', 'settings.str.overviewMetricsLabel': '第一行实时指标 (左 → 右,1~4 项,可拖拽)',
'settings.str.overviewMetricsInactiveHint': '当前已移出「实时指标」模块,此配置将在悬浮窗启用或重新添加模块时生效', 'settings.str.overviewMetricsInactiveHint': '当前已移出「实时指标」模块,此配置将在悬浮窗启用或重新添加模块时生效',
'settings.str.addOverviewMetric': '添加指标 ({count}/{max})', 'settings.str.addOverviewMetric': '添加指标 ({count}/{max})',
'settings.str.stepsSection': '调用明细字段', 'settings.str.stepsSection': '调用明细字段',
'settings.str.stepsBadge': '{count} 列', 'settings.str.stepsBadge': '{count} 列',
'settings.str.stepTurnRailToggle': '对话轮次导轨', 'settings.str.stepTurnRailToggle': '对话轮次导轨',
'settings.str.stepAgentBadgeToggle': '主/子代理标识', 'settings.str.stepAgentBadgeToggle': '主/子代理标识',
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列)', 'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)',
'settings.str.addStepCol': '添加字段 ({count}/{max})', 'settings.str.addStepCol': '添加字段 ({count}/{max})',
'settings.slot.dragHint': '按住上下拖动调整顺序',
'settings.slot.moveUp': '前移', 'settings.slot.moveUp': '前移',
'settings.slot.moveDown': '后移', 'settings.slot.moveDown': '后移',
'settings.slot.remove': '移除此项', 'settings.slot.remove': '移除此项',
'settings.slot.minReached': '至少保留 {min} 项', 'settings.slot.minReached': '至少保留 {min} 项',
'settings.slot.alreadyAdded': '已添加', 'settings.slot.alreadyAdded': '已添加',
'settings.mock.sessionTitle': '重构鉴权中间件与会话缓存',
'settings.mock.subRole': '接口审计',
'settings.mock.turnPromptLatest': '排查并发刷新令牌时的竞态问题,补齐单元测试',
'settings.mock.turnPromptPrev': '梳理路由守卫与过期会话清理逻辑',
// Preferences -> Other Tab // Preferences -> Other Tab
'settings.oth.modelTitle': '模型标识显示', 'settings.oth.modelTitle': '模型标识显示',
+8
View File
@@ -89,4 +89,12 @@ export const SVG_ICON_DEFS = Object.freeze({
close: [ close: [
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
], ],
grip: [
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '6', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
],
}); });
+34 -16
View File
@@ -246,6 +246,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: '', text: '',
toneClass: '',
running: false, running: false,
warn: false, warn: false,
danger: false, danger: false,
@@ -262,6 +263,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: true, showRing: true,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: '--%', text: '--%',
toneClass: '',
running: false, running: false,
warn: false, warn: false,
danger: false, danger: false,
@@ -269,6 +271,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
} }
const isDanger = slotCtx.usedPct >= 88; const isDanger = slotCtx.usedPct >= 88;
const isWarn = !isDanger && slotCtx.usedPct >= 70; const isWarn = !isDanger && slotCtx.usedPct >= 70;
const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : '';
return { return {
hidden: false, hidden: false,
metric: 'context', metric: 'context',
@@ -277,6 +280,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: true, showRing: true,
dashOffset: slotCtx.dashOffset, dashOffset: slotCtx.dashOffset,
text: `${Math.round(slotCtx.usedPct)}%`, text: `${Math.round(slotCtx.usedPct)}%`,
toneClass,
running: false, running: false,
warn: isWarn, warn: isWarn,
danger: isDanger, danger: isDanger,
@@ -293,12 +297,14 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: '-- t/s', text: '-- t/s',
toneClass: '',
running: false, running: false,
warn: false, warn: false,
danger: false, danger: false,
}; };
} }
const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0; const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0;
const toneClass = hasValidTps ? getSpeedToneClass(slotCtx.tps) : '';
const tpsText = hasValidTps const tpsText = hasValidTps
? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s` ? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s`
: slotCtx.isRunning : slotCtx.isRunning
@@ -312,15 +318,17 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: tpsText, text: tpsText,
toneClass,
running: Boolean(slotCtx.isRunning), running: Boolean(slotCtx.isRunning),
warn: false, warn: toneClass === 'tone-warn',
danger: false, danger: toneClass === 'tone-danger',
}; };
} }
if (metricKey === 'avg_tps') { if (metricKey === 'avg_tps') {
const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null; const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null;
const valid = Number.isFinite(avgVal) && avgVal > 0; const valid = Number.isFinite(avgVal) && avgVal > 0;
const toneClass = valid ? getSpeedToneClass(avgVal) : '';
return { return {
hidden: false, hidden: false,
metric: 'avg_tps', metric: 'avg_tps',
@@ -329,9 +337,10 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s', text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s',
toneClass,
running: false, running: false,
warn: false, warn: toneClass === 'tone-warn',
danger: false, danger: toneClass === 'tone-danger',
}; };
} }
@@ -339,8 +348,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
const val = slotCtx.hasTelemetry ? slotCtx.ttft : null; const val = slotCtx.hasTelemetry ? slotCtx.ttft : null;
const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0; const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
const numVal = valid ? Number(val) : 0; const numVal = valid ? Number(val) : 0;
const isDanger = valid && numVal >= 30; const toneClass = valid ? getTtftToneClass(numVal) : '';
const isWarn = valid && !isDanger && numVal >= 15;
return { return {
hidden: false, hidden: false,
metric: 'ttft', metric: 'ttft',
@@ -349,9 +357,10 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: valid ? formatCompactCapsuleTtft(numVal) : '--s', text: valid ? formatCompactCapsuleTtft(numVal) : '--s',
toneClass,
running: false, running: false,
warn: isWarn, warn: toneClass === 'tone-warn',
danger: isDanger, danger: toneClass === 'tone-danger',
}; };
} }
@@ -361,6 +370,10 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
: metricKey === 'session_cost' : metricKey === 'session_cost'
? slotCtx.sessionCost ? slotCtx.sessionCost
: slotCtx.stepCost; : slotCtx.stepCost;
const toneClass =
metricKey === 'cost' && slotCtx.hasTelemetry && costVal != null
? getStepCostToneClass(costVal)
: '';
return { return {
hidden: false, hidden: false,
metric: metricKey, metric: metricKey,
@@ -369,9 +382,10 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--', text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--',
toneClass,
running: false, running: false,
warn: false, warn: toneClass === 'tone-warn',
danger: false, danger: toneClass === 'tone-danger',
}; };
} }
@@ -379,9 +393,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null; const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null;
const valid = cachePct != null && Number.isFinite(Number(cachePct)); const valid = cachePct != null && Number.isFinite(Number(cachePct));
const numVal = valid ? Number(cachePct) : 0; const numVal = valid ? Number(cachePct) : 0;
const hasPrompt = slotCtx.latestPromptTokens == null || Number(slotCtx.latestPromptTokens) > 0; const toneClass = valid ? getCacheToneClass(numVal, slotCtx.latestPromptTokens) : '';
const isDanger = valid && hasPrompt && numVal < 30;
const isWarn = valid && hasPrompt && !isDanger && numVal < 65;
return { return {
hidden: false, hidden: false,
metric: 'cache_hit', metric: 'cache_hit',
@@ -390,9 +402,10 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: valid ? `${Math.round(numVal)}%` : '--%', text: valid ? `${Math.round(numVal)}%` : '--%',
toneClass,
running: false, running: false,
warn: isWarn, warn: toneClass === 'tone-warn',
danger: isDanger, danger: toneClass === 'tone-danger',
}; };
} }
@@ -407,6 +420,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: valid ? formatTokens(Number(tokVal)) : '--', text: valid ? formatTokens(Number(tokVal)) : '--',
toneClass: '',
running: false, running: false,
warn: false, warn: false,
danger: false, danger: false,
@@ -420,6 +434,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
: resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey);
const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15); const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15);
const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30); const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30);
const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : '';
return { return {
hidden: false, hidden: false,
metric: metricKey, metric: metricKey,
@@ -428,6 +443,7 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
showRing: false, showRing: false,
dashOffset: ringCircumference, dashOffset: ringCircumference,
text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'), text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'),
toneClass,
running: false, running: false,
warn: isWarn, warn: isWarn,
danger: isDanger, danger: isDanger,
@@ -504,6 +520,8 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
} }
if (metricKey === 'avg_tps') { if (metricKey === 'avg_tps') {
const hasAvgSpeed = Number.isFinite(active.avgTokPerSec) && Number(active.avgTokPerSec) > 0;
const avgSpeedTone = hasAnySteps && hasAvgSpeed ? getSpeedToneClass(active.avgTokPerSec) : '';
return { return {
key: 'avg_tps', key: 'avg_tps',
label: t('ovMetric.avg_tps'), label: t('ovMetric.avg_tps'),
@@ -511,7 +529,7 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
iconSize: 11, iconSize: 11,
isPulsing: false, isPulsing: false,
valueText: formatMetric(active.avgTokPerSec, ' tok/s'), valueText: formatMetric(active.avgTokPerSec, ' tok/s'),
valueClass: 'cell-value', valueClass: avgSpeedTone ? `cell-value ${avgSpeedTone}` : 'cell-value',
subText: t('ovMetric.subValidSamples', { subText: t('ovMetric.subValidSamples', {
samples: sampleSummary(active.speedSummary), samples: sampleSummary(active.speedSummary),
}), }),
@@ -22,15 +22,19 @@ export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
metrics: { metrics: {
key: 'metrics', key: 'metrics',
labelKey: 'module.metrics', labelKey: 'module.metrics',
create: ({ mode, isVisibleFn }) => MetricMatrixWidget({ mode, isVisibleFn }), create: ({ mode, isVisibleFn, preview, getCtxAgentId }) =>
MetricMatrixWidget({ mode, isVisibleFn, preview, getCtxAgentId }),
}, },
context: { context: {
key: 'context', key: 'context',
labelKey: 'module.context', labelKey: 'module.context',
create: ({ mode, isVisibleFn }) => create: ({ mode, isVisibleFn, preview, getCtxAgentId, setCtxAgentId }) =>
ContextWindowWidget({ ContextWindowWidget({
interactiveInspector: mode !== 'hover', interactiveInspector: mode !== 'hover',
isVisibleFn, isVisibleFn,
preview,
getCtxAgentId,
setCtxAgentId,
}), }),
}, },
quotas: { quotas: {
@@ -44,10 +48,12 @@ export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
live_tasks: { live_tasks: {
key: 'live_tasks', key: 'live_tasks',
labelKey: 'module.live_tasks', labelKey: 'module.live_tasks',
create: ({ mode, isVisibleFn }) => create: ({ mode, isVisibleFn, preview, getCtxAgentId }) =>
LiveActivityWidget({ LiveActivityWidget({
interactive: mode !== 'hover', interactive: mode !== 'hover',
isVisibleFn, isVisibleFn,
preview,
getCtxAgentId,
}), }),
}, },
}); });
@@ -73,11 +79,26 @@ export function getOverviewModuleOptions() {
export function createDynamicWidgetHost({ export function createDynamicWidgetHost({
containerEl, containerEl,
mode = 'overview', mode = 'overview',
preview = false,
isVisibleFn = () => true, isVisibleFn = () => true,
initialModuleKeys = [], initialModuleKeys = [],
}) { }) {
const instances = new Map(); const instances = new Map();
let currentKeys = []; let currentKeys = [];
let previewCtxAgentId = 'auto';
let latestUpdatePayload = null;
const getCtxAgentId = preview ? () => previewCtxAgentId : undefined;
const setCtxAgentId = preview
? (nextId) => {
previewCtxAgentId = String(nextId || 'auto');
if (latestUpdatePayload) {
for (const key of currentKeys) {
instances.get(key)?.refs?.update?.(latestUpdatePayload);
}
}
}
: undefined;
function syncModules(nextKeys) { function syncModules(nextKeys) {
const validKeys = []; const validKeys = [];
@@ -105,7 +126,13 @@ export function createDynamicWidgetHost({
// Instantiate newly added widgets // Instantiate newly added widgets
for (const key of validKeys) { for (const key of validKeys) {
if (!instances.has(key)) { if (!instances.has(key)) {
const inst = OVERVIEW_WIDGET_REGISTRY[key].create({ mode, isVisibleFn }); const inst = OVERVIEW_WIDGET_REGISTRY[key].create({
mode,
preview,
isVisibleFn,
getCtxAgentId,
setCtxAgentId,
});
instances.set(key, inst); instances.set(key, inst);
} }
} }
@@ -135,6 +162,7 @@ export function createDynamicWidgetHost({
} }
function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) { function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) {
latestUpdatePayload = { data, minuteTick };
const validKeys = syncModules(moduleKeys); const validKeys = syncModules(moduleKeys);
for (const key of validKeys) { for (const key of validKeys) {
const inst = instances.get(key); const inst = instances.get(key);
+1
View File
@@ -25,6 +25,7 @@ export const uiStore = createReactiveStore({
activeView: 'overview', activeView: 'overview',
stepsSubTab: 'steps', // 'steps' | 'models' stepsSubTab: 'steps', // 'steps' | 'models'
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other' settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId> selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId> ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
}); });
+19 -2
View File
@@ -290,8 +290,8 @@
text-align: center; text-align: center;
} }
.wm-seg-speed.state-running { .wm-seg-speed.state-running:not([class*="tone-"]) {
color: var(--metric-speed); color: var(--accent-primary);
font-weight: 500; font-weight: 500;
} }
@@ -347,6 +347,18 @@
text-align: center; text-align: center;
} }
.wm-cap-slot.tone-good,
.wm-cap-slot.tone-good .wm-slot-text {
color: var(--metric-ok);
font-weight: 500;
}
.wm-cap-slot.tone-info,
.wm-cap-slot.tone-info .wm-slot-text {
color: var(--metric-info);
font-weight: 500;
}
.wm-cap-slot.tone-warn, .wm-cap-slot.tone-warn,
.wm-cap-slot.tone-warn .wm-slot-text { .wm-cap-slot.tone-warn .wm-slot-text {
color: var(--metric-warn); color: var(--metric-warn);
@@ -359,6 +371,11 @@
font-weight: 500; font-weight: 500;
} }
.wm-cap-slot.tone-muted,
.wm-cap-slot.tone-muted .wm-slot-text {
color: var(--text-muted);
}
/* 仅在超窄 ring-only 折叠态下使用右上角 5px 提示圆点;常规态由柔和微胶囊 .wm-update-btn 承载 */ /* 仅在超窄 ring-only 折叠态下使用右上角 5px 提示圆点;常规态由柔和微胶囊 .wm-update-btn 承载 */
.wm-update-dot { .wm-update-dot {
position: absolute; position: absolute;
@@ -42,6 +42,55 @@
font-weight: 500; font-weight: 500;
} }
/* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */
.settings-thirdnav-bar {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
flex-shrink: 0;
}
.structure-thirdnav-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
height: 25px;
min-width: 0;
padding: 0 6px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-subtle);
color: var(--text-secondary);
font-size: var(--fs-md);
font-weight: 500;
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast);
}
.structure-thirdnav-btn:hover {
color: var(--text-primary);
border-color: var(--border-strong);
background: var(--surface-hover);
}
.structure-thirdnav-btn.is-active {
color: var(--accent-primary);
background: var(--accent-primary-soft);
border-color: var(--accent-primary-border);
font-weight: 600;
}
.structure-thirdnav-label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.settings-tab-stack { .settings-tab-stack {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -170,6 +219,193 @@
color: var(--accent-primary); color: var(--accent-primary);
} }
.collapsible-title-static {
display: inline-flex;
align-items: center;
gap: 6px;
flex: 1;
min-width: 0;
color: var(--text-primary);
font-size: var(--fs-base);
font-weight: 600;
}
/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */
.structure-preview-canvas {
position: relative;
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.structure-preview-canvas.is-scaled {
zoom: 0.86;
}
.wm-hover-tip.is-preview {
position: relative;
top: auto;
left: auto;
width: 100%;
max-height: none;
padding: 0;
border: none;
border-radius: 0;
background: transparent;
z-index: 1;
pointer-events: auto;
box-shadow: none;
animation: none;
}
.overview-modules-host.is-preview {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.structure-preview-empty,
.preview-sidebar-note {
padding: 7px 10px;
font-size: var(--fs-sm);
line-height: 1.4;
color: var(--text-secondary);
background: var(--surface-panel);
border: 1px dashed var(--border-hairline);
border-radius: var(--radius-xs);
text-align: center;
}
.capsule-preview-widget {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.preview-capsule-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 36px;
padding: 4px 8px;
background: var(--surface-bg);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
overflow-x: auto;
user-select: none;
}
.preview-capsule-bar.is-composer {
border-radius: var(--radius-sm);
background: var(--surface-panel);
}
.preview-capsule-bar.is-composer .wm-multi-btn,
.preview-capsule-bar.is-composer .wm-capsule-btn {
height: 26px;
border-radius: var(--radius-pill);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
}
.preview-capsule-bar.is-composer .wm-multi-btn {
padding: 0 7px;
}
.preview-capsule-bar.is-composer .wm-capsule-btn {
padding: 0 8px;
}
.preview-capsule-bar.is-sidebar-only {
opacity: 0.42;
filter: grayscale(0.35);
}
.preview-capsule-cluster {
display: inline-flex;
align-items: center;
gap: 6px;
margin-left: auto;
flex-shrink: 0;
}
.preview-host-left {
display: inline-flex;
align-items: center;
gap: 5px;
min-width: 0;
color: var(--text-muted);
font-size: var(--fs-sm);
flex-shrink: 1;
overflow: hidden;
}
.preview-win-title {
font-weight: 600;
letter-spacing: 0.01em;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.preview-composer-chip {
display: inline-flex;
align-items: center;
gap: 3px;
height: 22px;
padding: 0 7px;
border-radius: var(--radius-pill);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
color: var(--text-secondary);
font-size: var(--fs-xs);
white-space: nowrap;
}
.preview-win-controls {
display: inline-flex;
align-items: center;
gap: 5px;
padding-left: 4px;
flex-shrink: 0;
}
.preview-win-dot {
width: 7px;
height: 7px;
border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
}
.preview-composer-send {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: var(--radius-pill);
background: var(--accent-primary-soft);
color: var(--accent-primary);
flex-shrink: 0;
}
.step-table-preview-host {
position: relative;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-panel);
overflow: hidden;
}
.step-table-preview-host .data-table tbody tr:last-child td {
border-bottom: none;
}
.collapsible-chevron { .collapsible-chevron {
color: var(--text-secondary); color: var(--text-secondary);
transition: transform var(--dur-fast) var(--ease-fast); transition: transform var(--dur-fast) var(--ease-fast);
@@ -272,6 +508,54 @@
max-height: 216px; max-height: 216px;
} }
.slot-drag-handle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 22px;
margin-left: -2px;
color: var(--text-muted);
border-radius: var(--radius-xs);
cursor: grab;
flex-shrink: 0;
touch-action: none;
transition:
color var(--dur-instant) var(--ease-fast),
background-color var(--dur-instant) var(--ease-fast);
}
.editable-slot-row:hover .slot-drag-handle:not(.is-disabled) {
color: var(--text-secondary);
}
.slot-drag-handle:hover:not(.is-disabled) {
color: var(--text-primary);
background: var(--surface-hover);
}
.slot-drag-handle.is-disabled {
opacity: 0.25;
cursor: default;
}
.editable-slot-list.is-dragging-list,
.editable-slot-list.is-dragging-list * {
cursor: grabbing !important;
user-select: none !important;
}
.editable-slot-row.is-dragging {
z-index: 40;
border-color: var(--accent-primary);
background: color-mix(in srgb, var(--accent-primary) 9%, var(--surface-panel));
box-shadow: var(--shadow-popover);
}
.editable-slot-row.is-dragging .slot-drag-handle {
color: var(--accent-primary);
}
.slot-remove-btn { .slot-remove-btn {
color: var(--text-secondary); color: var(--text-secondary);
} }
+2
View File
@@ -66,6 +66,7 @@ export const SettingsView = defineComponent({
subNavSwitch.setValue(target); subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general'); patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure'); patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account'); patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other'); patchAttr(otherTab.el, 'hidden', target !== 'other');
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings'; const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
@@ -90,6 +91,7 @@ export const SettingsView = defineComponent({
const rootEl = h('div', { className: 'settings-view-root' }, [ const rootEl = h('div', { className: 'settings-view-root' }, [
subNavBar, subNavBar,
structureTab.refs.thirdNavBar,
viewScrollbar.el, viewScrollbar.el,
]); ]);
+17 -349
View File
@@ -22,15 +22,9 @@ import {
resolveModelDisplayInfo, resolveModelDisplayInfo,
} from '../core/formatters.js'; } from '../core/formatters.js';
import { createSvgIcon } from '../icons/SvgIcon.js'; import { createSvgIcon } from '../icons/SvgIcon.js';
import { getEffectiveLocale, i18nStore, isEnglishLocale, t } from '../i18n/index.js'; import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
import { import {
DEFAULT_STEP_COLUMN_KEYS,
STEP_COLUMN_REGISTRY,
} from '../registries/stepColumnRegistry.js';
import {
formatAgentBadgeText,
formatAgentLabel, formatAgentLabel,
getAgentBadgeClass,
normalizeClientStepColumns, normalizeClientStepColumns,
resolveScopedConversation, resolveScopedConversation,
telemetryStore, telemetryStore,
@@ -47,6 +41,7 @@ import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { CustomSelect } from '../components/ui/CustomSelect.js'; import { CustomSelect } from '../components/ui/CustomSelect.js';
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js'; import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { StepTableWidget } from '../components/widgets/StepTableWidget.js';
function mergeSelectedAgentUnits(units) { function mergeSelectedAgentUnits(units) {
const combinedSteps = []; const combinedSteps = [];
@@ -193,16 +188,6 @@ function getFitMetricSwitchOptions() {
]; ];
} }
function formatTurnPromptText(rawPrompt) {
const text = String(rawPrompt || '').trim();
if (!text || !isEnglishLocale()) return text;
if (text === '[图片/附件提问]') return t('steps.turnMediaOnly');
if (text.endsWith(' [附图]')) {
return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`;
}
return text;
}
export const StepsDetailView = defineComponent({ export const StepsDetailView = defineComponent({
name: 'StepsDetailView', name: 'StepsDetailView',
setup({ onCleanup }) { setup({ onCleanup }) {
@@ -273,78 +258,25 @@ export const StepsDetailView = defineComponent({
}, },
}); });
// --- 子视图 1:单步明细表(动态表头与行内列插槽由 `stepColumnRegistry.js` 驱动) --- // --- 子视图 1:单步明细表(委托给可复用的 `StepTableWidget` 解耦组件) ---
const stepsTheadRow = h('tr'); const stepTableWidget = StepTableWidget({
const stepsTbody = h('tbody'); onSelectAgentScopes: applyAgentScopesSelection,
});
function syncTableHeaderColumns(colKeys) { const {
const locale = getEffectiveLocale(); stepsTablePane,
patchKeyedList(stepsTheadRow, colKeys, { stepsTableEl,
keyFn: (colKey) => colKey, stepsTheadRow,
sigFn: (colKey) => `${locale}:${colKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel()}`,
createRow: (colKey) => {
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel() });
return { el: th, refs: { th } };
},
updateRow: (refs, colKey) => {
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel());
},
});
}
syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS);
const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [
h('thead', {}, [stepsTheadRow]),
stepsTbody, stepsTbody,
]); turnTipEl,
const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]); hideTurnTip,
syncTableHeaderColumns,
renderStepTable,
} = stepTableWidget.refs;
const stepsScroll = CustomScrollbar({ const stepsScroll = CustomScrollbar({
contentEl: stepsTablePane, contentEl: stepsTablePane,
className: 'table-scroll-host', className: 'table-scroll-host',
}); });
const turnTipEl = h('div', {
className: 'turn-prompt-tip',
role: 'tooltip',
hidden: true,
});
const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true);
function showTurnTip(anchorCell, promptText) {
const text = String(promptText || '').trim();
if (!anchorCell || !text) {
hideTurnTip();
return;
}
patchText(turnTipEl, text);
patchAttr(turnTipEl, 'hidden', false);
if (
typeof panelEl.getBoundingClientRect === 'function' &&
typeof anchorCell.getBoundingClientRect === 'function'
) {
const panelRect = panelEl.getBoundingClientRect();
const cellRect = anchorCell.getBoundingClientRect();
if (panelRect.width > 0 && panelRect.height > 0) {
const tipH = turnTipEl.offsetHeight || 36;
const tipW = turnTipEl.offsetWidth || 180;
const placeAbove =
panelRect.bottom - cellRect.bottom < tipH + 10 &&
cellRect.top - panelRect.top > tipH + 6;
const topPx = placeAbove
? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4))
: Math.round(cellRect.bottom - panelRect.top + 4);
const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8));
const leftPx = Math.min(
maxLeft,
Math.max(6, Math.round(cellRect.left - panelRect.left + 4))
);
turnTipEl.style.top = `${topPx}px`;
turnTipEl.style.left = `${leftPx}px`;
}
}
}
// --- 子视图 2:总汇总分析面板 --- // --- 子视图 2:总汇总分析面板 ---
let selectedLineMetric = 'totalTokens'; let selectedLineMetric = 'totalTokens';
let selectedFitMetric = 'tps'; let selectedFitMetric = 'tps';
@@ -493,8 +425,7 @@ export const StepsDetailView = defineComponent({
turnTipEl, turnTipEl,
] ]
); );
stepsTablePane.addEventListener('scroll', hideTurnTip); stepTableWidget.refs.setBoundsElGetter(() => panelEl);
stepsTbody.addEventListener('mouseleave', hideTurnTip);
const rootEl = h('div', { className: 'view-pane' }, [panelEl]); const rootEl = h('div', { className: 'view-pane' }, [panelEl]);
@@ -567,268 +498,6 @@ export const StepsDetailView = defineComponent({
} }
} }
function renderStepTable(tableSteps, cascadeId, colKeys, locale, {
effectiveScopes,
hasSubagents,
isMergedMultiAgents,
showStepTurnRail,
showStepAgentBadge,
displaySettings,
}) {
const colOrderSig = colKeys.join(',');
const wantedSet = new Set(colKeys);
syncTableHeaderColumns(colKeys);
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
const cellCtx = {
hasSubagents,
showAgentBadge,
effectiveScopes,
scopeSigKey: effectiveScopes.join(','),
displaySettings,
onSelectAgentScopes: applyAgentScopesSelection,
};
const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents);
const getStepTurnIdx = (st) =>
useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex;
const getStepIsStart = (st) =>
Boolean(useRootTurn ? (st?.isRootTurnStart ?? st?.isTurnStart) : st?.isTurnStart);
const getStepIsLatest = (st) =>
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
const getStepPrompt = (st) =>
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
const turnKeyOf = (st) => {
if (!showStepTurnRail) return '';
const tIdx = getStepTurnIdx(st);
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`;
};
const decoratedSteps = tableSteps.map((st, idx) => {
const tKey = turnKeyOf(st);
const hasTurn = Boolean(tKey);
const hasUp = Boolean(hasTurn && idx > 0 && turnKeyOf(tableSteps[idx - 1]) === tKey);
const hasDown = Boolean(
hasTurn && idx + 1 < tableSteps.length && turnKeyOf(tableSteps[idx + 1]) === tKey
);
return {
st,
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
hasTurn,
hasUp,
hasDown,
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
isLatest: hasTurn && getStepIsLatest(st),
prompt: hasTurn ? formatTurnPromptText(getStepPrompt(st)) : '',
};
});
const railActive = Boolean(showStepTurnRail && decoratedSteps.some((d) => d.hasTurn));
if (!railActive) {
hideTurnTip();
}
patchClasses(stepsTableEl, { 'has-turn-rail': railActive });
patchKeyedList(stepsTbody, decoratedSteps, {
keyFn: (item) => item.rowKey,
sigFn: (item) => {
const { st } = item;
const parts = colKeys
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
.join('|');
const badgeSig = `${showAgentBadge}:${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`;
return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
},
createRow: () => {
const tr = h('tr');
const railLineEl = h('span', { className: 'turn-rail-line', hidden: true });
const railDotEl = h('span', { className: 'turn-rail-dot', hidden: true });
const railEl = h(
'span',
{ className: 'turn-rail', 'aria-hidden': 'true', hidden: true },
[railLineEl, railDotEl]
);
const agentBadgeEl = h('span', {
className: 'agent-badge is-clickable',
hidden: true,
style: 'margin-right: 4px;',
});
return {
el: tr,
refs: {
cellMap: new Map(),
colOrderSig: '',
railEl,
railLineEl,
railDotEl,
agentBadgeEl,
hoverTd: null,
},
};
},
updateRow: (refs, item, _idx, tr) => {
const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item;
if (refs.colOrderSig !== colOrderSig) {
if (refs.hoverTd) {
refs.hoverTd.onmouseenter = null;
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
refs.hoverTd = null;
}
for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) {
if (refs.railEl.parentNode === entry.td) {
entry.td.removeChild(refs.railEl);
}
if (refs.agentBadgeEl.parentNode === entry.td) {
entry.td.removeChild(refs.agentBadgeEl);
}
tr.removeChild(entry.td);
refs.cellMap.delete(oldColKey);
}
}
for (const [i, colKey] of colKeys.entries()) {
if (!refs.cellMap.has(colKey)) {
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
}
const targetTd = refs.cellMap.get(colKey).td;
const currentTd = tr.children[i] || null;
if (currentTd !== targetTd) {
tr.insertBefore(targetTd, currentTd);
}
}
refs.colOrderSig = colOrderSig;
}
for (const colKey of colKeys) {
const cellEntry = refs.cellMap.get(colKey);
STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx);
}
const firstColKey = colKeys[0];
const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null;
if (firstTd) {
if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) {
firstTd.insertBefore(refs.railEl, firstTd.firstChild);
}
const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null;
if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) {
firstTd.insertBefore(refs.agentBadgeEl, afterRail);
}
}
patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd);
if (showAgentBadge && firstTd) {
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
const badgeText = isEnglishLocale()
? formatAgentBadgeText({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
badgeText: st.agentBadge,
})
: st.agentBadge || (st.isSubagent ? '子' : '主');
patchText(refs.agentBadgeEl, badgeText);
const targetScope = st.agentId || 'main';
const isSoleTarget =
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
const agentName = isEnglishLocale()
? formatAgentLabel({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
role: st.agentRole || '',
})
: st.agentLabel || t('steps.unitAgent');
patchAttr(
refs.agentBadgeEl,
'title',
isSoleTarget
? t('steps.badgeBackAll')
: t('steps.badgeFilterAgent', { agent: agentName })
);
refs.agentBadgeEl.onclick = (e) => {
if (typeof applyAgentScopesSelection !== 'function') return;
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
const next = effectiveScopes.includes(targetScope)
? effectiveScopes.filter((id) => id !== targetScope)
: [...effectiveScopes, targetScope];
applyAgentScopesSelection(next.length > 0 ? next : ['all']);
} else {
applyAgentScopesSelection(isSoleTarget ? ['all'] : [targetScope]);
}
};
} else {
refs.agentBadgeEl.onclick = null;
}
const showRowRail = Boolean(railActive && hasTurn && firstTd);
patchAttr(refs.railEl, 'hidden', !showRowRail);
if (showRowRail) {
patchClasses(refs.railEl, {
'is-latest': isLatest,
'has-up': hasUp,
'has-down': hasDown,
});
patchAttr(refs.railLineEl, 'hidden', !hasUp && !hasDown);
const showOrigin = isStart;
const showCap = !showOrigin && !hasUp && hasDown;
patchAttr(refs.railDotEl, 'hidden', !showOrigin && !showCap);
patchClasses(refs.railDotEl, {
'is-origin': showOrigin,
'is-cap': showCap,
});
}
const targetHoverTd = firstTd;
if (refs.hoverTd && refs.hoverTd !== targetHoverTd) {
refs.hoverTd.onmouseenter = null;
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
}
refs.hoverTd = targetHoverTd;
if (targetHoverTd) {
const badgeEl = refs.agentBadgeEl;
if (firstColKey === 'step') {
targetHoverTd.onmouseenter = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
showTurnTip(targetHoverTd, prompt);
};
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
} else {
targetHoverTd.onmouseenter = null;
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
const rect = targetHoverTd.getBoundingClientRect?.();
const relX = rect ? (ev?.clientX ?? 0) - rect.left : 0;
if (relX <= 18) {
showTurnTip(targetHoverTd, prompt);
} else {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
}
}
},
});
}
function renderStepsData(slice) { function renderStepsData(slice) {
if (!slice) return; if (!slice) return;
const uiSt = uiStore.getState(); const uiSt = uiStore.getState();
@@ -1439,12 +1108,11 @@ export const StepsDetailView = defineComponent({
); );
onCleanup(() => { onCleanup(() => {
stepsTablePane.removeEventListener('scroll', hideTurnTip);
stepsTbody.removeEventListener('mouseleave', hideTurnTip);
unsubUi(); unsubUi();
unsubTelemetry(); unsubTelemetry();
unsubView(); unsubView();
unsubI18n(); unsubI18n();
stepTableWidget.destroy();
sessionLineChart.destroy?.(); sessionLineChart.destroy?.();
modelFitChart.destroy?.(); modelFitChart.destroy?.();
inlineScopeSelect.destroy(); inlineScopeSelect.destroy();
@@ -1,21 +1,24 @@
/** /**
* @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构"). * @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构").
* Provides 4 collapsible customization sections with `+` / `-` / `↑` / `↓`: * Organizes the 4 structure settings panes under a dedicated 3rd-level menu bar,
* 1. 挂载与胶囊栏 (`windowMountMode`, `showTopbarMultiSession`, `topbarCapsuleSlots` 1..5) * renders live previews powered by the decoupled real UI components (`CapsuleBarWidget`,
* 2. 鼠标悬浮窗 (`hoverModules` 0..4) * `createDynamicWidgetHost` in `hover` / `overview` modes, and `StepTableWidget`)
* 3. 实时监控布局 (`overviewModules` 1..4 + `overviewMetrics` 1..4) * with simulated telemetry, and supports smooth mouse drag-and-drop reordering.
* 4. 调用明细字段 (`stepTableColumns` 2..12)
*/ */
import { defineComponent } from '../../core/component.js'; import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchText } from '../../core/domPatch.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { t } from '../../i18n/index.js'; import { getEffectiveLocale, t } from '../../i18n/index.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { import {
getCapsuleMetricOptions, getCapsuleMetricOptions,
getOverviewMetricOptions, getOverviewMetricOptions,
} from '../../registries/metricRegistry.js'; } from '../../registries/metricRegistry.js';
import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js'; import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js';
import { getOverviewModuleOptions } from '../../registries/widgetRegistry.js'; import {
createDynamicWidgetHost,
getOverviewModuleOptions,
} from '../../registries/widgetRegistry.js';
import { import {
DEFAULT_CLIENT_HOVER_MODULES, DEFAULT_CLIENT_HOVER_MODULES,
DEFAULT_CLIENT_OVERVIEW_METRICS, DEFAULT_CLIENT_OVERVIEW_METRICS,
@@ -30,10 +33,26 @@ import {
normalizeClientWindowMountMode, normalizeClientWindowMountMode,
saveSettingsPatch, saveSettingsPatch,
} from '../../store/telemetryStore.js'; } from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js';
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js'; import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
import { EditableSlotList } from '../../components/settings/EditableSlotList.js'; import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js';
import { CustomSelect } from '../../components/ui/CustomSelect.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js';
import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
import { CapsuleBarWidget } from '../../components/widgets/CapsuleBarWidget.js';
import { StepTableWidget } from '../../components/widgets/StepTableWidget.js';
const STRUCTURE_THIRD_TABS = Object.freeze([
{ key: 'mount', icon: 'dock', labelKey: 'settings.str.tabMount' },
{ key: 'hover', icon: 'layers', labelKey: 'settings.str.tabHover' },
{ key: 'overview', icon: 'pulse', labelKey: 'settings.str.tabOverview' },
{ key: 'steps', icon: 'table', labelKey: 'settings.str.tabSteps' },
]);
function normalizeStructureTabKey(raw) {
const k = String(raw || '').trim();
return k === 'hover' || k === 'overview' || k === 'steps' ? k : 'mount';
}
function getMountModeOptions() { function getMountModeOptions() {
return [ return [
@@ -61,6 +80,7 @@ function isSameList(a, b) {
export const SettingsStructureTab = defineComponent({ export const SettingsStructureTab = defineComponent({
name: 'SettingsStructureTab', name: 'SettingsStructureTab',
setup({ props, onCleanup }) { setup({ props, onCleanup }) {
let activeThirdTab = normalizeStructureTabKey(uiStore.getState().settingsStructureTab);
let draftWindowMountMode = 'dual'; let draftWindowMountMode = 'dual';
let draftShowTopbarMulti = true; let draftShowTopbarMulti = true;
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
@@ -72,6 +92,26 @@ export const SettingsStructureTab = defineComponent({
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
let latestSettings = null; let latestSettings = null;
function isStructureVisible() {
const st = uiStore.getState();
return st.activeView === 'settings' && st.settingsSubTab === 'structure';
}
function buildDraftTelemetry() {
return buildStructurePreviewTelemetry(latestSettings, {
windowMountMode: draftWindowMountMode,
enableWindowOverlay: draftWindowMountMode !== 'sidebar',
showTopbarMultiSession: draftShowTopbarMulti,
topbarCapsuleSlots: draftTopbarSlots,
hoverModules: draftHoverModules,
overviewModules: draftOverviewModules,
overviewMetrics: draftOverviewMetrics,
showStepTurnRail: draftShowStepTurnRail,
showStepAgentBadge: draftShowStepAgentBadge,
stepTableColumns: draftStepColumns,
});
}
async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') {
sectionComp.refs.showStatus(t('settings.saving'), 0); sectionComp.refs.showStatus(t('settings.saving'), 0);
try { try {
@@ -85,7 +125,51 @@ export const SettingsStructureTab = defineComponent({
} }
} }
// --- Section 1: 挂载与胶囊栏 (defaultExpanded: true) --- // --- 3rd-Level Navigation Bar ---
const thirdNavBtnMap = new Map();
const thirdNavBtns = STRUCTURE_THIRD_TABS.map((item) => {
const labelEl = h('span', {
className: 'structure-thirdnav-label',
text: t(item.labelKey),
});
const btn = h(
'button',
{
type: 'button',
className: `structure-thirdnav-btn${item.key === activeThirdTab ? ' is-active' : ''}`,
role: 'tab',
'aria-selected': item.key === activeThirdTab ? 'true' : 'false',
'data-structure-tab': item.key,
onClick: () => {
if (uiStore.getState().settingsStructureTab !== item.key) {
uiStore.setState({ settingsStructureTab: item.key });
} else {
applyActiveThirdTab(item.key);
}
},
},
[createSvgIcon(item.icon, { size: 12 }), labelEl]
);
thirdNavBtnMap.set(item.key, { btn, labelEl, labelKey: item.labelKey });
return btn;
});
const thirdNavBar = h(
'div',
{
className: 'settings-thirdnav-bar',
role: 'tablist',
'aria-label': t('settings.str.thirdTabAria'),
},
thirdNavBtns
);
// --- Pane 1: 挂载与胶囊栏 (`mount`) ---
const capsulePreviewWidget = CapsuleBarWidget({});
const mountPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
capsulePreviewWidget.el,
]);
const mountModeLabelEl = h('span', { const mountModeLabelEl = h('span', {
className: 'form-label', className: 'form-label',
text: t('settings.str.mountMode'), text: t('settings.str.mountMode'),
@@ -107,6 +191,7 @@ export const SettingsStructureTab = defineComponent({
const nextMode = normalizeClientWindowMountMode(val); const nextMode = normalizeClientWindowMountMode(val);
draftWindowMountMode = nextMode; draftWindowMountMode = nextMode;
syncMountSectionMeta(); syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, { void persistStructurePatch(mountSection, {
windowMountMode: nextMode, windowMountMode: nextMode,
enableWindowOverlay: nextMode !== 'sidebar', enableWindowOverlay: nextMode !== 'sidebar',
@@ -133,6 +218,10 @@ export const SettingsStructureTab = defineComponent({
minItems: 1, minItems: 1,
maxItems: 5, maxItems: 5,
addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }),
onPreview: (previewItems) => {
draftTopbarSlots = normalizeClientTopbarSlots(previewItems);
refreshMountPreview();
},
onChange: (nextItems) => { onChange: (nextItems) => {
draftTopbarSlots = normalizeClientTopbarSlots(nextItems); draftTopbarSlots = normalizeClientTopbarSlots(nextItems);
syncMountSectionMeta(); syncMountSectionMeta();
@@ -144,11 +233,10 @@ export const SettingsStructureTab = defineComponent({
}); });
const mountSection = CollapsibleSection({ const mountSection = CollapsibleSection({
collapsible: false,
icon: 'dock', icon: 'dock',
title: t('settings.str.mountSection'), title: t('settings.str.mountSection'),
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }), badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
defaultExpanded: true,
onToggle: () => props.onLayoutChange?.(),
onReset: () => { onReset: () => {
draftWindowMountMode = 'dual'; draftWindowMountMode = 'dual';
draftShowTopbarMulti = true; draftShowTopbarMulti = true;
@@ -167,6 +255,8 @@ export const SettingsStructureTab = defineComponent({
); );
}, },
children: [ children: [
mountPreviewCanvas,
h('div', { className: 'settings-divider' }),
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
h('div', { className: 'settings-inline-row' }, [ h('div', { className: 'settings-inline-row' }, [
multiToggleLabelEl, multiToggleLabelEl,
@@ -176,6 +266,11 @@ export const SettingsStructureTab = defineComponent({
], ],
}); });
function refreshMountPreview() {
if (!isStructureVisible() || activeThirdTab !== 'mount') return;
capsulePreviewWidget.refs.update({ data: buildDraftTelemetry() });
}
function syncMountSectionMeta() { function syncMountSectionMeta() {
windowMountSelect.setProps({ windowMountSelect.setProps({
modelValue: draftWindowMountMode, modelValue: draftWindowMountMode,
@@ -198,9 +293,31 @@ export const SettingsStructureTab = defineComponent({
draftShowTopbarMulti === true && draftShowTopbarMulti === true &&
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS); isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
mountSection.refs.setResetDisabled(isDefault); mountSection.refs.setResetDisabled(isDefault);
refreshMountPreview();
} }
// --- Section 2: 鼠标悬浮窗 (0..4 items) --- // --- Pane 2: 鼠标悬浮窗 (`hover`) ---
const hoverWidgetsContainerEl = h('div', { className: 'wm-hover-widgets' });
const hoverPreviewTipEl = h('div', { className: 'wm-hover-tip is-preview' }, [
hoverWidgetsContainerEl,
]);
const hoverPreviewEmptyEl = h('div', {
className: 'structure-preview-empty',
hidden: true,
text: t('settings.str.hoverEmptyHint'),
});
const hoverPreviewHost = createDynamicWidgetHost({
containerEl: hoverWidgetsContainerEl,
mode: 'hover',
preview: true,
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover',
initialModuleKeys: [],
});
const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [
hoverPreviewTipEl,
hoverPreviewEmptyEl,
]);
const hoverModulesLabelEl = h('span', { const hoverModulesLabelEl = h('span', {
className: 'form-label', className: 'form-label',
text: t('settings.str.hoverModulesLabel'), text: t('settings.str.hoverModulesLabel'),
@@ -213,6 +330,10 @@ export const SettingsStructureTab = defineComponent({
maxItems: 4, maxItems: 4,
emptyHintText: t('settings.str.hoverEmptyHint'), emptyHintText: t('settings.str.hoverEmptyHint'),
addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }), addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }),
onPreview: (previewItems) => {
draftHoverModules = normalizeClientHoverModules(previewItems);
refreshHoverPreview();
},
onChange: (nextItems) => { onChange: (nextItems) => {
draftHoverModules = normalizeClientHoverModules(nextItems); draftHoverModules = normalizeClientHoverModules(nextItems);
syncHoverSectionMeta(); syncHoverSectionMeta();
@@ -224,11 +345,10 @@ export const SettingsStructureTab = defineComponent({
}); });
const hoverSection = CollapsibleSection({ const hoverSection = CollapsibleSection({
collapsible: false,
icon: 'layers', icon: 'layers',
title: t('settings.str.hoverSection'), title: t('settings.str.hoverSection'),
badgeText: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }), badgeText: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => { onReset: () => {
draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES]; draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
syncHoverSectionMeta(); syncHoverSectionMeta();
@@ -239,9 +359,25 @@ export const SettingsStructureTab = defineComponent({
'settings.resetDone' 'settings.resetDone'
); );
}, },
children: [h('div', { className: 'form-row' }, [hoverModulesLabelEl, hoverModulesList.el])], children: [
hoverPreviewCanvas,
h('div', { className: 'settings-divider' }),
h('div', { className: 'form-row' }, [hoverModulesLabelEl, hoverModulesList.el]),
],
}); });
function refreshHoverPreview() {
if (!isStructureVisible() || activeThirdTab !== 'hover') return;
const hasModules = draftHoverModules.length > 0;
patchAttr(hoverPreviewTipEl, 'hidden', !hasModules);
patchAttr(hoverPreviewEmptyEl, 'hidden', hasModules);
patchText(hoverPreviewEmptyEl, t('settings.str.hoverEmptyHint'));
hoverPreviewHost.update({
moduleKeys: draftHoverModules,
data: buildDraftTelemetry(),
});
}
function syncHoverSectionMeta() { function syncHoverSectionMeta() {
hoverModulesList.refs.setProps({ hoverModulesList.refs.setProps({
items: draftHoverModules, items: draftHoverModules,
@@ -254,10 +390,25 @@ export const SettingsStructureTab = defineComponent({
? t('settings.str.hoverBadgeOff') ? t('settings.str.hoverBadgeOff')
: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }) : t('settings.str.hoverBadgeCount', { count: draftHoverModules.length })
); );
hoverSection.refs.setResetDisabled(isSameList(draftHoverModules, DEFAULT_CLIENT_HOVER_MODULES)); hoverSection.refs.setResetDisabled(
isSameList(draftHoverModules, DEFAULT_CLIENT_HOVER_MODULES)
);
refreshHoverPreview();
} }
// --- Section 3: 实时监控布局 (Modules 1..4 + First-Row Metrics 1..4) --- // --- Pane 3: 实时监控布局 (`overview`) ---
const overviewPreviewContainerEl = h('div', { className: 'overview-modules-host is-preview' });
const overviewPreviewHost = createDynamicWidgetHost({
containerEl: overviewPreviewContainerEl,
mode: 'overview',
preview: true,
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview',
initialModuleKeys: [],
});
const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [
overviewPreviewContainerEl,
]);
const overviewModulesLabelEl = h('span', { const overviewModulesLabelEl = h('span', {
className: 'form-label', className: 'form-label',
text: t('settings.str.overviewModulesLabel'), text: t('settings.str.overviewModulesLabel'),
@@ -278,6 +429,11 @@ export const SettingsStructureTab = defineComponent({
minItems: 1, minItems: 1,
maxItems: 4, maxItems: 4,
addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }), addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }),
onPreview: (previewItems) => {
draftOverviewModules = normalizeClientOverviewModules(previewItems);
patchAttr(overviewMetricsHintEl, 'hidden', draftOverviewModules.includes('metrics'));
refreshOverviewPreview();
},
onChange: (nextItems) => { onChange: (nextItems) => {
draftOverviewModules = normalizeClientOverviewModules(nextItems); draftOverviewModules = normalizeClientOverviewModules(nextItems);
syncOverviewSectionMeta(); syncOverviewSectionMeta();
@@ -294,6 +450,10 @@ export const SettingsStructureTab = defineComponent({
minItems: 1, minItems: 1,
maxItems: 4, maxItems: 4,
addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }), addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }),
onPreview: (previewItems) => {
draftOverviewMetrics = normalizeClientOverviewMetrics(previewItems);
refreshOverviewPreview();
},
onChange: (nextItems) => { onChange: (nextItems) => {
draftOverviewMetrics = normalizeClientOverviewMetrics(nextItems); draftOverviewMetrics = normalizeClientOverviewMetrics(nextItems);
syncOverviewSectionMeta(); syncOverviewSectionMeta();
@@ -305,14 +465,13 @@ export const SettingsStructureTab = defineComponent({
}); });
const overviewSection = CollapsibleSection({ const overviewSection = CollapsibleSection({
collapsible: false,
icon: 'pulse', icon: 'pulse',
title: t('settings.str.overviewSection'), title: t('settings.str.overviewSection'),
badgeText: t('settings.str.overviewBadge', { badgeText: t('settings.str.overviewBadge', {
modCount: draftOverviewModules.length, modCount: draftOverviewModules.length,
metCount: draftOverviewMetrics.length, metCount: draftOverviewMetrics.length,
}), }),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => { onReset: () => {
draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES]; draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS]; draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
@@ -328,6 +487,8 @@ export const SettingsStructureTab = defineComponent({
); );
}, },
children: [ children: [
overviewPreviewCanvas,
h('div', { className: 'settings-divider' }),
h('div', { className: 'form-row' }, [overviewModulesLabelEl, overviewModulesList.el]), h('div', { className: 'form-row' }, [overviewModulesLabelEl, overviewModulesList.el]),
h('div', { className: 'settings-divider' }), h('div', { className: 'settings-divider' }),
h('div', { className: 'form-row' }, [ h('div', { className: 'form-row' }, [
@@ -338,6 +499,14 @@ export const SettingsStructureTab = defineComponent({
], ],
}); });
function refreshOverviewPreview() {
if (!isStructureVisible() || activeThirdTab !== 'overview') return;
overviewPreviewHost.update({
moduleKeys: draftOverviewModules,
data: buildDraftTelemetry(),
});
}
function syncOverviewSectionMeta() { function syncOverviewSectionMeta() {
overviewModulesList.refs.setProps({ overviewModulesList.refs.setProps({
items: draftOverviewModules, items: draftOverviewModules,
@@ -361,9 +530,18 @@ export const SettingsStructureTab = defineComponent({
isSameList(draftOverviewModules, DEFAULT_CLIENT_OVERVIEW_MODULES) && isSameList(draftOverviewModules, DEFAULT_CLIENT_OVERVIEW_MODULES) &&
isSameList(draftOverviewMetrics, DEFAULT_CLIENT_OVERVIEW_METRICS); isSameList(draftOverviewMetrics, DEFAULT_CLIENT_OVERVIEW_METRICS);
overviewSection.refs.setResetDisabled(isDefault); overviewSection.refs.setResetDisabled(isDefault);
refreshOverviewPreview();
} }
// --- Section 4: 调用明细字段 (Turn Rail + Agent Badge Toggles + Step Table Columns 2..12) --- // --- Pane 4: 调用明细字段 (`steps`) ---
const stepTablePreview = StepTableWidget({
standalone: true,
interactiveBadges: false,
});
const stepsPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
stepTablePreview.el,
]);
const stepTurnRailLabelEl = h('span', { const stepTurnRailLabelEl = h('span', {
className: 'form-label', className: 'form-label',
text: t('settings.str.stepTurnRailToggle'), text: t('settings.str.stepTurnRailToggle'),
@@ -409,6 +587,10 @@ export const SettingsStructureTab = defineComponent({
minItems: 2, minItems: 2,
maxItems: 12, maxItems: 12,
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
onPreview: (previewItems) => {
draftStepColumns = normalizeClientStepColumns(previewItems);
refreshStepsPreview();
},
onChange: (nextItems) => { onChange: (nextItems) => {
draftStepColumns = normalizeClientStepColumns(nextItems); draftStepColumns = normalizeClientStepColumns(nextItems);
syncStepsSectionMeta(); syncStepsSectionMeta();
@@ -420,11 +602,10 @@ export const SettingsStructureTab = defineComponent({
}); });
const stepsSection = CollapsibleSection({ const stepsSection = CollapsibleSection({
collapsible: false,
icon: 'table', icon: 'table',
title: t('settings.str.stepsSection'), title: t('settings.str.stepsSection'),
badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }), badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => { onReset: () => {
draftShowStepTurnRail = true; draftShowStepTurnRail = true;
draftShowStepAgentBadge = true; draftShowStepAgentBadge = true;
@@ -442,6 +623,8 @@ export const SettingsStructureTab = defineComponent({
); );
}, },
children: [ children: [
stepsPreviewCanvas,
h('div', { className: 'settings-divider' }),
h('div', { className: 'settings-inline-row' }, [ h('div', { className: 'settings-inline-row' }, [
stepTurnRailLabelEl, stepTurnRailLabelEl,
stepTurnRailToggle.el, stepTurnRailToggle.el,
@@ -455,6 +638,26 @@ export const SettingsStructureTab = defineComponent({
], ],
}); });
function refreshStepsPreview() {
if (!isStructureVisible() || activeThirdTab !== 'steps') return;
const mockData = buildDraftTelemetry();
const mockSteps = mockData.activeConversation?.recentSteps || [];
stepTablePreview.refs.renderStepTable(
mockSteps,
'mock-preview-conv',
draftStepColumns,
getEffectiveLocale(),
{
effectiveScopes: ['all'],
hasSubagents: true,
isMergedMultiAgents: true,
showStepTurnRail: draftShowStepTurnRail,
showStepAgentBadge: draftShowStepAgentBadge,
displaySettings: mockData.settings,
}
);
}
function syncStepsSectionMeta() { function syncStepsSectionMeta() {
stepTurnRailToggle.setProps({ stepTurnRailToggle.setProps({
modelValue: draftShowStepTurnRail ? 'show' : 'hide', modelValue: draftShowStepTurnRail ? 'show' : 'hide',
@@ -475,6 +678,49 @@ export const SettingsStructureTab = defineComponent({
draftShowStepAgentBadge === true && draftShowStepAgentBadge === true &&
isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS); isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS);
stepsSection.refs.setResetDisabled(isDefault); stepsSection.refs.setResetDisabled(isDefault);
refreshStepsPreview();
}
function syncPreviewTickers() {
const visible = isStructureVisible();
if (visible && activeThirdTab === 'hover') {
hoverPreviewHost.resumeTickers();
} else {
hoverPreviewHost.pauseTickers();
}
if (visible && activeThirdTab === 'overview') {
overviewPreviewHost.resumeTickers();
} else {
overviewPreviewHost.pauseTickers();
}
if (!visible || activeThirdTab !== 'steps') {
stepTablePreview.refs.hideTurnTip();
}
}
function refreshActivePreview() {
if (!isStructureVisible()) return;
if (activeThirdTab === 'mount') refreshMountPreview();
else if (activeThirdTab === 'hover') refreshHoverPreview();
else if (activeThirdTab === 'overview') refreshOverviewPreview();
else if (activeThirdTab === 'steps') refreshStepsPreview();
}
function applyActiveThirdTab(nextRawTab) {
const nextTab = normalizeStructureTabKey(nextRawTab);
activeThirdTab = nextTab;
for (const [key, entry] of thirdNavBtnMap.entries()) {
const isActive = key === nextTab;
patchClasses(entry.btn, { 'is-active': isActive });
patchAttr(entry.btn, 'aria-selected', isActive ? 'true' : 'false');
}
patchAttr(mountSection.el, 'hidden', nextTab !== 'mount');
patchAttr(hoverSection.el, 'hidden', nextTab !== 'hover');
patchAttr(overviewSection.el, 'hidden', nextTab !== 'overview');
patchAttr(stepsSection.el, 'hidden', nextTab !== 'steps');
refreshActivePreview();
syncPreviewTickers();
props.onLayoutChange?.();
} }
const rootEl = h('div', { className: 'settings-tab-stack' }, [ const rootEl = h('div', { className: 'settings-tab-stack' }, [
@@ -507,6 +753,11 @@ export const SettingsStructureTab = defineComponent({
} }
function refreshLabels() { function refreshLabels() {
patchAttr(thirdNavBar, 'aria-label', t('settings.str.thirdTabAria'));
for (const entry of thirdNavBtnMap.values()) {
patchText(entry.labelEl, t(entry.labelKey));
}
mountSection.refs.setTitle(t('settings.str.mountSection')); mountSection.refs.setTitle(t('settings.str.mountSection'));
mountSection.refs.setResetLabel(t('settings.resetBtn')); mountSection.refs.setResetLabel(t('settings.resetBtn'));
patchText(mountModeLabelEl, t('settings.str.mountMode')); patchText(mountModeLabelEl, t('settings.str.mountMode'));
@@ -535,12 +786,41 @@ export const SettingsStructureTab = defineComponent({
syncStepsSectionMeta(); syncStepsSectionMeta();
} }
let wasStructureVisible = isStructureVisible();
const unsubUi = uiStore.subscribe(
(st) => ({
activeView: st.activeView,
settingsSubTab: st.settingsSubTab,
settingsStructureTab: st.settingsStructureTab,
}),
(slice) => {
const nowVisible =
slice.activeView === 'settings' && slice.settingsSubTab === 'structure';
const enteredStructure = nowVisible && !wasStructureVisible;
wasStructureVisible = nowVisible;
if (normalizeStructureTabKey(slice.settingsStructureTab) !== activeThirdTab) {
applyActiveThirdTab(slice.settingsStructureTab);
} else {
if (enteredStructure) {
refreshActivePreview();
}
syncPreviewTickers();
}
}
);
syncMountSectionMeta(); syncMountSectionMeta();
syncHoverSectionMeta(); syncHoverSectionMeta();
syncOverviewSectionMeta(); syncOverviewSectionMeta();
syncStepsSectionMeta(); syncStepsSectionMeta();
applyActiveThirdTab(activeThirdTab);
onCleanup(() => { onCleanup(() => {
unsubUi();
capsulePreviewWidget.destroy();
hoverPreviewHost.destroy();
overviewPreviewHost.destroy();
stepTablePreview.destroy();
windowMountSelect.destroy(); windowMountSelect.destroy();
multiSessionToggle.destroy(); multiSessionToggle.destroy();
topbarSlotsList.destroy(); topbarSlotsList.destroy();
@@ -559,6 +839,11 @@ export const SettingsStructureTab = defineComponent({
return { return {
el: rootEl, el: rootEl,
refs: { refs: {
thirdNavBar,
capsulePreviewWidget,
hoverPreviewHost,
overviewPreviewHost,
stepTablePreview,
windowMountSelect, windowMountSelect,
multiSessionToggle, multiSessionToggle,
topbarSlotsList, topbarSlotsList,
+303 -2
View File
@@ -3262,6 +3262,55 @@ input {
font-weight: 500; font-weight: 500;
} }
/* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */
.settings-thirdnav-bar {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
flex-shrink: 0;
}
.structure-thirdnav-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
height: 25px;
min-width: 0;
padding: 0 6px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-subtle);
color: var(--text-secondary);
font-size: var(--fs-md);
font-weight: 500;
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast);
}
.structure-thirdnav-btn:hover {
color: var(--text-primary);
border-color: var(--border-strong);
background: var(--surface-hover);
}
.structure-thirdnav-btn.is-active {
color: var(--accent-primary);
background: var(--accent-primary-soft);
border-color: var(--accent-primary-border);
font-weight: 600;
}
.structure-thirdnav-label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.settings-tab-stack { .settings-tab-stack {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -3390,6 +3439,193 @@ input {
color: var(--accent-primary); color: var(--accent-primary);
} }
.collapsible-title-static {
display: inline-flex;
align-items: center;
gap: 6px;
flex: 1;
min-width: 0;
color: var(--text-primary);
font-size: var(--fs-base);
font-weight: 600;
}
/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */
.structure-preview-canvas {
position: relative;
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.structure-preview-canvas.is-scaled {
zoom: 0.86;
}
.wm-hover-tip.is-preview {
position: relative;
top: auto;
left: auto;
width: 100%;
max-height: none;
padding: 0;
border: none;
border-radius: 0;
background: transparent;
z-index: 1;
pointer-events: auto;
box-shadow: none;
animation: none;
}
.overview-modules-host.is-preview {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.structure-preview-empty,
.preview-sidebar-note {
padding: 7px 10px;
font-size: var(--fs-sm);
line-height: 1.4;
color: var(--text-secondary);
background: var(--surface-panel);
border: 1px dashed var(--border-hairline);
border-radius: var(--radius-xs);
text-align: center;
}
.capsule-preview-widget {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.preview-capsule-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 36px;
padding: 4px 8px;
background: var(--surface-bg);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
overflow-x: auto;
user-select: none;
}
.preview-capsule-bar.is-composer {
border-radius: var(--radius-sm);
background: var(--surface-panel);
}
.preview-capsule-bar.is-composer .wm-multi-btn,
.preview-capsule-bar.is-composer .wm-capsule-btn {
height: 26px;
border-radius: var(--radius-pill);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
}
.preview-capsule-bar.is-composer .wm-multi-btn {
padding: 0 7px;
}
.preview-capsule-bar.is-composer .wm-capsule-btn {
padding: 0 8px;
}
.preview-capsule-bar.is-sidebar-only {
opacity: 0.42;
filter: grayscale(0.35);
}
.preview-capsule-cluster {
display: inline-flex;
align-items: center;
gap: 6px;
margin-left: auto;
flex-shrink: 0;
}
.preview-host-left {
display: inline-flex;
align-items: center;
gap: 5px;
min-width: 0;
color: var(--text-muted);
font-size: var(--fs-sm);
flex-shrink: 1;
overflow: hidden;
}
.preview-win-title {
font-weight: 600;
letter-spacing: 0.01em;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.preview-composer-chip {
display: inline-flex;
align-items: center;
gap: 3px;
height: 22px;
padding: 0 7px;
border-radius: var(--radius-pill);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
color: var(--text-secondary);
font-size: var(--fs-xs);
white-space: nowrap;
}
.preview-win-controls {
display: inline-flex;
align-items: center;
gap: 5px;
padding-left: 4px;
flex-shrink: 0;
}
.preview-win-dot {
width: 7px;
height: 7px;
border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
}
.preview-composer-send {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: var(--radius-pill);
background: var(--accent-primary-soft);
color: var(--accent-primary);
flex-shrink: 0;
}
.step-table-preview-host {
position: relative;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-panel);
overflow: hidden;
}
.step-table-preview-host .data-table tbody tr:last-child td {
border-bottom: none;
}
.collapsible-chevron { .collapsible-chevron {
color: var(--text-secondary); color: var(--text-secondary);
transition: transform var(--dur-fast) var(--ease-fast); transition: transform var(--dur-fast) var(--ease-fast);
@@ -3492,6 +3728,54 @@ input {
max-height: 216px; max-height: 216px;
} }
.slot-drag-handle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 22px;
margin-left: -2px;
color: var(--text-muted);
border-radius: var(--radius-xs);
cursor: grab;
flex-shrink: 0;
touch-action: none;
transition:
color var(--dur-instant) var(--ease-fast),
background-color var(--dur-instant) var(--ease-fast);
}
.editable-slot-row:hover .slot-drag-handle:not(.is-disabled) {
color: var(--text-secondary);
}
.slot-drag-handle:hover:not(.is-disabled) {
color: var(--text-primary);
background: var(--surface-hover);
}
.slot-drag-handle.is-disabled {
opacity: 0.25;
cursor: default;
}
.editable-slot-list.is-dragging-list,
.editable-slot-list.is-dragging-list * {
cursor: grabbing !important;
user-select: none !important;
}
.editable-slot-row.is-dragging {
z-index: 40;
border-color: var(--accent-primary);
background: color-mix(in srgb, var(--accent-primary) 9%, var(--surface-panel));
box-shadow: var(--shadow-popover);
}
.editable-slot-row.is-dragging .slot-drag-handle {
color: var(--accent-primary);
}
.slot-remove-btn { .slot-remove-btn {
color: var(--text-secondary); color: var(--text-secondary);
} }
@@ -3930,8 +4214,8 @@ input {
text-align: center; text-align: center;
} }
.wm-seg-speed.state-running { .wm-seg-speed.state-running:not([class*="tone-"]) {
color: var(--metric-speed); color: var(--accent-primary);
font-weight: 500; font-weight: 500;
} }
@@ -3987,6 +4271,18 @@ input {
text-align: center; text-align: center;
} }
.wm-cap-slot.tone-good,
.wm-cap-slot.tone-good .wm-slot-text {
color: var(--metric-ok);
font-weight: 500;
}
.wm-cap-slot.tone-info,
.wm-cap-slot.tone-info .wm-slot-text {
color: var(--metric-info);
font-weight: 500;
}
.wm-cap-slot.tone-warn, .wm-cap-slot.tone-warn,
.wm-cap-slot.tone-warn .wm-slot-text { .wm-cap-slot.tone-warn .wm-slot-text {
color: var(--metric-warn); color: var(--metric-warn);
@@ -3999,6 +4295,11 @@ input {
font-weight: 500; font-weight: 500;
} }
.wm-cap-slot.tone-muted,
.wm-cap-slot.tone-muted .wm-slot-text {
color: var(--text-muted);
}
/* 仅在超窄 ring-only 折叠态下使用右上角 5px 提示圆点;常规态由柔和微胶囊 .wm-update-btn 承载 */ /* 仅在超窄 ring-only 折叠态下使用右上角 5px 提示圆点;常规态由柔和微胶囊 .wm-update-btn 承载 */
.wm-update-dot { .wm-update-dot {
position: absolute; position: absolute;
+200 -13
View File
@@ -32,7 +32,10 @@ import {
getTtftToneClass, getTtftToneClass,
} from '../src/core/formatters.js'; } from '../src/core/formatters.js';
import { setI18nLanguage } from '../src/i18n/index.js'; import { setI18nLanguage } from '../src/i18n/index.js';
import { resolveOverviewMetricCell } from '../src/registries/metricRegistry.js'; import {
resolveCapsuleMetricPresentation,
resolveOverviewMetricCell,
} from '../src/registries/metricRegistry.js';
import { backendHarness } from './backend-harness.mjs'; import { backendHarness } from './backend-harness.mjs';
test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and strict target/origin filtering', () => { test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and strict target/origin filtering', () => {
@@ -753,6 +756,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const i = arr.indexOf(fn); const i = arr.indexOf(fn);
if (i >= 0) arr.splice(i, 1); if (i >= 0) arr.splice(i, 1);
}, },
dispatchEvent(ev) {
for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev);
},
}; };
const mockLocation = { const mockLocation = {
@@ -1504,6 +1510,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Settings subnav uses auto-sized equal columns regardless of visible tab count' 'Settings subnav uses auto-sized equal columns regardless of visible tab count'
); );
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack'); const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const thirdNavBar = settingsRoot.querySelector('.settings-thirdnav-bar');
assert.ok(thirdNavBar, '3rd-level structure menu bar mounted in SettingsView');
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when General tab is active');
assert.equal(generalPane.hasAttribute('hidden'), false, 'General tab active by default'); assert.equal(generalPane.hasAttribute('hidden'), false, 'General tab active by default');
assert.equal(structurePane.hasAttribute('hidden'), true); assert.equal(structurePane.hasAttribute('hidden'), true);
assert.equal(otherPane.hasAttribute('hidden'), true); assert.equal(otherPane.hasAttribute('hidden'), true);
@@ -1624,19 +1633,41 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(mockSettings.autoUpdatePlugin, false); assert.equal(mockSettings.autoUpdatePlugin, false);
assert.equal(topbarUpdateBtn.hasAttribute('hidden'), false, 'Topbar update pill visible when mode=manual'); assert.equal(topbarUpdateBtn.hasAttribute('hidden'), false, 'Topbar update pill visible when mode=manual');
// --- Tab 1: 结构 (4 accordion sections: capsule 1..5, hover 0..4, overview 1..4 + 1..4, step columns 2..12) --- // --- Tab 1: 结构 (3rd-level menu + 4 real-UI live previews + mouse drag reordering) ---
subNavBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); subNavBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15)); await new Promise((r) => setTimeout(r, 15));
assert.equal(structurePane.hasAttribute('hidden'), false); assert.equal(structurePane.hasAttribute('hidden'), false);
assert.equal(thirdNavBar.hasAttribute('hidden'), false, '3rd-level menu visible when Structure tab is active');
const thirdNavBtns = thirdNavBar.querySelectorAll('.structure-thirdnav-btn');
assert.deepEqual(
thirdNavBtns.map((btn) => btn.querySelector('.structure-thirdnav-label').textContent),
['挂载与胶囊', '鼠标悬浮窗', '实时监控布局', '调用明细字段'],
'3rd-level menu renders 4 structure sub-tabs'
);
assert.equal(thirdNavBtns[0].classList.contains('is-active'), true, 'First 3rd-level tab active by default');
const accordionSections = structurePane.querySelectorAll('.collapsible-section'); const accordionSections = structurePane.querySelectorAll('.collapsible-section');
assert.equal(accordionSections.length, 4, 'Structure tab has 4 collapsible sections'); assert.equal(accordionSections.length, 4, 'Structure tab has 4 static pane sections');
assert.equal(accordionSections[0].classList.contains('is-expanded'), true, 'Section 1 expanded by default'); assert.equal(accordionSections[0].hasAttribute('hidden'), false, 'Pane 0 visible by default');
assert.equal(accordionSections[1].classList.contains('is-expanded'), false, 'Section 2 collapsed by default'); assert.equal(accordionSections[1].hasAttribute('hidden'), true, 'Pane 1 hidden until selected');
assert.equal(accordionSections[2].hasAttribute('hidden'), true, 'Pane 2 hidden until selected');
assert.equal(accordionSections[3].hasAttribute('hidden'), true, 'Pane 3 hidden until selected');
const sec0 = accordionSections[0]; const sec0 = accordionSections[0];
assert.equal(sec0.querySelector('.structure-preview-stage'), null, 'No outer preview wrapper box');
assert.equal(sec0.querySelector('.structure-preview-head'), null, 'No redundant mock data label header');
const previewCapsuleBar = sec0.querySelector('.preview-capsule-bar');
const previewCapsuleSlots = sec0.querySelectorAll('.wm-cap-slot');
const previewMultiBtn = sec0.querySelector('.wm-multi-btn');
assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview');
assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots');
assert.equal(previewCapsuleSlots[0].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview renders simulated context %');
assert.equal(previewCapsuleSlots[1].children[0].textContent, '68.4 t/s', 'Preview renders simulated speed');
assert.equal(previewCapsuleSlots[1].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards');
assert.equal(previewCapsuleSlots[2].children[0].textContent, '余 52%', 'Preview renders simulated quota_auto (min of 5h 64% and weekly 52%)');
const mountSelectEl = sec0.querySelectorAll('.custom-select')[0]; const mountSelectEl = sec0.querySelectorAll('.custom-select')[0];
// Toggle windowMountSelect: dual -> composer -> sidebar -> dual // Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar)
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏')); assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏'));
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
mountSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); mountSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1644,6 +1675,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(mockSettings.windowMountMode, 'composer', 'windowMountMode persisted as composer'); assert.equal(mockSettings.windowMountMode, 'composer', 'windowMountMode persisted as composer');
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay stays true in composer mode'); assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay stays true in composer mode');
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('输入框挂载'), 'UI reflects composer mode'); assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('输入框挂载'), 'UI reflects composer mode');
assert.equal(previewCapsuleBar.getAttribute('data-mount-mode'), 'composer', 'Preview bar switches to composer mode');
assert.equal(previewCapsuleBar.classList.contains('is-composer'), true);
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
mountSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} }); mountSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1651,6 +1684,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(mockSettings.windowMountMode, 'sidebar', 'windowMountMode persisted as sidebar'); assert.equal(mockSettings.windowMountMode, 'sidebar', 'windowMountMode persisted as sidebar');
assert.equal(mockSettings.enableWindowOverlay, false, 'enableWindowOverlay persisted as false'); assert.equal(mockSettings.enableWindowOverlay, false, 'enableWindowOverlay persisted as false');
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('仅侧边栏'), 'UI reflects sidebar mode'); assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('仅侧边栏'), 'UI reflects sidebar mode');
assert.equal(previewCapsuleBar.classList.contains('is-sidebar-only'), true);
assert.equal(sec0.querySelector('.preview-sidebar-note').hasAttribute('hidden'), false, 'Sidebar-only preview hint shown');
// Re-open popover after sidebar closed it and switch back to dual // Re-open popover after sidebar closed it and switch back to dual
ov.open(); ov.open();
@@ -1659,6 +1694,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.windowMountMode, 'dual', 'windowMountMode persisted back to dual'); assert.equal(mockSettings.windowMountMode, 'dual', 'windowMountMode persisted back to dual');
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true'); assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
assert.equal(previewCapsuleBar.getAttribute('data-mount-mode'), 'dual');
// Toggle topbar multi-session switch: show -> hide -> show // Toggle topbar multi-session switch: show -> hide -> show
const topbarSegBtns = sec0.querySelectorAll('.seg-btn'); const topbarSegBtns = sec0.querySelectorAll('.seg-btn');
@@ -1667,13 +1703,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.showTopbarMultiSession, false); assert.equal(mockSettings.showTopbarMultiSession, false);
assert.equal(multiBtn.hasAttribute('hidden'), true, 'Topbar multi-session button hidden immediately'); assert.equal(multiBtn.hasAttribute('hidden'), true, 'Topbar multi-session button hidden immediately');
assert.equal(previewMultiBtn.hasAttribute('hidden'), true, 'Preview multi-session button hidden immediately');
assert.equal(capsuleHost.getAttribute('data-multi'), 'off'); assert.equal(capsuleHost.getAttribute('data-multi'), 'off');
topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30)); await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.showTopbarMultiSession, true); assert.equal(mockSettings.showTopbarMultiSession, true);
assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately'); assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately');
assert.equal(previewMultiBtn.hasAttribute('hidden'), false, 'Preview multi-session button restored immediately');
// Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓) // Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓ & mouse drag-and-drop)
const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot'); const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep'); const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep');
assert.equal(capSlots.length, 5, '5 capsule slot nodes pre-reserved'); assert.equal(capSlots.length, 5, '5 capsule slot nodes pre-reserved');
@@ -1692,6 +1730,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context'); assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
assert.equal(capSlots[0].children[0].textContent, '余 44%'); assert.equal(capSlots[0].children[0].textContent, '余 44%');
assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h');
assert.equal(previewCapsuleSlots[0].children[0].textContent, '余 64%', 'Preview slot 0 renders simulated gemini_5h');
capRowSelects[1].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[1].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
capRowSelects[1].querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[1].querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1713,6 +1753,46 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(capSlots[0].children[0].textContent, '0.85s'); assert.equal(capSlots[0].children[0].textContent, '0.85s');
assert.equal(capSlots[1].children[0].textContent, '余 44%'); assert.equal(capSlots[1].children[0].textContent, '余 44%');
// Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft']
const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list');
for (const rowEl of capSlotListEl.children) {
rowEl.getBoundingClientRect = () => {
const curIdx = capSlotListEl.children.indexOf(rowEl);
return { left: 0, right: 280, top: curIdx * 30, bottom: curIdx * 30 + 28, width: 280, height: 28 };
};
}
const firstDragHandle = capSlotListEl.children[0].querySelector('.slot-drag-handle');
assert.ok(firstDragHandle, 'Drag handle rendered on EditableSlotList row');
firstDragHandle.dispatchEvent({ type: 'pointerdown', button: 0, clientY: 14, preventDefault() {}, stopPropagation() {} });
mockDocument.dispatchEvent({ type: 'pointermove', clientY: 78, preventDefault() {} });
assert.equal(capSlotListEl.classList.contains('is-dragging-list'), true, 'List enters dragging state on pointermove');
assert.deepEqual(
mockSettings.topbarCapsuleSlots,
['ttft', 'gemini_5h', 'cost'],
'Settings API not spammed mid-drag before pointerup'
);
assert.equal(
previewCapsuleSlots[0].getAttribute('data-metric'),
'gemini_5h',
'Real CapsuleBarWidget preview updates live during mouse drag'
);
assert.equal(
previewCapsuleSlots[2].getAttribute('data-metric'),
'ttft',
'Dragged metric moved to slot 2 in live preview'
);
mockDocument.dispatchEvent({ type: 'pointerup', clientY: 78 });
await new Promise((r) => setTimeout(r, 30));
assert.equal(capSlotListEl.classList.contains('is-dragging-list'), false, 'Dragging state cleared on pointerup');
assert.deepEqual(
mockSettings.topbarCapsuleSlots,
['gemini_5h', 'cost', 'ttft'],
'Mouse drag order persisted once on pointerup'
);
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
assert.equal(capSlots[1].getAttribute('data-metric'), 'cost');
assert.equal(capSlots[2].getAttribute('data-metric'), 'ttft');
// Click `+ 添加指标` twice to expand from 3 -> 5 slots // Click `+ 添加指标` twice to expand from 3 -> 5 slots
const capAddBtn = capSlotWrap.querySelector('.slot-add-btn'); const capAddBtn = capSlotWrap.querySelector('.slot-add-btn');
capAddBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); capAddBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1743,9 +1823,18 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0'); assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0');
assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%'); assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%');
// Section 1: Hover Popup Modules (0..4) — removing all 3 suppresses hover popup while click popover still works // Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview
const sec1 = accordionSections[1]; const sec1 = accordionSections[1];
sec1.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); thirdNavBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(thirdNavBtns[1].classList.contains('is-active'), true, 'Hover 3rd-level tab active');
assert.equal(sec0.hasAttribute('hidden'), true, 'Mount pane hidden');
assert.equal(sec1.hasAttribute('hidden'), false, 'Hover pane visible');
const hoverPreviewTip = sec1.querySelector('.wm-hover-tip');
const hoverPreviewWidgets = hoverPreviewTip.querySelector('.wm-hover-widgets');
assert.equal(hoverPreviewTip.classList.contains('is-preview'), true, 'Real .wm-hover-tip mounted inline in preview');
assert.equal(hoverPreviewWidgets.children.length, 3, 'Default 3 real hover widgets mounted in preview');
const hoverSlotWrap = sec1.querySelector('.editable-slot-wrap'); const hoverSlotWrap = sec1.querySelector('.editable-slot-wrap');
for (let r = 0; r < 3; r += 1) { for (let r = 0; r < 3; r += 1) {
const remBtns = hoverSlotWrap.querySelectorAll('.slot-remove-btn'); const remBtns = hoverSlotWrap.querySelectorAll('.slot-remove-btn');
@@ -1754,6 +1843,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
} }
assert.deepEqual(mockSettings.hoverModules, [], 'Hover modules emptied to 0 items'); assert.deepEqual(mockSettings.hoverModules, [], 'Hover modules emptied to 0 items');
assert.equal(hoverSlotWrap.querySelector('.editable-slot-empty').hasAttribute('hidden'), false, '0-module empty hint visible'); assert.equal(hoverSlotWrap.querySelector('.editable-slot-empty').hasAttribute('hidden'), false, '0-module empty hint visible');
assert.equal(hoverPreviewTip.hasAttribute('hidden'), true, 'Hover preview tip hidden when 0 modules');
assert.equal(sec1.querySelector('.structure-preview-empty').hasAttribute('hidden'), false, 'Empty preview state shown');
// Temporarily set pluginUpdateMode=off via Settings UI so update banner is also absent, then close popover and hover capsuleBtn // Temporarily set pluginUpdateMode=off via Settings UI so update banner is also absent, then close popover and hover capsuleBtn
updateModeSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); updateModeSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
updateModeSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} }); updateModeSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1769,10 +1860,19 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
sec1.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} }); sec1.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 40)); await new Promise((r) => setTimeout(r, 40));
assert.deepEqual(mockSettings.hoverModules, ['metrics', 'context', 'quotas']); assert.deepEqual(mockSettings.hoverModules, ['metrics', 'context', 'quotas']);
assert.equal(hoverPreviewTip.hasAttribute('hidden'), false, 'Hover preview tip restored');
assert.equal(hoverPreviewWidgets.children.length, 3, '3 real hover widgets restored in preview');
// Section 2: Live Overview Layout (overviewModules 1..4 + overviewMetrics 1..4) // Pane 2 (3rd-level tab 'overview'): Live Overview Layout + real overview UI preview
const sec2 = accordionSections[2]; const sec2 = accordionSections[2];
sec2.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); thirdNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(thirdNavBtns[2].classList.contains('is-active'), true, 'Overview 3rd-level tab active');
assert.equal(sec1.hasAttribute('hidden'), true);
assert.equal(sec2.hasAttribute('hidden'), false);
const overviewPreviewHostEl = sec2.querySelector('.overview-modules-host');
assert.equal(overviewPreviewHostEl.children.length, 4, 'Overview preview mounts all 4 real overview widgets');
const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap'); const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap');
// Move row 2 ('quotas') up above 'context' -> ['metrics', 'quotas', 'context', 'live_tasks'] // Move row 2 ('quotas') up above 'context' -> ['metrics', 'quotas', 'context', 'live_tasks']
ovModWrap.querySelectorAll('.slot-move-btn')[6].dispatchEvent({ type: 'click', stopPropagation() {} }); ovModWrap.querySelectorAll('.slot-move-btn')[6].dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1784,6 +1884,11 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
ovMetricWrap.querySelectorAll('.slot-remove-btn')[2].dispatchEvent({ type: 'click', stopPropagation() {} }); ovMetricWrap.querySelectorAll('.slot-remove-btn')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft']); assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft']);
assert.equal(overviewPreviewHostEl.children[0].getAttribute('data-cols'), '2', 'Preview MetricMatrixWidget adapts to 2 columns');
assert.ok(
overviewPreviewHostEl.children[1].querySelector('.panel-title').children[1].textContent.includes('可用额度'),
'Preview QuotaPoolsWidget moved above ContextWindowWidget'
);
pillTabs[0].dispatchEvent({ type: 'click', stopPropagation() {} }); pillTabs[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15)); await new Promise((r) => setTimeout(r, 15));
const overviewHostEl = allPanes[0].querySelector('.overview-modules-host'); const overviewHostEl = allPanes[0].querySelector('.overview-modules-host');
@@ -1799,9 +1904,25 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.deepEqual(mockSettings.overviewModules, ['metrics', 'context', 'quotas', 'live_tasks']); assert.deepEqual(mockSettings.overviewModules, ['metrics', 'context', 'quotas', 'live_tasks']);
assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft', 'avg_tps', 'step_cost']); assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft', 'avg_tps', 'step_cost']);
// Section 3: Step Table Columns (2..12) + independent Turn Rail & Main/Sub Agent Badge switches // Pane 3 (3rd-level tab 'steps'): Step Table Columns (2..12) + real StepTableWidget preview
const sec3 = accordionSections[3]; const sec3 = accordionSections[3];
sec3.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); thirdNavBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(thirdNavBtns[3].classList.contains('is-active'), true, 'Steps 3rd-level tab active');
assert.equal(sec2.hasAttribute('hidden'), true);
assert.equal(sec3.hasAttribute('hidden'), false);
const previewStepTable = sec3.querySelector('.steps-data-table');
assert.ok(previewStepTable, 'Real StepTableWidget mounted in Steps structure preview');
assert.equal(previewStepTable.classList.contains('has-turn-rail'), true, 'Preview step table shows turn rail by default');
assert.equal(previewStepTable.children[0].children[0].children.length, 7, 'Preview step table renders 7 default columns');
assert.equal(previewStepTable.children[1].children.length, 4, 'Preview step table renders 4 simulated steps');
const previewFirstTd = previewStepTable.children[1].children[0].children[0];
previewFirstTd.onmouseenter?.({ target: previewFirstTd });
const previewTurnTip = sec3.querySelector('.turn-prompt-tip');
assert.equal(previewTurnTip.hasAttribute('hidden'), false, 'Hovering first cell in preview reveals turn prompt tooltip');
assert.ok(previewTurnTip.textContent.includes('并发刷新令牌'), 'Preview turn tooltip displays realistic engineering prompt');
previewFirstTd.onmouseleave?.();
const sec3SettingLabels = sec3.querySelectorAll('.form-label').map((el) => el.textContent); const sec3SettingLabels = sec3.querySelectorAll('.form-label').map((el) => el.textContent);
assert.ok(sec3SettingLabels.includes('对话轮次导轨'), 'Turn rail switch rendered in 调用明细字段'); assert.ok(sec3SettingLabels.includes('对话轮次导轨'), 'Turn rail switch rendered in 调用明细字段');
assert.ok(sec3SettingLabels.includes('主/子代理标识'), 'Main/Sub agent badge switch rendered in 调用明细字段'); assert.ok(sec3SettingLabels.includes('主/子代理标识'), 'Main/Sub agent badge switch rendered in 调用明细字段');
@@ -1811,9 +1932,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
sec3SegControls[0].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); sec3SegControls[0].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
assert.equal(mockSettings.showStepTurnRail, false, 'Turn rail switch updates showStepTurnRail to false'); assert.equal(mockSettings.showStepTurnRail, false, 'Turn rail switch updates showStepTurnRail to false');
assert.equal(previewStepTable.classList.contains('has-turn-rail'), false, 'Preview step table removes turn rail immediately');
sec3SegControls[1].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); sec3SegControls[1].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
assert.equal(mockSettings.showStepAgentBadge, false, 'Agent badge switch updates showStepAgentBadge to false'); assert.equal(mockSettings.showStepAgentBadge, false, 'Agent badge switch updates showStepAgentBadge to false');
assert.equal(
previewStepTable.querySelector('.agent-badge').hasAttribute('hidden'),
true,
'Preview step table hides Main/Sub agent badge immediately'
);
const stepColWrap = sec3.querySelector('.editable-slot-wrap'); const stepColWrap = sec3.querySelector('.editable-slot-wrap');
stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} }); stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} });
@@ -1821,6 +1948,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} }); stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
assert.equal(mockSettings.stepTableColumns.length, 9, 'Added time and duration columns (7 -> 9)'); assert.equal(mockSettings.stepTableColumns.length, 9, 'Added time and duration columns (7 -> 9)');
assert.equal(previewStepTable.children[0].children[0].children.length, 9, 'Preview step table expands to 9 columns live');
pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} }); pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15)); await new Promise((r) => setTimeout(r, 15));
const stepTableWhileRailOff = allPanes[2].querySelector('.data-table'); const stepTableWhileRailOff = allPanes[2].querySelector('.data-table');
@@ -1848,6 +1976,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15)); await new Promise((r) => setTimeout(r, 15));
assert.equal(otherPane.hasAttribute('hidden'), false); assert.equal(otherPane.hasAttribute('hidden'), false);
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when switching to Other tab');
const otherSelects = otherPane.querySelectorAll('.custom-select'); const otherSelects = otherPane.querySelectorAll('.custom-select');
assert.equal(otherSelects.length, 4); assert.equal(otherSelects.length, 4);
const modelFormatSelectEl = otherSelects[0]; const modelFormatSelectEl = otherSelects[0];
@@ -4618,4 +4747,62 @@ test('Step table semantic tone classes (speed/cache/ttft/cost) and domain-aligne
}); });
assert.equal(quotaCell.valueText, '余 42%'); assert.equal(quotaCell.valueText, '余 42%');
assert.equal(quotaCell.subText, 'Carbon 5h · 周 85%', 'Identifies pool/window without repeating 余 42%'); assert.equal(quotaCell.subText, 'Carbon 5h · 周 85%', 'Identifies pool/window without repeating 余 42%');
const avgTpsCell = resolveOverviewMetricCell('avg_tps', { active: mockActive });
assert.equal(avgTpsCell.valueClass, 'cell-value tone-info', 'avg_tps 57.3 tok/s uses same speed tone-info');
// 5. Capsule metric slots strictly match overview/hover/steps semantic tones
const capBaseCtx = {
hasTelemetry: true,
usedPct: 55.8,
dashOffset: 14,
isRunning: false,
tps: 43.7,
avgTps: 57.3,
ttft: 22.3,
stepCost: 0.198,
sessionCost: 46.9,
cacheHitPct: 98.5,
latestPromptTokens: 155212,
sessionTokens: 25_500_000,
quotas: mockQuotas,
};
assert.equal(
resolveCapsuleMetricPresentation('tps', capBaseCtx, 32.67).toneClass,
'tone-info',
'Idle capsule 43.7 t/s matches hover card tone-info cyan'
);
assert.equal(
resolveCapsuleMetricPresentation('tps', { ...capBaseCtx, isRunning: true, tps: 68.4 }, 32.67).toneClass,
'tone-good',
'Running capsule 68.4 t/s matches overview/hover tone-good green instead of legacy orange'
);
assert.equal(
resolveCapsuleMetricPresentation('avg_tps', capBaseCtx, 32.67).toneClass,
'tone-info'
);
assert.equal(
resolveCapsuleMetricPresentation('cache_hit', capBaseCtx, 32.67).toneClass,
'tone-good',
'Capsule cache_hit 98.5% matches hover card tone-good green'
);
assert.equal(
resolveCapsuleMetricPresentation('cache_hit', { ...capBaseCtx, cacheHitPct: 77.6 }, 32.67).toneClass,
'tone-info'
);
assert.equal(
resolveCapsuleMetricPresentation('ttft', capBaseCtx, 32.67).toneClass,
'tone-warn',
'Capsule ttft 22.3s uses unified >=18s tone-warn threshold'
);
assert.equal(
resolveCapsuleMetricPresentation('ttft', { ...capBaseCtx, ttft: 16.0 }, 32.67).toneClass,
'',
'Capsule ttft 16.0s stays neutral (<18s) matching overview/step table'
);
assert.equal(
resolveCapsuleMetricPresentation('cost', capBaseCtx, 32.67).toneClass,
'tone-warn',
'Capsule step cost $0.198 matches tone-warn'
);
}); });