@lingda-ai/dsh-plugin-ledger 0.1.8 → 0.1.9

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/lib/client.js CHANGED
@@ -143,6 +143,34 @@ window.__ModuleLoader__.load({
143
143
 
144
144
  /** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
145
145
  const REFRESH_MS = 5000
146
+ /** 单次读取的超时:超过它就必须报错,而不是让面板一直转圈。 */
147
+ const READ_TIMEOUT_MS = 8000
148
+
149
+ /**
150
+ * 给一次远端读取加超时。
151
+ *
152
+ * RPC 卡住时 Promise 永远不 settle,界面就会停在"正在读取…"——用户既看不出坏在哪,
153
+ * 也没有重试的余地。宁可报"读取超时",也不要无声地转圈。
154
+ * @template T
155
+ * @param {Promise<T>} promise
156
+ * @param {number} ms
157
+ * @returns {Promise<T>}
158
+ */
159
+ function withTimeout(promise, ms) {
160
+ return new Promise((resolve, reject) => {
161
+ const timer = setTimeout(() => reject(new Error(`读取超时(${ms}ms)`)), ms)
162
+ promise.then(
163
+ (value) => {
164
+ clearTimeout(timer)
165
+ resolve(value)
166
+ },
167
+ (error) => {
168
+ clearTimeout(timer)
169
+ reject(error)
170
+ },
171
+ )
172
+ })
173
+ }
146
174
 
147
175
  // 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
148
176
  // 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
@@ -320,37 +348,66 @@ window.__ModuleLoader__.load({
320
348
  return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
321
349
  }
322
350
 
351
+ /**
352
+ * 最近一次成功读取的快照,按会话索引。
353
+ *
354
+ * 为什么放在模块级而不是组件 state:右栏 tab 是 keepMounted 的常驻 UI,
355
+ * 宿主在切会话/重挂时会重建组件;state 一丢就又回到"正在读取…"。
356
+ * 有了这份缓存,第二次打开是**立刻有数**,轮询只负责刷新。
357
+ * @type {Map<string, object>}
358
+ */
359
+ const viewCache = new Map()
360
+
323
361
  function makeLedgerBody(React, fetchView) {
324
362
  const h = React.createElement
325
363
 
326
364
  return function LedgerBody(props) {
327
365
  const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
328
- const [view, setView] = React.useState(undefined)
366
+ const [view, setView] = React.useState(() => (sessionId === null ? undefined : viewCache.get(sessionId)))
329
367
  const [busy, setBusy] = React.useState(false)
330
368
  const [expanded, setExpanded] = React.useState(false)
331
- // 请求序号:切会话时旧请求可能后到,不能让它把新会话的读数覆盖掉
332
- const seq = React.useRef(0)
369
+ // 正在飞的那一次请求:轮询必须跳过"上一拍还没回来"的这一次。
370
+ // 否则每 REFRESH_MS 就有一个新请求把上一个响应判定为过期,
371
+ // 只要单次读取慢于轮询间隔,面板就会**永远停在"正在读取…"**(真机上就是这个现象)。
372
+ const inFlight = React.useRef(false)
373
+ // 当前挂着的会话:响应回来时用它判断"是不是还在看同一个会话"
374
+ const liveSession = React.useRef(sessionId)
375
+ /** 挂载时刻:用来判断"这次读取是不是慢得反常" */
376
+ const mountedAt = React.useRef(Date.now())
333
377
 
334
378
  const refresh = React.useCallback(async () => {
335
379
  if (sessionId === null) return
336
- const mine = (seq.current += 1)
380
+ if (inFlight.current) return
381
+ inFlight.current = true
382
+ const forSession = sessionId
383
+ const startedAt = Date.now()
337
384
  setBusy(true)
338
385
  try {
339
- const next = await fetchView(sessionId)
340
- if (mine === seq.current) setView(next)
386
+ const next = await withTimeout(fetchView(forSession), READ_TIMEOUT_MS)
387
+ if (next !== null && next?.error === undefined) viewCache.set(forSession, next)
388
+ if (liveSession.current === forSession) setView(next)
389
+ } catch (error) {
390
+ // 任何异常都要落成可见的错误态。永久 loading 是最糟的失败方式:
391
+ // 用户既不知道坏在哪,也不知道能不能重试。
392
+ console.warn('[ledger] 读取账本快照失败:', error)
393
+ if (liveSession.current === forSession) {
394
+ setView({ error: `${error?.message ?? error}(耗时 ${Date.now() - startedAt}ms)` })
395
+ }
341
396
  } finally {
342
- if (mine === seq.current) setBusy(false)
397
+ inFlight.current = false
398
+ if (liveSession.current === forSession) setBusy(false)
343
399
  }
344
400
  }, [sessionId])
345
401
 
346
402
  React.useEffect(() => {
403
+ liveSession.current = sessionId
347
404
  // 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
348
405
  setView(undefined)
349
406
  void refresh()
350
407
  // 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
351
408
  const timer = setInterval(() => { void refresh() }, REFRESH_MS)
352
409
  return () => clearInterval(timer)
353
- }, [refresh])
410
+ }, [refresh, sessionId])
354
411
 
355
412
  const head = h(
356
413
  'div',
@@ -386,9 +443,24 @@ window.__ModuleLoader__.load({
386
443
  ),
387
444
  )
388
445
 
389
- // loading:还没跑完第一次
446
+ // loading:还没跑完第一次。超过 1.5 秒就把"读得慢"显出来,
447
+ // 永久转圈是最没法排查的失败方式(既没有错误码,也没有重试入口)
390
448
  if (view === undefined) {
391
- return h('div', null, head, h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, '正在读取…'))
449
+ const slow = Date.now() - mountedAt.current > 1500
450
+ return h(
451
+ 'div',
452
+ null,
453
+ head,
454
+ h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, slow ? '正在读取…(比预期慢)' : '正在读取…'),
455
+ slow
456
+ ? h(
457
+ 'p',
458
+ { style: { margin: '0 14px 12px', fontSize: 11, lineHeight: 1.7, color: INK3 } },
459
+ `已等待 ${Math.round((Date.now() - mountedAt.current) / 1000)} 秒 · 点「刷新」可重试。`
460
+ + '若一直如此,多半是快照文件还没落盘(Host 每 3 秒最多写一次)。',
461
+ )
462
+ : null,
463
+ )
392
464
  }
393
465
 
394
466
  // 通道或解析出错
package/lib/panel-view.js CHANGED
@@ -60,6 +60,34 @@ const SOURCE_HEAD = 6
60
60
 
61
61
  /** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
62
62
  const REFRESH_MS = 5000
63
+ /** 单次读取的超时:超过它就必须报错,而不是让面板一直转圈。 */
64
+ const READ_TIMEOUT_MS = 8000
65
+
66
+ /**
67
+ * 给一次远端读取加超时。
68
+ *
69
+ * RPC 卡住时 Promise 永远不 settle,界面就会停在"正在读取…"——用户既看不出坏在哪,
70
+ * 也没有重试的余地。宁可报"读取超时",也不要无声地转圈。
71
+ * @template T
72
+ * @param {Promise<T>} promise
73
+ * @param {number} ms
74
+ * @returns {Promise<T>}
75
+ */
76
+ function withTimeout(promise, ms) {
77
+ return new Promise((resolve, reject) => {
78
+ const timer = setTimeout(() => reject(new Error(`读取超时(${ms}ms)`)), ms)
79
+ promise.then(
80
+ (value) => {
81
+ clearTimeout(timer)
82
+ resolve(value)
83
+ },
84
+ (error) => {
85
+ clearTimeout(timer)
86
+ reject(error)
87
+ },
88
+ )
89
+ })
90
+ }
63
91
 
64
92
  // 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
65
93
  // 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
@@ -237,37 +265,66 @@ function formatShare(share) {
237
265
  return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
238
266
  }
239
267
 
268
+ /**
269
+ * 最近一次成功读取的快照,按会话索引。
270
+ *
271
+ * 为什么放在模块级而不是组件 state:右栏 tab 是 keepMounted 的常驻 UI,
272
+ * 宿主在切会话/重挂时会重建组件;state 一丢就又回到"正在读取…"。
273
+ * 有了这份缓存,第二次打开是**立刻有数**,轮询只负责刷新。
274
+ * @type {Map<string, object>}
275
+ */
276
+ const viewCache = new Map()
277
+
240
278
  function makeLedgerBody(React, fetchView) {
241
279
  const h = React.createElement
242
280
 
243
281
  return function LedgerBody(props) {
244
282
  const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
245
- const [view, setView] = React.useState(undefined)
283
+ const [view, setView] = React.useState(() => (sessionId === null ? undefined : viewCache.get(sessionId)))
246
284
  const [busy, setBusy] = React.useState(false)
247
285
  const [expanded, setExpanded] = React.useState(false)
248
- // 请求序号:切会话时旧请求可能后到,不能让它把新会话的读数覆盖掉
249
- const seq = React.useRef(0)
286
+ // 正在飞的那一次请求:轮询必须跳过"上一拍还没回来"的这一次。
287
+ // 否则每 REFRESH_MS 就有一个新请求把上一个响应判定为过期,
288
+ // 只要单次读取慢于轮询间隔,面板就会**永远停在"正在读取…"**(真机上就是这个现象)。
289
+ const inFlight = React.useRef(false)
290
+ // 当前挂着的会话:响应回来时用它判断"是不是还在看同一个会话"
291
+ const liveSession = React.useRef(sessionId)
292
+ /** 挂载时刻:用来判断"这次读取是不是慢得反常" */
293
+ const mountedAt = React.useRef(Date.now())
250
294
 
251
295
  const refresh = React.useCallback(async () => {
252
296
  if (sessionId === null) return
253
- const mine = (seq.current += 1)
297
+ if (inFlight.current) return
298
+ inFlight.current = true
299
+ const forSession = sessionId
300
+ const startedAt = Date.now()
254
301
  setBusy(true)
255
302
  try {
256
- const next = await fetchView(sessionId)
257
- if (mine === seq.current) setView(next)
303
+ const next = await withTimeout(fetchView(forSession), READ_TIMEOUT_MS)
304
+ if (next !== null && next?.error === undefined) viewCache.set(forSession, next)
305
+ if (liveSession.current === forSession) setView(next)
306
+ } catch (error) {
307
+ // 任何异常都要落成可见的错误态。永久 loading 是最糟的失败方式:
308
+ // 用户既不知道坏在哪,也不知道能不能重试。
309
+ console.warn('[ledger] 读取账本快照失败:', error)
310
+ if (liveSession.current === forSession) {
311
+ setView({ error: `${error?.message ?? error}(耗时 ${Date.now() - startedAt}ms)` })
312
+ }
258
313
  } finally {
259
- if (mine === seq.current) setBusy(false)
314
+ inFlight.current = false
315
+ if (liveSession.current === forSession) setBusy(false)
260
316
  }
261
317
  }, [sessionId])
262
318
 
263
319
  React.useEffect(() => {
320
+ liveSession.current = sessionId
264
321
  // 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
265
322
  setView(undefined)
266
323
  void refresh()
267
324
  // 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
268
325
  const timer = setInterval(() => { void refresh() }, REFRESH_MS)
269
326
  return () => clearInterval(timer)
270
- }, [refresh])
327
+ }, [refresh, sessionId])
271
328
 
272
329
  const head = h(
273
330
  'div',
@@ -303,9 +360,24 @@ function makeLedgerBody(React, fetchView) {
303
360
  ),
304
361
  )
305
362
 
306
- // loading:还没跑完第一次
363
+ // loading:还没跑完第一次。超过 1.5 秒就把"读得慢"显出来,
364
+ // 永久转圈是最没法排查的失败方式(既没有错误码,也没有重试入口)
307
365
  if (view === undefined) {
308
- return h('div', null, head, h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, '正在读取…'))
366
+ const slow = Date.now() - mountedAt.current > 1500
367
+ return h(
368
+ 'div',
369
+ null,
370
+ head,
371
+ h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, slow ? '正在读取…(比预期慢)' : '正在读取…'),
372
+ slow
373
+ ? h(
374
+ 'p',
375
+ { style: { margin: '0 14px 12px', fontSize: 11, lineHeight: 1.7, color: INK3 } },
376
+ `已等待 ${Math.round((Date.now() - mountedAt.current) / 1000)} 秒 · 点「刷新」可重试。`
377
+ + '若一直如此,多半是快照文件还没落盘(Host 每 3 秒最多写一次)。',
378
+ )
379
+ : null,
380
+ )
309
381
  }
310
382
 
311
383
  // 通道或解析出错
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-ledger",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "DSH 插件搜索入口:运行时账本(成本/用量观测)。自包含单包,不依赖其他 npm 包,便于从镜像源安装。",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [