perf(panel): add incremental step transport, memoized aggregation, atomic cache writes, and hidden-view gating

- Project display-only step fields in /api/telemetry, skip unchanged step payloads via stepRevision, coalesce identical client refreshes, and share in-flight backend trajectory scans across same-account requests
- Reuse normalized step values and memoize up to two range aggregations in usage-aggregator gated by step timestamps, pricing revision, model overrides, timezone, and source identity; cache per-trajectory model facts and single-agent step preparation via WeakMap/WeakRef
- Persist trajectory checkpoints atomically in trajectory-cache-file.mjs via chunked writevSync + renameSync while reusing serialized step byte slices for unchanged conversations
- Render step turn-rail lines/dots via CSS pseudo-elements, allocate speed-reason nodes on demand, short-circuit unchanged table reconciliations, and cache per-series LOESS publication fits in SessionStepCharts
- Gate DOM updates and timers across closed overlay panels, hover popups, inactive settings tabs, and unchanged ConsumptionView payloads
- Distinguish canceled steps (CORTEX_STEP_STATUS_CANCELED) and untimed compaction steps from generic incomplete timing in speed-metrics and bilingual i18n labels
This commit is contained in:
fish
2026-11-15 23:33:08 +09:00
parent 03d3160ef0
commit 8968e03adb
33 changed files with 1692 additions and 920 deletions
@@ -317,7 +317,8 @@ export function computePublicationFit(
let swx = 0;
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;
const base = 1 - u * u * u;
const w = u >= 1 ? 0 : base * base * base;
wBuf[j] = w;
sw += w;
swx += w * xs[j];
@@ -339,6 +340,8 @@ export function computePublicationFit(
const dx0 = x0 - mx;
const useSlope = sxxW > 1e-12;
const inverseWeightSum = 1 / sw;
const slopeScale = useSlope ? dx0 / sxxW : 0;
let rawFit = 0;
let leverageNormSq = 0;
let diagHat = 0;
@@ -346,7 +349,7 @@ export function computePublicationFit(
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);
const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0);
rawFit += lj * ys[j];
leverageNormSq += lj * lj;
if (j === diagIdx) diagHat = lj;
@@ -1477,6 +1480,26 @@ export function createModelFitChart() {
let hoveredIdx = -1;
let lastSig = '';
let lastUpdateParams = null;
let fitCacheMetric = '';
const fitCache = new Map();
function reusePublicationFit(key, xs, ys, maxVal, isMultiCompare) {
const previous = fitCache.get(key);
if (
previous && previous.xs.length === xs.length &&
xs.every((x, i) => x === previous.xs[i] && ys[i] === previous.ys[i])
) {
return previous.result;
}
const result = computePublicationFit(xs, ys, {
minVal: 0,
maxVal,
gridSize: isMultiCompare ? 56 : 64,
span: 0.5,
});
fitCache.set(key, { xs, ys, result });
return result;
}
function syncViewWidth() {
const measured = Math.round(
@@ -1802,7 +1825,16 @@ export function createModelFitChart() {
}
}
if (fitCacheMetric !== metric) {
fitCache.clear();
fitCacheMetric = metric;
}
for (const key of fitCache.keys()) {
if (isMultiCompare ? !targetKeySet.has(key) : key !== null) fitCache.delete(key);
}
if (matchedItems.length === 0) {
fitCache.clear();
currentSamples = [];
lastSig = 'empty';
patchAttr(ciBandPath, 'd', '');
@@ -1834,12 +1866,7 @@ export function createModelFitChart() {
if (items.length === 0) continue;
const xs = items.map((d) => d.xVal);
const rawYs = items.map((d) => d.rawVal);
const pubFit = computePublicationFit(xs, rawYs, {
minVal: minBound,
maxVal: maxBound,
gridSize: 56,
span: 0.5,
});
const pubFit = reusePublicationFit(key, xs, rawYs, maxBound, true);
const colorVar =
modelColorByGroup?.get(key) || MODEL_COLOR_VARS[kIdx % MODEL_COLOR_VARS.length];
seriesList.push({
@@ -2067,12 +2094,7 @@ export function createModelFitChart() {
const filtered = matchedItems;
const xs = filtered.map((d) => d.xVal);
const rawYs = filtered.map((d) => d.rawVal);
const pubFit = computePublicationFit(xs, rawYs, {
minVal: minBound,
maxVal: maxBound,
gridSize: 64,
span: 0.5,
});
const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归');
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
@@ -120,6 +120,7 @@ export const TopSessionHeader = defineComponent({
} else if (currentCascadeId) {
lastActiveCascadeId = currentCascadeId;
}
if (!uiSt.monitorVisible) return;
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
@@ -283,10 +284,18 @@ export const TopSessionHeader = defineComponent({
(st) => st.locale,
() => renderHeaderState()
);
const unsubVisibility = uiStore.subscribe(
(st) => st.monitorVisible,
(visible) => {
if (visible) renderHeaderState();
},
{ immediate: false }
);
onCleanup(() => {
unsubTelemetry();
unsubI18n();
unsubVisibility();
convSelect.destroy();
});
@@ -1091,11 +1091,15 @@ export function mountWindowOverlay() {
}
}
function stopMultiLiveTicker() {
function pauseMultiLiveTicker() {
if (multiLiveTickTimer) {
clearInterval(multiLiveTickTimer);
multiLiveTickTimer = null;
}
}
function stopMultiLiveTicker() {
pauseMultiLiveTicker();
multiTimersMap.clear();
}
@@ -1563,6 +1567,7 @@ export function mountWindowOverlay() {
);
// 完整四标签悬浮容器
uiStore.setState({ monitorVisible: false });
const appInstance = App();
const popoverEl = h(
'div',
@@ -2238,10 +2243,13 @@ export function mountWindowOverlay() {
patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) });
patchAttr(multiPanelEl, 'hidden', !multiOpen);
if (multiOpen) {
renderCapsuleTelemetry();
positionFloatingElements();
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => positionFloatingElements());
}
} else {
pauseMultiLiveTicker();
}
}
@@ -2272,6 +2280,7 @@ export function mountWindowOverlay() {
patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) });
patchAttr(hoverTipEl, 'hidden', !tooltipOpen);
if (tooltipOpen) {
renderHoverWidgets();
hoverWidgetHost.resumeTickers();
positionFloatingElements();
if (typeof requestAnimationFrame === 'function') {
@@ -2296,6 +2305,7 @@ export function mountWindowOverlay() {
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
patchAttr(popoverEl, 'hidden', !popoverOpen);
uiStore.setState({ monitorVisible: popoverOpen && !document.hidden }, { sync: true });
if (popoverOpen) {
positionFloatingElements();
if (typeof requestAnimationFrame === 'function') {
@@ -2313,125 +2323,17 @@ export function mountWindowOverlay() {
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
}
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) ---
function renderCapsuleTelemetry() {
if (disposed) return;
const telSt = telemetryStore.getState();
const uiSt = uiStore.getState();
const telemetry = telSt.telemetry;
setI18nLanguage(telemetry?.settings?.language);
applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false });
applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true });
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
patchAttr(multiBtn, 'hidden', !showMulti);
patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off');
if (!showMulti && multiOpen) {
setMultiOpen(false);
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
if (manualSubExpandMap.size > 0) {
const runningIds = new Set(rawRunningList.map((item) => item.cascadeId));
for (const id of manualSubExpandMap.keys()) {
if (!runningIds.has(id)) manualSubExpandMap.delete(id);
}
}
const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots);
const layoutInputsChanged =
showMulti !== lastShowMulti || slotKeys.length !== lastSlotCount;
if (layoutInputsChanged) {
lastShowMulti = showMulti;
lastSlotCount = slotKeys.length;
updateResponsiveLayout();
}
if (!telemetry) {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero'));
patchText(multiRunningMetaEl, t('multi.loading'));
stopMultiLiveTicker();
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
return;
}
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
);
const activeConv = telemetry.activeConversation || {};
const overviewActive = overviewScopedConv || activeConv;
const ctx = ctxAgent?.context || overviewActive.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);
if (!multiOpen || document.hidden) return;
const localeKey = getEffectiveLocale();
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 ---
const rawRunningList =
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0
? telemetry.runningConversations
: activeConv.isRunning || aggregated?.isRunning
? [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
isCurrentSelected: true,
isMainRunning: Boolean(activeConv.isRunning),
isRunning: true,
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, (agents?.length || 1) - 1),
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
contextUsedPct: usedPct,
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: s.badgeText || t('fmt.subBadge', { 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 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 hostRouteLower = String(
telSt.hostRouteConversationId || extractHostRouteCascadeId() || ''
hostRouteConversationId || extractHostRouteCascadeId() || ''
).toLowerCase();
patchText(
@@ -2445,20 +2347,10 @@ export function mountWindowOverlay() {
patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
patchAttr(multiRunningListEl, 'hidden', runningCount === 0);
const runningIdsLower = new Set(
rawRunningList.map((item) => String(item.cascadeId || '').toLowerCase())
);
if (runningCount === 0) {
stopMultiLiveTicker();
manualSubExpandMap.clear();
patchKeyedList(multiRunningListEl, [], {});
} else {
for (const cid of [...manualSubExpandMap.keys()]) {
if (!runningIdsLower.has(String(cid || '').toLowerCase())) {
manualSubExpandMap.delete(cid);
}
}
const activeTimerKeys = new Set();
for (const item of rawRunningList) {
activeTimerKeys.add(`main:${item.cascadeId}`);
@@ -2646,7 +2538,135 @@ export function mountWindowOverlay() {
}
}
ensureMultiLiveTicker();
tickMultiElapsedDisplay();
}
}
function renderHoverWidgets() {
const { telemetry, minuteTick } = telemetryStore.getState();
hoverWidgetHost.update({
moduleKeys: normalizeClientHoverModules(telemetry?.settings?.hoverModules),
data: telemetry,
minuteTick: Number(minuteTick || Math.floor(Date.now() / 30000)),
});
}
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) ---
function renderCapsuleTelemetry() {
if (disposed) return;
const telSt = telemetryStore.getState();
const uiSt = uiStore.getState();
const telemetry = telSt.telemetry;
setI18nLanguage(telemetry?.settings?.language);
applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false });
applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true });
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
patchAttr(multiBtn, 'hidden', !showMulti);
patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off');
if (!showMulti && multiOpen) {
setMultiOpen(false);
}
const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots);
const layoutInputsChanged =
showMulti !== lastShowMulti || slotKeys.length !== lastSlotCount;
if (layoutInputsChanged) {
lastShowMulti = showMulti;
lastSlotCount = slotKeys.length;
updateResponsiveLayout();
}
if (!telemetry) {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero'));
patchText(multiRunningMetaEl, t('multi.loading'));
stopMultiLiveTicker();
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
return;
}
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
);
const activeConv = telemetry.activeConversation || {};
const overviewActive = overviewScopedConv || activeConv;
const ctx = ctxAgent?.context || overviewActive.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);
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 ---
const rawRunningList =
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0
? telemetry.runningConversations
: activeConv.isRunning || aggregated?.isRunning
? [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
isCurrentSelected: true,
isMainRunning: Boolean(activeConv.isRunning),
isRunning: true,
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, (agents?.length || 1) - 1),
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
contextUsedPct: usedPct,
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: s.badgeText || t('fmt.subBadge', { 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 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);
renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId);
// --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 ---
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
@@ -2752,13 +2772,8 @@ export function mountWindowOverlay() {
if (hoverModuleKeys.length === 0 && !showUpdatePrompt && tooltipOpen) {
setTooltipOpen(false);
}
const minuteTick = Number(telSt.minuteTick || Math.floor(Date.now() / 30000));
hoverWidgetHost.update({
moduleKeys: hoverModuleKeys,
data: telemetry,
minuteTick,
});
if (tooltipOpen) {
renderHoverWidgets();
positionFloatingElements();
}
}
@@ -2867,6 +2882,8 @@ export function mountWindowOverlay() {
const onDocFocusIn = () => syncHostRouteIfChanged();
const onVisibilityChange = () => {
if (document.hidden) {
uiStore.setState({ monitorVisible: false });
pauseMultiLiveTicker();
hasPointerCoords = false;
if (tooltipOpen) {
setTooltipOpen(false);
@@ -2877,6 +2894,8 @@ export function mountWindowOverlay() {
return;
}
if (!document.hidden && !disposed) {
uiStore.setState({ monitorVisible: popoverOpen });
if (multiOpen) renderCapsuleTelemetry();
syncHostRouteIfChanged();
void fetchTelemetry({ force: false });
}
@@ -128,6 +128,34 @@ export const StepTableWidget = defineComponent({
stepsTablePane.addEventListener('scroll', hideTurnTip);
stepsTbody.addEventListener('mouseleave', hideTurnTip);
const hoverRows = new WeakMap();
let lastRenderedRows = null;
let lastRenderOptions = '';
function enterStepCell(event) {
const { badge, prompt } = hoverRows.get(this);
if (event?.target === badge) hideTurnTip();
else showTurnTip(this, prompt);
}
function moveInStepCell(event) {
if (event?.target === hoverRows.get(this).badge) hideTurnTip();
}
function moveAlongTurnRail(event) {
const { badge, prompt } = hoverRows.get(this);
const rect = this.getBoundingClientRect?.();
const relX = rect ? (event?.clientX ?? 0) - rect.left : 0;
if (event?.target !== badge && relX <= 18) showTurnTip(this, prompt);
else hideTurnTip();
}
function clearCellHover(cell) {
if (!cell || !hoverRows.delete(cell)) return;
cell.onmouseenter = null;
cell.onmousemove = null;
cell.onmouseleave = null;
}
function renderStepTable(
tableSteps,
@@ -144,6 +172,16 @@ export const StepTableWidget = defineComponent({
} = {}
) {
const colOrderSig = colKeys.join(',');
const renderOptions = JSON.stringify([
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
showStepTurnRail, showStepAgentBadge, displaySettings.showUpstreamModel,
displaySettings.orchestratorIdMode,
]);
if (lastRenderOptions === renderOptions && lastRenderedRows &&
(lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length &&
tableSteps.every((step, i) => step === lastRenderedRows[i])))) {
return;
}
const wantedSet = new Set(colKeys);
syncTableHeaderColumns(colKeys);
@@ -166,20 +204,23 @@ export const StepTableWidget = defineComponent({
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 turnKeys = showStepTurnRail ? tableSteps.map((st) => {
const tIdx = getStepTurnIdx(st);
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`;
};
}) : [];
const formattedPrompts = new Map();
function formattedTurnPrompt(st) {
const raw = getStepPrompt(st);
if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw));
return formattedPrompts.get(raw);
}
const decoratedSteps = tableSteps.map((st, idx) => {
const tKey = turnKeyOf(st);
const tKey = turnKeys[idx];
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
);
const hasUp = hasTurn && turnKeys[idx - 1] === tKey;
const hasDown = hasTurn && turnKeys[idx + 1] === tKey;
return {
st,
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
@@ -188,7 +229,7 @@ export const StepTableWidget = defineComponent({
hasDown,
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
isLatest: hasTurn && getStepIsLatest(st),
prompt: hasTurn ? formatTurnPromptText(getStepPrompt(st)) : '',
prompt: hasTurn ? formattedTurnPrompt(st) : '',
};
});
@@ -205,32 +246,20 @@ export const StepTableWidget = defineComponent({
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 || ''}`;
const badgeSig = showAgentBadge
? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`
: '';
return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
},
createRow: () => {
const tr = h('tr');
const railLineEl = h('span', { className: 'turn-rail-line', hidden: true });
const railDotEl = h('span', { className: 'turn-rail-dot', hidden: true });
const railEl = h(
'span',
{ className: 'turn-rail', 'aria-hidden': 'true', hidden: true },
[railLineEl, railDotEl]
);
const agentBadgeEl = h('span', {
className: 'agent-badge',
hidden: true,
style: 'margin-right: 4px;',
});
return {
el: tr,
refs: {
cellMap: new Map(),
colOrderSig: '',
railEl,
railLineEl,
railDotEl,
agentBadgeEl,
railEl: null,
agentBadgeEl: null,
hoverTd: null,
},
};
@@ -240,17 +269,15 @@ export const StepTableWidget = defineComponent({
if (refs.colOrderSig !== colOrderSig) {
if (refs.hoverTd) {
refs.hoverTd.onmouseenter = null;
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
clearCellHover(refs.hoverTd);
refs.hoverTd = null;
}
for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) {
if (refs.railEl.parentNode === entry.td) {
if (refs.railEl?.parentNode === entry.td) {
entry.td.removeChild(refs.railEl);
}
if (refs.agentBadgeEl.parentNode === entry.td) {
if (refs.agentBadgeEl?.parentNode === entry.td) {
entry.td.removeChild(refs.agentBadgeEl);
}
tr.removeChild(entry.td);
@@ -258,14 +285,19 @@ export const StepTableWidget = defineComponent({
}
}
for (const [i, colKey] of colKeys.entries()) {
if (!refs.cellMap.has(colKey)) {
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
const isNewRow = refs.colOrderSig === '';
for (let i = 0; i < colKeys.length; i++) {
const colKey = colKeys[i];
let cell = refs.cellMap.get(colKey);
if (!cell) {
cell = STEP_COLUMN_REGISTRY[colKey].createCell();
refs.cellMap.set(colKey, cell);
}
const targetTd = refs.cellMap.get(colKey).td;
const currentTd = tr.children[i] || null;
if (currentTd !== targetTd) {
tr.insertBefore(targetTd, currentTd);
if (isNewRow) {
tr.appendChild(cell.td);
} else {
const currentTd = tr.children[i] || null;
if (currentTd !== cell.td) tr.insertBefore(cell.td, currentTd);
}
}
refs.colOrderSig = colOrderSig;
@@ -278,12 +310,22 @@ export const StepTableWidget = defineComponent({
const firstColKey = colKeys[0];
const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null;
const showRowRail = Boolean(hasTurn && firstTd);
if (showRowRail && !refs.railEl) {
refs.railEl = h('span', { className: 'turn-rail', 'aria-hidden': 'true' });
}
if (showAgentBadge && firstTd && !refs.agentBadgeEl) {
refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' });
}
if (firstTd) {
if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) {
if (refs.railEl && (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) {
const afterRail = refs.railEl
? refs.railEl.nextSibling ?? firstTd.children[1] ?? null
: firstTd.firstChild;
if (refs.agentBadgeEl &&
(refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) {
firstTd.insertBefore(refs.agentBadgeEl, afterRail);
}
}
@@ -334,72 +376,29 @@ export const StepTableWidget = defineComponent({
patchAttr(refs.agentBadgeEl, 'title', null);
refs.agentBadgeEl.onclick = null;
}
} else {
} else if (refs.agentBadgeEl) {
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 marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : '';
patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`);
}
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;
}
const hoverTd = showRowRail && prompt ? firstTd : null;
if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd);
refs.hoverTd = hoverTd;
if (hoverTd) {
hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt });
hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null;
hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail;
hoverTd.onmouseleave = hideTurnTip;
}
},
});
lastRenderOptions = renderOptions;
lastRenderedRows = tableSteps;
}
onCleanup(() => {