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
@@ -21,8 +21,12 @@ import {
import { formatElapsedSec } from '../../core/formatters.js';
import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js';
import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js';
import { createSvgIcon, patchSvgIcon, SVG_NS } from '../../icons/SvgIcon.js';
import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js';
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
import {
RING_CIRCUMFERENCE,
createCapsuleSlotNode,
syncCapsuleSlotNodes,
} from '../widgets/CapsuleBarWidget.js';
import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js';
import {
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 FLOATING_CARD_WIDTH = 522;
const MULTI_PANEL_WIDTH = 464;
const RING_RADIUS = 5.2;
const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
/**
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
@@ -1183,75 +1185,13 @@ export function mountWindowOverlay() {
[multiDot, multiLabel]
);
// 构建可复用的预占胶囊槽位节点(支持 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,
};
}
// 构建可复用的预占胶囊槽位节点(由 CapsuleBarWidget 共享创建,支持 1..5 项动态槽位)
const capsuleSlots = [
createCapsuleSlot(0, 'context'),
createCapsuleSlot(1, 'tps'),
createCapsuleSlot(2, 'quota_auto'),
createCapsuleSlot(3, 'none'),
createCapsuleSlot(4, 'none'),
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' }),
@@ -2370,53 +2310,7 @@ export function mountWindowOverlay() {
}
function applyCapsuleSlots(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 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) : '');
}
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
}
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) ---
@@ -1,6 +1,7 @@
/**
* @fileoverview Reusable Accordion / Collapsible Section (`CollapsibleSection.js`)
* for `SettingsStructureTab`.
* @fileoverview Reusable Section Card (`CollapsibleSection.js`)
* for `SettingsStructureTab` — supports both accordion mode (`collapsible: true`)
* and static 3rd-level pane card mode (`collapsible: false`).
*/
import { defineComponent } from '../../core/component.js';
@@ -11,38 +12,44 @@ import { t } from '../../i18n/index.js';
export const CollapsibleSection = defineComponent({
name: 'CollapsibleSection',
setup({ props, onCleanup }) {
let expanded = Boolean(props.defaultExpanded);
const isCollapsible = props.collapsible !== false;
let expanded = isCollapsible ? Boolean(props.defaultExpanded) : true;
let statusTimer = null;
const chevronIcon = createSvgIcon('chevron-right', {
size: 12,
className: 'collapsible-chevron',
});
const chevronIcon = isCollapsible
? createSvgIcon('chevron-right', {
size: 12,
className: 'collapsible-chevron',
})
: null;
const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null;
const titleTextEl = h('span', {
className: 'collapsible-title-text',
text: props.title || '',
});
const triggerChildren = [chevronIcon];
const triggerChildren = [];
if (chevronIcon) triggerChildren.push(chevronIcon);
if (sectionIcon) triggerChildren.push(sectionIcon);
triggerChildren.push(titleTextEl);
const triggerBtn = h(
'button',
{
type: 'button',
className: 'collapsible-trigger',
'aria-expanded': expanded ? 'true' : 'false',
onClick: () => {
setExpanded(!expanded);
if (typeof props.onToggle === 'function') {
props.onToggle(expanded);
}
},
},
triggerChildren
);
const triggerBtn = isCollapsible
? h(
'button',
{
type: 'button',
className: 'collapsible-trigger',
'aria-expanded': expanded ? 'true' : 'false',
onClick: () => {
setExpanded(!expanded);
if (typeof props.onToggle === 'function') {
props.onToggle(expanded);
}
},
},
triggerChildren
)
: h('div', { className: 'collapsible-title-static' }, triggerChildren);
const statusTextEl = h('span', { className: 'collapsible-status', text: '' });
const badgeEl = h('span', {
@@ -89,12 +96,13 @@ export const CollapsibleSection = defineComponent({
const sectionEl = h(
'section',
{
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}`,
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}${isCollapsible ? '' : ' is-static-pane'}`,
},
[headerRow, bodyEl]
);
function setExpanded(next) {
if (!isCollapsible) return;
expanded = Boolean(next);
patchClasses(sectionEl, { 'is-expanded': expanded });
patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false');
@@ -149,13 +157,15 @@ export const CollapsibleSection = defineComponent({
triggerBtn,
bodyEl,
resetBtn,
badgeEl,
statusTextEl,
setExpanded,
isExpanded: () => expanded,
setTitle,
setBadge,
setResetLabel,
setResetDisabled,
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),
* 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 { h, patchAttr, patchText } from '../../core/domPatch.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.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({
name: 'EditableSlotList',
setup({ props, onCleanup }) {
@@ -19,6 +38,7 @@ export const EditableSlotList = defineComponent({
let currentOptions = Array.isArray(props.options) ? [...props.options] : [];
let emptyHintText = String(props.emptyHintText || '');
let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null;
let activeDrag = null;
const listEl = h('div', { className: 'editable-slot-list' });
const emptyEl = h('div', {
@@ -52,13 +72,162 @@ export const EditableSlotList = defineComponent({
function emitChange(nextItems) {
currentItems = [...nextItems];
syncRows();
if (typeof props.onPreview === 'function') {
props.onPreview([...currentItems]);
}
if (typeof props.onChange === 'function') {
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() {
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 selectComp = CustomSelect({
modelValue: '',
@@ -123,14 +292,25 @@ export const EditableSlotList = defineComponent({
[createSvgIcon('minus', { size: 12 })]
);
const rowEl = h('div', { className: 'editable-slot-row' }, [
indexBadge,
selectComp.el,
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]),
]);
const orderBtnsEl = h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]);
const rowEl = h(
'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 {
rowEl,
dragHandle,
indexBadge,
selectComp,
upBtn,
@@ -160,6 +340,8 @@ export const EditableSlotList = defineComponent({
tailChild?.remove?.();
}
const canDrag = count > 1;
const dragTitle = canDrag ? t('settings.slot.dragHint') : '';
const canRemove = count > minItems;
const removeTitle = canRemove
? t('settings.slot.remove')
@@ -171,6 +353,8 @@ export const EditableSlotList = defineComponent({
entry.setIndex(i);
patchAttr(entry.rowEl, 'data-slot-row', String(i));
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 rowOpts = currentOptions.map((opt) => {
@@ -222,7 +406,7 @@ export const EditableSlotList = defineComponent({
}
function setProps(next = {}) {
if (Array.isArray(next.items)) {
if (!activeDrag && Array.isArray(next.items)) {
currentItems = [...next.items];
}
if (Array.isArray(next.options)) {
@@ -240,6 +424,7 @@ export const EditableSlotList = defineComponent({
syncRows();
onCleanup(() => {
teardownActiveDrag({ revert: false });
for (const entry of rowPool) {
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',
setup({ props, onCleanup }) {
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 =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
@@ -275,7 +283,6 @@ export const ContextWindowWidget = defineComponent({
}
}
const uiSt = uiStore.getState();
const {
hasSubagents,
effectiveCtxScope,
@@ -283,7 +290,7 @@ export const ContextWindowWidget = defineComponent({
aggregated,
scopedConv,
ctxAgent,
} = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId);
} = resolveScopedConversation(data, 'all', getCtxAgentId());
const active = scopedConv || data.activeConversation || {};
const ctx = ctxAgent?.context || active.context || {};
@@ -411,7 +418,7 @@ export const ContextWindowWidget = defineComponent({
ctxPillsExpanded = !ctxPillsExpanded;
if (latestData) update({ data: latestData });
} else {
uiStore.setState({ ctxInspectorAgentId: item.key });
setCtxAgentId(item.key);
}
};
},
@@ -423,6 +430,9 @@ export const ContextWindowWidget = defineComponent({
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
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(
ctxSummaryText,
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
@@ -28,6 +28,11 @@ export const LiveActivityWidget = defineComponent({
name: 'LiveActivityWidget',
setup({ props, onCleanup }) {
const interactive = props.interactive !== false;
const preview = Boolean(props.preview);
const getCtxAgentId =
typeof props.getCtxAgentId === 'function'
? props.getCtxAgentId
: () => uiStore.getState().ctxInspectorAgentId;
const isVisibleFn =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
@@ -203,11 +208,10 @@ export const LiveActivityWidget = defineComponent({
return;
}
const uiSt = uiStore.getState();
const { agents, aggregated } = resolveScopedConversation(
data,
'all',
uiSt.ctxInspectorAgentId
getCtxAgentId()
);
const rawRunningList =
@@ -310,7 +314,7 @@ export const LiveActivityWidget = defineComponent({
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
patchText(refs.titleEl, convTitle);
if (interactive) {
if (interactive && !preview) {
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
refs.titleEl.onclick = () => {
if (item.cascadeId && item.cascadeId !== 'current') {
@@ -23,7 +23,11 @@ import { uiStore } from '../../store/uiStore.js';
export const MetricMatrixWidget = defineComponent({
name: 'MetricMatrixWidget',
setup() {
setup({ props }) {
const getCtxAgentId =
typeof props?.getCtxAgentId === 'function'
? props.getCtxAgentId
: () => uiStore.getState().ctxInspectorAgentId;
const matrixEl = h('section', {
className: 'telemetry-matrix',
'aria-label': t('module.metrics'),
@@ -54,11 +58,10 @@ export const MetricMatrixWidget = defineComponent({
patchAttr(matrixEl, 'data-cols', String(colCount));
patchStyleVar(matrixEl, '--matrix-cols', String(colCount));
const uiSt = uiStore.getState();
const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation(
data,
'all',
uiSt.ctxInspectorAgentId
getCtxAgentId()
);
const active = scopedConv || data?.activeConversation || {};
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)}%`);
patchClasses(refs.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-warn': used5hVal >= 70 && 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)}%`);
patchClasses(refs.fillWk, {
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
'tone-warn': usedWkVal >= 70 && 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,
},
};
},
});