dsh-token-bar 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-token-bar contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,101 @@
1
+ # dsh-token-bar
2
+
3
+ [![MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
+
5
+ A **per-turn token usage strip** for the [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) Web UI. It lives in each reply's own icon row — the line carrying copy / branch / usage / timestamp — and draws that turn's cache structure as a grey / yellow / green segmented bar, with a written legend that carries each slice's share.
6
+
7
+ ![The per-turn strip in a reply's icon row: grey = uncached input, yellow = cache read, green = output, followed by a legend with each share](docs/screenshot-turn-bar.png)
8
+
9
+ **Featherweight**: presentation only — no network, no storage, no host routes, no session-log writes, and no patching of any official package.
10
+ **Zero dependencies**: one hand-written bundle that only uses the platform-provided React.
11
+
12
+ English | [中文](README.md)
13
+
14
+ ---
15
+
16
+ ## Why
17
+
18
+ The shipped turn-usage popover has the exact numbers, but a list of numbers has to be read while a shape is understood at a glance:
19
+
20
+ - Was this turn served entirely from cache?
21
+ - Did a large uncached prefix appear (a prefix invalidated, cost jumping)?
22
+ - Is the output share abnormal?
23
+
24
+ `dsh-token-bar` turns those three figures into a scannable strip with a legend — **you know what each slice is and how big it is without hovering**.
25
+
26
+ ## What it looks like
27
+
28
+ | | |
29
+ |---|---|
30
+ | Slice / legend order | **grey (uncached input) → yellow (cache read) → green (output)** — the strip and the legend share one order |
31
+ | Strip width | 132px |
32
+ | Minimum slice | **6px** for any non-zero bucket, so a 0.1% share still shows and keeps matching the legend |
33
+ | Legend | dot + name + this turn's share |
34
+ | Type size | one notch below body copy: `calc(var(--dsh-content-font-size-secondary, 13px) - 1px)`, so it tracks the shell font setting |
35
+ | Colours | the `--dsw-*` theme tokens only, so light and dark follow the shell |
36
+ | Alignment | vertically centred on the icon row |
37
+
38
+ Hovering shows the full breakdown: cache hit rate plus every bucket's exact token count and share.
39
+
40
+ > Cache write is not a slice: this route reports 0 for it.
41
+
42
+ ## Where the numbers come from
43
+
44
+ It reads `tokenUsage` from this Turn's `turn-tail` location data — **this turn's** accounting, the same value the shipped "turn usage" popover prints, never the session-wide projection.
45
+
46
+ The `conversation.chat.assistant-actions` slot hands over only a **message id**, so the component resolves the Turn back through `useChat`: every completed Turn publishes a `turn-tail` entry carrying both its closing `messageId` and its own `tokenUsage`, so matching the id recovers this turn's accounting. `useChat` ships on the session standard kit (`SessionStandardProps` in `dsh-client-ui-chat`'s `slots.d.ts`), so nothing extra has to be injected.
47
+
48
+ Credit to [dsh-token-counter](https://github.com/OkliaoliO/dsh-token-counter) for the implementation reference.
49
+
50
+ ## Install
51
+
52
+ ```sh
53
+ dsh plugin --profile web add dsh-token-bar
54
+ ```
55
+
56
+ From a local directory (development):
57
+
58
+ ```sh
59
+ dsh plugin --profile web add /path/to/dsh-token-bar
60
+ ```
61
+
62
+ Restart `dsh web` afterwards. Uninstall with `dsh plugin --profile web remove dsh-token-bar`.
63
+
64
+ ## Compatibility
65
+
66
+ | Component | Supported |
67
+ |---|---|
68
+ | DSH | `>=0.2.0-rc.1 <0.3.0-0`, verified on `0.2.0-rc.2` |
69
+ | Node.js | `>=20` |
70
+ | UI | DSH Web (needs the `conversation.chat.assistant-actions` slot) |
71
+ | OS | macOS / Linux / Windows (pure JavaScript) |
72
+
73
+ ## Development
74
+
75
+ ```sh
76
+ npm run check # syntax
77
+ npm test # pure helpers + render
78
+ ```
79
+
80
+ `npm test` verifies the **source** `client.js` by default. To verify the build the browser actually receives, snapshot it from a running `dsh web`:
81
+
82
+ ```sh
83
+ node scripts/snapshot-bundle.mjs "http://127.0.0.1:3080/?token=<token printed at startup>"
84
+ npm test # with verify-module.js present, tests the served bundle instead
85
+ ```
86
+
87
+ ## Tunables
88
+
89
+ All at the top of `client.js`: `BUCKETS` (slices, order, colours), `MIN_SEGMENT_PX` (default `6`), `TRACK_PX` (default `132`), `FONT_SIZE`.
90
+
91
+ ## Known limits
92
+
93
+ - Completed (`turn/end`) turns only; the turn currently streaming has no strip.
94
+ - **The icon row is kept visible**: upstream only keeps the newest reply's row on screen and fades older ones in on hover. So the strip stays reachable, the plugin pins the assistant row visible — scoped to the row carrying `data-clock="end"`, leaving the user bubble alone. The cost is that every reply now shows its icon row permanently.
95
+ - **Position is bounded by the official layout**: that row is hard-coded as copy → plugin actions → branch → usage → timestamp, and the only plugin slot sits between copy and branch. The strip therefore lands to the left of the usage pill rather than between usage and timestamp — there is no slot there.
96
+ - It relies on the official `turn-tail` location-data shape; a change there needs a matching update here.
97
+ - There is no settings UI — restyle by editing the source.
98
+
99
+ ## License
100
+
101
+ MIT
package/README.md CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # dsh-token-bar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
+
5
+ 给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的 Web 界面加一条**单轮 token 用量条**:放在每条回复自己的图标行里(复制 / 分支 / 用量 / 时间那一行),把这一轮的缓存结构画成灰 / 黄 / 绿三段条,配一条带百分比的完整图例。
6
+
7
+ ![回复图标行里的单轮用量条:灰=未缓存输入、黄=缓存读取、绿=输出,后面跟带百分比的图例](docs/screenshot-turn-bar.png)
8
+
9
+ **极轻量**:纯客户端展示,不联网、不落盘、不注册任何 Host 路由、不写会话日志、不改任何官方包。
10
+ **零依赖**:一个手写 bundle,只用平台提供的 React。
11
+
12
+ [English](README.en.md) | 中文
13
+
14
+ ---
15
+
16
+ ## 它解决什么
17
+
18
+ 官方在每条回复末尾的用量气泡里,点开能看到「本轮用量」的精确数字。但**数字是列表,要读;结构是形状,一眼就懂**:
19
+
20
+ - 这一轮是不是全命中缓存?
21
+ - 有没有跑出大量未缓存输入(意味着前缀失效、成本变高)?
22
+ - 输出占比是否异常?
23
+
24
+ `dsh-token-bar` 把这三个数字变成一条可扫视的带状图,并且带图例——**不需要悬停也知道每段是什么、占多少**。
25
+
26
+ ## 外观
27
+
28
+ | 项 | 值 |
29
+ |---|---|
30
+ | 段序 / 图例序 | **灰(未缓存输入)→ 黄(缓存读取)→ 绿(输出)**,条与图例完全同序 |
31
+ | 条宽 | 132px |
32
+ | 最小段宽 | 只要有 token 就至少 **6px**,再小的占比也看得见,不会和图例对不上 |
33
+ | 图例 | 色点 + 名称 + 本轮占比百分比 |
34
+ | 字号 | 比正文小一号:`calc(var(--dsh-content-font-size-secondary, 13px) - 1px)`,跟随设置里的字号 |
35
+ | 配色 | 全部取自 `--dsw-*` 主题 token,浅色 / 深色自动跟随 |
36
+ | 对齐 | 图标行内垂直居中 |
37
+
38
+ 悬停显示本轮完整明细:缓存命中率 + 每段精确 token 数与占比。
39
+
40
+ > 缓存写入未单独成段——当前路由上该值恒为 0。
41
+
42
+ ## 数据来源
43
+
44
+ 读本轮 `turn-tail` location data 里的 `tokenUsage`,即**本轮**的用量(和官方「本轮用量」弹窗同源),**不是**会话累计。
45
+
46
+ `conversation.chat.assistant-actions` 这个插槽只把**消息 id** 交给组件,所以 `useChat` 会从本轮数据反查一次:每条完成的 Turn 都会发布一份 `turn-tail`,里面既有收尾消息的 `messageId`,也有它自己的 `tokenUsage`——对上 id 就拿到了这一轮的账目。`useChat` 属于会话级插槽标配(`dsh-client-ui-chat` 的 `slots.d.ts` 把 `useChat` 挂在 `SessionStandardProps` 上),不需要额外注入。
47
+
48
+ 感谢 [dsh-token-counter](https://github.com/OkliaoliO/dsh-token-counter) 提供的实现参考。
49
+
50
+ ## 安装
51
+
52
+ ```sh
53
+ dsh plugin --profile web add dsh-token-bar
54
+ ```
55
+
56
+ 或从本地目录安装(开发时):
57
+
58
+ ```sh
59
+ dsh plugin --profile web add /path/to/dsh-token-bar
60
+ ```
61
+
62
+ 安装后**重启 `dsh web`** 生效。
63
+
64
+ 卸载:
65
+
66
+ ```sh
67
+ dsh plugin --profile web remove dsh-token-bar
68
+ ```
69
+
70
+ ## 兼容性
71
+
72
+ | 组件 | 支持 |
73
+ |---|---|
74
+ | DSH | `>=0.2.0-rc.1 <0.3.0-0`,在 `0.2.0-rc.2` 上实测 |
75
+ | Node.js | `>=20` |
76
+ | 界面 | DSH Web(依赖 `conversation.chat.assistant-actions` 插槽) |
77
+ | 系统 | macOS / Linux / Windows(纯 JavaScript) |
78
+
79
+ ## 开发
80
+
81
+ ```sh
82
+ npm run check # 语法检查
83
+ npm test # 纯函数测试 + 渲染测试
84
+ ```
85
+
86
+ `npm test` 默认测试**源码** `client.js`。想验证浏览器实际收到的那份构建产物,从运行中的 `dsh web` 抽一份快照:
87
+
88
+ ```sh
89
+ node scripts/snapshot-bundle.mjs "http://127.0.0.1:3080/?token=<启动时打印的 token>"
90
+ npm test # 检测到 verify-module.js 后,自动改为测试服务端下发的产物
91
+ ```
92
+
93
+ ### 网络受限时推送
94
+
95
+ 如果所在网络访问不了 `github.com:443`(`git push` 卡住超时)但 `api.github.com` 可以访问,用 REST API 推送:
96
+
97
+ ```sh
98
+ node scripts/push-via-api.mjs <owner>/<repo> --dry-run # 先看要推什么
99
+ node scripts/push-via-api.mjs <owner>/<repo> # 真正推送
100
+ ```
101
+
102
+ 它会按 blobs → trees → commits 重放本地历史,并把分支指向**远端生成的**新 commit SHA(API 创建的 commit 与本地 SHA 不同,这点最容易踩坑)。
103
+
104
+ ## 可调参数
105
+
106
+ 都在 `client.js` 顶部:
107
+
108
+ | 常量 | 作用 |
109
+ |---|---|
110
+ | `BUCKETS` | 三段(顺序、名称、颜色) |
111
+ | `MIN_SEGMENT_PX` | 最小段宽,默认 `6` |
112
+ | `TRACK_PX` | 条宽,默认 `132` |
113
+ | `FONT_SIZE` | 字号,默认比正文小一号 |
114
+
115
+ ## 已知限制
116
+
117
+ - 只覆盖完成(`turn/end`)的轮次;正在流式输出的那一轮没有条。
118
+ - **图标行常驻**:官方默认只让最新一条回复的图标行常驻,更早的回复要悬停才淡入。为了让条一直看得见,插件把助手那一行固定为可见——只动带 `data-clock="end"` 的行,用户气泡不受影响。代价是每条回复下方的图标行都常显。
119
+ - **位置受官方排列约束**:那一行的顺序是硬编码的(复制 → 插件动作 → 分支 → 用量 → 时间),唯一可用的插件插槽在复制与分支之间。所以条落在用量左侧,而不是「用量和时间之间」——官方没有在那里留插槽。
120
+ - 依赖官方 `turn-tail` 的 location data 结构;DSH 若改动该结构,需要跟随适配。
121
+ - 没有设计器 / 配置界面,改样式需要编辑源码。
122
+
123
+ ## 许可
124
+
125
+ MIT
package/client.js ADDED
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Client half of dsh-token-bar.
3
+ *
4
+ * One seat: `conversation.chat.assistant-actions` (a `list` slot) renders into
5
+ * the reply's own icon row — the line that carries copy / branch / usage /
6
+ * timestamp. The strip therefore sits inline with that metadata instead of on
7
+ * a separate line under the reply.
8
+ *
9
+ * GRAIN — the strip reads THIS TURN, not the session. This slot hands over only
10
+ * the durable `messageId`, so the Turn is resolved backwards through `useChat`:
11
+ * the session standard kit provides that selector on every session-scoped seat,
12
+ * and a Turn publishes its `turn-tail` location data carrying both the closing
13
+ * message id and this Turn's `tokenUsage` — the same figure the shipped
14
+ * "本轮用量" popover prints. The session-wide `tokenUsage` projection is
15
+ * deliberately NOT used; mixing the two grains beside each other misreads.
16
+ *
17
+ * SEGMENT ORDER follows the legend dots that trail the strip:
18
+ * grey (uncached input) → yellow (cache read) → green (output). The strip is
19
+ * wide enough that the smallest slice stays visible.
20
+ *
21
+ * Hand-written bundle: the module loader materializes `factory(require)` and
22
+ * takes its return value as the exports; React comes from the browser module
23
+ * table.
24
+ */
25
+ window.__ModuleLoader__.load({
26
+ id: 'dsh-token-bar',
27
+ factory(require) {
28
+ const React = require('react')
29
+ const h = React.createElement
30
+
31
+ /** Style element id; a hot reload must not stack duplicate sheets. */
32
+ const STYLE_ID = 'dsh-token-bar-style'
33
+ /** Diagnostics label. */
34
+ const NS = 'dsh-token-bar'
35
+
36
+ /**
37
+ * Buckets in STRIP AND LEGEND order — grey (uncached input) on the left,
38
+ * yellow (cache read) in the middle, green (output) on the right, matching
39
+ * the LobeHub convention. Cache write is omitted: this route reports 0.
40
+ */
41
+ const BUCKETS = [
42
+ {
43
+ key: 'uncachedInputTokens',
44
+ label: '未缓存输入',
45
+ color: 'var(--dsw-static-neutral-bluish-500)',
46
+ },
47
+ {
48
+ key: 'cacheReadTokens',
49
+ label: '缓存读取',
50
+ color: 'var(--dsw-alias-state-warn-primary, var(--dsw-static-amber-500))',
51
+ },
52
+ {
53
+ key: 'outputTokens',
54
+ label: '输出',
55
+ color: 'var(--dsw-alias-state-success-primary, var(--dsw-static-green-500))',
56
+ },
57
+ ]
58
+
59
+ /**
60
+ * Smallest rendered slice, in px. A highly cached Turn is 99.6% yellow, so
61
+ * a literal share would shrink the other two to sub-pixel slivers and the
62
+ * strip would stop matching its own legend. Every non-zero bucket keeps at
63
+ * least this much width; the remainder is shared by the real proportions.
64
+ */
65
+ const MIN_SEGMENT_PX = 6
66
+ /** Strip width in px; wider now that two legend rows sit beside it. */
67
+ const TRACK_PX = 132
68
+
69
+ /**
70
+ * The legend is deliberately one notch BELOW body copy: it is metadata,
71
+ * and `font-size: inherit` picked up the tail row's larger type and
72
+ * outranked the reply text. Derived from the shell's content scale so it
73
+ * still tracks the user's font setting; the secondary scale (the shipped
74
+ * pill's own basis) minus another point is the floor.
75
+ */
76
+ const FONT_SIZE =
77
+ 'calc(var(--dsh-content-font-size-secondary, 13px) - 1px)'
78
+
79
+ const CSS = `
80
+ .dsh-tb-root{box-sizing:border-box;display:inline-flex;align-items:center;gap:8px;align-self:center;flex:none;font-family:inherit;font-size:${FONT_SIZE};font-weight:400;line-height:16px;color:var(--dsw-alias-label-tertiary)}
81
+ .dsh-tb-track{box-sizing:border-box;display:inline-flex;gap:1px;overflow:hidden;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover,var(--dsw-static-neutral-bluish-100));flex:none;align-items:stretch;height:5px;width:${TRACK_PX}px}
82
+ .dsh-tb-seg{display:block;height:100%;flex:none;min-width:${MIN_SEGMENT_PX}px;transition:width .18s ease}
83
+ .dsh-tb-seg:first-child{border-top-left-radius:999px;border-bottom-left-radius:999px}
84
+ .dsh-tb-seg:last-child{border-top-right-radius:999px;border-bottom-right-radius:999px}
85
+ .dsh-tb-legend{display:inline-flex;align-items:center;gap:9px;flex:none;white-space:nowrap}
86
+ .dsh-tb-item{display:inline-flex;align-items:center;gap:4px;flex:none}
87
+ .dsh-tb-dot{display:inline-block;flex:none;width:5px;height:5px;border-radius:50%}
88
+ .dsh-tb-name{color:var(--dsw-alias-label-tertiary)}
89
+ .dsh-tb-pct{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
90
+ @media (hover:hover){
91
+ /* The official row fades in on hover for every reply except the last
92
+ (TurnTailNodeView sets data-actions-reveal="hover" unless the Turn ends with
93
+ the final response). With the strip living in that row, a hover-only row
94
+ would hide the very numbers the plugin exists to show, so keep the row
95
+ visible. Scoped by the row's own data-clock="end", which only the assistant
96
+ tail carries; the user bubble's row is untouched. */
97
+ [data-actions-reveal=hover] [data-clock=end]{opacity:1!important}
98
+ }
99
+ @media (prefers-reduced-motion:reduce){.dsh-tb-seg{transition:none}}
100
+ `
101
+
102
+ /**
103
+ * A usable count from one usage field: missing, non-numeric, NaN, Infinity
104
+ * and negative values all count as zero, so arithmetic below never turns a
105
+ * malformed payload into a broken strip or a "NaN%" label.
106
+ */
107
+ function num(value) {
108
+ const parsed = Number(value)
109
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
110
+ }
111
+
112
+ /** Format a token count the way the shipped pill does: 812 / 12.3K / 716.5K / 1.2M. */
113
+ function formatTokens(value) {
114
+ const n = num(value)
115
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
116
+ if (n >= 1e3) {
117
+ const kilo = (n / 1e3).toFixed(1)
118
+ // 999_950 would otherwise print "1000.0K"; roll it into the next unit.
119
+ return kilo === '1000.0' ? '1.0M' : `${kilo}K`
120
+ }
121
+ return n >= 999.5 ? '1.0K' : String(Math.round(n))
122
+ }
123
+
124
+ /** Cache hit share of prompt-side input, one decimal, trailing `.0` dropped. */
125
+ function cacheHit(usage) {
126
+ const prompt = num(usage?.uncachedInputTokens) + num(usage?.cacheReadTokens) + num(usage?.cacheWriteTokens)
127
+ if (prompt <= 0) return null
128
+ const pct = (num(usage?.cacheReadTokens) / prompt) * 100
129
+ const text = pct >= 99.95 ? '100' : pct.toFixed(1)
130
+ return text.endsWith('.0') ? text.slice(0, -2) : text
131
+ }
132
+
133
+ /**
134
+ * Non-empty buckets with the px width they occupy in the strip.
135
+ *
136
+ * A bucket with any tokens always draws at least MIN_SEGMENT_PX, so a
137
+ * 99.6%-cached Turn still shows a visible grey sliver and a visible green
138
+ * sliver — the strip keeps matching the legend. The rest of the track is
139
+ * split by the real proportions, so the dominant slice stays dominant.
140
+ */
141
+ function segmentsOf(usage) {
142
+ const counts = BUCKETS.map((bucket) => num(usage?.[bucket.key]))
143
+ const total = counts.reduce((sum, count) => sum + count, 0)
144
+ if (total <= 0) return null
145
+ const present = BUCKETS.map((bucket, slot) => ({
146
+ ...bucket,
147
+ tokens: counts[slot],
148
+ weight: counts[slot] / total,
149
+ })).filter((segment) => segment.tokens > 0)
150
+
151
+ const reserved = present.length * MIN_SEGMENT_PX
152
+ const remainder = Math.max(0, TRACK_PX - reserved)
153
+ return present.map((segment) => ({
154
+ ...segment,
155
+ px: MIN_SEGMENT_PX + segment.weight * remainder,
156
+ }))
157
+ }
158
+
159
+ /** One-decimal percentage label, e.g. "99.6%". */
160
+ function percentLabel(segment) {
161
+ return `${(segment.weight * 100).toFixed(1)}%`
162
+ }
163
+
164
+ /** Hover text naming every bucket and its share. */
165
+ function titleOf(name, usage, segments) {
166
+ const hit = cacheHit(usage)
167
+ const lines = segments.map(
168
+ (segment) => `${segment.label} ${formatTokens(segment.tokens)} · ${percentLabel(segment)}`,
169
+ )
170
+ if (hit !== null) lines.unshift(`缓存命中 ${hit}%`)
171
+ return `${name}\n${lines.join('\n')}`
172
+ }
173
+
174
+ /**
175
+ * Segmented strip plus a written legend: one dot, the bucket name, and its
176
+ * share of this Turn — all in the same left-to-right order as the strip.
177
+ * @param {object} props
178
+ * @param {Array} props.segments - non-empty bucket list, in strip order.
179
+ * @param {string} props.title - hover text.
180
+ */
181
+ function TokenBar({ segments, title }) {
182
+ const label = title.replace(/\n/g, ',')
183
+ return h(
184
+ 'span',
185
+ // One accessible name for the whole graphic: the strip and the legend
186
+ // are its visual halves, so they stay out of the accessibility tree and
187
+ // a screen reader reads the hover text once instead of two fragments.
188
+ { className: 'dsh-tb-root', title, role: 'img', 'aria-label': label },
189
+ h(
190
+ 'span',
191
+ { className: 'dsh-tb-track', 'aria-hidden': 'true' },
192
+ segments.map((segment) =>
193
+ h('span', {
194
+ key: segment.key,
195
+ className: 'dsh-tb-seg',
196
+ style: { width: `${segment.px}px`, background: segment.color },
197
+ }),
198
+ ),
199
+ ),
200
+ h(
201
+ 'span',
202
+ { className: 'dsh-tb-legend', 'aria-hidden': 'true' },
203
+ segments.map((segment) =>
204
+ h(
205
+ 'span',
206
+ { key: segment.key, className: 'dsh-tb-item' },
207
+ h('span', { className: 'dsh-tb-dot', style: { background: segment.color } }),
208
+ h('span', { className: 'dsh-tb-name' }, segment.label),
209
+ h('span', { className: 'dsh-tb-pct' }, percentLabel(segment)),
210
+ ),
211
+ ),
212
+ ),
213
+ )
214
+ }
215
+
216
+ /**
217
+ * Per-snapshot index: closing message id → that Turn's accounting.
218
+ *
219
+ * A completed Turn publishes a `turn-tail` location-data entry holding both
220
+ * `closing.finalNode.messageId` and its own `tokenUsage`, so matching the id
221
+ * recovers the same per-Turn figure the shipped popover prints.
222
+ *
223
+ * Built ONCE per snapshot rather than scanned per reply: every mounted seat
224
+ * re-runs its selector on every store update (one per streamed chunk), so N
225
+ * visible replies scanning a list of T Turns would cost O(N·T) each time.
226
+ * The WeakMap is keyed on the snapshot itself, so the index dies with it.
227
+ */
228
+ const USAGE_INDEX = new WeakMap()
229
+
230
+ function usageIndex(snapshot) {
231
+ // Also keeps a non-object snapshot out of the WeakMap below.
232
+ if (snapshot === null || typeof snapshot !== 'object') return undefined
233
+ const cached = USAGE_INDEX.get(snapshot)
234
+ if (cached !== undefined) return cached
235
+ const index = new Map()
236
+ const turns = snapshot.timeline?.turns
237
+ if (turns !== undefined && turns !== null && typeof turns.values === 'function') {
238
+ for (const turn of turns.values()) {
239
+ const data = typeof turn?.data?.get === 'function' ? turn.data.get('turn-tail') : undefined
240
+ if (data === undefined || data === null) continue
241
+ const messageId = data.closing?.finalNode?.messageId
242
+ if (messageId === undefined || messageId === null) continue
243
+ // First writer wins: the strip must not flicker between Turns that
244
+ // somehow share a closing message.
245
+ if (index.has(messageId)) continue
246
+ index.set(messageId, data.tokenUsage)
247
+ }
248
+ }
249
+ USAGE_INDEX.set(snapshot, index)
250
+ return index
251
+ }
252
+
253
+ /**
254
+ * Whether two usages draw the same strip. The selector compares by these
255
+ * four counts instead of by object identity, because the stored
256
+ * `tokenUsage` object is rebuilt on every snapshot and identity would
257
+ * re-render every reply on every streamed chunk.
258
+ */
259
+ function sameUsage(left, right) {
260
+ if (left === right) return true
261
+ if (left === undefined || left === null || right === undefined || right === null) return false
262
+ return (
263
+ num(left.uncachedInputTokens) === num(right.uncachedInputTokens) &&
264
+ num(left.cacheReadTokens) === num(right.cacheReadTokens) &&
265
+ num(left.cacheWriteTokens) === num(right.cacheWriteTokens) &&
266
+ num(left.outputTokens) === num(right.outputTokens)
267
+ )
268
+ }
269
+
270
+ /**
271
+ * The strip for one reply.
272
+ *
273
+ * The capability gate lives OUTSIDE the component that calls the hook: a
274
+ * seat that gets no `useChat` renders nothing at all, so the hook call can
275
+ * never appear or disappear between renders of a mounted instance — which
276
+ * would violate the hook order React enforces.
277
+ */
278
+ function TurnBar(props) {
279
+ const useChat = props?.useChat
280
+ const messageId = props?.messageId
281
+ if (typeof useChat !== 'function' || messageId === undefined || messageId === null) {
282
+ return null
283
+ }
284
+ return h(TurnBarSeat, { useChat, messageId })
285
+ }
286
+
287
+ /** The seat proper: one unconditional selector over this reply's Turn. */
288
+ function TurnBarSeat({ useChat, messageId }) {
289
+ const usage = useChat((snapshot) => usageIndex(snapshot)?.get(messageId), sameUsage)
290
+ if (usage === undefined || usage === null) return null
291
+ const segments = segmentsOf(usage)
292
+ if (segments === null) return null
293
+ return h(TokenBar, { segments, title: titleOf('本轮用量', usage, segments) })
294
+ }
295
+
296
+ return {
297
+ inject: ['slots'],
298
+ apply(ctx) {
299
+ ctx.effect(() => {
300
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID) !== null) return
301
+ const element = document.createElement('style')
302
+ element.id = STYLE_ID
303
+ element.setAttribute('data-plugin', NS)
304
+ element.textContent = CSS
305
+ document.head.appendChild(element)
306
+ return () => element.remove()
307
+ }, 'token-bar: styles')
308
+
309
+ // The strip rides the reply's own icon row. This seat hands over only
310
+ // the durable `messageId`; TurnBar resolves that back to the Turn's
311
+ // accounting through the session kit's `useChat` (see usageIndex).
312
+ // order 95 keeps it to the right of dsh-mnemon's save action (90),
313
+ // i.e. as close to the shipped usage pill as a supported slot allows.
314
+ ctx.slots.inject('conversation.chat.assistant-actions', () =>
315
+ ctx.slots.register(
316
+ {
317
+ name: 'conversation.chat.assistant-actions',
318
+ id: 'token-bar-turn',
319
+ order: 95,
320
+ },
321
+ TurnBar,
322
+ ),
323
+ )
324
+ },
325
+ }
326
+ },
327
+ })
@@ -0,0 +1,6 @@
1
+ # dsh-token-bar bundle patch: the row inserts this package into the host
2
+ # composition. The browser half is declared by `dsh.client` in package.json
3
+ # and needs no row of its own.
4
+ - insert:
5
+ - id: token-bar
6
+ name: 'dsh-token-bar'
Binary file
package/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Host half of dsh-token-bar.
3
+ *
4
+ * Purely presentational: every number the browser half shows is already in
5
+ * the Client (the `tokenUsage` projection and the per-turn `tokenUsage` node
6
+ * data), so this half registers nothing and holds no state. The row exists
7
+ * only because a profile bundle is mounted through its patch entry.
8
+ *
9
+ * @module dsh-token-bar
10
+ */
11
+
12
+ export const name = 'token-bar'
13
+
14
+ /** No host services are needed; the Client half is declared in package.json. */
15
+ export const inject = []
16
+
17
+ /** @param {import('@deepseek-ai/cordis').Context} _ctx - host context (unused). */
18
+ export function apply(_ctx) {}
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "dsh-token-bar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "type": "module",
5
+ "description": "A per-turn token usage strip for DeepSeek Harness: a segmented bar plus a written legend in every reply's icon row, showing this turn's uncached input / cache read / output split.",
6
+ "keywords": [
7
+ "deepseek",
8
+ "deepseek-harness",
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "cordis",
12
+ "client-plugin",
13
+ "token",
14
+ "usage",
15
+ "cache",
16
+ "web"
17
+ ],
18
+ "license": "MIT",
19
+ "main": "index.js",
20
+ "exports": {
21
+ ".": "./index.js",
22
+ "./client": "./client.js",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "index.js",
27
+ "client.js",
28
+ "cordis.patch.yml",
29
+ "README.md",
30
+ "README.en.md",
31
+ "LICENSE",
32
+ "docs"
33
+ ],
34
+ "scripts": {
35
+ "test": "node test-helpers.mjs && node test-served-bundle.mjs",
36
+ "check": "node --check index.js && node --check client.js"
37
+ },
38
+ "engines": {
39
+ "node": ">=20",
40
+ "dsh": ">=0.2.0-rc.1 <0.3.0-0"
41
+ },
42
+ "dsh": {
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ },
46
+ "client": {
47
+ "platform": "web"
48
+ },
49
+ "compatibility": {
50
+ "dsh": ">=0.2.0-rc.1 <0.3.0-0",
51
+ "dshReleases": {
52
+ "0.2.0-rc.2": "compatible"
53
+ }
54
+ }
55
+ },
56
+ "peerDependencies": {
57
+ "react": "^18.2.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "react": {
61
+ "optional": true
62
+ }
63
+ },
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "https://github.com/LobotomyCorporation/dsh-token-bar.git"
67
+ },
68
+ "bugs": {
69
+ "url": "https://github.com/LobotomyCorporation/dsh-token-bar/issues"
70
+ },
71
+ "homepage": "https://github.com/LobotomyCorporation/dsh-token-bar#readme"
72
+ }