feat(panel): modularize 3-tab preferences, add model context windows, and optimize telemetry

- Refactor Preferences into decoupled General, Structure, and Other tabs with unified settings schema, factory reset, and trajectory cache rebuild endpoints
- Extract standalone widget, metric, and step-table column registries to customize topbar/composer slots, hover popup modules, live overview layout, and step detail columns
- Add bilingual zh-CN/en-US i18n dictionaries, theme accent presets, and font scale controls across Shadow DOM overlay and sidebar views
- Support per-model host-advertised context window rules across App and IDE transports
- Preserve CLEARED step generation timings, memoize per-poll model resolution, optimize LOESS sorted-x fitting, and update bilingual READMEs and test suites
This commit is contained in:
fish
2026-11-15 01:18:29 +09:00
parent ad33e9cc62
commit 18c608ae63
63 changed files with 16614 additions and 5873 deletions
@@ -260,24 +260,63 @@ export function computePublicationFit(
// n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带
const q = Math.max(5, Math.min(n, Math.ceil(span * n)));
const distBuf = new Float64Array(n);
const wBuf = new Float64Array(n);
const sortedXs = q <= n && xs.slice(0, n).every(
(x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x)
);
function loessBandwidth(x0) {
// 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。
let left = 0;
let right = n - q;
while (left < right) {
const mid = (left + right) >>> 1;
if (x0 - xs[mid] > xs[mid + q] - x0) {
left = mid + 1;
} else {
right = mid;
}
}
return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0));
}
function evalLoessPoint(x0, diagIdx = -1) {
for (let j = 0; j < n; j++) {
distBuf[j] = Math.abs(xs[j] - x0);
}
const sortedDists = Array.from(distBuf).sort((a, b) => a - b);
let h = sortedDists[q - 1];
if (h <= 1e-9) {
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
let h;
if (sortedXs) {
h = loessBandwidth(x0);
if (h <= 1e-9) {
h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6);
}
} else {
const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b);
h = sortedDists[q - 1];
if (h <= 1e-9) {
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
}
}
const maxDist = h * 1.0001;
let start = 0;
let end = n;
if (sortedXs) {
// 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。
let right = n;
while (start < right) {
const mid = (start + right) >>> 1;
if (x0 - xs[mid] >= maxDist) start = mid + 1;
else right = mid;
}
let left = start;
while (left < end) {
const mid = (left + end) >>> 1;
if (xs[mid] - x0 < maxDist) left = mid + 1;
else end = mid;
}
}
let sw = 0;
let swx = 0;
for (let j = 0; j < n; j++) {
const u = distBuf[j] / maxDist;
for (let j = start; j < end; j++) {
const u = Math.abs(xs[j] - x0) / maxDist;
const w = u >= 1 ? 0 : (1 - u * u * u) ** 3;
wBuf[j] = w;
sw += w;
@@ -291,7 +330,7 @@ export function computePublicationFit(
const mx = swx / sw;
let sxxW = 0;
for (let j = 0; j < n; j++) {
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const dx = xs[j] - mx;
@@ -304,7 +343,7 @@ export function computePublicationFit(
let leverageNormSq = 0;
let diagHat = 0;
for (let j = 0; j < n; j++) {
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const lj = w / sw + (useSlope ? (w * (xs[j] - mx) * dx0) / sxxW : 0);
@@ -6,6 +6,7 @@
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { i18nStore, t } from '../../i18n/index.js';
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
import {
fetchTelemetry,
@@ -20,9 +21,13 @@ function formatConvOptionMeta(c) {
if (!c) return '';
const subs = Number(c.subagentCount || 0);
if (subs > 0) {
return `主${c.stepCount || 0} · ${subs}子 (共${c.totalStepCount || c.stepCount || 0}步)`;
return t('header.convMetaWithSubs', {
main: c.stepCount || 0,
subs,
total: c.totalStepCount || c.stepCount || 0,
});
}
return `${c.stepCount || 0}步`;
return t('header.convMetaSteps', { count: c.stepCount || 0 });
}
export const TopSessionHeader = defineComponent({
@@ -30,8 +35,8 @@ export const TopSessionHeader = defineComponent({
setup({ onCleanup }) {
const convSelect = CustomSelect({
modelValue: telemetryStore.getState().selectedConversationId,
placeholder: '跟随最新会话',
options: [{ value: '', label: '跟随最新会话' }],
placeholder: t('header.followLatest'),
options: [{ value: '', label: t('header.followLatest') }],
onUpdateModelValue: (nextConvId) => {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
telemetryStore.setState({ selectedConversationId: nextConvId });
@@ -40,7 +45,7 @@ export const TopSessionHeader = defineComponent({
});
const updateBtnIcon = createSvgIcon('arrow-down', { size: 11 });
const updateBtnText = h('span', { text: '有新版本' });
const updateBtnText = h('span', { text: t('header.hasUpdate') });
let isHeaderUpdating = false;
const updateBtn = h(
'button',
@@ -48,11 +53,11 @@ export const TopSessionHeader = defineComponent({
type: 'button',
className: 'update-badge-btn',
hidden: true,
'aria-label': '发现新版本,点击升级',
'aria-label': t('header.ariaUpdate'),
onClick: async () => {
if (isHeaderUpdating) return;
isHeaderUpdating = true;
patchText(updateBtnText, '升级中…');
patchText(updateBtnText, t('header.upgrading'));
patchAttr(updateBtn, 'disabled', true);
try {
const res = await triggerPluginUpdate();
@@ -67,7 +72,9 @@ export const TopSessionHeader = defineComponent({
const cs = telemetryStore.getState().telemetry?.cloudStatus;
patchText(
updateBtnText,
cs?.latestPluginVersion ? `升级 v${cs.latestPluginVersion}` : '有新版本'
cs?.latestPluginVersion
? t('header.upgradeToVer', { ver: cs.latestPluginVersion })
: t('header.hasUpdate')
);
}
},
@@ -76,7 +83,7 @@ export const TopSessionHeader = defineComponent({
);
const statusIcon = createSvgIcon('pulse', { size: 12 });
const statusText = h('span', { text: '实时 2s' });
const statusText = h('span', { text: t('header.statusLive') });
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
const refreshBtn = h(
@@ -84,7 +91,7 @@ export const TopSessionHeader = defineComponent({
{
type: 'button',
className: 'icon-btn',
'aria-label': '刷新数据',
'aria-label': t('header.ariaRefresh'),
onClick: () => fetchTelemetry({ force: true }),
},
[createSvgIcon('refresh', { size: 13 })]
@@ -114,6 +121,9 @@ export const TopSessionHeader = defineComponent({
lastActiveCascadeId = currentCascadeId;
}
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
const actConv = telemetry?.activeConversation;
const convs = telemetry?.conversations || [];
const hostRouteId = telSt.hostRouteConversationId || '';
@@ -122,12 +132,12 @@ export const TopSessionHeader = defineComponent({
(actConv?.cascadeId === hostRouteId ? actConv : null)
: null;
const defaultOptLabel = hostRouteId
? hostMatchedConv?.title
? `当前窗口 (${hostMatchedConv.title})`
: `当前窗口 (${hostRouteId.slice(0, 8)})`
? t('header.currentWindowNamed', {
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
})
: convs[0]?.title
? `最新 (${convs[0].title})`
: '跟随最新会话';
? t('header.latestNamed', { title: convs[0].title })
: t('header.followLatest');
const defaultOptMeta = hostRouteId
? hostMatchedConv
? formatConvOptionMeta({
@@ -153,14 +163,14 @@ export const TopSessionHeader = defineComponent({
const lockedTitle =
isLoadedLocked && actConv?.title
? actConv.title
: `已锁定会话 (${String(lockedId).slice(0, 8)})`;
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
const lockedMeta = isLoadedLocked
? formatConvOptionMeta({
stepCount: actConv.stepCount,
subagentCount: actConv.subagentCount,
totalStepCount: actConv.totalStepsAllAgents,
})
: '已锁定';
: t('header.lockedMeta');
options.splice(1, 0, {
value: lockedId,
label: lockedTitle,
@@ -169,6 +179,7 @@ export const TopSessionHeader = defineComponent({
}
convSelect.setProps({
modelValue: telSt.selectedConversationId,
placeholder: t('header.followLatest'),
options,
});
@@ -186,8 +197,8 @@ export const TopSessionHeader = defineComponent({
patchText(
updateBtnText,
cloudStatus?.latestPluginVersion
? `升级 v${cloudStatus.latestPluginVersion}`
: '有新版本'
? t('header.upgradeToVer', { ver: cloudStatus.latestPluginVersion })
: t('header.hasUpdate')
);
}
@@ -203,7 +214,7 @@ export const TopSessionHeader = defineComponent({
if (isSyncing) {
patchSvgIcon(statusIcon, 'refresh');
patchText(statusText, '同步中');
patchText(statusText, t('header.statusSyncing'));
patchClasses(statusTag, {
'state-running': false,
'state-synced': true,
@@ -211,7 +222,7 @@ export const TopSessionHeader = defineComponent({
});
} else if (isSynced) {
patchSvgIcon(statusIcon, 'check');
patchText(statusText, '已刷新');
patchText(statusText, t('header.statusSynced'));
patchClasses(statusTag, {
'state-running': false,
'state-synced': true,
@@ -219,7 +230,7 @@ export const TopSessionHeader = defineComponent({
});
} else if (isError) {
patchSvgIcon(statusIcon, 'warning');
patchText(statusText, '重试中');
patchText(statusText, t('header.statusRetrying'));
patchClasses(statusTag, {
'state-running': false,
'state-synced': false,
@@ -230,7 +241,7 @@ export const TopSessionHeader = defineComponent({
const runSuffix =
hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : '';
patchSvgIcon(statusIcon, 'bolt');
patchText(statusText, `生成中${runSuffix}`);
patchText(statusText, t('header.statusGenerating', { suffix: runSuffix }));
patchClasses(statusTag, {
'state-running': true,
'state-synced': false,
@@ -238,7 +249,10 @@ export const TopSessionHeader = defineComponent({
});
} else if (quotaStale) {
patchSvgIcon(statusIcon, 'warning');
patchText(statusText, quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线');
patchText(
statusText,
quotaMeta?.hasOfficialData ? t('header.statusQuotaCached') : t('header.statusQuotaOffline')
);
patchClasses(statusTag, {
'state-running': false,
'state-synced': false,
@@ -246,7 +260,7 @@ export const TopSessionHeader = defineComponent({
});
} else {
patchSvgIcon(statusIcon, 'pulse');
patchText(statusText, '实时 2s');
patchText(statusText, t('header.statusLive'));
patchClasses(statusTag, {
'state-running': false,
'state-synced': false,
@@ -265,8 +279,14 @@ export const TopSessionHeader = defineComponent({
() => renderHeaderState()
);
const unsubI18n = i18nStore.subscribe(
(st) => st.locale,
() => renderHeaderState()
);
onCleanup(() => {
unsubTelemetry();
unsubI18n();
convSelect.destroy();
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,162 @@
/**
* @fileoverview Reusable Accordion / Collapsible Section (`CollapsibleSection.js`)
* for `SettingsStructureTab`.
*/
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js';
export const CollapsibleSection = defineComponent({
name: 'CollapsibleSection',
setup({ props, onCleanup }) {
let expanded = Boolean(props.defaultExpanded);
let statusTimer = null;
const chevronIcon = createSvgIcon('chevron-right', {
size: 12,
className: 'collapsible-chevron',
});
const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null;
const titleTextEl = h('span', {
className: 'collapsible-title-text',
text: props.title || '',
});
const triggerChildren = [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 statusTextEl = h('span', { className: 'collapsible-status', text: '' });
const badgeEl = h('span', {
className: 'collapsible-badge text-mono',
hidden: !props.badgeText,
text: props.badgeText || '',
});
const resetBtnText = h('span', { text: props.resetLabel || t('settings.resetBtn') });
const resetBtn =
typeof props.onReset === 'function'
? h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
disabled: props.resetDisabled !== false,
onClick: (e) => {
e.stopPropagation();
props.onReset();
},
},
[resetBtnText]
)
: null;
const rightChildren = [statusTextEl, badgeEl];
if (resetBtn) rightChildren.push(resetBtn);
const headerRow = h('div', { className: 'collapsible-header-row' }, [
triggerBtn,
h('span', { className: 'collapsible-right' }, rightChildren),
]);
const bodyEl = h(
'div',
{
className: 'collapsible-body',
hidden: !expanded,
},
Array.isArray(props.children) ? props.children : []
);
const sectionEl = h(
'section',
{
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}`,
},
[headerRow, bodyEl]
);
function setExpanded(next) {
expanded = Boolean(next);
patchClasses(sectionEl, { 'is-expanded': expanded });
patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false');
patchAttr(bodyEl, 'hidden', !expanded);
}
function setTitle(text) {
patchText(titleTextEl, text || '');
}
function setBadge(text) {
patchAttr(badgeEl, 'hidden', !text);
patchText(badgeEl, text || '');
}
function setResetLabel(text) {
if (resetBtn) {
patchText(resetBtnText, text || t('settings.resetBtn'));
}
}
function setResetDisabled(disabled) {
if (resetBtn) {
patchAttr(resetBtn, 'disabled', Boolean(disabled));
}
}
function showStatus(text, autoClearMs = 1500) {
if (statusTimer) {
clearTimeout(statusTimer);
statusTimer = null;
}
patchText(statusTextEl, text || '');
if (text && autoClearMs > 0) {
statusTimer = setTimeout(() => {
statusTimer = null;
patchText(statusTextEl, '');
}, autoClearMs);
}
}
onCleanup(() => {
if (statusTimer) {
clearTimeout(statusTimer);
statusTimer = null;
}
});
return {
el: sectionEl,
refs: {
triggerBtn,
bodyEl,
resetBtn,
setExpanded,
isExpanded: () => expanded,
setTitle,
setBadge,
setResetLabel,
setResetDisabled,
showStatus,
},
};
},
});
@@ -0,0 +1,261 @@
/**
* @fileoverview Reusable `+` / `-` / `↑` / `↓` 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).
*/
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js';
import { CustomSelect } from '../ui/CustomSelect.js';
export const EditableSlotList = defineComponent({
name: 'EditableSlotList',
setup({ props, onCleanup }) {
const minItems = Math.max(0, Number(props.minItems ?? 1));
const maxItems = Math.max(minItems, Number(props.maxItems ?? 5));
let currentItems = Array.isArray(props.items) ? [...props.items] : [];
let currentOptions = Array.isArray(props.options) ? [...props.options] : [];
let emptyHintText = String(props.emptyHintText || '');
let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null;
const listEl = h('div', { className: 'editable-slot-list' });
const emptyEl = h('div', {
className: 'editable-slot-empty',
hidden: true,
text: emptyHintText,
});
const addBtnLabel = h('span', { text: '' });
const addBtn = h(
'button',
{
type: 'button',
className: 'slot-add-btn',
onClick: () => {
if (currentItems.length >= maxItems) return;
const usedSet = new Set(currentItems);
const nextOpt = currentOptions.find((opt) => !usedSet.has(opt.value));
if (!nextOpt) return;
emitChange([...currentItems, nextOpt.value]);
},
},
[createSvgIcon('plus', { size: 11 }), addBtnLabel]
);
const footerEl = h('div', { className: 'editable-slot-footer' }, [addBtn]);
const rootEl = h('div', { className: 'editable-slot-wrap' }, [emptyEl, listEl, footerEl]);
const rowPool = [];
function emitChange(nextItems) {
currentItems = [...nextItems];
syncRows();
if (typeof props.onChange === 'function') {
props.onChange([...currentItems]);
}
}
function createSlotRow() {
let rowIndex = 0;
const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' });
const selectComp = CustomSelect({
modelValue: '',
options: [],
onUpdateModelValue: (nextVal) => {
if (!nextVal || currentItems[rowIndex] === nextVal) return;
if (currentItems.some((v, idx) => idx !== rowIndex && v === nextVal)) return;
const next = [...currentItems];
next[rowIndex] = nextVal;
emitChange(next);
},
});
const upBtn = h(
'button',
{
type: 'button',
className: 'slot-move-btn',
onClick: (e) => {
e.stopPropagation();
if (rowIndex <= 0) return;
const next = [...currentItems];
const tmp = next[rowIndex - 1];
next[rowIndex - 1] = next[rowIndex];
next[rowIndex] = tmp;
emitChange(next);
},
},
[createSvgIcon('chevron-up', { size: 12 })]
);
const downBtn = h(
'button',
{
type: 'button',
className: 'slot-move-btn',
onClick: (e) => {
e.stopPropagation();
if (rowIndex >= currentItems.length - 1) return;
const next = [...currentItems];
const tmp = next[rowIndex + 1];
next[rowIndex + 1] = next[rowIndex];
next[rowIndex] = tmp;
emitChange(next);
},
},
[createSvgIcon('chevron-down', { size: 12 })]
);
const removeBtn = h(
'button',
{
type: 'button',
className: 'slot-move-btn slot-remove-btn',
onClick: (e) => {
e.stopPropagation();
if (currentItems.length <= minItems) return;
const next = currentItems.filter((_, idx) => idx !== rowIndex);
emitChange(next);
},
},
[createSvgIcon('minus', { size: 12 })]
);
const rowEl = h('div', { className: 'editable-slot-row' }, [
indexBadge,
selectComp.el,
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]),
]);
return {
rowEl,
indexBadge,
selectComp,
upBtn,
downBtn,
removeBtn,
setIndex(idx) {
rowIndex = idx;
},
};
}
function syncRows() {
const count = currentItems.length;
patchAttr(emptyEl, 'hidden', count > 0 || !emptyHintText);
if (emptyHintText) {
patchText(emptyEl, emptyHintText);
}
patchAttr(listEl, 'hidden', count === 0);
while (rowPool.length < count) {
rowPool.push(createSlotRow());
}
while (listEl.children && listEl.children.length > count) {
const tailIdx = listEl.children.length - 1;
const tailChild = listEl.children[tailIdx];
tailChild?.remove?.();
}
const canRemove = count > minItems;
const removeTitle = canRemove
? t('settings.slot.remove')
: t('settings.slot.minReached', { min: minItems });
for (let i = 0; i < count; i += 1) {
const entry = rowPool[i];
const itemVal = currentItems[i];
entry.setIndex(i);
patchAttr(entry.rowEl, 'data-slot-row', String(i));
patchText(entry.indexBadge, String(i + 1));
const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i));
const rowOpts = currentOptions.map((opt) => {
const isTaken = otherUsed.has(opt.value);
return isTaken
? {
...opt,
disabled: true,
meta: t('settings.slot.alreadyAdded'),
}
: opt;
});
entry.selectComp.setProps({
modelValue: itemVal,
options: rowOpts,
});
patchAttr(entry.upBtn, 'disabled', i === 0);
patchAttr(entry.upBtn, 'title', t('settings.slot.moveUp'));
patchAttr(entry.upBtn, 'aria-label', t('settings.slot.moveUp'));
patchAttr(entry.downBtn, 'disabled', i === count - 1);
patchAttr(entry.downBtn, 'title', t('settings.slot.moveDown'));
patchAttr(entry.downBtn, 'aria-label', t('settings.slot.moveDown'));
patchAttr(entry.removeBtn, 'disabled', !canRemove);
patchAttr(entry.removeBtn, 'title', removeTitle);
patchAttr(entry.removeBtn, 'aria-label', removeTitle);
if (!listEl.children || listEl.children[i] !== entry.rowEl) {
listEl.appendChild(entry.rowEl);
}
}
// Close any hidden pooled selects
for (let j = count; j < rowPool.length; j += 1) {
rowPool[j].selectComp.close();
}
const usedAll = new Set(currentItems);
const hasAvailableOption = currentOptions.some((opt) => !usedAll.has(opt.value));
const disableAdd = count >= maxItems || !hasAvailableOption;
patchAttr(addBtn, 'disabled', disableAdd);
const addLabel = addBtnTextFn
? addBtnTextFn(count, maxItems)
: `+ (${count}/${maxItems})`;
patchText(addBtnLabel, addLabel);
}
function setProps(next = {}) {
if (Array.isArray(next.items)) {
currentItems = [...next.items];
}
if (Array.isArray(next.options)) {
currentOptions = [...next.options];
}
if (next.emptyHintText !== undefined) {
emptyHintText = String(next.emptyHintText || '');
}
if (typeof next.addBtnTextFn === 'function') {
addBtnTextFn = next.addBtnTextFn;
}
syncRows();
}
syncRows();
onCleanup(() => {
for (const entry of rowPool) {
entry.selectComp.destroy();
}
rowPool.length = 0;
});
return {
el: rootEl,
refs: {
listEl,
addBtn,
emptyEl,
setProps,
getItems: () => [...currentItems],
getSelects: () => rowPool.slice(0, currentItems.length).map((r) => r.selectComp),
},
};
},
});
@@ -0,0 +1,108 @@
/**
* @fileoverview Host-aware Theme Accent Swatch Picker (`ThemeColorPicker.js`).
* Provides the default "跟随宿主" (`host`) pill plus 6 curated color swatches.
*/
import { defineComponent } from '../../core/component.js';
import {
THEME_ACCENT_PRESETS,
normalizeClientThemeAccent,
} from '../../core/appearance.js';
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js';
export const ThemeColorPicker = defineComponent({
name: 'ThemeColorPicker',
setup({ props }) {
let currentKey = normalizeClientThemeAccent(props.modelValue);
const hostLabelEl = h('span', { text: t('settings.gen.accentHost') });
const hostBtn = h(
'button',
{
type: 'button',
className: 'theme-host-chip',
'data-accent-key': 'host',
onClick: () => selectAccent('host'),
},
[hostLabelEl]
);
const swatchPresets = THEME_ACCENT_PRESETS.filter((p) => p.key !== 'host');
const swatchEntries = swatchPresets.map((preset) => {
const checkIcon = createSvgIcon('check', { size: 11 });
const btn = h(
'button',
{
type: 'button',
className: 'theme-swatch-btn',
'data-accent-key': preset.key,
title: t(preset.labelKey),
'aria-label': t(preset.labelKey),
onClick: () => selectAccent(preset.key),
},
[checkIcon]
);
patchStyleVar(btn, '--swatch-color', preset.cssColor);
return { preset, btn, checkIcon };
});
const swatchGroup = h(
'span',
{ className: 'theme-swatch-group' },
swatchEntries.map((s) => s.btn)
);
const rootEl = h('div', { className: 'theme-color-picker' }, [hostBtn, swatchGroup]);
function syncVisuals() {
const isHost = currentKey === 'host';
patchClasses(hostBtn, { 'is-active': isHost });
patchAttr(hostBtn, 'aria-pressed', isHost ? 'true' : 'false');
for (const entry of swatchEntries) {
const active = entry.preset.key === currentKey;
patchClasses(entry.btn, { 'is-active': active });
patchAttr(entry.btn, 'aria-pressed', active ? 'true' : 'false');
patchAttr(entry.checkIcon, 'hidden', !active);
}
}
function refreshLabels() {
patchText(hostLabelEl, t('settings.gen.accentHost'));
for (const entry of swatchEntries) {
const label = t(entry.preset.labelKey);
patchAttr(entry.btn, 'title', label);
patchAttr(entry.btn, 'aria-label', label);
}
}
function selectAccent(nextRaw) {
const normalized = normalizeClientThemeAccent(nextRaw);
if (normalized === currentKey) return;
currentKey = normalized;
syncVisuals();
if (typeof props.onUpdateModelValue === 'function') {
props.onUpdateModelValue(currentKey);
}
}
function setValue(nextRaw) {
currentKey = normalizeClientThemeAccent(nextRaw);
syncVisuals();
}
syncVisuals();
return {
el: rootEl,
refs: {
hostBtn,
swatchEntries,
setValue,
refreshLabels,
getValue: () => currentKey,
},
};
},
});
@@ -13,6 +13,7 @@ import {
patchKeyedList,
patchText,
} from '../../core/domPatch.js';
import { isEnglishLocale, t } from '../../i18n/index.js';
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
@@ -120,6 +121,7 @@ export const CustomSelect = defineComponent({
function chooseOption(option) {
if (!option) return;
if (option.disabled && !getSelectedSet().has(option.value)) return;
const { multiple, options = [], allValue = '', collapseAll = false } = getProps();
if (!multiple) {
const prevVal = getProps().modelValue;
@@ -203,7 +205,7 @@ export const CustomSelect = defineComponent({
patchKeyedList(menuEl, options, {
keyFn: (opt) => opt.value,
sigFn: (opt, idx) =>
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
createRow: (opt) => {
const checkboxIcon = createSvgIcon('check', { size: 10 });
const checkboxBox = h('span', { className: 'select-checkbox', hidden: true }, [
@@ -233,6 +235,7 @@ export const CustomSelect = defineComponent({
const isMulti = Boolean(getProps().multiple);
const selected = selSet.has(opt.value);
const focused = idx === focusedIndex;
const isDisabled = Boolean(opt.disabled && !selected);
patchAttr(refs.checkboxBox, 'hidden', !isMulti);
patchClasses(refs.checkboxBox, { 'is-checked': selected });
patchAttr(refs.checkboxIcon, 'hidden', !selected);
@@ -243,7 +246,10 @@ export const CustomSelect = defineComponent({
patchClasses(el, {
'is-selected': selected,
'is-focused': focused,
'is-disabled': isDisabled,
});
patchAttr(el, 'disabled', isDisabled);
patchAttr(el, 'aria-disabled', isDisabled ? 'true' : null);
patchAttr(el, 'aria-selected', selected ? 'true' : 'false');
patchAttr(el, 'data-value', opt.value);
},
@@ -254,11 +260,11 @@ export const CustomSelect = defineComponent({
const {
options = [],
modelValue,
placeholder = '请选择',
placeholder = t('fmt.selectPlaceholder'),
icon,
multiple = false,
allValue = '',
multiUnit = '项',
multiUnit = isEnglishLocale() ? 'items' : '项',
} = getProps();
patchClasses(rootEl, { 'is-multi': Boolean(multiple) });
patchAttr(leadIcon, 'hidden', !icon);
@@ -281,8 +287,11 @@ export const CustomSelect = defineComponent({
titleText = labelText;
} else {
const names = vals.map((v) => options.find((o) => String(o.value) === v)?.label || v);
labelText = `已选 ${vals.length} ${multiUnit}`;
titleText = `已选 (${vals.length}):${names.join('、')}`;
labelText = t('fmt.selectedCount', { count: vals.length, unit: multiUnit });
titleText = t('fmt.selectedListTitle', {
count: vals.length,
names: names.join(isEnglishLocale() ? ', ' : '、'),
});
}
} else {
const matchedOpt = options.find((o) => o.value === modelValue);
@@ -0,0 +1,497 @@
/**
* @fileoverview Standalone decoupled Context Window Widget (`ContextWindowWidget.js`).
* Supports both interactive multi-agent inspector mode (`LiveOverviewView`)
* and pointer-events-none in-place pre-allocated mode (`WindowOverlayShell` hover popup).
*/
import { defineComponent } from '../../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchText,
} from '../../core/domPatch.js';
import { formatTokens, resolveModelDisplayInfo } from '../../core/formatters.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
import {
formatAgentBadgeText,
formatAgentLabel,
getAgentBadgeClass,
resolveScopedConversation,
} from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js';
import { ContextSegmentMeter } from '../ui/ContextSegmentMeter.js';
const CTX_PILL_BASE_PAD_PX = 14;
const CTX_CJK_CHAR_PX = 11;
const CTX_ASCII_CHAR_PX = 6.1;
const CTX_PILL_GAP_PX = 4;
const CTX_DEFAULT_BAR_WIDTH_PX = 310;
function estimateCtxPillWidth(text) {
let w = CTX_PILL_BASE_PAD_PX;
for (const ch of String(text || '')) {
w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX;
}
return Math.ceil(w);
}
/**
* 10 通道上下文窗口构成定义(通过动态 getter 自动跟随当前激活语言)。
*/
export const CTX_CHANNEL_DEFS = [
{
key: 'assistant',
labelKey: 'ctx.ch.assistant',
titleKey: 'ctx.ch.assistantTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-assistant',
getValue: (c) => Number(c.assistantTokens || 0),
},
{
key: 'toolResults',
labelKey: 'ctx.ch.toolResults',
titleKey: 'ctx.ch.toolResultsTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-tool-results',
getValue: (c) => Number(c.toolResultsTokens || 0),
},
{
key: 'userInput',
labelKey: 'ctx.ch.userInput',
titleKey: 'ctx.ch.userInputTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-user-input',
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
},
{
key: 'subagent',
labelKey: 'ctx.ch.subagent',
titleKey: 'ctx.ch.subagentTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-subagent-msg',
getValue: (c) => Number(c.subagentTokens || 0),
},
{
key: 'checkpoint',
labelKey: 'ctx.ch.checkpoint',
titleKey: 'ctx.ch.checkpointTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-checkpoint',
getValue: (c) => Number(c.checkpointTokens || 0),
},
{
key: 'systemPrompt',
labelKey: 'ctx.ch.systemPrompt',
titleKey: 'ctx.ch.systemPromptTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-system-prompt',
getValue: (c) => Number(c.systemPromptTokens || 0),
},
{
key: 'systemTools',
labelKey: 'ctx.ch.systemTools',
titleKey: 'ctx.ch.systemToolsTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-system-tools',
getValue: (c) => Number(c.systemToolsTokens || 0),
},
{
key: 'mcpTools',
labelKey: 'ctx.ch.mcpTools',
titleKey: 'ctx.ch.mcpToolsTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-mcp-tools',
getValue: (c) => Number(c.mcpToolsTokens || 0),
},
{
key: 'skills',
labelKey: 'ctx.ch.skills',
titleKey: 'ctx.ch.skillsTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-skills',
getValue: (c) => Number(c.skillsTokens || 0),
},
{
key: 'userRules',
labelKey: 'ctx.ch.userRules',
titleKey: 'ctx.ch.userRulesTitle',
get label() {
return t(this.labelKey);
},
get title() {
return t(this.titleKey);
},
segClass: 'seg-user-rules',
getValue: (c) => Number(c.userRulesTokens || 0),
},
];
export const ContextWindowWidget = defineComponent({
name: 'ContextWindowWidget',
setup({ props, onCleanup }) {
const interactiveInspector = props.interactiveInspector !== false;
const isVisibleFn =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
const titleTextEl = h('span', { text: t('module.context') });
const ctxAgentBadge = h('span', {
className: 'agent-badge badge-main',
hidden: true,
text: t('fmt.mainAgent'),
});
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
const ctxInspectorBar = h(
'div',
{ className: 'ctx-inspector-bar', hidden: true },
[ctxPillGroup]
);
const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => {
const swatchEl = h('span', { className: `swatch ${ch.segClass}` });
const labelEl = h('span', { text: ch.label });
const valEl = h('strong', { className: 'text-mono', text: '0' });
const itemEl = h(
'div',
{ className: 'legend-item', ...(interactiveInspector ? { title: ch.title } : {}) },
[h('span', { className: 'legend-left' }, [swatchEl, labelEl]), valEl]
);
return { ch, defaultOrder: idx, swatchEl, labelEl, valEl, itemEl };
});
const ctxLegendGrid = h(
'div',
{ className: 'ctx-legend-grid' },
ctxChannels.map((entry) => entry.itemEl)
);
let lastLegendOrderSig = ctxChannels.map((entry) => entry.ch.key).join(',');
let lastLocale = getEffectiveLocale();
const children = [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('layers', { size: 13 }),
titleTextEl,
ctxAgentBadge,
]),
h('span', { className: 'panel-meta' }, [ctxSummaryText]),
]),
];
if (interactiveInspector) {
children.push(ctxInspectorBar);
}
children.push(ctxSegmentBar.el, ctxLegendGrid);
const ctxPanel = h('section', { className: 'panel' }, children);
let latestData = null;
let ctxPillsExpanded = false;
let lastCascadeId = '';
let cachedBarWidth = 0;
function update({ data } = {}) {
latestData = data || null;
const curLocale = getEffectiveLocale();
patchText(titleTextEl, t('module.context'));
if (!data) {
if (curLocale !== lastLocale) {
lastLocale = curLocale;
for (const entry of ctxChannels) {
patchText(entry.labelEl, entry.ch.label);
if (interactiveInspector) {
patchAttr(entry.itemEl, 'title', entry.ch.title);
}
}
}
return;
}
let availRowWidth = CTX_DEFAULT_BAR_WIDTH_PX;
if (interactiveInspector) {
const measuredWidth =
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
if (measuredWidth > 160) {
cachedBarWidth = measuredWidth;
}
availRowWidth = cachedBarWidth > 160 ? cachedBarWidth : CTX_DEFAULT_BAR_WIDTH_PX;
const currentCascadeId = data.activeConversation?.cascadeId || '';
if (currentCascadeId && currentCascadeId !== lastCascadeId) {
if (lastCascadeId) {
ctxPillsExpanded = false;
}
lastCascadeId = currentCascadeId;
}
}
const uiSt = uiStore.getState();
const {
hasSubagents,
effectiveCtxScope,
agents,
aggregated,
scopedConv,
ctxAgent,
} = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId);
const active = scopedConv || data.activeConversation || {};
const ctx = ctxAgent?.context || active.context || {};
patchAttr(ctxAgentBadge, 'hidden', !(hasSubagents && ctxAgent));
if (hasSubagents && ctxAgent) {
const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain));
patchAttr(ctxAgentBadge, 'class', `agent-badge ${badgeCls}`);
const badgeFullText = formatAgentLabel(ctxAgent);
patchText(ctxAgentBadge, badgeFullText);
if (interactiveInspector) {
patchAttr(ctxAgentBadge, 'title', badgeFullText);
}
}
if (interactiveInspector) {
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
if (hasSubagents && ctxAgent) {
const rawActiveBadge = aggregated?.activeAgentBadge || '主';
const activeBadgeText = isEnglishLocale()
? rawActiveBadge === '主'
? t('fmt.mainBadge')
: rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n }))
: rawActiveBadge;
const pillItems = [
{
key: 'auto',
label: t('ctx.followActive', { badge: activeBadgeText }),
title: t('ctx.followActiveTitle'),
isActive: effectiveCtxScope === 'auto',
mode: 'ctx-only',
},
];
const allAgentPills = agents.map((ag) => {
const agPct = ag.context?.usedPct ?? 0;
const agModelDisplay = resolveModelDisplayInfo(ag, data.settings, {
fallback: t('fmt.unknownModel'),
}).text;
const badgeLabel = formatAgentBadgeText(ag);
return {
key: ag.agentId,
label: `${badgeLabel} ${agPct}%`,
title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${t('header.convMetaSteps', { count: ag.stepCount || 0 })})`,
isActive: effectiveCtxScope === ag.agentId,
mode: 'ctx-only',
};
});
const firstPillWidth =
pillItems.length > 0 ? estimateCtxPillWidth(pillItems[0].label) : 0;
const totalAllWidth = allAgentPills.reduce(
(sum, p) => sum + CTX_PILL_GAP_PX + estimateCtxPillWidth(p.label),
firstPillWidth
);
const needsCollapse = totalAllWidth > availRowWidth && allAgentPills.length > 2;
if (needsCollapse && !ctxPillsExpanded) {
const toggleSample = t('ctx.expandMore', { count: allAgentPills.length });
const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample);
let usedW = firstPillWidth;
let fitCount = 0;
for (let i = 0; i < allAgentPills.length; i += 1) {
const pw = CTX_PILL_GAP_PX + estimateCtxPillWidth(allAgentPills[i].label);
if (fitCount >= 1 && usedW + pw + toggleReservePx > availRowWidth) {
break;
}
usedW += pw;
fitCount += 1;
}
const maxKeep = Math.max(1, allAgentPills.length - 2);
const maxCollapsedCount = Math.max(1, Math.min(maxKeep, fitCount));
const visibleAgentPills = allAgentPills.slice(0, maxCollapsedCount);
const activeHiddenPill = allAgentPills
.slice(maxCollapsedCount)
.find((p) => p.isActive);
if (activeHiddenPill) {
if (visibleAgentPills.length >= 2) {
visibleAgentPills[visibleAgentPills.length - 1] = activeHiddenPill;
} else {
visibleAgentPills.push(activeHiddenPill);
}
}
const hiddenCount = allAgentPills.length - visibleAgentPills.length;
pillItems.push(...visibleAgentPills, {
key: '__toggle_more__',
label: t('ctx.expandMore', { count: hiddenCount }),
title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }),
isActive: false,
isMoreToggle: true,
mode: 'toggle-expand',
});
} else {
pillItems.push(...allAgentPills);
if (needsCollapse) {
pillItems.push({
key: '__toggle_more__',
label: t('ctx.collapse'),
title: t('ctx.collapseTitle'),
isActive: false,
isMoreToggle: true,
mode: 'toggle-expand',
});
}
}
patchKeyedList(ctxPillGroup, pillItems, {
keyFn: (item) => item.key,
sigFn: (item) =>
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`,
createRow: () => {
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' });
return { el: btn, refs: { btn } };
},
updateRow: (refs, item) => {
patchText(refs.btn, item.label);
patchAttr(refs.btn, 'title', item.title);
patchClasses(refs.btn, {
'is-active': item.isActive,
'is-more-toggle': Boolean(item.isMoreToggle),
});
refs.btn.onclick = () => {
if (item.mode === 'toggle-expand') {
ctxPillsExpanded = !ctxPillsExpanded;
if (latestData) update({ data: latestData });
} else {
uiStore.setState({ ctxInspectorAgentId: item.key });
}
};
},
});
}
}
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;
patchText(
ctxSummaryText,
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
);
ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } });
if (interactiveInspector) {
const localeChanged = curLocale !== lastLocale;
lastLocale = curLocale;
const scored = ctxChannels.map((entry) => {
const val = entry.ch.getValue(ctx);
if (localeChanged) {
patchText(entry.labelEl, entry.ch.label);
patchAttr(entry.itemEl, 'title', entry.ch.title);
}
patchText(entry.valEl, formatTokens(val));
return { entry, val };
});
scored.sort((a, b) => b.val - a.val || a.entry.defaultOrder - b.entry.defaultOrder);
const nextLegendOrderSig = scored.map((x) => x.entry.ch.key).join(',');
if (nextLegendOrderSig !== lastLegendOrderSig) {
lastLegendOrderSig = nextLegendOrderSig;
for (const { entry } of scored) {
ctxLegendGrid.appendChild(entry.itemEl);
}
}
} else {
lastLocale = curLocale;
const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({
ch,
defaultOrder,
val: ch.getValue(ctx),
}));
scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder);
for (let i = 0; i < ctxChannels.length; i += 1) {
const slot = ctxChannels[i];
const item = scoredChannels[i];
if (!slot || !item) continue;
patchAttr(slot.swatchEl, 'class', `swatch ${item.ch.segClass}`);
patchText(slot.labelEl, item.ch.label);
patchText(slot.valEl, formatTokens(item.val));
}
}
}
let ro = null;
if (interactiveInspector && typeof ResizeObserver !== 'undefined') {
ro = new ResizeObserver(() => {
if (!isVisibleFn()) return;
const nextW =
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
if (nextW > 160 && Math.abs(nextW - cachedBarWidth) >= 6) {
cachedBarWidth = nextW;
if (latestData?.activeConversation?.hasSubagents) {
update({ data: latestData });
}
}
});
ro.observe(ctxPanel);
}
onCleanup(() => {
if (ro) ro.disconnect();
ctxSegmentBar.destroy();
});
return {
el: ctxPanel,
refs: { update, ctxSegmentBar },
};
},
});
@@ -0,0 +1,478 @@
/**
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
* Displays active multi-session running conversations & collapsible subagent activity
* with an isolated 1s elapsed timer lifecycle.
*/
import { defineComponent } from '../../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchText,
} from '../../core/domPatch.js';
import { formatElapsedSec } from '../../core/formatters.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
import {
fetchTelemetry,
formatAgentBadgeText,
getAgentBadgeClass,
resolveScopedConversation,
telemetryStore,
} from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js';
export const LiveActivityWidget = defineComponent({
name: 'LiveActivityWidget',
setup({ props, onCleanup }) {
const interactive = props.interactive !== false;
const isVisibleFn =
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
const liveActivityBar = h('div', {
className: 'live-activity-list',
hidden: true,
'aria-live': 'polite',
});
const expandedTaskConvIds = new Set();
const activityTimersMap = new Map();
let liveTickTimer = null;
let latestData = null;
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
const now = Date.now();
const prev = activityTimersMap.get(timerKey);
let startMs = prev?.startMs || 0;
if (!prev || prev.sig !== sig) {
const validRaw = Number(rawStartMs || 0);
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
startMs = Number(rawStartMs);
}
activityTimersMap.set(timerKey, { sig, startMs, el: targetEl });
const elapsedSec = Math.max(0, (now - startMs) / 1000);
patchText(targetEl, formatElapsedSec(elapsedSec));
}
function updateLiveElapsedDisplay() {
const now = Date.now();
for (const entry of activityTimersMap.values()) {
if (!entry?.el) continue;
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
patchText(entry.el, formatElapsedSec(elapsedSec));
}
}
function pauseTicker() {
if (liveTickTimer) {
clearInterval(liveTickTimer);
liveTickTimer = null;
}
}
function stopLiveTicker() {
pauseTicker();
activityTimersMap.clear();
}
function ensureLiveTicker() {
if (!isVisibleFn() || activityTimersMap.size === 0) {
pauseTicker();
return;
}
if (!liveTickTimer) {
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
}
}
function resumeTicker() {
if (activityTimersMap.size > 0) {
updateLiveElapsedDisplay();
ensureLiveTicker();
}
}
function createLiveTaskCard() {
const dotIcon = createSvgIcon('dot', { size: 11 });
patchClasses(dotIcon, { 'is-pulsing': true });
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
const titleEl = h('strong', {
className: 'live-task-title',
text: t('live.currentSession'),
});
const subToggleBtn = h('button', {
type: 'button',
className: 'live-sub-toggle',
hidden: true,
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
});
const elapsedEl = h('span', {
className: 'live-activity-elapsed text-mono',
text: '0s',
});
const headerEl = h('div', { className: 'live-task-header' }, [
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
]);
const mainBadge = h('span', {
className: 'agent-badge badge-main',
hidden: true,
text: t('fmt.mainBadge'),
});
const mainPhase = h('strong', {
className: 'live-activity-phase',
text: t('live.thinking'),
});
const mainProgress = h('span', {
className: 'live-activity-progress text-mono',
hidden: true,
text: '',
});
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
const mainDetail = h('span', {
className: 'live-activity-detail',
hidden: true,
text: '',
});
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
mainBadge,
mainPhase,
mainProgress,
mainSep,
mainDetail,
]);
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
return {
el: cardEl,
refs: {
cardEl,
dotIcon,
titleEl,
subToggleBtn,
elapsedEl,
mainBadge,
mainPhase,
mainProgress,
mainSep,
mainDetail,
subListEl,
},
};
}
function createLiveSubRow() {
const subBadge = h('span', {
className: 'agent-badge badge-sub-1',
text: t('fmt.subBadge', { index: 1 }),
});
const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') });
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
const rowEl = h('div', { className: 'live-sub-row' }, [
h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]),
subElapsed,
]);
return {
el: rowEl,
refs: {
rowEl,
subBadge,
subRole,
subSummary,
subElapsed,
},
};
}
function update({ data } = {}) {
latestData = data || null;
if (!data) {
patchAttr(liveActivityBar, 'hidden', true);
stopLiveTicker();
return;
}
const uiSt = uiStore.getState();
const { agents, aggregated } = resolveScopedConversation(
data,
'all',
uiSt.ctxInspectorAgentId
);
const rawRunningList =
Array.isArray(data.runningConversations) && data.runningConversations.length > 0
? data.runningConversations
: data.activeConversation?.isRunning || aggregated?.isRunning
? [
{
cascadeId: data.activeConversation?.cascadeId || 'current',
title: data.activeConversation?.title || t('live.currentSession'),
isCurrentSelected: true,
isMainRunning: Boolean(data.activeConversation?.isRunning),
isRunning: true,
mainActivity:
data.activeConversation?.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, agents.length - 1),
runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length,
subagents: agents
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
isRunning: Boolean(s.isRunning),
stepCount: Number(s.stepCount || 0),
lastModifiedMs: s.lastModifiedMs || 0,
liveActivity: s.liveActivity || {
phase: s.isRunning ? 'thinking' : 'done',
label: s.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
]
: [];
const hasRunningTasks = rawRunningList.length > 0;
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
if (!hasRunningTasks) {
stopLiveTicker();
expandedTaskConvIds.clear();
return;
}
const activeTimerKeys = new Set();
for (const item of rawRunningList) {
activeTimerKeys.add(`main:${item.cascadeId}`);
for (const sub of item.subagents || []) {
if (sub?.isRunning) {
activeTimerKeys.add(`sub:${sub.cascadeId}`);
}
}
}
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
for (const id of [...expandedTaskConvIds]) {
if (!runningIdsSet.has(id)) {
expandedTaskConvIds.delete(id);
}
}
const locale = getEffectiveLocale();
patchKeyedList(liveActivityBar, rawRunningList, {
keyFn: (item) => item.cascadeId,
sigFn: (item) => {
const isExp = interactive
? expandedTaskConvIds.has(item.cascadeId)
: Number(item.runningSubagentCount || 0) > 0;
const subSig = (item.subagents || [])
.map(
(s) =>
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
)
.join('|');
return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
},
createRow: createLiveTaskCard,
updateRow: (refs, item) => {
const act = item.mainActivity || {
phase: 'thinking',
label: t('live.thinking'),
detail: '',
stepProgress: '',
startedAtMs: item.lastModifiedMs || 0,
signature: `fallback:${item.lastModifiedMs || 0}`,
};
const isWaiting = act.phase === 'waiting';
const isCompacting = act.phase === 'compacting';
patchClasses(refs.cardEl, {
'is-waiting': isWaiting,
'is-compacting': isCompacting,
});
patchClasses(refs.dotIcon, { 'is-pulsing': true });
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
patchText(refs.titleEl, convTitle);
if (interactive) {
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
refs.titleEl.onclick = () => {
if (item.cascadeId && item.cascadeId !== 'current') {
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
telemetryStore.setState({ selectedConversationId: item.cascadeId });
fetchTelemetry({ force: false });
}
};
}
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
const runSubCount = Number(item.runningSubagentCount || 0);
const isExpanded = interactive
? expandedTaskConvIds.has(item.cascadeId)
: runSubCount > 0;
patchText(refs.mainBadge, t('fmt.mainBadge'));
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
if (subCount > 0) {
const arrow = isExpanded ? '▾' : '▸';
const toggleText =
runSubCount > 0
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
: t('live.subToggleIdle', { total: subCount, arrow });
patchText(refs.subToggleBtn, toggleText);
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
if (interactive) {
patchAttr(
refs.subToggleBtn,
'title',
isExpanded ? t('live.subCollapseTitle') : t('live.subExpandTitle')
);
refs.subToggleBtn.onclick = (e) => {
e.stopPropagation();
if (expandedTaskConvIds.has(item.cascadeId)) {
expandedTaskConvIds.delete(item.cascadeId);
} else {
expandedTaskConvIds.add(item.cascadeId);
}
if (latestData) update({ data: latestData });
};
}
}
const mainTimerKey = `main:${item.cascadeId}`;
activeTimerKeys.add(mainTimerKey);
bindLiveElapsedTimer(
mainTimerKey,
`${item.cascadeId}:${act.signature || act.label}`,
act.startedAtMs,
refs.elapsedEl
);
patchText(refs.mainPhase, act.label || t('live.thinking'));
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
patchAttr(refs.mainProgress, 'hidden', !progText);
if (progText) {
patchText(refs.mainProgress, progText);
}
const detailStr = act.detail || '';
patchAttr(refs.mainSep, 'hidden', !detailStr);
patchAttr(refs.mainDetail, 'hidden', !detailStr);
patchText(refs.mainDetail, detailStr);
if (interactive) {
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
patchAttr(refs.cardEl, 'title', fullTooltip);
}
const showSubs = subCount > 0 && isExpanded;
patchAttr(refs.subListEl, 'hidden', !showSubs);
if (showSubs) {
const subItems = item.subagents || [];
patchKeyedList(refs.subListEl, subItems, {
keyFn: (sub) => sub.cascadeId,
sigFn: (sub) =>
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
createRow: createLiveSubRow,
updateRow: (subRefs, sub) => {
const subAct = sub.liveActivity || {
phase: sub.isRunning ? 'thinking' : 'done',
label: sub.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: sub.lastModifiedMs || 0,
};
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
const subBadgeText = formatAgentBadgeText({
...sub,
isMain: false,
index: sub.index || 1,
});
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
patchText(subRefs.subBadge, subBadgeText);
const roleText = sub.role || sub.shortLabel || t('fmt.subAgent');
patchText(subRefs.subRole, roleText);
const rawSubLabel = sub.isRunning
? subAct.label || ''
: subAct.label || t('live.done');
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || '']
.filter(Boolean)
.join(' ');
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
patchText(subRefs.subSummary, summaryStr);
if (interactive) {
patchAttr(
subRefs.rowEl,
'title',
`[${subBadgeText}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}`
);
}
if (sub.isRunning) {
const subTimerKey = `sub:${sub.cascadeId}`;
activeTimerKeys.add(subTimerKey);
bindLiveElapsedTimer(
subTimerKey,
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
subAct.startedAtMs,
subRefs.subElapsed
);
} else {
activityTimersMap.delete(`sub:${sub.cascadeId}`);
patchText(
subRefs.subElapsed,
t('header.convMetaSteps', { count: sub.stepCount || 0 })
);
}
},
});
}
},
});
for (const key of [...activityTimersMap.keys()]) {
if (!activeTimerKeys.has(key)) {
activityTimersMap.delete(key);
}
}
updateLiveElapsedDisplay();
ensureLiveTicker();
}
onCleanup(() => {
stopLiveTicker();
});
return {
el: liveActivityBar,
refs: {
update,
pauseTicker,
resumeTicker,
stopLiveTicker,
},
};
},
});
@@ -0,0 +1,106 @@
/**
* @fileoverview Standalone decoupled Metric Matrix Widget (`MetricMatrixWidget.js`).
* Renders 1..4 user-selected telemetry cells dynamically via `metricRegistry.js`.
*/
import { defineComponent } from '../../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchStyleVar,
patchText,
} from '../../core/domPatch.js';
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
import { resolveOverviewMetricCell } from '../../registries/metricRegistry.js';
import {
normalizeClientOverviewMetrics,
resolveScopedConversation,
} from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js';
export const MetricMatrixWidget = defineComponent({
name: 'MetricMatrixWidget',
setup() {
const matrixEl = h('section', {
className: 'telemetry-matrix',
'aria-label': t('module.metrics'),
'data-cols': '4',
});
patchStyleVar(matrixEl, '--matrix-cols', '4');
function createMetricCellNode() {
const labelSpan = h('span', { text: '—' });
const iconSvg = createSvgIcon('pulse', { size: 11 });
const valueEl = h('strong', { className: 'cell-value', text: '—' });
const subEl = h('span', { className: 'cell-sub', text: '—' });
const el = h('div', { className: 'matrix-cell' }, [
h('div', { className: 'cell-label' }, [labelSpan, iconSvg]),
valueEl,
subEl,
]);
return {
el,
refs: { labelSpan, iconSvg, valueEl, subEl },
};
}
function update({ data } = {}) {
patchAttr(matrixEl, 'aria-label', t('module.metrics'));
const metricKeys = normalizeClientOverviewMetrics(data?.settings?.overviewMetrics);
const colCount = Math.max(1, Math.min(4, metricKeys.length));
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
);
const active = scopedConv || data?.activeConversation || {};
const ctx = ctxAgent?.context || active.context || {};
const quotas = data?.quotas || {};
const settings = data?.settings || {};
const locale = getEffectiveLocale();
const cells = metricKeys.map((key) =>
resolveOverviewMetricCell(key, {
active,
ctx,
quotas,
settings,
hasSubagents,
})
);
patchKeyedList(matrixEl, cells, {
keyFn: (cell) => cell.key,
sigFn: (cell) =>
`${locale}:${cell.key}:${cell.label}:${cell.icon}:${cell.isPulsing}:${cell.valueClass}:${cell.valueText}:${cell.subClass}:${cell.subText}`,
createRow: createMetricCellNode,
updateRow: (refs, cell) => {
patchText(refs.labelSpan, cell.label);
patchSvgIcon(refs.iconSvg, cell.icon);
refs.iconSvg.setAttribute('width', String(cell.iconSize));
refs.iconSvg.setAttribute('height', String(cell.iconSize));
patchClasses(refs.iconSvg, { 'is-pulsing': Boolean(cell.isPulsing) });
patchAttr(refs.valueEl, 'class', cell.valueClass);
patchText(refs.valueEl, cell.valueText);
patchAttr(refs.subEl, 'class', cell.subClass);
patchText(refs.subEl, cell.subText);
},
});
}
// Initialize default 4-cell skeleton so hover/overview has zero initial height jump
update({ data: null });
return {
el: matrixEl,
refs: { update },
};
},
});
@@ -0,0 +1,359 @@
/**
* @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`).
* Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT)
* and weekly summary footer for both `LiveOverviewView` and `WindowOverlayShell`.
*/
import { defineComponent } from '../../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchStyleVar,
patchText,
} from '../../core/domPatch.js';
import { formatCountdown, formatTokens, formatUsd } from '../../core/formatters.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
/**
* 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。
*
* @param {object|null|undefined} quotas
* @param {number} minuteTick
* @param {{ isPending?: boolean }} [options]
* @returns {Array<object>}
*/
export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) {
const safeQuotas = quotas || {};
const activePool = safeQuotas.activePool || {};
const rawPools =
Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0
? safeQuotas.pools
: [
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
];
const weekly = safeQuotas.weekly || {};
const poolItems = rawPools.map((p) => {
const key = p.poolKey || p.family || p.poolLabel || 'Other';
const poolLabel = p.poolLabel || p.family || key;
const isActivePool =
Boolean(activePool.family) &&
(activePool.poolKey === key ||
activePool.family === p.family ||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
return {
key,
poolLabel,
poolData: p,
fallbackWeekly: weekly,
isActivePool,
minuteTick,
isPending,
};
});
if (
weekly?.isOfficial === false &&
poolItems.length > 0 &&
!poolItems.some((item) => item.isActivePool)
) {
poolItems[0].isActivePool = true;
}
return poolItems;
}
/**
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
*/
export function createPoolQuotaRow() {
const title5h = h('span', { className: 'quota-win-title', text: '5h' });
const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]);
const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
const fill5h = h('div', { className: 'progress-fill' });
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]),
h('div', { className: 'progress-track' }, [fill5h]),
]);
const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') });
const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]);
const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
const fillWk = h('div', { className: 'progress-fill' });
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]),
h('div', { className: 'progress-track' }, [fillWk]),
]);
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
row5h,
rowWk,
]);
return {
el,
refs: {
row5h,
left5h,
title5h,
usage5h,
meta5h,
fill5h,
rowWk,
leftWk,
titleWk,
usageWk,
metaWk,
fillWk,
},
};
}
/**
* 格式化可用额度面板底部的汇总行文案(官方配额模式下展示各池周期合计,自定义预算模式下展示自然周累计)。
*/
export function formatQuotaSummaryFooter(quotas, account) {
const weekly = quotas?.weekly || {};
const isCustomLocal = weekly.isOfficial === false;
const tokStr = formatTokens(weekly.tokens || 0);
const costStr = formatUsd(weekly.costUsd || 0);
const leftText = isCustomLocal
? t('quota.footTokensCustom', { tok: tokStr, cost: costStr })
: t('quota.footTokensCycle', { tok: tokStr, cost: costStr });
const rightText =
Number(account?.aiCredits) > 0
? t('quota.footCredits', { credits: account.aiCredits })
: isCustomLocal
? t('quota.footCallsCustom', { calls: weekly.calls || 0 })
: t('quota.footCallsCycle', { calls: weekly.calls || 0 });
const tooltip = isCustomLocal ? t('quota.footTipCustom') : t('quota.footTipCycle');
return { leftText, rightText, tooltip };
}
/**
* 同步单个配额池行的 5h 与每周窗口状态。
*/
export function syncPoolQuotaRow(refs, item, idx, rowEl) {
const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item;
patchAttr(
rowEl,
'style',
idx === 0
? 'display: flex; flex-direction: column; gap: 8px;'
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
);
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false);
const wkUsedRaw = useCustomWeekly
? fallbackWeekly?.usedPct
: poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
const wkRemRaw = useCustomWeekly
? fallbackWeekly?.remainingPct
: poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
const wkResetRaw = useCustomWeekly
? fallbackWeekly?.resetTime || poolData?.weeklyResetTime
: poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
const hasWk = wkUsedRaw != null && wkRemRaw != null;
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
const hide5h = !has5h && hasWk;
const hideWk = !hasWk && has5h;
refs.row5h.hidden = hide5h;
refs.row5h.style.display = hide5h ? 'none' : 'flex';
refs.rowWk.hidden = hideWk;
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed');
patchText(refs.title5h, `5h (${poolLabel})`);
const c5h = poolData?.cycle5h;
if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) {
const tok5h = formatTokens(c5h.tokens || 0);
const cost5h = formatUsd(c5h.costUsd || 0);
const calls5h = Number(c5h.calls || 0);
refs.usage5h.hidden = false;
patchText(refs.usage5h, `· ${tok5h} (${cost5h})`);
patchAttr(
refs.left5h,
'title',
t('quota.cycle5hTitle', {
pool: poolLabel,
tok: tok5h,
cost: cost5h,
calls: calls5h,
})
);
} else {
refs.usage5h.hidden = true;
patchText(refs.usage5h, '');
patchAttr(refs.left5h, 'title', null);
}
patchText(
refs.meta5h,
has5h
? t('quota.usedAndLeft', {
reset: formatCountdown(poolData.resetTime),
used: used5hVal.toFixed(1),
rem: rem5hVal.toFixed(1),
})
: fallbackMetaText
);
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(refs.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-danger': used5hVal >= 85,
});
const customTitle =
useCustomWeekly && fallbackWeekly?.title
? fallbackWeekly.title
: t('quota.weeklyPool', { pool: poolLabel });
patchText(refs.titleWk, customTitle);
const cWk = useCustomWeekly
? fallbackWeekly
: poolData?.cycleWeekly || (isActivePool ? fallbackWeekly : null);
if (!isPending && hasWk && cWk && (cWk.tokens != null || cWk.costUsd != null)) {
const tokWk = formatTokens(cWk.tokens || 0);
const costWk = formatUsd(cWk.costUsd || 0);
const callsWk = Number(cWk.calls || 0);
refs.usageWk.hidden = false;
patchText(refs.usageWk, `· ${tokWk} (${costWk})`);
patchAttr(
refs.leftWk,
'title',
useCustomWeekly
? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk })
: t('quota.cycleWkPoolTitle', {
pool: poolLabel,
tok: tokWk,
cost: costWk,
calls: callsWk,
})
);
} else {
refs.usageWk.hidden = true;
patchText(refs.usageWk, '');
patchAttr(refs.leftWk, 'title', null);
}
patchText(
refs.metaWk,
hasWk
? t('quota.usedAndLeft', {
reset: formatCountdown(wkResetRaw),
used: usedWkVal.toFixed(1),
rem: remWkVal.toFixed(1),
})
: fallbackMetaText
);
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(refs.fillWk, {
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
'tone-danger': usedWkVal >= 85,
});
}
export function quotaPoolRowSig(item, idx) {
const c5h = item.poolData?.cycle5h;
const cWk = item.poolData?.cycleWeekly;
const fw = item.fallbackWeekly;
return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`;
}
export const QuotaPoolsWidget = defineComponent({
name: 'QuotaPoolsWidget',
setup({ props }) {
const compactHover = Boolean(props.compactHover);
const titleTextEl = h('span', { text: t('module.quotas') });
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
const poolsListEl = h(
'div',
compactHover
? { className: 'wm-hover-quota-pools' }
: { style: 'display: flex; flex-direction: column; gap: 0;' }
);
if (compactHover) {
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
keyFn: (item) => item.key,
sigFn: quotaPoolRowSig,
createRow: createPoolQuotaRow,
updateRow: syncPoolQuotaRow,
});
}
const initFoot = formatQuotaSummaryFooter(null, null);
const wkFootLeft = h('span', { className: 'text-muted', text: initFoot.leftText });
const wkFootRight = h('span', {
className: 'text-muted',
text: compactHover ? initFoot.rightText : '',
});
const quotaPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('pulse', { size: 13 }),
titleTextEl,
]),
tierBadge,
]),
poolsListEl,
h(
'div',
compactHover
? { className: 'panel-header wm-hover-quota-foot' }
: { className: 'panel-header', style: 'font-size: var(--fs-md); padding-top: 2px;' },
[wkFootLeft, wkFootRight]
),
]);
function update({ data, minuteTick } = {}) {
patchText(titleTextEl, t('module.quotas'));
if (!data) {
if (compactHover) {
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
keyFn: (item) => item.key,
sigFn: quotaPoolRowSig,
createRow: createPoolQuotaRow,
updateRow: syncPoolQuotaRow,
});
const pendingFoot = formatQuotaSummaryFooter(null, null);
patchText(wkFootLeft, pendingFoot.leftText);
patchText(wkFootRight, pendingFoot.rightText);
}
return;
}
const quotas = data.quotas || {};
const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000);
patchText(
tierBadge,
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
);
patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick), {
keyFn: (item) => item.key,
sigFn: quotaPoolRowSig,
createRow: createPoolQuotaRow,
updateRow: syncPoolQuotaRow,
});
const footSummary = formatQuotaSummaryFooter(quotas, data.account);
patchText(wkFootLeft, footSummary.leftText);
patchText(wkFootRight, footSummary.rightText);
patchAttr(wkFootLeft, 'title', footSummary.tooltip);
patchAttr(wkFootRight, 'title', footSummary.tooltip);
}
return {
el: quotaPanel,
refs: { update, poolsListEl },
};
},
});