Files

3448 lines
145 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Cost and balance readings in the composer dock.
*
* The Client half of `@local/dsh-cost-balance-footer`. It contributes one
* entry to `conversation.composer.dock`, beside the shipped activity and usage
* pills, and renders two readings:
*
* - `Spent ≈ …` — an estimate of what this session has cost so far, priced
* from the durable `tokenUsage` projection with DeepSeek's published list
* prices. Each observed usage delta is priced in the tariff band (peak or
* idle, Beijing time) that was in force when it was observed, and the
* per-model, per-band token counters are cached in `localStorage` so a page
* reload does not re-price or double-count the session's history.
* - `Balance …` — the account's remaining recharge and granted wallets, read
* through the account Remote on mount, after a turn advances the usage
* projection, and on demand by clicking the reading.
*
* Both are display-only: they never consume a model request, write Session
* events, or touch another plugin's DOM.
*/
window.__ModuleLoader__.load({
id: '@local/dsh-cost-balance-footer',
factory(require) {
const React = require('react');
const ReactDOM = require('react-dom');
const h = React.createElement;
const NS = 'costBalance';
const PLUGIN_ID = '@local/dsh-cost-balance-footer';
const CSS_ID = `${PLUGIN_ID}/composer-dock.css`;
const DEFAULT_MODEL = 'deepseek-flash';
/**
* DeepSeek list prices, peak band, per 1M tokens. Idle-band prices are
* exactly half (DeepSeek's published tariff: Beijing time Monday-Friday
* 9:00-12:00 and 14:00-18:00 is peak, everything else including weekends
* and Chinese public holidays is idle). CNY figures are the official
* Chinese price table; USD figures are the published English one.
*/
const PEAK_PRICES = {
CNY: {
'deepseek-flash': { miss: 2, hit: 0.04, output: 8 },
'deepseek-v4-pro': { miss: 9, hit: 0.3, output: 27 },
},
USD: {
'deepseek-flash': { miss: 0.3, hit: 0.006, output: 0.6 },
'deepseek-v4-pro': { miss: 1.32, hit: 0.044, output: 3.96 },
},
};
const CURRENCY_SYMBOL = { CNY: '¥', USD: '$' };
const DEFAULT_CURRENCY = 'CNY';
/** Cache-write tokens have no DeepSeek price of their own; they bill as uncached input. */
const BANDS = ['peak', 'idle'];
const STORAGE_PREFIX = 'dsh-cost-balance/';
const STORAGE_VERSION = 1;
const BALANCE_MIN_INTERVAL_MS = 30_000;
const BALANCE_POLL_MS = 60_000;
/** Re-read the tariff band so the lamp flips at the peak/idle boundary. */
const TARIFF_POLL_MS = 30_000;
// #region price helpers
/** Map a provider-owned model id onto one of the priced DeepSeek routes. */
function pricedModel(model) {
const id = typeof model === 'string' ? model.toLowerCase() : '';
if (id.includes('pro')) return 'deepseek-v4-pro';
if (id.includes('flash')) return 'deepseek-flash';
return DEFAULT_MODEL;
}
/** Peak-band list price for one model id and display currency. */
function priceOf(model, currency) {
const table = PEAK_PRICES[currency] ?? PEAK_PRICES[DEFAULT_CURRENCY];
return table[pricedModel(model)] ?? table[DEFAULT_MODEL];
}
/** Beijing-time tariff band at one instant. */
function bandAt(time) {
const beijing = new Date(time + 8 * 3_600_000);
const day = beijing.getUTCDay();
if (day === 0 || day === 6) return 'idle';
const hour = beijing.getUTCHours();
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18) ? 'peak' : 'idle';
}
function emptyBand() {
return { miss: 0, hit: 0, out: 0 };
}
function emptyBuckets() {
return { peak: emptyBand(), idle: emptyBand() };
}
// #endregion
// #region cost ledger
/**
* Per-session token ledger. Counters are token counts (never money), so a
* later currency or price change re-prices the same observations instead
* of compounding an old conversion.
*/
function createLedger(sessionId) {
const storageKey = STORAGE_PREFIX + String(sessionId);
const state = readState();
function readState() {
try {
const raw = window.localStorage.getItem(storageKey);
if (typeof raw === 'string') {
const parsed = JSON.parse(raw);
if (parsed && parsed.version === STORAGE_VERSION && parsed.models && typeof parsed.models === 'object') {
return {
version: STORAGE_VERSION,
last: parsed.last && typeof parsed.last === 'object' ? parsed.last : null,
lastRaw: parsed.lastRaw && typeof parsed.lastRaw === 'object' ? parsed.lastRaw : null,
models: parsed.models,
};
}
}
} catch {
/* Private mode, quota, or a corrupt cache: fall back to a fresh ledger. */
}
return { version: STORAGE_VERSION, last: null, lastRaw: null, models: {} };
}
function writeState() {
try {
window.localStorage.setItem(storageKey, JSON.stringify(state));
} catch {
/* A memory-only ledger still works for this page. */
}
}
function bucketsOf(model) {
const key = pricedModel(model);
let buckets = state.models[key];
if (buckets === undefined || buckets === null) {
buckets = emptyBuckets();
state.models[key] = buckets;
}
for (const band of BANDS) {
if (buckets[band] === undefined) buckets[band] = emptyBand();
}
return buckets;
}
function add(model, band, delta) {
const buckets = bucketsOf(model);
const target = buckets[band] ?? (buckets[band] = emptyBand());
target.miss += delta.miss;
target.hit += delta.hit;
target.out += delta.out;
}
function snapshotOf(usage) {
return {
miss: count(usage.uncachedInputTokens) + count(usage.cacheWriteTokens),
hit: count(usage.cacheReadTokens),
out: count(usage.outputTokens),
};
}
/** The same observation with cache writes kept apart, for the history. */
function rawSnapshotOf(usage) {
return {
miss: count(usage.uncachedInputTokens),
write: count(usage.cacheWriteTokens),
hit: count(usage.cacheReadTokens),
out: count(usage.outputTokens),
};
}
return {
sessionId,
/**
* Fold one durable usage observation into the ledger.
* @param usage - `tokenUsage` projection value.
* @param model - model route of the requests that produced the delta.
* @param priced - whether DeepSeek list prices describe that route.
*/
observe(usage, model, priced) {
const raw = rawSnapshotOf(usage);
const current = {
miss: raw.miss + raw.write,
hit: raw.hit,
out: raw.out,
};
const previousRaw =
state.lastRaw !== null && typeof state.lastRaw === 'object' ? state.lastRaw : null;
/* The raw delta is what the shared token history records: it keeps
* cache writes apart and never includes the pre-installation bulk. */
const rawDelta =
previousRaw === null
? undefined
: {
miss: Math.max(0, raw.miss - count(previousRaw.miss)),
write: Math.max(0, raw.write - count(previousRaw.write)),
hit: Math.max(0, raw.hit - count(previousRaw.hit)),
out: Math.max(0, raw.out - count(previousRaw.out)),
};
state.lastRaw = raw;
if (state.last === null) {
/* First sight of this session: price its whole history at the
* band in force now, then continue with exact per-band deltas. */
if (priced) add(model, bandAt(Date.now()), current);
state.last = current;
writeState();
return undefined;
}
const previous = state.last;
const delta = {
miss: Math.max(0, current.miss - count(previous.miss)),
hit: Math.max(0, current.hit - count(previous.hit)),
out: Math.max(0, current.out - count(previous.out)),
};
state.last = current;
if (priced && delta.miss + delta.hit + delta.out > 0) {
add(model, bandAt(Date.now()), delta);
}
writeState();
return rawDelta;
},
/**
* Estimated money spent so far, in the requested wallet currency.
* @param currency - 'CNY' or 'USD'.
*/
cost(currency) {
let total = 0;
for (const [model, buckets] of Object.entries(state.models)) {
const price = PEAK_PRICES[currency]?.[model] ?? PEAK_PRICES[currency]?.[DEFAULT_MODEL];
if (price === undefined) continue;
for (const band of BANDS) {
const counts = buckets[band] ?? emptyBand();
const factor = band === 'peak' ? 1 : 0.5;
total +=
((count(counts.miss) * price.miss) +
(count(counts.hit) * price.hit) +
(count(counts.out) * price.output)) *
(factor / 1_000_000);
}
}
return total;
},
};
}
function count(value) {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
}
// #endregion
// #region spend ledger
/**
* Machine-local spending history and the user's own soft limits.
*
* Money is counted from the balance readings this plugin already polls, but
* not from the remainder alone: a gateway that caps a key reports what is
* left *under that cap*, so editing the cap in the billing cabinet moved
* the reading and the ledger booked the difference as spending. Each
* reading is reduced to a spend meter instead — the gateway's own usage
* counter, the whole-account wallet, or the remainder while its cap stays
* unchanged — and only a meter that grew between two samples is spending.
* That keeps the numbers honest for third-party gateways too, where a token
* has no price this plugin knows.
*
* A delta covers the time since the previous sample, so it is spread evenly
* over the hours it may have happened in (capped) instead of landing as one
* spike on the hour the app came back.
*
* Hour buckets are keyed by local epoch hour, so day/week/month windows and
* the hourly view follow the user's own time zone.
*/
const SPEND_KEY = 'dsh-cost-balance/spend/v1';
const SPEND_VERSION = 1;
const SPEND_EVENT = 'dsh-cost-balance/spend-changed';
const SPEND_ROUTE = '/api/cost-balance/spend';
const SPEND_TIMEOUT_MS = 5_000;
const SPEND_PERSIST_DELAY_MS = 250;
const SPEND_PULL_MS = 30_000;
const HOUR_MS = 3_600_000;
const MAX_SMEAR_HOURS = 72;
const SPEND_RETENTION_DAYS = 400;
const RATIO_WARN = 0.7;
const SYMBOL_TO_CURRENCY = { '₽': 'RUB', $: 'USD', '¥': 'CNY' };
const CURRENCY_TO_SYMBOL = { RUB: '₽', USD: '$', CNY: '¥' };
const LIMIT_PERIODS = ['day', 'week', 'month'];
function emptySpend() {
return { version: SPEND_VERSION, currency: 'RUB', hours: {}, samples: {}, limits: {}, tokens: {} };
}
/**
* The ledger now lives in the Host's SQLite database. This half keeps a
* synchronous in-memory copy: the dock and the statistics render from it
* without waiting for a round trip, every mutation updates it, notifies the
* views and schedules a debounced PUT of the whole document. A GET on mount
* hydrates it, and a periodic GET picks up what another window recorded.
*
* The browser storage is read only once, to migrate the history written by
* older versions, and is used as a fallback while a Host without the ledger
* route is still running — the Client bundle hot-reloads before the Host
* process restarts.
*/
let spendState = emptySpend();
/** `pending` until the Host answers, then `server` (SQLite) or `local`. */
let spendMode = 'pending';
let spendWarned = false;
/** Operations queued for the Host: explicit edits, then merges. */
let pendingOps = [];
let mergePending = false;
/* ------------------------------------------------------------------ */
/* Daily central-bank rates */
/* ------------------------------------------------------------------ */
/**
* DeepSeek wallets bill in dollars or yuan while the operator wallet and
* the user's budgets are in rubles. The Host caches the Central Bank rates
* for a day; this half keeps them in memory and folds foreign spend into
* the ruble totals, so switching providers does not hide spending.
*/
const FX_ROUTE = '/api/cost-balance/rates';
const FX_EVENT = 'dsh-cost-balance/rates-changed';
const FX_REFRESH_MS = 6 * 3_600_000;
let fxRates = {};
let fxDate = '';
let fxStatus = 'idle';
let fxRequest = null;
function notifyFx() {
try {
window.dispatchEvent(new CustomEvent(FX_EVENT));
} catch {
/* Non-browser test rigs have no CustomEvent. */
}
}
async function refreshFxRates() {
if (fxRequest !== null) return fxRequest;
if (fxStatus === 'idle') fxStatus = 'loading';
fxRequest = (async () => {
try {
const response = await fetch(FX_ROUTE, {
cache: 'no-store',
credentials: 'same-origin',
signal: AbortSignal.timeout(SPEND_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`http-${String(response.status)}`);
const payload = await response.json();
if (payload === null || typeof payload !== 'object' || payload.ok !== true) {
throw new Error('bad-payload');
}
const rates = {};
for (const [code, value] of Object.entries(payload.rates ?? {})) {
const rate = finite(value);
if (/^[A-Z]{3}$/.test(code) && rate !== undefined && rate > 0) rates[code] = rate;
}
fxRates = rates;
fxDate = typeof payload.date === 'string' ? payload.date : '';
fxStatus = Object.keys(rates).length > 0 ? 'ready' : 'unavailable';
} catch {
fxStatus = Object.keys(fxRates).length > 0 ? 'ready' : 'unavailable';
} finally {
fxRequest = null;
}
notifyFx();
})();
return fxRequest;
}
let persistTimer = 0;
let persistRunning = false;
let persistAgain = false;
function notifySpend() {
try {
window.dispatchEvent(new CustomEvent(SPEND_EVENT));
} catch {
/* Non-browser test rigs have no CustomEvent; nothing to notify. */
}
}
/** Whether a document key is a local epoch-hour bucket. */
function isHourKey(key) {
const hour = Number(key);
return Number.isSafeInteger(hour) && hour >= 0;
}
/** Clamp one document to the ledger shape shared with the Host. */
function parseSpend(value) {
const state = emptySpend();
if (value === null || typeof value !== 'object') return state;
if (typeof value.currency === 'string' && value.currency !== '') state.currency = value.currency;
if (value.hours !== null && typeof value.hours === 'object') {
for (const [key, bucket] of Object.entries(value.hours)) {
if (!isHourKey(key) || bucket === null || typeof bucket !== 'object') continue;
const amounts = {};
for (const [currency, amount] of Object.entries(bucket)) {
const parsed = finite(amount);
if (parsed === undefined || parsed === 0) continue;
amounts[currency] = parsed;
}
if (Object.keys(amounts).length > 0) state.hours[key] = amounts;
}
}
if (value.samples !== null && typeof value.samples === 'object') {
for (const [provider, sample] of Object.entries(value.samples)) {
if (sample === null || typeof sample !== 'object') continue;
state.samples[provider] = { ...sample };
}
}
if (value.limits !== null && typeof value.limits === 'object') {
const read = (raw) => {
const parsed = finite(raw);
return parsed !== undefined && parsed > 0 ? parsed : 0;
};
for (const [key, limits] of Object.entries(value.limits)) {
if (limits === null || typeof limits !== 'object') continue;
/* Older documents keyed limits by currency; the shared ledger keys
* them by the provider that owns the wallet. */
const legacy = /^[A-Z]{3}$/.test(key);
const owner = legacy ? ownerForCurrency(key) : key;
if (!/^[a-z0-9-]{1,32}$/.test(owner)) continue;
const stored =
typeof limits.currency === 'string' && /^[A-Z]{3}$/.test(limits.currency)
? limits.currency
: legacy
? key
: state.currency;
/* One entry per owner: when a legacy document carries both wallet
* currencies, the yuan entry wins over the dollar one. */
const previous = state.limits[owner];
if (previous !== undefined && previous.currency === 'CNY' && stored === 'USD') continue;
state.limits[owner] = {
currency: stored,
day: read(limits.day),
week: read(limits.week),
month: read(limits.month),
};
}
}
if (value.tokens !== null && typeof value.tokens === 'object') {
for (const [key, models] of Object.entries(value.tokens)) {
if (!isHourKey(key) || models === null || typeof models !== 'object') continue;
const entries = {};
const read = (raw) => {
const parsed = finite(raw);
return parsed !== undefined && parsed > 0 ? parsed : 0;
};
for (const [model, entry] of Object.entries(models)) {
if (entry === null || typeof entry !== 'object') continue;
const miss = read(entry.miss);
const write = read(entry.write);
const hit = read(entry.hit);
const out = read(entry.out);
if (miss + write + hit + out <= 0) continue;
entries[model] = { miss, write, hit, out };
}
if (Object.keys(entries).length > 0) state.tokens[key] = entries;
}
}
return state;
}
/** The document written by versions that kept it in `localStorage`. */
function readLegacySpend() {
try {
const raw = window.localStorage.getItem(SPEND_KEY);
if (typeof raw === 'string') {
const parsed = JSON.parse(raw);
if (parsed !== null && typeof parsed === 'object' && parsed.version === SPEND_VERSION) {
return parseSpend(parsed);
}
}
} catch {
/* Private mode, quota, or a corrupt cache: start a fresh ledger. */
}
return emptySpend();
}
function writeLegacySpend(state) {
try {
window.localStorage.setItem(SPEND_KEY, JSON.stringify(state));
} catch {
/* A memory-only ledger still works for this page. */
}
}
/** The ledger the views render from. */
function readSpend() {
return spendState;
}
/**
* Replace the in-memory ledger, publish it, and persist it.
*
* Ordinary writes carry `mode: 'merge'`: several windows poll the same
* wallet and the Host folds their observations together instead of letting
* the last writer win. Explicit edits (limits, one day, clearing) name
* their operation so they are not swallowed by a merge.
*/
function writeSpend(state, op) {
/* Callers mutate the cached document in place, so the published state
* must be a fresh object: React skips an update that returns the same
* reference, and the dock would keep showing the previous reading. */
spendState = {
...state,
hours: { ...state.hours },
samples: { ...state.samples },
limits: { ...state.limits },
tokens: { ...state.tokens },
};
if (spendMode === 'server') {
if (op !== undefined && op.mode !== 'merge') {
pendingOps.push(op);
if (persistTimer !== 0) {
window.clearTimeout(persistTimer);
persistTimer = 0;
}
void flushSpend();
} else {
mergePending = true;
scheduleSpendPersist();
}
} else if (spendMode === 'local') {
writeLegacySpend(spendState);
}
notifySpend();
}
function isEmptySpend(state) {
return (
Object.keys(state.hours).length === 0 &&
Object.keys(state.samples).length === 0 &&
Object.keys(state.limits).length === 0
);
}
/** One bounded JSON call to the Host half. */
async function spendRequest(route, method, body) {
const init = {
method,
cache: 'no-store',
credentials: 'same-origin',
signal: AbortSignal.timeout(SPEND_TIMEOUT_MS),
};
if (body !== undefined) {
init.headers = { 'content-type': 'application/json' };
init.body = JSON.stringify(body);
}
const response = await fetch(route, init);
if (!response.ok) throw new Error(`http-${String(response.status)}`);
return response.json();
}
/**
* Fold a browser document into the shared one.
*
* Two windows polling the same wallet observe the same spend, so summing
* their hours would double count it; taking the larger value per hour (and
* per model for tokens) keeps the richer observation instead. Samples take
* the newer reading, limits keep what the shared ledger already has and
* take the browser copy only for owners it does not cover.
*/
function mergeSpendDocuments(base, extra) {
const merged = {
...base,
hours: {},
samples: { ...base.samples },
limits: { ...base.limits },
tokens: {},
};
for (const [key, bucket] of Object.entries(base.hours)) merged.hours[key] = { ...bucket };
for (const [key, models] of Object.entries(base.tokens)) {
merged.tokens[key] = { ...models };
}
for (const [hour, bucket] of Object.entries(extra.hours)) {
const target = merged.hours[hour] ?? (merged.hours[hour] = {});
for (const [currency, amount] of Object.entries(bucket)) {
const current = target[currency];
if (typeof current !== 'number' || amount > current) target[currency] = amount;
}
}
for (const [hour, models] of Object.entries(extra.tokens)) {
const target = merged.tokens[hour] ?? (merged.tokens[hour] = {});
for (const [model, entry] of Object.entries(models)) {
const current = target[model];
if (current === undefined) {
target[model] = { ...entry };
continue;
}
target[model] = {
miss: Math.max(current.miss, entry.miss),
write: Math.max(current.write, entry.write),
hit: Math.max(current.hit, entry.hit),
out: Math.max(current.out, entry.out),
};
}
}
for (const [provider, sample] of Object.entries(extra.samples)) {
const current = merged.samples[provider];
if (current === undefined || (sample.at ?? 0) > (current.at ?? 0)) {
merged.samples[provider] = { ...sample };
}
}
for (const [owner, limits] of Object.entries(extra.limits)) {
if (merged.limits[owner] === undefined) merged.limits[owner] = { ...limits };
}
return merged;
}
/**
* Load the ledger from the Host, folding the browser history into it once.
* Any failure leaves the old browser storage in charge, so the plugin keeps
* working against a Host that predates the ledger route.
*/
async function hydrateSpend() {
const legacy = readLegacySpend();
try {
const payload = await spendRequest(SPEND_ROUTE, 'GET');
if (payload === null || typeof payload !== 'object' || payload.ok !== true) {
throw new Error('bad-payload');
}
let state = parseSpend(payload.state);
if (!isEmptySpend(legacy)) {
/* Another window may have reached the database first; fold this
* window's history into it instead of skipping the migration. */
state = mergeSpendDocuments(state, legacy);
await spendRequest(SPEND_ROUTE, 'PUT', { state, mode: 'merge' });
try {
window.localStorage.removeItem(SPEND_KEY);
} catch {
/* The merged copy still stands even if the old key cannot be removed. */
}
}
spendState = state;
spendMode = 'server';
} catch (error) {
spendState = legacy;
spendMode = 'local';
/* A Host that predates the ledger route is expected right after an
* update; warn once, then keep retrying quietly on the ledger poll. */
if (!spendWarned) {
spendWarned = true;
try {
console.warn('cost-balance: spending ledger route unavailable, using browser storage', error);
} catch {
/* A test rig without a console still gets the fallback. */
}
}
}
if (spendMode === 'server') spendWarned = false;
notifySpend();
return spendState;
}
/**
* Pull what another window recorded, unless local changes are unsaved.
* In the browser-storage fallback this retries the one-time migration, so
* a Host restarted with the ledger route takes over without a page reload.
*/
async function pullSpend() {
if (spendMode === 'local') {
await hydrateSpend();
return;
}
if (spendMode !== 'server' || persistTimer !== 0 || persistRunning) return;
try {
const payload = await spendRequest(SPEND_ROUTE, 'GET');
if (payload === null || typeof payload !== 'object' || payload.ok !== true) return;
const next = parseSpend(payload.state);
if (JSON.stringify(next) === JSON.stringify(spendState)) return;
spendState = next;
notifySpend();
} catch {
/* Keep the current copy; the next pull retries. */
}
}
function scheduleSpendPersist() {
if (persistTimer !== 0) return;
persistTimer = window.setTimeout(() => {
persistTimer = 0;
void flushSpend();
}, SPEND_PERSIST_DELAY_MS);
}
/**
* Write the current document back, one request at a time: a mutation that
* lands while a PUT is in flight marks another round, so the database ends
* on the newest copy instead of racing an older one.
*/
async function flushSpend() {
if (persistRunning) {
persistAgain = true;
return;
}
persistRunning = true;
try {
do {
persistAgain = false;
while (pendingOps.length > 0) {
const op = pendingOps.shift();
await spendRequest(SPEND_ROUTE, 'PUT', {
state: spendState,
mode: op.mode,
...(op.day === undefined ? {} : { day: op.day }),
});
}
if (mergePending) {
mergePending = false;
await spendRequest(SPEND_ROUTE, 'PUT', { state: spendState, mode: 'merge' });
}
} while (persistAgain || pendingOps.length > 0 || mergePending);
} catch {
/* The next mutation retries; the in-memory ledger stays correct. */
} finally {
persistRunning = false;
}
}
/** Local epoch hour that one instant belongs to. */
function hourKey(ms) {
return Math.floor(ms / HOUR_MS) * HOUR_MS;
}
function startOfDay(ms) {
const date = new Date(ms);
date.setHours(0, 0, 0, 0);
return date.getTime();
}
/** Monday 00:00 of the week holding `ms`. */
function startOfWeek(ms) {
const date = new Date(startOfDay(ms));
const offset = (date.getDay() + 6) % 7;
date.setDate(date.getDate() - offset);
return date.getTime();
}
function startOfMonth(ms) {
const date = new Date(ms);
date.setHours(0, 0, 0, 0);
date.setDate(1);
return date.getTime();
}
function addHourSpend(state, currency, hourStart, amount) {
if (!(amount > 0)) return;
const key = String(hourStart);
const bucket = state.hours[key] ?? (state.hours[key] = {});
bucket[currency] = (bucket[currency] ?? 0) + amount;
}
/** Drop buckets older than the retention window. */
function pruneSpend(state) {
const cutoff = hourKey(Date.now() - SPEND_RETENTION_DAYS * 24 * HOUR_MS);
for (const key of Object.keys(state.hours)) {
if (Number(key) < cutoff) delete state.hours[key];
}
for (const key of Object.keys(state.tokens ?? {})) {
if (Number(key) < cutoff) delete state.tokens[key];
}
}
/** Finite number from a number or a numeric string, else undefined. */
function finite(value) {
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
if (typeof value === 'string' && value.trim() !== '') {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
}
/**
* The quantity a reading moves only when money is really spent.
*
* Polling a remainder cannot tell a purchase from a bookkeeping change, and
* a gateway that caps a key reports the remainder *under that cap*, so
* editing the cap moved it and the ledger booked the move as spending.
* Each reading is therefore reduced to one meter, preferred in this order:
*
* - the gateway's own `usage` counter for the current window: only billed
* requests move it;
* - the whole-account wallet: only billed requests lower it (a top-up
* raises it, and a raised meter is rebased, never booked);
* - the displayed remainder, but only while the cap it is computed against
* stays the same.
*
* A meter carries a tag — the window identity, the meter kind, the key cap —
* and a delta is booked only between two samples with the same tag. A
* changed tag rebases the sample instead of inventing a spend for the
* difference.
*/
function meterOf(sample) {
if (sample === null || typeof sample !== 'object') return undefined;
const used = finite(sample.used);
if (used !== undefined) {
return { tag: `usage|${sample.window ?? ''}|${sample.resetsAt ?? ''}`, value: used };
}
const wallet = finite(sample.wallet);
if (wallet !== undefined) return { tag: 'wallet', value: -wallet };
const amount = finite(sample.amount);
if (amount !== undefined) return { tag: `balance|${finite(sample.cap) ?? ''}`, value: -amount };
return undefined;
}
/**
* Fold one balance reading into the history.
* @param provider - balance owner, e.g. `deepseek` or `openrusrouter`.
* @param sample - what the reading knows: `amount` (the displayed
* remainder) plus, when the gateway reports them, `wallet`, `used`,
* `cap`, `window` and `resetsAt`.
* @param currency - ISO code the amounts are denominated in.
* @param at - observation time.
*/
function recordBalanceSample(provider, sample, currency, at) {
if (typeof provider !== 'string' || provider === '') return;
if (typeof currency !== 'string' || currency === '') return;
const meter = meterOf(sample);
if (meter === undefined) return;
const state = readSpend();
const previous = state.samples[provider];
state.samples[provider] = { ...sample, currency, at };
state.currency = currency;
const before = meterOf(previous);
if (
before !== undefined &&
previous.currency === currency &&
Number.isFinite(previous.at) &&
before.tag === meter.tag
) {
const spent = meter.value - before.value;
if (spent > 0) {
const elapsed = Math.max(0, at - previous.at);
const hours = Math.min(MAX_SMEAR_HOURS, Math.max(1, Math.ceil(elapsed / HOUR_MS)));
const perHour = spent / hours;
const firstHour = hourKey(at) - (hours - 1) * HOUR_MS;
for (let index = 0; index < hours; index += 1) {
addHourSpend(state, currency, firstHour + index * HOUR_MS, perHour);
}
}
}
pruneSpend(state);
writeSpend(state);
}
/** Rubles per one unit of `currency`, or undefined when it is unknown. */
function rateOf(currency) {
if (currency === 'RUB') return 1;
const rate = fxRates[currency];
return typeof rate === 'number' && Number.isFinite(rate) && rate > 0 ? rate : undefined;
}
/** Currencies with recorded spending that the current rates cannot convert. */
function unconvertedCurrencies(state) {
const codes = new Set();
for (const bucket of Object.values(state.hours ?? {})) {
for (const [code, amount] of Object.entries(bucket ?? {})) {
if (code !== 'RUB' && amount > 0 && rateOf(code) === undefined) codes.add(code);
}
}
return [...codes];
}
/**
* Money of one window in `currency`.
*
* A ruble total folds every wallet in, using the daily Central Bank rates;
* another currency keeps only its own entries, because converting into a
* foreign unit would invent a number nobody budgeted in.
*/
function sumMoney(state, currency, fromMs, toMs = Date.now()) {
if (currency !== 'RUB') return sumSpend(state, currency, fromMs, toMs);
let total = 0;
for (const [key, bucket] of Object.entries(state.hours ?? {})) {
const hour = Number(key);
if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue;
for (const [code, amount] of Object.entries(bucket ?? {})) {
const rate = rateOf(code);
if (rate === undefined || typeof amount !== 'number' || !Number.isFinite(amount)) continue;
total += amount * rate;
}
}
return total;
}
/** Money spent in `currency` from `fromMs` (inclusive) through now. */
function sumSpend(state, currency, fromMs, toMs = Date.now()) {
let total = 0;
for (const [key, bucket] of Object.entries(state.hours)) {
const hour = Number(key);
if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue;
const value = bucket?.[currency];
if (typeof value === 'number' && Number.isFinite(value)) total += value;
}
return total;
}
/**
* Soft limits belong to the provider that bills the model, not to the
* window or to whatever currency happened to be written last: the
* operator's wallet is in rubles, the DeepSeek account in its own wallet
* currency. Every window and session reads the same owner entry from the
* shared ledger.
*/
function limitOwner(provider) {
return provider === 'openrusrouter' ? 'openrusrouter' : 'deepseek';
}
/** The owner a wallet currency belongs to (legacy currency-keyed limits). */
function ownerForCurrency(currency) {
return currency === 'RUB' ? 'openrusrouter' : 'deepseek';
}
function limitOwnerLabel(owner) {
return owner === 'openrusrouter' ? 'OpenRusRouter' : 'DeepSeek';
}
/** Configured soft limits for one owner; zero means "not set". */
function limitsOf(state, owner) {
const stored = state.limits?.[owner];
const read = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
return {
day: read(stored?.day),
week: read(stored?.week),
month: read(stored?.month),
};
}
/** Whether an owner has at least one limit set. */
function hasLimits(state, owner) {
const limits = limitsOf(state, owner);
return limits.day > 0 || limits.week > 0 || limits.month > 0;
}
/** Currency of an owner's limits, or the fallback. */
function limitCurrency(state, owner, fallback) {
const code = state.limits?.[owner]?.currency;
return typeof code === 'string' && code !== '' ? code : fallback;
}
/**
* Which owner's limits a panel should show. The current provider wins when
* it has limits; otherwise the owner that does, so limits never appear to
* vanish just because the session uses another provider.
*/
function resolveLimitOwner(state, preferred) {
if (preferred !== undefined && hasLimits(state, preferred)) return preferred;
const owners = Object.keys(state.limits ?? {}).filter((owner) => hasLimits(state, owner));
if (owners.length > 0) return owners[0];
return preferred ?? ownerForCurrency(state.currency);
}
function writeLimits(owner, currency, limits) {
const state = readSpend();
const store = (value) => {
const parsed = Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
};
state.limits[owner] = {
currency,
day: store(limits.day),
week: store(limits.week),
month: store(limits.month),
};
state.currency = currency;
writeSpend(state, { mode: 'limits' });
}
/** Forget the recorded spending and token history, keeping the soft limits. */
function clearSpendHistory() {
const state = readSpend();
state.hours = {};
state.samples = {};
state.tokens = {};
writeSpend(state, { mode: 'clear' });
}
/** Local `YYYY-MM-DD` value for a date input. */
function dateInputValue(ms) {
const date = new Date(ms);
const pad = (value) => String(value).padStart(2, '0');
return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/** Local day start from a `YYYY-MM-DD` value, or undefined. */
function parseDayInput(value) {
if (typeof value !== 'string') return undefined;
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (match === null) return undefined;
const time = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime();
return Number.isFinite(time) ? time : undefined;
}
/**
* Replace one local day's recorded spending with a single total.
*
* Only the day sum is known by hand, never its hourly split, so the total is
* spread over the hours of that day that have already passed: a past day is
* flat across all 24, and today only up to the current hour, so the sum is
* visible in the day window straight away. Zero (or an empty amount that
* reaches here) clears the day instead.
*/
function writeDayTotal(currency, dayStart, amount) {
const state = readSpend();
const dayEnd = dayStart + 24 * HOUR_MS;
for (const key of Object.keys(state.hours)) {
const hour = Number(key);
if (Number.isFinite(hour) && hour >= dayStart && hour < dayEnd) delete state.hours[key];
}
const value = Number(amount);
const buckets = {};
if (Number.isFinite(value) && value > 0) {
const elapsed = Math.max(1, Math.min(24, Math.ceil((Math.min(Date.now(), dayEnd) - dayStart) / HOUR_MS)));
const firstHour = hourKey(dayStart);
const perHour = value / elapsed;
for (let index = 0; index < elapsed; index += 1) {
const hour = firstHour + index * HOUR_MS;
addHourSpend(state, currency, hour, perHour);
buckets[String(hour)] = perHour;
}
}
state.currency = currency;
/* The Host replaces just this day, so a manual correction is not undone
* by another window's automatic merge. */
writeSpend(state, { mode: 'day', day: { start: dayStart, currency, buckets } });
}
/** Model id used as a key in the token history. */
function tokenModelId(model) {
const id = typeof model === 'string' && model.trim() !== '' ? model.trim() : 'unknown';
return id.length > 64 ? id.slice(0, 64) : id;
}
/**
* Fold one raw token delta into the hour it was observed in.
*
* Cache writes are stored apart from uncached input: pricing folds them
* together, but the cache tab has to show how much was written into the
* cache versus read from it.
*/
function recordTokenSample(model, delta, at) {
if (delta === undefined || delta === null) return;
const miss = finite(delta.miss) ?? 0;
const write = finite(delta.write) ?? 0;
const hit = finite(delta.hit) ?? 0;
const out = finite(delta.out) ?? 0;
if (miss + write + hit + out <= 0) return;
const state = readSpend();
const key = String(hourKey(at));
const id = tokenModelId(model);
const bucket = state.tokens[key] ?? {};
const entry = bucket[id] ?? { miss: 0, write: 0, hit: 0, out: 0 };
state.tokens[key] = {
...bucket,
[id]: {
miss: entry.miss + miss,
write: entry.write + write,
hit: entry.hit + hit,
out: entry.out + out,
},
};
pruneSpend(state);
writeSpend(state);
}
/** Colour band for one spent/limit pair. */
function limitLevel(spent, limit) {
if (!(limit > 0)) return 'none';
const ratio = spent / limit;
if (ratio >= 1) return 'over';
if (ratio >= RATIO_WARN) return 'warn';
return 'ok';
}
/**
* Geometry of the two-tone limit bar. The bar is normalised to the larger
* of the spend and the limit, so an overrun stays inside the card instead
* of being clipped at 100%: the blue part ends exactly at the limit and
* the red part is the excess. With no limit both widths are zero and the
* track stays empty.
*/
function limitBar(spent, limit) {
const over = limit > 0 && spent > limit;
const scale = over ? spent : limit;
/* A visible sliver for a nonzero spend, an empty track for a zero one. */
const baseWidth = spent > 0 && scale > 0 ? Math.max(2, (Math.min(spent, limit) / scale) * 100) : 0;
return {
over,
baseWidth,
overWidth: over ? Math.max(0, 100 - baseWidth) : 0,
overAmount: over ? spent - limit : 0,
};
}
/**
* Live view of the ledger: notified on local writes, pulled from the Host
* while the page is open so another window's records show up too, and
* re-read when the tab becomes visible again.
*/
function useSpendLedger() {
const [state, setState] = React.useState(readSpend);
React.useEffect(() => {
const refresh = () => setState(readSpend());
const pull = () => {
void pullSpend().finally(refresh);
};
/* While the old browser storage is in charge, another tab still writes
* there; follow those writes the way the previous version did. */
const onStorage = () => {
if (spendMode !== 'local') return;
spendState = readLegacySpend();
refresh();
};
const onVisibility = () => {
if (document.visibilityState === 'visible') pull();
};
window.addEventListener(SPEND_EVENT, refresh);
window.addEventListener('storage', onStorage);
document.addEventListener('visibilitychange', onVisibility);
const timer = window.setInterval(pull, SPEND_PULL_MS);
return () => {
window.removeEventListener(SPEND_EVENT, refresh);
window.removeEventListener('storage', onStorage);
document.removeEventListener('visibilitychange', onVisibility);
window.clearInterval(timer);
};
}, []);
return state;
}
/** Daily Central Bank rates; rerenders the views when they arrive. */
function useFxRates() {
const [snapshot, setSnapshot] = React.useState(() => ({
rates: fxRates,
date: fxDate,
status: fxStatus,
}));
React.useEffect(() => {
const refresh = () => setSnapshot({ rates: fxRates, date: fxDate, status: fxStatus });
window.addEventListener(FX_EVENT, refresh);
if (fxStatus === 'idle') void refreshFxRates();
return () => window.removeEventListener(FX_EVENT, refresh);
}, []);
return snapshot;
}
// #endregion
// #region formatting
const formatters = new Map();
function formatNumber(value, digits) {
try {
let formatter = formatters.get(digits);
if (formatter === undefined) {
formatter = new Intl.NumberFormat(undefined, {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
});
formatters.set(digits, formatter);
}
return formatter.format(value);
} catch {
return value.toFixed(digits);
}
}
/** Money for a pill: sub-unit amounts keep enough digits to stay nonzero. */
function formatMoney(value, currency) {
return formatMoneySymbol(value, CURRENCY_SYMBOL[currency] ?? '');
}
/** Money with one explicit currency symbol (third-party operator balances). */
function formatMoneySymbol(value, symbol) {
const abs = Math.abs(value);
const text = formatNumber(value, abs > 0 && abs < 1 ? 4 : 2);
/* Rubles read as a suffix; other wallet currencies stay prefixed. */
return symbol === '₽' ? `${text} ${symbol}` : symbol + text;
}
/** A per-1M rate with its trailing zeros trimmed. */
function formatRate(value) {
return String(Number(value.toFixed(4)));
}
/**
* Human name of the provider serving the selected model, for the balance
* reading. Ids come from `modelSelection`; the branded spellings are
* fixed here because an id such as `openrusrouter` does not title-case
* into the operator's own name.
*/
function providerLabel(provider) {
if (provider === undefined || provider === null || provider === '') return 'DeepSeek';
if (provider === 'deepseek-account' || provider === 'deepseek-official') return 'DeepSeek';
if (provider === 'openrusrouter') return 'OpenRusRouter';
return provider.charAt(0).toUpperCase() + provider.slice(1);
}
// #endregion
// #region icons
function CostIcon() {
return h(
'svg',
{ viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': true, style: { display: 'block', flex: 'none' } },
h('circle', { cx: 8, cy: 8, r: 6, fill: 'none', stroke: 'currentColor', strokeWidth: 1.2 }),
h('path', {
d: 'M5.6 5.1 8 8l2.4-2.9M8 8v3.7M6.1 9.3h3.8',
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.2,
strokeLinecap: 'round',
strokeLinejoin: 'round',
}),
);
}
function BalanceIcon() {
return h(
'svg',
{ viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': true, style: { display: 'block', flex: 'none' } },
h('rect', {
x: 1.9,
y: 4.3,
width: 12.2,
height: 8.2,
rx: 1.7,
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.2,
}),
h('path', { d: 'M1.9 7.1h6.2', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
h('circle', { cx: 11.3, cy: 10, r: 0.9, fill: 'currentColor' }),
);
}
// #endregion
// #region statistics
/**
* Money with a compact, integer-leaning rendering for charts and chips.
* The sign goes outside the currency symbol, so a negative remainder reads
* "-200 ₽" / "-$200" rather than "$-200", and the ruble stays a suffix.
*/
function formatShortMoney(value, symbol) {
const abs = Math.abs(value);
const digits = abs > 0 && abs < 1 ? 2 : 0;
const text = formatNumber(abs, digits);
const sign = value < 0 ? '-' : '';
return symbol === '₽' ? `${sign}${text} ${symbol}` : `${sign}${symbol}${text}`;
}
function daysInMonth(ms) {
const date = new Date(ms);
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}
/** 24 hourly totals for one local day. */
function hourlySeries(state, currency, dayStart) {
const values = [];
for (let hour = 0; hour < 24; hour += 1) {
const from = dayStart + hour * HOUR_MS;
values.push(sumMoney(state, currency, from, from + HOUR_MS - 1));
}
return values;
}
/** One total per local day, `count` days from `fromMs`. */
function dailySeries(state, currency, fromMs, count) {
const cursor = new Date(fromMs);
cursor.setHours(0, 0, 0, 0);
const values = [];
for (let index = 0; index < count; index += 1) {
const from = cursor.getTime();
values.push(sumMoney(state, currency, from, from + 24 * HOUR_MS - 1));
cursor.setDate(cursor.getDate() + 1);
}
return values;
}
function weekdayShort(ms) {
try {
return new Intl.DateTimeFormat(undefined, { weekday: 'short' }).format(new Date(ms));
} catch {
return String(new Date(ms).getDay());
}
}
function dayLabel(ms) {
const date = new Date(ms);
return `${date.getDate()}.${String(date.getMonth() + 1).padStart(2, '0')}`;
}
/** Compact token counts: 980, 12.4K, 1.23M. */
function formatTokens(value) {
const abs = Math.abs(value);
if (abs >= 1_000_000) return `${formatNumber(value / 1_000_000, 2)}M`;
if (abs >= 1_000) return `${formatNumber(value / 1_000, abs >= 10_000 ? 0 : 1)}K`;
return formatNumber(value, 0);
}
function formatPercent(value) {
if (!Number.isFinite(value) || value <= 0) return '0%';
return `${formatNumber(value >= 10 ? Math.round(value) : Math.round(value * 10) / 10, value >= 10 ? 0 : 1)}%`;
}
/** Token totals of one window, with the input side folded for display. */
function tokenTotals(state, fromMs, toMs) {
const totals = { miss: 0, write: 0, hit: 0, out: 0 };
for (const [key, models] of Object.entries(state.tokens ?? {})) {
const hour = Number(key);
if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue;
for (const entry of Object.values(models ?? {})) {
if (entry === null || typeof entry !== 'object') continue;
totals.miss += finite(entry.miss) ?? 0;
totals.write += finite(entry.write) ?? 0;
totals.hit += finite(entry.hit) ?? 0;
totals.out += finite(entry.out) ?? 0;
}
}
totals.input = totals.miss + totals.write;
totals.total = totals.input + totals.hit + totals.out;
return totals;
}
/** Cache-read share of the input traffic (hit against hit + input). */
function cacheShare(totals) {
const inputSide = (totals.input ?? 0) + (totals.hit ?? 0);
return inputSide > 0 ? ((totals.hit ?? 0) / inputSide) * 100 : 0;
}
/** One row per model of one window, largest first. */
function tokenModels(state, fromMs, toMs) {
const models = new Map();
for (const [key, buckets] of Object.entries(state.tokens ?? {})) {
const hour = Number(key);
if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue;
for (const [model, entry] of Object.entries(buckets ?? {})) {
if (entry === null || typeof entry !== 'object') continue;
const row = models.get(model) ?? { model, miss: 0, write: 0, hit: 0, out: 0 };
row.miss += finite(entry.miss) ?? 0;
row.write += finite(entry.write) ?? 0;
row.hit += finite(entry.hit) ?? 0;
row.out += finite(entry.out) ?? 0;
models.set(model, row);
}
}
return [...models.values()]
.map((row) => ({
...row,
input: row.miss + row.write,
total: row.miss + row.write + row.hit + row.out,
}))
.sort((left, right) => right.total - left.total);
}
/**
* Background of one daily bar. Days that went past the daily limit reuse
* the two-tone language of the card bar: blue up to the limit, red above,
* so the days with an overrun stand out in the week/month chart.
*/
function barBackground(value, dayLimit) {
if (!(dayLimit > 0) || value <= dayLimit) return undefined;
const share = (dayLimit / value) * 100;
return (
'linear-gradient(to top,' +
' var(--dsw-alias-state-business-primary) 0 ' + share + '%,' +
' var(--dsw-alias-state-error-primary) ' + share + '% 100%)'
);
}
/**
* Bar chart built from plain flex boxes so it scales with the panel.
*
* `valueLabel` prints the bar's number above it. Adjacent bars are placed
* on two vertical levels: 24 or 31 bars in one row are narrow, and two
* three-digit labels side by side would otherwise collide.
*/
function BarChart({ values, labels, formatTitle, highlight, selected, onSelect, dayLimit, scaleMax, valueLabel }) {
const max = Math.max(1, scaleMax ?? Math.max(...values));
return h(
'div',
{ className: 'dshStats_chart' },
h(
'div',
{ className: 'dshStats_bars' },
values.map((value, index) => {
/* Zero buckets keep an empty slot: no stub bar and no label, so
* the chart shows only hours and days that actually have spend. */
const heightPct = value > 0 ? Math.max(3, (value / max) * 100) : 0;
const label = valueLabel === undefined ? null : valueLabel(value);
const level = index % 2;
/* The value is a sibling of the bar, not a child: the bar carries
* opacity, and a label inside it would fade together with it. Both
* levels sit above the bar top, so neighbours at a similar height
* never share one row. */
const labelStyle =
label === null || label === undefined
? undefined
: { bottom: `calc(${heightPct}% + ${level === 0 ? 2 : 14}px)` };
return h(
'div',
{
key: index,
className: 'dshStats_barSlot',
title: formatTitle(index, value),
},
h('div', {
className: [
'dshStats_bar',
highlight === index ? 'dshStats_barCurrent' : '',
selected === index ? 'dshStats_barSelected' : '',
onSelect === undefined ? '' : 'dshStats_barClickable',
]
.filter((name) => name !== '')
.join(' '),
style: {
height: `${heightPct}%`,
background: barBackground(value, dayLimit),
},
onClick: onSelect === undefined ? undefined : () => onSelect(index),
}),
label === null || label === undefined
? null
: h(
'span',
{
className: 'dshStats_barValue',
'data-level': level === 0 ? 'low' : 'high',
style: labelStyle,
},
label,
),
);
}),
),
h(
'div',
{ className: 'dshStats_axis' },
labels.map((label, index) => h('span', { key: index, className: 'dshStats_axisLabel' }, label)),
),
);
}
/**
* Spending history, period totals, hourly detail, and the soft limits.
* Mounted twice: inside Settings and as a dock overlay.
*/
function StatsPanel({ t, onClose, provider }) {
const spend = useSpendLedger();
const fx = useFxRates();
const [period, setPeriod] = React.useState('day');
const [view, setView] = React.useState('spend');
const [selectedDay, setSelectedDay] = React.useState(null);
/* The spending tab is the tallest one, and a modal that grows and
* shrinks as the user flips tabs is disorienting. Measure it while it is
* on screen and reserve that height for the shorter tabs; the reserve
* only grows, so expanding a day or switching the period never shrinks
* the dialog under the pointer. */
const rootRef = React.useRef(null);
const [reservedHeight, setReservedHeight] = React.useState(0);
React.useEffect(() => {
if (view !== 'spend') return;
const node = rootRef.current;
if (node === null || node === undefined) return;
const height = typeof node.offsetHeight === 'number' ? node.offsetHeight : 0;
if (height > 0) setReservedHeight((previous) => (height > previous ? height : previous));
}, [view, period, selectedDay, spend]);
const now = Date.now();
/* Limits belong to the provider that bills the selected model; in the
* settings section there is no provider, so the owner that has limits
* wins and they never look as if they disappeared. */
const limitOwnerId = resolveLimitOwner(
spend,
provider === undefined ? undefined : limitOwner(provider),
);
const currency = limitCurrency(spend, limitOwnerId, spend.currency);
const symbol = CURRENCY_TO_SYMBOL[currency] ?? '';
const limits = limitsOf(spend, limitOwnerId);
const limitsKey = `${currency}:${limits.day}:${limits.week}:${limits.month}`;
/* The inputs keep their raw text so a half-typed "0." is not rounded
* away; the ledger stores the parsed number. */
const draftOf = (value) => ({
day: value.day > 0 ? String(value.day) : '',
week: value.week > 0 ? String(value.week) : '',
month: value.month > 0 ? String(value.month) : '',
});
const [draft, setDraft] = React.useState(() => draftOf(limits));
React.useEffect(() => {
setDraft(draftOf(limits));
}, [limitsKey]);
/* Manual correction of one day's total. The per-hour split of a past day
* is rarely worth reconstructing, so the user types the day sum and the
* recorded hours of that day are replaced by it. */
const [manualDate, setManualDate] = React.useState(() => dateInputValue(Date.now()));
const [manualAmount, setManualAmount] = React.useState('');
const manualStart = parseDayInput(manualDate);
const manualTotal =
manualStart === undefined ? 0 : sumSpend(spend, currency, manualStart, manualStart + 24 * HOUR_MS - 1);
const manualKey = `${manualDate}:${Math.round(manualTotal * 100)}`;
React.useEffect(() => {
setManualAmount(manualTotal > 0 ? String(Math.round(manualTotal * 100) / 100) : '');
}, [manualKey]);
const dayStart = startOfDay(now);
const weekStart = startOfWeek(now);
const monthStart = startOfMonth(now);
const spent = {
day: sumMoney(spend, currency, dayStart, now),
week: sumMoney(spend, currency, weekStart, now),
month: sumMoney(spend, currency, monthStart, now),
};
const fxRateLine =
currency === 'RUB' && fx.status === 'ready' && Object.keys(fx.rates).length > 0
? t('stats.fxNote', {
rates: Object.entries(fx.rates)
.map(([code, rate]) => `${code} ${formatNumber(rate, 2)} ₽`)
.join(' · '),
})
: null;
const fxMissingCodes = currency === 'RUB' ? unconvertedCurrencies(spend) : [];
const fxMissingLine =
fxMissingCodes.length > 0
? t('stats.fxMissing', { codes: fxMissingCodes.join(', ') })
: null;
const fxNotes =
fxRateLine === null && fxMissingLine === null
? null
: h(
'div',
{ className: 'dshStats_fxNotes' },
fxRateLine === null ? null : h('p', { key: 'rate', className: 'dshStats_hint' }, fxRateLine),
fxMissingLine === null
? null
: h('p', { key: 'missing', className: 'dshStats_hint' }, fxMissingLine),
);
/* Values printed on the bars: plain numbers, no kopecks and no currency
* symbol (the currency is already named by the section subtitle). A
* smeared delta can leave a fraction in a bucket; rounding it to zero
* must not print "0" on the chart, so only a non-zero rounded value is
* labelled and drawn at all. */
const moneyValueLabel = (value) => {
const rounded = Math.round(value);
return rounded > 0 ? formatNumber(rounded, 0) : null;
};
const tokenValueLabel = (value) => {
const rounded = Math.round(value);
return rounded > 0 ? formatTokens(rounded) : null;
};
const shareValueLabel = (value) => {
const rounded = Math.round(value);
return rounded > 0 ? formatPercent(rounded) : null;
};
const periodName = (key) => t(`stats.period.${key}`);
const levelOf = (key) => limitLevel(spent[key], limits[key]);
const cards = h(
'div',
{ className: 'dshStats_cards' },
LIMIT_PERIODS.map((key) => {
const level = levelOf(key);
const limit = limits[key];
const spentNow = spent[key];
const bar = limitBar(spentNow, limit);
return h(
'button',
{
key,
type: 'button',
className: ['dshStats_card', period === key ? 'dshStats_cardActive' : ''].filter(Boolean).join(' '),
'data-level': level,
onClick: () => {
setPeriod(key);
setSelectedDay(null);
},
},
h('span', { className: 'dshStats_cardLabel' }, periodName(key)),
h('span', { className: 'dshStats_cardValue' }, formatShortMoney(spentNow, symbol)),
h(
'span',
{ className: 'dshStats_cardLimit' },
limit > 0
? bar.over
? t('stats.overLimit', {
over: formatShortMoney(bar.overAmount, symbol),
limit: formatShortMoney(limit, symbol),
})
: t('stats.ofLimit', { limit: formatShortMoney(limit, symbol) })
: t('stats.noLimit'),
),
h(
'span',
{ className: 'dshStats_progress' },
bar.baseWidth > 0
? h('span', {
className: 'dshStats_progressFill',
style: { width: `${bar.baseWidth}%` },
})
: null,
bar.overWidth > 0
? h('span', {
className: 'dshStats_progressOver',
style: { width: `${bar.overWidth}%` },
})
: null,
),
);
}),
);
let chart;
let detail = null;
if (period === 'day') {
const values = hourlySeries(spend, currency, dayStart);
chart = h(BarChart, {
values,
labels: values.map((_, hour) => (hour % 3 === 0 ? String(hour) : '')),
formatTitle: (hour, value) =>
t('stats.hourTitle', {
hour: String(hour).padStart(2, '0'),
amount: formatShortMoney(value, symbol),
}),
highlight: new Date(now).getHours(),
valueLabel: moneyValueLabel,
});
} else {
const count = period === 'week' ? 7 : daysInMonth(now);
const from = period === 'week' ? weekStart : monthStart;
const values = dailySeries(spend, currency, from, count);
const dayStarts = [];
const walker = new Date(from);
walker.setHours(0, 0, 0, 0);
for (let index = 0; index < count; index += 1) {
dayStarts.push(walker.getTime());
walker.setDate(walker.getDate() + 1);
}
const selectedIndex = selectedDay === null ? -1 : dayStarts.indexOf(startOfDay(selectedDay));
chart = h(BarChart, {
values,
labels: dayStarts.map((day, index) =>
period === 'week' ? weekdayShort(day) : index % 5 === 0 ? String(new Date(day).getDate()) : '',
),
formatTitle: (index, value) =>
limits.day > 0 && value > limits.day
? t('stats.dayOverTitle', {
date: dayLabel(dayStarts[index]),
amount: formatShortMoney(value, symbol),
over: formatShortMoney(value - limits.day, symbol),
})
: t('stats.dayTitle', {
date: dayLabel(dayStarts[index]),
amount: formatShortMoney(value, symbol),
}),
highlight: dayStarts.indexOf(dayStart),
selected: selectedIndex >= 0 ? selectedIndex : undefined,
onSelect: (index) => setSelectedDay(dayStarts[index]),
dayLimit: limits.day,
valueLabel: moneyValueLabel,
});
if (selectedDay !== null) {
const detailStart = startOfDay(selectedDay);
const hours = hourlySeries(spend, currency, detailStart);
detail = h(
'div',
{ className: 'dshStats_detail' },
h(
'div',
{ className: 'dshStats_detailHeader' },
h(
'span',
{ className: 'dshStats_detailTitle' },
t('stats.hourlyFor', { date: dayLabel(detailStart) }),
),
h(
'button',
{
type: 'button',
className: 'dshStats_linkButton',
onClick: () => setSelectedDay(null),
},
t('stats.back'),
),
),
h(BarChart, {
values: hours,
labels: hours.map((_, hour) => (hour % 3 === 0 ? String(hour) : '')),
formatTitle: (hour, value) =>
t('stats.hourTitle', {
hour: String(hour).padStart(2, '0'),
amount: formatShortMoney(value, symbol),
}),
valueLabel: moneyValueLabel,
}),
);
}
}
const periodLimit = limits[period];
const periodSpent = spent[period];
const periodOver = periodLimit > 0 && periodSpent > periodLimit;
const summary = h(
'div',
{ className: 'dshStats_summary' },
h('span', { className: 'dshStats_summaryAmount', 'data-level': levelOf(period) }, formatShortMoney(periodSpent, symbol)),
periodLimit > 0
? h(
'span',
{ className: 'dshStats_summaryNote', 'data-level': periodOver ? 'over' : undefined },
periodOver
? t('stats.overLimit', {
over: formatShortMoney(periodSpent - periodLimit, symbol),
limit: formatShortMoney(periodLimit, symbol),
})
: t('stats.leftOfLimit', {
left: formatShortMoney(Math.max(0, periodLimit - periodSpent), symbol),
limit: formatShortMoney(periodLimit, symbol),
}),
)
: h('span', { className: 'dshStats_summaryNote' }, t('stats.noLimit')),
);
/* Tokens and cache reuse the period selector and the same hourly/daily
* buckets as the spending chart. */
const bucketStep = period === 'day' ? HOUR_MS : 24 * HOUR_MS;
const bucketStarts = [];
if (period === 'day') {
for (let hour = 0; hour < 24; hour += 1) bucketStarts.push(dayStart + hour * HOUR_MS);
} else {
const count = period === 'week' ? 7 : daysInMonth(now);
const walker = new Date(period === 'week' ? weekStart : monthStart);
walker.setHours(0, 0, 0, 0);
for (let index = 0; index < count; index += 1) {
bucketStarts.push(walker.getTime());
walker.setDate(walker.getDate() + 1);
}
}
const periodFrom = period === 'day' ? dayStart : period === 'week' ? weekStart : monthStart;
const bucketTotals = bucketStarts.map((start) => tokenTotals(spend, start, start + bucketStep - 1));
const tokenPeriod = tokenTotals(spend, periodFrom, now);
const modelRows = tokenModels(spend, periodFrom, now);
const bucketLabels =
period === 'day'
? bucketStarts.map((_, hour) => (hour % 3 === 0 ? String(hour) : ''))
: period === 'week'
? bucketStarts.map((day) => weekdayShort(day))
: bucketStarts.map((day, index) => (index % 5 === 0 ? String(new Date(day).getDate()) : ''));
const chartHighlight = period === 'day' ? new Date(now).getHours() : bucketStarts.indexOf(dayStart);
const tokenTitle = (index, value) =>
period === 'day'
? t('stats.tokens.hourTitle', { hour: String(index).padStart(2, '0'), amount: formatTokens(value) })
: t('stats.tokens.dayTitle', { date: dayLabel(bucketStarts[index]), amount: formatTokens(value) });
const cacheTitle = (index, value) =>
period === 'day'
? t('stats.cache.hourTitle', { hour: String(index).padStart(2, '0'), percent: formatPercent(value) })
: t('stats.cache.dayTitle', { date: dayLabel(bucketStarts[index]), percent: formatPercent(value) });
const modelTable = (columns) =>
h(
'div',
{ className: 'dshStats_tableBlock' },
h('div', { className: 'dshStats_chartTitle' }, t('stats.tokens.byModel')),
modelRows.length === 0
? h('p', { className: 'dshStats_hint' }, t('stats.tokens.empty'))
: h(
'div',
{ className: 'dshStats_table' },
h(
'div',
{ className: 'dshStats_tableRow dshStats_tableHead' },
h('span', null, t('stats.tokens.model')),
columns.map((column) =>
h('span', { key: column.key, className: 'dshStats_num' }, t(column.label)),
),
),
modelRows.map((row) =>
h(
'div',
{ key: row.model, className: 'dshStats_tableRow' },
h('span', { className: 'dshStats_modelCell', title: row.model }, row.model),
columns.map((column) =>
h('span', { key: column.key, className: 'dshStats_num' }, column.value(row)),
),
),
),
),
);
const tokenCards = h(
'div',
{ className: 'dshStats_cards' },
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.input')),
h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.input)),
h(
'span',
{ className: 'dshStats_cardLimit' },
t('stats.tokens.writeNote', { amount: formatTokens(tokenPeriod.write) }),
),
),
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.cached')),
h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.hit)),
h(
'span',
{ className: 'dshStats_cardLimit' },
t('stats.cache.shareNote', { percent: formatPercent(cacheShare(tokenPeriod)) }),
),
),
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.output')),
h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.out)),
h(
'span',
{ className: 'dshStats_cardLimit' },
t('stats.tokens.totalNote', { amount: formatTokens(tokenPeriod.total) }),
),
),
);
const cacheCards = h(
'div',
{ className: 'dshStats_cards' },
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.ratio')),
h('span', { className: 'dshStats_cardValue' }, formatPercent(cacheShare(tokenPeriod))),
h(
'span',
{ className: 'dshStats_cardLimit' },
t('stats.cache.summaryNote', {
hit: formatTokens(tokenPeriod.hit),
total: formatTokens(tokenPeriod.input + tokenPeriod.hit),
}),
),
),
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.hit')),
h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.hit)),
),
h(
'div',
{ className: 'dshStats_card dshStats_cardStatic' },
h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.miss')),
h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.input)),
),
);
const tokensContent = [
tokenCards,
h(
'div',
{ className: 'dshStats_summary' },
h('span', { className: 'dshStats_summaryAmount' }, formatTokens(tokenPeriod.total)),
h('span', { className: 'dshStats_summaryNote' }, t('stats.tokens.unit')),
),
h(
'div',
{ className: 'dshStats_chartBlock' },
h(
'div',
{ className: 'dshStats_chartTitle' },
period === 'day' ? t('stats.byHour') : t('stats.byDay'),
),
h(BarChart, {
values: bucketTotals.map((totals) => totals.total),
labels: bucketLabels,
formatTitle: tokenTitle,
highlight: chartHighlight,
valueLabel: tokenValueLabel,
}),
),
modelTable([
{ key: 'input', label: 'stats.tokens.input', value: (row) => formatTokens(row.input) },
{ key: 'hit', label: 'stats.tokens.cached', value: (row) => formatTokens(row.hit) },
{ key: 'out', label: 'stats.tokens.output', value: (row) => formatTokens(row.out) },
]),
];
const cacheContent = [
cacheCards,
h(
'div',
{ className: 'dshStats_chartBlock' },
h(
'div',
{ className: 'dshStats_chartTitle' },
period === 'day' ? t('stats.byHour') : t('stats.byDay'),
),
h(BarChart, {
values: bucketTotals.map((totals) => cacheShare(totals)),
labels: bucketLabels,
formatTitle: cacheTitle,
highlight: chartHighlight,
scaleMax: 100,
valueLabel: shareValueLabel,
}),
),
modelTable([
{ key: 'hit', label: 'stats.cache.hit', value: (row) => formatTokens(row.hit) },
{ key: 'miss', label: 'stats.cache.miss', value: (row) => formatTokens(row.input) },
{ key: 'share', label: 'stats.cache.ratio', value: (row) => formatPercent(cacheShare(row)) },
]),
];
const applyLimits = (next) => {
setDraft(next);
writeLimits(limitOwnerId, currency, next);
};
const deriveFromMonth = () => {
const month = Number(draft.month);
if (!Number.isFinite(month) || month <= 0) return;
applyLimits({
day: String(Math.round(month / 30)),
week: String(Math.round((month * 7) / 30)),
month: String(Math.round(month)),
});
};
/* Readings recorded before the ledger learned to ignore bookkeeping
* changes stay in the history; one click drops them without touching the
* limits. */
const resetHistory = () => {
const ask = typeof window === 'undefined' ? undefined : window.confirm;
if (typeof ask === 'function' && !ask(t('stats.resetConfirm'))) return;
clearSpendHistory();
};
const applyManualDay = () => {
if (manualStart === undefined) return;
const text = String(manualAmount).trim();
if (text === '') return;
/* A decimal comma is what the Russian keyboard produces; an unparsable
* amount must not silently clear the day. */
const parsed = Number(text.replace(',', '.'));
if (!Number.isFinite(parsed) || parsed < 0) return;
writeDayTotal(currency, manualStart, parsed);
};
const historyContent = [
h(
'div',
{ className: 'dshStats_limitsBlock' },
h('h3', { className: 'dshStats_limitsTitle' }, t('stats.manualTitle')),
h('p', { className: 'dshStats_hint' }, t('stats.manualHint', { symbol })),
h(
'div',
{ className: 'dshStats_manualRow' },
h(
'label',
{ className: 'dshStats_limitField' },
h('span', { className: 'dshStats_limitLabel' }, t('stats.manualDay')),
h(
'span',
{ className: 'dshStats_inputWrap' },
h('input', {
type: 'date',
className: 'dshStats_input dshStats_date',
value: manualDate,
max: dateInputValue(Date.now()),
onChange: (event) => setManualDate(event.target.value),
}),
),
),
h(
'label',
{ className: 'dshStats_limitField' },
h('span', { className: 'dshStats_limitLabel' }, t('stats.manualTotal')),
h(
'span',
{ className: 'dshStats_inputWrap' },
h('input', {
type: 'number',
min: '0',
step: '10',
inputMode: 'decimal',
className: 'dshStats_input',
value: manualAmount,
placeholder: t('stats.notSet'),
onChange: (event) => setManualAmount(event.target.value),
}),
h('span', { className: 'dshStats_symbol' }, symbol),
),
),
h('button', { type: 'button', className: 'dshStats_button', onClick: applyManualDay }, t('stats.manualApply')),
),
h(
'div',
{ className: 'dshStats_actions' },
h('button', { type: 'button', className: 'dshStats_button', onClick: resetHistory }, t('stats.resetHistory')),
h('span', { className: 'dshStats_hint' }, t('stats.resetHint')),
),
),
];
return h(
'div',
{
ref: rootRef,
className: 'dshStats_root',
style: view === 'spend' || reservedHeight === 0 ? undefined : { minHeight: `${reservedHeight}px` },
},
h(
'div',
{ className: 'dshStats_header' },
h(
'div',
{ className: 'dshStats_titles' },
h('h2', { className: 'dshStats_title' }, t('stats.title')),
h(
'p',
{ className: 'dshStats_subtitle' },
view === 'spend'
? t('stats.subtitle', { symbol })
: view === 'tokens'
? t('stats.tokens.subtitle')
: view === 'cache'
? t('stats.cache.subtitle')
: t('stats.history.subtitle'),
),
),
onClose === undefined
? null
: h(
'button',
{
type: 'button',
className: 'dshStats_close',
onClick: onClose,
'aria-label': t('stats.close'),
title: t('stats.close'),
},
'×',
),
),
h(
'div',
{ className: 'dshStats_periods' },
LIMIT_PERIODS.map((key) =>
h(
'button',
{
key,
type: 'button',
className: ['dshStats_period', period === key ? 'dshStats_periodActive' : ''].filter(Boolean).join(' '),
onClick: () => {
setPeriod(key);
setSelectedDay(null);
},
},
periodName(key),
),
),
),
h(
'div',
{ className: 'dshStats_views' },
[
['spend', 'stats.view.spend'],
['tokens', 'stats.view.tokens'],
['cache', 'stats.view.cache'],
['history', 'stats.view.history'],
].map(([id, key]) =>
h(
'button',
{
key: id,
type: 'button',
className: ['dshStats_view', view === id ? 'dshStats_viewActive' : ''].filter(Boolean).join(' '),
onClick: () => {
setView(id);
setSelectedDay(null);
},
},
t(key),
),
),
),
view === 'spend'
? [
cards,
summary,
fxNotes,
h(
'div',
{ className: 'dshStats_chartBlock' },
h(
'div',
{ className: 'dshStats_chartTitle' },
period === 'day' ? t('stats.byHour') : t('stats.byDay'),
),
chart,
period === 'day'
? null
: [
h('p', { key: 'click', className: 'dshStats_hint' }, t('stats.clickHint')),
limits.day > 0
? h('p', { key: 'over', className: 'dshStats_hint' }, t('stats.overDaysHint'))
: null,
],
),
detail,
h(
'div',
{ className: 'dshStats_limitsBlock' },
h('h3', { className: 'dshStats_limitsTitle' }, t('stats.limitsTitle')),
h(
'p',
{ className: 'dshStats_hint' },
t('stats.limitsOwnerHint', { provider: limitOwnerLabel(limitOwnerId), symbol }),
),
h(
'div',
{ className: 'dshStats_limitRow' },
LIMIT_PERIODS.map((key) =>
h(
'label',
{ key, className: 'dshStats_limitField' },
h('span', { className: 'dshStats_limitLabel' }, t(`stats.limit.${key}`)),
h(
'span',
{ className: 'dshStats_inputWrap' },
h('input', {
type: 'number',
min: '0',
step: '10',
inputMode: 'decimal',
className: 'dshStats_input',
value: draft[key],
placeholder: t('stats.notSet'),
onChange: (event) => {
applyLimits({ ...draft, [key]: event.target.value });
},
}),
h('span', { className: 'dshStats_symbol' }, symbol),
),
),
),
),
h(
'div',
{ className: 'dshStats_actions' },
h('button', { type: 'button', className: 'dshStats_button', onClick: deriveFromMonth }, t('stats.derive')),
h('span', { className: 'dshStats_hint' }, t('stats.deriveHint')),
),
),
]
: view === 'tokens'
? tokensContent
: view === 'cache'
? cacheContent
: historyContent,
);
}
/**
* Reload action in the sidebar footer, beside the settings and profile
* rows. A page reload re-fetches the shell and every client plugin bundle;
* running agents live in the Host process, so the sessions keep working and
* the page simply reconnects to them.
*/
function ReloadButton({ wide, t }) {
return h(
'div',
{ className: 'dshReload_wrap', 'data-wide': wide === false ? 'false' : 'true' },
h(
'button',
{
type: 'button',
className: 'dshReload_button',
title: t('quickReload.title'),
'aria-label': t('quickReload.title'),
'data-composer-stat': 'reload',
onClick: () => {
try {
window.location.reload();
} catch {
/* A test rig without a location cannot reload. */
}
},
},
h(
'svg',
{
viewBox: '0 0 16 16',
width: 16,
height: 16,
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.4,
strokeLinecap: 'round',
strokeLinejoin: 'round',
'aria-hidden': true,
},
h('path', { d: 'M12.6 8a4.6 4.6 0 1 1-1.35-3.25' }),
h('path', { d: 'M12.6 2.55v2.5h-2.5' }),
),
/* The rail has no room for a caption; the pill shows it when wide. */
wide === false ? null : h('span', { className: 'dshReload_label' }, t('quickReload.label')),
),
);
}
/**
* Clock: today's remaining budget. Same 16x16 viewBox, stroke width, and
* circle radius as the balance and spend icons, so the three glyphs share
* one optical size and baseline in the dock row.
*/
function DayIcon() {
return h(
'svg',
{
viewBox: '0 0 16 16',
width: 16,
height: 16,
'aria-hidden': true,
style: { display: 'block', flex: 'none' },
},
h('circle', {
cx: 8,
cy: 8,
r: 6,
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.2,
}),
h('path', {
d: 'M8 4.9V8l2.3 1.4',
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.2,
strokeLinecap: 'round',
strokeLinejoin: 'round',
}),
);
}
// #endregion
// #region component
function sumWallets(wallets, currency) {
let total = 0;
for (const wallet of wallets ?? []) {
if (wallet === null || typeof wallet !== 'object') continue;
if (wallet.currency !== currency) continue;
const amount = Number(wallet.balance);
if (Number.isFinite(amount)) total += amount;
}
return total;
}
function pickCurrency(wallets, bonusWallets) {
for (const wallet of wallets ?? []) {
if (wallet && (wallet.currency === 'CNY' || wallet.currency === 'USD')) return wallet.currency;
}
for (const wallet of bonusWallets ?? []) {
if (wallet && (wallet.currency === 'CNY' || wallet.currency === 'USD')) return wallet.currency;
}
return DEFAULT_CURRENCY;
}
function CostBalanceDock({ useProjection, sessionId, t, fetchBalance }) {
const usage = useProjection('tokenUsage');
const selection = useProjection('modelSelection');
const model =
selection?.pending?.model ?? selection?.lastUsed?.model ?? DEFAULT_MODEL;
/* DeepSeek rates only describe DeepSeek routes; another provider's
* requests are not priced with them. */
const provider = selection?.pending?.provider ?? selection?.lastUsed?.provider;
const pricedProvider =
provider === undefined ||
provider === 'deepseek-account' ||
provider === 'deepseek-official';
const usageKey =
usage === undefined || usage === null
? 'none'
: `${usage.uncachedInputTokens}/${usage.cacheReadTokens}/${usage.cacheWriteTokens}/${usage.outputTokens}`;
const ledgerRef = React.useRef(null);
if (ledgerRef.current === null || ledgerRef.current.sessionId !== sessionId) {
ledgerRef.current = createLedger(sessionId);
}
const ledger = ledgerRef.current;
const [, bump] = React.useReducer((value) => value + 1, 0);
React.useEffect(() => {
if (usage === undefined || usage === null) return;
const delta = ledger.observe(usage, model, pricedProvider);
/* Tokens are real for every route, priced or not: the history keeps
* them so the token and cache tabs are not limited to DeepSeek. */
if (delta !== undefined) recordTokenSample(model, delta, Date.now());
bump();
}, [usageKey, model, pricedProvider, ledger]);
/* Current DeepSeek tariff band: idle (cheaper) or peak (full price). */
const [band, setBand] = React.useState(() => bandAt(Date.now()));
React.useEffect(() => {
const timer = window.setInterval(() => setBand(bandAt(Date.now())), TARIFF_POLL_MS);
return () => window.clearInterval(timer);
}, []);
const [balance, setBalance] = React.useState({ status: 'loading' });
/* Read inside the fetch callback, which outlives a route change. */
const pricedRef = React.useRef(pricedProvider);
pricedRef.current = pricedProvider;
const mounted = React.useRef(true);
const inFlight = React.useRef(false);
const lastRead = React.useRef(0);
React.useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const refresh = React.useCallback(
(force) => {
if (inFlight.current) return;
if (!force && Date.now() - lastRead.current < BALANCE_MIN_INTERVAL_MS) return;
inFlight.current = true;
lastRead.current = Date.now();
Promise.resolve()
.then(fetchBalance)
.then(
(value) => {
inFlight.current = false;
if (!mounted.current) return;
if (value !== null && pricedRef.current) {
/* Every reading is one spend sample. The DeepSeek wallet has
* no separate usage counter, so the whole wallet is the meter
* and a top-up simply rebases it. A third-party route hands
* over its own counter below. */
const walletCurrency = pickCurrency(value.wallets, value.bonusWallets);
const remaining =
sumWallets(value.wallets, walletCurrency) + sumWallets(value.bonusWallets, walletCurrency);
recordBalanceSample(
'deepseek',
{ amount: remaining, wallet: remaining },
walletCurrency,
Date.now(),
);
}
setBalance(
value === null
? { status: 'unavailable' }
: { status: 'ready', wallets: value.wallets, bonusWallets: value.bonusWallets },
);
},
() => {
inFlight.current = false;
if (mounted.current) setBalance({ status: 'unavailable' });
},
);
},
[fetchBalance],
);
React.useEffect(() => {
refresh(true);
}, [refresh]);
React.useEffect(() => {
refresh(false);
}, [usageKey, refresh]);
React.useEffect(() => {
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') refresh(false);
}, BALANCE_POLL_MS);
return () => window.clearInterval(timer);
}, [refresh]);
/* A model from a third-party route shows that operator's wallet instead
* of the DeepSeek account wallet. The Host half owns the API key and
* answers this same-origin route. */
const operatorProvider = pricedProvider ? null : provider ?? null;
const [operator, setOperator] = React.useState({ status: 'idle' });
const operatorGeneration = React.useRef(0);
const refreshOperator = React.useCallback(() => {
if (operatorProvider === null) {
setOperator({ status: 'idle' });
return;
}
const generation = ++operatorGeneration.current;
setOperator({ status: 'loading', provider: operatorProvider });
fetch(
`/api/cost-balance/operator-balance?provider=${encodeURIComponent(operatorProvider)}`,
{ cache: 'no-store', credentials: 'same-origin' },
)
/* Every miss carries a short code so the tooltip can say why the
* reading is a dash: a missing Host route, an unreachable gateway,
* or a credential the Host could not resolve. */
.then((response) => {
if (!response.ok) return { ok: false, reason: `http-${String(response.status)}` };
return response.json().catch(() => ({ ok: false, reason: 'bad-payload' }));
})
.then(
(payload) => {
if (generation !== operatorGeneration.current) return;
if (payload !== null && payload.ok === true && Number.isFinite(Number(payload.amount))) {
const amount = Number(payload.amount);
const operatorSymbol =
typeof payload.symbol === 'string' && payload.symbol !== '' ? payload.symbol : '$';
const operatorCurrency = SYMBOL_TO_CURRENCY[operatorSymbol] ?? 'RUB';
setOperator({
status: 'ready',
provider: operatorProvider,
label: typeof payload.displayName === 'string' && payload.displayName !== ''
? payload.displayName
: operatorProvider,
amount,
symbol: operatorSymbol,
currency: operatorCurrency,
/* The key's own spending cap; the pill shows what is left
* under it in parentheses, the way the cabinet describes it. */
limit: finite(payload.limit),
used: finite(payload.used),
});
/* The displayed operator remainder is capped by the key's own
* limit, so it is never the spend meter: the gateway's usage
* counter (or, failing that, the whole wallet) is. */
recordBalanceSample(
operatorProvider,
{
amount,
wallet: finite(payload.wallet),
used: finite(payload.used),
cap: finite(payload.limit),
window: typeof payload.window === 'string' ? payload.window : undefined,
resetsAt: typeof payload.resetsAt === 'string' ? payload.resetsAt : undefined,
},
operatorCurrency,
Date.now(),
);
} else if (payload !== null && payload.reason === 'unknown-provider') {
setOperator({ status: 'unknown', provider: operatorProvider });
} else {
setOperator({
status: 'unavailable',
provider: operatorProvider,
reason: typeof payload?.reason === 'string' ? payload.reason : 'unknown',
});
}
},
() => {
if (generation === operatorGeneration.current) {
setOperator({ status: 'unavailable', provider: operatorProvider, reason: 'network' });
}
},
);
}, [operatorProvider]);
React.useEffect(() => {
refreshOperator();
}, [refreshOperator]);
React.useEffect(() => {
if (operatorProvider === null) return undefined;
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') refreshOperator();
}, BALANCE_POLL_MS);
return () => window.clearInterval(timer);
}, [operatorProvider, refreshOperator]);
const spend = useSpendLedger();
const [statsOpen, setStatsOpen] = React.useState(false);
React.useEffect(() => {
if (!statsOpen) return undefined;
const onKeyDown = (event) => {
if (event.key === 'Escape') setStatsOpen(false);
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [statsOpen]);
const wallets = balance.status === 'ready' ? balance.wallets : null;
const bonusWallets = balance.status === 'ready' ? balance.bonusWallets : null;
const currency = pickCurrency(wallets, bonusWallets);
const symbol = CURRENCY_SYMBOL[currency] ?? '';
const price = priceOf(model, currency);
const billedTokens =
usage === undefined || usage === null
? 0
: count(usage.uncachedInputTokens) +
count(usage.cacheReadTokens) +
count(usage.cacheWriteTokens) +
count(usage.outputTokens);
const hasUsage = billedTokens > 0 && pricedProvider;
/* Limits are kept per wallet currency; the reading colours follow the
* money the current model is actually billed in. */
const displayCurrency =
operator.status === 'ready' && operator.provider === operatorProvider
? operator.currency ?? 'RUB'
: currency;
/* Whole minutes: the total stays stable across streaming re-renders and
* only moves when the ledger changes or a minute passes. */
const nowMs = Math.floor(Date.now() / 60_000) * 60_000;
const dayStartMs = startOfDay(nowMs);
/* Limits belong to the provider that bills the selected model: the
* operator wallet is in rubles, the DeepSeek account in its own wallet
* currency. A fallback keeps a compatible reading when the current
* provider has no limit set but another one does. */
useFxRates();
const dayOwner = limitOwner(provider);
const ownerLimits = limitsOf(spend, dayOwner);
const ownerCurrency = limitCurrency(spend, dayOwner, displayCurrency);
const limitedOwners = Object.keys(spend.limits ?? {}).filter(
(owner) => limitsOf(spend, owner).day > 0,
);
const fallbackOwner =
limitedOwners.find(
(owner) => sumMoney(spend, limitCurrency(spend, owner, displayCurrency), dayStartMs, nowMs) > 0,
) ?? limitedOwners[0];
const dayCurrency =
ownerLimits.day > 0
? ownerCurrency
: fallbackOwner === undefined
? displayCurrency
: limitCurrency(spend, fallbackOwner, displayCurrency);
const daySymbol = CURRENCY_TO_SYMBOL[dayCurrency] ?? symbol;
const spendLimits = ownerLimits.day > 0 ? ownerLimits : limitsOf(spend, fallbackOwner);
const spentDay = React.useMemo(
() => sumMoney(spend, dayCurrency, dayStartMs, nowMs),
[spend, dayCurrency, nowMs],
);
const dayLevel = limitLevel(spentDay, spendLimits.day);
/* The reading is the remaining daily budget; past the limit it goes
* negative, so the overrun reads as "-200 ₽" in the error colour
* instead of a clamped "0 ₽". */
const dayRemaining = spendLimits.day - spentDay;
const dayOver = spentDay > spendLimits.day;
const readings = [];
if (hasUsage) {
const spent = ledger.cost(currency);
const amount = formatMoney(spent, currency);
const rates = t('cost.rates', {
input: symbol + formatRate(price.miss),
cache: symbol + formatRate(price.hit),
output: symbol + formatRate(price.output),
});
const detail = t('cost.title', { rates, model: pricedModel(model) });
readings.push(
h(
'span',
{ key: 'cost', className: 'dshCostBalance_anchor', 'data-composer-stat': 'cost' },
h(
'span',
{ className: 'dshCostBalance_pill', title: detail },
h(CostIcon),
h('span', { className: 'dshCostBalance_label' }, t('cost', { amount })),
),
),
);
}
let balanceText;
let balanceDetail;
let balanceProvider;
const operatorReading =
operatorProvider !== null && operator.provider === operatorProvider && operator.status === 'ready';
const operatorPending =
operatorProvider !== null &&
operator.provider === operatorProvider &&
(operator.status === 'loading' || operator.status === 'unavailable');
/* The key-limited remainder shown in parentheses, when the operator
* reports both its cap and the window's spend; the account wallet stays
* the reading itself, so a limit edit can never look like money. */
const operatorRemaining =
operatorReading && Number.isFinite(operator.limit) && Number.isFinite(operator.used)
? Math.max(0, operator.limit - operator.used)
: undefined;
if (operatorReading) {
const amount = formatMoneySymbol(operator.amount, operator.symbol);
balanceText = amount;
balanceProvider = operator.label ?? providerLabel(operator.provider);
balanceDetail =
operatorRemaining === undefined
? t('balance.operator.title', { provider: balanceProvider, amount })
: t('balance.operator.titleKey', {
provider: balanceProvider,
amount,
remaining: formatMoneySymbol(operatorRemaining, operator.symbol),
});
} else if (operatorPending) {
balanceText = operator.status === 'loading' ? '…' : '—';
balanceProvider = providerLabel(operator.provider);
balanceDetail =
operator.status === 'unavailable' && typeof operator.reason === 'string'
? t('balance.operator.unavailableReason', {
provider: balanceProvider,
reason: operator.reason,
})
: t('balance.operator.unavailable', { provider: balanceProvider });
} else if (balance.status === 'ready') {
balanceProvider = providerLabel(provider);
const recharge = sumWallets(wallets, currency);
const bonus = sumWallets(bonusWallets, currency);
balanceText = formatMoney(recharge + bonus, currency);
balanceDetail =
bonus > 0
? t('balance.title', {
recharge: formatMoney(recharge, currency),
bonus: formatMoney(bonus, currency),
})
: t('balance.title.plain', { recharge: formatMoney(recharge, currency) });
} else if (balance.status === 'loading') {
balanceText = '…';
balanceProvider = providerLabel(provider);
balanceDetail = t('balance.title.unavailable');
} else {
balanceText = '—';
balanceProvider = providerLabel(provider);
balanceDetail = t('balance.title.unavailable');
}
const balanceReading = h(
'span',
{ className: 'dshCostBalance_anchor', 'data-composer-stat': 'balance' },
h(
'button',
{
type: 'button',
className: 'dshCostBalance_pill',
title: balanceDetail,
'aria-label': t('refresh'),
onClick: () => {
if (operatorProvider !== null) refreshOperator();
else refresh(true);
},
},
h(BalanceIcon),
h('span', { className: 'dshCostBalance_label' }, balanceText),
h(
'span',
{ className: 'dshCostBalance_provider' },
operatorRemaining === undefined
? t('balance.provider', { provider: balanceProvider })
: t('balance.keyLimit', {
amount: formatMoneySymbol(operatorRemaining, operator.symbol),
}),
),
),
);
readings.push(
h(
'span',
{ key: 'balance', className: 'dshCostBalance_pair' },
pricedProvider
? h(
'span',
{
key: 'tariff',
className: 'dshCostBalance_lampAnchor',
'data-band': band,
'data-composer-stat': 'tariff',
title: t(band === 'peak' ? 'tariff.peak' : 'tariff.idle'),
},
h('span', { className: 'dshCostBalance_lamp', 'aria-hidden': true }),
)
: null,
balanceReading,
),
);
/* The day budget sits right after the balance, in the same type, coloured
* by how much of today's limit is already used; clicking opens the
* statistics. Without a daily limit there is nothing to colour, so the
* same seat stays as the plain entry point to the section. */
const dayReading =
spendLimits.day > 0
? h(
'span',
{ key: 'limits', className: 'dshCostBalance_anchor' },
h(
'button',
{
type: 'button',
className: 'dshCostBalance_pill dshCostBalance_chip',
'data-level': dayLevel,
'data-composer-stat': 'limit-day',
title: dayOver
? t('limits.dayOverTitle', {
spent: formatShortMoney(spentDay, daySymbol),
limit: formatShortMoney(spendLimits.day, daySymbol),
over: formatShortMoney(spentDay - spendLimits.day, daySymbol),
})
: t('limits.dayTitle', {
spent: formatShortMoney(spentDay, daySymbol),
limit: formatShortMoney(spendLimits.day, daySymbol),
}),
onClick: () => setStatsOpen(true),
},
h(DayIcon),
formatShortMoney(dayRemaining, daySymbol),
),
)
: h(
'span',
{ key: 'limits', className: 'dshCostBalance_anchor' },
h(
'button',
{
type: 'button',
className: 'dshCostBalance_pill dshCostBalance_chip dshCostBalance_chipMuted',
title: t('stats.openTitle'),
onClick: () => setStatsOpen(true),
},
h(DayIcon),
t('stats.open'),
),
);
readings.push(dayReading);
return h(
'span',
{ className: 'dshCostBalance_row' },
readings,
statsOpen
? ReactDOM.createPortal(
h(
'div',
{ className: 'dshStats_overlay', role: 'presentation' },
h('div', {
className: 'dshStats_mask',
'aria-hidden': true,
onClick: () => setStatsOpen(false),
}),
h(
'div',
{
className: 'dshStats_modal',
role: 'dialog',
'aria-modal': 'true',
'aria-label': t('stats.title'),
},
h(StatsPanel, { t, provider, onClose: () => setStatsOpen(false) }),
),
),
document.body,
)
: null,
);
}
/** Settings page wrapper: the shell passes the session-less props and `t`. */
function StatsSection(props) {
return h(StatsPanel, { t: props.t });
}
/** Bar-chart glyph for the settings navigation row. */
function SectionIcon({ size }) {
const pixels = typeof size === 'number' && size > 0 ? size : 16;
return h(
'svg',
{
viewBox: '0 0 16 16',
width: pixels,
height: pixels,
'aria-hidden': true,
style: { display: 'block', flex: 'none' },
},
h('rect', { x: 2, y: 8, width: 3, height: 6, rx: 1, fill: 'currentColor' }),
h('rect', { x: 6.5, y: 5, width: 3, height: 9, rx: 1, fill: 'currentColor' }),
h('rect', { x: 11, y: 2, width: 3, height: 12, rx: 1, fill: 'currentColor' }),
);
}
/**
* The shipped usage pill spells the cache-hit reading out ("Cache hit 87%",
* "Попадание в кэш: 87%"). The dock is a row of compact numbers, so this
* plugin rewrites that one label in place and keeps the percentage.
*
* A locale override is not available: the locale service rejects a second
* dictionary for a namespace and locale that already registered, and the
* shipped dictionary belongs to the installation. The observer is limited
* to `[data-composer-stat="usage"]` and does nothing when the text already
* lost its label.
*/
const CACHE_LABELS = [
/Попадание в кэш:\s*/u,
/Cache hit\s+/u,
/缓存命中\s*/u,
/キャッシュヒット\s*/u,
/Aciertos de caché:\s*/u,
/Taux de réussite du cache\s*:\s*/u,
/Cache-Treffer:\s*/u,
/Acertos no cache:\s*/u,
];
function shortenCacheText(text) {
for (const pattern of CACHE_LABELS) {
if (pattern.test(text)) return text.replace(pattern, '');
}
return text;
}
function shortenUsagePills(root) {
const anchors = root.querySelectorAll?.('[data-composer-stat="usage"]') ?? [];
for (const anchor of anchors) {
const walker = document.createTreeWalker(anchor, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
for (const node of nodes) {
const current = node.nodeValue ?? '';
const next = shortenCacheText(current);
if (next !== current) node.nodeValue = next;
}
}
}
/** Keep the shipped usage pill compact for as long as the plugin is mounted. */
function installCacheLabelSquash() {
let queued = false;
const apply = () => {
queued = false;
shortenUsagePills(document);
};
const schedule = () => {
if (queued) return;
queued = true;
window.requestAnimationFrame(apply);
};
const observer = new MutationObserver(schedule);
observer.observe(document.body, { subtree: true, childList: true, characterData: true });
schedule();
return () => observer.disconnect();
}
// #endregion
// #region dictionaries
const en = {
'cost': 'Spent ≈ {amount}',
'cost.title':
'Estimated session spend at DeepSeek list prices ({rates} per 1M at peak; off-peak is half). Model: {model}.',
'cost.rates': 'input {input}/1M · cache {cache}/1M · output {output}/1M',
'balance': 'Balance {amount}',
'balance.loading': 'Balance …',
'balance.unavailable': 'Balance —',
'balance.title': 'Top-up {recharge} · Granted {bonus}. Click to refresh.',
'balance.title.plain': 'Top-up {recharge}. Click to refresh.',
'balance.title.unavailable': 'The account balance is unavailable. Sign in to see the remaining balance.',
'tariff.peak': 'Peak tariff now: DeepSeek full prices (peak is Mon-Fri 9:00-12:00 and 14:00-18:00 Beijing time).',
'tariff.idle': 'Idle tariff now: DeepSeek prices are half (idle is all other hours and weekends, Beijing time).',
'balance.operator.title': '{provider}: remaining {amount}. Click to refresh.',
'balance.operator.titleKey':
'{provider}: balance {amount}, {remaining} left under the key limit. Click to refresh.',
'balance.keyLimit': '({amount})',
'balance.operator.unavailable': '{provider}: balance is unavailable.',
'balance.operator.unavailableReason': '{provider}: balance is unavailable ({reason}).',
'balance.provider': '({provider})',
'refresh': 'Refresh balance',
'section.title': 'Usage',
'stats.title': 'Spending',
'stats.subtitle': 'Money spent from the balance, in {symbol}.',
'stats.view.spend': 'Spending',
'stats.view.tokens': 'Tokens',
'stats.view.cache': 'Cache',
'stats.view.history': 'History',
'stats.history.subtitle': 'Enter a day total by hand, or clear the recorded history.',
'stats.tokens.subtitle': 'Tokens used in the selected period: input, cache, and output.',
'stats.cache.subtitle': 'How much of the input traffic was served from the cache.',
'stats.tokens.input': 'Input',
'stats.tokens.cached': 'From cache',
'stats.tokens.output': 'Output',
'stats.tokens.writeNote': 'cache write {amount}',
'stats.tokens.totalNote': 'total {amount}',
'stats.tokens.unit': 'tokens',
'stats.tokens.byModel': 'By model',
'stats.tokens.model': 'Model',
'stats.tokens.empty': 'No tokens recorded in this period yet.',
'stats.tokens.hourTitle': '{hour}:00 — {amount} tokens',
'stats.tokens.dayTitle': '{date} — {amount} tokens',
'stats.cache.ratio': 'Cache share',
'stats.cache.hit': 'From cache',
'stats.cache.miss': 'Missed cache',
'stats.cache.shareNote': '{percent} of input',
'stats.cache.summaryNote': '{hit} of {total} input tokens',
'stats.cache.hourTitle': '{hour}:00 — {percent} from cache',
'stats.cache.dayTitle': '{date} — {percent} from cache',
'stats.period.day': 'Day',
'stats.period.week': 'Week',
'stats.period.month': 'Month',
'stats.ofLimit': 'of {limit}',
'stats.noLimit': 'no limit',
'stats.leftOfLimit': '{left} left of {limit}',
'stats.overLimit': 'over by {over} of {limit}',
'stats.hourTitle': '{hour}:00 — {amount}',
'stats.dayTitle': '{date} — {amount}',
'stats.hourlyFor': '{date}, by hour',
'stats.back': 'Back to days',
'stats.byHour': 'By hour',
'stats.byDay': 'By day',
'stats.clickHint': 'Click a bar to see that day by hour.',
'stats.overDaysHint': 'Red in a bar is the part above the daily limit.',
'stats.dayOverTitle': '{date} — {amount}, over by {over}',
'stats.limitsTitle': 'Soft limits',
'stats.limitsOwnerHint': 'For {provider} in {symbol}; saved as you type.',
'quickReload.title': 'Reload the interface. Running agents keep working on the host.',
'quickReload.label': 'reload',
'stats.fxNote': 'Central Bank rates: {rates}.',
'stats.fxMissing': 'No rate for {codes} yet — the totals leave that currency out.',
'stats.limit.day': 'Per day',
'stats.limit.week': 'Per week',
'stats.limit.month': 'Per month',
'stats.notSet': 'not set',
'stats.derive': 'Fill from monthly',
'stats.deriveHint': 'Day = month / 30, week = month × 7 / 30.',
'stats.resetHistory': 'Clear history',
'stats.resetHint': 'Deletes the recorded spending and token history; the limits stay.',
'stats.resetConfirm': 'Clear the recorded spending history?',
'stats.manualTitle': 'History entry',
'stats.manualHint':
'The day total in {symbol}; replaces the recorded hours of that day and is spread over the hours already passed. 0 clears the day.',
'stats.manualDay': 'Day',
'stats.manualTotal': 'Total',
'stats.manualApply': 'Save',
'stats.close': 'Close',
'stats.open': 'Statistics',
'stats.openTitle': 'Spending and limits',
'limits.dayTitle': 'Today: spent {spent} of {limit}',
'limits.dayOverTitle': 'Today: spent {spent} of {limit}, over by {over}',
};
const zh = {
'cost': '花费 ≈ {amount}',
'cost.title': '按 DeepSeek 价格估算的本次会话花费(高峰时段 {rates} / 1M;空闲时段减半)。模型:{model}。',
'cost.rates': '输入 {input}/1M · 缓存 {cache}/1M · 输出 {output}/1M',
'balance': '余额 {amount}',
'balance.loading': '余额 …',
'balance.unavailable': '余额 —',
'balance.title': '充值余额 {recharge} · 赠送余额 {bonus}。点击刷新。',
'balance.title.plain': '充值余额 {recharge}。点击刷新。',
'balance.title.unavailable': '账户余额不可用。登录后可查看剩余余额。',
'tariff.peak': '当前为高峰时段:按 DeepSeek 完整价格计费(高峰为北京时间周一至周五 9:00–12:00、14:00–18:00)。',
'tariff.idle': '当前为空闲时段:DeepSeek 价格减半(其余时间及周末,北京时间)。',
'balance.operator.title': '{provider}:剩余 {amount}。点击刷新。',
'balance.operator.unavailable': '{provider}:余额不可用。',
'balance.provider': '({provider})',
'refresh': '刷新余额',
};
const ru = {
'cost': 'Расход ≈ {amount}',
'cost.title':
'Оценка расхода сессии по прайсу DeepSeek ({rates} за 1M в пиковые часы; вне пика вдвое дешевле). Модель: {model}.',
'cost.rates': 'вход {input}/1M · кэш {cache}/1M · выход {output}/1M',
'balance': 'Баланс {amount}',
'balance.loading': 'Баланс …',
'balance.unavailable': 'Баланс —',
'balance.title': 'Пополненный {recharge} · Бонусный {bonus}. Нажмите, чтобы обновить.',
'balance.title.plain': 'Пополненный {recharge}. Нажмите, чтобы обновить.',
'balance.title.unavailable': 'Баланс аккаунта недоступен. Войдите в аккаунт, чтобы видеть остаток.',
'tariff.peak': 'Сейчас пиковый тариф DeepSeek: полные цены (пик — пн–пт 9:00–12:00 и 14:00–18:00 по Пекину).',
'tariff.idle': 'Сейчас непиковой тариф DeepSeek: цены вдвое ниже (непик — остальное время и выходные по Пекину).',
'balance.operator.title': '{provider}: остаток {amount}. Нажмите, чтобы обновить.',
'balance.operator.titleKey':
'{provider}: баланс {amount}, под лимитом ключа осталось {remaining}. Нажмите, чтобы обновить.',
'balance.keyLimit': '({amount})',
'balance.operator.unavailable': '{provider}: баланс недоступен.',
'balance.operator.unavailableReason': '{provider}: баланс недоступен ({reason}).',
'balance.provider': '({provider})',
'refresh': 'Обновить баланс',
'section.title': 'Статистика',
'stats.title': 'Потребление',
'stats.subtitle': 'Сколько списано с баланса, в {symbol}.',
'stats.view.spend': 'Потребление',
'stats.view.tokens': 'Токены',
'stats.view.cache': 'Кеш',
'stats.view.history': 'Правка истории',
'stats.history.subtitle': 'Ручная запись итога за день и сброс записанной истории.',
'stats.tokens.subtitle': 'Токены за выбранный период: вход, кеш и выход.',
'stats.cache.subtitle': 'Какая часть входного трафика обслужена из кеша.',
'stats.tokens.input': 'Вход',
'stats.tokens.cached': 'Из кеша',
'stats.tokens.output': 'Выход',
'stats.tokens.writeNote': 'кеш-запись {amount}',
'stats.tokens.totalNote': 'всего {amount}',
'stats.tokens.unit': 'токенов',
'stats.tokens.byModel': 'По моделям',
'stats.tokens.model': 'Модель',
'stats.tokens.empty': 'За этот период токенов пока нет.',
'stats.tokens.hourTitle': '{hour}:00 — {amount} токенов',
'stats.tokens.dayTitle': '{date} — {amount} токенов',
'stats.cache.ratio': 'Доля кеша',
'stats.cache.hit': 'Из кеша',
'stats.cache.miss': 'Мимо кеша',
'stats.cache.shareNote': '{percent} от входа',
'stats.cache.summaryNote': '{hit} из {total} входных токенов',
'stats.cache.hourTitle': '{hour}:00 — {percent} из кеша',
'stats.cache.dayTitle': '{date} — {percent} из кеша',
'stats.period.day': 'День',
'stats.period.week': 'Неделя',
'stats.period.month': 'Месяц',
'stats.ofLimit': 'из {limit}',
'stats.noLimit': 'лимит не задан',
'stats.leftOfLimit': 'осталось {left} из {limit}',
'stats.overLimit': 'перерасход {over} из {limit}',
'stats.hourTitle': '{hour}:00 — {amount}',
'stats.dayTitle': '{date} — {amount}',
'stats.hourlyFor': '{date}, по часам',
'stats.back': 'К дням',
'stats.byHour': 'По часам',
'stats.byDay': 'По дням',
'stats.clickHint': 'Нажмите на столбик, чтобы увидеть этот день по часам.',
'stats.overDaysHint': 'Красное в столбике — часть выше дневного лимита.',
'stats.dayOverTitle': '{date} — {amount}, перерасход {over}',
'stats.limitsTitle': 'Условные лимиты',
'stats.limitsOwnerHint': 'Для {provider} в {symbol}; сохраняется сразу.',
'quickReload.title': 'Перезагрузить интерфейс. Запущенные агенты продолжают работу на хосте.',
'quickReload.label': 'reload',
'stats.fxNote': 'Курс ЦБ: {rates}.',
'stats.fxMissing': 'Курса {codes} пока нет — в суммах эта валюта не учтена.',
'stats.limit.day': 'В день',
'stats.limit.week': 'В неделю',
'stats.limit.month': 'В месяц',
'stats.notSet': 'не задан',
'stats.derive': 'Заполнить из месячного',
'stats.deriveHint': 'День = месяц / 30, неделя = месяц × 7 / 30.',
'stats.resetHistory': 'Сбросить историю',
'stats.resetHint': 'Удаляет записанную историю расходов и токенов; лимиты сохраняются.',
'stats.resetConfirm': 'Сбросить записанную историю расходов?',
'stats.manualTitle': 'Правка истории',
'stats.manualHint':
'Итог за день в {symbol}; заменяет записанные часы этого дня и распределяется по уже прошедшим часам. 0 очищает день.',
'stats.manualDay': 'День',
'stats.manualTotal': 'Итог',
'stats.manualApply': 'Записать',
'stats.close': 'Закрыть',
'stats.open': 'Статистика',
'stats.openTitle': 'Расход и лимиты',
'limits.dayTitle': 'День: потрачено {spent} из {limit}',
'limits.dayOverTitle': 'День: потрачено {spent} из {limit}, перерасход {over}',
};
const ja = {
'cost': '消費 ≈ {amount}',
'cost.title':
'DeepSeek の料金(ピーク時 {rates} / 1M、アイドル時は半額)で見積もったこのセッションの消費額です。モデル: {model}。',
'cost.rates': '入力 {input}/1M · キャッシュ {cache}/1M · 出力 {output}/1M',
'balance': '残高 {amount}',
'balance.loading': '残高 …',
'balance.unavailable': '残高 —',
'balance.title': 'チャージ残高 {recharge} · 付与残高 {bonus}。クリックで更新。',
'balance.title.plain': 'チャージ残高 {recharge}。クリックで更新。',
'balance.title.unavailable': 'アカウント残高を取得できません。ログインすると残高を確認できます。',
'tariff.peak': '現在はピーク時間帯: DeepSeek の通常料金です(ピークは北京時間の平日 9:00–12:00、14:00–18:00)。',
'tariff.idle': '現在はアイドル時間帯: DeepSeek の料金は半額です(それ以外の時間と週末、北京時間)。',
'balance.operator.title': '{provider}: 残高 {amount}。クリックで更新。',
'balance.operator.unavailable': '{provider}: 残高を取得できません。',
'balance.provider': '({provider})',
'refresh': '残高を更新',
};
const es = {
'cost': 'Gasto ≈ {amount}',
'cost.title':
'Gasto estimado de la sesión con las tarifas de DeepSeek ({rates} por 1M en hora punta; en hora valle cuesta la mitad). Modelo: {model}.',
'cost.rates': 'entrada {input}/1M · caché {cache}/1M · salida {output}/1M',
'balance': 'Saldo {amount}',
'balance.loading': 'Saldo …',
'balance.unavailable': 'Saldo —',
'balance.title': 'Recargado {recharge} · Bonificado {bonus}. Haz clic para actualizar.',
'balance.title.plain': 'Recargado {recharge}. Haz clic para actualizar.',
'balance.title.unavailable': 'El saldo de la cuenta no está disponible. Inicia sesión para verlo.',
'tariff.peak': 'Ahora es hora punta: precios completos de DeepSeek (la punta es de lunes a viernes, 9:00-12:00 y 14:00-18:00, hora de Pekín).',
'tariff.idle': 'Ahora es hora valle: los precios de DeepSeek son la mitad (el resto del día y los fines de semana, hora de Pekín).',
'balance.operator.title': '{provider}: saldo {amount}. Haz clic para actualizar.',
'balance.operator.unavailable': '{provider}: el saldo no está disponible.',
'balance.provider': '({provider})',
'refresh': 'Actualizar saldo',
};
const fr = {
'cost': 'Dépense ≈ {amount}',
'cost.title':
'Dépense estimée de la session aux tarifs DeepSeek ({rates} par 1M en heures pleines ; heures creuses moitié prix). Modèle : {model}.',
'cost.rates': 'entrée {input}/1M · cache {cache}/1M · sortie {output}/1M',
'balance': 'Solde {amount}',
'balance.loading': 'Solde …',
'balance.unavailable': 'Solde —',
'balance.title': 'Rechargé {recharge} · Offert {bonus}. Cliquez pour actualiser.',
'balance.title.plain': 'Rechargé {recharge}. Cliquez pour actualiser.',
'balance.title.unavailable': 'Le solde du compte est indisponible. Connectez-vous pour le voir.',
'tariff.peak': 'Heure de pointe en cours : tarifs DeepSeek pleins (pointe du lundi au vendredi, 9h00-12h00 et 14h00-18h00, heure de Pékin).',
'tariff.idle': 'Heures creuses en cours : les tarifs DeepSeek sont divisés par deux (le reste du temps et les week-ends, heure de Pékin).',
'balance.operator.title': '{provider} : solde {amount}. Cliquez pour actualiser.',
'balance.operator.unavailable': '{provider} : le solde est indisponible.',
'balance.provider': '({provider})',
'refresh': 'Actualiser le solde',
};
const de = {
'cost': 'Ausgaben ≈ {amount}',
'cost.title':
'Geschätzte Ausgaben der Sitzung zu DeepSeek-Preisen ({rates} pro 1M zur Spitzenzeit; außerhalb der Spitzenzeiten halb so viel). Modell: {model}.',
'cost.rates': 'Eingabe {input}/1M · Cache {cache}/1M · Ausgabe {output}/1M',
'balance': 'Guthaben {amount}',
'balance.loading': 'Guthaben …',
'balance.unavailable': 'Guthaben —',
'balance.title': 'Aufgeladen {recharge} · Geschenkt {bonus}. Klicken zum Aktualisieren.',
'balance.title.plain': 'Aufgeladen {recharge}. Klicken zum Aktualisieren.',
'balance.title.unavailable': 'Das Kontoguthaben ist nicht verfügbar. Melden Sie sich an, um es zu sehen.',
'tariff.peak': 'Jetzt Spitzenzeit: volle DeepSeek-Preise (Spitzenzeit ist Mo-Fr 9:00-12:00 und 14:00-18:00 Pekinger Zeit).',
'tariff.idle': 'Jetzt Nebenzeit: DeepSeek-Preise sind halb so hoch (alle anderen Zeiten und Wochenenden, Pekinger Zeit).',
'balance.operator.title': '{provider}: Guthaben {amount}. Klicken zum Aktualisieren.',
'balance.operator.unavailable': '{provider}: Guthaben nicht verfügbar.',
'balance.provider': '({provider})',
'refresh': 'Guthaben aktualisieren',
};
const pt = {
'cost': 'Gasto ≈ {amount}',
'cost.title':
'Estimativa de gasto da sessão com os preços da DeepSeek ({rates} por 1M no pico; fora de pico custa metade). Modelo: {model}.',
'cost.rates': 'entrada {input}/1M · cache {cache}/1M · saída {output}/1M',
'balance': 'Saldo {amount}',
'balance.loading': 'Saldo …',
'balance.unavailable': 'Saldo —',
'balance.title': 'Recarregado {recharge} · Bônus {bonus}. Clique para atualizar.',
'balance.title.plain': 'Recarregado {recharge}. Clique para atualizar.',
'balance.title.unavailable': 'O saldo da conta não está disponível. Entre na conta para vê-lo.',
'tariff.peak': 'Agora é horário de pico: preços integrais da DeepSeek (pico é de segunda a sexta, 9:00-12:00 e 14:00-18:00, horário de Pequim).',
'tariff.idle': 'Agora é horário fora de pico: os preços da DeepSeek custam metade (demais horários e fins de semana, horário de Pequim).',
'balance.operator.title': '{provider}: saldo {amount}. Clique para atualizar.',
'balance.operator.unavailable': '{provider}: o saldo não está disponível.',
'balance.provider': '({provider})',
'refresh': 'Atualizar saldo',
};
/* The statistics panel copy ships in Russian and English; every other
* language keeps its translated dock strings and falls back to English for
* the newer keys instead of showing raw keys. */
const DICTIONARIES = {
en,
zh: { ...en, ...zh },
ru: { ...en, ...ru },
ja: { ...en, ...ja },
es: { ...en, ...es },
fr: { ...en, ...fr },
de: { ...en, ...de },
pt: { ...en, ...pt },
};
// #endregion
// #region styles
/** Host pill geometry, copied from the shipped statistics pills. */
const CSS = [
'.dshCostBalance_row{display:inline-flex;align-items:center;gap:12px;min-width:0}',
'.dshCostBalance_anchor{min-width:0;',
'font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);',
'line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));',
'display:inline-flex}',
'.dshCostBalance_pill{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;',
'color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;',
'line-height:inherit;white-space:nowrap;background:0 0;border:none;align-items:center;',
'gap:6px;padding:1px 8px;display:inline-flex}',
'button.dshCostBalance_pill{cursor:pointer}',
'button.dshCostBalance_pill:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid ',
'var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}',
'.dshCostBalance_label{text-overflow:ellipsis;min-width:0;overflow:hidden}',
'.dshCostBalance_provider{flex:none;opacity:.7}',
'.dshCostBalance_pair{display:inline-flex;align-items:center;gap:6px;min-width:0}',
'.dshCostBalance_lampAnchor{display:inline-flex;align-items:center;justify-content:center;',
'flex:none;padding:0 1px}',
'.dshCostBalance_lampAnchor[data-band="idle"]{color:var(--dsw-alias-state-success-primary)}',
'.dshCostBalance_lampAnchor[data-band="peak"]{color:var(--dsw-alias-state-warn-primary)}',
'.dshCostBalance_lamp{width:7px;height:7px;border-radius:50%;flex:none;display:block;',
'background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 20%,transparent)}',
'.dshCostBalance_pill[data-level="ok"]{color:var(--dsw-alias-state-success-primary)}',
'.dshCostBalance_pill[data-level="warn"]{color:var(--dsw-alias-state-warn-primary)}',
'.dshCostBalance_pill[data-level="over"]{color:var(--dsw-alias-state-error-primary)}',
'.dshCostBalance_chipMuted{color:var(--dsw-alias-label-tertiary)}',
'.dshStats_overlay{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;',
'justify-content:center}',
'.dshStats_mask{position:absolute;inset:0;background:var(--dsw-alias-bg-mask-1);',
'backdrop-filter:var(--dsw-mask-blur)}',
'.dshStats_modal{position:relative;z-index:1;box-sizing:border-box;width:720px;',
'max-width:calc(100vw - 48px);max-height:min(780px,calc(100vh - 48px));overflow:auto;',
'border-radius:var(--dsw-radius-panel,16px);background:var(--dsw-alias-bg-layer-2);',
'box-shadow:var(--dsw-elevation-prominent)}',
'.dshStats_root{box-sizing:border-box;display:flex;flex-direction:column;gap:14px;',
'padding:20px 24px 24px;color:var(--dsw-alias-label-primary);font-size:14px;line-height:20px;',
'min-width:0}',
'.dshStats_header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}',
'.dshStats_titles{min-width:0}',
'.dshStats_title{margin:0;font-size:16px;font-weight:500;line-height:24px}',
'.dshStats_subtitle{margin:2px 0 0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:18px}',
'.dshStats_close{flex:none;width:28px;height:28px;border:none;border-radius:var(--dsw-radius-sm);',
'background:0 0;color:var(--dsw-alias-label-secondary);font-size:20px;line-height:1;cursor:pointer}',
'.dshStats_close:hover{background:var(--dsw-alias-interactive-bg-hover)}',
'.dshStats_views{display:inline-flex;gap:2px;align-self:flex-start;',
'border-bottom:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}',
'.dshStats_view{border:none;background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;',
'padding:6px 12px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px}',
'.dshStats_viewActive{color:var(--dsw-alias-label-primary);',
'border-bottom-color:var(--dsw-alias-state-business-primary)}',
'.dshStats_tableBlock{display:flex;flex-direction:column;gap:6px}',
'.dshStats_table{display:flex;flex-direction:column}',
'.dshStats_tableRow{display:grid;grid-template-columns:minmax(0,2fr) repeat(3,minmax(0,1fr));',
'gap:8px;padding:5px 0;border-top:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);',
'font-variant-numeric:tabular-nums}',
'.dshStats_tableHead{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px;border-top:none}',
'.dshStats_modelCell{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;',
'color:var(--dsw-alias-label-secondary)}',
'.dshStats_num{text-align:right}',
'.dshStats_periods{display:inline-flex;gap:4px;padding:3px;border-radius:var(--dsw-radius-md);',
'background:color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);align-self:flex-start}',
'.dshStats_period{border:none;background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;',
'padding:4px 12px;border-radius:calc(var(--dsw-radius-md) - 3px);cursor:pointer}',
'.dshStats_periodActive{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);',
'box-shadow:0 1px 2px rgba(0,0,0,.12)}',
'.dshStats_cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}',
'.dshStats_card{display:flex;flex-direction:column;gap:2px;text-align:left;',
'border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);background:0 0;',
'border-radius:var(--dsw-radius-md);padding:10px 12px;color:var(--dsw-alias-label-primary);',
'font:inherit;cursor:pointer;min-width:0}',
'.dshStats_cardActive{border-color:var(--dsw-alias-state-business-primary)}',
'.dshStats_cardStatic{cursor:default}',
'.dshStats_cardLabel{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}',
'.dshStats_cardValue{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}',
'.dshStats_cardLimit{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px;',
'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.dshStats_card[data-level="ok"] .dshStats_cardValue{color:var(--dsw-alias-state-success-primary)}',
'.dshStats_card[data-level="warn"] .dshStats_cardValue{color:var(--dsw-alias-state-warn-primary)}',
'.dshStats_card[data-level="over"] .dshStats_cardValue{color:var(--dsw-alias-state-error-primary)}',
/* Two-segment track: blue up to the limit, red for the excess. */
/* The segments are flex siblings, so the split point is exact. */
'.dshStats_progress{display:flex;height:4px;border-radius:2px;margin-top:6px;overflow:hidden;',
'background:color-mix(in srgb,var(--dsw-alias-label-primary) 10%,transparent)}',
'.dshStats_progressFill{display:block;height:100%;flex:none;',
'background:var(--dsw-alias-state-business-primary)}',
'.dshStats_progressOver{display:block;height:100%;flex:none;',
'background:var(--dsw-alias-state-error-primary)}',
'.dshStats_summary{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}',
'.dshStats_summaryAmount{font-size:22px;font-weight:600;font-variant-numeric:tabular-nums}',
'.dshStats_summaryAmount[data-level="ok"]{color:var(--dsw-alias-state-success-primary)}',
'.dshStats_summaryAmount[data-level="warn"]{color:var(--dsw-alias-state-warn-primary)}',
'.dshStats_summaryAmount[data-level="over"]{color:var(--dsw-alias-state-error-primary)}',
'.dshStats_summaryNote{color:var(--dsw-alias-label-tertiary);font-size:13px}',
'.dshStats_summaryNote[data-level="over"]{color:var(--dsw-alias-state-error-primary)}',
'.dshStats_chartBlock{display:flex;flex-direction:column;gap:6px}',
'.dshStats_chartTitle{font-size:13px;color:var(--dsw-alias-label-secondary)}',
'.dshStats_chart{display:flex;flex-direction:column;gap:4px}',
'.dshStats_bars{display:flex;align-items:flex-end;gap:2px;height:132px;padding:28px 0 0;',
'border-bottom:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 10%,transparent)}',
'.dshStats_barSlot{flex:1 1 0;display:flex;align-items:flex-end;height:100%;min-width:0;',
'position:relative}',
'.dshStats_barValue{position:absolute;left:50%;transform:translateX(-50%);z-index:1;',
'font-size:9px;line-height:11px;color:var(--dsw-alias-label-secondary);white-space:nowrap;',
'pointer-events:none;font-variant-numeric:tabular-nums}',
'.dshStats_bar{width:100%;border-radius:2px 2px 0 0;background:var(--dsw-alias-state-business-primary);',
'opacity:.55;transition:opacity .12s}',
'.dshStats_barClickable{cursor:pointer}',
'.dshStats_barClickable:hover{opacity:.9}',
'.dshStats_barCurrent{opacity:.95}',
'.dshStats_barSelected{opacity:1;outline:1px solid var(--dsw-alias-state-business-primary)}',
'.dshStats_axis{display:flex;gap:2px}',
'.dshStats_axisLabel{flex:1 1 0;min-width:0;text-align:center;font-size:10px;line-height:14px;',
'color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden}',
'.dshStats_detail{display:flex;flex-direction:column;gap:8px;padding-top:4px}',
'.dshStats_detailHeader{display:flex;align-items:center;justify-content:space-between;gap:8px}',
'.dshStats_detailTitle{font-size:13px;color:var(--dsw-alias-label-secondary)}',
'.dshStats_linkButton{border:none;background:0 0;color:var(--dsw-alias-state-business-primary);',
'font:inherit;cursor:pointer;padding:0}',
'.dshStats_limitsBlock{display:flex;flex-direction:column;gap:8px;padding-top:6px;',
'border-top:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}',
'.dshStats_limitsTitle{margin:0;font-size:14px;font-weight:500}',
'.dshStats_hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}',
'.dshStats_limitRow{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}',
'.dshStats_manualRow{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}',
'.dshStats_fxNotes{display:flex;flex-direction:column;gap:2px}',
'.dshReload_wrap{display:flex;justify-content:flex-start;align-items:center;flex:1 1 auto;',
'min-width:0;padding-inline-start:var(--dsh-sidebar-row-padding,8px)}',
'.dshReload_wrap[data-wide="false"]{flex:none;padding-inline-start:0}',
'.dshReload_button{height:28px;border:none;border-radius:999px;background:0 0;',
'color:var(--dsw-alias-label-tertiary);cursor:pointer;padding:0 12px;display:inline-flex;',
'align-items:center;justify-content:center;gap:6px;flex:none;font:inherit;font-size:13px;line-height:1}',
'.dshReload_wrap[data-wide="false"] .dshReload_button{width:28px;padding:0}',
'.dshReload_label{white-space:nowrap}',
'.dshReload_button svg{flex:none}',
'.dshReload_button:hover{background:var(--dsw-alias-interactive-bg-hover);',
'color:var(--dsw-alias-label-secondary)}',
'.dshReload_button:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid ',
'var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}',
'.dshStats_date{width:auto;min-width:8.5em;color-scheme:inherit}',
'.dshStats_limitField{display:flex;flex-direction:column;gap:4px;min-width:0}',
'.dshStats_limitLabel{font-size:12px;color:var(--dsw-alias-label-secondary)}',
'.dshStats_inputWrap{display:flex;align-items:center;gap:6px;padding:4px 8px;',
'border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 14%,transparent);',
'border-radius:var(--dsw-radius-sm)}',
'.dshStats_input{border:none;background:0 0;color:var(--dsw-alias-label-primary);font:inherit;',
'font-variant-numeric:tabular-nums;width:100%;min-width:0;outline:none;padding:0}',
'.dshStats_symbol{color:var(--dsw-alias-label-tertiary);flex:none}',
'.dshStats_actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}',
'.dshStats_button{border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 14%,transparent);',
'border-radius:var(--dsw-radius-sm);background:0 0;color:var(--dsw-alias-label-primary);',
'font:inherit;padding:4px 12px;cursor:pointer}',
'.dshStats_button:hover{background:var(--dsw-alias-interactive-bg-hover)}',
].join('');
// #endregion
/** Services required by this Client half. */
const inject = ['slots', 'locale', 'remote', 'remote.account'];
/**
* Register the readings and their resources.
* @param ctx - Client plugin context.
*/
function apply(ctx) {
ctx.effect(
() =>
ctx.locale.register(NS, DICTIONARIES),
'cost-balance-footer: dictionaries',
);
ctx.effect(() => {
const tag = document.createElement('style');
tag.dataset.plugin = PLUGIN_ID;
tag.dataset.pluginCss = CSS_ID;
tag.textContent = CSS;
document.head.appendChild(tag);
return () => {
tag.remove();
};
}, 'cost-balance-footer: styles');
/** Identity for one account call, read at call time. */
const clientMetadata = () => {
const release = globalThis.__DSH_BOOT__?.release;
return {
version: typeof release?.version === 'string' ? release.version : '0.0.0',
locale: ctx.locale.getSnapshot().active,
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
};
};
/** Read the account's wallets; null means signed out or unavailable. */
const fetchBalance = async () => {
try {
const result = await ctx.remote.account.getBalance(clientMetadata());
if (!result || !result.ok) return null;
const balance = result.value;
if (!balance || balance.status !== 'ready') return null;
return {
wallets: Array.isArray(balance.value) ? balance.value : [],
bonusWallets: Array.isArray(balance.bonusWallets) ? balance.bonusWallets : [],
};
} catch {
return null;
}
};
/* Settings → Statistics: history, hourly view, and the soft limits. */
const tSettings = ctx.locale.bind(NS);
const registerSlots = () => {
ctx.slots.inject('conversation.composer.dock', () =>
ctx.slots.register(
{
name: 'conversation.composer.dock',
id: 'cost-balance',
order: 2,
locale: NS,
inject: () => ({ fetchBalance }),
},
CostBalanceDock,
),
);
ctx.slots.inject('settings.section', () =>
ctx.slots.register(
{
name: 'settings.section',
id: 'cost-balance',
order: 40,
label: () => tSettings('section.title'),
locale: NS,
},
StatsSection,
),
);
ctx.slots.inject('settings.section.icon', () =>
ctx.slots.register({ name: 'settings.section.icon', id: 'cost-balance', locale: NS }, SectionIcon),
);
};
/* Hydrate the ledger before the readings mount, so the first paint shows
* the stored history instead of an empty one. The route answers locally;
* its timeout still lets the plugin mount against an older Host. */
ctx.effect(() => {
let active = true;
void hydrateSpend().finally(() => {
if (active) registerSlots();
});
return () => {
active = false;
};
}, 'cost-balance: spending ledger');
/* Rates are published once a business day; refresh on start and every
* few hours so a long-running window picks the new one up. */
ctx.effect(() => {
void refreshFxRates();
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') void refreshFxRates();
}, FX_REFRESH_MS);
return () => window.clearInterval(timer);
}, 'cost-balance: daily exchange rates');
/* One click applies fresh client bundles and settings without digging
* into the profile menu; agents are unaffected. */
ctx.slots.inject('sidebar.footer.action', () =>
ctx.slots.register(
{ name: 'sidebar.footer.action', id: 'quick-reload', order: 100, locale: NS },
ReloadButton,
),
);
ctx.effect(() => installCacheLabelSquash(), 'cost-balance: compact cache label');
}
return { inject, apply };
},
});