@agy-daddy/plugin-context 1.1.0 → 1.1.4
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 +1 -1
- package/settings.schema.json +8 -0
- 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/README.md
CHANGED
|
@@ -1,14 +1,100 @@
|
|
|
1
1
|
# @agy-daddy/plugin-context
|
|
2
2
|
|
|
3
|
-
Agy-Daddy Layer
|
|
3
|
+
Agy-Daddy 官方 Layer 2 上下文监测插件:上下文环、审计面板、附件检查器与输入框实时脉冲胶囊。
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
- 可选消费:`usage.estimateCallsCost()`(未安装 `usage` 时安全降级)
|
|
5
|
+
- **npm 包名**:`@agy-daddy/plugin-context`
|
|
6
|
+
- **Layer 层级**:Layer 2(会话洞察与监控层)
|
|
7
|
+
- **信任等级**:官方 `T0`(声明 `dom:read`、`dom:write`、`rpc:read`、`fs:brain-read`、`bridge:route`、`native:install` 权限)
|
|
8
|
+
- **适用场景**:实时监测对话 Token 上下文大小、预警 240K/328K 提示缓存断崖,以及输入框生成速度与附件审计。
|
|
10
9
|
|
|
11
|
-
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 核心功能与安全默认值
|
|
13
|
+
|
|
14
|
+
- **实时上下文环与速率脉冲**:实时计算当前会话的总 Token 占用与生成速率(~tok/s),支持在输入框下方或顶栏展示动态环形指示器。
|
|
15
|
+
- **缓存断崖梯级预警**:支持 240K 预警与 328K 断崖阈值,自动标记超限风险,预防上下文溢出。
|
|
16
|
+
- **附件审计面板**:就近弹出详情面板,清晰呈现历史轮次、Prompt Cache 命中率及附件大小。
|
|
17
|
+
- **安全默认值**:
|
|
18
|
+
- `compactPolicy: "remind"`:默认仅提醒,绝不在用户输入中或模型生成时强行中断会话;
|
|
19
|
+
- `autoCompactOnCacheDrop: false`:默认关闭丢缓存强制压缩,必须由用户自主配置。
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 安装与启用方式
|
|
24
|
+
|
|
25
|
+
### 1. 随官方全量安装
|
|
26
|
+
```sh
|
|
27
|
+
agy-daddy plugin install --official
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 2. 单独安装
|
|
31
|
+
```sh
|
|
32
|
+
agy-daddy plugin install npm:@agy-daddy/plugin-context
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### 3. 宿主设置中心与顶栏/输入框交互
|
|
36
|
+
安装后自动激活(`onStartup`)。默认在输入框下方挂载上下文脉冲胶囊,或在顶栏(order: 10)挂载环形图元。点击就近弹出审计面板,亦可在设置中心「上下文与实时速度」进行策略定制。
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 配置项说明表
|
|
41
|
+
|
|
42
|
+
对照 `settings.schema.json`:
|
|
43
|
+
|
|
44
|
+
| Key | 类型 | 默认值 | 说明 |
|
|
45
|
+
|---|---|---|---|
|
|
46
|
+
| `displayLocation` | `enum` | `"composer"` | 胶囊显示位置:二选一:`composer`(仅在输入框下方)或 `topbar`(仅在顶栏显示实时胶囊),点击就近弹出详情面板 |
|
|
47
|
+
| `showSpeed` | `boolean` | `true` | 显示生成速度:在胶囊中实时显示流式估算速率 (~tok/s) 及完成后的精确速率 |
|
|
48
|
+
| `showCost` | `boolean` | `true` | 显示会话参考成本:在胶囊与详情面板中展示当前会话预估 API 参考费用(需启用用量插件;未启用时自动隐藏) |
|
|
49
|
+
| `pollIntervalMs` | `number` | `3000` | 轮询采样间隔:定期读取当前会话记录并重算 Token 构成的时间间隔(毫秒) |
|
|
50
|
+
| `warnThreshold` | `string` | `"240K"` | 预警阈值:支持绝对值(如 240K / 240000)或窗口百分比(如 50%);达到后胶囊变橙提醒 |
|
|
51
|
+
| `cliffThreshold` | `string` | `"328K"` | 断崖阈值:支持绝对值(如 328K / 328000)或窗口百分比(如 70%);达到后标记高风险断崖 |
|
|
52
|
+
| `compactPolicy` | `enum` | `"remind"` | 压缩触发策略:可选 `remind`(仅提醒)、`suggest`(空闲显示一键压缩)、`auto`(达断崖等本步结束自动发 /compact)、`both`(A+B 同时开启) |
|
|
53
|
+
| `autoCompactOnCacheDrop` | `boolean` | `false` | 丢缓存强行触发压缩:开启后若检测到缓存断崖且处于空闲状态,强制触发压缩提示 |
|
|
54
|
+
|
|
55
|
+
### 声明式操作(Actions)
|
|
56
|
+
- **立即重新扫描会话 (`rescan`)**:触发命令 `context.rescan`。
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 提供的服务 / 事件 / 命令 / 扩展位
|
|
61
|
+
|
|
62
|
+
严格依据 `agy-plugin.json` 声明:
|
|
63
|
+
|
|
64
|
+
- **Permissions**:`dom:read`、`dom:write`、`rpc:read`、`fs:brain-read`、`bridge:route`、`native:install`
|
|
65
|
+
- **Requires Anchors**:
|
|
66
|
+
- `topbar.rightCluster`:顶栏右侧集群锚点(用于挂载顶栏上下文环)
|
|
67
|
+
- `composer.root`:输入框根容器锚点(用于挂载输入框脉冲胶囊)
|
|
68
|
+
- **Services (provides)**:
|
|
69
|
+
- `context`(版本 `1.0.0`,realm: `node`)
|
|
70
|
+
- `context-ui`(版本 `1.0.0`,realm: `page-isolated`)
|
|
71
|
+
- **Consumes Services**:
|
|
72
|
+
- `usage`(版本 `^1.0.0`,optional: `true`)
|
|
73
|
+
- **Events (provides)**:
|
|
74
|
+
- `telemetry:generator-calls@1`:生成器调用遥测事件
|
|
75
|
+
- `context:auto-compact-triggered@1`:自动压缩触发事件
|
|
76
|
+
- **States (provides)**:
|
|
77
|
+
- `state:context.snapshot@1`:上下文快照状态
|
|
78
|
+
- **Commands (contributes)**:
|
|
79
|
+
- `context.rescan`:重新扫描会话
|
|
80
|
+
- **Topbar Units & Popovers (contributes)**:
|
|
81
|
+
- Topbar Unit: `ring`(order: `10`)
|
|
82
|
+
- Topbar Popover: `context-panel`(anchorId: `ring`)
|
|
83
|
+
- **Remote Panels (contributes["remote.panels"])**:
|
|
84
|
+
- `context`(绑定服务 `context`,为移动端 PWA 远程面板提供上下文快照)
|
|
85
|
+
- **Native Extension (contributes.native)**:
|
|
86
|
+
- MCP 服务器配置:`./native/mcp.json`(向宿主注入上下文治理 MCP 工具)
|
|
87
|
+
- Skills 技能目录:`./native/skills`(注入 context-governance 技能包)
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 使用示例与本地测试
|
|
92
|
+
|
|
93
|
+
### 使用示例
|
|
94
|
+
在长会话编码过程中,输入框下方的实时胶囊会动态变色(绿色正常、橙色预警、红色危险)并展示生成速度。当上下文接近 240K 时点击胶囊,审计面板会列出附件占比及各轮次 Token 消耗,方便针对性精简。
|
|
95
|
+
|
|
96
|
+
### 本地测试
|
|
97
|
+
在插件目录下执行自动化单元测试:
|
|
12
98
|
```sh
|
|
13
99
|
npm test
|
|
14
100
|
```
|
package/agy-plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"id": "agy-daddy.context",
|
|
4
4
|
"publisher": "agy-daddy",
|
|
5
|
-
"version": "1.1.
|
|
5
|
+
"version": "1.1.4",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"displayName": {
|
|
8
8
|
"zh-CN": "上下文与实时速度",
|
|
@@ -19,20 +19,40 @@
|
|
|
19
19
|
"main": "./src/node.js",
|
|
20
20
|
"renderer": "./src/renderer.js",
|
|
21
21
|
"world": "isolated",
|
|
22
|
-
"activationEvents": [
|
|
22
|
+
"activationEvents": [
|
|
23
|
+
"onStartup"
|
|
24
|
+
],
|
|
23
25
|
"requires": {
|
|
24
|
-
"anchors": [
|
|
26
|
+
"anchors": [
|
|
27
|
+
"topbar.rightCluster",
|
|
28
|
+
"composer.root"
|
|
29
|
+
]
|
|
25
30
|
},
|
|
26
31
|
"provides": {
|
|
27
32
|
"services": {
|
|
28
|
-
"context": {
|
|
29
|
-
|
|
33
|
+
"context": {
|
|
34
|
+
"version": "1.0.0",
|
|
35
|
+
"realm": "node"
|
|
36
|
+
},
|
|
37
|
+
"context-ui": {
|
|
38
|
+
"version": "1.0.0",
|
|
39
|
+
"realm": "page-isolated"
|
|
40
|
+
}
|
|
30
41
|
},
|
|
31
|
-
"events": [
|
|
32
|
-
|
|
42
|
+
"events": [
|
|
43
|
+
"telemetry:generator-calls@1",
|
|
44
|
+
"context:auto-compact-triggered@1"
|
|
45
|
+
],
|
|
46
|
+
"states": [
|
|
47
|
+
"state:context.snapshot@1",
|
|
48
|
+
"state:context.live@1"
|
|
49
|
+
]
|
|
33
50
|
},
|
|
34
51
|
"consumes": {
|
|
35
|
-
"usage": {
|
|
52
|
+
"usage": {
|
|
53
|
+
"version": "^1.0.0",
|
|
54
|
+
"optional": true
|
|
55
|
+
}
|
|
36
56
|
},
|
|
37
57
|
"permissions": [
|
|
38
58
|
"dom:read",
|
|
@@ -43,16 +63,41 @@
|
|
|
43
63
|
"native:install"
|
|
44
64
|
],
|
|
45
65
|
"contributes": {
|
|
46
|
-
"topbar.units": [
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
66
|
+
"topbar.units": [
|
|
67
|
+
{
|
|
68
|
+
"id": "ring",
|
|
69
|
+
"order": 10
|
|
70
|
+
}
|
|
71
|
+
],
|
|
72
|
+
"topbar.popovers": [
|
|
73
|
+
{
|
|
74
|
+
"id": "context-panel",
|
|
75
|
+
"anchorId": "ring"
|
|
76
|
+
}
|
|
77
|
+
],
|
|
78
|
+
"settings": {
|
|
79
|
+
"schema": "./settings.schema.json"
|
|
80
|
+
},
|
|
81
|
+
"remote.panels": [
|
|
82
|
+
{
|
|
83
|
+
"id": "context",
|
|
84
|
+
"service": "context"
|
|
85
|
+
}
|
|
86
|
+
],
|
|
50
87
|
"commands": [
|
|
51
|
-
{
|
|
88
|
+
{
|
|
89
|
+
"id": "context.rescan",
|
|
90
|
+
"title": {
|
|
91
|
+
"zh-CN": "重新扫描会话",
|
|
92
|
+
"en": "Rescan session"
|
|
93
|
+
}
|
|
94
|
+
}
|
|
52
95
|
],
|
|
53
96
|
"native": {
|
|
54
97
|
"mcp": "./native/mcp.json",
|
|
55
|
-
"skills": [
|
|
98
|
+
"skills": [
|
|
99
|
+
"./native/skills"
|
|
100
|
+
]
|
|
56
101
|
},
|
|
57
102
|
"locales": "./locales"
|
|
58
103
|
}
|
package/locales/en.json
CHANGED
|
@@ -6,5 +6,8 @@
|
|
|
6
6
|
"alert.warn240k": "Consider compacting (>240K cache degradation risk)",
|
|
7
7
|
"alert.cliff328k": "High cliff zone (>=328K cache miss risk)",
|
|
8
8
|
"alert.cacheDrop": "Context cache drop detected",
|
|
9
|
-
"alert.compressed": "Auto-compaction detected"
|
|
9
|
+
"alert.compressed": "Auto-compaction detected",
|
|
10
|
+
"cost.label": "Reference cost",
|
|
11
|
+
"cost.unavailable": "Enable Usage plugin to view session reference cost",
|
|
12
|
+
"cost.unpriced": "Pricing unavailable for current model"
|
|
10
13
|
}
|
package/locales/zh-CN.json
CHANGED
|
@@ -6,5 +6,8 @@
|
|
|
6
6
|
"alert.warn240k": "建议压缩上下文(>240K 缓存效率下降风险)",
|
|
7
7
|
"alert.cliff328k": "高风险断崖区(>=328K 易丢缓存)",
|
|
8
8
|
"alert.cacheDrop": "检测到上下文缓存失效",
|
|
9
|
-
"alert.compressed": "已触发自动压缩"
|
|
9
|
+
"alert.compressed": "已触发自动压缩",
|
|
10
|
+
"cost.label": "参考费用",
|
|
11
|
+
"cost.unavailable": "未启用「用量」插件,已隐藏参考费用",
|
|
12
|
+
"cost.unpriced": "当前模型暂无公开单价"
|
|
10
13
|
}
|
package/package.json
CHANGED
package/settings.schema.json
CHANGED
|
@@ -21,6 +21,14 @@
|
|
|
21
21
|
"label": { "zh-CN": "显示生成速度", "en": "Show generation speed" },
|
|
22
22
|
"description": { "zh-CN": "在胶囊中实时显示流式估算速率 (~tok/s) 及完成后的精确速率", "en": "Show live estimated streaming rate (~tok/s) and final exact rate in the capsule" }
|
|
23
23
|
},
|
|
24
|
+
{
|
|
25
|
+
"key": "showCost",
|
|
26
|
+
"type": "boolean",
|
|
27
|
+
"default": true,
|
|
28
|
+
"group": { "zh-CN": "显示位置与采样", "en": "Display & Sampling" },
|
|
29
|
+
"label": { "zh-CN": "显示会话参考成本", "en": "Show session reference cost" },
|
|
30
|
+
"description": { "zh-CN": "在胶囊与详情面板中展示当前会话预估 API 参考费用(需启用用量插件;未启用时自动隐藏)", "en": "Display estimated API reference cost for the current session in the capsule and panel (requires Usage plugin; auto-hidden when unavailable)" }
|
|
31
|
+
},
|
|
24
32
|
{
|
|
25
33
|
"key": "pollIntervalMs",
|
|
26
34
|
"type": "number",
|
package/src/context-analyzer.js
CHANGED
|
@@ -998,6 +998,106 @@ function summarizeSessionGeneratorCalls(gmRows, options = {}) {
|
|
|
998
998
|
};
|
|
999
999
|
}
|
|
1000
1000
|
|
|
1001
|
+
function collectSessionGeneratorCalls(gmRows, options = {}) {
|
|
1002
|
+
const rows = Array.isArray(gmRows) ? gmRows : [];
|
|
1003
|
+
const cascadeId = options.cascadeId || null;
|
|
1004
|
+
const source = options.source || 'desktop';
|
|
1005
|
+
const deduped = [];
|
|
1006
|
+
const byCallId = new Map();
|
|
1007
|
+
|
|
1008
|
+
for (let i = 0; i < rows.length; i++) {
|
|
1009
|
+
const row = rows[i];
|
|
1010
|
+
if (!row || typeof row !== 'object') continue;
|
|
1011
|
+
const cm = row.chatModel || {};
|
|
1012
|
+
const modelRaw = String(cm.model || cm.modelOrAlias?.model || cm.responseModel || cm.modelDisplayName || row.model || row.modelId || '').trim();
|
|
1013
|
+
if (isShadowOrImageModel(modelRaw)) continue;
|
|
1014
|
+
|
|
1015
|
+
const parsed = parseGeneratorCall(row, cascadeId, source, i, options);
|
|
1016
|
+
if (!parsed || parsed.totalTokens <= 0) continue;
|
|
1017
|
+
|
|
1018
|
+
if (byCallId.has(parsed.callId)) {
|
|
1019
|
+
deduped[byCallId.get(parsed.callId)] = parsed;
|
|
1020
|
+
} else {
|
|
1021
|
+
byCallId.set(parsed.callId, deduped.length);
|
|
1022
|
+
deduped.push(parsed);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
return deduped;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function formatCurrencyValue(amount, symbol = '$') {
|
|
1029
|
+
const safe = Math.max(0, Number(amount) || 0);
|
|
1030
|
+
if (safe === 0) return `${symbol}0.00`;
|
|
1031
|
+
if (safe >= 0.01) return `${symbol}${safe.toFixed(2)}`;
|
|
1032
|
+
if (safe < 0.0001) return `<${symbol}0.0001`;
|
|
1033
|
+
return `${symbol}${safe.toFixed(4).replace(/0+$/, '')}`;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function formatReferenceCost(referenceCost) {
|
|
1037
|
+
if (!referenceCost || typeof referenceCost !== 'object') return null;
|
|
1038
|
+
|
|
1039
|
+
const callsCount = Math.max(0, Number(referenceCost.callsCount || 0) || 0);
|
|
1040
|
+
const hasPricedCount = referenceCost.pricedCount !== undefined && referenceCost.pricedCount !== null;
|
|
1041
|
+
const pricedCount = hasPricedCount ? Math.max(0, Number(referenceCost.pricedCount) || 0) : null;
|
|
1042
|
+
const unpricedCount = Math.max(0, Number(referenceCost.unpricedCount || 0) || 0);
|
|
1043
|
+
|
|
1044
|
+
const rawCurrency = String(referenceCost.currency || 'USD').trim().toUpperCase();
|
|
1045
|
+
const currency = rawCurrency || 'USD';
|
|
1046
|
+
const symbol = referenceCost.currencySymbol || (currency === 'CNY' ? '¥' : '$');
|
|
1047
|
+
const rate = Number(referenceCost.exchangeRate) > 0
|
|
1048
|
+
? Number(referenceCost.exchangeRate)
|
|
1049
|
+
: (currency === 'CNY' ? 7.25 : 1);
|
|
1050
|
+
|
|
1051
|
+
const hasDisplay = referenceCost.totalDisplayCost !== undefined
|
|
1052
|
+
&& referenceCost.totalDisplayCost !== null
|
|
1053
|
+
&& Number.isFinite(Number(referenceCost.totalDisplayCost));
|
|
1054
|
+
const hasUsd = referenceCost.totalUsd !== undefined
|
|
1055
|
+
&& referenceCost.totalUsd !== null
|
|
1056
|
+
&& Number.isFinite(Number(referenceCost.totalUsd));
|
|
1057
|
+
|
|
1058
|
+
const amount = hasDisplay
|
|
1059
|
+
? Math.max(0, Number(referenceCost.totalDisplayCost))
|
|
1060
|
+
: (hasUsd ? Math.max(0, Number(referenceCost.totalUsd) * rate) : null);
|
|
1061
|
+
|
|
1062
|
+
const unpriced = pricedCount === 0 && (amount === null || amount === 0);
|
|
1063
|
+
if (amount === null && !unpriced) return null;
|
|
1064
|
+
|
|
1065
|
+
const modelBreakdown = [];
|
|
1066
|
+
if (referenceCost.byModel && typeof referenceCost.byModel === 'object') {
|
|
1067
|
+
for (const [model, stat] of Object.entries(referenceCost.byModel)) {
|
|
1068
|
+
if (!stat || !stat.isPriced || !Number.isFinite(Number(stat.costUSD))) continue;
|
|
1069
|
+
const modelUsd = Math.max(0, Number(stat.costUSD));
|
|
1070
|
+
const modelAmt = modelUsd * rate;
|
|
1071
|
+
modelBreakdown.push({
|
|
1072
|
+
model,
|
|
1073
|
+
calls: Number(stat.calls || 0) || 0,
|
|
1074
|
+
tokens: Number(stat.tokens || 0) || 0,
|
|
1075
|
+
costUsd: modelUsd,
|
|
1076
|
+
amount: modelAmt,
|
|
1077
|
+
text: formatCurrencyValue(modelAmt, symbol)
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
modelBreakdown.sort((a, b) => b.costUsd - a.costUsd);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const formatted = unpriced ? '--' : formatCurrencyValue(amount, symbol);
|
|
1084
|
+
return {
|
|
1085
|
+
hasCost: !unpriced,
|
|
1086
|
+
unpriced,
|
|
1087
|
+
partial: !unpriced && unpricedCount > 0,
|
|
1088
|
+
amount: unpriced ? null : amount,
|
|
1089
|
+
currency,
|
|
1090
|
+
symbol,
|
|
1091
|
+
exchangeRate: rate,
|
|
1092
|
+
compactText: formatted,
|
|
1093
|
+
displayText: formatted,
|
|
1094
|
+
callsCount,
|
|
1095
|
+
pricedCount,
|
|
1096
|
+
unpricedCount,
|
|
1097
|
+
modelBreakdown
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1001
1101
|
function getRingAccentToken(usagePercent, cacheAlert = {}) {
|
|
1002
1102
|
if (cacheAlert.isCacheDrop || Number(usagePercent) >= 80) {
|
|
1003
1103
|
return 'var(--ag-ring-danger, #ef4444)';
|
|
@@ -1018,6 +1118,8 @@ module.exports = {
|
|
|
1018
1118
|
parseTimestampMs,
|
|
1019
1119
|
parseDurationSec,
|
|
1020
1120
|
formatTokensShort,
|
|
1121
|
+
formatCurrencyValue,
|
|
1122
|
+
formatReferenceCost,
|
|
1021
1123
|
parseThresholdSpec,
|
|
1022
1124
|
resolveThresholdTokens,
|
|
1023
1125
|
formatThresholdLabel,
|
|
@@ -1031,6 +1133,7 @@ module.exports = {
|
|
|
1031
1133
|
extractStepTimestampsFromTrajectory,
|
|
1032
1134
|
extractCallId,
|
|
1033
1135
|
parseGeneratorCall,
|
|
1136
|
+
collectSessionGeneratorCalls,
|
|
1034
1137
|
summarizeSessionGeneratorCalls,
|
|
1035
1138
|
getRingAccentToken
|
|
1036
1139
|
};
|
package/src/node.js
CHANGED
|
@@ -10,6 +10,7 @@ const {
|
|
|
10
10
|
analyzeTrajectorySteps,
|
|
11
11
|
extractStepTimestampsFromTrajectory,
|
|
12
12
|
parseGeneratorCall,
|
|
13
|
+
collectSessionGeneratorCalls,
|
|
13
14
|
summarizeSessionGeneratorCalls,
|
|
14
15
|
resolveThresholdTokens,
|
|
15
16
|
formatThresholdLabel,
|
|
@@ -82,6 +83,7 @@ function readTranscriptStepTimestampsCached(cascadeId, brainDirs = null) {
|
|
|
82
83
|
}
|
|
83
84
|
|
|
84
85
|
let disposers = [];
|
|
86
|
+
let activeHost = null;
|
|
85
87
|
|
|
86
88
|
function pickTargetCascadeId(requestedId, summariesObj = {}) {
|
|
87
89
|
if (requestedId) return requestedId;
|
|
@@ -118,11 +120,15 @@ function buildAlerts(snapshot, settings = {}) {
|
|
|
118
120
|
}
|
|
119
121
|
|
|
120
122
|
async function activate(host) {
|
|
123
|
+
activeHost = host;
|
|
124
|
+
let deactivated = false;
|
|
121
125
|
const availableModels = new Map();
|
|
122
126
|
const seenCallIds = new Set();
|
|
123
127
|
const recentCalls = [];
|
|
124
128
|
const contextCacheBySession = new Map();
|
|
125
129
|
let latestSnapshot = null;
|
|
130
|
+
let lastSessionCalls = [];
|
|
131
|
+
let lastUsageCurrencyKey = '';
|
|
126
132
|
|
|
127
133
|
function loadSettings() {
|
|
128
134
|
const saved = (typeof host.settings?.get === 'function' ? host.settings.get() : null) || {};
|
|
@@ -135,6 +141,7 @@ async function activate(host) {
|
|
|
135
141
|
const showSpeed = saved.showSpeed !== undefined
|
|
136
142
|
? saved.showSpeed !== false
|
|
137
143
|
: saved.showSpeedInTopbar !== false;
|
|
144
|
+
const showCost = saved.showCost !== false;
|
|
138
145
|
const VALID_COMPACT_POLICIES = new Set(['remind', 'idle_prompt', 'cliff_auto', 'idle_and_cliff']);
|
|
139
146
|
const compactPolicy = VALID_COMPACT_POLICIES.has(saved.compactPolicy)
|
|
140
147
|
? saved.compactPolicy
|
|
@@ -144,6 +151,7 @@ async function activate(host) {
|
|
|
144
151
|
return {
|
|
145
152
|
displayLocation,
|
|
146
153
|
showSpeed,
|
|
154
|
+
showCost,
|
|
147
155
|
pollIntervalMs: Number(saved.pollIntervalMs) >= 1000 ? Number(saved.pollIntervalMs) : 3000,
|
|
148
156
|
warnThreshold,
|
|
149
157
|
cliffThreshold,
|
|
@@ -152,17 +160,73 @@ async function activate(host) {
|
|
|
152
160
|
};
|
|
153
161
|
}
|
|
154
162
|
|
|
155
|
-
function
|
|
156
|
-
|
|
163
|
+
async function checkUsageServiceAvailable() {
|
|
164
|
+
try {
|
|
165
|
+
if (typeof host.services?.has === 'function') {
|
|
166
|
+
return Boolean(await Promise.resolve(host.services.has('usage')));
|
|
167
|
+
}
|
|
168
|
+
} catch {}
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function buildEmptySnapshot(settings = loadSettings(), usageAvailable = null) {
|
|
173
|
+
return {
|
|
174
|
+
ok: true,
|
|
175
|
+
hasSession: false,
|
|
176
|
+
cascadeId: null,
|
|
177
|
+
status: 'idle',
|
|
178
|
+
used: null,
|
|
179
|
+
budget: null,
|
|
180
|
+
percent: null,
|
|
181
|
+
remainPercent: null,
|
|
182
|
+
model: null,
|
|
183
|
+
speed: null,
|
|
184
|
+
sessionUsage: summarizeSessionGeneratorCalls([]),
|
|
185
|
+
groups: null,
|
|
186
|
+
attachments: { items: [], totals: { count: 0, chars: 0, bytes: 0, low: 0, high: 0 } },
|
|
187
|
+
alerts: [],
|
|
188
|
+
referenceCost: null,
|
|
189
|
+
usageServiceAvailable: usageAvailable,
|
|
190
|
+
displayLocation: settings.displayLocation,
|
|
191
|
+
showSpeed: settings.showSpeed,
|
|
192
|
+
showCost: settings.showCost,
|
|
193
|
+
compactPolicy: settings.compactPolicy,
|
|
194
|
+
warnThreshold: settings.warnThreshold,
|
|
195
|
+
cliffThreshold: settings.cliffThreshold,
|
|
196
|
+
updatedAt: Date.now()
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function syncSnapshotFromSettings() {
|
|
157
201
|
const settings = loadSettings();
|
|
202
|
+
if (!latestSnapshot || !latestSnapshot.hasSession) {
|
|
203
|
+
latestSnapshot = {
|
|
204
|
+
...(latestSnapshot || buildEmptySnapshot(settings)),
|
|
205
|
+
displayLocation: settings.displayLocation,
|
|
206
|
+
showSpeed: settings.showSpeed,
|
|
207
|
+
showCost: settings.showCost,
|
|
208
|
+
compactPolicy: settings.compactPolicy,
|
|
209
|
+
warnThreshold: settings.warnThreshold,
|
|
210
|
+
cliffThreshold: settings.cliffThreshold,
|
|
211
|
+
updatedAt: Date.now()
|
|
212
|
+
};
|
|
213
|
+
host.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
158
216
|
const used = Number(latestSnapshot.used || 0);
|
|
159
217
|
const warnTokens = resolveThresholdTokens(settings.warnThreshold, latestSnapshot.budget, 240000);
|
|
160
218
|
const cliffTokens = resolveThresholdTokens(settings.cliffThreshold, latestSnapshot.budget, 328000);
|
|
161
219
|
const cacheCliffRisk = used >= cliffTokens
|
|
162
220
|
? 'critical'
|
|
163
221
|
: (used >= warnTokens ? 'warn' : 'none');
|
|
222
|
+
const prevShowCost = latestSnapshot.showCost !== false;
|
|
164
223
|
latestSnapshot = {
|
|
165
224
|
...latestSnapshot,
|
|
225
|
+
displayLocation: settings.displayLocation,
|
|
226
|
+
showSpeed: settings.showSpeed,
|
|
227
|
+
showCost: settings.showCost,
|
|
228
|
+
referenceCost: settings.showCost ? latestSnapshot.referenceCost : null,
|
|
229
|
+
compactPolicy: settings.compactPolicy,
|
|
166
230
|
warnThreshold: settings.warnThreshold,
|
|
167
231
|
cliffThreshold: settings.cliffThreshold,
|
|
168
232
|
warnThresholdTokens: warnTokens,
|
|
@@ -172,7 +236,10 @@ async function activate(host) {
|
|
|
172
236
|
updatedAt: Date.now()
|
|
173
237
|
};
|
|
174
238
|
host.storage.writeJson('latest-snapshot.json', latestSnapshot);
|
|
175
|
-
host.state
|
|
239
|
+
host.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
240
|
+
if (!prevShowCost && settings.showCost && !deactivated) {
|
|
241
|
+
void scanCascade({ cascadeId: latestSnapshot.cascadeId, force: true }).catch(() => {});
|
|
242
|
+
}
|
|
176
243
|
}
|
|
177
244
|
|
|
178
245
|
function recordNewGeneratorCalls(rows, cascadeId, parseOptions = {}) {
|
|
@@ -217,7 +284,7 @@ async function activate(host) {
|
|
|
217
284
|
}
|
|
218
285
|
|
|
219
286
|
let summaries = {};
|
|
220
|
-
if (!cascadeId) {
|
|
287
|
+
if (!cascadeId && !options.isNewChat) {
|
|
221
288
|
try {
|
|
222
289
|
const allResp = await host.rpc.call('GetAllCascadeTrajectories', {
|
|
223
290
|
metadata: { ideName: 'antigravity', extensionName: 'antigravity' }
|
|
@@ -228,26 +295,12 @@ async function activate(host) {
|
|
|
228
295
|
}
|
|
229
296
|
|
|
230
297
|
if (!cascadeId) {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
cascadeId: null,
|
|
235
|
-
status: 'idle',
|
|
236
|
-
used: null,
|
|
237
|
-
budget: null,
|
|
238
|
-
percent: null,
|
|
239
|
-
remainPercent: null,
|
|
240
|
-
model: null,
|
|
241
|
-
speed: null,
|
|
242
|
-
sessionUsage: summarizeSessionGeneratorCalls([]),
|
|
243
|
-
groups: null,
|
|
244
|
-
attachments: { items: [], totals: { count: 0, chars: 0, bytes: 0, low: 0, high: 0 } },
|
|
245
|
-
alerts: [],
|
|
246
|
-
referenceCost: null,
|
|
247
|
-
updatedAt: Date.now()
|
|
248
|
-
};
|
|
298
|
+
lastSessionCalls = [];
|
|
299
|
+
const usageAvailable = await checkUsageServiceAvailable();
|
|
300
|
+
const emptySnap = buildEmptySnapshot(settings, usageAvailable);
|
|
249
301
|
latestSnapshot = emptySnap;
|
|
250
|
-
host.
|
|
302
|
+
host.storage.writeJson('latest-snapshot.json', emptySnap);
|
|
303
|
+
host.state?.set?.('state:context.snapshot@1', emptySnap);
|
|
251
304
|
return emptySnap;
|
|
252
305
|
}
|
|
253
306
|
|
|
@@ -303,6 +356,12 @@ async function activate(host) {
|
|
|
303
356
|
stepTimestamps,
|
|
304
357
|
fallbackTimestampMs
|
|
305
358
|
});
|
|
359
|
+
const sessionCalls = collectSessionGeneratorCalls(gmRows, {
|
|
360
|
+
cascadeId,
|
|
361
|
+
source: 'desktop',
|
|
362
|
+
stepTimestamps,
|
|
363
|
+
fallbackTimestampMs
|
|
364
|
+
});
|
|
306
365
|
const sessionUsage = summarizeSessionGeneratorCalls(gmRows, { cascadeId });
|
|
307
366
|
|
|
308
367
|
const stepAnalysis = analyzeTrajectorySteps(steps, {
|
|
@@ -329,17 +388,27 @@ async function activate(host) {
|
|
|
329
388
|
contextCacheBySession.set(cascadeId, metaSummary);
|
|
330
389
|
}
|
|
331
390
|
|
|
332
|
-
// 软消费可选 usage 服务获取本会话参考费用(usage
|
|
391
|
+
// 软消费可选 usage 服务获取本会话参考费用(usage 未安装或开关关闭时安全返回 null)
|
|
333
392
|
let referenceCost = null;
|
|
393
|
+
let usageServiceAvailable = false;
|
|
334
394
|
const callsForSession = recentCalls.filter((c) => c.cascadeId === cascadeId);
|
|
335
|
-
const costInput = callsForSession.length ? callsForSession : newCalls;
|
|
336
|
-
|
|
395
|
+
const costInput = sessionCalls.length ? sessionCalls : (callsForSession.length ? callsForSession : newCalls);
|
|
396
|
+
lastSessionCalls = costInput;
|
|
397
|
+
if (settings.showCost && costInput.length > 0) {
|
|
337
398
|
try {
|
|
338
|
-
const usageRes = await host.services.call('usage', 'estimateCallsCost', [costInput], { optional: true });
|
|
339
|
-
if (usageRes?.ok
|
|
340
|
-
|
|
399
|
+
const usageRes = await host.services.call('usage', 'estimateCallsCost', [costInput], { optional: true, timeoutMs: 2000 });
|
|
400
|
+
if (usageRes?.ok) {
|
|
401
|
+
usageServiceAvailable = true;
|
|
402
|
+
if (usageRes.value) {
|
|
403
|
+
referenceCost = usageRes.value;
|
|
404
|
+
if (referenceCost.currency) {
|
|
405
|
+
lastUsageCurrencyKey = `${referenceCost.currency}:${referenceCost.exchangeRate || ''}:${referenceCost.currencySymbol || ''}`;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
341
408
|
}
|
|
342
409
|
} catch {}
|
|
410
|
+
} else {
|
|
411
|
+
usageServiceAvailable = await checkUsageServiceAvailable();
|
|
343
412
|
}
|
|
344
413
|
|
|
345
414
|
const snapshot = {
|
|
@@ -379,7 +448,12 @@ async function activate(host) {
|
|
|
379
448
|
compressionDrop: stepAnalysis.compressionDrop,
|
|
380
449
|
attachments: attachmentAudit,
|
|
381
450
|
referenceCost,
|
|
451
|
+
usageServiceAvailable,
|
|
382
452
|
alerts: [],
|
|
453
|
+
displayLocation: settings.displayLocation,
|
|
454
|
+
showSpeed: settings.showSpeed,
|
|
455
|
+
showCost: settings.showCost,
|
|
456
|
+
compactPolicy: settings.compactPolicy,
|
|
383
457
|
updatedAt: Date.now()
|
|
384
458
|
};
|
|
385
459
|
snapshot.alerts = buildAlerts(snapshot, settings);
|
|
@@ -391,7 +465,13 @@ async function activate(host) {
|
|
|
391
465
|
}
|
|
392
466
|
|
|
393
467
|
const serviceMethods = {
|
|
468
|
+
getSettings() {
|
|
469
|
+
return loadSettings();
|
|
470
|
+
},
|
|
394
471
|
async getSnapshot(opts = {}) {
|
|
472
|
+
if (opts.isNewChat && !opts.cascadeId) {
|
|
473
|
+
return await scanCascade(opts);
|
|
474
|
+
}
|
|
395
475
|
if (!opts.force && latestSnapshot && (!opts.cascadeId || opts.cascadeId === latestSnapshot.cascadeId) && Date.now() - latestSnapshot.updatedAt < 1000) {
|
|
396
476
|
return latestSnapshot;
|
|
397
477
|
}
|
|
@@ -445,15 +525,44 @@ async function activate(host) {
|
|
|
445
525
|
sessionUsage: snap.sessionUsage || summarizeSessionGeneratorCalls([]),
|
|
446
526
|
alerts: snap.alerts || [],
|
|
447
527
|
attachmentSummary: snap.attachments?.totals || { count: 0, high: 0 },
|
|
448
|
-
referenceCost: snap.referenceCost || null,
|
|
528
|
+
referenceCost: settings.showCost ? (snap.referenceCost || null) : null,
|
|
529
|
+
usageServiceAvailable: snap.usageServiceAvailable ?? null,
|
|
530
|
+
showCost: settings.showCost,
|
|
449
531
|
updatedAt: snap.updatedAt
|
|
450
532
|
};
|
|
451
533
|
},
|
|
452
534
|
ingestRendererSnapshot(payload = {}) {
|
|
453
535
|
if (!payload || typeof payload !== 'object') return { ok: false };
|
|
454
|
-
|
|
455
|
-
|
|
536
|
+
const settings = loadSettings();
|
|
537
|
+
latestSnapshot = {
|
|
538
|
+
...(latestSnapshot || {}),
|
|
539
|
+
...payload,
|
|
540
|
+
displayLocation: payload.displayLocation ?? settings.displayLocation,
|
|
541
|
+
showSpeed: payload.showSpeed ?? settings.showSpeed,
|
|
542
|
+
showCost: payload.showCost ?? settings.showCost,
|
|
543
|
+
compactPolicy: payload.compactPolicy ?? settings.compactPolicy,
|
|
544
|
+
updatedAt: Date.now()
|
|
545
|
+
};
|
|
546
|
+
host.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
456
547
|
return { ok: true, snapshot: latestSnapshot };
|
|
548
|
+
},
|
|
549
|
+
ingestLiveState(payload = {}) {
|
|
550
|
+
if (payload === null) {
|
|
551
|
+
host.state?.set?.('state:context.live@1', null);
|
|
552
|
+
return { ok: true, live: null };
|
|
553
|
+
}
|
|
554
|
+
if (!payload || typeof payload !== 'object') return { ok: false };
|
|
555
|
+
const live = {
|
|
556
|
+
cascadeId: payload.cascadeId ? String(payload.cascadeId) : null,
|
|
557
|
+
busy: Boolean(payload.busy),
|
|
558
|
+
phase: String(payload.phase || (payload.busy ? 'waiting' : 'idle')),
|
|
559
|
+
tps: payload.tps === null || payload.tps === undefined ? null : Number(payload.tps),
|
|
560
|
+
ttft: payload.ttft === null || payload.ttft === undefined ? null : Number(payload.ttft),
|
|
561
|
+
estimatedOutputTokens: Number(payload.estimatedOutputTokens || 0),
|
|
562
|
+
updatedAt: Number(payload.updatedAt) || Date.now()
|
|
563
|
+
};
|
|
564
|
+
host.state?.set?.('state:context.live@1', live);
|
|
565
|
+
return { ok: true, live };
|
|
457
566
|
}
|
|
458
567
|
};
|
|
459
568
|
|
|
@@ -462,31 +571,74 @@ async function activate(host) {
|
|
|
462
571
|
const stopRescanRoute = await host.bridge.registerRoute('/rescan', async (body) => serviceMethods.rescan(body || {}));
|
|
463
572
|
const stopAuditRoute = await host.bridge.registerRoute('/audit-attachments', async (body) => serviceMethods.auditAttachments(body?.media || []));
|
|
464
573
|
const stopIngestRoute = await host.bridge.registerRoute('/ingest-renderer-snapshot', async (body) => serviceMethods.ingestRendererSnapshot(body || {}));
|
|
574
|
+
const stopLiveRoute = await host.bridge.registerRoute('/live-state', async (body) => serviceMethods.ingestLiveState(body ?? null));
|
|
465
575
|
const stopSettingsSub = typeof host.settings?.onChange === 'function'
|
|
466
|
-
? host.settings.onChange((
|
|
467
|
-
|
|
468
|
-
if (
|
|
469
|
-
keys.length === 0 ||
|
|
470
|
-
keys.includes('warnThreshold') ||
|
|
471
|
-
keys.includes('cliffThreshold') ||
|
|
472
|
-
keys.includes('warnThresholdTokens') ||
|
|
473
|
-
keys.includes('cliffThresholdTokens')
|
|
474
|
-
) {
|
|
475
|
-
recomputeAlertsFromSettings();
|
|
476
|
-
}
|
|
576
|
+
? host.settings.onChange(() => {
|
|
577
|
+
syncSnapshotFromSettings();
|
|
477
578
|
})
|
|
478
579
|
: () => {};
|
|
580
|
+
const stopUsageStateSub = typeof host.state?.subscribe === 'function'
|
|
581
|
+
? await Promise.resolve(host.state.subscribe('state:usage.summary@1', (rawVal) => {
|
|
582
|
+
if (deactivated) return;
|
|
583
|
+
const val = (rawVal && typeof rawVal === 'object' && 'value' in rawVal) ? rawVal.value : rawVal;
|
|
584
|
+
if (!val || typeof val !== 'object') return;
|
|
585
|
+
const settings = loadSettings();
|
|
586
|
+
const curKey = `${val.currency || ''}:${val.exchangeRate || ''}:${val.currencySymbol || ''}`;
|
|
587
|
+
const currencyChanged = Boolean(val.currency) && curKey !== lastUsageCurrencyKey;
|
|
588
|
+
if (val.currency) lastUsageCurrencyKey = curKey;
|
|
589
|
+
|
|
590
|
+
if (!settings.showCost || !latestSnapshot?.hasSession) return;
|
|
591
|
+
if (latestSnapshot.referenceCost && currencyChanged && Number.isFinite(Number(latestSnapshot.referenceCost.totalUsd))) {
|
|
592
|
+
const rate = Number(val.exchangeRate) > 0 ? Number(val.exchangeRate) : (val.currency === 'CNY' ? 7.25 : 1);
|
|
593
|
+
const symbol = val.currencySymbol || (val.currency === 'CNY' ? '¥' : '$');
|
|
594
|
+
const nextCost = {
|
|
595
|
+
...latestSnapshot.referenceCost,
|
|
596
|
+
currency: val.currency,
|
|
597
|
+
exchangeRate: rate,
|
|
598
|
+
currencySymbol: symbol,
|
|
599
|
+
totalDisplayCost: Number((Number(latestSnapshot.referenceCost.totalUsd) * rate).toFixed(4))
|
|
600
|
+
};
|
|
601
|
+
latestSnapshot = {
|
|
602
|
+
...latestSnapshot,
|
|
603
|
+
referenceCost: nextCost,
|
|
604
|
+
usageServiceAvailable: true,
|
|
605
|
+
updatedAt: Date.now()
|
|
606
|
+
};
|
|
607
|
+
host.storage.writeJson('latest-snapshot.json', latestSnapshot);
|
|
608
|
+
host.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
if (!latestSnapshot.referenceCost && lastSessionCalls.length > 0) {
|
|
612
|
+
void host.services.call('usage', 'estimateCallsCost', [lastSessionCalls], { optional: true, timeoutMs: 2000 })
|
|
613
|
+
.then((res) => {
|
|
614
|
+
if (deactivated || !res?.ok || !res.value || !latestSnapshot?.hasSession) return;
|
|
615
|
+
latestSnapshot = {
|
|
616
|
+
...latestSnapshot,
|
|
617
|
+
referenceCost: res.value,
|
|
618
|
+
usageServiceAvailable: true,
|
|
619
|
+
updatedAt: Date.now()
|
|
620
|
+
};
|
|
621
|
+
host.storage.writeJson('latest-snapshot.json', latestSnapshot);
|
|
622
|
+
host.state?.set?.('state:context.snapshot@1', latestSnapshot);
|
|
623
|
+
})
|
|
624
|
+
.catch(() => {});
|
|
625
|
+
}
|
|
626
|
+
}))
|
|
627
|
+
: () => {};
|
|
479
628
|
const stopRescanCmd = typeof host.commands?.register === 'function'
|
|
480
629
|
? await host.commands.register('context.rescan', async (opts = {}) => serviceMethods.rescan(opts || {}))
|
|
481
630
|
: () => {};
|
|
482
631
|
|
|
483
632
|
disposers.push(
|
|
633
|
+
() => { deactivated = true; },
|
|
484
634
|
stopSvc,
|
|
485
635
|
stopSnapRoute,
|
|
486
636
|
stopRescanRoute,
|
|
487
637
|
stopAuditRoute,
|
|
488
638
|
stopIngestRoute,
|
|
639
|
+
stopLiveRoute,
|
|
489
640
|
stopSettingsSub,
|
|
641
|
+
stopUsageStateSub,
|
|
490
642
|
stopRescanCmd
|
|
491
643
|
);
|
|
492
644
|
}
|
|
@@ -496,6 +648,12 @@ async function deactivate() {
|
|
|
496
648
|
try { if (typeof fn === 'function') fn(); } catch {}
|
|
497
649
|
}
|
|
498
650
|
disposers = [];
|
|
651
|
+
const host = activeHost;
|
|
652
|
+
activeHost = null;
|
|
653
|
+
try {
|
|
654
|
+
host?.state?.set?.('state:context.snapshot@1', null);
|
|
655
|
+
host?.state?.set?.('state:context.live@1', null);
|
|
656
|
+
} catch {}
|
|
499
657
|
}
|
|
500
658
|
|
|
501
659
|
module.exports = {
|
package/src/panel-styles.js
CHANGED
|
@@ -259,6 +259,44 @@ const CONTEXT_PANEL_CSS = `
|
|
|
259
259
|
color: var(--ag-text-secondary);
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
+
.ag-ctx-cost-row {
|
|
263
|
+
display: flex;
|
|
264
|
+
align-items: baseline;
|
|
265
|
+
justify-content: space-between;
|
|
266
|
+
gap: 8px;
|
|
267
|
+
padding-top: 6px;
|
|
268
|
+
margin-top: 2px;
|
|
269
|
+
border-top: 1px dashed var(--ag-border-subcard);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
.ag-ctx-cost-label {
|
|
273
|
+
display: inline-flex;
|
|
274
|
+
align-items: baseline;
|
|
275
|
+
gap: 5px;
|
|
276
|
+
font-size: 11px;
|
|
277
|
+
color: var(--ag-text-secondary);
|
|
278
|
+
min-width: 0;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
.ag-ctx-cost-note {
|
|
282
|
+
font-size: 10.5px;
|
|
283
|
+
color: var(--ag-text-muted);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
.ag-ctx-cost-val {
|
|
287
|
+
font-size: 13.5px;
|
|
288
|
+
font-weight: 600;
|
|
289
|
+
font-variant-numeric: tabular-nums;
|
|
290
|
+
letter-spacing: -0.01em;
|
|
291
|
+
color: var(--ag-text-primary);
|
|
292
|
+
white-space: nowrap;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
.ag-ctx-cost-val[data-muted="true"] {
|
|
296
|
+
color: var(--ag-text-muted);
|
|
297
|
+
font-weight: 500;
|
|
298
|
+
}
|
|
299
|
+
|
|
262
300
|
.ag-ctx-help-list {
|
|
263
301
|
margin: 6px 0 0;
|
|
264
302
|
padding-left: 14px;
|
package/src/pulse-capsule.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { formatTokensShort, getRingAccentToken } = require('./context-analyzer');
|
|
3
|
+
const { formatTokensShort, formatReferenceCost, getRingAccentToken } = require('./context-analyzer');
|
|
4
4
|
|
|
5
5
|
const SESSION_STACK_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2.5 2.5 5.5 8 8.5l5.5-3L8 2.5Z"/><path d="M2.5 8.5 8 11.5l5.5-3"/><path d="M2.5 11.5 8 14.5l5.5-3"/></svg>';
|
|
6
|
+
const COST_COIN_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="5.6"/><path d="M8 4.6v6.8"/><path d="M10.1 6.1c0-.9-.95-1.4-2.1-1.4s-2.1.5-2.1 1.4c0 1.8 4.2.9 4.2 2.8 0 .95-.95 1.5-2.1 1.5s-2.1-.55-2.1-1.5"/></svg>';
|
|
6
7
|
const SPEED_BOLT_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.2 1.8 3.6 9h4.1l-.9 5.2L12.4 7H8.3l.9-5.2Z"/></svg>';
|
|
7
8
|
const ALERT_TRIANGLE_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2.3 14 13H2L8 2.3Z"/><path d="M8 6.4v3.2"/><circle cx="8" cy="11.4" r="0.55" fill="currentColor" stroke="none"/></svg>';
|
|
8
9
|
const COMPACT_ICON_SVG = '<svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v4.5M5.5 4.2 8 6.7l2.5-2.5"/><path d="M8 14V9.5M5.5 11.8 8 9.3l2.5 2.5"/><path d="M2.5 8h11"/></svg>';
|
|
@@ -190,6 +191,17 @@ function buildCapsuleSegments(snap, opts = {}) {
|
|
|
190
191
|
}
|
|
191
192
|
];
|
|
192
193
|
|
|
194
|
+
if (opts.showCost !== false && snap.showCost !== false) {
|
|
195
|
+
const costInfo = formatReferenceCost(snap.referenceCost);
|
|
196
|
+
if (costInfo && costInfo.hasCost) {
|
|
197
|
+
segments.push({
|
|
198
|
+
kind: 'cost',
|
|
199
|
+
iconSvg: COST_COIN_ICON_SVG,
|
|
200
|
+
text: costInfo.compactText
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
193
205
|
if (opts.showSpeed !== false) {
|
|
194
206
|
const live = opts.liveSpeed;
|
|
195
207
|
if (live && live.active) {
|
|
@@ -244,6 +256,15 @@ function buildCapsuleTooltip(snap, opts = {}) {
|
|
|
244
256
|
`当前对话累计: ${formatTokensShort(sessionTotal)} (${su.callsCount || 0} 次调用 · 输出 ${formatTokensShort(su.outputTokens ?? snap.outputTokens ?? 0)})`,
|
|
245
257
|
speedLine
|
|
246
258
|
];
|
|
259
|
+
if (opts.showCost !== false && snap.showCost !== false) {
|
|
260
|
+
const costInfo = formatReferenceCost(snap.referenceCost);
|
|
261
|
+
if (costInfo && costInfo.hasCost) {
|
|
262
|
+
const partialNote = costInfo.partial ? ` · 含 ${costInfo.unpricedCount} 次未知模型` : '';
|
|
263
|
+
lines.push(`当前会话参考费用: ${costInfo.displayText} (${costInfo.currency} API 费率折算${partialNote})`);
|
|
264
|
+
} else if (costInfo && costInfo.unpriced) {
|
|
265
|
+
lines.push('当前会话参考费用: -- (当前模型暂无公开单价)');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
247
268
|
if (Array.isArray(snap.alerts) && snap.alerts.length) {
|
|
248
269
|
lines.push(`风险提示: ${snap.alerts.map((a) => a.message).join(';')}`);
|
|
249
270
|
}
|
|
@@ -264,7 +285,12 @@ function createPulseCapsuleController(options = {}) {
|
|
|
264
285
|
const onCompactClick = typeof options.onCompactClick === 'function' ? options.onCompactClick : () => {};
|
|
265
286
|
const mountedEntries = new Set(); // { wrap, btn, compactBtn }
|
|
266
287
|
let lastSnapshot = null;
|
|
267
|
-
let lastState = {
|
|
288
|
+
let lastState = {
|
|
289
|
+
showSpeed: options.showSpeed !== false,
|
|
290
|
+
showCost: options.showCost !== false,
|
|
291
|
+
liveSpeed: null,
|
|
292
|
+
showQuickCompact: false
|
|
293
|
+
};
|
|
268
294
|
let enabled = options.enabled !== false;
|
|
269
295
|
|
|
270
296
|
function applyStyleAndContent(entry, snap, stateOpts = lastState) {
|
|
@@ -427,6 +453,7 @@ function createPulseCapsuleController(options = {}) {
|
|
|
427
453
|
if (stateOpts && typeof stateOpts === 'object') {
|
|
428
454
|
lastState = {
|
|
429
455
|
showSpeed: stateOpts.showSpeed !== undefined ? stateOpts.showSpeed !== false : lastState.showSpeed,
|
|
456
|
+
showCost: stateOpts.showCost !== undefined ? stateOpts.showCost !== false : lastState.showCost,
|
|
430
457
|
liveSpeed: stateOpts.liveSpeed !== undefined ? stateOpts.liveSpeed : lastState.liveSpeed,
|
|
431
458
|
showQuickCompact: stateOpts.showQuickCompact !== undefined ? Boolean(stateOpts.showQuickCompact) : lastState.showQuickCompact
|
|
432
459
|
};
|
|
@@ -471,6 +498,7 @@ function createPulseCapsuleController(options = {}) {
|
|
|
471
498
|
|
|
472
499
|
module.exports = {
|
|
473
500
|
SESSION_STACK_ICON_SVG,
|
|
501
|
+
COST_COIN_ICON_SVG,
|
|
474
502
|
SPEED_BOLT_ICON_SVG,
|
|
475
503
|
ALERT_TRIANGLE_ICON_SVG,
|
|
476
504
|
COMPACT_ICON_SVG,
|
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
|
);
|