@agy-daddy/plugin-context 1.0.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -7
- package/agy-plugin.json +59 -14
- package/locales/en.json +4 -1
- package/locales/zh-CN.json +4 -1
- package/package.json +2 -2
- package/settings.schema.json +8 -0
- package/src/attachment-audit.js +9 -1
- package/src/context-analyzer.js +103 -0
- package/src/node.js +201 -43
- package/src/panel-styles.js +38 -0
- package/src/pulse-capsule.js +30 -2
- package/src/renderer.js +244 -13
package/src/renderer.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const {
|
|
4
4
|
formatTokensShort,
|
|
5
|
+
formatReferenceCost,
|
|
5
6
|
formatThresholdLabel,
|
|
6
7
|
resolveThresholdTokens,
|
|
7
8
|
getRingAccentToken
|
|
@@ -61,6 +62,7 @@ function normalizeContextSettings(raw = {}) {
|
|
|
61
62
|
const showSpeed = src.showSpeed !== undefined
|
|
62
63
|
? src.showSpeed !== false
|
|
63
64
|
: src.showSpeedInTopbar !== false;
|
|
65
|
+
const showCost = src.showCost !== false;
|
|
64
66
|
const VALID_COMPACT_POLICIES = new Set(['remind', 'idle_prompt', 'cliff_auto', 'idle_and_cliff']);
|
|
65
67
|
const compactPolicy = VALID_COMPACT_POLICIES.has(src.compactPolicy)
|
|
66
68
|
? src.compactPolicy
|
|
@@ -70,6 +72,7 @@ function normalizeContextSettings(raw = {}) {
|
|
|
70
72
|
return {
|
|
71
73
|
displayLocation,
|
|
72
74
|
showSpeed,
|
|
75
|
+
showCost,
|
|
73
76
|
pollIntervalMs: Number(src.pollIntervalMs) >= 1000 ? Number(src.pollIntervalMs) : 3000,
|
|
74
77
|
warnThreshold,
|
|
75
78
|
cliffThreshold,
|
|
@@ -79,13 +82,19 @@ function normalizeContextSettings(raw = {}) {
|
|
|
79
82
|
};
|
|
80
83
|
}
|
|
81
84
|
|
|
82
|
-
function formatTopbarRingLabel(snapshot, showSpeed = true, liveSpeed = null) {
|
|
85
|
+
function formatTopbarRingLabel(snapshot, showSpeed = true, liveSpeed = null, showCost = true) {
|
|
83
86
|
if (!snapshot || !snapshot.hasSession || snapshot.used === null) {
|
|
84
87
|
return '--';
|
|
85
88
|
}
|
|
86
89
|
const ratio = `${formatTokensShort(snapshot.used)}/${formatTokensShort(snapshot.budget)}`;
|
|
87
90
|
const sessionTotal = snapshot.sessionUsage?.totalTokens ?? snapshot.used;
|
|
88
91
|
const parts = [ratio, formatTokensShort(sessionTotal)];
|
|
92
|
+
if (showCost && snapshot.showCost !== false) {
|
|
93
|
+
const costInfo = formatReferenceCost(snapshot.referenceCost);
|
|
94
|
+
if (costInfo && costInfo.hasCost) {
|
|
95
|
+
parts.push(costInfo.compactText);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
89
98
|
if (showSpeed) {
|
|
90
99
|
if (liveSpeed?.active) {
|
|
91
100
|
parts.push(liveSpeed.tps ? `~${formatSpeedCompact(liveSpeed.tps)}` : '…');
|
|
@@ -136,7 +145,7 @@ function formatAttachmentMeta(attachments) {
|
|
|
136
145
|
return high > 0 ? `附件 ${count} 项 · 约 ${formatTokensShort(high)}` : `附件 ${count} 项`;
|
|
137
146
|
}
|
|
138
147
|
|
|
139
|
-
function renderPanelHtml(snapshot, onRescan, liveSpeed = null) {
|
|
148
|
+
function renderPanelHtml(snapshot, onRescan, liveSpeed = null, opts = {}) {
|
|
140
149
|
if (!snapshot || !snapshot.hasSession) {
|
|
141
150
|
return '暂无活跃 Antigravity 会话,点击刷新以采样。';
|
|
142
151
|
}
|
|
@@ -151,10 +160,20 @@ function renderPanelHtml(snapshot, onRescan, liveSpeed = null) {
|
|
|
151
160
|
`模型: ${snapshot.model || 'Unknown'}${statusStr}`,
|
|
152
161
|
`上下文窗口: ${formatTokensShort(snapshot.used)} / ${formatTokensShort(snapshot.budget)} (${snapshot.percent ?? '--'}%) · 剩余 ${snapshot.remainPercent ?? '--'}%`,
|
|
153
162
|
`单轮缓存: 命中 ${snapshot.cacheHitRate ?? 0}% (${formatTokensShort(snapshot.cachedTokens)} / ${formatTokensShort(snapshot.inputTokens)})`,
|
|
154
|
-
`本对话累计: ${formatTokensShort(sessionTotal)} · 输出 ${formatTokensShort(su.outputTokens ?? snapshot.outputTokens)} · 缓存读 ${formatTokensShort(su.cachedTokens ?? snapshot.cachedTokens)} · ${su.callsCount || 0}
|
|
163
|
+
`本对话累计: ${formatTokensShort(sessionTotal)} · 输出 ${formatTokensShort(su.outputTokens ?? snapshot.outputTokens)} · 缓存读 ${formatTokensShort(su.cachedTokens ?? snapshot.cachedTokens)} · ${su.callsCount || 0} 次`
|
|
164
|
+
];
|
|
165
|
+
if (opts?.showCost !== false && snapshot.showCost !== false) {
|
|
166
|
+
const costInfo = formatReferenceCost(snapshot.referenceCost);
|
|
167
|
+
if (costInfo && costInfo.hasCost) {
|
|
168
|
+
lines.push(`参考费用: ${costInfo.displayText} (${costInfo.currency})`);
|
|
169
|
+
} else if (costInfo && costInfo.unpriced) {
|
|
170
|
+
lines.push('参考费用: -- (当前模型暂无公开单价)');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
lines.push(
|
|
155
174
|
`生成速度: ${speedText} · 纯吐字 ${snapshot.speed?.streamingTps ?? '--'} tok/s · TTFT ${liveSpeed?.active ? (liveSpeed.ttft ?? '--') : (snapshot.speed?.ttft ?? '--')}s`,
|
|
156
175
|
formatAttachmentMeta(snapshot.attachments)
|
|
157
|
-
|
|
176
|
+
);
|
|
158
177
|
const groups = buildSortedGroups(snapshot.groups);
|
|
159
178
|
if (groups.length) {
|
|
160
179
|
lines.push(`上下文构成: ${groups.map((d) => `${d.label} ${formatTokensShort(d.val)}`).join(' · ')}`);
|
|
@@ -214,6 +233,92 @@ async function mount(ctx) {
|
|
|
214
233
|
|
|
215
234
|
const docRefGlobal = globalThis.document;
|
|
216
235
|
const speedTracker = createStreamSpeedTracker();
|
|
236
|
+
let lastObservedCascadeId = null;
|
|
237
|
+
let lastObservedIsNewEmptyChat = false;
|
|
238
|
+
let refreshSeq = 0;
|
|
239
|
+
let lastPublishedLiveKey = '';
|
|
240
|
+
let lastPublishedLiveAt = 0;
|
|
241
|
+
let lastPublishedPhase = '';
|
|
242
|
+
let lastPublishedHasTps = false;
|
|
243
|
+
|
|
244
|
+
function publishLiveState(cascadeId, busy, live, force = false) {
|
|
245
|
+
const phase = live?.phase || (busy ? 'waiting' : 'idle');
|
|
246
|
+
const tps = live?.tps ?? null;
|
|
247
|
+
const ttft = live?.ttft ?? null;
|
|
248
|
+
const estimatedOutputTokens = live?.estimatedOutputTokens ?? 0;
|
|
249
|
+
const key = `${cascadeId || ''}:${busy ? 1 : 0}:${phase}:${tps ?? ''}`;
|
|
250
|
+
const now = Date.now();
|
|
251
|
+
const hasTps = tps !== null;
|
|
252
|
+
const majorTransition = phase !== lastPublishedPhase || (!lastPublishedHasTps && hasTps);
|
|
253
|
+
if (!force && key === lastPublishedLiveKey) return;
|
|
254
|
+
if (!force && !majorTransition && busy && now - lastPublishedLiveAt < 280) return;
|
|
255
|
+
lastPublishedLiveKey = key;
|
|
256
|
+
lastPublishedLiveAt = now;
|
|
257
|
+
lastPublishedPhase = phase;
|
|
258
|
+
lastPublishedHasTps = hasTps;
|
|
259
|
+
try {
|
|
260
|
+
const payload = {
|
|
261
|
+
cascadeId: cascadeId || null,
|
|
262
|
+
busy: Boolean(busy),
|
|
263
|
+
phase,
|
|
264
|
+
tps,
|
|
265
|
+
ttft,
|
|
266
|
+
estimatedOutputTokens,
|
|
267
|
+
updatedAt: now
|
|
268
|
+
};
|
|
269
|
+
Promise.resolve(ctx.state?.set?.('state:context.live@1', payload)).catch(() => {});
|
|
270
|
+
Promise.resolve(ctx.bridge?.post?.('/live-state', payload)).catch(() => {});
|
|
271
|
+
} catch {}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function readDomSessionContext() {
|
|
275
|
+
const cascadeId = ctx.hostDom?.getSessionId?.() || null;
|
|
276
|
+
const busy = Boolean(ctx.hostDom?.isAssistantBusy?.());
|
|
277
|
+
const turnEls = typeof docRefGlobal?.querySelectorAll === 'function'
|
|
278
|
+
? docRefGlobal.querySelectorAll('[data-testid="user-message"], [data-testid="agent-response"]')
|
|
279
|
+
: [];
|
|
280
|
+
const turnCount = turnEls ? turnEls.length : 0;
|
|
281
|
+
const isNewEmptyChat = !cascadeId && !busy && turnCount === 0;
|
|
282
|
+
return { cascadeId, busy, turnCount, isNewEmptyChat };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function buildRendererEmptySnapshot(cascadeId = null) {
|
|
286
|
+
return {
|
|
287
|
+
ok: true,
|
|
288
|
+
hasSession: false,
|
|
289
|
+
cascadeId: cascadeId || null,
|
|
290
|
+
status: 'idle',
|
|
291
|
+
used: null,
|
|
292
|
+
budget: null,
|
|
293
|
+
percent: null,
|
|
294
|
+
remainPercent: null,
|
|
295
|
+
model: null,
|
|
296
|
+
speed: null,
|
|
297
|
+
sessionUsage: {
|
|
298
|
+
totalTokens: 0,
|
|
299
|
+
inputTokens: 0,
|
|
300
|
+
cachedTokens: 0,
|
|
301
|
+
outputTokens: 0,
|
|
302
|
+
thinkingTokens: 0,
|
|
303
|
+
responseTokens: 0,
|
|
304
|
+
callsCount: 0,
|
|
305
|
+
avgTps: null,
|
|
306
|
+
avgStreamingTps: null
|
|
307
|
+
},
|
|
308
|
+
groups: null,
|
|
309
|
+
attachments: { items: [], totals: { count: 0, chars: 0, bytes: 0, low: 0, high: 0 } },
|
|
310
|
+
alerts: [],
|
|
311
|
+
referenceCost: null,
|
|
312
|
+
usageServiceAvailable: null,
|
|
313
|
+
displayLocation: settings.displayLocation,
|
|
314
|
+
showSpeed: settings.showSpeed,
|
|
315
|
+
showCost: settings.showCost,
|
|
316
|
+
compactPolicy: settings.compactPolicy,
|
|
317
|
+
warnThreshold: settings.warnThreshold,
|
|
318
|
+
cliffThreshold: settings.cliffThreshold,
|
|
319
|
+
updatedAt: Date.now()
|
|
320
|
+
};
|
|
321
|
+
}
|
|
217
322
|
|
|
218
323
|
const stopPulseStyles = typeof ctx.styles?.inject === 'function'
|
|
219
324
|
? ctx.styles.inject(PULSE_CAPSULE_CSS, { scope: 'document', id: 'context-pulse-styles' })
|
|
@@ -439,7 +544,7 @@ async function mount(ctx) {
|
|
|
439
544
|
if (!panelNode) return;
|
|
440
545
|
const docRef = panelNode.ownerDocument || globalThis.document;
|
|
441
546
|
if (!docRef?.createElement) {
|
|
442
|
-
panelNode.textContent = renderPanelHtml(snap, null, liveSpeed);
|
|
547
|
+
panelNode.textContent = renderPanelHtml(snap, null, liveSpeed, { showCost: settings.showCost });
|
|
443
548
|
return;
|
|
444
549
|
}
|
|
445
550
|
|
|
@@ -574,6 +679,45 @@ async function mount(ctx) {
|
|
|
574
679
|
sessSub.appendChild(buildEl(docRef, 'span', '', `思考 ${formatTokensShort(su.thinkingTokens || 0)} · 回答 ${formatTokensShort(su.responseTokens ?? su.outputTokens ?? 0)}`));
|
|
575
680
|
sessSub.appendChild(buildEl(docRef, 'span', '', '独立于顶栏用量'));
|
|
576
681
|
sessSec.appendChild(sessSub);
|
|
682
|
+
|
|
683
|
+
if (settings.showCost && snap.showCost !== false) {
|
|
684
|
+
const costInfo = formatReferenceCost(snap.referenceCost);
|
|
685
|
+
if (costInfo && costInfo.hasCost) {
|
|
686
|
+
const costRow = buildEl(docRef, 'div', 'ag-ctx-cost-row');
|
|
687
|
+
costRow.setAttribute('data-ctx-cost', '1');
|
|
688
|
+
const labelWrap = buildEl(docRef, 'span', 'ag-ctx-cost-label');
|
|
689
|
+
labelWrap.appendChild(buildEl(docRef, 'span', '', '参考费用'));
|
|
690
|
+
const noteText = costInfo.partial
|
|
691
|
+
? `API 折算 · 含 ${costInfo.unpricedCount} 次未知模型`
|
|
692
|
+
: `API 折算 · ${costInfo.currency}`;
|
|
693
|
+
labelWrap.appendChild(buildEl(docRef, 'span', 'ag-ctx-cost-note', noteText));
|
|
694
|
+
costRow.appendChild(labelWrap);
|
|
695
|
+
costRow.appendChild(buildEl(docRef, 'span', 'ag-ctx-cost-val', costInfo.displayText));
|
|
696
|
+
sessSec.appendChild(costRow);
|
|
697
|
+
|
|
698
|
+
if (costInfo.modelBreakdown.length > 1) {
|
|
699
|
+
const bdLine = buildEl(docRef, 'div', 'ag-ctx-subline');
|
|
700
|
+
bdLine.appendChild(buildEl(docRef, 'span', '', costInfo.modelBreakdown.map((m) => `${m.model} ${m.text}`).join(' · ')));
|
|
701
|
+
sessSec.appendChild(bdLine);
|
|
702
|
+
}
|
|
703
|
+
} else if (costInfo && costInfo.unpriced) {
|
|
704
|
+
const costRow = buildEl(docRef, 'div', 'ag-ctx-cost-row');
|
|
705
|
+
costRow.setAttribute('data-ctx-cost', 'unpriced');
|
|
706
|
+
const labelWrap = buildEl(docRef, 'span', 'ag-ctx-cost-label');
|
|
707
|
+
labelWrap.appendChild(buildEl(docRef, 'span', '', '参考费用'));
|
|
708
|
+
labelWrap.appendChild(buildEl(docRef, 'span', 'ag-ctx-cost-note', '当前模型暂无公开单价'));
|
|
709
|
+
costRow.appendChild(labelWrap);
|
|
710
|
+
const valEl = buildEl(docRef, 'span', 'ag-ctx-cost-val', '--');
|
|
711
|
+
valEl.setAttribute('data-muted', 'true');
|
|
712
|
+
costRow.appendChild(valEl);
|
|
713
|
+
sessSec.appendChild(costRow);
|
|
714
|
+
} else if (snap.usageServiceAvailable === false) {
|
|
715
|
+
const hintLine = buildEl(docRef, 'div', 'ag-ctx-subline');
|
|
716
|
+
hintLine.setAttribute('data-ctx-cost', 'unavailable');
|
|
717
|
+
hintLine.appendChild(buildEl(docRef, 'span', '', '未启用「用量」插件,已隐藏参考费用'));
|
|
718
|
+
sessSec.appendChild(hintLine);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
577
721
|
panelNode.appendChild(sessSec);
|
|
578
722
|
|
|
579
723
|
// 4. 生成速度
|
|
@@ -657,6 +801,7 @@ async function mount(ctx) {
|
|
|
657
801
|
for (const tip of [
|
|
658
802
|
'上下文窗口:单次请求的记忆容量(外环=占用、内环=缓存命中),刻度线为预警/断崖阈值,建议超 240K 时执行 /compact。',
|
|
659
803
|
'本对话累计:仅汇总当前对话全轮次模型消耗,与顶栏「用量」的跨会话历史总账相互独立。',
|
|
804
|
+
'参考费用:联动「用量」插件按当前币种与模型 API 公开费率估算本对话花费(未启用用量插件或关闭开关时自动隐藏)。',
|
|
660
805
|
'生成速度:总速率含首字等待 (TTFT),纯吐字仅计流式输出阶段;生成中带 ~ 为实时估算,完成后切回实测值。'
|
|
661
806
|
]) {
|
|
662
807
|
helpList.appendChild(buildEl(docRef, 'li', '', tip));
|
|
@@ -673,13 +818,14 @@ async function mount(ctx) {
|
|
|
673
818
|
isCliff328k: snap?.cacheCliffRisk === 'critical',
|
|
674
819
|
isWarn240k: snap?.cacheCliffRisk === 'warn'
|
|
675
820
|
});
|
|
676
|
-
const labelText = formatTopbarRingLabel(snap, settings.showSpeed, liveSpeed);
|
|
821
|
+
const labelText = formatTopbarRingLabel(snap, settings.showSpeed, liveSpeed, settings.showCost);
|
|
677
822
|
const svgHtml = buildTopbarRingSvg(snap?.percent || 0, color);
|
|
678
823
|
const segments = buildCapsuleSegments(snap, {
|
|
679
824
|
showSpeed: settings.showSpeed,
|
|
825
|
+
showCost: settings.showCost,
|
|
680
826
|
liveSpeed
|
|
681
827
|
});
|
|
682
|
-
const tooltip = buildCapsuleTooltip(snap, { liveSpeed });
|
|
828
|
+
const tooltip = buildCapsuleTooltip(snap, { showCost: settings.showCost, liveSpeed });
|
|
683
829
|
const tone = (snap?.cacheCliffRisk === 'critical' || snap?.cacheDropDetected)
|
|
684
830
|
? 'danger'
|
|
685
831
|
: (snap?.cacheCliffRisk === 'warn' ? 'warn' : '');
|
|
@@ -754,6 +900,7 @@ async function mount(ctx) {
|
|
|
754
900
|
anchors: ctx.anchors,
|
|
755
901
|
enabled: settings.displayLocation === 'composer',
|
|
756
902
|
showSpeed: settings.showSpeed,
|
|
903
|
+
showCost: settings.showCost,
|
|
757
904
|
onClick(btnEl) {
|
|
758
905
|
const anchorRect = extractAnchorRect(btnEl);
|
|
759
906
|
popoverHandle?.toggle(undefined, { anchorRect, placement: 'top' });
|
|
@@ -773,8 +920,8 @@ async function mount(ctx) {
|
|
|
773
920
|
order: 10,
|
|
774
921
|
label: '--',
|
|
775
922
|
iconSvg: buildTopbarRingSvg(0),
|
|
776
|
-
segments: buildCapsuleSegments(latestSnapshot, { showSpeed: settings.showSpeed, liveSpeed: latestLiveSpeed }),
|
|
777
|
-
title: buildCapsuleTooltip(latestSnapshot, { liveSpeed: latestLiveSpeed }),
|
|
923
|
+
segments: buildCapsuleSegments(latestSnapshot, { showSpeed: settings.showSpeed, showCost: settings.showCost, liveSpeed: latestLiveSpeed }),
|
|
924
|
+
title: buildCapsuleTooltip(latestSnapshot, { showCost: settings.showCost, liveSpeed: latestLiveSpeed }),
|
|
778
925
|
render(node) {
|
|
779
926
|
unitNode = node;
|
|
780
927
|
},
|
|
@@ -794,6 +941,7 @@ async function mount(ctx) {
|
|
|
794
941
|
pulseController.setEnabled(true);
|
|
795
942
|
pulseController.update(latestSnapshot, {
|
|
796
943
|
showSpeed: settings.showSpeed,
|
|
944
|
+
showCost: settings.showCost,
|
|
797
945
|
liveSpeed: latestLiveSpeed,
|
|
798
946
|
showQuickCompact
|
|
799
947
|
});
|
|
@@ -806,6 +954,7 @@ async function mount(ctx) {
|
|
|
806
954
|
} else {
|
|
807
955
|
pulseController.update(latestSnapshot, {
|
|
808
956
|
showSpeed: settings.showSpeed,
|
|
957
|
+
showCost: settings.showCost,
|
|
809
958
|
liveSpeed: latestLiveSpeed,
|
|
810
959
|
showQuickCompact
|
|
811
960
|
});
|
|
@@ -831,7 +980,42 @@ async function mount(ctx) {
|
|
|
831
980
|
return String(list?.textContent || '');
|
|
832
981
|
}
|
|
833
982
|
|
|
983
|
+
function resetToEmptySessionState(cascadeId = null) {
|
|
984
|
+
speedTracker.reset();
|
|
985
|
+
latestLiveSpeed = null;
|
|
986
|
+
pendingAutoCompact = null;
|
|
987
|
+
showQuickCompact = false;
|
|
988
|
+
latestSnapshot = buildRendererEmptySnapshot(cascadeId);
|
|
989
|
+
evaluateCompactState(latestSnapshot, { allowAutoTrigger: false });
|
|
990
|
+
syncActiveDisplays();
|
|
991
|
+
try {
|
|
992
|
+
void ctx.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
993
|
+
} catch {}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
function syncSessionTransition() {
|
|
997
|
+
const domCtx = readDomSessionContext();
|
|
998
|
+
const cascadeChanged = domCtx.cascadeId !== lastObservedCascadeId;
|
|
999
|
+
const enteredNewEmpty = domCtx.isNewEmptyChat && !lastObservedIsNewEmptyChat;
|
|
1000
|
+
const leftNewEmpty = !domCtx.isNewEmptyChat && lastObservedIsNewEmptyChat;
|
|
1001
|
+
if (!cascadeChanged && !enteredNewEmpty && !leftNewEmpty) {
|
|
1002
|
+
return domCtx;
|
|
1003
|
+
}
|
|
1004
|
+
lastObservedCascadeId = domCtx.cascadeId;
|
|
1005
|
+
lastObservedIsNewEmptyChat = domCtx.isNewEmptyChat;
|
|
1006
|
+
|
|
1007
|
+
if (cascadeChanged || enteredNewEmpty) {
|
|
1008
|
+
refreshSeq += 1;
|
|
1009
|
+
resetToEmptySessionState(domCtx.cascadeId);
|
|
1010
|
+
void refresh(false);
|
|
1011
|
+
} else if (leftNewEmpty) {
|
|
1012
|
+
void refresh(true);
|
|
1013
|
+
}
|
|
1014
|
+
return domCtx;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
834
1017
|
function sampleLiveStreaming() {
|
|
1018
|
+
const domCtx = syncSessionTransition();
|
|
835
1019
|
const busy = Boolean(ctx.hostDom?.isAssistantBusy?.());
|
|
836
1020
|
const text = busy ? getLiveAssistantText() : '';
|
|
837
1021
|
const { live, completed } = speedTracker.sample({ busy, text });
|
|
@@ -842,6 +1026,7 @@ async function mount(ctx) {
|
|
|
842
1026
|
? `${live.phase}:${live.tps}:${live.estimatedOutputTokens}`
|
|
843
1027
|
: 'idle';
|
|
844
1028
|
latestLiveSpeed = live;
|
|
1029
|
+
publishLiveState(domCtx?.cascadeId || null, busy, live, completed || !busy);
|
|
845
1030
|
|
|
846
1031
|
const prevQuick = showQuickCompact;
|
|
847
1032
|
evaluateCompactState(latestSnapshot);
|
|
@@ -854,10 +1039,25 @@ async function mount(ctx) {
|
|
|
854
1039
|
}
|
|
855
1040
|
|
|
856
1041
|
async function refresh(force = false) {
|
|
1042
|
+
const seq = ++refreshSeq;
|
|
857
1043
|
try {
|
|
858
1044
|
const endpoint = force ? '/rescan' : '/snapshot';
|
|
859
|
-
const
|
|
860
|
-
|
|
1045
|
+
const domCtx = readDomSessionContext();
|
|
1046
|
+
lastObservedCascadeId = domCtx.cascadeId;
|
|
1047
|
+
lastObservedIsNewEmptyChat = domCtx.isNewEmptyChat;
|
|
1048
|
+
const snap = await ctx.bridge.post(endpoint, {
|
|
1049
|
+
cascadeId: domCtx.cascadeId,
|
|
1050
|
+
isNewChat: domCtx.isNewEmptyChat,
|
|
1051
|
+
force
|
|
1052
|
+
});
|
|
1053
|
+
const afterCtx = readDomSessionContext();
|
|
1054
|
+
if (
|
|
1055
|
+
seq !== refreshSeq
|
|
1056
|
+
|| afterCtx.cascadeId !== domCtx.cascadeId
|
|
1057
|
+
|| (afterCtx.isNewEmptyChat && !domCtx.isNewEmptyChat)
|
|
1058
|
+
) {
|
|
1059
|
+
return null;
|
|
1060
|
+
}
|
|
861
1061
|
if (snap && typeof snap === 'object') {
|
|
862
1062
|
latestSnapshot = snap;
|
|
863
1063
|
evaluateCompactState(snap);
|
|
@@ -904,6 +1104,7 @@ async function mount(ctx) {
|
|
|
904
1104
|
? ctx.settings.onChange((nextValues, changedKeys) => {
|
|
905
1105
|
const prevPoll = settings.pollIntervalMs;
|
|
906
1106
|
const prevLocation = settings.displayLocation;
|
|
1107
|
+
const prevShowCost = settings.showCost;
|
|
907
1108
|
settings = normalizeContextSettings(nextValues);
|
|
908
1109
|
const keys = Array.isArray(changedKeys) ? changedKeys : [];
|
|
909
1110
|
if (settings.displayLocation !== prevLocation || keys.includes('displayLocation') || keys.includes('showPulseCapsule')) {
|
|
@@ -916,14 +1117,22 @@ async function mount(ctx) {
|
|
|
916
1117
|
const used = Number(latestSnapshot.used || 0);
|
|
917
1118
|
latestSnapshot = {
|
|
918
1119
|
...latestSnapshot,
|
|
1120
|
+
showCost: settings.showCost,
|
|
919
1121
|
warnThreshold: settings.warnThreshold,
|
|
920
1122
|
cliffThreshold: settings.cliffThreshold,
|
|
921
1123
|
warnThresholdTokens: warnTokens,
|
|
922
1124
|
cliffThresholdTokens: cliffTokens,
|
|
923
1125
|
cacheCliffRisk: used >= cliffTokens ? 'critical' : (used >= warnTokens ? 'warn' : 'none')
|
|
924
1126
|
};
|
|
925
|
-
if (
|
|
926
|
-
|
|
1127
|
+
if (
|
|
1128
|
+
keys.length === 0
|
|
1129
|
+
|| keys.includes('warnThreshold')
|
|
1130
|
+
|| keys.includes('cliffThreshold')
|
|
1131
|
+
|| keys.includes('warnThresholdTokens')
|
|
1132
|
+
|| keys.includes('cliffThresholdTokens')
|
|
1133
|
+
|| (settings.showCost && !prevShowCost)
|
|
1134
|
+
) {
|
|
1135
|
+
void refresh(settings.showCost && !prevShowCost);
|
|
927
1136
|
}
|
|
928
1137
|
evaluateCompactState(latestSnapshot);
|
|
929
1138
|
}
|
|
@@ -934,6 +1143,20 @@ async function mount(ctx) {
|
|
|
934
1143
|
})
|
|
935
1144
|
: () => {};
|
|
936
1145
|
|
|
1146
|
+
let lastUiUsageKey = '';
|
|
1147
|
+
const stopUsageStateSub = typeof ctx.state?.subscribe === 'function'
|
|
1148
|
+
? await Promise.resolve(ctx.state.subscribe('state:usage.summary@1', (rawVal) => {
|
|
1149
|
+
const val = (rawVal && typeof rawVal === 'object' && 'value' in rawVal) ? rawVal.value : rawVal;
|
|
1150
|
+
if (!val || typeof val !== 'object') return;
|
|
1151
|
+
const nextKey = `${val.currency || ''}:${val.exchangeRate || ''}:${val.currencySymbol || ''}`;
|
|
1152
|
+
if (nextKey === lastUiUsageKey && latestSnapshot?.referenceCost) return;
|
|
1153
|
+
lastUiUsageKey = nextKey;
|
|
1154
|
+
if (settings.showCost && latestSnapshot?.hasSession) {
|
|
1155
|
+
void refresh(false);
|
|
1156
|
+
}
|
|
1157
|
+
}))
|
|
1158
|
+
: () => {};
|
|
1159
|
+
|
|
937
1160
|
const stopUiSvc = ctx.services.provide('context-ui', {
|
|
938
1161
|
getSnapshot: () => latestSnapshot,
|
|
939
1162
|
rescan: () => refresh(true),
|
|
@@ -955,6 +1178,12 @@ async function mount(ctx) {
|
|
|
955
1178
|
sampleLiveStreaming: () => sampleLiveStreaming()
|
|
956
1179
|
});
|
|
957
1180
|
|
|
1181
|
+
const initDomCtx = readDomSessionContext();
|
|
1182
|
+
lastObservedCascadeId = initDomCtx.cascadeId;
|
|
1183
|
+
lastObservedIsNewEmptyChat = initDomCtx.isNewEmptyChat;
|
|
1184
|
+
if (initDomCtx.isNewEmptyChat) {
|
|
1185
|
+
resetToEmptySessionState(null);
|
|
1186
|
+
}
|
|
958
1187
|
syncDisplayLocation();
|
|
959
1188
|
await refresh(false);
|
|
960
1189
|
startPollLoop();
|
|
@@ -969,10 +1198,12 @@ async function mount(ctx) {
|
|
|
969
1198
|
trackedTimers.clear();
|
|
970
1199
|
},
|
|
971
1200
|
stopSettingsSub,
|
|
1201
|
+
stopUsageStateSub,
|
|
972
1202
|
stopUiSvc,
|
|
973
1203
|
() => { if (typeof stopUnit === 'function') stopUnit(); stopUnit = null; unitNode = null; },
|
|
974
1204
|
() => popoverHandle?.dispose(),
|
|
975
1205
|
() => pulseController.dispose(),
|
|
1206
|
+
() => { try { Promise.resolve(ctx.state?.set?.('state:context.live@1', null)).catch(() => {}); } catch {} },
|
|
976
1207
|
stopPanelStyles,
|
|
977
1208
|
stopPulseStyles
|
|
978
1209
|
);
|