@lingda-ai/dsh-plugin-ledger 0.1.4 → 0.1.6
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/docs/technical.md +41 -4
- package/lib/client.js +1090 -206
- package/lib/client.src.js +302 -0
- package/package.json +2 -2
package/lib/client.js
CHANGED
|
@@ -1,217 +1,1101 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 生成文件,勿手改。源在 lib/*.src.js 与 lib/panel-*.js,改完跑:
|
|
3
|
+
* node scripts/build-client.mjs --pkg <该包目录>
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* 1) 类型登记 @ dsh-client-ui-sidebar-right
|
|
7
|
-
* ctx.sidebarRightTabs.register(definition) → disposer
|
|
8
|
-
* definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
|
|
9
|
-
* guide entry: { id, order, title(), description?(), icon?, commandId? }
|
|
10
|
-
*
|
|
11
|
-
* 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
|
|
12
|
-
* - 'sidebar.right.pane.tab'
|
|
13
|
-
* - 'sidebar.right.pane.tab.title'
|
|
14
|
-
* 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
|
|
15
|
-
* ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
|
|
16
|
-
*
|
|
17
|
-
* 3) React 由宿主模块表提供(sidebar-right 编译产物里是 require("react")),
|
|
18
|
-
* 故这里用动态 import 取,取不到就退回"只登记类型、不挂正文"的降级态。
|
|
19
|
-
*
|
|
20
|
-
* 取数通道(已接,细节见 docs/spikes.md C-3):
|
|
21
|
-
* 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
|
|
22
|
-
* 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
|
|
23
|
-
* 接入点集中在 createFetchView() 一处。
|
|
24
|
-
*
|
|
25
|
-
* 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
/** 本实现的身份,也是两个 keyed seat 的 key。 */
|
|
29
|
-
const LEDGER_ID = '@lingda-ai/ledger'
|
|
30
|
-
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
31
|
-
const LEDGER_KIND = 'ledger.cost'
|
|
32
|
-
|
|
33
|
-
/** 面板用到的 seat 名,抽出来避免字符串散落。 */
|
|
34
|
-
const SEAT_BODY = 'sidebar.right.pane.tab'
|
|
35
|
-
const SEAT_TITLE = 'sidebar.right.pane.tab.title'
|
|
36
|
-
|
|
37
|
-
import { panelRelativePath } from './panel-path.js'
|
|
38
|
-
import {
|
|
39
|
-
makeLedgerBody,
|
|
40
|
-
makeLedgerTitle,
|
|
41
|
-
renderPayload,
|
|
42
|
-
formatAmount,
|
|
43
|
-
formatTokens,
|
|
44
|
-
formatShare,
|
|
45
|
-
formatClock,
|
|
46
|
-
shortId,
|
|
47
|
-
sourceLabel,
|
|
48
|
-
} from './panel-view.js'
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
/** 会话 id 太长时截断成 chip 能放下的样子。 */
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
|
|
55
|
-
*
|
|
56
|
-
* 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
|
|
57
|
-
* list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
|
|
58
|
-
* stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
|
|
59
|
-
* read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
|
|
60
|
-
* 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
|
|
61
|
-
* 先用相对路径 stat 换出 absolutePath,再 read。
|
|
62
|
-
*
|
|
63
|
-
* 返回形状:
|
|
64
|
-
* null → 还没有快照(Host 未开启或尚未落盘)
|
|
65
|
-
* { error: '...' } → 通道/解析失败,面板显示原因
|
|
66
|
-
* payload → Host 写的 JSON(version / totals / topSources / sources)
|
|
67
|
-
*
|
|
68
|
-
* @param {any} ctx - 浏览器侧 cordis 上下文
|
|
69
|
-
* @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
|
|
5
|
+
* 形态由宿主决定:dsh-client-modules 会把本文件原样拼进 classic script,
|
|
6
|
+
* 所以这里不能出现任何 import / export 语句。
|
|
70
7
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
const relative = panelRelativePath(sessionId)
|
|
79
|
-
|
|
80
|
-
let stat
|
|
81
|
-
try {
|
|
82
|
-
stat = await files.stat(sessionId, relative, opts.signal)
|
|
83
|
-
} catch (error) {
|
|
84
|
-
return { error: stringifyError(error) }
|
|
85
|
-
}
|
|
86
|
-
if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
|
|
87
|
-
const absolutePath = stat.value?.absolutePath
|
|
88
|
-
if (typeof absolutePath !== 'string') return null
|
|
89
|
-
// 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
|
|
90
|
-
const bytes = stat.value?.bytes
|
|
91
|
-
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
92
|
-
|
|
93
|
-
let page
|
|
94
|
-
try {
|
|
95
|
-
page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
|
|
96
|
-
} catch (error) {
|
|
97
|
-
return { error: stringifyError(error) }
|
|
98
|
-
}
|
|
99
|
-
if (!page?.ok) return { error: '读取快照失败' }
|
|
100
|
-
const text = page.value?.text
|
|
101
|
-
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
102
|
-
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
8
|
+
window.__ModuleLoader__.load({
|
|
9
|
+
id: "@lingda-ai/dsh-plugin-ledger",
|
|
10
|
+
factory: (require) => {
|
|
11
|
+
var module = { exports: {} };
|
|
12
|
+
var exports = module.exports;
|
|
13
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
103
14
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const tabs = ctx.sidebarRightTabs
|
|
146
|
-
if (!tabs || typeof tabs.register !== 'function') return
|
|
147
|
-
|
|
148
|
-
const definition = {
|
|
149
|
-
id: LEDGER_ID,
|
|
150
|
-
kind: LEDGER_KIND,
|
|
151
|
-
title: () => '账本',
|
|
152
|
-
priority: 'extension',
|
|
153
|
-
guide: [
|
|
154
|
-
{
|
|
155
|
-
id: 'ledger.cost',
|
|
156
|
-
order: 10,
|
|
157
|
-
title: () => '账本',
|
|
158
|
-
description: () => '本会话的 token 用量与成本归因',
|
|
159
|
-
},
|
|
160
|
-
],
|
|
161
|
-
// 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
|
|
162
|
-
keepMounted: true,
|
|
163
|
-
}
|
|
15
|
+
//#region panel-path.js
|
|
16
|
+
/**
|
|
17
|
+
* 面板快照的路径约定(纯函数,两侧共用)。
|
|
18
|
+
*
|
|
19
|
+
* 为什么单独成文件:Host 半要写盘(用 node:fs),浏览器半要读回(用 workspace 文件 remote)。
|
|
20
|
+
* 两侧必须给出**同名同路径**,所以文件名规则和相对路径只在这里定义一次,
|
|
21
|
+
* 不能一边用 node:path 拼、一边又手写一遍。
|
|
22
|
+
*
|
|
23
|
+
* 路径形态:相对路径 `<root>/.dsh/ledger/<safeSessionId>.json`。
|
|
24
|
+
* `workspaceFiles.stat/list` 接受以 Session cwd 为基准的相对路径,
|
|
25
|
+
* `read` 则要绝对路径 —— 客户端先 stat 拿 `absolutePath` 再 read,无需配置。
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** 默认目录(相对会话工作区根)。 */
|
|
29
|
+
const PANEL_DIR = '.dsh/ledger'
|
|
30
|
+
|
|
31
|
+
/** 快照文件名的固定后缀。 */
|
|
32
|
+
const PANEL_SUFFIX = '.json'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* sessionId 进文件名前必须清洗:只留 `[A-Za-z0-9_-]`。
|
|
36
|
+
* 换掉 `../` 这类字符是为了不让会话 id 变成路径穿越。
|
|
37
|
+
* @param {unknown} sessionId
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
function safeFileName(sessionId) {
|
|
41
|
+
const raw = typeof sessionId === 'string' ? sessionId : ''
|
|
42
|
+
const safe = raw.replace(/[^A-Za-z0-9_-]/g, '_')
|
|
43
|
+
return safe.length > 0 ? safe : 'unknown'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 一份快照在工作区里的相对路径。
|
|
48
|
+
* @param {unknown} sessionId
|
|
49
|
+
* @param {string} [dir] - 相对目录,默认 {@link PANEL_DIR}
|
|
50
|
+
* @returns {string}
|
|
51
|
+
*/
|
|
52
|
+
function panelRelativePath(sessionId, dir = PANEL_DIR) {
|
|
53
|
+
return `${dir}/${safeFileName(sessionId)}${PANEL_SUFFIX}`
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
164
56
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
57
|
+
//#region tool-size.js
|
|
58
|
+
/**
|
|
59
|
+
* 工具结果的"体积":只数字符,不估 token。
|
|
60
|
+
*
|
|
61
|
+
* 为什么不估 token:不同 provider 的 tokenizer 不同,用 1 token ≈ 4 字符这种
|
|
62
|
+
* 经验系数去报"约 xx token",就是把不确定的东西伪装成确定。面板要显示的是
|
|
63
|
+
* "这次工具结果有多大",字符数本身就是事实。
|
|
64
|
+
*
|
|
65
|
+
* 只数 text:图片、文件引用等非文本块不占"文本上下文",数进去反而误导。
|
|
66
|
+
*/
|
|
67
|
+
function toolResultChars(message) {
|
|
68
|
+
const blocks = message?.content
|
|
69
|
+
if (!Array.isArray(blocks)) return 0
|
|
70
|
+
let chars = 0
|
|
71
|
+
for (const block of blocks) {
|
|
72
|
+
if (block !== null && typeof block === 'object' && typeof block.text === 'string') chars += block.text.length
|
|
73
|
+
}
|
|
74
|
+
return chars
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 给面板用的紧凑写法:18,442 → 18.4k(超过 1 万才缩写,小数字不做无意义转换) */
|
|
78
|
+
function formatChars(chars) {
|
|
79
|
+
if (typeof chars !== 'number' || !Number.isFinite(chars) || chars < 0) return null
|
|
80
|
+
if (chars < 10_000) return `${chars.toLocaleString('en-US')} 字符`
|
|
81
|
+
return `${(chars / 1000).toFixed(1)}k 字符`
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
170
84
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
85
|
+
//#region panel-view.js
|
|
86
|
+
/** 缓存节省:为 null 或 0 时都不画收益行——0 收益不值得占版面,未知更不该冒充 0 */
|
|
87
|
+
function savedOf(view) {
|
|
88
|
+
const saved = view.totals?.saved
|
|
89
|
+
if (!saved || typeof saved.amount !== 'number' || saved.amount <= 0) return null
|
|
90
|
+
return saved
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 明细第二行的路由文案;压缩条目已经写了"压缩前 42.0k",再写一次"上下文压缩"就是重复 */
|
|
94
|
+
function routeTextOf(item) {
|
|
95
|
+
if (item.route !== null && typeof item.route === 'object') {
|
|
96
|
+
return `${item.route.provider ?? '?'}/${item.route.model ?? '?'}`
|
|
97
|
+
}
|
|
98
|
+
if (typeof item.contextBeforeTokens === 'number') return null
|
|
99
|
+
return item.system === 'compaction' ? '上下文压缩' : '无路由'
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
|
|
103
|
+
/** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
|
|
104
|
+
function tokensTotal(tokens) {
|
|
105
|
+
if (!tokens || typeof tokens !== 'object') return null
|
|
106
|
+
const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
|
|
107
|
+
if (!parts.every((v) => Number.isFinite(v))) return null
|
|
108
|
+
return parts[0] + parts[1] + parts[2] + parts[3]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function formatContextTokens(value) {
|
|
112
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return null
|
|
113
|
+
if (value < 10_000) return value.toLocaleString('en-US')
|
|
114
|
+
return `${(value / 1000).toFixed(1)}k`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 面板的纯展示部分:样式常量、格式化、组件工厂。
|
|
119
|
+
*
|
|
120
|
+
* 这里不碰 ctx、不发请求、不写文件 —— 输入是"已经拿到的快照",
|
|
121
|
+
* 输出是 React 元素。取数与注册留在 client.js。
|
|
122
|
+
*/
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 数字的可信度要能自证:面板上每个金额都来自内置官方价表,
|
|
126
|
+
* 用户看到这一行才知道"这是按什么价、哪天的价算的",也才知道该不该信。
|
|
127
|
+
*/
|
|
128
|
+
/** 警示色(与预算 ≥80% 同色系):只用来标"这个数不是确定值" */
|
|
129
|
+
const WARN = '#c98a12'
|
|
130
|
+
|
|
131
|
+
/** 收益色(品牌绿):压缩省下的上下文属于"赚到了",不能和支出一个颜色 */
|
|
132
|
+
const GOOD = '#2f7d64'
|
|
133
|
+
|
|
134
|
+
/** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
|
|
135
|
+
const SOURCE_HEAD = 6
|
|
136
|
+
|
|
137
|
+
// 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
|
|
138
|
+
// 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
|
|
139
|
+
const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
|
|
140
|
+
|
|
141
|
+
/** 原因码 → 用户能看懂的一句话。原因码在代码里稳定,人话在这里换。 */
|
|
142
|
+
const PRICING_ERROR_TEXT = {
|
|
143
|
+
'bad-json': 'pricing.json 不是合法 JSON',
|
|
144
|
+
'not-an-object': 'pricing.json 顶层不是对象',
|
|
145
|
+
'no-rates': 'pricing.json 缺少 rates 字段',
|
|
146
|
+
'all-rejected': 'pricing.json 里没有一个完整费率',
|
|
147
|
+
'read-failed': 'pricing.json 读取失败',
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 费率脚注:用户看到这一行,才知道这些金额按什么价、哪天的价算的。
|
|
152
|
+
*
|
|
153
|
+
* 三种状态必须分开显示,尤其第三种:
|
|
154
|
+
* - 自定义生效:说明日期,用户知道自己改过;
|
|
155
|
+
* - 没文件:内置价 + 基准日;
|
|
156
|
+
* - 文件写了但没生效:**必须显形**。静默回退内置价、金额照常显示,
|
|
157
|
+
* 会让人以为自己调过价——这比显示"未知"危险得多。
|
|
158
|
+
*
|
|
159
|
+
* @returns {{text:string, warn:boolean, kind:'builtin'|'file'}}
|
|
160
|
+
*/
|
|
161
|
+
function pricingNoteOf(pricing) {
|
|
162
|
+
if (!pricing || typeof pricing !== 'object') {
|
|
163
|
+
return { text: PRICING_NOTE, banner: null, warn: false, kind: 'builtin' }
|
|
164
|
+
}
|
|
165
|
+
const asOf = typeof pricing.asOf === 'string' && pricing.asOf.length > 0 ? pricing.asOf : null
|
|
166
|
+
const rejected = Array.isArray(pricing.rejected) ? pricing.rejected.length : 0
|
|
167
|
+
|
|
168
|
+
if (pricing.kind === 'file') {
|
|
169
|
+
if (rejected > 0) {
|
|
170
|
+
// 部分被拒:金额里混了两套价,必须顶到显眼位置说清楚,
|
|
171
|
+
// 页脚只留一句来源,避免同一个信息说两遍
|
|
172
|
+
return {
|
|
173
|
+
text: `费率:自定义${asOf !== null ? ` ${asOf}` : ''}`,
|
|
174
|
+
banner: `${rejected} 个模型费率无效,已按内置价处理`,
|
|
175
|
+
warn: true,
|
|
176
|
+
kind: 'file',
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
text: asOf !== null ? `按自定义费率估算 · ${asOf}` : '按自定义费率估算 · 日期未标注',
|
|
181
|
+
banner: null,
|
|
182
|
+
warn: false,
|
|
183
|
+
kind: 'file',
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (typeof pricing.error === 'string' && pricing.error.length > 0) {
|
|
188
|
+
const why = PRICING_ERROR_TEXT[pricing.error] ?? `pricing.json 未生效(${pricing.error})`
|
|
189
|
+
const detail = typeof pricing.detail === 'string' ? `(${pricing.detail})` : ''
|
|
190
|
+
return {
|
|
191
|
+
// 页脚只说"现在按什么价算",为什么没生效放顶部的 banner
|
|
192
|
+
text: asOf !== null ? `费率:内置官方价 ${asOf}` : '费率:内置官方价',
|
|
193
|
+
banner: `${why}${detail},金额仍按内置价计算`,
|
|
194
|
+
warn: true,
|
|
195
|
+
kind: 'builtin',
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
text: asOf !== null ? `按内置官方价估算 · ${asOf}` : PRICING_NOTE,
|
|
201
|
+
banner: null,
|
|
202
|
+
warn: rejected > 0,
|
|
203
|
+
kind: 'builtin',
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 费率异常警示条。为什么放顶部而不是页脚:
|
|
209
|
+
* 页脚 10.5px 灰字等于藏起来。而"我改的价没生效、金额其实是内置价算的"
|
|
210
|
+
* 如果不说清楚,用户会拿着一个自己以为调过的错数字去做判断。
|
|
211
|
+
*/
|
|
212
|
+
function pricingBanner(React, note) {
|
|
213
|
+
if (!note || note.warn !== true || note.banner === null) return null
|
|
214
|
+
const h = React.createElement
|
|
215
|
+
return h(
|
|
216
|
+
'div',
|
|
217
|
+
{
|
|
218
|
+
style: {
|
|
219
|
+
margin: '10px 14px 0',
|
|
220
|
+
padding: '8px 10px',
|
|
221
|
+
background: '#fdf6e7',
|
|
222
|
+
borderLeft: `2px solid ${WARN}`,
|
|
223
|
+
fontSize: 10.5,
|
|
224
|
+
lineHeight: 1.65,
|
|
225
|
+
color: '#8a5a00',
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
note.banner,
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const INK = '#1f2733'
|
|
233
|
+
const INK2 = '#5a6472'
|
|
234
|
+
const INK3 = '#8a93a0'
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 时间一律按**本地时区**显示。
|
|
238
|
+
*
|
|
239
|
+
* 为什么不能直接截 ISO 字符串:快照里的 generatedAt 是 UTC(toISOString),
|
|
240
|
+
* 而明细行的"最近"用的是本地时间戳。同一块面板上"07:35"和"15:35"并存,
|
|
241
|
+
* 用户只会以为数据错了。同一个面板里只能有一套时间口径。
|
|
242
|
+
*/
|
|
243
|
+
function formatLocalTime(value) {
|
|
244
|
+
if (typeof value !== 'string' || value.length === 0) return '—'
|
|
245
|
+
const d = new Date(value)
|
|
246
|
+
if (Number.isNaN(d.getTime())) return '—'
|
|
247
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
248
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
|
|
249
|
+
+ `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function shortId(sessionId) {
|
|
253
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return '—'
|
|
254
|
+
return sessionId.length <= 10 ? sessionId : `${sessionId.slice(0, 6)}…${sessionId.slice(-3)}`
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 金额精度按量级自适应。
|
|
259
|
+
*
|
|
260
|
+
* 为什么不能固定 4 位:单步模型调用常在 1e-5 量级,缓存命中那档一档只有 3.2e-5 元,
|
|
261
|
+
* toFixed(4) 会显示成 ¥0.0000 —— 用户读到的是"这一步没花钱",而那是假信息。
|
|
262
|
+
* 和"未知"一样,显示一个不存在的 0 也是撒谎。
|
|
263
|
+
*/
|
|
264
|
+
function formatAmount(amount, currency) {
|
|
265
|
+
if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
|
|
266
|
+
let digits = 4
|
|
267
|
+
if (amount !== 0 && Math.abs(amount) < 0.001) digits = 6
|
|
268
|
+
// 再小就换科学计数:1e-7 量级写 0.0000001 已经读不清了
|
|
269
|
+
const n = amount !== 0 && Math.abs(amount) < 1e-6 ? amount.toExponential(1) : amount.toFixed(digits)
|
|
270
|
+
return currency === 'CNY' ? `¥${n}` : `${n} ${currency ?? ''}`.trim()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** token 数:千分位,缺失显示 —。 */
|
|
274
|
+
function formatTokens(value) {
|
|
275
|
+
return typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US') : '—'
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 来源桶的显示名。三个保留 key 有业务含义,直接显示原始字符串会让人以为坏了。
|
|
280
|
+
* @param {string} key
|
|
281
|
+
*/
|
|
282
|
+
function sourceLabel(key) {
|
|
283
|
+
if (key === 'shared:unknown') return '多个插件共同(拆不开)'
|
|
284
|
+
if (key === 'unattributed') return '未归因'
|
|
285
|
+
if (key === 'system:compaction') return '上下文压缩'
|
|
286
|
+
return key
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** 时间戳 → HH:MM(面板只到分钟;没有就 —)。 */
|
|
290
|
+
function formatClock(at) {
|
|
291
|
+
if (typeof at !== 'number' || !Number.isFinite(at)) return '—'
|
|
292
|
+
const d = new Date(at)
|
|
293
|
+
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 占比:0.362 → 36.2%。 */
|
|
297
|
+
function formatShare(share) {
|
|
298
|
+
return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function makeLedgerBody(React, fetchView) {
|
|
302
|
+
const h = React.createElement
|
|
303
|
+
|
|
304
|
+
return function LedgerBody(props) {
|
|
305
|
+
const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
|
|
306
|
+
const [view, setView] = React.useState(undefined)
|
|
307
|
+
const [busy, setBusy] = React.useState(false)
|
|
308
|
+
const [expanded, setExpanded] = React.useState(false)
|
|
309
|
+
|
|
310
|
+
const refresh = React.useCallback(async () => {
|
|
311
|
+
if (sessionId === null) return
|
|
312
|
+
setBusy(true)
|
|
313
|
+
try {
|
|
314
|
+
setView(await fetchView(sessionId))
|
|
315
|
+
} finally {
|
|
316
|
+
setBusy(false)
|
|
317
|
+
}
|
|
318
|
+
}, [sessionId])
|
|
319
|
+
|
|
320
|
+
React.useEffect(() => {
|
|
321
|
+
void refresh()
|
|
322
|
+
}, [refresh])
|
|
323
|
+
|
|
324
|
+
const head = h(
|
|
325
|
+
'div',
|
|
326
|
+
{
|
|
327
|
+
style: {
|
|
328
|
+
display: 'flex',
|
|
329
|
+
alignItems: 'center',
|
|
330
|
+
gap: 8,
|
|
331
|
+
padding: '10px 14px 8px',
|
|
332
|
+
borderBottom: '1px solid #eef1f5',
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
h('span', { style: { fontSize: 13, fontWeight: 600, color: INK } }, '账本'),
|
|
336
|
+
h('span', { style: { fontSize: 11, color: INK3 } }, `会话 ${shortId(sessionId)}`),
|
|
337
|
+
h(
|
|
338
|
+
'button',
|
|
339
|
+
{
|
|
340
|
+
type: 'button',
|
|
341
|
+
onClick: () => void refresh(),
|
|
342
|
+
disabled: busy || sessionId === null,
|
|
343
|
+
style: {
|
|
344
|
+
marginLeft: 'auto',
|
|
345
|
+
border: '1px solid #d8dee7',
|
|
346
|
+
background: '#fff',
|
|
347
|
+
borderRadius: 7,
|
|
348
|
+
padding: '3px 9px',
|
|
349
|
+
fontSize: 11.5,
|
|
350
|
+
color: busy ? INK3 : INK2,
|
|
351
|
+
cursor: busy ? 'default' : 'pointer',
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
busy ? '刷新中' : '刷新',
|
|
355
|
+
),
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
// loading:还没跑完第一次
|
|
359
|
+
if (view === undefined) {
|
|
360
|
+
return h('div', null, head, h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, '正在读取…'))
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// 通道或解析出错
|
|
364
|
+
if (view !== null && typeof view.error === 'string') {
|
|
365
|
+
return h(
|
|
366
|
+
'div',
|
|
367
|
+
null,
|
|
368
|
+
head,
|
|
369
|
+
h('p', { style: { margin: '12px 14px', fontSize: 12, lineHeight: 1.7, color: '#a03a2a' } }, `读取失败:${view.error}`),
|
|
370
|
+
h(
|
|
371
|
+
'p',
|
|
372
|
+
{ style: { margin: '0 14px 12px', fontSize: 11.5, lineHeight: 1.7, color: INK3 } },
|
|
373
|
+
'通道细节见 docs/spikes.md 的 C-3 节。',
|
|
374
|
+
),
|
|
375
|
+
)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// 还没有快照:Host 未开启或尚未落盘(这不是错误)
|
|
379
|
+
if (view === null) {
|
|
380
|
+
return h(
|
|
381
|
+
'div',
|
|
382
|
+
null,
|
|
383
|
+
head,
|
|
384
|
+
h(
|
|
385
|
+
'div',
|
|
386
|
+
{ style: { padding: '12px 14px', fontSize: 12, lineHeight: 1.75, color: INK2 } },
|
|
387
|
+
h('p', { style: { margin: 0 } }, '这个会话还没有成本快照。'),
|
|
388
|
+
h(
|
|
389
|
+
'p',
|
|
390
|
+
{ style: { margin: '8px 0 0', color: INK3, fontSize: 11.5 } },
|
|
391
|
+
'在插件配置里打开 panel.enabled,Host 会按 panel.intervalMs 把只读快照写进工作区;',
|
|
392
|
+
'也可以先在对话里用 ledger_query 查。',
|
|
393
|
+
),
|
|
394
|
+
),
|
|
395
|
+
)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// 来源多于 6 个时才能展开:展开只是"多显示几行",不做分页、不过滤
|
|
399
|
+
return renderPayload(React, view, sessionId, head, { expanded, onToggleSources: () => setExpanded((v) => !v) })
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** 副标题:条数 + 未归因条数(未归因来自来源桶,不是"金额未知") */
|
|
404
|
+
function summaryOf(totals, list) {
|
|
405
|
+
const entries = totals.entries ?? 0
|
|
406
|
+
const unattributed = list.find((item) => item?.plugin === 'unattributed')
|
|
407
|
+
const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
|
|
408
|
+
return lost === null ? `${entries} 条` : `${entries} 条 · 未归因 ${lost}`
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
|
|
412
|
+
function callsLeftOf(budget) {
|
|
413
|
+
const left = budget?.callsLeft
|
|
414
|
+
if (typeof left !== 'number' || !Number.isFinite(left)) return ''
|
|
415
|
+
// 0 次不能写成"还可约 0 次":读起来像还能问,实际是已经问不起了
|
|
416
|
+
return left === 0 ? ' · 余量不足一问' : ` · 还可约 ${left} 次`
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** 命中率是"输入里走了缓存的比例",分母不含缓存写 */
|
|
420
|
+
function hitRateOf(rate) {
|
|
421
|
+
return typeof rate === 'number' && Number.isFinite(rate) ? ` · 占输入 ${Math.round(rate * 100)}%` : ''
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 空态:装完第一次打开右栏看到的就是这一屏。
|
|
426
|
+
*
|
|
427
|
+
* 为什么不能沿用主面板渲染:零条目时主面板会显示一个大「—」加一排空区块,
|
|
428
|
+
* 用户第一反应是"这东西坏了"。空态要回答三个问题——这是什么、为什么还没数据、
|
|
429
|
+
* 我该做什么——而不是把一张空表摆出来。
|
|
430
|
+
*
|
|
431
|
+
* 也不显示"¥0.0000":0 元的意思是"确认没花钱",而"还没有数据"不是那个意思。
|
|
432
|
+
* 这两者混淆是成本类产品最常见的错误。
|
|
433
|
+
*/
|
|
434
|
+
function renderEmptyState(React, view, sessionId, head, options = {}) {
|
|
435
|
+
const h = React.createElement
|
|
436
|
+
const note = pricingNoteOf(view?.pricing)
|
|
437
|
+
const item = (title, detail) =>
|
|
438
|
+
h(
|
|
439
|
+
'div',
|
|
440
|
+
{ style: { marginTop: 8 } },
|
|
441
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: INK2 } }, title),
|
|
442
|
+
h('div', { style: { fontSize: 10.5, lineHeight: 1.65, color: INK3, marginTop: 2 } }, detail),
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
return h(
|
|
446
|
+
'div',
|
|
447
|
+
null,
|
|
448
|
+
head,
|
|
449
|
+
pricingBanner(React, note),
|
|
450
|
+
h(
|
|
451
|
+
'div',
|
|
452
|
+
{ style: { padding: '14px 14px 6px' } },
|
|
453
|
+
h('div', { style: { fontSize: 16, fontWeight: 600, color: INK } }, '本会话还没有模型调用'),
|
|
454
|
+
h(
|
|
455
|
+
'div',
|
|
456
|
+
{ style: { fontSize: 11.5, lineHeight: 1.7, color: INK2, marginTop: 6 } },
|
|
457
|
+
'发一条消息,这里就开始记账。只读观测,不改你的请求。',
|
|
458
|
+
),
|
|
459
|
+
h('div', { style: { height: 1, background: '#e8ebef', margin: '12px 0 10px' } }),
|
|
460
|
+
h('div', { style: { fontSize: 10.5, color: INK3, letterSpacing: 0.3 } }, '会记什么'),
|
|
461
|
+
item('每步花多少', '未命中输入 / 缓存命中 / 输出 分开计价,不用平均价套总数'),
|
|
462
|
+
item('谁花的', '按同轮上一步的工具调用归因,跨轮不硬猜'),
|
|
463
|
+
item('还能问几次', '按预算与均价估算;费率未知的条目不进均价'),
|
|
464
|
+
h(
|
|
465
|
+
'div',
|
|
466
|
+
{
|
|
467
|
+
style: {
|
|
468
|
+
marginTop: 14,
|
|
469
|
+
padding: '8px 10px',
|
|
470
|
+
background: '#f6f7f9',
|
|
471
|
+
borderLeft: `2px solid ${INK3}`,
|
|
472
|
+
fontSize: 10.5,
|
|
473
|
+
lineHeight: 1.7,
|
|
474
|
+
color: INK2,
|
|
475
|
+
},
|
|
476
|
+
},
|
|
477
|
+
'一直为空?面板靠 Host 落盘快照取数,需要在 profile 里打开 ',
|
|
478
|
+
h('span', { style: { color: INK, fontWeight: 600 } }, 'panel.enabled'),
|
|
479
|
+
'。',
|
|
480
|
+
),
|
|
481
|
+
),
|
|
482
|
+
h(
|
|
483
|
+
'div',
|
|
484
|
+
{ style: { padding: '4px 14px 12px', fontSize: 10.5, color: note.warn ? WARN : INK3 } },
|
|
485
|
+
note.text,
|
|
486
|
+
),
|
|
186
487
|
)
|
|
187
|
-
|
|
188
|
-
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function renderPayload(React, view, sessionId, head, options = {}) {
|
|
491
|
+
const expanded = options.expanded === true
|
|
492
|
+
const note = pricingNoteOf(view?.pricing)
|
|
493
|
+
const h = React.createElement
|
|
494
|
+
const totals = view.totals ?? {}
|
|
495
|
+
const peak = view.peak ?? null
|
|
496
|
+
const unknownCount = typeof view.totals?.cost?.unknownEntries === 'number' ? view.totals.cost.unknownEntries : 0
|
|
497
|
+
const cost = totals.cost ?? {}
|
|
498
|
+
const tokens = totals.tokens ?? null
|
|
499
|
+
const parts = cost.parts ?? null
|
|
500
|
+
const list = Array.isArray(view.sources) && view.sources.length > 0 ? view.sources : view.topSources ?? []
|
|
501
|
+
const recent = Array.isArray(view.recent) ? view.recent.filter((item) => item !== null) : []
|
|
502
|
+
const others = Array.isArray(view.overview)
|
|
503
|
+
? view.overview.filter((row) => row !== null && row?.sessionId !== undefined && row.sessionId !== sessionId)
|
|
504
|
+
: []
|
|
505
|
+
|
|
506
|
+
// 零条目走空态。判据用 entries(账本累计条目数),不用 cost.amount:
|
|
507
|
+
// 金额为 null 可能是"有调用但费率未知",那不是空会话
|
|
508
|
+
const entryCount = typeof totals?.entries === 'number' ? totals.entries : recent.length
|
|
509
|
+
if (entryCount === 0) return renderEmptyState(React, view, sessionId, head, options)
|
|
510
|
+
|
|
511
|
+
return h(
|
|
512
|
+
'div',
|
|
513
|
+
null,
|
|
514
|
+
head,
|
|
515
|
+
pricingBanner(React, note),
|
|
516
|
+
// 合计
|
|
517
|
+
h(
|
|
518
|
+
'div',
|
|
519
|
+
{ style: { padding: '12px 14px 6px' } },
|
|
520
|
+
h(
|
|
521
|
+
'div',
|
|
522
|
+
{ style: { display: 'flex', alignItems: 'baseline', gap: 8 } },
|
|
523
|
+
h(
|
|
524
|
+
'span',
|
|
525
|
+
{ style: { fontSize: 22, fontWeight: 600, color: INK, fontVariantNumeric: 'tabular-nums' } },
|
|
526
|
+
formatAmount(cost.amount, cost.currency),
|
|
527
|
+
),
|
|
528
|
+
h('span', { style: { fontSize: 11, color: INK3 } }, summaryOf(totals, list)),
|
|
529
|
+
),
|
|
530
|
+
// 合计偏低必须说:有未知费率的条目时,这个数字就是下限,不能摆得像确定值
|
|
531
|
+
unknownCount > 0
|
|
532
|
+
? h(
|
|
533
|
+
'div',
|
|
534
|
+
{ style: { marginTop: 4, fontSize: 10.5, lineHeight: 1.6, color: WARN } },
|
|
535
|
+
`其中 ${unknownCount} 条费率未知,合计偏低`,
|
|
536
|
+
)
|
|
537
|
+
: null,
|
|
538
|
+
// 收益行:账本里唯一能严格算出的"省了多少钱"(两个单价都在价表里,差额确定)。
|
|
539
|
+
// 位置刻意紧贴总支出——商业化上,客户先看见"省了多少"才会觉得这个插件有价值。
|
|
540
|
+
savedOf(view) === null
|
|
541
|
+
? null
|
|
542
|
+
: h(
|
|
543
|
+
'div',
|
|
544
|
+
{ style: { marginTop: 4, fontSize: 10.5, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
|
|
545
|
+
`缓存命中已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
|
|
546
|
+
typeof view.totals.savedShare === 'number'
|
|
547
|
+
? ` · 占应花 ${formatShare(view.totals.savedShare)}`
|
|
548
|
+
: ''
|
|
549
|
+
}`,
|
|
550
|
+
),
|
|
551
|
+
),
|
|
552
|
+
// 预算条:只有配置了 limit 才画,未计价时不假装花了 0
|
|
553
|
+
view.budget !== null && view.budget !== undefined
|
|
554
|
+
? h(
|
|
555
|
+
'div',
|
|
556
|
+
{ style: { padding: '0 14px 10px' } },
|
|
557
|
+
h(
|
|
558
|
+
'div',
|
|
559
|
+
{ style: { display: 'flex', justifyContent: 'space-between', fontSize: 11, color: INK3, marginBottom: 4 } },
|
|
560
|
+
h('span', null, `预算 ${formatAmount(view.budget.limit, view.budget.currency)}`),
|
|
561
|
+
h(
|
|
562
|
+
'span',
|
|
563
|
+
null,
|
|
564
|
+
view.budget.used === null
|
|
565
|
+
? '未计价'
|
|
566
|
+
: `已用 ${Math.round((view.budget.ratio ?? 0) * 100)}%${callsLeftOf(view.budget)}`,
|
|
567
|
+
),
|
|
568
|
+
),
|
|
569
|
+
h(
|
|
570
|
+
'div',
|
|
571
|
+
{ style: { height: 4, borderRadius: 2, background: '#eef1f5', overflow: 'hidden' } },
|
|
572
|
+
h('div', {
|
|
573
|
+
style: {
|
|
574
|
+
height: '100%',
|
|
575
|
+
width: `${Math.round((view.budget.ratio ?? 0) * 100)}%`,
|
|
576
|
+
background: (view.budget.ratio ?? 0) >= 0.8 ? '#c98a12' : '#2f7d64',
|
|
577
|
+
},
|
|
578
|
+
}),
|
|
579
|
+
),
|
|
580
|
+
)
|
|
581
|
+
: null,
|
|
582
|
+
// token 四档
|
|
583
|
+
h(
|
|
584
|
+
'div',
|
|
585
|
+
{ style: { padding: '4px 14px 10px' } },
|
|
586
|
+
!tokens
|
|
587
|
+
? h('p', { style: { margin: 0, fontSize: 11.5, color: INK3 } }, '该会话没有可用的 token 计数')
|
|
588
|
+
: h(
|
|
589
|
+
'div',
|
|
590
|
+
{ style: { borderTop: '1px solid #eef1f5', paddingTop: 6 } },
|
|
591
|
+
// 金额只由 Host 给(pricing.parts);没有已知条目时整列给 —,不显示 0
|
|
592
|
+
rowOf(React, '未缓存输入', formatAmount(parts?.input, cost.currency), `${formatTokens(tokens.input)} tok`),
|
|
593
|
+
rowOf(
|
|
594
|
+
React,
|
|
595
|
+
'缓存命中',
|
|
596
|
+
formatAmount(parts?.cacheRead, cost.currency),
|
|
597
|
+
`${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
|
|
598
|
+
),
|
|
599
|
+
rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`),
|
|
600
|
+
rowOf(React, '输出', formatAmount(parts?.output, cost.currency), `${formatTokens(tokens.output)} tok · 含 reasoning`),
|
|
601
|
+
),
|
|
602
|
+
),
|
|
603
|
+
// 来源
|
|
604
|
+
h(
|
|
605
|
+
'div',
|
|
606
|
+
{ style: { padding: '0 14px 10px' } },
|
|
607
|
+
h(
|
|
608
|
+
'div',
|
|
609
|
+
{ style: { display: 'flex', alignItems: 'center', gap: 6, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
|
|
610
|
+
h('span', { style: { fontSize: 12, fontWeight: 600, color: INK } }, '谁花的'),
|
|
611
|
+
h(
|
|
612
|
+
'span',
|
|
613
|
+
{ style: { display: 'flex', alignItems: 'baseline', gap: 6 } },
|
|
614
|
+
h(
|
|
615
|
+
'span',
|
|
616
|
+
{ style: { fontSize: 10.5, color: INK3 } },
|
|
617
|
+
view.sourceCount === null || view.sourceCount === undefined ? '' : `共 ${view.sourceCount} 个来源`,
|
|
618
|
+
),
|
|
619
|
+
// 只在前 6 条放不下时才给按钮:按钮一出来就说明"你少看了几条"
|
|
620
|
+
list.length > SOURCE_HEAD
|
|
621
|
+
? h(
|
|
622
|
+
'button',
|
|
623
|
+
{
|
|
624
|
+
type: 'button',
|
|
625
|
+
onClick: options.onToggleSources,
|
|
626
|
+
style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize: 10.5, color: '#2f7d64' },
|
|
627
|
+
},
|
|
628
|
+
expanded ? '收起' : `展开全部 ${list.length}`,
|
|
629
|
+
)
|
|
630
|
+
: null,
|
|
631
|
+
),
|
|
632
|
+
),
|
|
633
|
+
list.length === 0
|
|
634
|
+
? h('p', { style: { margin: 0, fontSize: 11.5, color: INK3 } }, '还没有可归因的来源')
|
|
635
|
+
: (expanded ? list : list.slice(0, SOURCE_HEAD)).map((source, index) =>
|
|
636
|
+
h(
|
|
637
|
+
'div',
|
|
638
|
+
{
|
|
639
|
+
key: `${source.plugin ?? 'unknown'}-${index}`,
|
|
640
|
+
style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '4px 0' },
|
|
641
|
+
},
|
|
642
|
+
h(
|
|
643
|
+
'span',
|
|
644
|
+
{ style: { fontSize: 12, color: INK2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
|
|
645
|
+
sourceLabel(source.plugin ?? 'unattributed'),
|
|
646
|
+
),
|
|
647
|
+
h(
|
|
648
|
+
'span',
|
|
649
|
+
{ style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
650
|
+
`${formatAmount(source.amount, cost.currency)} ${formatShare(source.share)}`,
|
|
651
|
+
),
|
|
652
|
+
),
|
|
653
|
+
),
|
|
654
|
+
view.truncated === true
|
|
655
|
+
? h('p', { style: { margin: '6px 0 0', fontSize: 11, color: INK3 } }, '明细已截断,只保留合计与 Top 来源')
|
|
656
|
+
: null,
|
|
657
|
+
),
|
|
658
|
+
// 明细(表格视图):最近几条,金额未知时显示原因而不是 0
|
|
659
|
+
recent.length > 0
|
|
660
|
+
? h(
|
|
661
|
+
'div',
|
|
662
|
+
{ style: { padding: '0 14px 8px' } },
|
|
663
|
+
h(
|
|
664
|
+
'div',
|
|
665
|
+
{ style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
|
|
666
|
+
h('span', { style: { fontSize: 12, fontWeight: 600, color: INK } }, '最近'),
|
|
667
|
+
peak === null
|
|
668
|
+
? null
|
|
669
|
+
: h(
|
|
670
|
+
'span',
|
|
671
|
+
{ style: { fontSize: 10.5, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
672
|
+
`最贵一步 ${formatAmount(peak.amount, cost.currency)}`,
|
|
673
|
+
),
|
|
674
|
+
),
|
|
675
|
+
recent.slice(0, 5).map((item, index) =>
|
|
676
|
+
h(
|
|
677
|
+
'div',
|
|
678
|
+
{ key: `r-${index}`, style: { padding: '4px 0' } },
|
|
679
|
+
h(
|
|
680
|
+
'div',
|
|
681
|
+
{ style: { display: 'flex', justifyContent: 'space-between', gap: 8 } },
|
|
682
|
+
h(
|
|
683
|
+
'span',
|
|
684
|
+
{ style: { fontSize: 11.5, color: INK2, fontVariantNumeric: 'tabular-nums' } },
|
|
685
|
+
formatClock(item.at),
|
|
686
|
+
h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 6 } }, item.kind === 'compaction' ? '压缩' : '模型'),
|
|
687
|
+
// 轮次:治理时要能定位到"哪一问最贵",时间不够用
|
|
688
|
+
typeof item.turn === 'number'
|
|
689
|
+
? h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 6 } }, `T${item.turn}·S${item.step ?? '—'}`)
|
|
690
|
+
: null,
|
|
691
|
+
),
|
|
692
|
+
h(
|
|
693
|
+
'span',
|
|
694
|
+
{ style: { fontSize: 11.5, color: item.amount === null ? INK3 : INK, fontVariantNumeric: 'tabular-nums' } },
|
|
695
|
+
item.amount === null ? `— ${item.unknownReason ?? ''}`.trim() : formatAmount(item.amount, cost.currency),
|
|
696
|
+
),
|
|
697
|
+
),
|
|
698
|
+
h(
|
|
699
|
+
'div',
|
|
700
|
+
{ style: { fontSize: 10.5, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
|
|
701
|
+
// 工具结果的体量排在最前:它是"这一步为什么贵"的直接解释,
|
|
702
|
+
// 归属和路由被省略号截掉了也不影响判断
|
|
703
|
+
// 压缩:前值 → 下一步的值;省下的量用水绿标出来,它是一笔"收益"不是支出
|
|
704
|
+
item.contextBeforeTokens === null || item.contextBeforeTokens === undefined
|
|
705
|
+
? null
|
|
706
|
+
: h(
|
|
707
|
+
'span',
|
|
708
|
+
{ style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
|
|
709
|
+
// 省下的量记在"压缩后的第一条调用"上;这条只有前值,就别画一个悬空的箭头
|
|
710
|
+
`压缩前 ${formatContextTokens(item.contextBeforeTokens)}`,
|
|
711
|
+
),
|
|
712
|
+
item.contextSavedTokens === null || item.contextSavedTokens === undefined
|
|
713
|
+
? null
|
|
714
|
+
: h(
|
|
715
|
+
'span',
|
|
716
|
+
{ style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
|
|
717
|
+
`↓省 ${formatContextTokens(item.contextSavedTokens)}`,
|
|
718
|
+
),
|
|
719
|
+
item.contextChars === null || item.contextChars === undefined
|
|
720
|
+
? null
|
|
721
|
+
: h(
|
|
722
|
+
'span',
|
|
723
|
+
{ style: { color: item.contextChars >= 10_000 ? WARN : INK3, marginRight: 6 } },
|
|
724
|
+
`↑${formatChars(item.contextChars)}`,
|
|
725
|
+
),
|
|
726
|
+
routeTextOf(item),
|
|
727
|
+
tokensTotal(item.tokens) === null ? '' : ` · ${formatTokens(tokensTotal(item.tokens))} tok`,
|
|
728
|
+
item.plugin === null ? '' : ` · ${sourceLabel(item.plugin)}`,
|
|
729
|
+
),
|
|
730
|
+
),
|
|
731
|
+
),
|
|
732
|
+
)
|
|
733
|
+
: null,
|
|
734
|
+
// 会话对比:只给其他会话,自己已经在顶部
|
|
735
|
+
others.length > 0
|
|
736
|
+
? h(
|
|
737
|
+
'div',
|
|
738
|
+
{ style: { padding: '0 14px 8px' } },
|
|
739
|
+
h(
|
|
740
|
+
'div',
|
|
741
|
+
{ style: { fontSize: 12, fontWeight: 600, color: INK, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
|
|
742
|
+
'其他会话',
|
|
743
|
+
),
|
|
744
|
+
others.slice(0, 3).map((row, index) =>
|
|
745
|
+
h(
|
|
746
|
+
'div',
|
|
747
|
+
{
|
|
748
|
+
key: `o-${index}`,
|
|
749
|
+
style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '3px 0', fontSize: 11.5 },
|
|
750
|
+
},
|
|
751
|
+
h('span', { style: { color: INK2 } }, shortId(row.sessionId)),
|
|
752
|
+
h(
|
|
753
|
+
'span',
|
|
754
|
+
{ style: { color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
755
|
+
`${formatAmount(row.amount, row.currency ?? cost.currency)} · ${row.entries ?? 0} 条`,
|
|
756
|
+
),
|
|
757
|
+
),
|
|
758
|
+
),
|
|
759
|
+
)
|
|
760
|
+
: null,
|
|
761
|
+
// 页脚
|
|
762
|
+
h(
|
|
763
|
+
'div',
|
|
764
|
+
{ style: { padding: '6px 14px 12px', fontSize: 10.5, color: INK3 } },
|
|
765
|
+
`快照生成于 ${formatLocalTime(view.generatedAt)}`,
|
|
766
|
+
),
|
|
767
|
+
h(
|
|
768
|
+
'div',
|
|
769
|
+
{
|
|
770
|
+
// 费率脚注:自定义生效用正文色、无效用警示色,绝不与"内置价"混成一色
|
|
771
|
+
style: { padding: '0 14px 12px', fontSize: 10.5, color: note.warn ? WARN : INK3 },
|
|
772
|
+
},
|
|
773
|
+
note.text,
|
|
774
|
+
),
|
|
189
775
|
)
|
|
190
776
|
}
|
|
191
|
-
|
|
777
|
+
|
|
778
|
+
function rowOf(React, label, value, hint) {
|
|
779
|
+
const h = React.createElement
|
|
780
|
+
return h(
|
|
781
|
+
'div',
|
|
782
|
+
{ style: { display: 'flex', justifyContent: 'space-between', gap: 10, padding: '5px 0' } },
|
|
783
|
+
h(
|
|
784
|
+
'span',
|
|
785
|
+
{ style: { fontSize: 12, color: INK2 } },
|
|
786
|
+
label,
|
|
787
|
+
hint === undefined ? null : h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 4 } }, hint),
|
|
788
|
+
),
|
|
789
|
+
h('span', { style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums' } }, value),
|
|
790
|
+
)
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function makeLedgerTitle(React) {
|
|
794
|
+
const h = React.createElement
|
|
795
|
+
return function LedgerTitle() {
|
|
796
|
+
return h('span', null, '账本')
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
//#endregion
|
|
192
800
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
801
|
+
//#region client.src.js
|
|
802
|
+
/**
|
|
803
|
+
* @lingda-ai/ledger —— 浏览器半(右侧栏 tab)**源码**
|
|
804
|
+
*
|
|
805
|
+
* 注意:本文件不是发布产物。发布入口是 `lib/client.js`,由
|
|
806
|
+
* `node scripts/build-client.mjs` 从本文件 + panel-view.js + panel-path.js +
|
|
807
|
+
* tool-size.js 打包成宿主要求的 loader 形态(`window.__ModuleLoader__.load`)。
|
|
808
|
+
* 手工改 `lib/client.js` 会在下次构建时被覆盖。
|
|
809
|
+
*
|
|
810
|
+
* 为什么必须有这一步(真机崩溃换来的):
|
|
811
|
+
* dsh-client-modules 的 Node 半侧把每个包的 `client.js` **原样拼接**成一个
|
|
812
|
+
* combo 脚本(`/plugins/??a/client.js,b/client.js&rev=…`),浏览器按 classic
|
|
813
|
+
* script 解析。所以客户端入口里不能出现任何 `import` / `export` 语句,
|
|
814
|
+
* 否则整页抛 `SyntaxError: Cannot use import statement outside a module`,
|
|
815
|
+
* 连宿主一起带崩。0.1.4 就是直接发布了 ESM 源码,一重启就崩。
|
|
816
|
+
*
|
|
817
|
+
* 已核实的契约(源码逐条对过,勿凭记忆改):
|
|
818
|
+
*
|
|
819
|
+
* 1) 类型登记 @ dsh-client-ui-sidebar-right
|
|
820
|
+
* ctx.sidebarRightTabs.register(definition) → disposer
|
|
821
|
+
* definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
|
|
822
|
+
* guide entry: { id, order, title(), description?(), icon?, commandId? }
|
|
823
|
+
*
|
|
824
|
+
* 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
|
|
825
|
+
* - 'sidebar.right.pane.tab'
|
|
826
|
+
* - 'sidebar.right.pane.tab.title'
|
|
827
|
+
* 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
|
|
828
|
+
* ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
|
|
829
|
+
*
|
|
830
|
+
* 3) React 来自宿主模块表(`require("react")`)。本文件在 Node 侧(单测、脚本)
|
|
831
|
+
* 走动态 import('react');打进 client.js 后由构建产物通过 __setReactLoader
|
|
832
|
+
* 注入 factory 拿到的 require。两条路都失败时退回"只登记类型、不挂正文"。
|
|
833
|
+
*
|
|
834
|
+
* 取数通道(已接,细节见 docs/spikes.md C-3):
|
|
835
|
+
* 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
|
|
836
|
+
* 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
|
|
837
|
+
* 接入点集中在 createFetchView() 一处。
|
|
838
|
+
*
|
|
839
|
+
* 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
|
|
840
|
+
*/
|
|
841
|
+
|
|
842
|
+
/** 本实现的身份,也是两个 keyed seat 的 key。 */
|
|
843
|
+
const LEDGER_ID = '@lingda-ai/ledger'
|
|
844
|
+
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
845
|
+
const LEDGER_KIND = 'ledger.cost'
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
|
|
849
|
+
*
|
|
850
|
+
* 这条**必须声明**。cordis 的 ctx 是代理:访问未声明的服务属性会直接抛
|
|
851
|
+
* `cannot get property "sidebarRightTabs" without inject`,而且是在 apply 里抛,
|
|
852
|
+
* 等同于让宿主启动失败(0.1.5 重启即崩就是这么来的——之前只写了 package.json 的
|
|
853
|
+
* dsh.client.inject,那是"先加载哪个包",不是"这个插件依赖哪个服务",两回事)。
|
|
854
|
+
*/
|
|
855
|
+
const inject = ['sidebarRightTabs']
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* 取可选服务。不能写成 `ctx.xxx`——没在 inject 里声明的服务,属性访问会抛。
|
|
859
|
+
* 宿主提供了 `ctx.get(name)` 这条不受 inject 约束的通道;Node 侧单测的假 ctx
|
|
860
|
+
* 没有 get,退回普通属性读。
|
|
861
|
+
* @param {any} ctx
|
|
862
|
+
* @param {string} name
|
|
863
|
+
*/
|
|
864
|
+
function optionalService(ctx, name) {
|
|
865
|
+
if (typeof ctx?.get === 'function') {
|
|
866
|
+
try {
|
|
867
|
+
return ctx.get(name) ?? null
|
|
868
|
+
} catch {
|
|
869
|
+
return null
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
try {
|
|
873
|
+
return ctx?.[name] ?? null
|
|
874
|
+
} catch {
|
|
875
|
+
return null
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** 面板用到的 seat 名,抽出来避免字符串散落。 */
|
|
880
|
+
const SEAT_BODY = 'sidebar.right.pane.tab'
|
|
881
|
+
const SEAT_TITLE = 'sidebar.right.pane.tab.title'
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* React 取用方式:默认走动态 import(Node 侧单测/脚本)。
|
|
885
|
+
* 构建成 client.js 后,产物在 factory 里用宿主模块表的 `require('react')` 覆盖它——
|
|
886
|
+
* 浏览器里没有裸 `import('react')` 能解析的相对路径,动态 import 必然失败。
|
|
887
|
+
* @type {() => Promise<any>}
|
|
888
|
+
*/
|
|
889
|
+
// 产物里没有裸 import 可解析;由 wrapper 的 __setReactLoader 覆盖
|
|
890
|
+
let reactLoader = async () => null
|
|
891
|
+
|
|
892
|
+
/** 只给构建产物用:把 React 换成宿主模块表给的 require。 */
|
|
893
|
+
function __setReactLoader(fn) {
|
|
894
|
+
if (typeof fn === 'function') reactLoader = fn
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
/** 会话 id 太长时截断成 chip 能放下的样子。 */
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
|
|
905
|
+
*
|
|
906
|
+
* 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
|
|
907
|
+
* list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
|
|
908
|
+
* stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
|
|
909
|
+
* read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
|
|
910
|
+
* 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
|
|
911
|
+
* 先用相对路径 stat 换出 absolutePath,再 read。
|
|
912
|
+
*
|
|
913
|
+
* 返回形状:
|
|
914
|
+
* null → 还没有快照(Host 未开启或尚未落盘)
|
|
915
|
+
* { error: '...' } → 通道/解析失败,面板显示原因
|
|
916
|
+
* payload → Host 写的 JSON(version / totals / topSources / sources)
|
|
917
|
+
*
|
|
918
|
+
* @param {any} ctx - 浏览器侧 cordis 上下文
|
|
919
|
+
* @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
|
|
920
|
+
*/
|
|
921
|
+
function createFetchView(ctx) {
|
|
922
|
+
return async function fetchView(sessionId, opts = {}) {
|
|
923
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return null
|
|
924
|
+
const files = optionalService(ctx, 'remote')?.workspaceFiles
|
|
925
|
+
if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
|
|
926
|
+
return { error: '宿主未提供 workspaceFiles 通道' }
|
|
927
|
+
}
|
|
928
|
+
const relative = panelRelativePath(sessionId)
|
|
929
|
+
|
|
930
|
+
let stat
|
|
931
|
+
try {
|
|
932
|
+
stat = await files.stat(sessionId, relative, opts.signal)
|
|
933
|
+
} catch (error) {
|
|
934
|
+
return { error: stringifyError(error) }
|
|
935
|
+
}
|
|
936
|
+
if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
|
|
937
|
+
const absolutePath = stat.value?.absolutePath
|
|
938
|
+
if (typeof absolutePath !== 'string') return null
|
|
939
|
+
// 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
|
|
940
|
+
const bytes = stat.value?.bytes
|
|
941
|
+
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
942
|
+
|
|
943
|
+
let page
|
|
944
|
+
try {
|
|
945
|
+
page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
|
|
946
|
+
} catch (error) {
|
|
947
|
+
return { error: stringifyError(error) }
|
|
948
|
+
}
|
|
949
|
+
if (!page?.ok) return { error: '读取快照失败' }
|
|
950
|
+
const text = page.value?.text
|
|
951
|
+
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
952
|
+
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
953
|
+
|
|
954
|
+
try {
|
|
955
|
+
const parsed = JSON.parse(text)
|
|
956
|
+
return parsed && typeof parsed === 'object' ? parsed : { error: '快照格式无法识别' }
|
|
957
|
+
} catch {
|
|
958
|
+
return { error: '快照不是合法 JSON(可能正写到一半)' }
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/** 把任意抛出物变成一句话。 */
|
|
964
|
+
function stringifyError(error) {
|
|
965
|
+
if (error instanceof Error) return error.message
|
|
966
|
+
if (typeof error === 'string') return error
|
|
967
|
+
return '未知错误'
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/** CNY 用 ¥,其它币种保留原符号 + 代码。 */
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* 正文组件。用 createElement 而不引 JSX,避免给独立仓库引入构建链。
|
|
974
|
+
* @param {any} React - 宿主的 React
|
|
975
|
+
* @param {(sid: string, opts?: object) => Promise<any>} fetchView
|
|
976
|
+
*/
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* 渲染已取到的快照。
|
|
980
|
+
*
|
|
981
|
+
* 从组件里抽出来是为了可测:SSR 不跑 effect,组件首帧永远是"读取中",
|
|
982
|
+
* 只有把渲染当纯函数,才能在测试里断言四档金额、明细、预算条真的画出来了。
|
|
983
|
+
* @param {any} React
|
|
984
|
+
* @param {any} view - 快照 payload
|
|
985
|
+
* @param {string|null} sessionId
|
|
986
|
+
* @param {any} head - 已在组件侧建好的头部(含刷新按钮)
|
|
987
|
+
*/
|
|
988
|
+
|
|
989
|
+
/** 一行 label / value,两个渲染入口共用。 */
|
|
990
|
+
|
|
991
|
+
/** 标题组件:chip 上的实时文案(不做金额,避免每次事件都改布局)。 */
|
|
992
|
+
|
|
993
|
+
/** @param {import('@deepseek-ai/cordis').Context} ctx */
|
|
994
|
+
async function apply(ctx) {
|
|
995
|
+
const tabs = ctx.sidebarRightTabs
|
|
996
|
+
if (!tabs || typeof tabs.register !== 'function') return
|
|
997
|
+
|
|
998
|
+
const definition = {
|
|
999
|
+
id: LEDGER_ID,
|
|
1000
|
+
kind: LEDGER_KIND,
|
|
1001
|
+
title: () => '账本',
|
|
1002
|
+
priority: 'extension',
|
|
1003
|
+
guide: [
|
|
1004
|
+
{
|
|
1005
|
+
id: 'ledger.cost',
|
|
1006
|
+
order: 10,
|
|
1007
|
+
title: () => '账本',
|
|
1008
|
+
description: () => '本会话的 token 用量与成本归因',
|
|
1009
|
+
},
|
|
1010
|
+
],
|
|
1011
|
+
// 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
|
|
1012
|
+
keepMounted: true,
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// 客户端契约里除 sidebarRightTabs 之外的部分都没被真机证实过。
|
|
1016
|
+
// 这是一个 UI 插件:任何一处契约偏差都应该退化成"没有面板",而不是让宿主起不来。
|
|
1017
|
+
let disposeTab = null
|
|
1018
|
+
try {
|
|
1019
|
+
disposeTab = tabs.register(definition)
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
console.warn('[ledger] 右栏 tab 登记失败,面板不出现(宿主其它功能不受影响):', error)
|
|
1022
|
+
return
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
const sidebarRight = optionalService(ctx, 'sidebarRight')
|
|
1026
|
+
let disposeClose = null
|
|
1027
|
+
if (typeof sidebarRight?.registerCloseHandler === 'function') {
|
|
1028
|
+
try {
|
|
1029
|
+
disposeClose = sidebarRight.registerCloseHandler(LEDGER_KIND, () => {})
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
console.warn('[ledger] registerCloseHandler 失败:', error)
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// 正文与标题:宿主把 seat 声明在 sidebar-right 里,先 inject 再 register
|
|
1036
|
+
let disposeBody = null
|
|
1037
|
+
let disposeTitle = null
|
|
1038
|
+
const slots = optionalService(ctx, 'slots')
|
|
1039
|
+
if (typeof slots?.inject === 'function' && typeof slots.register === 'function') {
|
|
1040
|
+
let React = null
|
|
1041
|
+
try {
|
|
1042
|
+
React = await reactLoader()
|
|
1043
|
+
} catch {
|
|
1044
|
+
React = null // 宿主没给 React:保持无正文的降级态
|
|
1045
|
+
}
|
|
1046
|
+
if (React !== null) {
|
|
1047
|
+
try {
|
|
1048
|
+
const fetchView = createFetchView(ctx)
|
|
1049
|
+
disposeBody = slots.inject(SEAT_BODY, () =>
|
|
1050
|
+
slots.register({ name: SEAT_BODY, key: LEDGER_ID }, makeLedgerBody(React, fetchView)),
|
|
1051
|
+
)
|
|
1052
|
+
disposeTitle = slots.inject(SEAT_TITLE, () =>
|
|
1053
|
+
slots.register({ name: SEAT_TITLE, key: LEDGER_ID }, makeLedgerTitle(React)),
|
|
1054
|
+
)
|
|
1055
|
+
} catch (error) {
|
|
1056
|
+
// seat 名对不上、权限不足、host 版本差异:只丢面板正文,tab 仍在
|
|
1057
|
+
console.warn('[ledger] 面板正文挂载失败(只剩 tab 标题):', error)
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
const cleanup = () => {
|
|
1063
|
+
for (const dispose of [disposeTitle, disposeBody, disposeClose, disposeTab]) {
|
|
1064
|
+
try {
|
|
1065
|
+
dispose?.()
|
|
1066
|
+
} catch {
|
|
1067
|
+
// 卸载阶段的异常同样不能冒泡
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
|
|
1072
|
+
else ctx.on('dispose', cleanup)
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* 测试可见的内部件。实现都在 panel-view.js(纯展示),
|
|
1077
|
+
* 这里重导出,是为了让断言只认 `client.js` 一个入口。
|
|
1078
|
+
*/
|
|
1079
|
+
const __internal = {
|
|
1080
|
+
makeLedgerBody,
|
|
1081
|
+
makeLedgerTitle,
|
|
1082
|
+
renderPayload,
|
|
1083
|
+
formatAmount,
|
|
1084
|
+
formatTokens,
|
|
1085
|
+
formatShare,
|
|
1086
|
+
formatClock,
|
|
1087
|
+
shortId,
|
|
1088
|
+
sourceLabel,
|
|
1089
|
+
}
|
|
1090
|
+
//#endregion
|
|
202
1091
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
formatShare,
|
|
214
|
-
formatClock,
|
|
215
|
-
shortId,
|
|
216
|
-
sourceLabel,
|
|
217
|
-
}
|
|
1092
|
+
// React 只能来自宿主模块表:浏览器里没有裸 import('react') 能解析的路径
|
|
1093
|
+
__setReactLoader(() => require("react"));
|
|
1094
|
+
|
|
1095
|
+
exports.apply = apply;
|
|
1096
|
+
// 硬依赖必须跟着产物一起导出:cordis 靠它判断"什么时候允许 apply",
|
|
1097
|
+
// 漏了就会在 apply 里抛 cannot get property "..." without inject,把宿主启动带崩。
|
|
1098
|
+
exports.inject = inject;
|
|
1099
|
+
return module.exports;
|
|
1100
|
+
},
|
|
1101
|
+
});
|