status-telemetry: session telemetry pill for the DSH composer dock

Client plugin bundle that contributes one entry to the
`conversation.composer.dock` list slot: a collapsed status pill that expands
in place into a token, performance and context panel. It adds a distinct
entry id and changes nothing the app already renders, so disabling the bundle
restores the previous UI.

- package.json declares dsh.bundle.patch and dsh.client (platform: web)
- cordis.patch.yml inserts the status-telemetry Loader row
- index.js is the mountable host half
- test/client.test.mjs runs offline with node --test (17 pass, 1 skip)

install.sh registers the bundle in dsh.profile.bundles as a bare package
name, which is the only form the loader resolves: it looks the entry up
through node_modules from the profile directory.
This commit is contained in:
Andre Neto
2026-10-08 11:42:36 +01:00
commit 232c26b8d0
10 changed files with 1483 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
node_modules/
npm-debug.log*
*.log
.DS_Store
.vscode/
.idea/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Andre Neto (ags-neto)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+114
View File
@@ -0,0 +1,114 @@
# status-telemetry — rich session status for the DSH composer dock
A DSH **client plugin bundle** that contributes a session status pill to the
`conversation.composer.dock` slot. It sits beside the built-in chat stats entry
and expands in place into a full telemetry panel.
This replaces nothing: the shipped `stats` entry keeps its id and continues to
render. Disabling this bundle restores the previous UI exactly.
## What it shows
Collapsed — one line, in the host's own type and colour language:
```
◔ ● 12 turns · 41 steps · 634k tok · 84% cached · 150 tok/s
```
The glyph dot is a live health reading derived from decode speed
(`ok` / `warn` / `bad`).
Expanded — four sections:
| Section | Readings |
|---|---|
| Conversation | Turns, steps, throughput, output tokens |
| Token usage | Total, billed input, uncached input, cached input, cache write, cache-hit share |
| Performance | LLM time, tool time, average first token, decode speed, tool share of work |
| Context | Occupancy (share of the advertised window), window size, projected prompt, reported prompt, plus a composition bar for system / tools / messages |
Every reading is *derived* from host-computed projections — no client-side log
folding, no polling, no model calls. When a capability is absent in the current
profile, the panel says so instead of rendering a misleading zero.
## Data sources
| Projection | Owner package | Used for |
|---|---|---|
| `sessionStats` | `@deepseek-ai/dsh-session-stats` | turns, steps, LLM/tool/TTFT/decode wall time |
| `tokenUsage` | `@deepseek-ai/dsh-token-meter` | uncached/cached/cache-write input, output |
| `contextPressure` | `@deepseek-ai/dsh-token-meter` | occupancy, window, projected and reported prompt |
| `contextBreakdown` | `@deepseek-ai/dsh-token-meter` | system / tools / messages composition |
Everything reaches the component through the slot framework's standard session
kit (`useProjection`) and locale service. The bundle imports exactly one module,
`react`, from the browser module table.
## Layout
| File | Purpose |
|---|---|
| `package.json` | Bundle manifest: `dsh.bundle.patch` plus `dsh.client` (`platform: web`) |
| `cordis.patch.yml` | Inserts the `status-telemetry` Loader row |
| `index.js` | Host half; mountable, contributes no host behaviour |
| `client.js` | Browser half: the ModuleLoader factory, component, styles, locale |
| `test/client.test.mjs` | Offline suite: formatters, rendered output, registration contract |
| `install.sh` | Root install / uninstall for the profile |
## Install
The plugin is installed into the DSH profile, **not** into `/opt/dsh`. On this
host `/` is mounted read-only, so installing needs root once:
```bash
sudo /srv/workspaces/infra/status-telemetry/install.sh
```
The script remounts `/` read-write, copies the package to
`$DSH_PROFILE_DIR/node_modules/@local/dsh-status-telemetry`, appends the bundle to
`dsh.profile.bundles`, restores ownership, and remounts read-only. It is
idempotent, and `--uninstall` removes everything it added, byte-for-byte
restoring the profile `package.json`.
**Only the bundle list is edited.** A profile composes its bundles plus its own
`cordis.patch.yml`, and listing a bundle applies that bundle's `dsh.bundle.patch`
— so this package's `cordis.patch.yml` supplies the `status-telemetry` Loader
row. Adding that row to the profile patch as well would load the plugin twice,
and the second slot registration at the same id and priority would throw.
Then hard-refresh the page. The profile watcher recomposes the composition live;
`dsh-client-hmr` re-serves an edited `client.js` within ~500 ms. A restart is
only needed if the row does not appear:
```bash
sudo systemctl restart dsh.service # rotates the web token; re-fetch on 401
```
## Test
```bash
cd /srv/workspaces/infra/status-telemetry
node --test test/client.test.mjs
```
React is not present on the Node side of this host (the browser resolves it from
the boot module table), so the suite exercises the component through a small
React double that mimics hook dispatch and element creation; the one cross-check
against real React skips itself when React is unavailable. The suite cannot
verify visual appearance in the live GUI.
## Design notes
- **A distinct entry, not a shadow.** `conversation.composer.dock` is a `list`
slot with unique ids: a second registration at the same `priority` throws, and
reusing `id: "stats"` would require `priority: -1` shadowing. Adding a new id
keeps the built-in entry intact and makes the change reversible by disabling
one row.
- **Styles ride the component.** The stylesheet is rendered as a `<style>`
element inside the entry, so unmounting removes it and the module factory stays
side-effect free.
- **Theme tokens only.** Every colour, radius, and elevation comes from
`--dsw-*` tokens, so the panel follows light/dark switching and future theme
changes.
- **No Harness package imports.** Only `react` is required; the entry reads data
through props and renders its own controls.
+646
View File
@@ -0,0 +1,646 @@
/**
* Browser half of @local/dsh-status-telemetry.
*
* Contributes one entry to the `conversation.composer.dock` list slot: a
* session status pill that expands into a full telemetry panel. It sits beside
* the built-in chat stats entry (which keeps the id `stats`); this entry uses
* its own id so both coexist.
*
* Only session projections and locale are consumed, so the entry needs no
* host-side service beyond `slots`.
*
* Hand-written in the ModuleLoader bundle format, matching the shipped
* `templates/decoration/client.js` shape: executing the bundle registers a
* lazy factory and has no side effects.
*/
const PLUGIN_ID = '@local/dsh-status-telemetry';
const NS = 'statusTelemetry';
const SLOT = 'conversation.composer.dock';
const ENTRY_ID = 'status-telemetry';
/** Style tag identity; one tag per plugin, removed with the bundle's styles. */
const STYLE_TAG_ID = PLUGIN_ID + '/status-telemetry.css';
/** Decode-speed thresholds in tokens/second. */
const TPS_GOOD = 50;
const TPS_FAIR = 20;
/** Average TTFT thresholds in milliseconds. */
const TTFT_GOOD_MS = 800;
const TTFT_FAIR_MS = 2500;
/** Context-occupancy thresholds as a share of the advertised window (0-1). */
const CONTEXT_GOOD = 0.7;
const CONTEXT_FAIR = 0.9;
/** Cache-hit share below which a session is worth flagging (0-1). */
const CACHE_LOW = 0.3;
const CSS = [
'.sl-root{box-sizing:border-box;width:100%;display:flex;justify-content:center;font-size:12px;line-height:18px}',
'.sl-pill{display:flex;align-items:center;gap:6px;max-width:100%;padding:2px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-md);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;cursor:pointer;transition:background .12s ease,color .12s ease,border-color .12s ease}',
'.sl-pill:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
'.sl-pill:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}',
'.sl-pill[aria-expanded="true"]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2)}',
'.sl-icon{flex:none;display:grid;place-items:center;color:var(--dsw-alias-label-tertiary)}',
'.sl-label{display:flex;align-items:center;gap:6px;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.sl-sep{color:var(--dsw-alias-label-caption)}',
'.sl-count{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}',
'.sl-unit{color:var(--dsw-alias-label-tertiary)}',
'.sl-dot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-label-caption)}',
'.sl-dot--ok{background:var(--dsw-alias-state-business-primary)}',
'.sl-dot--warn{background:var(--dsw-alias-state-warn-primary)}',
'.sl-dot--bad{background:var(--dsw-alias-state-error-primary)}',
'.sl-panel{width:100%;max-width:560px;margin:0 auto;display:flex;flex-direction:column;gap:10px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-menu);box-shadow:var(--dsw-elevation-panel);max-height:min(58vh,520px);overflow-y:auto;overscroll-behavior:contain;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}',
'.sl-head{display:flex;align-items:center;gap:8px}',
'.sl-title{flex:1;min-width:0;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.sl-actions{display:flex;align-items:center;gap:4px}',
'.sl-close{display:grid;place-items:center;padding:2px;border:none;border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}',
'.sl-close:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
'.sl-section{display:flex;flex-direction:column;gap:5px}',
'.sl-section + .sl-section{padding-top:9px;border-top:1px solid var(--dsw-alias-separator-primary, var(--dsw-alias-border-l1))}',
'.sl-caption{color:var(--dsw-alias-label-tertiary);font-size:11px;font-weight:500;letter-spacing:.02em;text-transform:uppercase}',
'.sl-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:6px 14px}',
'.sl-cell{display:flex;align-items:baseline;justify-content:space-between;gap:10px;min-width:0}',
'.sl-key{color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.sl-val{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap}',
'.sl-val--ok{color:var(--dsw-alias-state-business-primary)}',
'.sl-val--warn{color:var(--dsw-alias-state-warn-primary)}',
'.sl-val--bad{color:var(--dsw-alias-state-error-primary)}',
'.sl-note{color:var(--dsw-alias-label-tertiary);font-size:11px}',
'.sl-absent{color:var(--dsw-alias-label-caption);font-style:italic}',
'.sl-bar{display:flex;height:4px;border-radius:2px;overflow:hidden;background:var(--dsw-alias-border-l1)}',
'.sl-bar-seg{display:block;height:100%}',
'.sl-bar-seg--system{background:var(--dsw-alias-state-business-primary)}',
'.sl-bar-seg--tools{background:var(--dsw-alias-label-primary-bluish, var(--dsw-alias-state-business-primary))}',
'.sl-bar-seg--messages{background:var(--dsw-alias-label-caption)}'
].join('');
/**
* The plugin stylesheet, rendered as a React element inside the dock entry.
* Mounting the entry inserts it and unmounting removes it, so the plugin leaves
* no trace in the document when it is disabled.
*/
function StyleSheet() {
return React.createElement('style', {
'data-plugin-css': STYLE_TAG_ID,
'data-plugin': PLUGIN_ID,
dangerouslySetInnerHTML: { __html: CSS }
});
}
/** Round to one decimal without trailing `.0`. */
function round1(value) {
const rounded = Math.round(value * 10) / 10;
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
}
/** Thousands-separated integer. */
function group(value) {
try {
return new Intl.NumberFormat().format(value);
} catch {
return String(value);
}
}
/** Compact token count: 1.2M, 34.5k, 812. */
function compactTokens(value) {
const n = Number(value);
if (!Number.isFinite(n) || n <= 0) return '0';
if (n >= 1e6) return round1(n / 1e6) + 'M';
if (n >= 1e3) return round1(n / 1e3) + 'k';
return String(Math.round(n));
}
/** Compact duration: 812ms, 45.2s, 2m42s, 1h03m. */
function compactDuration(ms) {
const n = Number(ms);
if (!Number.isFinite(n) || n <= 0) return '0ms';
if (n < 1000) return Math.round(n) + 'ms';
const seconds = n / 1000;
if (seconds < 60) return round1(seconds) + 's';
const whole = Math.round(seconds);
if (whole < 3600) return Math.floor(whole / 60) + 'm' + String(whole % 60).padStart(2, '0') + 's';
return Math.floor(whole / 3600) + 'h' + String(Math.floor((whole % 3600) / 60)).padStart(2, '0') + 'm';
}
/** Prompt-side billed input across the three disjoint buckets. */
function billedInput(usage) {
return (usage.uncachedInputTokens || 0) + (usage.cacheReadTokens || 0) + (usage.cacheWriteTokens || 0);
}
/** Cache-hit share of billed input, or null when nothing was billed. */
function cacheHitRatio(usage) {
const total = billedInput(usage);
if (total <= 0) return null;
return (usage.cacheReadTokens || 0) / total;
}
/** Percentage text; keeps sub-100 rounding honest for near-perfect hits. */
function percentText(ratio) {
const percent = ratio * 100;
if (percent >= 99.95) return '100';
if (percent >= 10) return String(Math.round(percent));
return round1(percent);
}
/** Tokens/second over decode time, or null when decode time is unknown. */
function tokensPerSecond(stats) {
if (!stats || !(stats.decodeMs > 0) || !(stats.decodeTokens > 0)) return null;
return stats.decodeTokens / (stats.decodeMs / 1000);
}
/** Average TTFT in milliseconds, or null when no step reported a first token. */
function averageTtft(stats) {
if (!stats || !(stats.ttftSteps > 0)) return null;
return stats.ttftMs / stats.ttftSteps;
}
/** Context occupancy share of the advertised window, or null when unknown. */
function contextOccupancy(pressure) {
if (!pressure || !(pressure.contextWindow > 0)) return null;
const used = pressure.projectedTokens ?? pressure.pressureTokens;
if (!(used > 0)) return null;
return Math.min(1, used / pressure.contextWindow);
}
/** Severity bucket for a value against descending thresholds. */
function severity(value, good, fair) {
if (value === null || value === undefined) return 'none';
if (value >= good) return 'ok';
if (value >= fair) return 'warn';
return 'bad';
}
/** Severity for a share where lower is better. */
function severityInverse(value, good, fair) {
if (value === null || value === undefined) return 'none';
if (value <= good) return 'ok';
if (value <= fair) return 'warn';
return 'bad';
}
/** Per-document SVG helpers. */
function svgProps(size) {
return {
viewBox: '0 0 16 16',
width: size,
height: size,
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.4,
strokeLinecap: 'round',
strokeLinejoin: 'round',
'aria-hidden': 'true'
};
}
/** Gauge glyph matching the host's stats affordance. */
function GaugeIcon({ size = 14 }) {
const h = React.createElement;
return h(
'svg',
svgProps(size),
h('path', { d: 'M2.2 11.4a6.2 6.2 0 1 1 11.6 0' }),
h('path', { d: 'M8 11.2 10.9 7.3' }),
h('circle', { cx: 8, cy: 11.4, r: 1 })
);
}
/** Close glyph for the expanded panel. */
function CloseIcon({ size = 12 }) {
const h = React.createElement;
return h('svg', svgProps(size), h('path', { d: 'M3.6 3.6l8.8 8.8M12.4 3.6l-8.8 8.8' }));
}
/**
* One labelled reading.
* @param props - label, formatted value, optional severity, optional note.
*/
function Cell({ label, value, severity: state, note }) {
const h = React.createElement;
const valueClass = state && state !== 'none' ? 'sl-val sl-val--' + state : 'sl-val';
return h(
'div',
{ className: 'sl-cell' },
h('span', { className: 'sl-key' }, label),
note
? h('span', null, h('span', { className: valueClass }, value), h('span', { className: 'sl-note' }, ' ', note))
: h('span', { className: valueClass }, value)
);
}
/** A titled block of readings. */
function Section({ title, children }) {
const h = React.createElement;
return h('section', { className: 'sl-section' }, h('div', { className: 'sl-caption' }, title), h('div', { className: 'sl-grid' }, children));
}
/** Message rows rendered when no projection has arrived yet. */
function Absent({ children }) {
const h = React.createElement;
return h('div', { className: 'sl-absent' }, children);
}
/** Composed context bar: system / tools / messages shares. */
function CompositionBar({ breakdown, t }) {
const h = React.createElement;
const total = (breakdown.systemTokens || 0) + (breakdown.toolsTokens || 0) + (breakdown.messageTokens || 0);
if (!(total > 0)) return h(Absent, null, t('context.absent'));
const segments = [
['system', breakdown.systemTokens || 0],
['tools', breakdown.toolsTokens || 0],
['messages', breakdown.messageTokens || 0]
];
return h(
'div',
{ className: 'sl-bar', role: 'img', 'aria-label': t('context.barLabel') },
segments.map(([kind, tokens]) =>
h('span', { key: kind, className: 'sl-bar-seg sl-bar-seg--' + kind, style: { width: (tokens / total) * 100 + '%' } })
)
);
}
/**
* Session status pill and telemetry panel.
*
* Props are supplied by the slot framework: `useProjection` reads host-computed
* session projections, `t` is the bound locale function for this plugin's
* namespace.
*/
function StatusTelemetry({ useProjection, t }) {
const h = React.createElement;
const [open, setOpen] = React.useState(false);
const usage = useProjection('tokenUsage');
const stats = useProjection('sessionStats');
const pressure = useProjection('contextPressure');
const breakdown = useProjection('contextBreakdown');
const speed = tokensPerSecond(stats);
const cacheHit = usage !== undefined && usage !== null ? cacheHitRatio(usage) : null;
const turns = stats ? stats.turns : 0;
const steps = stats ? stats.steps : 0;
const totalTokens = usage !== undefined && usage !== null ? billedInput(usage) + (usage.outputTokens || 0) : 0;
// Nothing durable has been recorded for this session yet: stay out of the way.
if (steps === 0 && totalTokens === 0) return null;
const speedState = severity(speed, TPS_GOOD, TPS_FAIR);
const summary = [
h('span', { key: 'turns', className: 'sl-count' }, group(turns)),
h('span', { key: 'turns-u', className: 'sl-unit' }, turns === 1 ? ' turn' : ' turns'),
h('span', { key: 'sep1', className: 'sl-sep', 'aria-hidden': true }, '·'),
h('span', { key: 'steps', className: 'sl-count' }, group(steps)),
h('span', { key: 'steps-u', className: 'sl-unit' }, steps === 1 ? ' step' : ' steps')
];
if (totalTokens > 0) {
summary.push(h('span', { key: 'sep2', className: 'sl-sep', 'aria-hidden': true }, '·'));
summary.push(h('span', { key: 'tok', className: 'sl-count' }, compactTokens(totalTokens)));
summary.push(h('span', { key: 'tok-u', className: 'sl-unit' }, ' tok'));
}
if (cacheHit !== null) {
summary.push(h('span', { key: 'sep3', className: 'sl-sep', 'aria-hidden': true }, '·'));
summary.push(h('span', { key: 'cache', className: 'sl-count' }, percentText(cacheHit) + '%'));
summary.push(h('span', { key: 'cache-u', className: 'sl-unit' }, ' cached'));
}
if (speed !== null) {
summary.push(h('span', { key: 'sep4', className: 'sl-sep', 'aria-hidden': true }, '·'));
summary.push(h('span', { key: 'tps', className: 'sl-count' }, round1(speed)));
summary.push(h('span', { key: 'tps-u', className: 'sl-unit' }, ' tok/s'));
}
const pill = h(
'button',
{
type: 'button',
className: 'sl-pill',
'data-status-telemetry-pill': true,
'aria-haspopup': 'dialog',
'aria-expanded': open,
'aria-label': t('pill.aria', { turns: group(turns), steps: group(steps) }),
onClick: () => setOpen(!open)
},
h('span', { className: 'sl-icon' }, h(GaugeIcon, null)),
speedState !== 'none' ? h('span', { className: 'sl-dot sl-dot--' + speedState, 'aria-hidden': true }) : null,
h('span', { className: 'sl-label' }, summary)
);
if (!open) {
return h('div', { className: 'sl-root', 'data-status-telemetry': true }, h(StyleSheet, { key: 'style' }), pill);
}
const ttft = averageTtft(stats);
const occupancy = contextOccupancy(pressure);
const tpsState = severity(speed, TPS_GOOD, TPS_FAIR);
const ttftState = ttft === null ? 'none' : severityInverse(ttft, TTFT_GOOD_MS, TTFT_FAIR_MS);
const occupancyState = occupancy === null ? 'none' : severityInverse(occupancy, CONTEXT_GOOD, CONTEXT_FAIR);
const cacheState = cacheHit === null ? 'none' : cacheHit < CACHE_LOW ? 'warn' : 'ok';
const conversation = h(
Section,
{ title: t('section.conversation'), key: 'conversation' },
h(Cell, { key: 'turns', label: t('count.turns'), value: group(turns) }),
h(Cell, { key: 'steps', label: t('count.steps'), value: group(steps) }),
speed !== null ? h(Cell, { key: 'tps', label: t('label.tps'), value: round1(speed) + ' tok/s', severity: tpsState }) : null,
usage !== undefined && usage !== null && (usage.outputTokens || 0) > 0
? h(Cell, { key: 'output', label: t('usage.output'), value: group(usage.outputTokens) })
: null
);
let tokens = null;
if (usage !== undefined && usage !== null) {
const billed = billedInput(usage);
tokens = h(
Section,
{ title: t('section.tokens'), key: 'tokens' },
h(Cell, { key: 'total', label: t('usage.total'), value: group(totalTokens) }),
h(Cell, { key: 'billed', label: t('usage.billed'), value: group(billed) }),
h(Cell, { key: 'uncached', label: t('usage.uncached'), value: group(usage.uncachedInputTokens || 0) }),
h(Cell, { key: 'cacheRead', label: t('usage.cacheRead'), value: group(usage.cacheReadTokens || 0) }),
(usage.cacheWriteTokens || 0) > 0
? h(Cell, { key: 'cacheWrite', label: t('usage.cacheWrite'), value: group(usage.cacheWriteTokens) })
: null,
cacheHit !== null
? h(Cell, {
key: 'cacheHit',
label: t('usage.cacheHit'),
value: percentText(cacheHit) + '%',
severity: cacheState
})
: null
);
}
const performance =
stats && (stats.llmMs > 0 || stats.toolMs > 0 || ttft !== null || speed !== null)
? h(
Section,
{ title: t('section.performance'), key: 'performance' },
stats.llmMs > 0 ? h(Cell, { key: 'llm', label: t('perf.llm'), value: compactDuration(stats.llmMs) }) : null,
stats.toolMs > 0 ? h(Cell, { key: 'tool', label: t('perf.tool'), value: compactDuration(stats.toolMs) }) : null,
ttft !== null
? h(Cell, { key: 'ttft', label: t('perf.ttft'), value: compactDuration(ttft), severity: ttftState })
: null,
speed !== null ? h(Cell, { key: 'tps2', label: t('perf.tps'), value: round1(speed) + ' tok/s', severity: tpsState }) : null,
stats.llmMs > 0 && stats.toolMs > 0
? h(Cell, {
key: 'share',
label: t('perf.toolShare'),
value: percentText(Math.min(1, stats.toolMs / (stats.llmMs + stats.toolMs))) + '%'
})
: null
)
: null;
const contextParts = [];
if (pressure && (pressure.pressureTokens || pressure.projectedTokens)) {
contextParts.push(
h(Cell, {
key: 'ctx',
label: t('context.occupancy'),
value: occupancy !== null ? percentText(occupancy) + '%' : compactTokens(pressure.projectedTokens ?? pressure.pressureTokens) + ' tok',
severity: occupancyState
})
);
}
if (pressure && pressure.contextWindow > 0) {
contextParts.push(h(Cell, { key: 'window', label: t('context.window'), value: group(pressure.contextWindow) }));
}
if (pressure && pressure.projectedTokens > 0) {
contextParts.push(h(Cell, { key: 'projected', label: t('context.projected'), value: group(pressure.projectedTokens) }));
}
if (pressure && pressure.pressureTokens > 0) {
contextParts.push(h(Cell, { key: 'reported', label: t('context.reported'), value: group(pressure.pressureTokens) }));
}
const contextSection = contextParts.length
? h(
Section,
{ title: t('section.context'), key: 'context' },
contextParts,
breakdown ? h(CompositionBar, { key: 'bar', breakdown, t }) : null,
breakdown
? h('div', { key: 'legend', className: 'sl-note' }, t('context.legend'))
: null
)
: null;
const panel = h(
'div',
{
className: 'sl-panel',
role: 'dialog',
'data-status-telemetry-panel': true,
'aria-label': t('panel.title'),
onKeyDown: (event) => {
if (event.key === 'Escape') {
event.stopPropagation();
setOpen(false);
}
}
},
h(
'div',
{ className: 'sl-head' },
h('span', { className: 'sl-icon' }, h(GaugeIcon, null)),
h('span', { className: 'sl-title' }, t('panel.title')),
h(
'span',
{ className: 'sl-actions' },
h(
'button',
{
type: 'button',
className: 'sl-close',
'data-status-telemetry-close': true,
'aria-label': t('panel.close'),
onClick: () => setOpen(false)
},
h(CloseIcon, null)
)
)
),
conversation,
tokens,
tokens === null ? h(Absent, { key: 'notokens' }, t('absent.tokens')) : null,
performance,
performance === null ? h(Absent, { key: 'noperf' }, t('absent.performance')) : null,
contextSection,
contextSection === null ? h(Absent, { key: 'noctx' }, t('absent.context')) : null
);
return h(
'div',
{ className: 'sl-root sl-root--open', 'data-status-telemetry': true, 'data-status-telemetry-open': true },
h(StyleSheet, { key: 'style' }),
pill,
panel
);
}
/** English dictionary. Missing keys fall back to the key text. */
const en = {
'panel.title': 'Session telemetry',
'panel.close': 'Collapse telemetry',
'pill.aria': 'Session telemetry: {turns} turns, {steps} steps. Expand for detail.',
'section.conversation': 'Conversation',
'section.tokens': 'Token usage',
'section.performance': 'Performance',
'section.context': 'Context',
'count.turns': 'Turns',
'count.steps': 'Steps',
'label.tps': 'Throughput',
'usage.total': 'Total',
'usage.billed': 'Billed input',
'usage.uncached': 'Uncached input',
'usage.cacheRead': 'Cached input',
'usage.cacheWrite': 'Cache write',
'usage.cacheHit': 'Cache hit',
'usage.output': 'Output',
'perf.llm': 'LLM time',
'perf.tool': 'Tool time',
'perf.ttft': 'Avg first token',
'perf.tps': 'Decode speed',
'perf.toolShare': 'Tool share of work',
'context.occupancy': 'Occupancy',
'context.window': 'Window',
'context.projected': 'Projected prompt',
'context.reported': 'Reported prompt',
'context.legend': 'Composition is a heuristic: system, tools, then messages.',
'context.barLabel': 'Context composition by heuristic tokens',
'context.absent': 'No context composition recorded yet.',
'absent.tokens': 'Token accounting is unavailable in this profile.',
'absent.performance': 'No model timing recorded yet.',
'absent.context': 'Context pressure is unavailable in this profile.'
};
const zh = {
'panel.title': '会话遥测',
'panel.close': '收起遥测',
'pill.aria': '会话遥测:{turns} 轮,{steps} 步。展开查看详情。',
'section.conversation': '会话',
'section.tokens': 'Token 用量',
'section.performance': '性能',
'section.context': '上下文',
'count.turns': '轮次',
'count.steps': '步数',
'label.tps': '吞吐',
'usage.total': '总计',
'usage.billed': '计费输入',
'usage.uncached': '未缓存输入',
'usage.cacheRead': '缓存读取',
'usage.cacheWrite': '缓存写入',
'usage.cacheHit': '缓存命中',
'usage.output': '输出',
'perf.llm': '模型耗时',
'perf.tool': '工具耗时',
'perf.ttft': '平均首字',
'perf.tps': '解码速度',
'perf.toolShare': '工具耗时占比',
'context.occupancy': '占用',
'context.window': '窗口',
'context.projected': '预估提示',
'context.reported': '上报提示',
'context.legend': '组成为启发式估算:系统、工具、消息。',
'context.barLabel': '按启发式 Token 估算的上下文组成',
'context.absent': '尚无上下文组成记录。',
'absent.tokens': '此配置不支持 Token 统计。',
'absent.performance': '尚无模型计时记录。',
'absent.context': '此配置不支持上下文压力。'
};
let React = null;
/**
* Mount the Client contributions.
* @param ctx - Client root context.
*/
function apply(ctx) {
ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'status-telemetry: dictionaries');
const t = ctx.locale.bind(NS);
ctx.slots.inject(SLOT, () =>
ctx.slots.register(
{
name: SLOT,
id: ENTRY_ID,
order: 1,
locale: NS,
inject: () => ({})
},
StatusTelemetry
)
);
}
const inject = ['slots', 'locale'];
// Browser: register the lazy factory. Node (tests): export the same values.
if (typeof window !== 'undefined' && window.__ModuleLoader__) {
window.__ModuleLoader__.load({
id: PLUGIN_ID,
factory(require) {
React = require('react');
return { inject, apply };
}
});
}
export {
PLUGIN_ID,
NS,
SLOT,
ENTRY_ID,
inject,
apply,
StatusTelemetry,
Cell,
Section,
CompositionBar,
Absent,
StyleSheet,
CSS,
round1,
group,
compactTokens,
compactDuration,
billedInput,
cacheHitRatio,
percentText,
tokensPerSecond,
averageTtft,
contextOccupancy,
severity,
severityInverse,
en,
zh
};
/** Internals and seams the offline test suite exercises. */
export const __test = {
setReact(value) {
React = value;
},
CSS,
round1,
group,
compactTokens,
compactDuration,
billedInput,
cacheHitRatio,
percentText,
tokensPerSecond,
averageTtft,
contextOccupancy,
severity,
severityInverse,
StatusTelemetry,
Cell,
Section,
CompositionBar,
Absent,
StyleSheet,
en,
zh,
/** Values the component treats as thresholds. */
thresholds: { TPS_GOOD, TPS_FAIR, TTFT_GOOD_MS, TTFT_FAIR_MS, CONTEXT_GOOD, CONTEXT_FAIR, CACHE_LOW }
};
+12
View File
@@ -0,0 +1,12 @@
# Bundle patch for @local/dsh-status-telemetry.
#
# This file is applied because the profile lists the bundle in
# dsh.profile.bundles. Do not also insert this row into the profile's own
# cordis.patch.yml: the plugin would then load twice, and the second slot
# registration at the same id and priority would throw.
#
# `insert` names are anchored beside this file, so the specifier below resolves
# to this directory once the bundle is installed in the profile.
- insert:
- id: status-telemetry
name: '@local/dsh-status-telemetry'
+10
View File
@@ -0,0 +1,10 @@
/**
* Host half of the status-telemetry bundle.
*
* The Client module owns everything the user sees; this half only has to exist
* and be mountable so the Loader row resolves and `client-modules` can derive
* the browser bundle path from this package's manifest.
*/
/** Mount the host half. It contributes no host-side behaviour. */
export function apply() {}
Executable
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env bash
#
# Install or remove the status-telemetry plugin for the DSH web profile.
#
# Must run as root on the Pi: / is mounted read-only in normal operation, so the
# script remounts it read-write, installs, and remounts read-only again.
#
# sudo ./install.sh # install (or update) the plugin
# sudo ./install.sh --uninstall # remove it, restoring the profile
# sudo ./install.sh --no-remount # fail instead of remounting / read-write
#
# Idempotent: re-running replaces the installed copy and re-asserts the profile
# rows without duplicating anything.
set -euo pipefail
readonly PLUGIN_NAME='@local/dsh-status-telemetry'
readonly ROW_ID='status-telemetry'
profile_dir="${DSH_PROFILE_DIR:-/home/dsh/.dsh/profiles/web}"
src_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
mode='install'
allow_remount=1
for arg in "$@"; do
case "$arg" in
--uninstall) mode='uninstall' ;;
--no-remount) allow_remount=0 ;;
-h|--help) sed -n '2,13p' "${BASH_SOURCE[0]}"; exit 0 ;;
*) printf 'unknown argument: %s\n' "$arg" >&2; exit 2 ;;
esac
done
log() { printf ' %s\n' "$*"; }
step() { printf '\n== %s\n' "$*"; }
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
[ -d "$profile_dir" ] || die "profile directory not found: $profile_dir"
readonly profile_json="$profile_dir/package.json"
readonly owner="$(stat -c '%U:%G' "$profile_dir")"
readonly as_root="$([ "$(id -u)" -eq 0 ] && echo 1 || echo 0)"
# --- read-only root handling ------------------------------------------------
# Root is needed only when the profile lives on a read-only mount and must be
# remounted, or when ownership has to be restored. A user who can already write
# the profile (a widened mount, or the profile's own owner) installs without it.
remounted=0
ensure_writable() {
if [ -w "$profile_dir" ]; then return 0; fi
[ "$as_root" -eq 1 ] || die "$profile_dir is not writable; re-run as root (sudo $0 $*)"
[ "$allow_remount" -eq 1 ] || die "$profile_dir is not writable and --no-remount was given"
step "remounting / read-write (profile is on the read-only root)"
mount -o remount,rw / || die "could not remount / read-write"
remounted=1
}
restore_ro() {
[ "$remounted" -eq 1 ] || return 0
step "restoring / to read-only"
sync
mount -o remount,ro / || log "warning: / left read-write; remount it manually when convenient"
remounted=0
}
# Only root may change ownership, and only root's remount may need undoing.
restore_owner() {
[ "$as_root" -eq 1 ] || return 0
step "restoring ownership"
chown -R "$owner" "$profile_dir"
}
trap 'restore_ro' EXIT
ensure_writable
# --- profile edits ----------------------------------------------------------
# The editor lives beside this script so it can be tested on its own; it keeps
# the profile manifest valid JSON and the operation idempotent.
edit_profile() { # <add|remove>
node "$src_dir/profile-bundles.mjs" "$1" "$profile_json" "$PLUGIN_NAME"
}
# --- host steps -------------------------------------------------------------
target_dir="$profile_dir/node_modules/$PLUGIN_NAME"
if [ "$mode" = 'uninstall' ]; then
step "deregistering the bundle"
# Removing the bundle is enough: the bundle's own patch supplies its row.
edit_profile remove
step "removing installed package"
if [ -d "$target_dir" ]; then
rm -rf -- "${target_dir:?}"
log "removed $target_dir"
else
log "not installed at $target_dir"
fi
restore_owner
restore_ro
printf '\nRemoved %s. Reload the web page; no restart is required.\n' "$PLUGIN_NAME"
exit 0
fi
step "installing package into the profile"
mkdir -p "$profile_dir/node_modules/$PLUGIN_NAME"
for file in package.json index.js client.js cordis.patch.yml; do
[ -f "$src_dir/$file" ] || die "missing source file: $src_dir/$file"
install -m 0644 "$src_dir/$file" "$target_dir/$file"
log "installed $file"
done
step "registering the bundle"
# Only the bundle list is edited. Listing the bundle composes its own
# cordis.patch.yml, which inserts the status-telemetry row; inserting that row
# into the profile patch as well would load the plugin twice, and the second
# slot registration at the same id and priority would throw.
edit_profile add
restore_owner
restore_ro
printf '\nInstalled %s\n' "$PLUGIN_NAME"
printf ' profile: %s\n' "$profile_dir"
printf ' installed: %s\n' "$target_dir"
printf ' Loader row: %s (from the bundle patch)\n' "$ROW_ID"
printf '\nReload the web page (hard refresh). The profile watcher recomposes the\n'
printf 'composition live; if the entry does not appear, restart the service:\n'
printf ' sudo systemctl restart dsh.service\n'
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@local/dsh-status-telemetry",
"version": "1.0.0",
"private": true,
"description": "Rich session status and telemetry for the DSH composer dock.",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ags-neto/dsh-status-telemetry.git"
},
"scripts": {
"test": "node --test test/client.test.mjs"
},
"type": "module",
"exports": {
".": "./index.js",
"./client": "./client.js"
},
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
},
"client": {
"platform": "web",
"immediately": true,
"inject": [
"@deepseek-ai/dsh-client-ui-conversation"
]
}
}
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Add or remove the status-telemetry bundle in a DSH profile manifest.
*
* node profile-bundles.mjs <add|remove> <profile-package.json> <plugin-name>
*
* The bundle list in `dsh.profile.bundles` is the single registration point: a
* profile composes its bundles plus its own cordis.patch.yml, so listing the
* bundle applies that bundle's own patch. The profile patch is never touched.
*
* Idempotent, and a `remove` restores the list to exactly what `add` found.
*/
import { readFileSync, writeFileSync } from 'node:fs';
const [action, profileJson, pluginName] = process.argv.slice(2);
if (action !== 'add' && action !== 'remove') {
console.error(`usage: profile-bundles.mjs <add|remove> <profile-package.json> <plugin-name>`);
process.exit(2);
}
if (!profileJson || !pluginName) {
console.error('usage: profile-bundles.mjs <add|remove> <profile-package.json> <plugin-name>');
process.exit(2);
}
let doc;
try {
doc = JSON.parse(readFileSync(profileJson, 'utf8'));
} catch (error) {
console.error(`cannot read profile manifest ${profileJson}: ${error.message}`);
process.exit(1);
}
const bundles = doc?.dsh?.profile?.bundles;
if (!Array.isArray(bundles)) {
console.error(`profile manifest ${profileJson} has no dsh.profile.bundles array`);
process.exit(1);
}
// The list holds bare package names: the loader resolves each entry through
// Node's node_modules lookup from the profile directory, so the package only
// has to sit in `<profile>/node_modules/<name>`. A `file:` specifier is not a
// package name and the loader skips it at startup.
const specifier = pluginName;
if (action === 'add') {
if (bundles.includes(specifier)) {
console.log(`bundles already lists ${pluginName}`);
} else {
bundles.push(specifier);
console.log(`bundled ${pluginName}`);
}
} else {
const before = bundles.length;
// Also drop a legacy `file:` specifier, in case an older install used one.
for (const candidate of [specifier, pluginName]) {
const at = bundles.indexOf(candidate);
if (at !== -1) bundles.splice(at, 1);
}
console.log(bundles.length < before ? `unbundled ${pluginName}` : `bundles does not list ${pluginName}`);
}
writeFileSync(profileJson, `${JSON.stringify(doc, null, 2)}\n`);
+450
View File
@@ -0,0 +1,450 @@
/**
* Offline test suite for the status-telemetry client module.
*
* The client bundle is hand-written plain JS, so nothing type-checks it; this
* suite exercises the real module through a tiny React double that mimics the
* hook dispatch order the component relies on. It covers:
* - pure formatters and derivations,
* - rendered output for populated, absent, and empty sessions,
* - the slot registration contract the framework validates at load.
*
* Run: node --test test/
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join } from 'node:path';
const here = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
// The client bundle is an ES module here (package type: module) even though the
// browser consumes it as a ModuleLoader bundle; the test imports it directly.
const mod = await import(pathToFileURL(join(here, '..', 'client.js')).href);
const T = mod.__test;
// React is not part of the Node installation: the browser resolves it from the
// boot module table. Use it for a cross-check only when it happens to be present.
let realReact = null;
try {
realReact = require('/opt/dsh/node_modules/react');
} catch {
realReact = null;
}
/**
* Minimal React double: element creation plus the hook dispatch the component
* uses. `useState` answers from a queue so one render can be scripted.
*/
function makeReact(states = []) {
let cursor = 0;
const setterCalls = [];
return {
createElement(type, props, ...children) {
return {
type,
props: props ?? {},
children: children.flat().filter((child) => child !== null && child !== undefined && child !== false)
};
},
useState(initial) {
const index = cursor++;
const value = index < states.length ? states[index] : initial;
const setter = (next) => setterCalls.push(next);
return [value, setter];
},
__setterCalls: setterCalls
};
}
/** Flatten an element tree to its text content. */
function textOf(node) {
if (node === null || node === undefined || node === false) return '';
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(textOf).join('');
if (typeof node.type === 'function') return textOf(node.type({ ...node.props, children: node.children }));
return (node.children ?? []).map(textOf).join('');
}
/** Every element in the tree, depth first, expanding function components. */
function elementsOf(node, out = []) {
if (!node || typeof node !== 'object') return out;
if (Array.isArray(node)) {
node.forEach((child) => elementsOf(child, out));
return out;
}
out.push(node);
if (typeof node.type === 'function') {
elementsOf(node.type({ ...node.props, children: node.children }), out);
return out;
}
(node.children ?? []).forEach((child) => elementsOf(child, out));
return out;
}
/** Find the first element with the given class. */
function findByClass(tree, className) {
return elementsOf(tree).find((element) => String(element.props.className ?? '').split(' ').includes(className));
}
/** Find the first element carrying the given data attribute. */
function findByAttr(tree, attr) {
return elementsOf(tree).find((element) => element.props[attr] !== undefined);
}
/**
* Render the component with scripted projections.
* @param projections - map of projection key to value; absent keys read undefined.
* @param options - `open` scripts the initial useState value, `t` overrides the locale function.
*/
function render(projections, options = {}) {
const react = makeReact(options.open ? [options.open] : []);
T.setReact(react);
const seen = [];
const useProjection = (key) => {
seen.push(key);
return projections[key];
};
const t = options.t ?? ((key, params) => (params ? T.en[key]?.replace(/\{(\w+)\}/g, (m, n) => String(params[n] ?? m)) ?? key : T.en[key] ?? key));
const tree = T.StatusTelemetry({ useProjection, t });
return { tree, seen, react };
}
const POPULATED = {
sessionStats: {
turns: 12,
steps: 41,
llmMs: 96_400,
toolMs: 31_200,
ttftMs: 3_600,
ttftSteps: 9,
decodeMs: 42_000,
decodeTokens: 6_300
},
tokenUsage: {
uncachedInputTokens: 82_000,
cacheReadTokens: 512_000,
cacheWriteTokens: 14_000,
outputTokens: 26_000
},
contextPressure: { projectedTokens: 96_000, pressureTokens: 88_000, contextWindow: 128_000 },
contextBreakdown: { systemTokens: 4_000, toolsTokens: 12_000, messageTokens: 80_000 }
};
test('registration contract matches the slot framework', () => {
assert.equal(mod.SLOT, 'conversation.composer.dock');
// A list slot rejects a duplicate id at the same priority, so the entry must
// not reuse the built-in chat entry's id.
assert.notEqual(mod.ENTRY_ID, 'stats');
assert.ok(mod.inject.includes('slots'));
assert.ok(mod.inject.includes('locale'));
});
test('apply registers one entry with locale and a distinct id', () => {
const registered = [];
const injected = [];
const localeRegistrations = [];
const ctx = {
effect: (fn) => fn(),
locale: {
register: (ns, dicts) => {
localeRegistrations.push({ ns, dicts });
return () => {};
},
bind: (ns) => (key) => `[${ns}]${key}`
},
slots: {
inject: (key, callback) => {
injected.push(key);
return callback();
},
register: (options, component) => {
registered.push({ options, component });
return () => {};
}
}
};
mod.apply(ctx);
assert.deepEqual(injected, ['conversation.composer.dock']);
assert.equal(registered.length, 1);
const { options, component } = registered[0];
assert.equal(options.name, 'conversation.composer.dock');
assert.equal(options.id, mod.ENTRY_ID);
assert.equal(options.locale, mod.NS);
assert.equal(typeof options.order, 'number');
assert.equal(typeof options.inject, 'function');
assert.equal(typeof component, 'function');
assert.deepEqual(Object.keys(options.inject()), []);
// Locale dictionaries for the plugin namespace must be available before the
// entry renders, or `t` throws on an unregistered namespace.
assert.equal(localeRegistrations.length, 1);
assert.equal(localeRegistrations[0].ns, mod.NS);
assert.ok(localeRegistrations[0].dicts.en['panel.title']);
});
test('formatters render professional, unambiguous values', () => {
assert.equal(T.compactTokens(0), '0');
assert.equal(T.compactTokens(812), '812');
assert.equal(T.compactTokens(6_300), '6.3k');
assert.equal(T.compactTokens(1_240_000), '1.2M');
assert.equal(T.compactDuration(0), '0ms');
assert.equal(T.compactDuration(812), '812ms');
assert.equal(T.compactDuration(45_200), '45.2s');
assert.equal(T.compactDuration(162_000), '2m42s');
assert.equal(T.compactDuration(3_780_000), '1h03m');
assert.equal(T.round1(48.04), '48');
assert.equal(T.round1(48.06), '48.1');
assert.equal(T.group(1234567), '1,234,567');
assert.equal(T.percentText(0.9999), '100');
assert.equal(T.percentText(0.862), '86');
assert.equal(T.percentText(0.0412), '4.1');
});
test('derivations are defensive about absent and zeroed projections', () => {
const usage = POPULATED.tokenUsage;
assert.equal(T.billedInput(usage), 82_000 + 512_000 + 14_000);
assert.equal(T.cacheHitRatio(usage), 512_000 / 608_000);
assert.equal(T.cacheHitRatio({ uncachedInputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }), null);
assert.equal(T.tokensPerSecond(POPULATED.sessionStats), 6_300 / 42);
assert.equal(T.tokensPerSecond({ decodeMs: 0, decodeTokens: 0 }), null);
assert.equal(T.tokensPerSecond(undefined), null);
assert.equal(T.averageTtft(POPULATED.sessionStats), 3_600 / 9);
assert.equal(T.averageTtft({ ttftMs: 0, ttftSteps: 0 }), null);
assert.equal(T.contextOccupancy(POPULATED.contextPressure), 96_000 / 128_000);
assert.equal(T.contextOccupancy({ contextWindow: 0 }), null);
assert.equal(T.contextOccupancy({}), null);
// severity: higher is better; severityInverse: lower is better.
assert.equal(T.severity(60, 50, 20), 'ok');
assert.equal(T.severity(30, 50, 20), 'warn');
assert.equal(T.severity(10, 50, 20), 'bad');
assert.equal(T.severity(null, 50, 20), 'none');
assert.equal(T.severityInverse(100, 800, 2500), 'ok');
assert.equal(T.severityInverse(1_500, 800, 2500), 'warn');
assert.equal(T.severityInverse(4_000, 800, 2500), 'bad');
});
test('a session with activity shows a collapsed pill with real figures', () => {
const { tree, seen } = render({ sessionStats: POPULATED.sessionStats, tokenUsage: POPULATED.tokenUsage });
const pill = findByAttr(tree, 'data-status-telemetry-pill');
assert.ok(pill, 'pill is rendered');
assert.equal(pill.props['aria-expanded'], false);
assert.equal(pill.props.type, 'button');
const text = textOf(pill);
assert.match(text, /12/);
assert.match(text, /turns/);
assert.match(text, /41/);
assert.match(text, /steps/);
assert.match(text, /634k/); // (82k + 512k + 14k + 26k) compacted
assert.match(text, /84% cached/); // 512/608
assert.match(text, /150 tok\/s/); // 6300 / 42s
assert.equal(findByAttr(tree, 'data-status-telemetry-panel'), undefined, 'panel stays collapsed');
assert.deepEqual(seen, ['tokenUsage', 'sessionStats', 'contextPressure', 'contextBreakdown']);
});
test('an empty session renders nothing at all', () => {
const { tree } = render({});
assert.equal(tree, null);
});
test('sessions with steps but no billed tokens still render', () => {
const { tree } = render({ sessionStats: { ...POPULATED.sessionStats, decodeMs: 0, decodeTokens: 0 } });
const pill = findByAttr(tree, 'data-status-telemetry-pill');
assert.ok(pill);
assert.doesNotMatch(textOf(pill), /cached/);
assert.doesNotMatch(textOf(pill), /tok\/s/);
});
test('the expanded panel exposes every telemetry section', () => {
const { tree } = render(POPULATED, { open: true });
const panel = findByAttr(tree, 'data-status-telemetry-panel');
assert.ok(panel, 'panel renders when open');
assert.equal(panel.props.role, 'dialog');
assert.equal(panel.props['aria-label'], 'Session telemetry');
assert.equal(findByAttr(tree, 'data-status-telemetry-open').props['data-status-telemetry-open'], true);
const text = textOf(panel);
for (const expected of [
'Conversation',
'Token usage',
'Performance',
'Context',
'Turns',
'Steps',
'Throughput',
'Billed input',
'Uncached input',
'Cached input',
'Cache write',
'Cache hit',
'Output',
'LLM time',
'Tool time',
'Avg first token',
'Decode speed',
'Tool share of work',
'Occupancy',
'Window'
]) {
assert.ok(text.includes(expected), `panel shows "${expected}"`);
}
// Values must be formatted, not raw.
assert.match(text, /1m36s/); // llmMs 96_400
assert.match(text, /31\.2s/); // toolMs 31_200
assert.match(text, /400ms/); // avg ttft 3600/9
assert.match(text, /128,000/); // context window grouped
assert.match(text, /75%/); // occupancy 96000/128000
assert.match(text, /24%/); // tool share 31200/(96400+31200)
// The composition bar renders inside the Context section with proportional segments.
const bar = findByClass(panel, 'sl-bar');
assert.ok(bar, 'composition bar renders with the context breakdown');
assert.equal(bar.props.role, 'img');
assert.equal(bar.props['aria-label'], T.en['context.barLabel'], 'bar label is localized');
const segments = elementsOf(bar).filter((element) => String(element.props.className ?? '').includes('sl-bar-seg'));
assert.equal(segments.length, 3, 'system, tools, and messages segments');
assert.match(segments[0].props.style.width, /4\.\d+%/); // 4000 / 96000
assert.match(segments[1].props.style.width, /12\.5%/); // 12000 / 96000
assert.match(segments[2].props.style.width, /83\.3/); // 80000 / 96000
// Severity classes must come from the documented token set.
const values = elementsOf(panel).filter((element) => String(element.props.className ?? '').startsWith('sl-val'));
assert.ok(values.length > 0);
for (const value of values) {
const severityClass = String(value.props.className).split(' ')[1];
if (severityClass === undefined) continue;
assert.match(severityClass, /^sl-val--(ok|warn|bad)$/, `${severityClass} is a known severity class`);
}
});
test('missing token accounting degrades explicitly instead of silently', () => {
const { tree } = render({ sessionStats: POPULATED.sessionStats }, { open: true });
const panel = findByAttr(tree, 'data-status-telemetry-panel');
assert.match(textOf(panel), /Token accounting is unavailable in this profile\./);
assert.match(textOf(panel), /Context pressure is unavailable in this profile\./);
});
test('missing model timing degrades explicitly', () => {
const { tree } = render({ tokenUsage: POPULATED.tokenUsage }, { open: true });
const panel = findByAttr(tree, 'data-status-telemetry-panel');
assert.match(textOf(panel), /No model timing recorded yet\./);
});
test('collapsing is reachable and escape closes the panel', () => {
const { tree } = render(POPULATED, { open: true });
const close = findByAttr(tree, 'data-status-telemetry-close');
assert.ok(close, 'collapse control exists');
assert.equal(close.props['aria-label'], 'Collapse telemetry');
let stopped = false;
const panel = findByAttr(tree, 'data-status-telemetry-panel');
panel.props.onKeyDown({ key: 'Escape', stopPropagation: () => { stopped = true; } });
assert.ok(stopped, 'Escape does not leak to the app');
panel.props.onKeyDown({ key: 'a', stopPropagation: () => { throw new Error('must not stop propagation'); } });
});
test('setters are wired: pill toggles open, close collapses', () => {
const collapsed = render(POPULATED);
findByAttr(collapsed.tree, 'data-status-telemetry-pill').props.onClick();
assert.deepEqual(collapsed.react.__setterCalls, [true]);
const expanded = render(POPULATED, { open: true });
findByAttr(expanded.tree, 'data-status-telemetry-close').props.onClick();
assert.deepEqual(expanded.react.__setterCalls, [false]);
});
test('a session with stats but zero turns still renders safely', () => {
const { tree } = render({
sessionStats: { turns: 0, steps: 2, llmMs: 1_000, toolMs: 0, ttftMs: 0, ttftSteps: 0, decodeMs: 0, decodeTokens: 0 }
});
const pill = findByAttr(tree, 'data-status-telemetry-pill');
assert.ok(pill);
assert.match(textOf(pill), /0 turns/);
assert.match(textOf(pill), /2 steps/);
});
test('stylesheet uses only documented theme tokens', () => {
const tokens = [...T.CSS.matchAll(/var\((--dsw-[a-z0-9-]+)/g)].map((match) => match[1]);
assert.ok(tokens.length > 0, 'styles reference theme tokens');
const known = [
'--dsw-alias-label-primary',
'--dsw-alias-label-secondary',
'--dsw-alias-label-tertiary',
'--dsw-alias-label-caption',
'--dsw-alias-label-primary-bluish',
'--dsw-alias-interactive-bg-hover',
'--dsw-alias-border-l1',
'--dsw-alias-border-l2',
'--dsw-alias-separator-primary',
'--dsw-alias-scrollbar-bg-l2',
'--dsw-alias-scrollbar-hover-l2',
'--dsw-alias-state-business-primary',
'--dsw-alias-state-warn-primary',
'--dsw-alias-state-error-primary',
'--dsw-specific-menu',
'--dsw-elevation-panel',
'--dsw-radius-sm',
'--dsw-radius-md',
'--dsw-radius-lg'
];
for (const token of new Set(tokens)) {
assert.ok(known.includes(token), `${token} is a documented token`);
}
});
test('styles render inside the entry so unmounting removes them', () => {
const collapsed = render(POPULATED);
const collapsedStyle = findByAttr(collapsed.tree, 'data-plugin-css');
assert.ok(collapsedStyle, 'collapsed state carries the stylesheet');
assert.equal(collapsedStyle.type, 'style');
assert.equal(collapsedStyle.props['data-plugin'], mod.PLUGIN_ID);
assert.equal(collapsedStyle.props.dangerouslySetInnerHTML.__html, T.CSS);
const expanded = render(POPULATED, { open: true });
assert.equal(findByAttr(expanded.tree, 'data-plugin-css').type, 'style');
// The bundle must not touch document.head directly: the style belongs to the
// component tree, and the module factory must stay side-effect free.
const source = readFileSync(join(here, '..', 'client.js'), 'utf8');
assert.doesNotMatch(source, /document\.head/);
assert.doesNotMatch(source, /document\.createElement/);
assert.match(source, /function StyleSheet\(\)/);
});
test('locale dictionaries are complete and parallel', () => {
const enKeys = Object.keys(T.en).sort();
const zhKeys = Object.keys(T.zh).sort();
assert.deepEqual(zhKeys, enKeys);
assert.ok(enKeys.length >= 25, 'dictionary covers the panel');
for (const key of enKeys) {
assert.ok(T.en[key].length > 0, `${key} has English copy`);
assert.ok(T.zh[key].length > 0, `${key} has Chinese copy`);
}
// Message placeholders must match across locales.
for (const key of enKeys) {
const placeholders = (value) => [...value.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
assert.deepEqual(placeholders(T.zh[key]), placeholders(T.en[key]), `${key} placeholders align`);
}
});
test('the module is a valid plain-JS bundle with no build step', () => {
// The component must only use the documented slot props.
const source = readFileSync(join(here, '..', 'client.js'), 'utf8');
assert.match(source, /window\.__ModuleLoader__\.load\(\{/);
assert.match(source, /factory\(require\)/);
assert.match(source, /require\('react'\)/);
// Forbidden: importing Harness client packages as modules.
assert.doesNotMatch(source, /require\('@deepseek-ai\//);
// Forbidden: DOM writes outside the shimmed style tag.
assert.doesNotMatch(source, /document\.body\.append/);
});
test('real React accepts the produced element tree', { skip: realReact === null ? 'react is not installed on this host' : false }, () => {
// The hand-rolled tree must be structurally identical to React's own output
// contract, so validate one element against the real implementation.
T.setReact(realReact);
const element = realReact.createElement('span', { className: 'x' }, 'ok');
assert.equal(element.type, 'span');
assert.equal(element.props.className, 'x');
assert.equal(element.props.children, 'ok');
});