@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.
@@ -0,0 +1,302 @@
1
+ /**
2
+ * @lingda-ai/ledger —— 浏览器半(右侧栏 tab)**源码**
3
+ *
4
+ * 注意:本文件不是发布产物。发布入口是 `lib/client.js`,由
5
+ * `node scripts/build-client.mjs` 从本文件 + panel-view.js + panel-path.js +
6
+ * tool-size.js 打包成宿主要求的 loader 形态(`window.__ModuleLoader__.load`)。
7
+ * 手工改 `lib/client.js` 会在下次构建时被覆盖。
8
+ *
9
+ * 为什么必须有这一步(真机崩溃换来的):
10
+ * dsh-client-modules 的 Node 半侧把每个包的 `client.js` **原样拼接**成一个
11
+ * combo 脚本(`/plugins/??a/client.js,b/client.js&rev=…`),浏览器按 classic
12
+ * script 解析。所以客户端入口里不能出现任何 `import` / `export` 语句,
13
+ * 否则整页抛 `SyntaxError: Cannot use import statement outside a module`,
14
+ * 连宿主一起带崩。0.1.4 就是直接发布了 ESM 源码,一重启就崩。
15
+ *
16
+ * 已核实的契约(源码逐条对过,勿凭记忆改):
17
+ *
18
+ * 1) 类型登记 @ dsh-client-ui-sidebar-right
19
+ * ctx.sidebarRightTabs.register(definition) → disposer
20
+ * definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
21
+ * guide entry: { id, order, title(), description?(), icon?, commandId? }
22
+ *
23
+ * 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
24
+ * - 'sidebar.right.pane.tab'
25
+ * - 'sidebar.right.pane.tab.title'
26
+ * 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
27
+ * ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
28
+ *
29
+ * 3) React 来自宿主模块表(`require("react")`)。本文件在 Node 侧(单测、脚本)
30
+ * 走动态 import('react');打进 client.js 后由构建产物通过 __setReactLoader
31
+ * 注入 factory 拿到的 require。两条路都失败时退回"只登记类型、不挂正文"。
32
+ *
33
+ * 取数通道(已接,细节见 docs/spikes.md C-3):
34
+ * 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
35
+ * 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
36
+ * 接入点集中在 createFetchView() 一处。
37
+ *
38
+ * 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
39
+ */
40
+
41
+ /** 本实现的身份,也是两个 keyed seat 的 key。 */
42
+ const LEDGER_ID = '@lingda-ai/ledger'
43
+ /** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
44
+ const LEDGER_KIND = 'ledger.cost'
45
+
46
+ /**
47
+ * 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
48
+ *
49
+ * 这条**必须声明**。cordis 的 ctx 是代理:访问未声明的服务属性会直接抛
50
+ * `cannot get property "sidebarRightTabs" without inject`,而且是在 apply 里抛,
51
+ * 等同于让宿主启动失败(0.1.5 重启即崩就是这么来的——之前只写了 package.json 的
52
+ * dsh.client.inject,那是"先加载哪个包",不是"这个插件依赖哪个服务",两回事)。
53
+ */
54
+ export const inject = ['sidebarRightTabs']
55
+
56
+ /**
57
+ * 取可选服务。不能写成 `ctx.xxx`——没在 inject 里声明的服务,属性访问会抛。
58
+ * 宿主提供了 `ctx.get(name)` 这条不受 inject 约束的通道;Node 侧单测的假 ctx
59
+ * 没有 get,退回普通属性读。
60
+ * @param {any} ctx
61
+ * @param {string} name
62
+ */
63
+ function optionalService(ctx, name) {
64
+ if (typeof ctx?.get === 'function') {
65
+ try {
66
+ return ctx.get(name) ?? null
67
+ } catch {
68
+ return null
69
+ }
70
+ }
71
+ try {
72
+ return ctx?.[name] ?? null
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+
78
+ /** 面板用到的 seat 名,抽出来避免字符串散落。 */
79
+ const SEAT_BODY = 'sidebar.right.pane.tab'
80
+ const SEAT_TITLE = 'sidebar.right.pane.tab.title'
81
+
82
+ /**
83
+ * React 取用方式:默认走动态 import(Node 侧单测/脚本)。
84
+ * 构建成 client.js 后,产物在 factory 里用宿主模块表的 `require('react')` 覆盖它——
85
+ * 浏览器里没有裸 `import('react')` 能解析的相对路径,动态 import 必然失败。
86
+ * @type {() => Promise<any>}
87
+ */
88
+ // #region react-loader-default
89
+ let reactLoader = async () => {
90
+ const mod = await import('react')
91
+ return mod.default ?? mod ?? null
92
+ }
93
+ // #endregion react-loader-default
94
+
95
+ /** 只给构建产物用:把 React 换成宿主模块表给的 require。 */
96
+ export function __setReactLoader(fn) {
97
+ if (typeof fn === 'function') reactLoader = fn
98
+ }
99
+
100
+ import { panelRelativePath } from './panel-path.js'
101
+ import {
102
+ makeLedgerBody,
103
+ makeLedgerTitle,
104
+ renderPayload,
105
+ formatAmount,
106
+ formatTokens,
107
+ formatShare,
108
+ formatClock,
109
+ shortId,
110
+ sourceLabel,
111
+ } from './panel-view.js'
112
+
113
+
114
+ /** 会话 id 太长时截断成 chip 能放下的样子。 */
115
+
116
+ /**
117
+ * 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
118
+ *
119
+ * 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
120
+ * list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
121
+ * stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
122
+ * read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
123
+ * 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
124
+ * 先用相对路径 stat 换出 absolutePath,再 read。
125
+ *
126
+ * 返回形状:
127
+ * null → 还没有快照(Host 未开启或尚未落盘)
128
+ * { error: '...' } → 通道/解析失败,面板显示原因
129
+ * payload → Host 写的 JSON(version / totals / topSources / sources)
130
+ *
131
+ * @param {any} ctx - 浏览器侧 cordis 上下文
132
+ * @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
133
+ */
134
+ export function createFetchView(ctx) {
135
+ return async function fetchView(sessionId, opts = {}) {
136
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return null
137
+ const files = optionalService(ctx, 'remote')?.workspaceFiles
138
+ if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
139
+ return { error: '宿主未提供 workspaceFiles 通道' }
140
+ }
141
+ const relative = panelRelativePath(sessionId)
142
+
143
+ let stat
144
+ try {
145
+ stat = await files.stat(sessionId, relative, opts.signal)
146
+ } catch (error) {
147
+ return { error: stringifyError(error) }
148
+ }
149
+ if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
150
+ const absolutePath = stat.value?.absolutePath
151
+ if (typeof absolutePath !== 'string') return null
152
+ // 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
153
+ const bytes = stat.value?.bytes
154
+ if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
155
+
156
+ let page
157
+ try {
158
+ page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
159
+ } catch (error) {
160
+ return { error: stringifyError(error) }
161
+ }
162
+ if (!page?.ok) return { error: '读取快照失败' }
163
+ const text = page.value?.text
164
+ if (typeof text !== 'string') return { error: '快照内容为空' }
165
+ if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
166
+
167
+ try {
168
+ const parsed = JSON.parse(text)
169
+ return parsed && typeof parsed === 'object' ? parsed : { error: '快照格式无法识别' }
170
+ } catch {
171
+ return { error: '快照不是合法 JSON(可能正写到一半)' }
172
+ }
173
+ }
174
+ }
175
+
176
+ /** 把任意抛出物变成一句话。 */
177
+ function stringifyError(error) {
178
+ if (error instanceof Error) return error.message
179
+ if (typeof error === 'string') return error
180
+ return '未知错误'
181
+ }
182
+
183
+ /** CNY 用 ¥,其它币种保留原符号 + 代码。 */
184
+
185
+ /**
186
+ * 正文组件。用 createElement 而不引 JSX,避免给独立仓库引入构建链。
187
+ * @param {any} React - 宿主的 React
188
+ * @param {(sid: string, opts?: object) => Promise<any>} fetchView
189
+ */
190
+
191
+ /**
192
+ * 渲染已取到的快照。
193
+ *
194
+ * 从组件里抽出来是为了可测:SSR 不跑 effect,组件首帧永远是"读取中",
195
+ * 只有把渲染当纯函数,才能在测试里断言四档金额、明细、预算条真的画出来了。
196
+ * @param {any} React
197
+ * @param {any} view - 快照 payload
198
+ * @param {string|null} sessionId
199
+ * @param {any} head - 已在组件侧建好的头部(含刷新按钮)
200
+ */
201
+
202
+ /** 一行 label / value,两个渲染入口共用。 */
203
+
204
+ /** 标题组件:chip 上的实时文案(不做金额,避免每次事件都改布局)。 */
205
+
206
+ /** @param {import('@deepseek-ai/cordis').Context} ctx */
207
+ export async function apply(ctx) {
208
+ const tabs = ctx.sidebarRightTabs
209
+ if (!tabs || typeof tabs.register !== 'function') return
210
+
211
+ const definition = {
212
+ id: LEDGER_ID,
213
+ kind: LEDGER_KIND,
214
+ title: () => '账本',
215
+ priority: 'extension',
216
+ guide: [
217
+ {
218
+ id: 'ledger.cost',
219
+ order: 10,
220
+ title: () => '账本',
221
+ description: () => '本会话的 token 用量与成本归因',
222
+ },
223
+ ],
224
+ // 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
225
+ keepMounted: true,
226
+ }
227
+
228
+ // 客户端契约里除 sidebarRightTabs 之外的部分都没被真机证实过。
229
+ // 这是一个 UI 插件:任何一处契约偏差都应该退化成"没有面板",而不是让宿主起不来。
230
+ let disposeTab = null
231
+ try {
232
+ disposeTab = tabs.register(definition)
233
+ } catch (error) {
234
+ console.warn('[ledger] 右栏 tab 登记失败,面板不出现(宿主其它功能不受影响):', error)
235
+ return
236
+ }
237
+
238
+ const sidebarRight = optionalService(ctx, 'sidebarRight')
239
+ let disposeClose = null
240
+ if (typeof sidebarRight?.registerCloseHandler === 'function') {
241
+ try {
242
+ disposeClose = sidebarRight.registerCloseHandler(LEDGER_KIND, () => {})
243
+ } catch (error) {
244
+ console.warn('[ledger] registerCloseHandler 失败:', error)
245
+ }
246
+ }
247
+
248
+ // 正文与标题:宿主把 seat 声明在 sidebar-right 里,先 inject 再 register
249
+ let disposeBody = null
250
+ let disposeTitle = null
251
+ const slots = optionalService(ctx, 'slots')
252
+ if (typeof slots?.inject === 'function' && typeof slots.register === 'function') {
253
+ let React = null
254
+ try {
255
+ React = await reactLoader()
256
+ } catch {
257
+ React = null // 宿主没给 React:保持无正文的降级态
258
+ }
259
+ if (React !== null) {
260
+ try {
261
+ const fetchView = createFetchView(ctx)
262
+ disposeBody = slots.inject(SEAT_BODY, () =>
263
+ slots.register({ name: SEAT_BODY, key: LEDGER_ID }, makeLedgerBody(React, fetchView)),
264
+ )
265
+ disposeTitle = slots.inject(SEAT_TITLE, () =>
266
+ slots.register({ name: SEAT_TITLE, key: LEDGER_ID }, makeLedgerTitle(React)),
267
+ )
268
+ } catch (error) {
269
+ // seat 名对不上、权限不足、host 版本差异:只丢面板正文,tab 仍在
270
+ console.warn('[ledger] 面板正文挂载失败(只剩 tab 标题):', error)
271
+ }
272
+ }
273
+ }
274
+
275
+ const cleanup = () => {
276
+ for (const dispose of [disposeTitle, disposeBody, disposeClose, disposeTab]) {
277
+ try {
278
+ dispose?.()
279
+ } catch {
280
+ // 卸载阶段的异常同样不能冒泡
281
+ }
282
+ }
283
+ }
284
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
285
+ else ctx.on('dispose', cleanup)
286
+ }
287
+
288
+ /**
289
+ * 测试可见的内部件。实现都在 panel-view.js(纯展示),
290
+ * 这里重导出,是为了让断言只认 `client.js` 一个入口。
291
+ */
292
+ export const __internal = {
293
+ makeLedgerBody,
294
+ makeLedgerTitle,
295
+ renderPayload,
296
+ formatAmount,
297
+ formatTokens,
298
+ formatShare,
299
+ formatClock,
300
+ shortId,
301
+ sourceLabel,
302
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-ledger",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "DSH 插件搜索入口:运行时账本(成本/用量观测)。自包含单包,不依赖其他 npm 包,便于从镜像源安装。",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -46,4 +46,4 @@
46
46
  "engines": {
47
47
  "node": ">=18"
48
48
  }
49
- }
49
+ }